language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
MacCyrillic
424
2.625
3
[]
no_license
import java.util.Scanner; public class homeTask2Ex1_22_ { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println(" x "); double x = in.nextDouble(); double y= 7*(Math.pow(x,2))-3*x+6; System.out.print("y= "+y); in.close(); } }
Ruby
UTF-8
961
3.90625
4
[]
no_license
# return n! % m == 0 def factorial_div?(n, m) return true if m < n primes = build_primes(n) prime_count_hash = prime_count(primes, n) primes.each do |prime| prime_count = 0 factor_max = Math.sqrt(m) while prime*prime_count < factor_max return false if prime_count > prime_count_hash[prime] prime_count += 1 end end true end def build_primes(n) return [] if n < 2 idx = 2 primes = [] while idx <= n primes << idx if is_prime?(idx, primes) idx += 1 end primes end def is_prime?(idx, primes) primes.each do |prime| return false if idx % prime == 0 end true end def prime_count(primes, n) prime_count_hash = Hash.new(0) primes.each do |prime| (1..n).each do |i| idx = 1 while prime*idx <= i prime_count_hash[prime] += 1 if i % prime*idx == 0 idx += 1 end end end prime_count_hash end puts factorial_div?(4, 6) puts factorial_div?(5, 12)
JavaScript
UTF-8
90
3.1875
3
[]
no_license
var age = prompt('Enter age', ''); alert('You will soon be ' + age + 1 + ' years old');
Rust
UTF-8
2,169
2.6875
3
[]
no_license
use account; use my_channel; use std::fs::File; use std::io::prelude::*; #[cfg(test)] mod AccountsDB { use super::*; #[test] fn create_works() { let db = account::AccountsDB::create(); println!("{:?}", db); } #[test] fn import_works() { let mut db = account::AccountsDB::create(); db.import("test.json"); println!("{:?}", db); } #[test] fn export_works() { let mut db = account::AccountsDB::create(); db.import("test.json"); db.export("test.json"); } #[test] fn query_found() { let mut db = account::AccountsDB::create(); db.import("test.json"); println!("{:?}", db.query("username").unwrap()); } #[test] fn query_notfound() { let mut db = account::AccountsDB::create(); db.import("test.json"); println!("{:?}", db.query("notfound")); } #[test] fn authorize_right_account() { let mut db = account::AccountsDB::create(); db.import("test.json"); println!("{:?}", db.authorize("username", "password").unwrap()); assert_eq!(db.authorize("username", "password").unwrap(), true); } #[test] fn authorize_wrong_account() { let mut db = account::AccountsDB::create(); db.import("test.json"); println!("{:?}", db.authorize("username", "wrong_password").unwrap()); assert_eq!(db.authorize("username", "wrong_password").unwrap(), false); } #[test] fn authorize_notfound() { let mut db = account::AccountsDB::create(); db.import("test.json"); println!("{:?}", db.authorize("notfound", "password")); } #[test] fn register_success() { let mut db = account::AccountsDB::create(); db.import("test.json"); println!("{:?}", db.register("new_account", "new_password")); println!("{:?}", db.query("new_account")); assert_eq!(db.exists("new_account"), true); } } #[cfg(test)] mod Channel { fn create_work() { let ch = my_channel::MyChannel::new("Channel name", "0.0.0.0:12110", 5, account::AccountsDB::new()) } }
Markdown
UTF-8
8,434
3.03125
3
[]
no_license
# Circro Circro is a Matlab based application for rendering nodes and edges as circular diagrams. Built with a code architecture similar to [MRIcroS](http://www.nitrc.org/projects/mricros/). ![4colorBars](readmeImgs/4colorBars.png) ##Requirements Tested on Matlab 2014. ##Installation 1. Download 2. Add to Matlab Path ##How to Use Launch GUI by typing below at Matlab command prompt: ```matlab Circro; ``` ###Render Node Labels Functions => Circro => Set/Add Node Labels => Choose labels file (example file at data/labels.xlsx) ![labels](readmeImgs/labels.png) ###Render Node Sizes Now we shall add node sizes to diagram from above Functions => Circro => Set/Add Node Sizes A pop up is shown asking if we wish to update the current diagram, or create a new one based on the sizes. Let's update the current diagram. ![sizesPopup](readmeImgs/sizesPopup.png) Choose data/sizes.xlsx for the sizes ![labelsSizesSameDiagram](readmeImgs/labelsSizesSameDiagram.png) ###Render Node Colors Functions => Circro => Set/Add Node Colors As there is a already a diagram, we are prompted if we wish to create a new diagram or update current. To highlight the ability to render multiple diagrams, choose "New", & then select data/colors.xlsx. ![colorsPopup](readmeImgs/colorsPopup.png) When prompted if you wish to choose a colorscheme, choose "yes" and then type "jet". ![labelsSizesSameColorsDiff](readmeImgs/labelsSizesSameColorsDiff.png) ###Toggle Labels The above colors diagram has the default labels. These can be toggled off via: Functions => Circro => Toggle Labels Make sure Circle Index 2 is selected for the labels to be toggled (index 2 because it was the second diagram added) ![toggleLabelsIndex2](readmeImgs/toggleLabelsIndex2.png) The labels are no longer displayed ![labelsSizesSameColorsWithNoLabelsDiff](readmeImgs/labelsSizesSameColorsWithNoLabelsDiff.png) ###Update Diagram Dimensions To prevent the overlay between the two diagrams, the dimensions (radius, label radius, & start radian) of either of the diagrams can be changed. Functions => Circro => Set Dimensions - select index 2 for colors diagram - select the following dimensions - radius .7 - label radius .8 (toggled off so won't be displayed anyway) - start radian 1.5708 (pi/2, default) ![colorsDimensionsPopup](readmeImgs/colorsDimensionsPopup.png) ![labelsSizesSameColorsSmallDiff](readmeImgs/labelsSizesSameColorsSmallDiff.png) ###Render Edge Weights Functions => Circro => Set/Add Edge Weights Choose update to add to the colors diagram, index 2. Than select data/matrix. A PDF of the edge weights will be displayed. A threshold of .96 is selected for this example ![edgesPdf](readmeImgs/edgesPdf.png) Select 'copper' for the edge weights color scheme. ![labelsSizesSameColorsSmallDiffEdges](readmeImgs/labelsSizesSameColorsSmallDiffEdges.png) Note the colorbars have different limits for the different data represented ###Support for Multiple Colorbars Circro provides support for rendering 3 colorbars for nodes, and 1 colorbar for edges. Colorbars associated with nodes are rendered on the left, and colorbars associated with edges are rendered on the right. If your diagram requires more than 3 colorbars on the left (for nodes) or more than 1 colorbar on the right (for edges), then manual positioning of the colorbars will be necessary to prevent overlap. To highlight the capability of representing multiple colorbars, we can add color to the diagram with sized nodes. Functions => Circro => Set/Add Node Colors => Update Circle (index 1) => data/colors.xslx => Set Color Scheme ('hot') ![sizesColored](readmeImgs/sizesColored.png) We will render a third diagram with the following steps: 1. Functions => Circro => Set/Add Node Colors => New => data/colors.xlsx => Set Color Scheme => 'bone' * Functions => Circro => Toggle Labels => Index 3 (turn off labels) * Functions => Circro => Set Dimensions (Index 3) => radius = .85, label radius = .85 (irrelevant because toggled off), start radian = 1.5708 (pi/2, default) ![4colorBars](readmeImgs/4colorBars.png) ###Update Edge Threshold Functions => Circro => Set Edge Threshold (should automatically set the index to the diagram with edges) => .93 ![lowerThresh](readmeImgs/lowerThresh.png) ###Simultaneously Render Diagram with Many Characteristics File => Circro => Add Diagram ![simultaneousOptions](readmeImgs/simultaneousOptions.png) ###Scripting All GUI functionality can be scripted. ####Code Architecture The [GUI callbacks](https://github.com/bonilhamusclab/circro/tree/master/+circro/+gui/) just obtain user input and than invoke a command in the [+circro/+commands folder](https://github.com/bonilhamusclab/circro/tree/master/+circro/+commands/). However, the GUI callback does not invoke the command directly, instead the command name & paramaters are passed to the "Circro" command. For example, the Set/Add Node Labels Callback invokes circro.commands.circro.setNodeLabels via: ``` Circro('circro.setNodeLabels', labelsFile, circleIndex); ``` Invoking a command through "Circro" ensures that the command history is recorded. ####Viewing Code History The commands corresponding to a particular GUI session can be viewed by: Functions => Echo instructions to command window The following history corresponds to the example shown above ``` %%Command History%% Circro('circro.setNodeLabels','data/labels.xlsx',1); Circro('circro.setNodeSizes','data/sizes.xlsx',1); Circro('circro.setNodeColors','data/colors.xlsx',2,'jet'); Circro('circro.toggleLabels',2); Circro('circro.setDimensions',0.7,0.8,1.5708,2); Circro('circro.setEdgeMatrix','data/matrix.xlsx',0.96,'copper',2); Circro('circro.setNodeColors','data/colors.xlsx',1,'hot'); Circro('circro.setNodeColors','data/colors.xlsx',3,'bone'); Circro('circro.toggleLabels',3); Circro('circro.setDimensions',0.85,0.85,1.5708,3); Circro('circro.setEdgeThreshold',0.92,2); %%%% ``` On the to-do list is to create documentation for each of the circro.commands. Until then, the inputs each command takes can be viewed by the command's associated code or by viewing the history output. ####Editing Graphics Via Code Circro is rendered as a Matlab figure, therefore features associated with Matlab plotting are available (data point selection, image export, adding text, etc..) The handle to the Matlab figure can be obtained by: ```matlab v = Circro; ``` It is possible to become familiar with v through exploring it's properties on the Matlab command prompt. This allows for setting properties of the figure & children via code, as shown in the example below, which changes a node's label. ```matlab v = Circro('circro.setNodeColors', 'data/colors.xlsx'); axesChild = v.Children(2); %1 is the colorbar for i = 1:length(axesChild.Children) graphObj = axesChild.Children(i); isLabel = isprop(graphObj, 'String'); isLabel13 = false; if isLabel, isLabel13 = strcmp(graphObj.String, '13'); end if isLabel13 set(graphObj, 'String', 'Special Node'); set(graphObj, 'horizontalalignment', 'right'); end end ``` ![Special Node](readmeImgs/specialNodeLabel.png) ##Data Inputs Circro expects excel files as input. Sample files may be found in the [data folder](https://github.com/bonilhamusclab/circro/tree/master/data) - Labels: - 2 columns with label names - left column labels rendered counter clock wise from start radian. - right column labels rendered clock wise from start radian - Colors - 2 columns with numbers ranging from 0 to 1 - color specified according to number & chosen color map - color map set in application, not in file - left column rendered counter clock wise from start radian - right colomn rendered clock wise from start radian - Sizes - same 2 column layout as labels & colors - specifies the distance from the node's outer edge to the radius - Matrix - matrix of size n x n (n is number of nodes) - the value corresponds to the edge strength between the nodes - only upper triangle of matrix is analyzed ##To Do List 1. Add Support for plain-text CSV 2. Add documentation for each of the circro.commands ##Contributions - [Dr. Bonilha Lab at MUSC](http://academicdepartments.musc.edu/neurosciences/neurology/research/bonilha/) - [Special thanks to JCMosher for providing code to render a label's text at the same angle as the corresponding node](https://github.com/bonilhamusclab/circro/issues/1)
C++
UTF-8
2,879
3.203125
3
[ "MIT" ]
permissive
#include <iostream> #include <fstream> #include <stdlib.h> #include <vector> #include <algorithm> #include <map> #include <utility> static const int pX = 0; static const int pY = 1; static const int pZ = 2; static const int vX = 3; static const int vY = 4; static const int vZ = 5; static const int aX = 6; static const int aY = 7; static const int aZ = 8; static const int PCOUNTER = 1000; static const int TEST = 1000; // tho', it needs only 10 tests :) static const std::string separators = ",><"; std::vector<int> parseLine(std::string line) { std::vector<int> tmp; size_t last = 0; for (int i = 0; i < 3; ++ i) { last = line.find_first_of(separators, last + 1) + 1; for (int j = 0; j < 3; ++ j) { size_t curr = line.find_first_of(separators, last + 1); tmp.push_back(std::stoi(line.substr(last, curr - last ))); last = curr + 1; } } return tmp; } void tick(std::vector<int> var[PCOUNTER], std::vector<int> ind) { for (const auto& i : ind) { var[i][pX] += (var[i][vX] += var[i][aX]); var[i][pY] += (var[i][vY] += var[i][aY]); var[i][pZ] += (var[i][vZ] += var[i][aZ]); } } bool solveCollisions(std::vector<int> var[PCOUNTER], std::vector<int>& ind) { std::map<std::vector<int>, std::vector<int> > M; bool collision = false; for (const auto& i : ind) { M[std::vector<int>(var[i].begin(), var[i].begin() + 3)].push_back(i); } for (const auto& x : M) { if (x.second.size() > 1) { collision = true; for (const auto& p : x.second) ind.erase(std::find(ind.begin(), ind.end(), p)); } } return collision; } int solveTask1(std::vector<int> var[PCOUNTER], int partNr) { int part = -1, min = (1 << 30); for (int i = 0; i < partNr; ++ i) { if (abs(var[i][aX]) + abs(var[i][aY]) + abs(var[i][aZ]) < min) { min = abs(var[i][aX]) + abs(var[i][aY]) + abs(var[i][aZ]); part = i; } } return part; } int solveTask2(std::vector<int> var[PCOUNTER], int partNr) { std::vector<int> ind; int noCollision = 0; for (int i = 0; i < partNr; ++ i) { ind.push_back(i); } while (noCollision < TEST) { tick(var, ind); if (solveCollisions(var, ind)) { noCollision = 0; } else { ++ noCollision; } } return ind.size(); } int main() { std::ifstream fin("data.in"); std::string line; std::vector<int> var[PCOUNTER]; int partNr = 0; while (std::getline(fin, line)) { var[partNr ++] = parseLine(line); } fin.close(); std::cout << "The answer for part1 is: " << solveTask1(var, partNr) << "\n"; std::cout << "The answer for part2 is: " << solveTask2(var, partNr) << "\n"; return 0; }
JavaScript
UTF-8
337
2.9375
3
[]
no_license
<!-- working with number--> var noOfSecsinaMinute=60; var noOfMinsinaHour=60; var noOfHoursinDays=24; var noOfDaysinWeek=7; var noOfDaysInYear=365; var noOfDaysInMonth=31; var noOfweeksInyear=52; var secondsPerDay = noOfSecsinaMinute * noOfMinsinaHour * noOfHoursinDays; document.write('There are '+secondsPerDay+' seconds in a day');
Markdown
UTF-8
13,573
2.828125
3
[]
no_license
Short Course of Stochastic Process ==================== ## Why we study a stochastic process for machine learning? - Machine Learning은 기본적으로 정적인 분포를 가진 데이터를 다룬다. - 그런데 실제적으로 보면 이는 미소 시간의 차이를 가진 상태의 즉, Continuous/Discrete Stochastic Process 처럼 컴퓨터에 인가된다. - 그러므로 Stochastic Process에서 다루는 수학적 기법들을 사용하여 보다 Machine Learning을 더 잘 이해할 수 있으며 - 동시에 뭔가 새로운 것을 만들어 낼 수도 있다. ### Stochastic Process 공부에서의 Tip - Linear Algebra와 Duality를 생각한다. - 왜 **random variable**은 많은 교과서에서 **Bold 체**로 쓰여 있을까? **벡터**처럼? - Linear Algebra에서 가장 중요한 연산은 **Inner Product** 이다. 그럼 **확률/통계**에서는? - Stochastic Process만의 특징들을 이해한다. - Wiener Process의 이해가 Stohastic Process의 공학적 이용의 90% - Markov Process 나아가 **Martingale** 특성의 이해 - 현대 Stochastic Process는 90년대 이후 Stochastic Calculus 없이 이해할 수 없다. Stochastic Process의 접근방법은 실로 다종 다양하나, 본 접근은 Stochastic Calculus에 기반하여 접근하는 방법론을 취한다. - Stochastic Process를 정의하기 위한 **대수구조는 집합**. 그러므로 집합 구조에 대한 정의를 내려야 한다. - 어떤 Topological Space의 특징을 가질 것인가. : **집합의 대수** - Stochastic Process는 무한(그러나 가부번)의 구조를 가져야 한다. ## Preliminaries ### $\sigma$ -Algebra (or $\sigma$-Fields) A $\sigma$-fields is a field(an Algebra), which is closed w.r.t.**countable unions** and **countable intersections** of its members, that is a collection of subset of that satisfies $$ \begin{align} &\varnothing, \Omega \in \mathcal{F} \\ &A \in \mathcal{F} \implies A^c \in \mathcal{F} \\ &A_1, A_2, \cdots, A_n \in \mathcal{F} \implies \cup_{n=1}^{\infty} A_n \in \mathcal{F}, \;\;\textit{and}\;\; \cap_{n=1}^{\infty} A_n \in \mathcal{F} \end{align} $$ - 가부번 집합연산의 결과를 포함하는 집합대수 : 가부번 (간략히 무한) 집합 연산이 가능해짐 - 무한번 발생하는 사건에 대한 해석이 가능 : 바로 Stochastic Process - 미분을 사용할 수 있는 여지가 발생 (Stochastic Differential Equation) ### Borel Set 일반적인 $\sigma$-fields의 구성 집합의 원소는 각종 사건 - {H,T} 처럼 임의의 모든 사건이 가능하다. - 가급적 사건이 어떤 숫자 이었으면 좋겠음 - 숫자로 이루어진 사건의 집합 (Borel Set), 그리고 $\sigma$-fields를 정의하고자 한다. #### Borel Class (or Borel $\sigma$-field) n 차원 유클리드 공간 $\mathbb{R}^n$의 모든 Open Set이 생성하는 $\sigma$-field중 가장 작은 것을 n 차원 Borel Class 혹은 Borel $\sigma$-field 라 한다. ##### Borel Set Borel Class의 원소가 Borel Set (즉, 숫자로 이루어진 사건. 혹은 Vector Space위에 정의된 사건 집합) ### Probablity Space #### Sample Space - 발생 가능한 모든 사건을 담고 있는 집합, 전체 사건 집합 - Example - 시간 $t \in [1, T]$에서 특정 증권의 주가 $S_t$ - $\Omega = \{ w : w = (S_1, S_2, \cdots S_t) \}$, t 차원의 vector, 순서쌍, 이러한 순서쌍 혹은 벡터 전체는 무수히 많다. 그래서 Stochastic Process #### 사건 집합의 Field 앞에서 살펴본 $\sigma$ - field 와 같은 의미 - $\mathcal{F}_0$ : $\mathcal{F}_0 = \{\varnothing, \Omega \}$, $S_t$ 값이 없으므로 - $\mathcal{F}_1$ : Set $A={w:w=S_1}$ then $\mathcal{F}_1 = \{\varnothing, A, \Omega-A, \Omega\} - 살펴보면 $t$가 증가 할 수록 field는 더욱 커져야 한다. : 이 점에서 새로운 개념 (**Filtration** 도출) #### Probability A **Probability** $P$ on $(\Omega, \mathcal{F})$ is a set function on $\mathcal{F}$, s.t. - $P(\Omega) = 1$ - If $A \in \mathcal{F}$ then $P(A^c) = 1 - P(A)$ - Countable Additivity ( $\sigma$- Additivity) - If $A_1, A_2, \cdots A_n \in \mathcal{F}$ are mutually exclusive, then - $ P(\cup_{n=1}^{\infty}) = \sum_{n=1}^{\infty} P(A_n)$ - 확률은 결국 집합의 크기를 계측하는 함수, 확률측도라한다. #### Probability Space $(\Omega, \mathcal{F}, P)$ #### Filtration A Filtration $\mathbb{F}$ is a **collection of fields** such that $$ \mathbb{F} = \{\mathcal{F}_0, \mathcal{F}_1 \cdots \mathcal{F}_t, \cdot \mathcal{F}_T \} \;\; \mathcal{F}_t \subset \mathcal{F}_{t+1} $$ - 시간이 지날 수록 더욱 많은 정보가 들어온다는 의미 #### Random Variable - 확률 변수, 사건을 실수값에 대응 시키는 변수 - 일반적 확률변수 : $X : (\Omega, \mathcal{F}) \rightarrow (E, \mathcal{E})$ - 이때, $E = \mathbb{R}, \mathcal{E} = \mathcal{B}(\mathbb{R})$ 이면 확률변수라 한다. ($\mathcal{B}$ : Borel Set으로 이루어진 $\sigma$-field) - 즉, 확률변수는 사건을 숫자로 표시할 수 있게 하는 것 - 그리고 Topology를 그대로 보존하여 확률측도를 사용할 수 있게 한다. ### Stochastic Process #### Definition A stochastic process is a collection of random variables , each random variable $\{ X_t \}$ is on for $t=1, 2, ..., T$. #### A stochastic process adapted to Filtration - When a r.v. $X_t$ is $\mathcal{F}_t$-measurable i.e. if $\forall t \in [0, T], X_t$ is a random vriable on $\mathcal{F}_t$, we say $X_t$ is adapted to the Filtration $\mathbb{F}$ - 즉, 시간에 따라 확장되는 $\mathcal{F}_t$를 정의역으로 하는 확률변수의 모임을 의미한다. #### Filtration Generated by a stochastic Process 역으로 Stochastic process에 의해 Filtration을 정의할 수 있다. 즉, (확률)위상공간 $\mathcal{F}_t = \sigma(\{X_s, 0 \leq s \leq t \})$ 과 stochastic process $\{ X_t\}$ 가 주어졌을 떄, 이는 r.v. $X_s$에 의해 Generated 된 $\sigma$-Field 이고 이러한 $\sigma$-Field로 만들어진 Filtration을 Filtration Generated by a stochastic Process 라 하며 가장 자연적이고 일반적인 형태의 Filtration 이다. - Machine Learning에서 Data가 시간에 따라 들어온다고 하면 그것 역시 Stochastic Process 입장에서 하나의 Filtration을 구성하는 것이며 이를 $\mathcal{D}$ 라고 표시할 수 있다. #### Predictable Process Filtration $\mathbb{F} = \{\mathcal{F}_0, \mathcal{F}_1 \cdots \mathcal{F}_t, \cdot \mathcal{F}_T \} \;\; \mathcal{F}_t \subset \mathcal{F}_{t+1}$ 이 주어졌을 떄, 각 $t$에 대하여 시간 $t$의 Stochastic process $H_t$가 $\mathcal{F}_{t-1}$ measurable 일때. - 즉, 바로 직전 시간까지 들어온 데이터 조합으로 $H_t$를 가측할 수 있을 때를 Predictable Process - 실제 Filter 설계에 있어 가장 중요한 개념이다. ## Wiener Process (Brownian Motion) 이런 Stochastic Process를 생각해보자. R.V. $X_\tau$가 확률 $\frac{1}{2}$로 1의 값을 $\frac{1}{2}$로 -1의 값을 가진다고 하자. 그리고 그 크기는 $\Delta x$로 균일하다고 하면 이러한 Stochastic Process $W_\tau$는 다음과 같다. $$ W_\tau = \Delta x (X_1 + X_2 + \cdots + x_{[\tau/\Delta \tau]}) $$ $X_k$의 평균은 0 이고 $\mathbb{E}X_n X_m = \left(1 \cdot 1 \cdot p^2 + 2 \cdot 1 \cdot -1 \cdot p(1-p) + -1 \cdot -1\cdot (1-p)^2 \right)_{p=1/2} = 0$ 이므로 $$ \begin{align} \mathbb{E}(W_\tau) &= \Delta x \mathbb{E}(\sum_{k=1}^{\tau/\Delta \tau} X_k) = \Delta x \frac{\tau}{\Delta \tau}\mathbb{E}(X_k) = 0 \\ \mathbb{E}(W_\tau - \mathbb{E}(W_\tau))^2 &= \mathbb{E}W_\tau^2 = (\Delta x)^2 \mathbb{E} (\sum_{k=1}^{\tau/\Delta \tau} X_k)^2 = (\Delta x)^2 \cdot \frac{\tau}{\Delta \tau} \end{align} $$ 여기에서 $\Delta x = 1$, $\tau = t \Delta \tau$ 라고 하면 $Var(W_t) = t $. ### Definition : Gaussian Process A stochastic process ${X_t, t \geq 0}$ is called a Gaussian Process, if $X_{t_1}, \cdots X_{t_n}$ has multivariate **normal distribution** for all $t_1 \cdots t_n$. - 위에서 정의한 $W_t$의 경우 De-Moivre-Laplace Theorem (1738)에 의해 $t$가 충분히 클 때, 혹은 $\Delta \tau$가 충분히 작을 떄, 이항분포의 근사분포는 정규분포를 따른다. - 다시말해, $t = t_k - t_{k-1}$ 가 많은 $\Delta \tau$로 만들어질 수 있으면 Transition Probability $p(t, x, y)$는 Gaussin 혹은 정규분포를 따른다. ### Definition : Wiener Process A wtochastic process $W_t \in mathbb{R}$ defined for $t \in [0, \infty]$ such that - $W_0 = 0$ a.s. - the sample paths $ t \mapsto W_t$ are a.s. continuous - for any finite sequence of times $0 < t_1 < \cdots < t_n$ and Borel sets $A_1, \cdots A_n \subset \mathbb{R}$, $$ P(W_t \in A_1, \cdots, W_{t_n} \in A_n) = \int_{A_1} \cdots \int_{A_n} p(t_1, 0, x_1)p(t_2 -t_1, x_1, x_2) \cdots p(t_n - t_{n-1}, x_{n-1}, x_n) dx_1 \cdots dx_n $$ where $p(t,x,y)=\frac{1}{\sqrt{2 \pi t}} \exp(\frac{-(x - y)^2}{2t})$ for $x, y \in \mathbb{R}$ and $t > 0$. It is called a **Transition Probability**. ### Wiener Process의 특성 - 초기시간 0 , 위치 0 에서 시간 $t$에서 $x$ 까지의 전이 확률은 $f_{W_t}(x) = p(t,0,x)=\frac{1}{\sqrt{2 \pi t}} \exp(\frac{-x^2}{2t})$ 이것은 다음 2차 편미분 방정식의 해이다. $$ \frac{\partial f}{\partial t} = \frac{1}{2} \frac{\partial^2 f}{\partial x^2} $$ 이는 Wiener Process의 해석에 미분을 사용할 수 있다는 의미이다. - $W_s, W_t$의 Covariance는 $\mathbb{E}(W_t, W_s) = \min(t, s)$. - $\mathbb{E}(|W_t- W_s|^2) = |t - s|$. 이는 Independent Increment 라는 강력한 개념과 연결된다. (Linear Algebra와 연결된다.) - 전이 확률은 독립사건의 확률 분포함수이다 고로 $f_{W_s, W_t}(x,y)= p(s, 0, x)p(t-s, x, y)$ 따라서 $$ P(W_t - W_s \in A) = \int_A p(t -s, 0, u)du $$ 따라서 **Stationary Process** 이다. (시간 Shift에 대하여 분포 특성이 달라지지 않는다. 여기에 $t \rightarrow \infty$에서 평균과 Variance 특성이 일치하므로 **Ergodic process**이다.) ### Independent Increments Wiener Process의 Increments $W_t - W_s$는 **independent** 이다. i.e. for $t > s$ $$ \mathbb{E}(W_s(W_t - W_s)) = 0 \;\;\because \mathbb{E}(W_s(W_t - W_s)) = \mathbb{E}(W_s W_t) - \mathbb{E}(W_s^2 ) = \min(t,s) - s = 0 $$ 따라서 for $0 \leq r \leq s \leq t \leq u$ $$ \mathbb{E}((W_u - W_t)(W_s - W_r)) = \mathbb{E}(W_uW_s) - E(W_uW_r) - E(W_t W_s) - E(W_t W_r) = s - r -s + r = 0 $$ ### Note - Stochastic Proces에서 Covariance 라는 것은 Random Variable에 대한 **Inner Product**이다. 즉, 이렇게 생각해야 한다. $$ \mathbb{E}(X_t X_s| A) = \int_A x p(X_t = x|A) y p(X_s = y|A) dx dy = \int_A x y p(W_t = x|A)p(X_s = y |A) dx dy = \langle X_t, X_s \rangle $$ - Independent Increments의 의미 $$ W_s \perp (W_t - W_s), \;\; (W_u - W_t) \perp (W_s - W_r) $$ - 만일 Independent Increments가 매우 작은 구간에서 정의된다면 such that $$dW_t = \lim_{\Delta t \rightarrow 0} W_{t+\Delta t} - W_t$$ 서로 다른 $dW_t$, $dW_s$ 는 서로 Orthogonal 하다. 즉, $$ \mathbb{E}(dW_t dW_s) = 0 \implies dW_t \perp dW_s \Leftrightarrow \langle dW_t, dW_s \rangle = 0$$ - 그러므로 $dW_t$는 Orthogonal 한 좌표계를 만들어줄 수 있다. 일반적인 Cartesian 좌표계를 줄 수 있다. - **Stochastic Process가 Linear Algebra 로 치환되어 해석된다. 기하 구조를 줄 수 있다.** - $dW_t$ 에 대한 **미분 구조**를 줄 수 있다. 기하 구조를 줄 수 있으므로 ## Martingale A Stochastic Process $\{X_t, t \geq 0 \}$ adapted to a filtration $\mathbb{F}$ is a **martingale** if for any t, - $\{X(t), t \geq 0 \}$ is integrable, i.e. $|\mathbb{E}(X_t)| < \infty$ - For any $s < t$ (Core Definition) $$ \mathbb{E}(X_t | \mathcal{F}_s) = X_s $$ - Super Martingale $\mathbb{E}(X_t | \mathcal{F}_s) \leq X_s$ , Sub Martingale $\mathbb{E}(X_t | \mathcal{F}_s) \geq X_s$ ### Doob-Levy Martingale Let $Y$ be an integrable r.v. , that is, $\mathbb{E}(|Y|) < \infty$, then $M_t = E(Y | \mathcal{F}_t)$ is a martingale. $$ \mathbb{E}(M_t | \mathcal{F}_s) = \mathbb{E}(\mathbb{E}(Y|\mathcal{F}_t)|\mathcal{F}_s) = \mathbb{E}(Y|\mathcal{F}_s) = M_s $$ - 만일, 시간 $t$까지의 Filtration 의 한 $\sigma$-algebra $\mathcal{F}_t$ 을 그떄까지 정보의 집합 혹은 입력 데이터의 집합이라고 하면 이것을 통해 **미래의 데이터 값을 유추**할 수 있다는 의미가 된다. - **Winer Process**는 **Martingale** 이다. i.e. $\mathbb{E}(W_t | \mathcal{F}_s) = W_s$, for $s < t$. ### Martingale의 특징 - $\{W_t^2 - t \}$ 는 Martingale 이다. i.e. $\mathbb{E}(W_t^2 - t | \mathcal{F}_s) = W_s^2 - s - $\{\exp (W_t - \frac{1}{2} t ) \}$ 는 Martingale 이다. i.e. $\mathbb{E}(exp (W_t - \frac{1}{2} t)| \mathcal{F}_s) = exp (W_s - \frac{1}{2} s )$ - **Independent Increment의 Kernel Space** : $W_t - W_s \perp \mathcal{F}_s$ ### Martingale의 의의 - **Stochastic Calculus 를 정의할 수 있다.**. 고로 미분을 통해 과거 데이터에서 **미래를 예측**할 수 있다. **없던 것을 과거의 것을 조합하여 만들 수 있다.** - 기존 Winer Process를 조합하여 만든 Process에 대한 해석을 엄밀하게 할 수 있다. (By Girsanov Theorem) - GAN (Generative Adversarial Network)을 엄밀하게 정의하고 뭔가 새로운 알고리즘을 만들 수 있다. - 2차 비선형 편미분 방정식의 일반 해를 비교적 쉽게 구할 수 있다. (예: Feynmann-Kac 방정식)
JavaScript
UTF-8
3,668
2.703125
3
[]
no_license
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var template_1 = require("./template"); var dom_1 = require("./dom"); /** * The return type of `html`, which holds a Template and the values from * interpolated expressions. */ var TemplateResult = /** @class */ (function () { function TemplateResult(strings, values, type) { this.strings = strings; this.values = values; this.type = type; } /** * Returns a string of HTML used to create a `<template>` element. */ TemplateResult.prototype.getHTML = function () { var endIndex = this.strings.length - 1; var html = ''; for (var i = 0; i < endIndex; i++) { var s = this.strings[i]; var match = template_1.matchLastAttributeName(s); if (match) { // We're starting a new bound attribute. // Add the safe attribute suffix, and use unquoted-attribute-safe // marker. html += s.substr(0, match.index) + match[1] + match[2] + template_1.boundAttributeSuffix + match[3] + template_1.marker; } else { // We're either in a bound node, or trailing bound attribute. // Either way, nodeMarker is safe to use. html += s + template_1.nodeMarker; } } html += this.strings[endIndex]; return html; }; // getHTML():string{ // let content = ''; // this.strings.forEach((str,index)=>{ // const val = this.values[index]; // content += str; // if(val != null){ // content += val; // } // }); // return content; // } TemplateResult.prototype.getTemplateElement = function () { var template = document.createElement('template'); template.innerHTML = this.getHTML(); return template; }; return TemplateResult; }()); exports.TemplateResult = TemplateResult; /** * A TemplateResult for SVG fragments. * * This class wraps HTMl in an `<svg>` tag in order to parse its contents in the * SVG namespace, then modifies the template to remove the `<svg>` tag so that * clones only container the original fragment. */ var SVGTemplateResult = /** @class */ (function (_super) { __extends(SVGTemplateResult, _super); function SVGTemplateResult() { return _super !== null && _super.apply(this, arguments) || this; } SVGTemplateResult.prototype.getHTML = function () { return "<svg>" + _super.prototype.getHTML.call(this) + "</svg>"; }; SVGTemplateResult.prototype.getTemplateElement = function () { var template = _super.prototype.getTemplateElement.call(this); var content = template.content; var svgElement = content.firstChild; content.removeChild(svgElement); dom_1.reparentNodes(content, svgElement.firstChild); return template; }; return SVGTemplateResult; }(TemplateResult)); exports.SVGTemplateResult = SVGTemplateResult;
Java
UTF-8
29,649
2.21875
2
[ "EPL-1.0", "Classpath-exception-2.0", "LicenseRef-scancode-unicode", "LicenseRef-scancode-warranty-disclaimer", "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-protobuf", "CDDL-1.1", "W3C", "APSL-1.0", "GPL-2.0-only", "Apache-2.0", "LicenseRef-scancode-public-domain", "SAX-PD", "MPL-2.0", "MPL-1.1", "CC-PDDC", "BSD-2-Clause", "Plexus", "EPL-2.0", "CDDL-1.0", "LicenseRef-scancode-proprietary-license", "MIT", "CC0-1.0", "APSL-2.0", "LicenseRef-scancode-unknown-license-reference", "LGPL-2.1-only", "LGPL-2.1-or-later", "UPL-1.0" ]
permissive
/* * Copyright (c) 2000, 2023, Oracle and/or its affiliates. * * Licensed under the Universal Permissive License v 1.0 as shown at * https://oss.oracle.com/licenses/upl. */ // ---- class: com.tangosol.coherence.component.util.collections.WrapperMap package com.tangosol.coherence.component.util.collections; /* * Integrates * java.util.Map * using Component.Dev.Compiler.Integrator.Wrapper */ @SuppressWarnings({"deprecation", "rawtypes", "unused", "unchecked", "ConstantConditions", "DuplicatedCode", "ForLoopReplaceableByForEach", "IfCanBeSwitch", "RedundantArrayCreation", "RedundantSuppression", "SameParameterValue", "TryFinallyCanBeTryWithResources", "TryWithIdenticalCatches", "UnnecessaryBoxing", "UnnecessaryUnboxing", "UnusedAssignment"}) public class WrapperMap extends com.tangosol.coherence.component.util.Collections implements java.util.Map { // ---- Fields declarations ---- /** * Property Map * * Wrapped Map */ private transient java.util.Map __m_Map; private static com.tangosol.util.ListMap __mapChildren; // Static initializer static { __initStatic(); } // Default static initializer private static void __initStatic() { // register child classes __mapChildren = new com.tangosol.util.ListMap(); __mapChildren.put("EntrySet", WrapperMap.EntrySet.class); __mapChildren.put("KeySet", WrapperMap.KeySet.class); __mapChildren.put("Values", WrapperMap.Values.class); } // Default constructor public WrapperMap() { this(null, null, true); } // Initializing constructor public WrapperMap(String sName, com.tangosol.coherence.Component compParent, boolean fInit) { super(sName, compParent, false); if (fInit) { __init(); } } // Main initializer public void __init() { // private initialization __initPrivate(); // containment initialization: children // signal the end of the initialization set_Constructed(true); } // Private initializer protected void __initPrivate() { super.__initPrivate(); } //++ getter for static property _Instance /** * Getter for property _Instance.<p> * Auto generated */ public static com.tangosol.coherence.Component get_Instance() { return new com.tangosol.coherence.component.util.collections.WrapperMap(); } //++ getter for static property _CLASS /** * Getter for property _CLASS.<p> * Property with auto-generated accessor that returns the Class object for a * given component. */ public static Class get_CLASS() { return WrapperMap.class; } //++ getter for autogen property _Module /** * This is an auto-generated method that returns the global [design time] * parent component. * * Note: the class generator will ignore any custom implementation for this * behavior. */ private com.tangosol.coherence.Component get_Module() { return this; } //++ getter for autogen property _ChildClasses /** * This is an auto-generated method that returns the map of design time * [static] children. * * Note: the class generator will ignore any custom implementation for this * behavior. */ protected java.util.Map get_ChildClasses() { return __mapChildren; } //++ java.util.Map integration // Access optimization // properties integration // methods integration public void clear() { getMap().clear(); } public boolean containsKey(Object oKey) { return getMap().containsKey(oKey); } public boolean containsValue(Object oValue) { return getMap().containsValue(oValue); } private java.util.Set entrySet$Router() { return getMap().entrySet(); } public java.util.Set entrySet() { WrapperMap.EntrySet set = (WrapperMap.EntrySet) _newChild("EntrySet"); set.setSet(entrySet$Router()); return set; } public Object get(Object oKey) { return getMap().get(oKey); } public boolean isEmpty() { return getMap().isEmpty(); } private java.util.Set keySet$Router() { return getMap().keySet(); } public java.util.Set keySet() { WrapperMap.KeySet set = (WrapperMap.KeySet) _newChild("KeySet"); set.setSet(keySet$Router()); return set; } public Object put(Object oKey, Object oValue) { return getMap().put(oKey, oValue); } public void putAll(java.util.Map map) { getMap().putAll(map); } public Object remove(Object oKey) { return getMap().remove(oKey); } public int size() { return getMap().size(); } private java.util.Collection values$Router() { return getMap().values(); } public java.util.Collection values() { WrapperMap.Values col = (WrapperMap.Values) _newChild("Values"); col.setCollection(values$Router()); return col; } //-- java.util.Map integration // From interface: java.util.Map // Declared at the super level public boolean equals(Object obj) { if (obj instanceof WrapperMap) { return getMap().equals( ((WrapperMap) obj).getMap()); } return false; } // Accessor for the property "Map" /** * Getter for property Map.<p> * Wrapped Map */ public java.util.Map getMap() { return __m_Map; } // From interface: java.util.Map // Declared at the super level public int hashCode() { return getMap().hashCode(); } public static WrapperMap instantiate(java.util.Map map) { WrapperMap mapWrapper = new WrapperMap(); mapWrapper.setMap(map); return mapWrapper; } // Accessor for the property "Map" /** * Setter for property Map.<p> * Wrapped Map */ public void setMap(java.util.Map map) { _assert(map != null && getMap() == null, "Map is not resettable"); __m_Map = (map); } // Declared at the super level public String toString() { return super.toString() + ":\n" + getMap(); } // ---- class: com.tangosol.coherence.component.util.collections.WrapperMap$EntrySet @SuppressWarnings({"deprecation", "rawtypes", "unused", "unchecked", "ConstantConditions", "DuplicatedCode", "ForLoopReplaceableByForEach", "IfCanBeSwitch", "RedundantArrayCreation", "RedundantSuppression", "SameParameterValue", "TryFinallyCanBeTryWithResources", "TryWithIdenticalCatches", "UnnecessaryBoxing", "UnnecessaryUnboxing", "UnusedAssignment"}) public static class EntrySet extends com.tangosol.coherence.component.util.collections.wrapperSet.EntrySet { // ---- Fields declarations ---- private static com.tangosol.util.ListMap __mapChildren; // Static initializer static { __initStatic(); } // Default static initializer private static void __initStatic() { // register child classes __mapChildren = new com.tangosol.util.ListMap(); __mapChildren.put("Entry", WrapperMap.EntrySet.Entry.class); __mapChildren.put("Iterator", WrapperMap.EntrySet.Iterator.class); } // Default constructor public EntrySet() { this(null, null, true); } // Initializing constructor public EntrySet(String sName, com.tangosol.coherence.Component compParent, boolean fInit) { super(sName, compParent, false); if (fInit) { __init(); } } // Main initializer public void __init() { // private initialization __initPrivate(); // containment initialization: children // signal the end of the initialization set_Constructed(true); } // Private initializer protected void __initPrivate() { super.__initPrivate(); } //++ getter for static property _Instance /** * Getter for property _Instance.<p> * Auto generated */ public static com.tangosol.coherence.Component get_Instance() { return new com.tangosol.coherence.component.util.collections.WrapperMap.EntrySet(); } //++ getter for static property _CLASS /** * Getter for property _CLASS.<p> * Property with auto-generated accessor that returns the Class object * for a given component. */ public static Class get_CLASS() { return WrapperMap.EntrySet.class; } //++ getter for autogen property _Module /** * This is an auto-generated method that returns the global [design * time] parent component. * * Note: the class generator will ignore any custom implementation for * this behavior. */ private com.tangosol.coherence.Component get_Module() { return this.get_Parent(); } //++ getter for autogen property _ChildClasses /** * This is an auto-generated method that returns the map of design time * [static] children. * * Note: the class generator will ignore any custom implementation for * this behavior. */ protected java.util.Map get_ChildClasses() { return __mapChildren; } // ---- class: com.tangosol.coherence.component.util.collections.WrapperMap$EntrySet$Entry @SuppressWarnings({"deprecation", "rawtypes", "unused", "unchecked", "ConstantConditions", "DuplicatedCode", "ForLoopReplaceableByForEach", "IfCanBeSwitch", "RedundantArrayCreation", "RedundantSuppression", "SameParameterValue", "TryFinallyCanBeTryWithResources", "TryWithIdenticalCatches", "UnnecessaryBoxing", "UnnecessaryUnboxing", "UnusedAssignment"}) public static class Entry extends com.tangosol.coherence.component.util.collections.wrapperSet.EntrySet.Entry { // ---- Fields declarations ---- // Default constructor public Entry() { this(null, null, true); } // Initializing constructor public Entry(String sName, com.tangosol.coherence.Component compParent, boolean fInit) { super(sName, compParent, false); if (fInit) { __init(); } } // Main initializer public void __init() { // private initialization __initPrivate(); // signal the end of the initialization set_Constructed(true); } // Private initializer protected void __initPrivate() { super.__initPrivate(); } //++ getter for static property _Instance /** * Getter for property _Instance.<p> * Auto generated */ public static com.tangosol.coherence.Component get_Instance() { return new com.tangosol.coherence.component.util.collections.WrapperMap.EntrySet.Entry(); } //++ getter for static property _CLASS /** * Getter for property _CLASS.<p> * Property with auto-generated accessor that returns the Class * object for a given component. */ public static Class get_CLASS() { return WrapperMap.EntrySet.Entry.class; } //++ getter for autogen property _Module /** * This is an auto-generated method that returns the global [design * time] parent component. * * Note: the class generator will ignore any custom implementation * for this behavior. */ private com.tangosol.coherence.Component get_Module() { return this.get_Parent().get_Parent(); } } // ---- class: com.tangosol.coherence.component.util.collections.WrapperMap$EntrySet$Iterator @SuppressWarnings({"deprecation", "rawtypes", "unused", "unchecked", "ConstantConditions", "DuplicatedCode", "ForLoopReplaceableByForEach", "IfCanBeSwitch", "RedundantArrayCreation", "RedundantSuppression", "SameParameterValue", "TryFinallyCanBeTryWithResources", "TryWithIdenticalCatches", "UnnecessaryBoxing", "UnnecessaryUnboxing", "UnusedAssignment"}) public static class Iterator extends com.tangosol.coherence.component.util.collections.wrapperSet.EntrySet.Iterator { // ---- Fields declarations ---- // Default constructor public Iterator() { this(null, null, true); } // Initializing constructor public Iterator(String sName, com.tangosol.coherence.Component compParent, boolean fInit) { super(sName, compParent, false); if (fInit) { __init(); } } // Main initializer public void __init() { // private initialization __initPrivate(); // signal the end of the initialization set_Constructed(true); } // Private initializer protected void __initPrivate() { super.__initPrivate(); } //++ getter for static property _Instance /** * Getter for property _Instance.<p> * Auto generated */ public static com.tangosol.coherence.Component get_Instance() { return new com.tangosol.coherence.component.util.collections.WrapperMap.EntrySet.Iterator(); } //++ getter for static property _CLASS /** * Getter for property _CLASS.<p> * Property with auto-generated accessor that returns the Class * object for a given component. */ public static Class get_CLASS() { return WrapperMap.EntrySet.Iterator.class; } //++ getter for autogen property _Module /** * This is an auto-generated method that returns the global [design * time] parent component. * * Note: the class generator will ignore any custom implementation * for this behavior. */ private com.tangosol.coherence.Component get_Module() { return this.get_Parent().get_Parent(); } } } // ---- class: com.tangosol.coherence.component.util.collections.WrapperMap$KeySet @SuppressWarnings({"deprecation", "rawtypes", "unused", "unchecked", "ConstantConditions", "DuplicatedCode", "ForLoopReplaceableByForEach", "IfCanBeSwitch", "RedundantArrayCreation", "RedundantSuppression", "SameParameterValue", "TryFinallyCanBeTryWithResources", "TryWithIdenticalCatches", "UnnecessaryBoxing", "UnnecessaryUnboxing", "UnusedAssignment"}) public static class KeySet extends com.tangosol.coherence.component.util.collections.wrapperSet.KeySet { // ---- Fields declarations ---- private static com.tangosol.util.ListMap __mapChildren; // Static initializer static { __initStatic(); } // Default static initializer private static void __initStatic() { // register child classes __mapChildren = new com.tangosol.util.ListMap(); __mapChildren.put("Iterator", WrapperMap.KeySet.Iterator.class); } // Default constructor public KeySet() { this(null, null, true); } // Initializing constructor public KeySet(String sName, com.tangosol.coherence.Component compParent, boolean fInit) { super(sName, compParent, false); if (fInit) { __init(); } } // Main initializer public void __init() { // private initialization __initPrivate(); // containment initialization: children // signal the end of the initialization set_Constructed(true); } // Private initializer protected void __initPrivate() { super.__initPrivate(); } //++ getter for static property _Instance /** * Getter for property _Instance.<p> * Auto generated */ public static com.tangosol.coherence.Component get_Instance() { return new com.tangosol.coherence.component.util.collections.WrapperMap.KeySet(); } //++ getter for static property _CLASS /** * Getter for property _CLASS.<p> * Property with auto-generated accessor that returns the Class object * for a given component. */ public static Class get_CLASS() { return WrapperMap.KeySet.class; } //++ getter for autogen property _Module /** * This is an auto-generated method that returns the global [design * time] parent component. * * Note: the class generator will ignore any custom implementation for * this behavior. */ private com.tangosol.coherence.Component get_Module() { return this.get_Parent(); } //++ getter for autogen property _ChildClasses /** * This is an auto-generated method that returns the map of design time * [static] children. * * Note: the class generator will ignore any custom implementation for * this behavior. */ protected java.util.Map get_ChildClasses() { return __mapChildren; } // ---- class: com.tangosol.coherence.component.util.collections.WrapperMap$KeySet$Iterator @SuppressWarnings({"deprecation", "rawtypes", "unused", "unchecked", "ConstantConditions", "DuplicatedCode", "ForLoopReplaceableByForEach", "IfCanBeSwitch", "RedundantArrayCreation", "RedundantSuppression", "SameParameterValue", "TryFinallyCanBeTryWithResources", "TryWithIdenticalCatches", "UnnecessaryBoxing", "UnnecessaryUnboxing", "UnusedAssignment"}) public static class Iterator extends com.tangosol.coherence.component.util.collections.WrapperSet.Iterator { // ---- Fields declarations ---- // Default constructor public Iterator() { this(null, null, true); } // Initializing constructor public Iterator(String sName, com.tangosol.coherence.Component compParent, boolean fInit) { super(sName, compParent, false); if (fInit) { __init(); } } // Main initializer public void __init() { // private initialization __initPrivate(); // signal the end of the initialization set_Constructed(true); } // Private initializer protected void __initPrivate() { super.__initPrivate(); } //++ getter for static property _Instance /** * Getter for property _Instance.<p> * Auto generated */ public static com.tangosol.coherence.Component get_Instance() { return new com.tangosol.coherence.component.util.collections.WrapperMap.KeySet.Iterator(); } //++ getter for static property _CLASS /** * Getter for property _CLASS.<p> * Property with auto-generated accessor that returns the Class * object for a given component. */ public static Class get_CLASS() { return WrapperMap.KeySet.Iterator.class; } //++ getter for autogen property _Module /** * This is an auto-generated method that returns the global [design * time] parent component. * * Note: the class generator will ignore any custom implementation * for this behavior. */ private com.tangosol.coherence.Component get_Module() { return this.get_Parent().get_Parent(); } } } // ---- class: com.tangosol.coherence.component.util.collections.WrapperMap$Values @SuppressWarnings({"deprecation", "rawtypes", "unused", "unchecked", "ConstantConditions", "DuplicatedCode", "ForLoopReplaceableByForEach", "IfCanBeSwitch", "RedundantArrayCreation", "RedundantSuppression", "SameParameterValue", "TryFinallyCanBeTryWithResources", "TryWithIdenticalCatches", "UnnecessaryBoxing", "UnnecessaryUnboxing", "UnusedAssignment"}) public static class Values extends com.tangosol.coherence.component.util.collections.WrapperCollection { // ---- Fields declarations ---- private static com.tangosol.util.ListMap __mapChildren; // Static initializer static { __initStatic(); } // Default static initializer private static void __initStatic() { // register child classes __mapChildren = new com.tangosol.util.ListMap(); __mapChildren.put("Iterator", WrapperMap.Values.Iterator.class); } // Default constructor public Values() { this(null, null, true); } // Initializing constructor public Values(String sName, com.tangosol.coherence.Component compParent, boolean fInit) { super(sName, compParent, false); if (fInit) { __init(); } } // Main initializer public void __init() { // private initialization __initPrivate(); // containment initialization: children // signal the end of the initialization set_Constructed(true); } // Private initializer protected void __initPrivate() { super.__initPrivate(); } //++ getter for static property _Instance /** * Getter for property _Instance.<p> * Auto generated */ public static com.tangosol.coherence.Component get_Instance() { return new com.tangosol.coherence.component.util.collections.WrapperMap.Values(); } //++ getter for static property _CLASS /** * Getter for property _CLASS.<p> * Property with auto-generated accessor that returns the Class object * for a given component. */ public static Class get_CLASS() { return WrapperMap.Values.class; } //++ getter for autogen property _Module /** * This is an auto-generated method that returns the global [design * time] parent component. * * Note: the class generator will ignore any custom implementation for * this behavior. */ private com.tangosol.coherence.Component get_Module() { return this.get_Parent(); } //++ getter for autogen property _ChildClasses /** * This is an auto-generated method that returns the map of design time * [static] children. * * Note: the class generator will ignore any custom implementation for * this behavior. */ protected java.util.Map get_ChildClasses() { return __mapChildren; } // ---- class: com.tangosol.coherence.component.util.collections.WrapperMap$Values$Iterator @SuppressWarnings({"deprecation", "rawtypes", "unused", "unchecked", "ConstantConditions", "DuplicatedCode", "ForLoopReplaceableByForEach", "IfCanBeSwitch", "RedundantArrayCreation", "RedundantSuppression", "SameParameterValue", "TryFinallyCanBeTryWithResources", "TryWithIdenticalCatches", "UnnecessaryBoxing", "UnnecessaryUnboxing", "UnusedAssignment"}) public static class Iterator extends com.tangosol.coherence.component.util.collections.WrapperCollection.Iterator { // ---- Fields declarations ---- // Default constructor public Iterator() { this(null, null, true); } // Initializing constructor public Iterator(String sName, com.tangosol.coherence.Component compParent, boolean fInit) { super(sName, compParent, false); if (fInit) { __init(); } } // Main initializer public void __init() { // private initialization __initPrivate(); // signal the end of the initialization set_Constructed(true); } // Private initializer protected void __initPrivate() { super.__initPrivate(); } //++ getter for static property _Instance /** * Getter for property _Instance.<p> * Auto generated */ public static com.tangosol.coherence.Component get_Instance() { return new com.tangosol.coherence.component.util.collections.WrapperMap.Values.Iterator(); } //++ getter for static property _CLASS /** * Getter for property _CLASS.<p> * Property with auto-generated accessor that returns the Class * object for a given component. */ public static Class get_CLASS() { return WrapperMap.Values.Iterator.class; } //++ getter for autogen property _Module /** * This is an auto-generated method that returns the global [design * time] parent component. * * Note: the class generator will ignore any custom implementation * for this behavior. */ private com.tangosol.coherence.Component get_Module() { return this.get_Parent().get_Parent(); } } } }
JavaScript
UTF-8
1,691
4.5625
5
[]
no_license
/* P: Take the number 735291 and rotate it by one digit to the left, getting 352917. Next, keep the first digit fixed in place and rotate the remaining digits to get 329175. Keep the first two digits fixed in place and rotate again to get 321759. Keep the first three digits fixed in place and rotate again to get 321597. Finally, keep the first four digits fixed in place and rotate the final two digits to get 321579. The resulting number is called the maximum rotation of the original number. Write a function that takes an integer as an argument, and returns the maximum rotation of that integer. You can (and probably should) use the rotateRightmostDigits function from the previous exercise. D: Input = Output = A: - - - - - - */ function rotateArray(arr) { if (!Array.isArray(arr)) { return undefined; } else if (arr == 0) { return []; } return arr.slice(1).concat(arr[0]); } function rotateRightmostDigits(num, rotation) { if (String(num).length < rotation) { return undefined; } let splitDigits = [...String(num)]; let rotatedArray = rotateArray(splitDigits.slice(-rotation)); return +splitDigits.join``.slice(0, -rotation).concat(rotatedArray.join``); } function maxRotation(num) { let length = String(num).length for (length; length > 0; length--) { num = rotateRightmostDigits(num, length); } return num; } console.log(maxRotation(735291)); // 321579 console.log(maxRotation(3)); // 3 console.log(maxRotation(35)); // 53 console.log(maxRotation(105)); // 15 -- the leading zero gets dropped console.log(maxRotation(8703529146)); // 7321609845
Python
UTF-8
17,759
2.765625
3
[]
no_license
import pygame import random import math import time background_color = (0,0,255) colorInt = 0; forward = True (width, height) = (1000, 700) screen = pygame.display.set_mode((width, height)) pygame.display.set_caption('Human test') running = True pygame.init() myfont = pygame.font.SysFont("monospace", 72) state = 0 selected = 0 gravity = 7 offset = 0 class Barrier(): def __init__ (self,(x,y),leng,wid): self.x = x self.y = y self.leng = leng self.wid = wid self.rect = pygame.Rect(x,y,leng,wid) def update(self): for e in enemies: if(self.rect.colliderect(e.contactRect)): if(e.y+290>self.y and e.x>self.x and e.x<self.x+self.leng): e.y = self.y-290 if(e.x+120>self.x and e.x-120<self.x and e.y+290 > self.y): e.x = self.x-50 if(e.x-120<self.x+self.leng and e.x+120 > self.x+self.leng and e.y+290 > self.y): e.x = self.x+self.leng+120 if(self.rect.colliderect(player.contactRect)): if(player.y+290>self.y): player.falling = False player.walking = True player.y-=gravity if(player.y+290>self.y and player.x>self.x and player.x<self.x+self.leng): player.y = self.y-290 if(player.x+120>self.x and player.x-120<self.x and player.y+290 > self.y): player.x = self.x-120 if(player.x-120<self.x+self.leng and player.x+120 > self.x+self.leng and player.y+290 > self.y): player.x = self.x+self.leng+120 self.rect = pygame.Rect(self.x,self.y,self.leng,self.wid) def display(self): pygame.draw.rect(screen,(165,42,42),self.rect,0) class Space(Barrier): def update(self): print("") def display(self): print("") class Enemy(object): def __init__(self,(x,y), health,damage): self.x = x self.y = y self.health = health self.damage = damage self.dead = False self.contactRect = pygame.Rect(x-10,y-10,20,20) def update(self): if(self.contactRect.colliderect(player.contactRect)): player.health-=self.damage player.gettingHit = True walking = False jumping = False if(player.y+290<self.y): player.y-=50 if(player.x>self.x): player.x+=30 player.updatePos() player.updateStatus() player.display() else: player.x-=30 player.updatePos() player.updateStatus() player.display() self.health-=self.damage if(self.health<=0): self.dead = True enemies.remove(self) self.contactRect = pygame.Rect(self.x-10,self.y-10,20,20) def display(self): pygame.draw.circle(screen,(255,0,255),(self.x,self.y),10,0) pygame.draw.rect(screen,(255,0,0),self.contactRect,1) class Torbot(Enemy): def __init__(self,(x,y),health,damage): self.x = x self.y = y self.health = health self.damage = damage self.dead = False self.rect = pygame.Rect(x-10,y-10,20,20) self.headColor = (255,255,255) self.bodyColor = (255,0,0) self.armColor = (0,0,0) self.head = ((x-120,y-50),(x+120,y-50),(x+80,y+50),(x-80,y+50)) self.body = (x-80,y+50,160,200) self.arm1start = (self.x-150,self.y+100) self.arm1finish = (self.x-80,self.y+100) self.arm2start = (self.x+80,self.y+100) self.arm2finish = (self.x+150,self.y+100) self.leg1start = (self.x-80,self.y+250) self.leg1finish = (self.x-80-45,self.y+250+45) self.leg2start = (self.x+80,self.y+250) self.leg2finish = (self.x+80+45,self.y+250+45) self.leye = (x-60,y-30) self.reye = (x+60,y-30) self.antennaStart = (self.x,self.y-50) self.antennaFinish = (self.x+20,self.y-80) self.contactRect = pygame.Rect(self.x-120,y-50,240,350) def update(self): x = self.x y = self.y self.head = ((x-120,y-50),(x+120,y-50),(x+80,y+50),(x-80,y+50)) self.body = (x-80,y+50,160,200) self.leg1start = (self.x-80,self.y+250) self.leg1finish = (self.x-80-45,self.y+250+45) self.leg2start = (self.x+80,self.y+250) self.leg2finish = (self.x+80+45,self.y+250+45) self.arm1start = (self.x-150,self.y+100) self.arm1finish = (self.x-80,self.y+100) self.arm2start = (self.x+80,self.y+100) self.arm2finish = (self.x+150,self.y+100) self.leye = (x-60,y-10) self.reye = (x+60,y-10) self.antennaStart = (self.x,self.y-50) self.antennaFinish = (self.x+20,self.y-80) self.y+=gravity super(Torbot, self).update() self.contactRect = pygame.Rect(self.x-120,y-50,240,350) def display(self): pygame.draw.rect(screen,self.bodyColor,self.body,0) pygame.draw.polygon(screen,self.headColor,self.head,0) pygame.draw.line(screen,self.armColor,self.leg1start,self.leg1finish,5) pygame.draw.line(screen,self.armColor,self.leg2start,self.leg2finish,5) pygame.draw.line(screen,self.armColor,self.arm1start,self.arm1finish,5) pygame.draw.line(screen,self.armColor,self.arm2start,self.arm2finish,5) pygame.draw.circle(screen,self.armColor,self.leye,15,5) pygame.draw.circle(screen,self.armColor,self.reye,15,5) pygame.draw.circle(screen,self.armColor,self.leye,5,0) pygame.draw.circle(screen,self.armColor,self.reye,5,0) pygame.draw.line(screen,self.armColor,self.antennaStart,self.antennaFinish,5) pygame.draw.circle(screen,self.armColor,self.antennaFinish,10,0) pygame.draw.rect(screen,self.bodyColor,self.contactRect,1) class Item(): def __init__(self,(x,y)): self.x = x self.y = y self.val = 1 def update(self): self.val+=1 def display(): pygame.draw.circle(screen,(255,255,255),(self.x,self.y),40,0) class Health(Item) : def __init__(self,(x,y),value): self.x = x self.y = y self.value = value self.dead = False self.rect = pygame.Rect(x-40,y-40,80,80) def update(self): if(self.rect.colliderect(player.contactRect)): player.health+=self.value self.dead = True self.rect = pygame.Rect(self.x-40,self.y-40,80,80) def display(self): pygame.draw.circle(screen,(255,255,255),(self.x,self.y),40,0) pygame.draw.rect(screen,(255,0,0),self.rect,1) class Ammo(Item): def __init__(self,(x,y),value): self.x = x self.y = y self.value = value self.dead = False self.rect = pygame.Rect(x-40,y-40,80,80) def update(self): if(self.rect.colliderect(player.contactRect)): player.ammo+=self.value self.dead = True self.rect = pygame.Rect(self.x-40,self.y-40,80,80) def display(self): pygame.draw.circle(screen,(255,0,255),(self.x,self.y),40,0) pygame.draw.rect(screen,(255,0,0),self.rect,1) class Laser(Item): def __init__(self,(x,y),(a,b)): self.x = x self.y = y self.a = a self.b = b self.dead = False self.timer = 5 def update(self): self.timer-=1 if(not self.dead and self.timer ==0): self.dead = True rect = pygame.Rect(self.a,self.b,1,1) for e in enemies: if(rect.colliderect(e.contactRect)): e.health-=2 def display(self): pygame.draw.line(screen,(255,255,0),(self.x,self.y),(self.a,self.b),5) class Player(): def __init__(self, (x,y), health) : self.x = x self.y = y self.health = health self.ammo = 5 self.maxHealth = 100 self.maxAmmo = 5 self.walking = True self.falling = False self.jumping = False self.gettingHit = False self.dead = False self.contactRect = pygame.Rect(x-120,y-50,240,340) self.delay = 0 self.flinchTimer = 0 self.skinColor = (226,188,122) self.bodyColor = (255,0,0) self.armColor = (0,255,0) self.legColor = (0,0,255) self.eyeColor = (255,255,255) self.pupilColor = (0,0,0) self.noseColor = (255,0,0) self.mouthColor = (255,0,0) self.hairColor = (0,0,0) self.buckleColor = (255,255,0) self.shoeColor = (0,0,20) self.body = (x-50,y+80,100,100) self.rSleeve = (x-80,y+50,40,50) self.lSleeve = (x+40,y+50,40,50) self.rArm1 = (x-120,y+60,40,30) self.lArm1 = (x+80,y+60,40,30) self.lleg = (x-50,y+180 ,30,100) self.rleg = (x+20,y+180,30,100) self.leye = (x-20,y-10) self.reye = (x+20,y-10) self.nose = ((x,y),(x-5,y+10),(x+5,y+10)) self.mouthRect = (x-20,y+10,40,30) self.hairRect = (x-30, y-50, 60,20) self.pantRect = (x-50,y+150,100,30) self.buckleRect = (x-10,y+160,20,10) self.lShoeRect = (x-70,y+270,50,20) self.rShoeRect = (x+20,y+270,50,20) def update(self): self.updatePos() self.updateStatus() def updatePos(self): if(self.walking): if(pygame.key.get_pressed()[pygame.K_w] != 0): self.y-=5 self.jumping = True self.walking = False self.delay = 15 elif(self.jumping): if(self.delay>0): self.delay-=1 self.y-=20 else: self.falling = True self.jumping = False walking = False if(self.gettingHit): self.skinColor = (255,0,0) self.gettingHit = False else: self.skinColor = (226,188,122) if(pygame.key.get_pressed()[pygame.K_d] != 0): self.x+=5 if(pygame.key.get_pressed()[pygame.K_a] != 0): self.x-=5 if(self.y<50): self.y=50 elif(self.y>700): self.dead = True self.y+=gravity self.contactRect = (self.x-50,self.y-50,100,340) def updateStatus(self): if(pygame.key.get_pressed()[pygame.K_SPACE] != 0 and self.ammo > 0): dist = 501 nearest = None for e in enemies: if math.hypot(e.x-self.x,e.y-self.y) <=dist: nearest = e dist = math.hypot(e.x-self.x,e.y-self.y) if nearest != None and dist<500: self.ammo-=1 (mouseX, mouseY) = pygame.mouse.get_pos() laser = Laser((self.x,self.y),(mouseX,mouseY)) items.append(laser) time.sleep(0.1) if(self.health>self.maxHealth): self.health = self.maxHealth if(self.ammo > self.maxAmmo): self.ammo = self.maxAmmo if(self.health<=0): self.dead = True def display(self): x = (int(self.x)) y = (int(self.y)) self.body = (x-50,y+80,100,100) self.rSleeve = (x-80,y+50,40,50) self.lSleeve = (x+40,y+50,40,50) self.rArm1 = (x-120,y+60,40,30) self.lArm1 = (x+80,y+60,40,30) self.lleg = (x-50,y+180 ,30,100) self.rleg = (x+20,y+180,30,100) self.leye = (x-20,y-10) self.reye = (x+20,y-10) self.nose = ((x,y),(x-5,y+10),(x+5,y+10)) self.mouthRect = (x-20,y+10,40,30) self.hairRect = (x-30, y-50, 60,20) self.pantRect = (x-50,y+150,100,30) self.buckleRect = (x-10,y+160,20,10) self.lShoeRect = (x-70,y+270,50,20) self.rShoeRect = (x+20,y+270,50,20) pygame.draw.rect(screen,self.bodyColor, self.body, 0) pygame.draw.circle(screen,self.bodyColor,(x,y+80),50,0) pygame.draw.rect(screen,self.bodyColor,self.rSleeve,0) pygame.draw.rect(screen,self.bodyColor,self.lSleeve,0) pygame.draw.rect(screen,self.skinColor,self.rArm1,0) pygame.draw.rect(screen,self.skinColor,self.lArm1,0) pygame.draw.ellipse(screen,self.shoeColor,self.lShoeRect,0) pygame.draw.ellipse(screen,self.shoeColor,self.rShoeRect,0) pygame.draw.rect(screen,self.legColor,self.lleg,0) pygame.draw.rect(screen,self.legColor,self.rleg,0) pygame.draw.rect(screen,self.legColor,self.pantRect,0) pygame.draw.rect(screen,self.buckleColor,self.buckleRect,2); pygame.draw.circle(screen,self.skinColor,(x,y),50,0) pygame.draw.circle(screen, self.eyeColor, self.leye,10,0) pygame.draw.circle(screen, self.eyeColor, self.reye,10,0) pygame.draw.circle(screen, self.pupilColor, self.leye,5,0) pygame.draw.circle(screen, self.pupilColor, self.reye,5,0) pygame.draw.polygon(screen,self.noseColor,self.nose,0) pygame.draw.arc(screen,self.mouthColor,self.mouthRect,3,6.5,2) pygame.draw.arc(screen,self.hairColor,self.hairRect,0,3.14,10) pygame.draw.rect(screen,(255,0,0),self.contactRect,1) pygame.draw.rect(screen,(255,255,255),(0,0,150,60),0) pygame.draw.rect(screen,(255,255,255),(0,60,150,60),0) label = myfont.render(str(self.health), 10, (0,255,0)) label2 = myfont.render(str(self.ammo), 10, (0,255,0)) screen.blit(label, (0,0)) screen.blit(label2, (0,60)) def shiftEntities(stuff,forward): for a in stuff: if(forward): a.x-=int(offset*0.01) else: a.x+=int(offset*0.01) def generateTerrain(): length = 1000 while length < 100000: if(random.randint(0,1)==0): curLen = random.randint(100,150) length+=curLen else: curLen = random.randint(50,600) curHeight = random.randint(0,200) bar = Barrier((length,700-curHeight),curLen,curHeight) length+=curLen tiles.append(bar) def resetGame(): player = Player((130,300), 100) enemy = Enemy((500,500), 50,10) enemy2 = Enemy((600,600), 50,10) health = Health((300,200),10) ammo = Ammo((300,100),10) barrier = Barrier((0,650),400,50) barrier2 = Barrier((400,500),300,200) barrier3 = Barrier((700,650),300,50) tiles = [barrier,barrier2,barrier3] enemies = [enemy,enemy2] items = [health,ammo] player = Player((130,300), 100) enemy = Enemy((500,500), 50,10) enemy2 = Enemy((600,600), 50,10) torbot = Torbot((800,200),50,10) health = Health((300,200),10) ammo = Ammo((300,100),10) barrier = Barrier((0,650),400,50) barrier2 = Barrier((400,500),300,200) barrier3 = Barrier((700,650),300,50) tiles = [barrier,barrier2,barrier3] generateTerrain() enemies = [torbot] items = [health,ammo] while running: time.sleep(0.01) screen.fill(background_color) if(forward): colorInt+=2 else: colorInt-=2 if(colorInt==254 or colorInt==0): forward = not(forward) background_color = (10,colorInt,100) if state == 0: options = ["Start"] labels = [] selectedColor = (0,255,0) otherColor = (255,0,0) if pygame.key.get_pressed()[pygame.K_UP] != 0: if(selected > 0): selected -= 1 else: selected = len(options)-1 elif pygame.key.get_pressed()[pygame.K_DOWN] != 0: if(selected == len(options)-1): selected = 0 else: selected += 1 elif pygame.key.get_pressed()[pygame.K_RETURN] != 0: state = 1 for a in range(0,len(options)): if(a==selected): label = myfont.render(options[a], 10,selectedColor) else: label = myfont.render(options[a], 10,otherColor) screen.blit(label, (400,a*300 + 400)) if state == 1: offset = abs(player.x - (width/2)) if(offset>5): if(player.x>width/2): shiftEntities(tiles,True) shiftEntities(enemies,True) shiftEntities(items,True) player.x-=int(offset*0.01) elif(player.x<width/2): shiftEntities(tiles,False) shiftEntities(enemies,False) shiftEntities(items,False) player.x+=int(offset*0.01) player.update() for t in tiles: t.update() t.display() for e in enemies: if(not e.dead): e.update() e.display() else: remove(e) for i in items: if(not i.dead): i.update() i.display() else: items.remove(i) player.display() if(player.dead): state = 3 if state == 3: screen.fill((255,0,0)) label = myfont.render('You dun goofed', 10, (0,255,255)) screen.blit(label, (200,300)) ## label2 = myfont.render('Retry?' , 10, (0,255,0)) ## screen.blit(label2,(300,500)) ## if pygame.key.get_pressed()[pygame.K_RETURN] != 0: ## print('Reset') ## state = 0 ## running = True ## resetGame() ## player.dead = False pygame.display.flip() for event in pygame.event.get(): if event.type == pygame.QUIT: running = False pygame.display.quit() pygame.display.quit()
PHP
UTF-8
576
3.796875
4
[]
no_license
<?php namespace Hackathon\LevelA; class Palindrome { private $str; public function __construct($str) { $this->str = $str; } /** * This function creates a palindrome with his $str attributes * If $str is abc then this function return abccba * * @TODO * @return string */ public function generatePalindrome() { $rev = ''; for ($i = mb_strlen($this->str); $i>=0; $i--){ $rev .= mb_substr($this->str, $i, 1); } $res = $this->str. $rev; return $res; } }
Markdown
UTF-8
1,265
2.65625
3
[ "MIT", "CC-BY-3.0" ]
permissive
# Arch Update Indicator > Creates a taskbar icon that indicates if updates are available and provides a context menu to inspect and install them. Uses wxpython to create a taskbar icon that visually indicates if updates are available using `checkupdates` from the pacman-contrib package. You can use `UPDATE_CMD` environment variable to configure the command that will be executed to update (default is `sudo pacman -Syu`). The `ICONS_FOLDER` environment variable is used to configure the path where the icons are stored (default is `/usr/share/pixmaps/archupdate-indicator`). With `UPDATE_PERIOD` the time between checking for updates is set in ms (default 1h). Use `TERMINAL` to change the terminal emulator (default is `xterm`). ## Installation ### Manual installation ```sh # install dependencies pacman -S pacman-contrib python-wxpython git clone 'https://github.com/epsilontheta/archupdate-indicator.git' cd archupdate-indicator/ cp archupdate-indicator.py /usr/local/bin/ cp -r img/ /usr/share/pixmaps/archupdate-indicator ``` ### AUR https://aur.archlinux.org/packages/archupdate-indicator/ ## Release History * 1.0.0 * Add return code 2 handling of checkupdates * 0.0.2 * Add additional environment variables * 0.0.1 * Initial release
C#
UTF-8
4,930
2.953125
3
[]
no_license
using System; using System.Collections; namespace RailwayReservation { /// <summary> /// This class inherits User class and implements User class /// used to implement the functionalities of Clerk /// </summary> class BookingClerk : User { /// <summary> /// Readonly property password to retrieve /// </summary> public new string Password { get { return RailwayData.clerkDetails[1].ToString(); } } /// <summary> /// Readonly property ClerkID to retrieve /// </summary> public int ClerkID { get { return (int)RailwayData.clerkDetails[0]; } } /// <summary> /// For booking the tickets - abstract method defined in derived class /// </summary> /// <param name="customerID">ID of the customer</param> /// <param name="trainID">TrainID of the train</param> /// <param name="serviceType">service type selected by user</param> /// <param name="noOfSeats">noofseats to be booked</param> /// <param name="ticketStatus">ticket status of booking ticket</param> public override void BookTicket(int customerID, int trainID, string serviceType, int noOfSeats, out string ticketStatus) { ticketStatus = "WaitingList"; int index = 0; Ticket bookTicket = new Ticket(); foreach (Seats item in RailwayData.seats) { index = RailwayData.seats.IndexOf(item); Seats searchSeat = (Seats)item; if (searchSeat.TrainID == trainID && searchSeat.ServiceType == serviceType) { RailwayData.seats.Remove(searchSeat); searchSeat.NumberOfSeats = searchSeat.NumberOfSeats - noOfSeats; RailwayData.seats.Insert(index, searchSeat); bookTicket.TicketID = rn.Next(100, 1000); bookTicket.CustomerID = customerID; bookTicket.DateOfBooking = DateTime.Now.Date.ToString("dd-mmm-yyyy"); Console.Write("\nEnter the dateof journey :"); bookTicket.DateOfJourney = Console.ReadLine(); bookTicket.FromStation = ((TrainSchedule)RailwayData.trainSchedule[trainID]).FromStation; bookTicket.ToStation = ((TrainSchedule)RailwayData.trainSchedule[trainID]).ToStation; bookTicket.TotalFare = searchSeat.FarePerPerson * noOfSeats; bookTicket.TrainID = trainID; bookTicket.ServiceType = serviceType; bookTicket.NumberOfSeats = noOfSeats; bookTicket.PnrNumber = rn.Next(1000, 2000).ToString(); if (searchSeat.NumberOfSeats > noOfSeats) { ticketStatus = "Booked"; } else { ticketStatus = "Waiting"; } bookTicket.TicketStatus = ticketStatus; bookTicket.Passengers = new ArrayList(); for (int count = 0; count < noOfSeats; count++) { Console.WriteLine("\nEnter the passenger details \n"); Passenger passenger = AddPassengerDetails(bookTicket.PnrNumber, count); bookTicket.Passengers.Add(passenger); } RailwayData.ticketDetails.Add(bookTicket.PnrNumber, bookTicket); Console.WriteLine("PNR Number :" + bookTicket.PnrNumber); serializerRef.Serialize("myTicket.xml", bookTicket); break; } } } /// <summary> /// To cancel the tickets /// </summary> /// <param name="customerID">ID of the user</param> /// <param name="pnrNumber">pnrnumber if the passenger</param> public override void CancelTickets(int customerID, string pnrNumber) { ((Ticket)RailwayData.ticketDetails[pnrNumber]).TicketStatus = "Cancelled"; int index = 0; Ticket cancelTicket = (Ticket)RailwayData.ticketDetails[pnrNumber]; foreach (Seats item in RailwayData.seats) { index = RailwayData.seats.IndexOf(item); Seats searchSeat = (Seats)item; if (searchSeat.TrainID == cancelTicket.TrainID && searchSeat.ServiceType == cancelTicket.ServiceType) { RailwayData.seats.Remove(searchSeat); searchSeat.NumberOfSeats = searchSeat.NumberOfSeats + cancelTicket.NumberOfSeats; RailwayData.seats.Insert(index, searchSeat); } } } } }
C#
UTF-8
6,759
3.109375
3
[]
no_license
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; namespace Ensembler { public class Function { const float INTERVAL_TIME = 1.0f / 60; // Time of each frame in seconds Movement movement; Vector2 startPos = new Vector2(0,0); Vector2 midPos = new Vector2(0,0); Vector2 endPos = new Vector2(0,0); Vector2 shiftPos = new Vector2(0, 0); bool isStraightLine = false; /// <summary> /// The number of intervals /// </summary> public int Size { get; private set; } public Vector2[] Positions { get; private set; } public Vector2[] Slopes { get; private set; } public Vector2[] drawPositions { get; private set; } public void drawPosition() { List<Vector2> draw = new List<Vector2>(); float lastPx = -1; float lastPy = -1; foreach (Vector2 p in Positions) { if ((lastPx < 0 || Math.Sqrt((lastPx - p.X) * (lastPx - p.X) + (lastPy - p.Y) * (lastPy - p.Y)) > 5)) { draw.Add(p); lastPx = p.X; lastPy = p.Y; } } drawPositions = draw.ToArray(); } /// <summary> /// Draws a curve between startCoordinate and endCoordinate of movement according to the max offset, /// specified by amp. Drawn using a sine function with rotation /// Note that both Positions and slope have length of number of intervals + 1. This is for drawing purpose only. /// </summary> /// <param name="movement"></param> /// <param name="bpm"></param> /// <param name="amp"></param> public Function(Movement movement, int bpm, float amp) { this.movement = movement; Size = (int)((movement.endBeat - movement.startBeat + 1) / (float)bpm * 60 / INTERVAL_TIME) * 8; Positions = new Vector2[Size + 1]; // Change coordinates so that (0,0) is bottom left // Original start and ending positions specified by XML Vector2 oStartPos = new Vector2(movement.startCoordinate.X, movement.startCoordinate.Y); Vector2 oEndPos = new Vector2(movement.endCoordinate.X, movement.endCoordinate.Y); shiftPos = oStartPos; endPos = oEndPos - shiftPos; if (amp == 0) { isStraightLine = true; Position(); } else { Vector2 endPosPrime = new Vector2(Vector2.Distance(oStartPos, oEndPos), 0); Vector2 midPosPrime = new Vector2(endPosPrime.X / 2, 2 * amp); // Rotation angle double theta = Math.Atan((oEndPos.Y - oStartPos.Y) / (oEndPos.X - oStartPos.X)); if (oEndPos.X < oStartPos.X) theta += Math.PI; double midPosX = Math.Cos(theta) * midPosPrime.X - Math.Sin(theta) * midPosPrime.Y; double midPosY = Math.Sin(theta) * midPosPrime.X + Math.Cos(theta) * midPosPrime.Y; midPos = new Vector2((float)midPosX, (float)midPosY); Position(); } } /// <summary> /// Set each value in the position array to the appropriate value /// </summary> /// <param name="startPos">P0 of the Bezier curve</param> /// <param name="midPos">P1 of the Bezier curve</param> /// <param name="endPos">P2 of the Bezier curve</param> /// <param name="size">Number of intervals over which to draw the curve</param> /// <param name="isStraightline">True if the curve is a straight line</param> public void Position() { float t = 0; float incre = 1 / (float)Size; if (isStraightLine) // straight line { for (int i = 0; i < Size + 1; i++) { Positions[i] = new Vector2((1 - t) * startPos.X + t * endPos.X + shiftPos.X, GameEngine.HEIGHT - ((1 - t) * startPos.Y + t * endPos.Y + shiftPos.Y)); t += incre; } } else // curve { for (int i = 0; i < Size + 1; i++) { Positions[i] = new Vector2((1 - t * t) * startPos.X + 2 * (1 - t) * t * midPos.X + t * t * endPos.X + shiftPos.X, GameEngine.HEIGHT - ((1 - t * t) * startPos.Y + 2 * (1 - t) * t * midPos.Y + t * t * endPos.Y + shiftPos.Y)); t += incre; } } drawPosition(); } /// <summary> /// Compute the an array of slope /// </summary> /// <param name="size">Number of intervals over which to compute the slopes</param> /// <param name="isStraightline">True if the curve is a straight line</param> public Vector2[] Slope(int size) { Slopes = new Vector2[size+1]; if (isStraightLine) // straight line { Vector2 slope = Vector2.Normalize(new Vector2(endPos.X - startPos.X, startPos.Y - endPos.Y)); for (int i = 0; i < size + 1; i++) { Slopes[i] = slope; } } else // curve { float t = 0; float incre = 1 / (float)size; Vector2 lastPos = new Vector2((1 - t * t) * startPos.X + 2 * (1 - t) * t * midPos.X + t * t * endPos.X, (1 - t * t) * startPos.Y + 2 * (1 - t) * t * midPos.Y + t * t * endPos.Y); t += incre; Slopes[0] = new Vector2(0, 0); // this value is never used in movement evaluator for (int i = 1; i < size + 1; i++) { Vector2 newPos = new Vector2((1 - t * t) * startPos.X + 2 * (1 - t) * t * midPos.X + t * t * endPos.X, (1 - t * t) * startPos.Y + 2 * (1 - t) * t * midPos.Y + t * t * endPos.Y); Vector2 posDiff = new Vector2(newPos.X - lastPos.X, newPos.Y - lastPos.Y); Slopes[i] = Vector2.Normalize(new Vector2(posDiff.X / incre, -posDiff.Y / incre)); t += incre; } } return Slopes; } } }
Markdown
UTF-8
24,795
2.90625
3
[ "MIT" ]
permissive
<!-- README.md is generated from README.Rmd. Please edit that file --> # pdqr: Work with Custom Distribution Functions <!-- badges: start --> [![R build status](https://github.com/echasnovski/pdqr/workflows/R-CMD-check/badge.svg)](https://github.com/echasnovski/pdqr/actions) [![Coverage status](https://codecov.io/gh/echasnovski/pdqr/branch/master/graph/badge.svg)](https://app.codecov.io/gh/echasnovski/pdqr?branch=master) [![CRAN](https://www.r-pkg.org/badges/version/pdqr?color=blue)](https://cran.r-project.org/package=pdqr) [![Dependencies](https://tinyverse.netlify.com/badge/pdqr)](https://CRAN.R-project.org/package=pdqr) [![Downloads](http://cranlogs.r-pkg.org/badges/pdqr)](https://cran.r-project.org/package=pdqr) <!-- badges: end --> Create, transform, and summarize custom random variables with distribution functions (analogues of `p*()`, `d*()`, `q*()`, and `r*()` functions from base R), all of which called “pdqr-functions”. General idea is to work with manually created distributions which can be described in four interchangeable functional ways. Typical usage is to: 1. Create pdqr-function from sample or data frame (with `new_*()` family), and/or convert from some other existing distribution function (with `as_*()` family). 2. Make necessary transformations with `form_*()` family. 3. Compute summary values with `summ_*()` family. Two types of pdqr-functions, representing different types of distributions, are supported: - **Type “discrete”**: random variable has *finite number of output values*. Pdqr-function is explicitly defined by the collection of its values with their corresponding probability. Usually is used when underlying distribution is discrete (even if in theory there are infinite number of output values). - **Type “continuous”**: random variable has *infinite number of output values in the form of continuous random variable*. It is explicitly defined by piecewise-linear density function with finite support and values. Usually is used when underlying distribution is continuous (even if in theory it has infinite support and/or density values). Implemented approaches often emphasize approximate and numerical solutions: - All distributions assume **finite support** (output values are bounded from below and above) and **finite values of density function** (density function in case of “continuous” type can’t go to infinity). - Some methods implemented with **simulation techniques**. **Note** that to fully use this package, one needs to be familiar with basics of probability theory (concepts such as probability, distribution, density, etc.). This README covers the following topics: - How to install in [Installation](#installation). - How to quickly start using ‘pdqr’ by looking at [Quick examples](#pdqr-quick). - How to create pdqr-function from sample or data frame in [Create with `new_*()`](#pdqr-create). - How to convert existing distribution functions to pdqr-functions in [Convert with `as_*()`](#pdqr-convert). - How to transform distribution in [Transform with `form_*()`](#pdqr-transform). - How to summarize distribution in [Summarize with `summ_*()`](#pdqr-summarize). - What are the other packages with similar functionality in [Similar packages](#similar-packages). ## Installation ‘pdqr’ is not yet on CRAN. You can install the development version from [GitHub](https://github.com/) with: ``` r # install.packages("devtools") devtools::install_github("echasnovski/pdqr") ``` ## <a id="pdqr-quick"></a> Quick examples Generate a sample from a distribution defined by some reference sample: ``` r # Treat input sample as coming from a continuous distribution r_mpg <- new_r(mtcars$mpg, type = "continuous") r_mpg(n = 10) #> [1] 17.3792362 10.4822955 22.8221407 21.8118788 15.5166760 16.3005293 20.5809388 16.8043292 #> [9] 21.1901692 19.9680967 ``` Compute winsorized mean: ``` r # Import 'magrittr' to use pipe operator `%>%` library(magrittr) # Take a sample mtcars$mpg %>% # Create pdqr-function of any class treating input as discrete new_d(type = "discrete") %>% # Winsorize tails form_tails(level = 0.1, method = "winsor", direction = "both") %>% # Compute mean of distribution summ_mean() #> [1] 20.19375 ``` Compute and visualize distribution of difference of sample means: ``` r # Compute distribution of first sample mean treating input as continuous mpg_vs0 <- mtcars$mpg[mtcars$vs == 0] d_vs0 <- new_d(mpg_vs0, "continuous") (d_vs0_mean <- form_estimate( d_vs0, stat = mean, sample_size = length(mpg_vs0) )) #> Density function of continuous type #> Support: ~[12.14822, 20.63362] (511 intervals) # Compute distribution of second sample mean treating input as continuous mpg_vs1 <- mtcars$mpg[mtcars$vs == 1] d_vs1 <- new_d(mpg_vs1, "continuous") (d_vs1_mean <- form_estimate( d_vs1, stat = mean, sample_size = length(mpg_vs1) )) #> Density function of continuous type #> Support: ~[18.42035, 31.00767] (511 intervals) # Compute distribution of difference of sample means using random simulation (mpg_diffmean <- d_vs0_mean - d_vs1_mean) #> Density function of continuous type #> Support: ~[-15.97734, 0.93274] (511 intervals) # Visualize with base `plot()` plot(mpg_diffmean, main = "Distribution of difference of sample means") ``` ![](man/figures/README-pdqr-quick_diff-means-1.png)<!-- --> Compute and visualize 95% highest density region for mixture of normal distributions: ``` r # Create a list of pdqr-functions norm_list <- list( as_d(dnorm), as_d(dnorm, mean = 2, sd = 0.25), as_d(dnorm, mean = 4, sd = 0.5) ) # Form a mixture with custom weights norm_mix <- form_mix(norm_list, weights = c(0.6, 0.2, 0.2)) # Compute 95% highest density region (norm_hdr <- summ_hdr(norm_mix, level = 0.95)) #> left right #> 1 -1.82442072 2.53095750 #> 2 3.19649819 4.79334429 # Visualize plot(norm_mix, main = "95% highest density region for normal mixture") region_draw(norm_hdr) ``` ![](man/figures/README-pdqr-quick_mixture-hdr-1.png)<!-- --> ## <a id="pdqr-create"></a> Create with `new_*()` All `new_*()` functions create a pdqr-function of certain class (“p”, “d”, “q”, or “r”) and type (“discrete” or “continuous”) based on sample or data frame (with appropriate structure): - **Sample input** is converted into data frame of appropriate structure that defines distribution (see next list item). It is done based on type. For “discrete” type it gets tabulated with frequency of unique values serving as their probability. For “continuous” type distribution density is estimated using [`density()`](https://rdrr.io/r/stats/density.html) function if input has at least 2 elements. For 1 element special “dirac-like” pdqr-function is created: an *approximation of single number* as triangular distribution with very narrow support (1e-8 order of magnitude). - **Data frame input** should completely define distribution. For “discrete” type it should have “x” and “prob” columns for output values and their probabilities. For “continuous” type - “x” and “y” columns for points, which define piecewise-linear continuous density function. Columns “prob” and “y” will be automatically normalized to represent proper distribution: sum of “prob” will be 1 and total square under graph of piecewise-linear function will be 1. All information about distribution that pdqr-function represents is stored in its **“x_tbl” metadata**: a data frame describing distribution with format similar to data frame input of `new_*()` functions. One can get it using `meta_x_tbl()` function. Pdqr class correspond to the following functions describing distribution: - **P-function** is a cumulative distribution function. Created with `new_p()`. - **D-function** is a probability mass function for “discrete” type and density function for “continuous”. Created with `new_d()`. Generally speaking, it is a derivative of distribution’s p-function. - **Q-function** is a quantile function. Created with `new_q()`. Inverse of distribution’s p-function. - **R-function** is a random generation function. Created with `new_r()`. Generates a random sample from distribution. For more details see [vignette about creating pdqr-functions](https://echasnovski.github.io/pdqr/articles/pdqr-01-create.html). ### Create pdqr-function from sample ``` r # Treat input as discrete (p_mpg_dis <- new_p(mtcars$mpg, type = "discrete")) #> Cumulative distribution function of discrete type #> Support: [10.4, 33.9] (25 elements) (d_mpg_dis <- new_d(mtcars$mpg, type = "discrete")) #> Probability mass function of discrete type #> Support: [10.4, 33.9] (25 elements) (q_mpg_dis <- new_q(mtcars$mpg, type = "discrete")) #> Quantile function of discrete type #> Support: [10.4, 33.9] (25 elements) (r_mpg_dis <- new_r(mtcars$mpg, type = "discrete")) #> Random generation function of discrete type #> Support: [10.4, 33.9] (25 elements) ## "x_tbl" metadata is the same for all `*_mpg_dis()` pdqr-functions head(meta_x_tbl(p_mpg_dis), n = 3) #> x prob cumprob #> 1 10.4 0.06250 0.06250 #> 2 13.3 0.03125 0.09375 #> 3 14.3 0.03125 0.12500 # Treat input as continuous (p_mpg_con <- new_p(mtcars$mpg, type = "continuous")) #> Cumulative distribution function of continuous type #> Support: ~[2.96996, 41.33004] (511 intervals) (d_mpg_con <- new_d(mtcars$mpg, type = "continuous")) #> Density function of continuous type #> Support: ~[2.96996, 41.33004] (511 intervals) (q_mpg_con <- new_q(mtcars$mpg, type = "continuous")) #> Quantile function of continuous type #> Support: ~[2.96996, 41.33004] (511 intervals) (r_mpg_con <- new_r(mtcars$mpg, type = "continuous")) #> Random generation function of continuous type #> Support: ~[2.96996, 41.33004] (511 intervals) ## "x_tbl" metadata is the same for all `*_mpg_con()` pdqr-functions head(meta_x_tbl(p_mpg_con), n = 3) #> x y cumprob #> 1 2.96996269 0.000114133557 0.00000000e+00 #> 2 3.04503133 0.000125168087 8.98202438e-06 #> 3 3.12009996 0.000136934574 1.88198694e-05 # Output of `new_*()` is actually a function p_mpg_dis(15:20) #> [1] 0.18750 0.31250 0.34375 0.40625 0.46875 0.56250 ## Random generation. "discrete" type generates only values from input r_mpg_dis(10) #> [1] 10.4 33.9 26.0 19.2 24.4 18.7 17.8 18.7 15.5 21.4 r_mpg_con(10) #> [1] 35.7089680 33.3634914 31.1541225 15.6482281 20.8554689 13.7275908 11.3686051 16.7155604 #> [9] 20.6710197 20.5132727 # Special case of dirac-like pdqr-function, which numerically approximates # single number with distribution with narrow support (r_dirac <- new_r(3.14, "continuous")) #> Random generation function of continuous type #> Support: ~[3.14, 3.14] (2 intervals) meta_x_tbl(r_dirac) #> x y cumprob #> 1 3.13999999 0 0.0 #> 2 3.14000000 100000001 0.5 #> 3 3.14000001 0 1.0 ``` ### Create pdqr-function from data frame ``` r # Type "discrete" dis_tbl <- data.frame(x = 1:4, prob = 4:1 / 10) new_d(dis_tbl, type = "discrete") #> Probability mass function of discrete type #> Support: [1, 4] (4 elements) new_r(dis_tbl, type = "discrete")(10) #> [1] 4 1 3 1 2 4 3 2 4 1 # Type "continuous" con_tbl <- data.frame(x = 1:4, y = c(0, 1, 1, 1)) new_d(con_tbl, type = "continuous") #> Density function of continuous type #> Support: [1, 4] (3 intervals) new_r(con_tbl, type = "continuous")(10) #> [1] 2.21323986 1.58190910 2.85635049 2.32440194 2.44538842 2.89743821 3.29852362 2.43084969 #> [9] 2.81580878 2.79585280 ``` ## <a id="pdqr-convert"></a> Convert with `as_*()` Family of `as_*()` functions should be used to convert existing distribution functions into desired class (“p”, “d”, “q”, or “r”). Roughly, this is a `new_*()` family but with function as an input. There are two main use cases: - Convert existing pdqr-functions to different type. - Convert (create) pdqr-function based on some other user-supplied distribution function. For more details see [vignette about converting pdqr-functions](https://echasnovski.github.io/pdqr/articles/pdqr-02-convert.html). ### Existing pdqr-functions Converting existing pdqr-function to desired type is done straightforwardly by changing function’s class without touching the underlying distribution (“x_tbl” metadata is the same): ``` r d_dis <- new_d(1:4, "discrete") meta_x_tbl(d_dis) #> x prob cumprob #> 1 1 0.25 0.25 #> 2 2 0.25 0.50 #> 3 3 0.25 0.75 #> 4 4 0.25 1.00 # This is equivalent to `new_p(1:4, "discrete")` (p_dis <- as_p(d_dis)) #> Cumulative distribution function of discrete type #> Support: [1, 4] (4 elements) meta_x_tbl(p_dis) #> x prob cumprob #> 1 1 0.25 0.25 #> 2 2 0.25 0.50 #> 3 3 0.25 0.75 #> 4 4 0.25 1.00 ``` ### Other distribution functions Another important use case for `as_*()` functions is to convert some other distribution functions to be pdqr-functions. Except small number of special cases, output of `as_*()` function will have “continuous” type. The reason is because identifying exact values of distribution in discrete case is very hard in this setup (when almost nothing is known about the input function). It is assumed that if user knows those values, some `new_*()` function with data frame input can be used to create arbitrary discrete pdqr-function. General conversion algorithm is as follows: - If user didn’t supply support, detect it using algorithms targeted for every pdqr class separately. If *input function belongs to a certain set of “honored” distributions* (currently, it is all common univariate distributions [from ‘stats’ package](https://rdrr.io/r/stats/Distributions.html)), support is detected in predefined way. - Using detected support, data frame input for corresponding `new_*()` function is created which approximates input function. Approximation precision can be tweaked with `n_grid` (and `n_sample` for `as_r()`) argument. **Note** that output is usually an approximation of input due to the following facts: - Output density has piecewise-linear nature, which is almost never the case for input function. - Possible infinite tails are removed to obtain finite support. Usually output support “loses” only around 1e-6 probability on each infinite tail. - Possible infinite values of density are linearly approximated from neighborhood points. ``` r # "Honored" distributions as_d(dnorm) #> Density function of continuous type #> Support: ~[-4.75342, 4.75342] (10000 intervals) ## Different picewise-linear approximation precision as_d(dnorm, n_grid = 101) #> Density function of continuous type #> Support: ~[-4.75342, 4.75342] (100 intervals) ## Different extra arguments for input as_d(dnorm, mean = 10, sd = 0.1) #> Density function of continuous type #> Support: ~[9.52466, 10.47534] (10000 intervals) # Custom functions my_d <- function(x) { ifelse(x >= -1 & x <= 1, 0.75 * (1 - x^2), 0) } ## With algorithmic support detection as_d(my_d) #> Density function of continuous type #> Support: ~[-1.00018, 1.00019] (7588 intervals) ## Providing custom, maybe only partially known, support as_d(my_d, support = c(-1, NA)) #> Density function of continuous type #> Support: ~[-1, 1.00007] (9327 intervals) as_d(my_d, support = c(-1, 1)) #> Density function of continuous type #> Support: [-1, 1] (10000 intervals) ``` ## <a id="pdqr-transform"></a> Transform with `form_*()` and base operations Concept of form functions is to take one or more pdqr-function(s) and return a transformed pdqr-function. Argument `method` is used to choose function-specific algorithm of computation. For more details see [vignette about transforming pdqr-functions](https://echasnovski.github.io/pdqr/articles/pdqr-03-transform.html). ### `form_*()` family There are several `form_*()` functions. Here are some examples: ``` r # Transform support of pdqr-function with `form_resupport()`. Usually useful # for dealing with bounded values. d_smpl <- new_d(runif(1000), type = "continuous") d_smpl_bounded <- form_resupport(d_smpl, support = c(0, 1), method = "reflect") plot(d_smpl, main = "Estimating density of bounded quantity", col = "black") lines(d_smpl_bounded, col = "blue") ## Reference uniform distribution lines(as_d(dunif), col = "red") ``` ![](man/figures/README-pdqr-transform_form-1.png)<!-- --> ``` r # Perform general transformation with `form_trans()`. This is usually done by # randomly simulating sample from output distribution and then calling one of # `new_*()` functions. d_norm <- as_d(dnorm) ## More accurate result would give use of `+` directly with: d_norm + d_norm d_norm_2 <- form_trans(list(d_norm, d_norm), trans = `+`) plot(d_norm_2, col = "black") lines(as_d(dnorm, sd = sqrt(2)), col = "red") ``` ![](man/figures/README-pdqr-transform_form-2.png)<!-- --> ### Base operations Almost all basic R operations (implemented with [S3 group generic functions](https://rdrr.io/r/base/groupGeneric.html)) has methods for pdqr-functions. Operations are done as if applied to independent random variables with distributions represented by input pdqr-function(s). Many of methods have random nature and are implemented with `form_trans()`, but have little tweaks that make their direct usage better than `form_trans()`. ``` r d_norm <- as_d(dnorm) d_unif <- as_d(dunif) # Distribution of difference of random variables. Computed with random # simulation. d_norm - d_unif #> Density function of continuous type #> Support: ~[-5.02445, 3.65236] (511 intervals) # Comparing random variables results into boolean random variable represented # by boolean pdqr-function (type "discrete" with values 0 for FALSE and 1 for # TRUE). Here it means that random value of `d_norm` will be greater than random # value of `d_unif` with probability around 0.316. This is computed directly, # without random simulation. d_norm > d_unif #> Probability mass function of discrete type #> Support: [0, 1] (2 elements, probability of 1: ~0.31563) # Distribution of maximum of three random variables. Computed with random # simulation. max(d_norm, d_norm, d_norm) #> Density function of continuous type #> Support: ~[-2.3575, 4.11583] (511 intervals) ``` ## <a id="pdqr-summarize"></a> Summarize with `summ_*()` Concept of summary functions is to take one or more pdqr-function(s) and return a summary value. Argument `method` is used to choose function-specific algorithm of computation. For more details see [vignette about summarizing pdqr-functions](https://echasnovski.github.io/pdqr/articles/pdqr-04-summarize.html). ### Basic summary ``` r my_d <- as_d(dbeta, shape1 = 1, shape2 = 3) # There are wrappers for all center summaries summ_center(my_d, method = "mean") #> [1] 0.249999259 summ_center(my_d, method = "median") #> [1] 0.20629921 summ_center(my_d, method = "mode") #> [1] 0 # There are wrappers for spread summaries summ_spread(my_d, method = "sd") #> [1] 0.193647842 # These return essentially the same result summ_moment(my_d, order = 2, central = TRUE) #> [1] 0.0374994867 summ_spread(my_d, method = "var") #> [1] 0.0374994867 ``` ### Regions Distributions can be summarized with regions: union of closed intervals. They are represented as data frame with rows representing intervals and two columns “left” and “right” with left and right interval edges respectively. ``` r # 90% highest density region (HDR) summ_hdr(my_d, level = 0.9) #> left right #> 1 0 0.535887 ## In case of unimodal distribution HDR is essentially the same as 90% interval ## of minimum width summ_interval(my_d, level = 0.9, method = "minwidth") #> left right #> 1 0 0.535839727 summ_interval(my_d, level = 0.9, method = "percentile") #> left right #> 1 0.0169524103 0.631594521 ``` ### Distance Function `summ_distance()` takes two pdqr-functions and returns a distance between two distributions they represent. Many methods of computation are available. This might be useful for doing comparative statistical inference. ``` r my_d_2 <- as_d(dnorm, mean = 0.5) # Kolmogorov-Smirnov distance summ_distance(my_d, my_d_2, method = "KS") #> [1] 0.397684098 # Total variation distance summ_distance(my_d, my_d_2, method = "totvar") #> [1] 0.706221267 # Probability of one distribution be bigger than the other, normalized to [0;1] summ_distance(my_d, my_d_2, method = "compare") #> [1] 0.194615851 # Wassertein distance: "average path density point should go while transforming # from one into another" summ_distance(my_d, my_d_2, method = "wass") #> [1] 0.685534883 # Cramer distance: integral of squared difference of p-functions summ_distance(my_d, my_d_2, method = "cramer") #> [1] 0.165921075 # "Align" distance: path length for which one of distribution should be "moved" # towards the other so that they become "aligned" (probability of one being # greater than the other is 0.5) summ_distance(my_d, my_d_2, method = "align") #> [1] 0.251020429 # "Entropy" distance: `KL(f, g) + KL(g, f)`, where `KL()` is Kullback-Leibler # divergence. Usually should be used for distributions with same support, but # works even if they are different (with big numerical penalty). summ_distance(my_d, my_d_2, method = "entropy") #> [1] 12.6930974 ``` ### Separation, classification, and ROC curve Function `summ_separation()` computes a threshold that optimally separates distributions represented by pair of input pdqr-functions. In other words, `summ_separation()` solves a binary classification problem with one-dimensional linear classifier: values not more than some threshold are classified as one class, and more than threshold - as another. Order of input functions doesn’t matter. ``` r summ_separation(my_d, my_d_2, method = "KS") #> [1] 0.637042714 summ_separation(my_d, my_d_2, method = "F1") #> [1] -6.02372908e-05 ``` Functions `summ_classmetric()` and `summ_classmetric_df()` compute metric of classification setup, similar to one used in `summ_separation()`. Here classifier threshold should be supplied and order of input matters. Classification is assumed to be done as follows: any x value not more than threshold value is classified as “negative”; if strictly greater - “positive”. Classification metrics are computed based on two pdqr-functions: `f`, which represents the distribution of values which should be classified as “negative” (“true negative”), and `g` - the same for “positive” (“true positive”). ``` r # Many threshold values can be supplied thres_vec <- seq(0, 1, by = 0.2) summ_classmetric(f = my_d, g = my_d_2, threshold = thres_vec, method = "F1") #> [1] 0.513819342 0.580222932 0.614898704 0.603832562 0.549732861 0.471575705 # In `summ_classmetric_df()` many methods can be supplied summ_classmetric_df( f = my_d, g = my_d_2, threshold = thres_vec, method = c("GM", "F1", "MCC") ) #> threshold GM F1 MCC #> 1 0.0 0.000000000 0.513819342 -0.427093061 #> 2 0.2 0.549127659 0.580222932 0.106817345 #> 3 0.4 0.650557843 0.614898704 0.333936376 #> 4 0.6 0.656293762 0.603832562 0.450433146 #> 5 0.8 0.615655766 0.549732861 0.472055694 #> 6 1.0 0.555461222 0.471575705 0.427093061 ``` With `summ_roc()` and `summ_rocauc()` one can compute data frame of ROC curve points and ROC AUC value respectively. There is also a `roc_plot()` function for predefined plotting of ROC curve. ``` r my_roc <- summ_roc(my_d, my_d_2) head(my_roc) #> threshold fpr tpr #> 1 5.25342531 0 0.00000000e+00 #> 2 5.24391846 0 4.81164585e-08 #> 3 5.23441161 0 9.84577933e-08 #> 4 5.22490476 0 1.51116706e-07 #> 5 5.21539791 0 2.06194913e-07 #> 6 5.20589106 0 2.63798357e-07 summ_rocauc(my_d, my_d_2) #> [1] 0.597307926 roc_plot(my_roc) ``` ![](man/figures/README-pdqr-summarize_roc-1.png)<!-- --> ## <a id="similar-packages"></a> Similar packages - [“distrXXX”-family](http://distr.r-forge.r-project.org/) of packages: S4 classes for distributions. - [distr6](https://alan-turing-institute.github.io/distr6/): Unified and Object Oriented Probability Distribution Interface for R written in R6. - [distributions3](https://alexpghayes.github.io/distributions3/): Probability Distributions as S3 Objects. - [fitdistrplus](https://CRAN.R-project.org/package=fitdistrplus): Help to Fit of a Parametric Distribution to Non-Censored or Censored Data. - [Probability Distributions](https://CRAN.R-project.org/view=Distributions) CRAN Task View has more examples of packages intended to work with probability distributions. - [hdrcde](https://CRAN.R-project.org/package=hdrcde): Highest Density Regions and Conditional Density Estimation.
JavaScript
UTF-8
1,752
2.609375
3
[]
no_license
const express = require('express'); const app = express(); const bcrypt = require('bcrypt'); const authRoute = express.Router(); let User = require('../models/user'); async function checkPassword(p1,p2){ return p1==p2 ? true : false; } async function hashPassword(password) { const salt = await bcrypt.genSalt(10) const hash = await bcrypt.hash(password, salt) return hash; } authRoute.route('/register').post((req, res, next) => { if(checkPassword(req.body.password,req.body.repassword)){ hashPassword(req.body.password).then(hash => { let data = { username: req.body.username, email:req.body.email, password:hash }; User.create(data, (error, data) => { if (error) { return handleError(error) } else { res.json(data) } }) }); } }); authRoute.route('/login').post((req, res, next) => { User.find( { username:req.body.username } , (error, data) => { if (error) { return next(error) } else { if(data[0] != null){ bcrypt.compare(req.body.password, data[0]['password']).then(isSamePassword=>{ if(isSamePassword){ data[0].password = undefined; res.json(data); }else{ res.json({msg:"Password incorrect"}); } });; }else{ res.json({msg:"User not found"}); } } }); }); // Get Auth authRoute.route('/logout').post((req, res) => { User.find({username: req.params.username, password: req.params.password}, (error, data) => { if (error) { return next(error) } else { res.json(data) } }) }) module.exports = authRoute;
Java
UTF-8
927
3.375
3
[]
no_license
package Lesson.L03.EX02; import Lesson.ContentOfEx; import java.util.Arrays; public class Exercise02 { public int getCountPrefix() { return countPrefix; } private int countPrefix; public int prefixes(String tab[], String prefix) { for (String s : tab) { if (s.equals(prefix)) countPrefix++; } return countPrefix; } public void solve(){ System.out.println(ContentOfEx.L03_EX02); System.out.println(); String sampleTab [] = {"32323","1112", "10","546","10","864","10"}; String samplePrefix = "10"; System.out.println("Sample Prefixes:"); Arrays.stream(sampleTab).forEach(el-> System.out.print(el +", ")); System.out.println(); System.out.println("Sample Prefix: " + samplePrefix); System.out.println("Prefixes " + samplePrefix + " are " + prefixes(sampleTab, samplePrefix)); } }
Java
UTF-8
5,978
1.929688
2
[ "MIT" ]
permissive
/* Copyright (c) 2016 lib4j * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * You should have received a copy of The MIT License (MIT) along with this * program. If not, see <http://opensource.org/licenses/MIT/>. */ package org.libx4j.jetty; import java.io.IOException; import java.net.URL; import java.util.HashMap; import java.util.Map; import org.eclipse.jetty.security.ConstraintSecurityHandler; import org.eclipse.jetty.security.HashLoginService; import org.eclipse.jetty.security.authentication.BasicAuthenticator; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.server.SecureRequestCustomizer; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.SslConnectionFactory; import org.eclipse.jetty.server.handler.HandlerList; import org.eclipse.jetty.server.handler.ResourceHandler; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.util.resource.Resource; import org.eclipse.jetty.util.security.Constraint; import org.eclipse.jetty.util.security.Credential; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.lib4j.lang.Resources; public abstract class EmbeddedServletContext { private static final Map<String,Map<String,Constraint>> roleToConstraint = new HashMap<String,Map<String,Constraint>>(); private static Constraint getConstraint(final Map<String,Constraint> authTypeToConstraint, final String authType, final String role) { Constraint constraint = authTypeToConstraint.get(authType); if (constraint != null) return constraint; authTypeToConstraint.put(authType, constraint = new Constraint(authType, role)); constraint.setAuthenticate(true); return constraint; } protected static Constraint getBasicAuthConstraint(final String authType, final String role) { Map<String,Constraint> authTypeToConstraint = roleToConstraint.get(role); if (authTypeToConstraint == null) roleToConstraint.put(role, authTypeToConstraint = new HashMap<String,Constraint>()); return getConstraint(authTypeToConstraint, authType, role); } private static Connector makeConnector(final Server server, final int port, final String keyStorePath, final String keyStorePassword) { if (keyStorePath == null || keyStorePassword == null) { final ServerConnector connector = new ServerConnector(server); connector.setPort(port); return connector; } final HttpConfiguration https = new HttpConfiguration(); https.addCustomizer(new SecureRequestCustomizer()); final SslContextFactory sslContextFactory = new SslContextFactory(); sslContextFactory.setKeyStorePath(Resources.getResource(keyStorePath).getURL().toExternalForm()); sslContextFactory.setKeyStorePassword(keyStorePassword); final ServerConnector connector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(https)); connector.setPort(port); return connector; } protected static ServletContextHandler createServletContextHandler(final Realm realm) { final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); final ConstraintSecurityHandler security = new ConstraintSecurityHandler(); if (realm != null) { final HashLoginService login = new HashLoginService(realm.getName()); for (final Map.Entry<String,String> entry : realm.getCredentials().entrySet()) for (final String role : realm.getRoles()) login.putUser(entry.getKey(), Credential.getCredential(entry.getValue()), new String[] {role}); security.setRealmName(realm.getName()); security.setLoginService(login); security.setAuthenticator(new BasicAuthenticator()); } context.setSecurityHandler(security); return context; } private final Server server = new Server(); public EmbeddedServletContext(final int port, final String keyStorePath, final String keyStorePassword, final boolean externalResourcesAccess, final ServletContextHandler context) { server.setConnectors(new Connector[] {makeConnector(server, port, keyStorePath, keyStorePassword)}); final HandlerList handlerList = new HandlerList(); if (externalResourcesAccess) { // FIXME: HACK: Why cannot I just get the "/" resource? In the IDE it works, but in the stand-alone jar, it does not try { final String resourceName = getClass().getName().replace('.', '/') + ".class"; final String configResourcePath = Resources.getResource(resourceName).getURL().toExternalForm(); final URL rootResourceURL = new URL(configResourcePath.substring(0, configResourcePath.length() - resourceName.length())); final ResourceHandler resourceHandler = new ResourceHandler(); resourceHandler.setDirectoriesListed(true); resourceHandler.setBaseResource(Resource.newResource(rootResourceURL)); handlerList.addHandler(resourceHandler); } catch (final IOException e) { throw new UnsupportedOperationException(e); } } handlerList.addHandler(context); server.setHandler(handlerList); } public void start() throws Exception { server.start(); } public void join() throws InterruptedException { server.join(); } }
Python
UTF-8
730
3.078125
3
[]
no_license
# -*- coding:utf-8 -*- fail_rate = dict() def solution(N, stages): answer=[] users = len(stages) for i in range(1,N+2): fail_rate[i]=[] for s in stages: fail_rate[s].append(1) print(fail_rate) for i in range(1,N+2): temp = len(fail_rate[i]) print(temp) print(float(users)) if(temp == 0): fail_rate[i]=0 else: fail_rate[i] = temp/float(users) users -= temp del(fail_rate[N+1]) for stage_number in sorted(fail_rate, key=fail_rate.get, reverse=True): answer.append(stage_number) return answer print( solution(7, [1,3,4,4,2,6,5,8,5,4,4,2] ) )
Java
UTF-8
2,563
3.984375
4
[ "MIT" ]
permissive
package hash; import java.util.TreeMap; public class HashTable<K extends Comparable<K>, V> { private TreeMap<K, V>[] table; private int M; //一个素数,其实也是 buckets 的目录(数组长度) private int size; //元素总个数 //指定数组长度的构造器 public HashTable(int M) { this.M = M; size = 0; table = new TreeMap[M]; //数组长度也是 M //数组的元素也要初始化 for(int i = 0; i < M; i++) { table[i] = new TreeMap<>(); } } //默认数组长度 97,当然也可以是其他素数 public HashTable() { this(97); } //Hashtable的 hash函数 (要直接拿到存储索引的,而不是只求出hash值) private int hash(K key) { // 0x7fffffff 相当于去掉整型的符号位 //因为 java 本身实现的 hashCode 本身可能为负值(这里运算后最高位一定是0,即正数) //不用与运算,用 Math.abs 也是可以的,但效率不高 return (key.hashCode() & 0x7fffffff) % M; } public int getSize() { return size; } public void add(K key, V value) { //先要看一下是否存在 (不存在才存储;否则是修改) TreeMap<K, V> map = table[hash(key)]; map.put(key, value); if(!map.containsKey(key)) { //新添加 size++; } } //删除 public V remove(K key) { TreeMap<K, V> map = table[hash(key)]; V ret = null; //在相应的 map 中查找 if(map.containsKey(key)) { ret = map.remove(key); //删除之后要维护 size size--; } return ret; } //修改 public void set(K key, V value) { TreeMap<K, V> map = table[hash(key)]; if(!map.containsKey(key)) { throw new IllegalArgumentException(key + "不存在"); } map.put(key, value); } //查询 public boolean contains(K key) { //TreeMap<K, V> map = table[hash(key)]; return table[hash(key)].containsKey(key); } public V get(K key) { return table[hash(key)].get(key); } public static void main(String[] args) { HashTable<String, Integer> hashTable = new HashTable<>(); hashTable.add("nihao", 1); hashTable.add("hello", 2); System.out.println(hashTable.contains("nihao")); //true hashTable.set("hello", 3); System.out.println(hashTable.get("hello")); //3 } }
Java
UTF-8
2,591
2.15625
2
[ "Apache-2.0" ]
permissive
package io.github.rcarlosdasilva.weixin.api.internal; import java.util.List; import io.github.rcarlosdasilva.weixin.model.response.user.group.bean.UserGroup; /** * 用户组API * * @author <a href="mailto:[email protected]">Dean Zhao</a> */ public interface UserGroupApi { /** * 创建用户组. * * <p> * 一个公众账号,最多支持创建100个分组 * * @param name * 组名 * @return 用户组id * @see <a href= * "http://mp.weixin.qq.com/wiki/8/d6d33cf60bce2a2e4fb10a21be9591b8.html" * >用户分组管理</a> */ int create(String name); /** * 查询所有用户组. * * @return {@link UserGroupApi} 列表 * @see <a href= * "http://mp.weixin.qq.com/wiki/8/d6d33cf60bce2a2e4fb10a21be9591b8.html" * >用户分组管理</a> */ List<UserGroup> list(); /** * 通过用户的OpenID查询其所在的GroupID. * * @param openId * OpenId * @return 用户组id * @see <a href= * "http://mp.weixin.qq.com/wiki/8/d6d33cf60bce2a2e4fb10a21be9591b8.html" * >用户分组管理</a> */ int getByOpenId(String openId); /** * 修改分组名. * * @param id * 用户组id * @param newName * 新组名 * @return 是否成功 * @see <a href= * "http://mp.weixin.qq.com/wiki/8/d6d33cf60bce2a2e4fb10a21be9591b8.html" * >用户分组管理</a> */ boolean update(int id, String newName); /** * 移动用户分组. * * @param toGroupId * 到分组id * @param openId * 用户OpenId * @return 是否成功 * @see <a href= * "http://mp.weixin.qq.com/wiki/8/d6d33cf60bce2a2e4fb10a21be9591b8.html" * >用户分组管理</a> */ boolean moveMemberTo(int toGroupId, String openId); /** * 批量移动用户分组. * * @param openIds * 用户OpenId列表 * @param toGroupId * 到分组id * @return 是否成功 * @see <a href= * "http://mp.weixin.qq.com/wiki/8/d6d33cf60bce2a2e4fb10a21be9591b8.html" * >用户分组管理</a> */ boolean moveMemberBatchTo(int toGroupId, List<String> openIds); /** * 删除用户组. * * @param id * 用户组id * @return 是否成功 * @see <a href= * "http://mp.weixin.qq.com/wiki/8/d6d33cf60bce2a2e4fb10a21be9591b8.html" * >用户分组管理</a> */ boolean delete(int id); }
C#
UTF-8
363
2.59375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace string_formats { class Program { static void Main(string[] args) { //Övning1 DateTime dt = DateTime.Today; Console.WriteLine(dt.ToString("yyyy MM dd")); } } }
JavaScript
UTF-8
504
2.703125
3
[ "MIT" ]
permissive
import capitalize from '../src/capitalize.js' test('Stringify number', () => { expect(capitalize(200)).toBe("200") }) test('Return already capitalized', () => { expect(capitalize("Capitalized")).toBe("Capitalized") }) test('Capitalize first letter', () => { expect(capitalize("small letters only")).toBe("Small letters only") }) test('Handle all caps', () => { expect(capitalize("ALL CAPS")).toBe("All caps") }) test('Handle empty string', () => { expect(capitalize("")).toBe("") })
C
UTF-8
1,750
3.078125
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* availability.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hczuba <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/07/24 20:49:18 by hczuba #+# #+# */ /* Updated: 2016/07/24 20:49:58 by hczuba ### ########.fr */ /* */ /* ************************************************************************** */ int row_col_check(int puzzle[][9], int row, int col, int num) { int i; i = 0; while (i < 9) { if (i != row) { if (puzzle[i][col] == num) { return (0); } } if (i != col) { if (puzzle[row][i] == num) return (0); } i++; } return (1); } int grid_check(int puzzle[][9], int row, int col, int num) { int c; int r; int row_start; int col_start; row_start = (row / 3) * 3; col_start = (col / 3) * 3; r = 0; while (r < 3) { c = 0; while (c < 3) { if ((row_start + r) != row && c != (col_start + c)) { if (puzzle[row_start + r][col_start + c] == num) return (0); } c++; } r++; } return (1); } int available(int puzzle[][9], int row, int col, int num) { if (!(row_col_check(puzzle, row, col, num))) return (0); if (!(grid_check(puzzle, row, col, num))) return (0); return (1); }
Python
UTF-8
8,313
2.796875
3
[]
no_license
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import torch from pathlib import Path from IPython.display import display from sklearn.metrics import classification_report, confusion_matrix from BaselineRemoval import BaselineRemoval from scipy.signal import welch, find_peaks, savgol_filter sns.set_style("whitegrid") plt.style.use('ggplot') sns.set(font_scale=1.5) sns.set_palette("bright") def load_data(train_folder, test_folder, train_labels, test_labels): """ loads train and test signals and labels input: train and test signal and label folder in .txt form returns numpy ndarray of train, test signals and labels """ train_pathlist = sorted(Path(train_folder).rglob('*.txt')) test_pathlist = sorted(Path(test_folder).rglob('*.txt')) train_signals = [np.loadtxt(path) for path in train_pathlist] train_signals = np.transpose(np.array(train_signals), (1, 2, 0)) test_signals = [np.loadtxt(path) for path in test_pathlist] test_signals = np.transpose(np.array(test_signals), (1, 2, 0)) train_labels = np.loadtxt(Path(train_labels)) test_labels = np.loadtxt(Path(test_labels)) print("number of train signals, length of each signal, number of components:", train_signals.shape) print("number of test signals, length of each signal, number of components:", test_signals.shape) return train_signals, test_signals, train_labels, test_labels def get_classification_results(models, X_train, X_test, y_train, y_test): """ input: Dictionary of ML models with Gridsearch parameters. Prints classification reports and confusion matrices. """ for i in models: models[i].fit(X_train, y_train) print(i, "Report:") print("############################################") print("Train Accuracy: {}".format(models[i].score(X_train, y_train))) print("Test Accuracy : {}".format(models[i].score(X_test, y_test))) y_pred = models[i].predict(X_test) best_params = models[i].best_params_ best_params_df = pd.DataFrame(best_params, index=[0]) print (" ") print("Best parameters:") display(best_params_df) report = classification_report(y_test, y_pred, output_dict=True) df = pd.DataFrame(report).transpose() print (" ") print("Classification Report:") display(df) cf_matrix = confusion_matrix(y_test, y_pred) print (" ") print("Confusion Matrix:") df1 = pd.DataFrame(cf_matrix) display(df1) cf_matrix_normalized_p = cf_matrix / cf_matrix.astype(np.float).sum(axis=0) cf_matrix_normalized_r = cf_matrix / cf_matrix.astype(np.float).sum(axis=1) plt.figure(figsize=[8, 6]) print("Normalized precision cf") sns.heatmap(cf_matrix_normalized_p, annot=True, cmap='Blues') plt.show() plt.figure(figsize=[8, 6]) print("Normalized recall cf") sns.heatmap(cf_matrix_normalized_r, annot=True, cmap='Blues') plt.show() def train_class(model, num_epochs, bs, train_loader, test_loader, optimizer, criterion): """ Trains a CNN classifier and prints train and test results. input: CNN model, number of epochs, batch size, PyTorch train loader and test loaders, optimizer and loss function returns a Pandas dataframe with loss values, plots training and test losses """ loss_values = { 'train': [], 'test': [] } accuracy_values = { 'train': [], 'test': [] } final_loss_df = pd.DataFrame() final_acc_df = pd.DataFrame() for epoch in range(num_epochs): start = timer() model.train() avg_training_loss = 0. correct = 0. for i, (inputs, labels) in enumerate(train_loader): inputs, labels = Variable(inputs), Variable(labels) if torch.cuda.is_available(): inputs = inputs.cuda() labels = labels.cuda() outputs = model(inputs) loss = criterion(outputs, labels) optimizer.zero_grad() loss.backward() optimizer.step() avg_training_loss += loss.item() / len(train_loader) # correct += (outputs == labels).float().sum() loss_values['train'].append(avg_training_loss) # accuracy_values['train'].append((100 * correct // len(X_train_tensor))) model.eval() avg_test_loss = 0. correct = 0. for i, (inputs, labels) in enumerate(test_loader): inputs, labels = Variable(inputs), Variable(labels) if torch.cuda.is_available(): inputs = inputs.cuda() labels = labels.cuda() outputs = model(inputs) loss = criterion(outputs, labels) # Calculate the loss optimizer.zero_grad() loss.backward() optimizer.step() avg_test_loss += loss.item() / len(train_loader) # correct += (outputs == labels).float().sum() loss_values['test'].append(avg_test_loss) # accuracy_values['train'].append((100 * correct // len(X_train_tensor))) end = timer() elapsed_time = end - start if epoch % 10 == 1: print('Epoch {}/{} \t loss={:.4f} \t test_loss={:.4f} \t time={:.2f}s'.format( epoch + 1, num_epochs, avg_training_loss, avg_test_loss, elapsed_time)) # print(loss_values) loss_df = pd.DataFrame.from_dict(loss_values) # acc_df = pd.DataFrame.from_dict(accuracy_values) final_loss_df = final_loss_df.append(loss_df) # final_acc_df = final_acc_df.append(acc_df) final_loss_df['epoch'] = final_loss_df.index final_loss_df = final_loss_df.groupby('epoch').mean().reset_index() print('average fold losses: \n', final_loss_df) # print('average fold losses: \n', final_acc_df) plt.plot(final_loss_df.epoch, final_loss_df.train, label='train') plt.plot(final_loss_df.epoch, final_loss_df.test, label='test') plt.legend() plt.show() plt.savefig('train_test_plot.jpg') def get_cnn_cf_matrix(model, X_test_tensor, test_labels): """ input: CNN model, test data in tensor form, test labels. Prints classification reports and confusion matrices. """ with torch.no_grad(): output = model(X_test_tensor) pred = np.argmax(output, axis=1) + 1 report = classification_report(pred, test_labels, output_dict=True) df = pd.DataFrame(report).transpose() display(df) cf_matrix = confusion_matrix(pred, test_labels) df1 = pd.DataFrame(cf_matrix) print("Number of samples in each class in test set:", np.unique(test_labels, return_counts=True)) display(df1) plt.figure(figsize=[8, 6]) cf_matrix_normalized_p = cf_matrix / cf_matrix.astype(np.float).sum(axis=0) cf_matrix_normalized_r = cf_matrix / cf_matrix.astype(np.float).sum(axis=1) print("Normalized precision cf:") sns.heatmap(cf_matrix_normalized_p, annot=True, cmap='Blues') plt.show() plt.figure(figsize=[8, 6]) print("Normalized recall cf:") sns.heatmap(cf_matrix_normalized_r, annot=True, cmap='Blues') plt.show() def plot_stem (x, y, title): """ input: frequencies and intensities as lists (x, y). title is user defined title returns stem plot """ plt.figure(figsize=[8, 6]) plt.stem(x, y, use_line_collection=True) plt.xlabel('time/Sec') plt.ylabel('amplitude') plt.title(title) plt.plot(x, y) plt.show() def plot_feature(x, y, feature): """ input: frequencies and intensities as lists (x, y). title is user defined title for features, FFT, PSD, etc. returns baseline smoothed spectrum with peak detection """ baseObj=BaselineRemoval(y) y=baseObj.ModPoly(2) y = savgol_filter(y, 5, 2) peaks, _ = find_peaks(y) first_n_freq = x[peaks][np.argsort(-y[peaks])][0:5] first_n_int = y[peaks][np.argsort(-y[peaks])][0:5] plt.plot(x, y) plt.plot(x[peaks], y[peaks], "x") plt.xlabel('Freq/Hz') plt.ylabel('amplitude') plt.title(feature) plt.show()
C++
UTF-8
962
3.484375
3
[]
no_license
/* Almost got this one right first time. Only error was in the event that the input string started with a closed bracket. When this happened, it would fail the first "if" and then segfault on the second one because it couldn't access "stack.back()". To remedy this, I just added "stack.empty()" as a condition for the first if, so now the first element always goes in there. https://codility.com/demo/results/trainingHMYNTV-GNG/ */ #include <vector> int solution(string &S) { vector<int> stack; for (int i = 0 ; i < (int) S.length() ; i++ ) { if (S[i] == '(' || S[i] == '[' || S[i] == '{' || stack.empty() ) { stack.push_back(S[i]); } else if (S[i] == ')' && stack.back() == '(' ) { stack.pop_back(); } else if (S[i] == ']' && stack.back() == '[' ) { stack.pop_back(); } else if (S[i] == '}' && stack.back() == '{' ) { stack.pop_back(); } else { return 0; } } if (stack.empty()) return 1; else return 0; }
Java
UTF-8
271
1.648438
2
[]
no_license
package jp.co.brycen.wms.sequence.dto; import jp.co.brycen.common.dto.response.AbstractResponse; /** * 概要:シーケンス取得 */ public class SequenceResponse extends AbstractResponse { // シーケンス public SequenceDto sequence = new SequenceDto(); }
Java
UTF-8
655
1.789063
2
[]
no_license
package com.xy.user.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.xy.model.TeamRecord; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import java.sql.Timestamp; import java.util.Date; import java.util.Vector; @Repository public interface TeamRecordMapper extends BaseMapper<TeamRecord> { Vector<TeamRecord> findTeamRecord(); void insertPastTeamRecord(@Param("sUserId") Integer sUserId, @Param("xUserId") Integer xUserId, @Param("xNumbers") Integer xNumbers); void updateCurrentTeamRecord(@Param("iNumbers") Integer iNumbers, @Param("iUserId") Integer iUserId); }
C++
UTF-8
827
2.890625
3
[ "MIT" ]
permissive
// solved: 2013-12-24 18:33:42 #include <iostream> #include <vector> #include <string> using namespace std; int main() { string l; cin >> l; long long int right = 0, left = 0; int n = l.length(), piv; vector<int> lev(n, 0); for (int i = 0; i < n; i++) { if (l[i] == '^') { piv = i; } if (l[i] != '=') { lev[i] = int(l[i] - 48); } } int rc = piv + 1, lc = piv - 1; while (lc >= 0 || rc <= n - 1) { if (lc >= 0) left += lev[lc] * (piv - lc); if (rc <= n - 1) right += lev[rc] * (rc - piv); lc--; rc++; } if (right > left) cout << "right"; else if (left > right) cout << "left"; else cout << "balance"; return 0; }
C#
UTF-8
1,089
3.53125
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ejercicio15 { class Calculadora { public static double Calcular(double numeroUno, double numeroDos, char operando) { double resultado = 0; if (operando != '/' && operando == '+') { resultado = numeroUno + numeroDos; } if (operando != '/' && operando == '-') { resultado = numeroUno - numeroDos; } if (operando != '/' && operando == '*') { resultado = numeroUno * numeroDos; } if (operando == '/' && Validar(numeroDos)) { resultado = numeroUno / numeroDos; } return resultado; } private static bool Validar(double divisor) { if (divisor != 0) { return true; } else return false; } } }
C#
UTF-8
3,006
2.546875
3
[]
no_license
using InterprocessRPC.Common; using InterprocessRPC.Wrappers.ClientWrappers; using System; using System.Windows.Forms; namespace InterprocessRPC.TestClient { public partial class MainForm : Form { private readonly IClientWrapper clientWrapper; public MainForm(IClientWrapper clientWrapper) { this.clientWrapper = clientWrapper; InitializeComponent(); } private async void btnStart_Click(object sender, EventArgs e) { try { using (var execTime = new ExecutionTime()) { await clientWrapper.Start(); } } catch (Exception exc) { MessageBox.Show(exc.Message); } } private void btnStop_Click(object sender, EventArgs e) { Stop(); } private async void btnCheckConnection_Click(object sender, EventArgs e) { try { var result = false; using (var execTime = new ExecutionTime()) { result = await clientWrapper.CheckConnection(); } MessageBox.Show("Connection state: " + (result ? "connected" : "disconnected")); } catch (Exception exc) { MessageBox.Show(exc.Message); } } private async void btnGetMessage_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(tbName.Text)) { MessageBox.Show("Please enter your name"); return; } try { var message = string.Empty; using (var execTime = new ExecutionTime()) { message = await clientWrapper.GetHelloMessage(tbName.Text); } MessageBox.Show(message); } catch (Exception exc) { MessageBox.Show(exc.Message); } } private async void btnGetServerInfo_Click(object sender, EventArgs e) { try { DateTime dateTime; using (var execTime = new ExecutionTime()) { dateTime = await clientWrapper.GetServerTime(); } MessageBox.Show(dateTime.ToString()); } catch (Exception exc) { MessageBox.Show(exc.Message); } } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { Stop(); } private void Stop() { try { clientWrapper.Stop(); } catch (Exception exc) { MessageBox.Show(exc.Message); } } } }
C++
UTF-8
260
2.734375
3
[]
no_license
#pragma once class VertexBuffer { private: unsigned int id; size_t size; public: VertexBuffer(const void* data, size_t size); ~VertexBuffer(); void Bind()const; inline size_t GetSize()const { return size; } void Unbind()const; };
C#
UTF-8
1,415
2.78125
3
[ "MIT" ]
permissive
using CrudLocalDb.Models; using Microsoft.EntityFrameworkCore; using System; using System.IO; namespace CrudLocalDb.Database { public class AppDbContext : DbContext { public DbSet<Item> Items { get; set; } public DbSet<Tag> Tags { get; set; } public AppDbContext() { Database.EnsureCreated(); Database.Migrate(); } protected override void OnModelCreating(ModelBuilder modelBuilder) { #region Tags config modelBuilder.Entity<Tag>().ToTable("Tags"); modelBuilder.Entity<Tag>() .HasKey(x => x.Id); modelBuilder.Entity<Tag>() .HasOne(x => x.Item) .WithMany(x => x.Tags) .HasForeignKey(x => x.ItemForeignKey); #endregion modelBuilder.ApplyConfiguration(new ItemEntityConfiguration()); base.OnModelCreating(modelBuilder); } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { var dbName = "itemdb.db"; var databasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), dbName); optionsBuilder.EnableSensitiveDataLogging(true); optionsBuilder.UseSqlite($"Filename={databasePath}"); base.OnConfiguring(optionsBuilder); } } }
Ruby
UTF-8
1,672
2.765625
3
[ "MIT" ]
permissive
# frozen_string_literal: true require 'date' require 'logger' require 'twitter' require_relative 'national_rail_request' # Checks the service status and tweets (if appropriate) class NationalRailNotifier attr_reader :options def self.run(options) new(options).run end def initialize(options) @options = options end def run return if cannot_run? || !post_the_status? post_notification(service.status) end private def post_notification(status) logger.info "service.status: #{service.status}" twitter_account.update(status) end def post_the_status? !on_time? && !status_already_tweeted? && new_status? end def cannot_run? weekend? || !service end def service @service ||= NationalRailRequest.check_service(options) end def weekend? [6, 0].include? Date.today.wday end def latest_tweets twitter_account.user_timeline.first(5) end def twitter_account @twitter_account ||= Twitter::REST::Client.new do |config| config.consumer_key = ENV['TWITTER_NOTIFIER_CONSUMER_KEY'] config.consumer_secret = ENV['TWITTER_NOTIFIER_CONSUMER_SECRET'] config.access_token = ENV['TWITTER_NOTIFIER_ACCESS_TOKEN'] config.access_token_secret = ENV['TWITTER_NOTIFIER_ACCESS_TOKEN_SECRET'] end end def logger @logger ||= Logger.new('log/application.log', 'daily') end def status_already_tweeted? latest_tweets.any? do |tweet| service.status == tweet.text && tweet.created_at.day == Time.now.day end end def new_status? service.status != latest_tweets.first.text end def on_time? service.status == 'On time' end end
C++
UTF-8
3,584
2.546875
3
[]
no_license
#pragma once #include "../base/include.h" namespace Mander { USING_BASE_LIB static INLINE void triangleNormalCcwScaledBySurface(float * n, const float * A, const float * B, const float * C) { float ab[3] = {B[0]-A[0],B[1]-A[1],B[2]-A[2]}; float ac[3] = {C[0]-A[0],C[1]-A[1],C[2]-A[2]}; n[0] = ab[1]*ac[2] - ab[2]*ac[1]; n[1] = ab[2]*ac[0] - ab[0]*ac[2]; n[2] = ab[0]*ac[1] - ab[1]*ac[0]; } static INLINE void triangleTangentBinormalScaledBySurface(float * vTangent, float * vBinormal, float& fSur, const float * A, const float * B, const float * C, const float * TA, const float * TB, const float * TC) { float ab[3] = {B[0]-A[0],B[1]-A[1],B[2]-A[2]}; float ac[3] = {C[0]-A[0],C[1]-A[1],C[2]-A[2]}; float tab[2] = {TB[0]-TA[0],TB[1]-TA[1]}; float tac[2] = {TC[0]-TA[0],TC[1]-TA[1]}; float X[3] = {tac[1]*ab[0] - tab[1]*ac[0], tac[1]*ab[1] - tab[1]*ac[1], tac[1]*ab[2] - tab[1]*ac[2]}; float Y[3] = {tac[0]*ab[0] - tab[0]*ac[0], tac[0]*ab[1] - tab[0]*ac[1], tac[0]*ab[2] - tab[0]*ac[2]}; float fX = 1.0f/(tab[0]*tac[1] - tab[1]*tac[0]); float fY = 1.0f/(tab[1]*tac[0] - tab[0]*tac[1]); X[0] *= fX; X[1] *= fX; X[2] *= fX; Y[0] *= fY; Y[1] *= fY; Y[2] *= fY; float n[3]; n[0] = ab[1]*ac[2] - ab[2]*ac[1]; n[1] = ab[2]*ac[0] - ab[0]*ac[2]; n[2] = ab[0]*ac[1] - ab[1]*ac[0]; fSur = sqrtf(n[0]*n[0] + n[1]*n[1] + n[2]*n[2]); float fXq = X[0]*X[0] + X[1]*X[1] + X[2]*X[2]; float fYq = Y[0]*Y[0] + Y[1]*Y[1] + Y[2]*Y[2]; if(fXq > 1e+32 || fXq < 1e-32)X[0]=X[1]=X[2]=0; if(fYq > 1e+32 || fYq < 1e-32)Y[0]=Y[1]=Y[2]=0; vTangent[0] = X[0]*fSur; vTangent[1] = X[1]*fSur; vTangent[2] = X[2]*fSur; vBinormal[0] = Y[0]*fSur; vBinormal[1] = Y[1]*fSur; vBinormal[2] = Y[2]*fSur; } static INLINE void triangleNormalCcwScaledBySurface(Vector3f& n, const Vector3f& A, const Vector3f& B, const Vector3f& C) { triangleNormalCcwScaledBySurface(n.a, A.a, B.a, C.a); } static INLINE void triangleTangentBinormalScaledBySurface(Vector3f& tangent, Vector3f& binormal, float& surface, const Vector3f& A, const Vector3f& B, const Vector3f& C, const Vector2f& TA, const Vector2f& TB, const Vector2f& TC) { triangleTangentBinormalScaledBySurface(tangent.a, binormal.a, surface, A.a, B.a, C.a, TA.a, TB.a, TC.a); } struct TangentAndBinormal { Vector3f tangent; Vector3f binormal; }; template<class t_Operator, class t_Vert> static inline void calcTangentAndBinormal(t_Operator& op, t_Vert *aVert, uint vertexCount, const uint32* aIndex, uint trianglesCount) { TangentAndBinormal* aVertexTB = new TangentAndBinormal[vertexCount]; for(uint tr=0; tr < trianglesCount; tr++) { uint iA = aIndex[tr*3 + 0]; uint iB = aIndex[tr*3 + 1]; uint iC = aIndex[tr*3 + 2]; Vector3f vA = op.getPosition(aVert[iA]); Vector3f vB = op.getPosition(aVert[iB]); Vector3f vC = op.getPosition(aVert[iC]); Vector2f tA = op.getTexCoord(aVert[iA]); Vector2f tB = op.getTexCoord(aVert[iB]); Vector2f tC = op.getTexCoord(aVert[iC]); Vector3f tangent, binormal; float s; triangleTangentBinormalScaledBySurface(tangent, binormal, s, vA, vB, vC, tA, tB, tC); aVertexTB[iA].tangent += tangent; aVertexTB[iB].tangent += tangent; aVertexTB[iC].tangent += tangent; aVertexTB[iA].binormal += binormal; aVertexTB[iB].binormal += binormal; aVertexTB[iC].binormal += binormal; } for(uint i=0; i < vertexCount; ++i) { if(aVertexTB[i].tangent.lenghtSquare() > 1e-32f) op.setTangent(aVert[i], aVertexTB[i].tangent.normal()); if(aVertexTB[i].binormal.lenghtSquare() > 1e-32f) op.setBinormal(aVert[i], aVertexTB[i].binormal.normal()); } delete aVertexTB; } }
C#
UTF-8
504
3
3
[]
no_license
using System; using System.Collections.Generic; using System.Text; namespace Snap.Classes { public class Result { int Player1Tally = 0; int Player2Tally = 0; public String Output() { if (Player1Tally > Player2Tally) return "Player 1 wins"; else if ((Player2Tally > Player1Tally)) return "Player 2 wins"; else return "It was a drawer"; } } }
Python
UTF-8
2,466
2.90625
3
[ "Apache-2.0" ]
permissive
from __future__ import print_function import sqlite3 from .tablenice import TableNice class SqlNice(object): def __init__(self, sqlite_path_db): # Connection is automatic during the contructor self.conn = sqlite3.connect(sqlite_path_db) self.cursor = self.conn.cursor() self.table_list_names = self.get_tables_names() self.columns_by_tables = self.get_tables_schemas() self.table_list_obj = {} def close(self): self.rollback() self.conn.close() def commit(self): # TODO: Add a control to find if has anything to commit # https://trello.com/c/8wahdvLz/48-checking-queries-before-commit self.conn.commit() def rollback(self): # TODO: Add the same control of queries to rollback self.conn.rollback() def cursor(self): return self.cursor def create_table(self, table_name, columns, types=None): pass def drop_table(self, table_name): pass def get_tables_names(self): """ Take the tables inside the sqlite3 db :return: List of tables names """ res = self.conn.execute("SELECT name FROM sqlite_master WHERE type='table';") return [str(name[0]) for name in res] def get_columns_names(self, table_name): """ Take the columns details and add to attributes of the class :return: List of Columns Names """ self.cursor.execute("SELECT * FROM " + table_name) return [name[0] for name in self.cursor.description] def get_tables_schemas(self): """ Build a dict with each data from columns by table :return: Dict with {Table_name: [Columns_names]} """ return {table: self.get_columns_names(table) for table in self.table_list_names} def __getitem__(self, item): """ Build the table object if it was requested. :param item: Table name :return: Dict element of the item """ if item in self.table_list_obj: return self.table_list_obj[item] else: if item in self.table_list_names: t = TableNice(item, self.columns_by_tables[item], self.conn) else: raise Exception('The table ' + str(item) + ' doesn\'t belong to this database') self.table_list_obj[item] = t return self.table_list_obj[item]
C
UTF-8
1,215
3.859375
4
[]
no_license
/* ============================================================================ Name : str2.c Author : Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define BUF_SIZE 1024 int main(void) { char title[BUF_SIZE]; char hello1[BUF_SIZE]; //stack char* hello2= (char*)malloc(sizeof(char*)*BUF_SIZE); //heap memset(hello1, 0 , BUF_SIZE); memset(hello2, 0 , BUF_SIZE); strcpy(hello1, "hello1"); //배열에 넣는건 {"h","e",...} 이런식으로~ strcpy(hello2, "hello2"); printf("%s\n", hello1); printf("%s\n", hello2); strcat(hello1," world"); strcat(hello2," world"); printf("%s\n", hello1); printf("%s\n", hello2); sprintf(title,"<title>%s</title>",hello1); printf("%s\n",title); printf("<title>%s</title>\n",hello2); free(hello2); hello2=NULL; // 이 밑에도 많은 소스코드가 있을 때 유용. 체크용 //만약 실수로 free하기 전 malloc을 또 해버리면 이전 데이터는 (더 이상 접근할 수 없는)더미데이터가 된다. return EXIT_SUCCESS; }
Python
UTF-8
3,230
2.53125
3
[ "MIT" ]
permissive
import os import cv2 import dlib import numpy as np from sklearn.svm import SVC from sklearn import svm from sklearn.metrics import confusion_matrix from sklearn.preprocessing import LabelBinarizer from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report from sklearn.preprocessing import LabelEncoder import matplotlib.pyplot as plt import time import pandas as pd import joblib data_path = "C:/Users/busraguler/PycharmProjects/emotiondetection/dataset2" data_dir_list = os.listdir(data_path) detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") emotions = ["anger", "contempt", "disgust", "fear", "happiness", "neutral", "sadness", "surprise"] #Emotion liste test_dataset=[] test_labels=[] for data in data_dir_list: img_list=os.listdir(data_path+'/'+ data) print(''+'{}\n'.format(data)) for img in img_list[-10:]: input_img=cv2.imread(data_path + '/'+ data + '/'+ img) print(img) imgGray = cv2.cvtColor(input_img, cv2.COLOR_BGR2GRAY) faces = detector(imgGray) for face in faces: x1 = face.left() y1 = face.top() x2 = face.right() y2 = face.bottom() # img=cv2.rectangle(img, (x1,y1), (x2,y2), (0,255,0), 2) landmarks = predictor(imgGray, face) katilimci_landmarks=[] for n in range(0, 68): x = landmarks.part(n).x y = landmarks.part(n).y cv2.circle(input_img, (x, y), 3, (0, 0, 255), cv2.FILLED) katilimci_landmarks.append([x,y]) landmark_sol=katilimci_landmarks[0] landmark_sag=katilimci_landmarks[16] landmark_sol_kas=katilimci_landmarks[19] landmark_sag_kas=katilimci_landmarks[24] landmark_ust=np.array((landmark_sol_kas)+(landmark_sag_kas))/2 landmark_alt=katilimci_landmarks[8] x_kayma=float(landmark_sol[0]) y_kayma=float(landmark_ust[1]) x_olcek=float(landmark_sag[0]-landmark_sol[0]) y_olcek=float(landmark_alt[1]-landmark_ust[1]) katilimci_landmarks_np = np.array(katilimci_landmarks) katilimci_landmarks_np = katilimci_landmarks_np.astype(np.float32) katilimci_landmarks_np[:, 0] = 5.0 * (katilimci_landmarks_np[:, 0] - x_kayma) / x_olcek katilimci_landmarks_np[:, 1] = 5.0 * (katilimci_landmarks_np[:, 1] - y_kayma) / y_olcek test_dataset.append(katilimci_landmarks_np.tolist()) test_labels.append(data) cv2.imshow("image", input_img) cv2.waitKey(0) cv2.destroyAllWindows() testing_dataset=np.array(test_dataset) testing_labels=np.array(test_labels) # Kategorik etiketleri dönüştür testing_labels_df= pd.DataFrame(testing_labels, columns=['Emotion_Types']) labelencoder = LabelEncoder() testing_labels_df['Emotion_Types_Cat'] = labelencoder.fit_transform(testing_labels_df['Emotion_Types']) testing_labels_cat = testing_labels_df['Emotion_Types_Cat'] testing_dataset = testing_dataset.reshape(testing_dataset.shape[0], (testing_dataset.shape[1]*testing_dataset.shape[2])) np.savez('test_dataset2',test_data =testing_dataset , test_labels = testing_labels_cat);
Python
UTF-8
4,111
2.84375
3
[ "BSD-3-Clause" ]
permissive
# (C) Copyright 2005-2020 Enthought, Inc., Austin, TX # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in LICENSE.txt and may be redistributed only under # the conditions described in the aforementioned license. The license # is also available online at http://www.enthought.com/licenses/BSD.txt # # Thanks for using Enthought open source! """ The interface for an interactive Python shell. """ from traits.api import Event, HasTraits from pyface.key_pressed_event import KeyPressedEvent from pyface.i_widget import IWidget class IPythonShell(IWidget): """ The interface for an interactive Python shell. """ # 'IPythonShell' interface --------------------------------------------- #: A command has been executed. command_executed = Event() #: A key has been pressed. key_pressed = Event(KeyPressedEvent) # ------------------------------------------------------------------------ # 'IPythonShell' interface. # ------------------------------------------------------------------------ def interpreter(self): """ Get the shell's interpreter Returns ------- interpreter : InteractiveInterpreter instance Returns the InteractiveInterpreter instance. """ def bind(self, name, value): """ Binds a name to a value in the interpreter's namespace. Parameters ---------- name : str The python idetifier to bind the value to. value : any The python object to be bound into the interpreter's namespace. """ def execute_command(self, command, hidden=True): """ Execute a command in the interpreter. Parameters ---------- command : str A Python command to execute. hidden : bool If 'hidden' is True then nothing is shown in the shell - not even a blank line. """ def execute_file(self, path, hidden=True): """ Execute a file in the interpeter. Parameters ---------- path : str The path to the Python file to execute. hidden : bool If 'hidden' is True then nothing is shown in the shell - not even a blank line. """ def get_history(self): """ Return the current command history and index. Returns ------- history : list of str The list of commands in the new history. history_index : int from 0 to len(history) The current item in the command history navigation. """ def set_history(self, history, history_index): """ Replace the current command history and index with new ones. Parameters ---------- history : list of str The list of commands in the new history. history_index : int The current item in the command history navigation. """ class MPythonShell(HasTraits): """ The mixin class that contains common code for toolkit specific implementations of the IPythonShell interface. Implements: bind(), _on_command_executed() """ # ------------------------------------------------------------------------ # 'IPythonShell' interface. # ------------------------------------------------------------------------ def bind(self, name, value): """ Binds a name to a value in the interpreter's namespace. Parameters ---------- name : str The python idetifier to bind the value to. value : any The python object to be bound into the interpreter's namespace. """ self.interpreter().locals[name] = value # ------------------------------------------------------------------------ # Private interface. # ------------------------------------------------------------------------ def _on_command_executed(self): """ Called when a command has been executed in the shell. """ self.command_executed = self
Python
UTF-8
442
2.75
3
[]
no_license
#Default Imports import numpy as np ipl_matches_array =np.genfromtxt("data/ipl_matches_small.csv", dtype="|S50", skip_header=1, delimiter=",") #Your Solution def get_wicket_delivery_numbers_array(player): sliced_delivery=ipl_matches_array[:,11:12] sliced_batsman_wicket=ipl_matches_array[:,20:21] data=np.hstack((sliced_delivery,sliced_batsman_wicket)) deliveries=data[(np.where(data[:,1:]==player))] return deliveries
Markdown
UTF-8
2,940
2.546875
3
[]
no_license
Formats: [HTML](/news/2007/10/25/ehud-barak-the-defense-minister-of-israel-approves-a-plan-to-cut-off-supplies-of-electricity-to-the-gaza-strip-which-has-been-recently-de.html) [JSON](/news/2007/10/25/ehud-barak-the-defense-minister-of-israel-approves-a-plan-to-cut-off-supplies-of-electricity-to-the-gaza-strip-which-has-been-recently-de.json) [XML](/news/2007/10/25/ehud-barak-the-defense-minister-of-israel-approves-a-plan-to-cut-off-supplies-of-electricity-to-the-gaza-strip-which-has-been-recently-de.xml) ### [2007-10-25](/news/2007/10/25/index.md) ##### Ehud Barak # Ehud Barak, the Defense Minister of Israel, approves a plan to cut off supplies of electricity to the Gaza Strip which has been recently declared as "hostile territory". ### Sources: 1. [CNN](http://edition.cnn.com/2007/WORLD/meast/10/25/israel.gaza/index.html) ### Related: 1. [Following over 150 rockets being fired into Israel over the past four days from Gaza and attacks by Israel, Egypt has mediated a truce. Both Hamas and Ehud Barak praise the efforts for peace. ](/news/2012/11/13/following-over-150-rockets-being-fired-into-israel-over-the-past-four-days-from-gaza-and-attacks-by-israel-egypt-has-mediated-a-truce-both.md) _Context: Ehud Barak, Gaza Strip, Israel_ 2. [A Bolivian-flagged all-female international aid ship bound for Gaza is delayed as Cyprus bans it from passing, with Israel's Ehud Barak calling on France and the United States to prevent it from sailing because, he says, it is "a needless provocation". ](/news/2010/08/22/a-bolivian-flagged-all-female-international-aid-ship-bound-for-gaza-is-delayed-as-cyprus-bans-it-from-passing-with-israel-s-ehud-barak-call.md) _Context: Ehud Barak, Gaza Strip, Israel_ 3. [Israel asks the United Nations to suspend attempts to organise an international inquiry into the Gaza flotilla raid, with Israeli Defence Minister Ehud Barak saying "some organisation, probably backed by a terror organisation, (is) once again trying to send a vessel into Gaza." ](/news/2010/06/22/israel-asks-the-united-nations-to-suspend-attempts-to-organise-an-international-inquiry-into-the-gaza-flotilla-raid-with-israeli-defence-mi.md) _Context: Ehud Barak, Gaza Strip, Israel_ 4. [ Ehud Barak, the new Minister for Defense, states that Israel will admit "humanitarian cases" of Palestinians fleeing the Hamas-controlled Gaza Strip. ](/news/2007/06/20/ehud-barak-the-new-minister-for-defense-states-that-israel-will-admit-humanitarian-cases-of-palestinians-fleeing-the-hamas-controlled-g.md) _Context: Ehud Barak, Gaza Strip, Israel_ 5. [Gazan officials say Israeli soldiers killed a Palestinian farmer on his own land in the Gaza Strip. An Israeli military spokesperson said that he got too close to the border fence. ](/news/2018/03/3/gazan-officials-say-israeli-soldiers-killed-a-palestinian-farmer-on-his-own-land-in-the-gaza-strip-an-israeli-military-spokesperson-said-th.md) _Context: Gaza Strip, Israel_
C++
WINDOWS-1252
940
2.796875
3
[]
no_license
#include<stdio.h> #include<string.h> #include<algorithm> #include<sstream> #include<iostream> #include<math.h> #include<stdlib.h> typedef long long ll; using namespace std; struct Node { int deadline; int reduce; int use; }node[1001]; bool cmp(Node x,Node y) { if( x.reduce == y.reduce ) return x.deadline < y.deadline; return x.reduce > y.reduce ; } int main() { int t; scanf("%d",&t); for(int i=1;i<=t;i++) { int m; scanf("%d",&m); for(int j=0;j<m;j++) scanf("%d",&node[j].deadline ); for(int j=0;j<m;j++) scanf("%d",&node[j].reduce ); for(int j=0;j<m;j++) node[j].use=0; sort(node, node +m, cmp); int k; int sum=0; for(int j=0;j<m;j++) { for(k= node[j].deadline ;k>0;k--) //Ӻǰʱ { if( node[k].use ==0 ) { node[k].use =1; break; } } if( k == 0) sum += node[j].reduce ; } printf("%d\n",sum); } return 0; }
Java
UTF-8
3,016
2.046875
2
[]
no_license
package ru.vyukov.myappposition.utils; import com.codeborne.selenide.Configuration; import com.codeborne.selenide.junit.ScreenShooter; import lombok.extern.slf4j.Slf4j; import org.junit.Rule; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import java.util.Properties; /** * @author Oleg Vyukov */ @Slf4j @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, properties = "server.port=8080") @ActiveProfiles("mvc-test") @ContextConfiguration(classes = SelenideTest.Config.class) public abstract class SelenideTest { static { //use "-Dselenide.browser=firefox" for override in command line Properties props = System.getProperties(); props.setProperty("browser", "chrome"); } @Rule public ScreenShooter makeScreenshotOnFailure = ScreenShooter.failedTests().succeededTests(); @Autowired protected User demoUser; @TestConfiguration public static class Config extends WebSecurityConfigurerAdapter { private final String username = "demo_user"; public Config(@Value("${server.port}") int port, @Value("${tests.hostname}") String hostname) { Configuration.baseUrl = String.format("http://%s:%s", hostname, port); log.info("SELENIDE: baseUrl = " + Configuration.baseUrl); log.info("SELENIDE: browser = " + Configuration.browser); log.info("SELENIDE: remote = " + Configuration.remote); } @Bean UserDetails demoUser() { return User.withUsername(username).password("qwerty").authorities("USER").build(); } @Bean UserDetailsService mockUserDetailsService() { return (username) -> demoUser(); } @Bean MockUserFilter mockUserFilter() { return new MockUserFilter(demoUser()); } @Override protected void configure(HttpSecurity http) throws Exception { http.addFilterBefore( mockUserFilter(), BasicAuthenticationFilter.class); } } }
Swift
UTF-8
5,521
2.65625
3
[]
no_license
// // ViewController.swift // StretchMyHeader // // Created by Kevin Cleathero on 2017-07-04. // Copyright © 2017 Kevin Cleathero. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet var tableView: UITableView! @IBOutlet var headerView: UITableView! @IBOutlet var dateLabel: UILabel! @IBOutlet var imageHeaderView: UIView! let kTableHeaderHeight = CGFloat(200.0) //an array of newsItems var newsObjects = [NewsItem]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. configureTable() generateNews() setDate() } //MARK - Table Setup func configureTable() { // We set the table view header. //UITableViewAutomaticDimension - set my row height equal to the sum of all the constraints self.tableView.rowHeight = UITableViewAutomaticDimension self.tableView.estimatedRowHeight = 50.0 tableView.tableHeaderView = nil tableView.addSubview(imageHeaderView) //Next, we need to move our tableView down, let’s move it the size of our kTableHeaderHeight. Tableview comes with two properties that will be helpful to us: contentInset and contentOffSet. The contentInset property is used to set padding (kTableHeaderHeight). The contentOffset property is used to set how far we want to offset the start of your content (-kTableHeaderHeight, because -kTableHeaderHeight is now the top of the screen) self.tableView.contentInset = UIEdgeInsets(top: kTableHeaderHeight, left:0, bottom:0, right:0) self.tableView.contentOffset = CGPoint(x: 0, y: -kTableHeaderHeight) } func scrollViewDidScroll(_ scrollView: UIScrollView) { updateHeaderView() } func updateHeaderView() { var headerRect = CGRect(x: 0, y: -kTableHeaderHeight, width: tableView.bounds.width, height: kTableHeaderHeight) if tableView.contentOffset.y < -kTableHeaderHeight { headerRect.origin.y = tableView.contentOffset.y headerRect.size.height = -tableView.contentOffset.y } imageHeaderView.frame = headerRect } override var prefersStatusBarHidden: Bool { return true } //MARK - Data setup func generateNews(){ let news1 = NewsItem(category: "World", headline: "Climate change protests, divestments meet fossil fuels realities") let news2 = NewsItem(category: "Europe", headline: "Scotland's 'Yes' leader says independence vote is 'once in a lifetime'") let news3 = NewsItem(category: "Middle East", headline: "Airstrikes boost Islamic State, FBI director warns more hostages possible") let news4 = NewsItem(category: "Africa", headline: "Nigeria says 70 dead in building collapse; questions S. Africa victim claim") let news5 = NewsItem(category: "Asia Pacific", headline: "Despite UN ruling, Japan seeks backing for whale hunting") let news6 = NewsItem(category: "Americas", headline: "Officials: FBI is tracking 100 Americans who fought alongside IS in Syria") let news7 = NewsItem(category: "World", headline: "South Africa in $40 billion deal for Russian nuclear reactors") let news8 = NewsItem(category: "Europe", headline: "'One million babies' created by EU student exchanges") newsObjects.append(news1) newsObjects.append(news2) newsObjects.append(news3) newsObjects.append(news4) newsObjects.append(news5) newsObjects.append(news6) newsObjects.append(news7) newsObjects.append(news8) } //MARK - UITableView Delegates func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 5 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell:CustomTableCell = self.tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! CustomTableCell let newsItem = newsObjects[indexPath.row] cell.categoryLabel.text = "World" cell.headlineLabel.numberOfLines = 0 cell.headlineLabel.lineBreakMode = .byWordWrapping cell.headlineLabel.text = "Climate change protests, divestments meet fossil fuels realities" switch newsItem.category { case "World": cell.categoryLabel.textColor = UIColor.red case "Americas": cell.categoryLabel.textColor = UIColor.blue case "Europe": cell.categoryLabel.textColor = UIColor.green case "Middle East": cell.categoryLabel.textColor = UIColor.yellow case "Africa": cell.categoryLabel.textColor = UIColor.orange case "Asia Pacific": cell.categoryLabel.textColor = UIColor.purple default: cell.categoryLabel.textColor = UIColor.black } return cell } func setDate() { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MMMM dd" let today = NSDate() let date = dateFormatter.string(from: today as Date) dateLabel.text = date } }
C#
UTF-8
7,872
2.890625
3
[ "MIT" ]
permissive
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; //Required for MenuItem, means that this is an Editor script, must be placed in an Editor folder, and cannot be compiled! using System.Linq; //Used for Select public class ColorWindow : EditorWindow { //Now is of type EditorWindow [MenuItem("Custom Tools/ Color Window")] //This the function below it as a menu item, which appears in the tool bar public static void CreateShowcase() //Menu items can call STATIC functions, does not work for non-static since Editor scripts cannot be attached to objects { EditorWindow window = GetWindow<ColorWindow>("Color Window"); } private Color[,] colors; private int width = 8; private int height = 8; float randomnessBound = 0; private float colorComparisonTolerance = 0.1f; private bool fill = false; Texture colorTexture; Renderer textureTarget; Color selectedColor = Color.white; Color eraseColor = Color.white; public void OnEnable() { colors = new Color[height, width]; for (int i = 0; i < colors.GetLength(0); i++) for (int j = 0; j < colors.GetLength(1); j++) { colors[i, j] = GetRandomColor(); } colorTexture = EditorGUIUtility.whiteTexture; } private Color GetRandomColor() //Built a get random color tool { return new Color(Random.value, Random.value, Random.value, 1f); } private Color GetVariatedColor(Color color) { float randomness = Random.Range(0, randomnessBound); Color variant = color; variant.r += color.r * randomness; variant.g += color.g * randomness; variant.b += color.b * randomness; return variant; } void OnGUI() //Called every frame in Editor window { GUILayout.BeginHorizontal(); //Have each element below be side by side DoControls(); DoCanvas(); GUILayout.EndHorizontal(); } void DoControls() { GUILayout.BeginVertical(); //Start vertical section, all GUI draw code after this will belong to same vertical GUILayout.Label("ToolBar", EditorStyles.largeLabel); //A label that says "Toolbar" randomnessBound = EditorGUILayout.FloatField("Random", randomnessBound); if (randomnessBound < 0) randomnessBound = 0; if (randomnessBound > 1) randomnessBound = 1; selectedColor = EditorGUILayout.ColorField("Paint Color", selectedColor); //Make a color field with the text "Paint Color" and have it fill the selectedColor var fill = EditorGUILayout.Toggle("Fill", fill); eraseColor = EditorGUILayout.ColorField("Erase Color", eraseColor); //Make a color field with the text "Erase Color" if (GUILayout.Button("Fill All")) //A button, if pressed, returns true { for (int i = 0; i < colors.GetLength(0); i++) for (int j = 0; j < colors.GetLength(1); j++) { colors[i, j] = selectedColor; } } GUILayout.FlexibleSpace(); //Flexible space uses any left over space in the loadout textureTarget = EditorGUILayout.ObjectField("Output Renderer", textureTarget, typeof(Renderer), true) as Renderer; //Build an object field that accepts a renderer if (GUILayout.Button("Save to Object")) { Texture2D t2d = new Texture2D(width, height); //Create a new texture t2d.filterMode = FilterMode.Point; //Simplest non-blend texture mode textureTarget.material = new Material(Shader.Find("Diffuse")); //Materials require Shaders as an arguement, Diffuse is the most basic type textureTarget.sharedMaterial.mainTexture = t2d; //sharedMaterial is the MAIN RESOURCE MATERIAL. Changing this will change ALL objects using it, .material will give you the local instance for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { t2d.SetPixel(i, j, colors[i, j]); //Color every pixel using our color table, the texture is 8x8 pixels large, but strecthes to fit } } t2d.Apply(); //Apply all changes to texture } GUILayout.EndVertical(); //end vertical section } void DoCanvas() { Event evt = Event.current; //Grab the current event Color oldColor = GUI.color; //GUI color uses a static var, need to save the original to reset it GUILayout.BeginHorizontal(); //All following gui will be on one horizontal line until EndHorizontal is called for (int i = 0; i < width; i++) { GUILayout.BeginVertical(); //All following gui will be in a vertical line for (int j = 0; j < height; j++) { int index = j + i * height; //Rememeber, this is just like a 2D array, but in 1D Rect colorRect = GUILayoutUtility.GetRect(GUIContent.none, GUIStyle.none, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); //Reserve a square, which will autofit to the size given if ((evt.type == EventType.MouseDown || evt.type == EventType.MouseDrag) && colorRect.Contains(evt.mousePosition)) //Can now paint while dragging update { if (evt.button == 0) //If mouse button pressed is left { if (fill) { FloodFill(i, j, selectedColor, colors[i, j]); } else colors[i, j] = GetVariatedColor(selectedColor); } else colors[i, j] = GetVariatedColor(eraseColor); //Set the color of the index evt.Use(); //The event was consumed, if you try to use event after this, it will be non-sensical } GUI.color = colors[i, j]; //Same as a 2D array GUI.DrawTexture(colorRect, colorTexture); //This is colored by GUI.Color!!! } GUILayout.EndVertical(); //End Vertical Zone } GUILayout.EndHorizontal(); //End horizontal zone GUI.color = oldColor; //Restore the old color } bool CompareColors(Color a, Color b) { return Mathf.Abs(a.r - b.r) < colorComparisonTolerance && Mathf.Abs(a.g - b.g) < colorComparisonTolerance && Mathf.Abs(a.b - b.b) < colorComparisonTolerance; } void FloodFill(int x, int y, Color fillColor, Color canvasColor) { if (x < 0 || x >= height || y < 0 || y >= width || !CompareColors(canvasColor, colors[x, y]) || CompareColors(colors[x, y], fillColor) ) { return; } colors[x, y] = GetVariatedColor(fillColor); FloodFill(x + 1, y, fillColor, canvasColor); FloodFill(x - 1, y, fillColor, canvasColor); FloodFill(x, y + 1, fillColor, canvasColor); FloodFill(x, y - 1, fillColor, canvasColor); } }
Java
UTF-8
785
2.28125
2
[]
no_license
package com.client.transaction.webapi.dtos.response; import com.client.transaction.webapi.enums.RequestStatusEnum; public class ResponseDto { private RequestStatusEnum requestStatusEnum; private String notes; public ResponseDto() { } public ResponseDto(RequestStatusEnum requestStatusEnum, String notes) { this.requestStatusEnum = requestStatusEnum; this.notes = notes; } public RequestStatusEnum getRequestStatusEnum() { return requestStatusEnum; } public void setRequestStatusEnum(RequestStatusEnum requestStatusEnum) { this.requestStatusEnum = requestStatusEnum; } public String getNotes() { return notes; } public void setNotes(String notes) { this.notes = notes; } }
Java
UTF-8
697
2.921875
3
[]
no_license
package engine.entity; import engine.model.AnimatedModel; import engine.model.animation.Animator; /** * Entity which is able to run an animation */ public class AnimatedEntity extends Entity implements Simulated { protected Animator animator; public AnimatedEntity() { super(); this.animator = new Animator(); } public void update(double dt) { AnimatedModel model = (AnimatedModel) this.getModel().getModel(); this.animator.update(model.getJoints(), model.getRootJoint(), dt); } @Override public void simulate(double dt) { this.update(dt); } public Animator getAnimator() { return this.animator; } }
C#
UTF-8
972
2.765625
3
[]
no_license
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WYJK.Framework.Caching { /// <summary> /// 缓存管理器 /// </summary> public static class CacheManager { private static readonly ICache DefaultCache = new MemoryCacheHandle(); private static readonly ConcurrentDictionary<string,ICache> CacheContainer = new ConcurrentDictionary<string, ICache>(); /// <summary> /// 获取默认缓存容器 /// </summary> public static ICache Cache { get; } = DefaultCache; /// <summary> /// 获取指定名称的缓存容器 /// </summary> /// <param name="name"></param> /// <returns></returns> public static ICache GetCache(string name) { return CacheContainer.GetOrAdd(name, k => new MemoryCacheHandle(name)); } } }
Ruby
UTF-8
723
3.140625
3
[]
no_license
def after_midnight(time) array = time.split(":", 2).map { |number| number.to_i} return 0 if array[0] == 24 || time == "00:00" array[0] * 60 + array[1] end def before_midnight(time) array = time.split(":", 2).map { |number| number.to_i} return 0 if array[0] == 24 || time == "00:00" 1440 - (array[0] * 60 + array[1]) end p after_midnight('00:00') == 0 p before_midnight('00:00') == 0 p after_midnight('12:34') == 754 p before_midnight('12:34') == 686 p after_midnight('24:00') == 0 p before_midnight('24:00') == 0 p after_midnight('00:00') == 0 p before_midnight('00:05') == 1435 p after_midnight('12:54') == 774 p before_midnight('12:34') == 686 p after_midnight('24:00') == 0 p before_midnight('24:00') == 0
Python
UTF-8
642
2.78125
3
[]
no_license
import requests from bs4 import BeautifulSoup import html2text url = 'http://www.composingprograms.com/' r = requests.get(url) raw_html = r.text soup = BeautifulSoup(raw_html, 'lxml') links = soup.select('a[href^="./pages/"]') pages = [] for link in links: pages.append(url+link.get('href')[2:]) for link in pages: rq = requests.get(link) html = rq.text s = BeautifulSoup(html, 'lxml') contents = s.select('.inner-content') with open('sicp-python3.md', encoding='utf-8', mode='a') as sicp: sicp.write(html2text.html2text(str(contents[0]).replace('Â', '').replace('â', '').replace('../img', url+'img')))
C
UTF-8
964
3.921875
4
[]
no_license
#include<stdio.h> #include<ctype.h> int main(){ char word[50],upper; //intialization of character and words int i=0; printf("Enter the words:\n"); //printing input and storing it in word scanf("%49s",&word); printf("The upper case of given words is "); while(word[i]){ //looping the every character of word upper=word[i]; //storing the string of words to upper printf("%c",toupper(upper)); //converting the lowercase to uppercase one word at time due to loop i++; //loop will end when i will pass the last character of upper } printf("."); return 0; ///> }
C#
UTF-8
2,635
3.609375
4
[]
no_license
using _03.ShoppingSpree.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace _03.ShoppingSpree { public class Starter { public void Start() { List<Person> people = new List<Person>(); string[] peopleInput = Console.ReadLine() .Split(";", StringSplitOptions.RemoveEmptyEntries); foreach (var personInfo in peopleInput) { string[] personNameAndMoney = personInfo.Split("="); string name = personNameAndMoney[0]; decimal money = decimal.Parse(personNameAndMoney[1]); try { Person person = new Person(name, money); people.Add(person); } catch (ArgumentException ae) { Console.WriteLine(ae.Message); return; } } List<Product> products = new List<Product>(); string[] productsInput = Console.ReadLine() .Split(";", StringSplitOptions.RemoveEmptyEntries); foreach (var productInfo in productsInput) { string[] productNameAndCost = productInfo.Split("="); string name = productNameAndCost[0]; decimal cost = decimal.Parse(productNameAndCost[1]); try { Product product = new Product(name, cost); products.Add(product); } catch (ArgumentException ae) { Console.WriteLine(ae.Message); return; } } string[] command = Console.ReadLine() .Split(" ",StringSplitOptions.RemoveEmptyEntries); while (command[0]!="END") { string personName = command[0]; string productToBuy = command[1]; Person person = people.FirstOrDefault(n=>n.Name==personName); int personIndex = people.FindIndex(x=>x.Name==personName); Product product = products.FirstOrDefault(n=>n.Name==productToBuy); person.AddProduct(product); people[personIndex] = person; command = Console.ReadLine() .Split(" ", StringSplitOptions.RemoveEmptyEntries); } foreach (var person in people) { Console.WriteLine(person); } } } }
JavaScript
UTF-8
768
3.359375
3
[]
no_license
// builds mat function createMat(ROWS, COLS) { var mat = [] for (var i = 0; i < ROWS; i++) { var row = [] for (var j = 0; j < COLS; j++) { row.push('') } mat.push(row) } return mat } // rnd num function getRandomInteger(min, max) { var minNum = Math.ceil(min); var maxNum = Math.floor(max); return Math.floor(Math.random() * (maxNum - minNum) + minNum); } // Move the player by keyboard arrows function handleKey(event) { var i = gGamerPos.i; var j = gGamerPos.j; switch (event.key) { case 'ArrowLeft': moveTo(i, j - 1); break; case 'ArrowRight': moveTo(i, j + 1); break; case 'ArrowUp': moveTo(i - 1, j); break; case 'ArrowDown': moveTo(i + 1, j); break; } }
Java
UTF-8
933
2.109375
2
[]
no_license
package com.bolsadeideias.springboot.app.modell; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import lombok.AllArgsConstructor; import lombok.Data; @Data @AllArgsConstructor @Entity @Table(name = "creditos") public class Credito implements Serializable{ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY ) private Integer id; private String tipodecliente; private String tipodecredito; private String intervalodevalor; private String prazodereembolso; private double juroaplicavel; private double taxadeincumprimento; private String descricao; public Credito() { } }
TypeScript
UTF-8
4,868
2.578125
3
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
/// <reference path="./Pose.ts"/> /// <reference path="./PoseEvent.ts"/> /// <reference path="./Skeleton.ts"/> /// <reference path="./Bone.ts"/> /// <reference path="./SkeletonPoseLibrary.ts"/> /// <reference path="../../queue/PovProcessor.ts"/> /// <reference path="../../queue/MotionEvent.ts"/> /// <reference path="../../queue/EventSeries.ts"/> module QI{ export class PoseProcessor extends PovProcessor { public static INTERPOLATOR_GROUP_NAME = "SKELETON"; private _bones : Array<Bone>; public _lastPoseRun : string = "basis"; // only public for Pose constructor(private _skeleton : Skeleton, parentMesh : BABYLON.Mesh, skipRegistration : boolean){ super(parentMesh, skipRegistration); this._name = PoseProcessor.INTERPOLATOR_GROUP_NAME; // override dummy var nBones = this._skeleton.bones.length; this._skeleton.validateSkeleton(); } // =================================== inside before render ================================== /** * Called by the beforeRender() registered by this._mesh * SkeletonInterpolator is a subclass of POV.BeforeRenderer, so need to call its beforeRender method, _incrementallyMove() */ public incrementallyDeform(): boolean { super._incrementallyMove(); // test of this._currentSeries is duplicated, since super.incrementallyMove() cannot return a value // is possible to have a MotionEvent(with no deformation), which is not a SkeletalDeformation sub-class if (this._currentSeries === null || !(this._currentStepInSeries instanceof PoseEvent) ) return false; this._lastPoseRun = (<PoseEvent> this._currentStepInSeries).poseName; if (this._ratioComplete < 0) return false; // MotionEvent.BLOCKED or MotionEvent.WAITING for(var i = 0, nBones = this._skeleton.bones.length; i < nBones; i++){ (<Array<Bone>>this._skeleton.bones)[i]._incrementallyDeform(this._ratioComplete); } return true; } /** * @returns {string}- This is the name of which is the last one * in the queue. If there is none in the queue, then a check is done of the event currently * running, if any. * * If a pose has not been found yet, then get the last recorded pose. */ public getLastPoseNameQueuedOrRun() : string { // check the queue first for the last pose set to run var lastPose : any; for (var i = this._queue.length - 1; i >= 0; i--){ lastPose = this._getLastPoseEventInSeries(this._queue[i]); if (lastPose) return lastPose; } // queue could be empty, return last of current series if exists if (this._currentSeries){ lastPose = this._getLastPoseEventInSeries(this._currentSeries); if (lastPose) return lastPose; } // nothing running or queued; return last recorded return this._lastPoseRun; } private _getLastPoseEventInSeries(series : EventSeries) : string { var events = series._events; for (var i = events.length - 1; i >= 0; i--){ if (events[i] instanceof PoseEvent) return (<PoseEvent> events[i]).poseName; } return null; } // ======================================== event prep ======================================= /** called by super._incrementallyMove() */ public _nextEvent(event : MotionEvent) : void { var movementScaling : number; // is possible to have a MotionEvent(with no deformation), not SkeletalDeformation sub-class if (event instanceof PoseEvent){ var poseEvent = <PoseEvent> event; var pose = this._skeleton._poseLibrary.poses[poseEvent.poseName]; if (pose){ // sub-pose addition / substraction if (poseEvent.options.subposes){ for(var i = 0, len = poseEvent.options.subposes.length; i < len; i++){ if (poseEvent.options.revertSubposes) this._skeleton.removeSubPose(poseEvent.options.subposes[i]); else this._skeleton.addSubPose(poseEvent.options.subposes[i]); } } pose._assignPose(this._skeleton); } else if (poseEvent.poseName !== null) { BABYLON.Tools.Error("PoseProcessor: pose(" + poseEvent.poseName + ") not found"); return; } } super._nextEvent(event, this._skeleton._skelDimensionsRatio); } } }
Java
UTF-8
3,960
1.992188
2
[]
no_license
package com.urwoo.web.controller; import com.urwoo.framework.lang.StringUtils; import com.urwoo.framework.web.controller.base.BaseController; import com.urwoo.framework.web.response.UrwooResponse; import com.urwoo.framework.web.response.UrwooResponses; import com.urwoo.po.RightPo; import com.urwoo.query.RightQueryParam; import com.urwoo.query.order.OrderParam; import com.urwoo.service.RightService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/right/") public class RightController extends BaseController{ @Autowired private RightService rightService; @GetMapping(path = "query", produces = {DEFAULT_PRODUCES}) public UrwooResponse query(@RequestParam(name = "name", required = false) String name, @RequestParam(name = "propertyName", required = false) String propertyName, @RequestParam(name = "isAsc", required = false)Boolean isAsc, @RequestParam(name = "start", defaultValue = DEFAULT_START) Integer start, @RequestParam(name = "limit", defaultValue = DEFAULT_LIMIT) Integer limit){ RightQueryParam param = new RightQueryParam(); if (StringUtils.isNotBlank(name)) { param.setName(name); } if (StringUtils.isNotBlank(propertyName)){ OrderParam orderParam = new OrderParam(); orderParam.setPropertyName(propertyName); orderParam.setAsc(null == isAsc ? true : isAsc); param.setOrderParam(orderParam); } List<RightPo> rightList = rightService.rightList(param, start, limit); int count = rightService.rightCount(param); return UrwooResponses.page(rightList, count, start, limit); } @GetMapping(path = "get/{id}", produces = {DEFAULT_PRODUCES}) public UrwooResponse get(@PathVariable(name = "id") Integer id){ RightPo rightPo = rightService.getRight(id); return UrwooResponses.success(rightPo); } @PostMapping(path = "save", produces = {DEFAULT_PRODUCES}) public UrwooResponse save(@RequestParam(name = "name") String name, @RequestParam(name = "type") Integer type, @RequestParam(name = "url") String url, @RequestParam(name = "rightCode") String rightCode, @RequestParam(name = "parentId") Integer parentId){ RightPo rightPo = new RightPo(); rightPo.setName(name); rightPo.setType(type); rightPo.setUrl(url); rightPo.setRightCode(rightCode); rightPo.setParentId(parentId); rightService.saveRight(rightPo); return UrwooResponses.success(); } @PostMapping(path = "update/{id}", produces = {DEFAULT_PRODUCES}) public UrwooResponse update(@PathVariable(name = "id") Integer id, @RequestParam(name = "name") String name, @RequestParam(name = "type") Integer type, @RequestParam(name = "url") String url, @RequestParam(name = "rightCode") String rightCode, @RequestParam(name = "parentId") Integer parentId){ RightPo rightPo = new RightPo(); rightPo.setId(id); rightPo.setName(name); rightPo.setType(type); rightPo.setUrl(url); rightPo.setRightCode(rightCode); rightPo.setParentId(parentId); rightService.updateRight(rightPo); return UrwooResponses.success(); } @GetMapping(path = "delete", produces = {DEFAULT_PRODUCES}) public UrwooResponse delete(@RequestParam(name = "ids") Integer[] ids){ rightService.deleteRight(ids); return UrwooResponses.success(); } }
Java
UTF-8
18,991
1.820313
2
[]
no_license
package com.yourong.api.service.impl; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.alibaba.fastjson.JSONObject; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.yourong.api.dto.BindSecurityBankCardDto; import com.yourong.api.dto.MemberNonSecurityBankCardDto; import com.yourong.api.dto.SimpleMemberBankCardDto; import com.yourong.api.service.BalanceService; import com.yourong.api.service.MemberBankCardService; import com.yourong.common.domain.ResultDO; import com.yourong.common.enums.ResultCode; import com.yourong.common.exception.ManagerException; import com.yourong.common.exception.ServiceException; import com.yourong.common.thirdparty.sinapay.SinaPayClient; import com.yourong.common.thirdparty.sinapay.common.domain.ResultDto; import com.yourong.common.thirdparty.sinapay.common.enums.BankCode; import com.yourong.common.thirdparty.sinapay.member.domain.result.CardBindingResult; import com.yourong.common.util.BeanCopyUtil; import com.yourong.common.util.Collections3; import com.yourong.common.util.DateUtils; import com.yourong.core.common.MessageClient; import com.yourong.core.fin.manager.WithdrawLogManager; import com.yourong.core.uc.manager.MemberBankCardManager; import com.yourong.core.uc.model.MemberBankCard; @Service public class MemberBankCardServiceImpl implements MemberBankCardService { private Logger logger = LoggerFactory.getLogger(MemberBankCardServiceImpl.class); @Autowired private MemberBankCardManager memberBankCardManager; @Autowired private WithdrawLogManager withdrawLogManager; @Autowired private BalanceService balanceService; @Autowired private SinaPayClient sinaPayClient; @Override public MemberBankCard selectDeletedBankCard(Long id) { try { return memberBankCardManager.selectDeletedBankCard(id); } catch (ManagerException ex) { logger.error("selectDeletedBankCard", ex); } return null; } @Override @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED) public ResultDO<Object> addMemberBankCard(MemberBankCard memberBankCard) throws Exception { ResultDO<Object> result = checkBankCard(memberBankCard); if (result.isError()) { return result; } ResultDto<?> cardResult = sinaPayClient.bindingBankCard( memberBankCard.getMemberId(), memberBankCard.getBankCode(), memberBankCard.getCardNumber(), memberBankCard.getCardHolder(), memberBankCard.getBankMobile().toString(), false, memberBankCard.getUserBindIp()); if (cardResult.isSuccess() && cardResult.getModule() != null) { CardBindingResult cardBindingResult = (CardBindingResult) cardResult.getModule(); String card_id = cardBindingResult.getCardId(); memberBankCard.setOuterSourceId(card_id); } else { String errorResult = cardResult != null ? cardResult.getErrorMsg() : ""; String message = String.format("第三方支付,绑定银行卡异常MemberBankCard= %s,异常原因%s", memberBankCard.toString(), errorResult); thirdPayProsessError(result, errorResult, message); return result; } memberBankCard.setCreateTime(DateUtils.getCurrentDateTime()); memberBankCard.setUpdateTime(DateUtils.getCurrentDateTime()); memberBankCard.setDelFlag(1); memberBankCard.setCardType(1); memberBankCard.setIsSecurity(0); memberBankCardManager.insertSelective(memberBankCard); MessageClient.sendMsgForBindBandCard(memberBankCard.getBankCode(), memberBankCard.getCardNumber(), memberBankCard.getMemberId()); result.setSuccess(true); return result; } private void thirdPayProsessError(ResultDO<Object> result, String errorResult, String message) { result.setResult(message); logger.info("第三支付绑卡失败",message); result.setSuccess(false); result.setResult(errorResult); ResultCode.SINA_PAY_ERROR.setMsg(errorResult); result.setResultCode(ResultCode.SINA_PAY_ERROR); } /** * 检查提现卡 * @param memberBankCard * @return */ private ResultDO<Object> checkBankCard(MemberBankCard memberBankCard) { ResultDO<Object> result = new ResultDO<>(); BankCode bscBank = BankCode.getBankCode(memberBankCard.getBankCode()); if (bscBank == null) { // 银行不存在 result.setSuccess(false); result.setResultCode(ResultCode.MEMBER_BANK_NOT_EXIST_ERROR); return result; } if (memberBankCard.getBankMobile() == null || memberBankCard.getBankMobile() == 0) { // 手机号码 result.setSuccess(false); result.setResultCode(ResultCode.ERROR_SYSTEM_PARAM_FORMAT); return result; } // 银行卡号是否存在 MemberBankCard bankCard = getMemberBankCardByCardNumberAndMemberId(memberBankCard.getCardNumber(), memberBankCard.getMemberId()); if (bankCard != null) { // 银行卡号已经存在 result.setSuccess(false); result.setResultCode(ResultCode.MEMBER_BANK_CARD_EXIST_ERROR); return result; } return result; } /** * 快捷支付,效验卡信息 * @param memberBankCard * @return */ private ResultDO<Object> checkBankCardOnQuickPay(MemberBankCard memberBankCard) { ResultDO<Object> result = new ResultDO<>(); BankCode bscBank = BankCode.getBankCode(memberBankCard.getBankCode()); if (bscBank == null) { // 银行不存在 result.setSuccess(false); result.setResultCode(ResultCode.MEMBER_BANK_NOT_EXIST_ERROR); return result; } if(bscBank.getType() != 2 ){ // 银行不支持快捷支付 result.setSuccess(false); result.setResultCode(ResultCode.MEMBER_BANK_NOTSUPPORT_PAY); return result; } if (memberBankCard.getBankMobile() == null || memberBankCard.getBankMobile() == 0) { // 手机号码 result.setSuccess(false); result.setResultCode(ResultCode.ERROR_SYSTEM_PARAM_FORMAT); return result; } if(!memberBankCard.isUpgradeSecurity()){ // 银行卡号是否存在 MemberBankCard bankCard = getMemberBankCardByCardNumberAndMemberId( memberBankCard.getCardNumber(), memberBankCard.getMemberId()); if (memberBankCard.getId() != null && memberBankCard.getId() != 0) { if (bankCard == null) { // 银行卡号不存在 result.setSuccess(false); result.setResultCode(ResultCode.MEMBER_USERNAME_WITHDRAW_BANKID); return result; } }else{ if (bankCard != null) { // 银行卡号已经存在 result.setSuccess(false); result.setResultCode(ResultCode.MEMBER_BANK_CARD_EXIST_ERROR); return result; } } }else{//如果是升级,银行卡必须存在 try { if (memberBankCard.getId() == null) { result.setSuccess(false); result.setResultCode(ResultCode.MEMBER_USERNAME_WITHDRAW_BANKID); return result; } MemberBankCard bankCard2 = memberBankCardManager.getMemberBankCardById(memberBankCard.getId(), memberBankCard.getMemberId()); if(bankCard2 == null || bankCard2.getDelFlag() < 0){ // 银行卡号不存在 result.setSuccess(false); result.setResultCode(ResultCode.MEMBER_USERNAME_WITHDRAW_BANKID); return result; } if(bankCard2.getCardType() != 1){ // 银行卡号不存在 result.setSuccess(false); result.setResultCode(ResultCode.MEMBER_BANK_CARD_IS_QUICK_PAY); return result; } //为了安全考虑银行卡号不需客户端传递 memberBankCard.setCardNumber(bankCard2.getCardNumber()); } catch (ManagerException e) { e.printStackTrace(); } } return result; } @Override public MemberBankCard getMemberBankCardByCardNumberAndMemberId( String cardNumber, Long memberId) { try { return memberBankCardManager.getMemberBankCardByCardNumberAndMemberId(cardNumber, memberId); } catch (ManagerException ex) { logger.error("getMemberBankCardByCardNumberAndMemberId", ex); } return null; } @Override public ResultDO<Object> sendThirdPayCheckBlankCode(MemberBankCard memberBankCard) { ResultDO<Object> result = checkBankCardOnQuickPay(memberBankCard); if (result.isError()) { return result; } try { ResultDto<?> cardResult = sinaPayClient.bindingBankCard(memberBankCard.getMemberId(), memberBankCard.getBankCode(), memberBankCard.getCardNumber(), memberBankCard.getCardHolder(), memberBankCard.getBankMobile().toString(),true, memberBankCard.getUserBindIp()); if (cardResult.isSuccess() && cardResult.getModule() != null) { CardBindingResult cardBindingResult = (CardBindingResult) cardResult.getModule(); Map<String, Object> map = Maps.newHashMap(); map.put("ticket", cardBindingResult.getTicket()); map.put("cardId", cardBindingResult.getCardId()); result.setSuccess(true); result.setResult(map); } else { thirdPayProsessError(result, cardResult.getErrorMsg(), cardResult.getErrorMsg()); } } catch (Exception e) { logger.error("第三方接口绑定银行卡异常 memberBankCard =" + memberBankCard, e); result.setResultCode(ResultCode.SINA_PAY_ERROR); } return result; } @Override public ResultDO<Object> sendThirdPayCheckBlankCodeAdvance(String ticket ,String validCode,MemberBankCard memberBankCard) { ResultDO<Object> result = checkBankCardOnQuickPay(memberBankCard); if (result.isError()) { return result; } try { ResultDto<?> cardResult = sinaPayClient.bindingBankCardAdvance(ticket, validCode, memberBankCard.getUserBindIp()); if (cardResult.isError() || cardResult.getModule() == null) { setMessage(result, cardResult); return result; } CardBindingResult cardBindingResult = (CardBindingResult) cardResult.getModule(); // //卡未认证 // if (!cardBindingResult.isVerified()){ // setMessage(result, cardResult); // return result; // } if (memberBankCard.getId() != null && memberBankCard.getId() != 0) { MemberBankCard bankCard = this.memberBankCardManager.selectByPrimaryKey(memberBankCard.getId()); bankCard.setOuterSourceId(cardBindingResult.getCardId()); bankCard.setUpdateTime(DateUtils.getCurrentDateTime()); bankCard.setBankMobile(memberBankCard.getBankMobile()); bankCard.setCardType(2); this.memberBankCardManager.updateMemberBankCardQuickPay(bankCard); } else { memberBankCard.setOuterSourceId(cardBindingResult.getCardId()); memberBankCard.setCreateTime(DateUtils.getCurrentDateTime()); memberBankCard.setUpdateTime(DateUtils.getCurrentDateTime()); memberBankCard.setDelFlag(1); memberBankCard.setIsDefault(0); memberBankCard.setIsSecurity(0); memberBankCard .setCardType(2); memberBankCardManager.insertSelective(memberBankCard); } MessageClient.sendMsgForOpenQuickPayment(memberBankCard.getMemberId(), memberBankCard.getCardNumber(), memberBankCard.getBankCode()); JSONObject json = new JSONObject(); json.put("cardId", memberBankCard.getId()); result.setResult(json); result.setSuccess(true); } catch (Exception e) { logger.error("第三方接口绑定银行卡异常 ", e); result.setResultCode(ResultCode.SINA_PAY_ERROR); } return result; } private void setMessage(ResultDO<Object> result, ResultDto<?> cardResult) { // ResultCode.MEMBER_BANK_ADVACE_CODE.setMsg(cardResult.getErrorMsg()); result.setResultCode(ResultCode.MEMBER_ADVACE_CODE_EROOR); result.setResult(cardResult.getErrorMsg()); } @Override public List<MemberBankCard> getMemberBankCardByMemberId(Long memberId) { try { return memberBankCardManager.selectByMemberID(memberId); } catch (ManagerException ex) { logger.error("getMemberBankCardByMemberId", ex); } return null; } @Override @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED) public ResultDO<Object> deleteMemberBankCard(Long id, Long memberId, String userIp) throws Exception { ResultDO<Object> resultDO = new ResultDO<>(); try { MemberBankCard card = memberBankCardManager.selectByPrimaryKey(id); if (card == null) { resultDO.setResultCode(ResultCode.MEMBER_BANK_NOT_EXIST_ERROR); return resultDO; } if (memberId .compareTo( card.getMemberId()) !=0) { resultDO.setResultCode(ResultCode.MEMBER_USERNAME_WRONG_BANKID); return resultDO; } if (card.getDelFlag() != 1) { resultDO.setResultCode(ResultCode.MEMBER_USERNAME_WITHDRAW_BANKID); return resultDO; } boolean isWithDrawIng = withdrawLogManager.cardIsWithDrawIng(card.getMemberId(), id); if (isWithDrawIng){ resultDO.setResultCode(ResultCode.MEMBER_USERNAME_ISWITHDRAWING_BANKID); return resultDO; } if (card.getIsSecurity() == 1 && card.getCardType() == 2) { boolean isZero = balanceService.isZeroMemberTotalAsset(card.getMemberId()); if (!isZero) { resultDO.setResultCode(ResultCode.MEMBER_BANKCARD_NOT_ZERO); return resultDO; } } ResultDto<?> unBindingBankCard = sinaPayClient.unBindingBankCard(card.getMemberId(), card.getOuterSourceId(), userIp); if (unBindingBankCard.isSuccess()) { int i = memberBankCardManager.deleteMemberBankCard(id, userIp); if (i == 1){ resultDO.setSuccess(true); MessageClient.sendMsgForDeleteBankCard(card.getMemberId(), card.getCardNumber(), card.getBankCode()); } } } catch (Exception e) { logger.error("删除银行卡失败 id={},memberId={}",id,memberId,e); throw new ServiceException(e); } return resultDO; } @Override public int setDefaultMemberBankCard(Long id, Long memberId) { try { memberBankCardManager.resetMemberBankCardDefaultStatus(memberId); return memberBankCardManager.setDefaultMemberBankCard(id); } catch (Exception e) { logger.error("设置默认银行卡异常 memberId=" + memberId + " id=" + id, e); } return 0; } @Override public MemberBankCard getDefaultBankCardByMemberId(Long memberId) { try { return memberBankCardManager.getDefaultBankCardByMemberId(memberId); } catch (Exception e) { logger.error("获取默认银行卡失败 memberId=" + memberId, e); } return null; } @Override public boolean isExist(Long id, Long memberId) { try { return memberBankCardManager.isExist(id, memberId); } catch (Exception e) { logger.error("查询 id memberId=" + memberId, e); } return false; } @Override public List<MemberBankCard> selectAllQuickPayBankCard(Long memberId) { try { MemberBankCard bankCard = querySecurityBankCard(memberId); if(bankCard == null){ return memberBankCardManager.selectAllQuickPayBankCard(memberId); }else{ List<MemberBankCard> list = Lists.newArrayList(); list.add(bankCard); return list; } }catch (Exception e){ logger.error("查询 用户会员快捷支付卡id memberId=" + memberId, e); } return null; } @Override public MemberBankCard selectByPrimaryKey(Long id) { try { return memberBankCardManager.selectByPrimaryKey(id); } catch (Exception e) { logger.error("查询 银行卡 id =" + id, e); } return null; } @Override public MemberBankCard querySecurityBankCard(Long memberId) { try { return memberBankCardManager.querySecurityBankCard(memberId); } catch (Exception e) { logger.error("获得用户安全快捷支付卡信息异常,memberId=" + memberId, e); } return null; } @Override public List<MemberNonSecurityBankCardDto> selectNonSecurityBankCard(Long memberId) { try { List<MemberBankCard> bankCardList = memberBankCardManager.selectNonSecurityBankCard(memberId); if(Collections3.isNotEmpty(bankCardList)){ return BeanCopyUtil.mapList(bankCardList, MemberNonSecurityBankCardDto.class); } } catch (Exception e) { logger.error("获取用户非安全卡的银行卡异常,memberId=" + memberId, e); } return null; } @Override public BindSecurityBankCardDto bindSecurity(Long memberId) { BindSecurityBankCardDto dto = new BindSecurityBankCardDto(); // MemberBankCard securityBankCard = querySecurityBankCard(memberId); // if(securityBankCard != null){ // dto.setSecurity(true); // return dto; // } List<MemberNonSecurityBankCardDto> bankCardList = selectNonSecurityBankCard(memberId); if(Collections3.isNotEmpty(bankCardList)){ dto.setBankCardList(bankCardList); } return dto; } @Override public SimpleMemberBankCardDto getMemberBankCardById(Long id, Long memberId) { try { MemberBankCard bankCard = memberBankCardManager.getMemberBankCardById(id, memberId); if(bankCard != null){ return BeanCopyUtil.map(bankCard, SimpleMemberBankCardDto.class); } } catch (ManagerException e) { e.printStackTrace(); } return null; } }
JavaScript
UTF-8
353
3.3125
3
[]
no_license
const input = document.querySelector("input#name-input"); const userName = document.querySelector("span#name-output"); const isEmpty = (str) => !str.trim().length; input.addEventListener("input", function (e) { if (isEmpty(this.value)) { userName.textContent = "незнакомец"; return; } userName.textContent = e.target.value; });
Java
UTF-8
721
2.859375
3
[]
no_license
package com.mvn.javafx; import java.sql.SQLException; import static com.mvn.javafx.Enum.operations.*; public class Model { public float calculation(float a, float b, String operation) throws SQLException, ClassNotFoundException { if (PLUS.toString().equals(operation)) { return a + b; } else if (MINUS.toString().equals(operation)) { return a - b; } else if (MULTIPLICATION.toString().equals(operation)) { return a * b; } else if (DIVISION.toString().equals(operation)) { if (b == 0) { return 0; } return a / b; } System.out.println("N/A"); return (float) 0.0; } }
Markdown
UTF-8
2,240
3.796875
4
[]
no_license
# 5. Errors ### Error의 종류 - Compile-time error (syntax error, type error) - 여기서는 선언 있으면 ok - Link-time error - 선언은 있는데 그 실체가 없는 경우 - Runtime error - Logic error - 코드는 돌아가지만 잘못된 아웃풋 발생 #### Bad Function Arguments ~~~cpp int area(int length, int width){ return length*width; } int main(){ int x1=area(7); //컴파일에러 int x2=area("seven", 10); //컴파일에러 //아래는 컴파일러가 못걸러줌 int x3=area(7.5,10) //강제 형변환 이루어짐(7.5->7) int x4=area(-7,10) //타입은 맞지만 make no sense } ~~~ 컴파일러로 거를 수 없는 이 코드는 어떻게 해야할까 ~~~cpp int x4=area(-7,10) ~~~ 1. function(callee)이 내부적으로 체크하는 것이 안전 2. 외부에게 input이 잘못되었음을 알려야함.<br> => 어떻게 알릴까?<br> 1) 'return -1'과 같이 error value를 리턴<br> 2) 전역변수로 error status에 대한 지표 설정 <br> 1)과 2)의 단점: 1.caller가 체크하지 않으면 무시되고 2. 정상적인 흐름과 error가 발생했을 때의 흐름의 구분이 어려워진다. 3) ** throw an exception ** <br> 앞의 단점을 해결할 수 있음. 가독성 증가 ~~~cpp class Bad_area{}; int area(int length, int width){ if(length<=0 || width <=0) throw Bad_area{}; //throw 되는 순간 함수 종료, 모든 정상적인 흐름 종료됨 return length*width; } ~~~ *** #### 예외처리 예제 ex01 ~~~cpp void function3() { cout << "function3 start" << endl; throw(exception()); cout << "function3 end" << endl; } void function2() { cout << "function2 start" << endl; function3(); cout << "function2 end" << endl; } void function1() { cout << "function1 start" << endl; function2(); cout << "function1 end" << endl; } int main() { cout << "main start" << endl; function1(); cout << "main end" << endl; } ~~~ 결과 ~~~ main start function1 start function2 start function3 start ~~~ 예외를 던진 이후 모두 종료됨 ex02 ~~~cpp ~~~
PHP
UTF-8
2,080
2.8125
3
[]
no_license
<?php //include('login.html'); $servername = "localhost"; $username = "root"; $password = "root"; // Create connection $conn = new mysqli($servername, $username, $password); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } mysqli_select_db($conn,'animal_shelter'); $sql = 'SELECT * from profile'; $result=mysqli_query($conn,$sql); if(!$result){ die('Could not get data: '.mysqli_error()); } ?> <html> <head> <title>HOMEPAGE</title> </head> <h1>Welcome to Animal Shelter</h1> <hr> <h3>Add a new animal:</h3> <form action="newAnimal.php" method="post"> <input type="submit" name="addA"> </form> <h3>Make a donation:</h3> <form action="newDonation.php" method="post"> <input type="submit" name="addD"> </form> <h3>Adopt animal:</h3> <form action="newAdoption.php" method="post"> <input type="submit" name="adoption"> </form> <h3>Inquire about animal:</h3> <form action="newInquiry.php" method="post"> <input type="submit" name="addInquiry"> </form> <h3>View Database:</h3> <form action="database.php" method="post"> <input type="submit" name="adddy"> </form> <h1> Animals</h1> <table> <table border ='1'> <hr> <tr> <th>Animal_ID</th> <th>Description</th> <th>Age</th> <th>Type</th> <th>Breed</th> <th>Size</th> <th>Color</th> <th>Availability</th> </tr> <?php $sql = 'SELECT * from animal'; $result=mysqli_query($conn,$sql); if(!$result){ die('Could not get data: '.mysqli_error()); } while($row=mysqli_fetch_assoc($result)){ //echo "Profile_ID: {$row['Profile_ID']} <br>"; echo "<tr>"; echo "<td>".$row['Animal_ID']."</td>"; echo "<td>".$row['Description']."</td>"; echo "<td>".$row['Age']."</td>"; echo "<td>".$row['Type']."</td>"; echo "<td>".$row['Breed']."</td>"; echo "<td>".$row['Size']."</td>"; echo "<td>".$row['Color']."</td>"; echo "<td>".$row['Availability']."</td>"; echo "</tr>"; } mysqli_free_result($result); //echo "Fetched data successfully\n"; //mysqli_close($conn); ?> </table> </html>
Java
UTF-8
391
2.046875
2
[]
no_license
package com.RestBotLambda.lambda.function; public enum TableStatus { INITIATED(false), PAYMENT_PENDING(false), PAYMENT_SUCCESS(false), ACCEPTED(true), CONFIRMED(true), CONFORMED(true), AVALIBLE( true); private Boolean showAdmin; private TableStatus(Boolean showAdmin) { this.showAdmin = showAdmin; } public Boolean getShowAdmin() { return showAdmin; } }
Java
UTF-8
292
1.703125
2
[]
no_license
package com.manager.repository; import com.manager.model.MessageForUser; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface MessageForUserRepository extends JpaRepository<MessageForUser, Integer> { }
Java
UTF-8
977
2.359375
2
[]
no_license
package com.os.details; public class patient { private int patientID; private String patientName; private int age; private String gender; private String address; private String result; public int getPatientID() { return patientID; } public void setPatientID(int patientID) { this.patientID = patientID; } public String getPatientName() { return patientName; } public void setPatientName(String patientName) { this.patientName = patientName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } }
Markdown
UTF-8
2,318
2.546875
3
[ "Apache-2.0" ]
permissive
# Data identifiers and locators Hybrid ICN makes use of data identifiers to name the data produced by an end host. Data identifiers are encoded using a routable name prefix and a non routable name suffix to provide the ability to index a single IP packet in an prefix is unambigous manner. A full data name is composed of 160 bits. A routable name prefix in IPv4 network is 32 bits long while in IPv6 is 128 bits long. A name prefix is a valid IPv4 or IPv6 address. The 32 rightmost bits are used by the applications to index data within the same stream. A data source that is using the hicn stack is reacheable through IP routing where a producer socket is listening as the producer name prefix is IP routable. Locators are IP interface identifiers and are IPv4 or IPv6 addresses. Data consumers are reacheable through IP routing over their locators. For requests, the name prefix is stored in the destination address field of the IP header while the source address field stored the locator of the consumer. # Producer/Consumer Architecture Applications make use of the hicn network architecture by using a Prod/Cons API. Each communication socket is connection-less as a data producer makes data available to data consumer by pushing data into a named buffer. Consumers are responsible for pulling data from data producers by sending requests indexing the full data name which index a single MTU sized data packet. The core # Packet forwarding Packet forwarding leverages IP routing as requests are forwarded using name prefixes and replies using locators. # Relay nodes A relay node is implemented by using a packet cache which is used to temporarily store requests and replies. The relay node acts as a virtual proxy for the data producers as it caches data packets which can be sent back to data consumer by using the full name as an index. Requests must be cached and forwarded upstream towards data producers which will be able reach back the relay nodes by using the IP locators of the relays. Cached requests store all locators as currently written in the source address field of the request while requests forwarded upstream will get the source address rewritten with the relay node locator. Data packets can reach the original consumers via the relay nodes by using the requence of cached locators.
TypeScript
UTF-8
3,095
2.8125
3
[]
no_license
function throwStatus(response: Response) { if (!response.ok) { throw new Error("Failed (" + response.url + ") with status " + response.status + " " + response.statusText); } else { return response; } } /** * Just like a fetch but setup sensible defaults + setState({ loading }) before and after fetch * @param {string} url - URL to call * @param {Object} opts - Fetch options (default applied) * @param {this} that - Component to update state */ function ftch(url: string, opts?: any, that?: any) { opts = opts ? opts : {} opts.method = opts.method || "GET" opts.mode = opts.mode || "same-origin" opts.credentials = opts.credentials || "same-origin" if (typeof opts.headers === "undefined") { opts.headers = {} } if (opts.method !== "GET") { opts.headers["Content-Type"] = opts.headers["Content-Type"] || "application/json" if (typeof opts.body === "object" && opts.headers["Content-Type"] === "application/json") { opts.body = JSON.stringify(opts.body) } } opts.headers.Accept = opts.headers.Accept || "application/json" opts.loading = opts.loading || "loading" const loadingStarted = {}; loadingStarted[opts.loading] = true; const loadingFinished = {}; loadingFinished[opts.loading] = false; const stateResultError = opts.stateResultError || (opts.stateResult && that ? that.state[opts.stateResult] : null) console.log(`Fetch ${opts.method} ${url}`) if (that) that.setState(loadingStarted) return fetch(url, opts) .then(response => { if (opts.stateResponse) { const res = {}; res[opts.stateResponse] = response; that.setState(res); }; return throwStatus(response).json(); }) // parses response to JSON .catch(error => { console.error(`Fetch ${opts.method} ${url} error: `, error, arguments); if (that) that.setState(Object.assign({ error: error ? error.message : "unknown", exception: error }, loadingFinished)); if (opts.stateResult && that) { const res = {} res[opts.stateResult] = stateResultError that.setState(res) } else { throw new Error(error ? error : "unknown") } }).then(json => { if (typeof json === "undefined" || json.error) { console.error(`Fetch ${opts.method} ${url} error: `, json ? json.error : "undefined"); if (opts.stateResult && that) { const res = <any> {} res.error = json ? json.error : "undefined" res[opts.stateResult] = stateResultError that.setState(Object.assign(res, loadingFinished)) } else { if (that) that.setState(Object.assign({ error: json ? json.error : "undefined" }, loadingFinished)); } } else { console.log(`Fetch ${opts.method} ${url} complete: `, json); if (opts.stateResult && that) { const res = {} res[opts.stateResult] = json that.setState(Object.assign(res, loadingFinished)) } else { if (that) that.setState(loadingFinished) } } return new Promise((resolve) => resolve(json)) }) } export { throwStatus, ftch };
Java
UTF-8
5,707
2.65625
3
[]
no_license
package com.project.paging; import java.util.ArrayList; import java.util.List; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.project.dto.MemberDTO; import com.project.dto.OrderDTO; import com.project.dto.PageDTO; import com.project.dto.ShopBoardDTO; import com.project.dto.ShopPagingDTO; import com.project.dto.Tl_BoardDTO; @Component public class AdminPaging { @Autowired private SqlSessionTemplate sst; //페이징 알고리즘 관련 메소드 //여기서 받을 매개변수는 클라이언트에서 입력받은 페이지의 값이다. public List<String> aPaging(int page, int totalCount) { //데이터베이스에서 검색된 게시물의 갯수(이건 데이터베이스의 select문에 따라 변해야 함) int countList = 10;//한 페이지에 출력될 게시물의 수(이는 웹사이트에 따라 다를 수 있지만 기본적으로는 10개임) int totalPage = totalCount / countList;//총 게시물의 수 / 한 페이지당 들어갈 게시물의 수로 총 페이지의 수를 구한다 if (totalCount % 10 > 0){totalPage++;} //만일 현재 페이지 번호가 총 페이지 번호보다 크다면? //->현재 페이지를 강제로 총 페이지 번호로 치환시킬 수 있음 //if(totalPage < page){page = totalPage;} //int page = 14;//이건 클라이언트에서 사용자가 페이지번호를 클릭했을 때 받는 값이다. //(이 값을 기점으로 아래의 페이지가 변할 것이니 주의하도록) int countPage = 10; //한 페이지당 보여줄 수 있는 최대 숫자 //보여줄 수 있는 페이지의 시작과 끝값 int startPage = ((page-1)/10) * 10 + 1; int endPage = startPage + countPage -1; /* //각 페이지당 데이터베이스의 글을 보여줄 수 있음 int startCount = (page - 1) * countPage + 1; int endCount = page * countPage; */ //위와 같은 로직으로 짤 경우 맨 마지막 페이지를 보정해줘야 함 if(endPage > totalPage){endPage = totalPage;} List<String> pageList = new ArrayList(); //만일 받아온 페이지의 값이 1보다 클 경우에는 이전을 추가로 달아준다. if(page > 1){pageList.add("<이전");} //입력받은 페이지번호를 화면에 출력시킨다. for(int i = startPage; i<=endPage; i++ ){ pageList.add(" "+ i +" ");} //만일 현재 페이지보다 전체 페이지의 값이 더 큰 경우 다음을 추가로 달아준다. if(page < totalPage){pageList.add("다음>");} //만일 endPage보다 총 페이지가 더 클 경우 끝을 추가로 달아준다. //if(endPage < totalPage){pageList.add("<끝>");} return pageList; } //각 페이지에 해당하는 게시글(멤버) 10개를 출력시키는 메소드(검색없이) public List<MemberDTO> SelectPageList(int page){ int countPage = 10; int startCount = (page - 1) * countPage + 1; int endCount = page * countPage; List<MemberDTO>BoardContentList = sst.selectList("AdminDAO.PageMemberselect", new PageDTO(startCount , endCount)); return BoardContentList;} //각 페이지에 해당하는 게시글 10개를 출력시키는 메소드(검색 키워드로 이동했을 경우) public List<MemberDTO>SelectPageKeywordList(int page ,String keyword){ int countPage = 10; int startCount = (page - 1) * countPage + 1; int endCount = page * countPage; List<MemberDTO>BoardContentList = sst.selectList("AdminDAO.PageMemberIdselect", new PageDTO(startCount,endCount,keyword)); return BoardContentList;} //각 페이지에 해당하는 게시글(샵보드) 10개를 출력시키는 메소드(검색없이) public List<ShopBoardDTO> ShopBoardSelectPageList(int page){ int countPage = 10; int startCount = (page - 1) * countPage + 1; int endCount = page * countPage; List<ShopBoardDTO>ShopBoardContentList = sst.selectList("AdminDAO.PageShopBoardSelect", new PageDTO(startCount , endCount)); return ShopBoardContentList;} //각 페이지에 해당하는 게시글(오더) 10개를 출력시키는 메소드(검색없이) public List<OrderDTO> OrderBoardSelectPageList(int page){ int countPage = 10; int startCount = (page - 1) * countPage + 1; int endCount = page * countPage; List<OrderDTO>OrderBoardContentList = sst.selectList("AdminDAO.PageOrderBoardSelect", new PageDTO(startCount , endCount)); return OrderBoardContentList;} //각 페이지에 해당하는 게시글(SNS) 10개를 출력시키는 메소드(검색없이) public List<Tl_BoardDTO> SNSBoardSelectPageList(int page){ int countPage = 10; int startCount = (page - 1) * countPage + 1; int endCount = page * countPage; List<Tl_BoardDTO>SNSBoardContentList = sst.selectList("AdminDAO.PageSNSBoardSelect", new PageDTO(startCount , endCount)); return SNSBoardContentList;} //각 페이지에 해당하는 게시글(SNS) 10개를 출력시키는 메소드(SNS 제목 검색 키워드로 이동했을 경우) public List<Tl_BoardDTO>SelectTitlePageSNSBoardSelect(int page ,String keyword){ int countPage = 10; int startCount = (page - 1) * countPage + 1; int endCount = page * countPage; List<Tl_BoardDTO>SelectTitleSNSBoardContentList = sst.selectList("AdminDAO.SelectTitlePageSNSBoardSelect", new PageDTO(startCount,endCount,keyword)); return SelectTitleSNSBoardContentList;} }
Python
UTF-8
3,649
2.6875
3
[]
no_license
import bs4 import requests from mongoengine import * from bson.objectid import ObjectId import datetime class LineStop(EmbeddedDocument): _id = ObjectIdField(required=True, default=ObjectId,unique=True, primary_key=True) title = StringField(required=True) time = StringField() url = StringField(required=True) class Line(Document): number = StringField(required=True) url = StringField(required=True) leftTable = EmbeddedDocumentListField(LineStop, default=[]) rightTable = EmbeddedDocumentListField(LineStop, default=[]) published = DateTimeField(default=datetime.datetime.now) class getAllLine(): def __init__(self,zditmURL): self.zditmURL = zditmURL # connect('publictransportwebdb', host='localhost', port=27017) self.getBS() def getBS(self): self.zditmHTML = requests.get(basicURL) self.zditmBS = bs4.BeautifulSoup(self.zditmHTML.text,'html.parser') def getLine(self,url): self.getLineStops(url) def getLines(self): for table in self.zditmBS.find_all('ul',{'class':'listalinii'}): for line in table: linePost = Line(number=line.a.text, url=line.a.attrs['href']) linePost = self.getLineStops(line.a.attrs['href'],linePost) linePost.save() def getLineStops(self,lineURL,line): lineStopsBS = bs4.BeautifulSoup(requests.get('https://www.zditm.szczecin.pl/' + lineURL).text,'html.parser') #print left table lineTableLeft = lineStopsBS.find('div',{'class':'trasywierszelewo'}) tableLeft = lineTableLeft.find_all('tr',{'class': None}) for table in tableLeft: time = table.find('td',{'class': 'czas'}) busStop = table.find('td',{'class': 'przystanek'}) timeDic = '' titleDic = '' urlDic = '' try: if busStop.a.find('span',{'class':'przystanekdod'}) == None: try: timeDic = time.text except: pass titleDic = busStop.text urlDic = busStop.a.attrs['href'] except: pass if titleDic and urlDic: line.leftTable.create(title=titleDic, time=timeDic, url=urlDic) #print left table lineTableRight = lineStopsBS.find('div',{'class':'trasywierszeprawo'}) tableRight = lineTableRight.find_all('tr',{'class': None}) for table in tableRight: time = table.find('td',{'class': 'czas'}) busStop = table.find('td',{'class': 'przystanek'}) timeDic = '' titleDic = '' urlDic = '' try: if busStop.a.find('span',{'class':'przystanekdod'}) == None: try: timeDic = time.text except: pass titleDic = busStop.text urlDic = busStop.a.attrs['href'] except: pass if titleDic and urlDic: line.rightTable.create(title=titleDic, time=timeDic, url=urlDic) return line basicURL = "https://www.zditm.szczecin.pl/pl/pasazer/rozklady-jazdy,wedlug-linii" connect('publictransportwebdb', host='localhost', port=27017) abc = getAllLine(basicURL) abc.getLines() # print('\n\n\n') # abc.getLines() # linePost = Line(number='1', url='pl/pasazer/rozklady-jazdy,linia,1') # linePost = abc.getLineStops('pl/pasazer/rozklady-jazdy,linia,1',linePost) # linePost.save()
Swift
UTF-8
962
2.796875
3
[]
no_license
// // UIImageView.swift // MusicPlayer // // Created by yang.zhang on 2018/11/8. // Copyright © 2018 yang.zhang. All rights reserved. // import UIKit extension UIImageView { func downloaded(from src: String?, contentMode mode: UIView.ContentMode = .scaleAspectFit, useFallImage fall: UIImage? = nil ) -> Void { contentMode = mode guard let src = src else { self.image = fall return } guard let url = URL.ATS(string: src) else { self.image = fall return } MPBaseURLSession.getImage(withUrl: url) { image, error in guard let image = image, error == nil else { DispatchQueue.main.async() { self.image = fall } return } DispatchQueue.main.async() { self.image = image } } } }
SQL
WINDOWS-1251
17,768
3.125
3
[]
no_license
/* --PEKPQ*/ create or replace package body PEKPQ as procedure PEKPQ_DELETE(acursession CHAR, aInstanceID CHAR) as aObjType varchar2(255); begin select objtype into aObjType from instance where instanceid=ainstanceid; if aObjType ='PEKPQ' then declare cursor child_PEKPQ_DEF is select PEKPQ_DEF.PEKPQ_DEFid ID from PEKPQ_DEF where PEKPQ_DEF.InstanceID = ainstanceid; row_PEKPQ_DEF child_PEKPQ_DEF%ROWTYPE; begin --open child_PEKPQ_DEF; for row_PEKPQ_DEF in child_PEKPQ_DEF loop PEKPQ_DEF_DELETE (acursession,row_PEKPQ_DEF.id,aInstanceID); end loop; --close child_PEKPQ_DEF; end; return; <<del_error>> return; end if; end; procedure PEKPQ_HCL(acursession CHAR, aROWID CHAR, aIsLocked out integer) as aObjType varchar2(255); atmpStr varchar2(255); aUserID CHAR(38); aLockUserID CHAR(38); aLockSessionID CHAR(38); begin select objtype into aObjtype from instance where instanceid=aRowid; if aobjtype = 'PEKPQ' then select usersid into auserID from the_session where the_sessionid=acursession; declare cursor lch_PEKPQ_DEF is select PEKPQ_DEF.PEKPQ_DEFid ID from PEKPQ_DEF where PEKPQ_DEF.InstanceID = arowid; ROW_PEKPQ_DEF lch_PEKPQ_DEF%ROWTYPE; begin --open lch_PEKPQ_DEF; for row_PEKPQ_DEF in lch_PEKPQ_DEF loop select LockUserID,LockSessionID into aLockUserID,aLockSessionID from PEKPQ_DEF where PEKPQ_DEFid=row_PEKPQ_DEF.id; if not aLockUserID is null then if aLockUserID <> auserID then aisLocked := 4; /* CheckOut by another user */ close lch_PEKPQ_DEF; return; end if; end if; if not aLockSessionID is null then if aLockSessionID <> aCURSESSION then aisLocked:= 3; /* Lockes by another user */ close lch_PEKPQ_DEF; return; end if; end if; PEKPQ_DEF_HCL (acursession,ROW_PEKPQ_DEF.id,aisLocked); if aisLocked >2 then close lch_PEKPQ_DEF; return; end if; end loop; --close lch_PEKPQ_DEF; end; end if; aIsLocked:=0; end; procedure PEKPQ_propagate(acursession CHAR, aROWID CHAR) as aObjType varchar2(255); atmpStr varchar2(255); achildlistid CHAR(38); assid CHAR(38); begin select objtype into aObjType from instance where instanceid=aRowid; if aobjtype = 'PEKPQ' then select securitystyleid into aSSID from instance where instanceid=aRowID; declare cursor pch_PEKPQ_DEF is select PEKPQ_DEF.PEKPQ_DEFid id from PEKPQ_DEF where PEKPQ_DEF.InstanceID = arowid; row_PEKPQ_DEF pch_PEKPQ_DEF%ROWTYPE; begin --open pch_PEKPQ_DEF; for row_PEKPQ_DEF in pch_PEKPQ_DEF loop PEKPQ_DEF_SINIT( acursession,row_PEKPQ_DEF.id,assid); PEKPQ_DEF_propagate( acursession,row_PEKPQ_DEF.id); end loop; --close pch_PEKPQ_DEF; end; end if; end; procedure PEKPQ_DEF_BRIEF ( aCURSESSION CHAR, aPEKPQ_DEFid CHAR, aBRIEF out varchar2 ) as aaccess integer; atmpStr varchar2(255); atmpID CHAR(38); existsCnt integer; begin -- checking the_session -- select count(*) into existsCnt from the_session where the_sessionid=acursession and closed=0 ; if existsCnt=0 then raise_application_error(-20000,' .'); return; end if; if aPEKPQ_DEFid is null then aBRIEF:=''; return; end if; -- Brief body -- select count(*)into existsCnt from PEKPQ_DEF where PEKPQ_DEFID=aPEKPQ_DEFID; if existsCnt >0 then -- verify access -- select SecurityStyleID into atmpid from PEKPQ_DEF where PEKPQ_DEFid=aPEKPQ_DEFID; CheckVerbRight (acursession=>acursession,aThe_Resource=>atmpID,averb=>'BRIEF',aaccess=>aaccess); if aaccess=0 then raise_application_error(-20000,'No access for BRIEF Structure=PEKPQ_DEF'); return; end if; aBRIEF:=func.PEKPQ_DEF_BRIEF_F(aPEKPQ_DEFid); else aBRIEF:= ' '; end if; aBRIEF:=substr(aBRIEF,1,255); end; procedure PEKPQ_DEF_DELETE /* */ ( aCURSESSION CHAR, aPEKPQ_DEFid CHAR, ainstanceid char ) as aSysLogID CHAR(38); aaccess integer; aSysInstID CHAR(38); atmpID CHAR(38); existsCnt integer; aChildListid CHAR(38); begin select Instanceid into aSysInstID from instance where objtype='MTZSYSTEM'; select count(*) into existsCnt from the_session where the_sessionid=acursession and closed=0 ; if existsCnt=0 then raise_application_error(-20000,' .'); return; end if; -- Delete body -- select count(*) into existsCnt from PEKPQ_DEF where PEKPQ_DEFID=aPEKPQ_DEFID; if existsCnt >0 then -- verify access -- select SecurityStyleID into atmpID from PEKPQ_DEF where PEKPQ_DEFid=aPEKPQ_DEFID; CheckVerbRight (acursession=>acursession,aThe_Resource=>atmpID,averb=>'DELETEROW',aaccess=>aaccess ) ; if aaccess=0 then CheckVerbRight (acursession=>acursession,aThe_Resource=>atmpID,averb=>'DELETEROW:PEKPQ_DEF',aaccess=>aaccess); if aaccess=0 then raise_application_error(-20000,' . =PEKPQ_DEF'); return; end if; end if; -- verify lock -- PEKPQ_DEF_ISLOCKED( acursession=>acursession,aROWID=>aPEKPQ_DEFid,aIsLocked=>aaccess); if aaccess>2 then raise_application_error(-20000,' . =PEKPQ_DEF'); return; end if; --begin tran-- -- erase child items -- select MTZ.newid() into aSysLogid from SYS.DUAL; MTZSystem.SysLog_SAVE (aCURSESSION=>acursession ,aTheSession=>acursession, aInstanceID=>aSysInstID, aSysLogid=>aSysLogid, aLogStructID => 'PEKPQ_DEF', aVERB=>'DELETEROW', aThe_Resource=>aPEKPQ_DEFid, aLogInstanceID=>aInstanceID); declare cursor chld_PEKPQ_DEF is select instanceid ID from instance where OwnerPartName ='PEKPQ_DEF' and OwnerRowID=aPEKPQ_DEFid; row_PEKPQ_DEF chld_PEKPQ_DEF%ROWTYPE; begin --open chld_PEKPQ_DEF; for row_PEKPQ_DEF in chld_PEKPQ_DEF loop Kernel.INSTANCE_OWNER (acursession,row_PEKPQ_DEF.id,null,null); Kernel.INSTANCE_DELETE (acursession,row_PEKPQ_DEF.id); end loop; --close chld_PEKPQ_DEF; end ; delete from PEKPQ_DEF where PEKPQ_DEFID = aPEKPQ_DEFID; end if; -- close transaction -- <<del_error>> existsCnt:=0; end; /**/ procedure PEKPQ_DEF_SAVE /* */ ( aCURSESSION CHAR, aPEKPQ_DEFid CHAR, aInstanceID CHAR ,aORG CHAR := null /* *//* */ ,asequence NUMBER/* *//* */ ,aTheDate DATE/* *//* */ ,aTheDept CHAR/* *//* */ ,aTheComment VARCHAR2/* *//* */ ,aTheSumm NUMBER/* *//* */ ,aToSuplier CHAR/* *//* */ ,aTheDescription VARCHAR2 := null /* *//* */ ,aTheDogovor CHAR := null /* *//* */ ,aCode1C VARCHAR2 := null /* 1 *//* 1 */ ) as aSysLogid CHAR(38); aUniqueRowCount integer; atmpStr varchar2(255); atmpID CHAR(38); aaccess int; aSysInstID CHAR(38); existsCnt integer; begin select Instanceid into aSysInstID from instance where objtype='MTZSYSTEM'; -- checking the_session -- select count(*) into existsCnt from the_session where the_sessionid=acursession and closed=0 ; if existsCnt =0 then raise_application_error(-20000,' .'); return; end if; -- Insert / Update body -- select count(*) into existsCnt from PEKPQ_DEF where PEKPQ_DEFID=aPEKPQ_DEFID; if existsCnt >0 then -- UPDATE -- -- verify access -- select SecurityStyleID into atmpID from PEKPQ_DEF where PEKPQ_DEFid=aPEKPQ_DEFID; CheckVerbRight( acursession=>acursession,aThe_Resource=>atmpID,averb=>'EDITROW',aaccess=>aaccess); if aaccess=0 then CheckVerbRight (acursession=>acursession,aThe_Resource=>atmpID,averb=>'EDITROW:PEKPQ_DEF',aaccess=>aaccess ); if aaccess=0 then raise_application_error(-20000,' . =PEKPQ_DEF'); return; end if; end if; -- verify lock -- PEKPQ_DEF_ISLOCKED( acursession=>acursession,aROWID=>aPEKPQ_DEFid,aIsLocked=>aaccess); if aaccess>2 then raise_application_error(-20000,' . =PEKPQ_DEF'); return; end if; -- update row -- select mtz.newid() into asyslogid from sys.dual; MTZSystem.SysLog_SAVE( aTheSession=>acursession,aCURSESSION=>acursession, aInstanceID=>asysinstid, aSysLogid=>aSysLogid, aLogStructID => 'PEKPQ_DEF', aVERB=>'EDITROW', aThe_Resource=>aPEKPQ_DEFid,aLogInstanceID=>aInstanceID); update PEKPQ_DEF set ChangeStamp=sysdate , ORG=aORG , sequence=asequence , TheDate=aTheDate , TheDept=aTheDept , TheComment=aTheComment , TheSumm=aTheSumm , ToSuplier=aToSuplier , TheDescription=aTheDescription , TheDogovor=aTheDogovor , Code1C=aCode1C where PEKPQ_DEFID = aPEKPQ_DEFID; -- checking unique constraints -- else -- INSERT -- -- verify access -- select SecurityStyleID into atmpID from instance where instanceid=ainstanceid; CheckVerbRight (acursession=>acursession,aThe_Resource=>atmpID,averb=>'CREATEROW',aaccess=>aaccess ); if aaccess=0 then CheckVerbRight (acursession=>acursession,aThe_Resource=>atmpID,averb=>'CREATEROW:PEKPQ_DEF',aaccess=>aaccess); if aaccess=0 then raise_application_error(-20000,' . =PEKPQ_DEF'); return; end if; end if; MTZ.Kernel.instance_ISLOCKED( acursession=>acursession,aROWID=>aInstanceID,aIsLocked=>aaccess); if aaccess>2 then raise_application_error(-20000,' . =PEKPQ_DEF'); return; end if; select Count(*) into existsCnt from PEKPQ_DEF where InstanceID=aInstanceID; if existsCnt >0 then raise_application_error(-20000,' . : <PEKPQ_DEF>'); return; End if; select MTZ.newid() into aSysLogID from sys.dual; MTZSystem.SysLog_SAVE( aTheSession=>acursession,aCURSESSION=>acursession, aInstanceID=>asysinstid, aSysLogid=>aSysLogid, aLogStructID => 'PEKPQ_DEF', aVERB=>'CREATEROW', aThe_Resource=>aPEKPQ_DEFid,aLogInstanceID=>aInstanceID); insert into PEKPQ_DEF ( PEKPQ_DEFID ,InstanceID ,ORG ,sequence ,TheDate ,TheDept ,TheComment ,TheSumm ,ToSuplier ,TheDescription ,TheDogovor ,Code1C ) values ( aPEKPQ_DEFID ,aInstanceID ,aORG ,asequence ,aTheDate ,aTheDept ,aTheComment ,aTheSumm ,aToSuplier ,aTheDescription ,aTheDogovor ,aCode1C ); PEKPQ_DEF_SINIT( aCURSESSION,aPEKPQ_DEFid,atmpid); -- checking unique constraints -- end if; -- close transaction -- end; procedure PEKPQ_DEF_PARENT /* */ ( aCURSESSION CHAR, aRowID CHAR , aParentID out CHAR , aParentTable out varchar2 ) as existsCnt integer; begin -- checking the_session -- select count(*)into existsCnt from the_session where the_sessionid=acursession and closed=0 ; if existsCnt=0 then raise_application_error(-20000,' .'); return; end if; aParentTable := 'INSTANCE'; select INSTANCEID into aParentID from PEKPQ_DEF where PEKPQ_DEFid=aRowID; end; procedure PEKPQ_DEF_ISLOCKED /* */ ( aCURSESSION CHAR, aRowID CHAR , aIsLocked out integer ) as aParentID CHAR(38); aUserID CHAR(38); aLockUserID CHAR(38); aLockSessionID CHAR(38); aParentTable varchar2(255); existsCnt integer; astr varchar2(4000); begin aisLocked := 0; -- checking the_session -- select count(*) into existsCnt from the_session where the_sessionid=acursession and closed=0; if existsCnt=0 then raise_application_error(-20000,' .'); return; end if; select usersid into auserID from the_session where the_sessionid=acursession; select LockUserID,LockSessionID into aLockUserID, aLockSessionID from PEKPQ_DEF where PEKPQ_DEFid=aRowID; /* verify this row */ if not aLockUserID is null then if aLockUserID <> auserID then aisLocked := 4; /* CheckOut by another user */ return; else aisLocked := 2; /* CheckOut by caller */ return; end if; end if; if not aLockSessionID is null then if aLockSessionID <> aCURSESSION then aisLocked := 3; /* Lockes by another user */ return; else aisLocked := 1; /* Locked by caller */ return; end if; end if; aisLocked := 0; PEKPQ_DEF_parent (aCURSESSION,aROWID,aParentID,aParentTable); if aparenttable='INSTANCE' then astr := 'begin Kernel.' || aPARENTTABLE || '_islocked (:1,:2,:3); end;'; Else astr := 'begin PEKPQ.' || aPARENTTABLE || '_islocked (:1,:2,:3); end;'; end if; execute immediate astr using aCURSESSION,aParentID ,out aISLocked; end; procedure PEKPQ_DEF_LOCK /* */ ( aCURSESSION CHAR, aRowID CHAR , aLockMode integer ) as aParentID CHAR(38); aUserID CHAR(38); atmpID CHAR(38); aaccess integer; aIsLocked integer; aParentTable varchar2(255); existsCnt integer; begin select count(*) into existsCnt from the_session where the_sessionid=acursession and closed=0; -- checking the_session -- if existsCnt=0 then raise_application_error(-20000,' .'); return; end if; select usersid into auserid from the_session where the_sessionid=acursession; PEKPQ_DEF_ISLOCKED (aCURSESSION,aROWID,aISLocked ); if aIsLocked >=3 then raise_application_error(-20000,' '); return; end if; if aIsLocked =0 then PEKPQ_DEF_HCL (acursession,aRowID,aisLocked); if aIsLocked >=3 then raise_application_error(-20000,' , '); return; end if; end if; select SecurityStyleID into atmpID from PEKPQ_DEF where PEKPQ_DEFid=aROWID; CheckVerbRight (acursession=>acursession,aThe_Resource=>atmpID,averb=>'LOCKROW',aaccess=>aaccess); if aaccess=0 then raise_application_error(-20000,' . =PEKPQ_DEF'); return; end if; if aLockMode =2 then update PEKPQ_DEF set LockUserID =auserID ,LockSessionID =null where PEKPQ_DEFid=aRowID; return; end if; if aLockMode =1 then update PEKPQ_DEF set LockUserID =null,LockSessionID =aCURSESSION where PEKPQ_DEFid=aRowID; return; end if; end ; procedure PEKPQ_DEF_HCL /* */ ( aCURSESSION CHAR, aRowID CHAR , aIsLocked out integer ) as achildlistid CHAR(38); aUserID CHAR(38); aLockUserID CHAR(38); aLockSessionID CHAR(38); begin select usersid into auserID from the_session where the_sessionid=acursession; aIsLocked :=0; end; procedure PEKPQ_DEF_UNLOCK /* */ ( aCURSESSION CHAR, aRowID CHAR ) as aParentID CHAR(38); aUserID CHAR(38); aIsLocked integer; aParentTable varchar2(255); existsCnt integer; begin -- checking the_session -- select count(*) into existsCnt from the_session where the_sessionid=acursession and closed=0 ; if existsCnt=0 then raise_application_error(-20000,' .'); return; end if; select usersid into auserID from the_session where the_sessionid=acursession; PEKPQ_DEF_ISLOCKED( aCURSESSION,aROWID,aISLocked); if aIsLocked >=3 then raise_application_error(-20000,' '); return; end if; if aIsLocked =2 then update PEKPQ_DEF set LockUserID =null where PEKPQ_DEFid=aRowID; return; end if; if aIsLocked =1 then update PEKPQ_DEF set LockSessionID =null where PEKPQ_DEFid=aRowID; return; end if; end; procedure PEKPQ_DEF_SINIT /* */ ( aCURSESSION CHAR, aRowID CHAR , aSecurityStyleID CHAR ) as aParentID CHAR(38); aParentTable varchar2(255); aStr varchar2(4000); aStyleID CHAR(38); atmpID CHAR(38); aaccess integer; begin select SecurityStyleID into atmpID from PEKPQ_DEF where PEKPQ_DEFid=aROWID; CheckVerbRight (acursession=>acursession,aThe_Resource=>atmpID,averb=>'SECURE',aaccess=>aaccess); if aaccess=0 then raise_application_error(-20000,' . =PEKPQ_DEF'); return; end if; if aSecurityStyleID is null then PEKPQ_DEF_parent( aCURSESSION,aROWID,aParentID ,aParentTable); astr:= 'select SecurityStyleID from ' || aParentTable || ' where ' ||aParentTable || 'id=:1' ; execute immediate astr into aStyleID using aParentid; update PEKPQ_DEF set securitystyleid =aStyleID where PEKPQ_DEFid = aRowID; else update PEKPQ_DEF set securitystyleid =aSecurityStyleID where PEKPQ_DEFid = aRowID; end if; end ; procedure PEKPQ_DEF_propagate /* */ ( aCURSESSION CHAR, aRowID CHAR ) as achildlistid CHAR(38); aSSID CHAR(38); begin select securityStyleid into aSSID from PEKPQ_DEF where PEKPQ_DEFid=aRowid; end; end PEKPQ; /
Python
UTF-8
12,614
3.46875
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: Pranay S. Yadav """ from collections import Counter from itertools import compress, islice from time import perf_counter from ETC.NSRWS.x1D import core from ETC.seq.recode import cast from ETC.seq.check import arraytype def _mask_and_count(seq, mask, order): """ Apply binary mask to a sequence and count most frequently occurring windows This function does 3 things in the following sequence: 1. Create sliding windows of a given size (order) - using zip and islice 2. Apply a supplied mask to the sliding windows - using compress 3. Count most frequently occurring window - using Counter In the NSRWS algorithm, this is the most time consuming step. Essentially expands a 1D sequence to a 2D sequence - where the sequence follows row-wise & the columnar expansion encodes a sliding window for each row: 1D sequence: (1,2,3,4,5,6,7) 2D expansion for window order=3: ((1,2,3), (2,3,4), (3,4,5), (4,5,6), (5,6,7)) The mask is applied row-wise & must be of the same length as the number of rows in this 2D expansion. This is given by: len(mask) = len(seq) - (order - 1) Example application of the mask (1,0,0,1,1): 1 -> ((1,2,3), 0 -> (2,3,4), ----> ((1,2,3), 0 -> (3,4,5), (4,5,6), 1 -> (4,5,6), (5,6,7)) 1 -> (5,6,7)) Unique windows (rows of 2D expansion) are counted and most frequently occurring row is returned with counts. 1D sequence with overlap: (1,1,1,1,1,2,1) 2D expansion for window order=3: ((1,1,1), (1,1,1), ----> overlap (1,1,1), ----> overlap (1,1,2), (1,2,1)) mask will be (1,0,0,1,1) and its application will yield: ((1,1,1), (1,1,2), (1,2,1)) Here, each window occurs once and the first one is returned -> (1,1,1) Parameters ---------- seq : array.array Discrete symbolic sequence containing 32-bit unsigned integers. mask : array.array Collection of Booleans, where 0s indicate locations on "seq" to mask out. 0s correspond to overlapping windows. order : int Size of window for NSRWS, 2 or greater. Returns ------- freq_window : array.array Most frequently occurring non-overlapping "window" of size "order". count : int Number of times the most frequently occurring window occurs. """ # Create overlapped sliding windows (each window a tuple of size order) & apply mask filtered = compress(zip(*(islice(seq, i, None) for i in range(order))), mask) # Count sliding windows (tuples are hashable!) & get the one most common with counts freq_window, count = Counter(filtered).most_common(1)[0] # Assign array type and return freq_window = cast(freq_window) return freq_window, count def _onestep_pairs(seq, verbose=True): """ Execute one full step of NSRPS (NSRWS with order=2) for a given sequence Makes use of 2 functions written in Cython & _mask_and_count in the following steps: 1. Find overlapping pairs & store their indices for masking -> get_mask_pairs() 2. Apply the mask and find most frequent pair -> _mask_and_count() 3. Substitute all occurrences of the most frequent pair -> substitute_pairs() This function is different from _onestep_windows because: 1. It is *much* faster due to fewer nested loops 2. It targets a more common use case scenario: for distances, for CCC, etc 3. For higher window orders, correctness needs to be proved outside of tests The implementation will benefit from: 1. Decorators for timing 2. Decorators for verbosity of output 3. Cython implementation of the slowest part: _mask_and_count problem: counting windows in C? Parameters ---------- seq : array.array Discrete symbolic sequence containing 32-bit unsigned integers. verbose : bool, optional Whether to report extra details. These include the frequent pair that was substituted, its counts & total time taken. The default is True. Returns ------- tuple, of the following fixed elements: seq : array.array Discrete symbolic sequence containing 32-bit unsigned integers, with most frequently occurring non-sequentially overlapping pair substituted. signal : bool indicator for the state of sequence with all distinct pairs (count=1) optional elements of tuple that depend on verbosity: freq_pair : array.array Frequent pair substituted count : int Number of times the frequent pair occurred in the sequence time_taken : float Time taken to execute step """ # Initialize timer before = perf_counter() # Initialize signal for tracking sequence state with all distinct pairs signal = False # Compute mask for overlapping pairs mask = core.get_mask_pairs(seq) # Apply mask and find most frequent pair freq_pair, count = _mask_and_count(seq, mask, 2) # Get value for substitution of the most frequent pair with sub_value = 1 + max(seq) # If all distinct pairs, substitute the first one & set signal to True if count == 1: out = cast(seq[1:]) out[0] = sub_value signal = True # Else, substitute all instances of the frequent pair else: out = cast(core.substitute_pairs(seq, freq_pair, sub_value)) # Completion timer after = perf_counter() # If verbose, return more things if verbose: time_taken = after - before return out, signal, freq_pair, count, time_taken # Else return bare essentials return out, signal def _onestep_windows(seq, order, verbose=True): """ Execute one full step of NSRWS with order>=2 for a given sequence Makes use of 2 functions written in Cython & _mask_and_count in the following steps: 1. Find overlapping windows & store their indices as mask -> get_mask_windows() 2. Apply the mask and find most frequent window -> _mask_and_count() 3. Substitute all occurrences of most frequent window -> substitute_windows() This function is different from _onestep_pairs because: 1. This is slower due to more nested loops and checks 2. Of course, it handles the generalized case for different window orders 3. For higher window orders, correctness needs to be proved outside of tests The implementation will benefit from: 1. Decorators for timing 2. Decorators for verbosity of output 3. Cython implementation of the slowest part: _mask_and_count problem: counting windows in C? Parameters ---------- seq : array.array Discrete symbolic sequence containing 32-bit unsigned integers. order : int Size of window for NSRWS, 2 or greater. verbose : bool, optional Whether to report extra details. These include the frequent pair that was substituted, its counts & total time taken. The default is True. Returns ------- tuple, of the following fixed elements: seq : array.array Discrete symbolic sequence containing 32-bit unsigned integers, with most frequently occurring non-sequentially overlapping window substituted. signal : bool indicator for the state of sequence with all distinct pairs (count=1) optional elements of tuple that depend on verbosity: freq_pair : array.array Frequent window substituted count : int Number of times the frequent window occurred in the sequence time_taken : float Time taken to execute step """ # Initialize timer before = perf_counter() # Initialize signal for tracking sequence state with all distinct windows signal = False # Compute mask for overlapping windows mask = core.get_mask_windows(seq, order) # Apply mask and find most frequent window freq_window, count = _mask_and_count(seq, mask, order) # Get value for substitution of the most frequent window with sub_value = 1 + max(seq) # If all distinct windows, substitute the first one & set signal to True if count == 1: out = cast(seq[order - 1 :]) out[0] = sub_value signal = True # Else, substitute all instances of the frequent window else: out = cast(core.substitute_windows(seq, order, freq_window, sub_value)) # Completion timer after = perf_counter() # If verbose, return more things if verbose: return out, signal, freq_window, count, after - before # Else return bare essentials return out, signal def _onestep(seq, order, verbose=True): """ Wrapper that switches routine (pairs vs windows) depending on order For pairs (order=2), execute _onestep_pairs which is faster For higher orders, execute _onestep_windows Parameters ---------- seq : array.array Discrete symbolic sequence containing 32-bit unsigned integers. order : int Size of window for NSRWS, 2 or greater. verbose : bool, optional Whether to report extra details. These include the frequent pair that was substituted, its counts & total time taken. The default is True. Returns ------- tuple, of the following fixed elements: seq : array.array Discrete symbolic sequence containing 32-bit unsigned integers, with most frequently occurring non-sequentially overlapping window substituted. signal : bool indicator for the state of sequence with all distinct pairs (count=1) optional elements of tuple that depend on verbosity: freq_pair : array.array Frequent window substituted count : int Number of times the frequent window occurred in the sequence time_taken : float Time taken to execute step """ if order == 2: return _onestep_pairs(seq[:], verbose) if order > 2: return _onestep_windows(seq[:], order, verbose) def onestep(seq, order, verbose=True, check=True): """ Execute one step of NSRWS on given sequence and window size. This function exposes the functionality of NSRWS with various checks for inputs and sizes. Wraps around _onestep & for convenience, allows disabling of equality check. Parameters ---------- seq : array.array Discrete symbolic sequence containing 32-bit unsigned integers. order : int Size of window for NSRWS, 2 or greater. verbose : bool, optional Whether to report extra details. These include the frequent pair that was substituted, its counts & total time taken. The default is True. check : bool, optional Check for equality of all symbols in sequence. The default is True. Returns ------- tuple, of the following fixed elements in this order: array.array Discrete symbolic sequence containing 32-bit unsigned integers, with most frequently occurring non-sequentially overlapping window substituted. bool indicator for the state of sequence with all distinct pairs (count=1) optional elements of tuple that depend on verbosity: array.array Frequent window substituted int Number of times the frequent window occurred in the sequence float Time taken to execute step """ # Coerce input to appropriate array type, if not possible throw a fit & exit if not arraytype(seq): seq = cast(seq) if seq is None: return None # Check whether all elements are equal, if requested, & exit if True if check and core.check_equality(seq): print("> All elements in sequence are equal!") return None # Check if size of sequence is shorter than order, exit if True if len(seq) < order: print("> Sequence input shorter than order!\n> Can't perform substitution ...") return None # Else execute one step of NSRWS and return return _onestep(seq, order, verbose)
Markdown
UTF-8
3,252
2.640625
3
[ "MIT" ]
permissive
--- title: Mártir date: 2019-01-11 13:00:00 topics: - martir - filosofia --- Do grego martys, mártir significa "testemunha". Pode tratar-se de um testemunho no plano histórico, jurídico ou religioso. Um "mártir" é alguém que é morto injustamente por aquilo em que acredita. Por extensão, pessoa que sofre extremamente ou morre por uma causa. Figuradamente, todo e qualquer gênero de sofrimento corporal ou moral. ### Martírio? Sofrimento e morte suportados por fiéis à fé. Morte ou tormentos sofridos pela religião cristã: a palma do martírio; o martírio de Cristo. ### O que é a "era dos Mártires"? No governo do imperador Diocleciano, é a grande quantidade de vítimas ocorridas entre 303 e 313. ### Há diferença entre martirológico e martirológio? Martirológico diz respeito à história dos mártires. Martirológio, ou seja, louvor dos mártires, significa a lista dos mártires com as datas das suas mortes. Por extensão, catálogo de vítimas. ### Que passagem evangélica sublinha o testemunho do sangue? "Mártir é aquele que dá sua vida por fidelidade ao testemunho de Jesus" (cf. At 7,55-60). ### Por que Jesus é o protótipo do mártir? Pela voluntariedade do seu sacrifício, deu o testemunho supremo da sua fidelidade à missão que o Pai lhe confiou. "Eu nasci e vim ao mundo para dar testemunho da verdade" (cf. Ap 1,5; 3,14). ### Como Lucas sublinha, na Paixão de Jesus, os traços definidores do mártir? Conforto da graça divina na hora da angústia (Lc 22,43); silêncio e paciência diante das acusações e dos ultrajes (23,9); inocência reconhecida por Pilatos e Herodes (23,4); esquecimento dos próprios sofrimentos (23,28); acolhida prestada ao ladrão arrependido (23,43); perdão dado a Pedro (22,61) e aos próprios perseguidores (22,51; 23,34). ### Como são representados os mártires? De modo geral, são representados como instrumento de seu suplício: aureola, coroa e palma do martírio. ### A morte de Sócrates foi vista como um martírio? Sim. Para a Igreja cristã, como Jesus era o Verbo, Sócrates fora uma espécie de cristão pré-cristianismo. ### Há mártires no Espiritismo? Na religião, o martírio liga-se ao derramamento de sangue. Como o Espiritismo não é uma religião, não há necessidade desse derramamento. Na Revista Espírita (abril de 1862), Allan Kardec diz que os mártires do Espiritismo encontram-se naqueles que lutam pela ideia nova; são chamados de loucos, insensatos, visionários. Acrescenta: "O progresso do tempo trocou as torturas físicas pelo martírio da concepção e do parto cerebral das ideias que, filhas do passado, serão mães do futuro". ### Bibliografia GRANDE ENCICLOPÉDIA PORTUGUESA E BRASILEIRA. Lisboa/Rio de Janeiro: Editorial Enciclopédia, \[s.d. p.\]. LEMAÎTRE, Nicole, QUINSON, Marie-Thérèse e SOT, Véronique. Dicionário Cultural do Cristianismo. Tradução de Gilmar Saint'Clair Ribeiro, Maria Stela Gonçalves e Yvone Maria de Campos Teixeira da Silva. São Paulo: Loyola, 1999. LEON-DUFOUR, X. et al. Vocabulário de Teologia Bíblica. Rio de Janeiro: Vozes, 1972. ## Fonte [Aprofundamento Doutrinário](https://sites.google.com/view/aprofundamentodoutrinario/mártir) Autor: Sérgio Biagi Gregório ## Veja Também TODO
Java
UTF-8
1,143
1.851563
2
[ "MIT" ]
permissive
package com.ruoyi.activiti.mapper; import java.util.List; import com.ruoyi.activiti.domain.RyProduct; /** * 产品Mapper接口 * * @author xiaoguo * @date 2020-09-25 */ public interface RyProductMapper { /** * 查询产品 * * @param id 产品ID * @return 产品 */ public RyProduct selectRyProductById(Long id); /** * 查询产品列表 * * @param ryProduct 产品 * @return 产品集合 */ public List<RyProduct> selectRyProductList(RyProduct ryProduct); /** * 新增产品 * * @param ryProduct 产品 * @return 结果 */ public int insertRyProduct(RyProduct ryProduct); /** * 修改产品 * * @param ryProduct 产品 * @return 结果 */ public int updateRyProduct(RyProduct ryProduct); /** * 删除产品 * * @param id 产品ID * @return 结果 */ public int deleteRyProductById(Long id); /** * 批量删除产品 * * @param ids 需要删除的数据ID * @return 结果 */ public int deleteRyProductByIds(String[] ids); }
Markdown
UTF-8
8,279
2.625
3
[]
no_license
--- title: Release Notes description: platform: Web updatedAt: Thu Sep 05 2019 04:01:39 GMT+0800 (CST) --- # Release Notes ## Overview Designed as a substitute for the legacy Agora Signaling SDK, the Agora Real-time Messaging SDK provides a more streamlined implementation and more stable messaging mechanism for you to quickly implement real-time messaging scenarios. > For more information about the SDK features and applications, see [Agora RTM Overview](../../en/Real-time-Messaging/RTM_product.md). ## v1.0.1 v1.0.1 is released on September 5, 2019. ### Issues Fixed - Peer-to-peer messages have a chance to become offline messages even if [enableOfflineMessaging](https://docs.agora.io/en/Real-time-Messaging/API%20Reference/RTM_web/interfaces/sendmessageoptions.html) is not set. - The local user has a chance of not being able to retrieve the latest user attributes of a remote user, if the remote user updates his/her attributes immediately after logging in the Agora RTM system. ### Improvements - Caches up to six seconds of peer-to-peer messages sent when the network is interrupted, and resends the cached messages immediately after the SDK reconnects to the Agora RTM system. - Timeout for sending a peer-to-peer message is reset to 10 seconds. ## v1.0.0 v1.0.0 is released on August 5th, 2019. ### New Features #### Interconnects with the legacy Agora Signaling SDK v1.0.0 implements the `LocalInvitation.channelId` and `LocalInvitation.channelId` property. > - To intercommunicate with the legacy Agora Signaling SDK, you MUST set the channel ID. However, even if the callee successfully accepts the call invitation, the Agora RTM SDK does not join the channel of the specified channel ID. > - If your App does not involve the legacy Agora Signaling SDK, we recommend using the `LocalInvitation.content` or the `RemoteInvitation.response` property to set customized contents. #### Sets the output log level of the SDK Supports setting the output log level of the SDK using the `logFilter` parameter. The log level follows the sequence of OFF, ERROR, WARNING, and INFO. Choose a level to see the logs preceding that level. If, for example, you set the log level to WARNING, you see the logs within levels ERROR and WARNING. ### API Changes #### Adds - [logFilter](https://docs.agora.io/en/Real-time-Messaging/API%20Reference/RTM_web/interfaces/rtmparameters.html#logfilter) - [setParameters](https://docs.agora.io/en/Real-time-Messaging/API%20Reference/RTM_web/classes/rtmclient.html#setparameters) ## v0.9.3 v0.9.3 is released on July 24th, 2019. ### New Features #### Sends an (offline) peer-to-peer message to a specified user (receiver) This version allows you to send a message to a specified user when he/she is offline. If you set a message as an offline message and the specified user is offline when you send it, the RTM server caches it. Please note that for now we only cache 200 offline messages for up to seven days for each receiver. When the number of the cached messages reaches this limit, the newest message overrides the oldest one. #### User attribute-related operations This version allows you to set or update a user's attributes. You can: - Substitutes the local user's attributes with new ones. - Adds or updates the local user's attribute(s). - Deletes the local user's attributes using attribute keys. - Clears all attributes of the local user. - Gets all attributes of a specified user. - Gets the attributes of a specified user using attribute keys. > The attributes you set will be cleard when you log out of the RTM system. #### Queries the Online Status of the Specified Users This release introduces a new concept: online and offline. - Online: The user has logged in the Agora RTM system. - Offline: The user has logged out of the Agora RTM system. This release adds the function of querying the online status of the specified users. After logging in the Agora RTM system, you can get the online status of a maximum of 256 specified users. #### Renews the Token This release allows you to renew a token. ### API Changes #### Adds - [sendMessageToPeer](https://docs.agora.io/en/Real-time-Messaging/API%20Reference/RTM_web/classes/rtmclient.html#sendmessagetopeer) - [setLocalUserAttributes](https://docs.agora.io/en/Real-time-Messaging/API%20Reference/RTM_web/classes/rtmclient.html#setlocaluserattributes) - [addOrUpdateLocalUserAttributes](https://docs.agora.io/en/Real-time-Messaging/API%20Reference/RTM_web/classes/rtmclient.html#addorupdatelocaluserattributes) - [deleteLocalUserAttributesByKeys](https://docs.agora.io/en/Real-time-Messaging/API%20Reference/RTM_web/classes/rtmclient.html#deletelocaluserattributesbykeys) - [clearLocalUserAttributes](https://docs.agora.io/en/Real-time-Messaging/API%20Reference/RTM_web/classes/rtmclient.html#clearlocaluserattributes) - [getUserAttributes](https://docs.agora.io/en/Real-time-Messaging/API%20Reference/RTM_web/classes/rtmclient.html#getuserattributes) - [getUserAttributesByKeys](https://docs.agora.io/en/Real-time-Messaging/API%20Reference/RTM_web/classes/rtmclient.html#getuserattributesbykeys) - [queryPeersOnlineStatus](https://docs.agora.io/en/Real-time-Messaging/API%20Reference/RTM_web/classes/rtmclient.html#querypeersonlinestatus) - [renewToken](https://docs.agora.io/en/Real-time-Messaging/API%20Reference/RTM_web/classes/rtmclient.html#renewtoken) ## v0.9.1 v0.9.1 is released on May 20th, 2019. ### New Features This release adds the call invitation feature, allowing you to create, send, cancel, accept, and decline a call invitation in a one-to-one or one-to-many voice/video call. ### API Changes #### Adds - [createLocalInvitation](https://docs.agora.io/en/Real-time-Messaging/API%20Reference/RTM_web/classes/rtmclient.html#createlocalinvitation): Creates a call invitation. - [LocalInvitation.send](https://docs.agora.io/en/Real-time-Messaging/API%20Reference/RTM_web/classes/localinvitation.html#send): Allows the caller to send a call invitation to a specified user (callee). - [LocalInvitation.cancel](https://docs.agora.io/en/Real-time-Messaging/API%20Reference/RTM_web/classes/localinvitation.html#send)Allows the caller to cancel a sent call invitation. - [LocalInvitationState](https://docs.agora.io/en/Real-time-Messaging/API%20Reference/RTM_web/enums/localinvitationstate.html): **RETURNED TO THE CALLER** Call invitation status codes. - [LocalInvitationFailureReason](https://docs.agora.io/en/Real-time-Messaging/API%20Reference/RTM_web/enums/localinvitationfailurereason.html): **RETURNED TO THE CALLER** Reason for failure of the outgoing call invitation. - [RemoteInvitationReceived](https://docs.agora.io/en/Real-time-Messaging/API%20Reference/RTM_web/interfaces/rtmclientevents.html#remoteinvitationreceived): Occurs when the callee receives a call invitation. - [RemoteInvitation.accept](https://docs.agora.io/en/Real-time-Messaging/API%20Reference/RTM_web/classes/remoteinvitation.html#accept): Allows the callee to accept an incoming call invitation. - [RemoteInvitation.refuse](https://docs.agora.io/en/Real-time-Messaging/API%20Reference/RTM_web/classes/remoteinvitation.html#refuse): Allows the callee to declien an incoming call invitation. - [RemoteInvitationState](https://docs.agora.io/en/Real-time-Messaging/API%20Reference/RTM_web/enums/remoteinvitationstate.html): **RETURNED TO THE CALLEE**: Call invitation status codes. - [RemoteInvitationFailureReason](https://docs.agora.io/en/Real-time-Messaging/API%20Reference/RTM_web/enums/remoteinvitationfailurereason.html): **RETURNED TO THE CALLEE**: Reason for the failure of the incoming call invitation. #### Renames - `RtmClient.ConnectionStateChange` to [ConnectionStateChanged](https://docs.agora.io/en/Real-time-Messaging/API%20Reference/RTM_web/interfaces/rtmclientevents.html#connectionstatechanged) . #### Deletes - The `RtmChannel.getId()` method. Uses the [channelId](https://docs.agora.io/en/Real-time-Messaging/API%20Reference/RTM_web/classes/rtmchannel.html#channelid) property instead. ## v0.9.0 v0.9.0 is released on February 14th, 2019. Initial version. Key features: - Sends or receives peer-to-peer messages. - Joins or leaves a channel. - Sends or receives channel messages.
C
UTF-8
282
3.53125
4
[]
no_license
#include "holberton.h" /** *clear_bit - funtions to sets the value to 0 *@n: pointer *@index: given index *Return: 1 or -1 */ int clear_bit(unsigned long int *n, unsigned int index) { if (index > 64) { return (-1); } else { *n = *n & ~(1 << index); return (1); } }
Java
UTF-8
7,616
2.671875
3
[ "Apache-2.0" ]
permissive
package com.alex.simpleutils; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.provider.MediaStore; import android.view.View; /** * 关于图片的一些基本操作 * @author caisenchuan * */ public class SImageUtils { /*-------------------------- * 自定义类型 *-------------------------*/ /*-------------------------- * 常量 *-------------------------*/ private static final String TAG = SImageUtils.class.getSimpleName(); /**图片后缀名*/ private static final String PIC_FILE_EXT = ".jpeg"; public static final int JPEG_QUALITY = 50; /*-------------------------- * 成员变量 *-------------------------*/ /*-------------------------- * public方法 *-------------------------*/ /** * 调用系统应用拍照 * @param path 路径 * @param activity 拍完照片后接收Result的Activity,您需要在此Activity中实现onActivityResult方法 * @param requestCode 启动Activity时附带的requestCode,在onActivityResult需要用此进行判断 * @return 若成功,返回拍摄完照片的存储路径,若失败则返回null * */ public static String takePhoto(String path, Activity activity, int requestCode) { String filename = null; if(activity != null) { Intent i = new Intent("android.media.action.IMAGE_CAPTURE"); filename = SFileUtils.getUniqPath(path, PIC_FILE_EXT); File img = new File(filename); Uri imgUri = Uri.fromFile(img); SLog.d(TAG, "img uri : " + imgUri); i.putExtra(MediaStore.EXTRA_OUTPUT, imgUri); activity.startActivityForResult(i, requestCode); } return filename; } /** * 从相册选择照片 * @param activity 拍完照片后接收Result的Activity,您需要在此Activity中实现onActivityResult方法 * @param requestCode 启动Activity时附带的requestCode,在onActivityResult需要用此进行判断 */ public static void selectPhotoFromAlbum(Activity activity, int requestCode) { if(activity != null) { Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT); getAlbum.setType("image/*"); activity.startActivityForResult(getAlbum, requestCode); } else { SLog.w(TAG, "activity == null!"); } } /** * 将图片保存到SD卡中 * @param type 文件路径类型,决定了要把图片存在哪个目录下 * @param bm 图片bitmap * @return 若成功,返回照片的存储路径,若失败则返回null * */ public static String savePicToSD(String dir, Bitmap bm) { String filename = null; // 基本判断 if (!SFileUtils.isSDMount()) { return filename; } // 保存下来 filename = SFileUtils.getUniqPath(dir, PIC_FILE_EXT); File mPhoto = new File(filename); // 保存图片 try { BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(mPhoto)); bm.compress(Bitmap.CompressFormat.JPEG, JPEG_QUALITY, bos); bos.flush(); bos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); filename = null; } catch (IOException e) { e.printStackTrace(); filename = null; } return filename; } /** * 读取图片文件,进行一些压缩 * @param filePath 图片路径 * @param width 最大宽度 * @param height 最大高度 * @return */ public static Bitmap createNewBitmapAndCompressByFile(String filePath, int width, int height) { int offset = 100; File file = new File(filePath); long fileSize = file.length(); if (200 * 1024 < fileSize && fileSize <= 1024 * 1024) { offset = 90; } else if (1024 * 1024 < fileSize) { offset = 85; } BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; // 为true里只读图片的信息,如果长宽,返回的bitmap为null options.inPreferredConfig = Bitmap.Config.ARGB_8888; options.inDither = false; /** * 计算图片尺寸 * TODO 按比例缩放尺寸 */ BitmapFactory.decodeFile(filePath, options); int bmpheight = options.outHeight; int bmpWidth = options.outWidth; int inSampleSize = bmpheight / height > bmpWidth / width ? bmpheight / height : bmpWidth / width; //if(bmpheight / wh[1] < bmpWidth / wh[0]) // inSampleSize = inSampleSize * 2 / 3; //TODO 如果图片太宽而高度太小,则压缩比例太大。所以乘以2/3 if (inSampleSize > 1) { options.inSampleSize = inSampleSize;// 设置缩放比例 } options.inJustDecodeBounds = false; InputStream is = null; try { is = new FileInputStream(file); } catch (FileNotFoundException e) { return null; } Bitmap bitmap = null; try { bitmap = BitmapFactory.decodeStream(is, null, options); } catch (OutOfMemoryError e) { System.gc(); bitmap = null; } if (offset == 100) { return bitmap;// 缩小质量 } ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, offset, baos); byte[] buffer = baos.toByteArray(); options = null; if (buffer.length >= fileSize) { return bitmap; } return BitmapFactory.decodeByteArray(buffer, 0, buffer.length); } /** * 进行屏幕截图 * @param v 要截图的根View * @return 截图所在路径 */ public static String screenShot(String dir, View v) { String ret = ""; if(v != null) { String fname = SFileUtils.getUniqPath(dir, ".png"); View view = v.getRootView(); view.setDrawingCacheEnabled(true); view.buildDrawingCache(); Bitmap bitmap = view.getDrawingCache(); if(bitmap != null) { SLog.d(TAG, "bitmap got!"); try { FileOutputStream out = new FileOutputStream(fname); bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); ret = fname; } catch(Exception e) { SLog.e(TAG, "Exception", e); } } else { SLog.d(TAG, "bitmap is NULL!"); } } return ret; } /*-------------------------- * private方法 *-------------------------*/ }
Markdown
UTF-8
7,427
2.828125
3
[]
no_license
--- description: "How to Prepare Homemade Classic Gizz_Dodo" title: "How to Prepare Homemade Classic Gizz_Dodo" slug: 395-how-to-prepare-homemade-classic-gizz-dodo date: 2021-01-19T23:22:55.740Z image: https://img-global.cpcdn.com/recipes/f892e9bab7a82fd1/751x532cq70/classic-gizz_dodo-recipe-main-photo.jpg thumbnail: https://img-global.cpcdn.com/recipes/f892e9bab7a82fd1/751x532cq70/classic-gizz_dodo-recipe-main-photo.jpg cover: https://img-global.cpcdn.com/recipes/f892e9bab7a82fd1/751x532cq70/classic-gizz_dodo-recipe-main-photo.jpg author: Scott Patterson ratingvalue: 4.4 reviewcount: 26517 recipeingredient: - "10 fingers of ripe plantain" - " Carrots" - " Green beans" - " Fresh pepper" - " I kg Gizzard" - " Onion" - " Seasoning" - " Salt" - " Groundnut oil" - " Fresh tomatoes" recipeinstructions: - "Peel and dice into cubes sprinkle little salt" - "Wash the gizzard and season and allow to cook until it is tender" - "Put a dry pot on fire,add vegetable oil and fry the plantain" - "Dice the veggies mentioned above and add the Gizzard stock then mixed everything together and allow to boil for a few minutes and enjoy." categories: - Recipe tags: - classic - gizz_dodo katakunci: classic gizz_dodo nutrition: 288 calories recipecuisine: American preptime: "PT24M" cooktime: "PT57M" recipeyield: "3" recipecategory: Dessert --- ![Classic Gizz_Dodo](https://img-global.cpcdn.com/recipes/f892e9bab7a82fd1/751x532cq70/classic-gizz_dodo-recipe-main-photo.jpg) Hello everybody, it's Louise, welcome to my recipe page. Today, I'm gonna show you how to prepare a distinctive dish, classic gizz_dodo. One of my favorites. For mine, I'm gonna make it a little bit unique. This will be really delicious. Classic Gizz_Dodo is one of the most popular of current trending meals on earth. It's enjoyed by millions every day. It is simple, it is fast, it tastes yummy. Classic Gizz_Dodo is something which I've loved my whole life. They're nice and they look wonderful. Classic Gizz_Dodo Hubby always talk about eating it when he goes to work so i decided to make it in my home even tastier than what he eats out. Classic Gizz_Dodo Hubby always talk about eating it when he goes to work so i decided to make it in my home even tastier than what he eats out. See recipes for Gizz-Dodo, Classic Gizz_Dodo too. Classic Gizz_Dodo Hey everyone, I hope you&#39;re having an amazing day today. To get started with this recipe, we must prepare a few ingredients. You can cook classic gizz_dodo using 10 ingredients and 4 steps. Here is how you can achieve that. <!--inarticleads1--> ##### The ingredients needed to make Classic Gizz_Dodo: 1. Take 10 fingers of ripe plantain 1. Get Carrots 1. Make ready Green beans 1. Prepare Fresh pepper 1. Take I kg Gizzard 1. Prepare Onion 1. Take Seasoning 1. Get Salt 1. Take Groundnut oil 1. Get Fresh tomatoes Gizz-dodo has pretty much become a regular in my kitchen and believe me, a hit every time. Honestly, can&#39;t really remember how I came across this super awesome side-dish but I think it is one of my days of surfing the net (food tinz, you know na) and I saw the gizz-dodo recipe and it kinda got my attention. Gizz-dodo has pretty much become a regular in my kitchen and believe me, a hit every time. Honestly, can&#39;t really remember how I came across this super awesome side-dish but I think it is one of my days of surfing the net (food tinz, you know na) and I saw the gizz-dodo recipe and it kinda got my attention. <!--inarticleads2--> ##### Instructions to make Classic Gizz_Dodo: 1. Peel and dice into cubes sprinkle little salt 1. Wash the gizzard and season and allow to cook until it is tender 1. Put a dry pot on fire,add vegetable oil and fry the plantain 1. Dice the veggies mentioned above and add the Gizzard stock then mixed everything together and allow to boil for a few minutes and enjoy. Gizz-dodo has pretty much become a regular in my kitchen and believe me, a hit every time. Honestly, can&#39;t really remember how I came across this super awesome side-dish but I think it is one of my days of surfing the net (food tinz, you know na) and I saw the gizz-dodo recipe and it kinda got my attention. Honestly, can&#39;t really remember how I came across this super awesome side-dish but I think it is one of my days of surfing the net (food tinz, you know na) and I saw the gizz-dodo recipe and it kinda got my attention. Gizz-dodo has pretty much become a regular in my kitchen and believe me, a hit every time. Try Using Food to Improve Your Mood Many of us have been trained to think that comfort foods are bad and are to be avoided. Sometimes, if your comfort food is a high sugar food or another junk food, this is true. At times, comfort foods can be very healthy and good for us to consume. There are several foods that really can improve your moods when you consume them. If you seem to feel a little bit down and need a happiness pick me up, try a few of these. Eggs, believe it or not, are great for helping you combat depression. Just make sure that you don't get rid of the egg yolk. Every time you would like to cheer yourself up, the egg yolk is the most crucial part of the egg. Eggs, the egg yolks especially, are rich in B vitamins. B vitamins can be terrific for elevating your mood. This is because they help your neural transmitters--the parts of your brain that affect your mood--work better. Try consuming some eggs to jolly up! Put together a trail mixout of different seeds and nuts. Your mood can be elevated by consuming peanuts, almonds, cashews, sunflower seeds, pumpkin seeds, etcetera. This is because these nuts are high in magnesium, which helps to increase your production of serotonin. Serotonin is the "feel good" chemical that tells your brain how you feel all the time. The higher your serotonin levels, the better you will feel. Nuts, along with improving your mood, can be a superb protein source. Cold water fish are wonderful for eating if you want to fight depression. Salmon, herring, tuna fish, mackerel, trout, and so on, they're all high in omega-3s and DHA. These are two things that promote the quality and the function of your brain's grey matter. It's the truth: eating tuna fish sandwiches can actually help you fight your depression. Grains can be excellent for overcoming a bad mood. Barley, quinoa, millet, teff, etc are all wonderful for helping you be in a happier state of mind. They can help you feel full for longer too, which can help your mood too. It's not hard to feel low when you are starving! The reason these grains can improve your mood is that they are not difficult for your body to digest. These foods are easier to digest than others which helps promote a rise in your blood glucose which in turn takes your mood to a happier place. Your mood could actually be helped by green tea. You were simply expecting to read that here, weren't you? Green tea is rich in an amino acid referred to as L-theanine. Research has proved that this amino acid stimulates the production of brain waves. This helps sharpen your mental energy while simultaneously making the rest of your body more relaxed. You knew that green tea helps you be a lot healthier. Now you know that green tea can elevate your mood as well! Now you realize that junk food isn't necessarily what you have to eat when you want to help your moods get better. Test out these suggestions instead!
Java
UTF-8
754
2.1875
2
[]
no_license
package org.net.api.jdk; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import org.net.api.MessageEncoderHandler; /** * @Description 定义编码器: * @Author LUOBINGKAI * @Date 2019/7/20 3:07 * @Version 1.0 **/ public class JdkEncoder extends MessageEncoderHandler { private static JdkSerialization jdkSerialization = new JdkSerialization(); @Override protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf byteBuf) throws Exception { // 先计算数据的大小,并发送实际数据 byte[] bytes = jdkSerialization.serialize(o); int dataLength= bytes.length; byteBuf.writeInt(dataLength); byteBuf.writeBytes(bytes); } }
Java
UTF-8
1,816
2.53125
3
[]
no_license
package com.puuga.opennote.model; import android.util.Log; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; /** * Created by siwaweswongcharoen on 10/5/2015 AD. */ public class Message { public String id; public String message; public double lat; public double lng; public User user; public String created_at; public double distance_from_my_location; private Message() { } public static Message createMessage() { return new Message(); } public Message setId(String id) { this.id = id; return this; } public Message setMessage(String message) { this.message = message; return this; } public Message setLat(float lat) { this.lat = lat; return this; } public Message setLng(float lng) { this.lng = lng; return this; } public Message setUser(User user) { this.user = user; return this; } public Message setCreated_at(String created_at) { this.created_at = created_at; return this; } public Date getDateCreatedAt() { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US); Date date = null; try { date = simpleDateFormat.parse(created_at); } catch (ParseException e) { Log.d("ParseException", e.getMessage()); } return date; } public String toString() { return "message:" + message + ", lat:" + lat + ", lng:" + lng + ", distance_from_my_location:"+ distance_from_my_location + ", created_at:" + created_at + ", user:" + user; } }
PHP
UTF-8
687
2.671875
3
[]
no_license
<?php namespace App\Services\Api\V1; use Illuminate\Support\Facades\Hash; use App\Repositories\Contracts\Api\V1\ClientRepositoryInterface; class ClientService{ private $clientRepository; public function __construct(ClientRepositoryInterface $clientRepository){ $this->clientRepository = $clientRepository; } public function createNewClient(array $data){ return $this->clientRepository->createNewClient($data); } public function getClient(int $id){ return $this->clientRepository->getClient($id); } public function getClientByEmail(string $email){ return $this->clientRepository->getClientByEmail($email); } }
C++
UTF-8
1,756
3.53125
4
[]
no_license
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode* back=new ListNode(-1); ListNode* front=back; int forw=0; if((l1==NULL || l1->val==0)&&l1->next==NULL) { return l2; } if((l2==NULL || l2->val==0)&&l2->next==NULL) { return l1; } while(l1!=NULL && l2!=NULL) { back->next= new ListNode((l1->val + l2->val + forw)%10); forw=(l1->val + l2->val + forw)/10; back=back->next; l1=l1->next; l2=l2->next; } while(forw==1) { if(l1==NULL && l2==NULL) { back->next= new ListNode(1); forw=0; } else if(l1!=NULL) { back->next= new ListNode((l1->val + forw)%10); forw=(l1->val + forw)/10; back=back->next; l1=l1->next; } else if(l2!=NULL) { back->next= new ListNode((l2->val + forw)%10); forw=(l2->val + forw)/10; back=back->next; l2=l2->next; } } while(l1!=NULL) { back->next=l1; break; } while(l2!=NULL) { back->next=l2; break; } return front->next; } };
Markdown
UTF-8
14,323
3.40625
3
[ "MIT" ]
permissive
--- title: "PythonでJavaScriptの分割代入をどこまで再現できるかやってみた" date: 2020-01-13T00:00:00+09:00 draft: false tags: ["Python"] --- # はじめに JavaScript には分割代入(Destructuring assignment)と呼ばれる代入の方法があります。下記は[MDN](https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) のサンプルの一部です。 ```javascript let a, b, rest; [a, b] = [10, 20]; console.log(a); // => 10 console.log(b); // => 20 ``` ところで、Python でも似たような構文が使えます。実際、下記の Python コードは上記の JavaScript のコードと同じ意味です。 ```python >>> [a, b] = [10, 20] >>> print(a) 10 >>> print(b) 20 ``` そこで JavaScript の分割代入の知識は、Python ではどこまで活かせるのかが気になったので調査してみます。具体的には、下記の MDN のページのサンプルコードを Python で再現できるかどうか試していきます。以下に書く JavaScript のコードは下記ページからの引用です。 [分割代入 \- JavaScript \| MDN](https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) 以下、見出しは上記の MDN のページに合わせています。 # 配列の分割代入 ## 簡単な例 ```javascript var foo = ['one', 'two', 'three']; var [one, two, three] = foo; console.log(one); // "one" console.log(two); // "two" console.log(three); // "three" ``` これは Python でもほぼそっくりそのまま同じことができます。 ```python foo = ['one', 'two', 'three'] [one, two, three] = foo print(one) print(two) print(three) ``` 見た目もほとんど同じですね。 ## 宣言後の割り当て Python には変数を宣言する構文が存在しないのでパスします。 ## 既定値の設定 ```javascript var a, b; [a=5, b=7] = [1]; console.log(a); // 1 console.log(b); // 7 ``` 存在しない部分の値(上のコードでは `b` )にたいして代入するとき、初期値を決める例ですが、これは Python にはできません。少し考えてみましたが、スマートにやる方法も思いつきません(情報求む)。 ## 変数の入れ替え ```javascript var a = 1; var b = 3; [a, b] = [b, a]; console.log(a); // 3 console.log(b); // 1 ``` これはできます。 ```python a = 1 b = 3 [a, b] = [b, a] print(a) # 3 print(b) # 1 ``` 別に `a, b = b, a` とリストを使わずともできます[^1]。 [^1]: 実際には `a, b` はタプルに評価されているので、リストは使っていないけどタプルは使っていますが、見た目の上では現れないということで。 ## 関数から返された配列の解析 ```javascript function f() { return [1, 2]; } var a, b; [a, b] = f(); console.log(a); // 1 console.log(b); // 2 ``` これもできます。やっぱり見た目もほぼそっくりそのままです。 ```python def f(): return [1, 2] a, b = f() print(a) # 1 print(b) # 2 ``` 例えば scikit-learn の [train_test_split](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html) を使うときとかはよく使うんじゃないでしょうか。 ```python from sklearn.model_selection import train_test_split # X, y があらかじめ定義されているとして X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.25, random_state=42) ``` ## 返り値の無視 ```javascript function f() { return [1, 2, 3]; } var [a, , b] = f(); console.log(a); // 1 console.log(b); // 3 ``` Python の場合は JavaScript のように完全に無視することはできませんが、慣習として不要な変数は `_` で受けるのが一般的だと思います。 ```python def f(): return [1, 2, 3] [a, _, b] = f() print(a) # 1 print(b) # 3 ``` ## 配列の残余部分を変数に代入する ```javascript var [a, ...b] = [1, 2, 3]; console.log(a); // 1 console.log(b); // [2, 3] ``` `*` で展開すれば受け取れます。 ```python [a, *b] = [1, 2, 3] print(a) # 1 print(b) # [2, 3] ``` ## 正規表現のマッチからの値取得 ```javascript function parseProtocol(url) { var parsedURL = /^(\w+)\:\/\/([^\/]+)\/(.*)$/.exec(url); if (!parsedURL) { return false; } console.log(parsedURL); // ["https://developer.mozilla.org/ja/Web/JavaScript", "https", "developer.mozilla.org", "en-US/Web/JavaScript"] var [, protocol, fullhost, fullpath] = parsedURL; return protocol; } console.log(parseProtocol('https://developer.mozilla.org/ja/Web/JavaScript')); // "https" ``` サンプルコードが長いですが、ポイントは `parsedURL` が配列になっていることなので、Python の正規表現モジュール(`re`)を使ってマッチした結果が Python のリストで返ってくるかだけが争点です。で、結論から言うと `exec()` メソッドと(ほぼ同じ)返り値を持つ `re.findall()` メソッドがあるので、この例も Python で再現できます。。 ```python import re regex = r'^(\w+)\:\/\/([^\/]+)\/(.*)$' text = 'https://developer.mozilla.org/ja/Web/JavaScript' # 返り値がリストになっている: [('https', 'developer.mozilla.org', 'ja/Web/JavaScript')] # 分割代入を2度使う [(protocol, fullhost, fullpath)] = re.findall(regex, text) print(protocol) # https ``` # オブジェクトの分割代入 ## 簡単な例 ```javascript var o = {p: 42, q: true}; var {p, q} = o; console.log(p); // 42 console.log(q); // true ``` この簡単な例でさえ直接にはできません。Python のリストは分割代入をサポートしていますが、辞書型はサポートしていないためです。 下記の質問に様々な分割代入(のようなこと)を実現する例がありますが、多くは右辺をリストにしてリストの分割代入に帰着させています。 [python \- Destructuring\-bind dictionary contents \- Stack Overflow](https://stackoverflow.com/questions/2955412/destructuring-bind-dictionary-contents) 上のリンクの中で際立っているのは、 [`operator.itemgetter()`](https://docs.python.org/ja/3/library/operator.html#operator.itemgetter) を利用する方法でしょうか。 ```python from operator import itemgetter o = {'p': 42, 'q': True} p, q = itemgetter('p', 'q')(o) print(p) # 42 print(q) # True ``` [Python の公式ドキュメント](https://docs.python.org/ja/3/library/operator.html#operator.itemgetter)によれば、`itemgetter` は下記の関数と等価です。 ```python def itemgetter(*items): if len(items) == 1: item = items[0] def g(obj): return obj[item] else: def g(obj): return tuple(obj[item] for item in items) return g ``` そんなわけで、以降の例はほとんど(タプルやリストへの変換なしには)実現不可能です ## 宣言のない割り当て こちらも Python には変数宣言の構文が存在しないので省略します。 ## 異なる名前を持つ変数への代入 ```javascript var o = {p: 42, q: true}; var {p: foo, q: bar} = o; console.log(foo); // 42 console.log(bar); // true ``` あえていえば、上記で解説した `operator.itemgetter()` を使えばよいでしょう。 ```python from operator import itemgetter o = {'p': 42, 'q': True} foo, bar = itemgetter('p', 'q')(o) print(foo) # 42 print(bar) # True ``` ## 既定値の設定 ```javascript var {a = 10, b = 5} = {a: 3}; console.log(a); // 3 console.log(b); // 5 ``` 配列のときと同様できません。 ## 異なる名前の変数に代入して既定値を設定する ```javascript var {a: aa = 10, b: bb = 5} = {a: 3}; console.log(aa); // 3 console.log(bb); // 5 ``` こちらもできません、異なる変数名に代入できますが、既定値の設定ができないためです。 ## 関数の引数に対する規定値の設定 MDN のサイトの ES2015 バージョン のみ引用します。 ```javascript function drawES2015Chart({size = 'big', coords = {x: 0, y: 0}, radius = 25} = {}) { console.log(size, coords, radius); // do some chart drawing } drawES2015Chart({ coords: { x: 18, y: 30 }, radius: 30 }); ``` 関数であれば Python でもキーワード引数と辞書の展開(`**` 演算子)が使えるので、規定値の設定をしつつ、辞書型を渡せば似たようなことが実現できます。 ```python def draw_chart(size='big', coords=None, radius=25): print(size, coords, radius) dic = { 'coords': {'x': 18, 'y': 30}, 'radius': 30 } draw_chart(**dic) ``` ## 入れ子になったオブジェクトと配列の分割代入 ```javascript const metadata = { title: 'Scratchpad', translations: [ { locale: 'de', localization_tags: [], last_edit: '2014-04-14T08:43:37', url: '/de/docs/Tools/Scratchpad', title: 'JavaScript-Umgebung' } ], url: '/en-US/docs/Tools/Scratchpad' }; let { title: englishTitle, // rename translations: [ { title: localeTitle // rename }, ], } = metadata; console.log(englishTitle); // "Scratchpad" console.log(localeTitle); // "JavaScript-Umgebung" ``` 入れ子にする前からできないので、入れ子になったところでできません。 ## イテレーターでの分割代入の利用 ```javascript var people = [ { name: 'Mike Smith', family: { mother: 'Jane Smith', father: 'Harry Smith', sister: 'Samantha Smith' }, age: 35 }, { name: 'Tom Jones', family: { mother: 'Norah Jones', father: 'Richard Jones', brother: 'Howard Jones' }, age: 25 } ]; for (var {name: n, family: {father: f}} of people) { console.log('Name: ' + n + ', Father: ' + f); } // "Name: Mike Smith, Father: Harry Smith" // "Name: Tom Jones, Father: Richard Jones" ``` 上のサンプルコード自体は、オブジェクトの分割代入なのでできません。しかしリストであれば、Python でもイテレータと合わせて使うこともできます。簡単な例では次のようなものです: ```python L = [['a'], ['b'], ['c']] for [item] in L: print(item) # a # b # c ``` ささやかな抵抗です。 ## 引数に指定されたオブジェクトの属性への参照 ```javascript function userId({id}) { return id; } function whois({displayName, fullName: {firstName: name}}) { console.log(displayName + ' is ' + name); } var user = { id: 42, displayName: 'jdoe', fullName: { firstName: 'John', lastName: 'Doe' } }; console.log('userId: ' + userId(user)); // "userId: 42" whois(user); // "jdoe is John" ``` キーワード引数名と、辞書のキー名が同じであれば `**` による展開で同じことができます。しかし、不要なキーがあっても無視することが Python の場合はできないので、 `**kwargs` を使わなくても引数に定義しておく必要があります。また、辞書が入れ子になっているので `**` の展開では firstName のみ取り出すことができません。 ```python def user_id(id, **kwargs): return id def whois(display_name, full_name, **kwargs): # 入れ子の辞書のためここでは分割代入できない first_name = full_name['first_name'] print(display_name, 'is', first_name) user = { 'id': 42, 'display_name': 'jdoe', 'full_name': { 'first_name': 'John', 'last_name': 'Doe' } } print('userId:', user_id(**user)) # "userId: 42" whois(**user) # "jdoe is John" ``` ## 計算されたオブジェクトのプロパティの名前と分割代入 ```javascript let key = 'z'; let {[key]: foo} = {z: 'bar'}; console.log(foo); // "bar" ``` Python は辞書のキー用のリテラルが特にないので省略します。 ## オブジェクトの分割代入の残余 ```javascript let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40} a; // 10 b; // 20 rest; // { c: 30, d: 40 } ``` これもできないと思います。強いて言うなら、 `a` や `b` を `pop()` すれば残りが自動的に現れますが、もはや分割代入ではありません。 ## 無効な JavaScript 識別子をプロパティ名として使用する Python の識別子と JavaScript の識別子で無効なものは違うので省略します。 ## 配列とオブジェクトの分割代入を組み合わせる ```javascript const props = [ { id: 1, name: 'Fizz'}, { id: 2, name: 'Buzz'}, { id: 3, name: 'FizzBuzz'} ]; const [,, { name }] = props; console.log(name); // "FizzBuzz" ``` 3番目の 'name' だけ必要なので、 次のようになるでしょう。あくまでリストの分割代入をし、オブジェクトについては普通に取得します。 ```python props = [ { 'id': 1, 'name': 'Fizz'}, { 'id': 2, 'name': 'Buzz'}, { 'id': 3, 'name': 'FizzBuzz'} ] _, _ , prop = props print(prop['name']) ``` # まとめ * JavaScript の配列に対する分割代入と同じことは Python でもそこそこできる * JavaScript のオブジェクトに対する分割代入は Python では基本的にはできない * ただし、関数を使うときは、キーワード引数と `**`演算子による展開を組み合わせれば、一部機能は再現できる # 所感 もともと JavaScript の分割代入について調べていて、自分の知っている言語と比較しようとこの記事を書いてみたのですが、思っていたよりも JavaScript の分割代入が強力でした。特にオブジェクトのキーと変数名が一致していたら、 value をそのまま代入できるのがとても強力ですね。 とはいえ、リストについては Python もほぼ同じコードで分割代入の実現ができたので、決して非力ではないといったところでしょうか。 Ruby 2.7.0 からは(実験的なものとはいえ)パターンマッチの構文が入っているので、おそらくこの内容については Ruby のほうが簡潔に書けるんじゃないかなとか思います(未調査、無責任)。
Python
UTF-8
1,980
2.5625
3
[]
no_license
from config_data import ConfigData from opera_methods import OperaMethods from log.log_record import LogRecord class RunMain: def __init__(self): self.con = ConfigData() self.opera = OperaMethods() self.log = LogRecord() self.logger = self.log.get_log() def run_main(self): row_num = self.con.get_lines() for i in range(1,row_num): is_run = self.con.get_is_run(i) self.logger.info("44445") if is_run == "yes": opera_method = self.con.get_opera_method(i) opera_element_key = self.con.get_opera_element_key(i) opera_data = self.con.get_opera_data(i) expect_element_key = self.con.get_expect_element(i) expect_element_method = self.con.get_expect_method(i) expect_element_data = self.con.get_expect_result(i) method = getattr(self.opera, opera_method) if opera_element_key == None and opera_data == None: method() elif opera_element_key != None and opera_data == None: method(opera_element_key) elif opera_element_key == None and opera_data != None: method(opera_data) else: method(opera_element_key,opera_data) if expect_element_method: expect_method = getattr(self.opera,expect_element_method) if expect_element_key: result = expect_method(expect_element_key,expect_element_data) else: result = expect_method(expect_element_data) if result: self.con.write_real_result(i,"pass") else: self.con.write_real_result(i, "fail") self.log.close_handle() if __name__ == "__main__": r = RunMain() r.run_main()
Java
UTF-8
1,979
2.640625
3
[]
no_license
package com.example.android.bakingapp.adapters; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.android.bakingapp.Ingredient; import com.example.android.bakingapp.R; import java.util.ArrayList; public class IngredientsAdapter extends RecyclerView.Adapter<IngredientsAdapter.IngredientsAdapterViewHolder> { private Context mContext; private ArrayList<Ingredient> mIngredients; public void IngredientsAdapter(Context context) { mContext = context; } public void setIngredients(ArrayList<Ingredient> ingredients) { mIngredients = ingredients; notifyDataSetChanged(); } @NonNull @Override public IngredientsAdapterViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext()); View view = inflater.inflate(R.layout.ingredients_list_item, viewGroup, false); return new IngredientsAdapterViewHolder(view); } @Override public void onBindViewHolder(@NonNull IngredientsAdapterViewHolder ingredientsAdapterViewHolder, int i) { ingredientsAdapterViewHolder.mIngredientsTextView.setText((i + 1) + ".) " + mIngredients.get(i).getIngredientName()); } @Override public int getItemCount() { if (mIngredients == null) { return 0; } else { return mIngredients.size(); } } public class IngredientsAdapterViewHolder extends RecyclerView.ViewHolder { public final TextView mIngredientsTextView; public IngredientsAdapterViewHolder(@NonNull View itemView) { super(itemView); mIngredientsTextView = (TextView) itemView.findViewById(R.id.ingredient_text_view); } } }
Rust
UTF-8
1,044
3.328125
3
[ "Apache-2.0", "MIT" ]
permissive
use crate::runtime::{RawStr, Rtti, StaticType, VariantRtti}; use std::fmt; use std::sync::Arc; /// Type information about a value, that can be printed for human consumption /// through its [Display][fmt::Display] implementation. #[derive(Debug, Clone)] pub enum TypeInfo { /// The static type of a value. StaticType(&'static StaticType), /// Reference to an external type. Any(RawStr), /// A named type. Typed(Arc<Rtti>), /// A variant. Variant(Arc<VariantRtti>), } impl fmt::Display for TypeInfo { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::StaticType(ty) => { write!(fmt, "{}", ty.name)?; } Self::Any(type_name) => { write!(fmt, "{}", *type_name)?; } Self::Typed(rtti) => { write!(fmt, "{}", rtti.item)?; } Self::Variant(rtti) => { write!(fmt, "{}", rtti.item)?; } } Ok(()) } }
C
UTF-8
2,928
2.640625
3
[]
no_license
#include "rtpersrc/pd_common.hh" #include "rtpersrc/pu_common.hh" /*********************************************************************** * * Routine name: pd_ConsWholeNumber64 * * Description: This routine encompasses the rules to decode a * constrained whole number as specified in section * 10.5 of the X.691 standard. * * Inputs: * * Name Type Description * ---- ---- ----------- * pdbuf struct Pointer to PER decode buffer structure * value uint* Pointer to value to receive decoded result * lower uint Lower constraint value * upper uint Upper constraint value * * Outputs: * * Name Type Description * ---- ---- ----------- * status int Completion status of encode operation * **********************************************************************/ #ifndef _NO_INT64_SUPPORT EXTPERMETHOD int pd_ConsWholeNumber64 (OSCTXT* pctxt, OSUINT64* padjusted_value, OSUINT64 range_value) { OSUINT32 nocts, range_bitcnt, temp = 0; int stat = 0; /* If unaligned, decode non-negative binary integer in the minimum */ /* number of bits necessary to represent the range (10.5.6) */ if (!pctxt->buffer.aligned) { range_bitcnt = pu_bitcnt64 (range_value - 1); } /* If aligned, encoding depended on range value (10.5.7) */ else { /* aligned */ /* If range is <= 255, bit-field case (10.5.7a) */ if (range_value <= 255) { range_bitcnt = pu_bitcnt64 (range_value - 1); } /* If range is exactly 256, one-octet case (10.5.7b) */ else if (range_value == 256) { stat = PD_BYTE_ALIGN (pctxt); if (stat != 0) return LOG_RTERR (pctxt, stat); range_bitcnt = 8; } /* If range > 256 and <= 64k (65535), two-octet case (10.5.7c) */ else if (range_value <= OSINTCONST(65536)) { stat = PD_BYTE_ALIGN (pctxt); if (stat != 0) return LOG_RTERR (pctxt, stat); range_bitcnt = 16; } /* If range > 64k, indefinite-length case (10.5.7d) */ else { OSUINT32 nbits = (range_value > OSUINT32_MAX) ? 3 : 2; stat = pd_bits (pctxt, &nocts, nbits); if (stat != 0) return LOG_RTERR (pctxt, stat); PU_INSLENFLD (pctxt); stat = PD_BYTE_ALIGN (pctxt); if (stat != 0) return LOG_RTERR (pctxt, stat); range_bitcnt = (nocts + 1) * 8; } } if (range_bitcnt > sizeof (OSUINT32) * 8) { stat = pd_bits (pctxt, &temp, range_bitcnt - sizeof (OSUINT32) * 8); range_bitcnt = sizeof (OSUINT32) * 8; } if (stat == 0) { *padjusted_value = temp; *padjusted_value <<= sizeof (OSUINT32) * 8; stat = pd_bits (pctxt, &temp, range_bitcnt); *padjusted_value |= temp; } else return LOG_RTERR (pctxt, stat); return 0; } #endif
Python
UTF-8
914
3.296875
3
[]
no_license
import random, os, sys from time import sleep from typewriter import Typewriter from attributes import Attributes #typewriter delays the text and print it out one sign at the time. races = ["Dwarf", "Elf","Human", "Orc"] Typewriter("Welcome to xxx!!!") print() Typewriter("Important commands: !attributes, !racelist, !classlist, !stats") print() Typewriter("What do you wish to be called? ") name = input() Typewriter("What race do you wanna be? Type \"!raceinfo\"" "to find out details.") print() Typewriter("Do wish to be a dwarf, elf, human or an orc? ") print() race = input() r = len(races) for r in races: if races == "!raceinfo": print(r, end='') sys.stdout.flush() sleep(0.45) print() """else races == "!dwarf": for attributes in Attributes: print (dwarf, end='') sys.stdout.flush() sleep(0.45) print()"""
Shell
UTF-8
258
2.671875
3
[]
no_license
#!/bin/bash file="PID.txt" echo "Lista cu PID-ul proceselor pornite cu comenzile localizate în /sbin/ : ">$file ps aux | grep -w "/sbin/*" | awk '{ print $2;}'>>$file exit 0; grep -w, --word-regexp selecteaza liniile ce contin cuvintele alese
Java
UTF-8
1,197
2.671875
3
[]
no_license
package GenerateTraj; /** * Created by Tom.fu on 28/11/2014. */ public class DescInfo { public int nBins; // number of bins for vector quantization public int fullOrientation; // 0: 180 degree; 1: 360 degree public int norm; // 1: L1 normalization; 2: L2 normalization public float threshold; //threshold for normalization public int flagThre; // whether thresholding or not public int nxCells; // number of cells in x direction public int nyCells; public int ntCells; public int dim; // dimension of the descriptor public int blockHeight; // size of the block for computing the descriptor public int blockWidth; public DescInfo(int nBins, int flag, int orientation, int size, int nxy_cell, int nt_cell, float min_flow){ this.nBins = nBins; this.fullOrientation = orientation; this.norm = 2; this.threshold = min_flow; this.flagThre = flag; this.nxCells = nxy_cell; this.nyCells = nxy_cell; this.ntCells = nt_cell; this.dim = this.nBins * this.nxCells * this.nyCells; this.blockHeight = size; this.blockWidth = size; } }
Markdown
UTF-8
5,792
2.84375
3
[ "MIT" ]
permissive
# Mastering Machine Learning on AWS <a href="https://www.packtpub.com/in/big-data-and-business-intelligence/mastering-machine-learning-aws"><img src="https://www.packtpub.com/media/catalog/product/cache/ecd051e9670bd57df35c8f0b122d8aea/9/7/9781789349795_cover_0.png" alt="Mastering Machine Learning on AWS" height="256px" align="right"></a> This is the code repository for [Mastering Machine Learning on AWS](https://www.packtpub.com/in/big-data-and-business-intelligence/mastering-machine-learning-aws), published by Packt. **Advanced machine learning in Python using SageMaker, Apache Spark, and TensorFlow** ## What is this book about? AWS is constantly driving new innovations that empower data scientists to explore a variety of machine learning (ML) cloud services. This book is your comprehensive reference for learning and implementing advanced ML algorithms in AWS cloud. As you go through the chapters, you’ll gain insights into how these algorithms can be trained, tuned and deployed in AWS using Apache Spark on Elastic Map Reduce (EMR), SageMaker, and TensorFlow. While you focus on algorithms such as XGBoost, linear models, factorization machines, and deep nets, the book will also provide you with an overview of AWS as well as detailed practical applications that will help you solve real-world problems. Every practical application includes a series of companion notebooks with all the necessary code to run on AWS. In the next few chapters, you will learn to use SageMaker and EMR Notebooks to perform a range of tasks, right from smart analytics, and predictive modeling, through to sentiment analysis. By the end of this book, you will be equipped with the skills you need to effectively handle machine learning projects and implement and evaluate algorithms on AWS. This book covers the following exciting features: * Manage AI workflows by using AWS cloud to deploy services that feed smart data products * Use SageMaker services to create recommendation models * Scale model training and deployment using Apache Spark on EMR * Understand how to cluster big data through EMR and seamlessly integrate it with SageMaker * Build deep learning models on AWS using TensorFlow and deploy them as services * Enhance your apps by combining Apache Spark and Amazon SageMaker If you feel this book is for you, get your [copy](https://www.amazon.com/Mastering-Machine-Learning-AWS-TensorFlow/dp/1789349796) today! <a href="https://www.packtpub.com/?utm_source=github&utm_medium=banner&utm_campaign=GitHubBanner"><img src="https://raw.githubusercontent.com/PacktPublishing/GitHub/master/GitHub.png" alt="https://www.packtpub.com/" border="5" /></a> ## Instructions and Navigations All of the code is organized into folders. For example, Chapter02. The code will look like the following: ``` vectorizer = CountVectorizer(input=dem_text + gop_text, stop_words=stop_words, max_features=1200) ``` **Following is what you need for this book:** This book is for data scientists, machine learning developers, deep learning enthusiasts and AWS users who want to build advanced models and smart applications on the cloud using AWS and its integration services. Some understanding of machine learning concepts, Python programming and AWS will be beneficial. With the following software and hardware list you can run all code files present in the book (Chapter 1-11). ### Software and Hardware List | Chapter | Software required | OS required | | -------- | ------------------------------------ | ----------------------------------- | | All | Python 3.6 or higher | Windows, Mac OS X, and Linux (Any) | | All | Jupyter notebook | Windows, Mac OS X, and Linux (Any) | We also provide a PDF file that has color images of the screenshots/diagrams used in this book. [Click here to download it](https://www.packtpub.com/sites/default/files/downloads/9781789349795_ColorImages.pdf). ### Related products * Effective Amazon Machine Learning [[Packt]](https://www.packtpub.com/in/big-data-and-business-intelligence/effective-amazon-machine-learning) [[Amazon]](https://www.amazon.com/Effective-Amazon-Machine-Learning-Perrier/dp/1785883232) * Machine Learning with AWS [[Packt]](https://www.packtpub.com/in/big-data-and-business-intelligence/beginning-machine-learning-aws) [[Amazon]](https://www.amazon.com/Machine-Learning-AWS-artificial-intelligence/dp/1789806194) ## Get to Know the Authors **Dr. Saket S.R. Mengle** holds a PhD in text mining from Illinois Institute of Technology, Chicago. He has worked in a variety of fields, including text classification, information retrieval, large-scale machine learning, and linear optimization. He currently works as senior principal data scientist at dataxu, where he is responsible for developing and maintaining the algorithms that drive dataxu's real-time advertising platform. **Maximo Gurmendez** holds a master's degree in computer science/AI from Northeastern University, where he attended as a Fulbright Scholar. Since 2009, he has been working with dataxu as data science engineering lead. He's also the founder of Montevideo Labs (a data science and engineering consultancy). Additionally, Maximo is a computer science professor at the University of Montevideo and is director of its data science for business program. ### Suggestions and Feedback [Click here](https://docs.google.com/forms/d/e/1FAIpQLSdy7dATC6QmEL81FIUuymZ0Wy9vH1jHkvpY57OiMeKGqib_Ow/viewform) if you have any feedback or suggestions. ### Download a free PDF <i>If you have already purchased a print or Kindle version of this book, you can get a DRM-free PDF version at no cost.<br>Simply click on the link to claim your free PDF.</i> <p align="center"> <a href="https://packt.link/free-ebook/9781789349795">https://packt.link/free-ebook/9781789349795 </a> </p>
Java
UTF-8
3,282
3.921875
4
[ "MIT" ]
permissive
package com.zs.letcode.array_string; /** * 实现 strStr() * 实现strStr()函数。 * <p> * 给你两个字符串haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。 * <p> * <p> * 说明: * <p> * 当needle是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。 * <p> * 对于本题而言,当needle是空字符串时我们应当返回 0 。这与 C 语言的strstr()以及 Java 的indexOf()定义相符。 * <p> * <p> * 示例 1: * <p> * 输入:haystack = "hello", needle = "ll" * 输出:2 * 示例 2: * <p> * 输入:haystack = "aaaaa", needle = "bba" * 输出:-1 * 示例 3: * <p> * 输入:haystack = "", needle = "" * 输出:0 * <p> * <p> * 提示: * <p> * 0 <= haystack.length, needle.length <= 5 * 104 * haystack 和 needle 仅由小写英文字符组成 * <p> * 作者:力扣 (LeetCode) * 链接:https://leetcode-cn.com/leetbook/read/array-and-string/cm5e2/ * 来源:力扣(LeetCode) * 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 * * @author madison * @description * @date 2021/4/28 21:47 */ public class Chapter10 { public static void main(String[] args) { Solution solution = new Solution(); System.out.println(solution.strStr1("hello", "ll")); System.out.println("hello".indexOf("ll")); } private static class Solution { /** * 方法一:暴力匹配 * * @param haystack * @param needle * @return */ public int strStr(String haystack, String needle) { int n = haystack.length(), m = needle.length(); for (int i = 0; i + m <= n; i++) { boolean flag = true; for (int j = 0; j < m; j++) { if (haystack.charAt(i + j) != needle.charAt(j)) { flag = false; break; } } if (flag) { return i; } } return -1; } /** * 方法二:Knuth-Morris-Pratt 算法 */ public int strStr1(String haystack, String needle) { int n = haystack.length(), m = needle.length(); if (m == 0) { return 0; } int[] pi = new int[m]; for (int i = 0, j = 0; i < m; i++) { while (j > 0 && needle.charAt(i) != needle.charAt(j)) { j = pi[j - 1]; } if (needle.charAt(i) == needle.charAt(j)) { j++; } pi[i] = j; } for (int i = 0, j = 0; i < n; i++) { while (j > 0 && haystack.charAt(i) != needle.charAt(j)) { j = pi[j - 1]; } if (haystack.charAt(i) == needle.charAt(j)) { j++; } if (j == m) { return i - m + 1; } } return -1; } } }
Java
UTF-8
400
1.898438
2
[]
no_license
package com.linangran.openstone.context; import com.linangran.openstone.card.ICard; import com.linangran.openstone.card.IHeroCard; import com.linangran.openstone.card.IMinionCard; import java.util.List; /** * Created by Admin on 1/21/14. */ public class IGameConfig { public List<ICard> cardList; public List<IHeroCard> heroList; public String groovyClasspath; public String resourcePath; }
Python
UTF-8
7,039
2.8125
3
[]
no_license
## PURPOSE: get unique motif for indistinguishable miRNA using IUPAC code with shifting distance starting from center ## INPUT: miRBase data miRBase21-master.tsv ## OUTPUT: table containing motifs unique_motifs.tsv import numpy as np import pandas as pd import difflib mirna_file = '/Users/chens22/Documents/miRBase21/miRBase21-master.tsv' mirna_data = pd.read_table(mirna_file, header='infer', sep='\t') def getMatureSeqDist(motif, sequences): dupli_seq = 0 dist = 0 for s in sequences: if motif in s: dupli_seq += 1 else: for d in difflib.ndiff(motif, s): if d[0]=='-' or d[0]=='+': dist += 1 if len(sequences)-dupli_seq < 1: return 0 return (dist/(len(sequences)-dupli_seq))-dupli_seq def inMatureSeq(motif, sequences): for s in sequences: if motif in s: return True return False def translateIUPAC(seq): codes = {'N':['A', 'G', 'C', 'T'], 'V':['A', 'G', 'C'], 'H':['A', 'T', 'C'], 'D':['A', 'G', 'T'], 'B':['T', 'G', 'C'], 'M':['A', 'C'], 'K':['G', 'T'], 'W':['A', 'T'], 'S':['G', 'C'], 'Y':['T', 'C'], 'R':['A', 'G'], } def inIUPACMatureSeq(motif, sequences): motif_len = len(motif) for seq in sequences: for i in range(0, len(seq)-motif_len+1): temp_seq = seq[i:i+motif_len] for m in range(0, motif_len): if motif[m] in 'N': temp_seq = temp_seq[:m] + 'N' + temp_seq[m+1:] if temp_seq in motif or motif in temp_seq: return True return False def getMotif(seq, mid, length): start = mid - int(length/2) end = mid + int(round(length/2)) + 1 motif = seq[start:end] return motif def getAltNumSeq(n): result = [] for i in range(0, round(n/2)): result.append(i) result.append(n-i) return result def getDistanceFromCenter(motif, seq): start_margin = seq.find(motif) end_margin = len(seq) - (start_margin + len(motif)) return end_margin - start_margin def getIUPAC(base): codes = {'N':['A', 'G', 'C', 'T'], 'V':['A', 'G', 'C'], 'H':['A', 'T', 'C'], 'D':['A', 'G', 'T'], 'B':['T', 'G', 'C'], 'M':['A', 'C'], 'K':['G', 'T'], 'W':['A', 'T'], 'S':['G', 'C'], 'Y':['T', 'C'], 'R':['A', 'G'], } result = [] for key in codes: values = codes[key] if base in values: result.append(key) return result def chop_motif(motif): n_pos = str.find(motif, 'N') if n_pos==-1: return([motif]) n_num = 0 i = n_pos while i<len(motif) and motif[i]=='N': i+=1 n_num+=1 return([motif[:n_pos], n_num] + chop_motif(motif[n_pos+n_num:])) print(chop_motif('NNNTAGAGGGAAGCGCTTTNNN')) ''' dupli_mirna = list(set(mirna_data.loc[mirna_data['DUPLIMOTIF']==True]['MIRNA'])) final_motifs = {} for d in dupli_mirna: print(d) curr_seq = str(list(set(mirna_data.loc[mirna_data['MIRNA']==d]['SEQUENCE']))[0]) print(curr_seq) sequences = list(set(mirna_data.loc[mirna_data['MIRNA']!=d]['SEQUENCE'])) mid = int(len(curr_seq)/2) bound = 3 max_dist = 0 motif = getMotif(curr_seq, mid, 13) most_unique_motif = motif for i in range(-bound, bound): dist = getMatureSeqDist(motif, sequences) if dist > max_dist: max_dist = dist most_unique_motif = motif shift = i motif = most_unique_motif print(motif) start_motif = curr_seq.find(motif) end_motif = start_motif + len(motif) while inMatureSeq(motif, sequences): if start_motif > 0: start_motif-=1 motif = curr_seq[start_motif:end_motif] if end_motif < len(curr_seq): if inMatureSeq(motif, sequences): end_motif+=1 else: break motif = curr_seq[start_motif:end_motif] print(motif) start_motif = curr_seq.find(motif) end_motif = start_motif + len(motif) if len(motif) > 13: for i in range(0, round(len(motif)/2)): temp_start_motif = start_motif + 1 temp_motif = curr_seq[temp_start_motif:end_motif] if not inMatureSeq(temp_motif, sequences) and len(temp_motif)>=13: start_motif = temp_start_motif temp_end_motif = end_motif - 1 temp_motif = curr_seq[start_motif:temp_end_motif] if not inMatureSeq(temp_motif, sequences) and len(temp_motif)>=13: end_motif = temp_end_motif motif = curr_seq[start_motif:end_motif] print(motif) dist_cent = getDistanceFromCenter(motif, curr_seq) print('DISTANCE FROM CENTER: ' + str(dist_cent)) jump = 1 if dist_cent < 0: jump = -1 for i in range(0, dist_cent, jump): temp_motif = curr_seq[start_motif + i:end_motif+i] if not inMatureSeq(temp_motif, sequences): motif = temp_motif if dist_cent < 0: start_motif += dist_cent else: end_motif += dist_cent motif = curr_seq[start_motif:end_motif] print(motif) dist_cent = getDistanceFromCenter(motif, curr_seq) print('DISTANCE FROM CENTER: ' + str(dist_cent)) if len(motif) > 13: for i in range(1, int((len(motif)-13)/2)): temp_motif = 'N'*i + motif[i:] if inIUPACMatureSeq(temp_motif, sequences): motif = temp_motif temp_motif = motif[:len(motif)-i] + 'N'*i if inIUPACMatureSeq(temp_motif, sequences): motif = temp_motif start = 0 end = len(motif) for i in range(0, round(len(motif)/2)): temp_motif = motif[i:end] if not inIUPACMatureSeq(temp_motif, sequences) and len(temp_motif)>=13: start = i temp_motif = motif[start:len(motif)-i] if not inIUPACMatureSeq(temp_motif, sequences) and len(temp_motif)>=13: end = len(motif)-i motif = motif[start:end] print(motif) final_motifs[d] = [motif, curr_seq, dist_cent] with open('/Users/chens22/Documents/mirBase21/unique-duplimotifs.tsv', 'w') as f: headers = ['MIRNA', 'MOTIF', 'SEQUENCE', 'DISTANCE.FROM.CENTER'] f.write('\t'.join(headers) + '\n') for m in final_motifs.keys(): row = [m] for i in range(0, len(headers)-1): curr_element = final_motifs[m][i] row.append(str(curr_element)) f.write('\t'.join(row) + '\n') '''
Java
UTF-8
1,657
2.328125
2
[]
no_license
package harbour.SpringApp; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import lombok.RequiredArgsConstructor; import net.rgielen.fxweaver.core.FxWeaver; import net.rgielen.fxweaver.core.FxmlView; import org.springframework.stereotype.Component; @Component @FxmlView("employee-scene.fxml") @RequiredArgsConstructor public class EmployeeController { private final FxWeaver fxWeaver; @FXML private AnchorPane pane; public void addEmployee(ActionEvent actionEvent) { fxWeaver.load(EmployeeAddController.class).getController().show(); hide(actionEvent); } public void findEmployee(ActionEvent actionEvent) { fxWeaver.load(EmployeeFindController.class).getController().show(); hide(actionEvent); } public void removeEmployee(ActionEvent actionEvent) { fxWeaver.load(EmployeeDeleteController.class).getController().show(); hide(actionEvent); } public void findAllEmployee(ActionEvent actionEvent) { fxWeaver.load(EmployeeTableController.class).getController().show(); hide(actionEvent); } public void show(){ Stage stage = new Stage(); stage.setScene(new Scene(pane)); stage.show(); } public void backToPreviousWindow(ActionEvent actionEvent) { fxWeaver.load(MainController.class).getController().show(); hide(actionEvent); } private void hide(ActionEvent actionEvent) { ((Node) actionEvent.getSource()).getScene().getWindow().hide(); } }
C++
UTF-8
2,707
2.5625
3
[]
no_license
#include<iostream> using namespace std; int height,width,testcase; int dustmap[50][50]; int dy[4]={-1,0,1,0}; int dx[4]={0,-1,0,1}; int countera; int clocka; void movedust(){ int tmpdustmap[50][50]={0,}; for(int i=0;i<height;i++){ for(int j=0;j<width;j++){ if(dustmap[i][j]<=0){ continue; } int cnt=0; for(int d=0;d<4;d++){ int ny=i+dy[d]; int nx=j+dx[d]; if(ny>=0&&ny<height&&nx>=0&&nx<width){ if(dustmap[ny][nx]!=-1){ tmpdustmap[ny][nx]=tmpdustmap[ny][nx]+dustmap[i][j]/5; cnt++; } } } if(cnt>0){ dustmap[i][j]=dustmap[i][j]-(dustmap[i][j]/5)*cnt; } } } for(int i=0;i<height;i++){ for(int j=0;j<width;j++){ if(dustmap[i][j]!=-1){ dustmap[i][j]=dustmap[i][j]+tmpdustmap[i][j]; } } } } void circulate(){ int tmpdustmap[50][50]={0,}; for(int i=1;i<width-1;i++){ tmpdustmap[countera][i+1]=dustmap[countera][i]; } for(int i=countera;i>=1;i--){ tmpdustmap[i-1][width-1]=dustmap[i][width-1]; } for(int i=width-1;i>=1;i--){ tmpdustmap[0][i-1]=dustmap[0][i]; } for(int i=0;i<countera-1;i++){ tmpdustmap[i+1][0]=dustmap[i][0]; } for(int i=1;i<width-1;i++){ tmpdustmap[clocka][i+1]=dustmap[clocka][i]; } for(int i=clocka;i<height-1;i++){ tmpdustmap[i+1][width-1]=dustmap[i][width-1]; } for(int i=width-1;i>=1;i--){ tmpdustmap[height-1][i-1]=dustmap[height-1][i]; } for(int i=height-1;i>clocka+1;i--){ tmpdustmap[i-1][0]=dustmap[i][0]; } for(int i=0;i<height;i++){ for(int j=0;j<width;j++){ if(i==0||i==countera||i==clocka||i==height-1||j==0||j==width-1){ dustmap[i][j]=tmpdustmap[i][j]; } } } } int count(){ int result=0; for(int i=0;i<height;i++){ for(int j=0;j<width;j++){ if(dustmap[i][j]>0){ result=result+dustmap[i][j]; } } } return result; } int main(void){ cin>>height>>width>>testcase; bool found=false; for(int i=0;i<height;i++){ for(int j=0;j<width;j++){ cin>>dustmap[i][j]; if(!found&&dustmap[i][j]==-1){ countera=i; clocka=i+1; found=true; } } } for(int t=0;t<testcase;t++){ movedust(); circulate(); } cout<<count(); return 0; }
C++
UTF-8
408
2.65625
3
[]
no_license
#include <iostream> #include <cstring> using namespace std; char c[35],s[100100]; int n,m,i,nr; bool cautare(int p) { for(int j=p,i=0;i<m;j++,i++) if(s[j]!=c[i]) return 0; return 1; } int main() { cin.getline(s,100100); cin.getline(c,35); n=strlen(s); m=strlen(c); n-=m; for(i=0;i<=n;i++) if(cautare(i)) { nr++; i+=m-1; } cout<<nr; }
Markdown
UTF-8
884
2.6875
3
[]
no_license
--- layout: post title: 改变系统启动级别 tags: [linux, inittab , gui , tty, termianl] author: Luhux comment: true --- 编辑/etc/inittab文件 ``` # Default runlevel. (Do not set to 0 or 6) id:3:initdefault: ``` * id:num:initdefault:中的num表示默认运行级别 修改开机默认模式请修改num为以下数字: | num | 描述 | |-----|------------------------| | 1 | 单用户模式 | | 2 | 未设定模式,与3模式相同 | | 3 | 多用户名令行模式, 默认不开机自启图形请选择 | | 4 | 登录管理器模式,默认开机自启图形请选择 | | 5 | 空模式,与3模式相同| 例如: 开机自动进入TTY: ``` # Default runlevel. (Do not set to 0 or 6) id:3:initdefault: ``` 开机自动进入登录管理器: ``` # Default runlevel. (Do not set to 0 or 6) id:4:initdefault: ``` 修改保存