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
Python
UTF-8
763
2.859375
3
[]
no_license
#!/usr/bin/env python # -*- coding: UTF-8 -*- #------------------------------------------------------------------------------- # Name: модуль1 # Purpose: # # Author: Prapor # # Created: 19.10.2017 # Copyright: (c) Prapor 2017 # Licence: <your licence> #------------------------------------------------------------------------------- import unittest from Mymath import * class TestFactorial(unittest.TestCase): def test_ziro(self): self.assertEqual(factorial(0), 1) def test_noneziro(self): self.assertAlmostEqual(factorial(5), 120) self.assertAlmostEqual(factorial(1), 1) class TestBinom(unittest.TestCase): def test_all(self): self.assertEqual(binom(4, 2), 6) unittest.main()
PHP
UTF-8
556
2.640625
3
[]
no_license
<?php declare(strict_types=1); use Prooph\EventSourcing\AggregateChanged; use Ramsey\Uuid\Uuid; class BalanceCreated extends AggregateChanged { public static function forUser(UUid $balanceUuid, Uuid $userId, int $amount = 0) :self { return self::occur($balanceUuid->toString(), ['user' => $userId->toString(), 'amount' => $amount]); } public function amount() : int { return $this->payload['amount']; } public function userId() : Uuid { return Uuid::fromString($this->payload['user']); } }
Java
UTF-8
6,257
1.921875
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package net.torabipour.ChatHubBot.model.botStructure.stateHandler; import com.pengrad.telegrambot.TelegramBot; import com.pengrad.telegrambot.model.Message; import com.pengrad.telegrambot.model.Update; import com.pengrad.telegrambot.request.EditMessageText; import java.util.List; import net.torabipour.ChatHubBot.controller.BotHandler; import net.torabipour.ChatHubBot.db.TransactionalDBAccess; import net.torabipour.ChatHubBot.model.Language; import net.torabipour.ChatHubBot.model.User; import net.torabipour.ChatHubBot.model.UserStatus; import net.torabipour.ChatHubBot.model.anonChat.Chat; import net.torabipour.ChatHubBot.model.anonChat.ChatRequest; import net.torabipour.ChatHubBot.model.botStructure.AbstractStateHandler; import net.torabipour.ChatHubBot.model.utils.AnonymousChatHandler; import net.torabipour.ChatHubBot.model.utils.MediaManager; import net.torabipour.ChatHubBot.model.utils.UserInterfaceException; import org.hibernate.Session; /** * * @author mohammad */ public class InChatHandler extends AbstractStateHandler { private Chat currentChat; private User endpoint1; private User endpoint2; public InChatHandler(Update update, TelegramBot bot) { super(update, bot); currentChat = Chat.loadByEndpoint(localUser); if (currentChat != null) { endpoint1 = currentChat.getEndpoint1(); endpoint2 = currentChat.getEndpoint2(); } } @Override protected void validateInput(Message message, String messageText) throws UserInterfaceException { if (currentChat == null) { throw new UserInterfaceException(null,null); } } @Override protected void onInvalidInput(User localUser, Message message, String messageText) { localUser.setStatus(UserStatus.Registered); new TransactionalDBAccess() { @Override protected void operation(Session session) { session.saveOrUpdate(localUser); } }.execute(); sendChatTerminated(message.chat().id(), isEnglish); sendMainMenu(message.chat().id(), isEnglish); } @Override protected void onOperation(User localUser, Message message, String messageText) throws UserInterfaceException { if (update.editedMessage() != null) { Integer originalReply; net.torabipour.ChatHubBot.model.anonChat.Message msg = net.torabipour.ChatHubBot.model.anonChat.Message.loadBySendId(message.messageId()); if (msg == null) { msg = net.torabipour.ChatHubBot.model.anonChat.Message.loadByReceiveId(message.messageId()); if (msg == null) { originalReply = message.messageId(); } else { originalReply = msg.getSendId(); } } else { originalReply = msg.getReceiveId(); } Long chatId = currentChat.getEndpoint1().getId().equals(localUser.getId()) ? currentChat.getEndpoint2().getChatId() : currentChat.getEndpoint1().getChatId(); if (message.text() != null) { bot.execute(new EditMessageText(chatId, originalReply, message.text())); } return; } new AnonymousChatHandler() { @Override public TelegramBot getBot() { return bot; } @Override public Update getUpdate() { return update; } @Override public Chat getCurrentChat() { return currentChat; } @Override public User getLocalUser() { return localUser; } }.copyMessageAndForward(endpoint1.getChatId().equals(message.chat().id()) ? endpoint2.getChatId() : endpoint1.getChatId(), isEnglish); } @Override protected void onUnsuccessfullOperation(User localUser, Message message, String messageText) { } @Override protected void sendMessageOnSuccess(Long chatId, Boolean isEnglish, MediaManager mediaManager) { } @Override protected UserStatus getAbortUserStatus() { return UserStatus.Registered; } @Override protected void onAbort(User localUser, Message message, String messageText) { currentChat.setActive(false); endpoint1.setStatus(UserStatus.Registered); endpoint2.setStatus(UserStatus.Registered); List<ChatRequest> prevEnd1 = ChatRequest.loadByRequester(endpoint1); List<ChatRequest> prevEnd2 = ChatRequest.loadByRequester(endpoint2); new TransactionalDBAccess() { @Override protected void operation(Session session) { session.update(currentChat); session.merge(endpoint1); session.merge(endpoint2); if (prevEnd1 != null) { prevEnd1.forEach(x -> { x.setActive(false); session.merge(x); }); } if (prevEnd2 != null) { prevEnd2.forEach(x -> { x.setActive(false); session.merge(x); }); } } }.execute(); } @Override protected void sendMessageOnAbort(Long chatId, Boolean isEnglish, MediaManager mediaManager) { sendChatTerminated(endpoint1.getChatId(), endpoint1.getLang().equals(Language.English)); sendChatTerminated(endpoint2.getChatId(), endpoint2.getLang().equals(Language.English)); sendMainMenu(endpoint1.getChatId(), endpoint1.getLang().equals(Language.English)); sendMainMenu(endpoint2.getChatId(), endpoint2.getLang().equals(Language.English)); } private void sendChatTerminated(Long chatId, Boolean isEnglish) { mediaManager.messageSend(isEnglish ? "Chat terminated.\n" : "چت اتمام یافت.", chatId); } }
Markdown
UTF-8
7,913
3.40625
3
[]
no_license
## Алгоритм Пусть дан массив из $n$ чисел, и требуется с предподсчётом за $O(n \\log n)$ отвечать на запрос "минимум на отрезке" за $O(1)$ в онлайне. ### Предподсчёт Для этого сделаем следующий предподсчёт: в массиве для каждого подотрезка, длина которого является степенью 2, найдём минимум в нём. Таким обазом мы хотим найти минимум в отрезках $\[0, 0\],\\ \[1, 1\],\\ \\ldots,\\ \[n-1, n - 1\]$, $\[0, 1\],\\ \[1, 2\],\\ \\ldots,\\ \[n - 2, n - 1\]$, $\[0, 3\],\\ \[1, 4\],\\ \\ldots,\\ \[n - 4, n - 1\]$, и так далее. Заметим, что сделать мы это можем за $O(n \\log n)$. Заведём массив $S\[n\]\[\\log n\]$ (этот массив и называется Sparse Table). Мы хотим, чтобы $S\[i\]\[j\]$ было равно минимуму в отрезке, начиная с $i$ и имеющему длину $2^j$. Нетрудно заметить, что $S\[i\]\[0\]$ равно числу, стоящему на $i$-м месте массива. Теперь научимся для фиксированного $j$ и всех возможных $i$ считать $S\[i\]\[j\]$, если мы уже знаем все $S\[i\]\[j - 1\]$. Как мы знаем, $S\[i\]\[j\]$ этот минимум в отрезке массива, начинающегося в позиции $i$ и имеющем длину $2^j$. Такой отрезок можно разделить на 2 меньших отрезка длиной $2^{j - 1}$, начинающихся в позициях $i$ и $i + 2^{j - 1}$. Тогда если посчитан минимум в обоих таких отрезках, то мы можем найти минимум в исходном, что нам и требовалось сделать. Соответственно, так можно посчитать все $S\[i\]\[j\]$. Также сделаем следующий предподсчёт: для всех чисел от 1 до $n$ найдём максимальную степень 2, не превышающую данного числа. Точнее, нам понадобится логарифм этого числа, так как в $S$ мы используем именно их. Сделать этот предподсчёт можно, например, следующим элегантным кодом ``` C++ vector<int> logs(n + 1, 0); logs[1] = 0; for (int i = 1; i <= n; ++i) { logs[i] = logs[i / 2] + 1; } ``` ### Ответ на запрос Сделав эти 2 предподсчёта, мы готовы быстро отвечать на запросы. Пусть нам даны пары индексов $l$ и $r$, и мы хотим найти минимум на отрезке от $l$ до $r$. Длина такого отрезка равна $r - l + 1$. Для этой длины мы уже преподсчитали максимальное $k$, что $2^k \\le r - l + 1$. Тогда заметим, что если мы возьмём два отрезка, длиной $2^k$, один из которых начинается в $l$, а второй заканчивается в $r$, то эти 2 отрезка будут находится полностью внутри начального отрезка, причём так как их суммарная длина больше длины нашего отрезка (по определению $k$), то они полностью покроют отрезок с $l$ по $r$ (некоторые части будут покрыты 2 раза). Тогда чтобы ответить на запрос минимума на отрезке с $l$ по $r$, надо просто взять минимум из уже посчитанных минимумов в этих двух отрезках (т.е. ответ это $min(S\[l\]\[k\], S\[r - 2^{k} + 1\]\[k\])$). Заметим, что на самом деле Sparse Table можно строить не только для операции минимума, но и для многих других операций, таких что повторение одной и той же части отрезка в операции дважды не влияет на ответ. Например Sparse Table можно построить для побитового И и побитового ИЛИ, но нельзя построить для побитового XOR или для количества минимумов. Для этих операций тоже есть некий аналог Sparse Table, [Disjoint Sparse Table](Disjoint_Sparse_Table "wikilink"). ## Несколько измерений Sparse Table можно построить не только для одномерного массива, но и для таблиц из нескольких измерений. Для примера рассмотрим такую задачу. Есть таблица $n \\times m$, надо сделать предподсчёт за $O(n\\,m \\log(n) \\log(m))$, после чего отвечать на запрос "минимум в прямоугольнике". В одномерном случае мы считали минимум в отрезках с длиной, равной степени 2. Расширим эту идею и будем считать минимум в прямоугольниках, у которых длина каждой стороны это степень 2. Заметим, что посчитать минимум в прямоугольниках, у которых высота равна $1=2^0$, а длина это какая-то степень 2 мы можем так же, как мы считали Sparse Table для одномерного массива. Так же заметим, что прямоугольник, у которого высота это $2^k$ делится на 2 прямоугольника, у которых высота $2^{k - 1}$. Тогда мы можем для второго измерения всё делать так же, как и для одномерного случая. Ответ на запрос тоже аналогичен одномерному случаю. Если надо найти минимум в прямоугольнике, с координатами от клетки $(x_1, y_1)$ до клетки $(x_2, y_2)$, то найдём максимальные $k$ и $l$, что $2^k \\le x_1 - x_2 + 1$ и $2^l \\le y_1 - y_2 + 1$. Тогда заметим, что если в углы начального прямоугольника поставить прямоугольники с длиной по $x$ равной $2^k$, а с длиной по $y$ равной $2^l$, то эти 4 прямоугольника полностью его покроют, но за границы не выйдут. Тогда взяв миинимум по этим 4 прямоугольникам мы ответим за запрос. ## См. также [Disjoint Sparse Table](Disjoint_Sparse_Table "wikilink") [Категория:Конспект](Категория:Конспект "wikilink") [Категория:Структуры данных для запросов на отрезке](Категория:Структуры_данных_для_запросов_на_отрезке "wikilink") [Категория:Многомерные структуры данных](Категория:Многомерные_структуры_данных "wikilink")
Python
UTF-8
226
2.859375
3
[]
no_license
def char_ frequency(str1): dict={} for n in str1: keys=dict.keys() if n in keys: dict[n]+=str1 else: dict[n]=str1 return dict print (char.frequency('google.com'))
Markdown
UTF-8
36,614
3.40625
3
[]
no_license
Divide and Conquer - Classification Using Decision Trees and Rules ================ Emma Grossman 4/19/2021 Decision Trees and rule learners make complex decisions form sets of simple choices. The result is logical structures that require little statistical knowledge, which is very useful for business strategy and process improvement. # Understanding decision trees Called “decision trees” because of their **tree structure**, these classifiers uses a structure of branches that channel examples into a final predicted class value. Decision trees begin with a **root node**, then moves to **decision nodes**, both of which ask a binary question. With the question answered, data are filtered by **branches** which indicate potential outcomes of a decision. **Leaf nodes**, or **terminal nodes** as they are also called, denote the action to be taken as a result of the question answers. The format of a decision tree is especially helpful for humans, since it is very intuitive to understand. This means it is quite easy to identify why a model works well or doesn’t. Additionally, if a model needs to be transparent for legal reasons, like credit scoring models, marketing studies, and diagnosis of medical conditions. > Decision trees are the single most widely used machine learning > technique, and can be applied for modeling almost any type of data - > often with excellent out-of-the-box performance. That being said, in cases where our data has many nominal features with many levels or a large number of numeric data, decision trees might generate a very complex tree and they already have a tendency to overfit the data. ## Divide and conquer **Divide and conquer**, also known as **recursive partitioning**, is the method underlying decision trees because they split the data into subsets, split those subsets into smaller subsets and so on until the algorithm decides the subgroups are sufficiently homogeneous or another stopping criterion is reached. Ideally, the root node is a feature that is most predictive of the target class, and a branch is created based on this node. The algorithm continues to chose features for decision nodes until the stopping criterion is reached. Some examples of stopping criterion are: 1. most examples at the node have the same class 2. all features have been used 3. tree has grown to predetermined size limit A drawback of decision trees is that it only considers one feature at a time and thus can only make **axis-parallel splits** and not diagonal splits. # The C5.0 decision tree algorithm The C5.0 decision tree algorithm is generally the industry standard for computing decision trees. Strengths: - does well on many types of problems - handles numeric, nominal and missing data well - excludes unimportant features - small and large data sets - model and be interpreted by folks with non-mathematical background (small trees) - more efficient than complex models Weaknesses - biases toward models that split of features that have a large number of levels - easy to overfit or underfit - some relationships are difficult to model because of axis-parallel split restraint - sensitive to small changes in training data - large trees can be difficult to interpret and may be counterintuitive ## Chosing the best split The first challenge of a decision tree is deciding where to split a feature. Subsets that result in a single class are **pure** and subsets are measured by their **purity**. C5.0 uses **entropy** to measure purity. High entropy means data are diverse and provide little information about other features. Entropy is typically measured in **bits**; with two classes the range of possible values is 0 to 1 and with all other classes the range is 0 to \(\log_2(n)\). For all cases, lower values are better and 0 indicates homogeneity while the maximum indicates the most diverse possible. \[ \text{Engropy}(S) = \sum_{i=1}^{c} - p_i\log_2(p_i)\] S = a given segment of our data \(c\) = number of class levels \(p_i\) = proportion of values falling into class level i For example, with two classes red (60%) and white (40%): ``` r -.60*log2(0.6) - 0.4*log2(0.4) ``` ## [1] 0.9709506 And we can visualize this as well: ``` r curve(-x *log2(x)-(1-x)*log2(1-x), col = "red", xlab = "x", ylab = "Entropy", lwd = 4) ``` ![](week4_MLwR_decisiontrees_files/figure-gfm/unnamed-chunk-2-1.png)<!-- --> In order to use entropy to find the best feature to split on, the algorithm calculates **information gain** which is the change in homogeneity that results from a split on each possible feature. To calculate the information gain for feature \(F\), we find the distance between the entropy of the segment before the split (\(S_1\)) and the partitions resulting from the split (\(S_2\)): $ (F) = (S\_1) - (S\_2)$. This can be complicated, though, if after the split, the data is divided into more than one partition. We would then need to consider the total entropy across all partitions. To do this, each partition’s entropy is weighted according to the proportion of all records falling into that partition. The formula is then $ (S) = \_{i=1}^{n}w\_i(P\_i)$. The higher the information gain, the better a feature is a creating homogeneous groups ## Pruning the decision tree In order to avoid overfitting the training data, we **prune** the decision tree. One way to prune is to tell the tree to stop growing once a certain number of decisions have been made, called **early stopping** or **pre-pruning**. The result is that the tree doesn’t perform needless tasks but it could also miss subtle but important patterns by stopping early. The other way to prune is **post-pruning**, which allows a large tree to grow, then prunes leaf nodes to reduce the size of the tree. This is generally more effective than pre-pruning. The C5.0 algorithm does most of the work for us and will prune leaves or branches with fairly reasonable defaults. The process of removing entire branches and replacing them with smaller decisions is known as **subtree raising** and **subtree replacement**. # Example - identifying risky bank loans using C5.0 decision trees ``` r credit <- read.csv("https://raw.githubusercontent.com/stedy/Machine-Learning-with-R-datasets/master/credit.csv", header = TRUE) ``` ## Step 2 - exploring and preparing the data ``` r str(credit) ``` ## 'data.frame': 1000 obs. of 21 variables: ## $ checking_balance : Factor w/ 4 levels "< 0 DM","> 200 DM",..: 1 3 4 1 1 4 4 3 4 3 ... ## $ months_loan_duration: int 6 48 12 42 24 36 24 36 12 30 ... ## $ credit_history : Factor w/ 5 levels "critical","delayed",..: 1 5 1 5 2 5 5 5 5 1 ... ## $ purpose : Factor w/ 10 levels "business","car (new)",..: 8 8 5 6 2 5 6 3 8 2 ... ## $ amount : int 1169 5951 2096 7882 4870 9055 2835 6948 3059 5234 ... ## $ savings_balance : Factor w/ 5 levels "< 100 DM","> 1000 DM",..: 5 1 1 1 1 5 4 1 2 1 ... ## $ employment_length : Factor w/ 5 levels "> 7 yrs","0 - 1 yrs",..: 1 3 4 4 3 3 1 3 4 5 ... ## $ installment_rate : int 4 2 2 2 3 2 3 2 2 4 ... ## $ personal_status : Factor w/ 4 levels "divorced male",..: 4 2 4 4 4 4 4 4 1 3 ... ## $ other_debtors : Factor w/ 3 levels "co-applicant",..: 3 3 3 2 3 3 3 3 3 3 ... ## $ residence_history : int 4 2 3 4 4 4 4 2 4 2 ... ## $ property : Factor w/ 4 levels "building society savings",..: 3 3 3 1 4 4 1 2 3 2 ... ## $ age : int 67 22 49 45 53 35 53 35 61 28 ... ## $ installment_plan : Factor w/ 3 levels "bank","none",..: 2 2 2 2 2 2 2 2 2 2 ... ## $ housing : Factor w/ 3 levels "for free","own",..: 2 2 2 1 1 1 2 3 2 2 ... ## $ existing_credits : int 2 1 1 1 2 1 1 1 1 2 ... ## $ default : int 1 2 1 1 2 1 1 1 1 2 ... ## $ dependents : int 1 1 2 2 2 2 1 1 1 1 ... ## $ telephone : Factor w/ 2 levels "none","yes": 2 1 1 1 1 2 1 2 1 1 ... ## $ foreign_worker : Factor w/ 2 levels "no","yes": 2 2 2 2 2 2 2 2 2 2 ... ## $ job : Factor w/ 4 levels "mangement self-employed",..: 2 2 4 2 2 4 2 1 4 1 ... ``` r credit <- credit %>% mutate( default = as.factor(ifelse(default==1,"no","yes")), existing_credits = as.factor(existing_credits), dependents = as.factor(dependents) ) ``` There are some variables that seem likely to predict a default and we can check those out with `table()`. ``` r table(credit$checking_balance) ``` ## ## < 0 DM > 200 DM 1 - 200 DM unknown ## 274 63 269 394 ``` r table(credit$savings_balance) ``` ## ## < 100 DM > 1000 DM 101 - 500 DM 501 - 1000 DM unknown ## 603 48 103 63 183 DM stands for Deutsche Mark, which was the currency used in Germany (where this data originated from) before they adopted the Euro. ``` r summary(credit$months_loan_duration) ``` ## Min. 1st Qu. Median Mean 3rd Qu. Max. ## 4.0 12.0 18.0 20.9 24.0 72.0 ``` r summary(credit$amount) ``` ## Min. 1st Qu. Median Mean 3rd Qu. Max. ## 250 1366 2320 3271 3972 18424 We can also look at whether folks defaulted on their loans: ``` r table(credit$default) ``` ## ## no yes ## 700 300 ### Data preperation - creating random training and test datasets ``` r # we want 90% of the data in the training set and 10% in the testing set set.seed(843) train_sample <- sample(nrow(credit), nrow(credit)*0.9) ``` ``` r credit_train <- credit[train_sample,] credit_test <- credit[-train_sample,] ``` There should still be about 30% of folks defaulting on the loan for each data set, so let’s make sure that is the case: ``` r prop.table(table(credit_train$default)) ``` ## ## no yes ## 0.6977778 0.3022222 ``` r prop.table(table(credit_test$default)) ``` ## ## no yes ## 0.72 0.28 That is satisfactory. ## Step 3 - training a model on the data ``` r # install.packages("C50") library(C50) ``` Creating the C5.0 model ``` r credit_model <- C5.0(credit_train[-17], credit_train$default) credit_model ``` ## ## Call: ## C5.0.default(x = credit_train[-17], y = credit_train$default) ## ## Classification Tree ## Number of samples: 900 ## Number of predictors: 20 ## ## Tree size: 64 ## ## Non-standard options: attempt to group attributes To see the tree’s decisions we can use `summary()` ``` r summary(credit_model) ``` ## ## Call: ## C5.0.default(x = credit_train[-17], y = credit_train$default) ## ## ## C5.0 [Release 2.07 GPL Edition] Wed Apr 21 10:00:18 2021 ## ------------------------------- ## ## Class specified by attribute `outcome' ## ## Read 900 cases (21 attributes) from undefined.data ## ## Decision tree: ## ## checking_balance in {> 200 DM,unknown}: no (411/54) ## checking_balance in {< 0 DM,1 - 200 DM}: ## :...months_loan_duration <= 22: ## :...other_debtors = co-applicant: ## : :...age <= 39: no (8/1) ## : : age > 39: yes (2) ## : other_debtors = guarantor: ## : :...purpose in {business,car (used),domestic appliances,education, ## : : : furniture,others,radio/tv,repairs,retraining}: no (23) ## : : purpose = car (new): ## : : :...credit_history in {critical,delayed,fully repaid, ## : : : fully repaid this bank}: yes (3) ## : : credit_history = repaid: no (1) ## : other_debtors = none: ## : :...credit_history in {critical,delayed}: no (76/13) ## : credit_history = fully repaid this bank: yes (15/2) ## : credit_history in {fully repaid,repaid}: ## : :...savings_balance in {> 1000 DM,501 - 1000 DM}: no (16/1) ## : savings_balance in {< 100 DM,101 - 500 DM,unknown}: ## : :...job = mangement self-employed: ## : :...amount <= 7582: no (10/1) ## : : amount > 7582: yes (3) ## : job = unemployed non-resident: ## : :...savings_balance in {< 100 DM, ## : : : 101 - 500 DM}: yes (3) ## : : savings_balance = unknown: no (3/1) ## : job = unskilled resident: ## : :...installment_plan = none: no (28/8) ## : : installment_plan = stores: yes (1) ## : : installment_plan = bank: ## : : :...checking_balance = < 0 DM: no (1) ## : : checking_balance = 1 - 200 DM: yes (3) ## : job = skilled employee: ## : :...personal_status = divorced male: yes (3/1) ## : personal_status = married male: ## : :...telephone = none: yes (6/1) ## : : telephone = yes: no (4) ## : personal_status = single male: ## : :...savings_balance in {101 - 500 DM, ## : : : unknown}: no (10/1) ## : : savings_balance = < 100 DM: ## : : :...existing_credits = 1: no (15/6) ## : : existing_credits in {2,3,4}: yes (4) ## : personal_status = female: ## : :...residence_history <= 1: ## : :...checking_balance = < 0 DM: no (4) ## : : checking_balance = 1 - 200 DM: ## : : :...amount <= 1424: yes (2) ## : : amount > 1424: no (2) ## : residence_history > 1: ## : :...residence_history <= 3: yes (14) ## : residence_history > 3: ## : :...amount <= 2273: yes (10/2) ## : amount > 2273: no (6/1) ## months_loan_duration > 22: ## :...savings_balance in {> 1000 DM,unknown}: ## :...checking_balance = < 0 DM: ## : :...existing_credits = 4: yes (0) ## : : existing_credits in {2,3}: no (3) ## : : existing_credits = 1: ## : : :...installment_rate <= 2: no (3/1) ## : : installment_rate > 2: yes (8/1) ## : checking_balance = 1 - 200 DM: ## : :...amount <= 9960: no (17) ## : amount > 9960: ## : :...installment_rate <= 1: yes (2) ## : installment_rate > 1: no (2) ## savings_balance in {< 100 DM,101 - 500 DM,501 - 1000 DM}: ## :...months_loan_duration > 42: yes (36/6) ## months_loan_duration <= 42: ## :...other_debtors = co-applicant: yes (11/3) ## other_debtors = guarantor: ## :...checking_balance = < 0 DM: no (5) ## : checking_balance = 1 - 200 DM: yes (2) ## other_debtors = none: ## :...purpose in {domestic appliances,others,repairs, ## : retraining}: yes (2) ## purpose = car (used): ## :...age <= 28: yes (6/1) ## : age > 28: no (14/1) ## purpose = education: ## :...employment_length in {0 - 1 yrs,4 - 7 yrs}: no (3) ## : employment_length in {> 7 yrs,1 - 4 yrs, ## : unemployed}: yes (4) ## purpose = furniture: ## :...installment_plan in {bank,none}: yes (22/5) ## : installment_plan = stores: no (3) ## purpose = car (new): ## :...savings_balance = 501 - 1000 DM: yes (0) ## : savings_balance = < 100 DM: ## : :...installment_rate <= 2: no (3/1) ## : : installment_rate > 2: yes (16/1) ## : savings_balance = 101 - 500 DM: ## : :...job = mangement self-employed: yes (1) ## : job in {skilled employee,unemployed non-resident, ## : unskilled resident}: no (4) ## purpose = business: ## :...savings_balance = 501 - 1000 DM: yes (0) ## : savings_balance = 101 - 500 DM: ## : :...personal_status = female: yes (1) ## : : personal_status in {divorced male,married male, ## : : single male}: no (4) ## : savings_balance = < 100 DM: ## : :...telephone = none: no (3) ## : telephone = yes: ## : :...dependents = 1: yes (8) ## : dependents = 2: no (3/1) ## purpose = radio/tv: ## :...dependents = 2: yes (4) ## dependents = 1: ## :...employment_length in {> 7 yrs,4 - 7 yrs, ## : unemployed}: no (7) ## employment_length in {0 - 1 yrs,1 - 4 yrs}: ## :...amount <= 2708: yes (9) ## amount > 2708: ## :...job in {mangement self-employed, ## : unemployed non-resident, ## : unskilled resident}: no (2) ## job = skilled employee: ## :...installment_rate <= 2: no (2) ## installment_rate > 2: yes (3) ## ## ## Evaluation on training data (900 cases): ## ## Decision Tree ## ---------------- ## Size Errors ## ## 61 114(12.7%) << ## ## ## (a) (b) <-classified as ## ---- ---- ## 605 23 (a): class no ## 91 181 (b): class yes ## ## ## Attribute usage: ## ## 100.00% checking_balance ## 54.33% months_loan_duration ## 46.44% other_debtors ## 40.11% savings_balance ## 27.00% credit_history ## 16.78% purpose ## 16.00% job ## 9.44% personal_status ## 7.78% amount ## 6.44% installment_plan ## 4.33% installment_rate ## 4.22% residence_history ## 4.22% dependents ## 3.67% existing_credits ## 3.33% employment_length ## 3.33% age ## 2.67% telephone ## ## ## Time: 0.0 secs Interpreting the first few lines in plain language: 1. If the checking account balance is unknown or greater than 200 DM, then classify as “not likely to default” 2. Otherwise, if the checking account balance is less than zero DM or between one and 200 DM… 3. … and the credit history is perfect or very good, the classify as “likely to default” The numbers in the parentheses indicate the number of correct and incorrect examples in that decision. So for (411/54), it means that 411 were correctly classified by the decision and 54 defaulted when it predicted they would not. A confusion matrix is also produced. The model correctly classified all by 114 cases, which is an error rater of 12.7%. 23 cases were classified as default when they did not default while 91 folks who were predicted not to default did. Decision trees have a tendency to overfit the data, so the error rate produced by this confusion matrix might be optimistic. ## Step 4 - evaluating model performance ``` r credit_pred <- predict(credit_model, credit_test) ``` ``` r library(gmodels) CrossTable(credit_test$default, credit_pred, prop.chisq = FALSE, prop.c = FALSE, prop.r = FALSE, dnn = c("actual default", "predicted default")) ``` ## ## ## Cell Contents ## |-------------------------| ## | N | ## | N / Table Total | ## |-------------------------| ## ## ## Total Observations in Table: 100 ## ## ## | predicted default ## actual default | no | yes | Row Total | ## ---------------|-----------|-----------|-----------| ## no | 66 | 6 | 72 | ## | 0.660 | 0.060 | | ## ---------------|-----------|-----------|-----------| ## yes | 14 | 14 | 28 | ## | 0.140 | 0.140 | | ## ---------------|-----------|-----------|-----------| ## Column Total | 80 | 20 | 100 | ## ---------------|-----------|-----------|-----------| ## ## The model correctly classified 66 cases as not defaulting and 14 as defaulting. It incorrectly predicted that 6 people would default who didn’t and 14 people as not defaulting but did. Let’s see if we can improve this. ## Step 5 - improving model performance ### Boosting the accuracy of decision trees We can boost performance by combining several models. By using the `trials` argument of the `C5.0()` function, we can ask the function to create several trees and use the boosted team. It is an upper limit, so if the algorithm determines that it has enough trees before reaching the `trials` number, it will stop. 10 is fairly standard to start with. ``` r credit_boost10 <- C5.0(credit_train[-17], credit_train$default, trials = 10) credit_boost10 ``` ## ## Call: ## C5.0.default(x = credit_train[-17], y = credit_train$default, trials = 10) ## ## Classification Tree ## Number of samples: 900 ## Number of predictors: 20 ## ## Number of boosting iterations: 10 ## Average tree size: 50.5 ## ## Non-standard options: attempt to group attributes Our tree size shrunk from 64 to 50.5, which is a large decrease. Let’s take a look at the confusion matrix. ``` r # summary(credit_boost10) # (a) (b) <-classified as # ---- ---- # 628 (a): class 1 # 19 253 (b): class 2 ``` Only 19 mistakes were made, which is an improvement. ``` r credit_boost_pred10 <- predict(credit_boost10, credit_test) CrossTable(credit_test$default, credit_boost_pred10, prop.chisq = FALSE, prop.c = FALSE, prop.r = FALSE, dnn = c("actual default", "predicted default")) ``` ## ## ## Cell Contents ## |-------------------------| ## | N | ## | N / Table Total | ## |-------------------------| ## ## ## Total Observations in Table: 100 ## ## ## | predicted default ## actual default | no | yes | Row Total | ## ---------------|-----------|-----------|-----------| ## no | 65 | 7 | 72 | ## | 0.650 | 0.070 | | ## ---------------|-----------|-----------|-----------| ## yes | 12 | 16 | 28 | ## | 0.120 | 0.160 | | ## ---------------|-----------|-----------|-----------| ## Column Total | 77 | 23 | 100 | ## ---------------|-----------|-----------|-----------| ## ## While this is an improvement, we are still not doing super well at predicting defaults, with only 16/28 = 57% predicted correctly. Why do we automatically apply boosting, if it is so helpful? A couple reasons, (1) they can take a lot of time and (2) if our data is noisy sometimes it won’t improve our results at all. ### Making some mistakes cost more than others We could mitigate the false negatives by rejecting more people who are on the cusp of default/non-default. The C5.0 algorithm allows us to weigh the errors differently, so that a tree will not make costly mistakes. A **cost matrix** specifies how much more costly each error is relative to any other. ``` r matrix_dimensions <- list(c("no", "yes"), c("no", "yes")) names(matrix_dimensions) <- c("predicted", "actual") matrix_dimensions ``` ## $predicted ## [1] "no" "yes" ## ## $actual ## [1] "no" "yes" We can now fill in the costs, though the ordering is specific and we should be careful. ``` r error_cost <- matrix(c(0,1,4,0), nrow = 2, dimnames = matrix_dimensions) error_cost ``` ## actual ## predicted no yes ## no 0 4 ## yes 1 0 There is no cost associated with correct interpretations, but false negatives cost 4 times more than false positives. Let’s apply this to our decision tree. ``` r credit_cost <- C5.0(credit_train[-17], credit_train$default, costs = error_cost) credit_cost_pred <- predict(credit_cost, credit_test) CrossTable(credit_test$default, credit_cost_pred, prop.chisq = FALSE, prop.c = FALSE, prop.r = FALSE, dnn = c("actual default", "predicted default")) ``` ## ## ## Cell Contents ## |-------------------------| ## | N | ## | N / Table Total | ## |-------------------------| ## ## ## Total Observations in Table: 100 ## ## ## | predicted default ## actual default | no | yes | Row Total | ## ---------------|-----------|-----------|-----------| ## no | 40 | 32 | 72 | ## | 0.400 | 0.320 | | ## ---------------|-----------|-----------|-----------| ## yes | 7 | 21 | 28 | ## | 0.070 | 0.210 | | ## ---------------|-----------|-----------|-----------| ## Column Total | 47 | 53 | 100 | ## ---------------|-----------|-----------|-----------| ## ## There are more overall mistakes for this tree, but there are less folks given loans who default on them. Now, 21/28 = 75% of actual defaults were correctly classified. ## Understanding classification rules There are two components of classification: the **antecedent** and the **consequent**, which forms the statement “if this happens, then that happens”. Rule learners are similar to decision trees and can be used for applications that generate knowledge for future action. The are more simple, direct and more easily understood than decision trees. Rule learners excel at identifying rare events and are often used when features are primarily nominal. ### Separate and conquer Rule learners create many rules that classify data. The rules seem to cover portions of the data and because of that, are often called **covering algorithms** and the rules called covering rules. ### The 1R algorithm **ZeroR** is the simplest classifier that considers no features and learns no rules. It always predicts the most common class (similar to k-NN with k equal to n?). In contrast, the **1R algorithm** (or **One Rule** or **OneR**) selects a single rule and performs better than you might expect. Strengths: - single, easy to understand rule - performs surprising well - benchmark to compare more complex algorithms Weaknesses: - only one feature - overly simple ### The RIPPER algorithm Early rule learning algorithms were slow (and thus ineffective with large datasets) and generally inaccurate with noisy data. To solve these issues, the **incremental reduced error pruning (IREP) algorithm** was created and used pre-pruning and post-pruning with complex rules and before separating the instances from the full dataset. Though this helped, decision trees still performed better. The next step was the **repeated incremental pruning to produce error reduction (RIPPER) algorithm** which improved IREP to generate rules that match/exceed the performance of decision trees. Strengths: - easy to understand with human readable rules - efficient on large and noisy datasets - generally, smpler model than a comparable decision tree Weaknesses: - rules may seem to defy common sense - not ideal for numeric data - may not perform as well as some complex models Generally, RIPPER is a three step process: 1. Grow 2. Prune 3. Optimize To grow, the separate and conquer technique adds conditions to a rule until it perfectly classifies as subset/runes out of attributes for splitting. Information gain is used to identify each splitting attribute. A rule is immediately pruned when increasing its specificity no longer reduces entropy. ### Rules from decision trees By following each branch down to the decision node, a rule can be created from a decision tree. If we use decision trees to generate rules, the resulting rules tend to be more complex than would be found by a rule learner but it can be computationally efficient to generate rules from trees. ### What makes trees and rules greedy? Both decision trees ad rule learners are **greedy learners**. This is because data is used on a first come first service basis. The downside of greedy learners is that they are not guaranteed to produce the best (optimal, most accurate, or smallest number of rules) model. Rule learners can re-conquer data but decision trees can only further subdivide. The computational cost of rule learners is somewhat higher than decision trees. # Example - identifying poisonous mushrooms with rule learners ## Step 1 - collecting data ``` r mushrooms <- read.csv("https://raw.githubusercontent.com/stedy/Machine-Learning-with-R-datasets/master/mushrooms.csv", header = TRUE, stringsAsFactors = TRUE) ``` ## Step 2 - exploring and preparing the data ``` r str(mushrooms) ``` ## 'data.frame': 8124 obs. of 23 variables: ## $ type : Factor w/ 2 levels "e","p": 2 1 1 2 1 1 1 1 2 1 ... ## $ cap_shape : Factor w/ 6 levels "b","c","f","k",..: 6 6 1 6 6 6 1 1 6 1 ... ## $ cap_surface : Factor w/ 4 levels "f","g","s","y": 3 3 3 4 3 4 3 4 4 3 ... ## $ cap_color : Factor w/ 10 levels "b","c","e","g",..: 5 10 9 9 4 10 9 9 9 10 ... ## $ bruises : Factor w/ 2 levels "f","t": 2 2 2 2 1 2 2 2 2 2 ... ## $ odor : Factor w/ 9 levels "a","c","f","l",..: 7 1 4 7 6 1 1 4 7 1 ... ## $ gill_attachment : Factor w/ 2 levels "a","f": 2 2 2 2 2 2 2 2 2 2 ... ## $ gill_spacing : Factor w/ 2 levels "c","w": 1 1 1 1 2 1 1 1 1 1 ... ## $ gill_size : Factor w/ 2 levels "b","n": 2 1 1 2 1 1 1 1 2 1 ... ## $ gill_color : Factor w/ 12 levels "b","e","g","h",..: 5 5 6 6 5 6 3 6 8 3 ... ## $ stalk_shape : Factor w/ 2 levels "e","t": 1 1 1 1 2 1 1 1 1 1 ... ## $ stalk_root : Factor w/ 5 levels "?","b","c","e",..: 4 3 3 4 4 3 3 3 4 3 ... ## $ stalk_surface_above_ring: Factor w/ 4 levels "f","k","s","y": 3 3 3 3 3 3 3 3 3 3 ... ## $ stalk_surface_below_ring: Factor w/ 4 levels "f","k","s","y": 3 3 3 3 3 3 3 3 3 3 ... ## $ stalk_color_above_ring : Factor w/ 9 levels "b","c","e","g",..: 8 8 8 8 8 8 8 8 8 8 ... ## $ stalk_color_below_ring : Factor w/ 9 levels "b","c","e","g",..: 8 8 8 8 8 8 8 8 8 8 ... ## $ veil_type : Factor w/ 1 level "p": 1 1 1 1 1 1 1 1 1 1 ... ## $ veil_color : Factor w/ 4 levels "n","o","w","y": 3 3 3 3 3 3 3 3 3 3 ... ## $ ring_number : Factor w/ 3 levels "n","o","t": 2 2 2 2 2 2 2 2 2 2 ... ## $ ring_type : Factor w/ 5 levels "e","f","l","n",..: 5 5 5 5 1 5 5 5 5 5 ... ## $ spore_print_color : Factor w/ 9 levels "b","h","k","n",..: 3 4 4 3 4 3 3 4 3 3 ... ## $ population : Factor w/ 6 levels "a","c","n","s",..: 4 3 3 4 1 3 3 4 5 4 ... ## $ habitat : Factor w/ 7 levels "d","g","l","m",..: 6 2 4 6 2 2 4 4 2 4 ... We’re going to drop `mushrooms$veil_type` since it is a factor with only one level. ``` r mushrooms$veil_type <- NULL ``` And let’s look at the distribution of mushroom type, our response. ``` r table(mushrooms$type) ``` ## ## e p ## 4208 3916 52% are edible, 48% are poisonous. An important assumption that we are going to make is that our set of mushrooms is exhaustive. We are not trying to classify unknown mushrooms but trying to discover rules that will inform our complete set of mushrooms. Thus, we do not need to create a training and testing set. ## Step 3 - training a model on the data If we used a ZeroR model, which classifies based only on most likely group, we would find that all mushrooms are edible. Not what we need, but we would be correct 52% of the time. This will be our benchmark for comparison. We’ll first implement a 1R algorithm. ``` r # install.packages("OneR") library(OneR) ``` ``` r (mushroom_1R <- OneR(type~., data = mushrooms)) ``` ## ## Call: ## OneR.formula(formula = type ~ ., data = mushrooms) ## ## Rules: ## If odor = a then type = e ## If odor = c then type = p ## If odor = f then type = p ## If odor = l then type = e ## If odor = m then type = p ## If odor = n then type = e ## If odor = p then type = p ## If odor = s then type = p ## If odor = y then type = p ## ## Accuracy: ## 8004 of 8124 instances classified correctly (98.52%) The algorithm found that `odor` was the optimal feature to split on. If a mushroom smells unappetizing, don’t eat it, is essentially the rule we found. ## Step 4 - evaluating model performance Nearly 99% of cases were classified correctly, but that 1% leads to someone being poisoned, so we need to do better. Let’s create a confusion matrix and see what is being misclassified. ``` r mushroom_1R_pred <- predict(mushroom_1R, mushrooms) table(actual = mushrooms$type, predicted = mushroom_1R_pred) ``` ## predicted ## actual e p ## e 4208 0 ## p 120 3796 So, 120 mushrooms that were poisonous were classified as edible, certainly not ideal. Not bad for only using one rule, but we can improve this by adding more, so let’s do that. ## Step 5 - improving model performance ``` r # install.packages("RWeka") library(RWeka) ``` ## ## Attaching package: 'RWeka' ## The following object is masked from 'package:OneR': ## ## OneR ``` r (mushroom_JRip <- JRip(type~., data = mushrooms)) ``` ## JRIP rules: ## =========== ## ## (odor = f) => type=p (2160.0/0.0) ## (gill_size = n) and (gill_color = b) => type=p (1152.0/0.0) ## (gill_size = n) and (odor = p) => type=p (256.0/0.0) ## (odor = c) => type=p (192.0/0.0) ## (spore_print_color = r) => type=p (72.0/0.0) ## (stalk_surface_below_ring = y) and (stalk_surface_above_ring = k) => type=p (68.0/0.0) ## (habitat = l) and (cap_color = w) => type=p (8.0/0.0) ## (stalk_color_above_ring = y) => type=p (8.0/0.0) ## => type=e (4208.0/0.0) ## ## Number of Rules : 9 A total of 9 rules were found and these can be read as ifelse statements. The last rule being that if none of the other rules apply, the mushroom is edible. ``` r mushroom_JRip_pred <- predict(mushroom_JRip, mushrooms) table(actual = mushrooms$type, predicted = mushroom_JRip_pred) ``` ## predicted ## actual e p ## e 4208 0 ## p 0 3916 All of the mushrooms were correctly classified.
SQL
UTF-8
644
3.71875
4
[]
no_license
DROP TABLE StationNeighbour; CREATE TABLE StationNeighbour( stationNeighbourId int AUTO_INCREMENT, stationID1 varchar(20), stationID2 varchar(20), lineID int, PRIMARY KEY (stationNeighbourId) ); ALTER TABLE StationNeighbour ADD FOREIGN KEY StationNeighbour_Station_1 (stationID1) REFERENCES Station(stationID) ON DELETE CASCADE; ALTER TABLE StationNeighbour ADD FOREIGN KEY StationNeighbour_Station_2 (stationID2) REFERENCES Station(stationID) ON DELETE CASCADE; ALTER TABLE StationNeighbour ADD FOREIGN KEY StationNeighbour_Line (lineID) REFERENCES Line(lineID) ON DELETE CASCADE;
C#
UTF-8
5,206
2.875
3
[]
no_license
using MandelbrotDrawer.MandelbrotCalcServiceReference; using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Linq; using System.ServiceModel; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace MandelbrotDrawer { internal class Mandelbrot { int Width; int Height; List<double[]> Scales; public Mandelbrot(int width, int height) { this.Width = width; this.Height = height; Scales = new List<double[]>(); Scales.Add(new double[] { 3.5d, -2.5d, 2.0d, -1.0d }); } public List<double[]> GetScales() { return Scales; } double ScaleY0(int y0, double[] scale) { return scale[2] * (((double)y0) / (Height - 1)) + scale[3]; } double ScaleX0(int x0, double[] scale) { return scale[0] * (((double)x0) / (Width - 1)) + scale[1]; } public void CalculateScaleAttributes(int x1, int x2, int y1, int y2, int numberOfFrames) { double[] scale = Scales[Scales.Count - 1], scaleTmp; int deltaX1 = x1 / numberOfFrames; int deltaX2 = (Width - x2) / numberOfFrames; int deltaY1 = y1 / numberOfFrames; int deltaY2 = (Height - y2) / numberOfFrames; int xScreen1 = 0, xScreen2 = Width, yScreen1 = 0, yScreen2 = Height; for (int i = 0; i < numberOfFrames; i++) { scaleTmp = scale; xScreen1 += deltaX1; xScreen2 -= deltaX2; yScreen1 += deltaY1; yScreen2 -= deltaY2; Scales.Add(CalculateOneScaleAttribute(xScreen1, xScreen2, yScreen1, yScreen2, scaleTmp)); } } public double[] CalculateOneScaleAttribute(int x1, int x2, int y1, int y2, double[] scale) { double[] scaleTmp = new double[4]; double coordinateX1, coordinateX2, coordinateY1, coordinateY2; coordinateX1 = ScaleX0(x1, scale); coordinateX2 = ScaleX0(x2, scale); coordinateY1 = ScaleY0(y1, scale); coordinateY2 = ScaleY0(y2, scale); scaleTmp[1] = coordinateX1; scaleTmp[0] = coordinateX2 + Math.Abs(scaleTmp[1]); scaleTmp[3] = coordinateY1; scaleTmp[2] = coordinateY2 + Math.Abs(scaleTmp[3]); return scaleTmp; } public int Calculate_mandelbrot(int xp, int yp, double[] scale, int numberOfIterations) { double x, y, x2, y2; int iteration = 0; double x0 = ScaleX0(xp, scale); double y0 = ScaleY0(yp, scale); x = y = x2 = y2 = 0.0; while (x2 + y2 <= 4.0 && iteration < numberOfIterations) { double tmp = x2 - y2 + x0; y = 2.0 * x * y + y0; x = tmp; iteration++; x2 = x * x; y2 = y * y; } return iteration == numberOfIterations ? 0 : iteration; } public Bitmap DrawMandelbrot(int variant, int numberOfIterations) { double[] scale; int startIteration; if(variant == 0) { startIteration = Scales.Count-1; } else { startIteration = 0; } Bitmap bitmap = new Bitmap(Width, Height); for (int count = startIteration; count < Scales.Count; count++) { bitmap = new Bitmap(Width, Height); scale = Scales[count]; Parallel.For(0, Width, i => { Parallel.For(0, Height, j => { int result = Calculate_mandelbrot(i, j, scale, numberOfIterations); lock (bitmap) { if (result > 0 && result < 333) { bitmap.SetPixel(i, j, Color.FromArgb(result & 255, 0, 0)); } else if (result >= 333 && result < 666) { bitmap.SetPixel(i, j, Color.FromArgb(0, result & 255, 0)); } else if (result >= 666 && result < 999) bitmap.SetPixel(i, j, Color.FromArgb(0, 0, result & 255)); else { bitmap.SetPixel(i, j, Color.FromArgb(0, 0, 0)); } } }); }); try { bitmap.Save("bitmap" + count.ToString() + ".Jpeg", ImageFormat.Jpeg); }catch(Exception ex) { Console.Write(ex); } } return bitmap; } } }
Shell
UTF-8
339
2.703125
3
[ "BSD-2-Clause" ]
permissive
#! /bin/bash # This runs browser-sync, watching this directory for changes. You should # simply point your web browser to http://localhost:3000/. docker kill browser-sync docker rm browser-sync docker run \ -dt \ --name browser-sync \ -p 3000:3000 \ -p 3001:3001 \ -v $(pwd):/source \ -w /source \ browser-sync \ /run.sh
Java
MacCentralEurope
975
2.796875
3
[]
no_license
package PTUCharacterCreator.Moves; import PTUCharacterCreator.Move; public class Substitute extends Move { { name = "Substitute"; effect = "The user loses 1/4 of their maximum Hit Points. This Hit Point loss cannot be prevented in any way. The user creates an Illusory Substitute Coat, which has Hit Points equal to 1/4th of the users full Hit Points +1. If the user would be hit by a Move or attack, instead the Substitute gets hit. Apply weakness, resistance and stats to the Substitute. The Substitute is immune to Status Afflictions and Status Moves. Moves with the Social or Sonic keywords completely ignore and bypass the Substitute. Once the Substitute has been destroyed, the user may be hit as normal. Substitute cannot be used if the user has less than 1/4 of their full Hit Points."; damageBase = 0; mDamageBase = 0; AC = 0; frequency = "Scene"; range = "Self, Illusion, Coat"; type = "Normal"; category = "Status"; } public Substitute(){} }
Java
UTF-8
1,304
3.015625
3
[]
no_license
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class CalculatorTest { Calculator calculator; @BeforeEach public void setUp(){ calculator = new Calculator(); } @Test public void addNumberTest(){ //Arrange Calculator calculator = new Calculator(); //Act int actual = calculator.addNumber(12,20); //Assert int expected = 32; assertEquals(expected,actual); } @Test public void subNumberTest(){ //A Calculator calculator = new Calculator(); //A int actual = calculator.subNumber(10,546); //A int expected = -536; assertEquals(expected,actual); } @Test public void getCubeTest(){ int actual= new Calculator().getCube(3); int expected = 27; assertEquals(actual,expected); } @Test public void findMaxNumberTest(){ Calculator c = new Calculator(); int actual = c.findMaxNumber(new int[] {2,4,5,4,8,2,6,5,4,5,6}); int ex = 8; assertEquals(actual,ex); } @Test public void testForReverseString(){ assertEquals("cba", calculator.reverseString("abc")); } }
Markdown
UTF-8
476
2.671875
3
[]
no_license
# What I Learned Today February 2021 ## 1/31/2021 Including the last day of January since that is when I decided to formally keep track of "what I learned today". Linear Algebra review: Learned the formal representation of Real vector spaces as the set of all n-tuples with Real valued components and how to represent that using Latex $$ \begin{bmatrix} x_{1} \\ x_{2} \\ \vdots \\ x_{n} \end{bmatrix} \space \epsilon \space \mathbb{R}^n $$ ```python ```
Java
UTF-8
777
2.109375
2
[]
no_license
package com.example.exercisesqlite; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { Button btnadd; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnadd= (Button) findViewById(R.id.btnadd); btnadd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent (MainActivity.this,activity_tambah_data.class); startActivity(i); } }); } }
Swift
UTF-8
3,342
2.78125
3
[]
no_license
// // GraphButton.swift // TonikAnalytics // // Created by Wesley Espinoza on 10/8/19. // Copyright © 2019 HazeWritesCode. All rights reserved. // import Foundation import UIKit class GraphButton: UIButton{ var socialLabel = UILabel() var mainCounter: Int = 0 { didSet { if mainCounter > 0 { negGrowth.isHidden = true } else if mainCounter == 0 { posGrowth.isHidden = true negGrowth.isHidden = true } else { posGrowth.isHidden = true } mainCounterLabel.text = "\(mainCounter)" } } var mainCounterLabel = UILabel() var negGrowth = UIImageView(image: UIImage(named: "downSymbol")) var posGrowth = UIImageView(image: UIImage(named: "upSymbol")) override init(frame: CGRect) { super.init(frame: frame) setupViews() self.backgroundColor = UIColor.init(hexString: "#f6b1cd") self.dropShadow() self.layer.cornerRadius = 15 } func setupViews(){ socialLabel.textAlignment = .center mainCounterLabel.textAlignment = .center socialLabel.adjustsFontSizeToFitWidth = true socialLabel.lineBreakMode = .byClipping self.translatesAutoresizingMaskIntoConstraints = false add(subview: socialLabel) { (v, p) in [ v.centerXAnchor.constraint(equalTo: p.safeAreaLayoutGuide.centerXAnchor, constant: 0), v.topAnchor.constraint(equalTo: p.safeAreaLayoutGuide.topAnchor, constant: 8), v.leadingAnchor.constraint(equalTo: p.safeAreaLayoutGuide.leadingAnchor, constant: 8), v.trailingAnchor.constraint(equalTo: p.safeAreaLayoutGuide.trailingAnchor, constant: -8), v.heightAnchor.constraint(equalToConstant: 25) ]} add(subview: negGrowth) { (v, p) in [ v.centerXAnchor.constraint(equalTo: p.safeAreaLayoutGuide.centerXAnchor, constant: 0), v.bottomAnchor.constraint(equalTo: p.bottomAnchor, constant: -5), v.widthAnchor.constraint(equalToConstant: 50), v.heightAnchor.constraint(equalToConstant: 25) ]} add(subview: posGrowth) { (v, p) in [ v.centerXAnchor.constraint(equalTo: p.safeAreaLayoutGuide.centerXAnchor, constant: 0), v.topAnchor.constraint(equalTo: socialLabel.bottomAnchor, constant: 5), v.widthAnchor.constraint(equalToConstant: 50), v.heightAnchor.constraint(equalToConstant: 25) ]} add(subview: mainCounterLabel) { (v, p) in [ v.centerXAnchor.constraint(equalTo: p.safeAreaLayoutGuide.centerXAnchor, constant: 0), v.centerYAnchor.constraint(equalTo: p.safeAreaLayoutGuide.centerYAnchor, constant: 16), v.leadingAnchor.constraint(equalTo: p.safeAreaLayoutGuide.leadingAnchor, constant: 8), v.trailingAnchor.constraint(equalTo: p.safeAreaLayoutGuide.trailingAnchor, constant: -8), v.heightAnchor.constraint(equalToConstant: 25) ]} layoutIfNeeded() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
Swift
UTF-8
3,007
3.4375
3
[ "MIT" ]
permissive
// import SwiftUI struct SightComponent: Shape { let angle: Angle func path(in rect: CGRect) -> Path { Path { path in let radius: CGFloat = min(rect.size.width, rect.size.height) / 2 path.addArc( center: CGPoint(x: radius, y: radius), radius: radius, startAngle: angle / 2, endAngle: -angle / 2, clockwise: true, transform: .identity ) path.move(to: CGPoint(x: radius * 1.8, y: radius)) path.addLine(to: CGPoint(x: radius * 2.2, y: radius)) } } } struct SightView: View { let strokeWidth: CGFloat let rotationCount: Int let angle: Double let innerRadius: CGFloat var body: some View { ZStack { ForEach(0..<rotationCount, id: \.self) { i in SightComponent(angle: .degrees(self.angle)) .stroke(style: StrokeStyle(lineWidth: self.strokeWidth, lineCap: .round)) .aspectRatio(1, contentMode: .fit) .padding(40) .rotationEffect(.degrees(Double(i) / Double(self.rotationCount)) * 360.0) } Circle() .frame(width: innerRadius, height: innerRadius) } } } struct LogoView: View { let strokeWidth: CGFloat let rotationCount: Int let angle: Double let innerRadius: CGFloat var sightView: some View { SightView(strokeWidth: strokeWidth, rotationCount: rotationCount, angle: angle, innerRadius: innerRadius) } func gradient(for geometry: GeometryProxy) -> RadialGradient { RadialGradient( gradient: Gradient(colors: [.red, .orange]), center: UnitPoint(x: 0.25, y: 0.25), startRadius: 0, endRadius: geometry.size.width ) } var body: some View { ZStack { sightView .hidden() GeometryReader { geometry in self.gradient(for: geometry) .mask(self.sightView) } } } } struct LogoSettingsView: View { @Binding var strokeWidth: CGFloat @Binding var innerCircleRadius: CGFloat @Binding var rotationNumber: Int @Binding var angle: Double var body: some View { List { Section { LogoView(strokeWidth: self.strokeWidth, rotationCount: self.rotationNumber, angle: self.angle, innerRadius: self.innerCircleRadius) } Section(header: Text("Stroke Width: ")) { Slider(value: $strokeWidth, in: 0...100, step: 0.1) } Section(header: Text("Inner Circle Radius: ")) { Slider(value: $innerCircleRadius, in: 0...100, step: 0.1) } Section { Stepper("Rotations: ", value: $rotationNumber) } Section(header: Text("Arc Angle: ")) { Slider(value: $angle, in: 10...120, step: 1) } } .listStyle(GroupedListStyle()) .environment(\.horizontalSizeClass, .regular) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { LogoSettingsView( strokeWidth: .constant(16), innerCircleRadius: .constant(20), rotationNumber: .constant(3), angle: .constant(90)) } }
C
UTF-8
453
3.640625
4
[]
no_license
#include <stdio.h> #include <stdlib.h> int ToNumber(char *a) { if (*a < 'A') return *a - '0'; else return *a - 'A' + 10; } int main() { char a, b, c; int n; int x,y,z; scanf("%c%c%c", &a, &b, &c); x = ToNumber(&a); y = ToNumber(&b); z = ToNumber(&c); n = x * 16 * 16 + y * 16 + z; if (x == 0 && y == 0) printf("%c %d %o", c, n, n); else if (x == 0) printf("%c%c %d %o", b, c, n, n); else printf("%c%c%c %d %o", a, b, c, n, n); return 0; }
Markdown
UTF-8
2,900
3.140625
3
[]
no_license
--- title: "簡單方法判斷自己是不是老了" subtitle: "無關年齡,而在於心" description: "幾天前,我看到一篇文寫:「當你對新技術嗤之以鼻,認為都只是噱頭時,你就已經老了。」當時我如被人搧了後腦杓般,內心震了一下..." excerpt: "幾天前,我看到一篇文寫:「當你對新技術嗤之以鼻,認為都只是噱頭時,你就已經老了。」當時我如被人搧了後腦杓般,內心震了一下..." date: 2021-12-13 author: "Siddharam|西打藍" cover: "" image: "" tags: [""] categories: ["慢慢想"] keywords: - 年齡 - 年紀 - 老 - 心態 - 幣圈 draft: false --- <article style="font-family: 'Noto Sans TC', '微軟正黑體', sans-serif; font-weight: 300;"> <br>文 / 西打藍 Siddharam<br><br> 幾天前,我看到一篇文寫:「當你對新技術嗤之以鼻,認為都只是噱頭時,你就已經老了。」<br><br> 當時我如被人搧了後腦杓般,內心震了一下。想起自己曾認為抖音是小孩玩的、幣圈買賣是詐騙,而現在卻成為顯學。<br><br> 當我一副自認甚高,認為「那些東西」上不了檯面,只以譏笑態度面對時,我身體雖未老,心卻是老了。<br><br> 回頭看那篇文,我發現重點不是新技術,而是「學習」。學習、認識新技術,而非遠離、瞧不上它。<br><br> 於是我問自己:「我們是因為不再學習而老,還是因老了而無能學習呢?」<br><br> 答案很明顯。<br><br> 在上頭文章中,我看見有人留言:「我今年 50 多歲,除了接觸加密貨幣,還在台灣創立 NFT 有關公司。」我大受震驚。連忙打開他的個人簡介,點開他的 IG,滿是好看的 NFT 設計。<br><br> 這時心中再度自責,自責自己曾經的保守與優越。同時也佩服留言者的學習與開創精神,心中對「老」的定義越發明確。<br><br> 當然,學習不一定都是好事。<br><br> 我最近收到一封老朋友來信,他在信中描述自己投遞履歷時,發現自己完全不符合公司條件,因此連面試都不敢去,而對自己失望。<br><br> 若朋友因此努力學習,是因為恐懼而不得不「追趕」,還是因為「好奇」而學?<br><br> 觀察自己的學習動機,是內心充滿恐懼,還是滿懷興趣,就能更知道自己的狀態。<br><br> 2021 年將要過去,希望時刻提醒自己的心,別老了,也別為了追趕別人的腳步,而忘了走只屬於自己的道路。<br><br> <br><br> <br><br><br> </article> <div style="color: #bfbfbf; font-size: 15px;" id="busuanzi_container_page_pv"> 閱讀量<span id="busuanzi_value_page_pv"></span>次 </div> <script src="../../js/post.js"></script>
Java
UTF-8
5,650
2.484375
2
[]
no_license
package cn.cote.controller; import cn.cote.myutils.WebData; import cn.cote.pojo.User; import cn.cote.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.io.File; import java.io.IOException; import java.util.UUID; @Controller @RequestMapping("user") @ResponseBody public class UserController { @Autowired UserService userService; /** * 登陆 * @param request * @param session * @return 前端数据数组 */ @CrossOrigin @RequestMapping(value = "login",method = RequestMethod.POST) public WebData login(HttpServletRequest request,HttpSession session){ //获取用户数据,放入User模型中 User this_user =new User(); this_user.setUserName(request.getParameter("userName")); this_user.setUserPassword(request.getParameter("userPassword")); //引用工具类返回前端 this_user=userService.findUserMessage(this_user); WebData data =new WebData(); if(this_user!=null){ //------------手动日志------------- System.out.println("登陆:找到的User为:"+this_user); //------------手动日志------------- data.setCode(1); data.setMessage("FindIt"); data.setData(this_user); session.setAttribute("userId",this_user.getUserId()); }else{ data.setCode(0); data.setMessage("NotFind"); } return data; } /** * 注册 * @param request * @return 前端数据数组 */ @CrossOrigin @RequestMapping(value = "register",method = RequestMethod.POST) public WebData register(HttpServletRequest request,HttpSession session){ User this_user =new User(); this_user.setUserName(request.getParameter("userName")); this_user.setUserPassword(request.getParameter("userPassword")); WebData data = new WebData(); //尝试插入当前新用户数据 int code=userService.insertUser(this_user); if(code==1){ data.setCode(1); data.setMessage("注册成功"); //通过Session创建userId this_user = userService.findUserMessage(this_user); session.setAttribute("userId",this_user.getUserId()); //------------手动日志------------- System.out.println("新入户入驻,userId为:"+this_user.getUserId()); //------------手动日志------------- }else if(code==0){ data.setCode(0); data.setMessage("用户存在"); } else{ data.setCode(-1); data.setMessage("注册失败"); } return data; } /** * 修改昵称信息 * @param request * @param session * @return 前端数据数组 */ @CrossOrigin @RequestMapping(value = "registerNc",method = RequestMethod.POST) public WebData registerNc(HttpServletRequest request,HttpSession session){ String this_userNc =request.getParameter("userNc"); //从当前的Session中获取当前用户的userId int this_id= (int) session.getAttribute("userId"); int code=userService.changeRegisterNc(this_userNc,this_id); WebData data=new WebData(); data.setCode(code); data.setMessage("修改成功"); return data; } /** *修改用户头像 * @param file * @return * @throws IOException */ @CrossOrigin @RequestMapping(value = "registerImg",method = RequestMethod.POST) public WebData registerImg(MultipartFile file,HttpSession session,HttpServletRequest request) throws IOException { WebData data = new WebData(); if (!file.isEmpty()) { // 设置图片存放路径 // String path = "D:\\Web\\JavaDemo\\ShopApp\\web\\view\\img\\userImg\\"; // String path = "D:\\WebApp\\IdeaApp\\learngit\\ShopApp\\web\\view\\img\\userImg\\"; String path = request.getSession().getServletContext().getInitParameter("IMGPATH") + "userImg\\"; String originalFileName = file.getOriginalFilename(); String type =originalFileName.substring(originalFileName.lastIndexOf(".")); if(".GIF".equals(type.toUpperCase())||".PNG".equals(type.toUpperCase())||".JPG".equals(type.toUpperCase())){ String newFileName = UUID.randomUUID() + type;// 新的图片名称 File newFile = new File(path + newFileName);// 新的图片 //------------手动日志------------- System.out.println("接受到图片为:\n"+newFile); //------------手动日志------------- file.transferTo(newFile); // 将内存中的数据写入磁盘 // 存入数据库 int this_id= (int) session.getAttribute("userId"); int code = userService.addUserImg(newFileName,this_id); data.setCode(code); data.setMessage("修改头像操作完成"); data.setData("/img/userImg/"+newFileName); }else{data.setCode(0);data.setMessage("图片为不接受的类型");} }else {data.setCode(-1);data.setMessage("发生未知错误");} return data; } }
Python
UTF-8
89
2.9375
3
[]
no_license
set_A={1,2,3,4} set_B={'a','b','c','d'} print(set_A|set_B) print(set_A.union(set_B))
JavaScript
UTF-8
373
2.796875
3
[ "MIT" ]
permissive
import { Component } from 'react' function * generatorMethod () { yield 1 } async function fooBar () { for (let val of generatorMethod()) { return val } } export default class Index extends Component { async otherMethod () { await fooBar() } render () { const foo = new Map([['cats', 'dogs']]) return <h1>Garbage {foo.get('cats')}</h1> } }
PHP
UTF-8
753
3.796875
4
[ "MIT" ]
permissive
<?php class Solution { //暴力法 function findOcurrences($text, $first, $second) { if (empty($text)) { return []; } $arr = explode(' ', $text); $count = count($arr); $out = []; for ($i=0;$i<$count;$i++) { if (empty($arr[$i])) { continue; } if ($i==$count - 1) { break; } if ($arr[$i] == $first && $arr[$i+1] == $second && isset($arr[$i+2])) { $out[] = $arr[$i+2]; } } return $out; } } $so = new Solution(); $nums = [10,100]; $val = 3; $res = $so->findOcurrences("alice is a good girl she is a good student","a","good"); var_dump($res);
PHP
UTF-8
3,722
2.75
3
[ "MIT" ]
permissive
<?php class Audio extends Eloquent { protected $table = 'audio'; public function artists() { return $this->belongsTo('Artist', 'artist'); } public static function isValid($id, $data) { $validator = Validator::make($data, [ 'track' => 'required|max:32|unique:audio,track,' . $id, 'album' => 'max:32|unique:audio,album,' . $id ]); if($validator->passes()) { return true; } else { return $validator->messages(); } } public static function save_data($id) { $data = Input::all(); if(self::isValid($id, $data) === true) { if($id > 0) { $audio = Audio::find($id); } else { /* author -> release_album -> cover && file(author_release_album_file.mp3) */ $audio = new Audio; $artist_slug = strtoupper(Translit::slug(Artist::find(array_get($data, 'artist'))->name)); $album_slug = strtoupper(Translit::slug(array_get($data, 'album'))); $track_slug = strtoupper(Translit::slug(array_get($data, 'track'))); $dir = self::makeDirectory($artist_slug); if(array_get($data, 'album')) { $dir = self::makeDirectory($artist_slug, array_get($data, 'release'), $album_slug); $cover = self::upload_cover($album_slug, $dir); } else { $cover = self::upload_cover($track_slug, $dir); } } $audio->artist = array_get($data, 'artist'); $audio->track = array_get($data, 'track'); $audio->album = array_get($data, 'album'); $audio->release = array_get($data, 'release'); $audio->dir = $dir; $audio->cover = $cover; $audio->file = self::upload_file($track_slug, $dir); $audio->save(); Session::flash('alert', array('green', 'Ok')); return $audio; } else { Session::flash('alert_valid', self::isValid($id, $data)->toArray()); //Session::flash('post', $data); Input::flashOnly('username', 'email'); Input::old('username'); return false; } } public static function destroy_data($id) { if(!empty($id)) { $user = Audio::find($id); $user->delete(); Session::flash('alert', array('green', 'Удалено')); } } public static function makeDirectory($artist, $release = false, $album = false) { if(!empty($album)) { $dir = $artist . '/' . $release . '-' . $album; } else { $dir = $artist; } if(!is_dir('./uploads/music/' . $dir)) { mkdir('./uploads/music/' . $dir, 0777); } return $dir; } public static function upload_cover($name, $dir) { $data = Input::file('cover'); $input = array('cover' => Input::file('cover')); $validation = Validator::make($input, array( 'cover' => 'max:1024|mimes:jpeg,gif,png' )); if($validation->passes() && !empty($name)) { $dir = './uploads/music/' . $dir . '/'; $file_name = $name . '.' . $data->getClientOriginalExtension(); $img = Image::make($_FILES['cover']['tmp_name']); $img->fit(250, 250, function ($constraint) { $constraint->upsize(); }); $img->save($dir . $file_name); return $file_name; } else { Session::flash('alert_valid', $validation->messages()->toArray()); return false; } } public static function upload_file($name, $dir) { $data = Input::file('audio'); $input = array('audio' => Input::file('audio')); $validation = Validator::make($input, array( 'audio' => 'max:15360|mimes:bin,mp4a,mpga' )); if($validation->passes()) { $dir = './uploads/music/' . $dir . '/'; $file_name = $name . '.mp3'; $data->move($dir, $file_name); return $file_name; } else { Session::flash('alert_valid', $validation->messages()->toArray()); return false; } } }
Markdown
UTF-8
2,545
2.8125
3
[]
no_license
# Quick Analysis - Coffee Chain in US: # 📝Problem Statement * To help Coffee Chains in the US. * This Coffee Chain is planning to invest in Online & Offline marketing campaigns for its products in different States. * We are asked to figure out which products are worth spending the dominant share of the marketing budget on. # ⏳ Dataset Download the database for this project from following Link - * [Coffee Chain in US Dataset](https://github.com/Lokesh-Attarde/Quick-Analysis_Coffee-Chain-in-US/blob/bc02a8da15ee178a415bfea31e2daf72af47868f/CoffeeChain-SimplifiedData.csv) # 🏽‍ Data Analysis In the datasets, we are provided with 14 columns(Features) of data. * Product Id : Unique ID of a Product. * Product Type : Type of the Product. * Product : Name of the Product. * State : State where Coffee Chain belongs * Profit : Profit they have made w.r.t. Product. * Sales : Sales made w.r.t. Product. * Date : Date where transaction takes place. Out of the 14 features given in the datasets 07 are Continuous and 07 (including the target variable) are Categorical features. # 🖥️ Technologies: ## 🛠️ Tools Used * **BI Tool :** Tableau Desktop 2021.3 # 🏽‍ Some Exciting Glimpse of the Visuals: ![Glimpse 1](https://user-images.githubusercontent.com/84115928/139469628-9b5e71b6-ffff-4448-a00e-e117a4776c4a.gif) For more details, please go Tableau Dashboard link given below - # 🎯 Quick Analysis - Coffee Chain in US - - 🌱 You can have a look on Coffee Chain Dashboard [here.](https://public.tableau.com/views/UpdatedQuickAnalysisCoffeeChaininUS/Dashboard1CoffeeChainQuickAnalysis?:language=en-US&:display_count=n&:origin=viz_share_link) # 🏽‍ Conclusions * Coffee Sales - Espresso is the best Selling overall Product Type, but the difference from other Products is not that high. Let's Analyze Further. * Colombian Coffee is the best Product among all Product Types, it's a clear winner which brings majority of sales. * Sales by States - We can clearly see that California and New York are bringing-in the more Sales of around $96.89K and $70.85K respectively. * In terms of Seasonal Fluctuations, July is the best Month whereas in November, we see the most slump in Sales. # 🎉 Help Me Improve Hello Mr. Reader, if you find any bug or anything else that could add more value in this project then please consider raising it to me I will address them asap. # 📫 Feedback If you have any feedback, please reach out to me via [LinkedIn](https://www.linkedin.com/in/lokesh-attarde-145086141/)
JavaScript
UTF-8
360
3.03125
3
[]
no_license
'use strict'; const button = document.querySelectorAll('.button'); const body = document.querySelector('body'); function click2 (event) { if (body.classList.contains('body')){ body.classList.remove('body'); } else { body.classList.add('body'); } } for (let i= 0; i<button.length; i++){ button[i].addEventListener("click", click2); }
PHP
UTF-8
3,580
2.78125
3
[]
no_license
<?php /** * QRReferralLink class definition. * * @package Klaviyo for SUMO. */ namespace EmpireArtist\KlaviyoSumo\Subscribers; defined( 'ABSPATH' ) || exit; use QRcode; use WP_User; use EmpireArtist\KlaviyoSumo\Interfaces\HasActions; use EmpireArtist\KlaviyoSumo\Interfaces\HasFilters; use function EmpireArtist\KlaviyoSumo\get_plugin_file_path; use function EmpireArtist\KlaviyoSumo\get_referral_link; use function EmpireArtist\KlaviyoSumo\get_referral_qr_url; /** * Subscribe to WordPress and WooCommerce hooks to provide membership tracking * functionality. */ class QRReferralLink implements HasActions, HasFilters { /** * Constructor. * * @param Klaviyo $klaviyo Klaviyo API client instance. * * @return void */ function __construct() { if ( ! class_exists( 'QRcode' ) ) { require_once get_plugin_file_path( 'lib/phpqrcode/qrlib.php' ); } } /** * @see HasActions */ public function get_actions() { return [ 'init' => [ 'add_rewrite_rule' ], 'woocommerce_init' => [ 'hook_display_qr_code' ], 'template_redirect' => [ 'return_qr_code' ], ]; } /** * @see HasFilters */ public function get_filters() { return [ 'query_vars' => [ 'add_query_var' ], ]; } /** * Create rewrite rule for QR code. * * @return void */ public function add_rewrite_rule() { add_rewrite_rule( 'qr/(.*)[/]?$', 'index.php?empire_artist_qr=$matches[1]', 'top' ); } /** * Add query var for QR code. * * @return void */ public function add_query_var( array $query_vars ) { $query_vars[] = 'empire_artist_qr'; return $query_vars; } /** * Track user registration. * * @param int $user_id User ID. * * @return void */ public function return_qr_code() { global $wp_query; $username = get_query_var( 'empire_artist_qr', false ); if ( $username === false ) { return; } $user = get_user_by( 'login', urldecode( $username ) ); if ( ! $user ) { status_header( 404 ); $wp_query->set_404(); return; } $url = get_referral_link( $user ); if ( ! $url ) { status_header( 404 ); $wp_query->set_404(); return; } header( 'Pragma: public' ); header( 'Cache-Control: max-age=86400' ); header( 'Expires: ' . gmdate( 'D, d M Y H:i:s \G\M\T', time() + 86400 ) ); QRcode::png( $url, false, QR_ECLEVEL_L, 16 ); exit; } /** * Hook QR code display based on plugin settings. * * @return void */ public function hook_display_qr_code() { $hook = ( '2' === get_option( 'rs_display_generate_referral' ) ) ? 'woocommerce_after_my_account' : 'woocommerce_before_my_account'; add_action( $hook, [ $this, 'display_qr_code' ], 11 ); } /** * Display QR code on account page. * * Re-implements conditions used for displaying the static referral link * table, so that if it is not displayed, the QR code is not displayed. * * @return void */ public function display_qr_code() { $user = wp_get_current_user(); if ( 'yes' !== get_option( 'rs_reward_content' ) ) { return; } if ( '2' === get_option( 'rs_show_hide_generate_referral' ) ) { return; } if ( in_array( check_banning_type( $user->ID ), [ 'earningonly', 'both' ] ) ) { return; } if ( ! check_if_referral_is_restricted() ) { return; } if ( ! check_if_referral_is_restricted_based_on_history() ) { return; } if ( ! check_referral_count_if_exist( $user->ID ) ) { return; } printf( '<img src="%s" alt="QR code for your referral link." width="128" height="128">', esc_url( get_referral_qr_url( $user ) ) ); } }
JavaScript
UTF-8
2,709
3.859375
4
[]
no_license
//Vous demandez au client le type de Jeep // Sport 33290$ // SportS 37240$ // Havane 39235). // Vous demandez ensuite le terme (24, 48, 60 ou 84) mois. // Vous demandez la couleur, si c’est rouge ou vert, ajoutez 1399$ au prix du véhicule. // Vous demandez si la transmission est manuelle (0$), automatique (1500$) ou automatique 8 vitesses (2400$). // Calculez une taxe de 15%. // Le taux d’intérêt est toujours 0% // Affichez le paiement mensuel incluant la taxe et un résumé de la transaction. //Choix du modèle ------------------------------------------------------------------------------------------------------------------------- let typejeep = prompt("Veuillez choisir le type de Jeep entre Sport, Sport S et Havane."); let prixmodele; if (typejeep === "Sport"){ prixmodele = 33290; } else if (typejeep === "Sport S"){ prixmodele = 37240; } else if (typejeep === "havane"){ prixmodele = 39235; } //Choix du terme -------------------------------------------------------------------------------------------------------------------------- let terme = Number(prompt("Veuillez choisir le terme entre 24, 28, 60 ou 84 mois.")); //Choix de la couleur --------------------------------------------------------------------------------------------------------------------- let prixcouleur = prompt("Veuillez choisir la couleur de votre Jeep. Les couleurs vert et rouge ajoutent 1399$ au prix du véhicule."); if (prixcouleur === "rouge" || "vert"){ prixcouleur === 1399; } else { prixcouleur === 0 } //Choix de la transmission ---------------------------------------------------------------------------------------------------------------- let prixtransmission = prompt("Choisissez entre une transmission manuelle (0$), une transmission automatique (1500$) ou une transmission automatique 8 vitesses (2400$)."); if (prixtransmission === "automatique"){ prixtransmission === 1500; } else if (prixtransmission === "automatique 8 vitesses"){ prixtransmission === 2400; } else { prixtransmission === 0; } //Calcul du prix brut --------------------------------------------------------------------------------------------------------------------- let prixbrut = (prixmodele + prixcouleur + prixtransmission); //Calcul du prix net ---------------------------------------------------------------------------------------------------------------------- let prixnet = (prixbrut * .15); //Calcul des paiements mensuels ---------------------------------------------------------------------------------------------------------- let paiementmensuel = (prixnet/terme); document.write ("Le Jeep que vous avez configué vous coutera " + paiementmensuel + " $ par mois.");
C++
UTF-8
1,373
3.59375
4
[]
no_license
#include <iostream> #include <string> using namespace std; class User { public: void setfName(string fName) { f_name = fName; } string getfName() { return f_name; } void setlName(string lName) { l_name = lName; } string getlName() { return l_name; } void setID(int ID1) { ID = ID1; } int getID() { return ID; } void displayInfo(string info, string info2, int i) { cout << "The first name is " << f_name << endl; cout << "The Last name is " << l_name << endl; cout << "The ID number is " << ID << endl; } private: string f_name; string l_name; int ID; }; class student : public User { public: void studentMessage() { cout << "student class Success" << endl; } }; class instructor : public User { public: void instructorMessage() { cout << "instructor class Success" << endl; } }; class admin : public User { public: void adminMessage() { cout << "admin class Success" << endl; } }; int main() { User user1; student student1; instructor instructor1; admin admin1; user1.setfName("Gary"); user1.setlName("Williams"); user1.setID(8189); user1.displayInfo(user1.getfName(), user1.getlName(), user1.getID()); student1.studentMessage(); instructor1.instructorMessage(); admin1.adminMessage(); }
C#
UTF-8
1,629
3.109375
3
[]
no_license
using System; namespace NeuralNetwork.Matrix { public class MatrixMath { public static Matrix Add(Matrix a, Matrix b) { throw new NotImplementedException(); } public static void Copy(Matrix source, Matrix target) { throw new NotImplementedException(); } public static Matrix DeleteCol(Matrix matrix, int deleted) { throw new NotImplementedException(); } public static Matrix DeleteRow(Matrix matrix, int deleted) { throw new NotImplementedException(); } public static Matrix Divide(Matrix a, Matrix b) { throw new NotImplementedException(); } public static double DotProduct(Matrix a, Matrix b) { throw new NotImplementedException(); } public static Matrix Identity(int size) { throw new NotImplementedException(); } public static Matrix Multiply(Matrix a, double b) { throw new NotImplementedException(); } public static Matrix Multiply(Matrix a, Matrix b) { throw new NotImplementedException(); } public static Matrix Substract(Matrix a, Matrix b) { throw new NotImplementedException(); } public static Matrix Transpose(Matrix input) { throw new NotImplementedException(); } public static double VectorLength(Matrix input) { throw new NotImplementedException(); } } }
Java
UTF-8
402
3.53125
4
[]
no_license
//inner class interface Annoyinner1 { void eat(); } //child class class fruits1 { public static void main(String[] args) { //created method Annoyinner1 obj = new Annoyinner1() { //refer to parent class object public void eat() { System.out.println("ORANGES"); } }; //calling method obj.eat(); } }
Python
UTF-8
529
3
3
[ "BSD-2-Clause" ]
permissive
# -*- coding: utf-8 -*- # Original project https://github.com/zacharyvoase/slugify """A generic slugifier utility (currently only for Latin-based scripts).""" import re import unicodedata __version__ = '0.0.1' def slugify(string): """ Slugify a unicode string. Example: >>> slugify(u"Héllø Wörld") u"hello-world" """ return re.sub(r'[-\s]+', '_', re.sub(r'[^\._\w\s-]', '', unicodedata.normalize('NFKD', string).encode('ascii', 'ignore').decode("ascii")).strip().lower())
C++
UTF-8
3,212
2.578125
3
[]
no_license
#include "precomp.h" #include "audiomenu.h" #define AUDIOMENU_MUSICONOFF 0 #define AUDIOMENU_MUSICVOLUME 1 #define AUDIOMENU_SOUNDONOFF 2 #define AUDIOMENU_SOUNDVOLUME 3 AudioMenu::AudioMenu() : Menu(MenuId::AudioMenu, "Audio") { _items.push_back(MenuItem(AUDIOMENU_MUSICONOFF, "")); _items.push_back(MenuItem(AUDIOMENU_MUSICVOLUME, "")); _items.push_back(MenuItem(AUDIOMENU_SOUNDONOFF, "")); _items.push_back(MenuItem(AUDIOMENU_SOUNDVOLUME, "")); UpdateMenuText(); _colorTable.push_back(XMFLOAT4(Colors::Yellow)); _colorTable.push_back(XMFLOAT4(Colors::Red)); } void AudioMenu::OnSelected(_In_ MenuItem item) { Config config = ConfigDuplicate(); switch(item.id) { case AUDIOMENU_MUSICONOFF: config.MusicOn = !config.MusicOn; break; case AUDIOMENU_SOUNDONOFF: config.SoundOn = !config.SoundOn; break; } ConfigApply(config); UpdateMenuText(); } void AudioMenu::OnDismiss() { GetGame().ShowMenu(MenuId::OptionsMenu); } _Use_decl_annotations_ void AudioMenu::OnRightSelected(MenuItem item) { Config config = ConfigDuplicate(); switch(item.id) { case AUDIOMENU_MUSICONOFF: config.MusicOn = !config.MusicOn; break; case AUDIOMENU_MUSICVOLUME: config.MusicVolume++; if (config.MusicVolume > MaxAudioVolume) { config.MusicVolume = MaxAudioVolume; } break; case AUDIOMENU_SOUNDONOFF: config.SoundOn = !config.SoundOn; break; case AUDIOMENU_SOUNDVOLUME: config.SoundVolume++; if (config.SoundVolume > MaxAudioVolume) { config.SoundVolume = MaxAudioVolume; } break; } ConfigApply(config); UpdateMenuText(); } _Use_decl_annotations_ void AudioMenu::OnLeftSelected(MenuItem item) { Config config = ConfigDuplicate(); switch(item.id) { case AUDIOMENU_MUSICONOFF: config.MusicOn = !config.MusicOn; break; case AUDIOMENU_MUSICVOLUME: config.MusicVolume--; if (config.MusicVolume < 0) { config.MusicVolume = 0; } break; case AUDIOMENU_SOUNDONOFF: config.SoundOn = !config.SoundOn; break; case AUDIOMENU_SOUNDVOLUME: config.SoundVolume--; if (config.SoundVolume < 0) { config.SoundVolume = 0; } break; } ConfigApply(config); UpdateMenuText(); } void AudioMenu::UpdateMenuText() { Config config = GetConfig(); _items[AUDIOMENU_MUSICONOFF].text = config.MusicOn ? "Music: \t1 On" : "Music: \t2 Off"; _items[AUDIOMENU_SOUNDONOFF].text = config.SoundOn ? "Sound: \t1 On" : "Sound: \t2 Off"; _items[AUDIOMENU_MUSICVOLUME].text = "Music Volume: \t1" + std::to_string(config.MusicVolume); _items[AUDIOMENU_MUSICVOLUME].enabled = config.MusicOn; _items[AUDIOMENU_SOUNDVOLUME].text = "Sound Volume: \t1" + std::to_string(config.SoundVolume); _items[AUDIOMENU_SOUNDVOLUME].enabled = config.SoundOn; }
Markdown
UTF-8
746
2.71875
3
[ "MIT" ]
permissive
# my-first-webpage #### This application will show the basics of HTML and the different languages we are going to be learning. #### By Jesse White, Nick Reeder, and Eric Roragen-Eggers ## Technologies Used * _HTML_ * _CSS_ * _VS Code_ ## Description This is the first web page that we created in class and have been updating as we progress through the program. I do not know what else to write sinse there is really nothing on the page to talk about. ## Setup/Installation Requirements * _Open the application in your browser to view the content_ * _No other requirments needed for the program to run_ ## Known Bugs * _It is crap_ * _Please do not hurt me_ ## License _.MIT soon to come._ ## Contact Information _Jesse White - jesse.white6@gmail.com_, _Nick Reeder - nickreeder32@gmail.com_, Eric Roragen-Eggers - Eric.D.Eggers@Gmail.com
TypeScript
UTF-8
1,308
2.609375
3
[]
no_license
import logger from "redux-logger"; import reduxThunk from "redux-thunk"; import { state } from "./utility"; import { applyMiddleware, Store, createStore, compose } from "redux"; const saveToLocalStorage = (state: any) => { try { const serializedState = JSON.stringify(state); localStorage.setItem("state", serializedState); } catch (e) { console.log(e); } }; const loadFromLocalStorage = () => { try { const serializedState = localStorage.getItem("state"); if (serializedState === null) { return undefined; } return JSON.parse(serializedState); } catch (e) { console.log(e); return undefined; } }; //this is how we actually build the store //you really shouldn't ever have to change this file const a: any = window; //if they have devtools installed, let them be used //otherwise use the default from redux const composeEnhancers = a.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; const enhancer = composeEnhancers( applyMiddleware(reduxThunk, logger) //exists in dispatch step ); const persistedState = loadFromLocalStorage(); //this will be the store object that we use to give data to our components export const store: Store<any> = createStore(state, persistedState, enhancer); store.subscribe(() => saveToLocalStorage(store.getState()));
Python
UTF-8
759
2.9375
3
[]
no_license
''' Using python's request library, retrieve the HTML of the website you created that now lives online at <your-gh-username>.github.io/<your-repo-name> BONUS: extend your python program so that it reads your original HTML file and returns True if the HTML from the response is the same as the the contents of the original HTML file. <<<<<<< HEAD ''' # from requests_html import HTMLSession import requests_html url = "https://arnobali.github.io/food_menus_Outpost_Ubud/" session = requests_html.HTMLSession() r = session.get(url) # r.html.render() # for link in r.html.absolute_links: # print(link) a = r.html.html with open('outpost_food.html', 'r', encoding='utf-8') as fin: if fin.read() == a: print(True) # print(a)
Java
UTF-8
2,024
2.46875
2
[ "ISC" ]
permissive
/** * SPDX-License-Identifier: ISC * Copyright © 2014-2019 Bitmark. All rights reserved. * Use of this source code is governed by an ISC * license that can be found in the LICENSE file. */ package com.bitmark.cryptography.crypto.key; import com.bitmark.cryptography.crypto.Box; import java.util.Objects; import static com.bitmark.cryptography.crypto.Box.PRIVATE_KEY_BYTE_LENGTH; import static com.bitmark.cryptography.crypto.Box.PUB_KEY_BYTE_LENGTH; public class BoxKeyPair implements KeyPair { private final byte[] publicKey; private final byte[] privateKey; public static BoxKeyPair from(byte[] publicKey, byte[] privateKey) { return new BoxKeyPair(publicKey, privateKey); } protected BoxKeyPair(byte[] publicKey, byte[] privateKey) { this.publicKey = publicKey; this.privateKey = privateKey; } @Override public PublicKey publicKey() { return PublicKey.from(publicKey); } @Override public PrivateKey privateKey() { return PrivateKey.from(privateKey); } @Override public boolean isValid() { boolean isValidLength = publicKey.length == PUB_KEY_BYTE_LENGTH && privateKey.length == PRIVATE_KEY_BYTE_LENGTH; if (!isValidLength) { return false; } final KeyPair receiver = Box.generateKeyPair(); final byte[] messageSent = new byte[]{0x7F}; final byte[] nonce = new byte[Box.NONCE_BYTE_LENGTH]; final byte[] cipher = Box.box( messageSent, nonce, receiver.publicKey().toBytes(), privateKey ); final byte[] messageReceived = Box.unbox( cipher, nonce, publicKey, receiver.privateKey().toBytes() ); return Objects.deepEquals(messageSent, messageReceived); } }
JavaScript
UTF-8
498
3.625
4
[]
no_license
const events = require('events'); const util = require('util'); let Person = function (name) { this.name = name; } util.inherits(Person, events.EventEmitter); let james = new Person('James'); let mary = new Person('Mary'); let ryu = new Person('Ryu'); let people = [james, mary, ryu]; people.forEach(function (person) { person.on('speak', function (msg) { console.log(person.name + ' said: ' + msg); }); }); james.emit('speak', 'hey dudes'); ryu.emit('speak', 'hello all');
Markdown
UTF-8
600
2.53125
3
[]
no_license
## scpf - Copy folders over ssh like a crazy maniac. >Copying files from server to client in *nix is often done with scp or sftp. > >However most ppl knows that if they are going to download the whole webfolder it would take about 1 hour ++ > > This is what i aim to solve with scpf > ### Requirements ### * Bash * openssh client * tar ### Installation ### ``` bash git clone https://bitbucket.org/dm0nk/scpf /tmp/scpf cp /tmp/scpf/scpf /usr/local/bin/scpf chmod +x /usr/local/bin/scpf ``` ### Usage ### ``` bash scpf user@host.tcl /fullPath/To/RemoteDirectory /fullPath/To/LocalDirectory ```
C++
UTF-8
825
2.796875
3
[ "MIT" ]
permissive
#include <bits/stdc++.h> using namespace std; int main() { vector<int> nums = {0,1,0,3,12}; vector<int>temp; //temp. int cntInd = 0; for(auto i : nums) { if(i != 0) { cntInd++; temp.push_back(i); } //else } //cout<<" cntInd "<<cntInd<<" nums.size "<<nums.size()<<endl; for(int i = cntInd; i<nums.size(); i++) { temp.push_back(0); } // for(int i = 0 ; i < nums.size(); i++) // { // cout<<temp[i]<<" "; // } // for(int i = 0 ; i < nums.size(); i++) // { // cout<<nums[i]<<" "; // } for(int i = 0 ; i < nums.size(); i++) { nums[i] = temp[i]; } // for(int i = 0 ; i < nums.size(); i++) // { // cout<<nums[i]<<" "; // } }
Markdown
UTF-8
2,082
3.34375
3
[]
no_license
--- title: JQuery-03事件绑定与插件 date: 2019-10-27 22:06:15 tags: - JQuery categories: - 前端 - JQuery --- <center> 引言: JQuery的事件绑定与插件 </center> <!--more--> ----- # 事件绑定 1. JQuery标准的绑定方式 `jqObj.事件方法(回调函数)` ```js //鼠标点击,进入,离开,可以链式编程 $("button").click(function () { alert(1); }).mouseover(function () { alert("鼠标来了"); }).mouseleave(function () { alert("鼠标离开"); }) $("#input1").focus(); //让文本输入框获得焦点 $("#form1").submit(); //会让表单提交 ``` 2. on绑定事件/off解除绑定 `jqObj.on("事件名称",回调函数)` `jqObj.off("事件名称")` ```js $("button:eq(0)").on("click",function () { alert("我被点击了"); //点击后取消他的点击事件 $("button:eq(0)").off("click"); //不传递参数会将组件上的所有事件全部解绑 }) ``` 3. 事件切换:toggle > **1.9版本后移除**,可以使用插件`migrate`来恢复此功能 `jqObj.toggle(fn1,fn2...)`点击第一下执行fn1,第二下点fn2 ```js $("button").toggle(function () { alert(1); },function () { alert(2); }) //重复点击会来回切换fn1和fn2 ``` # 插件 增强JQuery功能 ,jQuery提供了两种插件的方式 1. `$.fn.extend(obj)`对象级别插件 增强通过jQuery获取的对象的功能 2. `$.extend(obj)`全局级别插件 增强jQuery对象自身的功能 ## 小案例 使用插件实现全选的功能 ```html <button class="button1">全选</button> <button class="button2">取消全选</button> <input type="checkbox">一个 <input type="checkbox">二个 <input type="checkbox">三个 ``` ```js $.fn.extend({ check:function () { //选中所有的复选框 this.prop("checked",true); }, unCheck:function () { //取消全选 this.prop("checked",false); } }); $(".button1").click(function () { $("input[type='checkbox']").check(); }); $(".button2").click(function () { $("input[type='checkbox']").unCheck(); }) ```
Ruby
UTF-8
1,524
2.96875
3
[]
no_license
require('rspec') require('artists') require('albums') describe(Artists) do before() do Artists.clear() end describe('#name') do it("returns the name of the artist") do test_art = Artists.new("Bob") expect(test_art.name()).to(eq("Bob")) end end describe('#id') do it("returns the id of the artist") do test_art = Artists.new("Bob") expect(test_art.id()).to(eq(1)) end end describe('#cd') do it("initially returns an empty array of cd for the artist") do test_art = Artists.new("Bob") expect(test_art.cd()).to(eq([])) end end describe("#save") do it("adds a album to the array of saved artist") do test_art = Artists.new("Bob") test_art.save() expect(Artists.all()).to(eq([test_art])) end end describe(".all") do it("is empty at first") do expect(Artists.all()).to(eq([])) end end describe(".clear") do it("empties out all of the saved Artists") do Artists.new("Bob").save() Artists.clear() expect(Artists.all()).to(eq([])) end end describe(".find") do it("returns a artist by its id number") do test_art = Artists.new("Bob") test_art.save() test_art2 = Artists.new("Jane") test_art2.save() expect(Artists.find(test_art.id())).to(eq(test_art)) end end describe("#add_cd") do it('adds a new vehicle to the dealership') do test_art = Artists.new("Getro") test_cd = Albums.new("source") test_art.add_cd(test_cd) expect(test_art.cd()).to(eq([test_cd])) end end end
JavaScript
UTF-8
3,884
2.765625
3
[]
no_license
var questions = [{ question: "1. How many teams played the 2007 T20 World Cup?", choices: ["8","10","12","14"], correctAnswer: 2 }, { question: "2. Who bowled the first ball at the inaugural T20 World Cup?", choices: ["Shaun Pollock","Makhaya Ntini","Ravi Rampaul","Morne Morkel"], correctAnswer: 0 }, { question: "3. The first T20I hundred was recorded in the first match of this World Cup. Who scored the century?", choices: ["Chris Gayle","Virender Sehwag","Imran Nazir","Suresh Raina"], correctAnswer: 0 }, { question: "4. The first T20 World Cup wicket came only in the 14th over. Who was the bowler?", choices: ["Vernon Philander","Makhaya Ntini","Ravi Rampaul","Morne Morkel"], correctAnswer: 0 }, { question: "5. India and Pakistan played the first tied game. How was the winner decided?", choices: ["Points Shared","One-Over Bowl-Out","Super Over","Toss of a Coin"], correctAnswer: 1 }, { question: "6. Who was the leading wicket-taker in the 2007 T20 World Cup?", choices: ["RP Singh","Shaun Pollock","Shahid Afridi","Umar Gul"], correctAnswer: 3 }, { question: "7. Name the batsman who scored the most runs in the tournament.", choices: ["Matthew Hayden","Yuvraj Singh","Misbah-ul-Haq","Kevin Pietersen"], correctAnswer: 0 }, { question: "8. Ashraful made 61 off 27 balls in Bangladesh's win v West Indies. What was special about the knock?", choices: ["First Half-Century of the T20 WC","Fastest T20I Fifty at the time","Included five sixex in a row","Had only sixex,no fours"], correctAnswer: 1 }, { question: "9. Who was the Player of the Match in Zimbabwe's thrilling win over Australia?", choices: ["Gary Brent","Brendan Taylor","Hamilton Masakadza","Elton Chigumbura"], correctAnswer: 1 }, { question: "10. Which match witnessed the highest margin of victory – a record that stood until 2019?", choices: ["Sri Lanka v Kenya","England v Australia","India v Scotland","South Africa v West Indies"], correctAnswer: 0 }]; var currentQuestion = 0; var correctAnswer = 0; var quizOver = false; $(document).ready(function () { displayCurrentQuestion(); $(this).find(".quizMessage").hide(); $(this).find(".nextButton").on("click", function(){ if(!quizOver){ value = $("input[type='radio']:checked").val(); if(value == undefined){ $(document).find(".quizMessage").text("Please Select an Answer"); $(document).find(".quizMessage").show(); } else { $(document).find(".quizMessage").hide(); if(value == questions[currentQuestion].correctAnswer){ correctAnswer++; } currentQuestion++; if(currentQuestion < questions.length){ displayCurrentQuestion(); } else{ displayScore(); $(document).find(".nextButton").text("Play Again"); quizOver = true; } } } else{ quizOver = false; $(document).find(".nextButton").text("Next Question"); resetQuiz(); displayCurrentQuestion(); hideScore(); } }); }); function displayCurrentQuestion() { console.log("In display current question"); var question = questions[currentQuestion].question; var questionClass = $(document).find(".quizContainer > .question"); var choiceList = $(document).find(".quizContainer > .choiceList"); var numChoices = questions[currentQuestion].choices.length; $(questionClass).text(question); $(choiceList).find("li").remove(); var choice; for(i=0; i < numChoices; i++){ choice = questions[currentQuestion].choices[i]; $('<li><input type="radio" value=' + i + ' name="dynradio" />' + choice + '</li>' ).appendTo(choiceList); } } function resetQuiz() { currentQuestion = 0; correctAnswer = 0; hideScore(); } function displayScore(){ $(document).find(".quizContainer > .result").text("You Scored: " + correctAnswer + " out of: " + questions.length); $(document).find(".quizContainer > .result").show(); } function hideScore() { $(document).find(".result").hide(); }
TypeScript
UTF-8
560
3.203125
3
[ "MIT" ]
permissive
/*! * Determine if an element is in the viewport * (c) 2017 Chris Ferdinandi, MIT License, https://gomakethings.com * @param {Node} elem The element * @return {Boolean} Returns true if element is in the viewport */ export const isInViewport = (elem) => { const distance = elem.getBoundingClientRect(); return ( distance.top >= 0 && distance.left >= 0 && distance.bottom <= (window.innerHeight || document.documentElement.clientHeight) && distance.right <= (window.innerWidth || document.documentElement.clientWidth) ); };
PHP
UTF-8
1,383
2.953125
3
[]
no_license
<?php namespace Utils; class Criterio { public $coluna; public $operacao; public $valor; public $colunapropriedade; public $valorpropriedade; public $juncao; public $condicaojuncao; public function Or($coluna, $operacao, $valor, $colunapropriedade = true, $valorpropriedade = false){ return $this->Juncao('OR', $coluna, $operacao, $valor, $colunapropriedade, $valorpropriedade); } public function And($coluna, $operacao, $valor, $colunapropriedade = true, $valorpropriedade = false){ return $this->Juncao('AND', $coluna, $operacao, $valor, $colunapropriedade, $valorpropriedade); } public function Juncao($juncao, $coluna, $operacao, $valor, $colunapropriedade = true, $valorpropriedade = false){ $this->juncao = $juncao; $this->condicaojuncao = Criterio::Condicao($coluna, $operacao, $valor, $colunapropriedade, $valorpropriedade); return $this->condicaojuncao; } public static function Condicao($coluna, $operacao, $valor, $colunapropriedade = true, $valorpropriedade = false){ $criterio = new Criterio(); $criterio->coluna = $coluna; $criterio->operacao = $operacao; $criterio->valor = $valor; $criterio->colunapropriedade = $colunapropriedade; $criterio->valorpropriedade = $valorpropriedade; return $criterio; } }
Java
UTF-8
262
2.71875
3
[]
no_license
public class Grub extends Creature { public Grub(Animation left, Animation right, Animation deadLeft, Animation deadRight) { super(left, right, deadLeft, deadRight); } public float getMaxSpeed() { return 0.05f; } }
C
UTF-8
2,487
2.53125
3
[]
no_license
/* * MRMGenParams.h * * INTEL CORPORATION PROPRIETARY INFORMATION * This software is supplied under the terms of a license agreement or * nondisclosure agreement with Intel Corporation and may not be copied * or disclosed except in accordance with the terms of that agreement. * * Copyright (c) 1998 Intel Corporation. All Rights Reserved. * * */ #ifndef MRMGENPARAMS_DOT_H #define MRMGENPARAMS_DOT_H // parameter valid flags #define MRMGP_ALL 0xffffffff #define MRMGP_MERGETHRESH 0x00000001 #define MRMGP_MERGEWITHIN 0x00000002 #define MRMGP_PROGRESSCALLBACK 0x00000004 #define MRMGP_PROGRESSFREQUENCY 0x00000008 #define MRMGP_NUMBASEVERTICES 0x00000010 // if this is valid then baseVertices is valid #define MRMGP_METRIC 0x00000020 #define MRMGP_METRIC2 0x00000040 // if this is valid then metric2Start is valid #define MRMGP_NORMALSMODE 0x00000080 #define MRMGP_CREASEANGLE 0x00000100 extern "C" { typedef enum _MRMG_METRIC { HYBRID0, HYBRID1, HYBRID2, HYBRID3 } MRMG_METRIC; typedef void (* MRMG_PROGRESSCALLBACK) (int pairsRemaining); typedef enum {PerVertex, PerFacePerVertex,} NormalsMode; typedef struct MRMGENPARAMS_TAG { unsigned long size; // size of MRMGenParams; unsigned long flags; // indicates which fields are valid. float mergeThresh; // Vertices within this distance of each other are allowed to merge even if not connected by edges. unsigned long mergeWithin; // This allows vertices within the same object to merge, default behavior is to only merge across objects. MRMG_PROGRESSCALLBACK progressCallback;// this will be called after progressFrequency unsigned long progressFrequency; // number of edge removals per call back, first callback occurs at 0. unsigned long numBaseVertices; // number entries in the baseVertices array. unsigned long *baseVertices; // array of vertex indicies. Indicates vertices that should be removed last. MRMG_METRIC metric; // this metric always starts with first vertex removed MRMG_METRIC metric2; unsigned long metric2Start; // which vertex deletion should trigger switch to metric2. NormalsMode normalsMode; // Indicates how normals should be maintained and updated. float normalsCreaseAngle; // If PerFacePerVertex normals are used, normalCreaseAngle indicates // a angle (deg) threshold for sharing a vertex normal b/t two faces. } MRMGenParams;; } #endif
JavaScript
UTF-8
883
2.671875
3
[]
no_license
import {useState} from 'react'; import Visualization from './Visualization' import * as htmlToImage from 'html-to-image'; const HtmlToImage = ({data, saveAs, }) =>{ const [time, setTime] = useState(0) const exportAsPicture = () => { var t0 = performance.now() var data = document.getElementsByClassName('htmlToImageVis') for (var i = 0; i < data.length; ++i){ htmlToImage.toPng(data[i]).then((dataUrl) => { saveAs(dataUrl, 'my-node.png'); }); } var t1 = performance.now() var t = t1 - t0 setTime(t.toFixed(3)) } return <div> <h1>HTML TO IMAGE</h1> {data.map(vis=>{ return <Visualization visualization={vis} className="htmlToImageVis"/> })} <button onClick={exportAsPicture}>capture</button> <p>TOTAL TIME: {time} ms</p> </div> }; export default HtmlToImage;
JavaScript
UTF-8
616
3.671875
4
[]
no_license
console.log("prototype"); function Parents(name) { this.name = name; } Parents.prototype.sayName = function() { console.log(`sayName: ${this.name}`); }; Parents.prototype.doSomthing = function() { console.log(`doSomthings: ${this.name}`); }; function Child(name, parentName) { Parents.call(this, parentName); this.name = name; } function f() {} f.prototype = Parents.prototype; Child.prototype = new f(); Child.prototype.sayName = function() { console.log(`child sayName: ${this.name}`); }; const child = new Child("son", "parents"); child.sayName(); child.doSomthing();
Java
UTF-8
5,130
2.390625
2
[]
no_license
package Controleurs; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import GestionnairesMetier.GestionnaireDemande; import Metier.Demande; import Models.ModelDemande; import Utils.Help; import Vues.VueConsulterDemandeCitoyen; import Vues.VueInfoProc; import Vues.VueUploadDocument; public class ControleurConsulterDemande { private VueConsulterDemandeCitoyen vueConsulter; private Demande dem; private VueUploadDocument vueMAj; public ControleurConsulterDemande(Demande dem) { this.dem = dem; vueConsulter = new VueConsulterDemandeCitoyen(this); setVue(); vueConsulter.setVisible(true); } private void setVue() { vueConsulter.getLibelleProc().setText(dem.getNomProc()); vueConsulter.getTxtDateDepot().setText(dem.getDateDepo().toString()); vueConsulter.getEtat().setValue(valueSlider(dem.getId_proc(), dem.getIdEtapeActuel())); if(dem.getEtat().equals("validee")) { vueConsulter.getEtat().setValue(100); vueConsulter.getEtatFinal().setText("Demande accepter"); }else if(dem.getEtat().equals("rejetee")){ vueConsulter.getEtatFinal().setText("Demande rejetee"); vueConsulter.getEtpactuel().setText("Rejette"); }else if(dem.getEtat().equals("en cours de traitement")) { vueConsulter.getEtpactuel().setText("En cours de traitement"); vueConsulter.getEtatFinal().setText("En cours de traitement"); }else if(dem.getEtat().equals("mise a jour")) { vueConsulter.getEtpactuel().setText("Mise a jour"); vueConsulter.getEtatFinal().setText("En cours de traitement"); vueConsulter.getInfo().setEnabled(true); vueConsulter.getMaj().setEnabled(true); } } public void showVueInfo() { VueInfoProc vue = new VueInfoProc(GestionnaireDemande.infoMaj(dem.getJeton(), dem.getIdEtapeActuel())); vue.getLbl().setText("information des documents necessaires"); vue.setVisible(true); } public void showVueMaj() { vueMAj = new VueUploadDocument("", "", this); vueMAj.getText().setText("Importer les documents necessaires pour la mise a jour"); vueMAj.setVisible(true); } public void deleteDoc(int row) { ModelDemande model = (ModelDemande) vueMAj.getFiles().getModel(); model.removeDoc(row); } public void addDoc() { ModelDemande model = (ModelDemande) vueMAj.getFiles().getModel(); JFileChooser chooser = new JFileChooser(); chooser.showOpenDialog(null); File f = chooser.getSelectedFile(); if(f!= null) { String[] file = new String[2]; file[1] = f.getAbsolutePath(); file[0] = f.getName(); model.addDoc(file); } } public void miseAJour() { ModelDemande model = (ModelDemande) vueMAj.getFiles().getModel(); int count = model.getRowCount(); int nbDoc = GestionnaireDemande.infoMaj(dem.getJeton(), dem.getIdEtapeActuel()).size(); if(count<nbDoc) { JOptionPane.showMessageDialog(null,"Il vous manque certains documents :\n veuillez reessayer:","Warning",JOptionPane.WARNING_MESSAGE); }else if(count>nbDoc) { JOptionPane.showMessageDialog(null,"vous avez ajouter plusieurs documents :\n veuillez reessayer:","Warning",JOptionPane.WARNING_MESSAGE); }else { ArrayList<String> paths =createRepDocument(dem.getJeton(),String.valueOf(dem.getIdEtapeActuel())); if(paths ==null) JOptionPane.showMessageDialog(null, "Erreur lors de l'importation des documents \n veuillez ressayer","Erreur",JOptionPane.ERROR_MESSAGE); else { if(GestionnaireDemande.majDemande(paths, dem.getJeton(), dem.getIdEtapeActuel())) { JOptionPane.showMessageDialog(null, "Mise a jour effectuer avec succes","succes",JOptionPane.INFORMATION_MESSAGE); vueConsulter.getEtpactuel().setText("en cours de traitement"); vueConsulter.getInfo().setEnabled(false); vueConsulter.getMaj().setEnabled(false); vueMAj.dispose(); vueConsulter.getPanel().repaint(); }else { JOptionPane.showMessageDialog(null, "Erreur veuillez ressayer","Erreur",JOptionPane.ERROR_MESSAGE); Help.deleteRep(new File("../Demandes/" + dem.getJeton() +"/" + String.valueOf(dem.getIdEtapeActuel()))); } } } } private int valueSlider(int idProc,int idEtape) { ArrayList<Integer> list = Help.getIdEtapes(idProc); for(int i=0; i<list.size();i++) { if(list.get(i) == idEtape){ return (int)Help.percent(i, list.size()); } } return -1; } private ArrayList<String> createRepDocument(String jeton,String id) { ArrayList<String> paths = new ArrayList<String>(); ModelDemande model = (ModelDemande) vueMAj.getFiles().getModel(); ArrayList<String[]> listModel = model.getListDoc(); String path = "../Demandes/" +jeton + "/" + id + "/"; File dir = new File(path); dir.mkdir(); for(int i = 0; i< listModel.size(); i++) { try { Files.copy(Paths.get(listModel.get(i)[1]), new File(path+listModel.get(i)[0]).toPath(), StandardCopyOption.REPLACE_EXISTING); paths.add(path+listModel.get(i)[0]); }catch(Exception e) { e.printStackTrace(); return null; } } return paths; } }
C++
UTF-8
14,884
3.25
3
[ "MIT" ]
permissive
#ifndef SQL_EXPRESSIONS #define SQL_EXPRESSIONS #include "MyDB_AttType.h" #include "MyDB_Catalog.h" #include <unordered_map> #include <string> #include <vector> // create a smart pointer for database tables using namespace std; class ExprTree; typedef shared_ptr <ExprTree> ExprTreePtr; enum Type {BOOL_TYPE, NUMERIC_TYPE, STRING_TYPE, TERMINAL }; // this class encapsules a parsed SQL expression (such as "this.that > 34.5 AND 4 = 5") // class ExprTree is a pure virtual class... the various classes that implement it are below class ExprTree { public: virtual string toString () = 0; virtual ~ExprTree () {} virtual Type getType() = 0; virtual bool validCheck(MyDB_CatalogPtr myCatalog, unordered_map<string, string>& alisaTableMap) { return true; }; }; class BoolLiteral : public ExprTree { private: bool myVal; public: BoolLiteral (bool fromMe) { myVal = fromMe; } string toString () { if (myVal) { return "bool[true]"; } else { return "bool[false]"; } } Type getType(){ return Type::BOOL_TYPE; } }; class DoubleLiteral : public ExprTree { private: double myVal; public: DoubleLiteral (double fromMe) { myVal = fromMe; } string toString () { return "double[" + to_string (myVal) + "]"; } ~DoubleLiteral () {} Type getType(){ return Type::NUMERIC_TYPE; } }; // this implement class ExprTree class IntLiteral : public ExprTree { private: int myVal; public: IntLiteral (int fromMe) { myVal = fromMe; } string toString () { return "int[" + to_string (myVal) + "]"; } ~IntLiteral () {} Type getType(){ return Type::NUMERIC_TYPE; } }; class StringLiteral : public ExprTree { private: string myVal; public: StringLiteral (char *fromMe) { fromMe[strlen (fromMe) - 1] = 0; myVal = string (fromMe + 1); } string toString () { return "string[" + myVal + "]"; } ~StringLiteral () {} Type getType(){ return Type::STRING_TYPE; } }; class Identifier : public ExprTree { private: string tableName; string attName; Type type; public: Identifier (char *tableNameIn, char *attNameIn) { tableName = string (tableNameIn); attName = string (attNameIn); type = Type::TERMINAL; } string toString () { return "[" + tableName + "_" + attName + "]"; } ~Identifier () {} Type getType(){ return type; } bool validCheck(MyDB_CatalogPtr myCatalog, unordered_map<string, string>& alisaTableMap){ //check whether the alias exists or not if(alisaTableMap.find(tableName) == alisaTableMap.end()){ cout << "Error: This alias: " << tableName << " for attribute:" << attName << " is not recorded." << endl; return false; } //if yes, get the original name of the table string tableOriginName = alisaTableMap[tableName]; string attType; //check whether the attribute exists in the table above bool found = myCatalog->getString(tableOriginName + "." + attName + ".type", attType); if(!found){ cout << "Error: The attribute " << attName << "doesn't exist in table " << tableOriginName << endl; return false; } else{ if(attType.compare("int") == 0 || attType.compare("double") == 0){ type = Type::NUMERIC_TYPE; } else if(attType.compare("string") == 0){ type = Type::STRING_TYPE; } else{ type = Type::BOOL_TYPE; } } return true; } }; class MinusOp : public ExprTree { private: ExprTreePtr lhs; ExprTreePtr rhs; public: MinusOp (ExprTreePtr lhsIn, ExprTreePtr rhsIn) { lhs = lhsIn; rhs = rhsIn; } string toString () { return "- (" + lhs->toString () + ", " + rhs->toString () + ")"; } Type getType(){ return Type::NUMERIC_TYPE; } ~MinusOp () {} bool validCheck(MyDB_CatalogPtr myCatalog, unordered_map<string, string>& alisaTableMap){ //both lhs and rhs should be valid if(!lhs->validCheck(myCatalog,alisaTableMap) || !rhs->validCheck(myCatalog,alisaTableMap)){ return false; } //lhs shoube be of type numeric if(lhs->getType() != Type::NUMERIC_TYPE){ cout << "Error: Minus Opeartion - The left hand side (" << lhs->toString() << ") is not Numeric Type" << endl; return false; } //rhs shoube be of type numeric if(rhs->getType() != Type::NUMERIC_TYPE){ cout << "Error: Minus Opeartion - The right hand side (" << rhs->toString() <<") is not Numeric Type" << endl; return false; } return true; } }; class PlusOp : public ExprTree { private: ExprTreePtr lhs; ExprTreePtr rhs; Type type; public: PlusOp (ExprTreePtr lhsIn, ExprTreePtr rhsIn) { lhs = lhsIn; rhs = rhsIn; type = NUMERIC_TYPE; } string toString () { return "+ (" + lhs->toString () + ", " + rhs->toString () + ")"; } ~PlusOp () {} Type getType(){ return type; } bool validCheck(MyDB_CatalogPtr myCatalog, unordered_map<string, string>& alisaTableMap){ //both lhs and rhs should be valid if(!lhs->validCheck(myCatalog,alisaTableMap) || !rhs->validCheck(myCatalog,alisaTableMap)){ return false; } if(lhs->getType() != rhs->getType()){ cout << "Error: Plus Operation - The type of left hand side(" << lhs->toString() << ") and the type of right hand side(" << rhs->toString() + ") is not the same." << endl; return false; } if(lhs->getType() == Type::BOOL_TYPE){ cout << "Error: Plus Operation - Boolean Type is not allowed in plus Operation." << endl; return false; } else if(lhs->getType() == Type::STRING_TYPE){ type = Type::STRING_TYPE; return true; } else if(lhs->getType() == Type::NUMERIC_TYPE){ type = Type::NUMERIC_TYPE; return true; } } }; class TimesOp : public ExprTree { private: ExprTreePtr lhs; ExprTreePtr rhs; public: TimesOp (ExprTreePtr lhsIn, ExprTreePtr rhsIn) { lhs = lhsIn; rhs = rhsIn; } string toString () { return "* (" + lhs->toString () + ", " + rhs->toString () + ")"; } ~TimesOp () {} Type getType(){ return Type::NUMERIC_TYPE; } bool validCheck(MyDB_CatalogPtr myCatalog, unordered_map<string, string>& alisaTableMap){ //both lhs and rhs should be valid if(!lhs->validCheck(myCatalog,alisaTableMap) || !rhs->validCheck(myCatalog,alisaTableMap)){ return false; } //lhs shoube be of type numeric if(lhs->getType() != Type::NUMERIC_TYPE){ cout << "Error: Times Opeartion - The left hand side (" << lhs->toString() <<") is not Numeric Type" << endl; return false; } //rhs shoube be of type numeric if(rhs->getType() != Type::NUMERIC_TYPE){ cout << "Error: Times Opeartion - The right hand side (" << rhs->toString() <<") is not Numeric Type" << endl; return false; } return true; } }; class DivideOp : public ExprTree { private: ExprTreePtr lhs; ExprTreePtr rhs; public: DivideOp (ExprTreePtr lhsIn, ExprTreePtr rhsIn) { lhs = lhsIn; rhs = rhsIn; } string toString () { return "/ (" + lhs->toString () + ", " + rhs->toString () + ")"; } ~DivideOp () {} Type getType(){ return Type::NUMERIC_TYPE; } bool validCheck(MyDB_CatalogPtr myCatalog, unordered_map<string, string>& alisaTableMap){ //both lhs and rhs should be valid if(!lhs->validCheck(myCatalog,alisaTableMap) || !rhs->validCheck(myCatalog,alisaTableMap)){ return false; } //lhs shoube be of type numeric if(lhs->getType() != Type::NUMERIC_TYPE){ cout << "Error: Divide Opeartion - The left hand side (" << lhs->toString() <<") is not Numeric Type" << endl; return false; } //rhs shoube be of type numeric if(rhs->getType() != Type::NUMERIC_TYPE){ cout << "Error: Divide Opeartion - The right hand side (" << rhs->toString() <<") is not Numeric Type" << endl; return false; } return true; } }; class GtOp : public ExprTree { private: ExprTreePtr lhs; ExprTreePtr rhs; public: GtOp (ExprTreePtr lhsIn, ExprTreePtr rhsIn) { lhs = lhsIn; rhs = rhsIn; } string toString () { return "> (" + lhs->toString () + ", " + rhs->toString () + ")"; } ~GtOp () {} Type getType(){ return Type::BOOL_TYPE; } bool validCheck(MyDB_CatalogPtr myCatalog, unordered_map<string, string>& alisaTableMap){ //both lhs and rhs should be valid if(!lhs->validCheck(myCatalog,alisaTableMap) || !rhs->validCheck(myCatalog,alisaTableMap)){ return false; } //lhs and rhs should be of same type if(lhs->getType() != rhs->getType()){ cout << "Error: Greater Than Operation - The type of lhs hand side(" << lhs->toString() <<") is not the same as that of right hand side(" << rhs->toString() << ")." << endl; return false; } return true; } }; class LtOp : public ExprTree { private: ExprTreePtr lhs; ExprTreePtr rhs; public: LtOp (ExprTreePtr lhsIn, ExprTreePtr rhsIn) { lhs = lhsIn; rhs = rhsIn; } string toString () { return "< (" + lhs->toString () + ", " + rhs->toString () + ")"; } ~LtOp () {} Type getType(){ return Type::BOOL_TYPE; } bool validCheck(MyDB_CatalogPtr myCatalog, unordered_map<string, string>& alisaTableMap){ //both lhs and rhs should be valid if(!lhs->validCheck(myCatalog,alisaTableMap) || !rhs->validCheck(myCatalog,alisaTableMap)){ return false; } //lhs and rhs should be of same type if(lhs->getType() != rhs->getType()){ cout << "Error: Less Than Operation - The type of lhs hand side(" << lhs->toString() <<") is not the same as that of right hand side(" << rhs->toString() << ")." << endl; return false; } return true; } }; class NeqOp : public ExprTree { private: ExprTreePtr lhs; ExprTreePtr rhs; public: NeqOp (ExprTreePtr lhsIn, ExprTreePtr rhsIn) { lhs = lhsIn; rhs = rhsIn; } string toString () { return "!= (" + lhs->toString () + ", " + rhs->toString () + ")"; } ~NeqOp () {} Type getType(){ return Type::BOOL_TYPE; } bool validCheck(MyDB_CatalogPtr myCatalog, unordered_map<string, string>& alisaTableMap){ //both lhs and rhs should be valid if(!lhs->validCheck(myCatalog,alisaTableMap) || !rhs->validCheck(myCatalog,alisaTableMap)){ return false; } //lhs and rhs should be of same type if(lhs->getType() != rhs->getType()){ cout << "Error: Not Equal Operation - The type of lhs hand side(" << lhs->toString() <<") is not the same as that of right hand side(" << rhs->toString() << ")." << endl; return false; } return true; } }; class OrOp : public ExprTree { private: ExprTreePtr lhs; ExprTreePtr rhs; public: OrOp (ExprTreePtr lhsIn, ExprTreePtr rhsIn) { lhs = lhsIn; rhs = rhsIn; } string toString () { return "|| (" + lhs->toString () + ", " + rhs->toString () + ")"; } ~OrOp () {} Type getType(){ return Type::BOOL_TYPE; } bool validCheck(MyDB_CatalogPtr myCatalog, unordered_map<string, string>& alisaTableMap){ //both lhs and rhs should be valid if(!lhs->validCheck(myCatalog,alisaTableMap) || !rhs->validCheck(myCatalog,alisaTableMap)){ return false; } //lhs should be of type boolean if(lhs->getType() != Type::BOOL_TYPE){ cout << "Error: Or Operation - The type of lhs hand side(" << lhs->toString() <<") is not the type of Boolean" << endl; return false; } //lhs should be of type boolean if(rhs->getType() != Type::BOOL_TYPE){ cout << "Error: Or Operation - The type of rhs hand side(" << rhs->toString() <<") is not the type of Boolean" << endl; return false; } return true; } }; class EqOp : public ExprTree { private: ExprTreePtr lhs; ExprTreePtr rhs; public: EqOp (ExprTreePtr lhsIn, ExprTreePtr rhsIn) { lhs = lhsIn; rhs = rhsIn; } string toString () { return "== (" + lhs->toString () + ", " + rhs->toString () + ")"; } ~EqOp () {} Type getType(){ return Type::BOOL_TYPE; } bool validCheck(MyDB_CatalogPtr myCatalog, unordered_map<string, string>& alisaTableMap){ //both lhs and rhs should be valid if(!lhs->validCheck(myCatalog,alisaTableMap) || !rhs->validCheck(myCatalog,alisaTableMap)){ return false; } //lhs and rhs should be of same type if(lhs->getType() != rhs->getType()){ cout << "Error: Equal Operation - The type of lhs hand side(" << lhs->toString() +") is not the same as that of right hand side(" << rhs->toString() << ")." << endl; if(lhs->getType() == Type::BOOL_TYPE){ cout << "lhs:bool" <<endl; } else if(lhs->getType() == Type::NUMERIC_TYPE){ cout << "lhs:num" << endl; } else if(lhs->getType() == Type::STRING_TYPE){ cout << "lhs:string" << endl; } else if(lhs->getType() == Type::TERMINAL){ cout << "lhs:terminal" << endl; } if(rhs->getType() == Type::BOOL_TYPE){ cout << "rhs:bool" <<endl; } else if(rhs->getType() == Type::NUMERIC_TYPE){ cout << "rhs:num" << endl; } else if(rhs->getType() == Type::STRING_TYPE){ cout << "rhs:string" << endl; } else if(rhs->getType() == Type::TERMINAL){ cout << "rhs:terminal" << endl; } return false; } return true; } }; class NotOp : public ExprTree { private: ExprTreePtr child; public: NotOp (ExprTreePtr childIn) { child = childIn; } string toString () { return "!(" + child->toString () + ")"; } ~NotOp () {} Type getType(){ return Type::BOOL_TYPE; } bool validCheck(MyDB_CatalogPtr myCatalog, unordered_map<string, string>& alisaTableMap){ //child should be valid if(!child->validCheck(myCatalog,alisaTableMap)){ return false; } //child should be of type boolean if(child->getType() != Type::BOOL_TYPE){ cout << "Error: Not Operation - The type of child(" << child->toString() <<") is not the type of Boolean" << endl; return false; } return true; } }; class SumOp : public ExprTree { private: ExprTreePtr child; public: SumOp (ExprTreePtr childIn) { child = childIn; } string toString () { return "sum(" + child->toString () + ")"; } ~SumOp () {} Type getType(){ return Type::NUMERIC_TYPE; } bool validCheck(MyDB_CatalogPtr myCatalog, unordered_map<string, string>& alisaTableMap){ //both lhs and rhs should be valid if(!child->validCheck(myCatalog,alisaTableMap)){ return false; } //child should be of type numeric if(child->getType() != Type::NUMERIC_TYPE){ cout << "Error: Sum Operation - The type of child(" << child->toString() <<") is not the type of Numeric" << endl; return false; } return true; } }; class AvgOp : public ExprTree { private: ExprTreePtr child; public: AvgOp (ExprTreePtr childIn) { child = childIn; } string toString () { return "avg(" + child->toString () + ")"; } ~AvgOp () {} Type getType(){ return Type::NUMERIC_TYPE; } bool validCheck(MyDB_CatalogPtr myCatalog, unordered_map<string, string>& alisaTableMap){ //both lhs and rhs should be valid if(!child->validCheck(myCatalog,alisaTableMap)){ return false; } //child should be of type numeric if(child->getType() != Type::NUMERIC_TYPE){ cout << "Error: Sum Operation - The type of child(" << child->toString() <<") is not the type of Numeric" << endl; return false; } return true; } }; #endif
Markdown
UTF-8
599
2.890625
3
[]
no_license
A simple url encoder and decoder written in Python 3. ## urlencode Use it on a file: ```sh python /path/from/root/to/urlencode/dir/urlencode my_file.txt ``` Or with a pipe: ```sh pbpaste | python /path/from/root/to/urlencode/dir/urlencode ``` Install by adding ```sh export PATH="/path/from/root/to/urlencode/dir:$PATH" ``` to `~/.bash_profile` (MacOS 10.12+). Then you can run it from anywhere without including the path or invoking python directly: ```sh urlencode myfile.txt ``` ```sh echo "test" | urlencode ``` ## urldecode Same as above, but replace `urlencode` with `urldecode`.
Java
UTF-8
8,229
1.914063
2
[]
no_license
package com.coffeetime.warkop; import android.annotation.SuppressLint; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.Fragment; import android.support.v7.app.AlertDialog; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.coffeetime.R; import com.coffeetime.adapter.MenuWarkopAdapter; import com.coffeetime.model.Kopi; import com.coffeetime.model.Warkop; import com.coffeetime.networkmanager.Connection; import com.coffeetime.networkmanager.Endpoints; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.ArrayList; import java.util.List; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class MenuFragment extends Fragment { TextView namakopi, jeniskopi, hargakopi; private RecyclerView recyclerView; private MenuWarkopAdapter adapter; private List<Kopi> kopiArrayList; private FloatingActionButton tambah_menu; AlertDialog.Builder dialog; LayoutInflater inflater; View dialogView; EditText nama_kopi, harga_kopi; Spinner jenis_kopi; Endpoints endpoints; Kopi kopi; Warkop warkop; //Tes SharedPreferences sharedPreferences; SharedPreferences.Editor editor; Gson gson; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_menu_warkop, container, false); tambah_menu = view.findViewById(R.id.tambah_menu); recyclerView = view.findViewById(R.id.recyclerviewmenuwarkop); //adapter = new MenuWarkopAdapter(kopiArrayList); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity()); recyclerView.setLayoutManager(layoutManager); //recyclerView.setAdapter(adapter); sharedPreferences = getActivity().getSharedPreferences("coffee",0); editor = sharedPreferences.edit(); editor.apply(); gson = new Gson(); String json = sharedPreferences.getString("user",""); warkop = gson.fromJson(json, new TypeToken<Warkop>(){ }.getType()); tambah_menu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { DialogForm(); } }); //SERVICE loopingStart(); return view; } public void loopingStart() { final boolean keepRunning1 = true; Thread t = new Thread(){ @Override public void run(){ while(keepRunning1){ // Make the thread wait half a second. If you want... try { Thread.sleep(500); } catch (InterruptedException e) { Toast.makeText(getActivity().getApplicationContext(), "Default Signature Fail", Toast.LENGTH_LONG).show(); e.printStackTrace(); } // here you check the value of getActivity() and break up if needed if(getActivity() == null) return; getActivity().runOnUiThread(new Runnable(){ @Override public void run(){ tampildata(); // Toast.makeText(getContext(),"BERHASIL",Toast.LENGTH_SHORT).show(); } }); } } }; t.start(); } private void DialogForm() { dialog = new AlertDialog.Builder(getActivity()); inflater = getLayoutInflater(); dialogView = inflater.inflate(R.layout.form_menu, null); dialog.setView(dialogView); dialog.setCancelable(true); dialog.setIcon(R.mipmap.ic_launcher); dialog.setTitle("Form Tambah Menu"); nama_kopi = dialogView.findViewById(R.id.nama_kopi); harga_kopi = dialogView.findViewById(R.id.harga_kopi); jenis_kopi = dialogView.findViewById(R.id.listJenisKopi); dialog.setPositiveButton("SUBMIT", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { kopi = new Kopi(); kopi.setNamaKopi(nama_kopi.getText().toString()); kopi.setHargaKopi(harga_kopi.getText().toString()); kopi.setJenisKopi(jenis_kopi.getSelectedItem().toString()); kopi.setIdWarkop(warkop.getIdWarkop()); //request connection endpoints = Connection.getEndpoints(getActivity()); endpoints.aadKopi(kopi).enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { try { JSONObject jsonObject = new JSONObject(response.body().string()); if (jsonObject.getString("status").equals("sukses")) { String id_kopi = jsonObject.getString("id"); String id_warkop = warkop.getIdWarkop(); warkop.setIdKopi(id_kopi); editor.putString("id_kopi",id_kopi); String json = gson.toJson(warkop); editor.putString("id_warkop",id_warkop); editor.putString("warkop",json); editor.commit(); } } catch (JSONException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { } }); dialog.dismiss(); } }); dialog.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dialog.show(); } private void tampildata() { kopi = new Kopi(); kopi.setIdKopi(warkop.getIdKopi()); kopi.setIdWarkop(warkop.getIdWarkop()); //data kopi endpoints = Connection.getEndpoints(getActivity()); endpoints.getKopi(kopi).enqueue(new Callback<List<Kopi>>() { @Override public void onResponse(Call<List<Kopi>> call, Response<List<Kopi>> response) { if (response.body() != null){ kopiArrayList = new ArrayList<>(response.body()); //Log.i("ceksize",""+kopiArrayList); adapter = new MenuWarkopAdapter(kopiArrayList); recyclerView.setAdapter(adapter); } } @Override public void onFailure(Call<List<Kopi>> call, Throwable t) { } }); } }
Shell
UTF-8
836
2.875
3
[ "BSD-3-Clause" ]
permissive
#!/bin/sh -xe plugin=`find . -name 'eventlog.so' | head -n 1` if [ -z "$plugin" ]; then echo "Unable to find the eventlog plugin" exit 1 fi ln -fs "$srcdir/../../src/test/dns.pcap" dns.pcap-dist ln -fs "$srcdir/../../src/test/dns6.pcap" dns6.pcap-dist ln -fs "$srcdir/../../src/test/dnso1tcp.pcap" dnso1tcp.pcap-dist ../../src/dnscap -r dns.pcap-dist -g -P "$plugin" -? ../../src/dnscap -r dns.pcap-dist -g -P "$plugin" ../../src/dnscap -r dns.pcap-dist -g -P "$plugin" -o test1.out -o test1.out ../../src/dnscap -r dns.pcap-dist -g -P "$plugin" -s ../../src/dnscap -r dns.pcap-dist -g -P "$plugin" -t ../../src/dnscap -r dns.pcap-dist -g -P "$plugin" -n test ! ../../src/dnscap -r dns.pcap-dist -g -P "$plugin" -X ../../src/dnscap -r dns6.pcap-dist -g -P "$plugin" ../../src/dnscap -T -r dnso1tcp.pcap-dist -g -P "$plugin"
Markdown
UTF-8
6,708
2.875
3
[ "MIT" ]
permissive
--- layout: post permalink: blog/blog54/ categories: [Data Science, Extra] --- ![Image for post](https://miro.medium.com/max/12000/0*2BBlbk_QjecT2lI0) Photo by [Campaign Creators](https://unsplash.com/@campaign_creators?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral) <!--end_excerpt--> ## Creating Online Data-Driven Presentations ### Using Reveal.js and D3.js in order to create interactive online data science presentations ## Introduction Being able to summarise data science projects and show their potential business benefits can play a really important role in securing new customers and make it easier for non-technical audiences to understand some key design concepts. In this article, I am going to introduce you to two free programming frameworks which can be used in order to create interactive online presentations and data-based storytelling reports. ## Reveal.js [Reveal.js](https://github.com/hakimel/reveal.js/) is an open-source presentation framework completely built on open web technologies. Using Reveal.js, can then be possible to easily create web-based presentations and to export them in other formats such as PDF. Some of the most interesting features of Reveal.js are Latex and Markdown support, CSS customization, speaker notes functionalities and syntax highlighting code tools. ### Set-up Reveal.js can be easily installed by cloning the official repository: git clone https://github.com/hakimel/reveal.js.git Our presentation can then be developed by modifying the provided ***index.html*** file in the reveal.js directory. Using Node.js, we can then easily observe (on a local server at port: [http://localhost:8000](http://localhost:8000/)) in real-time how our updates in the ***index.html*** file. cd reveal.js && npm install npm start A simple example of ***index.html*** presentation file is available below. As we can see from the code snippet, we first import the Reveal.js library and then black as our theme for the slides (many more themes options are listed on the [Reveal.js documentation page!](https://revealjs.com/themes/)). Each different slide, can then be created by enclosing each of them in a section tag and write all the desired content inside. Nesting different section tags, it can then be possible to create different subsections in the presentation. Finally, in the last script tag, Reveal.js is initialised (passing different optional parameters, functionalities such as Latex and Math formatting can be added). <html> <head> <link rel="stylesheet" href="dist/reveal.css"> <link rel="stylesheet" href="dist/theme/black.css"> </head> <body> <div class="reveal"> <div class="slides"> <section>First Slide</section> <section>Second Slide</section> <section> <section>Subsection Slide 1</section> <section>Subsection Slide 2</section> </section> </div> </div> <script src="dist/reveal.js"></script> <script> Reveal.initialize(); </script> </body> </html> Additionally, it is also possible to create the slides in Markdown instead of using HTML and Javascript, by instantiating a slide using the following format and importing the plugin. <section data-markdown> <textarea data-template> ## Slide Title Example text. </textarea> </section> <script src="plugin/markdown/markdown.js"></script> <script> Reveal.initialize({ plugins: [ RevealMarkdown ] }); </script> A fully working example presentation created using Reveal.js, is available at [this link (FIgure 1).](https://ppiconsulting.dev/Epidemics-Modelling/presentation//index.html#/) ![Figure 1: Video Example](https://cdn-images-1.medium.com/max/3840/1*FUS1Yr2imWQ0DQvkYZdCCg.gif) ## D3.js D3.js is an open-source Javascript library designed to create data-driven visualizations in the web using HTML, CSS and SVG. D3.js can be simply loaded by adding the following line in our working files. # As new versions of the library might be released, updated versions # of this link might can be found at this link: https://d3js.org/ <script src="https://d3js.org/d3.v5.min.js"></script> Using D3.js, elements can be selected by either using their name or CSS selector. Additionally, D3.js provides utilities in order to load datasets and pre-process the data for visualization. A simple example code to show how to setup D3.js in order to create an ellipse chart, is available below. <html> <head> <script src="https://d3js.org/d3.v5.min.js"></script> </head> <body> <h1>D3.js Template Example</h1> <script> var svg = d3.select("body") .append("svg") .attr("width", 270) .attr("height", 270); svg.append("ellipse") .attr("cx", 140) .attr("cy", 100) .attr("rx", 120) .attr("ry", 70) .attr("opacity", 0.3) .attr("fill", "blue") </script> </body> </html> ![Figure 2: D3.js example code output](https://cdn-images-1.medium.com/max/2000/1*A__p-xFllB6pB3b1muBXYg.png) D3.js charts can then be used in order to create powerful presentations by integrating them with a scroller architecture. Fortunately, multipurpose scrollers (which can be used for any type of narrative) have been developed in the past few years thanks to authors such as [Jim Vallandingham](https://vallandingham.me/scroller.html) and [Cuthbert Chow](https://towardsdatascience.com/how-i-created-an-interactive-scrolling-visualisation-with-d3-js-and-how-you-can-too-e116372e2c73). A fully working example of a data-driven narrative created by me using a D3.js based scroller is available in the animation below. This can also be tested at the [following link.](https://ppiconsulting.dev/Epidemics-Modelling/d3_scroller//index.html) ![Figure 3: D3.js Scroller Presentation](https://cdn-images-1.medium.com/max/2774/1*u5jVoV2Q3UD4Y5JmlnO-3w.gif) In case you are interested in learning more about how to create D3.js charts, the [D3 Graph Gallery documentation](https://www.d3-graph-gallery.com/intro_d3js.html) is a great place where to start. Finally, if you are interested in making your presentations available offline, the [FPDF](https://pyfpdf.readthedocs.io/en/latest/index.html) and [python-pptx](https://python-pptx.readthedocs.io/en/latest/) Python libraries can be used in order to automatically generate respectively PDFs and PowerPoints in Python. *I hope you enjoyed this article, thank you for reading!*
PHP
UTF-8
1,279
2.546875
3
[ "MIT" ]
permissive
<?php namespace Stu\Orm\Entity; interface TradeTransactionInterface { public function getId(): int; public function getWantedCommodityId(): int; public function setWantedCommodityId(int $wantedCommodityId): TradeTransactionInterface; public function getWantedCommodityCount(): int; public function setWantedCommodityCount(int $wantedCommodityCount): TradeTransactionInterface; public function getOfferedCommodityId(): int; public function setOfferedCommodityId(int $offeredCommodityId): TradeTransactionInterface; public function getOfferedCommodityCount(): int; public function setOfferedCommodityCount(int $offeredCommodityCount): TradeTransactionInterface; public function getDate(): int; public function setDate(int $date): TradeTransactionInterface; public function getTradePostId(): int; public function setTradePostId(int $tradepost_id): TradeTransactionInterface; public function getWantedCommodity(): CommodityInterface; public function setWantedCommodity(CommodityInterface $wantedCommodity): TradeTransactionInterface; public function getOfferedCommodity(): CommodityInterface; public function setOfferedCommodity(CommodityInterface $offeredCommodity): TradeTransactionInterface; }
PHP
UTF-8
3,244
2.765625
3
[]
no_license
<?php require_once 'app/models/kayttaja.php'; class BaseController{ public static function get_user_logged_in(){ if(isset($_SESSION['kayttaja'])){ $tunnus = $_SESSION['kayttaja']; return Kayttaja::haeTunnuksella($tunnus); }else{ return null; } } //kirjautumisen tarkistus - MUISTA AINA public static function check_logged_in(){ if(!isset($_SESSION['kayttaja'])){ self::redirect_to('/virhe', array('viesti' => 'Et ole kirjautunut sisään!')); } } public static function tarkista_onko_yllapitaja(){ self::check_logged_in(); $kayttaja = self::get_user_logged_in(); if(!$kayttaja->yllapitaja){ self::redirect_to('/virhe', array('viesti' => 'Et ole ylläpitäjä!')); } } public static function render_view($view, $content = array()){ Twig_Autoloader::register(); $twig_loader = new Twig_Loader_Filesystem('app/views'); $twig = new Twig_Environment($twig_loader); try{ if(isset($_SESSION['flash_message'])){ $flash = json_decode($_SESSION['flash_message']); foreach($flash as $key => $value){ $content[$key] = $value; } unset($_SESSION['flash_message']); } $content['base_path'] = self::base_path(); if(method_exists(__CLASS__, 'get_user_logged_in')){ $kayttaja = self::get_user_logged_in(); $content['kirjautunut_kayttaja'] = $kayttaja; $content['kirjautunut_yllapitaja'] = $kayttaja != null ? $kayttaja->yllapitaja : false; } echo $twig->render($view, $content); } catch (Exception $e){ die('Virhe näkymän näyttämisessä: ' . $e->getMessage()); } exit(); } public static function redirect_to($location, $message = null){ if(!is_null($message)){ $_SESSION['flash_message'] = json_encode($message); } header('Location: ' . self::base_path() . $location); exit(); } public static function render_json($object){ header('Content-Type: application/json; charset=utf-8'); echo json_encode($object); exit(); } public static function base_path(){ $script_name = $_SERVER['SCRIPT_NAME']; $explode = explode('/', $script_name); if($explode[1] == 'index.php'){ $base_folder = ''; }else{ $base_folder = $explode[1]; } return '/' . $base_folder; } //nämä funktiot palauttavat ajan ja päivämäärän postgresql:llän aikaleimasta //suomalaisessa muodossa 11.9.2001 ja 10:55:05 public static function haeAika($aikaLeima){ return date('H:i:s', strtotime($aikaLeima)); } public static function haePvm($aikaLeima){ return date('d.m.Y', strtotime($aikaLeima)); } /** * jos ehto ei täyty, käyttäjä ohjataan etusivulle ja näytetään virheviesti */ public static function tarkista($ehto, $virheViesti){ if(!$ehto){ self::redirect_to('/etusivu', array('virheviesti' => $virheViesti)); exit(); } } }
Shell
UTF-8
1,242
3.609375
4
[]
no_license
#!/bin/bash if [ $# -lt 1 ]; then echo "" echo "[DESCRIPTION]" echo "Put device into kDFU mode using pwnediBSS" echo "" echo "[USAGE]" echo "./enterkdfu <device IP>" echo "" echo "[EXAMPLE]" echo "./enterkdfu 192.168.1.88" echo "" exit fi if [ $# -gt 1 ]; then echo "[ERROR] Too many arguments" exit fi ip=$1 if [ $OSTYPE = msys ]; then echo "Windows Detected" path="/c/Users/`whoami`/Downloads" platform="win" elif [[ $OSTYPE == "darwin"* ]]; then echo "macOS Detected" path="/Users/`whoami`/Downloads" platform="macos" else echo "Not supported" exit fi cd "$path/blobs/odysseus-0.999.0/$platform" if [ -e "pwnediBSS" ]; then echo "" echo "Found pwnediBSS" else echo "" echo "Did not find pwnediBSS, have you ran ./patchipsw?" exit 1 fi echo "" echo "Attempting to enter kDFU" echo "" echo "If asked, type yes, then the default password is \"alpine\"" echo "" echo "WHEN YOUR DEVICE TURNS OFF, DISCONNECT THEN RECONNECT YOUR DEVICE TO YOUR COMPUTER, PRESS CONTROL+C, AND PROCEED TO \"./dumpblobs\". IGNORE ITUNES" echo "" ./sshtool -k ../kloader -b pwnediBSS -p 22 $ip echo "" echo "IF YOUR DEVICE DID NOT TURN OFF, SEE TROUBLESHOOTING" echo ""
Java
UTF-8
16,240
1.945313
2
[]
no_license
/* * Copyright 2000,2005 wingS development team. * * This file is part of wingS (http://wingsframework.org). * * wingS is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * Please see COPYING for the complete licence. */ package org.wings.template.parser; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wings.session.SessionManager; import org.wings.template.LabelTagHandler; import org.wings.template.TemplateSource; /** * <CODE>PageParser</CODE> * parses SGML markup'd pages and executes * <em>active</em> Tag. Returns its output * through a HttpServletResponse (given in a ParseContext). * Active Tags are handled with SpecialTagHandlers which * can be registered for a specific Tag. * <p/> * <p><h4>Error handling:</h4> * To simplify error detection and correction, * exceptions thrown by the <CODE>executeTag()</CODE>-methods of the * pluggable handlers (e.g. called servlets) are printed, * enclosed in comments ("&lt;!-- ... --&gt;"), in the HTML output. * * @author <A href="mailto:zeller@think.de">Henner Zeller</A> * @see javax.servlet.http.HttpServlet */ public class PageParser { private final static Log log = LogFactory.getLog(PageParser.class); private static PageParser sharedInstance = null; /** * returns a singleton instance of this PageParser. * You usually want to use the singleton instance to make * use of a central cache. */ public static PageParser getInstance() { if (sharedInstance == null) { synchronized (PageParser.class) { if (sharedInstance == null) sharedInstance = new PageParser(); } } return sharedInstance; } /** * This Map contains the cached parsed * pages, saved in TemplateSourceInfo-Objects. * The key is the canonical name of the Data * Source. */ private final Map/*<String, TemplateSourceInfo>*/ pages = new HashMap(); /** * a Hashtable with key/value=tagname/handlerClass */ private final Map/*<String,Class>*/ handlerClasses = new HashMap(); /** * Constructs a new PageParser. */ public PageParser() { } /** * Process a general DataStore representing a Template * * @param source The template TemplateSource * @param context The context used while parsing; contains * at least the HttpServletRequest and * HttpServletResponse. * @see ParseContext * @see TemplateSource */ public void process(TemplateSource source, ParseContext context) throws IOException { interpretPage(source, getPageParts(source, context), context); } public Set<String> getContainedComponents(TemplateSource source, ParseContext context) throws IOException { getPageParts(source, context); String cName = source.getCanonicalName(); TemplateSourceInfo sourceInfo = (TemplateSourceInfo)pages.get(cName); return sourceInfo.containedComponents; } public Map<String, Map<String, String>> getComponentProperties(TemplateSource source, ParseContext context) throws IOException { getPageParts(source, context); String cName = source.getCanonicalName(); TemplateSourceInfo sourceInfo = (TemplateSourceInfo)pages.get(cName); return sourceInfo.componentProperties; } public Map getLabels(TemplateSource source) { String cName = source.getCanonicalName(); if (cName == null) return null; TemplateSourceInfo sourceInfo = (TemplateSourceInfo) pages.get(cName); if (sourceInfo == null) return null; return sourceInfo.labels; } /** * register a handler for a specific tag (Class name). * Tags are case-insensitive. * * @param tagname the name of the tag like 'MYSPECIALTAG' or 'SERVLET' * @param handlerClassName the <em>name of class</em> implementing the * action for this tag. This class must * implement the SpecialTagHandler * interface. * @throws ClassNotFoundException if the class with the specified * name is not found. */ public void addTagHandler(String tagname, String handlerClassName) throws ClassNotFoundException { handlerClasses.put(tagname.toUpperCase(), Class.forName(handlerClassName)); } /** * register a handler for a specific tag (Class). * Tags are case-insensitive. * * @param tagname the name of the tag like 'MYSPECIALTAG' or 'SERVLET' * @param handlerClass the <em>class</em> implementing the * action for this tag. This class must * implement the SpecialTagHandler * interface. */ public void addTagHandler(String tagname, Class handlerClass) { handlerClasses.put(tagname.toUpperCase(), handlerClass); } /** * @return Itearator of all Tags which are special to * this PageParser */ public Iterator getRegisteredTags() { return handlerClasses.keySet().iterator(); } /** * If TemplateSource has changed or has not yet been loaded, load * it and chop into sections, storing result for future use. * Otherwise, return stored preprocessed page. * * @param source TemplateSource for which we want page section list * @return list of page sections, as described in parsePage(). * @see #parsePage */ private List getPageParts(TemplateSource source, ParseContext context) throws IOException { // first, check to see if we have cached version String cName = source.getCanonicalName(); TemplateSourceInfo sourceInfo = null; if (cName != null) sourceInfo = (TemplateSourceInfo) pages.get(cName); /* * parse the page if it has changed or no cached * information is available. */ if (sourceInfo == null || sourceInfo.lastModified != source.lastModified()) { // if no cached version, or modified, load sourceInfo = parsePage(source, context); if (cName != null) pages.put(cName, sourceInfo); } return sourceInfo.parts; } /** * Scan through vector of page sections and build * output. * Read the static areas of the TemplateSource and copy them to the * output until the beginning of the next special tag. Invokes * the <CODE>executeTag()</CODE> Method for the tagand goes on with copying. * or invoking the servlets to which they refer. * * @param parts page sections, as provide by parsePage() * @see #parsePage */ private void interpretPage(TemplateSource source, List parts, ParseContext context) throws IOException { Writer out = new OutputStreamWriter(context.getOutputStream(), getStreamEncoding()); Reader in = null; char[] buf = null; try { // input in = new InputStreamReader(source.getInputStream(), getStreamEncoding()); long inPos = 0; /* * Get Copy Buffer. * If we allocate it here once and pass it to the * copy()-function we don't have to create and garbage collect * a buffer each time we call copy(). * * REVISE: this should use a buffer Manager: * a queue which stores buffers. This * way the JVM doesn't have to garbage collect the buffers * created here, so we may use larger Buffers * here. */ buf = new char[4096]; // Get buffer from Buffer Manager for (int i = 0; i < parts.size(); i++) { /** <critical-path> **/ SpecialTagHandler part = (SpecialTagHandler) parts.get(i); // copy TemplateSource content till the beginning of the Tag: copy(in, out, part.getTagStart() - inPos, buf); context.startTag(i); try { part.executeTag(context, in); } /* * Display any Exceptions or Errors as * comment in the page */ catch (Throwable e) { out.flush(); PrintWriter pout = new PrintWriter(out); pout.println("<!-- ERROR: ------------"); e.printStackTrace(pout); pout.println("-->"); pout.flush(); } context.doneTag(i); inPos = part.getTagStart() + part.getTagLength(); /** </critical-path> **/ } // copy rest until end of TemplateSource copy(in, out, -1, buf); } finally { // clean up resouce: opened input stream if (in != null) in.close(); buf = null; // return buffer to Buffer Manager } out.flush(); } /** * copies an InputStream to an OutputStream. copies max. length * bytes. * * @param in The source reader * @param out The destination writer * @param length number of bytes to copy; -1 for unlimited * @param buf Buffer used as temporary space to copy * block-wise. */ private static void copy(Reader in, Writer out, long length, char[] buf) throws IOException { int len; boolean limited = (length >= 0); int rest = limited ? (int) length : buf.length; while (rest > 0 && (len = in.read(buf, 0, (rest > buf.length) ? buf.length : rest)) > 0) { out.write(buf, 0, len); if (limited) rest -= len; } out.flush(); } /** * Open and read source, returning list of contents. * The returned vector will contain a list of * <CODE>SpecialTagHandler</CODE>s, containing the * position/length within the input source they are * responsible for. * This Vector is used within <CODE>interpretPage()</CODE> * to create the output. * * @param source source to open and process * @param context The context used while parsing; contains * at least the HttpServletRequest and HttpServletResponse * @return TemplateSourceInfo containing page elements. * <!-- see private <a href="#interpretPage">interpretPage()</a> --> */ private TemplateSourceInfo parsePage(TemplateSource source, ParseContext context) throws IOException { /* * read source contents. The SGMLTag requires * to read from a Reader which supports the * mark() operation so we need a BufferedReader * here. * * The PositionReader may be asked at which Position * it currently is (much like the java.io.LineNumberReader); this * is used to determine the exact position of the Tags in the * page to be able to loop through the fast copy/execute/copy * sequence in interpretPage(). * * Since interpreting is operating on an InputStream which * copies and skip()s bytes, any source position count done here * assumes that sizeof(char) == sizeof(byte). * So we force the InputStreamReader to interpret the Stream's content * as ISO8859_1, because the localized default behaviour may * differ (e.g. UTF8 for which sizeof(char) != sizeof (byte) */ PositionReader fin = null; // from JDK 1.1.6, the name of the encoding is ISO8859_1, but the old // value is still accepted. fin = new PositionReader(new BufferedReader(new InputStreamReader(source.getInputStream(), getStreamEncoding()))); TemplateSourceInfo sourceInfo = new TemplateSourceInfo(); try { // scan through page parsing SpecialTag statements sourceInfo.lastModified = source.lastModified(); sourceInfo.parts = new ArrayList(); sourceInfo.labels = new HashMap(); long startPos; SGMLTag tag, endTag; long startTime = System.currentTimeMillis(); do { endTag = null; startPos = fin.getPosition(); tag = new SGMLTag(fin, false); if (tag.getName() != null) { String upName = tag.getName().toUpperCase(); if (handlerClasses.containsKey(upName)) { SpecialTagHandler handler = null; try { Class handlerClass = (Class) handlerClasses.get(upName); handler = (SpecialTagHandler) handlerClass.newInstance(); endTag = handler.parseTag(context, fin, startPos, tag); } catch (Exception e) { log.warn("Exception",e); } if (endTag != null) { if ("LABEL".equals(upName)) { LabelTagHandler labelHandler = (LabelTagHandler) handler; sourceInfo.labels.put(labelHandler.getFor(), labelHandler.getContent()); } sourceInfo.parts.add(handler); } } } } while (!tag.finished()); sourceInfo.containedComponents = context.getContainedComponents(); sourceInfo.componentProperties = context.getComponentProperties(); /*** sourceInfo.parseTime = System.currentTimeMillis() - startTime; System.err.println ("PageParser: parsing '" + source.getCanonicalName() + "' took " + sourceInfo.parseTime + "ms for " + sourceInfo.parts.size() + " handlers"); ***/ } finally { if (fin != null) fin.close(); } return sourceInfo; } /** * Source info holds the parse information for * a TemplateSource .. and some statistical stuff which * may be interesting for administrative * frontends */ private static final class TemplateSourceInfo { ArrayList parts; Map labels; long lastModified; Set<String> containedComponents; Map<String, Map<String, String>> componentProperties; public TemplateSourceInfo() {} } /** * Returns the encoding of the streams. * * @return The encoding of the streams. */ private final String getStreamEncoding() { String encoding = (String) SessionManager.getSession().getProperty("wings.template.layout.encoding"); if (encoding == null || "".equals(encoding)) { encoding = "UTF-8"; } return encoding; } }
Markdown
UTF-8
729
2.53125
3
[]
no_license
--- layout: page title: Work permalink: /portfolio/ bodyClass: work --- Below is a sampling of work that will cross several disciplines: Visual, interaction, branding, research, and UI design. <ul class="work-list"> {% for work in site.work reversed %} <li> <h5>{{ work.name }}: {{ work.involvement }}</h5> <ul> {% for item in work.workItems %} <li> {% if item.url %} <a href="{{ item.url | replace: "__CLOUD_FILES_URL__", site.cloud_files_url }}"> {{ item.name }} </a> {% else %} {{ item }} {% endif %} </li> {% endfor %} </ul> </li> {% endfor %} <li> <h5><a href="rae-cabello-resume.pdf">Rae D. Cabello Resume</a></h5> </li> </ul>
JavaScript
UTF-8
625
2.609375
3
[]
no_license
var Utils = (function () { function Utils() { } Utils._isFirefox = null; Utils._firefoxUrlBase = undefined; Utils.platform = function platform() { if(Utils._isFirefox == null) { Utils._isFirefox = !!($.browser.mozilla); } if(Utils._isFirefox) { return 'firefox'; } else { return 'chrome'; } } Utils.url = function url(path) { if(Utils.platform() == 'chrome') { return chrome.extension.getURL(path); } else { return Utils._firefoxUrlBase + path; } } return Utils; })();
Go
UTF-8
4,164
2.8125
3
[ "MIT" ]
permissive
package handler_test import ( "bytes" "net/http" "testing" "github.com/suzuki-shunsuke/go-graylog/v8/testutil" ) func TestHandleGetInput(t *testing.T) { server, client, err := testutil.GetServerAndClient() if err != nil { t.Fatal(err) } defer server.Close() input := testutil.Input() if _, err := server.AddInput(input); err != nil { t.Fatal(err) } act, _, err := client.GetInput(input.ID) if err != nil { t.Fatal(err) } if input.Node != act.Node { t.Fatalf("Node == %s, wanted %s", act.Node, input.Node) } if _, _, err := client.GetInput(""); err == nil { t.Fatal("input id is required") } if _, _, err := client.GetInput("h"); err == nil { t.Fatal(`no input whose id is "h"`) } } func TestHandleGetInputs(t *testing.T) { server, client, err := testutil.GetServerAndClient() if err != nil { t.Fatal(err) } defer server.Close() act, _, _, err := client.GetInputs() if err != nil { t.Fatal(err) } if act == nil { t.Fatal("client.GetInputs() returns nil") } if len(act) != 1 { t.Fatalf("len(act) == %d, wanted 1", len(act)) } } func TestHandleCreateInput(t *testing.T) { server, client, err := testutil.GetServerAndClient() if err != nil { t.Fatal(err) } defer server.Close() input := testutil.Input() if _, err := client.CreateInput(input); err != nil { t.Fatal(err) } if input.ID == "" { t.Fatal(`client.CreateInput() == ""`) } if _, err := client.CreateInput(nil); err == nil { t.Fatal("input is nil") } body := bytes.NewBuffer([]byte("hoge")) req, err := http.NewRequest( http.MethodPost, client.Endpoints().Inputs(), body) if err != nil { t.Fatal(err) } req.SetBasicAuth(client.Name(), client.Password()) hc := &http.Client{} resp, err := hc.Do(req) if err != nil { t.Fatal(err) } if resp.StatusCode != 400 { t.Fatalf("resp.StatusCode == %d, wanted 400", resp.StatusCode) } } func TestHandleUpdateInput(t *testing.T) { server, client, err := testutil.GetServerAndClient() if err != nil { t.Fatal(err) } defer server.Close() input := testutil.Input() if _, err := server.AddInput(input); err != nil { t.Fatal(err) } id := input.ID input.Title += " updated" if _, _, err := client.UpdateInput(input.NewUpdateParams()); err != nil { t.Fatal(err) } act, _, err := server.GetInput(id) if err != nil { t.Fatal(err) } if act == nil { t.Fatal("input is not found") } if act.Title != input.Title { t.Fatalf(`UpdateInput title "%s" != "%s"`, act.Title, input.Title) } input.ID = "" if _, _, err := client.UpdateInput(input.NewUpdateParams()); err == nil { t.Fatal("input id is required") } input.ID = "h" if _, _, err := client.UpdateInput(input.NewUpdateParams()); err == nil { t.Fatal(`no input whose id is "h"`) } input.ID = id input.Attrs = nil if _, _, err := client.UpdateInput(input.NewUpdateParams()); err == nil { t.Fatal("input attributes is required") } input.Attrs = act.Attrs input.Title = "" if _, _, err := client.UpdateInput(input.NewUpdateParams()); err == nil { t.Fatal("input title is required") } input.Title = act.Title if _, _, err := client.UpdateInput(nil); err == nil { t.Fatal("input is required") } body := bytes.NewBuffer([]byte("hoge")) u, err := client.Endpoints().Input(id) if err != nil { t.Fatal(err) } req, err := http.NewRequest( http.MethodPut, u.String(), body) if err != nil { t.Fatal(err) } req.SetBasicAuth(client.Name(), client.Password()) hc := &http.Client{} resp, err := hc.Do(req) if err != nil { t.Fatal(err) } if resp.StatusCode != 400 { t.Fatalf("resp.StatusCode == %d, wanted 400", resp.StatusCode) } } func TestHandleDeleteInput(t *testing.T) { server, client, err := testutil.GetServerAndClient() if err != nil { t.Fatal(err) } defer server.Close() input := testutil.Input() if _, err = server.AddInput(input); err != nil { t.Fatal(err) } if _, err = client.DeleteInput(input.ID); err != nil { t.Fatal("Failed to DeleteInput", err) } if _, err := client.DeleteInput(""); err == nil { t.Fatal("input id is required") } if _, err := client.DeleteInput("h"); err == nil { t.Fatal(`no input whose id is "h"`) } }
Java
UTF-8
1,407
2.5625
3
[]
no_license
package pl.coderslab.web; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; @WebServlet("/addToSession") public class Sess03_Add extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("key"); String value = request.getParameter("value"); HttpSession sess = request.getSession(); sess.setAttribute(name, value ); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.getWriter().append("<form action= '' method='POST'>\n" + " <label>\n" + " Key:\n" + " <input type=\"text\" name=\"key\">\n" + " </label>\n" + " <label>\n" + " Value:\n" + " <input type=\"text\" name=\"value\">\n" + " </label>\n" + " <input type=\"submit\">\n"); response.getWriter().append("</form>"); } }
PHP
UTF-8
2,223
2.703125
3
[]
no_license
<?php /** * Good (Gif oriented object drawing) * * @version 1.0 * @author franckysolo <franckysolo@gmail.com> */ namespace Good\Gd\Transformation; use Good\Gd\Resource; use Good\Gd\Transformation; use Good\Gd\LayerList; use Good\Gd\Layer; /** * The merge transformation class * * @author franckysolo <franckysolo@gmail.com> * @since 27 sept. 2012 * @license http://creativecommons.org/licenses/by-sa/3.0/ CC BY-SA 3.0 * @category Good * @package Good\Gd * @subpackage Transformation */ class Merge extends Transformation { /** * The layerList to merge * * @access protected * @var LayerList */ protected $_layerList; /** * Add a layerList to merge * * @access public * @param LayerList $list * @return \Good\Gd\Transformation\Merge */ public function addLayerList(LayerList $list) { $this->_layerList = $list; return $this; } /** * (non-PHPdoc) * @see Good\Gd.Transformation::execute() */ public function execute() { $source = $this->_layerList->get(0); $this->_layerList->remove(0); foreach($this->_layerList->getLayers() as $key => $layer) { if($layer->hasFilter()) { foreach($layer->getFilters() as $filter) { $filter->apply($layer->getResource()); } } $source = $this->_copyMerge($source, $layer, $layer->getTransparence()); $this->_layerList->remove($key); } $this->_resource = $source->getResource(); return $source; } /** * Copy & merge layers * * @param Layer $source * @param Layer $copy * @param integer $transparence * @throws \RuntimeException * @return \Good\Gd\Layer */ protected function _copyMerge($source, $copy, $transparence) { $rc = $copy->getResource(); $rs = $source->getResource(); $x = imagesx($rc); $y = imagesy($rc); // $color = imagecolorat($rc, 0, 0); // imagecolortransparent($rc, $color); if(!imagecopymerge ($rc, $rs, 0, 0, 0, 0, $x, $y, $transparence)) { throw new \RuntimeException('Unable to merge layers', 500); } $layer = new Layer($copy->getName(), $copy->getClassResource()); $layer->setTransparence($transparence); return $layer; } }
C++
UTF-8
1,328
2.6875
3
[]
no_license
// CF1248D1.cpp #include <bits/stdc++.h> using namespace std; const int MAX_N = 550; char str[MAX_N]; int n, val; pair<int, int> answer; int calc() { int cnt = 0, min_pos = -1, min_val = n; for (int i = 1; i <= n; i++) { if (str[i] == '(') cnt++; else cnt--; if (str[i] == '(' && cnt < min_val) min_val = cnt, min_pos = i; } cnt = 0; int pans = 0; for (int i = 1, j = min_pos; i <= n; i++, j = ((j == n) ? 1 : j + 1)) { if (str[j] == '(') cnt++; else { cnt--; if (cnt == 0) pans++; } } return pans; } int main() { scanf("%d%s", &n, str + 1); int lbrucket = 0, rbrucket = 0; for (int i = 1; i <= n; i++) lbrucket += (str[i] == '('), rbrucket += (str[i] == ')'); if (lbrucket != rbrucket) printf("0\n1 1"), exit(0); val = calc(), answer = make_pair(1, 1); for (int i = 1; i <= n; i++) for (int j = i + 1; j <= n; j++) { swap(str[i], str[j]); int pans = calc(); if (pans > val) val = pans, answer = make_pair(i, j); swap(str[i], str[j]); } printf("%d\n%d %d", val, answer.first, answer.second); return 0; }
C++
UTF-8
1,067
3.5625
4
[]
no_license
#include <array> #include <string> using namespace std; // GradeBook class definition class GradeBook { public: //contants --number of students who took the test static const size_t students = 10; // number of students GradeBook() {}; // GradeBook(const std::string &, const std::array< int, students > &); void setCourseName(const std::string &); // set the course name string getCourseName() const; // retrieve the course name void displayMessage() const; // display a welcome message // void processGrades() const; // perform operations on the grade data int getMinimum() const; // find the minimum grade in the grade book int getMaximum() const; // find the maximum grade in the grade book double getAverage() const; void outputBarChart() const; // output bar chart of grade distribution void outputGrades() const; // output the contents of the grades array private: std::string courseName; // course name for this grade book const array< int, GradeBook::students > grades = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 }; }; // end class GradeBook
JavaScript
UTF-8
2,124
3.34375
3
[]
no_license
const inquirer = require("inquirer"); const generateChoices = require("../generateChoices"); const { validateAnswerLength } = require("../questionValidators") const addEmployee = async (db) => { allRoles = await db.selectAllFromTable("role") const newEmployeeQs = [ { type: "input", message: "What is the employee's first name?", name: "first_name", validate: (first_name) => { return validateAnswerLength(first_name) } }, { type: "input", message: "What is the employee's last name?", name: "last_name", validate: (last_name) => { return validateAnswerLength(last_name) } }, { type: "list", message: "Which of the below roles would you like to assign the employee to?", name: "role_id", choices: generateChoices(allRoles, "role_title", "id"), }, { type: "confirm", message: "Would you like to assign a manager to this employee?", name: "hasManager", } ] const newEmployee = await inquirer.prompt(newEmployeeQs) console.log(newEmployee) if (newEmployee.hasManager == true ) { // get all employees and add a full name key allEmployees = await db.selectAllFromTable("employee") const allEmployeesWithFullNameKey = allEmployees.map(function (employee) { employee.fullName = `${employee.first_name} ${employee.last_name}` return employee}); const selectManagerQ = { type: "list", message: "Which of the below employees would you like to assign as the manager?", name: "manager_id", choices: generateChoices(allEmployeesWithFullNameKey, "fullName", "id"), } const {manager_id} = await inquirer.prompt(selectManagerQ) // hello :) thanks for marking my work! // I tried to set the manager id here using the bracket notation but it didn't work - do you know why this may be? newEmployee.manager_id = manager_id } // delete not needed hasManager key delete newEmployee.hasManager await db.insert("employee", newEmployee) return } module.exports = addEmployee
JavaScript
UTF-8
133
2.5625
3
[ "MIT" ]
permissive
function getFlag(flag){ const index = process.argv.indexOf(flag) + 1 return process.argv[index] } module.exports = getFlag
Python
UTF-8
2,392
2.953125
3
[]
no_license
from typing import * import torch class MaxTripletLoss(torch.nn.Module): # TODO def __init__(self, margin: float): super(MaxTripletLoss, self).__init__() self.margin = margin def forward(self, s_pos: torch.Tensor, s_neg: torch.Tensor) -> torch.Tensor: """ Computes the max triplet loss. :param s_pos: F[Batch, PosCand, Output=1] :param s_neg: F[Batch, NegCand, Output=1] :return: F[] """ s1 = s_pos.squeeze(dim=2) # F[Batch, PosCand] s0 = s_neg.squeeze(dim=2) # F[Batch, NegCand] s0_best, _ = torch.max(s0, dim=1) # F[Batch] s0_best_expanded = s0_best.unsqueeze(dim=1).expand(-1, s1.size(1)) # F[Batch, PosCand] diff = s0_best_expanded - s1 + self.margin # F[Batch, PosCand] return torch.mean(torch.relu(diff)) class MeanTripletLoss(torch.nn.Module): def __init__(self, margin: float): super(MeanTripletLoss, self).__init__() self.margin = margin def forward(self, s_pos: torch.Tensor, s_neg: torch.Tensor) -> torch.Tensor: # y_pos: torch.Tensor, y_neg: torch.Tensor """ Computes the mean triplet loss. :param s_pos: F[Batch, PosCand, Output=1] :param s_neg: F[Batch, NegCand, Output=1] :return: F[] """ s1 = s_pos.squeeze(dim=2) # F[Batch, PosCand] s0 = s_neg.squeeze(dim=2) # F[Batch, NegCand] s1e = s1.unsqueeze(dim=2).expand(-1, -1, s0.size(1)) # F[Batch, PosCand, NegCand] s0e = s0.unsqueeze(dim=1).expand(-1, s1.size(1), -1) # F[Batch, PosCand, NegCand] #y1e = y_pos.unsqueeze(dim=2).expand(-1, -1, s0.size(1)) #y0e = y_neg.unsqueeze(dim=1).expand(-1, s1.size(1), -1) diff = s0e - s1e + self.margin # F[Batch, PosCand, NegCand] return torch.mean(torch.relu(diff)) class PairwiseHingeLoss(torch.nn.Module): def __init__(self, margin: float): super(PairwiseHingeLoss, self).__init__() self.margin = margin def forward(self, s_pos: torch.Tensor, s_neg: torch.Tensor, y_pos: torch.Tensor, y_neg: torch.Tensor) -> torch.Tensor: """ :param s_pos: F[Batch, Output=1] :param s_neg: F[Batch, Output=1] :return: """ diff = s_neg - s_pos + self.margin * (y_pos - y_neg) # F[Batch, Score] return torch.mean(torch.relu(diff))
Java
UTF-8
900
1.945313
2
[]
no_license
package com.example.liquibaseDemo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.support.rowset.SqlRowSet; import javax.sql.DataSource; import java.util.List; import java.util.Map; @SpringBootApplication public class LiquibaseDemoApplication implements CommandLineRunner { @Autowired private JdbcTemplate jdbcTemplate; public static void main(String[] args) { SpringApplication.run(LiquibaseDemoApplication.class, args); } @Override public void run(String...args) throws InterruptedException { Thread.sleep(5000); String sql = "SELECT * FROM CLIENT"; System.out.println(jdbcTemplate.queryForList(sql)); } }
C#
UTF-8
468
2.875
3
[]
no_license
using System; namespace Enums { public enum SpriteNames { Astronaut, AlienDrone, AlienKing, AlienGunner, Bullet, Blast, MedKit, Laser, RapidFire, Shotgun, Bounce } static class SpriteNamesMethods { public static string GetString(this SpriteNames spriteName) { if (spriteName == SpriteNames.Astronaut) { return spriteName.ToString(); } return spriteName + "(Clone)"; } } }
Java
UTF-8
2,910
2.671875
3
[]
no_license
package com.cheekymammoth.ui; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Rectangle; import com.cheekymammoth.graphics.CMSprite; public class SpriteMenuIcon extends MenuIcon { private boolean isSpriteCentered; private float spriteOffsetX; protected CMSprite sprite; protected CMSprite bullet; public SpriteMenuIcon() { this(-1, null); } public SpriteMenuIcon(int category, TextureRegion region) { super(category); sprite = new CMSprite(region); sprite.setY(-sprite.getHeight() / 2); addSpriteChild(sprite); updateBounds(); } public boolean isSpriteCentered() { return isSpriteCentered; } public void setSpriteCentered(boolean value) { if (value != isSpriteCentered) { isSpriteCentered = value; updateBounds(); } } public float getSpriteOffsetX() { return spriteOffsetX; } public void setSpriteOffsetX(float value) { spriteOffsetX = value; } public CMSprite getBullet() { return bullet; } public void setBullet(CMSprite bullet) { if (this.bullet != null) removeSpriteChild(this.bullet); this.bullet = bullet; if (bullet != null) addSpriteChild(bullet); updateBounds(); dispatchEvent(MenuButton.EV_TYPE_BROADCAST_STATE_REQUEST, this); } @Override protected void updateBounds() { super.updateBounds(); if (isSpriteCentered) { if (bullet != null) { sprite.setX(-(bullet.getWidth() + spriteOffsetX + sprite.getWidth()) / 2); bullet.setX(sprite.getX() - (spriteOffsetX + bullet.getWidth())); bullet.setY(-bullet.getHeight() / 2); } else sprite.setX(-(spriteOffsetX + sprite.getWidth()) / 2); } else { if (bullet != null) { sprite.setX(bullet.getWidth() + spriteOffsetX); bullet.setY(-bullet.getHeight() / 2); } else sprite.setX(spriteOffsetX); } if (bullet != null) setSize( bullet.getWidth() + spriteOffsetX + sprite.getWidth(), Math.max(bullet.getHeight(), sprite.getHeight())); else setSize( spriteOffsetX + sprite.getWidth(), sprite.getHeight()); // Actor won't send this message if width/height didn't change, but x/y did. sizeChanged(); } @Override public Rectangle getIconBounds() { Rectangle bounds = super.getIconBounds(); if (bullet != null) { bounds.set( getX() + Math.min(bullet.getX(), sprite.getX()), getY() + Math.min(bullet.getY(), sprite.getY()), bullet.getWidth() + spriteOffsetX + sprite.getWidth(), Math.max(bullet.getHeight(), sprite.getHeight())); } else { bounds.set( getX() + sprite.getX() - spriteOffsetX, getY() + sprite.getY(), spriteOffsetX + sprite.getWidth(), sprite.getHeight()); } return bounds; } @Override protected void setColorsForIndex(int index) { sprite.setColor(sprite.getColor().set(iconColors[index])); if (bullet != null) bullet.setColor(bullet.getColor().set(bulletColors[index])); } }
JavaScript
UTF-8
1,990
3.96875
4
[ "MIT" ]
permissive
// 基本类型,表示独一无二的值 const s1 = Symbol(); console.log(s1); const s2 = Symbol(); // s1 !== s2 const s3 = Symbol('jack'); console.log(s3.toString()); console.log(Boolean(s3)); console.log(!s3); const s4 = Symbol('name'); const info = { [s4]: 'leo', age: 18, sex: 'male' } console.log(info); info[s4] = 'tim'; console.log(info); // 以下方式均拿不到对象中的 symbol 属性 let keys = []; for (const k in info) { keys.push(k); } console.log(keys); console.log(Object.keys(info)); console.log(Object.getOwnPropertyNames(info)); console.log(JSON.stringify(info)); // 如何拿到 symbol 属性? console.log(Object.getOwnPropertySymbols(info)); console.log(Reflect.ownKeys(info)); const s5 = Symbol('test'); const s6 = Symbol.for('test'); const s7 = Symbol.for('test'); // s5 !== s6 // s6 === s7 console.log(Symbol.keyFor(s5)); // undefined console.log(Symbol.keyFor(s6)); // 'test' // 内置 symbol 值 // Symbol.hasInstance // instanceof 时会调用该值声明的函数 const obj1 = { [Symbol.hasInstance] (other) { console.log(other); return true; } } console.log({a:'a'} instanceof obj1); // Symbol.isConcatSpreadable let arr = [1, 2]; console.log([].concat(arr, [3, 4])); // 自动扁平化 arr[Symbol.isConcatSpreadable] = false; console.log([].concat(arr, [3, 4])); // 不会扁平化 // 相应的调用会触发相应 symbol 值声明的函数 // Symbol.match、Symbol.search、Symbol.split const obj2 = { [Symbol.match] (str) { console.log(str.length); } } 'abcde'.match(obj2); // 获取数组迭代器 let arr2 = [1, 2]; const iterator = arr2[Symbol.iterator](); console.log(iterator.next()); console.log(iterator.next()); console.log(iterator.next()); // 自定义基础类型转换 let obj3 = { [Symbol.toPrimitive] (type) { console.log(type); } } let ret = obj3++; let obj4 = { [Symbol.toStringTag]: 'obj4' } console.log(obj4.toString()); // '[object obj4]'
PHP
UTF-8
4,925
2.65625
3
[]
no_license
<?php class EntregaController extends BaseController { protected $entrega; public function __construct(Entrega $entrega) { $this->entrega = $entrega; } /** * Display a listing of the resource. * * @return Response */ public function index() { $entrega = DB::table('entrega') ->join('usuario', 'entrega.usuario_id', '=', 'usuario.id') ->select('entrega.id','entrega.nombre','entrega.email','usuario.usuario','usuario.active','entrega.usuario_id') ->where('active','=',1) ->get(); return View::make('entrega.index', compact('entrega')); } /** * Show the form for creating a new resource. * * @return Response */ public function create() { return View::make('entrega.create'); } /** * Store a newly created resource in storage. * * @return Response */ public function store() { $input = Input::all(); $validation = Validator::make($input, Entrega::$rules); if($input['pass'] == $input['repass']){ $validacionPass = true; $msj = ''; }else{ $validacionPass = false; $msj = '.. Las contraseñas deben ser iguales'; } if($validation->passes() && $validacionPass) { $usuario = new User; $usuario->usuario = $input['usuario']; $usuario->password = Hash::make($input['pass']); $usuario->active = 1; $usuario->nivel = 1; $usuario->save(); $entrega = new Entrega; $entrega->usuario_id = $usuario->id; $entrega->nombre = $input['nombre']; $entrega->email = $input['email']; $entrega->save(); return Redirect::route('entrega.show', $entrega->id); } return Redirect::route('entrega.create') ->withInput() ->withErrors($validation) ->with('message','Existe un error al procesar la informacion'. $msj); } /** * Display the specified resource. * * @param int $id * @return Response */ public function show($id) { $entrega = DB::table('entrega') ->join('usuario', 'entrega.usuario_id', '=', 'usuario.id') ->select('entrega.id','entrega.nombre','entrega.email','usuario.usuario','usuario.active','entrega.usuario_id') ->where('entrega.id','=',$id) ->get(); return View::make('entrega.show', compact('entrega')); } /** * Show the form for editing the specified resource. * * @param int $id * @return Response */ public function edit($id) { $entrega = DB::table('entrega') ->join('usuario', 'entrega.usuario_id', '=', 'usuario.id') ->select('entrega.id','entrega.nombre','entrega.email','usuario.usuario','usuario.active','entrega.usuario_id') ->where('entrega.id','=',$id) ->get(); return View::make('entrega.edit', compact('entrega')); } public function editPassword($id) { $entrega = DB::table('entrega') ->join('usuario', 'entrega.usuario_id', '=', 'usuario.id') ->select('entrega.id','entrega.nombre','entrega.email','usuario.usuario','usuario.active','entrega.usuario_id') ->where('entrega.id','=',$id) ->get(); return View::make('entrega.editpass', compact('entrega')); } public function updatePass($id) { $input = Input::all(); $rules = array('pass' => 'required|min:5', 'repass' => 'required|min:5' ); $validation = Validator::make($input, $rules); if($input['pass'] == $input['repass']){ $validacionPass = true; $msj = ''; }else{ $validacionPass = false; $msj = '.. Las contraseñas deben ser iguales'; } if($validation->passes() && $validacionPass) { $usuario = User::find($input['usuario_id']); $usuario->password = Hash::make($input['pass']); $usuario->save(); return Redirect::route('entrega.show',$id); } return Redirect::route('entrega.editPassword', $id) ->withInput() ->withErrors($validation) ->with('message','Existe un error al procesar la informacion'. $msj); } /** * Update the specified resource in storage. * * @param int $id * @return Response */ public function update($id) { $input = Input::all(); $validation = Validator::make($input, Entrega::$rulesSimple); if($validation->passes()) { $entrega = $this->entrega->find($id); $entrega->nombre = $input['nombre']; $entrega->email = $input['email']; $entrega->save(); $usuario = User::find($input['usuario_id']); $usuario->active = $input['status']; $usuario->save(); return Redirect::route('entrega.show', $id); } return Redirect::route('entrega.edit', $id) ->withInput() ->withErrors($validation) ->with('message','Existen errores al procesar la informacion'); } /** * Remove the specified resource from storage. * * @param int $id * @return Response */ public function destroy($id) { $usuario = User::find($id); $usuario->active = -1; $usuario->save(); return Redirect::route('entrega.index'); } }
Java
UTF-8
3,987
2.609375
3
[]
no_license
package com.passkey; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.security.KeyStore; import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.util.Enumeration; import com.sun.org.apache.xml.internal.security.utils.Base64; public class VerifiSign2 { public static void main(String[] args) { VerifiSign2 v=new VerifiSign2(); v.getPrivateKeyInfo(); v.getPublicKeyInfo(); } /** * 获取私钥别名等信息 */ public String getPrivateKeyInfo() { String privKeyFileString = "d:/test.pfx"; String privKeyPswdString = "cfca1234" ; String keyAlias = null; try { KeyStore keyStore = KeyStore.getInstance("PKCS12"); FileInputStream fileInputStream = new FileInputStream(privKeyFileString); char[] nPassword = null; if ((privKeyPswdString == null) || privKeyPswdString.trim().equals("")) { nPassword = null; } else { nPassword = privKeyPswdString.toCharArray(); } keyStore.load(fileInputStream, nPassword); fileInputStream.close(); System.out.println("keystore type=" + keyStore.getType()); Enumeration<String> enumeration = keyStore.aliases(); if (enumeration.hasMoreElements()) { keyAlias = (String) enumeration.nextElement(); System.out.println("alias=[" + keyAlias + "]"); } System.out.println("is key entry=" + keyStore.isKeyEntry(keyAlias)); PrivateKey prikey = (PrivateKey) keyStore.getKey(keyAlias, nPassword); Certificate cert = keyStore.getCertificate(keyAlias); PublicKey pubkey = cert.getPublicKey(); System.out.println("cert class = " + cert.getClass().getName()); System.out.println("cert = " + cert); System.out.println("public key = " + Base64.encode(pubkey.getEncoded())); System.out.println("private key = " + Base64.encode(prikey.getEncoded())); } catch (Exception e) { System.out.println(e); } return keyAlias; } /** * 获取公钥信息 */ public void getPublicKeyInfo() { String tmp0 = ""; String tmp1 = ""; try { tmp1 = getPublicKey("").replaceAll("\n", ""); System.out.println("商户公钥字符串:\n" + tmp1); System.out.println("\n商户公钥字符给定串:\n" + tmp0); if (tmp0.equals(tmp1)) System.out.println("========="); else { System.out.println("**************"); } } catch (CertificateException e) { e.printStackTrace(); System.out.println(e); } catch (IOException e) { e.printStackTrace(); System.out.println(e); } } /** * 读取公钥cer * * @param path * .cer文件的路径 如:c:/abc.cer * @return base64后的公钥串 * @throws IOException * @throws CertificateException */ public static String getPublicKey(String path) throws IOException, CertificateException { InputStream inStream = new FileInputStream(path); ByteArrayOutputStream out = new ByteArrayOutputStream(); int ch; String res = ""; while ((ch = inStream.read()) != -1) { out.write(ch); } byte[] result = out.toByteArray(); // res = Base64.byteArrayToBase64(result); res = Base64.encode(result); return res; } }
Python
UTF-8
832
2.890625
3
[]
no_license
def lps(pat,M,lps1): len1 = 0 lps1[0] = 0 i = 1 while i < M: if pat[i] == pat[len1]: len1 += 1 lps1[i] = len1 i += 1 else: if len1 != 0: len1 = lps1[len1 - 1] else: lps1[i] = 0 i += 1 def kmp(pat,text,list1): M = len(pat) N = len(text) lps1 = [0] * M j = 0 lps(pat,M,lps1) i = 0 while i < N: if pat[j] == text[i]: i += 1 j += 1 if j == M: #print i - j list1.append(i - j) #count += 1 j = lps1[j - 1] elif i < N and pat[j] != text[i]: if j != 0: j = lps1[j-1] else: i += 1 while True: try: M = input() pat = raw_input() text = raw_input() list1 = [] kmp(pat,text,list1) #print count for ele in list1: print ele if len(list1) == 0: print print except: break #DONE
C
UTF-8
950
2.984375
3
[]
no_license
#ifndef LANGANT_VIEW_H #define LANGANT_VIEW_H /* * If adding new colors, note: * 1. 0 is not assignable * 2. add the following line to view.c: * init_pair(####, COLOR_BLACK, COLOR_****); * where #### is the name of the macro and **** is the color of the background * 3. There is a maximum number of colors that can be used (ncurses.COLORS) * * If you wish to create a color with RGB, note the * int init_color(short index, short red, short green, short blue) method in ncurses. (value between 0 and 1000) * * e.g. * #define GRAY_INDEX 10 * init_color(GRAY_INDEX, 500, 500, 500); * init_pair(GRAY_INDEX, COLOR_BLACK, GRAY_INDEX); */ #define BLACK_INDEX 1 #define WHITE_INDEX 2 #define RED_INDEX 3 #define GREEN_INDEX 4 #define CYAN_INDEX 5 #define MAGENTA_INDEX 6 #define YELLOW_INDEX 7 #define BLUE_INDEX 8 #define ORANGE_INDEX 9 void init_view(); void draw_game(); void draw_border(); #endif //LANGANT_VIEW_H
Shell
UTF-8
5,635
3.453125
3
[ "Apache-2.0" ]
permissive
#!/bin/bash # # Copyright 2013 Jérôme Gasperi # # Licensed under the Apache License, version 2.0 (the "License"); # You may not use this file except in compliance with the License. # You may obtain a copy of the License at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # # Paths are mandatory from command line SUPERUSER=postgres DB=itag USER=itag HOSTNAME=localhost usage="## iTag French data sources installation\n\n Usage $0 -D <data directory> [-d <database name> -s <database SUPERUSER> -u <database USER> -F -H <server HOSTNAME>]\n\n -D : absolute path to the data directory containing french datasources\n -s : database SUPERUSER (default "postgres")\n -u : database USER (default "itag")\n -d : database name (default "itag")\n -H : postgres server hostname (default localhost)\n -F : drop schema datasources first\n" while getopts "D:d:s:u:H:hF" options; do case $options in D ) DATADIR=`echo $OPTARG`;; d ) DB=`echo $OPTARG`;; u ) USER=`echo $OPTARG`;; s ) SUPERUSER=`echo $OPTARG`;; H ) HOSTNAME=`echo "-h "$OPTARG`;; h ) echo -e $usage;; F ) DROPFIRST=YES;; \? ) echo -e $usage exit 1;; * ) echo -e $usage exit 1;; esac done if [ "$DATADIR" = "" ] then echo -e $usage exit 1 fi ##### DROP SCHEMA FIRST ###### if [ "$DROPFIRST" = "YES" ] then psql -d $DB -U $SUPERUSER -h $HOSTNAME << EOF DROP SCHEMA IF EXISTS france CASCADE; EOF fi psql -d $DB -U $SUPERUSER -h $HOSTNAME << EOF CREATE SCHEMA france; EOF # ================== France ===================== ## French communes shp2pgsql -g geom -W LATIN1 -s 2154:4326 -I $DATADIR/GEOFLA_2-1_COMMUNE_SHP_LAMB93_FXX_2015-12-01/GEOFLA/1_DONNEES_LIVRAISON_2015/GEOFLA_2-1_SHP_LAMB93_FR-ED152/COMMUNE/COMMUNE.shp france.commune | psql -d $DB -U $SUPERUSER -h $HOSTNAME shp2pgsql -g geom -a -W LATIN1 -s 4471:4326 -I $DATADIR/GEOFLA_2-1_COMMUNE_SHP_RGM04UTM38S_D976_2015-12-01/GEOFLA/1_DONNEES_LIVRAISON_2015/GEOFLA_2-1_SHP_RGM04UTM38S_D976-ED152/COMMUNE/COMMUNE.shp france.commune | psql -d $DB -U $SUPERUSER -h $HOSTNAME shp2pgsql -g geom -a -W LATIN1 -s 2975:4326 -I $DATADIR/GEOFLA_2-1_COMMUNE_SHP_RGR92UTM40S_D974_2015-12-01/GEOFLA/1_DONNEES_LIVRAISON_2015/GEOFLA_2-1_SHP_RGR92UTM40S_D974-ED152/COMMUNE/COMMUNE.shp france.commune | psql -d $DB -U $SUPERUSER -h $HOSTNAME shp2pgsql -g geom -a -W LATIN1 -s 2970:4326 -I $DATADIR/GEOFLA_2-1_COMMUNE_SHP_UTM20W84GUAD_D971_2015-12-01/GEOFLA/1_DONNEES_LIVRAISON_2015/GEOFLA_2-1_SHP_UTM20W84GUAD_D971-ED152/COMMUNE/COMMUNE.shp france.commune | psql -d $DB -U $SUPERUSER -h $HOSTNAME shp2pgsql -g geom -a -W LATIN1 -s 2973:4326 -I $DATADIR/GEOFLA_2-1_COMMUNE_SHP_UTM20W84MART_D972_2015-12-01/GEOFLA/1_DONNEES_LIVRAISON_2015/GEOFLA_2-1_SHP_UTM20W84MART_D972-ED152/COMMUNE/COMMUNE.shp france.commune | psql -d $DB -U $SUPERUSER -h $HOSTNAME shp2pgsql -g geom -a -W LATIN1 -s 2972:4326 -I $DATADIR/GEOFLA_2-1_COMMUNE_SHP_UTM22RGFG95_D973_2015-12-01/GEOFLA/1_DONNEES_LIVRAISON_2015/GEOFLA_2-1_SHP_UTM22RGFG95_D973-ED152/COMMUNE/COMMUNE.shp france.commune | psql -d $DB -U $SUPERUSER -h $HOSTNAME # update geometries in EPSG:4326 psql -d $DB -U $SUPERUSER -h $HOSTNAME << EOF ALTER TABLE france.commune ALTER COLUMN x_centroid TYPE decimal; ALTER TABLE france.commune ALTER COLUMN y_centroid TYPE decimal; ALTER TABLE france.commune ALTER COLUMN x_chf_lieu TYPE decimal; ALTER TABLE france.commune ALTER COLUMN y_chf_lieu TYPE decimal; UPDATE france.commune SET x_centroid = ST_X(ST_Transform(ST_SetSRID(ST_MakePoint(x_centroid,y_centroid), 2154), 4326)) WHERE code_reg NOT IN ('01', '02', '03', '04', '06'); UPDATE france.commune SET y_centroid = ST_Y(ST_Transform(ST_SetSRID(ST_MakePoint(x_centroid,y_centroid), 2154), 4326)) WHERE code_reg NOT IN ('01', '02', '03', '04', '06'); UPDATE france.commune SET x_chf_lieu = ST_X(ST_Transform(ST_SetSRID(ST_MakePoint(x_chf_lieu,y_chf_lieu), 2154), 4326)) WHERE code_reg NOT IN ('01', '02', '03', '04', '06'); UPDATE france.commune SET y_chf_lieu = ST_Y(ST_Transform(ST_SetSRID(ST_MakePoint(x_chf_lieu,y_chf_lieu), 2154), 4326)) WHERE code_reg NOT IN ('01', '02', '03', '04', '06'); UPDATE france.commune SET x_centroid = ST_X(ST_Transform(ST_SetSRID(ST_MakePoint(x_centroid,y_centroid), 2970), 4326)) WHERE code_reg = '01'; UPDATE france.commune SET x_centroid = ST_X(ST_Transform(ST_SetSRID(ST_MakePoint(x_centroid,y_centroid), 2973), 4326)) WHERE code_reg = '02'; UPDATE france.commune SET x_centroid = ST_X(ST_Transform(ST_SetSRID(ST_MakePoint(x_centroid,y_centroid), 2972), 4326)) WHERE code_reg = '03'; UPDATE france.commune SET x_centroid = ST_X(ST_Transform(ST_SetSRID(ST_MakePoint(x_centroid,y_centroid), 2975), 4326)) WHERE code_reg = '04'; UPDATE france.commune SET x_centroid = ST_X(ST_Transform(ST_SetSRID(ST_MakePoint(x_centroid,y_centroid), 4471), 4326)) WHERE code_reg = '06'; EOF psql -d $DB -U $SUPERUSER -h $HOSTNAME << EOF CREATE INDEX idx_communefrance_commune ON france.commune (nom_com); CREATE INDEX idx_communefrance_dept ON france.commune (nom_dept); CREATE INDEX idx_communefranc_region ON france.commune (nom_reg); EOF # GRANT RIGHTS TO itag USER psql -U $SUPERUSER -d $DB -h $HOSTNAME << EOF GRANT ALL on SCHEMA france to $USER; GRANT SELECT on france.commune to $USER; GRANT SELECT on france.commune_gid_seq to $USER; EOF
Markdown
UTF-8
1,725
3.421875
3
[]
no_license
# 第一次使用时建构 (Construct On First Use) ##目的 确保对象只在第一次使用到的时候才进行初始化,特别是全局的静态对象。 ##别名 延迟建构或求值 (Lazy construction/evaluation) ##动机 静态对象必须在被使用前进行建构,如果考虑不周,也可能在它的初始化程中访问到全局静态对象。 ``` struct Bar { Bar () { cout << "Bar::Bar()\n"; } void f () { cout << "Bar::f()\n"; } }; struct Foo { Foo () { bar_.f (); } static Bar bar_; }; Foo f; Bar Foo::bar_; int main () {} ``` 上面代码中,`Bar::f()`会在建构前被调用,这种情况通常是典型undefined问题,应该避免。 ##解决方案及示例 有两个解决方案,它们的分别取决于对象的析构函数是否有较为复杂的语义(non-trivial destruction semantics.)。将静态对象封装到一个函数中,这样函数可以确保在它使用前初始化它。 * 在第一次使用时,通过动态分配的方式建构 ``` struct Foo { Foo () { bar().f (); } Bar & bar () { static Bar *b = new Bar (); return *b; } }; ``` 如果对象析构的语义比较复杂,就可台通过下面的方式。 * 在第一次使用时,通过局部静态对象建构 ``` struct Foo { Foo () { bar().f (); } Bar & bar () { static Bar b; return b; } }; ``` ##已知的应用 * 单例模式经常使用这个方法。译注:另外还要考虑线程安全的解决方案Double check的方式。 * ACE(Adaptive Communication Environment)中ACE_TSS<T>模板类使用这个惯用法在TSS (Thread specific storage)中创建和使用对象。 ##相关的惯用法 * Nifty/Schwarz Counter ##参考
PHP
UTF-8
3,859
3.25
3
[ "MIT" ]
permissive
<?php namespace Smoren\MultiCurl; use RuntimeException; /** * MultiCurl wrapper for making parallel HTTP requests * @author <ofigate@gmail.com> Smoren */ class MultiCurl { /** * @var int max parallel connections count */ protected $maxConnections; /** * @var array<int, mixed> common CURL options for every request */ protected $commonOptions = []; /** * @var array<string, string> common headers for every request */ protected $commonHeaders = []; /** * @var array<string, array<int, mixed>> map of CURL options including headers by custom request ID */ protected $requestsConfigMap = []; /** * MultiCurl constructor * @param int $maxConnections max parallel connections count * @param array<int, mixed> $commonOptions common CURL options for every request * @param array<string, string> $commonHeaders common headers for every request */ public function __construct( int $maxConnections = 100, array $commonOptions = [], array $commonHeaders = [] ) { $this->maxConnections = $maxConnections; $this->commonOptions = [ CURLOPT_URL => '', CURLOPT_RETURNTRANSFER => 1, CURLOPT_ENCODING => '' ]; foreach($commonOptions as $key => $value) { $this->commonOptions[$key] = $value; } $this->commonHeaders = $commonHeaders; } /** * Executes all the requests and returns their results map * @param bool $dataOnly if true: return only response body data, exclude status code and headers * @param bool $okOnly if true: return only responses with (200 <= status code < 300) * @return array<string, mixed> responses mapped by custom request IDs * @throws RuntimeException */ public function makeRequests(bool $dataOnly = false, bool $okOnly = false): array { $runner = new MultiCurlRunner($this->requestsConfigMap, $this->maxConnections); $runner->run(); $this->requestsConfigMap = []; return $dataOnly ? $runner->getResultData($okOnly) : $runner->getResult($okOnly); } /** * Adds new request to execute * @param string $requestId custom request ID * @param string $url URL for request * @param mixed $body body data (will be json encoded if array) * @param array<int, mixed> $options CURL request options * @param array<string, string> $headers request headers * @return self */ public function addRequest( string $requestId, string $url, $body = null, array $options = [], array $headers = [] ): self { foreach($this->commonOptions as $key => $value) { if(!array_key_exists($key, $options)) { $options[$key] = $value; } } foreach($this->commonHeaders as $key => $value) { if(!array_key_exists($key, $headers)) { $headers[$key] = $value; } } if(is_array($body)) { $body = json_encode($body); } if($body !== null) { $options[CURLOPT_POSTFIELDS] = strval($body); } $options[CURLOPT_HTTPHEADER] = $this->formatHeaders($headers); $options[CURLOPT_URL] = $url; $this->requestsConfigMap[$requestId] = $options; return $this; } /** * Formats headers from associative array * @param array<string, string> $headers request headers associative array * @return array<string> headers array to pass to curl_setopt_array */ protected function formatHeaders(array $headers): array { $result = []; foreach($headers as $key => $value) { $result[] = "{$key}: {$value}"; } return $result; } }
TypeScript
UTF-8
7,035
2.734375
3
[ "ISC" ]
permissive
import { GlobalProvider } from '../code/globalprovider'; import { isNumber, isBoolean, isArray, isObject, isFunction } from '../code/utils'; /** * The support method for server side rendering method of components. Just import, but never call directly. The TypeScript compiler uses this function. * * It's a default export, so this import will work: * * `import JSX from '@nyaf/lib';` * * Usually it'S combined with the import of the base class: * * `import JSX, { BaseComppnent } from '@nyaf/lib';` * * Also, don't forget to setup *tsconfig.json* properly to support *jsx* and use the namespace JSX (in uppercase letters). * * */ const JSXSSR: any = { Fragment: null, createElement(name: string | null, props: { [id: string]: any }, ...content: string[]): string { content = [].concat.apply([], content); const flat = function (arr1: string[]): string[] { return arr1.reduce((acc: string[], val: string[] | string) => (Array.isArray(val) ? acc.concat(flat(val)) : acc.concat(val)), []); }; props = props || {}; let ifStore = true; let isRepeater = false; const styleStore: { [rule: string]: string } = {}; let propsstr = ''; if (props['n-repeat']) { try { const data: [] = isArray(props['n-repeat']) ? props['n-repeat'] : JSON.parse(props['n-repeat']); data.forEach(dataItem => { if (!isObject(dataItem)) { throw new Error('Element are not objects.') } }) delete props['n-repeat']; const resolvedProps = Object.assign({}, props); const processedProps: any[] = []; const processedContent = [...content]; const dataElements = data.map(dataItem => { Object.keys(props).forEach((prop: string) => { if (dataItem[props[prop]]) { if (props[prop].indexOf('@@') === 0) { resolvedProps[prop] = dataItem[props[prop].replace('@@', '')]; } else { resolvedProps[prop] = dataItem[props[prop]]; } processedProps.push(props[prop]); } }); for (let i = 0; i < content.length; i++) { Object.keys(dataItem).forEach(item => { processedContent[i] = content[i].replace(`@@${item}@@`, dataItem[item]); }); } return this.createElement(name, resolvedProps, processedContent); }); isRepeater = true; // props = undefined; processedProps.forEach(prop => { delete props[prop]; }) propsstr = dataElements.join(''); } catch (err) { console.error('Cannot parse n-repeat data. ' + err); } } if (name === 'n-bind' && props['data']) { // props['n-bind'] = `${props['data']}`; return `<!-- #n-bind=${props['data']}-->` } if (!isRepeater) { propsstr = Object.keys(props) .map(key => { // TODO: make this an Map and check for duplicate attributes let value = props[key]; switch (key) { // class allows an array case 'className': case 'class': if (Array.isArray(value)) { return `class="${(<any>value).join(' ')}"`; } else { return `class="${value}"`; } case 'n-hide': if (!!value) { styleStore['display'] = 'none'; } break; case 'n-show': if (!value) { styleStore['display'] = 'none'; } break; case 'n-else': ifStore = !value; break; case 'n-if': ifStore = !!value; break; case 'n-iif': const expression = props['n-iif']; // Create a proxy from expression // if proxy changes, evaluate expression // if false, remove element, but keep a parent reference // if true, use parent reference to re-add the element return `n-bind='${value.name}'`; case 'n-expand': return GlobalProvider.TagExpander.get(value)?.expand(); default: if (key.startsWith('n-on-')) { if (value.name === key) { return `${key}='${value.toString().replace(/'/g, '&#39;')}'`; } if (isFunction(value)) { return `${key}='this.${value.name}'`; } } // check for implicit bindings of complex objects // Stringify and mark as complex to handle the read/write procedure in the Proxy handler if (isArray(value)) { delete props[key]; return `${key}='${JSON.stringify(value)}' n-type-${key}='array'`; } else if (isObject(value)) { delete props[key]; return `${key}='${JSON.stringify(value)}' n-type-${key}='object'`; } else if (isBoolean(value)) { return `${key}='${JSON.stringify(value)}' n-type-${key}='boolean'`; } else if (isNumber(value)) { return `${key}='${JSON.stringify(value)}' n-type-${key}='number'`; } else { // single quotes to process JSON.stringify (needed, because web components support only string) // In case argument has already single quotes, we replace with escaped double quotes if (value !== null && value !== undefined) { const sanitizedValue = value.toString().replace(/'/g, '&quot;'); return `${key}='${sanitizedValue}'`; } if (value !== null) { return `${key}='${key}'`; } // we rule null out as "please don't write this attribute at all" } } }) .join(' ') || ''; if (!name) { return `${flat(content).join('')}`; // support for <> </> fake container tag } if (!ifStore) { return ''; // if excluded by condition return nothing at all before any further processing } if (styleStore && Object.keys(styleStore).length > 0) { const styles = Object.keys(styleStore).map(o => `${o}:${styleStore[o]};`); propsstr += `style="${styles}"`; } return `<${name}${propsstr ? ' ' : ''}${propsstr}>${flat(content).join('')}</${name}>`; } else { // if repeater, we don't return the former repeater template, but just the generated code return propsstr; } } }; export default JSXSSR;
Python
UTF-8
2,562
2.734375
3
[ "BSD-3-Clause" ]
permissive
import numpy as np import astropy.units as u from astropy.coordinates import SkyCoord from astropy.wcs.utils import pixel_to_skycoord import warnings def build_plotting_moc(moc, wcs): # Get the WCS cdelt giving the deg.px^(-1) resolution. cdelt = wcs.wcs.cdelt # Convert in rad.px^(-1) cdelt = np.abs((2*np.pi/360)*cdelt[0]) # Get the minimum depth such as the resolution of a cell is contained in 1px. depth_res = int(np.floor(np.log2(np.sqrt(np.pi/3)/cdelt))) depth_res = max(depth_res, 0) # Degrade the moc to that depth for plotting purposes. It is not necessary to plot pixels # that we will not see because they are contained in 1px. moc_plot = moc if moc.max_order > depth_res: moc_plot = moc.degrade_to_order(depth_res) moc_plot = moc_plot.refine_to_order(min_depth=2) # Get the MOC delimiting the FOV polygon width_px = int(wcs.wcs.crpix[0]*2.) # Supposing the wcs is centered in the axis heigth_px = int(wcs.wcs.crpix[1]*2.) # Compute the sky coordinate path delimiting the viewport. # It consists of a closed polygon of (4 - 1)*4 = 12 vertices x_px = np.linspace(0, width_px, 4) y_px = np.linspace(0, heigth_px, 4) X, Y = np.meshgrid(x_px, y_px) X_px = np.append(X[0, :-1], X[:-1, -1]) X_px = np.append(X_px, X[-1, 1:][::-1]) X_px = np.append(X_px, X[:-1, 0]) Y_px = np.append(Y[0, :-1], Y[:-1, -1]) Y_px = np.append(Y_px, Y[-1, :-1]) Y_px = np.append(Y_px, Y[1:, 0][::-1]) # Disable the output of warnings when encoutering NaNs. warnings.filterwarnings("ignore") # Inverse projection from pixel coordinate space to the world coordinate space viewport = pixel_to_skycoord(X_px, Y_px, wcs) # If one coordinate is a NaN we exit the function and do not go further ra_deg, dec_deg = viewport.icrs.ra.deg, viewport.icrs.dec.deg warnings.filterwarnings("default") if np.isnan(ra_deg).any() or np.isnan(dec_deg).any(): return moc_plot center_x_px, center_y_px = wcs.wcs.crpix[0], wcs.wcs.crpix[1] inside = pixel_to_skycoord(center_x_px, center_y_px, wcs) # Import MOC here to avoid circular imports from ..moc import MOC # Create a rough MOC (depth=3 is sufficient) from the viewport moc_viewport = MOC.from_polygon_skycoord(viewport, max_depth=3) # The moc to plot is the INPUT_MOC & MOC_VIEWPORT. For small FOVs this can reduce # a lot the time to draw the MOC along with its borders. moc_plot = moc_plot.intersection(moc_viewport) return moc_plot
Python
UTF-8
99
3.3125
3
[]
no_license
arr = [1,2,3,4,5] print arr[2:] print arr[-1::-1] print arr[:-2] for k in range(1,5): print k
JavaScript
UTF-8
983
2.78125
3
[]
no_license
const { Given, When, Then } = require('cucumber'); const assert = require('assert').strict; const restHelper = require('../util/resthelper'); Given('un contacto {}', (x) => { this.result = JSON.parse(x); }); When('envio una solicitud POST a {}', async (path) => { //console.log(`${process.env.SERVICE_URL}${path}`); this.response = await restHelper.postData(`http://localhost:80${path}`, this.result); }); Then('yo obtengo el codigo de respuesta {int}', async (code) => { assert.equal(this.response.status, code); }); Given('un id contacto {int}', (x) => { this.result = x ; }); When('envio una solicitud GET a {}', async (path) => { //console.log(`${process.env.SERVICE_URL}${path}`); this.response = await restHelper.getData(`http://localhost:80${path}${this.result}`); }); Then('yo obtengo la respuesta {}', async (expectedResponse) => { console.log(JSON.parse(expectedResponse)); assert.deepEqual(this.response.data, JSON.parse(expectedResponse)); });
Java
UTF-8
173
1.742188
2
[ "Apache-2.0" ]
permissive
package com.mycompany; public interface ApiPath { String PATH_CUSTOMER = "/customer", ID = "id", PATH_CUSTOMER_ID = "/customer/{" + ID + "}"; }
Python
UTF-8
836
2.890625
3
[ "BSD-2-Clause" ]
permissive
import logging from kafka import KafkaConsumer from kafka.errors import KafkaError def are_kafka_settings_valid(brokers, topics): """ Check to see if the broker(s) and topics exist. :param brokers: The broker names. :return: True if they exist. """ try: consumer = KafkaConsumer(bootstrap_servers=brokers) except KafkaError as error: logging.error(f"Could not connect to Kafka brokers: {error}") return False result = True try: existing_topics = consumer.topics() for tp in topics: if tp not in existing_topics: logging.error(f"Could not find topic: {tp}") result = False except KafkaError as error: logging.error(f"Could not get topics from Kafka: {error}") return False return result
Markdown
UTF-8
7,680
2.625
3
[]
no_license
# Kubernetes dynamic hostpath provisioner This is a Persistent Volume Claim (PVC) provisioner for Kubernetes. It dynamically provisions hostPath volumes to provide storage for PVCs. Please see [Original README](#original-readme) for more information. ## Test environment - IBM Cloud Private 3.1 (uses Kubernetes 1.11.1) with three worker nodes. - Each worker node has shared NFS directory. - [deployment.yaml](deployment/deployment.yaml) used to deploy provisioner to ICP. - [storageclass.yaml](deployment/storageclass.yaml) used to create StorageClass for dynamic provisioning. ## Usage - Set up NFS or some other network/shared storage to all worker nodes prior to deploying this provisioner. - Remember to configure the mounted directory in [deployment.yaml](deployment/deployment.yaml) and [storageclass.yaml](deployment/storageclass.yaml). - Deploy provisioner: - Change volume paths to your environment. Default is: ```/dynfs```. - ```kubectl create -f deployment/deployment.yaml``` - Create storage class: - Change name and other parameters to your own. Default storage class name is ```dynfs```. - If you want this to be default storage class, set the annotation to *true*. - Make sure that *pvDir* is the same as volume paths in deployment.yaml. - ```kubectl create -f deployment/storageclass.yaml``` - Test: - Create PVC: ```kubectl create -f deployment/testclaim.yaml``` - Verify that directory was created. - Delete PVC: ```kubectl delete -f deployment/testclaim.yaml``` - Verify that directory was deleted (only if claim policy was Delete). - When deploying workloads, use the storage class name when dynamically provisioning. ## Something to keep in mind - Provisioner uses privileged container. - [deployment.yaml](deployment/deployment.yaml) creates PodSecurityPolicy to allow it. - Paths of dynamically created directories: - ```/pvdir/namespace/claim-name``` - *pvdir*, directory given in StorageClass configuration and it must be mounted in provisioner (see both [deployment.yaml](deployment/deployment.yaml) and [storageclass.yaml](deployment/storageclass.yaml)). - *namespace* where PVC will be created. Default is *default* (which is ICP default namespace). - *claim-name* is the claim-name given when pod is deployed. If *claim-name* exists, a number is appended. - Directories that are created have 777 permissions. - If the mounted directory is deleted while the provisioner is deployed, provisioning may not work. - Default PersistentVolumeReclaimPolicy is Delete. When claim is deleted so is the provisioned directory. - This can be changed in StorageClass configuration. ## Changes from the original - Changed Dockerfile to build provisioner. No need to install Go on local machine. - Removed vendor-dir. - Copied new provisioner code from https://github.com/kubernetes-sigs/sig-storage-lib-external-provisioner/tree/master/examples/hostpath-provisioner and made changes based on the torchbox code. - Added sample yaml-files for deployment, storage class and claim. - PV dir name generated as in https://github.com/nmasse-itix/OpenShift-HostPath-Provisioner/blob/master/src/hostpath-provisioner/hostpath-provisioner.go. - Logging changes as in https://www.ardanlabs.com/blog/2013/11/using-log-package-in-go.html. - And some other changes. # Original README Kubernetes hostpath provisioner =============================== This is a Persistent Volume Claim (PVC) provisioner for Kubernetes. It dynamically provisions hostPath volumes to provide storage for PVCs. It is based on the [demo hostpath-provisioner](https://github.com/kubernetes-incubator/external-storage/tree/master/docs/demo/hostpath-provisioner). Unlike the demo provisioner, this version is intended to be suitable for production use. Its purpose is to provision storage on network filesystems mounted on the host, rather than using Kubernetes' built-in network volume support. This has some advantages over storage-specific provisioners: * There is no need to expose PV credentials to users (cephfs-provisioner requires this, for example). * PVs can be provisioned on network storage not natively supported in Kubernetes, e.g. `ceph-fuse`. * The network storage configuration is centralised on the node (e.g., in `/etc/fstab`); this means you can change the storage configuration, or even completely change the storage type (e.g. NFS to CephFS) without having to update every PV by hand. There are also some disadvantages: * Every node requires full access to the storage containing all PVs. This may defeat attempts to limit node access in Kubernetes, such as the Node authorizor. * Storage can no longer be introspected via standard Kubernetes APIs. * Kubernetes cannot report storage-related errors such as failures to mount storage; this information will not be available to users. * Moving storage configuration from Kubernetes to the host will not work well in environments where host access is limited, such as GKE. We test and use this provisioner with CephFS and `ceph-fuse`, but in principal it should work with any network filesystem. You **cannot** use it without a network filesystem unless you can ensure all provisioned PVs will only be used on the host where they were provisioned; this is an inherent limitation of `hostPath`. Unlike the demo hostpath-provisioner, there is no attempt to identify PVs by node name, because the intended use is with a network filesystem mounted on all hosts. Deployment ---------- ### Mount the network storage First, mount the storage on each host. You can do this any way you like; systemd mount units or `/etc/fstab` is the typical method. The storage **must** be mounted at the same path on every host. However you decide to provision the storage, you should set the mountpoint immutable: ``` # mkdir /mynfs # chattr +i /mynfs # mount -tnfs mynfsserver:/export/mynfs /mynfs ``` This ensures that nothing can be written to `/mynfs` if the storage is unmounted. Without this protection, a failure to mount the storage could result in PVs being provisioned on the host instead of on the network storage. This would initially appear to work, but then lead to data loss. Note that the immutable flag is set on the underlying mountpoint, *not* the mounted filesystem. Once the filesystem is mounted, the immutable mountpoint is hidden and files can be created as normal. ### Create a StorageClass The provisioner must be associated with a Kubernetes StorageClass: ``` apiVersion: storage.k8s.io/v1 kind: StorageClass metadata: name: cephfs annotations: storageclass.kubernetes.io/is-default-class: "true" provisioner: torchbox.com/hostpath parameters: pvDir: /ceph/pvs ``` * The `name` can be anything you like; you could name it after the storage type (such as `cephfs-ssd` or `bignfs`), or give it a generic name like `pvstorage`. * If you *don't* want this to be the default storage class, delete the `is-default-class` annotation; then this class will only be used if explicitly requested in the PVC. * Set `pvDir` to the root path on the host where volumes should be provisioned. This must be on network storage, but does not need to be the root of the storage or the mountpoint. * Unless you're running multiple provisioners, leave `provisioner` at the default `torchbox.com/hostpath`. If you want to run multiple provisioners, the value passed to `-name` when starting the provisioner must match the value of `provisioner`. ### Start the provisioner Please see the rest in [the original repository](https://github.com/torchbox/k8s-hostpath-provisioner/tree/fe8dcfde450cfbb505cb7f2044c404bc5b86bbc8).
Python
UTF-8
563
3.15625
3
[]
no_license
# Example One --> Timer from microbit import * currentDisplay = 0 def startTimer(): global currentDisplay while currentDisplay > 0: display.show(str(currentDisplay)) currentDisplay += -1; sleep(1000) if currentDisplay == 0: display.show(Image.HAPPY); while True: display.show(str(currentDisplay)) if button_a.is_pressed(): currentDisplay += 1; display.show(str(currentDisplay)) sleep(100) if button_b.is_pressed(): startTimer();
Python
UTF-8
807
2.71875
3
[ "MIT" ]
permissive
#!/usr/bin/env python2 # -*- coding: utf8 -*- # # Copyright (c) 2014 unfoldingWord # http://creativecommons.org/licenses/MIT/ # See LICENSE file for details. # # Contributors: # Jesse Griffin <jesse@distantshores.org> # ''' Returns version number of specified language. ''' import os import sys import json import urllib2 catalog_url = u'https://api.unfoldingword.org/obs/txt/1/obs-catalog.json' def getURL(url): try: request = urllib2.urlopen(url).read() return request except: print ' => ERROR retrieving {0}\nCheck the URL'.format(url) return if __name__ == '__main__': lang = sys.argv[1] cat = json.loads(getURL(catalog_url)) for x in cat: if lang == x['language']: print x['status']['version'] sys.exit(0) print 'NOT FOUND'
Java
UTF-8
1,814
2.84375
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.tsg.recharge; /** * * @author user */ public class LuhnAlgoImplValidateCreditCard { public static boolean Check(String LZ_CardNumber) { int sum = 0; boolean alternate = false; for (int i = LZ_CardNumber.length() - 1; i >= 0; i--) { int n = Integer.parseInt(LZ_CardNumber.substring(i, i + 1)); if (alternate) { n *= 2; if (n > 9) { n = (n % 10) + 1; } } sum += n; alternate = !alternate; } return (sum % 10 == 0); } public static String getCreditCardType(String LZ_CardNumber) { String LZ_CardType = ""; if (LZ_CardNumber.startsWith("4")) { LZ_CardType = "VISA"; } else if (LZ_CardNumber.startsWith("51") || LZ_CardNumber.startsWith("52") || LZ_CardNumber.startsWith("53") || LZ_CardNumber.startsWith("54") || LZ_CardNumber.startsWith("55")) { LZ_CardType = "MASTER"; } else if (LZ_CardNumber.startsWith("34") || LZ_CardNumber.startsWith("37") || LZ_CardNumber.startsWith("30")) { LZ_CardType = "AMEX"; } return LZ_CardType; } public String validateCardExpiryAndCVV(String expiry,String cvv) { String response = ""; return response; } public static void main(String... args) { String creditCardNo = "5176521007767041"; LuhnAlgoImplValidateCreditCard lhn = new LuhnAlgoImplValidateCreditCard(); boolean status = lhn.Check(creditCardNo); System.out.println("status=" + status + "CatrdType=" + lhn.getCreditCardType("5176521007767041")); } }
Java
UTF-8
1,079
2.0625
2
[]
no_license
package com.jrtp.ies.dc.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import com.jrtp.ies.constants.AppConstants; import com.jrtp.ies.dc.model.IncomeDetail; import com.jrtp.ies.dc.service.DataCollectionService; @Controller public class SnapController { @Autowired private DataCollectionService dataCollectionServ; @PostMapping("saveSnapDetails") public String handleNextBtn(@ModelAttribute("incomeDet") IncomeDetail incomeDet, Model model) { boolean isIncomeDetSaved = dataCollectionServ.saveIncomeDetails(incomeDet); String pageName = null; if(isIncomeDetSaved) { model.addAttribute("caseId", incomeDet.getCaseId()); pageName = "eligibilityDetermination"; }else { model.addAttribute("failMsg", AppConstants.SNAP_CASE+" "+AppConstants.PLAN_SAVE_ERRMSG); pageName = "incomeDetails"; } return pageName; } }
JavaScript
UTF-8
965
2.609375
3
[]
no_license
var zurag = [ "url(1.jpg)", "url(2.jpg)", "url(3.jpg)", "url(4.jpg)", "url(5.jpg)", "url(6.jpg)", "url(7.jpg)" ]; i = 0; document.querySelector("button").addEventListener("click", function(){ i = i < zurag.length ? ++i : 0; document.querySelector("body").style.background = zurag[i] }) var ungu = [ "#ef5777" , "#575fcf" , "#4bcffa" , "#34e7e4" , "#0be881" , "#ffc048" , "#485460" ]; var i = 0; function first(){ i = i < ungu.length ? ++i : 0; document.querySelector(".oorch , #text").style.background = ungu[i] } function second(){ document.querySelector("#text").innerHTML = "Okey I change it" } i = 0; function three(){ i = i < ungu.length ? ++i : 0; document.querySelector("#text").style.color = ungu[i] }
Shell
UTF-8
364
2.5625
3
[]
no_license
#!---------------------------------------------------------------------------- #! #! changeAsetup.sh #! #! change Asetup default version #! #! Usage: #! source changeAsetup.sh <version> #! #! History: #! 27Apr15: A. De Silva, First version #! #!---------------------------------------------------------------------------- export ALRB_asetupVersion=$1 return 0
TypeScript
UTF-8
25,027
3.328125
3
[]
no_license
/** * Converts object properties to Mongoose enum (string array) * * @param {any} obj * @returns {string[]} */ function obj2enum(obj: any): string[] { let arr: string[] = [] for (let key in obj) { arr.push(obj[key]) } return arr } /*************************** * UPLOAD IMAGE PROCESSING * ***************************/ /** * Interface for image types * * @interface IImageTypes */ interface IImageTypes { AVATAR: string PHOTO: string } /** * Image types * * @constant IMAGE_TYPES * @type {IImageTypes} */ export const IMAGE_TYPES: IImageTypes = { AVATAR: 'avatar', PHOTO: 'photo' } /** * Suffix for thumbnail images * * @constant THUMBNAIL * @type {string} */ export const THUMBNAIL = '.thumb' /** * .75x | ldpi | 120dpi | 240px * 1x | mdpi | 160dpi | 320px * 1.5x | hdpi | 240dpi | 480px * 2x | xhdpi | 320dpi | 720px * 3x | xxhdpi | 480dpi | 1080px * 4x | xxxhdpi | 640dpi | 1440px */ /** * Interface for different image sizes in pixels, * each set is a tuple in the format of [number, number, boolean] * representing width, height and whether this is the default set * * @interface IImageSizes */ interface IImageSizes { [key: string]: [number, number | null, boolean][] AVATAR: [number, number, boolean][] PHOTO: [number, number | null, boolean][] } /** * @constant IMAGE_SIZES * @type {IImageSizes} */ export const IMAGE_SIZES: IImageSizes = { AVATAR: [ [48, 48, true], // for Android [32, 32, false], [48, 48, false], [64, 64, false], [96, 96, false], [128, 128, false], // for iOS [40, 40, false], [80, 80, false], [120, 120, false], // for OKII watches [36, 36, false], [46, 46, false], [56, 56, false], [148, 148, false], [168, 168, false], ], PHOTO: [ [240, null, true], // for Android [320, null, false], [480, null, false], [720, null, false], [1080, null, false], [1440, null, false], // for iOS [640, null, false], // iPhone SE [750, null, false], // iPhone 6/7/8 [1125, null, false], // iPhone X [1242, null, false] // iPhone 6/7/8 Plus ] } /************************************************* * TOTP (Time-based One-time Password algorithm) * *************************************************/ /** * Interface for TOTP types * * @interface ITotpTypes */ interface ITotpTypes { EMAIL: string SMS: string QR: string } /** * TOTP types * in key/value-pair format * * @constant TOTP_TYPES * @type {ItotpTypes} */ export const TOTP_TYPES: ITotpTypes = { EMAIL: 'email', SMS: 'sms', QR: 'qr' } export namespace Status { enum totp { email = 'email', sms = 'sms', qr = 'qr' } } /** * TOTP types * in string array format * * @constant TOTP_TYPES_ENUM * @type {string[]} */ export const TOTP_TYPES_ENUM: string[] = obj2enum(TOTP_TYPES) /********************** * USER RELATED ITEMS * **********************/ /** * Interface for user types * * @interface IUserTypes */ interface IUserTypes { CONSUMER: string PROVIDER: string PLATFORM: string } /** * User types, using model names for referencing * in key/value-pair format * * @constant * @type {IUserTypes} */ export const USER_TYPES: IUserTypes = { CONSUMER: 'Consumer', PROVIDER: 'Provider', PLATFORM: 'Platform' } /** * User types * in string array format */ export const USER_TYPES_ENUM: string[] = obj2enum(USER_TYPES) /** * Interface for user roles * * @interface IUserRoles */ interface IUserRoles { CONSUMER: { GUEST: string MEMBER: string CONTRIBUTOR: string AUTHOR: string ORGANIZER: string } PROVIDER: { STAFF: string SUPERVISOR: string MANAGER: string } PLATFORM: { ADMIN: string EDITOR: string SUPER: string } } /** * User roles * in key/value-pair format * * @constant USER_ROLES * @type {IUserRoles} */ export const USER_ROLES: IUserRoles = { CONSUMER: { GUEST: 'guest', MEMBER: 'member', CONTRIBUTOR: 'contributor', AUTHOR: 'author', ORGANIZER: 'organizer' }, PROVIDER: { STAFF: 'staff', SUPERVISOR: 'supervisor', MANAGER: 'manager' }, PLATFORM: { ADMIN: 'admin', EDITOR: 'editor', SUPER: 'super' } } /** * User roles * in string array format * * @constant CONSUMER_USER_ROLES_ENUM * @type {string[]} */ export const CONSUMER_USER_ROLES_ENUM: string[] = obj2enum(USER_ROLES.CONSUMER) /** * @constant PROVIDER_USER_ROLES_ENUM * @type {string[]} */ export const PROVIDER_USER_ROLES_ENUM: string[] = obj2enum(USER_ROLES.PROVIDER) /** * @constant PLATFORM_USER_ROLES_ENUM * @type {string[]} */ export const PLATFORM_USER_ROLES_ENUM: string[] = obj2enum(USER_ROLES.PLATFORM) /** * Interface for content creator roles * * @interface ICreatorRoles */ interface ICreatorRoles { [key: string]: string[] POST: string[] EVENT: string[] } /** * Content creator roles * * @constant CONTENT_CREATOR_ROLES * @type {ICreatorRoles} */ export const CONTENT_CREATOR_ROLES: ICreatorRoles = { POST: [ USER_ROLES.CONSUMER.CONTRIBUTOR, USER_ROLES.CONSUMER.AUTHOR ], EVENT: [ USER_ROLES.CONSUMER.ORGANIZER ] } /****************************************** * USER GROUP MEMBERSHIP CONTROL SETTINGS * ******************************************/ /** * Interface for user membership control settings * * @interface IUserActions */ interface IGroup_Settings { MEMBERSHIP: { CLOSED: string OPEN: string MANAGED: string } } /** * User group membership settings * in key/value-pair format * * @constant GROUP_SETTINGS * @type {IGroup_Settings} */ export const GROUP_SETTINGS: IGroup_Settings = { MEMBERSHIP: { CLOSED: 'closed', OPEN: 'open', MANAGED: 'managed' } } /** * User group membership settings * in string array format * @constant GROUP_SETTINGS_MEMBERSHIP_ENUM * @type {string[]} */ export const GROUP_SETTINGS_MEMBERSHIP_ENUM: string[] = obj2enum(GROUP_SETTINGS.MEMBERSHIP) /***************************** * USER ACTION RELATED ITEMS * *****************************/ /** * Interface for user actions * * @interface IUserActions */ interface IUserActions { COMMON: { LIST: string GET: string UNIQUE: string CREATE: string UPDATE: string UPLOAD: string DELETE: string LOGIN: string LOGOUT: string RESET_PASSWORD: string } CONSUMER: { LIKE: string UNDO_LIKE: string DISLIKE: string UNDO_DISLIKE: string SAVE: string UNDO_SAVE: string SHARE: string DOWNLOAD: string REMOVE: string FOLLOW: string UNFOLLOW: string SUBSCRIBE: string UNSUBSCRIBE: string SUBMIT: string RETRACT: string REPORT: string CHAT: string } PROVIDER: { ENROLL: string UNDO_ENROLL: string SUBMIT: string RETRACT: string CHAT: string } PLATFORM: { REQUEST: string HOLD: string CANCEL: string VERIFY: string APPROVE: string REJECT: string SUSPEND: string } GROUP: { ADD_MEMBER: string KICK_MEMBER: string TRANSFER_MANAGER: string } } /** * User actions * in key/value-pair format * * @constant USER_ACTIONS * @type {IUserActions} */ export const USER_ACTIONS: IUserActions = { COMMON: { LIST: 'LIST', GET: 'GET', UNIQUE: 'UNIQUE', CREATE: 'CREATE', UPDATE: 'UPDATE', UPLOAD: 'UPLOAD', DELETE: 'DELETE', LOGIN: 'LOGIN', LOGOUT: 'LOGOUT', RESET_PASSWORD: 'RESET_PASSWORD' }, CONSUMER: { LIKE: 'LIKE', UNDO_LIKE: 'UNDO_LIKE', DISLIKE: 'DISLIKE', UNDO_DISLIKE: 'UNDO_DISLIKE', SAVE: 'SAVE', UNDO_SAVE: 'UNDO_SAVE', SHARE: 'SHARE', DOWNLOAD: 'DOWNLOAD', REMOVE: 'REMOVE', FOLLOW: 'FOLLOW', UNFOLLOW: 'UNFOLLOW', SUBSCRIBE: 'SUBSCRIBE', UNSUBSCRIBE: 'UNSUBSCRIBE', SUBMIT: 'SUBMIT', RETRACT: 'RETRACT', REPORT: 'REPORT', CHAT: 'CHAT' }, PROVIDER: { ENROLL: 'ENROLL', UNDO_ENROLL: 'UNDO_ENROLL', SUBMIT: 'SUBMIT', RETRACT: 'RETRACT', CHAT: 'CHAT' }, PLATFORM: { REQUEST: 'REQUEST', HOLD: 'HOLD', CANCEL: 'CANCEL', VERIFY: 'VERIFY', APPROVE: 'APPROVE', REJECT: 'REJECT', SUSPEND: 'SUSPEND' }, GROUP: { ADD_MEMBER: 'ADD_MEMBER', KICK_MEMBER: 'KICK_MEMBER', TRANSFER_MANAGER: 'TRANSFER_MANAGER' } } /** * User actions * in string array format * * @constant CONSUMER_USER_ACTIONS_ENUM * @type {string[]} */ export const CONSUMER_USER_ACTIONS_ENUM: string[] = obj2enum(USER_ACTIONS.CONSUMER) /** * @constant PROVIDER_USER_ACTIONS_ENUM * @type {string[]} */ export const PROVIDER_USER_ACTIONS_ENUM: string[] = obj2enum(USER_ACTIONS.PROVIDER) /** * @constant PLATFORM_USER_ACTIONS_ENUM * @type {string[]} */ export const PLATFORM_USER_ACTIONS_ENUM: string[] = obj2enum(USER_ACTIONS.PLATFORM) /** * Interface for user action targets * * @interface IActionTargets */ interface IActionTargets { [key: string]: string CONSUMER: string PROVIDER: string PLATFORM: string GROUP: string POST: string EVENT: string SIGNUP: string PRODUCT: string ORDER: string COMMENT: string PROCESS: string ACTIVITY: string REMINDER: string } /** * User action targets * in key/value-pair format * * @constant ACTION_TARGETS * @type {IActionTargets} */ export const ACTION_TARGETS: IActionTargets = { CONSUMER: 'Consumer', PROVIDER: 'Provider', PLATFORM: 'Platform', GROUP: 'Group', POST: 'Post', EVENT: 'Event', SIGNUP: 'Signup', PRODUCT: 'Product', ORDER: 'Order', COMMENT: 'Comment', PROCESS: 'Process', ACTIVITY: 'Activity', REMINDER: 'Reminder' } /** * User action targets * in string array format * * @constant ACTION_TARGETS_ENUM * @type {string[]} */ export const ACTION_TARGETS_ENUM: string[] = obj2enum(ACTION_TARGETS) /** * Interface for action models * * @interface IActionModels */ interface IActionModels { [key: string]: string LIKE: string DISLIKE: string SAVE: string SHARE: string DOWNLOAD: string FOLLOW: string } /** * Action models * in key/value-pair format * * @constant ACTION_MODELS * @type {IActionModels} */ export const ACTION_MODELS: IActionModels = { LIKE: 'Like', DISLIKE: 'Dislike', SAVE: 'Save', SHARE: 'Share', DOWNLOAD: 'Download', FOLLOW: 'Follow' } /** * Action models * in string array format * * @constant ACTION_MODELS_ENUM * @type {string[]} */ export const ACTION_MODELS_ENUM: string[] = obj2enum(ACTION_MODELS) /******************************* * OBJECT STATUS RELATED ITEMS * *******************************/ /** * Interface for object statuses * * @interface IStatuses */ interface IStatuses { [key: string]: { [key: string]: string } CONSUMER: { ACTIVE: string SUSPENDED: string } PROVIDER: { ACTIVE: string SUSPENDED: string } PLATFORM: { ACTIVE: string SUSPENDED: string } GROUP: { ACTIVE: string SUSPENDED: string } CONTENT: { EDITING: string PENDING: string APPROVED: string REJECTED: string SUSPENDED: string EXPIRED: string } EVENT_BATCH: { ACCEPTING: string FILLED: string PASTDUE: string CONCLUDED: string SUSPENDED: string } SIGNUP: { PENDING: string APPROVED: string REJECTED: string } PAYMENT: { PENDING: string PROCESSING: string SUCCESS: string VERIFIED: string FAILED: string CANCELED: string DUPLICATED: string NETWORK: string UNKNOWN: string } PROCESS: { PENDING: string CANCELLED: string FINALIZED: string } } /** * Object statuses * in key/value-pair format * * @constant STATUSES * @type {IStatuses} */ export const STATUSES: IStatuses = { CONSUMER: { ACTIVE: 'active', SUSPENDED: 'suspended' }, PROVIDER: { ACTIVE: 'active', SUSPENDED: 'suspended' }, PLATFORM: { ACTIVE: 'active', SUSPENDED: 'suspended' }, GROUP: { ACTIVE: 'active', SUSPENDED: 'suspended' }, CONTENT: { EDITING: 'editing', PENDING: 'pending', APPROVED: 'approved', REJECTED: 'rejected', SUSPENDED: 'suspended', EXPIRED: 'expired' }, EVENT_BATCH: { ACCEPTING: 'accepting', FILLED: 'filled', PASTDUE: 'pastdue', CONCLUDED: 'concluded', SUSPENDED: 'suspended' }, SIGNUP: { PENDING: 'pending', APPROVED: 'approved', REJECTED: 'rejected', }, PAYMENT: { PENDING: 'pending', PROCESSING: 'processing', SUCCESS: 'success', VERIFIED: 'verified', FAILED: 'failed', CANCELED: 'canceled', DUPLICATED: 'duplicated', NETWORK: 'network connection error', UNKNOWN: 'unknown' }, PROCESS: { PENDING: 'pending', CANCELLED: 'cancelled', FINALIZED: 'finalized' } } /** * Object statuses * in string array format * * @constant CONSUMER_STATUSES_ENUM * @type {string[]} */ export const CONSUMER_STATUSES_ENUM: string[] = obj2enum(STATUSES.CONSUMER) /** * @constant PROVIDER_STATUSES_ENUM * @type {string[]} */ export const PROVIDER_STATUSES_ENUM: string[] = obj2enum(STATUSES.PROVIDER) /** * @constant PLATFORM_STATUSES_ENUM * @type {string[]} */ export const PLATFORM_STATUSES_ENUM: string[] = obj2enum(STATUSES.PLATFORM) /** * @constant GROUP_STATUSES_ENUM * @type {string[]} */ export const GROUP_STATUSES_ENUM: string[] = obj2enum(STATUSES.GROUP) /** * @constant POST_STATUSES_ENUM * @type {string[]} */ export const POST_STATUSES_ENUM: string[] = obj2enum(STATUSES.CONTENT) /** * @constant EVENT_STATUSES_ENUM * @type {string[]} */ export const EVENT_STATUSES_ENUM: string[] = obj2enum(STATUSES.CONTENT) /** * @constant EVENT_BATCH_STATUSES_ENUM * @type {string[]} */ export const EVENT_BATCH_STATUSES_ENUM: string[] = obj2enum(STATUSES.EVENT_BATCH) /** * @constant SIGNUP_STATUSES_ENUM * @type {string[]} */ export const SIGNUP_STATUSES_ENUM: string[] = obj2enum(STATUSES.SIGNUP) /** * @constant PAYMENT_STATUSES_ENUM * @type {string[]} */ export const PAYMENT_STATUSES_ENUM: string[] = obj2enum(STATUSES.PAYMENT) /** * @constant TODOLIST_STATUSES_ENUM * @type {string[]} */ export const TODOLIST_STATUSES_ENUM: string[] = obj2enum(STATUSES.CONTENT) /********************************* * CONTENT SETTING RELATED ITEMS * *********************************/ /** * Interface for content settings * * @interface IContent_Settings */ interface IContent_Settings { [key: string]: { [key: string]: string } COMMENT: { OPEN: string CLOSED: string } RECURRENCE: { DAY_OF_WEEK: string DATE_OF_MONTH: string DAY_OF_MONTH: string DATE_OF_YEAR: string DAY_OF_YEAR: string WORKDAYS: string WEEKDAYS: string WEEKENDS: string } } export const CONTENT_SETTINGS: IContent_Settings = { COMMENT: { OPEN: 'open', CLOSED: 'closed' }, RECURRENCE: { DAY_OF_WEEK: 'day_of_week', DATE_OF_MONTH: 'date_of_month', DAY_OF_MONTH: 'day_of_month', DATE_OF_YEAR: 'date_of_year', DAY_OF_YEAR: 'day_of_year', WEEKDAYS: 'weekdays', WEEKENDS: 'weekends', WORKDAYS: 'workdays' } } /** * @constant COMMENT_SETTINGS_ENUM * @type {string[]} */ export const COMMENT_SETTINGS_ENUM: string[] = obj2enum(CONTENT_SETTINGS.COMMENT) /** * @constant RECURRENCE_ENUM * @type {string[]} */ export const RECURRENCE_ENUM: string[] = obj2enum(CONTENT_SETTINGS.RECURRENCE) /******************************************* * ADMINISTRATIVE PROCESSING RELATED ITEMS * *******************************************/ /** * Interface for process types * * @interface IProcessTypes */ interface IProcessTypes { APPROVAL: string } /** * Process types * in key/value-pair format * * @constant PROCESS_TYPES * @type {IProcessTypes} */ export const PROCESS_TYPES: IProcessTypes = { APPROVAL: 'approval' } /** * Process types * in string array format * * @constant PROCESS_TYPES_ENUM * @type {string[]} */ export const PROCESS_TYPES_ENUM: string[] = obj2enum(PROCESS_TYPES) /** * Interface for activity states * * @interface IActivityStates */ interface IActivityStates { READY: string PROCESSING: string COMPLETED: string } /** * Activity states * in key/value-pair format * * @constant ACTIVITY_STATES * @type {IActivityStates} */ export const ACTIVITY_STATES: IActivityStates = { READY: 'ready', PROCESSING: 'processing', COMPLETED: 'completed' } /** * Activity states * in string array format * * @constant ACTIVITY_STATES_ENUM * @type {string[]} */ export const ACTIVITY_STATES_ENUM: string[] = obj2enum(ACTIVITY_STATES) /********************* * INVITATION STATES * *********************/ /** * Interface for invitation states * * @interface IInvitationStates */ interface IInvitationStates { PENDING: string ACCEPTED: string REJECTED: string IGNORED: string EXPIRED: string WITHDRAWN: string } /** * Invitation states * in key/value-pair format * * @constant INVITATION_STATES * @type {IActivityStates} */ export const INVITATION_STATES: IInvitationStates = { PENDING: 'pending', ACCEPTED: 'accepted', REJECTED: 'rejected', IGNORED: 'ignored', EXPIRED: 'expired', WITHDRAWN: 'withdrawn' } /** * Invitation states * in string array format * * @constant INVITATION_STATES_ENUM * @type {string[]} */ export const INVITATION_STATES_ENUM: string[] = obj2enum(INVITATION_STATES) /******************* * PAYMENT METHODS * *******************/ /** * Interface for payment methods * * @interface IPaymentMethods */ interface IPaymentMethods { CASH: string ALIPAY: string WECHAT: string PAYPAL: string } /** * Payment methods * in key/value-pair format * * @constant PAYMENT_METHODS * @type {IPaymentMethods} */ export const PAYMENT_METHODS: IPaymentMethods = { CASH: 'cash', ALIPAY: 'Alipay', WECHAT: 'WeChat_Pay', PAYPAL: 'PayPal' } /** * Payment methods * in string array format * * @constant PAYMENT_METHODS_ENUM * @type {string[]} */ export const PAYMENT_METHODS_ENUM: string[] = obj2enum(PAYMENT_METHODS) /********************** * VIEW RELATED ITEMS * **********************/ /** * Consumer user default handle prefix * * @constant CONSUMER_HANDLE_PREFIX * @type {string} */ export const CONSUMER_HANDLE_PREFIX: string = 'User_' /** * Provider user default handle prefix * * @constant PROVIDER_HANDLE_PREFIX * @type {string} */ export const PROVIDER_HANDLE_PREFIX: string = 'User_' /** * Platform user default handle prefix * * @constant PLATFORM_HANDLE_PREFIX * @type {string} */ export const PLATFORM_HANDLE_PREFIX: string = 'Admin_' /** * Default number of list items per page * * @constant DEFAULT_PAGE_COUNT * @type {number} */ export const DEFAULT_PAGE_COUNT: number = 20 /** * Default number of comments to showcase * * @constant COMMENT_SHOWCASE_COUNT * @type {number} */ export const COMMENT_SHOWCASE_COUNT: number = 3 /** * Consumer information opened to the public * * @constant PUBLIC_CONSUMER_INFO * @type {string} */ export const PUBLIC_CONSUMER_INFO: string = 'handle gender avatar status points level viewCount commentCount postCount eventCount likes dislikes saves shares dowloads followers followings' /** * Consumer information embeded in lists * * @constant PUBLIC_CONSUMER_INFO_LIST * @type {string} */ export const PUBLIC_CONSUMER_INFO_LIST: string = 'handle gender avatar status points level totalFollowers viewCount postCount eventCount commentCount' /** * Basic consumer information * * @constant BASIC_USER_INFO * @type {string} */ export const BASIC_USER_INFO: string = 'handle username avatar status points level' /** * Basic content information * shared across posts, events, etc. * * @constant BASIC_CONTENT_INFO * @type {string} */ export const BASIC_CONTENT_INFO: string = 'title slug' /** * Content (including posts and events) counters * * @constant COUNTERS * @type {string} */ const COUNTERS: string = ' viewCount commentCount likeCount dislikeCount saveCount shareCount downloadCount' /** * Number of posts shown in short lists * * @constant CONSUMER_POST_SHOWCASE_COUNT * @type {number} */ export const CONSUMER_POST_SHOWCASE_COUNT: number = 3 /** * Post fields displayed within a list * * @constant CONSUMER_POST_SHOWCASE_KEYS * @type {string} */ export const CONSUMER_POST_SHOWCASE_KEYS: string = 'slug title excerpt hero tags' + COUNTERS /** * Number of events shown in short lists * * @constant CONSUMER_EVENT_SHOWCASE_COUNT * @type {number} */ export const CONSUMER_EVENT_SHOWCASE_COUNT: number = 3 /** * Event fields displayed within a list * * @constant CONSUMER_EVENT_SHOWCASE_KEYS * @type {string} */ export const CONSUMER_EVENT_SHOWCASE_KEYS: string = 'slug title excerpt hero tags' + COUNTERS /** * List sort order * * @interface ISortOrder */ interface ISortOrder { viewCount: number _id: number } /** * Default list sort order * * @constant DEFAULT_SORT_ORDER * @type {ISortOrder} */ export const DEFAULT_SORT_ORDER: ISortOrder = { viewCount: -1, _id: -1 } /** * Fields to show on comment's parent * * @constant COMMENT_PARENT_FIELD_LIST * @type {string} */ export const COMMENT_PARENT_FIELD_LIST: string = 'creator slug title excerpt comments commentCount totalRating averageRating' /** * Fields to show on like's parent * * @constant LIKE_PARENT_FIELD_LIST * @type {string} */ export const LIKE_PARENT_FIELD_LIST: string = 'creator slug title excerpt likes likeCount' /** * Sublists * * @constant SUBLISTS * @type {string} */ export const SUBLISTS: string[] = ['likes', 'dislikes', 'saves', 'shares', 'downloads'] /** * User information not directly updatable via API */ export const USER_UNUPDATABLE_FIELDS: string = '_id id ref updated roles status verified expires history points level balance viewCount commentCount postCount eventCount signupCount orderCount' /** * Content information not directly updatable via API */ export const CONTENT_UNUPDATABLE_FIELDS: string = '_id id status updated totalRating commentCount viewCount likeCount dislikeCount saveCount shareCount downloadCount' /************************ * DEVICE RELATED ITEMS * ************************/ /** * Interface for local storage types * * @interface IStorageType */ interface IStorageType { ASYNC: string LOCAL: string } /** * Local storage types * in key/value-pair format * * @constant STORAGE_TYPES * @type {IStorageType} */ export const STORAGE_TYPES: IStorageType = { ASYNC: 'ASYNC', LOCAL: 'LOCAL' } /** * Interface for local storage keys * * @interface IStorageKey */ interface IStorageKey { ACCESS_TOKEN: string USER: string } /** * Local storage keys * * @constant STORAGE_KEY * @type {IStorageKey} */ export const STORAGE_KEY: IStorageKey = { ACCESS_TOKEN: 'token', USER: 'user' } /**************************** * INPUT FORM RELATED ITEMS * ****************************/ /** * Interface for common user input limits * * @interface IInputLimits */ interface IInputLimits { MIN_HANDLE_LENGTH: number MAX_HANDLE_LENGTH: number MIN_PASSWORD_LENGTH: number MAX_PASSWORD_LENGTH: number MIN_NAME_LENGTH: number MAX_NAME_LENGTH: number MIN_USERNAME_LENGTH: number MAX_USERNAME_LENGTH: number } /** * Common user input limits * * @constant INPUT_LIMITS * @type {IInputLimits} */ export const INPUT_LIMITS: IInputLimits = { MIN_HANDLE_LENGTH: 2, MAX_HANDLE_LENGTH: 20, MIN_PASSWORD_LENGTH: 6, MAX_PASSWORD_LENGTH: 20, MIN_NAME_LENGTH: 0, MAX_NAME_LENGTH: 50, MIN_USERNAME_LENGTH: 6, MAX_USERNAME_LENGTH: 30 } /** * Interface for administrative user input limits * * @interface IPlatformLimits */ interface IPlatformLimits { MIN_USERNAME_LENGTH: number MAX_USERNAME_LENGTH: number MIN_PASSWORD_LENGTH: number MAX_PASSWORD_LENGTH: number // MIN_HANDLE_LENGTH: number // MAX_HANDLE_LENGTH: number // MIN_NAME_LENGTH: number // MAX_NAME_LENGTH: number } /** * Administrative user input limits * * @constant PLATFORM_LIMITS * @type {IPlatformLimits} */ export const PLATFORM_LIMITS: IPlatformLimits = { MIN_USERNAME_LENGTH: INPUT_LIMITS.MIN_USERNAME_LENGTH, MAX_USERNAME_LENGTH: INPUT_LIMITS.MAX_USERNAME_LENGTH, MIN_PASSWORD_LENGTH: INPUT_LIMITS.MIN_PASSWORD_LENGTH, MAX_PASSWORD_LENGTH: INPUT_LIMITS.MAX_PASSWORD_LENGTH } /** * THIRD-PARTY CONFIGURATIONS */ export const PAYMENT_REQUEST_URLS = { ALIPAY: { DIST: "https://openapi.alipay.com/gateway.do?", DEV: "https://openapi.alipaydev.com/gateway.do?" } } /** * APP CONSTANTS * */ export const ACCESS_TOKEN: string = 'access_token' export const USER: string = 'user' interface IAccountActions { LOGIN: string BIND: string SIGNUP: string } export const ACCOUNT_ACTIONS: IAccountActions = { LOGIN: 'LOGIN', BIND: 'BIND', SIGNUP: 'SIGNUP' }
Markdown
UTF-8
4,435
3
3
[]
no_license
--- title: 'Nuclear Throne: a case study in player feedback' author: Malcolm layout: post redirect_from: wp/nuclear-throne-a-case-study-in-player-feedback/165/ categories: - blog tags: - games - analysis --- Nuclear Throne, an early access retro-styled action game from [Vlambeer][1], has held my attention since I bought it last week. The randomly generated levels maintain balance, the game is challenging but rarely unfair, and the game looks great, but what is most impressive is the 'juiciness' it provides. <iframe width="420" height="315" src="https://www.youtube.com/embed/xn46bj4r0so" frameborder="0" allowfullscreen></iframe> Juiciness, in games, is usually described as 'the satisfying feeling when potential energy is converted into kinetic energy.' More loosely it's the feedback presented to the user upon input, and it can have a huge impact on the 'feel' of a game, the part that talks to a player's subconscious. Nuclear Throne is at its juiciest, appropriately enough given its action focus, the moment you fire your weapon. #### Picking up a weapon We've heard that half the fun is in the anticipation, and Nuclear Throne provides this by hinting at the kinetic energy present the moment you pick up a weapon. A crossbow will show a red line stretching across the screen from the character, and the player's view will shift slightly further away from the character and towards the crosshair, hinting at a long range accurate attack. Change weapons to a shotgun and the screen will close in on the player again, as if zooming in on the focus point of action. #### Firing Audio and visuals combine to make every click feel powerful and physical by maximizing feedback. The screen judders back for a fraction of a second away from the direction of firing, imitating the kick of every trigger pull. Larger weapons have a more pronounced screen shake, that appear to shake the room instead of just tapping it back and almost appear to push the character backwards. Simultaneously, you'll hear the sound of the gun firing, and each weapon type is immediately recognizable, with shotguns giving a low bark and lasers a brief zap. <iframe src="http://gfycat.com/ifr/ArtisticCarelessAkitainu" frameborder="0" scrolling="no" width="576" height="360" style="-webkit-backface-visibility: hidden;-webkit-transform: scale(1);" ></iframe> #### Impact Unlike the firing noises, the impact sound effect is nearly always the same. When the bullets are flying and you're racing for cover while firing blindly into a mass of enemies, the brief thud of impact indicating one of your shots connected provides immediate feedback to the player. In addition, to emphasise the amount of potential energy expended with each shot, upon death the cartoonish enemies' corpses will fling across the room, impacting (and damaging) environmental objects and even other enemies. Certain weapons, like explosives, will show their impact not just with impact sprites, sound, and screen shake but by actually destroying portions of the wall around them. This destruction of what in other games would be immutable emphasises the danger to the player of standing too close, and also indicates the approximate radius of such danger. Other weapons have their own special behaviour upon impact. Shotgun pellets reflect individually off walls, each with their own impact sound. Arrows fired from crossbows thump as they pass through multiple enemies and finally impact in a wall. #### Extrinsic reward Enemies drop experience points, and with upgrades can also provide health and ammunition. It's also necessary to defeat everyone to proceed to the next level. These extrinsic rewards provide the end of this feedback loop, and provide a gameplay-affecting reason to re-enter the loop. The dropped vials of experience also pull towards the character as they near, like the game-world manifestation of the players desire. #### Maximizing output for input The final effect is that each weapon feels very different from any other, and without needing to spend extensive time learning each one, players can follow hints of screen shake, sound effects, projectile speed and so forth to hint at the potential uses of each. For me, this stacking of feedback all adds up to a experience that feels *solid,* in a way that's easy to understand upon playing but hard to communicate otherwise. [1]: http://www.vlambeer.com/
Java
UTF-8
1,857
2.15625
2
[]
no_license
package com.icbc.api; import org.junit.Test; import static org.junit.Assert.*; import com.icbc.api.request.B2cPassfreePaymentPayRequestV3; import com.icbc.api.request.B2cPassfreePaymentPayRequestV3.B2cPassfreePaymentPayRequestV3Biz; import com.icbc.api.response.B2cPassfreePaymentPayResponseV3; public class B2cPassfreePaymentPayV3Test { //appid protected static final String APP_ID = "xxxxx"; //合作方私钥 protected static final String MY_PRIVATE_KEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALAWAcPiTMRU906PTdy0ozspX7XptZnkEw2C8R64RDB9BiRFXAj0cU4aTA1MyfmGIlceeVdgJf7OnmvpHnYxjQ7sGxMItPtodrGwA2y8j0AEbHc5pNWU8Hn0zoY9smHS5e+KjSbWv+VNbdnrRFTpDeiJ3+s2E/cKI2CDRbo7cAarAgMBAAECgYABiA933q4APyTvf/uTYdbRmuiEMoYr0nn/8hWayMt/CHdXNWs5gLbDkSL8MqDHFM2TqGYxxlpOPwnNsndbW874QIEKmtH/SSHuVUJSPyDW4B6MazA+/e6Hy0TZg2VAYwkB1IwGJox+OyfWzmbqpQGgs3FvuH9q25cDxkWntWbDcQJBAP2RDXlqx7UKsLfM17uu+ol9UvpdGoNEed+5cpScjFcsB0XzdVdCpp7JLlxR+UZNwr9Wf1V6FbD2kDflqZRBuV8CQQCxxpq7CJUaLHfm2kjmVtaQwDDw1ZKRb/Dm+5MZ67bQbvbXFHCRKkGI4qqNRlKwGhqIAUN8Ynp+9WhrEe0lnxo1AkEA0flSDR9tbPADUtDgPN0zPrN3CTgcAmOsAKXSylmwpWciRrzKiI366DZ0m6KOJ7ew8z0viJrmZ3pmBsO537llRQJAZLrRxZRRV6lGrwmUMN+XaCFeGbgJ+lphN5/oc9F5npShTLEKL1awF23HkZD9HUdNLS76HCp4miNXbQOVSbHi2QJAUw7KSaWENXbCl5c7M43ESo9paHHXHT+/5bmzebq2eoBofn+IFsyJB8Lz5L7WciDK7WvrGC2JEbqwpFhWwCOl/w=="; //网关公钥 protected static final String APIGW_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwFgHD4kzEVPdOj03ctKM7KV+16bWZ5BMNgvEeuEQwfQYkRVwI9HFOGkwNTMn5hiJXHnlXYCX+zp5r6R52MY0O7BsTCLT7aHaxsANsvI9ABGx3OaTVlPB59M6GPbJh0uXvio0m1r/lTW3Z60RU6Q3oid/rNhP3CiNgg0W6O3AGqwIDAQAB"; @Test public void test_cop() throws IcbcApiException { DefaultIcbcClient client = new DefaultIcbcClient(APP_ID, MY_PRIVATE_KEY, APIGW_PUBLIC_KEY); B2cPassfreePaymentPayRequestV3 request = new B2cPassfreePaymentPayRequestV3(); //根据测试环境和生产环境替换相应ip和端口 request.setServiceUrl("https://ip:port/api/b2c/passfree/payment/pay/V3"); B2cPassfreePaymentPayRequestV3Biz bizContent = new B2cPassfreePaymentPayRequestV3Biz(); bizContent.setConsumerId("xxx"); bizContent.setOrderDate("20161029204438"); bizContent.setOrderId("20161029000111"); bizContent.setAmount("10000"); bizContent.setMerchantId("1234567890"); bizContent.setExternalAgreementNo("xxxxxxx"); bizContent.setMerchantAcct("xxxxx"); bizContent.setMerchantType("1"); bizContent.setTimeout("900"); bizContent.setExtendParams("abcdef"); request.setBizContent(bizContent); B2cPassfreePaymentPayResponseV3 response; boolean testFlag = true; try { response = client.execute(request, "msgId"); if (response.isSuccess()) { // 业务成功处理 // String orderId = response.getOrderId(); testFlag = true; } else { // 失败 testFlag = false; } assertEquals(true, testFlag); } catch (IcbcApiException e) { e.printStackTrace(); } } }
C#
UTF-8
2,191
3.046875
3
[]
no_license
using System; using System.Linq; using System.Windows.Input; using Prism.Commands; using Prism.Mvvm; namespace HQF.Tutorial.JsonFormater.ViewModels { public class ViewAViewModel : BindableBase { public ViewAViewModel() { // This command will be executed when the selection of the ListBox in the view changes. this.FormatJsonCommand = new DelegateCommand(OnItemSelected ,()=>!string.IsNullOrEmpty(OrignJson)); } public ICommand FormatJsonCommand { get; private set; } private string _orignJson = "{ \"Data\":\"Hello World\" }"; private string _formatedJson; public string OrignJson { get { return _orignJson; } set { SetProperty(ref _orignJson, value); } } public string FormatedJson { get { return _formatedJson; } set { SetProperty(ref _formatedJson, value); } } private void OnItemSelected() { FormatedJson=JsonHelper.FormatJson(OrignJson); } } public class JsonHelper { private const string INDENT_STRING = " "; public static string FormatJson(string json) { int indentation = 0; int quoteCount = 0; var result = from ch in json let quotes = ch == '"' ? quoteCount++ : quoteCount let lineBreak = ch == ',' && quotes % 2 == 0 ? ch + Environment.NewLine + String.Concat(Enumerable.Repeat(INDENT_STRING, indentation)) : null let openChar = ch == '{' || ch == '[' ? ch + Environment.NewLine + String.Concat(Enumerable.Repeat(INDENT_STRING, ++indentation)) : ch.ToString() let closeChar = ch == '}' || ch == ']' ? Environment.NewLine + String.Concat(Enumerable.Repeat(INDENT_STRING, --indentation)) + ch : ch.ToString() select lineBreak == null ? openChar.Length > 1 ? openChar : closeChar : lineBreak; return String.Concat(result); } } }
TypeScript
UTF-8
1,824
3.140625
3
[ "MIT" ]
permissive
import lineReader from 'line-reader' type Reader = typeof lineReader.open extends (file, cb: (err, reader: infer P) => void) => void ? P : never const createReader = (filename: string): Promise<Reader> => new Promise((resolve, reject) => { lineReader.open(filename, (err, reader) => { if (err) { reject(err) } else { resolve(reader) } }) }) const nextLine = (reader: Reader): Promise<string> => new Promise((resolve, reject) => { reader.nextLine((err, line) => { if (err) { reject(err) } else { resolve(line) } }) }) const closeReader = (reader: Reader): Promise<void> => new Promise((resolve, reject) => { reader.close(err => { if (err) reject(err) else resolve() }) }) export interface LineReader { getLineNumber(): number hasNextLine(): boolean nextLine(): Promise<string> } export class FileLineReader { private readonly filename: string private reader: Reader private lineNumber: number = -1 constructor(filename: string) { this.filename = filename } getLineNumber(): number { return this.lineNumber } hasNextLine(): boolean { return this.reader.hasNextLine() } async nextLine(): Promise<string> { if (!this.reader) { this.reader = await createReader(this.filename) } if (!this.reader.hasNextLine()) { await closeReader(this.reader) return null } ++this.lineNumber return await nextLine(this.reader) } }
Go
UTF-8
3,787
2.828125
3
[]
no_license
package main import ( "context" "fmt" "io" "log" "net" "strconv" "time" "github.com/andreasatle/grpc-go-course/greet/greetpb" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/reflection" ) // server implements the GreetServiceServer interface. // This is confusing, since there are more than one of GreetManyTimes in the auto-generated file. type server struct{} func (s *server) Greet(ctx context.Context, req *greetpb.GreetRequest) (*greetpb.GreetResponse, error) { fmt.Printf("Server Greet function invoked with req: %v\n", req) res := &greetpb.GreetResponse{ Result: "Hello " + req.GetGreeting().GetFirstName(), } return res, nil } func (s *server) GreetManyTimes(req *greetpb.GreetManyTimesRequest, stream greetpb.GreetService_GreetManyTimesServer) error { fmt.Printf("Server GreetManyTimes function invoked with req: %v\n", req) firstName := req.GetGreeting().GetFirstName() for i := 0; i < 10; i++ { result := "Hello " + firstName + " " + strconv.Itoa(i) res := &greetpb.GreetManyTimesResponse{ Result: result, } err := stream.Send(res) if err != nil { log.Fatalf("Error sending data to client: %v\n", err) return err } time.Sleep(time.Second) } return nil } func (s *server) LongGreet(stream greetpb.GreetService_LongGreetServer) error { fmt.Println("Server LongGreet function invoked") result := "" for { req, err := stream.Recv() if err == io.EOF { // Once client done, then return the result. return stream.SendAndClose(&greetpb.LongGreetResponse{ Result: result, }) } if err != nil { log.Fatalf("Error receiving stream from client: %v\n", err) return err } // retrieve next first name. firstName := req.GetGreeting().GetFirstName() log.Println("Received data from client:", req) result += "Hello " + firstName + "! " } } func (s *server) GreetAll(stream greetpb.GreetService_GreetAllServer) error { fmt.Println("Server GreetAll function invoked") for { req, err := stream.Recv() if err == io.EOF { return nil } if err != nil { log.Fatalf("Error receiving data from client: %v\n", err) return err } firstName := req.GetGreeting().GetFirstName() result := "Hello " + firstName + "!" err = stream.Send(&greetpb.GreetAllResponse{ Result: result, }) if err != nil { log.Fatalf("Error sending data to client: %v\n", err) return err } } } func (s *server) GreetWithDeadline(ctx context.Context, req *greetpb.GreetWithDeadlineRequest) (*greetpb.GreetWithDeadlineResponse, error) { fmt.Printf("Server GreetWithDeadline function invoked with req: %v\n", req) for i := 0; i < 3; i++ { if ctx.Err() == context.Canceled { fmt.Println("The client canceled the request") } time.Sleep(time.Second) } res := &greetpb.GreetWithDeadlineResponse{ Result: "Hello " + req.GetGreeting().GetFirstName(), } return res, nil } func main() { // Setup the logging, for if program crashes log.SetFlags(log.LstdFlags | log.Lshortfile) fmt.Println("Hello, I'm serving a greeting!") // Start a tcp listener listener, err := net.Listen("tcp", "0.0.0.0:50051") if err != nil { log.Fatalf("Failed to listen at tcp: %v\n", err) } tls := true opts := []grpc.ServerOption{} if tls { certFile := "ssl/server.crt" keyFile := "ssl/server.pem" creds, err := credentials.NewServerTLSFromFile(certFile, keyFile) if err != nil { log.Fatal("Error loading certificates: %v", err) return } opts = append(opts, grpc.Creds(creds)) } // Create a new server s := grpc.NewServer(opts...) // Register service greetpb.RegisterGreetServiceServer(s, &server{}) reflection.Register(s) // Serve service if err := s.Serve(listener); err != nil { log.Fatalf("Failed to serve: %v\n", err) } }
C++
UTF-8
548
3.203125
3
[]
no_license
//author @Nishant /* Compact matrix and vector types: a. Using the cv::Mat33f and cv::Vec3f objects (respectively), create a 3 × 3 matrix and 3-row vector. b. Can you multiply them together directly? If not, why not? */ #include <opencv2/opencv.hpp> #include <iostream> using namespace cv; using namespace std; int main(int argc, char **argv){ Matx33f M(1, 2, 3, 4, 5, 6, 7, 8, 9); Vec3f V (1,2,3); Mat A = Mat(M); Mat B = Mat(V); Mat AB1 = A*B; //vector multiplication Mat AB2 = A.mul(B); //multiplication return 0; }
JavaScript
UTF-8
874
2.65625
3
[]
no_license
var http = require("http"); var fs = require("fs"); var data = [ { EmpNo: 101, EmpName: "ABC" }, { EmpNo: 102, EmpName: "CDS" }, { EmpNo: 103, EmpName: "CDCDF" } ]; var server = http.createServer(function(request, response) { // response.writeHead(200,{'Content-Type':' text/html'}); // response.write('hello '); // response.writeHead(200,{'Content-Type':' application/json'}); // response.write(JSON.stringify(data)); // response.end(); fs.readFile("./home.html", (err, data) => { if (err) { response.writeHead(404, { "Content-Type": " text/html" }); response.write("error"); response.end(); } else { response.writeHead(200, { "Content-Type": " text/html" }); response.write(data.toString()); response.end(); } }); }); server.listen(4050); console.log("Server up on 4050");
Java
UTF-8
221
1.898438
2
[]
no_license
package com.syntax.class21; public class ProgLanguageTest { public static void main(String[] args) { Java java=new Java("Java", "instance, local, static","Parameterized and non argument"); java.details(); } }