branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep>This deliverable details the results of task T2.4, in which we have compiled and trained
a library of models for enriching images with meta-data using recent advances in
state-of-the-art deep learning techniques.
## Deep Learning
Deep-learning is a subset of machine learning techniques ([Bishop 2006](#references)) which aims to perform simultaneous feature extraction and model training from labelled or unlabelled examples. Typically models are either feedforward or recurrent neural networks consisting of multiple layers of alternating linear-transformation followed by non-linear activation functions, hence the term "deep" ([Goodfellow et al. 2016](#references)).
The roots of deep-learning can be traced back to the early days of computer science, with the first multi-layer neural networks going back to at least as early as [Ivakhnenko & Lapa (1967)](#references). However it has not been until recent years that advances in data collection, parallel architectures and computational power have enabled large scale deep-learning, performing tasks such as image recognition ([Krizhevsky et al. 2012](#references)), language modeling ([Sutskever et al. 2011](#references)) and machine translation ([Sutskever et el. 2014](#references)) close to human-level performance.
More formally, given input and output data $$(x_i, y_i)$$, where the "input", $$x_i$$ is parametrized as a vector in a high dimensional vector space $$x_i \in \mathbb{R}^d$$, *supervised* deep learning is concerned with learning a function between this tuple:
$$f: x \longmapsto y$$
Such that $$\forall i \in 1, \dots, n$$:
$$f(x_i) \approx y_i$$
It is possible to prove that a simple "two-layered" perceptron is sufficient to express the multitude of all such functions, given conditions on differentiability and compactness of the domain of the function ([Cybenko 1989](#references)):
$$f(x) := W_o \sum_{j=1}^m \text{tanh}(W_x x + b_b) + b_o$$
However in principle, any number of "layers" may be applied to approach the task of finding a map between the two spaces:
$$f: = g_n \circ g_{n-1} \circ \dots g_1 \circ g_0$$
## Computer Vision
A text-book application of deep-learning, and indeed machine learning, is computer vision ([Goodfellow et al. 2016](#references)). Computer vision is the research field which pursues the goal (among others) of replicating the functionality of the human visual system using computer modelling and programs. In the early days of computer vision, methods were often based on painstakingly hand-crafted feature engineering using heuristics and extensive trial and error ([Lowe 1999](#references)). [Krizhevsky et al. (2012)](#references) showed that these features may be learnt more easily, achieving vastly superior performance, in a data driven way using neural networks with several important innovations over traditional neural networks:
- Many data points $$(x_i, y_i)$$ should be seen in training. This number of data points may only be handled by a "stochastic gradient descent algorithm" and parallel computation on a graphical processing unit (GPU), with data-parallelism over "mini-batches" of data points.
- Many more layers of alternating linear functions and non-linearities should be learnt than the traditional two or three layers.
- Explosion in the number of parameters should be restricted through the extensive use of "convolutional" layers in the initial stages of the neural network, i.e. tiled layerwise spatial filtering with learnt filter coefficients and expansion of the RGB channel space.
- Gradients should be forced to be well behaved through these layers using a "rectified linear-unit" non-linearity: $$\sigma(x) = \text{max}(0, x)$$
- Available data should be augmented using random affine transformations to avoid overfitting on the available training data.
## Natural Language Processing
In analogy to computer vision, natural language processing (NLP) is the research field which pursues the goal (among others) of replicating human linguistic ability using computer modelling and programs. As for computer vision, in the early days of NLP, methods were often based on painstakingly hand-crafted feature engineering using heuristics and extensive trial and error ([Liddy (2001)). Work on deep learning showed that these features may be learnt more easily, achieving superior performance, in a data driven way using recurrent neural networks (RNNs). Critical here are the following features in learning:
- Some technique must be used to combat vanishing/ exploding gradients encountered in e.g. traditional Elman RNNs. The prototypical method to achieve this is using a gated recurrent architecture, such as the LSTM ([Hochreiter & Schidhüber 2001](#references)).
- The use of attentional mechanisms is known to improve performance and learning ([Graves et al. 2014)](#references).
- As in computer vision, mini-batch learning with stochastic gradient descent must be used to combat the large dataset sizes.
- Parallelism across mutliple GPUs is necessary to tackle the large size of linguistic datasets.
- Various dropout techniques (ensembling methods applied to neural networks) may be applied in the case of smaller dataset sizes.
## Deep Learning in Fashion
Fashion is in many senses the prototypical and paradigmatic application of deep learning and computer vision in industry. The essence of fashion products is typically only captured by high resolution photos (or indeed videos), with companies such as Zalando SE (FB partner) displaying as many as seven high quality images of products as well as short video snippets of models demonstrating the products. The desideratum for deep-learning powered computer vision, that data be plentifully available, is additional exemplified in e-commerce companies such as Zalando SE, insofar as typically of the order of $$\sim 10^6$$ products are available in product catalogues as any given time.
The business case for deep-learning in fashion stems from the need to process and categorize this vast amount of product data and glean algorithms to further recommend products to suitable customers, intelligently index product data for search and perform high level tasks typically performed at great cost by domain experts, such as outfit construction.
## Tasks Addressed
In this deliverable we provide a schematic codebase and illustrative applications of deep-learning applied to fashion images. The final months of the work package will be used applying this schematic to the data obtained in T2.1 and T2.2. Using data from the historical Zalando catalogue already provided in the Fashion Project, we have trained a deep neural networks to perform:
1. Colour classification
2. Brand classification
3. Clothing type classification
4. Image annotation
## Overview of the Architectures
Our computer vision architecture is a classical 50 layered residual network ("resnet50") ([He et al. 2015](#references)). Residual networks have become the accepted architecture for performing image classification in computer vision due to their smooth gradients, accurate performance and modularity. See the image below for a schematic of a 34-layered residual network ("resnet34").
<img src="img/resnet.svg" style="width:450px"/>
For image annotation we use a gated recurrent unit (GRU) architecture, with initial hidden state initialized by the output of a *resnet50*:
<img src="img/annotation.svg" style="width:450px"/>
## Model Training and Codebase
Code is available here for download: https://github.com/zalandoresearch/fb-model-library
### Classification
A typical call to train a model image library takes the form:
```bash
python classify.py \
--mode train \
--model_type <brand/color/pool> \
--checkpoint <save-path> \
--lr <learning-rate> \
--n_epochs <number-of-epochs> \
> <save-path>/log
```
Visualization of training-progress as displayed in the log file may be invoked by:
```bash
python classify.py \
--mode plot \
--checkpoint <save-path>
```
The trained model may be tested by:
```bash
python classify.py \
--mode test \
--checkpoint <save-path>
```
At the highest level, the classification model, which is written in the Pytorch framework, is summarised as follows:
```python
class Classify(torch.nn.Module):
def __init__(self, n_classes, finetune=False):
torch.nn.Module.__init__(self)
self.cnn = resnet()
self.linear = torch.nn.Linear(2048, n_classes)
self.finetune = finetune
def forward(self, x):
if self.finetune:
return self.linear(self.cnn.features(x))
else:
return self.linear(self.cnn.features(x).detach())
```
Hence the nuts and bolts of the convolutional neural network are contained in the function ```resnet```.
### Image Annotation
Training proceeds by:
```bash
python annotate.py \
--mode train \
--catalog <dataset> \
--checkpoint <save-path> \
--lr <learning-rate> \
--n_epochs <number-of-epochs> \
> <save-path>/log
```
The core model in this task is:
```python
class Annotator(torch.nn.Module):
def __init__(self, n_vocab):
torch.nn.Module.__init__(self)
self.rnn = torch.nn.GRU(64, 512, 1, batch_first=False)
self.embed = torch.nn.Embedding(n_vocab, 64)
self.project = torch.nn.Linear(512, n_vocab)
self.init = torch.nn.Linear(2048, 512)
def forward(self, x, y, hidden=None):
if hidden is None:
hidden = self.init(x)
hidden = hidden[None, :, :]
hidden, _ = self.rnn(self.embed(y), hidden)
return self.project(hidden), hidden
def annotate(self, x, start, finish):
last = torch.LongTensor([start])
y = [start]
while True:
if len(y) == 1:
out, hidden = self(x[None, :], last[None, :])
else:
out, hidden = self(x[None, :], last[None, :], hidden)
last = out.squeeze().topk(1)[1]
y.append(last.item())
if y[-1] == finish:
break
return y
```
## References
<NAME>. (2006). Machine learning and pattern recognition. Information Science and Statistics. Springer, Heidelberg. [[url](https://www.springer.com/de/book/9780387310732?referer=www.springer.de)]
Goodfellow, I., <NAME>., <NAME>., & <NAME>. (2016). Deep learning (Vol. 1). Cambridge: MIT press. [[url](http://www.deeplearningbook.org/)]
<NAME>. (1999). Object recognition from local scale-invariant features. In *Computer vision, 1999. The proceedings of the seventh IEEE international conference on* (Vol. 2, pp. 1150-1157)
<NAME>., & <NAME>. (1967). Cybernetics and forecasting techniques. [[url](https://books.google.de/books/about/Cybernetics_and_forecasting_techniques.html?id=rGFgAAAAMAAJ&redir_esc=y)]
<NAME>., <NAME>., & <NAME>. (2012). Imagenet classification with deep convolutional neural networks. In *Advances in neural information processing systems* (pp. 1097-1105). [[url](http://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf)]
<NAME>., <NAME>., & <NAME>. (2011). Generating text with recurrent neural networks. In *Proceedings of the 28th International Conference on Machine Learning (ICML-11)* (pp. 1017-1024). [[url](https://www.cs.utoronto.ca/~ilya/pubs/2011/LANG-RNN.pdf)]
<NAME>., <NAME>., & <NAME>. (2014). Sequence to sequence learning with neural networks. In *Advances in neural information processing systems* (pp. 3104-3112). [[url](http://papers.nips.cc/paper/5346-sequence-to-sequence-learning-with-neural-networks.pdf)]
<NAME>. (1989). Approximation by superpositions of a sigmoidal function. *Mathematics of control, signals and systems*, *2*(4), 303-314. [[url](https://pdfs.semanticscholar.org/05ce/b32839c26c8d2cb38d5529cf7720a68c3fab.pdf)]
<NAME>., <NAME>., <NAME>., & <NAME>. (2016). Deep residual learning for image recognition. In *Proceedings of the IEEE conference on computer vision and pattern recognition* (pp. 770-778). [[url](http://openaccess.thecvf.com/content_cvpr_2016/papers/He_Deep_Residual_Learning_CVPR_2016_paper.pdf)]
<NAME>. (2001). Natural language processing.
<NAME>., <NAME>., & <NAME>. (2014). Neural turing machines. *arXiv preprint arXiv:1410.5401*.
<file_sep>import argparse
import classify
import json
import matplotlib.pyplot
import numpy
import os
import pandas
import PIL
import re
import torch
import torch.utils.data
import torchabc
import torchvision
class Data(torchabc.data.MultiModalData):
def __init__(self, dir_='data/coco'):
super().__init__(dir_=dir_, sep='\t')
class Iterator(torchabc.data.MultiModalIterator):
def __init__(self, data, fold='train', ssd=False):
super().__init__(
data,
fold=fold,
types_={'annotation': 'word', 'file_': 'image'},
stop=True,
start=True,
ssd=ssd,
)
normalize = torchvision.transforms.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225],
)
self.trans_ = torchvision.transforms.Compose([
torchvision.transforms.Resize(256),
torchvision.transforms.CenterCrop(224),
torchvision.transforms.ToTensor(),
normalize,
])
def reverse_batch(self, item):
y, l, x = self[item]
print(self.df.file_.iloc[item])
str_ = ' '.join(list(map(
self.lookup.__getitem__,
y.tolist()[:l.item() + 1],
)))
print(str_)
class Annotator(torch.nn.Module):
def __init__(self, n_vocab=1249):
torch.nn.Module.__init__(self)
self.resnet = classify.resnet()
self.rnn = torch.nn.GRU(64, 512, 1)
self.embed = torch.nn.Embedding(n_vocab, 64)
self.project = torch.nn.Linear(512, n_vocab)
self.init = torch.nn.Linear(2048, 512)
def forward(self, x, y, hidden=None):
if hidden is None:
hidden = self.init(self.resnet.features(x).detach())
hidden = hidden[None, :, :]
hidden, _ = self.rnn(self.embed(y.transpose(1, 0)), hidden)
return self.project(hidden), hidden
def feed(self, y, l, x):
return self(x, y)
def init_weights(self):
torch.nn.init.xavier_normal_(self.project.weight)
torch.nn.init.xavier_normal_(self.embed.weight)
torch.nn.init.xavier_normal_(self.init.weight)
def annotate(self, x, start, finish, sample=True):
last = torch.LongTensor([start])
y = [start]
hidden = None
while True:
out, hidden = self(x[None, :, :, :], last[None, :], hidden)
if sample:
p = out.squeeze().exp() / out.squeeze().exp().sum()
choice = numpy.random.choice(len(p), p=p.detach().numpy())
last = torch.LongTensor([choice])
y.append(choice)
else:
choice = out.topk(1)[1].squeeze().item()
y.append(choice)
last = torch.LongTensor([choice])
if y[-1] == finish:
break
return y
class Trainer(torchabc.train.Trainer):
def __init__(self,
save_,
dataset='coco',
n_epochs=2,
lr=0.01,
batch_size=2,
num_workers=0,
ssd=False,
subsample=None):
data = Data('data/' + dataset)
model = Annotator(len(data.dictionary))
optimizer = torch.optim.SGD(model.parameters(), lr=lr, momentum=0.9)
argz = {
'weights_interval': 25,
'dump_interval': 100,
'callback_interval': 1,
'n_epochs': n_epochs,
'annealing': 4,
'batch_size': batch_size,
'subsample': subsample,
'num_workers': num_workers,
'ssd': ssd,
}
super().__init__(
save_,
model,
data,
Iterator,
optimizer,
**argz,
)
def get_loss(self, y, l, x):
yhat = self.model(x, y)[0].transpose(1, 0)
loss = 0
for i in range(y.shape[0]):
loss += torch.nn.functional.cross_entropy(
yhat[i, :l[i, 0] - 1, :],
y[i, 1:l[i, 0]],
) / y.shape[0]
return loss
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'--mode',
type=str,
default='train_annotation',
help='script call',
)
parser.add_argument(
'--checkpoint',
type=str,
default='checkpoints/annotator',
help='model checkpoint',
)
parser.add_argument(
'--n_epochs',
type=int,
default=200,
help='number of epochs trained'
)
parser.add_argument(
'--lr',
type=float,
default=0.01,
help='learning rate of SGD'
)
parser.add_argument(
'--batch_size',
type=int,
default=25,
help='batch-size for training',
)
parser.add_argument(
'--catalog',
type=str,
default='coco',
help='type of model attributes to train on',
)
parser.add_argument(
'--ssd',
action='store_true',
help='use fusion drive',
)
args = parser.parse_args()
if args.mode == 'unit':
cf = torchabc.config.Config(
Data,
Iterator,
Annotator,
Trainer,
)
params = torchabc.config.Params(
{'dir_': 'data/coco'},
{'n_vocab': 11274},
{'dataset': 'coco', 'ssd': True},
)
torchabc.unit.Tester(
cf,
params=params,
subsample=200,
batch_size=2,
).test()
elif args.mode == 'train':
Trainer(
args.checkpoint,
args.catalog,
n_epochs=args.n_epochs,
lr=args.lr,
batch_size=args.batch_size,
ssd=args.ssd,
).train()
elif args.mode == 'plot':
torchabc.plot.Plotter(
Trainer,
args.checkpoint,
regex='(?!resnet)^.*'
).plot()
os.system('open {}/*.png'.format(args.checkpoint))
elif args.mode == 'annotate':
iterator = Iterator(Data('data/' + args.catalog), 'valid')
model = Annotator(len(iterator.dictionary))
model.load_state_dict(torch.load(
args.checkpoint + '/model.pt',
map_location=lambda storage, loc: storage,
))
for i in range(10):
choice = numpy.random.choice(len(iterator))
x = iterator[choice][2]
print(iterator.df.iloc[choice].file_)
y = model.annotate(
x, iterator.dictionary['<s>'], iterator.dictionary['</s>'],
sample=False,
)
print(' '.join(list(map(iterator.lookup.__getitem__, y))))
print('\n\n')
<file_sep>import argparse
import json
import math
import matplotlib.pyplot
import numpy
import os
import pandas
import re
import skimage.io
import skimage.transform
import torch
import torch.utils.data
import torch.utils.model_zoo
import tqdm
blurb = 'Fashion Brain: Library of trained deep learning models (D2.5)'
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return torch.nn.Conv2d(
in_planes,
out_planes,
kernel_size=3,
stride=stride,
padding=1,
bias=False
)
class BasicBlock(torch.nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = torch.nn.BatchNorm2d(planes)
self.relu = torch.nn.ReLU(inplace=True)
self.conv2 = conv3x3(planes, planes)
self.bn2 = torch.nn.BatchNorm2d(planes)
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class Bottleneck(torch.nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = \
torch.nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = torch.nn.BatchNorm2d(planes)
self.conv2 = torch.nn.Conv2d(
planes,
planes,
kernel_size=3,
stride=stride,
padding=1,
bias=False
)
self.bn2 = torch.nn.BatchNorm2d(planes)
self.conv3 = torch.nn.Conv2d(
planes,
planes * self.expansion,
kernel_size=1,
bias=False
)
self.bn3 = torch.nn.BatchNorm2d(planes * self.expansion)
self.relu = torch.nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class ResNet(torch.nn.Module):
def __init__(self, block, layers, num_classes=1000):
self.inplanes = 64
super(ResNet, self).__init__()
self.conv1 = torch.nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = torch.nn.BatchNorm2d(64)
self.relu = torch.nn.ReLU(inplace=True)
self.maxpool = torch.nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
self.avgpool = torch.nn.AvgPool2d(7, stride=1)
self.fc = torch.nn.Linear(512 * block.expansion, num_classes)
for m in self.modules():
if isinstance(m, torch.nn.Conv2d):
torch.nn.init.kaiming_normal_(
m.weight,
mode='fan_out',
nonlinearity='relu'
)
elif isinstance(m, torch.nn.BatchNorm2d):
torch.nn.init.constant_(m.weight, 1)
torch.nn.init.constant_(m.bias, 0)
def _make_layer(self, block, planes, blocks, stride=1):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = torch.nn.Sequential(
torch.nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
torch.nn.BatchNorm2d(planes * block.expansion),
)
layers = []
layers.append(block(self.inplanes, planes, stride, downsample))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(self.inplanes, planes))
return torch.nn.Sequential(*layers)
def features(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
return x
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
def resnet():
model = ResNet(Bottleneck, [3, 4, 6, 3])
model.load_state_dict(torch.utils.model_zoo.load_url(
'https://download.pytorch.org/models/resnet50-19c8e357.pth'
))
return model
class Classify(torch.nn.Module):
def __init__(self, n_classes, finetune=False):
torch.nn.Module.__init__(self)
self.cnn = resnet()
self.linear = torch.nn.Linear(2048, n_classes)
self.finetune = finetune
def forward(self, x):
if self.finetune:
return self.linear(self.cnn.features(x))
else:
return self.linear(self.cnn.features(x).detach())
class Data:
def __init__(self, model_type):
self.items = pandas.read_csv('data/{}.csv'.format(model_type))
with open('data/{}.json'.format(model_type)) as f:
self.dictionary = json.load(f)
self.lookup = dict(zip(
self.dictionary.values(), self.dictionary.keys()
))
ix = numpy.random.permutation(len(self.items))
self.items['fold'] = ['train' for _ in range(len(self.items))]
self.items['fold'].iloc[ix[-2000:-1000]] = 'valid'
self.items['fold'].iloc[ix[-1000:]] = 'test'
class Iterator:
def __init__(self, data, fold, model_type, local=False):
if fold == 'train':
self.items = stratify(
data.items[data.items.fold == fold],
model_type,
1000,
)
else:
self.items = stratify(
data.items[data.items.fold == fold],
model_type,
25,
)
self.dictionary = data.dictionary
self.lookup = data.lookup
self.model_type = model_type
self.local = local
def __getitem__(self, item):
if self.local:
x = 'data/img/' + \
str(self.items['ix'].iloc[item]).zfill(6) + '.jpg'
else:
x = '/data/fb-model-library/data/large/img/' + \
str(self.items['ix'].iloc[item]).zfill(6) + '.jpg'
x = torch.FloatTensor(skimage.io.imread(x).transpose(2, 0, 1))
y = torch.LongTensor([
self.dictionary[self.items.iloc[item][self.model_type]]
])
if torch.cuda.is_available():
x = x.cuda()
y = y.cuda()
return x, y
def __len__(self):
return len(self.items)
class Trainer:
def __init__(self,
save_='checkpoints/classify',
model_type='color',
n_epochs=200,
lr=0.01,
batch_size=50,
local=False):
self.save_ = save_
self.model_type = model_type
data = Data(model_type)
train_it = Iterator(
data, fold='train', local=local, model_type=model_type,
)
valid_it = Iterator(
data, fold='valid', local=local, model_type=model_type,
)
self.train_loader = torch.utils.data.DataLoader(
train_it,
batch_size=batch_size,
shuffle=True,
)
self.valid_loader = torch.utils.data.DataLoader(
valid_it,
batch_size=batch_size,
)
self.model = Classify(len(train_it.dictionary))
self.optimizer = \
torch.optim.SGD(self.model.parameters(), momentum=0.9, lr=lr)
self.n_epochs = n_epochs
self.it = 0
def train(self):
if torch.cuda.is_available():
self.model.cuda()
vl = []
va = []
for epoch in range(self.n_epochs):
print('EPOCH {} '.format(epoch) + '*' * 20)
loss, acc = self.do_epoch()
vl.append(loss)
va.append(acc)
format_str = \
'VALIDATION iteration: {}; validation-loss: {}; ' + \
'validation-acc: {};'
print(format_str.format(self.it, vl[-1], va[-1]))
if va[-1] == max(va):
print('saving...')
torch.save(self.model, self.save_ + '/model.pt')
else:
print('Annealing learning rate...')
for param_group in self.optimizer.param_groups:
param_group['lr'] /= 4
def do_epoch(self):
for x, y in self.train_loader:
loss, acc = self.get_loss(x, y)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
print('TRAIN iteration: {}; loss: {}; accuracy: {};'.format(
self.it, loss, acc,
))
self.it += 1
validation_loss = []
validation_acc = []
for x, y in self.valid_loader:
loss, acc = self.get_loss(x, y)
validation_loss.append(loss)
validation_acc.append(acc)
return sum(validation_loss) / len(validation_loss), \
sum(validation_acc) / len(validation_acc)
def get_loss(self, x, y):
yhat = self.model(x)
loss = torch.nn.functional.cross_entropy(yhat, y.squeeze())
acc = []
for i in range(yhat.shape[0]):
acc.append(y[i, 0] in yhat[i, :].topk(1)[1])
return loss, numpy.mean(acc)
def plot(checkpoint):
with open(checkpoint + '/log') as f:
lines = f.read().split('\n')
v_err = []
t_err = []
v_acc = []
t_acc = []
v_it = []
t_it = []
for line in lines:
matcher = 'TRAIN iteration: (\d+); ' + \
'loss: (\d+\.\d+); accuracy: (\d+\.\d+);'
match = re.search(matcher, line)
if match:
t_it.append(int(match.groups()[0]))
t_err.append(float(match.groups()[1]))
t_acc.append(float(match.groups()[2]))
matcher = 'VALIDATION iteration: (\d+); ' + \
'validation-loss: (\d+\.\d+); validation-acc: (\d+\.\d+);'
match = re.search(matcher, line)
if match:
v_it.append(int(match.groups()[0]))
v_err.append(float(match.groups()[1]))
v_acc.append(float(match.groups()[2]))
matplotlib.pyplot.figure()
matplotlib.pyplot.subplot(121)
matplotlib.pyplot.plot(t_it, t_err)
matplotlib.pyplot.plot(v_it, v_err, '-rx', linewidth=2, markersize=10)
matplotlib.pyplot.title('Learning curves: Classification')
matplotlib.pyplot.ylabel('Cross-Entropy Loss')
matplotlib.pyplot.xlabel('# Iteration')
matplotlib.pyplot.grid(linestyle='--')
matplotlib.pyplot.legend(['training', 'validation'])
matplotlib.pyplot.subplot(122)
matplotlib.pyplot.plot(t_it, t_acc)
matplotlib.pyplot.plot(v_it, v_acc, '-rx', linewidth=2, markersize=10)
matplotlib.pyplot.title('Learning curves: Classification')
matplotlib.pyplot.ylabel('Accuracy')
matplotlib.pyplot.xlabel('# Iteration')
matplotlib.pyplot.grid(linestyle='--')
matplotlib.pyplot.legend(['training', 'validation'])
matplotlib.pyplot.show()
def stratify(df, col, n):
vals = df[col].unique()
out = []
for i, val in enumerate(vals):
local = df[df[col] == val]
ix = numpy.random.choice(len(local), size=n, replace=True)
temp = local.iloc[ix]
out.append(temp)
return pandas.concat(out, axis=0)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=blurb)
parser.add_argument(
'--mode',
type=str,
default='train_annotation',
help='script call',
)
parser.add_argument(
'--checkpoint',
type=str,
default='checkpoints/classifier',
help='model checkpoint',
)
parser.add_argument(
'--n_epochs',
type=int,
default=200,
help='number of epochs trained'
)
parser.add_argument(
'--lr',
type=float,
default=0.01,
help='learning rate of SGD'
)
parser.add_argument(
'--batch_size',
type=int,
default=10,
help='batch-size for training',
)
parser.add_argument(
'--model_type',
type=str,
default='color',
help='type of model attributes to train on',
)
parser.add_argument(
'--local',
action='store_true',
help='run locally',
)
args = parser.parse_args()
if args.mode == 'train':
trainer = Trainer(
args.checkpoint,
args.model_type,
args.n_epochs,
args.lr,
args.batch_size,
args.local,
).train()
elif args.mode == 'plot':
plot(args.checkpoint)
elif args.mode == 'test':
model = torch.load(
args.checkpoint + '/model.pt',
map_location=lambda storage, loc: storage,
)
data = Data(args.model_type)
model_type = str(args.checkpoint).split('/')[-1]
iterator = Iterator(
data,
fold='test',
model_type=model_type,
local=args.local
)
choice = numpy.random.choice(len(iterator))
image = iterator[choice][0]
file_ = iterator.items.file.iloc[choice]
label = iterator.items[model_type].iloc[choice]
print(label)
prediction = model(image[None, :, :, :]).squeeze().detach().numpy()
best = iterator.lookup[numpy.argmax(prediction)]
print(best)
os.system('open ' + file_)
<file_sep>torch
pandas
scikit-image
tqdm
matplotlib
numpy
pillow
torchvision
git+https://github.com/blythed/torchabc.git
| d1ddfe2c9384deb844bfa23a8fcdca7ac3355d5a | [
"Markdown",
"Python",
"Text"
] | 4 | Markdown | Bharat123rox/fb-model-library | a17e226f7be1a7f4f054f408a2fe5ca0b67e78e4 | 9a542f06e9522eb81d212cff9ea78161fb811d97 |
refs/heads/master | <file_sep>package librarymanager.usecase;
import librarymanager.domain.LibraryBook;
import librarymanager.gateway.LibraryBookGateway;
public class AddLibraryBookUsecase {
private LibraryBookGateway libraryBookGateway;
public AddLibraryBookUsecase(LibraryBookGateway libraryBookGateway){
this.libraryBookGateway = libraryBookGateway;
}
public void execute(LibraryBook book) {
libraryBookGateway.saveLibraryBook(book);
}
}
<file_sep>package librarymanager.gateway;
import librarymanager.domain.LibraryBook;
import java.util.List;
public interface LibraryBookGateway {
LibraryBook saveLibraryBook(LibraryBook book);
List<LibraryBook> getAllBooks();
}
<file_sep>package librarymanager.gateway;
import librarymanager.domain.LibraryBook;
import java.util.ArrayList;
import java.util.List;
public class LibraryBookMemoryGateway implements LibraryBookGateway{
private List<LibraryBook> libraryBookList = new ArrayList<LibraryBook>();
public LibraryBook saveLibraryBook(LibraryBook book) {
libraryBookList.add(book);
return book;
}
public List<LibraryBook> getAllBooks() {
return libraryBookList;
}
}
| bc9957e2009449f853b462686859a467928fb9e0 | [
"Java"
] | 3 | Java | sfrubio/LibraryManager | 9b72d7befe3902cc39d82f4c67fd48498ef0fa0a | 88c21d3969179d6648f452aa1d1e7edfab9a4ece |
refs/heads/master | <repo_name>balachander1205/imageColorfulnessDetection<file_sep>/colorKMeans.py
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import argparse
import utils
import cv2
import os
import json
import string
from colorDetection import apply
# Algorithm
# 1. Clusters are of 10.
# 2. 6/10-clusters of gray colored (60% of gray)
# 3. Remaining clusters are of colored.
# 4. if maximum clusters are of gray:
# Then image is gray scale.
# else:
# Image is colored.
clusters = 10
def findKMeans(imagefile):
# load the image and convert it from BGR to RGB so that
# we can dispaly it with matplotlib
image = cv2.imread(imagefile)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# reshape the image to be a list of pixels
image = image.reshape((image.shape[0] * image.shape[1], 3))
# cluster the pixel intensities
clt = KMeans(n_clusters = clusters)
clt.fit(image)
# build a histogram of clusters and then create a figure
# representing the number of pixels labeled to each color
hist = utils.centroid_histogram(clt)
bar = utils.plot_colors(hist, clt.cluster_centers_)
clt_list = clt.cluster_centers_
for lst in clt_list:
# print(lst)
print(apply(lst))
# print(clt.cluster_centers_)
def list_all_files(path):
for root, dirs, files in os.walk(path):
for file in files:
p=os.path.join(root,file)
print (os.path.abspath(p))
findKMeans(os.path.abspath(p))
print(list_all_files("E:/hackathons/Use Case 1/Challenging Images/color/")) | 20057f835efabb9598416f5675f1c090a5dda08e | [
"Python"
] | 1 | Python | balachander1205/imageColorfulnessDetection | 11b0609352311968b1f9e70b1e59f4fea8acb568 | 484faed38e2d3c4335684c8b7cbb0e2f759cc68e |
refs/heads/master | <file_sep>package version3.ID;
/**
* Created by ${LiuShuo} on 2016/9/1.
*/
public class ID {
public static Object getModelIDCard(Object value, Object key) {
if (value == null || value.equals("null") || value.equals("")) return "";
if (value instanceof byte[]) return value;
String str = value + "";
str = str.replaceAll("\\s*", "");
str = str.replaceAll("\\u3000", "");
int isSuangYin = 0;
if (str.endsWith("\"") && str.startsWith("\"")) {
str = str.substring(1, str.length() - 1);
isSuangYin = 1;
}
int type = 0;
String s = "";
java.util.regex.Pattern p = java.util.regex.Pattern.compile("^(\u5357|\u5317|\u6C88|\u5170|\u6210|\u6D4E|\u5E7F|\u53C2|\u653F|\u540E|\u88C5|\u6D77|\u7A7A|\u4E1C|\u897F|\u4E2D)\\d{8}$");
java.util.regex.Pattern id18 = java.util.regex.Pattern.compile("^[1-8][0-9]{5}(19|20)[0-9]{2}[0-1][0-9][0-3][0-9](([0-9]{3}[Xx])|[0-9]{4})\\s*$");
java.util.regex.Pattern id15 = java.util.regex.Pattern.compile("^[0-9]{15}\\s*$");
if (id18.matcher(str).matches()) {
type = 18;
}
if (id15.matcher(str).matches()) {
type = 15;
}
if (p.matcher(str).matches()) {
type = 9;
}
if (type == 0) return value;
if (type == 18) {
s = str.substring(0, 6) + "************";
}
if (type == 15) {
s = str.substring(0, 6) + "*********";
}
if (type == 9) {
s = str.substring(0, 1) + "*********";
}
if (isSuangYin == 1) {
s = "\"" + s + "\"";
}
return s;
}
}
<file_sep>package com.wiseweb.ok;
//import java.util.Random;
//import java.util.regex.Matcher;
//import java.util.regex.Pattern;
/**
*完成版 清洗姓名
* Created by ${LiuShuo} on 2016/6/14.
*/
public class MakeUpNameREL {
/**
* 生成唯一姓名位数匹配
* 单姓可生成复姓
* 复姓只能生成复姓
* 少数民族取随机姓和名
* @param value
* @return
*/
public static Object getModelName(Object value) {
//判断参数是否为null、"null"、"" ,为true时不做处理
if (value==null||value.equals("null")||value.equals("")) return value;
//复姓的数组
String[] contain = {"万俟", "司马", "上官", "欧阳", "夏侯", "诸葛", "闻人", "东方", "赫连", "皇甫", "羊舌", "尉迟", "公羊", "澹台", "公冶", "宗正",
"濮阳", "淳于", "单于", "太叔", "申屠", "公孙", "仲孙", "轩辕", "令狐", "钟离", "宇文", "长孙", "慕容", "鲜于", "闾丘", "司徒", "司空", "兀官", "司寇",
"南门", "呼延", "子车", "颛孙", "端木", "巫马", "公西", "漆雕", "车正", "壤驷", "公良", "拓跋", "夹谷", "宰父", "谷梁", "段干", "百里", "东郭", "微生",
"梁丘", "左丘", "东门", "西门", "南宫", "第五", "公仪", "公乘", "太史", "仲长", "叔孙", "屈突", "尔朱", "东乡", "相里", "胡母", "司城", "张廖", "雍门",
"毋丘", "贺兰", "綦毋", "屋庐", "独孤", "南郭", "北宫", "王孙"};
/* 598 百家姓 */
String[] laName= {"赵","钱","孙","李","周","吴","郑","王","冯","陈","褚","卫","蒋","沈","韩","杨","朱","秦","尤","许",
"何","吕","施","张","孔","曹","严","华","金","魏","陶","姜","戚","谢","邹","喻","柏","水","窦","章","云","苏","潘","葛","奚","范","彭","郎",
"鲁","韦","昌","马","苗","凤","花","方","俞","任","袁","柳","酆","鲍","史","唐","费","廉","岑","薛","雷","贺","倪","汤","滕","殷",
"罗","毕","郝","邬","安","常","乐","于","时","傅","皮","卞","齐","康","伍","余","元","卜","顾","孟","平","黄","和",
"穆","萧","尹","姚","邵","湛","汪","祁","毛","禹","狄","米","贝","明","臧","计","伏","成","戴","谈","宋","茅","庞","熊","纪","舒",
"屈","项","祝","董","梁","杜","阮","蓝","闵","席","季","麻","强","贾","路","娄","危","江","童","颜","郭","梅","盛","林","刁","钟",
"徐","邱","骆","高","夏","蔡","田","樊","胡","凌","霍","虞","万","支","柯","昝","管","卢","莫","经","房","裘","缪","干","解","应",
"宗","丁","宣","贲","邓","郁","单","杭","洪","包","诸","左","石","崔","吉","钮","龚","程","嵇","邢","滑","裴","陆","荣","翁","荀",
"羊","于","惠","甄","曲","家","封","芮","羿","储","靳","汲","邴","糜","松","井","段","富","巫","乌","焦","巴","弓","牧","隗","山",
"谷","车","侯","宓","蓬","全","郗","班","仰","秋","仲","伊","宫","宁","仇","栾","暴","甘","钭","厉","戎","祖","武","符","刘","景",
"詹","束","龙","叶","幸","司","韶","郜","黎","蓟","溥","印","宿","白","怀","蒲","邰","从","鄂","索","咸","籍","赖","卓","蔺","屠",
"蒙","池","乔","阴","郁","胥","能","苍","双","闻","莘","党","翟","谭","贡","劳","逄","姬","申","扶","堵","冉","宰","郦","雍","却",
"璩","桑","桂","濮","牛","寿","通","边","扈","燕","冀","浦","尚","农","温","别","庄","晏","柴","瞿","阎","充","慕","连","茹","习",
"宦","艾","鱼","容","向","古","易","慎","戈","廖","庾","终","暨","居","衡","步","都","耿","满","弘","匡","国","文","寇","广","禄",
"阙","东","欧","殳","沃","利","蔚","越","夔","隆","师","巩","厍","聂","晁","勾","敖","融","冷","訾","辛","阚","那","简","饶","空",
"曾","毋","沙","乜","养","鞠","须","丰","巢","关","蒯","相","查","后","荆","红","游","郏","竺","权","逯","盖","益","桓","公","仉",
"督","岳","帅","缑","亢","况","郈","有","琴","归","海","晋","楚","闫","法","汝","鄢","涂","钦","商","牟","佘","佴","伯","赏","墨",
"哈","谯","篁","年","爱","阳","佟","言","福","南","火","铁","迟","漆","官","冼","真","展","繁","檀","祭","密","敬","揭","舜","楼",
"疏","冒","浑","挚","胶","随","高","皋","原","种","练","弥","仓","眭","蹇","覃","阿","门","恽","来","綦","召","仪","风","介","巨",
"木","京","狐","郇","虎","枚","抗","达","杞","苌","折","麦","庆","过","竹","端","鲜","皇","亓","老","是","秘","畅","邝","还","宾",
"闾","辜","纵","侴","万俟","司马","上官","欧阳","夏侯","诸葛","闻人","东方","赫连","皇甫","羊舌","尉迟","公羊","澹台","公冶","宗正",
"濮阳","淳于","单于","太叔","申屠","公孙","仲孙","轩辕","令狐","钟离","宇文","长孙","慕容","鲜于","闾丘","司徒","司空","兀官","司寇",
"南门","呼延","子车","颛孙","端木","巫马","公西","漆雕","车正","壤驷","公良","拓跋","夹谷","宰父","谷梁","段干","百里","东郭","微生",
"梁丘","左丘","东门","西门","南宫","第五","公仪","公乘","太史","仲长","叔孙","屈突","尔朱","东乡","相里","胡母","司城","张廖","雍门",
"毋丘","贺兰","綦毋","屋庐","独孤","南郭","北宫","王孙"};
//名字库
String[] fiName= {"修","宵","晨","戏","施","顺","祥","才","聪","银","戈","喻","声","生","铁","如","宸","誓","胜","挚","靖","齐",
"锦","少","舟","任","载","翱","青","迁","钧","钟","金","慈","昌","紫","砂","仁","祖","韶","绍","锐","峻","裕","镇","壮","商",
"翼","织","释","诚","常","净","秀","节","刊","信","崇","春","铭","秋","刚","诗","神","星","鉴","石","识","肃","瑞","新","鑫",
"盛","帅","馨","惜","散","慎","世","书","千","善","镜","然","资","笑","疏","西","捷","超","川","锋","实","聚","尊","承","钦",
"仕","众","思","茂","贤","棕","树","蓝","卷","谷","君","古","原","廉","建","庆","桦","统","若","攀","栋","荒","何","久","侠",
"奇","朴","鸽","东","嘉","冠","松","啸","祺","琪","雁","宜","琦","枝","坚","昂","毅","歌","标","固","吉","高","康","尧","果",
"杭","语","曲","肖","荷","芹","乾","义","杰","皓","凯","狂","本","勤","彬","景","月","兼","顷","柏","擎","荣","观","笃","恭",
"柯","言","菲","萧","乔","群","谦","国","极","轻","玉","业","材","相","苑","倚","岳","柳","贵","悟","健","彦","棋","楷","桐",
"气","颜","苛","池","闻","流","霜","福","泉","宏","弘","浅","熙","济","涛","震","和","闲","霖","向","波","渊","博","游","雨",
"润","湛","凡","奔","夫","潮","深","岸","辉","浚","复","封","飞","朋","江","奉","晖","绘","浪","鸣","百","鹤","沙","漾","泥",
"雪","孝","万","望","瀚","缈","淡","阜","保","阔","洪","恒","云","伯","玄","风","淘","合","文","莫","享","满","溪","妙","邦",
"华","冰","方","寒","鹏","陌","奋","秉","泽","豪","布","明","民","虎","帆","洋","名","拂","海","潭","清","勉","源","平","物",
"沧","霄","熊","论","彤","烟","阳","耀","励","晋","临","伦","日","传","炎","彰","全","丰","晓","瞻","拓","展","绩","炫","尘",
"征","昙","道","飘","鼎","龙","昊","腾","至","宝","驰","易","耿","昆","振","知","光","灿","智","畅","晴","迪","绿","扬","来",
"志","煊","遥","宁","衷","太","凌","天","璋","瑾","俊","里","韬","量","致","烨","忠","厉","理","路","年","循","昭","达","都",
"蝶","章","照","积","良","泰","烈","庭","折","进","晟","德","际","琢","利","哲","质","隆","田","煜","南","乐","翎","冬","图",
"暖","壤","佑","翔","伟","磊","欧","运","豫","维","坤","恩","永","意","野","幽","远","圣","山","城","音","韵","依","余","圆",
"勋","忆","叶","亦","卫","傲","融","勇","逸","育","唯","基","容","温","安","奥","引","影","羽","均","誉","越","辰","轩","延",
"境","宇","悠","益","岩","玮","威","硕","庸","懿","统","柏","彤","兼","昊","肖","杰","含","凯","振","秉","沧","享","朋","轻",
"俊","材","宇","松","依","池","钦","桦","芹","孝","炫","极","洋","舟","际","荒","衷","亦","狂","闻","幽","曲","耿","勇","奇",
"城","冰","柯","浦","林","和","明","名","建","尧","胜","朴","存","顺","昌","西","昙","砂","语","泰","伦","烈","杭","育","折",
"达","顷","忠","延","坤","佑","修","闲","坚","泉","劲","勋","枝","年","迁","致","治","健","羽","晓","卷","如","宸","荷","物",
"合","复","晖","易","灿","浅","悟","壮","临","荣","桦","乔","承","明","顺","物","原","统","哲","庭","运","修","远","峰","兼",
"杉","莫","均","幽","高","闲","宝","拓","若","材","玮","余","苛","欢","凌","函","享","陌","亦","旷","全","君","思","秀","威",
"海","烨","尧","声","展","秋","标","羽","昭","合","建","坤","南","利","华","伦","挚","宵","壮","众","晋","松","恩","阳","泉",
"恭","树","钟","致","苑","封","诗","晓","戏","荣","里","拂","至","奋","初","图","烈","金","如","钦","俊","贵","宸","狂","益",
"耿","积","复","勋","佑","肃","光","轻","施","任","巧","功","玄","白","田","由","甲","申","用","目","旦","玉","丘","生","主","加","占","可","兄","石","只","叭","弘","台","叮",
"包","卉","叫","另","古","尼","召","巨","司","句","幼","禾","札","本","丙","戊","布","卯","未","末","必","平","市","冬","孕","永","立",
"以","央","出","北","甘","凹","凸","刊","扎","母","瓜","正","奴","奶","它","外","瓦","充","示","卡","去","失","斥","丕","乏","半","皮",
"六","光","先","圭","戌","艮","羊","地","至","向","各","吉","名","后","舌","合","回","同","咤","臣","吋","吊","考","多","仲","伉","来",
"企","伊","全","伍","仰","任","伙","休","价","伏","份","在","行","汀","州","丞","年","存","舟","兆","寺","竹","卉","圳","朱","朴","米",
"朽","打","汁","次","冰","交","件","列","匠","宅","尖","老","宇","守","安","字","如","妄","亦","聿","因","夷","有","衣","羽","而","危",
"耳","印","西","先","旭","早","百","自","旨","曲","收","乒","乓","色","此","虫","肉","妃","好","帆","亥","充","再","共","住","佃","但",
"你","伴","佛","布","伶","夹","利","佣","余","位","伸","宋","似","作","坐","彷","畲","七","妏","妥","妞","努","妆","妘","妤","汝","妍",
"妙","妨","妣","克","谷","告","估","君","吕","兑","束","局","托","豆","足","占","言","佑","佐","吴","吾","呈","杏","串","吹","吟","冶",
"吸","吵","亨","伯","伺","何","含","别","刨","吧","灶","杜","町","牡","圾","赤","走","成","劫","坍","弄","坊","更","男","良","里","均",
"壮","辰","坎","床","杆","杖","李","孚","孝","材","村","杉","杞","秀","池","汐","汕","汗","廷","江","忍","忘","志","删","形","址","见",
"免","车","屁","身","甫","贝","旱","步","判","私","角","改","攻","即","弟","系","忙","兵","冷","宏","完","我","希","序","酉","辛","助",
"彤","夆","八","佶","供","佰","仑","佬","佛","岱","佩","夜","欣","例","来","侏","佳","征","依","彼","侑","并","往","府","侍","使","姑",
"姗","姒","妾","妻","始","妹","姓","妮","委","姐","姊","姆","妳","舍","和","咆","呼","咐","命","咒","或","咖","刮","咕","固","岩","冾",
"奇","知","居","林","周","店","味","京","尚","享","昔","卓","明","朋","昏","昊","服","昆","的","帛","昌","坦","昂","旺","者","易","升",
"昕","松","析","杵","虎","枋","杷","枇","杯","板","林","采","果","兔","枕","柑","杭","枚","东","析","采","青","炒","炊","快","忱","忽",
"忠","念","忭","忿","杰","炎","定","宙","空","宕","穹","官","宗","宜","宛","雨","沈","沙","沁","冲","沌","汲","沐","承","汽","乳","沛",
"函","没","汾","汴","汪","沅","沃","汶","沂","季","孟","坪","物","卦","坤","幸","社","到","坡","坻","硅","坨","岳","岸","玖","抖","扶",
"把","批","扳","扮","扭","抑","抗","狂","乖","沉","孤","盂","氓","氛","爸","版","牧","盲","门","非","庚","冈","奉","争","决","扺","弦",
"艾","武","协","所","抄","投","抓","抒","折","事","些","卷","劻","届","底","忝","状","竺","垧","亚","券","刷","刺","卒","卸","取","叔",
"受","并","奔","劾","卑","其","儿","狄","典","直","延","于","卧","具","金","长","奈","两","刻","找","制","祀","祁","秉","弧","房","放",
"斧","爬","九","勇","面","冠","军","厚","罕","俊","很","俐","侵","促","俗","系","待","信","衍","便","俘","俄","俏","律","后","侯","保",
"亭","俬","徊","韦","侣","室","客","穿","姨","姻","娃","姜","姝","姚","咪","计","咳","哄","哈","订","却","咨","讣","哉","咱","咻","品",
"亮","宦","科","秒","柄","柳","柏","枷","拐","柔","香","柿","染","柱","架","查","柯","柚","某","枯","柑","柒","皇","冒","昴","昧","昱",
"音","映","宣","星","春","肖","削","前","皆","是","昨","肝","怪","性","思","怙","急","怡","怕","炫","南","炯","炬","炭","炳","怎","炮",
"政","耐","泌","况","沸","癸","泡","沫","沽","泯","泳","油","沿","泉","泣","泄","泗","河","波","法","泓","泛","治","泊","注","泥","沾",
"沼","垮","型","垂","奎","封","重","致","垣","拆","拐","狗","剎","页","克","垮","拌","拂","抹","叛","披","拔","抛","拓","招","拇","拍",
"抱","拉","拄","拒","抽","抵","拘","押","拖","抬","芊","芃","芍","芒","玟","玫","珏","玩","毒","屋","幽","禺","竽","耶","食","昶","姿",
"咸","省","则","相","秋","怯","砍","契","奏","巷","甚","孩","衫","酋","剉","屎","故","泵","牯","皈","杯","看","竿","轨","泰","度","拓",
"劲","红","表","美","屏","虹","勉","勃","为","弈","狐","盆","革","扁","奕","叛","拜","建","帅","负","赴","砒","帝","界","段","研","纪",
"既","肚","狙","剌","彦","盈","禹","约","威","羿","施","俞","眉","首","盼","贞","风","奂","飞","竑","爰","十","厝","原","冤","冥","冢",
"准","凌","凄","座","俱","值","倪","伦","倘","倞","俩","修","倡","倩","倦","徐","径","借","倒","俶","倔","们","俾","徒","俺","倭","倚",
"个","幸","候","倍","俸","俯","剖","剥","刚","祟","留","峪","峮","城","岛","埔","埋","高","哥","记","唇","炮","唔","哭","哽","唐","讯",
"哲","讨","托","站","讪","讫","哨","训","员","讦","仓","哦","唈","哺","讧","宫","窈","家","案","窄","容","宬","宸","宴","宰","宵","害",
"贡","娱","娜","姬","娘","娓","娥","娩","娣","娌","娉","娟","拾","拭","持","按","拱","拷","拮","括","挖","拿","挑","指","拯","按","耘",
"桂","秧","栩","耕","桉","秘","租","粉","根","框","桌","栘","桑","格","桃","株","秤","秩","梳","冻","校","柴","栽","栓","料","殊","耗",
"桔","栗","桐","秦","核","洋","洹","洸","恭","洗","洛","洪","洲","流","津","酒","洞","庭","孙","洽","汹","洵","洳","泄","娑","活","派",
"洧","恒","耿","烙","恒","恐","烤","恬","烈","晋","晃","烔","肱","恃","息","耻","烘","恰","恕","恢","恩","恤","羔","书","肩","肴","朕",
"肥","时","肯","殉","骨","股","屑","朔","肢","剔","晁","育","晏","殷","桓","晌","峻","埂","城","峭","峨","峰","峡","崁","芹","芬","芮",
"芙","芭","芝","芛","芳","芽","芯","芸","花","芥","芫","芷","纹","纱","级","纯","索","紊","纺","纽","纷","纳","纸","秘","神","祠","祖",
"佑","祝","珈","珀","珊","珍","玻","玳","玲","珅","差","弱","拳","砸","臭","刍","虔","蚤","衰","航","破","配","般","亳","病","马","匪",
"狠","圃","亩","疲","笆","蚌","迅","躬","库","辱","鬼","特","展","砥","兼","钉","针","耽","只","斗","疼","翁","袁","迂","射","氧","爹",
"豹","豺","釜","狩","奚","真","蚓","夏","益","轩","旅","财","素","扇","乘","气","畜","笑","缺","翅","效","起","巡","席","卿","师","套",
"奘","疾","症","疹","矩","砧","蚪","衷","闪","旁","停","假","侦","偃","偌","伟","御","悠","偲","术","偶","健","偕","得","爽","偎","伪",
"修","徘","徙","徜","做","从","侧","偏","康","庸","庾","庶","痕","匾","匿","屠","痔","麻","庹","庵","疵","剪","勒","动","执","斩","副",
"软","务","野","邪","阡","邠","邦","那","浩","教","浪","涒","浙","涓","浚","浸","海","涕","泾","浣","涅","浦","消","浦","雪","浴","浮",
"昆","密","崩","毕","岗","堆","培","埤","基","堂","笛","仑","羚","坚","略","堉","域","崖","崇","埴","崎","崧","崔","梓","梗","舺","梁",
"粒","救","梯","桶","条","梨","梵","梆","斜","梧","敕","梢","械","梭","枭","杀","彪","弃","犁","杆","移","彬","梅","粗","彩","挺","捆",
"捏","振","捉","挪","挽","挨","挟","挫","捐","捕","捍","捌","晢","够","胖","干","恿","勖","章","顶","专","将","竟","您","胄","鸟","胎",
"悌","昼","皎","烹","眺","袒","豚","曼","尉","望","鱼","悁","胤","焉","晚","晤","悟","焊","胃","习","晟","患","晨","胥","冕","晦","曹",
"悉","悚","敏","胞","悍","胚","悖","奢","蚵","啪","啃","啦","国","甜","念","啄","朱","袈","诀","区","欲","哑","啊","问","唯","讶","讹",
"启","毫","设","常","商","船","许","唱","售","圈","讼","孰","盒","啤","唬","访","啡","婕","娄","婪","婀","娶","娼","婚","婢","婊","婉",
"妇","婆","珠","珞","佩","珙","珪","琉","敖","珣","晌","班","寄","寇","窒","窕","寀","寂","宿","寅","扎","累","终","统","绊","绍","组",
"细","绅","茁","笠","英","苑","茄","若","范","茉","茂","笨","苓","苕","苙","苞","茅","苗","苦","苹","苾","苟","荏","苔","笙","符","祥",
"强","旋","雀","处","顷","产","族","袖","牵","率","瓷","蛇","疏","参","巢","狭","匙","戚","羞","舷","蛆","蚯","赦","酗","袪","麦","凰",
"闭","觅","货","被","票","败","悔","背","瓶","瓠","舶","袍","馗","勘","钵","釱","钓","钏","钗","翎","张","蛋","袋","鹿","第","贪","伧",
"傒","徨","备","博","街","傅","傍","贷","家","循","婿","婼","媒","婷","媚","媞","媛","堪","凯","岚","崴","尧","场","堡","嵋","诊","啼",
"喃","喻","喊","喝","喉","证","距","注","喜","善","喨","舒","创","诉","词","残","单","喘","丧","诅","唤","彭","跑","喧","评","诃","结",
"喇","就","诈","跌","邵","掌","措","扫","探","挣","掮","接","掉","捱","掩","掏","授","卷","采","捧","扪","掰","排","舍","掀","挂","捷",
"棕","棵","棍","棺","植","杰","棠","栋","集","栈","椒","椅","巽","稍","程","稀","窗","棘","栖"};
//特殊字符
boolean isSpecial = false;
//复姓
boolean isTwoName = false;
//少数民族
boolean isRareName = false;
String lastName = "";
String firstName = "";
String newName = "";
String str = "";
int lastNameHashCode =0;
int firstNameHashCode =0;
//转换类型
str = value+"";
//判断是否含有特殊字符
java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("[0-9]*[A-Za-z]*[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]*");
for (int i=0;i<str.length();i++){
java.util.regex.Matcher matcher = pattern.matcher(str.substring(i,i+1));
boolean matches = matcher.matches();
if (matches){
isSpecial=matches;
break;
}
}
//判断是否是复姓
for(String s: contain){
if(str.contains(s)){
isTwoName = true;
}
}
//判断是否是少数民族“·”
if(str.contains("·")){
isRareName = true;
}
//正常名字
//复姓名字
//少数民族名字
if (!isSpecial){
lastName = str.substring(0,1);
firstName = str.substring(1,str.length());
if (isTwoName){
lastName = str.substring(0, 2);
firstName = str.substring(2,str.length());
}
if(isRareName){
String regex = "·";
String strAry[] = str.split(regex);
lastName = strAry[0];
firstName = strAry[1];
}
//少数民族拼新名字
if (isRareName){
for (int i=0;i<lastName.length();i++){
firstNameHashCode = Math.abs(lastName.substring(i,i+1).hashCode());
newName+=fiName[firstNameHashCode%(fiName.length-1)];
}
newName+="·";
for (int i=0;i<firstName.length();i++){
firstNameHashCode = Math.abs(firstName.substring(i,i+1).hashCode());
newName+=fiName[firstNameHashCode%(fiName.length-1)];
}
}else{
lastNameHashCode = Math.abs(lastName.hashCode());//姓取正数
newName = laName[lastNameHashCode%(laName.length-1)]; //获得一个固定的姓氏
if (isTwoName){
newName = contain[lastNameHashCode%(contain.length-1)]; //获得一个固定的姓氏
}
for (int i=0;i<firstName.length();i++){
firstNameHashCode = Math.abs(firstName.substring(i,i+1).hashCode());
newName+=fiName[firstNameHashCode%(fiName.length-1)];
}
}
}
//正常名字带特殊字符
//复姓名字带特殊字符
//少数民族名字带特殊字符
// Pattern pattern = Pattern.compile("[0-9]*[A-Za-z]*");
//判断汉字
java.util.regex.Pattern pattern1 = java.util.regex.Pattern.compile("[\\u4e00-\\u9fa5]");
// Pattern pattern = Pattern.compile("[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]");
//判断是否汉字[\u4e00-\u9fa5]
//特殊字符[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]
if (isSpecial){
int temp = 0;
//根据以上判断截取每个字符放入数组
String[] nameArray =new String [str.length()];
for (int i=0;i<str.length();i++){
nameArray[i] = str.substring(i,i+1);
}
if (isTwoName){
for (int i=0;i<nameArray.length;i++){
java.util.regex.Matcher matcher1 = pattern1.matcher(nameArray[i]);
boolean matches1 = matcher1.matches();
if (matches1&&temp==1){
firstName=nameArray[i];
firstNameHashCode = Math.abs(firstName.hashCode());//名取正数
newName = fiName[firstNameHashCode%(fiName.length-1)]; //获得一个固定的姓名字
nameArray[i]=newName.substring(0);
}
if (matches1&&temp==0){
lastName=nameArray[i]+nameArray[i+1];
lastNameHashCode = Math.abs(lastName.hashCode());//姓取正数
newName = contain[lastNameHashCode%(contain.length-1)]; //获得一个固定的姓氏
nameArray[i]=newName.substring(0,1);
nameArray[i+1]=newName.substring(1,2);
i+=1;
temp+=1;
}
}
}
if(isRareName){
for (int i=0;i<nameArray.length;i++){
java.util.regex.Matcher matcher1 = pattern1.matcher(nameArray[i]);
boolean matches1 = matcher1.matches();
if (matches1){
firstName=nameArray[i];
firstNameHashCode = Math.abs(firstName.hashCode());//名取正数
nameArray[i] = fiName[firstNameHashCode%(fiName.length-1)]; //获得一个固定的姓名字
}
}
}
for (int i=0;i<nameArray.length;i++){
java.util.regex.Matcher matcher1 = pattern1.matcher(nameArray[i]);
boolean matches1 = matcher1.matches();
if (matches1&&temp==1){
firstName=nameArray[i];
firstNameHashCode = Math.abs(firstName.hashCode());//名取正数
newName = fiName[firstNameHashCode%(fiName.length-1)]; //获得一个固定的姓名字
nameArray[i]=newName.substring(0);
}
if (matches1&&temp==0){
lastName=nameArray[i];
lastNameHashCode = Math.abs(lastName.hashCode());//姓取正数
newName = laName[lastNameHashCode%(laName.length-1)]; //获得一个固定的姓氏
nameArray[i]=newName.substring(0,1);
temp+=1;
}
}
//生成String类型新名字
newName="";
for (int i=0;i<nameArray.length;i++){
newName+=nameArray[i];
}
}
return newName;
}
/**
* 随机生成姓名位数匹配
* @param value
* @return
*/
public static Object getRandomName(Object value) {
///判断参数是否为null、"null"、"" ,为true时不做处理
if (value==null||value.equals("null")||value.equals("")) return value;
java.util.Random random = new java.util.Random(System.currentTimeMillis());
//复姓的数组
String[] contain = {"万俟", "司马", "上官", "欧阳", "夏侯", "诸葛", "闻人", "东方", "赫连", "皇甫", "羊舌", "尉迟", "公羊", "澹台", "公冶", "宗正",
"濮阳", "淳于", "单于", "太叔", "申屠", "公孙", "仲孙", "轩辕", "令狐", "钟离", "宇文", "长孙", "慕容", "鲜于", "闾丘", "司徒", "司空", "兀官", "司寇",
"南门", "呼延", "子车", "颛孙", "端木", "巫马", "公西", "漆雕", "车正", "壤驷", "公良", "拓跋", "夹谷", "宰父", "谷梁", "段干", "百里", "东郭", "微生",
"梁丘", "左丘", "东门", "西门", "南宫", "第五", "公仪", "公乘", "太史", "仲长", "叔孙", "屈突", "尔朱", "东乡", "相里", "胡母", "司城", "张廖", "雍门",
"毋丘", "贺兰", "綦毋", "屋庐", "独孤", "南郭", "北宫", "王孙"};
/* 598 百家姓 */
String[] laName= {"赵","钱","孙","李","周","吴","郑","王","冯","陈","褚","卫","蒋","沈","韩","杨","朱","秦","尤","许",
"何","吕","施","张","孔","曹","严","华","金","魏","陶","姜","戚","谢","邹","喻","柏","水","窦","章","云","苏","潘","葛","奚","范","彭","郎",
"鲁","韦","昌","马","苗","凤","花","方","俞","任","袁","柳","酆","鲍","史","唐","费","廉","岑","薛","雷","贺","倪","汤","滕","殷",
"罗","毕","郝","邬","安","常","乐","于","时","傅","皮","卞","齐","康","伍","余","元","卜","顾","孟","平","黄","和",
"穆","萧","尹","姚","邵","湛","汪","祁","毛","禹","狄","米","贝","明","臧","计","伏","成","戴","谈","宋","茅","庞","熊","纪","舒",
"屈","项","祝","董","梁","杜","阮","蓝","闵","席","季","麻","强","贾","路","娄","危","江","童","颜","郭","梅","盛","林","刁","钟",
"徐","邱","骆","高","夏","蔡","田","樊","胡","凌","霍","虞","万","支","柯","昝","管","卢","莫","经","房","裘","缪","干","解","应",
"宗","丁","宣","贲","邓","郁","单","杭","洪","包","诸","左","石","崔","吉","钮","龚","程","嵇","邢","滑","裴","陆","荣","翁","荀",
"羊","于","惠","甄","曲","家","封","芮","羿","储","靳","汲","邴","糜","松","井","段","富","巫","乌","焦","巴","弓","牧","隗","山",
"谷","车","侯","宓","蓬","全","郗","班","仰","秋","仲","伊","宫","宁","仇","栾","暴","甘","钭","厉","戎","祖","武","符","刘","景",
"詹","束","龙","叶","幸","司","韶","郜","黎","蓟","溥","印","宿","白","怀","蒲","邰","从","鄂","索","咸","籍","赖","卓","蔺","屠",
"蒙","池","乔","阴","郁","胥","能","苍","双","闻","莘","党","翟","谭","贡","劳","逄","姬","申","扶","堵","冉","宰","郦","雍","却",
"璩","桑","桂","濮","牛","寿","通","边","扈","燕","冀","浦","尚","农","温","别","庄","晏","柴","瞿","阎","充","慕","连","茹","习",
"宦","艾","鱼","容","向","古","易","慎","戈","廖","庾","终","暨","居","衡","步","都","耿","满","弘","匡","国","文","寇","广","禄",
"阙","东","欧","殳","沃","利","蔚","越","夔","隆","师","巩","厍","聂","晁","勾","敖","融","冷","訾","辛","阚","那","简","饶","空",
"曾","毋","沙","乜","养","鞠","须","丰","巢","关","蒯","相","查","后","荆","红","游","郏","竺","权","逯","盖","益","桓","公","仉",
"督","岳","帅","缑","亢","况","郈","有","琴","归","海","晋","楚","闫","法","汝","鄢","涂","钦","商","牟","佘","佴","伯","赏","墨",
"哈","谯","篁","年","爱","阳","佟","言","福","南","火","铁","迟","漆","官","冼","真","展","繁","檀","祭","密","敬","揭","舜","楼",
"疏","冒","浑","挚","胶","随","高","皋","原","种","练","弥","仓","眭","蹇","覃","阿","门","恽","来","綦","召","仪","风","介","巨",
"木","京","狐","郇","虎","枚","抗","达","杞","苌","折","麦","庆","过","竹","端","鲜","皇","亓","老","是","秘","畅","邝","还","宾",
"闾","辜","纵","侴","万俟","司马","上官","欧阳","夏侯","诸葛","闻人","东方","赫连","皇甫","羊舌","尉迟","公羊","澹台","公冶","宗正",
"濮阳","淳于","单于","太叔","申屠","公孙","仲孙","轩辕","令狐","钟离","宇文","长孙","慕容","鲜于","闾丘","司徒","司空","兀官","司寇",
"南门","呼延","子车","颛孙","端木","巫马","公西","漆雕","车正","壤驷","公良","拓跋","夹谷","宰父","谷梁","段干","百里","东郭","微生",
"梁丘","左丘","东门","西门","南宫","第五","公仪","公乘","太史","仲长","叔孙","屈突","尔朱","东乡","相里","胡母","司城","张廖","雍门",
"毋丘","贺兰","綦毋","屋庐","独孤","南郭","北宫","王孙"};
//名字库
String[] fiName= {"修","宵","晨","戏","施","顺","祥","才","聪","银","戈","喻","声","生","铁","如","宸","誓","胜","挚","靖","齐",
"锦","少","舟","任","载","翱","青","迁","钧","钟","金","慈","昌","紫","砂","仁","祖","韶","绍","锐","峻","裕","镇","壮","商",
"翼","织","释","诚","常","净","秀","节","刊","信","崇","春","铭","秋","刚","诗","神","星","鉴","石","识","肃","瑞","新","鑫",
"盛","帅","馨","惜","散","慎","世","书","千","善","镜","然","资","笑","疏","西","捷","超","川","锋","实","聚","尊","承","钦",
"仕","众","思","茂","贤","棕","树","蓝","卷","谷","君","古","原","廉","建","庆","桦","统","若","攀","栋","荒","何","久","侠",
"奇","朴","鸽","东","嘉","冠","松","啸","祺","琪","雁","宜","琦","枝","坚","昂","毅","歌","标","固","吉","高","康","尧","果",
"杭","语","曲","肖","荷","芹","乾","义","杰","皓","凯","狂","本","勤","彬","景","月","兼","顷","柏","擎","荣","观","笃","恭",
"柯","言","菲","萧","乔","群","谦","国","极","轻","玉","业","材","相","苑","倚","岳","柳","贵","悟","健","彦","棋","楷","桐",
"气","颜","苛","池","闻","流","霜","福","泉","宏","弘","浅","熙","济","涛","震","和","闲","霖","向","波","渊","博","游","雨",
"润","湛","凡","奔","夫","潮","深","岸","辉","浚","复","封","飞","朋","江","奉","晖","绘","浪","鸣","百","鹤","沙","漾","泥",
"雪","孝","万","望","瀚","缈","淡","阜","保","阔","洪","恒","云","伯","玄","风","淘","合","文","莫","享","满","溪","妙","邦",
"华","冰","方","寒","鹏","陌","奋","秉","泽","豪","布","明","民","虎","帆","洋","名","拂","海","潭","清","勉","源","平","物",
"沧","霄","熊","论","彤","烟","阳","耀","励","晋","临","伦","日","传","炎","彰","全","丰","晓","瞻","拓","展","绩","炫","尘",
"征","昙","道","飘","鼎","龙","昊","腾","至","宝","驰","易","耿","昆","振","知","光","灿","智","畅","晴","迪","绿","扬","来",
"志","煊","遥","宁","衷","太","凌","天","璋","瑾","俊","里","韬","量","致","烨","忠","厉","理","路","年","循","昭","达","都",
"蝶","章","照","积","良","泰","烈","庭","折","进","晟","德","际","琢","利","哲","质","隆","田","煜","南","乐","翎","冬","图",
"暖","壤","佑","翔","伟","磊","欧","运","豫","维","坤","恩","永","意","野","幽","远","圣","山","城","音","韵","依","余","圆",
"勋","忆","叶","亦","卫","傲","融","勇","逸","育","唯","基","容","温","安","奥","引","影","羽","均","誉","越","辰","轩","延",
"境","宇","悠","益","岩","玮","威","硕","庸","懿","统","柏","彤","兼","昊","肖","杰","含","凯","振","秉","沧","享","朋","轻",
"俊","材","宇","松","依","池","钦","桦","芹","孝","炫","极","洋","舟","际","荒","衷","亦","狂","闻","幽","曲","耿","勇","奇",
"城","冰","柯","浦","林","和","明","名","建","尧","胜","朴","存","顺","昌","西","昙","砂","语","泰","伦","烈","杭","育","折",
"达","顷","忠","延","坤","佑","修","闲","坚","泉","劲","勋","枝","年","迁","致","治","健","羽","晓","卷","如","宸","荷","物",
"合","复","晖","易","灿","浅","悟","壮","临","荣","桦","乔","承","明","顺","物","原","统","哲","庭","运","修","远","峰","兼",
"杉","莫","均","幽","高","闲","宝","拓","若","材","玮","余","苛","欢","凌","函","享","陌","亦","旷","全","君","思","秀","威",
"海","烨","尧","声","展","秋","标","羽","昭","合","建","坤","南","利","华","伦","挚","宵","壮","众","晋","松","恩","阳","泉",
"恭","树","钟","致","苑","封","诗","晓","戏","荣","里","拂","至","奋","初","图","烈","金","如","钦","俊","贵","宸","狂","益",
"耿","积","复","勋","佑","肃","光","轻","施","任","巧","功","玄","白","田","由","甲","申","用","目","旦","玉","丘","生","主","加","占","可","兄","石","只","叭","弘","台","叮",
"包","卉","叫","另","古","尼","召","巨","司","句","幼","禾","札","本","丙","戊","布","卯","未","末","必","平","市","冬","孕","永","立",
"以","央","出","北","甘","凹","凸","刊","扎","母","瓜","正","奴","奶","它","外","瓦","充","示","卡","去","失","斥","丕","乏","半","皮",
"六","光","先","圭","戌","艮","羊","地","至","向","各","吉","名","后","舌","合","回","同","咤","臣","吋","吊","考","多","仲","伉","来",
"企","伊","全","伍","仰","任","伙","休","价","伏","份","在","行","汀","州","丞","年","存","舟","兆","寺","竹","卉","圳","朱","朴","米",
"朽","打","汁","次","冰","交","件","列","匠","宅","尖","老","宇","守","安","字","如","妄","亦","聿","因","夷","有","衣","羽","而","危",
"耳","印","西","先","旭","早","百","自","旨","曲","收","乒","乓","色","此","虫","肉","妃","好","帆","亥","充","再","共","住","佃","但",
"你","伴","佛","布","伶","夹","利","佣","余","位","伸","宋","似","作","坐","彷","畲","七","妏","妥","妞","努","妆","妘","妤","汝","妍",
"妙","妨","妣","克","谷","告","估","君","吕","兑","束","局","托","豆","足","占","言","佑","佐","吴","吾","呈","杏","串","吹","吟","冶",
"吸","吵","亨","伯","伺","何","含","别","刨","吧","灶","杜","町","牡","圾","赤","走","成","劫","坍","弄","坊","更","男","良","里","均",
"壮","辰","坎","床","杆","杖","李","孚","孝","材","村","杉","杞","秀","池","汐","汕","汗","廷","江","忍","忘","志","删","形","址","见",
"免","车","屁","身","甫","贝","旱","步","判","私","角","改","攻","即","弟","系","忙","兵","冷","宏","完","我","希","序","酉","辛","助",
"彤","夆","八","佶","供","佰","仑","佬","佛","岱","佩","夜","欣","例","来","侏","佳","征","依","彼","侑","并","往","府","侍","使","姑",
"姗","姒","妾","妻","始","妹","姓","妮","委","姐","姊","姆","妳","舍","和","咆","呼","咐","命","咒","或","咖","刮","咕","固","岩","冾",
"奇","知","居","林","周","店","味","京","尚","享","昔","卓","明","朋","昏","昊","服","昆","的","帛","昌","坦","昂","旺","者","易","升",
"昕","松","析","杵","虎","枋","杷","枇","杯","板","林","采","果","兔","枕","柑","杭","枚","东","析","采","青","炒","炊","快","忱","忽",
"忠","念","忭","忿","杰","炎","定","宙","空","宕","穹","官","宗","宜","宛","雨","沈","沙","沁","冲","沌","汲","沐","承","汽","乳","沛",
"函","没","汾","汴","汪","沅","沃","汶","沂","季","孟","坪","物","卦","坤","幸","社","到","坡","坻","硅","坨","岳","岸","玖","抖","扶",
"把","批","扳","扮","扭","抑","抗","狂","乖","沉","孤","盂","氓","氛","爸","版","牧","盲","门","非","庚","冈","奉","争","决","扺","弦",
"艾","武","协","所","抄","投","抓","抒","折","事","些","卷","劻","届","底","忝","状","竺","垧","亚","券","刷","刺","卒","卸","取","叔",
"受","并","奔","劾","卑","其","儿","狄","典","直","延","于","卧","具","金","长","奈","两","刻","找","制","祀","祁","秉","弧","房","放",
"斧","爬","九","勇","面","冠","军","厚","罕","俊","很","俐","侵","促","俗","系","待","信","衍","便","俘","俄","俏","律","后","侯","保",
"亭","俬","徊","韦","侣","室","客","穿","姨","姻","娃","姜","姝","姚","咪","计","咳","哄","哈","订","却","咨","讣","哉","咱","咻","品",
"亮","宦","科","秒","柄","柳","柏","枷","拐","柔","香","柿","染","柱","架","查","柯","柚","某","枯","柑","柒","皇","冒","昴","昧","昱",
"音","映","宣","星","春","肖","削","前","皆","是","昨","肝","怪","性","思","怙","急","怡","怕","炫","南","炯","炬","炭","炳","怎","炮",
"政","耐","泌","况","沸","癸","泡","沫","沽","泯","泳","油","沿","泉","泣","泄","泗","河","波","法","泓","泛","治","泊","注","泥","沾",
"沼","垮","型","垂","奎","封","重","致","垣","拆","拐","狗","剎","页","克","垮","拌","拂","抹","叛","披","拔","抛","拓","招","拇","拍",
"抱","拉","拄","拒","抽","抵","拘","押","拖","抬","芊","芃","芍","芒","玟","玫","珏","玩","毒","屋","幽","禺","竽","耶","食","昶","姿",
"咸","省","则","相","秋","怯","砍","契","奏","巷","甚","孩","衫","酋","剉","屎","故","泵","牯","皈","杯","看","竿","轨","泰","度","拓",
"劲","红","表","美","屏","虹","勉","勃","为","弈","狐","盆","革","扁","奕","叛","拜","建","帅","负","赴","砒","帝","界","段","研","纪",
"既","肚","狙","剌","彦","盈","禹","约","威","羿","施","俞","眉","首","盼","贞","风","奂","飞","竑","爰","十","厝","原","冤","冥","冢",
"准","凌","凄","座","俱","值","倪","伦","倘","倞","俩","修","倡","倩","倦","徐","径","借","倒","俶","倔","们","俾","徒","俺","倭","倚",
"个","幸","候","倍","俸","俯","剖","剥","刚","祟","留","峪","峮","城","岛","埔","埋","高","哥","记","唇","炮","唔","哭","哽","唐","讯",
"哲","讨","托","站","讪","讫","哨","训","员","讦","仓","哦","唈","哺","讧","宫","窈","家","案","窄","容","宬","宸","宴","宰","宵","害",
"贡","娱","娜","姬","娘","娓","娥","娩","娣","娌","娉","娟","拾","拭","持","按","拱","拷","拮","括","挖","拿","挑","指","拯","按","耘",
"桂","秧","栩","耕","桉","秘","租","粉","根","框","桌","栘","桑","格","桃","株","秤","秩","梳","冻","校","柴","栽","栓","料","殊","耗",
"桔","栗","桐","秦","核","洋","洹","洸","恭","洗","洛","洪","洲","流","津","酒","洞","庭","孙","洽","汹","洵","洳","泄","娑","活","派",
"洧","恒","耿","烙","恒","恐","烤","恬","烈","晋","晃","烔","肱","恃","息","耻","烘","恰","恕","恢","恩","恤","羔","书","肩","肴","朕",
"肥","时","肯","殉","骨","股","屑","朔","肢","剔","晁","育","晏","殷","桓","晌","峻","埂","城","峭","峨","峰","峡","崁","芹","芬","芮",
"芙","芭","芝","芛","芳","芽","芯","芸","花","芥","芫","芷","纹","纱","级","纯","索","紊","纺","纽","纷","纳","纸","秘","神","祠","祖",
"佑","祝","珈","珀","珊","珍","玻","玳","玲","珅","差","弱","拳","砸","臭","刍","虔","蚤","衰","航","破","配","般","亳","病","马","匪",
"狠","圃","亩","疲","笆","蚌","迅","躬","库","辱","鬼","特","展","砥","兼","钉","针","耽","只","斗","疼","翁","袁","迂","射","氧","爹",
"豹","豺","釜","狩","奚","真","蚓","夏","益","轩","旅","财","素","扇","乘","气","畜","笑","缺","翅","效","起","巡","席","卿","师","套",
"奘","疾","症","疹","矩","砧","蚪","衷","闪","旁","停","假","侦","偃","偌","伟","御","悠","偲","术","偶","健","偕","得","爽","偎","伪",
"修","徘","徙","徜","做","从","侧","偏","康","庸","庾","庶","痕","匾","匿","屠","痔","麻","庹","庵","疵","剪","勒","动","执","斩","副",
"软","务","野","邪","阡","邠","邦","那","浩","教","浪","涒","浙","涓","浚","浸","海","涕","泾","浣","涅","浦","消","浦","雪","浴","浮",
"昆","密","崩","毕","岗","堆","培","埤","基","堂","笛","仑","羚","坚","略","堉","域","崖","崇","埴","崎","崧","崔","梓","梗","舺","梁",
"粒","救","梯","桶","条","梨","梵","梆","斜","梧","敕","梢","械","梭","枭","杀","彪","弃","犁","杆","移","彬","梅","粗","彩","挺","捆",
"捏","振","捉","挪","挽","挨","挟","挫","捐","捕","捍","捌","晢","够","胖","干","恿","勖","章","顶","专","将","竟","您","胄","鸟","胎",
"悌","昼","皎","烹","眺","袒","豚","曼","尉","望","鱼","悁","胤","焉","晚","晤","悟","焊","胃","习","晟","患","晨","胥","冕","晦","曹",
"悉","悚","敏","胞","悍","胚","悖","奢","蚵","啪","啃","啦","国","甜","念","啄","朱","袈","诀","区","欲","哑","啊","问","唯","讶","讹",
"启","毫","设","常","商","船","许","唱","售","圈","讼","孰","盒","啤","唬","访","啡","婕","娄","婪","婀","娶","娼","婚","婢","婊","婉",
"妇","婆","珠","珞","佩","珙","珪","琉","敖","珣","晌","班","寄","寇","窒","窕","寀","寂","宿","寅","扎","累","终","统","绊","绍","组",
"细","绅","茁","笠","英","苑","茄","若","范","茉","茂","笨","苓","苕","苙","苞","茅","苗","苦","苹","苾","苟","荏","苔","笙","符","祥",
"强","旋","雀","处","顷","产","族","袖","牵","率","瓷","蛇","疏","参","巢","狭","匙","戚","羞","舷","蛆","蚯","赦","酗","袪","麦","凰",
"闭","觅","货","被","票","败","悔","背","瓶","瓠","舶","袍","馗","勘","钵","釱","钓","钏","钗","翎","张","蛋","袋","鹿","第","贪","伧",
"傒","徨","备","博","街","傅","傍","贷","家","循","婿","婼","媒","婷","媚","媞","媛","堪","凯","岚","崴","尧","场","堡","嵋","诊","啼",
"喃","喻","喊","喝","喉","证","距","注","喜","善","喨","舒","创","诉","词","残","单","喘","丧","诅","唤","彭","跑","喧","评","诃","结",
"喇","就","诈","跌","邵","掌","措","扫","探","挣","掮","接","掉","捱","掩","掏","授","卷","采","捧","扪","掰","排","舍","掀","挂","捷",
"棕","棵","棍","棺","植","杰","棠","栋","集","栈","椒","椅","巽","稍","程","稀","窗","棘","栖"};
//特殊字符
boolean isSpecial = false;
//复姓
boolean isTwoName = false;
//少数民族
boolean isRareName = false;
String lastName = "";
String firstName = "";
String newName = "";
String str = "";
int lastNameHashCode =0;
int firstNameHashCode =0;
//转换类型
str = value+"";
//判断是否含有特殊字符
java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("[0-9]*[A-Za-z]*[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]*");
//根据以上判断截取姓、名、特殊字符放入数组
for (int i=0;i<str.length();i++){
java.util.regex.Matcher matcher = pattern.matcher(str.substring(i,i+1));
boolean matches = matcher.matches();
if (matches){
isSpecial=matches;
break;
}
}
//判断是否是复姓
for(String s: contain){
if(str.contains(s)){
isTwoName = true;
}
}
//判断是否是少数民族“·”
if(str.contains("·")){
isRareName = true;
}
//正常名字
//复姓名字
//少数民族名字
if (!isSpecial){
lastName = str.substring(0,1);
firstName = str.substring(1,str.length());
if (isTwoName){
lastName = str.substring(0, 2);
firstName = str.substring(2,str.length());
}
if(isRareName){
String regex = "·";
String strAry[] = str.split(regex);
lastName = strAry[0];
firstName = strAry[1];
}
//少数民族拼新名字
if (isRareName){
for (int i=0;i<lastName.length();i++){
firstNameHashCode = Math.abs(lastName.substring(i,i+1).hashCode());
newName+=fiName[random.nextInt(firstNameHashCode%(fiName.length-1))];
}
newName+="·";
for (int i=0;i<firstName.length();i++){
firstNameHashCode = Math.abs(firstName.substring(i,i+1).hashCode());
newName+=fiName[random.nextInt(firstNameHashCode%(fiName.length-1))];
}
}else{
lastNameHashCode = Math.abs(lastName.hashCode());//姓取正数
newName = laName[random.nextInt(lastNameHashCode%(laName.length-1))]; //获得一个固定的姓氏
if (isTwoName){
newName = contain[random.nextInt(lastNameHashCode%(contain.length-1))]; //获得一个固定的姓氏
}
for (int i=0;i<firstName.length();i++){
firstNameHashCode = Math.abs(firstName.substring(i,i+1).hashCode());
newName+=fiName[random.nextInt(firstNameHashCode%(fiName.length-1))];
}
}
}
//正常名字带特殊字符
//复姓名字带特殊字符
//少数民族名字带特殊字符
// Pattern pattern = Pattern.compile("[0-9]*[A-Za-z]*");
//判断汉字
java.util.regex.Pattern pattern1 = java.util.regex.Pattern.compile("[\\u4e00-\\u9fa5]");
// Pattern pattern = Pattern.compile("[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]");
//判断是否汉字[\u4e00-\u9fa5]
//特殊字符[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]
if (isSpecial){
int temp = 0;
//根据以上判断截取每个字符放入数组
String[] nameArray =new String [str.length()];
for (int i=0;i<str.length();i++){
nameArray[i] = str.substring(i,i+1);
}
if (isTwoName){
for (int i=0;i<nameArray.length;i++){
java.util.regex.Matcher matcher1 = pattern1.matcher(nameArray[i]);
boolean matches1 = matcher1.matches();
if (matches1&&temp==1){
firstName=nameArray[i];
firstNameHashCode = Math.abs(firstName.hashCode());//名取正数
newName = fiName[random.nextInt(firstNameHashCode%(fiName.length-1))]; //获得一个固定的姓名字
nameArray[i]=newName.substring(0);
}
if (matches1&&temp==0){
lastName=nameArray[i]+nameArray[i+1];
lastNameHashCode = Math.abs(lastName.hashCode());//姓取正数
newName = contain[random.nextInt(lastNameHashCode%(contain.length-1))]; //获得一个固定的姓氏
nameArray[i]=newName.substring(0,1);
nameArray[i+1]=newName.substring(1,2);
i+=1;
temp+=1;
}
}
}
if(isRareName){
for (int i=0;i<nameArray.length;i++){
java.util.regex.Matcher matcher1 = pattern1.matcher(nameArray[i]);
boolean matches1 = matcher1.matches();
if (matches1){
firstName=nameArray[i];
firstNameHashCode = Math.abs(firstName.hashCode());//名取正数
nameArray[i] = fiName[random.nextInt(firstNameHashCode%(fiName.length-1))]; //获得一个固定的姓名字
}
}
}
for (int i=0;i<nameArray.length;i++){
java.util.regex.Matcher matcher1 = pattern1.matcher(nameArray[i]);
boolean matches1 = matcher1.matches();
if (matches1&&temp==1){
firstName=nameArray[i];
firstNameHashCode = Math.abs(firstName.hashCode());//名取正数
newName = fiName[random.nextInt(firstNameHashCode%(fiName.length-1))]; //获得一个固定的姓名字
nameArray[i]=newName.substring(0);
}
if (matches1&&temp==0){
lastName=nameArray[i];
lastNameHashCode = Math.abs(lastName.hashCode());//姓取正数
newName = laName[random.nextInt(lastNameHashCode%(laName.length-1))]; //获得一个固定的姓氏
nameArray[i]=newName.substring(0,1);
temp+=1;
}
}
//生成String类型新名字
newName="";
for (int i=0;i<nameArray.length;i++){
newName+=nameArray[i];
}
}
return newName;
}
}<file_sep>package citic.password;
import java.math.BigDecimal;
/**
* Created by ${LiuShuo} on 2016/7/4.
*/
public class Password {
public static Object getM(Object value,Object key) {
//判断参数是否为null、"null"、"" ,为true时不做处理
if (value == null || value.equals("null") || value.equals("")) return value;
String s = value + "";
s="112233";
if(value instanceof BigDecimal){
return new BigDecimal(s);
}else if(value instanceof Long){
return Long.parseLong(s);
}else if(value instanceof Double){
return Double.parseDouble(s);
}
return s;
}
}
<file_sep>package version3;
/**
* Created by ${LiuShuo} on 8/16/2016.
*/
public class Test {
public static void main(String[] args) {
Object o = null;
try {
o = NameENameCompositeFilterAlgorithm.getModelComName("黑龙江省建三江农垦鑫龙水稻专业合作社", null);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(o);
}
}
<file_sep>package huanghe.taxpayer;
import two_param.taxpayer.*;
/**
* Created by ${LiuShuo} on 2016/6/30.
*/
public class TestTaxpayer {
public static void main(String[] args) {
// Object m = Taxpayer.getM("410104764886171", 123);
// Object m = Taxpayer.getM("22032319920308081x", 123);
// Object m = Taxpayer.getM("22032319920308081700", 123);
Object m = two_param.taxpayer.Taxpayer.getM("123456A2345678X", "77asdaww8787");
System.out.println(m);
/*
532 922 566 344 056
370 112 197 906 155 399
370 112 197 906 155 399
370 112 197 906 155 39900
220 800 530 102 875 00011
*/
}
}
<file_sep>package citic.telephone;
import java.math.BigDecimal;
import java.util.regex.Pattern;
/**
* 脱敏后6位号码,脱敏结果符合真实电话号生成规则且与原数据不同,如果同一原数据多次出现,脱敏生成的新数据也保持唯一。
* Created by ${LiuShuo} on 2016/7/4.
*/
public class Telephone {
public static Object getM(Object value,Object key) {
//判断参数是否为null、"null"、"" ,为true时不做处理
if (value == null || value.equals("null") || value.equals("")) return value;
String str = value + "";
str = str.replace(" ", "");
//验证是否数字
Pattern numRegex = Pattern.compile("^([0-9]{11})$");
if (!numRegex.matcher(str).matches()) return value;
if (str.length() != 11) return value;
String salt = key + "";
String saltok = salt.replace(" ", "");
//盐值hash
int hashSalt = 0;
if (salt.length() < 1) {
//没有盐值
} else {
hashSalt = Math.abs(saltok.hashCode());
}
String newStr2 = "";
String newStr1 ="";
String subStr1 = "";
int hash = 0;
if (str.substring(0,1).equals("0")){
newStr1 = str.substring(0,str.length()-6);
subStr1 = str.substring(str.length()-6,str.length());
hash = Math.abs(subStr1.hashCode() + hashSalt);
java.util.Random random1 = new java.util.Random(hash);
int dom = random1.nextInt(hash);
int code = (int) (((float)dom/(float)hash) * 1000);
if (code<10){
newStr2= "00" + code;
} else if (code < 100) {
newStr2= "0" + code;
} else {
newStr2= "" + code;
}
int code2 = (int) (((float)dom/(float)hash)*((float)dom/(float)hash)* 1000);
if (code2<10){
newStr2 += "00" + code2;
} else if (code2 < 100) {
newStr2 += "0" + code2;
} else {
newStr2 += "" + code2;
}
}else return value;
String s = newStr1+newStr2;
if(value instanceof BigDecimal){
return new BigDecimal(s);
}else if(value instanceof Long){
return Long.parseLong(s);
}else if(value instanceof Double){
return Double.parseDouble(s);
}
return s;
}
}
<file_sep>package two_param.group;
/**
* Created by ${LiuShuo} on 2016/6/22.
*/
public class TestGROUP {
public static void main(String[] args) {
Object m = Group.getM("A12345678","");
System.out.println(m);
}
}
<file_sep>package citic.group;
/**
* Created by ${LiuShuo} on 2016/7/4.
*/
public class Group {
public static Object getM(Object value,Object key) {
//判断参数是否为null、"null"、"" ,为true时不做处理
if (value == null || value.equals("null") || value.equals("")) return value;
String str = value + "";
str = str.replace(" ", "");
String salt = key + "";
String saltok = salt.replace(" ", "");
//盐值hash
int hashSalt = 0;
if (salt.length() < 1) {
//没有盐值
} else {
hashSalt = Math.abs(saltok.hashCode());
}
if (str.length() == 8){
}else if(str.length() == 9){
}else return value;
return "";
}
}
<file_sep>package com.wiseweb.common.util;
import java.io.UnsupportedEncodingException;
import java.util.Random;
/**
* Created by admin on 2016/6/13.
*/
public class MakeUpMethodUtil {
//-----------------------------------------姓名-----------------------------------------------------------
/**
* 根据原名获取固定姓名
* @param value
* @return
*/
public static Object getModelName(Object value){
boolean b = value instanceof String;
System.out.println(b);
String str = (String) value;
String lastName = str.substring(0,1);
String firstName = str.substring(1,str.length());
//作为判断是否复姓的数组
String[] contain= {"万俟","司马","上官","欧阳","夏侯","诸葛","闻人","东方","赫连","皇甫","羊舌","尉迟","公羊","澹台","公冶","宗正",
"濮阳","淳于","单于","太叔","申屠","公孙","仲孙","轩辕","令狐","钟离","宇文","长孙","慕容","鲜于","闾丘","司徒","司空","兀官","司寇",
"南门","呼延","子车","颛孙","端木","巫马","公西","漆雕","车正","壤驷","公良","拓跋","夹谷","宰父","谷梁","段干","百里","东郭","微生",
"梁丘","左丘","东门","西门","南宫","第五","公仪","公乘","太史","仲长","叔孙","屈突","尔朱","东乡","相里","胡母","司城","张廖","雍门",
"毋丘","贺兰","綦毋","屋庐","独孤","南郭","北宫","王孙"};
//把str分成名和姓*普通姓名:姓+名,例如:王立 *特殊姓名:名+·+姓(少数民族)例如:库尔班·热合曼
//判断是否复姓且不包含"·"
for(String s: contain){
if(s.equals(str.substring(0,2))&&!(str.contains("·"))){
// System.out.println("姓:"+str.substring(0,2));
// System.out.println("名:"+str.substring(2,str.length()));
lastName = str.substring(0, 2);
firstName = str.substring(2,str.length());
}
}
//包含"·"是少数民族名字
if(str.contains("·")){
String regex = "·";
String strAry[] = str.split(regex);
// for (int i = 0; i < strAry.length; i++) {
// System.out.println("i="+i+" Val="+strAry[i]);
// }
// System.out.println("姓:"+strAry[0]);
// System.out.println("名:"+strAry[1]);
lastName = strAry[0];
firstName = strAry[1];
}
System.out.println("姓:"+lastName);
System.out.println("名:"+firstName);
System.out.println("姓名长度:"+str.length());
int length = str.replaceAll("[0-9]*\\d*-*_*\\s*", "").length();
System.out.println("正则表达式判断:"+length);
// Pattern pattern=Pattern.compile("([0-9]*?|([abc]*?)([xyz]*?))([+-/*=])");
// Matcher matcher=pattern.matcher("12+13-ax+by=");
// while(matcher.find()){System.out.println("第一个:"+matcher.group(1)+",第二个:"+matcher.group(2)+",第三个:"+matcher.group(3)+",第四个:"+matcher.group(4));
int lastNameHashCode = Math.abs(lastName.hashCode());//姓取正数
int firstNameHashCode = Math.abs(firstName.hashCode());//名取正数
int nameHashCode = Math.abs(str.hashCode());//姓名取正数
Random random=new Random(nameHashCode);
/* 598 百家姓 */
String[] Surname= {"赵","钱","孙","李","周","吴","郑","王","冯","陈","褚","卫","蒋","沈","韩","杨","朱","秦","尤","许",
"何","吕","施","张","孔","曹","严","华","金","魏","陶","姜","戚","谢","邹","喻","柏","水","窦","章","云","苏","潘","葛","奚","范","彭","郎",
"鲁","韦","昌","马","苗","凤","花","方","俞","任","袁","柳","酆","鲍","史","唐","费","廉","岑","薛","雷","贺","倪","汤","滕","殷",
"罗","毕","郝","邬","安","常","乐","于","时","傅","皮","卞","齐","康","伍","余","元","卜","顾","孟","平","黄","和",
"穆","萧","尹","姚","邵","湛","汪","祁","毛","禹","狄","米","贝","明","臧","计","伏","成","戴","谈","宋","茅","庞","熊","纪","舒",
"屈","项","祝","董","梁","杜","阮","蓝","闵","席","季","麻","强","贾","路","娄","危","江","童","颜","郭","梅","盛","林","刁","钟",
"徐","邱","骆","高","夏","蔡","田","樊","胡","凌","霍","虞","万","支","柯","昝","管","卢","莫","经","房","裘","缪","干","解","应",
"宗","丁","宣","贲","邓","郁","单","杭","洪","包","诸","左","石","崔","吉","钮","龚","程","嵇","邢","滑","裴","陆","荣","翁","荀",
"羊","于","惠","甄","曲","家","封","芮","羿","储","靳","汲","邴","糜","松","井","段","富","巫","乌","焦","巴","弓","牧","隗","山",
"谷","车","侯","宓","蓬","全","郗","班","仰","秋","仲","伊","宫","宁","仇","栾","暴","甘","钭","厉","戎","祖","武","符","刘","景",
"詹","束","龙","叶","幸","司","韶","郜","黎","蓟","溥","印","宿","白","怀","蒲","邰","从","鄂","索","咸","籍","赖","卓","蔺","屠",
"蒙","池","乔","阴","郁","胥","能","苍","双","闻","莘","党","翟","谭","贡","劳","逄","姬","申","扶","堵","冉","宰","郦","雍","却",
"璩","桑","桂","濮","牛","寿","通","边","扈","燕","冀","浦","尚","农","温","别","庄","晏","柴","瞿","阎","充","慕","连","茹","习",
"宦","艾","鱼","容","向","古","易","慎","戈","廖","庾","终","暨","居","衡","步","都","耿","满","弘","匡","国","文","寇","广","禄",
"阙","东","欧","殳","沃","利","蔚","越","夔","隆","师","巩","厍","聂","晁","勾","敖","融","冷","訾","辛","阚","那","简","饶","空",
"曾","毋","沙","乜","养","鞠","须","丰","巢","关","蒯","相","查","后","荆","红","游","郏","竺","权","逯","盖","益","桓","公","仉",
"督","岳","帅","缑","亢","况","郈","有","琴","归","海","晋","楚","闫","法","汝","鄢","涂","钦","商","牟","佘","佴","伯","赏","墨",
"哈","谯","篁","年","爱","阳","佟","言","福","南","火","铁","迟","漆","官","冼","真","展","繁","檀","祭","密","敬","揭","舜","楼",
"疏","冒","浑","挚","胶","随","高","皋","原","种","练","弥","仓","眭","蹇","覃","阿","门","恽","来","綦","召","仪","风","介","巨",
"木","京","狐","郇","虎","枚","抗","达","杞","苌","折","麦","庆","过","竹","端","鲜","皇","亓","老","是","秘","畅","邝","还","宾",
"闾","辜","纵","侴","万俟","司马","上官","欧阳","夏侯","诸葛","闻人","东方","赫连","皇甫","羊舌","尉迟","公羊","澹台","公冶","宗正",
"濮阳","淳于","单于","太叔","申屠","公孙","仲孙","轩辕","令狐","钟离","宇文","长孙","慕容","鲜于","闾丘","司徒","司空","兀官","司寇",
"南门","呼延","子车","颛孙","端木","巫马","公西","漆雕","车正","壤驷","公良","拓跋","夹谷","宰父","谷梁","段干","百里","东郭","微生",
"梁丘","左丘","东门","西门","南宫","第五","公仪","公乘","太史","仲长","叔孙","屈突","尔朱","东乡","相里","胡母","司城","张廖","雍门",
"毋丘","贺兰","綦毋","屋庐","独孤","南郭","北宫","王孙"};
int index=random.nextInt(lastNameHashCode%(Surname.length-1));
String name = Surname[index]; //获得一个固定的姓氏
/* 从常用字中选取固定一个或两个字作为名 */
if(random.nextBoolean()){
name+=getModelChinese(firstNameHashCode)+getModelChinese(firstNameHashCode);
}else {
name+=getModelChinese(firstNameHashCode);
}
return name;
}
/**
* 获取随机姓名
* @return
*/
public static Object getRandomName(){
Random random=new Random(System.currentTimeMillis());
/* 598 百家姓 */
String[] Surname= {"赵","钱","孙","李","周","吴","郑","王","冯","陈","褚","卫","蒋","沈","韩","杨","朱","秦","尤","许",
"何","吕","施","张","孔","曹","严","华","金","魏","陶","姜","戚","谢","邹","喻","柏","水","窦","章","云","苏","潘","葛","奚","范","彭","郎",
"鲁","韦","昌","马","苗","凤","花","方","俞","任","袁","柳","酆","鲍","史","唐","费","廉","岑","薛","雷","贺","倪","汤","滕","殷",
"罗","毕","郝","邬","安","常","乐","于","时","傅","皮","卞","齐","康","伍","余","元","卜","顾","孟","平","黄","和",
"穆","萧","尹","姚","邵","湛","汪","祁","毛","禹","狄","米","贝","明","臧","计","伏","成","戴","谈","宋","茅","庞","熊","纪","舒",
"屈","项","祝","董","梁","杜","阮","蓝","闵","席","季","麻","强","贾","路","娄","危","江","童","颜","郭","梅","盛","林","刁","钟",
"徐","邱","骆","高","夏","蔡","田","樊","胡","凌","霍","虞","万","支","柯","昝","管","卢","莫","经","房","裘","缪","干","解","应",
"宗","丁","宣","贲","邓","郁","单","杭","洪","包","诸","左","石","崔","吉","钮","龚","程","嵇","邢","滑","裴","陆","荣","翁","荀",
"羊","于","惠","甄","曲","家","封","芮","羿","储","靳","汲","邴","糜","松","井","段","富","巫","乌","焦","巴","弓","牧","隗","山",
"谷","车","侯","宓","蓬","全","郗","班","仰","秋","仲","伊","宫","宁","仇","栾","暴","甘","钭","厉","戎","祖","武","符","刘","景",
"詹","束","龙","叶","幸","司","韶","郜","黎","蓟","溥","印","宿","白","怀","蒲","邰","从","鄂","索","咸","籍","赖","卓","蔺","屠",
"蒙","池","乔","阴","郁","胥","能","苍","双","闻","莘","党","翟","谭","贡","劳","逄","姬","申","扶","堵","冉","宰","郦","雍","却",
"璩","桑","桂","濮","牛","寿","通","边","扈","燕","冀","浦","尚","农","温","别","庄","晏","柴","瞿","阎","充","慕","连","茹","习",
"宦","艾","鱼","容","向","古","易","慎","戈","廖","庾","终","暨","居","衡","步","都","耿","满","弘","匡","国","文","寇","广","禄",
"阙","东","欧","殳","沃","利","蔚","越","夔","隆","师","巩","厍","聂","晁","勾","敖","融","冷","訾","辛","阚","那","简","饶","空",
"曾","毋","沙","乜","养","鞠","须","丰","巢","关","蒯","相","查","后","荆","红","游","郏","竺","权","逯","盖","益","桓","公","仉",
"督","岳","帅","缑","亢","况","郈","有","琴","归","海","晋","楚","闫","法","汝","鄢","涂","钦","商","牟","佘","佴","伯","赏","墨",
"哈","谯","篁","年","爱","阳","佟","言","福","南","火","铁","迟","漆","官","冼","真","展","繁","檀","祭","密","敬","揭","舜","楼",
"疏","冒","浑","挚","胶","随","高","皋","原","种","练","弥","仓","眭","蹇","覃","阿","门","恽","来","綦","召","仪","风","介","巨",
"木","京","狐","郇","虎","枚","抗","达","杞","苌","折","麦","庆","过","竹","端","鲜","皇","亓","老","是","秘","畅","邝","还","宾",
"闾","辜","纵","侴","万俟","司马","上官","欧阳","夏侯","诸葛","闻人","东方","赫连","皇甫","羊舌","尉迟","公羊","澹台","公冶","宗正",
"濮阳","淳于","单于","太叔","申屠","公孙","仲孙","轩辕","令狐","钟离","宇文","长孙","慕容","鲜于","闾丘","司徒","司空","兀官","司寇",
"南门","呼延","子车","颛孙","端木","巫马","公西","漆雕","车正","壤驷","公良","拓跋","夹谷","宰父","谷梁","段干","百里","东郭","微生",
"梁丘","左丘","东门","西门","南宫","第五","公仪","公乘","太史","仲长","叔孙","屈突","尔朱","东乡","相里","胡母","司城","张廖","雍门",
"毋丘","贺兰","綦毋","屋庐","独孤","南郭","北宫","王孙"};
int index=random.nextInt(Surname.length-1);
String name = Surname[index]; //获得一个随机的姓氏
/* 从常用字中随机选取一个或两个字作为名 */
if(random.nextBoolean()){
name+=getRandomChinese()+getRandomChinese();
}else {
name+=getRandomChinese();
}
return name;
}
//生成固定名
public static String getModelChinese(int i) {
String str = null;
int highPos, lowPos;
Random random = new Random(i);
highPos = (176 + Math.abs(random.nextInt(71)));//区码,0xA0打头,从第16区开始,即0xB0=11*16=176,16~55一级汉字,56~87二级汉字
random=new Random(i);
lowPos = 161 + Math.abs(random.nextInt(94));//位码,0xA0打头,范围第1~94列
byte[] bArr = new byte[2];
bArr[0] = (new Integer(highPos)).byteValue();
bArr[1] = (new Integer(lowPos)).byteValue();
try {
str = new String(bArr, "GB2312"); //区位码组合成汉字
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return str;
}
//生成随机名
public static String getRandomChinese() {
String str = null;
int highPos, lowPos;
Random random = new Random();
highPos = (176 + Math.abs(random.nextInt(71)));//区码,0xA0打头,从第16区开始,即0xB0=11*16=176,16~55一级汉字,56~87二级汉字
random=new Random();
lowPos = 161 + Math.abs(random.nextInt(94));//位码,0xA0打头,范围第1~94列
byte[] bArr = new byte[2];
bArr[0] = (new Integer(highPos)).byteValue();
bArr[1] = (new Integer(lowPos)).byteValue();
try {
str = new String(bArr, "GB2312"); //区位码组合成汉字
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return str;
}
//-----------------------------------------公司名称-------------------------------------------------------------
/**
* 随机生成公司名
* @return
*/
public static Object getRandomCompanyName(){
Random random=new Random(System.currentTimeMillis());
/* 598 百家姓 */
String[] Surname= {"修","宵","晨","戏","施","顺","祥","才","聪","银","戈","喻","声","生","铁","如","宸","誓","胜","挚","靖","齐",
"锦","少","舟","任","载","翱","青","迁","钧","钟","金","慈","昌","紫","砂","仁","祖","韶","绍","锐","峻","裕","镇","壮","商",
"翼","织","释","诚","常","净","秀","节","刊","信","崇","春","铭","秋","刚","诗","神","星","鉴","石","识","肃","瑞","新","鑫",
"盛","帅","馨","惜","散","慎","世","书","千","善","镜","然","资","笑","疏","西","捷","超","川","锋","实","聚","尊","承","钦",
"仕","众","思","茂","贤","棕","树","蓝","卷","谷","君","古","原","廉","建","庆","桦","统","若","攀","栋","荒","何","久","侠",
"奇","朴","鸽","东","嘉","冠","松","啸","祺","琪","雁","宜","琦","枝","坚","昂","毅","歌","标","固","吉","高","康","尧","果",
"杭","语","曲","肖","荷","芹","乾","义","杰","皓","凯","狂","本","勤","彬","景","月","兼","顷","柏","擎","荣","观","笃","恭",
"柯","言","菲","萧","乔","群","谦","国","极","轻","玉","业","材","相","苑","倚","岳","柳","贵","悟","健","彦","棋","楷","桐",
"气","颜","苛","池","闻","流","霜","福","泉","宏","弘","浅","熙","济","涛","震","和","闲","霖","向","波","渊","博","游","雨",
"润","湛","凡","奔","夫","潮","深","岸","辉","浚","复","封","飞","朋","江","奉","晖","绘","浪","鸣","百","鹤","沙","漾","泥",
"雪","孝","万","望","瀚","缈","淡","阜","保","阔","洪","恒","云","伯","玄","风","淘","合","文","莫","享","满","溪","妙","邦",
"华","冰","方","寒","鹏","陌","奋","秉","泽","豪","布","明","民","虎","帆","洋","名","拂","海","潭","清","勉","源","平","物",
"沧","霄","熊","论","彤","烟","阳","耀","励","晋","临","伦","日","传","炎","彰","全","丰","晓","瞻","拓","展","绩","炫","尘",
"征","昙","道","飘","鼎","龙","昊","腾","至","宝","驰","易","耿","昆","振","知","光","灿","智","畅","晴","迪","绿","扬","来",
"志","煊","遥","宁","衷","太","凌","天","璋","瑾","俊","里","韬","量","致","烨","忠","厉","理","路","年","循","昭","达","都",
"蝶","章","照","积","良","泰","烈","庭","折","进","晟","德","际","琢","利","哲","质","隆","田","煜","南","乐","翎","冬","图",
"暖","壤","佑","翔","伟","磊","欧","运","豫","维","坤","恩","永","意","野","幽","远","圣","山","城","音","韵","依","余","圆",
"勋","忆","叶","亦","卫","傲","融","勇","逸","育","唯","基","容","温","安","奥","引","影","羽","均","誉","越","辰","轩","延",
"境","宇","悠","益","岩","玮","威","硕","庸","懿","统","柏","彤","兼","昊","肖","杰","含","凯","振","秉","沧","享","朋","轻",
"俊","材","宇","松","依","池","钦","桦","芹","孝","炫","极","洋","舟","际","荒","衷","亦","狂","闻","幽","曲","耿","勇","奇",
"城","冰","柯","浦","林","和","明","名","建","尧","胜","朴","存","顺","昌","西","昙","砂","语","泰","伦","烈","杭","育","折",
"达","顷","忠","延","坤","佑","修","闲","坚","泉","劲","勋","枝","年","迁","致","治","健","羽","晓","卷","如","宸","荷","物",
"合","复","晖","易","灿","浅","悟","壮","临","荣","桦","乔","承","明","顺","物","原","统","哲","庭","运","修","远","峰","兼",
"杉","莫","均","幽","高","闲","宝","拓","若","材","玮","余","苛","欢","凌","函","享","陌","亦","旷","全","君","思","秀","威",
"海","烨","尧","声","展","秋","标","羽","昭","合","建","坤","南","利","华","伦","挚","宵","壮","众","晋","松","恩","阳","泉",
"恭","树","钟","致","苑","封","诗","晓","戏","荣","里","拂","至","奋","初","图","烈","金","如","钦","俊","贵","宸","狂","益",
"耿","积","复","勋","佑","肃","光","轻","施","任"};
int index=random.nextInt(Surname.length-1);
String name = Surname[index]; //获得一个随机的名字
if(random.nextBoolean()){
name+=Surname[random.nextInt(Surname.length-1)]+Surname[random.nextInt(Surname.length-1)]+"公司";
}else {
name+=Surname[random.nextInt(Surname.length-1)]+"公司";
}
return name;
}
/**
* 根据原公司名获取固定名称
* @param oldCompanyName
* @return
*/
public static Object getModelCompanyName(Object oldCompanyName){
String str = (String) oldCompanyName;
int i = Math.abs(str.hashCode());//取正数
Random random=new Random(i);
/* 公司名 */
String[] Surname= {"修","宵","晨","戏","施","顺","祥","才","聪","银","戈","喻","声","生","铁","如","宸","誓","胜","挚","靖","齐",
"锦","少","舟","任","载","翱","青","迁","钧","钟","金","慈","昌","紫","砂","仁","祖","韶","绍","锐","峻","裕","镇","壮","商",
"翼","织","释","诚","常","净","秀","节","刊","信","崇","春","铭","秋","刚","诗","神","星","鉴","石","识","肃","瑞","新","鑫",
"盛","帅","馨","惜","散","慎","世","书","千","善","镜","然","资","笑","疏","西","捷","超","川","锋","实","聚","尊","承","钦",
"仕","众","思","茂","贤","棕","树","蓝","卷","谷","君","古","原","廉","建","庆","桦","统","若","攀","栋","荒","何","久","侠",
"奇","朴","鸽","东","嘉","冠","松","啸","祺","琪","雁","宜","琦","枝","坚","昂","毅","歌","标","固","吉","高","康","尧","果",
"杭","语","曲","肖","荷","芹","乾","义","杰","皓","凯","狂","本","勤","彬","景","月","兼","顷","柏","擎","荣","观","笃","恭",
"柯","言","菲","萧","乔","群","谦","国","极","轻","玉","业","材","相","苑","倚","岳","柳","贵","悟","健","彦","棋","楷","桐",
"气","颜","苛","池","闻","流","霜","福","泉","宏","弘","浅","熙","济","涛","震","和","闲","霖","向","波","渊","博","游","雨",
"润","湛","凡","奔","夫","潮","深","岸","辉","浚","复","封","飞","朋","江","奉","晖","绘","浪","鸣","百","鹤","沙","漾","泥",
"雪","孝","万","望","瀚","缈","淡","阜","保","阔","洪","恒","云","伯","玄","风","淘","合","文","莫","享","满","溪","妙","邦",
"华","冰","方","寒","鹏","陌","奋","秉","泽","豪","布","明","民","虎","帆","洋","名","拂","海","潭","清","勉","源","平","物",
"沧","霄","熊","论","彤","烟","阳","耀","励","晋","临","伦","日","传","炎","彰","全","丰","晓","瞻","拓","展","绩","炫","尘",
"征","昙","道","飘","鼎","龙","昊","腾","至","宝","驰","易","耿","昆","振","知","光","灿","智","畅","晴","迪","绿","扬","来",
"志","煊","遥","宁","衷","太","凌","天","璋","瑾","俊","里","韬","量","致","烨","忠","厉","理","路","年","循","昭","达","都",
"蝶","章","照","积","良","泰","烈","庭","折","进","晟","德","际","琢","利","哲","质","隆","田","煜","南","乐","翎","冬","图",
"暖","壤","佑","翔","伟","磊","欧","运","豫","维","坤","恩","永","意","野","幽","远","圣","山","城","音","韵","依","余","圆",
"勋","忆","叶","亦","卫","傲","融","勇","逸","育","唯","基","容","温","安","奥","引","影","羽","均","誉","越","辰","轩","延",
"境","宇","悠","益","岩","玮","威","硕","庸","懿","统","柏","彤","兼","昊","肖","杰","含","凯","振","秉","沧","享","朋","轻",
"俊","材","宇","松","依","池","钦","桦","芹","孝","炫","极","洋","舟","际","荒","衷","亦","狂","闻","幽","曲","耿","勇","奇",
"城","冰","柯","浦","林","和","明","名","建","尧","胜","朴","存","顺","昌","西","昙","砂","语","泰","伦","烈","杭","育","折",
"达","顷","忠","延","坤","佑","修","闲","坚","泉","劲","勋","枝","年","迁","致","治","健","羽","晓","卷","如","宸","荷","物",
"合","复","晖","易","灿","浅","悟","壮","临","荣","桦","乔","承","明","顺","物","原","统","哲","庭","运","修","远","峰","兼",
"杉","莫","均","幽","高","闲","宝","拓","若","材","玮","余","苛","欢","凌","函","享","陌","亦","旷","全","君","思","秀","威",
"海","烨","尧","声","展","秋","标","羽","昭","合","建","坤","南","利","华","伦","挚","宵","壮","众","晋","松","恩","阳","泉",
"恭","树","钟","致","苑","封","诗","晓","戏","荣","里","拂","至","奋","初","图","烈","金","如","钦","俊","贵","宸","狂","益",
"耿","积","复","勋","佑","肃","光","轻","施","任"};
int index=random.nextInt(i%(Surname.length-1));
String name = Surname[index]; //获得一个固定的姓氏
/* 从常用字中选取固定一个或两个字作为名 */
if(random.nextBoolean()){
name+=Surname[random.nextInt(i%(Surname.length-1))]+Surname[random.nextInt(i%(Surname.length-1))]+"公司";
}else {
name+=Surname[random.nextInt(i%(Surname.length-1))]+"公司";
}
return name;
}
//-----------------------------------------身份证(18位&15位)--------------------------------------------------
//-----------------------------------------军官证---------------------------------------------------------------
//-----------------------------------------手机号码-------------------------------------------------------------
//-----------------------------------------座机号码-------------------------------------------------------------
//-----------------------------------------物理地址-------------------------------------------------------------
//-----------------------------------------邮编地址-------------------------------------------------------------
//-----------------------------------------邮箱地址-------------------------------------------------------------
//-----------------------------------------银行卡号-------------------------------------------------------------
//-----------------------------------------组织机构号-----------------------------------------------------------
//-----------------------------------------营业执照号-----------------------------------------------------------
//-----------------------------------------税务登记号-----------------------------------------------------------
}
<file_sep>package huanghe.email;
import two_param.email.*;
/**
* Created by ${LiuShuo} on 2016/6/29.
*/
public class TestEmail {
public static void main(String[] args) {
Object m = two_param.email.Email.getM("73574680@<EMAIL>", 111123);
System.out.println(m);
}
}
<file_sep>package citic.telephone;
/**
* Created by ${LiuShuo} on 2016/7/4.
*/
public class TestTel {
public static void main(String[] args) {
Object m = Telephone.getM("01012q45671", 1);
System.out.println(m);
}
}
<file_sep>package param;
/**
* Created by ${LiuShuo} on 8/15/2016.
*/
class Test01 {
public static void main(String[] args) {
StringBuffer s = new StringBuffer("good");
StringBuffer s2 = new StringBuffer("bad");
test(s, s2);
System.out.println(s);//9
System.out.println(s2);//10
}
static void test(StringBuffer s, StringBuffer s2) {
System.out.println(s);//1
System.out.println(s2);//2
s2 = s;//3
s = new StringBuffer("new");//4
System.out.println(s);//5
System.out.println(s2);//6
s.append("hah");//7
s2.append("hah");//8
}
}
<file_sep>package huanghe.group;
import two_param.group.*;
/**
* Created by ${LiuShuo} on 2016/6/22.
*/
public class TestGROUP {
public static void main(String[] args) {
Object m = two_param.group.Group.getM("A12345678","");
System.out.println(m);
}
}
<file_sep>package citic.mobile_phone;
/**
* Created by ${LiuShuo} on 2016/7/4.
*/
public class TestMobile {
public static void main(String[] args) {
Object m = MobilePhone.getM(13630950849L, 1);
System.out.println(m);
}
}
<file_sep>package param;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* 一、网络通信的要素:①要知道双方的通信地址:IP地址 ②要遵循一定的通信协议
* 二、IP:唯一的标识 internet上的一台计算机
* 1.一个ip地址,对应着java.net.InetAddress类的一个对象
* 2.如何实例化InetAddress
* ①getByName(String host)②获取本机的Ip地址:getLocalHost()
* 3.ip地址格式:比如192.168.10.165
* 为了方便的使用ip地址,我们提出了域名的概念。比如:www.baidu.com; www.atguigu.com;
* www.sina.com; www.mi.com;www.jd.com; www.vip.com;
* 4.两个常用的方法:getHostName():获取域名/主机名
* getHostAddress():获取主机的ip地址
* 5.本地的回路地址:127.0.0.1
* 三、端口号:用于区分一台主机上不同的进程。0--65535
* 常见的端口号: oracle:1521 mysql:3306 http:80 tomcat:8080 ...
*
* * Created by ${LiuShuo} on 8/16/2016.
*/
public class InetAddressT {
public static void main(String[] args) {
try {
// InetAddress byName = InetAddress.getByName("www.wiseweb.com.cn");
// System.out.println(byName);
// InetAddress byName2 = InetAddress.getByName("172.16.58.3");
// System.out.println(byName2);
// System.out.println(byName2.getHostName());
// System.out.println(byName2.getHostAddress());
// System.out.println(byName2.getCanonicalHostName());
//获取本机的ip地址对应的InetAddress类的对象
InetAddress localHost = InetAddress.getLocalHost();
System.out.println(localHost);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
<file_sep>package citic.idcard;
import java.util.regex.Pattern;
/**
* 身份证号码脱敏规则:身份证前四位不变,第五位到第六位按照加权算法修改。
* (见附件中的公式一)。18位身份证的第七位到第十位减2,第十一位到第十二位加7取12的余数,
* 07直接改为08。15位身份证的第七位到第八位减2,第九位到第十位加7取12的余数,特殊情况下,
* 对于15位身份证号需修改第十三位,对于18位身份证号需修改第十五位。(见附件中的公式二)。
* 18位身份证得出前17位身份证后,再按照校验算法计算出第十八位的效验位(见附件中的公式三)。
* 对于同时拥有15位和18位身份证的客户信息, 15位的身份证在相关算法操作后,仍然保持15位不变;
* 它证件种类脱敏规则;使用加权算法替换后两位号码,计算时原有号码中的汉字保持不变,并且不参与计算,
* 字母按照附件中的对比关系,替换成数字后进行换算(见附件中的公式四)。
公式一:
权数表示:A(n) ,使用:A=(2,7,5,6,1,1)
身份证表示:Id(n)
FOR n= 5 TO 6
FOR 1 TO n
An * Id(n) = C1C2( 两位整数 )
C1 + C2 = Dn
Dn=Dn mod 11 (mod 为取余数运算)
若Dn为10则取0
E=E + Dn
ENDFOR
E=E mod 11
E=11–E
若E为10则取0,若为11则取1.
Id(n)=E
ENDFOR
公式二:
SELECT
WHEN 原来的身份证位数=15
Id(7,8)= Id(7,8)-2
IF Id(9,12) not in (‘0729’,‘0730’,‘0731’)
Id(9,10)= (Id(9,10)+7)mod 12
ELSE
Id(13)=(ID(13)+1)mod 10
ENDIF
WHEN原来的身份证位数=18
C1C2C3=Id(9)*10+Id(10)+98
IF C1=0
Id(7,8)='19’
ENDIF
Id(9,10)=C2C3
IF Id(11,14) not in (‘0729’,‘0730’,‘0731’)
Id(11,12)= (Id(11,12)+7)mod 12
ELSE
Id(15)= (ID(15)+1)mod 10
ENDIF
OTHER
ENDSL
公式四:
字母和数字的对应关系表,大小写一致。
A B C D E F G H I
10 11 12 13 14 15 16 17 18
J K L M N O P Q R
19 20 21 22 23 24 25 26 27
S T U V W X Y Z
28 29 30 31 32 33 34 35
权数表示:A(n) ,使用:A=(2,7,5,6,1,1,5,4,3,1,9,6,8,1,2,2,3,5)
证件号码表示:Id(n),
FOR m= n-1 TO n
FOR 1 TO m
An * Id(m) = C1C2 ( 只取个位、十位两位结果 )
C1 + C2 = Dm
Dm=Dm mod 11
若Dm为10则取0
E=E + Dm
ENDFOR
E=E mod 11
E=11–E
若E为10则取0,若为11则取1.
Id(n)=E
ENDFOR
* Created by ${LiuShuo} on 2016/7/4.
*/
public class IdCard {
public static Object getM(Object value,Object key) {
//判断参数是否为null、"null"、"" ,为true时不做处理
if (value==null||value.equals("null")||value.equals("")) return value;
String str = value+"";
str=str.replace(" ", "");
//证件号长度小于4不做处理
if (str.length()<4) return value;
String salt = key + "";
String saltok = salt.replace(" ", "");
//盐值hash
int hashSalt = 0;
if (salt.length()<1){
//没有盐值
}else {
hashSalt=Math.abs(saltok.hashCode());
}
//正则表达式 数字
Pattern numRegex = Pattern.compile("^([0-9])$");
String subStr1 = "";
String subStr2 = "";
String subStr3 = "";
String subStr4 = "";
String newStr1 = "";
//15 15位身份证 18 18位身份证 0 其他(加权清洗后两位)
int type = 0;
//15位身份证都是数字 如果含有字母肯定不是(只能做到如此,不知道他们数据库有没有其他15的帐号)下同
if (str.length() == 15 && numRegex.matcher(str).matches()){
type = 15;
}
if (str.length() == 18 && numRegex.matcher(str.substring(0,17)).matches()){
type = 18;
}
if (type == 15){
newStr1 = str.substring(0,4);
subStr2 = str.substring(4,6);
subStr3 = str.substring(6,8);
subStr4 = str.substring(6,8);
}else if (type == 18){
}else {
}
return "";
}
}
<file_sep>package huanghe.address;
import sun.awt.SunHints;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Pattern;
/**
* Created by ${LiuShuo} on 2016/6/22.
*/
public class TestADDR {
public static void main(String[] args) {
//1号楼2单元301
// Pattern p = Pattern.compile("^([\\u4e00-\\u9fa5])*([A-Za-z0-9_])*+(省|市|县|区|街|镇|楼|村)+([\\u4e00-\\u9fa5])*([A-Za-z0-9_])*$");
// Pattern p = Pattern.compile("^([^\\x00-\\xff]|[A-Za-z0-9_])+$");
// Pattern p = Pattern.compile("^([\\u4e00-\\u9fa5]|[A-Za-z0-9_])*+(省|市|县|区|街|镇|楼|村)+([\\u4e00-\\u9fa5]|[A-Za-z0-9_])*$");
// Pattern p = Pattern.compile("^([\\u4e00-\\u9fa5])*([A-Za-z0-9_-])*(省|市|县|区|街|镇|楼|村)+([\\u4e00-\\u9fa5])*([A-Za-z0-9_-])*$");
// boolean matches = p.matcher().matches();
//
// System.out.println(matches);
// Object m = Address2.getM("辽宁省葫芦岛市其他连山市昆山路莲花", 1);
// System.out.println(m);
// String[] noChange2 = {"银川","中卫","固原","吴忠","石嘴山","蒙古族","自治县","二手","车行","物资","经营部","宁夏","农村","商业","银行","股份","有限","公司","支行","吴忠","苗木","种植","专业","合作社","吴忠","养殖","专业","合作社","村级","发展","资金","互助社","吴忠","果蔬","种植","专业","合作社","交通","资产","管理","银川","家私","制造","保洁","服务","中心","商业","餐饮","中卫","小额","贷款","青铜峡","中心","副食品","批发部","宁夏","农村","商业","银行","股份","有限","公司","支行","吴忠","陶瓷","经销部","清真","南寺","清真","清真寺","内蒙古","实业","集团","中卫","农民","专业","合作社","宁夏","园林","景观","工程"};
// Set s = new TreeSet();
// for (int i = 0; i < noChange2.length; i++) {
// s.add(noChange2[i]);
// }
// Iterator i = s.iterator();
// while (i.hasNext()){
// System.out.print("\""+i.next()+"\",");
// }
// byte[] b = {};
// String s = "";
// Object[] o = {b,s};
//// if (value instanceof byte[] )return value;
// if (o[0] instanceof byte[] ){
// System.out.println(123);
// }
//
// if (o[0] instanceof String ){
// System.out.println(456);
// }
// String str = "区小校";
// String[] arrStr1 = str.split("区");
// if (arrStr1.length < 2) System.out.println(123);
// System.out.println(arrStr1[1]);
// System.out.println("小区,单元,大街,酒店,公司,花园,社区,宿舍,幼儿,园区,水果,市场,酒楼,服装,贸易,商城,电器,维修,行政,中心,开发,工贸,批发,工业,机械,综合,休闲,码头,食堂".replace(",","\",\""));
// Object m = Address3.getM("嘉兴市天天嘉苑4幢1号办公房2层西区", 1);
// System.out.println(m);
/* String[] s = {
"缈","游","温","逸","嵋","瞻","颜","缺","渊","暖","清","觅","观","崧","遥","喻","更","喧","曲","崴","曼","罕","曹","崎","腾","湛","石","崇","喜","飞","飘","善","知",
"崖","风","矩","道","啸","巡","邦","昭","真","巧","映","巨","春","美","邵","省","昱","羚","溪","昴","羞","昶","眺","昊","源","明","昏","昌","群","昂","昆","昙","星",
"易","羿","商","州","川","羽","昕","昔","景","晨","顺","翁","晤","顶","翎","页","唱","翔","唯","满","智","唤","晴","都","致","晋","至","晃","唐","晟","西","臣","晖",
"翼","晓","自","皆","而","皇","袖","耀","馨","山","考","皎","袁","皓","耘","哲","枯","品","林","哈","屑","哉","枚","果","展","枝","极","屋","届","耿","首","耽","屏",
"枇","香","枋","居","耶","尼","潭","柳","柱","益","盈","咨","查","咱","聚","尧","柯","盛","柔","尘","聪","柒","尚","和","目","尖","酒","少","柚","柄","直","咖","酋",
"尊","盼","柏","将","封","相","肃","峰","周","朽","峻","朱","朴","未","末","峡","术","肖","本","峪","峨","峭","纱","呈","纳","望","纷","纹","纸","肩","纺","纽","朔",
"员","月","有","红","朋","服","肴","约","级","纪","纯","启","板","松","结","岳","含","统","绘","岸","杰","细","行","织","组","绅","杭","胜","吴","来","绍","绊","终",
"条","岩","名","维","同","杜","胥","岗","束","后","杞","吉","合","金","衷","各","绿","釜","材","岛","岚","白","采","百","李","杏","癸","衫","杉","表","君","野","量",
"吕","里","重","释","绩","向","衣","累","乾","埔","计","紫","氛","订","训","疾","讯","气","索","民","素","书","城","设","访","许","习","论","彭","九","埴","彬","彩",
"乘","永","彪","彤","乔","彦","乖","培","乐","乓","基","乒","义","茉","久","茄","茅","疏","彷","彰","茂","范","影","茁","主","为","弈","江","高","串","丰","语","荷",
"临","垂","弘","型","汀","荣","丙","丘","证","诀","业","汽","识","东","评","丞","汾","汴","词","弧","世","弦","强","垣","诗","诚","池","七","万","忆","价","必","坚",
"仲","町","仰","沐","甲","任","申","沛","田","沙","志","沅","沃","坊","沂","沁","均","莫","沈","甜","仕","生","忠","甘","仑","甚","仓","河","沼","沽","沾","沿","沸",
"油","念","沧","仁","坪","忽","坤","从","坦","坡","沫","亳","泓","菲","征","泗","径","法","泛","律","徒","徐","产","得","亦","圃","享","泊","徙","亩","泉","徘","亨",
"亮","圆","略","亭","徜","京","泰","御","留","云","场","泳","徨","地","驰","亚","圳","泽","波","泥","圭","界","德","马","争","注","圣","事","畅","于","般","斗","航",
"佩","洋","料","文","使","船","洛","舷","舶","洗","回","佳","住","舍","幼","幽","位","洪","新","因","幸","并","年","津","施","璋","平","方","斧","派","洽","舟","佛",
"余","图","洵","何","国","誉","洲","固","斩","佑","舒","佐","帛","帝","良","济","瓦","伯","传","流","米","浅","伦","伧","浙","师","浚","伺","旅","希","艾","旋","布",
"市","帅","伴","族","帆","浪","伊","常","浩","时","旷","伏","伍","旺","浣","企","浦","既","伟","旦","席","日","早","旨","海","众","旭","涅","信","琪","芯","芮","芭",
"俯","芬","修","琦","芫","琢","芷","芳","俱","涓","花","芽","攀","廉","芸","涛","芹","粗","政","润","延","放","粒","琉","节","芍","俏","理","收","俊","建","芊","俗",
"芒","俐","俞","芝","保","言","芙","粉","嘉","若","庚","府","侯","敖","效","英","瑾","庆","敏","淘","床","苹","故","便","淡","康","庶","庸","庾","侍","苑","苓","深",
"苔","度","瑞","座","苗","庭","依","央","冶","天","鑫","冰","太","冲","冬","珍","珏","珈","珊","珀","冠","拳","备","路","军","拉","夏","复","冒","拂","多","拓","珠",
"越","笃","奢","出","奥","函","凰","超","玖","笑","玉","凯","笙","抱","凡","笛","玄","好","率","玻","奂","笠","奇","奋","玫","凌","奔","奕","净","准","资","执","铭",
"扬","鱼","银","承","赤","扇","才","如","铁","妙","共","姬","兵","其","具","典","钦","兼","姿","全","六","贝","贡","财","贤","成","贵","兆","钟","克","光","先","钗",
"武","步","正","长","堡","傲","歌","镜","穹","空","镇","堆","堂","欢","欣","次","欧","犁","锦","程","锐","萧","锋","竟","捷","毫","站","闻","倩","闲","蓝","问","豆",
"门","立","闪","值","竿","牧","竹","牡","竺","倍","毅","物","章","豪","豫","倚","境","健","壮","振","壤","偃","殊","谷","挚","谦","桓","厚","桑","迪","桐","际","原",
"祥","桔","蝶","桂","桃","祺","迁","迅","进","祖","桦","远","运","神","祟","栗","悉","树","阔","标","悟","字","达","社","孟","孝","参","辰","栋","熙","阡","辉","季",
"栽","格","叶","悠","台","召","叮","可","孰","校","阳","熊","麦","古","栩","宋","守","秩","安","积","宏","北","雀","雁","轩","匙","宁","秦","宇","棕","棋","宛","恒",
"定","宙","照","实","宝","宜","轻","宗","鹏","雪","秉","雨","宫","秋","秀","恩","客","宣","煜","鹿","恭","息","容","恰","鹤","科","棠","家","南","卓","隆","寂","博",
"梓","升","禾","千","十","禹","华","梅","思","寒","梁","卉","福","卷","印","怡","梵","卿","鸽","卸","梳","梭","梯","融","卦","鸣","梨","寺","梧","卫","烨","青","靖",
"威","娄","功","虹","努","烈","娱","懿","硕","加","务","虎","虔","硅","革","劲","励","炬","霖","炯","勉","炫","勋","霜","勇","霄","龙","炎","婷","研","勤","齐","列",
"慈","则","刚","创","初","慎","灿","蛋","别","利","音","韵","韶","磊","韬","制","韦","前","鼎","意","瀚","修","宵","晨","戏","施","顺","祥","才","聪","银","戈","喻","声","生","铁","如","宸","誓","胜","挚","靖","齐",
"锦","少","舟","任","载","翱","青","迁","钧","钟","金","慈","昌","紫","砂","仁","祖","韶","绍","锐","峻","裕","镇","壮","商",
"翼","织","释","诚","常","净","秀","节","刊","信","崇","春","铭","秋","刚","诗","神","星","鉴","石","识","肃","瑞","新","鑫",
"盛","帅","馨","惜","散","慎","世","书","千","善","镜","然","资","笑","疏","西","捷","超","川","锋","实","聚","尊","承","钦",
"仕","众","思","茂","贤","棕","树","蓝","卷","谷","君","古","原","廉","建","庆","桦","统","若","攀","栋","荒","何","久","侠",
"奇","朴","鸽","东","嘉","冠","松","啸","祺","琪","雁","宜","琦","枝","坚","昂","毅","歌","标","固","吉","高","康","尧","果",
"杭","语","曲","肖","荷","芹","乾","义","杰","皓","凯","狂","本","勤","彬","景","月","兼","顷","柏","擎","荣","观","笃","恭",
"柯","言","菲","萧","乔","群","谦","国","极","轻","玉","业","材","相","苑","倚","岳","柳","贵","悟","健","彦","棋","楷","桐",
"气","颜","苛","池","闻","流","霜","福","泉","宏","弘","浅","熙","济","涛","震","和","闲","霖","向","波","渊","博","游","雨",
"润","湛","凡","奔","夫","潮","深","岸","辉","浚","复","封","飞","朋","江","奉","晖","绘","浪","鸣","百","鹤","沙","漾","泥",
"雪","孝","万","望","瀚","缈","淡","阜","保","阔","洪","恒","云","伯","玄","风","淘","合","文","莫","享","满","溪","妙","邦",
"华","冰","方","寒","鹏","陌","奋","秉","泽","豪","布","明","民","虎","帆","洋","名","拂","海","潭","清","勉","源","平","物",
"沧","霄","熊","论","彤","烟","阳","耀","励","晋","临","伦","日","传","炎","彰","全","丰","晓","瞻","拓","展","绩","炫","尘",
"征","昙","道","飘","鼎","龙","昊","腾","至","宝","驰","易","耿","昆","振","知","光","灿","智","畅","晴","迪","绿","扬","来",
"志","煊","遥","宁","衷","太","凌","天","璋","瑾","俊","里","韬","量","致","烨","忠","厉","理","路","年","循","昭","达","都",
"蝶","章","照","积","良","泰","烈","庭","折","进","晟","德","际","琢","利","哲","质","隆","田","煜","南","乐","翎","冬","图",
"暖","壤","佑","翔","伟","磊","欧","运","豫","维","坤","恩","永","意","野","幽","远","圣","山","城","音","韵","依","余","圆",
"勋","忆","叶","亦","卫","傲","融","勇","逸","育","唯","基","容","温","安","奥","引","影","羽","均","誉","越","辰","轩","延",
"境","宇","悠","益","岩","玮","威","硕","庸","懿","统","柏","彤","兼","昊","肖","杰","含","凯","振","秉","沧","享","朋","轻",
"俊","材","宇","松","依","池","钦","桦","芹","孝","炫","极","洋","舟","际","荒","衷","亦","狂","闻","幽","曲","耿","勇","奇",
"城","冰","柯","浦","林","和","明","名","建","尧","胜","朴","存","顺","昌","西","昙","砂","语","泰","伦","烈","杭","育","折",
"达","顷","忠","延","坤","佑","修","闲","坚","泉","劲","勋","枝","年","迁","致","治","健","羽","晓","卷","如","宸","荷","物",
"合","复","晖","易","灿","浅","悟","壮","临","荣","桦","乔","承","明","顺","物","原","统","哲","庭","运","修","远","峰","兼",
"杉","莫","均","幽","高","闲","宝","拓","若","材","玮","余","苛","欢","凌","函","享","陌","亦","旷","全","君","思","秀","威",
"海","烨","尧","声","展","秋","标","羽","昭","合","建","坤","南","利","华","伦","挚","宵","壮","众","晋","松","恩","阳","泉",
"恭","树","钟","致","苑","封","诗","晓","戏","荣","里","拂","至","奋","初","图","烈","金","如","钦","俊","贵","宸","狂","益",
"耿","积","复","勋","佑","肃","光","轻","施","任"
};*/
String[] s = {"款","初","班","饭","期","分","大","附","北","站","左","屯","坊","巷","城","省","厂","四","乡","九","院","路","县","区","园","室","镇","面","桥","堍","层","内","幢","洲","州","厦","家","楼","南","侧","店","前","部","弄","旁","组","庄","浜","十","户","中","社","荡","八","市","队","六","栋","后","五","东","号","村","右","第","苑","三","西","小","座","环","寺","一","七","二","口","委","道", "F","~","!","@","#","¥","%","…","^","……","&","*","(",")","—","—","+","}","{",":","“","》","《","?","-","(",")"
};
// String[] s = {"中学","小学","学校","高中","大学","增补","个人","代发","电声","浙江","针织","童装","旅游","塑料","回收","宾馆","装饰","工资","技校","勘察","地质","保险","物业","安装","实验","纺织","景观","超市","宾馆","商城","电视","建设","宁夏","核算","汽车","流通","木业","餐饮","家私","农民","酒店","水果","化工","支行","银川","维修","交通","发展","银行","器材","市场","实业","机械","工贸","二手","批发","食堂","车行","集中","机电","宿舍","小额","大街","电器","制造","固原","工程","专业","幼儿","农场","集团","综合","社区","科技","瓜果","清真","码头","园区","休闲","粮油","商行","管理","股份","商业","文化","传播","中卫","广播","酒楼","单元","中心","印刷","开发","防水","吴忠","电子","资金","大修","责任","建材","幕墙","印务","医疗","嘉兴","农村","有限","物资","器械","珠宝","电力","资产","贷款","苗木","办公","服装","服务","花园","村级","种植","公司","行政","咨询","养殖","保洁","小区","设备","天窗","街道","园林","公路","节能","销售","贸易","商贸","连锁","胶粘","制品","路桥","矿业","南寺","工业","陶瓷","农业","果蔬",
//
// };
// String[] s = {"经营部","农资店","青铜峡","自治县","内蒙古","石嘴山","加盟店","蒙古族","土特产","副食品","合作社","清真寺","互助社","竹纤维","批发部","经销部","电动车"};
//
/*
浙江
学
*/
Set se = new HashSet();
for (String str: s) {
se.add(str);
}
Iterator it = se.iterator();
while (it.hasNext()){
System.out.print("\""+it.next()+"\",");
}
// Object m = Address3.getM("中山东路县南街46号三楼",145);
// System.out.println(m);
}
}
<file_sep>package huanghe.address;
import com.sun.corba.se.spi.ior.TaggedProfileTemplate;
//import java.util.HashMap;
import java.util.LinkedHashMap;
/**
* Created by ${LiuShuo} on 2016/6/22.
*/
public class Address {
public static Object getM(Object value, Object key){
//判断参数是否为null、"null"、"" ,为true时不做处理
if (value==null||value.equals("null")||value.equals("")) return value;
String str = value+"";
//去掉前后空格长度小于等于1的直接返回
if (str.trim().length()<2) return value;
String salt = key + "";
String saltok = salt.replace(" ", "");
//盐值hash
int hashSalt = 0;
str = str.replace(" ", "");
if (salt.length()<1){
//没有盐值
}else {
hashSalt=Math.abs(saltok.hashCode());
}
//正则数字
java.util.regex.Pattern pattern1 = java.util.regex.Pattern.compile("[0-9]");
//村区
String[] randomName= {"修","宵","晨","戏","施","顺","祥","才","聪","银","戈","喻","声","生","铁","如","宸","誓","胜","挚","靖","齐",
"锦","少","舟","任","载","翱","青","迁","钧","钟","金","慈","昌","紫","砂","仁","祖","韶","绍","锐","峻","裕","镇","壮","商",
"翼","织","释","诚","常","净","秀","节","刊","信","崇","春","铭","秋","刚","诗","神","星","鉴","石","识","肃","瑞","新","鑫",
"盛","帅","馨","惜","散","慎","世","书","千","善","镜","然","资","笑","疏","西","捷","超","川","锋","实","聚","尊","承","钦",
"仕","众","思","茂","贤","棕","树","蓝","卷","谷","君","古","原","廉","建","庆","桦","统","若","攀","栋","荒","何","久","侠",
"奇","朴","鸽","东","嘉","冠","松","啸","祺","琪","雁","宜","琦","枝","坚","昂","毅","歌","标","固","吉","高","康","尧","果",
"杭","语","曲","肖","荷","芹","乾","义","杰","皓","凯","狂","本","勤","彬","景","月","兼","顷","柏","擎","荣","观","笃","恭",
"柯","言","菲","萧","乔","群","谦","国","极","轻","玉","业","材","相","苑","倚","岳","柳","贵","悟","健","彦","棋","楷","桐",
"气","颜","苛","池","闻","流","霜","福","泉","宏","弘","浅","熙","济","涛","震","和","闲","霖","向","波","渊","博","游","雨",
"润","湛","凡","奔","夫","潮","深","岸","辉","浚","复","封","飞","朋","江","奉","晖","绘","浪","鸣","百","鹤","沙","漾","泥",
"雪","孝","万","望","瀚","缈","淡","阜","保","阔","洪","恒","云","伯","玄","风","淘","合","文","莫","享","满","溪","妙","邦",
"华","冰","方","寒","鹏","陌","奋","秉","泽","豪","布","明","民","虎","帆","洋","名","拂","海","潭","清","勉","源","平","物",
"沧","霄","熊","论","彤","烟","阳","耀","励","晋","临","伦","日","传","炎","彰","全","丰","晓","瞻","拓","展","绩","炫","尘",
"征","昙","道","飘","鼎","龙","昊","腾","至","宝","驰","易","耿","昆","振","知","光","灿","智","畅","晴","迪","绿","扬","来",
"志","煊","遥","宁","衷","太","凌","天","璋","瑾","俊","里","韬","量","致","烨","忠","厉","理","路","年","循","昭","达","都",
"蝶","章","照","积","良","泰","烈","庭","折","进","晟","德","际","琢","利","哲","质","隆","田","煜","南","乐","翎","冬","图",
"暖","壤","佑","翔","伟","磊","欧","运","豫","维","坤","恩","永","意","野","幽","远","圣","山","城","音","韵","依","余","圆",
"勋","忆","叶","亦","卫","傲","融","勇","逸","育","唯","基","容","温","安","奥","引","影","羽","均","誉","越","辰","轩","延",
"境","宇","悠","益","岩","玮","威","硕","庸","懿","统","柏","彤","兼","昊","肖","杰","含","凯","振","秉","沧","享","朋","轻",
"俊","材","宇","松","依","池","钦","桦","芹","孝","炫","极","洋","舟","际","荒","衷","亦","狂","闻","幽","曲","耿","勇","奇",
"城","冰","柯","浦","林","和","明","名","建","尧","胜","朴","存","顺","昌","西","昙","砂","语","泰","伦","烈","杭","育","折",
"达","顷","忠","延","坤","佑","修","闲","坚","泉","劲","勋","枝","年","迁","致","治","健","羽","晓","卷","如","宸","荷","物",
"合","复","晖","易","灿","浅","悟","壮","临","荣","桦","乔","承","明","顺","物","原","统","哲","庭","运","修","远","峰","兼",
"杉","莫","均","幽","高","闲","宝","拓","若","材","玮","余","苛","欢","凌","函","享","陌","亦","旷","全","君","思","秀","威",
"海","烨","尧","声","展","秋","标","羽","昭","合","建","坤","南","利","华","伦","挚","宵","壮","众","晋","松","恩","阳","泉",
"恭","树","钟","致","苑","封","诗","晓","戏","荣","里","拂","至","奋","初","图","烈","金","如","钦","俊","贵","宸","狂","益",
"耿","积","复","勋","佑","肃","光","轻","施","任","巧","功","玄","白","田","由","甲","申","用","目","旦","玉","丘","生","主","加","占","可","兄","石","只","叭","弘","台","叮",
"包","卉","叫","另","古","尼","召","巨","司","句","幼","禾","札","本","丙","戊","布","卯","未","末","必","平","市","冬","孕","永","立",
"以","央","出","北","甘","凹","凸","刊","扎","母","瓜","正","奴","奶","它","外","瓦","充","示","卡","去","失","斥","丕","乏","半","皮",
"六","光","先","圭","戌","艮","羊","地","至","向","各","吉","名","后","舌","合","回","同","咤","臣","吋","吊","考","多","仲","伉","来",
"企","伊","全","伍","仰","任","伙","休","价","伏","份","在","行","汀","州","丞","年","存","舟","兆","寺","竹","卉","圳","朱","朴","米",
"朽","打","汁","次","冰","交","件","列","匠","宅","尖","老","宇","守","安","字","如","妄","亦","聿","因","夷","有","衣","羽","而","危",
"耳","印","西","先","旭","早","百","自","旨","曲","收","乒","乓","色","此","虫","肉","妃","好","帆","亥","充","再","共","住","佃","但",
"你","伴","佛","布","伶","夹","利","佣","余","位","伸","宋","似","作","坐","彷","畲","七","妏","妥","妞","努","妆","妘","妤","汝","妍",
"妙","妨","妣","克","谷","告","估","君","吕","兑","束","局","托","豆","足","占","言","佑","佐","吴","吾","呈","杏","串","吹","吟","冶",
"吸","吵","亨","伯","伺","何","含","别","刨","吧","灶","杜","町","牡","圾","赤","走","成","劫","坍","弄","坊","更","男","良","里","均",
"壮","辰","坎","床","杆","杖","李","孚","孝","材","村","杉","杞","秀","池","汐","汕","汗","廷","江","忍","忘","志","删","形","址","见",
"免","车","屁","身","甫","贝","旱","步","判","私","角","改","攻","即","弟","系","忙","兵","冷","宏","完","我","希","序","酉","辛","助",
"彤","夆","八","佶","供","佰","仑","佬","佛","岱","佩","夜","欣","例","来","侏","佳","征","依","彼","侑","并","往","府","侍","使","姑",
"姗","姒","妾","妻","始","妹","姓","妮","委","姐","姊","姆","妳","舍","和","咆","呼","咐","命","咒","或","咖","刮","咕","固","岩","冾",
"奇","知","居","林","周","店","味","京","尚","享","昔","卓","明","朋","昏","昊","服","昆","的","帛","昌","坦","昂","旺","者","易","升",
"昕","松","析","杵","虎","枋","杷","枇","杯","板","林","采","果","兔","枕","柑","杭","枚","东","析","采","青","炒","炊","快","忱","忽",
"忠","念","忭","忿","杰","炎","定","宙","空","宕","穹","官","宗","宜","宛","雨","沈","沙","沁","冲","沌","汲","沐","承","汽","乳","沛",
"函","没","汾","汴","汪","沅","沃","汶","沂","季","孟","坪","物","卦","坤","幸","社","到","坡","坻","硅","坨","岳","岸","玖","抖","扶",
"把","批","扳","扮","扭","抑","抗","狂","乖","沉","孤","盂","氓","氛","爸","版","牧","盲","门","非","庚","冈","奉","争","决","扺","弦",
"艾","武","协","所","抄","投","抓","抒","折","事","些","卷","劻","届","底","忝","状","竺","垧","亚","券","刷","刺","卒","卸","取","叔",
"受","并","奔","劾","卑","其","儿","狄","典","直","延","于","卧","具","金","长","奈","两","刻","找","制","祀","祁","秉","弧","房","放",
"斧","爬","九","勇","面","冠","军","厚","罕","俊","很","俐","侵","促","俗","系","待","信","衍","便","俘","俄","俏","律","后","侯","保",
"亭","俬","徊","韦","侣","室","客","穿","姨","姻","娃","姜","姝","姚","咪","计","咳","哄","哈","订","却","咨","讣","哉","咱","咻","品",
"亮","宦","科","秒","柄","柳","柏","枷","拐","柔","香","柿","染","柱","架","查","柯","柚","某","枯","柑","柒","皇","冒","昴","昧","昱",
"音","映","宣","星","春","肖","削","前","皆","是","昨","肝","怪","性","思","怙","急","怡","怕","炫","南","炯","炬","炭","炳","怎","炮",
"政","耐","泌","况","沸","癸","泡","沫","沽","泯","泳","油","沿","泉","泣","泄","泗","河","波","法","泓","泛","治","泊","注","泥","沾",
"沼","垮","型","垂","奎","封","重","致","垣","拆","拐","狗","剎","页","克","垮","拌","拂","抹","叛","披","拔","抛","拓","招","拇","拍",
"抱","拉","拄","拒","抽","抵","拘","押","拖","抬","芊","芃","芍","芒","玟","玫","珏","玩","毒","屋","幽","禺","竽","耶","食","昶","姿",
"咸","省","则","相","秋","怯","砍","契","奏","巷","甚","孩","衫","酋","剉","屎","故","泵","牯","皈","杯","看","竿","轨","泰","度","拓",
"劲","红","表","美","屏","虹","勉","勃","为","弈","狐","盆","革","扁","奕","叛","拜","建","帅","负","赴","砒","帝","界","段","研","纪",
"既","肚","狙","剌","彦","盈","禹","约","威","羿","施","俞","眉","首","盼","贞","风","奂","飞","竑","爰","十","厝","原","冤","冥","冢",
"准","凌","凄","座","俱","值","倪","伦","倘","倞","俩","修","倡","倩","倦","徐","径","借","倒","俶","倔","们","俾","徒","俺","倭","倚",
"个","幸","候","倍","俸","俯","剖","剥","刚","祟","留","峪","峮","城","岛","埔","埋","高","哥","记","唇","炮","唔","哭","哽","唐","讯",
"哲","讨","托","站","讪","讫","哨","训","员","讦","仓","哦","唈","哺","讧","宫","窈","家","案","窄","容","宬","宸","宴","宰","宵","害",
"贡","娱","娜","姬","娘","娓","娥","娩","娣","娌","娉","娟","拾","拭","持","按","拱","拷","拮","括","挖","拿","挑","指","拯","按","耘",
"桂","秧","栩","耕","桉","秘","租","粉","根","框","桌","栘","桑","格","桃","株","秤","秩","梳","冻","校","柴","栽","栓","料","殊","耗",
"桔","栗","桐","秦","核","洋","洹","洸","恭","洗","洛","洪","洲","流","津","酒","洞","庭","孙","洽","汹","洵","洳","泄","娑","活","派",
"洧","恒","耿","烙","恒","恐","烤","恬","烈","晋","晃","烔","肱","恃","息","耻","烘","恰","恕","恢","恩","恤","羔","书","肩","肴","朕",
"肥","时","肯","殉","骨","股","屑","朔","肢","剔","晁","育","晏","殷","桓","晌","峻","埂","城","峭","峨","峰","峡","崁","芹","芬","芮",
"芙","芭","芝","芛","芳","芽","芯","芸","花","芥","芫","芷","纹","纱","级","纯","索","紊","纺","纽","纷","纳","纸","秘","神","祠","祖",
"佑","祝","珈","珀","珊","珍","玻","玳","玲","珅","差","弱","拳","砸","臭","刍","虔","蚤","衰","航","破","配","般","亳","病","马","匪",
"狠","圃","亩","疲","笆","蚌","迅","躬","库","辱","鬼","特","展","砥","兼","钉","针","耽","只","斗","疼","翁","袁","迂","射","氧","爹",
"豹","豺","釜","狩","奚","真","蚓","夏","益","轩","旅","财","素","扇","乘","气","畜","笑","缺","翅","效","起","巡","席","卿","师","套",
"奘","疾","症","疹","矩","砧","蚪","衷","闪","旁","停","假","侦","偃","偌","伟","御","悠","偲","术","偶","健","偕","得","爽","偎","伪",
"修","徘","徙","徜","做","从","侧","偏","康","庸","庾","庶","痕","匾","匿","屠","痔","麻","庹","庵","疵","剪","勒","动","执","斩","副",
"软","务","野","邪","阡","邠","邦","那","浩","教","浪","涒","浙","涓","浚","浸","海","涕","泾","浣","涅","浦","消","浦","雪","浴","浮",
"昆","密","崩","毕","岗","堆","培","埤","基","堂","笛","仑","羚","坚","略","堉","域","崖","崇","埴","崎","崧","崔","梓","梗","舺","梁",
"粒","救","梯","桶","条","梨","梵","梆","斜","梧","敕","梢","械","梭","枭","杀","彪","弃","犁","杆","移","彬","梅","粗","彩","挺","捆",
"捏","振","捉","挪","挽","挨","挟","挫","捐","捕","捍","捌","晢","够","胖","干","恿","勖","章","顶","专","将","竟","您","胄","鸟","胎",
"悌","昼","皎","烹","眺","袒","豚","曼","尉","望","鱼","悁","胤","焉","晚","晤","悟","焊","胃","习","晟","患","晨","胥","冕","晦","曹",
"悉","悚","敏","胞","悍","胚","悖","奢","蚵","啪","啃","啦","国","甜","念","啄","朱","袈","诀","区","欲","哑","啊","问","唯","讶","讹",
"启","毫","设","常","商","船","许","唱","售","圈","讼","孰","盒","啤","唬","访","啡","婕","娄","婪","婀","娶","娼","婚","婢","婊","婉",
"妇","婆","珠","珞","佩","珙","珪","琉","敖","珣","晌","班","寄","寇","窒","窕","寀","寂","宿","寅","扎","累","终","统","绊","绍","组",
"细","绅","茁","笠","英","苑","茄","若","范","茉","茂","笨","苓","苕","苙","苞","茅","苗","苦","苹","苾","苟","荏","苔","笙","符","祥",
"强","旋","雀","处","顷","产","族","袖","牵","率","瓷","蛇","疏","参","巢","狭","匙","戚","羞","舷","蛆","蚯","赦","酗","袪","麦","凰",
"闭","觅","货","被","票","败","悔","背","瓶","瓠","舶","袍","馗","勘","钵","釱","钓","钏","钗","翎","张","蛋","袋","鹿","第","贪","伧",
"傒","徨","备","博","街","傅","傍","贷","家","循","婿","婼","媒","婷","媚","媞","媛","堪","凯","岚","崴","尧","场","堡","嵋","诊","啼",
"喃","喻","喊","喝","喉","证","距","注","喜","善","喨","舒","创","诉","词","残","单","喘","丧","诅","唤","彭","跑","喧","评","诃","结",
"喇","就","诈","跌","邵","掌","措","扫","探","挣","掮","接","掉","捱","掩","掏","授","卷","采","捧","扪","掰","排","舍","掀","挂","捷",
"棕","棵","棍","棺","植","杰","棠","栋","集","栈","椒","椅","巽","稍","程","稀","窗","棘","栖"};
//省
String[] provinces = {"吉林","广东","山东","河南","河北","四川"};
//------------------------------------------------------------------------------------------
//直辖市
// String[] arrZhiXiaShi = {"北京","上海","天津"};
//省下面的市
String[] jilin ={"吉林市","长春市","白山市","延边州","白城市","松原市","辽源市","通化市","四平市"};
String[] guangdong ={"东莞市","广州市","深圳市","惠州市","江门市","珠海市","汕头市","佛山市","湛江市","河源市","肇庆市","清远市","潮州市","韶关市","揭阳市","阳江市","梅州市","云浮市","茂名市","汕尾市"};
String[] shandong ={"济南市","青岛市","临沂市","济宁市","菏泽市","烟台市","淄博市","泰安市","潍坊市","日照市","威海市","滨州市","东营市","聊城市","德州市","莱芜市","枣庄市"};
String[] henan ={"郑州市","南阳市","新乡市","安阳市","洛阳市","信阳市","平顶山市","周口市","商丘市","开封市","焦作市","驻马店市","濮阳市","三门峡市","漯河市","许昌市","鹤壁市"};
String[] hebei ={"石家庄市","唐山市","保定市","邯郸市","邢台市","沧州市","秦皇岛市","张家口市","衡水市","廊坊市","承德市"};
String[] sichuan ={"成都市","绵阳市","广元市","达州市","南充市","德阳市","广安市","阿坝州","巴中市","遂宁市","内江市","凉山州","攀枝花市","乐山市","自贡市","泸州市","雅安市","宜宾市","资阳市","眉山市","甘孜州"};
//没用上
String[][] shi = {jilin,guangdong,shandong,henan,hebei,sichuan};
//市下面的区和县
//吉林
String[] beijing ={"朝阳区","海淀区","通州区","房山区","丰台区","昌平区","大兴区","顺义区","西城区","延庆县","石景山区","宣武区","怀柔区","崇文区","密云县","东城区","平谷区","门头沟区"};
String[] changchun ={"南关区","宽城区","朝阳区","二道区","绿园区","双阳区","九台区","榆树市","德惠市","农安县"};
String[] jilins ={"船营区","龙潭区","昌邑区","丰满区","永吉县","磐石市","桦甸市","蛟河市","舒兰市"};
String[] baishan ={"长白朝鲜族自治县","抚松县","靖宇县","临江市","浑江区"};
String[] yanbian ={"延吉市","图们市","龙井市","和龙市","汪清县","安图县"};
String[] baicheng ={"大安市","洮北区","洮南区","通榆县","镇赉县"};
String[] songyuan ={"扶余县","宁江区","前郭尔罗斯蒙古族自治县","乾安县","长岭县"};
String[] liaoyuan ={"龙山区","西安区","东丰县","东辽县"};
String[] tonghua ={"东昌区","二道江区","通化县","柳河县","辉南县"};
String[] siping ={"铁西区","铁东区","双辽市","梨树县","伊通满族自治县","公主岭市"};
//广东
String[] dongguan ={"莞城区","东城区","南城区","万江区"};
String[] guangzhou ={"越秀区","荔湾区","海珠区","天河区","白云区","黄埔区","萝岗区","番禺区","花都区","南沙区","萝岗区","增城市","从化市"};
String[] shenzhen ={"宝安区","福田区","龙岗区","罗湖区","南山区","盐田区"};
String[] huizhou ={"惠城区","惠阳区","惠东县","博罗县","龙门县"};
String[] jiangmen ={"蓬江区","江海区","新会区","台山市","开平市","鹤山市","恩平市"};
String[] zhuahi ={"斗门区","金湾区","香洲区"};
String[] shantou ={"金平区","龙湖区","澄海区","濠江区","潮南区","潮阳区","南澳县"};
String[] foshan ={"禅城区","南海区","顺德区","高明区","三水区"};
String[] zhanjiang ={"赤坎区","雷州市","廉江市","麻章区","坡头区","遂溪县","吴川市","霞山区","徐闻县"};
String[] heyuan ={"源城区","和平县","龙川县","东源县","紫金县","连平县"};
String[] zhaoqing ={"端州区","鼎湖区","高要区","广宁县","怀集县","封开县","德庆县","四会区"};
String[] qingyuan ={"清城区","清新区","佛冈县","阳山县","连南瑶族自治县","连山壮族瑶族自治县","英德市","连州市"};
String[] chaozhou ={"湘桥区","潮安区","枫溪区","饶平县"};
String[] meizhou ={"兴宁市","梅江区","梅县区","大埔县","丰顺县","五华县","平远县","蕉岭县"};
String[] shaoguan ={"浈江区","武江区","曲江区","乐昌市","南雄市","始兴县","仁化县","翁源县","新丰县","乳源瑶族自治县"};
String[] jieyang ={"榕城区","揭东区","揭西县","惠来县","普宁市"};
String[] yangjiang ={"江城区","阳东区","阳西县","阳春市"};
String[] yunfu ={"云城区","罗定市","云安区","新兴县","郁南县"};
String[] maoming ={"茂南区","电白区","高州市","化州市","信宜市"};
String[] shanwei ={"城区","陆丰市","海丰县","陆河县"};
//山东
String[] jinan ={"历下区","市中区","槐荫区","天桥区","历城区","长清区","平阴县","济阳县","商河县","章丘市"};
String[] qingdao ={"市南区","市北区","黄岛区","崂山区","李沧区","胶州市","即墨市","平度市","莱西市"};
String[] liyi ={"兰山区","罗庄区","河东区","郯城县","兰陵县","莒南县","沂水县","蒙阴县","平邑县","费县","沂南县","临沭县"};
String[] jining ={"任城区","兖州区","微山县","鱼台县","金乡县","嘉祥县","汶上县","泗水县","梁山县"};
String[] heze ={"牡丹区","开发区","定陶区","巨野县","曹县","成武县","单县","郓城县","鄄城县","东明县"};
String[] yantai ={"烟台高新技术产业开发区","烟台经济技术开发区","芝罘区","福山区","牟平区","莱山区","长岛县","龙口市","莱阳市","莱州市","蓬莱市","招远市","栖霞市","海阳市"};
String[] zibo ={"张店区","淄川区","博山区","周村区","临淄区","桓台县","高青县","沂源县"};
String[] taian ={"泰山区","岱岳区","新泰市","肥城市","宁阳县","东平县"};
String[] weifang ={"潍城区","奎文区","坊子区","寒亭区","青州市","诸城市","寿光市","安丘市","高密市","昌邑市","昌乐县","临朐县"};
String[] rizhao ={"东港区","岚山区","莒县","五莲县","日照经济技术开发区","山海天旅游度假区","日照高新技术产业开发区","日照国际海洋城"};
String[] weihai ={"地级威海市包括环翠区","文登区","经济技术开发区","火炬高技术产业开发区","进出口加工保税区","临港经济技术开发区","南海新区","荣成市","乳山市"};
String[] bingzhou ={"滨城区","沾化区","邹平县","博兴县","惠民县","阳信县","无棣县"};
String[] dongying ={"东营区","河口区","广饶县","垦利县","利津县"};
String[] liaocheng ={"东昌府区","开发区","临清市","茌平","东阿","高唐","阳谷","冠县","莘县","莱州市","蓬莱市","招远市","栖霞市","海阳市"};
String[] dezhou ={"德州市辖德城区","陵城区","禹城市","乐陵市","临邑县","平原县","夏津县","武城县","庆云县","宁津县","齐河县"};
String[] laiwu ={"莱城区","钢城区"};
String[] zaozhuang ={"薛城区","市中区","峄城区","山亭区","台儿庄区","滕州市"};
//河南
String[] zhengzhou ={"中原区","二七区","管城回族区","金水区","上街区","惠济区","中牟县","巩义市","荥阳市","新密市","新郑市","登封市"};
String[] nanyang ={"宛城区","卧龙区","南召县","镇平县","内乡县","淅川县","新野县","唐河县","桐柏县","方城县","西峡县","社旗县"};
String[] xinxiang ={"平原示范区","卫滨区","红旗区","凤泉区","牧野区","卫辉市","辉县市","新乡县","获嘉县","原阳县","延津县","封丘县"};
String[] anyang ={"文峰区","北关区","殷都区","龙安区","安阳县","汤阴县","内黄县","林州市"};
String[] luoyang ={"涧西区","西工区","老城区","瀍河回族区","洛龙区","吉利区","偃师市","孟津县","新安县","宜阳县","伊川县","洛宁县","嵩县","栾川县","汝阳县"};
String[] xinyang ={"浉河区","平桥区","息县","新县","罗山县","潢川县","光山县","商城县","固始县","淮滨县"};
String[] pingdingshan ={"辖新华区","卫东区","湛河区","石龙区","舞钢市","叶县","鲁山","宝丰","郏县"};
String[] zhoukou ={"川汇区","扶沟县","西华县","商水县","沈丘县","郸城县","淮阳县","太康县","鹿邑县","项城市"};
String[] shangqiu ={"永城市","睢阳区","梁园区","商丘新区","虞城县","柘城县","夏邑县","民权县","睢县","宁陵县"};
String[] kaifeng ={"鼓楼区","龙亭区","禹王台区","顺河回族区","祥符区和尉氏县","兰考县","杞县","通许县"};
String[] jiaozuo ={"解放区","中站区","马村区","山阳区","修武县","博爱县","武陟县","温县","沁阳市","孟州市"};
String[] zhumadian ={"驿城区","确山县","泌阳县","遂平县","西平县","上蔡县","汝南县","平舆县","正阳县","经济开发区","工业集聚区","装备产业集聚区"};
String[] puyang ={"华龙区","开发区","濮阳县","清丰县","南乐县","范县","台前县"};
String[] sanxiamen ={"湖滨区","渑池县","陕州区","卢氏县","义马市","灵宝市"};
String[] luohe ={"临颍县","舞阳县","郾城区","源汇区","召陵区"};
String[] xuchang ={"魏都区","许昌县","鄢陵县","襄城县","禹州市","长葛市"};
String[] hebi ={"淇滨区","山城区","鹤山区","淇县","浚县"};
//河北
String[] shijiazhuang ={"新华区","桥西区","长安区","裕华区","矿区","藁城区","鹿泉区","栾城区","辛集市","晋州市","新乐市","正定县","深泽县","无极县","赵县","高邑县","元氏县","赞皇县","井陉县","平山县","灵寿县","行唐县"};
String[] tangshan ={"路南区","路北区","古冶区","开平区","丰南区","丰润区","曹妃甸区","滦县","滦南县","乐亭县","迁西县","玉田县","遵化市","迁安市"};
String[] baoding ={"定州市","竞秀区","莲池区","满城区","清苑区","徐水区","高碑店市","安国市","涞水县","唐县","易县","涞源县","定兴县","顺平县","望都县","高阳县","安新县","雄县","容城县","曲阳县","阜平县","博野县","蠡县"};
String[] handan ={"邯山区","丛台区","复兴区","峰峰矿区","邯郸县","临漳县","成安县","大名县","涉县","磁县","肥乡县","永年县","邱县","鸡泽县","广平县","馆陶县","魏县","曲周县","武安市"};
String[] xingtai ={"桥东区","桥西区","南宫市","沙河市","邢台县","柏乡县","柏乡县","宁晋县","隆尧县","临城县","广宗县","临西县","内丘县","平乡县","巨鹿县","新河县","南和县"};
String[] cangzhou ={"运河区","新华区","泊头市","任丘市","黄骅市","河间市","沧县","青县","东光县","海兴县","盐山县","肃宁县","南皮县","吴桥县","献县","孟村回族自治县"};
String[] qinhuangdao ={"海港区","山海关区","抚宁区","北戴河区","青龙县","昌黎县","卢龙县"};
String[] zhangjiakou ={"桥西区","桥东区","下花园区","宣化区","万全区","崇礼区","张北县","康保县","沽源县","尚义县","蔚县","阳原县","怀安县","怀来县","涿鹿县","赤城县"};
String[] hengshui ={"桃城区","滨湖新区","工业新区","冀州","深州","枣强县","武邑县","武强县","饶阳县","安平县","故城县","阜城县","景县"};
String[] langfang ={"三河市","霸州市","香河县","固安县","永清县","文安县","大城县","大厂回族自治县"};
String[] chengde ={"承德县","隆化县","围场县","丰宁县","滦平县","兴隆县","青龙县","平泉县"};
//四川
String[] chengdu ={"武侯区","锦江区","青羊区","金牛区","成华区","龙泉驿区","温江区","新都区","青白江区","双流区","郫县","蒲江县","大邑县","金堂县","新津县","都江堰市","彭州市","邛崃市","崇州市","简阳市"};
String[] mianyang ={"涪城区","游仙区","安州区","三台县","盐亭县","梓潼县","平武县","北川羌族自治县","江油市"};
String[] guangyuan ={"利州区","昭化区","朝天区","旺苍县","青川县","剑阁县","苍溪县"};
String[] dazhou ={"通川区","达川区","宣汉县","开江县","大竹县","渠县","万源市"};
String[] nanyun ={"顺庆区","高坪区","嘉陵区","西充县","南部县","蓬安县","营山县","仪陇县","阆中市"};
String[] deyang ={"旌阳区","什邡市","广汉市","绵竹市","罗江县","中江县"};
String[] guangan ={"广安区","前锋区","岳池县","武胜县","邻水县","华蓥市"};
String[] aba ={"马尔康市","九寨沟县","小金县","阿坝县","若尔盖县","红原县","壤塘县","汶川县","理县","茂县","松潘县","金川县","黑水县"};
String[] bazhong ={"巴州区","恩阳区","通江县","南江县","平昌县"};
String[] suining ={"船山区","安居区","射洪县","蓬溪县","大英县"};
String[] neijiang ={"市中区","东兴区","资中县","威远县","隆昌县"};
String[] liangshan ={"西昌市","盐源县","德昌县","会理县","会东县","宁南县","普格县","布拖县","金阳县","昭觉县","喜德县","冕宁县","越西县","甘洛县","美姑县","雷波县","木里藏族自治县"};
String[] panzhihua ={"东区","西区","仁和区","米易县","盐边县"};
String[] zigong ={"自流井区","贡井区","大安区","沿滩区","荣县","富顺县"};
String[] luzhou ={"江阳区","龙马潭区","纳溪区","纳溪区","泸县","合江县","叙永县","古蔺县"};
String[] yaan ={"雨城区","名山区","县荥经县","汉源县","石棉县","天全县","芦山县","宝兴县"};;
String[] yibin ={"翠屏区","南溪区","宜宾县","江安县","长宁县","高县","筠连县","珙县","兴文县","屏山县"};
String[] ziyang ={"雁江区","安岳县","乐至县"};
String[] meishan ={"东坡区","彭山区","仁寿县","丹棱县","青神县","洪雅县"};
String[] ganzi ={"康定市","泸定县","丹巴县","九龙县","雅江县","道孚县","炉霍县","甘孜县","新龙县","德格县","白玉县","石渠县","色达县","理塘县","巴塘县","乡城县","稻城县","得荣县"};
java.util.HashMap<String,String[]> shengTOshi = new java.util.HashMap<>();
shengTOshi.put("吉林",jilin);
shengTOshi.put("广东",guangdong);
shengTOshi.put("山东",shandong);
shengTOshi.put("河南",henan);
shengTOshi.put("河北",hebei);
shengTOshi.put("四川",sichuan);
// HashMap<String,String[]> zhiXiaShi = new HashMap<>();
// zhiXiaShi.put("北京",beijing);
java.util.HashMap<String,String[]> shiTOqu = new java.util.HashMap<>();
shiTOqu.put("北京",beijing);
//吉林
shiTOqu.put("吉林市",jilins);
shiTOqu.put("长春市",changchun);
shiTOqu.put("白山市",baishan);
shiTOqu.put("延边州",yanbian);
shiTOqu.put("白城市",baicheng);
shiTOqu.put("松原市",songyuan);
shiTOqu.put("辽源市",liaoyuan);
shiTOqu.put("通化市",tonghua);
shiTOqu.put("四平市",siping);
//广东
shiTOqu.put("东莞市",dongguan);
shiTOqu.put("广州市",guangzhou);
shiTOqu.put("深圳市",shenzhen);
shiTOqu.put("惠州市",huizhou);
shiTOqu.put("江门市",jiangmen);
shiTOqu.put("珠海市",zhuahi);
shiTOqu.put("汕头市",shantou);
shiTOqu.put("佛山市",foshan);
shiTOqu.put("湛江市",zhanjiang);
shiTOqu.put("河源市",heyuan);
shiTOqu.put("肇庆市",zhaoqing);
shiTOqu.put("清远市",qingyuan);
shiTOqu.put("潮州市",chaozhou);
shiTOqu.put("梅州市",meizhou);
shiTOqu.put("韶关市",shaoguan);
shiTOqu.put("揭阳市",jieyang);
shiTOqu.put("阳江市",yangjiang);
shiTOqu.put("云浮市",yunfu);
shiTOqu.put("茂名市",maoming);
shiTOqu.put("汕尾市",shanwei);
//山东
shiTOqu.put("济南市",jinan);
shiTOqu.put("青岛市",qingdao);
shiTOqu.put("临沂市",liyi);
shiTOqu.put("济宁市",jining);
shiTOqu.put("菏泽市",heze);
shiTOqu.put("烟台市",yantai);
shiTOqu.put("淄博市",zibo);
shiTOqu.put("泰安市",taian);
shiTOqu.put("潍坊市",weifang);
shiTOqu.put("日照市",rizhao);
shiTOqu.put("威海市",weihai);
shiTOqu.put("滨州市",bingzhou);
shiTOqu.put("东营市",dongying);
shiTOqu.put("聊城市",liaocheng);
shiTOqu.put("德州市",dezhou);
shiTOqu.put("莱芜市",laiwu);
shiTOqu.put("枣庄市",zaozhuang);
//河南
shiTOqu.put("郑州市",zhengzhou);
shiTOqu.put("南阳市",nanyang);
shiTOqu.put("新乡市",xinxiang);
shiTOqu.put("安阳市",anyang);
shiTOqu.put("洛阳市",luoyang);
shiTOqu.put("信阳市",xinyang);
shiTOqu.put("平顶山市",pingdingshan);
shiTOqu.put("周口市",zhoukou);
shiTOqu.put("商丘市",shangqiu);
shiTOqu.put("开封市",kaifeng);
shiTOqu.put("焦作市",jiaozuo);
shiTOqu.put("驻马店市",zhumadian);
shiTOqu.put("濮阳市",puyang);
shiTOqu.put("三门峡市",sanxiamen);
shiTOqu.put("漯河市",luohe);
shiTOqu.put("许昌市",xuchang);
shiTOqu.put("鹤壁市",hebi);
//河北
shiTOqu.put("石家庄市",shijiazhuang );
shiTOqu.put("唐山市",tangshan);
shiTOqu.put("保定市",baoding);
shiTOqu.put("邯郸市",handan);
shiTOqu.put("邢台市",xingtai);
shiTOqu.put("沧州市",cangzhou);
shiTOqu.put("秦皇岛市",qinhuangdao);
shiTOqu.put("张家口市",zhangjiakou);
shiTOqu.put("衡水市",hengshui);
shiTOqu.put("廊坊市",langfang);
shiTOqu.put("承德市",chengde);
//四川
shiTOqu.put("成都市",chengdu);
shiTOqu.put("绵阳市",mianyang);
shiTOqu.put("广元市",guangyuan);
shiTOqu.put("达州市",dazhou);
shiTOqu.put("南充市",nanyun);
shiTOqu.put("德阳市",deyang);
shiTOqu.put("广安市",guangan);
shiTOqu.put("阿坝州",aba);
shiTOqu.put("巴中市",bazhong);
shiTOqu.put("遂宁市",suining);
shiTOqu.put("内江市",neijiang);
shiTOqu.put("凉山州",liangshan);
shiTOqu.put("攀枝花市",panzhihua);
shiTOqu.put("自贡市",zigong);
shiTOqu.put("泸州市",luzhou);
shiTOqu.put("雅安市",yaan);
shiTOqu.put("宜宾市",yibin);
shiTOqu.put("资阳市",ziyang);
shiTOqu.put("眉山市",meishan);
shiTOqu.put("甘孜州",ganzi);
String newStrSheng="";
String newStrShi="";
String newStrXian="";
String newStrQu="";
String newCun = "";
//默认hash是盐
int hash1 = hashSalt;
//type= :1 只有省没有市 2 有省有市 3 没省有市
int type = 0;
//获取省
if (str.contains("省")) {
String[] arrStr1 = str.split("省");
if (arrStr1.length < 2) return value;
hash1 = Math.abs(arrStr1[0].hashCode() + hashSalt);
newStrSheng = provinces[hash1 % (provinces.length - 1)];
str = arrStr1[1];
type = 1;
}
//获取市
if (str.contains("市")) {
String[] arrStr1 = str.split("市");
if (arrStr1.length < 2) return value;
hash1 = Math.abs(arrStr1[0].hashCode() + hashSalt);
if (type == 1) {
newStrShi = shengTOshi.get(newStrSheng)[hash1 % (shengTOshi.get(newStrSheng).length - 1)];
type = 2;
}else {
String[] arryTemp = shi[hash1 % (shi.length - 1)];
newStrShi =arryTemp[hash1 % (arryTemp.length - 1)];
type=3;
}
str = "";
for (int i = 1; i <arrStr1.length ; i++) {
str+=arrStr1[i]+"市";
}
str = str.substring(0,str.length()-1);
}
//-------------------------------------------------------------
if (str.contains("县")) {
String[] arrStr1 = str.split("县");
if (arrStr1.length < 2) return value;
hash1 = Math.abs(arrStr1[0].hashCode() + hashSalt);
if (type==1){
newStrShi = shengTOshi.get(newStrSheng)[hash1 % (shengTOshi.get(newStrSheng).length - 1)];
newStrQu = shiTOqu.get(newStrShi)[hash1 % (shiTOqu.get(newStrShi).length - 1)];
newStrShi="";
}
if (type==2){
newStrQu = shiTOqu.get(newStrShi)[hash1 % (shiTOqu.get(newStrShi).length - 1)];
}
if (type==3){
newStrQu = shiTOqu.get(newStrShi)[hash1 % (shiTOqu.get(newStrShi).length - 1)];
}
str = arrStr1[1];
}else if (str.contains("区")) {
if (str.contains("小区")){
String[] arrStr1xiaoqu = str.split("小区");
String tem = "";
if (arrStr1xiaoqu[0].contains("区")){
String[] arrStr1 = str.split("区");
tem = arrStr1[1];
if (arrStr1.length < 2) return value;
hash1 = Math.abs(arrStr1[0].hashCode() + hashSalt);
if (type==1){
newStrShi = shengTOshi.get(newStrSheng)[hash1 % (shengTOshi.get(newStrSheng).length - 1)];
newStrQu = shiTOqu.get(newStrShi)[hash1 % (shiTOqu.get(newStrShi).length - 1)];
newStrShi="";
}
if (type==2){
newStrQu = shiTOqu.get(newStrShi)[hash1 % (shiTOqu.get(newStrShi).length - 1)];
}
if (type==3){
newStrQu = shiTOqu.get(newStrShi)[hash1 % (shiTOqu.get(newStrShi).length - 1)];
}
// //没有市
// if (type==2){
// //随机一个不显示的市
// String[] arryTemp = shi[hash1 % (shi.length - 1)];
// newStrShi =arryTemp[hash1 % (arryTemp.length - 1)];
// newStrQu = shiTOqu.get(newStrShi)[hash1 % (shiTOqu.get(newStrShi).length - 1)];
// newStrShi="";
// }else {
// newStrQu = shiTOqu.get(newStrShi)[hash1 % (shiTOqu.get(newStrShi).length - 1)];
// }
}
str=tem+"小区"+arrStr1xiaoqu[1];
}else {
String[] arrStr1 = str.split("区");
if (arrStr1.length < 2) return value;
hash1 = Math.abs(arrStr1[0].hashCode() + hashSalt);
if (type==1){
newStrShi = shengTOshi.get(newStrSheng)[hash1 % (shengTOshi.get(newStrSheng).length - 1)];
newStrQu = shiTOqu.get(newStrShi)[hash1 % (shiTOqu.get(newStrShi).length - 1)];
newStrShi="";
}
if (type==2){
newStrQu = shiTOqu.get(newStrShi)[hash1 % (shiTOqu.get(newStrShi).length - 1)];
}
if (type==3){
newStrQu = shiTOqu.get(newStrShi)[hash1 % (shiTOqu.get(newStrShi).length - 1)];
}
str = arrStr1[1];
}
}
String[] arrStr = new String [str.length()];
for (int i = 0; i <arrStr.length ; i++) {
arrStr[i] = str.substring(i,i+1);
}
for (int i = 0; i <arrStr.length ; i++) {
if (arrStr[i].contains("路"))continue;
if (arrStr[i].contains("小") && arrStr[i + 1].contains("区")){
i+=1;
continue;
}
if (arrStr[i].contains("单") && arrStr[i + 1].contains("元")){
i+=1;
continue;
}
if (arrStr[i].contains("大") && arrStr[i + 1].contains("街")){
i+=1;
continue;
}
if (arrStr[i].contains("酒") && arrStr[i + 1].contains("店")){
i+=1;
continue;
}
if (arrStr[i].contains("公") && arrStr[i + 1].contains("司")){
i+=1;
continue;
}
if (arrStr[i].contains("花") && arrStr[i + 1].contains("园")){
i+=1;
continue;
}
if (arrStr[i].contains("社") && arrStr[i + 1].contains("区")){
i+=1;
continue;
}
if (arrStr[i].contains("宿") && arrStr[i + 1].contains("舍")){
i+=1;
continue;
}
if (arrStr[i].contains("市")){
arrStr[i]="街";
continue;
}
if (arrStr[i].contains("楼"))continue;
if (arrStr[i].contains("栋"))continue;
if (arrStr[i].contains("幢"))continue;
if (arrStr[i].contains("第"))continue;
if (arrStr[i].contains("号"))continue;
if (arrStr[i].contains("镇"))continue;
if (arrStr[i].contains("乡"))continue;
if (arrStr[i].contains("村"))continue;
if (arrStr[i].contains("组"))continue;
if (arrStr[i].contains("户"))continue;
if (arrStr[i].contains("室"))continue;
if (arrStr[i].contains("东"))continue;
if (arrStr[i].contains("西"))continue;
if (arrStr[i].contains("南"))continue;
if (arrStr[i].contains("北"))continue;
if (pattern1.matcher(arrStr[i]).matches()){
String s1 = Math.abs(arrStr[i].hashCode()+hashSalt)+"";
arrStr[i]=s1.substring(s1.length()-1,s1.length());
continue;
}
int hashTemp = Math.abs(arrStr[i].hashCode()+hashSalt);
arrStr[i] = randomName[hashTemp % (randomName.length - 1)];
}
for (int i = 0; i <arrStr.length ; i++) {
newCun+=arrStr[i];
}
if (!newStrSheng.equals("")){
newStrSheng+="省";
}
return newStrSheng+newStrShi+newStrXian+newStrQu+newCun;
}
public static Object getR(Object value, Object key){
return "";
}
}
<file_sep>package id;
/**
* Created by ${LiuShuo} on 8/2/2016.
*/
/**
* 有效证件混合过滤算法
* 包括15位身份证、18位身份证、军官证
* 前六后二不脱
* Created by zhengbing on 2016/6/21.
*/
public class ICCompositeFilterAlgorithm {
public static Object getModelIDCard(Object value,Object key){
if (value==null||value.equals("null")||value.equals("")) return "";
if (value instanceof byte[] )return value;
String str = value+"";
if (str.contains(" ")) return value;
int isSuangYin = 0;
if (str.endsWith("\"")&&str.startsWith("\"")){
str = str.substring(1, str.length() - 1);
isSuangYin = 1;
}
String salt = key + "";
String saltok = salt.replace(" ", "");
int hashSalt = 0;
if (salt.length()<1){
}else {
hashSalt=Math.abs(saltok.hashCode());
}
int type = 0;
String[] soldiers = {"\u5357","\u5317","\u6C88","\u5170","\u6210","\u6D4E","\u5E7F","\u53C2","\u653F","\u540E","\u88C5","\u6D77","\u7A7A","\u4E1C","\u897F","\u4E2D"};
String[] num18 = { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" };
int[] validate18 = {7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};
java.util.regex.Pattern p = java.util.regex.Pattern.compile("^(\u5357|\u5317|\u6C88|\u5170|\u6210|\u6D4E|\u5E7F|\u53C2|\u653F|\u540E|\u88C5|\u6D77|\u7A7A|\u4E1C|\u897F|\u4E2D)\\d{8}$");
if (str.length()==18){
type=18;
}
if (str.length()==15){
type=15;
}
if (p.matcher(str).matches()){
type=9;
}
if (type==0)return value;
java.util.Random random = new java.util.Random(hashSalt);
String newStr1="";
String newStr2="";
String newStr3="";
String newStr4="";
String subStr1="";
String subStr2="";
String subStr3="";
String subStr4="";
if (type>14){
int hash1 = 0;
int hash2 = 0;
int hash3 = 0;
int hash4 = 0;
int dom1 = 0;
int dom2 = 0;
java.util.Calendar birthday = java.util.Calendar.getInstance();
subStr1 = str.substring(0, 6);
if (type==18){
subStr2 = str.substring(6, 14);
subStr3 = str.substring(14, 17);
hash1 = Math.abs(subStr1.hashCode()+hashSalt);
hash2 = Math.abs(subStr2.hashCode()+hashSalt);
hash3 = Math.abs(subStr3.hashCode()+hashSalt);
dom1 = random.nextInt(hash2);
dom2 = random.nextInt(hash3);
newStr1 = subStr1;
birthday.set(java.util.Calendar.YEAR, (int)(((float)dom1/(float)hash2)*50)+ 1950);
birthday.set(java.util.Calendar.MONTH, (int)(((float)dom1/(float)hash2) * 12));
birthday.set(java.util.Calendar.DATE, (int)(((float)dom1/(float)hash2) * 31));
StringBuilder builder = new StringBuilder();
builder.append(birthday.get(java.util.Calendar.YEAR));
long month = birthday.get(java.util.Calendar.MONTH) + 1;
if (month < 10) {
builder.append("0");
}
builder.append(month);
long date = birthday.get(java.util.Calendar.DATE);
if (date < 10) {
builder.append("0");
}
builder.append(date);
newStr2=builder.toString();
int code =(int)(((float)dom2/(float)hash3)*100);
if (code < 10) {
newStr3= "0" + code;
} else {
newStr3= "" + code;
}
newStr3 +=subStr3.substring(subStr3.length()-1,subStr3.length());
int add17 = 0;
String temp17= newStr1 + newStr2 +newStr3;
for (int i = 0; i <temp17.length() ; i++) {
String s =temp17.substring(i,i+1);
add17 += Integer.parseInt(s) * validate18[i];
}
int validateCode = Math.abs(add17) % 11;
newStr4 = num18[validateCode]+"";
}
if (type==15){
subStr2 = str.substring(6, 12);
subStr3 = str.substring(12, 15);
hash1 = Math.abs(subStr1.hashCode()+hashSalt);
hash2 = Math.abs(subStr2.hashCode()+hashSalt);
hash3 = Math.abs(subStr3.hashCode()+hashSalt);
java.util.Random random2 = new java.util.Random(hash2);
dom1 = random2.nextInt(hash2);
dom2 = random.nextInt(hash3);
newStr1 = subStr1;
birthday.set(java.util.Calendar.YEAR, (int)(((float)dom1/(float)hash2)*50)+ 1950);
birthday.set(java.util.Calendar.MONTH, (int)(((float)dom1/(float)hash2) * 12));
birthday.set(java.util.Calendar.DATE, (int)(((float)dom1/(float)hash2) * 31));
StringBuilder builder = new StringBuilder();
builder.append(birthday.get(java.util.Calendar.YEAR));
long month = birthday.get(java.util.Calendar.MONTH) + 1;
if (month < 10) {
builder.append("0");
}
builder.append(month);
long date = birthday.get(java.util.Calendar.DATE);
if (date < 10) {
builder.append("0");
}
builder.append(date);
newStr2=builder.toString().substring(2,8);
int code =(int)(((float)dom2/(float)hash3)*100);
if (code < 10) {
newStr3= "0" + code;
} else {
newStr3= "" + code;
}
newStr3 +=subStr3.substring(subStr3.length()-1,subStr3.length());
}
}
if (type==9){
subStr1=str.substring(0,1);
subStr2=str.substring(1,str.length());
int hashSub1 = Math.abs(subStr1.hashCode() * subStr1.hashCode()+hashSalt);
int hashSub2 = Math.abs(subStr2.hashCode()+hashSalt);
int dom2 = random.nextInt(hashSub2);
newStr1 = soldiers[hashSub1 % (soldiers.length-1)];
int code =(int)(((float)dom2/(float)hashSub2)*10000);
if (code < 10) {
newStr2= "000" + code;
} else if (code < 100) {
newStr2= "00" + code;
} else if (code < 1000) {
newStr2= "0" + code;
} else {
newStr2= "" + code;
}
int code2 =(int)(((float)dom2/(float)hashSub2)*((float)dom2/(float)hashSub2)*10000);
if (code2 < 10) {
newStr3= "000" + code2;
} else if (code2 < 100) {
newStr3= "00" + code2;
} else if (code2 < 1000) {
newStr3= "0" + code2;
} else {
newStr3= "" + code2;
}
}
str =newStr1+newStr2+newStr3+newStr4;
if (isSuangYin == 1){
str = "\"" + str +"\"";
}
return str;
}
}<file_sep>package huanghe.bank;
import two_param.bank.*;
/**
* Created by ${LiuShuo} on 2016/6/22.
*/
public class TestBANK {
public static void main(String[] args) {
Object m = two_param.bank.Bank.getM(1234567890123456789L, 0);
System.out.println(m);
/*
*/
}
}
<file_sep>package two_param.bank;
/**
* Created by ${LiuShuo} on 2016/6/22.
*/
public class TestBANK {
public static void main(String[] args) {
Object m = Bank.getM(1234567890123456789L, 0);
System.out.println(m);
/*
*/
}
}
<file_sep>//\u5224\u65AD\u53C2\u6570\u662F\u5426\u4E3Anull\u3001"null"\u3001"" ,\u4E3Atrue\u65F6\u4E0D\u505A\u5904\u7406
if (value == null || value.equals("null") || value.equals("")) return value;
String str = value + "";
str = str.replace(" ", "");
//\u9A8C\u8BC1\u662F\u5426\u6570\u5B57
Pattern numRegex = Pattern.compile("^([0-9]{11})$");
if (!numRegex.matcher(str).matches()) return value;
if (str.length() != 11) return value;
String salt = key + "";
String saltok = salt.replace(" ", "");
//\u76D0\u503Chash
int hashSalt = 0;
if (salt.length() < 1) {
//\u6CA1\u6709\u76D0\u503C
} else {
hashSalt = Math.abs(saltok.hashCode());
}
String newStr2 = "";
String newStr1 ="";
String subStr1 = "";
int hash = 0;
if (str.substring(0,1).equals("0")){
newStr1 = str.substring(0,str.length()-6);
subStr1 = str.substring(str.length()-6,str.length());
hash = Math.abs(subStr1.hashCode() + hashSalt);
java.util.Random random1 = new java.util.Random(hash);
int dom = random1.nextInt(hash);
int code = (int) (((float)dom/(float)hash) * 1000);
if (code<10){
newStr2= "00" + code;
} else if (code < 100) {
newStr2= "0" + code;
} else {
newStr2= "" + code;
}
int code2 = (int) (((float)dom/(float)hash)*((float)dom/(float)hash)* 1000);
if (code2<10){
newStr2 += "00" + code2;
} else if (code2 < 100) {
newStr2 += "0" + code2;
} else {
newStr2 += "" + code2;
}
}else return value;
String s = newStr1+newStr2;
if(value instanceof BigDecimal){
return new BigDecimal(s);
}else if(value instanceof Long){
return Long.parseLong(s);
}else if(value instanceof Double){
return Double.parseDouble(s);
}
return s;<file_sep>package two_param.company;
/**
* Created by ${LiuShuo} on 2016/6/22.
*/
public class TestCOMP {
public static void main(String[] args) {
Object m = Company2.getM("永宁县望远镇沪宁物资经营部",1);
System.out.println(m );
}
}
<file_sep>package two_param.bank;
import java.util.*;
import java.math.*;
/**
* 完成
* Created by ${LiuShuo} on 2016/6/22.
*/
public class Bank {
public static Object getM(Object value, Object key){
//判断参数是否为null、"null"、"" ,为true时不做处理
if (value==null||value.equals("null")||value.equals("")) return value;
String str = value+"";
//不允许含有空格(证件含有空格,直接返回不做清洗)
if (str.contains(" ")) return value;
String salt = key + "";
String saltok = salt.replace(" ", "");
//盐值hash
int hashSalt = 0;
if (salt.length()<1){
//没有盐值
}else {
hashSalt=Math.abs(saltok.hashCode());
}
String newStr1="";
String newStr2="";
String newStr3="";
String newStrFir="";
String newStrEnd="";
int tempOdd = 0;//奇数
int tempEven = 0;//偶数
//类型判断 0:不符合标准不进行脱敏 16:贷记卡 19:借记卡
int type =0;
str = value+"";
if (str.length()==16){
type=16;
}
if (str.length()==19){
type=19;
}
//不符合标准不做处理
if (type==0){
return value;
}
//贷记卡
if (type==16){
String tempStr1="";
newStr1 = str.substring(0, 10);
String subStr11to15 = str.substring(10, 15);
int hash1 = Math.abs(subStr11to15.hashCode()+hashSalt);
java.util.Random random = new java.util.Random(hash1);
int dom1 = random.nextInt(hash1);
//生成5个固定数
int code = (int) (((float)dom1/(float)hash1) * 100000);
if (code<10){
tempStr1= "0000" + code;
} else if (code < 100) {
tempStr1= "000" + code;
} else if (code < 1000) {
tempStr1= "00" + code;
} else if (code < 10000) {
tempStr1= "0" + code;
} else {
tempStr1= "" + code;
}
newStr2 = tempStr1;
newStrFir = newStr1 + newStr2;
for (int i = 0; i < newStrFir.length(); i++) {
//奇数
if (i%2!=0){
String sOdd = newStrFir.substring(i, i + 1);
tempOdd+=Integer.parseInt(sOdd);
}else{
//偶数
String sEven = newStrFir.substring(i, i + 1);
int i1 = Integer.parseInt(sEven)*2;
if (i1>9){
tempEven+=(i1-(i1/10))+(i1/10);
}else {
tempEven+=i1;
}
}
for (int j = 0; j < 10; j++) {
if ((tempOdd+tempEven+i)%10==0){
newStrEnd=tempOdd+tempEven+i+"";
break;
}
}
}
}
//借记卡
if (type==19) {
String tempStr1 = "";
newStr1 = str.substring(0, 13);
String subStr14to18 = str.substring(13, 18);
int hash1 = Math.abs(subStr14to18.hashCode() + hashSalt);
java.util.Random random = new java.util.Random(hash1);
int dom1 = random.nextInt(hash1);
//生成5个固定数
int code = (int) (((float) dom1 / (float) hash1) * 100000);
if (code < 10) {
tempStr1 = "0000" + code;
} else if (code < 100) {
tempStr1 = "000" + code;
} else if (code < 1000) {
tempStr1 = "00" + code;
} else if (code < 10000) {
tempStr1 = "0" + code;
} else {
tempStr1 = "" + code;
}
newStr2 = tempStr1;
newStrFir = newStr1 + newStr2;
for (int i = 0; i < newStrFir.length(); i++) {
//奇数
if (i%2!=0){
String sOdd = newStrFir.substring(i, i + 1);
tempOdd+=Integer.parseInt(sOdd);
}else{
//偶数
String sEven = newStrFir.substring(i, i + 1);
int i1 = Integer.parseInt(sEven)*2;
if (i1>9){
tempEven+=(i1-(i1/10))+(i1/10);
}else {
tempEven+=i1;
}
}
for (int j = 0; j < 10; j++) {
if ((tempOdd+tempEven+j)%10==0){
newStrEnd=j+"";
break;
}
}
}
}
String s = newStrFir + newStrEnd;
if(value instanceof BigDecimal){
return new BigDecimal(s);
}else if(value instanceof Long){
return Long.parseLong(s);
}else if(value instanceof Double){
return Double.parseDouble(s);
}
return s;
}
public static Object getR(Object value, Object key){
return "";
}
}
<file_sep>package com.wiseweb.email;
//import java.util.regex.Pattern;
import java.util.regex.Matcher;
/**
* Created by ${LiuShuo} on 2016/6/22.
*/
public class Email {
public static Object getM(Object value,Object key){
//判断参数是否为null、"null"、"" ,为true时不做处理
if (value==null||value.equals("null")||value.equals("")) return value;
String str = value+"";
String newStr="";
java.util.regex.Pattern p = java.util.regex.Pattern.compile("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\\.[a-zA-Z0-9_-]{2,3}){1,2})$");
boolean b = p.matcher(str).find();
if (b){
if (str.startsWith("@")||str.startsWith(" "))return value;
String[] split = str.split("@");
for (int i = 0; i < split[0].length(); i++) {
}
newStr= ""+"@"+split[1];
}else return value;
return newStr;
}
public static Object getR(Object value){
return "";
}
}
<file_sep>package version3.Licence;
import java.math.BigDecimal;
/**
* Created by ${LiuShuo} on 2016/9/1.
*/
public class Licence {
public static Object getModelLicence(Object value, Object key) {
if (value == null || value.equals("null") || value.equals("")) return "";
String str = value + "";
str = str.replaceAll("\\s*", "");
str = str.replaceAll("\\u3000", "");
int isSuangYin = 0;
if (str.endsWith("\"") && str.startsWith("\"")) {
str = str.substring(1, str.length() - 1);
isSuangYin = 1;
}
if (str.length() != 15) return value;
String s = "";
s = str.substring(0,2)+"***********"+str.substring(str.length()-2,str.length());
if (isSuangYin == 1) {
s = "\"" + s + "\"";
}
return s;
}
}
<file_sep>package com.wiseweb.tax;
/**
* Created by ${LiuShuo} on 2016/6/22.
*/
public class TestTax {
}
<file_sep>package com.wise.version1;
import version1.NameENameCompositeFilterAlgorithm;
/**
* Created by ${LiuShuo} on 8/22/2016.
*/
public class Test {
public static void main(String[] args) {
/*日照市东港区北京路188号
算法:将所有replace(" ","")替换replaceAll("\\s*","")
*/
// Object o = SanFenGuiYuanQi.getModelNameAddr("中国", null);
// Object o = SHANDONGSanFenGuiYuanQi.getModelNameAddr("南宁市金谷隆粮油购销有限公司 元数据", null);
Object o = null;
try {
o = NameENameCompositeFilterAlgorithm.getModelComName("南宁市金谷隆粮油购销有限公司 元数据", null);
} catch (Exception e) {
e.printStackTrace();
}
// String replace = "南宁市金谷隆粮油购销有限公司 元数据".replaceAll("\\u3000", "");
// int i = " ".hashCode();
// int j = " ".hashCode();
// int k = " ".hashCode();
// System.out.println(i+"------"+j+"------"+k);o
System.out.println(o);
}
}
<file_sep>package com.wiseweb.email;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by ${LiuShuo} on 2016/6/22.
*/
public class TestEmail {
public static void main(String[] args) {
Pattern p = Pattern.compile("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\\.[a-zA-Z0-9_-]{2,3}){1,2})$");
String input = "<EMAIL>";
Matcher matcher = p.matcher(input);
boolean b = matcher.find();
System.out.println(b);
}
}
<file_sep>package huanghe.com_name;
/**
* Created by ${LiuShuo} on 2016/7/1.
*/
public class TestCI {
public static void main(String[] args) {
// 嘉兴市秀城区城南街道会计集中核算办公室
Object m = ComName3.getM("磁材六厂", 1);
System.out.println(m);
}
}
| 6b68a6597894bf78a58e1d27fc7a19bc67ea4513 | [
"Java",
"INI"
] | 30 | Java | LiuShuo2538/Random | f90732308951f813ce4a3de7a19d07f8e8751213 | 321b9d3765e7a0372ab2ea254f467203268034f3 |
refs/heads/main | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.UI.DataVisualization.Charting;
namespace vikapplogger
{
public partial class mylogreports : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ddlusers_SelectedIndexChanged(object sender, EventArgs e)
{
}
private static DataTable GetData(string query)
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand(query);
String constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Chart1.Visible = ddltcodes.SelectedValue != "";
string query = string.Format("select [Transaction Code], count([Transaction Code])from SM20_Logs_new where [Audit Log Message Te] LIKE '%Field content%' GROUP BY [Transaction Code]", ddltcodes.SelectedValue);
DataTable dt = GetData(query);
string[] x = new string[dt.Rows.Count];
int[] y = new int[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
x[i] = dt.Rows[i][0].ToString();
y[i] = Convert.ToInt32(dt.Rows[i][1]);
}
Chart1.Series[0].Points.DataBindXY(x, y);
Chart1.Series[0].ChartType = SeriesChartType.Pie;
Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;
Chart1.Legends[0].Enabled = true;
}
protected void SqlDataSource2_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
}
protected void DropDownDataSource_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
}
}
} | 54f1b6fdeed1b59d1179dd826d47d406704e3d62 | [
"C#"
] | 1 | C# | Vicksjsr/mylogger | be3839a05c45bd0bb53effa1ad16de198b50441c | 00ed139b5b0228128674b0644800916a8366c574 |
refs/heads/master | <repo_name>phamhiepst/ios-ductran<file_sep>/TipCalculator/TipCalculator/TipCalc.swift
//
// TipCalc.swift
// TipCalculator
//
// Created by <NAME> on 5/4/16.
// Copyright © 2016 phamhiepst. All rights reserved.
//
import Foundation
class TipCalc{
var amountBeforeTax: Float = 0
var tipPercentage: Float = 0
var tipAmount: Float = 0
var totalAmount:Float = 0
var numberOfPeople: Int = 0
var totalAmountPerPeople:Float = 0
init (amountBeforeTax: Float, tipPercentage: Float){
self.amountBeforeTax = amountBeforeTax
self.tipPercentage = tipPercentage
}
func calculateTip(){
tipAmount = amountBeforeTax * Float(Int(tipPercentage*100))/100
totalAmount = amountBeforeTax + tipAmount
totalAmountPerPeople = (totalAmount / Float(numberOfPeople))
}
}<file_sep>/MyPlayground.playground/Contents.swift
//: Playground - noun: a place where people can play
import UIKit
func currencyStringFromNumber(number: Float) -> String {
let formatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
formatter.currencyCode = NSLocale.currentLocale().displayNameForKey(NSLocaleCurrencySymbol, value: NSLocaleCurrencyCode)
return formatter.stringFromNumber(number)!
}
let currencyString = currencyStringFromNumber(5.0009)
print("Currency String is: \(currencyString)")<file_sep>/TipCalculator/TipCalculator/TipCalculatorViewController.swift
//
// TipCalculatorViewController.swift
// TipCalculator
//
// Created by <NAME> on 5/4/16.
// Copyright © 2016 phamhiepst. All rights reserved.
//
import UIKit
class TipCalculatorViewController: UIViewController, UITextFieldDelegate {
// MARK: - IBOutlets
@IBOutlet weak var amountBeforeTaxTextFeild: UITextField!
@IBOutlet weak var tipPercentageLabel: UILabel!
@IBOutlet weak var tipPercentageSlider: UISlider!
@IBOutlet weak var resultLable: UILabel!
@IBOutlet weak var numberOfPeopleLabel: UILabel!
@IBOutlet weak var numberOfPeopleSilder: UISlider!
@IBOutlet weak var totalAmountPerPeopleLabel: UILabel!
// MARK: - Properties
var tipCalc = TipCalc(amountBeforeTax: 100, tipPercentage: 0.05)
// MARK: - ViewController Life-cycle
override func viewDidLoad() {
super.viewDidLoad()
// default values
tipPercentageLabel.text = String(format: "Tip: %d%%", Int(tipCalc.tipPercentage * 100))
resultLable.text = String(format: "Total: $%0.2f Tip: $%0.2f", tipCalc.totalAmount, tipCalc.tipAmount)
numberOfPeopleLabel.text = String(format: "Split: %02d", Int(numberOfPeopleSilder.value))
}
func calcTip(){
tipCalc.tipPercentage = Float(tipPercentageSlider.value)
tipCalc.amountBeforeTax = (amountBeforeTaxTextFeild.text! as NSString).floatValue
tipCalc.numberOfPeople = Int(numberOfPeopleSilder.value)
tipCalc.calculateTip()
updateUI()
}
func updateUI(){
// update label
resultLable.text = String(format: "Total: $%0.2f Tip: $%0.2f", tipCalc.totalAmount, tipCalc.tipAmount)
totalAmountPerPeopleLabel.text = String(format: "$%0.2f", tipCalc.totalAmountPerPeople)
}
// MARK: - UIControl Events
@IBAction func amountOfBeforeTaxTextFeildChanged(sender: AnyObject) {
calcTip()
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
if textField == amountBeforeTaxTextFeild{
textField.resignFirstResponder()
calcTip()
// format currency in text field
// let amoutBeforeTaxFloat = (amountBeforeTaxTextFeild.text! as NSString).floatValue
// amountBeforeTaxTextFeild.text = currencyStringFromNumber(amoutBeforeTaxFloat)
}
return true
}
@IBAction func tipPercentageSliderValueChanged(sender: UISlider) {
tipPercentageLabel.text = String(format: "Tip: %d%%", Int(tipCalc.tipPercentage * 100))
calcTip()
}
@IBAction func numberOfPeopleValueChanged(sender: AnyObject) {
numberOfPeopleLabel.text = String(format: "Split: %02d", Int(numberOfPeopleSilder.value))
calcTip()
}
func currencyStringFromNumber(number: Float) -> String {
let formatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
formatter.currencyCode = NSLocale.currentLocale().displayNameForKey(NSLocaleCurrencySymbol, value: NSLocaleCurrencyCode)
return formatter.stringFromNumber(number)!
}
}
<file_sep>/Playlist/Playlist/PlayListViewController.swift
//
// PlayListViewController.swift
// Playlist
//
// Created by <NAME> on 4/24/16.
// Copyright © 2016 phamhiepst. All rights reserved.
//
import UIKit
class PlayListViewController: UIViewController {
// MARK: - Properties
@IBOutlet weak var coverImage0: UIImageView!
@IBOutlet weak var coverImage1: UIImageView!
@IBOutlet weak var coverImage2: UIImageView!
@IBOutlet weak var coverImage3: UIImageView!
@IBOutlet weak var coverImage4: UIImageView!
@IBOutlet weak var coverImage5: UIImageView!
@IBOutlet weak var coverImage6: UIImageView!
@IBOutlet weak var coverImage7: UIImageView!
@IBOutlet weak var coverImage8: UIImageView!
@IBOutlet weak var coverImage9: UIImageView!
@IBOutlet weak var coverImage10: UIImageView!
@IBOutlet weak var coverImage11: UIImageView!
var coverImages: [UIImageView]!
// MARK: - View controller life cycle
override func viewDidLoad() {
super.viewDidLoad()
// append all the cover images into the coverImages array
coverImages = [coverImage0,coverImage1,coverImage2,coverImage3,coverImage4,coverImage5,coverImage6,coverImage7,coverImage8,coverImage9,coverImage10,coverImage11]
updateUI()
}
// set the cover images for those UIOulets
func updateUI(){
for i in 0..<coverImages.count{
let coverImage = coverImages[i]
// grasp our model here
let album = Album(index: i)
coverImage.image = UIImage(named: album.coverImageName!)
}
}
// MARK: - Target / Action
@IBAction func showAlbum(sender: UITapGestureRecognizer) {
performSegueWithIdentifier("Show Album", sender: sender)
}
@IBAction func showFavoriteAlbum(sender: UIButton)
{
performSegueWithIdentifier("Show Favorite", sender: sender)
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let identifier = segue.identifier{
switch identifier {
case "Show Album":
// do something
let albumViewController = segue.destinationViewController as! AlbumViewController
let albumImageView = sender?.view as! UIImageView
if let index = coverImages.indexOf(albumImageView){
let album = Album(index: index)
albumViewController.album = album
}
default:
break
}
}
}
}
<file_sep>/inspirus/inspirus/ViewController.swift
//
// ViewController.swift
// inspirus
//
// Created by <NAME> on 4/23/16.
// Copyright © 2016 phamhiepst. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var quoteLabel: UILabel!
@IBOutlet weak var authorLable: UILabel!
@IBOutlet weak var backgroundImageView: UIImageView!
@IBOutlet weak var inspireMeButton: UIButton!
var quotes = Quotes()
@IBAction func inspireMeDidTap(sender: UIButton) {
// change the text
let quote = quotes.randomQuote()
quoteLabel.text = quote.0
authorLable.text = quote.1
// change color of the text
quoteLabel.backgroundColor = randomLableColor()
// change the background image
let image = randomImage()
backgroundImageView.image = image
// change button color
inspireMeButton.backgroundColor = randomButtonColor()
}
override func viewDidLoad() {
super.viewDidLoad()
// dynamically changing font size of UILabel
quoteLabel.adjustsFontSizeToFitWidth = true
// change the text randomly
let quote = quotes.randomQuote()
quoteLabel.text = quote.0
authorLable.text = quote.1
}
func randomImage() -> UIImage{
let imageCount = 6
let randomNumber = random() % (imageCount + 1)
if let image = UIImage(named: "image\(randomNumber)"){
return image
}
else{
return UIImage(named: "image1")!
}
}
func randomButtonColor() -> UIColor{
let randomNumber = random() % 5
switch randomNumber {
case 0:
return UIColor(red: 1, green: 0.8, blue: 0, alpha: 0.7) /* #ffcc00 */
case 1:
return UIColor(red: 0.8314, green: 0.4039, blue: 0.9176, alpha: 0.7) /* #d467ea */
case 2:
return UIColor(red: 0.3412, green: 0.7765, blue: 0.7059, alpha: 0.7) /* #57c6b4 */
case 3:
return UIColor(red: 0.3686, green: 0.7569, blue: 0.3333, alpha: 0.7) /* #5ec155 */
default:
return UIColor(red: 0.9765, green: 0.2745, blue: 0.1647, alpha: 0.7) /* #f9462a */
}
}
func randomLableColor() -> UIColor{
let randomNumber = random() % 5
switch randomNumber {
case 0:
return UIColor(red: 1, green: 0.8, blue: 0, alpha: 0.5) /* #ffcc00 */
case 1:
return UIColor(red: 0.8314, green: 0.4039, blue: 0.9176, alpha: 0.5) /* #d467ea */
case 2:
return UIColor(red: 0.3412, green: 0.7765, blue: 0.7059, alpha: 0.5) /* #57c6b4 */
case 3:
return UIColor(red: 0.3686, green: 0.7569, blue: 0.3333, alpha: 0.5) /* #5ec155 */
default:
return UIColor(red: 0.9765, green: 0.2745, blue: 0.1647, alpha: 0.5) /* #f9462a */
}
}
}
<file_sep>/Recap/Recap/MasterViewController.swift
//
// MasterViewController.swift
// Recap
//
// Created by <NAME> on 5/3/16.
// Copyright © 2016 phamhiepst. All rights reserved.
//
import UIKit
class MasterViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowDetailView"{
if let detailViewControler = segue.destinationViewController as? ViewController{
detailViewControler.defaultText = "Move me"
}
}
}
}
<file_sep>/Recap/Recap/ViewController.swift
//
// ViewController.swift
// Recap
//
// Created by <NAME> on 5/3/16.
// Copyright © 2016 phamhiepst. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var defaultText: String!
@IBOutlet weak var myTextField: UITextField!
@IBOutlet weak var myLabel: UILabel!
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
myTextField.delegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
myTextField.text = defaultText
}
}
extension ViewController: UITextFieldDelegate{
func textFieldShouldReturn(textField: UITextField) -> Bool {
myLabel.text = myTextField.text
return true
}
}
<file_sep>/Playlist/Playlist/AlbumViewController.swift
//
// AlbumViewController.swift
// Playlist
//
// Created by <NAME> on 4/24/16.
// Copyright © 2016 phamhiepst. All rights reserved.
//
import UIKit
class AlbumViewController: UIViewController {
// Model: an album
var album: Album?
// MARK: - Properties
@IBOutlet weak var backgroundImageView: UIImageView!
@IBOutlet weak var albumCoverImageView: UIImageView!
@IBOutlet weak var descriptionTextView: UITextView!
@IBOutlet weak var likeLabel: UILabel!
func updateUI() {
let albumName = "\((album?.title)!)"
backgroundImageView.image = UIImage(named: albumName)
albumCoverImageView.image = UIImage(named: albumName)
let songList = ((album?.songs)! as NSArray).componentsJoinedByString(", ")
descriptionTextView.text = "\((album?.description)!) \n\nSome songs in the album:\n\(songList)"
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Album"
updateUI()
}
// MARK: - Action
@IBAction func like(sender: UITapGestureRecognizer) {
if (likeLabel.text == "Like"){
likeLabel.text = "Liked"
likeLabel.textColor = UIColor.yellowColor()
} else {
likeLabel.text = "Like"
likeLabel.textColor = UIColor.whiteColor()
}
}
}
| 47660f2b60ad6c572e475bfc46a3411a27a1e660 | [
"Swift"
] | 8 | Swift | phamhiepst/ios-ductran | cbb60f0cf2a40df6e219070acabbc5469b1b48f4 | defa57ac4fed283385fcda882ced7d7b156474a7 |
refs/heads/master | <repo_name>microwaves/go-demoapp<file_sep>/ci/scripts/run_tests.sh
#!/bin/sh
set -e -u -x
cd git && go test -a -tags netgo -ldflags '-w'
<file_sep>/Dockerfile
FROM golang:1.16-alpine as builder
WORKDIR /go/src/github.com/microwaves/go-demoapp
ADD . .
RUN go mod init github.com/microwaves/go-demoapp && \
go get && \
CGO_ENABLED=0 go build -o /demoapp -a -tags netgo -ldflags '-w' main.go
FROM scratch
COPY --from=builder /demoapp /demoapp
ENTRYPOINT ["/demoapp"]
EXPOSE 8080
<file_sep>/main_test.go
package main
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
)
var writer *httptest.ResponseRecorder
func setup() {
writer = httptest.NewRecorder()
}
func TestIndexGet200(t *testing.T) {
setup()
expected := http.StatusOK
req, err := http.NewRequest("GET", "/", nil)
if err != nil {
t.Fatal("Creating 'GET /' request failed!")
}
indexHandler(writer, req)
resp := writer.Result()
if resp.StatusCode != expected {
t.Fatal("Server error: Returned code:", resp.StatusCode, "instead of:", expected)
}
}
func TestIndexBody(t *testing.T) {
setup()
expected := "Hey! This is supposed to be a demo. :-)"
req, err := http.NewRequest("GET", "/", nil)
if err != nil {
t.Fatal("Creating 'GET /' request failed!")
}
indexHandler(writer, req)
resp := writer.Result()
body, _ := ioutil.ReadAll(resp.Body)
if string(body) != expected {
t.Fatal("Error: Returned body:", string(body), "instead of:", expected)
}
}
<file_sep>/main.go
package main
import (
"fmt"
"io"
"log"
"net/http"
)
var port = 8080
func indexHandler(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "Hey! This is supposed to be a demo. :-)")
}
func main() {
http.HandleFunc("/", indexHandler)
fmt.Println("Now listening on port", fmt.Sprintf("%d", port))
log.Fatal(http.ListenAndServe(":"+fmt.Sprintf("%d", port), nil))
}
| bac0c063dc6b302709f5438932c9122c42446107 | [
"Go",
"Dockerfile",
"Shell"
] | 4 | Shell | microwaves/go-demoapp | d385697b55b3a72761e8fa3d170c92635fda2505 | 3df09f7c1aa8a2f92a26f71a8897bc09c667c8c4 |
refs/heads/master | <repo_name>petterin/studiox-proto<file_sep>/storyApp/ViewerController.swift
import UIKit
import AVFoundation
class ViewerController: UIViewController, AVAudioPlayerDelegate {
required init(coder aDecoder: NSCoder) {
self.audioPlayer = AVAudioPlayer()
super.init(coder: aDecoder)
}
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var controllerImageView: UIImageView!
let imageList = ["mokki1.jpg","mokki2.jpg","mokki3.jpg","mokki4.jpg","mokki5.jpg","mokki6.jpg","mokki7.jpg","mokki8.jpg","mokki9.jpg","mokki10.jpg","mokki11.jpg","mokki12.jpg","mokki13.jpg"]
let audioURLs = ["story1_audio", "story2_audio", "story3_audio", "story4_audio", "story5_audio", "story4_audio", "story4_audio", "story4_audio", "story4_audio", "story4_audio", "story4_audio", "story4_audio", "story4_audio"].map({(filename) -> NSURL in
let path = NSBundle.mainBundle().pathForResource(filename, ofType: "m4a")!
return NSURL(fileURLWithPath: path)!})
let playImage = UIImage(named: "play_icon")
let pauseImage = UIImage(named: "pause_icon")
var recordingStartedAtLeastOnce = false
var imageIndex = 0
var audioPlayer:AVAudioPlayer {
didSet{
audioPlayer.delegate = self
}
}
override func viewDidLoad() {
super.viewDidLoad()
var swipeRight = UISwipeGestureRecognizer(target: self, action: "swipedView:")
swipeRight.direction = UISwipeGestureRecognizerDirection.Right
imageView.addGestureRecognizer(swipeRight)
var swipeLeft = UISwipeGestureRecognizer(target: self, action: "swipedView:")
swipeLeft.direction = UISwipeGestureRecognizerDirection.Left
imageView.addGestureRecognizer(swipeLeft)
imageView.userInteractionEnabled = true
imageView.image = UIImage(named: imageList[0])
imageView.frame = UIScreen.mainScreen().applicationFrame
audioPlayer = AVAudioPlayer(contentsOfURL: audioURLs[0], error: nil)
audioPlayer.prepareToPlay()
}
override func viewWillAppear(animated: Bool) {
self.navigationController?.setToolbarHidden(true, animated: false)
}
override func viewWillDisappear(animated: Bool) {
//self.navigationController?.setToolbarHidden(false, animated: false)
self.navigationController?.setNavigationBarHidden(false, animated: false)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prefersStatusBarHidden() -> Bool {
return true
}
func swipedView(gesture: UIGestureRecognizer){
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.Right :
println("User swiped right")
imageIndex++
if imageIndex > imageList.count - 1 {
imageIndex = 0
}
imageView.image = UIImage(named: imageList[imageIndex])
audioPlayer = AVAudioPlayer(contentsOfURL: audioURLs[imageIndex], error: nil)
audioPlayer.play()
case UISwipeGestureRecognizerDirection.Left:
println("User swiped Left")
imageIndex--
if imageIndex < 0 {
imageIndex = imageList.count - 1
}
imageView.image = UIImage(named: imageList[imageIndex])
default:
break //stops the code/codes nothing.
}
}
imageView.contentMode = UIViewContentMode.ScaleAspectFill
}
@IBAction func controllerTapped(sender : AnyObject) {
if(controllerImageView.hidden == false) {
if(controllerImageView.image == pauseImage) {
controllerImageView.image = playImage
audioPlayer.pause()
}
else {
audioPlayer.play()
recordingStartedAtLeastOnce = true
controllerImageView.image = pauseImage
controllerImageView.hidden = true
self.navigationController?.setNavigationBarHidden(!self.navigationController!.navigationBarHidden, animated: false)
}
}
}
@IBAction func imageTapped(sender : AnyObject) {
controllerImageView.hidden = !controllerImageView.hidden
self.navigationController?.setNavigationBarHidden(!self.navigationController!.navigationBarHidden, animated: false)
}
func audioPlayerDidFinishPlaying(player: AVAudioPlayer!,
successfully flag: Bool){
if(imageIndex < imageList.count - 1) {
imageIndex++
imageView.image = UIImage(named: imageList[imageIndex])
audioPlayer = AVAudioPlayer(contentsOfURL: audioURLs[imageIndex], error: nil)
audioPlayer.play()
}
}
} | e46113dde8ef9b586ee661ee3af33bb6d325a752 | [
"Swift"
] | 1 | Swift | petterin/studiox-proto | e11dd20be3f52198cd6b5982cec1b1373c5f2277 | 77dc50cd784cce6c6d35f0cfc8888c1f91563759 |
refs/heads/master | <file_sep>import React from "react";
function AvengerMovies(props) {
return (
<ul>
{props.movies.map(movie => {
return <li key={movie}>{movie}</li>;
})}
</ul>
);
}
export default AvengerMovies;
<file_sep>import React from "react";
import { Route, Link } from "react-router-dom";
import AvengerDetails from "./AvengerDetails";
import AvengerMovies from "./AvengerMovies";
import "../styles.css";
function AvengerPage(props) {
const id = props.match.params.id;
const avenger = props.avengers.find(avenger => `${avenger.id}` === id);
if (!avenger) return <h1>Loading...</h1>;
return (
<div className="char-page">
<h1>Avengers Page</h1>
<img src={avenger.img} alt={avenger.name} />
<h2>{avenger.name}</h2>
<h4>({avenger.nickname})</h4>
<h3>Films:</h3>
<Link to={`/avengers/${props.match.params.id}/details`}>
Details
</Link>{" "}
<Link to={`/avengers/${props.match.params.id}/movies`}>Movies</Link>
<Route
path="/avengers/:id/details"
render={props => <AvengerDetails description={avenger.description} />}
/>
<Route
path="/avengers/:id/movies"
render={props => <AvengerMovies movies={avenger.movies} />}
/>
</div>
);
}
export default AvengerPage;
<file_sep>import React, { useState, useEffect } from "react";
import { Route, Link } from "react-router-dom";
import Home from "./components/Home";
import AvengersList from "./components/AvengersList";
import AvengerPage from "./components/AvengerPage";
import data from "./data.js";
import "./styles.css";
function App() {
const [avengers, setAvengers] = useState([]);
useEffect(() => {
setAvengers(data);
}, []);
return (
<div className="App">
<nav>
<Link to="/">Home</Link> <Link to="/avengers">Avengers</Link>
</nav>
<Route exact path="/" component={Home} />
<Route
exact
path="/avengers"
render={props => <AvengersList {...props} avengers={avengers} />}
/>
<Route
path="/avengers/:id"
render={props => <AvengerPage {...props} avengers={avengers} />}
/>
</div>
);
}
export default App;
| 3d0564f5b1c696bc94713dc9cd83fa9898c9cfd7 | [
"JavaScript"
] | 3 | JavaScript | MichaelHMods/avengersDone | 9b14dd532d12fbb29539027cf7c7107a26bd7367 | b5b3eed418af6d5b5817df742195e5c8c8a1800b |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using CRUDelicious.Models;
namespace CRUDelicious.Controllers
{
public class HomeController : Controller
{
private MyContext dbContext;
public HomeController(MyContext context)
{
dbContext = context;
}
[HttpGet("")]
public IActionResult Index()
{
Dish[] AllDishes = dbContext.Dishes.ToArray();
Dish[] ReverseDishes = AllDishes.OrderByDescending(dish => dish.CreatedAt).ToArray();
return View(ReverseDishes);
}
[HttpGet("new")]
public IActionResult MakeNewDish()
{
return View("NewDish");
}
[HttpPost("NewDish")]
public IActionResult NewDish(Dish dish)
{
if(ModelState.IsValid)
{
dbContext.Add(dish);
dbContext.SaveChanges();
return RedirectToAction("Index");
}
else
{
return View("NewDish");
}
}
[HttpGet("delete/{dishId}")]
public IActionResult DeleteDish(int dishId)
{
Dish DishToDelete = dbContext.Dishes.SingleOrDefault(dish => dish.DishId == dishId);
dbContext.Dishes.Remove(DishToDelete);
dbContext.SaveChanges();
return RedirectToAction("Index");
}
[HttpGet("edit/{dishId}")]
public IActionResult EditDish(int dishId)
{
Dish DishToEdit = dbContext.Dishes.SingleOrDefault(dish => dish.DishId == dishId);
return View(DishToEdit);
}
[HttpPost("UpdateDish")]
public IActionResult UpdateDish(int dishId, Dish editedDish)
{
if(ModelState.IsValid)
{
editedDish.DishId = dishId;
dbContext.Update(editedDish);
dbContext.Entry(editedDish).Property("CreatedAt").IsModified = false;
dbContext.SaveChanges();
return RedirectToAction("Index");
}
else
{
return View("EditDish", editedDish);
}
}
[HttpGet("{DishId}")]
public IActionResult Dish(int DishId)
{
Dish CurrentDish = dbContext.Dishes.FirstOrDefault(dish => dish.DishId == DishId);
return View(CurrentDish);
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
<file_sep>using System;
using System.ComponentModel.DataAnnotations;
namespace CRUDelicious.Models
{
public class Dish
{
[Key]
public int DishId {get; set;}
[Required (ErrorMessage = "Your dish requires a name")]
[MaxLength(45, ErrorMessage = "Whoah there, that's a really long dish name. Try something 45 characters or less.")]
public string Name {get; set;}
[Required (ErrorMessage = "Someone's gotta make the dish. Who's the chef?")]
[MaxLength(45, ErrorMessage = "I want name, not a dissertation. Keep it 45 characters or less.")]
public string Chef {get; set;}
[Required (ErrorMessage = "Give it a rating!")]
[Range(1,5, ErrorMessage = "Your rating should be between 1 and 5 stars.")]
public int? Tastiness {get; set;}
[Required (ErrorMessage = "It's not diet cheat day! Your dish must have calories!")]
[Range (0, double.PositiveInfinity, ErrorMessage="Your food must have a positive amount of calories.")]
public int? Calories {get; set;}
[Required (ErrorMessage = "Please input a description of the food. Otherwise no one will know what it's like!")]
public string Description {get; set;}
public DateTime CreatedAt {get; set;} = DateTime.Now;
public DateTime UpdatedAt {get; set;} = DateTime.Now;
}
} | c3397553a5eefe2e5d8dcea5cf3c9474e8810159 | [
"C#"
] | 2 | C# | ralumbaugh/CRUDelicious | 712a3b0ee0cd64cbfd5ee337f90f2d8a405808c1 | 2e2086e80b32f3a7a065137e2c163568c39d99d0 |
refs/heads/master | <repo_name>generalsys/spring-aop-demo<file_sep>/spring-customized/spring-customized-aop/src/main/java/com/baomw/util/ConfigurationUtil.java
package com.baomw.util;
import com.baomw.holder.ProxyBeanHolder;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* 描述:
*
*/
public class ConfigurationUtil {
/**
* aop标识注解类
*/
public static final String AOP_POINTCUT_ANNOTATION
= "com.baomw.annotation.AopJ";
/**
* 前置通知注解类
*/
public static final String BEFORE
= "com.baomw.annotation.BeforeBaomw";
/**
* 后置通知注解类
*/
public static final String AFTER
= "com.baomw.annotation.AfterBaomw";
/**
* 环绕通知注解类
*/
public static final String AROUND
= "com.baomw.annotation.AroundBaomw";
/**
* 存放需代理的全部目标对象类
*/
public static volatile Map<String,List<ProxyBeanHolder>> classzzProxyBeanHolder = new ConcurrentHashMap<>();
}
<file_sep>/spring-customized/spring-customized-aop/src/main/java/com/baomw/selector/CustomizedAopImportSelector.java
package com.baomw.selector;
import com.baomw.processor.RealizedAopBeanPostProcessor;
import com.baomw.processor.RegisterBeanFactoryPostProcessor;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;
/**
* 描述:
* 自定义aop实现,提交给spring处理的类
*
*/
public class CustomizedAopImportSelector implements ImportSelector {
public String[] selectImports(AnnotationMetadata annotationMetadata) {
return new String[]{RealizedAopBeanPostProcessor.class.getName(),RegisterBeanFactoryPostProcessor.class.getName()};
}
}
<file_sep>/spring-customized/spring-customized-aop/src/main/java/com/baomw/annotation/AroundBaomw.java
package com.baomw.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* 描述:
* 自定义环绕通知处理注解类
*
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface AroundBaomw {
String value() default "";
}
<file_sep>/spring-customized/spring-customized-aop/src/main/java/com/baomw/annotation/AfterBaomw.java
package com.baomw.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* 描述:
* 自定义后置通知注解类
*
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface AfterBaomw {
String value() default "";
}
<file_sep>/spring-customized/spring-aop/src/main/java/com/baomw/test/Test.java
package com.baomw.test;
import com.baomw.config.Appconfig;
import com.baomw.dao.IndexDao;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* ÃèÊö:
*
*/
public class Test {
public static void main(String[] args) {
AnnotationConfigApplicationContext annotationConfigApplicationContext
= new AnnotationConfigApplicationContext(Appconfig.class);
IndexDao indexDao = annotationConfigApplicationContext.getBean(IndexDao.class);
indexDao.query();
System.out.println("");
}
}
| c14fd23042e224614a49cee5a032a6ed63317b96 | [
"Java"
] | 5 | Java | generalsys/spring-aop-demo | 82035cf90937b0c963e88b54a7e5cc38de72080e | ce6d5b0db763026bf5b687c3e3171fa70dc13906 |
refs/heads/master | <repo_name>jordankbartos/file-transfer-sc<file_sep>/ftclient
#!/usr/bin/python3
###############################################################################
## Author: <NAME>
## Date: Februrary 6, 2020
## Class: CS 372-400 W2020
## Program: chatserve
## Description: This is the "server" end of the chat system. This program must
## be started on a certain port number for the chatclient to connect to. Once
## a connection is made, the two programs become peers and may exchange
## messages between them.
## Input:
## argv[1]: port number to begin the server on
##
## note: this program attempts to earn extra credit by allowing asynchronous
## sending/receiving of data over the TCP connection by use of SIGIO signals.
## This allows each user to send multiple messages at a time and to receive
## a message at any time.
###############################################################################
import threading
from socket import *
import sys
import os
import random
import signal
import fcntl
import time
#source for threading: https://www.geeksforgeeks.org/multithreading-python-set-1/
command = ""
file_name = ""
def parse_cl_args():
"""
Description: this function parses the command line arguments passed
to ftclient. It throws an exception if server_port or client_port
are not integers
Input: none
Output: none
Preconditions: either 4 or 5 command line arguments must be passed
into ftclient. They must be:
- argv[1] - server name, the name of the host running ftserver
- argv[2] - the server port number at which ftserver is listening
- argv[3] - the port number for ftclient to listen for the response
- argv[4] - the command to be sent to ftserver. Either -l for list
-g for get
-c for cd
- argv[5] - the file name for ftserver to return if command is -g
Postconditions: variables command, file_name, server_port, cient_port, and
server_name are populated with the corresponding arguments
"""
global file_name
global command
server_name = sys.argv[1]
server_port = int(sys.argv[2])
client_port = int(sys.argv[3])
command = sys.argv[4]
if len(sys.argv) > 5:
file_name = sys.argv[5]
else:
file_name = ""
return server_name, server_port, client_port, command, file_name
def build_message(command, file_name, listen_port):
"""
Description: builds the string to send to ftserver formatted in a way that
ftserver can interpret.
Input:
- command - the command to send to ftserver
- file_name - the name of the file to request from ftserver
- listen_port - the port number than ftclient will listen on for
a response from ftserver
Output: a string, formatted for sending to ftserver
"""
return command + "#" + file_name + "#" + str(listen_port) + "#"
def start_connection_p(server_host, server_port, command, file_name):
"""
Description: Opens a socket and connects to ftserver at server_host on
server_port. It then sends the request to ftserver and listens for a
response.
Input:
- server_host - the name of the host ftserver is running on
- server_port - the port number ftserver is listening on
- command - the command to send to ftserver. Should be -g, -l, or -c
- file_name - the name of the file to request if command is -g
Output:
- none
Preconditions:
- ftserver is listening for connections on server_host at server_port
Sources cited:
socket connection code source: https://docs.python.org/3/howto/sockets.html
"""
try:
connection_p = socket(AF_INET, SOCK_STREAM)
connection_p.connect((server_host, server_port))
except:
print("An exception occured in establishing connection P")
exit(1)
request_message = build_message(command, file_name, client_port)
connection_p.send(request_message.encode(encoding='utf-8'))
message_in = None
while(message_in != ""):
message_in = connection_p.recv(1024).decode(encoding='utf-8')
print(message_in, end="")
connection_p.close()
def open_connection_q(client_port):
"""
Description: Opens a socket and binds it to listen for a connection from
ftserver
"""
socket_Q = socket(AF_INET, SOCK_STREAM)
try:
socket_Q.bind(('', client_port))
except:
print("An error occured in binding socket for connection Q.")
exit(1)
return socket_Q
def get_file(file_name):
file_prefix, file_extension = file_name.split(".")[0], file_name.split(".")[1:]
if file_extension:
file_extension = "." + ".".join(file_extension)
else:
file_extension = ""
suffix = 1
if os.path.exists(file_name):
print(file_name, "already exists.")
while os.path.exists(file_prefix + "_" + str(suffix) + file_extension):
suffix += 1
print("Writing to", file_prefix + "_" + str(suffix) + file_extension, "instead...")
file_name = file_prefix + "_" + str(suffix) + file_extension
return file_name
def listen_q(socket_q):
"""
Description: this function runs connection q while it is open. If the
command sent was -g, then it saves the data it receives into a new
file named file_name. If the command was -l, then it expects text that
should be displayed to the screen.
Input: socket_q, the socket object that receives the connection from
ftserver
Output: none
"""
# pull command and file_name from the global space
global command
global file_name
# listen for incoming connections
socket_q.listen(5)
connect_q, address = socket_q.accept()
# when a connection is received, either save the data received to a file
# or display to screen depending on the command
msg = None
if command == "-g":
# open a new file in binary mode
file_name = get_file(file_name)
if file_name:
new_file = open(file_name, "w+b")
else:
return
total_bytes = 0
while True:
# read bytes and save them to the file
msg = connect_q.recv(1024)
if not msg:
break;
received = bytearray(msg)
new_file.write(received)
total_bytes += len(received)
new_file.close()
if total_bytes == 0:
print("0 Bytes received:", file_name, "was not created.")
os.remove(file_name)
print("File transfer complete.")
else:
# read characters and print them to screen
while not msg == "":
msg = connect_q.recv(1024).decode('utf-8')
print(msg, end="")
connect_q.shutdown(SHUT_RDWR)
connect_q.close()
def start_connection_q(client_port):
"""
Description: This function creates a socket for connection Q and then runs the
socket, accepting a connection and displaying/saving the data received on
that socket
Input: client_port - the port number on which to listen for connections
Output: none
"""
socket_q = open_connection_q(client_port)
listen_q(socket_q)
socket_q.shutdown(SHUT_RDWR)
socket_q.close()
if __name__ == "__main__":
"""
Description: this is the main function of the chatserver. It opens a socket
for receiving connections on and listens on that socket. When a connection
is made, the program conducts a chat between the connected client and the
server, alternately receiving and sending messages. When either user sends
'\quit', the connection is broken and chatserver resumes listening for new
connections.
Input:
argv[1] - the port number upon which chatserver will listen for connections
Output:
none
"""
server_host, server_port, client_port, command, file_name = parse_cl_args()
if (command == "-g" or command == "-c") and not file_name:
print("The", command, "command requires a file or folder name be supplied")
else:
threads = []
p_thread = threading.Thread(target=start_connection_p, args=(server_host, server_port, command, file_name,))
q_thread = threading.Thread(target=start_connection_q, args=(client_port,))
threads.append(p_thread)
threads.append(q_thread)
q_thread.start()
p_thread.start()
p_thread.join()
q_thread.join()
print("")
<file_sep>/makefile
# Author: <NAME>
# Date: February 4, 2020
# file: makefile
# Description: this is the makefile instructions for compiling the ftserver program
ftserver: ftserver.o
gcc -g -Wall -o ftserver ftserver.o
ftserver.o: ftserver.c
gcc -c -g -Wall ftserver.c
clean:
rm ftserver.o ftserver
debug:
make
valgrind -v --leak-check=full --show-leak-kinds=all ./ftserver $(port)
<file_sep>/README.md
Author: <NAME>
Date: February 21, 2020
File: README.md
This file contains instructions for compiling and running ftserver and ftclient programs
# Extra Credit
This implementation of ftserver and ftclient attempts to earn extra credit for the following features:
1. ftclient is multi-threaded. There are separate threads that handle connection P and connection Q
2. The client can change the working directory of the server. The command for this is -c for example, `./ftclient <ftserver host> <ftserver port> <data port> -c <directory_name>` will change the working directory of ftserver to <directory_name> if it is a valid name. If it is invalid, an error message is returned on connection P
3. This implementation of fterver/ftclient can transfer binary as well as text files.
# ftserver
The ftserver program is written in C. It receives requests from ftclient, processes the requests, and attempts to carry out the requested action. If an error is encountered, information about it is returned to ftclient on connection Q. To terminate ftserver, issue a SIGINT to the process with Ctrl+C.
### Compilation instructions and use of makefile
| MAKE COMMAND | RESULT |
| ---------------------------- | -------------------------------------------------------------- |
| `make` | compiles ftserver from source code |
| `make debug port=<portnum>` | re-compiles ftserver and runs it with valgrind on port=portnum |
| `make clean` | removes executable and .o files for ftserver |
### Execution
To run ftserver once it is compiled, issue the command `./ftserver <portnum>` where portnum is the port on which ftserver will listen for incoming connections.
# ftclient
### Compilation
The ftclient program is written as a Python script. If ftclient has execute permissions it can be run directly. If it does not have execute permissions, it must be invoked with an instance of python3.
### Execution
The command to execute ftclient takes one of these two forms:
1. `./ftclient <server_host> <server_port> <client_port> <command> <file_name>`
2. `python3 ftclient <server_host> <server_port> <client_port> <command> <file_name>`
### Command line arguments
The arguments to ftclient must be supplied in the order specified above. They are:
| ARGUMENT | DESCRIPTION |
| ----------- | ------------------------------------------------------------------------------------------------------------------ |
| sever_host | the hostname of the machine ftserver is running on. This can be the name of the host or the IP address of the host |
| server_port | the port number ftserver is listening for incoming connections on |
| client_port | the port number on which ftclient should listen for incoming data connections from ftserver |
| command | the command code for the interaction with ftserver |
| file_name | the file or directory name for the interaction with ftserver |
### Possible commands
| COMMAND | RESULT |
| ------- | ---------------------------------------------------------------------------------------------- |
| `-l` | list the regular files in ftserver's current working directory |
| `-la` | list all files and directories (including hidden ones) in ftserver's current working directory |
| `-c` | change ftserver's current working directory to `<file_name>` |
| `-g` | get `<file_name>` from ftserver to ftclient |
<file_sep>/ftserver.c
/*******************************************************************************
fork_connection_q(client_port)
* Name: <NAME>
* Last Modified: Feb 6, 2020
* File: chatclient.c
* Course: CS-372-400 W2020
* Description: this program runs from the command line. It connects to the
* chatserver program and forms a TCP connection. Once a connection is formed,
* the two end systems become peers and can exchange messages back and forth.
* Messages entered on one end are displayed on the other end and vice versa.
* The parts of this program that handle the TCP connection are adapted from
* my CS344 OTP assignment, which in turn was adapted from <NAME>'s
* CS344 lecture materials.
* Input:
* argv[1] - name of host that chatserver is running on
* argv[2] - port number that chatserver is listening on
*
* note: this program attempts to earn extra credit by allowing asynchronous
* sending/receiving of data over the TCP connection by use of SIGIO signals.
* This allows each user to send multiple messages at a time and to receive
* a message at any time.
*******************************************************************************/
#include <sys/types.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <errno.h>
#include <dirent.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/stat.h>
#include <arpa/inet.h>
#include <netdb.h>
#define TRUE 1
#define FALSE 0
#define MAX_PORT_NUMBER 65535
#define MIN_PORT_NUMBER 1
#define BUFFER_LENGTH 1024
#define MAX_COMMAND_LENGTH 10
#define MAX_FILE_NAME_LENGTH 255
#define LIST_CODE 5322345
#define TRANSFER_CODE 9912349
#define CD_CODE 126649
char LIST_ALL_COMMAND[4] = "-la";
char LIST_COMMAND[3] = "-l";
char TRANSFER_COMMAND[3] = "-g";
char MESSAGE_DIVIDER = '#';
char CD_COMMAND[3] = "-c";
int SHOW_HIDDEN = FALSE;
//global variables for signal-handler exit
char* sendString;
char* buffer;
/*******************************************************************************
* void validateArgs(int argc, char* argv[])
* Description: ensures that the supplied command-line arguments to this program
* are valid. There should only be one argument, a port number on which to run
* the server. It must be an integer between 1 and 65535
* Input:
* int argc - the number of arguments supplied to the process
* char* argv[] - an array of pointers to char containing the passed-in
* arguments
* Output:
* none
* Postconditions: the program is terminated if the arguments are invalid.
* Otherwise, execution continues normally
*******************************************************************************/
void validateArgs(int argc, char* argv[]) {
if (argc != 2) {
fprintf(stderr, "ERROR: %d arguments supplied. Expected 1\n", argc -1);
exit(1);
}
int portNumber = atoi(argv[1]);
if (portNumber < MIN_PORT_NUMBER || portNumber > MAX_PORT_NUMBER) {
fprintf(stderr, "ERROR: %s is not a valid port number.\n", argv[1]);
exit(1);
}
}
/*******************************************************************************
* void catchSIGINT(int sigNumber)
* Description: This function is the SIGINT handler. It frees dynamically
* allocated memory and terminates the process
* Input: sigNumber - the signal number that caused the interrupt
* Output: none
* Preconditions: the process receives a SIGINT from the user
* Postconditions: the process exits gracefully
*******************************************************************************/
void catchSIGINT(int sigNumber){
// free all dynamically allocated memory
free(sendString);
free(buffer);
exit(0);
}
/*******************************************************************************
* void catchSIGPIPE(int sigNumber)
* Description: This function is the signal handler for the SIGPIPE signal that
* arrives when ftclient shuts down before closing one/both of the connections
* Input: sigNumber - the signal number that caused the interrupt
* Output: None
* Preconditions: the process receives a SIGIO due to a prematurely closed
* connection
* Postconditions: the process exits gracefully
*******************************************************************************/
void catchSIGPIPE(int sigNumber){
// free all dynamically allocated memory
fprintf(stderr, "sigpipe encountered\n");
free(buffer);
free(sendString);
exit(3);
}
/*******************************************************************************
* void setSignalHandler()
* This code is adapted from my CS344 smallsh program (assignment 3). And that
* code was adapted from CS344 lectures in block 3 by <NAME>
*
* Description: this function sets up the signal handler for SIGINT and SIGIO
* Input: None
* Output: None
* Preconditions: None
* Postconditions: The process has signal handlers in place that will catch
* SIGINT and SIGPIPE signals and handle them accordingly
*******************************************************************************/
void setSignalHandler() {
// SIGINT
struct sigaction SIGINT_action = {{0}};
SIGINT_action.sa_handler = catchSIGINT;
sigfillset(&SIGINT_action.sa_mask);
SIGINT_action.sa_flags = 0;
sigaction(SIGINT, &SIGINT_action, NULL);
//SIGPIPE
struct sigaction SIGPIPE_action = {{0}};
SIGPIPE_action.sa_handler = catchSIGPIPE;
sigfillset(&SIGPIPE_action.sa_mask);
SIGPIPE_action.sa_flags = 0;
sigaction(SIGPIPE, &SIGPIPE_action, NULL);
}
/*******************************************************************************
* void activateListenSocket(int*, int*, struct sockaddr_in*)
* Sources cited: The code for this function is adapted from my CS344 OTP
* project, and the code for that was adapted from lecture materials for CS344
* provided by <NAME>
*
* Description: This function creates, binds, and activates a socket for
* connection P.
* Input:
* int* listenSocketFD - pointer to int that will hold the file descriptor for
* connection P
* int* portNumber - pointer to int that holds the port number to listen on
* struct sockaddr_in* - pointer to a struct sockaddr_in that will be
* populated with the data needed to open/run the socket
* Output:
* none
* Preconditions: none
* Postconditions: ftserver is listening on a socket, connection P, for incoming
* connections from ftclient
*******************************************************************************/
void activateListenSocket(int* listenSocketFD,
int* portNumber,
struct sockaddr_in* serverAddress) {
/* All socket programming code is adapted from my CS344 OTP assignment which
was, in turn, adapted from <NAME>'s CS344 lectures */
/* set up the address struct for the server socket */
memset((char*)serverAddress, '\0', sizeof(*serverAddress));
serverAddress->sin_family = AF_INET;
serverAddress->sin_port = htons(*portNumber);
serverAddress->sin_addr.s_addr = INADDR_ANY;
/* set up the socket */
*listenSocketFD = socket(AF_INET, SOCK_STREAM, 0);
if (listenSocketFD < 0) {
fprintf(stderr, "ERROR opening socket\n");
exit(1);
}
/* attempt to bind the socket for listening for connections */
if (bind(*listenSocketFD, (struct sockaddr*)serverAddress, sizeof(*serverAddress)) < 0) {
fprintf(stderr, "ERROR on binding socket\n");
exit(1);
}
listen(*listenSocketFD, 5);
}
/*******************************************************************************
* void openConnectionQ(char*, int)
* Sources cited: The code for this function is adapted from my CS344 OTP
* project, and the code for that was adapted from lecture materials for CS344
* provided by <NAME>
*
* Description: This function creates, binds, and activates a socket for
* connection Q. It then connects the socket to the listening ftclient process
* and returns the socket connection file descriptor
* Input:
* char* clientName - the host name or IP address of the ftclient
* int portNumber - the port number that client is listening on
*******************************************************************************/
int openConnectionQ(char* clientName, int clientPort) {
struct sockaddr_in clientAddress;
struct hostent* clientInfo;
// populate the client address sockaddr_in struct with the correct data
memset((char*)&clientAddress, '\0', sizeof(clientAddress));
clientAddress.sin_family = AF_INET;
clientAddress.sin_port = htons(clientPort);
clientInfo = gethostbyname(clientName);
if (clientInfo == NULL) {
fprintf(stderr, "ERROR: Could not connect to client on connection Q\n");
exit(2);
}
memcpy((char*)&clientAddress.sin_addr.s_addr, (char*)clientInfo->h_addr, clientInfo->h_length);
// create a socket
int socketFD = socket(AF_INET, SOCK_STREAM, 0);
if (socketFD < 0) {
fprintf(stderr, "ERROR: Could not open socket connection Q\n");
exit(2);
}
// use the socket and clientAddress struct to open a TCP connection to ftclient
// on connection Q
if (connect(socketFD, (struct sockaddr*)&clientAddress, sizeof(clientAddress)) < 0) {
fprintf(stderr, "ERROR: Could not connect on socket connetion Q\n");
fprintf(stderr, "%d: %s\n", errno, strerror(errno));
exit(2);
}
return socketFD;
}
/*******************************************************************************
* void parseCommands(char* buffer, char* command, char* fileName)
* Description: This function parses the commands that were sent from the client
* process. It sets command and fileName to point to their respective
* information
* Input:
* - char* buffer - this is a pointer to a char array that contains the string
* of characters received from the client process
* - char** command - this is a pointer to an uninitialized char*
* - char** fileName - a pointer to an uninitialized char*
* Output:
* - none
* Preconditions:
* - buffer points to an array of characters received from client
* Postconditions:
* - the contents of buffer are modified to create 2 sub-strings as follows:
* - *command points to the command that was sent
* - *fileName points to the fileName that was sent
* - Instances of MESSAGE_DIVIDER that are encountered are replaced with '\0'
*******************************************************************************/
void parseCommands(char* buffer, char** command, char** fileName, int* qClientPort) {
char* curr = buffer;
*command = buffer;
*fileName = NULL;
char* qClientPortStr = NULL;
while(*curr != '\0') {
if (*curr == MESSAGE_DIVIDER) {
if (*fileName == NULL) {
*curr = '\0';
*fileName = curr + 1;
}
else if (qClientPortStr == NULL){
*curr = '\0';
qClientPortStr = curr + 1;
}
else {
*curr = '\0';
}
}
curr += 1;
}
*qClientPort = atoi(qClientPortStr);
}
/*******************************************************************************
* int getCommandCode(char* command)
* Description: analyzes the command received from ftclient and determines
* whether the command is -l (list) or -g (get) or -c (cd)
* Input: char* command - a c-string containing the entire message recieved from
* ftclient
* Output: the integer code for the given command
* Preconditions: a message was received that contains a valid command from
* ftclient
* Postconditions: none
*******************************************************************************/
int getCommandCode(char* command) {
if(strcmp(command, TRANSFER_COMMAND) == 0) {
return TRANSFER_CODE;
}
if(strcmp(command, LIST_COMMAND) == 0) {
SHOW_HIDDEN = FALSE;
return LIST_CODE;
}
if(strcmp(command, LIST_ALL_COMMAND) == 0) {
SHOW_HIDDEN = TRUE;
return LIST_CODE;
}
if(strcmp(command, CD_COMMAND) == 0) {
return CD_CODE;
}
return -1;
}
/*******************************************************************************
* void sendDirectoryContents(int, int, char*, int)
* Sources cited: https://www.geeksforgeeks.org/c-program-list-files-sub-directories-directory/
*
* Description: This function sends a listing of the files in the current
* directory to ftclient on connection Q
* Input:
* int connectionP_FD - the file descriptor for the connection P socket
* int connectionQ_FD - the file descriptor for the connection Q socket
* char* clientIP - a c-string containing the host name or IP address of
* the host machine that ftclient is running on
* int clientPort - the port number that ftclient is listening on for
* connection Q
* Output:
* none
*******************************************************************************/
void sendDirectoryContents(int connectionP_FD, int connectionQ_FD, char* clientIP, int clientPort, int hostPort) {
printf("List directory requested on port %d\n", hostPort); fflush(stdout);
// open directory information
struct dirent* directoryEntry;
DIR *dir = opendir(".");
// get a safe amount of memory for filenames
sendString = malloc(sizeof(char) * (MAX_FILE_NAME_LENGTH + 512));
memset(sendString, '\0', MAX_FILE_NAME_LENGTH + 512);
if(dir == NULL) {
strcpy(sendString, "Error opening directory");
send(connectionP_FD, sendString, strlen(sendString), 0);
}
else {
printf("Sending directory contents to %s:%d\n", clientIP, clientPort); fflush(stdout);
// read the name of each file or directory in turn
while((directoryEntry = readdir(dir)) != NULL) {
memset(sendString, '\0', MAX_FILE_NAME_LENGTH + 512);
strcpy(sendString, directoryEntry->d_name);
if(directoryEntry->d_type == DT_DIR) {
strcat(sendString, "/");
}
// don't send hidden files or . and ..
if(SHOW_HIDDEN || sendString[0] != '.') {
sendString[strlen(sendString)] = '\n';
// send the name of the directory/file
send(connectionQ_FD, sendString, strlen(sendString), 0);
}
}
// close the directory
closedir(dir);
// close the connection
close(connectionQ_FD);
}
free(sendString);
sendString = NULL;
}
int min(int a, int b) {
if (a < b) {
return a;
}
return b;
}
/*******************************************************************************
* void sendFile(int, int, char*, int, int)
* sources cited: https://www.programmingsimplified.com/c-program-read-file
* https://stackoverflow.com/questions/25634483/send-binary-file-over-tcp-ip-connection
*
* Description: this function reads a file and sends it over connection Q to
* ftclient
* Input:
* int connectionP_FD - the file descriptor for connection P
* int connectionQ_FD - the file descriptor for connection Q
* char* filename - the name of the file to be sent
* char* clientiP - the IP address of the client
* int clientPort - so it can be displayed
* int hostPort - so it can be displayed
* Output:
* none
* Preconditions:
* - connectionP and connectionQ have been established
* - a file by the name of filename exists in the current directory
* Postconditions:
* - filename is sent over connectionQ to ftclient
*******************************************************************************/
void sendFile(int connectionP_FD, int connectionQ_FD, char* filename, char* clientIP, int clientPort, int hostPort){
printf("File \"%s\" requested on port %d.\n", filename, hostPort);
fflush(stdout);
FILE* filePtr;
// open the file to be sent in read/binary mode
filePtr = fopen(filename, "r+b");
// send an error message if the file cannot be sent
if(filePtr == NULL) {
printf("Requested file not found. Sending error message to %s:%d\n", clientIP, hostPort);
fflush(stdout);
char* errorMsg = "File not found\n";
send(connectionP_FD, errorMsg, strlen(errorMsg), 0);
}
// otherwise send the file in chunks until it's all sent
else {
fseek(filePtr, 0, SEEK_END);
long filesize = ftell(filePtr);
printf("Sending \"%s\" (%ld Bytes) to %s:%d\n", filename, filesize, clientIP, clientPort);
fflush(stdout);
rewind(filePtr);
if (filesize == EOF) {
fprintf(stderr, "ERROR: file read error\n");
exit(1);
}
if (filesize > 0) {
do {
size_t sendAmt = min(filesize, BUFFER_LENGTH);
sendAmt = fread(buffer, 1, sendAmt, filePtr);
int notSent = sendAmt;
unsigned char* sendPtr = (unsigned char*)buffer;
while (notSent > 0) {
int sent = send(connectionQ_FD, sendPtr, notSent, 0);
notSent -= sent;
sendPtr += sent;
}
filesize -= sendAmt;
}while(filesize > 0);
}
fclose(filePtr);
}
}
void sendError(int connectionP_FD, char* message) {
int num_bytes = strlen(message);
while (num_bytes > 0) {
int sent = send(connectionP_FD, message, strlen(message), 0);
num_bytes -= sent;
message += sent;
}
}
/*******************************************************************************
* void processClientRequest(int, char*)
* Description: This is the jumping off point once a command has been received
* from ftclient. This function determines what the command is, connects
* on connection Q, determines what data should be sent back and begins the
* transfer accordingly
* Input:
* int connectionP_FD - the file descriptor for connection P
* char* clientIP - the hostname or IP address that ftclient is running on
* int hostPort - the host port number for displaying status messages
* Output: none
* Preconditions: ftclient has connected on connection P and has sent a message
* string to ftserver
* Postconditions: the rest of the actions dictated by the command sent from
* ftclient have been handled
*******************************************************************************/
void processClientRequest(int connectionP_FD, char* clientIP, int hostPort) {
/* allocate memory for buffer, and create variables for command and file name */
char* command;
char* fileName;
int charsRead,
commandCode,
clientPort,
connectionQ_FD;
memset(buffer, '\0', BUFFER_LENGTH);
charsRead = recv(connectionP_FD, buffer, BUFFER_LENGTH, 0);
if (charsRead <= 0) {
exit(1);
}
parseCommands(buffer, &command, &fileName, &clientPort);
connectionQ_FD = openConnectionQ(clientIP, clientPort);
commandCode = getCommandCode(command);
switch (commandCode) {
case TRANSFER_CODE:
sendFile(connectionP_FD, connectionQ_FD, fileName, clientIP, clientPort, hostPort);
break;
case LIST_CODE:
sendDirectoryContents(connectionP_FD, connectionQ_FD, clientIP, clientPort, hostPort);
break;
case CD_CODE:
printf("Change directory request received from %s:%d\n", clientIP, hostPort);
fflush(stdout);
if(chdir(fileName) != 0) {
printf("Error switching to requested directory. Sending error message to %s:%d\n", clientIP, hostPort);
fflush(stdout);
sendError(connectionP_FD, "Error changing directory");
}
else {
printf("Working directory changed to %s\n", fileName);
fflush(stdout);
}
break;
default:;
char errorMsg[16] = "Invalid command";
send(connectionP_FD, errorMsg, strlen(errorMsg), 0);
break;
}
close(connectionP_FD);
close(connectionQ_FD);
}
/*******************************************************************************
* int main(int argc, char* argv[])
* Description: this is the main function that runs ftserver. It takes a port
* number passed in fromt he command line and opens a socket, listening on the
* supplied port number. When it recieves a connection, it runs the ft
* protol as specified in Programming Assignment #2 CS372
*
* Input:
* -argv[1] - the port number that ftserver will listen on for incoming
* connections
* Output:
* - no output. The server transfers files over a TCP connection to a client
* program
* - returns 0 upon successful completion of the program
*******************************************************************************/
int main(int argc, char *argv[])
{
/* variables */
int listenSocketFD,
connectionP_FD,
portNumber;
socklen_t sizeOfClientInfo;
struct sockaddr_in serverAddress, clientAddress;
char* clientIP;
buffer = (char*)malloc(sizeof(char) * BUFFER_LENGTH);
assert(buffer != NULL);
/* validate argument and get port number*/
validateArgs(argc, argv);
setSignalHandler();
portNumber = atoi(argv[1]);
/* activate the socket */
activateListenSocket(&listenSocketFD, &portNumber, &serverAddress);
sizeOfClientInfo = sizeof(clientAddress);
/* run the serer */
while(TRUE) {
printf("\nServer open on port %d\n", portNumber);
fflush(stdout);
connectionP_FD = accept(listenSocketFD,
(struct sockaddr*) &clientAddress,
&sizeOfClientInfo);
/* Source for getting clientIP address from an established connection
https://stackoverflow.com/questions/4282369/determining-the-ip-address-
of-a-connected-client-on-the-server
*/
clientIP = inet_ntoa(clientAddress.sin_addr);
printf("Connection from %s\n", clientIP);
fflush(stdout);
if(connectionP_FD < 0) {
fprintf(stderr, "ERROR on accepting incoming connection.\n");
exit(1);
}
else {
processClientRequest(connectionP_FD, clientIP, portNumber);
}
}
return 0;
}
| 868f4ae368f809013c13e114728213a7b0c997e4 | [
"Markdown",
"C",
"Python",
"Makefile"
] | 4 | Python | jordankbartos/file-transfer-sc | 92b608d47f1bc630330070e8dc16813fc86080a5 | 05f94fa7d349960c22d98956d42286fe19da9b36 |
refs/heads/main | <file_sep>/**
*
*/
package com.ss.sb.dto;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.ss.sb.de.User;
/**
* @author heman
*
*/
@Repository
public interface UserRepository extends CrudRepository<User, Integer> {
}
<file_sep>/**
*
*/
package com.ss.sb.de;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
/**
* @author heman
*
*/
/*
* User needs to verify himself with username and password before viewing
* accounts.
*/
/*
* When creating an account the user needs to give the following info: email,
* address, occupation, initial deposit (account's starting balance).
*/
@Entity
@Table(name = "user")
@Data
public class User {
@Id
private int user_id;
@Column(name = "username")
private String username;
@Column(name = "<PASSWORD>")
private String password;
@Column(name = "first_name")
private String first_name;
@Column(name = "last_name")
private String last_name;
@Column(name = "email")
private String email;
@Column(name = "occupation")
private String occupation;
/**
* @return the occupation
*/
public String getOccupation() {
return occupation;
}
/**
* @param occupation the occupation to set
*/
public void setOccupation(String occupation) {
this.occupation = occupation;
}
/**
* @return the user_id
*/
public int getUser_id() {
return user_id;
}
/**
* @param user_id the user_id to set
*/
public void setUser_id(int user_id) {
this.user_id = user_id;
}
/**
* @return the username
*/
public String getUsername() {
return username;
}
/**
* @param username the username to set
*/
public void setUsername(String username) {
this.username = username;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password the password to set
*/
public void setPassword(String password) {
this.password = <PASSWORD>;
}
/**
* @return the first_name
*/
public String getFirst_name() {
return first_name;
}
/**
* @param first_name the first_name to set
*/
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
/**
* @return the last_name
*/
public String getLast_name() {
return last_name;
}
/**
* @param last_name the last_name to set
*/
public void setLast_name(String last_name) {
this.last_name = last_name;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User [user_id=" + user_id + ", username=" + username + ", password=" + <PASSWORD> + ", first_name="
+ first_name + ", last_name=" + last_name + ", email=" + email + ", occupation=" + occupation + "]";
}
}
<file_sep>/**
*
*/
package com.ss.sb.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import com.ss.sb.dao.AccountDAO;
import com.ss.sb.dao.AccountTypeDAO;
import com.ss.sb.dao.UserDAO;
import com.ss.sb.de.Account;
import com.ss.sb.de.AccountType;
import com.ss.sb.de.User;
import ch.qos.logback.classic.Logger;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
/**
* @author heman
*
*/
@Service
@Slf4j
public class AccountService {
@Autowired
AccountDAO adao;
@Autowired
UserDAO udao;
@Autowired
AccountTypeDAO atdao;
public List<Account> getAllAccounts() {
List<Account> accounts = new ArrayList<>();
adao.findAll().forEach(accounts::add);
List<Account> activeaccounts = new ArrayList<>();
for(Account a: accounts) {
if(a.isActive()) {
activeaccounts.add(a);
}
}
return activeaccounts;
}
public List<Account> getAccountsByUser(Integer user_id) {
List<Account> accounts = new ArrayList<>();
if(user_id != null) {
adao.findAll().forEach(accounts::add);
}
List<Account> relevantaccounts = new ArrayList<>();
for(Account a: accounts) {
if((a.getUser().getUser_id() == user_id) && a.isActive()) {
relevantaccounts.add(a);
}
}
return relevantaccounts;
}
public Account createAccount(Account account) {
return adao.save(account);
}
public void deleteAccount(int account_id) {
List<Account> accounts = this.getAllAccounts();
for(Account a: accounts) {
if(a.getAccount_id() == account_id) {
a.setActive(false);
adao.save(a);
System.out.println(a);
}
}
}
}
<file_sep>/**
*
*/
package com.ss.sb.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.ss.sb.de.Transaction;
/**
* @author heman
*
*/
public interface TransactionDAO extends JpaRepository<Transaction, Integer> {
}
<file_sep>/**
*
*/
package com.ss.sb.de;
import javax.persistence.*;
import org.hibernate.annotations.Type;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
/**
* @author heman
*
*/
/*
* An account should display the account type, the account balance, the account
* number, as well as options for transactions and investments. User should also
* be allowed to transfer money between accounts.
*/
@Entity
@Table(name = "account")
@Data
public class Account {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int account_id;
// @Column(name = "transaction_id")
// private int transaction_id;
// @ManyToOne
// @JoinColumn(name = "transaction_id")
// private Transaction transaction;
//
// /**
// * @return the transaction
// */
// public Transaction getTransaction() {
// return transaction;
// }
//
// /**
// * @param transaction the transaction to set
// */
// public void setTransaction(Transaction transaction) {
// this.transaction = transaction;
// }
@Column(name = "investing_id")
private int investing_id;
@ManyToOne
@JoinColumn(name = "account_type_id")
private AccountType account_type;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
@Column(name = "balance")
private double balance;
/**
* @return the balance
*/
public double getBalance() {
return balance;
}
/**
* @param balance the balance to set
*/
public void setBalance(double balance) {
this.balance = balance;
}
/**
* @return the isActive
*/
public Boolean isActive() {
return isActive;
}
/**
* @param isActive the isActive to set
*/
public void setActive(Boolean isActive) {
this.isActive = isActive;
}
@Column(name = "isActive", nullable = false, columnDefinition = "TINYINT(1)")
private Boolean isActive;
/**
* @return the user
*/
public User getUser() {
return user;
}
/**
* @param user the user to set
*/
public void setUser(User user) {
this.user = user;
}
/**
* @return the account_id
*/
public int getAccount_id() {
return account_id;
}
/**
* @param account_id the account_id to set
*/
public void setAccount_id(int account_id) {
this.account_id = account_id;
}
//
// /**
// * @return the transaction_id
// */
// public int getTransaction_id() {
// return transaction_id;
// }
//
// /**
// * @param transaction_id the transaction_id to set
// */
// public void setTransaction_id(int transaction_id) {
// this.transaction_id = transaction_id;
// }
/**
* @return the investing_id
*/
public int getInvesting_id() {
return investing_id;
}
/**
* @param investing_id the investing_id to set
*/
public void setInvesting_id(int investing_id) {
this.investing_id = investing_id;
}
/**
* @return the account_type
*/
public AccountType getAccount_type() {
return account_type;
}
/**
* @param account_type the account_type to set
*/
public void setAccount_type(AccountType account_type) {
this.account_type = account_type;
}
@Override
public String toString() {
return "Account [account_id=" + account_id + ", investing_id=" + investing_id + ", account_type=" + account_type
+ ", user=" + user + ", balance=" + balance + ", isActive=" + isActive + "]";
}
}
<file_sep>/**
*
*/
package com.ss.sb.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.ss.sb.de.AccountType;
/**
* @author heman
*
*/
public interface AccountTypeDAO extends JpaRepository<AccountType, Integer>{
}
<file_sep>/**
*
*/
package com.ss.sb.service;
import java.util.List;
import java.util.stream.Collectors;
import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ss.sb.de.Account;
import com.ss.sb.de.AccountType;
import com.ss.sb.dto.AccountDTO;
import com.ss.sb.dto.AccountRepository;
import com.ss.sb.dto.UserRepository;
/**
* @author heman
*
*/
@Service
public class MapService {
@Autowired
AccountRepository accountrepository;
@Autowired
ModelMapper modelmapper;
public List<AccountDTO> getAllAccounts() {
return ((List<Account>) accountrepository.findAll()).stream().map(this::convertToAccountDTO)
.collect(Collectors.toList());
}
public AccountDTO convertToAccountDTO(Account account) {
modelmapper.getConfiguration().setMatchingStrategy(MatchingStrategies.LOOSE);
AccountDTO aDTO = modelmapper.map(account, AccountDTO.class);
return aDTO;
}
}
<file_sep>
spring.datasource.url= jdbc:mysql://localhost:3306/mydb?allowPublicKeyRetrieval=true&useSSL=false
server.port = 8090
spring.datasource.username= root
spring.datasource.password= <PASSWORD>
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto= update
<file_sep>/**
*
*/
package com.ss.sb.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.ss.sb.de.Account;
/**
* @author heman
*
*/
public interface AccountDAO extends JpaRepository<Account, Integer>{
}
| 5927b65893be1ea66af3d06ac78b33885762e247 | [
"Java",
"INI"
] | 9 | Java | SmoothBankers/SmoothBankAccount | e483a6c78f719c18309bb7f007c71e333545fe3f | 777f0c8c007f17d2d86e4d0c82678f88c03c2811 |
refs/heads/master | <repo_name>Vikasht34/Framework<file_sep>/TestProject/UnitTest1.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using DataAccess.Repository;
using DataEntity;
using DataEntity.DataModelCode;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using ServiceLayer;
namespace TestProject
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void UnitTest1_Test1()
{
IEmployeeRepository emeEmployeeRepository = GetEmployeeRepository();
IEnumerable<Employee> employees = emeEmployeeRepository.GetEmployees();
Assert.AreEqual(1,employees.ToList().Count);
}
[TestMethod]
public void SerVice_Test()
{
IEmployeeService employeeService = GetEmployeeService();
var employee = employeeService.GetEmployeeDtos();
Assert.AreEqual(1, employee.Count);
}
private IEmployeeService GetEmployeeService()
{
Mock<IEmployeeRepository> mock = new Mock<IEmployeeRepository>();
mock.Setup(x => x.GetEmployees()).Returns(GetListOfEmployee());
IEmployeeService employeeService = new EmployeeService(mock.Object);
return employeeService;
}
private IEmployeeRepository GetEmployeeRepository()
{
Mock<DbSet<Employee>> mockDbSetEmployee = MockFactory.CreateDbSetMock(GetListOfEmployee());
Mock<DbModel> dbMock = new Mock<DbModel>();
dbMock.Setup(x => x.Employees).Returns(mockDbSetEmployee.Object);
IEmployeeRepository employeeRepository = new EmployeeRepository(dbMock.Object);
return employeeRepository;
}
private IEnumerable<Employee> GetListOfEmployee()
{
return new List<Employee>
{
new Employee
{
Id = 1,
Name = "Rohan"
}
};
}
}
}
<file_sep>/TestApplication/Models/EmployeeModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Common.DTOS;
namespace TestApplication.Models
{
public class EmployeeModel
{
public List<EmployeeDto> GetEmployeeDtos { get; set; }
}
}<file_sep>/DependencyResolver/DataModule.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataAccess.Repository;
using DataEntity.DataModelCode;
using Ninject.Modules;
using Ninject.Web.Common;
using ServiceLayer;
namespace DependencyResolver
{
public class DataModule : NinjectModule
{
public override void Load()
{
BindRepositories();
}
private void BindRepositories()
{
Bind<IEmployeeRepository>().To<EmployeeRepository>().InRequestScope();
Bind<IDbModel>().To<DbModel>().InRequestScope();
Bind<IEmployeeService>().To<EmployeeService>().InRequestScope();
}
}
}
<file_sep>/WebApi/Controllers/ValuesController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Common.DTOS;
using ServiceLayer;
namespace WebApi.Controllers
{
public class ValuesController : ApiController
{
private IEmployeeService _employeeService;
public ValuesController(IEmployeeService employeeService)
{
_employeeService = employeeService;
}
[HttpGet]
[Route("api/GetEmployee")]
public HttpResponseMessage GetEmployee()
{
List<EmployeeDto> employee = _employeeService.GetEmployeeDtos();
return Request.CreateResponse(employee);
}
//// GET api/values
//public IEnumerable<string> Get()
//{
// return new string[] { "value1", "value2" };
//}
//// GET api/values/5
//public string Get(int id)
//{
// return "value";
//}
//// POST api/values
//public void Post([FromBody]string value)
//{
//}
//// PUT api/values/5
//public void Put(int id, [FromBody]string value)
//{
//}
//// DELETE api/values/5
//public void Delete(int id)
//{
//}
}
}
<file_sep>/DataEntity/DataModelCode/DbModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
namespace DataEntity.DataModelCode
{
public class DbModel : MSTestEntities, IDbModel
{
public DbModel()
{
Database.SetInitializer<MSTestEntities>(null);
}
public DbContext GetDbContext()
{
return (DbContext) this;
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
}
}
<file_sep>/ClientLibrary/IApiConnection.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace ClientLibrary
{
public interface IApiConnection
{
/// <summary>
/// Calls a GET request to the API to return data from the method provided.
/// </summary>
/// <typeparam name="T">Type of object for the JSON to convert into</typeparam>
/// <param name="apiMethodName">Name of the method called in the API</param>
/// <param name="pathParameters">List of optional path parameters to pass</param>
/// <returns>An object converted from JSON by the API</returns>
Task<T> RequestGet<T>(string apiMethodName, params string[] pathParameters);
/// <summary>
/// Calls a POST request to the API to send data to the API and return data from the method provided
/// </summary>
/// <typeparam name="T">Type of object for the JSON to convert into</typeparam>
/// <param name="apiMethodName">Name of the method called in the API</param>
/// <param name="objectToPost">An object that will be converted into JSON to use in the API method</param>
/// <returns>An object converted from JSON by the API</returns>
Task<T> RequestPost<T>(string apiMethodName, object objectToPost);
/// <summary>
/// Calls a GET request to the API to return a response from the server. Should only be used for quick ping-like requests.
/// </summary>
/// <param name="apiMethodName">Name of the method called in the API</param>
/// <returns>An HTTP request from the API</returns>
Task<HttpResponseMessage> RequestGetResponse(string apiMethodName);
/// <summary>
/// Calls a POST request to the API to return response from the server.
/// </summary>
/// <param name="apiMethodName">Name of the method called in the API</param>
/// <param name="objectToPost">An object that will be converted into JSON to use in the API method</param>
/// <returns>An HTTP request from the API</returns>
Task<HttpResponseMessage> RequestPostResponse(string apiMethodName, object objectToPost);
}
}
<file_sep>/APIIIII/Controllers/EmployeeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using ServiceLayer;
namespace APIIIII.Controllers
{
public class EmployeeController : ApiController
{
public IEmployeeService _EmployeeService;
public EmployeeController(IEmployeeService employeeService)
{
_EmployeeService = employeeService;
}
[HttpGet]
[Route("api/GetEmployee")]
public HttpResponseMessage GetEmployee()
{
var x = _EmployeeService.GetEmployeeDtos();
return Request.CreateResponse(x);
}
}
}
<file_sep>/DataAccess/Repository/EmployeeRepository.cs
using System.Collections.Generic;
using System.Linq;
using DataEntity;
using DataEntity.DataModelCode;
namespace DataAccess.Repository
{
public class EmployeeRepository : IEmployeeRepository
{
private readonly IDbModel _dbModel;
public EmployeeRepository(IDbModel dbModel)
{
_dbModel = dbModel;
}
public IEnumerable<Employee> GetEmployees()
{
return _dbModel.Employees.ToList();
}
}
}
<file_sep>/DataEntity/DataModelCode/IDBModel.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataEntity.DataModelCode
{
public interface IDbModel : IDisposable
{
/// <summary>
/// Returns the data model as a DbContext object
/// </summary>
/// <returns></returns>
DbContext GetDbContext();
/// <summary>
///
/// </summary>
/// <returns></returns>
int SaveChanges();
DbSet<Employee> Employees { get; set; }
}
}
<file_sep>/WebApi/App_Start/UnityContainer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DataAccess.Repository;
using ServiceLayer;
using Unity;
namespace WebApi.App_Start
{
public static class UnityContainer
{
public static void ConfigureIocUnityContainer()
{
IUnityContainer container = new Unity.UnityContainer();
RegisterService(container);
DependencyResolver.SetResolver(new UnityResolver(container));
}
private static void RegisterService(IUnityContainer container)
{
container.RegisterType<IEmployeeService, EmployeeService>();
container.RegisterType<IEmployeeRepository, EmployeeRepository>();
}
}
}<file_sep>/TestProject/MockFactory.cs
using Moq;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestProject
{
public class MockFactory
{
public static Mock<DbSet<T>> CreateDbSetMock<T>(IEnumerable<T> elements) where T : class
{
var elementsAsQueryable = elements.AsQueryable();
var dbSetMock = new Mock<DbSet<T>>();
dbSetMock.As<IQueryable<T>>().Setup(m => m.Provider).Returns(elementsAsQueryable.Provider);
dbSetMock.As<IQueryable<T>>().Setup(m => m.Expression).Returns(elementsAsQueryable.Expression);
dbSetMock.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(elementsAsQueryable.ElementType);
dbSetMock.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(elementsAsQueryable.GetEnumerator());
return dbSetMock;
}
public static Mock<DbSet<T>> CreateMockDbSetWithObjects<T>(IEnumerable<T> mockObjects) where T : class, new()
{
Mock<DbSet<T>> mockDbSet = new Mock<DbSet<T>>();
mockDbSet.SetupGet(m => m.Local).Returns(new ObservableCollection<T>(mockObjects));
IQueryable<T> mockComponentsAsQueryable = mockObjects.AsQueryable();
mockDbSet.As<IQueryable<T>>().Setup(m => m.Provider).Returns(mockComponentsAsQueryable.Provider);
mockDbSet.As<IQueryable<T>>().Setup(m => m.Expression).Returns(mockComponentsAsQueryable.Expression);
mockDbSet.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(mockComponentsAsQueryable.ElementType);
mockDbSet.As<IQueryable<T>>().Setup(m => m.GetEnumerator())
.Returns(mockComponentsAsQueryable.GetEnumerator());
mockDbSet.SetupGet(m => m.Add(It.IsAny<T>())).Returns(new T());
return mockDbSet;
}
}
}
<file_sep>/ServiceLayer/EmployeeService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Common.DTOS;
using DataAccess.Repository;
namespace ServiceLayer
{
public class EmployeeService : IEmployeeService
{
private readonly IEmployeeRepository _employeeRepository;
public EmployeeService(IEmployeeRepository employeeRepository)
{
_employeeRepository = employeeRepository;
}
public List<EmployeeDto> GetEmployeeDtos()
{
var x = _employeeRepository.GetEmployees().ToList();
List<EmployeeDto> outDtos = new List<EmployeeDto>();
foreach (var y in x)
{
outDtos.Add(new EmployeeDto
{
Id = y.Id,
Name = y.Name
});
}
return outDtos;
}
}
}
<file_sep>/ServiceLayer/IEmployeeService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Common.DTOS;
namespace ServiceLayer
{
public interface IEmployeeService
{
List<EmployeeDto> GetEmployeeDtos();
}
}
<file_sep>/WebApi/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ServiceLayer;
namespace WebApi.Controllers
{
public class HomeController : Controller
{
private IEmployeeService _employeeService;
public HomeController(IEmployeeService employeeService)
{
_employeeService = employeeService;
}
public ActionResult Index()
{
var x = _employeeService.GetEmployeeDtos();
ViewBag.Title = "Home Page";
return View();
}
}
}
<file_sep>/ClientTest/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ClientLibrary;
using Common.DTOS;
using System.Threading.Tasks;
namespace ClientTest.Controllers
{
public class HomeController : Controller
{
private readonly IApiConnection _apiConnection;
public HomeController(IApiConnection apiConnection)
{
_apiConnection = apiConnection;
}
public async Task<ActionResult> Index()
{
var x = await _apiConnection.RequestGet<List<EmployeeDto>>("GetEmployee");
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}<file_sep>/DataAccess/Repository/IEmployeeRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataEntity;
namespace DataAccess.Repository
{
public interface IEmployeeRepository
{
IEnumerable<Employee> GetEmployees();
}
}
| d31601b593a3ccfcc3cfa733514cef83ea60b55e | [
"C#"
] | 16 | C# | Vikasht34/Framework | 24ab97f214a49d35b98c76e699db6c3e1933ceba | 095a2b6541c510e2d637a3caaa103a8ed22da8f5 |
refs/heads/master | <repo_name>salarsen/Algorithms<file_sep>/slack/algos1/1-9-17_complete.js
// 1/9/2017 INTRO && REVERSE STRING && REMOVE BLANKS
// Reverse String: Implement reverseString(str) that, given a string, returns that string with characters reversed. Given 'creature' return 'erutaerc'. Tempting as it seems, do not use the built in reverse().
console.log(reverseString("creature"));
function reverseString(str){
var new_str = '';
for(var i = str.length - 1; i >= 0; i--){
new_str += str[i];
}
return new_str;
}
// Remove Blanks: Create a function that, given a string, returns all of that string's contents, but without the blanks. If given the string, " Pl ayThat fu nk ymus ic" return "PlayThatfunkyMusic".
// https://vimeo.com/198768506/8009787314
console.log(removeBlanks(" sdfsdf erwer sdfe"));
function removeBlanks(str){
var new_str = '';
for(var i = 0; i < str.length; i++){
if(str[i] !== ' ' || str[i] !== '\t' || str[i] !== '\n'){
new_str += str[i];
}
}
return new_str;
}
<file_sep>/book/ch4/stringslice.js
var test = "testing";
console.log(strsplice(test,2,4));
function strsplice(str,start,end){
var arr = str.split("");
var new_arr = [];
if (start == undefined){
start = 0;
} else if (start < 0){
start = str.length + start;
}
if (end == undefined){
end = str.length - 1;
}
for(var i = start; i <= end; i++){
new_arr.push(arr[i]);
}
return new_arr.join("");
}
<file_sep>/book/ch1/mof6.js
printMof6();
function printMof6(){
var i = 0;
while(i * 6 <= 60000){
console.log(i * 6);
i++;
}
}
<file_sep>/book/ch5/slist_avg.js
function ListNode(value){
return {
val : value,
next : null
}
}
function addBack(list,value){
var obj = ListNode(value);
if(list.head == null){
list.head = obj;
} else {
var node = list.head;
while(node.next != null){
node = node.next;
}
node.next = obj;
}
return list;
}
var myList = { head : null };
addBack(myList,10);
addBack(myList,20);
addBack(myList,0);
addBack(myList,10);
function avg(list){
var sum = 0;
var count = 0;
var runner = list.head;
while(runner != null){
sum = sum+ runner.val;
runner= runner.next;
count++;
}
return sum/count;
}
console.log(avg(myList));
<file_sep>/book/ch2/mostsignificantdigit.js
// most significant digit
function sigFig(num){
//console.log(num);
num = Math.abs(num);
while(num > 9 || num < 1){
if (num >= 10){
num = Math.floor(num / 10);
} else if (num < 1) {
num = num * 10;
} else {
num = Math.floor(num % 10);
}
}
console.log(num);
}
sigFig(12345);
sigFig(67.89);
sigFig(0.00987);
sigFig(-12345);
sigFig(-67.89);
sigFig(-0.00987);
<file_sep>/book/ch1/whatdoyouknow.js
whatdoyouknow("test");
function whatdoyouknow(incoming){
console.log(incoming);
}
<file_sep>/book/ch2/fulldate.js
// function fullDate(daynum){
// var sum = 0;
// for(var i = 1; i <= 12; i++){
// sum += monthToDays(i);
// if(sum >= daynum){
// break;
// }
// }
// sum -= monthToDays(i);
// console.log(weekdayName2(daynum - sum) + ", " + dayToMonth(daynum) + " " + (daynum - sum) + ", 2017");
// }
// fullDate(142);
// function fullDate2(datenum){
// var days = datenum % 365;
// days -= 1;
// var years = (datenum - (datenum % 365))/365;
// var num_leap_days = (years - (years % 4))/4;
// var sum = 0;
// for(var i = 1; i <= 12; i++){
// sum += monthToDays(i);
// if(sum >= days){
// break;
// }
// }
// sum -= monthToDays(i);
//
// // console.log(days);
// // console.log(years);
// // console.log(num_leap_days);
// // console.log(dayToMonth(days - num_leap_days));
// // console.log(days - num_leap_days - sum);
// // console.log(2017 + years);
// console.log(weekdayName2(days + num_leap_days - sum) + ", " + dayToMonth(days - num_leap_days) + " " + (days - num_leap_days - sum) + ", " + (2017 + years));
// }
// fullDate2(8475);
function fullDate3(datenum){
// calculate years passed
var years = (datenum - (datenum % 365))/365;
//calculate number of leap years passed
var numleapdays = 0;
for(var i = 2017; i <= 2017+years; i++){
if(leap_yr(i)){
numleapdays++;
}
}
//check if current year is leap, subtract one from leap days if so since we are working in current year
if(leap_yr(2017+years)){
numleapdays -= 1;
}
//adjust remaining days for leap years passed
var days_remaining = (datenum - numleapdays) % 365;
//calculate how far week is offset. Every year first day of the year shifts by a day, i.e. 2017, the first is a monday, 2017, the first is a tuesday, etc..
var dayoffset = years % 7;
//calculate total days passed non-inclusive of current month
var days_passed = 0;
for(var i = 1; i <= 12; i++){
days_passed += monthToDays(i);
if(days_passed >= days_remaining - 1){
break;
}
}
days_passed -= monthToDays(i); // remove current month to get days in current month passed
//account for leap day if leap year and passed february
if(leap_yr(2017+years) && i > 2){
days_passed += 1;
}
console.log(weekdayName2((((days_remaining - days_passed) % 6) + dayoffset) % 7) + ", " + dayToMonth(days_remaining) + " " + (days_remaining - days_passed) + ", " + (2017+years));
}
fullDate3(139947);
fullDate3(139957);
fullDate3(139977);
fullDate3(139978);
fullDate3(139979);
<file_sep>/book/ch2/characterart.js
// characterArt
function drawLeftChars(num, char){
var starstr = "";
if(num > 75){
return "Your string is bigger than 75 characters!";
} else {
for(var i = 0; i < num; i++){
starstr += char;
}
return starstr;
}
}
console.log(drawLeftChars(60,"t"));
console.log(drawLeftChars(50,"x"));
function drawRightChars(num,char){
var starstr = "";
if(num > 75){
return "Your string is bigger than 75 characters!";
} else {
for(var i = 0; i < 75; i++){
if(i < 75 - num){
starstr += " ";
} else {
starstr += char;
}
}
return starstr;
}
}
console.log(drawRightChars(60,"x"));
function drawCenteredChars(num,char){
var starstr = "";
if(num > 75){
return "Your string is bigger than 75 characters!";
} else {
for(var i = 0; i < 75; i++){
if(i < (75 - num)/2){
starstr += " ";
} else if (i < ((75 - num)/2) + num){
starstr += char;
} else {
starstr += " ";
}
}
return starstr;
}
}
console.log(drawCenteredChars(75,"t"));
console.log(drawCenteredChars(50,"t"));
<file_sep>/git_algos/week_01_arrays/arraysday4.js
//remove negatives
// console.log(removeNegs([2,-1,4,-2,5]));
// function removeNegs(arr){
// var popcnt = 0;
// var temp = 0;
// for(var i = 0; i < arr.length; i++){
// if(arr[i] < 0){
// if(arr[arr.length - 1] >= 0){
// arr[i] = arr[arr.length - 1];
// }
// arr.pop();
// }
// }
// return arr;
// }
//second to last
// console.log(secondToLast([42,true,4,"Liam",7]));
// console.log(secondToLast([42]));
// function secondToLast(arr){
// if(arr.length < 2){
// return null;
// } else{
// return arr[arr.length - 2];
// }
// }
//nth to last
// console.log(nthToLast([5,2,3,6,4,9,7],3));
// function nthToLast(arr,index){
// if (arr.length < index){
// return null;
// } else {
// return arr[arr.length - index];
// }
// }
// second largest
// console.log(secondLargest([42,4,1,Math.PI,7]));
// function secondLargest(arr){
// //find largest first
// var largest = 0;
// var secondlargest = 0;
// if(arr.length < 2){
// return null;
// } else{
// for(var i = 0; i < arr.length; i++){
// if(arr[i] > largest && arr[i] > secondlargest){
// secondlargest = largest;
// largest = arr[i];
// }else if(arr[i] < largest && secondlargest < arr[i]){
// secondlargest = arr[i];
// }
// }
// return secondlargest;
// }
// }
//
//nth largest
// console.log(nthLargest([42,4,1,Math.PI,7],3));
// function nthLargest(arr,nth){
// var findlvl = 0;
// var largest = 0;
// var nthvalue = 0;
// while(findlvl != nth){
// for(var i = 0; i < arr.length; i++){
// if(arr[i] < largest && arr[i] > nthvalue){
// nthvalue = largest;
// largest = arr[i];
// } else if (arr[i] < largest && nthvalue < arr[i]){
// nthvalue = arr[i];
// }
// }
// console.log("findlvl " + findlvl);
// console.log("largest " + largest);
// console.log("nth " + nthvalue);
// findlvl++;
// console.log("findlvl " + findlvl);
// }
// return nthvalue;
// }
<file_sep>/book/ch5/slist_min.js
function ListNode(value){
return {
val : value,
next : null
}
}
function addBack(list,value){
var obj = ListNode(value);
if(list.head == null){
list.head = obj;
} else {
var node = list.head;
while(node.next != null){
node = node.next;
}
node.next = obj;
}
return list;
}
var myList = { head : null }
addBack(myList,10);
addBack(myList,20);
addBack(myList,30);
addBack(myList,-5);
console.log(myList);
function min(list){
var min = 0;
var runner = list.head;
while(runner != null){
if(runner.val < min){
min = runner.val;
}
runner = runner.next;
}
return min;
}
console.log(min(myList));
<file_sep>/book/ch1/accurategrades.js
console.log(accurateGrades(88));
console.log(accurateGrades(61));
function accurateGrades(score){
if(score >= 90){
if(score >= 95){
return "Score: " + score + ". Grade: A";
} else{
return "Score: " + score + ". Grade: A-";
}
}else if(score >= 80){
if(score >= 88){
return "Score: " + score + ". Grade: B+";
} else if(score <= 82){
return "Score: " + score + ". Grade: B-";
} else{
return "Score: " + score + ". Grade: B";
}
}else if(score >= 70){
if(score >= 78){
return "Score: " + score + ". Grade: C+";
} else if(score <= 72){
return "Score: " + score + ". Grade: C-";
} else{
return "Score: " + score + ". Grade: C";
}
}else if(score >= 60){
if(score >= 68){
return "Score: " + score + ". Grade: D+";
} else if(score <= 62){
return "Score: " + score + ". Grade: D-";
} else{
return "Score: " + score + ". Grade: D";
}
} else {
return "Score: " + score + ". Grade: F";
}
}
<file_sep>/slack/algos1/1-19-17.js
// 1/19/2017 LINKED LIST: ADDFRONT && ISEMPTY
// isEmpty: Implement a method for your linked List Class that returns a boolean of whether the list is empty.
// addFront: Implement a method for your linked List Class that, given data, inserts a new Node containg the data at the front of the list.
//
// https://vimeo.com/200297395/595a7c68a1
<file_sep>/platform/linkedlists1/linkedlists-set5.js
function ListNode(value){
return {
val : value,
next : null,
}
}
function addBack(list, value){
var obj = ListNode(value);
if(!list.head){
list.head = obj;
return list;
}
var node = list.head;
while(node.next){
node = node.next;
}
node.next = obj;
return list;
}
function displayList(list) {
var displayStr = "";
var runner = list.head;
while (runner != null) {
if (runner.next != null) {
displayStr = displayStr + runner.val + ", ";
} else {
displayStr = displayStr + runner.val;
}
runner = runner.next;
}
return displayStr;
}
var myList = { head : null };
addBack(myList,11);
addBack(myList,10);
addBack(myList,5);
addBack(myList,3);
addBack(myList,6);
function moveMinToFront(list){
if(!list.head){return null};
var min = list.head;
var temp = null;
var runner = list.head.next;
while(runner){
if(runner.val < min.val){
temp = min;
min = runner;
}
runner = runner.next;
}
temp.next = min.next;
min.next = list.head;
list.head = min;
}
console.log('before',displayList(myList));
moveMinToFront(myList);
console.log('after',displayList(myList));
function moveMaxToFront(list){
if(!list.head) { return null };
var max = list.head;
var temp = null;
var runner = list.head.next;
while(runner.next){
console.log(runner.val);
if(runner.val > max.val){
temp = max;
max = runner;
}
runner = runner.next;
}
//check last
if(max.val > runner.val){
temp.next = max.next;
runner.next = max;
max.next= null;
}
// temp.next = max.next;
// runner = max;
}
moveMaxToFront(myList);
console.log('after max',displayList(myList));
function swapNodes(list,Node1,Node2){
if(!list.head) return null;
console.log('checking first node',list.head.val)
if(list.head.val === Node1.val){
Node2.next = list.head.next;
list.head = Node2;
return true;
}
var runner = list.head;
while(runner.next){
console.log(runner.next.val);
if(runner.next.val === Node1.val){
console.log(`swapping ${Node1.val} with ${Node2.val}`);
Node2.next = runner.next.next;
runner.next = Node2;
return true;
}
runner = runner.next;
}
return false;
}
var Node1 = new ListNode(6);
var Node2 = new ListNode(20);
console.log(swapNodes(myList,Node1,Node2));
console.log(displayList(myList));
var Node3 = new ListNode(30);
console.log(swapNodes(myList, Node3, Node2));
// console.log()<file_sep>/book/ch1/keeplastfew.js
console.log(keepLastFew([2,4,6,8,10],3));
function keepLastFew(arr,x){
console.log("[" + arr + "] " + x);
for(var i = 0; i < x; i++){
arr[i] = arr[arr.length - x + i];
}
arr.length = x;
return arr;
}
<file_sep>/book/ch1/thedojoway.js
theDojoWay();
function theDojoWay(){
for(var i = 1; i <=100; i++){
if(i%5 === 0){
console.log("Coding");
} else {
console.log(i);
}
}
}
<file_sep>/book/ch1/swapcenter.js
console.log(swapCenter([true,42,"Ada",2,"pizza"]));
console.log(swapCenter([1,2,3,4,5,6]));
function swapCenter(arr){
var temp = 0;
for(var i = 0; i < arr.length/2; i++){
if(i%2 ===0){
temp = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = temp;
}
}
return arr;
}
<file_sep>/book/ch4/romanize.js
var a = 349;
var b = 2344;
var c = 1492;
console.log(a + " - " + romanize(a));
console.log(b + " - " + romanize(b));
console.log(c + " - " + romanize(c));
function romanize(num){
var roman = [];
if(num < 4000){
roman.push(romanConv(num - (num % 1000)));
roman.push(romanConv((num % 1000) - (num % 1000 % 100)));
roman.push(romanConv((num % 1000 % 100) - (num % 1000 % 100 % 10)));
roman.push(romanConv(num % 1000 % 100 % 10));
}
return roman.join("");
}
function romanConv(num){
switch (num){
case 3000: return 'MMM'; break;
case 2000: return 'MM'; break;
case 1000: return 'M'; break;
case 900: return 'CM'; break;
case 800: return 'DCCC'; break;
case 700: return 'DCC'; break;
case 600: return 'DC'; break;
case 500: return 'D'; break;
case 400: return 'CD'; break;
case 300: return 'CCC'; break;
case 200: return 'CC'; break;
case 100: return 'C'; break;
case 90: return 'XC'; break;
case 80: return 'LXXX'; break;
case 70: return 'LXX'; break;
case 60: return 'LX'; break;
case 50: return 'L'; break;
case 40: return 'XL'; break;
case 30: return 'XXX'; break;
case 20: return 'XX'; break;
case 10: return 'X'; break;
case 9: return 'IX'; break;
case 8: return 'VIII'; break;
case 7: return 'VII'; break;
case 6: return 'VI'; break;
case 5: return 'V'; break;
case 4: return 'IV'; break;
case 3: return 'III'; break;
case 2: return 'II'; break;
case 1: return 'I'; break;
default: return '';
}
}
<file_sep>/book/ch4/removeshortstrings.js
// remove short strings
var a = ["string","hello","what","hi","cherry"];
console.log(removeShortStrings(a,5));
function removeShortStrings(oldArr,length){
var newArr = [];
for(i = 0; i < oldArr.length; i++){
if(oldArr[i].length > length){
newArr.push(oldArr[i]);
}
}
return newArr;
}
<file_sep>/book/ch2/clockhandangles.js
// clock hand angles
function clockHandAngles(seconds){
// 60 seconds per minute
// 60*60 seconds per hour
// 24 hours per day or 12 hours on clock face
// 7 days per week
var secondHand = seconds % 60;
var minutes = (seconds - secondHand)/60;
var minuteHand = minutes % 60;
var hours = (minutes - minuteHand)/60;
var hourHand = hours % 12;
var days = (hours - hourHand)/12;
var leftoverDays = (days/2) % 7;
var weeks = ((days/2) - leftoverDays)/7;
console.log("Day hand: " + ((leftoverDays/7)*360 + (hourHand/12/7)*360 + (minuteHand/60/12/7)*360 + (secondHand/60/12/60/7)*360));
console.log("Hour hand: " + ((hourHand / 12)*360 + ((minuteHand/60)/12)*360 + ((secondHand/60)/12/60*360)) + " degs");
console.log("Minute hand: " + ((minuteHand/60)*360 + (secondHand/60/60)*360) + " degs");
console.log("Second hand: " + ((secondHand/60)*360) + " degs");
}
clockHandAngles(3600);
clockHandAngles(119730);
clockHandAngles(604800 + 89400);
<file_sep>/book/ch4/removeevenlengthstrings.js
// remove even length strings
var a = ["Nope!","Its","Kris","starting","with","K!","(instead","of","Chris","with","C)","."];
console.log(removeEven(a));
function removeEven(arr){
var new_arr = [];
for (var i = 0; i < arr.length; i++){
if(arr[i].length % 2 == 0){
console.log("Removing \"" + arr[i] + "\" from array of length " + arr.length);
console.log("before: " + arr);
for(var x = i; x < arr.length - 1; x++){
arr[x] = arr[x+1];
}
arr.pop();
i--; //reset i so we can check the value that is now at i before we started the shift
console.log(divider("-",40));
}
}
return arr;
}
function divider(div_char, count){
var div_str = [];
for (var i = 0; i < count; i++){
div_str.push(div_char);
}
return div_str.join("");
}
<file_sep>/book/ch4/parensValid.js
var a = "Y(3(p)p(3)r)s";
var b = "N(0(p)3";
var c = "N(0)t )0 (k";
console.log(parensValid(a));
console.log(parensValid(b));
console.log(parensValid(c));
function parensValid(str){
var arr = str.split("");
// var valid = true;
var pairs_cnt = 0;
for(var i = 0; i < arr.length;i++){
if(arr[i] == "(" && pairs_cnt >= 0){
pairs_cnt++;
} else if (arr[i] == ")"){
pairs_cnt--;
}
}
if (pairs_cnt == 0)
return true;
else
return false;
}
<file_sep>/book/ch3/arrayrotate.js
//array rotate
console.log(rotateArr([1,2,3],-2));
function rotateArr(arr,shiftBy){
var shiftact = 0;
if(shiftBy > 0){
shiftact = shiftBy % arr.length;
} else if (shiftBy < 0){
shiftact = arr.length - (Math.abs(shiftBy) % arr.length);
}
console.log(shiftact);
if(shiftact === 0){
return arr;
} else {
var temp = 0;
for(var i = 0; i < shiftact; i++){
for(var x = arr.length - 1; x > 0; x--){
if(x === arr.length - 1){
temp = arr[x];
}
arr[x] = arr[x-1];
}
arr[0] = temp;
}
return arr;
}
}
<file_sep>/book/ch4/strsearch.js
var a = "hello";
function strsearch(needle,haystack){
var l = haystack.length - 1;
var n = needle.length;
var found = false;
var index = -1;
for(var i = 0; i < l; i++){
// console.log(i,haystack[i]);
for(var x = 0; x < n; x++){
// console.log(x,"-",haystack[i + x],"-",needle[x]);
if(needle[x] == haystack[x + i]){
found = true;
} else if (needle[x] != haystack[x+i]){
found = false;
break; //break out of loop since no point in checking rest
}
}
if(found){
index = i;
break; //break out of loop since we have found the needle, set position to where we found needle
}
}
// console.log(found);
return index;
}
console.log(strsearch("el",a));
console.log(strsearch("lo",a));
<file_sep>/book/ch3/doubletrouble.js
// Double Trouble
//
// Create a function that changes a given array to list each existing element twice, retaining original order. Convert [4,"Ulysses",42,false] to [4,4,"Ulysses","Ulysses",42,42,false,false].
a = [4,"Ulysses",42,false];
doubleTrouble(a);
function doubleTrouble(arr){
arr.length = arr.length * 2;
console.log(arr.length);
for(var i = (arr.length/2) - 1; i >= 0; i--){
//shift value
arr[i*2] = arr[i];
//duplicate value
arr[(i*2) + 1] = arr[i];
}
console.log(arr);
}
<file_sep>/book/ch1/ctof.js
console.log(cToF(21));
function cToF(cDegrees){
return ((9/5) + cDegrees) + 32;
}
<file_sep>/book/ch4/inverthash.js
var hash = {"name":"Zaphod", "charm":"high", "morals":"dicey"};
var newhash = {};
for (var key in hash){
newhash[hash[key]] = key;
}
console.log(newhash);
<file_sep>/book/ch2/extractomatic.js
// extract-o-matic
function extractDigit(num, digitNum){
num = Math.abs(num);
if(digitNum === 0){
console.log(Math.floor(num % 10));
} else if (digitNum === 1){
console.log(Math.floor((num % 100) / 10));
} else if (digitNum === 2){
console.log(Math.floor((num / 100) % 10));
} else if (digitNum === 3){
console.log(Math.floor(num / 1000));
} else if (digitNum === -1){
console.log(Math.floor(((num % 1)*100) % 100 / 10));
} else if (digitNum === -2){
console.log(Math.floor(((num % 1)*100) % 10));
}
}
extractDigit(1824,0);
extractDigit(1824,1);
extractDigit(1824,2);
extractDigit(1824,3);
extractDigit(123.45,-1);
extractDigit(123.45,-2);
extractDigit(-1824,3);
<file_sep>/book/ch1/incsec.js
console.log(incSec([1,2,3,4,5,6,7,8]));
function incSec(arr){
for(var i = 0; i < arr.length; i++){
if(i%2 !== 0){
arr[i] = arr[i] + 1;
}
console.log(arr[i]);
}
return arr;
}
<file_sep>/book/ch1/whatreallyhappenstoday.js
console.log(whatReallyHappensToday());
function whatReallyHappensToday(){
}
<file_sep>/book/ch6/slStack_Queue.js
function node(val){
this.value = val;
this.next = null;
}
function SLStack(){
var top = null;
this.push = function(val){
// console.log('pushing',val);
var newNode = new node(val);
if(!top){
// console.log('empty stack');
top = newNode;
} else {
// console.log('adding to top');
newNode.next = top;
top = newNode;
}
return this;
}
this.pop = function(){
if(!top){
return null;
} else {
var topVal = top.value;
top = top.next;
return topVal;
}
}
this.top = function(){
if(!top){
return null;
} else {
return top.value;
}
}
this.isEmpty = function(){
if(!top){
return true;
} else {
return false;
}
}
this.sizeOf = function(){
if(!top){
return 0;
} else {
var size = 0;
var runner = top;
while(runner){
size++;
runner = runner.next;
}
return size;
}
}
this.contains = function(val){
if(!top){
return null;
} else {
var runner = top;
while(runner){
if(runner.value === val){
return true;
}
runner = runner.next;
}
return false;
}
}
}
function SLQueue(){
var main = new SLStack();
var second = new SLStack();
this.enqueue = function(val){
console.log('pushing',val);
main.push(val);
return this;
}
this.front = function(){
// move to second stack to pull top
while(!main.isEmpty()){
second.push(main.pop());
}
var front = second.top();
// move back to main stack
while(!second.isEmpty()){
main.push(second.pop())
}
return front;
}
this.isEmpty = function(){
return main.isEmpty();
}
this.dequeue = function(){
if(main.isEmpty()){
return null;
} else {
while(!main.isEmpty()){
second.push(main.pop());
}
var front = second.pop();
while(!second.isEmpty()){
main.push(second.pop());
}
}
return front;
}
this.Contains = function(val){
return main.contains(val);
}
this.sizeOf = function(){
return main.sizeOf();
}
this.printQueue = function(){
if(!this.head){
return null;
} else {
var runner = this.head;
var str = "";
while(runner.next !== null){
str += runner.value;
str += ", ";
// console.log(str);
runner = runner.next;
}
return str;
}
}
}
var queue = new SLQueue();
queue.enqueue(1).enqueue(2).enqueue(3).enqueue(4).enqueue(5);
console.log(queue.dequeue());
console.log(queue.front());
console.log(queue.sizeOf());
console.log(queue.isEmpty());
console.log(queue.Contains(3));
<file_sep>/book/ch1/prevlen.js
console.log(prevLen(["test","testing","hello","goodbye"]));
function prevLen(arr){
var length = 0;
for(var i = 1; i < arr.length; i++){
arr[i - 1] = arr[i].length;
}
return arr;
}
<file_sep>/platform/linkedlists1/linkedLists-set6.js
//setup & display functions
function ListNode(value) {
return {
val: value,
next: null,
}
}
function addBack(list, value) {
var obj = ListNode(value);
if (!list.head) {
list.head = obj;
return list;
}
var node = list.head;
while (node.next) {
node = node.next;
}
node.next = obj;
return list;
}
function displayList(list) {
var displayStr = "";
var runner = list.head;
while (runner != null) {
if (runner.next != null) {
displayStr = displayStr + runner.val + ", ";
} else {
displayStr = displayStr + runner.val;
}
runner = runner.next;
}
return displayStr;
}
//dedupe Slist
function dedupe(list){
if(!list.head) return null;
var runner = list.head;
var secondRunner = null;
var temp = null;
while(runner){
// console.log(`Searching for ${runner.val}`);
secondRunner = runner.next;
temp = runner;
while(secondRunner){
// console.log(`-looking at ${secondRunner.val}`)
if(runner.val === secondRunner.val){
// console.log('Found duplicate');
temp.next = secondRunner.next;
}
temp = secondRunner;
secondRunner = secondRunner.next;
}
runner = runner.next;
}
return 0;
}
var slist = { head: null };
addBack(slist,3);
addBack(slist,4);
addBack(slist,9);
addBack(slist,15);
addBack(slist,4);
addBack(slist,11);
addBack(slist,4);
addBack(slist,13);
addBack(slist,13);
console.log(displayList(slist));
dedupe(slist);
console.log(displayList(slist));
//Dedupe Slist without buffer<file_sep>/book/ch1/pandr.js
console.log(pAndR([1,2]));
function pAndR(arr){
console.log(arr[0]);
return arr[1];
}
<file_sep>/slack/algos1/1-24-17.js
// 1/24/2017 INSERTAT, REMOVEAT, 2NDLARGEST, && SWAP
// insertAt(idx, val): Implement a Class method that inserts a new Node with the given val at the index specified.
// removeAt(idx): Implement a class method that removes the Node located at the specified index
// 2ndLargest(): implement a class method that returns the second largest value in a linked list containing comparable values
// swap(node1, node2): Implement a Class method that takes references to two nodes as parameters and swaps their locations
//
// https://vimeo.com/200925621/83182099bc
<file_sep>/book/ch3/pushfront.js
//push front
console.log(pushFront([1,2,3,4,5],0));
function pushFront(arr,newVal){
for(var i = arr.length - 1; i >= 0; i--){
arr[i + 1] = arr[i];
}
arr[0] = newVal;
return arr;
};
<file_sep>/git_algos/week_02_strings_assoc_arrays/2.4.js
// ##Strings and Associative Arrays Day 4
// ###Recreate these built-in functions from JavaScript’s string library:
// ###String.concat
// `string1.concat(str2,str3,...,strX)` - add string(s) to end of existing one. Return new string.
// var str1 = "test1";
// var str2 = "test2";
// var str3 = "test3";
// var str4 = "test4";
// // string = string.concat(str1, str2, str3, str4);
// console.log(concatstrs(str1,str2,str3));
// console.log(concatstrs(str1,str2,str3,str4));
//
// function concatstrs(){
// var new_str = "";
// for(var i = 0; i < arguments.length; i++){
// new_str += arguments[i];
// }
// return new_str;
// }
// ###String.slice
// `string.slice(start,end)` - extract part of a string and return in a new one. Start and end are indices into the string, with the first character at index 0. End param is optional and, if present, refers to one beyond the last character to include.
// + Bonus: include support for negative indices, representing offsets from string-end. Example: `string.slice(-1)` returns the string’s last character.
// var test = "testing";
// console.log(strsplice(test,2,4));
// console.log(strsplice(test,-1));
// function strsplice(str,start,end){
// var arr = str.split("");
// var new_arr = [];
// if (start == undefined){
// start = 0;
// } else if (start < 0){
// start = str.length + start;
// }
// if (end == undefined){
// end = str.length - 1;
// }
// for(var i = start; i <= end; i++){
// new_arr.push(arr[i]);
// }
// return new_arr.join("");
// }
// ###String.trim
// `string.trim()` - remove whitespace (spaces, tabs, newlines) from both sides, and return a new
// string.
// + Example: `"\n hellogoodbye\t ".trim()` should return `"hellogoodbye"`.
// var test_str = " \n hello goodbye \t ";
// console.log("\"" + trimstr(test_str) + "\"");
// function trimstr(str){
// var arr = str.split("");
// for(var i = 0; i < arr.length; i++){
// if(arr[i] == "\\" && arr[i + 1] == "n"){
// arr[i] = "";
// arr[i + 1] = "";
// } else if(arr[i] == "\\" && arr[i + 1] == "t"){
// arr[i] = "";
// arr[i + 1] = "";
// } else if(arr[i] == " "){
// arr[i] = "";
// }
// }
// return arr.join("");
// }
// ###String.split
// `string.split(separator,limit)` - split string into array of substrings, returning the new array. Separator specifies where to divide substrings and is not included in any substring. If `""` is specified, split string on every character. Limit is optional and indicates number of splits; additional post-limit items should be discarded.
// + Note: existing string is unaffected.
// var a = "testing a test string";
// function strsplit(str,separator,limit){
// var newstr = "";
// var arr = [];
//
// limit = limit || -1;
// separator = separator || "";
//
// //set so we're not calling the length function repeatedly
// var l = str.length;
// var al = arr.length;
//
// for(var i = 0; i < l; i++){
// if(al <= limit - 1 || limit == -1){
// if(str[i] == separator){
// arr.push(newstr);
// newstr = "";
// } else if (separator == ""){ //split all characters in the string
// arr.push(str[i]);
// } else {
// newstr += str[i];
// }
// }
// }
// return arr;
// }
//
// console.log(strsplit(a," ",3));
// console.log(strsplit(a,"",3));
// console.log(strsplit(a," "));
// console.log(strsplit(a));
// ###String.search
// `string.search(val)` - search string for val (another string). Return index position of first match (`-1` if not found).
// var a = "hello";
// function strsearch(needle,haystack){
//
// var l = haystack.length - 1;
// var n = needle.length;
// var found = false;
// var index = -1;
//
// for(var i = 0; i < l; i++){
// // console.log(i,haystack[i]);
// for(var x = 0; x < n; x++){
// // console.log(x,"-",haystack[i + x],"-",needle[x]);
// if(needle[x] == haystack[x + i]){
// found = true;
// } else if (needle[x] != haystack[x+i]){
// found = false;
// break; //break out of loop since no point in checking rest
// }
// }
// if(found){
// index = i;
// break; //break out of loop since we have found the needle, set position to where we found needle
// }
// }
// // console.log(found);
// return index;
// }
// console.log(strsearch("el",a));
// console.log(strsearch("lo",a));
<file_sep>/book/ch4/acronyms.js
// acronyms
var a = " there's no free lunch - gotta pay yer way.";
var b = "Live from new york, it's saturday night!";
console.log(acronyms(a));
console.log(acronyms(b));
function acronyms(str){
var wordArray = str.split(" ");
var acronym_str = [];
for (i = 0; i < wordArray.length; i++){
var individual_word = wordArray[i].split("");
acronym_str.push(individual_word[0]);
}
return acronym_str.join("").toUpperCase();
}
<file_sep>/book/ch1/setandswap.js
// setAndSwap();
function setAndSwap(){
var myNumber = 42;
var myName = "Spencer";
var temp = 0;
temp = myNumber;
myNumber = myName;
myName = temp;
}
<file_sep>/book/ch1/fplusl.js
console.log(fPlusL([1,2,3,4,5,6]));
console.log(fPlusL([true,2,3,4,5,6]));
console.log(fPlusL(["hello",2,3,4,5,6]));
function fPlusL(arr){
return arr[0] + arr.length;
}
<file_sep>/book/ch2/dojosweatshirt.js
// dojo sweatshirt
function sweatShirtPricing(num){
var pieceprice = 20;
if (num == 1){
return pieceprice;
} else if (num == 2){
return Math.ceil(num*pieceprice*(1-.09));
} else if (num == 3){
return Math.ceil(num*pieceprice*(1-.19));
} else if (num >= 4){
return Math.ceil(num*pieceprice*(1-.35));
}
}
console.log(sweatShirtPricing(1));
console.log(sweatShirtPricing(2));
console.log(sweatShirtPricing(3));
console.log(sweatShirtPricing(4));
<file_sep>/book/ch4/stringreverse.js
// string reverse
var a = "creature";
console.log(a);
console.log(reverseString(a));
function reverseString(str){
var new_str = [];
var letterArr = str.split("");
for (i = letterArr.length - 1; i >= 0; i--){
new_str.push(letterArr[i]);
}
return new_str.join("");
}
<file_sep>/book/ch4/removeBlanks.js
// remove blanks
var a = " Pl ayTha tF u nkyM usi c ";
console.log(removeBlanks(a));
function removeBlanks(a){
return a.split(" ").join("");
}
<file_sep>/book/ch6/cirQueue.js
// function CirQueue(cap){
// this.head = 0;
// this.tail = 0;
// this.capacity = cap;
// this.arr = [];
// this.front = function(){
// return this.arr[this.head];
// }
// this.back = function(){
// return this.arr[this.tail];
// }
// this.isEmpty = function(){
// return (this.arr[this.head]===undefined);
// }
// this.isFull = function(){
// return (this.arr[this.capacity - 1] !== undefined);
// }
// this.enQueue = function(val){
// if(this.head === this.tail){
// this.arr[this.tail] = val;
// this.tail++;
// } else if (this.tail < capacity && this.head === 0){
// this.arr[this.tail] = val;
// this.tail++;
// } else if (this.tail === capacity && this.head === 0){
// this.head++;
// this.arr[this.tail] = val;
// }
// }
// this.deQueue = function(){
// }
// this.contains = function(val){
// }
// this.grow = function(newCap){
// this.head = 0;
// this.tail = this.capacity - 1;
// this.capacity = newCap;
// }
// }
// let myCirQueue = new CirQueue(5);
// console.log(myCirQueue.enQueue(5).enQueue(2).enQueue(3).enQueue(4).enQueue(1).arr);
// console.log(myCirQueue.enQueue(10).arr);
// console.log(myCirQueue.enQueue(15).arr);
// console.log(myCirQueue.enQueue(17).arr);
// console.log(myCirQueue.enQueue(18).arr);
// console.log(myCirQueue.enQueue(21).arr);
// console.log(myCirQueue.enQueue(23).arr);
// console.log(myCirQueue.front())
// console.log(myCirQueue.isEmpty())
// console.log(myCirQueue.isFull())
var Queue = function(maxSize){
this.queue = [];
this.reset = function(){
this.tail = -1;
this.head = -1;
};
this.reset();
this.maxSize = maxSize || Queue.MAX_SIZE;
this.increment = function(number){
return (number + 1) % this.maxSize;
};
};
Queue.MAX_SIZE = Math.pow(2, 53) - 1;
Queue.prototype.enQueue = function(record){
if(this.isFull()){
throw new Error("Queue is full can't add new records");
}
if(this.isEmpty()){
this.head = this.increment(this.head);
}
this.tail = this.increment(this.tail);
//console.log("tail", this.tail);
this.queue[this.tail] = record;
};
Queue.prototype.setMaxSize = function(maxSize){
this.maxSize = maxSize;
};
Queue.prototype.push = Queue.prototype.enQueue;
Queue.prototype.insert = Queue.prototype.enQueue;
Queue.prototype.isFull = function(){
return this.increment(this.tail) === this.head;
};
Queue.prototype.deQueue = function(){
if(this.isEmpty()){
throw new Error("Can't remove element from an empty Queue");
}
// removing from the begining of the head
var removedRecord = this.queue[this.head];
this.queue[this.head] = null;
if(this.tail === this.head){
this.reset();
}else{
// if there are more records increase head.
this.head = this.increment( this.head );
}
return removedRecord;
};
Queue.prototype.pop = Queue.prototype.deQueue;
Queue.prototype.front = function(){
return this.queue[this.head] || null;
};
Queue.prototype.peak = Queue.prototype.front;
Queue.prototype.isEmpty = function(){
return this.tail === -1 && this.head === -1;
};
Queue.prototype.print = function(){
for(var i= this.head; i <= this.tail; i++){
console.log(this.queue[i]);
}
};
var q = new Queue(5);
q.enQueue(1);
q.enQueue(2);
q.enQueue(3);
q.enQueue(4);
q.deQueue();
q.deQueue();
q.deQueue();
q.enQueue(5);
q.enQueue(6);
q.enQueue(7);
q.enQueue(8);
q.deQueue();
q.deQueue();
q.deQueue();
q.deQueue();
q.deQueue();
//q.print();
//var el = q.deQueue();
//console.log("removed element" + el);
// console.clear();
q.print();
console.log("head", q.head);
console.log("tail", q.tail);
console.log(q.queue);<file_sep>/book/ch3/reversearray.js
//reverse array
console.log(revArr([3,1,6,4,2]));
function revArr(arr){
var temp = 0;
for(var i = 0; i < arr.length/2; i++){
temp = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = temp;
}
return arr;
}
<file_sep>/book/ch1/mof3.js
mOf3();
function mOf3(){
for (var i = -300; i < 0; i++){
if(i != -3 && i != -6 && i%3 === 0){
console.log(i);
}
}
}
<file_sep>/book/ch4/commonsuffix.js
var a = ["deforestation","citation","conviction","incrceration"];
var b = ["nice","ice","baby"];
console.log("a - " + commonSuffix(a));
console.log("b - " + commonSuffix(b));
function commonSuffix(wordArr){
var suffix = "";
var suffix_found = true;
while(suffix_found != false){
for(var x = 0; x < wordArr.length; x++){
if (x == 0 && suffix.length != wordArr[x].length){
// suffix = wordArr[x].substr(wordArr[x].length - suffix.length - 1, wordArr[x].length);
suffix = new_substr(wordArr[x],wordArr[x].length - suffix.length - 1, wordArr[x].length);
} else {
if(suffix != wordArr[x].substr(wordArr[x].length - suffix.length,wordArr[x].length)){
// suffix = suffix.substr(1,suffix.length);
suffix = new_substr(suffix,1,suffix.length);
suffix_found = false;
break;
}
}
}
}
if (suffix.length != 0){
return suffix;
} else {
return "";
}
}
// console.log(new_substr("testing",0,6));
function new_substr(str,start,end){
if(start > str.length || end > str.length || start > end){
return str;
} else {
var old_str = str.split("");
var new_str = [];
for(var i = start; i < end && i < str.length; i++){
new_str.push(old_str[i]);
}
return new_str.join("");
}
}
<file_sep>/book/ch4/ispalindrome.js
var a = "racecar";
console.log(isPalindrome(a));
console.log(isPalindrome("Dud"));
console.log(isPalindrome("oho!"));
console.log(isPalindrome("a x a"));
console.log(isPalindrome("hello"));
// function isPalindrome(str){
// var letterArr = str.split("");
// var palindrome = true;
// for (i = 0; i < (letterArr.length - 1) / 2; i++){
// if (letterArr[i] != letterArr[letterArr.length - 1 - i]){
// palindrome = false;
// break;
// }
// }
// return palindrome;
// }
function isPalindrome(str){
var letterArr = str.split("");
var searchStr = new RegExp("[^a-zA-Z0-9]");
for (var i = 0; i < letterArr.length; i++){
if(searchStr.test(letterArr[i])){
// console.log("Replacing " + letterArr[i]);
letterArr[i] = "";
} else {
letterArr[i] = letterArr[i].toLowerCase();
}
}
letterArr = letterArr.join("").split("");
// console.log(letterArr);
var palindrome = true;
for (i = 0; i < (letterArr.length - 1) / 2; i++){
if (letterArr[i] != letterArr[letterArr.length - 1 - i]){
palindrome = false;
break;
}
}
return palindrome;
}
<file_sep>/book/ch3/popfront.js
//pop front
console.log("front: " + popFront([1,2,3,4,5]));
function popFront(arr){
var front = arr[0];
for(var i = 0; i < arr.length - 1; i++){
arr[i] = arr[i+1];
}
arr.pop(arr.length - 1);
console.log(arr);
return front;
}
<file_sep>/book/ch6/slstack.js
function node(val){
this.value = val;
this.next = null;
}
function SLStack(){
var top = null;
this.push = function(val){
// console.log('pushing',val);
var newNode = new node(val);
if(!top){
// console.log('empty stack');
top = newNode;
} else {
// console.log('adding to top');
newNode.next = top;
top = newNode;
}
return this;
}
this.pop = function(){
if(!top){
return null;
} else {
var topVal = top.value;
top = top.next;
return top;
}
}
this.top = function(){
if(!top){
return null;
} else {
return top.value;
}
}
this.isEmpty = function(){
if(!top){
return true;
} else {
return false;
}
}
this.sizeOf = function(){
if(!top){
return 0;
} else {
var size = 0;
var runner = top;
while(runner){
size++;
runner = runner.next;
}
return size;
}
}
this.contains = function(val){
if(!top){
return null;
} else {
var runner = top;
while(runner){
if(runner.value === val){
return true;
}
runner = runner.next;
}
return false;
}
}
}
var ourStack = new SLStack();
var testStack = new SLStack();
// console.log(ourStack.isEmpty());
ourStack.push(3).push(4).push(6);
testStack.push(2).push(4).push(6);
// console.log(ourStack.isEmpty());
// console.log(ourStack.top());
// console.log(ourStack.contains(2));
function compareStacks(stackOne, stackTwo){
var tempStack = new SLStack();
var identical = true;
var size = stackOne.sizeOf();
// while(stackOne.top() !== null || identical !== false){
// for(var i = 0; i < size; i++){
while(stackOne.top() && stackTwo.top()){
if(stackOne.top() === stackTwo.top()){
console.log('top match');
console.log(stackOne.top(),stackTwo.top());
tempStack.push(stackOne.pop())
stackTwo.pop();
} else {
identical = false;
}
}
console.log(identical);
// } while(stackOne.top() || identical !== false)
// while(tempStack.top() !== null){
// stackOne.push(tempStack.top());
// stackTwo.push(tempStack.pop());
// }
return identical;
}
console.log(compareStacks(ourStack, testStack));
<file_sep>/book/ch5/listfront.js
function ListNode(value){
return {
val : value,
next : null
}
}
var myList = { head : null }
console.log(myList);
addBack(myList,"Bob");
console.log(myList);
addBack(myList,"Charlie");
console.log(myList);
addBack(myList,"Spencer");
console.log(myList);
console.log(myList);
console.log(addBack(myList,"testing"));
function addBack(list,value){
var obj = ListNode(value);
if(list.head == null){
list.head = obj;
} else {
var node = list.head;
while(node.next != null){
node = node.next;
}
node.next = obj;
}
return list;
}
function addFront(list,value){
var obj = ListNode(value);
if(list.head == null){
list.head = obj;
} else {
obj.next = list.head;
list.head = obj;
}
return list;
}
console.log(myList);
console.log(addFront(myList,"Rudy"));
console.log(getFront(myList));
function getFront(list){
if(list.head == null){
return null;
} else {
return list.head.val;
}
}
<file_sep>/book/ch3/removenegatives.js
//remove negatives
console.log(removeNegs([2,-1,4,-2,5]));
function removeNegs(arr){
var new_arr = [];
for(var i = 0; i < arr.length; i++){
if(arr[i] >= 0){
new_arr.push(arr[i]);
}
}
return new_arr;
}
<file_sep>/slack/algos1/1-23-17.js
// 1/23/2017 RLENGTH, REMOVEFRONT, REMOVEBACK, && CONTAINS
// rLength(): Implement a function that uses recursion to return the number of nodes in the linked list.
// removeFront(): Implement a class method removes the first node of a Linked List
// removeBack(): Implement a class method that removes the last Node of a Linked List
// contains(data): Implement a class method that returns whether teh Linked List contains a given value.
//
// https://vimeo.com/200765989/3c5cd1e386
<file_sep>/book/ch6/queues.js
function Node(value){
this.value = value;
this.next = null;
}
function SLQueue(){
var head = null;
var tail = null;
this.enqueue = function(val){
var newNode = new Node(val);
if(!this.head){
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
this.tail = this.tail.next;
}
return this;
}
this.front = function(){
if(!this.head){
return null;
}
else {
return this.head.value;
}
}
this.empty = function(){
if(!this.head){
return true;
} else {
return false;
}
}
this.dequeue = function(){
if(!this.head){
return null;
} else if (this.head.next === null){
var front = this.head.value;
this.head = null;
this.tail = null;
} else {
var front = this.head.value;
this.head = this.head.next;
}
return front;
}
this.Contains = function(val){
if(!this.head){
return null;
} else {
var runner = this.head;
while(runner){
if(runner.value === val){
return true;
}
runner = runner.next;
}
return false;
}
}
this.sizeOf = function(){
if(!this.head){
return 0;
} else {
var size = 0;
runner = this.head;
while(runner){
size++;
runner = runner.next;
}
return size;
}
}
this.printQueue = function(){
if(!this.head){
return null;
} else {
var runner = this.head;
var str = "";
while(runner.next !== null){
str += runner.value;
str += ", ";
// console.log(str);
runner = runner.next;
}
return str;
}
}
}
var queue = new SLQueue();
var queue2 = new SLQueue();
// console.log(queue.empty());
queue.enqueue(1).enqueue(2).enqueue(3).enqueue(4).enqueue(5);
queue2.enqueue(5).enqueue(4).enqueue(3).enqueue(4);
// console.log(queue.front());
// console.log(queue.empty());
// console.log(queue.dequeue(),queue);
// console.log(queue.dequeue(),queue);
// console.log(queue.Contains(3));
// console.log(queue.sizeOf());
// queue.dequeue();
// console.log(queue.Contains(5));
// console.log(queue.sizeOf());
// queue.dequeue();
// console.log(compareQueues(queue,queue2));
//
// function compareQueues(queue1, queue2){
// if(queue1.sizeOf() !== queue2.sizeOf()){
// return false;
// } else {
// while(!queue1.empty() && !queue2.empty()){
// if(queue1.front() !== queue2.front()){
// return false;
// } else {
// queue1.dequeue();
// queue2.dequeue();
// }
// }
// return true;
// }
// }
function removeMin(queue){
if(queue.empty()){
return null;
} else if(queue.head.next === null){
queue.dequeue();
return null;
} else {
var min = queue.head.value;
var runner = queue.head.next;
// find the minimum
while(runner){
if(runner.value < min){
min = runner.value;
}
runner = runner.next;
}
//remove the minimum
while(queue.front() === min){
queue.dequeue();
}
var previous = queue.head;
var runner = queue.head.next;
while(runner){
if(runner.value === min){
previous.next = runner.next;
} else {
previous = runner;
}
runner = runner.next;
}
return true;
}
}
// console.log(removeMin(queue));
// console.log(queue.Contains(3));
interLeaveQueue(queue);
function interLeaveQueue(queue){
// console.log(queue.head);
if(queue.empty()){
return null;
} else {
var size = queue.sizeOf();
var front = queue.front();
var newQueue = new SLQueue();
for(var i = 0; i < size/2; i++){
newQueue.enqueue(queue.dequeue());
}
do{
newQueue.enqueue(newQueue.dequeue());
newQueue.enqueue(queue.dequeue());
} while (newQueue.front() !== front);
console.log(newQueue.printQueue());
return this;
}
}
<file_sep>/book/ch2/generatecoinchange.js
// generate coin change
function generateCoinChange(cents){
var quarters = 0;
var dimes = 0;
var nickels = 0;
var pennies = 0;
var remainder = 0;
quarters = (cents - (cents % 25))/25;
dimes = ((cents % 25) - ((cents % 25) % 10))/10;;
nickels = (((cents % 25) % 10) - (((cents % 25) % 10) % 5))/5;
pennies = ((cents % 25) % 10) % 5;
console.log(cents + " cents can be represented by:");
console.log("quarters: " + quarters);
console.log("dimes: " + dimes);
console.log("nickels: " + nickels);
console.log("pennies: " + pennies)
}
generateCoinChange(94);
<file_sep>/book/ch4/bookindex.js
var pages = [1,13,14,15,37,38,70];
// return string "1, 13-15, 37-38, 70"
console.log(bookIndex(pages));
function bookIndex(arr){
var index_str = "";
var start_page = [];
for(var i = 0; i < arr.length; i++){
if(i+1 != arr.length){
if(arr[i] + 1 == arr[i + 1]){
start_page.push(arr[i]);
} else{
if (start_page.length != 0){
index_str = index_str + start_page[0] + "-" + arr[i] + ", ";
start_page = [];
} else {
index_str = index_str + arr[i] + ", ";
}
}
} else if (i == arr.length - 1){
index_str = index_str + arr[i];
}
}
return index_str;
}
<file_sep>/book/ch3/nthlargest.js
// nth largest
console.log(nthLargest([4,42,1,Math.PI,7],3));
function nthLargest(arr,nth){
var nthvalue = 0;
var largearr = [];
while(largearr.length != nth){
nthvalue = 0;
for(var i = 0; i < arr.length; i++){
if (arr[i] > nthvalue && largearr.length === 0){ //set largest value
nthvalue = arr[i];
} else if (arr[i] > nthvalue && arr[i] < largearr[largearr.length - 1]){
nthvalue = arr[i];
}
}
largearr.push(nthvalue);
}
return nthvalue;
}
<file_sep>/slack/algos1/1-26-17.js
// 1/26/2017 INTRO TO STACK DATA STRUCTURE
// Stack: Implement a new Class called a Stack with the following methods:
// push(data):
// Adds data to the Stack
// pop():
// Returns and removes from the Stack the most recent data added to the stack
// top():
// Returns the value of the most recently added data in the Stack
// isEmpty?():
// Returns a boolean whether the Stack is currently empty
// size():
// Returns the number of data stored in the Stack
// contains(data):
// Returns a boolean whether the Stack contains the given data
// Do this using a sinlgy linked list data structure and once with an array data structure holding the information.
//
// https://vimeo.com/201228681/86cb753700
<file_sep>/book/ch1/dblvis.js
console.log(dblVis([1,2,3,4]));
function dblVis(arr){
var new_arr = [];
for(var i = 0; i < arr.length; i++){
new_arr.push(arr[i] * 2);
}
return new_arr;
}
<file_sep>/book/ch1/printevenodd.js
printEvenOdd([1,1,1,2,2,2,3,4,4,4]);
function printEvenOdd(arr){
var countOdd = 0;
var countEven = 0;
for(var i = 0; i < arr.length; i++){
if(arr[i]%2 === 0){
countEven++;
} else {
countOdd++;
}
if(countOdd == 3){
console.log("That's odd!");
countOdd = 0;
} else if(countEven == 3){
console.log("Even More So")
countEven = 0;
}
}
}
<file_sep>/book/ch3/insertat.js
// insert at
// index is spot in array you wanted insert at, i.e. if we want index before 2 and after 1, we would set it to 2
console.log(insertAt([1,2,3,4,5],2,7));
function insertAt(arr,index,val){
for(var i = arr.length -1; i >= index - 1; i--){
arr[i + 1] = arr[i];
}
arr[index-1] = val;
return arr;
}
<file_sep>/book/ch3/mintofront.js
//array min to front
console.log(minToFront([4,3,1,5,6]));
function minToFront(arr){
var min = arr[0];
for(var i = 1; i < arr.length; i++){
if(arr[i] < min){
arr[0] = arr[i];
arr[i] = min;
min = arr[0];
}
}
return arr;
}
<file_sep>/book/ch2/claireiswhere.js
// claire is where?
function reset(){
position.x = 0;
position.y = 0;
}
function moveBy(x,y){
position.x = position.x + x;
position.y = position.y + y;
}
function xLocation(){
console.log(position.x);
}
function yLocation(){
console.log(position.y);
}
position = {
x : 0,
y : 0,
}
reset();
moveBy(1,-2);
moveBy(3,1);
xLocation();
yLocation();
function distFromHome(){
console.log(Math.sqrt((position.x^2)+(position.y^2)));
}
distFromHome();
<file_sep>/platform/algos2/week1session1.js
// console.clear();
function avg(arr){
if(!Array.isArray(arr)){
return false;
}
var sum = 0;
for(var idx = 0; idx < arr.length; idx++){
sum += arr[idx];
}
return sum/arr.length;
}
function isBalanced(arr){
if(!Array.isArray(arr)){
return false;
}
var sum1 = 0;
var sum2 = 0;
for(var i = 0; i < arr.length/2; i++){
sum1+= arr[i];
sum2+= arr[arr.length-1-i];
}
return (sum1===sum2)
}
console.log(isBalanced([4,5,3,5,4]));
<file_sep>/book/ch3/nthtolast.js
//nth to last
console.log(nthToLast([5,2,3,6,4,9,7],3));
function nthToLast(arr,index){
if (arr.length < index){
return null;
} else {
return arr[arr.length - index];
}
}
<file_sep>/book/ch2/statsuntildbles.js
// statistics until doubles
function rollD20(){
return Math.trunc(Math.random()*20)+1;
}
function statsUntilDbles(){
var num_rolls = 0;
var max = 0;
var sum = 0;
var prev = 0;
var roll = rollD20();
var min = roll;
while(prev !== roll){
if(roll > max){
max = roll;
} else if(roll < min){
min = roll;
}
sum+= roll;
prev = roll;
num_rolls++;
roll = rollD20();
console.log(prev + " - " + roll);
}
console.log("Number of rolls: " + num_rolls);
console.log("Min: " + min);
console.log("Max: " + max);
console.log("Avg: " + Math.floor(sum/num_rolls));
}
statsUntilDbles();
<file_sep>/book/ch2/monthnames.js
function monthName(monthNum){
monthArr = ["January","February","March","April","May","June","July","August","September","October","November","December"];
return monthArr[monthNum - 1];
}
console.log(monthName(5));
<file_sep>/book/ch3/arrayfilter.js
//array filter - maintain order
console.log(filterRange([1,2,3,4,5],2,4));
console.log(filterRange([2,5,3,1,0,6,3,8,4,9],2,4));
function filterRange(arr,min,max){
var index = 0;
while(index < arr.length){
if(arr[index] < min || arr[index] > max){ //lets shift everything down and pop the last
for (var i = index; i < arr.length - 1; i++){
arr[i] = arr[i+1];
//console.log(arr);
}
arr.pop();
} else {
index++;
}
}
return arr;
}
<file_sep>/book/ch2/daytomonth.js
function dayToMonth(daynum){
var sum = 0;
for(var i = 1; i <= 12; i++){
sum += monthToDays(i);
if(sum >= daynum - 1){
break;
}
}
return monthName(i);
}
console.log(dayToMonth(75));
console.log(dayToMonth(120));
console.log(dayToMonth(360));
<file_sep>/book/ch5/slist_back.js
function ListNode(value){
return {
val : value,
next : null
}
}
function addBack(list,value){
var obj = ListNode(value);
if(list.head == null){
list.head = obj;
} else {
var node = list.head;
while(node.next != null){
node = node.next;
}
node.next = obj;
}
return list;
}
var myList = { head : null }
addBack(myList,10);
addBack(myList,20);
addBack(myList,30);
addBack(myList,5);
console.log(myList);
function getBack(list){
if(!list.head) { return null };
var runner = list.head;
while(runner.next != null){
runner = runner.next;
}
return runner.val;
}
console.log(getBack(myList));
function removeBack(list){
if(!list.head) return null;
var runner = list.head;
while(runner.next){
if (!runner.next.next){
console.log(`removing ${runner.next.val}`);
runner.next = null;
return list;
}
runner = runner.next;
}
return 0;
}
console.log(removeBack(myList));
console.log(getBack(myList));<file_sep>/git_algos/week_01_arrays/arraysday5.js
// Shuffle
//
// Recreate the shuffle(arr) function built into JavaScript, to efficiently shuffle a given array’s values. Work in-place, of course. Do you need to return anything from your function?
// a = [20,30,40,50,60,70];
// console.log(a);
// shuffleArr(a);
// console.log(a);
// function shuffleArr(arr){
// var newpos = 0;
// var temp = 0;
// for(var i = 0; i < arr.length; i++){
// newpos = Math.trunc(Math.random()*(arr.length - 1));
// temp = arr[i];
// arr[i] = arr[newpos];
// arr[newpos] = temp;
// }
// }
//
// Remove array
//
// Given array, and indices start and end, remove vals in that index range, working in-place (hence shortening the array). Given ([20,30,40,50,60,70],2,4), change to [20,30,70] and return it.
// a = [20,30,40,50,60,70];
// removeArray(a,2,4);
// console.log(a);
// function removeArray(arr,start,stop){
// console.log("Remove values from " + arr[start] + " to " + arr[stop]);
// while(start - 1 != stop){
// //shift values left
// for(var i = start; i < arr.length - 1; i++){
// arr[i] = arr[i + 1];
// }
// arr.pop();
// stop--;
// }
// //console.log(arr);
// }
// Intermediate Sums
//
// You will be given an array of numbers. After every tenth element, add an additional element containing the sum of those ten values. If the array does not end aligned evenly with ten elements, add one last sum that includes those last elements not yet been included in one of the earlier sums. Given the array [1,2,1,2,1,2,1,2,1,2,1,2,1,2], change it to [1,2,1,2,1,2,1,2,1,2,15,1,2,1,2,6].
//
// a = [1,2,1,2,1,2,1,2,1,2,1,2,1,2];
// intermedSums(a);
// function intermedSums(arr){
// var sum = 0;
// console.log(arr);
// for(var i = 0; i < arr.length; i++){
// if((i + 1) % 10 === 0){
// //add last value
// sum += arr[i];
// arr.length = arr.length + 1;
// //shift remaining if not at end of array
// for(var x = arr.length - 1; x > i + 1; x--){
// arr[x] = arr[x - 1];
// }
// //set new value in list
// arr[i+1] = sum;
// sum = 0;
// i++;
// } else {
// sum += arr[i];
// }
// }
// if((i + 1) % 10 !== 0){
// arr.length = arr.length + 1;
// arr[i] = sum;
// }
// console.log(arr);
// }
// Double Trouble
//
// Create a function that changes a given array to list each existing element twice, retaining original order. Convert [4,"Ulysses",42,false] to [4,4,"Ulysses","Ulysses",42,42,false,false].
// a = [4,"Ulysses",42,false];
// doubleTrouble(a);
// function doubleTrouble(arr){
// arr.length = arr.length * 2;
// console.log(arr.length);
// for(var i = (arr.length/2) - 1; i >= 0; i--){
// //shift value
// arr[i*2] = arr[i];
// //duplicate value
// arr[(i*2) + 1] = arr[i];
// }
// console.log(arr);
// }
// Zip it
//
// Create a standalone function that accepts two arrays and combines their values sequentially into the first array, at alternating indices starting with the first array. Extra values from either array should be included afterward. Given [1,2] and [10,20,30,40], change first array to [1,10,2,20,30,40].
// a = [1,2,3];
// b = [10,20,30,40];
// // zipIt_new(a,b);
// zipIt(a,b);
// console.log(a);
// function zipIt_new(arr1, arr2){
// var delta = Math.abs(arr1.length - arr2.length);
// var index = 0;
// if (arr1.length > arr2.length){
// index = arr2.length;
// } else {
// index = arr1.length;
// }
// var new_arr = [];
// for(var i = 0; i < index; i++){
// new_arr.push(arr1[i]);
// new_arr.push(arr2[i]);
// }
// for(var i = index; i < index + delta; i++){
// if(arr1[i])
// new_arr.push(arr2[i]);
// else if (arr2[i])
// new_arr.push(arr2[i]);
// }
// console.log(new_arr);
// }
// function zipIt(arr1, arr2){
// arr1.length = arr1.length + arr2.length;
// //shift
// for(var i = arr1.length - arr2.length - 1; i > 0; i--){
// arr1[2 * i] = arr1[i];
// delete arr1[i];
// }
// var index = 0;
// for(var i = 1; i < arr1.length; i++){
// if(!arr1[i]){
// arr1[i] = arr2[index];
// index++;
// }
// }
// }
<file_sep>/book/ch4/stringconcat.js
var str1 = "test1";
var str2 = "test2";
var str3 = "test3";
var str4 = "test4";
// string = string.concat(str1, str2, str3, str4);
console.log(concatstrs(str1,str2,str3));
console.log(concatstrs(str1,str2,str3,str4));
function concatstrs(){
var new_str = "";
for(var i = 0; i < arguments.length; i++){
new_str += arguments[i];
}
return new_str;
}
<file_sep>/book/ch1/p1ra.js
console.log(p1rA([1,2,3,4,5,6]));
function p1rA(arr){
console.log(arr.length-1);
for(var i = 0; i < arr.length; i++){
if(i%2 !== 0){
break;
}
}
return i;
}
<file_sep>/book/ch3/arrayfilterrange.js
//array filter range (does not maintain order)
console.log(filterRange([1,2,3,4,5],2,4));
console.log(filterRange([2,5,3,1,0,6,3,8,4,9],2,4));
function filterRange(arr,min,max){
var index = 0;
while(index < arr.length){
if(arr[index] < min || arr[index] > max){
arr[index] = arr[arr.length - 1];
arr.pop();
} else {
index++;
}
console.log(arr);
}
return arr;
}
<file_sep>/book/ch1/outlook.js
console.log(outlook([1,-3,5]));
function outlook(arr){
for(var i = 0; i < arr.length; i++){
if(arr[i] > 0){
arr[i] = -1 * arr[i];
}
}
return arr;
}
<file_sep>/slack/algos1/1-11-17.js
// 1/11/2017 BUILT-INS && .SPLIT()
// split(string, split, limit): Read the documentation to learn the basic functionality of the String.split() method. Do not worry about re-creating a fully robust implementation that can handle multi-character split arguments. For example:
// split('<NAME>') // outputs: ['<NAME>']
// split('<NAME>','') // outputs: ['b','o','b',' ','r','o','s','s']
// split('<NAME>', ' ') // outputs: ['bob','ross']
// split('<NAME>', 'o') // outputs: ['b', 'b r', 'ss']
// split('<NAME>', 'o', 2) // outputs: ['b', 'b r']
<file_sep>/book/ch2/isprime.js
// is prime
function isPrime(num){
if(num % num === 0 && num % 1 === 0 && num % 2 !== 0){
return true;
} else {
return false;
}
}
console.log(isPrime(3));
console.log(isPrime(4));
console.log(isPrime(5));
console.log(isPrime(6));
<file_sep>/book/ch2/weekdayname.js
// date, on a deserted island
// 1)
function weekdayName(weekdayNum){
switch (weekdayNum){
case 1:
console.log("Sunday");
break;
case 2:
console.log("Monday");
break;
case 3:
console.log("Tuesday");
break;
case 4:
console.log("Wednesday");
break;
case 5:
console.log("Thursday");
break;
case 6:
console.log("Friday");
break;
case 7:
console.log("Saturday");
break;
default:
console.log("Evidently this isn't a day");
break;
}
}
weekdayName(1);
weekdayName(2);
weekdayName(3);
weekdayName(8);
function weekdayName2(weekdayNum){
switch (weekdayNum % 7){
case 0:
return "Sunday";
break;
case 1:
return "Monday";
break;
case 2:
return "Tuesday";
break;
case 3:
return "Wednesday";
break;
case 4:
return "Thursday";
break;
case 5:
return "Friday";
break;
case 6:
return "Saturday";
break;
default:
return "Evidently this isn't a day";
break;
}
}
weekdayName2(1);
weekdayName2(2);
weekdayName2(3);
weekdayName2(8);
weekdayName2(88);
<file_sep>/book/ch4/bracesValid.js
var a = "W(a{t}s[o(n{ c}o)m]e )h[e{r}e]!";
var b = "D(i{a}l[ t]o)n{e";
var c = "A(1)s[O (n]o{t) o}k";
console.log(bracesValid(a));
console.log(bracesValid(b));
console.log(bracesValid(c));
// function bracesValid(str){
// var arr = str.split("");
// var paren_cnt = 0;
// var squiggle_cnt = 0;
// var bracket_cnt = 0;
// var prev = [];
// for(var i = 0; i < arr.length;i++){
// if(arr[i] == "(" && paren_cnt >= 0){
// paren_cnt++;
// prev.push(arr[i]);
// } else if (arr[i] == ")" && prev[prev.length - 1] == "("){
// paren_cnt--;
// prev.pop();
// }
// if (arr[i] == "{" && squiggle_cnt >= 0){
// squiggle_cnt++;
// prev.push(arr[i]);
// } else if (arr[i] == "}" && prev[prev.length - 1] == "{"){
// squiggle_cnt--;
// prev.pop();
// }
// if (arr[i] == "[" && bracket_cnt >= 0){
// bracket_cnt++;
// prev.push(arr[i]);
// } else if(arr[i] == "]" && prev[prev.length - 1]){
// bracket_cnt--;
// prev.pop();
// }
// // console.log(arr[i] + ": " + paren_cnt + " - " + squiggle_cnt + " - " + bracket_cnt);
// }
// if(paren_cnt == 0 && squiggle_cnt == 0 && bracket_cnt == 0){
// return true;
// } else {
// return false;
// }
// }
function bracesValid(str){
var arr = str.split("");
var prev = [];
for(var i = 0; i < arr.length;i++){
if(arr[i] == "(" || arr[i] == "{" || arr[i] == "["){
prev.push(arr[i]);
} else {
if (arr[i] == ")" && prev[prev.length - 1] == "("){
prev.pop();
} else if (arr[i] == "}" && prev[prev.length - 1] == "{"){
prev.pop();
} else if (arr[i] == "]" && prev[prev.length - 1] == "["){
prev.pop();
}
}
}
if (prev.length == 0){
return true;
} else {
return false;
}
}
<file_sep>/book/ch3/removeduplicates.js
// array remove duplicates
console.log(removeDup([1,2,2,3,4,5,5,6]));
function removeDup(arr){
var new_arr = [];
for(var i = 0; i < arr.length; i++){ //go to 2nd to last element in array so we don't get an undefined on last
if(arr[i] !== arr[i+1]){
new_arr.push(arr[i]);
}
}
return new_arr;
}
<file_sep>/book/ch1/fitfirst.js
fitFirst([4,3,2]);
fitFirst([2,3,4]);
fitFirst([4,1,2,3]);
function fitFirst(arr){
if(arr[0] > arr.length){
console.log("too big!");
} else if (arr[0] < arr.length){
console.log("too small!");
} else{
console.log("just right!")
}
}
<file_sep>/book/ch2/messymath.js
// messy math
function messyMath(num){
var sum = 0;
for(var i = 0; i <= num; i++){
if(i % 3 === 0){
continue;
} else if (i % 7 === 0){
sum = sum + i + i;
} else{
if (i/num === 1/3){
return -1;
} else {
sum+= i;
}
}
}
return sum;
}
console.log(messyMath(4));
console.log(messyMath(8));
console.log(messyMath(15));
<file_sep>/book/ch4/deromanize.js
// 349 - CCCXLIX
// 2344 - MMCCCXLIV
var a = "CCCXLIX";
var b = "MMCCCXLIV";
var c = "DCIX";
var d = "MCDXCII";
console.log(deromanize(a));
console.log(deromanize(b));
console.log(deromanize(c));
console.log(deromanize(d));
function deromanize(str){
key = ['<KEY>CCC','LXX','XXX','VII','III','MM','CD','CM','DC','XC','LX','XL','XX','IX','VI','IV','II','CC','M','D','C','L','X','V','I'];
var total = 0;
for (var i = 0; i < key.length; i++){
// var pattern = new RegExp(key[i]);
for(var x = 0; x < key.length; x++){
if (str == key[x]){
total += romanConv(key[i]);
str = str.replace(key[i],"");
}
}
// if(pattern.test(str)){
// total += romanConv(key[i]);
// str = str.replace(pattern,"");
// }
}
return total;
}
function romanConv(num){
switch (num){
case 'MMM': return 3000; break;
case 'MM': return 2000; break;
case 'M': return 1000; break;
case 'CM': return 900; break;
case 'DCCC': return 800; break;
case 'DCC': return 700; break;
case 'DC': return 600; break;
case 'D': return 500; break;
case 'CD': return 400; break;
case 'CCC': return 300; break;
case 'CC': return 200; break;
case 'C': return 100; break;
case 'XC': return 90; break;
case 'LXXX': return 80; break;
case 'LXX': return 70; break;
case 'LX': return 60; break;
case 'L': return 50; break;
case 'XL': return 40; break;
case 'XXX': return 30; break;
case 'XX': return 20; break;
case 'X': return 10; break;
case 'IX': return 9; break;
case 'VIII': return 8; break;
case 'VII': return 7; break;
case 'VI': return 6; break;
case 'V': return 5; break;
case 'IV': return 4; break;
case 'III': return 3; break;
case 'II': return 2; break;
case 'I': return 1; break;
default: return 0;
}
}
<file_sep>/book/ch3/secondlargest.js
// second largest
console.log(secondLargest([42,4,1,Math.PI,7]));
function secondLargest(arr){
//find largest first
var largest = 0;
var secondlargest = 0;
if(arr.length < 2){
return null;
} else{
for(var i = 0; i < arr.length; i++){
if(arr[i] > largest && arr[i] > secondlargest){
secondlargest = largest;
largest = arr[i];
}else if(arr[i] < largest && secondlargest < arr[i]){
secondlargest = arr[i];
}
}
return secondlargest;
}
}
<file_sep>/book/ch2/fibonacci.js
// fibonacci
function fib(num){
var index = 0;
var first = 0;
var second = 1;
var temp = 0;
//console.log(first + " - " + second);
if(num === 0){
console.log(num + ": " + (second + first));
} else if (num === 1){
console.log(num + ": " + (second));
} else {
while(index < num - 1){
temp = second;
second = first + second;
first = temp;
index++;
}
console.log(num + ": " + second);
}
}
fib(0);
fib(1);
fib(2);
fib(3);
fib(4);
fib(5);
fib(6);
fib(7);
<file_sep>/book/ch4/numofval.js
var object = { band : "<NAME>", style: "country", album: "667"};
console.log(numvalues(object));
function numvalues(obj){
var num = 0;
for (key in obj){
num++;
}
return num;
}
<file_sep>/book/ch1/scalearr.js
console.log(scaleArr([1,2,3,4,5],3));
function scaleArr(arr,multi){
for(var i = 0; i < arr.length; i++){
arr[i] = arr[i] * multi;
}
return arr;
}
<file_sep>/book/ch1/mathhelp.js
console.log(mathHelp(10,5));
function mathHelp(m,b){
return -b/m;
}
<file_sep>/book/ch1/countdown2.js
countdown(8);
function countdown(num_in){
var new_arr = [];
for (var i = num_in; i >= 0; i--){
new_arr.push(i);
}
console.log(new_arr);
}
<file_sep>/book/ch2/threesandfives.js
// threes and fives
function threesAndFives(){
var sum = 0;
for(var i = 100; i <= 4000000; i++){
if(i % 3 === 0 || i % 5 === 0){
sum += i;
}
}
return sum;
}
console.log(threesAndFives());
// threes and fives
function betterThreesFives(start,end){
var sum = 0;
for(var i = start; i <= end; i++){
if(i % 3 === 0 || i % 5 === 0){
sum += i;
}
}
return sum;
}
console.log(betterThreesFives(3,15));
<file_sep>/slack/algorithms_1.js
// 11/28/2016 REVERSE STRING && REMOVE BLANKS
// Implement reverseString(str) that, given string, returns that string with characters reversed. Given 'creature', return 'erutaerc'. Tempting as it seems, do not use the built-in reverse()!
// Create a function that, given a string, returns the string, without blanks. Given " play that Funky music ", returns a string containing "playthatFunkymusic".
// var a = "creature";
// console.log(a);
// console.log(reverseString(a));
// function reverseString(str){
// var new_str = [];
// var letterArr = str.split("");
// for (i = letterArr.length - 1; i >= 0; i--){
// new_str.push(letterArr[i]);
// }
// return new_str.join("");
// }
//
// var a = " play that Funky music ";
// console.log(removeBlanks(a));
// function removeBlanks(str){
// return str.split(" ").join("");
// }
// No Recording
// 11/29/2016 ISPALINDROME() && GETDIGITS()
// Create a function that returns a boolean whether the string is a strict palindrome. For "a x a" or "racecar", return true. Do not ignore spaces, punctuation and capitalization: if given "Dud" of "oho!", return false.
// bonus: Now do ignore white spaces (spaces, tabs, returns), capitalization and punctuation.
// Create a function taht given a string returns the integer made from the string's digits. Given "0s1a3y5w7h9a2t4?6!80", the function should return the number 1,357,924,680.
// Session - https://vimeo.com/193619747/140303543f
// var a = "racecar";
// console.log(isPalindrome(a));
// console.log(isPalindrome("Dud"));
// console.log(isPalindrome("oho!"));
// console.log(isPalindrome("a x a"));
// function isPalindrome(str){
// var letterArr = str.split("");
// var palindrome = true;
// for (i = 0; i < (letterArr.length - 1) / 2; i++){
// if (letterArr[i] != letterArr[letterArr.length - 1 - i])
// palindrome = false;
// }
// return palindrome;
// }
//
// var b = "0s1a3y5w7h9a2t4?6!80";
// console.log(getDigits(b));
// function getDigits(str){
// var letterArr = str.split("");
// var new_str = [];
// for (i = 0; i < letterArr.length - 1; i++){
// if (letterArr[i] >= 0 && letterArr[i] <= 9){
// new_str.push(letterArr[i]);
// }
// }
// return new_str.join("");
// }
// 11/30/2016 STRING.SPLIT(CHAR, LIMIT) && ARRAY.JOIN(CHAR)
// Recreate the built-in JS methods, String.split() and Array.join as stand alone functions that take a string/array as parameters in addition to their normal parameters. Base your implementation off of w3schools documentation. Example: newSplit('abcdefg','',2) should return ['a','b'].
// Session - https://vimeo.com/193802036
var a = "abcdefg";
// 12/1/2016 ARRAYSTOMAP && COINCHANGEOBJECT
// Associative Arrays, or Objects, are sometimes referred to as maps, because a key (string) maps to a value. Given two arrays, create an associative array (map) containing keys of the first, and values of the second. For arr1 = ['abc', 3, 'yo'] and arr2 = [42, 'wassup', true], arraysToMap(arr1, arr2) should return {'abc': 42, '3':'wassup', 'yoo': true}
// Session - https://vimeo.com/album/4281485/video/193958597
// 12/2/2016 PARENS VALID && BRACES VALID
// Create a function parensValid(str) that takes a string that may contain parentheses and determine if the parentheses are in a valid order. Given "h(e(l)l)0" return true. Given "n)o(p)e" return false.
// Create a function bracesValid(str) that takes a string that may contain parentheses, braces, and brackets, and determine if they are in a valid format. Given "{h(e)y}[]" return true. Given "{h(e}l[l)o]" return false. There are many more examples of true and false varieties.
// Session - https://vimeo.com/194127428/eec1968ce5
// 12/8/2016 LONGEST COMMON SUFFIX
// Lance is writing his opus: Epitome, an epic tome of beat poetry. Always ready for a good rhyme, he contantly seeks words that end with the same letters. Write a function that, when given a word array, returns the largest suffix(word-end) common to all words in the array. For input ["deforestation", "citation", "conviction", "incarceration"], return "tion" (not very creative). If input is ["nice", "ice", "baby"], return "".
// Session - https://vimeo.com/album/4281485/video/194903365
// 12/9/2016 DNA TRANSCRIPTION && INVERT HASH
// Given an input string consisting of DNA nucleotides, e.g. 'ACGGGTAAG', return a list of the amino acids that would be assembled by the corresponding string of mRNA, in this case the mRNA strand would be 'UGCCCAUUC', which would produce a list of these amino-acids ['Cys','Pro','Phe']. The process is thus, DNA ('ACGGGTAAG') is converted to mRNA('UGCCCAUUC') which is then turned into codons ('UGC', 'CCA',UUC), which are then turned into nucleotides(Cys, Pro, Phe) using a codon chart.
// Additionally, write an algorithm that given a hash(Associative Array), returns the hash with previous keys as values and the values as keys. For example, invert({'a':'b'}) => {'b':'a'}. There are a wide variety of edge cases for this, it is up to you to document how and why you handle certain cases a certain way.
// Session - https://vimeo.com/195051444
<file_sep>/book/ch3/removearray.js
// Remove array
//
// Given array, and indices start and end, remove vals in that index range, working in-place (hence shortening the array). Given ([20,30,40,50,60,70],2,4), change to [20,30,70] and return it.
a = [20,30,40,50,60,70];
removeArray(a,2,4);
console.log(a);
function removeArray(arr,start,stop){
console.log("Remove values from " + arr[start] + " to " + arr[stop]);
while(start - 1 != stop){
//shift values left
for(var i = start; i < arr.length - 1; i++){
arr[i] = arr[i + 1];
}
arr.pop();
stop--;
}
//console.log(arr);
}
<file_sep>/slack/algos1/1-20-17.js
// 1/20/2017 ADDBACK && LENGTH
// addBack(value): Create a function that creates a listNode with given value and inserts it at end of a linked list.
// length(): Create a function that accepts a pointer to the first list node, and returns number of nodes in that sList.
<file_sep>/book/ch6/stacks.js
function Stack(){
var arr = [];
this.push = function(val){
arr.push(val);
return this;
}
this.pop = function(val){
if(arr.length === 0){
return null;
} else {
return arr.pop();
}
}
this.top = function(){
if(arr.length === 0){
return null;
} else {
return arr[arr.length - 1];
}
}
this.sizeOf = function(){
return arr.length;
}
this.isEmpty = function(){
if(arr.length === 0){
return true;
} else {
return false;
}
}
this.contains = function(val){
if(arr.length === 0){
return false;
} else {
for(var i = 0; i < arr.length; i++){
if(arr[i] === val){
return true;
}
}
return false;
}
}
}
var ourStack = new Stack();
console.log(ourStack.isEmpty());
ourStack.push(3).push(5).push(-3).push(10);
console.log(ourStack.pop());
console.log(ourStack.contains(6));
console.log(ourStack.isEmpty());
console.log(ourStack.sizeOf());
<file_sep>/book/ch1/countdown.js
countdown();
function countdown(){
var start = 2016;
while(start > 0){
console.log(start);
start-=4;
}
}
<file_sep>/git_algos/week_01_arrays/arraysday3.js
//Arrays Day 3
//array rotate
// console.log(rotateArr([1,2,3],-2));
// function rotateArr(arr,shiftBy){
// var shiftact = 0;
// if(shiftBy > 0){
// shiftact = shiftBy % arr.length;
// } else if (shiftBy < 0){
// shiftact = arr.length - (Math.abs(shiftBy) % arr.length);
// }
// console.log(shiftact);
// if(shiftact === 0){
// return arr;
// } else {
// var temp = 0;
// for(var i = 0; i < shiftact; i++){
// for(var x = arr.length - 1; x > 0; x--){
// if(x === arr.length - 1){
// temp = arr[x];
// }
// arr[x] = arr[x-1];
// }
// arr[0] = temp;
// }
// return arr;
// }
// }
//array filter range (does not maintain order)
//console.log(filterRange([1,2,3,4,5],2,4));
// console.log(filterRange([2,5,3,1,0,6,3,8,4,9],2,4));
// function filterRange(arr,min,max){
// var index = 0;
// while(index < arr.length){
// if(arr[index] < min || arr[index] > max){
// arr[index] = arr[arr.length - 1];
// arr.pop();
// } else {
// index++;
// }
// console.log(arr);
// }
// return arr;
// }
//array filter - maintain order
// console.log(filterRange([1,2,3,4,5],2,4));
// console.log(filterRange([2,5,3,1,0,6,3,8,4,9],2,4));
// function filterRange(arr,min,max){
// var index = 0;
// while(index < arr.length){
// if(arr[index] < min || arr[index] > max){ //lets shift everything down and pop the last
// for (var i = index; i < arr.length - 1; i++){
// arr[i] = arr[i+1];
//
// //console.log(arr);
// }
// arr.pop();
// } else {
// index++;
// }
// }
// return arr;
// }
// // Array concat
// console.log(arrayConcat(['a','b'],[1,2]));
// function arrayConcat(arr1, arr2){
// var new_arr = [];
// for(var i = 0; i < arr1.length; i++){
// new_arr.push(arr1[i]);
// }
// for(var i = 0; i < arr2.length; i++){
// new_arr.push(arr2[i]);
// }
// return new_arr;
// }
<file_sep>/book/ch1/whathappenstoday.js
console.log(whatHappensToday());
function whatHappensToday(){
}
<file_sep>/book/ch1/paramcountdown.js
paramcountdown(3,5,17,9);
function paramcountdown(param1, param2, param3, param4){
while(param2 < param3 ){
if(param2%param1 === 0 && param2 !== param4){
console.log(param2);
}
param2++;
}
}
<file_sep>/book/ch1/flexcountdown.js
flexcountdown(2,9,3);
function flexcountdown(lownum, highnum, mult){
while(highnum > lownum ){
console.log(highnum);
highnum-=mult;
}
}
<file_sep>/book/ch4/stringtrim.js
var test_str = " \n hello goodbye \t ";
console.log("\"" + trimstr(test_str) + "\"");
function trimstr(str){
var arr = str.split("");
for(var i = 0; i < arr.length; i++){
if(arr[i] == "\\" && arr[i + 1] == "n"){
arr[i] = "";
arr[i + 1] = "";
} else if(arr[i] == "\\" && arr[i + 1] == "t"){
arr[i] = "";
arr[i + 1] = "";
} else if(arr[i] == " "){
arr[i] = "";
}
}
return arr.join("");
}
<file_sep>/git_algos/week_01_arrays/arraysday2.js
//Divide and Conquery challenges
//reverse array
// console.log(revArr([3,1,6,4,2]));
// function revArr(arr){
// var temp = 0;
// for(var i = 0; i < arr.length/2; i++){
// temp = arr[i];
// arr[i] = arr[arr.length - 1 - i];
// arr[arr.length - 1 - i] = temp;
// }
// return arr;
// }
//remove negatives
// console.log(removeNegs([2,-1,4,-2,5]));
// function removeNegs(arr){
// var new_arr = [];
// for(var i = 0; i < arr.length; i++){
// if(arr[i] >= 0){
// new_arr.push(arr[i]);
// }
// }
// return new_arr;
// }
//array min to front
// console.log(minToFront([4,3,1,5,6]));
// function minToFront(arr){
// var min = arr[0];
// for(var i = 1; i < arr.length; i++){
// if(arr[i] < min){
// arr[0] = arr[i];
// arr[i] = min;
// min = arr[0];
// }
// }
// return arr;
// }
//skyline heights
// console.log(skylineHeights([1,-1,7,3]));
// function skylineHeights(arr){
// var new_arr = [];
// var prev = arr[0];
// new_arr.push(prev); //we assume we will always see the first building
// for(var i = 1; i < arr.length; i++){
// if(arr[i] > prev){
// prev = arr[i];
// new_arr.push(prev);
// }
// }
// return new_arr;
// }
<file_sep>/book/ch3/shuffle.js
// Shuffle
//
// Recreate the shuffle(arr) function built into JavaScript, to efficiently shuffle a given array’s values. Work in-place, of course. Do you need to return anything from your function?
a = [20,30,40,50,60,70];
console.log(a);
shuffleArr(a);
console.log(a);
function shuffleArr(arr){
var newpos = 0;
var temp = 0;
for(var i = 0; i < arr.length; i++){
newpos = Math.trunc(Math.random()*(arr.length - 1));
temp = arr[i];
arr[i] = arr[newpos];
arr[newpos] = temp;
}
}
<file_sep>/book/ch1/addodds.js
addOdds(-300000,300000);
function addOdds(start,finish){
var delta = start + finish;
if (delta !== 0){
for(var i = 0; i < delta; i++){
if(i%2 !== 0)
console.log(i);
}
} else {
console.log("values cancel");
}
}
<file_sep>/book/ch3/arrayconcat.js
// // Array concat
console.log(arrayConcat(['a','b'],[1,2]));
function arrayConcat(arr1, arr2){
var new_arr = [];
for(var i = 0; i < arr1.length; i++){
new_arr.push(arr1[i]);
}
for(var i = 0; i < arr2.length; i++){
new_arr.push(arr2[i]);
}
return new_arr;
}
<file_sep>/book/ch1/ftoc.js
console.log(fToC(60));
function fToC(fDegrees){
return ((fDegrees - 32) * 5) / 9;
}
| ccb338726d091b830c7aaf53376a6f59e5aef524 | [
"JavaScript"
] | 104 | JavaScript | salarsen/Algorithms | ce4d369fe626b95051d8f783cd972df4f93c7d95 | 81489ee234a3c4b5ad86467ed0708380700b79e1 |
refs/heads/master | <repo_name>wooly-booly/rentaway<file_sep>/routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
// Auth::routes();
Route::get('/', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('/', 'Auth\LoginController@login');
Route::post('logout', 'Auth\LoginController@logout')->name('logout');
Route::get('/products', 'ProductsController@list')->name('home');
Route::get('/products/{product}', 'ProductsController@product')->name('product');
Route::post('/products/{product}', 'ProductsController@store')->name('store.product.trip');
Route::get('/checkout', 'CheckoutController@checkout')->name('checkout');
Route::post('/checkout', 'CheckoutController@confirm')->name('checkout.confirm');<file_sep>/app/Presenters/ProductPresenter.php
<?php
namespace App\Presenters;
use Laracasts\Presenter\Presenter;
class ProductPresenter extends Presenter
{
public function price_per_day()
{
return '$ ' . $this->price * 24 . ' per day';
}
}<file_sep>/app/Http/Requests/TripRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class TripRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'date_start' => 'required',
'time_start' => 'required',
'date_end' => 'required',
'time_end' => 'required',
'trip_start' => [
// format must be like 'Tue, Nov 21, 2017 03:00 PM'
new \App\Rules\DateRules\CheckDateFormat(),
// if trip_start < now
'after:now',
],
'trip_end' => [
new \App\Rules\DateRules\CheckDateFormat(),
// if trip_start > trip_end
'after:trip_start',
// if interval between dates < 24 hours
new \App\Rules\DateRules\MinIntervalBetweenDates($this->trip_start),
// If another trip is already booked for this time
new \App\Rules\DateRules\AnotherTripAlreadyBooked($this->product, $this->trip_start, $this->trip_end),
],
];
}
protected function prepareForValidation()
{
$this->merge([
'trip_start' => $this->date_start . ' ' . $this->time_start,
'trip_end' => $this->date_end . ' ' . $this->time_end
]);
}
}
<file_sep>/database/factories/ProductImageFactory.php
<?php
use Faker\Generator as Faker;
$factory->define(App\Models\ProductImage::class, function (Faker $faker) {
return [
'product_id' => function() {
return factory(App\Models\Product::class)->create()->id;
},
'image' => $faker->imageUrl(640, 320, 'transport'),
'position' => $faker->randomDigitNotNull(),
];
});
<file_sep>/database/seeds/DemoDataSeeder.php
<?php
use Illuminate\Database\Seeder;
class DemoDataSeeder extends Seeder
{
public function run()
{
$this->truncateAllTables();
// Create product (in our example it's car)
factory(App\Models\Product::class, 20)->create()->each(
function ($product) {
// Create images for product
factory(App\Models\ProductImage::class, 4)->create(["product_id" => $product->id]);
// Create trip where we use created product
$trip = factory(App\Models\Trip::class)->create(["product_id" => $product->id]);
// Create order with created trip
factory(App\Models\Order::class)->create(["trip_id" => $trip->id]);
}
);
}
protected function truncateAllTables($excepts = ['migrations'])
{
$tables = DB::connection()
->getPdo()
->query("SHOW FULL TABLES")
->fetchAll();
DB::statement('SET FOREIGN_KEY_CHECKS=0;');
foreach ($tables as $table) {
$tableName = $table[0];
if (in_array($tableName, $excepts))
continue;
DB::table($tableName)->truncate();
}
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
}
}<file_sep>/app/Http/Controllers/CheckoutController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\CheckoutConfirmRequest;
use Illuminate\Support\Facades\DB;
use App\Models\Product;
use App\Models\Order;
use App\Models\Trip;
use Carbon\Carbon;
class CheckoutController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function checkout(Request $request)
{
$order = $this->getOrderInfo($request);
return view('checkout.checkout', compact('order'));
}
public function confirm(CheckoutConfirmRequest $request, Order $order, Trip $trip)
{
$data = $this->getOrderInfo($request);
DB::transaction(function() use ($order, $trip, $data, $request) {
$trip->fill([
'product_id' => $data['product']['id'],
'trip_start' => new Carbon($data['trip_start']),
'trip_end' => new Carbon($data['trip_end']),
])->save();
$order->fill([
'user_id' => $request->user()->id,
'trip_id' => $trip->id,
'total' => $data['total_price'],
])->save();
$request->session()->forget('trip_order');
$request->session()->flash('success',
'Trip order (' . $data['trip_start'] . ' - ' . $data['trip_end'] . ') created successfully!'
);
});
return back();
}
private function getOrderInfo(Request $request)
{
$order = [];
if ($request->session()->has('trip_order')) {
$order = $request->session()->get('trip_order')[0]->all();
$product = Product::findOrFail($order['product']);
$tripStart = new Carbon($order['trip_start']);
$tripEnd = new Carbon($order['trip_end']);
$order['trip_hours'] = $tripStart->diffInHours($tripEnd);
$order['total_price'] = $product->price * $order['trip_hours'];
$order['product'] = $product->toArray();
}
return $order;
}
}
<file_sep>/app/Rules/DateRules/AnotherTripAlreadyBooked.php
<?php
namespace App\Rules\DateRules;
use Illuminate\Contracts\Validation\Rule;
use App\Models\Trip;
use Carbon\Carbon;
class AnotherTripAlreadyBooked implements Rule
{
protected $productId;
protected $tripStart;
protected $tripEnd;
protected $alreadyBookedTrip = null;
/**
* Create a new rule instance.
*
* @return void
*/
public function __construct($productId, $tripStart, $tripEnd)
{
$this->productId = $productId;
$this->tripStart = (new Carbon($tripStart))->toDateTimeString();
$this->tripEnd = (new Carbon($tripEnd))->toDateTimeString();
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
$this->alreadyBookedTrip = Trip::where(function ($q) {
$q->whereBetween('trip_start', [$this->tripStart, $this->tripEnd])
->where('trip_start', '!=', $this->tripEnd)
->where('product_id', $this->productId);
})->orWhere(function ($q) {
$q->whereBetween('trip_end', [$this->tripStart, $this->tripEnd])
->where('trip_end', '!=', $this->tripStart)
->where('product_id', $this->productId);
})->orWhere(function ($q) {
$q->whereRaw('trip_start < ? and trip_end > ?', [$this->tripStart, $this->tripEnd])
->where('product_id', $this->productId);
})->first();
if ($this->alreadyBookedTrip) {
return false;
} else {
return true;
}
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
$tripStart = $this->dateFormat($this->alreadyBookedTrip->trip_start);
$tripEnd = $this->dateFormat($this->alreadyBookedTrip->trip_end);
return "Another trip ($tripStart - $tripEnd) already booked on this time.";
}
protected function dateFormat($date)
{
return (new Carbon($date))->toDayDateTimeString();
}
}
<file_sep>/app/Rules/DateRules/CheckDateFormat.php
<?php
namespace App\Rules\DateRules;
use Illuminate\Contracts\Validation\Rule;
class CheckDateFormat implements Rule
{
/**
* Create a new rule instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
if (\DateTime::createFromFormat('D, M d, Y H:i a', $value) !== false) {
return true;
} else {
return false;
}
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'Incorrect date format.';
}
}
<file_sep>/tests/Feature/TripsTest.php
<?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Carbon\Carbon;
use App\Models\Product;
use App\Models\Trip;
class TripsTest extends TestCase
{
use RefreshDatabase;
public function setUp()
{
parent::setUp();
$this->signIn();
$this->product = factory(\App\Models\Product::class)->create();
}
public function testTripStartMustBeGreaterThenCurrentTime()
{
$data = [
'product_id' => $this->product->id,
'date_start' => 'Fri, Nov 10, 2017',
'time_start' => '12:00 AM',
'date_end' => 'Thu, Dec 01, 2050',
'time_end' => '12:00 AM',
];
$this->post(
'/products/' . $this->product->id, $data, ['HTTP_X-Requested-With' => 'XMLHttpRequest']
)->assertSee('trip_start');
}
public function testTripStartCantBeGreaterTripEnd()
{
$data = [
'product_id' => $this->product->id,
'date_start' => 'Fri, Dec 02, 2050',
'time_start' => '12:00 AM',
'date_end' => 'Thu, Dec 01, 2050',
'time_end' => '12:00 AM',
];
$this->post(
'/products/' . $this->product->id, $data, ['HTTP_X-Requested-With' => 'XMLHttpRequest']
)->assertSee('trip_end');
}
public function testIntervalBetweenStartAndEndMustBe24Hours()
{
$data = [
'product_id' => $this->product->id,
'date_start' => 'Thu, Dec 01, 2050',
'time_start' => '11:00 PM',
'date_end' => 'Fri, Dec 02, 2050',
'time_end' => '12:00 AM',
];
$this->post(
'/products/' . $this->product->id, $data, ['HTTP_X-Requested-With' => 'XMLHttpRequest']
)->assertSee('trip_end');
}
public function testShouldNotBeAlreadyBookedTripsAtTimeWeWantToBook()
{
$trip = factory(\App\Models\Trip::class)->create([
'product_id' => $this->product->id,
'trip_start' => new Carbon('Fri, Nov 13, 2037 02:00 AM'),
'trip_end' => new Carbon('Sat, Nov 14, 2037 02:00 AM'),
]);
$data = [
'product_id' => $this->product->id,
'date_start' => 'Thu, Nov 12, 2037',
'time_start' => '11:00 PM',
'date_end' => 'Fri, Nov 13, 2050',
'time_end' => '05:00 AM',
];
$this->post(
'/products/' . $this->product->id, $data, ['HTTP_X-Requested-With' => 'XMLHttpRequest']
)->assertSee('trip_end')
->assertSee('already booked');
}
}
<file_sep>/app/Http/Controllers/ProductsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Product;
use App\Http\Requests\TripRequest;
use Session;
class ProductsController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function list(Product $products)
{
$products = $products->with('trips')->paginate(10);
return view('products.list', compact('products'));
}
public function product($id)
{
$product = Product::with(['trips', 'images'])->findOrFail($id);
return view('products.product', compact('product'));
}
public function store(TripRequest $request)
{
$data = $request->only(['trip_start', 'trip_end']);
$data['product'] = $request->product;
Session::forget('trip_order');
Session::push('trip_order', collect($data));
return redirect()->route('checkout');
}
}
<file_sep>/app/Models/Trip.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Trip extends Model
{
public $timestamps = false;
protected $fillable = [
'product_id', 'trip_start', 'trip_end'
];
public function product()
{
return $this->belongsTo('App\Models\Product');
}
public function order()
{
return $this->belongsTo('App\Models\Order', 'trip_id', 'id');
}
}
<file_sep>/database/factories/TripFactory.php
<?php
use Faker\Generator as Faker;
use Carbon\Carbon;
$factory->define(App\Models\Trip::class, function (Faker $faker) {
$trip_start = new Carbon('NOW + 24 hour');
$trip_end = clone $trip_start;
$trip_end->addHours($faker->numberBetween(24, 72));
return [
'product_id' => function() {
return factory(App\Models\Product::class)->create()->id;
},
'trip_start' => $trip_start,
'trip_end' => $trip_end,
];
});<file_sep>/database/factories/OrderFactory.php
<?php
use Faker\Generator as Faker;
use Carbon\Carbon;
$factory->define(App\Models\Order::class, function (Faker $faker) {
$trip_id = '';
return [
'user_id' => function() {
return factory(App\Models\User::class)->create()->id;
},
'trip_id' => function() use (&$trip_id) {
return $trip_id = factory(App\Models\Trip::class)->create()->id;
},
'comment' => $faker->sentence(),
'total' => function (array $post) use ($trip_id) {
$trip = App\Models\Trip::find($post['trip_id'] ?? $trip_id);
$trip_start = Carbon::parse($trip->trip_start);
$trip_end = Carbon::parse($trip->trip_end);
$hours = $trip_start->diffInHours($trip_end);
return $hours * $trip->product->price;
},
];
});<file_sep>/app/Rules/DateRules/MinIntervalBetweenDates.php
<?php
namespace App\Rules\DateRules;
use Illuminate\Contracts\Validation\Rule;
use Carbon\Carbon;
class MinIntervalBetweenDates implements Rule
{
protected $date;
/**
* Create a new rule instance.
*
* @return void
*/
public function __construct($date)
{
$this->date = new Carbon($date);
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
$date = new Carbon($value);
if ($this->date->diffInHours($date) < 24) {
return false;
} else {
return true;
}
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'Minimum rental period 24 hours.';
}
}
<file_sep>/database/factories/ProductFactory.php
<?php
use Faker\Generator as Faker;
$factory->define(App\Models\Product::class, function (Faker $faker) {
return [
'title' => $faker->word,
'description' => $faker->paragraph(),
'image' => $faker->imageUrl(640, 320, 'transport'),
'price' => $faker->numberBetween(5, 50), // Price per hour
];
}); | a40b4774dc9759aae651e5591350d431c69a1d6a | [
"PHP"
] | 15 | PHP | wooly-booly/rentaway | 1eebc4a6b5d8d7355f939827b10b2df5653927e1 | e73e0eec7d64d851c13e8c9c4db96cb206f33536 |
refs/heads/master | <repo_name>Ujjwal1987/wifihotspot<file_sep>/Wifiserver.py
import subprocess
from bottle import run, post, template, request, response, get, route, static_file
import shutil
import bottle
import os
bottle.TEMPLATE_PATH.insert(0,'/home/openhabian/')
@route('/')
def index():
return template('index')
@post('/wifi')
def setwifi():
wifissid = request.forms.get('wifissid')
password = request.forms.get('psw')
shutil.copy('/etc/wpa_supplicant/wpa_supplicant.conf', '/etc/wpa_supplicant/wpa_supplicant1.conf')
f = open("/etc/wpa_supplicant/wpa_supplicant1.conf", "r")
wpafile=f.readlines()
print wpafile[0],wpafile[1],wpafile[2],wpafile[3],wpafile[4],wpafile[5],wpafile[6],wpafile[7],wpafile[8]
ssidStart=wpafile[5].find("\"",1)
ssidEnd=wpafile[5].find("\"",ssidStart+1)
pswStart=wpafile[6].find("\"",1)
pswEnd=wpafile[6].find("\"",pswStart+1)
lenstr_ssid=len(wpafile[5])
lenstr_psw=len(wpafile[6])
f.close()
oldstr_ssid=wpafile[5][ssidStart+1:ssidEnd]
oldstr_psw= wpafile[6][pswStart+1:pswEnd]
repstr_ssid=wpafile[5].replace(oldstr_ssid,wifissid,1)
repstr_psw=wpafile[6].replace(oldstr_psw,password,1)
f1 = open("/etc/wpa_supplicant/wpa_supplicant.conf", "w")
f1.write(wpafile[0])
f1.write(wpafile[1])
f1.write(wpafile[2])
f1.write(wpafile[3])
f1.write(wpafile[4])
f1.write(repstr_ssid)
f1.write(repstr_psw)
f1.write(wpafile[7])
f1.write(wpafile[8])
print wpafile[0],wpafile[1],wpafile[2],wpafile[3],wpafile[4],repstr_ssid,repstr_psw,wpafile[7],wpafile[8]
f1.close()
f2 = open("/home/openhabian/wifistatus.txt", "w")
f2.write("1")
f2.close
shutil.copy('/etc/dnsmasq.conf.back1', '/etc/dnsmasq.conf')
shutil.copy('/etc/dhcpcd.conf.back1', '/etc/dhcpcd.conf')
os.system('reboot')
run(host='192.168.4.1', port=8000, debug=True)
<file_sep>/KuIncludedStartUp-first-boot.sh.back
#!/bin/bash
# Log everything to file
exec &> >(tee -a "/boot/first-boot.log")
timestamp() { date +"%F_%T_%Z"; }
fail_inprogress() {
rm -f /opt/openHABian-install-inprogress
touch /opt/openHABian-install-failed
echo -e "$(timestamp) [openHABian] Initial setup exiting with an error!\\n\\n"
exit 1
}
echo "$(timestamp) [openHABian] Starting the openHABian initial setup."
rm -f /opt/openHABian-install-failed
touch /opt/openHABian-install-inprogress
echo -n "$(timestamp) [openHABian] Storing configuration... "
cp /boot/openhabian.conf /etc/openhabian.conf
sed -i 's/\r$//' /etc/openhabian.conf
# shellcheck source=openhabian.raspbian.conf
source /etc/openhabian.conf
echo "OK"
userdef="pi"
echo -n "$(timestamp) [openHABian] Changing default username and password... "
if [ -z ${username+x} ] || ! id $userdef &>/dev/null || id "$username" &>/dev/null; then
echo "SKIPPED"
else
usermod -l "$username" $userdef
usermod -m -d "/home/$username" "$username"
groupmod -n "$username" $userdef
chpasswd <<< "$username:$userpw"
echo "OK"
fi
# While setup: show log to logged in user, will be overwritten by openhabian-setup.sh
echo "watch cat /boot/first-boot.log" > "/home/$username/.bash_profile"
if [ -z "${wifi_ssid}" ]; then
echo "$(timestamp) [openHABian] Setting up Ethernet connection... OK"
elif grep -q "openHABian" /etc/wpa_supplicant/wpa_supplicant.conf; then
echo "$(timestamp) [openHABian] Setting up Wi-Fi connection... OK"
else
echo -n "$(timestamp) [openHABian] Setting up Wi-Fi connection... "
echo -e "# config generated by openHABian first boot setup" > /etc/wpa_supplicant/wpa_supplicant.conf
echo -e "country=US\\nctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\\nupdate_config=1" >> /etc/wpa_supplicant/wpa_supplicant.conf
echo -e "network={\\n\\tssid=\"$wifi_ssid\"\\n\\tpsk=\"$wifi_psk\"\\n\\tkey_mgmt=WPA-PSK\\n}" >> /etc/wpa_supplicant/wpa_supplicant.conf
echo "OK, rebooting... "
reboot
fi
echo -n "$(timestamp) [openHABian] Ensuring network connectivity... "
cnt=0
until ping -c1 9.9.9.9 &>/dev/null || [ "$(wget -qO- http://www.msftncsi.com/ncsi.txt)" == "Microsoft NCSI" ]; do
sleep 1
cnt=$((cnt + 1))
#echo -n ". "
if [ $cnt -eq 100 ]; then
echo "FAILED"
if grep -q "openHABian" /etc/wpa_supplicant/wpa_supplicant.conf && iwconfig 2>&1 | grep -q "ESSID:off"; then
echo ""
echo "I was not able to connect to the configured Wi-Fi."
echo "Please try again with your correct SSID and password."
echo "Also check your signal quality. Available Wi-Fi networks:"
iwlist wlan0 scanning | grep "ESSID" | sed 's/^\s*ESSID:/\t- /g'
echo ""
else
echo "$(timestamp) [openHABian] The public internet is not reachable. Please check your network."
fi
fail_inprogress
fi
done
echo "OK"
echo -n "$(timestamp) [openHABian] Waiting for dpkg/apt to get ready... "
until apt update &>/dev/null; do sleep 1; done
echo "OK"
echo -n "$(timestamp) [openHABian] Updating repositories and upgrading installed packages... "
apt update &>/dev/null
apt --yes upgrade &>/dev/null
if [ $? -eq 0 ]; then echo "OK"; else echo "FAILED"; fail_inprogress; fi
echo -n "$(timestamp) [openHABian] Installing git package... "
apt update &>/dev/null
/usr/bin/apt -y install git &>/dev/null
if [ $? -eq 0 ]; then echo "OK"; else echo "FAILED"; fail_inprogress; fi
echo -n "$(timestamp) [openHABian] Cloning myself... "
/usr/bin/git clone -b master https://github.com/openhab/openhabian.git /opt/openhabian &>/dev/null
#/usr/bin/git clone -b develop https://github.com/openhab/openhabian.git /opt/openhabian &>/dev/null
if [ $? -eq 0 ]; then echo "OK"; else echo "FAILED"; fail_inprogress; fi
ln -sfn /opt/openhabian/openhabian-setup.sh /usr/local/bin/openhabian-config
echo "$(timestamp) [openHABian] Executing 'openhabian-setup.sh unattended'... "
if (/bin/bash /opt/openhabian/openhabian-setup.sh unattended); then
#if (/bin/bash /opt/openhabian/openhabian-setup.sh unattended_debug); then
systemctl start openhab2.service
rm -f /opt/openHABian-install-inprogress
touch /opt/openHABian-install-successful
else
fail_inprogress
fi
echo "$(timestamp) [openHABian] Execution of 'openhabian-setup.sh unattended' completed."
echo -n "$(timestamp) [openHABian] Waiting for openHAB to become ready... "
until wget -S --spider http://localhost:8080 2>&1 | grep -q 'HTTP/1.1 200 OK'; do
sleep 1
done
echo "OK"
echo "$(timestamp) [openHABian] Visit the openHAB dashboard now: http://$hostname:8080"
echo "$(timestamp) [openHABian] To gain access to a console, simply reconnect."
echo "$(timestamp) [openHABian] First time setup successfully finished."
#Executed after compltion of first_boot script
#######Install KuControl_startUp.sh script
# vim: filetype=sh
#!/bin/bash
cd /home/openhabian
echo 'git clone https://github.com/Ujjwal1987/wifihotspot.git'
/usr/bin/git clone -b master https://github.com/Ujjwal1987/wifihotspot.git &>/dev/null
echo 'aptt-get update'
until apt-get update &>/dev/null; do sleep 1 ; done
echo "OK"
echo 'apt-get -y install mosquitto mosquitto-clients'
until apt-get -y install mosquitto mosquitto-clients &>/dev/null; do sleep 1; done
echo "OK"
echo 'mosquitto_passwd -b /etc/mosquitto/passwd openhabian Ujjwal1234$'
mosquitto_passwd -b /etc/mosquitto/passwd openhabian Ujjwal1234$
echo 'systemctl enable mosquitto.service'
systemctl enable mosquitto.service
echo 'systemctl restart mosquitto.service'
systemctl restart mosquitto.service
echo 'apt-get -y install dnsmasq hostapd'
until apt-get -y install dnsmasq hostapd &>/dev/null; do sleep 1; done
echo "OK"
#echo 'git clone https://github.com/Ujjwal1987/wifihotspot.git'
#git clone https://github.com/Ujjwal1987/wifihotspot.git
#echo 'git clone https://github.com/Ujjwal1987/Autodiscovery.git'
#/usr/bin/git clone https://github.com/Ujjwal1987/Autodiscovery.git &>/dev/null
#if [ $? -eq 0 ]; then echo "OK"; else echo "Failed"; fi
echo 'cp -r /home/openhabian/wifihotspot/autodiscover /etc/systemd/'
cp -r /home/openhabian/wifihotspot/autodiscover /etc/systemd/
echo 'cp -r /home/openhabian/wifihotspot/autodiscover.service /etc/systemd/system/'
cp -r /home/openhabian/wifihotspot/autodiscover.service /etc/systemd/system/
#load addons in /var/lib....for execution of included functions before loading mqtt.cfg
echo 'load /var/lib/openhab2/config/org/openhab/openhabcloud.config'
file=/var/lib/openhab2/config/org/openhab/openhabcloud.config
file1=/home/openhabian/wifihotspot/openhabcloud.config
if [ ! -f $file ]
then cp $file1 $file
else
echo "/var/lib/openhab2/config/org/openhab/openhabcloud.config not copied-already exists"
fi
#load addons in /etc/openhab2/services...for execution of included functions before loading mqtt.cfg
echo 'load /etc/openhab2/services/addons.cfg'
file=/etc/openhab2/services/addons.cfg
file1=/home/openhabian/wifihotspot/addons.cfg
while [ ! -f $file ]
do
echo "addons.cfg file does not exist"
done
echo 'cp /home/openhabian/wifihotspot/addons.cfg /etc/openhab2/services/'
cp /home/openhabian/wifihotspot/addons.cfg /etc/openhab2/services/
#load mqtt.cfg in /etc/openhab2/services
echo 'load /etc/openhab2/service/mqtt.cfg'
file=/etc/openhab2/services/mqtt.cfg
file1=/home/openhabian/wifihotspot/mqtt.cfg
while [ ! -f $file ]
do
echo "mqtt.cfg file does not exist"
done
cp $file1 $file
echo 'cp /home/openhabian/wifihotspot/kucontrol.service /etc/avahi/services/'
cp /home/openhabian/wifihotspot/kucontrol.service /etc/avahi/services/
echo 'cp /home/openhabian/wifihotspot/dhcpcd.conf.back /etc/'
cp /home/openhabian/wifihotspot/dhcpcd.conf.back /etc/
echo 'cp /home/openhabian/wifihotspot/dhcpcd.conf.back1 /etc/'
cp /home/openhabian/wifihotspot/dhcpcd.conf.back1 /etc/
echo 'cp /home/openhabian/wifihotspot/dnsmasq.conf.back /etc/'
cp /home/openhabian/wifihotspot/dnsmasq.conf.back /etc/
echo 'cp /home/openhabian/wifihotspot/dnsmasq.conf.back1 /etc/'
cp /home/openhabian/wifihotspot/dnsmasq.conf.back1 /etc/
echo 'cp /home/openhabian/wifihotspot/hostapd.conf /etc/hostapd/hostapd.conf'
cp /home/openhabian/wifihotspot/hostapd.conf /etc/hostapd/hostapd.conf
echo 'cp /home/openhabian/wifihotspot/wifihotspot.service /etc/systemd/system/'
cp /home/openhabian/wifihotspot/wifihotspot.service /etc/systemd/system/
echo 'cp /home/openhabian/wifihotspot/wifi.sh /home/openhabian/'
cp /home/openhabian/wifihotspot/wifi.sh /home/openhabian/
echo 'cp /home/openhabian/wifihotspot/Wifiserver.py /home/openhabian'
cp /home/openhabian/wifihotspot/Wifiserver.py /home/openhabian
echo 'cp /home/openhabian/wifihotspot/index.html /home/openhabian'
cp /home/openhabian/wifihotspot/index.html /home/openhabian
echo 'cp /home/openhabian/wifihotspot/hostapd /etc/default/hostapd'
cp /home/openhabian/wifihotspot/hostapd /etc/default/hostapd
chmod 755 /etc/systemd/autodiscover/*
echo 'systemctl enable autodiscover.service'
systemctl enable autodiscover.service
echo 'systemctl start autodiscover.service'
systemctl start autodiscover.service
echo 'systemctl enable wifihotspot.service'
systemctl enable wifihotspot.service
echo 'systemctl start wifihotspot.service'
systemctl start wifihotspot.service
#echo 'systemctl /home/openhabian/wifihotspot unmask hostapd'
echo 'systemctl unmask hostapd'
#systemctl /home/openhabian/wifihotspot unmask hostapd
systemctl unmask hostapd
echo 'systemctl enable hostapd'
systemctl enable hostapd
echo 'systemctl start hostapd'
systemctl start hostapd
echo 'pip install bottle'
pip install bottle
<file_sep>/wifi.sh.papaback
#!/bin/bash
while true
do
sleep 120
connected_network="$(iwconfig wlan0| grep ESSID | cut -c 31-100)"
stored_network="$(cat /etc/wpa_supplicant/wpa_supplicant.conf | grep ssid | cut -c 8-100)"
echo 'connected_network=' $connected_network
echo 'stored_network=' $stored_network
if [ $connected_network == $stored_network ]; then
echo "i am if"
echo 'connected_network=' $connected_network
echo 'stored_network=' $stored_network
echo "1" > /home/openhabian/wifistatus.txt
wifistatus="$(cat /home/openhabian/wifistatus.txt)"
echo 'wifistatus=' $wifistatus
else
wifistatus="$(cat /home/openhabian/wifistatus.txt)"
sleep 2
echo 'wifistatus=' $wifistatus
if [[ $wifistatus == "0" ]]; then
echo 'I am else..python'
echo 'connected_network=' $connected_network
echo 'stored_network=' $stored_network
echo 'wifistatus=' $wifistatus
sudo python /home/openhabian/Wifiserver.py
else
echo "i am else..hotspot configuration"
echo 'connected_network=' $connected_network
echo 'stored_network=' $stored_network
echo 'wifistatus=' $wifistatus
sudo cp /etc/dhcpcd.conf.back /etc/dhcpcd.conf
sudo cp /etc/dnsmasq.conf.back /etc/dnsmasq.conf
#sudo systemctl restart dhcpcd.service
#sudo systemctl reload dnsmasq
echo "0" > /home/openhabian/wifistatus.txt
echo 'rebooting'
sudo reboot
fi
fi
done
<file_sep>/KuControl_StartUp.sh
echo 'apt-get update'
apt-get update
echo 'apt-get -y install mosquitto mosquitto-clients'
apt-get -y install mosquitto mosquitto-clients
echo 'mosquitto_passwd -b /etc/mosquitto/passwd openhabian Ujjwal1234$'
mosquitto_passwd -b /etc/mosquitto/passwd openhabian U<PASSWORD>34$
echo 'systemctl enable mosquitto.service'
systemctl enable mosquitto.service
echo 'systemctl restart mosquitto.service'
systemctl restart mosquitto.service
echo 'apt-get -y install dnsmasq hostapd'
apt-get -y install dnsmasq hostapd
echo 'git clone https://github.com/Ujjwal1987/wifihotspot.git'
git clone https://github.com/Ujjwal1987/wifihotspot.git
echo 'git clone https://github.com/Ujjwal1987/Autodiscovery.git'
git clone https://github.com/Ujjwal1987/Autodiscovery.git
echo 'cp -r /home/openhabian/wifihotspot/autodiscover /etc/systemd/'
cp -r /home/openhabian/wifihotspot/autodiscover /etc/systemd/
echo 'cp -r /home/openhabian/wifihotspot/autodiscover.service /etc/systemd/system/'
cp -r /home/openhabian/wifihotspot/autodiscover.service /etc/systemd/system/
echo 'cp /home/openhabian/wifihotspot/addons.cfg /etc/openhab2/services/'
cp /home/openhabian/wifihotspot/addons.cfg /etc/openhab2/services/
echo 'cp /home/openhabian/wifihotspot/kucontrol.service /etc/avahi/services/'
cp /home/openhabian/wifihotspot/kucontrol.service /etc/avahi/services/
echo 'cp /home/openhabian/wifihotspot/dhcpcd.conf.back /etc/'
cp /home/openhabian/wifihotspot/dhcpcd.conf.back /etc/
echo 'cp /home/openhabian/wifihotspot/dhcpcd.conf.back1 /etc/'
cp /home/openhabian/wifihotspot/dhcpcd.conf.back1 /etc/
echo 'cp /home/openhabian/wifihotspot/dnsmasq.conf.back /etc/'
cp /home/openhabian/wifihotspot/dnsmasq.conf.back /etc/
echo 'cp /home/openhabian/wifihotspot/dnsmasq.conf.back1 /etc/'
cp /home/openhabian/wifihotspot/dnsmasq.conf.back1 /etc/
echo 'cp /home/openhabian/wifihotspot/hostapd.conf /etc/hostapd/hostapd.conf'
cp /home/openhabian/wifihotspot/hostapd.conf /etc/hostapd/hostapd.conf
echo 'cp /home/openhabian/wifihotspot/wifihotspot.service /etc/systemd/system/'
cp /home/openhabian/wifihotspot/wifihotspot.service /etc/systemd/system/
echo 'cp /home/openhabian/wifihotspot/wifi.sh /home/openhabian/'
cp /home/openhabian/wifihotspot/wifi.sh /home/openhabian/
echo 'cp /home/openhabian/wifihotspot/Wifiserver.py /home/openhabian'
cp /home/openhabian/wifihotspot/Wifiserver.py /home/openhabian
echo 'cp /home/openhabian/wifihotspot/index.html /home/openhabian'
cp /home/openhabian/wifihotspot/index.html /home/openhabian
echo 'cp /home/openhabian/wifihotspot/hostapd /etc/default/hostapd'
cp /home/openhabian/wifihotspot/hostapd /etc/default/hostapd
chmod 755 /etc/systemd/autodiscover/*
echo 'systemctl enable autodiscover.service'
systemctl enable autodiscover.service
echo 'systemctl start autodiscover.service'
systemctl start autodiscover.service
echo 'systemctl enable wifihotspot.service'
systemctl enable wifihotspot.service
echo 'systemctl start wifihotspot.service'
systemctl start wifihotspot.service
echo 'systemctl /home/openhabian unmask hostapd'
systemctl /home/openhabian unmask hostapd
echo 'systemctl enable hostapd'
systemctl enable hostapd
echo 'systemctl start hostapd'
systemctl start hostapd
echo 'pip install bottle'
pip install bottle
echo 'sudo reboot'
sleep 10
sudo reboot
<file_sep>/autodiscover/AUTODISCOVER
#!/bin/bash
sudo /usr/bin/java -jar /etc/systemd/autodiscover/autodiscover.jar
| 9a113e29cca9a2a6da6435b71c0a42c4451f32f8 | [
"Python",
"Shell"
] | 5 | Python | Ujjwal1987/wifihotspot | 5c4634a49be1adec7d746727cab8c196924950d7 | bec9c2ad258ff05db5c573abbebe3e16370eafd0 |
refs/heads/master | <file_sep>self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "71f121b57f058ec91de8acc0af2a0f53",
"url": "/index.html"
},
{
"revision": "4275234329df5579aaf2",
"url": "/static/css/main.75d6fcaa.chunk.css"
},
{
"revision": "4c801da6dce4ca3098d2",
"url": "/static/js/2.5ac1d375.chunk.js"
},
{
"revision": "4275234329df5579aaf2",
"url": "/static/js/main.18e69ea8.chunk.js"
},
{
"revision": "97300621a1e59c7bc9ba",
"url": "/static/js/runtime-main.3a2dce39.js"
}
]); | a1ad4b4863fdf1fdcc64f89d43aaffbcc4565b11 | [
"JavaScript"
] | 1 | JavaScript | nets-intranets/publish | ca1bcda18c614af40eb02a1828f8da70497e95b3 | eb064e337afdeb62df36739aa782e373b9dc2b32 |
refs/heads/master | <repo_name>L0v3B3l/l0v3b3l.github.io<file_sep>/js/ima.js
// movimiento de imagenes
var humo = new Array();
humo[0] = "img/Smoke1.png";
humo[1] = "img/Smoke2.png";
humo[2] = "img/Smoke3.png";
var delay = 1000;
var count = 1;
var imaMovimiento = new Array();
for (i=0;i<humo.length;i++) {
imaMovimiento[i] = new Image();
imaMovimiento[i].src = humo[i];
}
function moviendo () {
if (window.createPopup)
humeante.filters[0].apply();
document.images.humeante.src = imaMovimiento[count].src;
if (window.createPopup)
humeante.filters[0].play();
count++;
if (count==imaMovimiento.length)
count = 0;
setTimeout("moviendo()",delay);
}
window.onload = new Function("setTimeout('moviendo()',delay)");
| 2120f2a493a8e900d35848d5be6fca37076c2260 | [
"JavaScript"
] | 1 | JavaScript | L0v3B3l/l0v3b3l.github.io | ba3d8b3b5509fd5392963264923d78c20935858b | b5dddd265236c6f1d081022135650f5d7efac3f4 |
refs/heads/master | <repo_name>githubisagit/CS301Assignment3<file_sep>/app/src/main/java/com/example/tan19/cs301assignment3/CannonMainActivity.java
package com.example.tan19.cs301assignment3;
import android.graphics.Color;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
/**
* CannonMainActivity
*
* This is the activity for the cannon animation. It creates a AnimationCanvas
* containing a particular Animator object
*
* @author <NAME>, <NAME>
* @version April 2017
*
*/
public class CannonMainActivity extends Activity implements SeekBar.OnSeekBarChangeListener, Button.OnClickListener {
/**
* creates an AnimationCanvas containing a CannonBallAnimator.
*/
private SeekBar angleSeekBar ;
private Button launchButton, gravButton;
private AnimationCanvas myCanvas;
private TextView hitText ;
private EditText gravText ;
CannonBallAnimator ballAnimator = new CannonBallAnimator();
private boolean launched = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cannon_main);
// Create an animation canvas and place it in the main layout
myCanvas = new AnimationCanvas(this, ballAnimator);
LinearLayout mainLayout = (LinearLayout) this
.findViewById(R.id.screen);
mainLayout.addView(myCanvas);
hitText = (TextView)findViewById(R.id.hitText);
gravText = (EditText)findViewById(R.id.gravText);
angleSeekBar = (SeekBar)findViewById(R.id.angleSeekBar);
angleSeekBar.setOnSeekBarChangeListener(this);
launchButton = (Button)findViewById(R.id.launchButton);
launchButton.setOnClickListener(this);
gravButton = (Button)findViewById(R.id.gravButton);
gravButton.setOnClickListener(this);
myCanvas.invalidate();//just in case!
}
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
int angle = i ;
ballAnimator.getMyCannon().translate(i);//sends the progress value of the seekBar as a degreeValue for the Cannon.
//these new values are used to rotate the CannonBall object along with the Cannon.
float newBallX = ballAnimator.getMyCannon().getRotatePointX();
float newBallY = ballAnimator.getMyCannon().getRotatePointY();
//set the new Cannon Ball Values.
ballAnimator.getMyBall().setOrigX(newBallX+40);
ballAnimator.getMyBall().setOrigY(newBallY+20);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
@Override
public void onClick(View view) {
//if the launched button has been pressed, trigger the launched flag.
if(view.getId() == launchButton.getId()) {
launched = !launched;
if (launched) {
ballAnimator.isLaunched(true);
} else {
ballAnimator.isLaunched(false);
}
}
//ADDED in HW3B, this button is used to change a ball's gravity value.
if(view.getId() == gravButton.getId()){
String gravString = gravText.getText().toString();
int newGravVal = Integer.parseInt(gravString);
float actualGravVal = (float)newGravVal;
actualGravVal = (actualGravVal / 10);
ballAnimator.getMyBall().setGravityDelta(actualGravVal);
ballAnimator.getMyBall().reset();
}
}
}
| acafecde6b95b1ba0f11333e7e0ecd1f1fdf5bce | [
"Java"
] | 1 | Java | githubisagit/CS301Assignment3 | b0543835c6bc1d2cd512d29fcdceb6872818f85f | 0704d00ab7c939b6ffeb0652db377368939c468d |
refs/heads/master | <repo_name>maraskaras123/Client-database<file_sep>/include/UpdateInteg.php
<?PHP
require_once("db.php");
$currBeforeCount = 0;
foreach ($_FILES['before']['name'] as $f => $name) {
$curr_path = "../photos/" . $_POST['visit'] . "_before_" . $currBeforeCount . ".jpg";
if(move_uploaded_file($_FILES["before"]["tmp_name"][$f], $curr_path)) {
echo "The file ". $name . " has been uploaded as " . $curr_path . "</br>";
$before_query = "UPDATE visits SET before_count = {$beforeCount} WHERE visit_id = {$_POST['visit']}";
DB::$db->query($before_query);
$currBeforeCount++; // Number of successfully uploaded file
}
}
$currAfterCount = 0;
foreach ($_FILES['after']['name'] as $f => $name) {
$curr_path = "../photos/" . $_POST['visit'] . "_after_" . $currAfterCount . ".jpg";
if(move_uploaded_file($_FILES["after"]["tmp_name"][$f], $curr_path)) {
echo "The file ". $name . " has been uploaded as " . $curr_path . "</br>";
$after_query = "UPDATE visits SET after_count = {$afterCount} WHERE visit_id = {$_POST['visit']}";
DB::$db->query($after_query);
$currAfterCount++; // Number of successfully uploaded file
}
}
$beforeCount = $currBeforeCount;
$afterCount = $currAfterCount;
if ($beforeCount > 0){
$before_query = "UPDATE visits SET before_count = {$beforeCount} WHERE visit_id = {$_POST['visit']}";
DB::$db->query($before_query);
}
if ($afterCount > 0){
$after_query = "UPDATE visits SET after_count = {$afterCount} WHERE visit_id = {$_POST['visit']}";
DB::$db->query($after_query);
}
header("Location: ../visit.php?id={$_POST['visit']}");
exit();
?><file_sep>/include/ClientInteg.php
<?PHP
require_once("db.php");
$createQuery = "INSERT INTO clients (name, surname, birth, sex, number, remarks) VALUES ".
"('".$_POST['name'].
"', '". $_POST['surname'].
"', '". $_POST['date'].
"', '". $_POST['sex'].
"', '". $_POST['country'].$_POST['number'].
"', '". $_POST['remarks']."')";
if (DB::$db->query($createQuery) === TRUE) {
echo "New record created successfully";
sleep(1);
header('Location: ../main.php'); exit();
} else {
echo "Error: " . $createQuery . "<br>" . DB::$db->error;
}
?><file_sep>/scripts/userPick.js
$(document).ready(function(){
if ($('.visit tbody').is(':parent'))
$('p').css("display", "none");
$('.visit tbody tr').click(function(){
var id = document.getElementById("person");
id.setAttribute("value", $(this).attr('id'));
var picker = document.getElementById("picker").setAttribute('style', 'display: none;');
var main = document.getElementById("main").setAttribute('style', 'display: block;');
});
});<file_sep>/include/DBInteg.php
<?php
require_once("db.php");
$main_query = "SELECT visit_id, person_id, date FROM visits";
$person_query = "SELECT name, surname, number FROM clients WHERE client_id = \"";
$name_query = "SELECT client_id, name, surname, number FROM clients WHERE name = \"";
$surname_query = "SELECT client_id, name, surname, number FROM clients WHERE surname = \"";
$name_surname_query = "SELECT client_id, name, surname, number FROM clients WHERE name = \"!\" AND surname = \"?\"";
$visit_query = "SELECT visit_id, date FROM visits WHERE person_id = \"";
$client_query = "SELECT client_id, name, surname, number FROM clients";
$date_query = "SELECT visit_id, person_id, date FROM visits WHERE date = \"";
$visitID_query = "SELECT visit_id, person_id, date, type, amount, currency, price, remarks, before_count, after_count FROM visits WHERE visit_id = \"";
$clientID_query = "SELECT client_id, name, surname, birth, sex, number, remarks FROM clients WHERE client_id = \"";
function getAllVisits($main_query, $person_query){
$main_result = DB::$db->query($main_query);
while($row = $main_result->fetch_assoc()){
$id = $row['person_id'];
$person_result = DB::$db->query($person_query . $id . "\"");
$person = $person_result->fetch_assoc();
echo ("<tr id=\"" . $row['visit_id'] . "\"><td>" . $person['name'] . "</td><td>" . $person['surname'] . "</td><td>" . $row['date'] . "</td><td>" . $person['number'] . "</td></tr>");
}
}
function getVisitsByName($name_query, $visit_query, $name){
$name_result = DB::$db->query($name_query . $name . "\"");
while($row = $name_result->fetch_assoc()){
$visit_result = DB::$db->query($visit_query . $row['client_id'] . "\"");
$visit = $visit_result->fetch_assoc();
echo ("<tr id=\"" . $visit['visit_id'] . "\"><td>" . $row['name'] . "</td><td>" . $row['surname'] . "</td><td>" . $visit['date'] . "</td><td>" . $row['number'] . "</td></tr>");
}
}
function getVisitsByNameAndSurname($name_surname_query, $visit_query, $name, $surname){
$query = str_replace("!", $name, $name_surname_query);
$query = str_replace("?", $surname, $query);
$name_surname_result = DB::$db->query($query);
while($row = $name_surname_result->fetch_assoc()){
$visit_result = DB::$db->query($visit_query . $row['client_id'] . "\"");
$visit = $visit_result->fetch_assoc();
echo ("<tr id=\"" . $visit['visit_id'] . "\"><td>" . $row['name'] . "</td><td>" . $row['surname'] . "</td><td>" . $visit['date'] . "</td><td>" . $row['number'] . "</td></tr>");
}
}
function getVisitsBySurname($surname_query, $visit_query, $surname){
$surname_result = DB::$db->query($surname_query . $surname . "\"");
while($row = $surname_result->fetch_assoc()){
$visit_result = DB::$db->query($visit_query . $row['client_id'] . "\"");
$visit = $visit_result->fetch_assoc();
echo ("<tr id=\"" . $visit['visit_id'] . "\"><td>" . $row['name'] . "</td><td>" . $row['surname'] . "</td><td>" . $visit['date'] . "</td><td>" . $row['number'] . "</td></tr>");
}
}
function getVisitsByDate($date_query, $person_query, $date){
$date = date("Y-m-d", strtotime($date));
$date_result = DB::$db->query($date_query . $date . "\"");
while($row = $date_result->fetch_assoc()){
$person_result = DB::$db->query($person_query . $row['person_id'] . "\"");
$person = $person_result->fetch_assoc();
echo ("<tr id=\"" . $row['visit_id'] . "\"><td>" . $person['name'] . "</td><td>" . $person['surname'] . "</td><td>" . $row['date'] . "</td><td>" . $person['number'] . "</td></tr>");
}
}
function getAllClients($client_query){
$client_result = DB::$db->query($client_query);
while($row = $client_result->fetch_assoc()){
echo ("<tr id=\"" . $row['client_id'] . "\"><td>" . $row['name'] . "</td><td>" . $row['surname'] . "</td><td>" . $row['number'] . "</td></tr>");
}
}
function getClientsByName($client_query, $name){
$client_result = DB::$db->query("{$client_query} WHERE name = \"{$name}\"");
while($row = $client_result->fetch_assoc()){
echo ("<tr id=\"" . $row['client_id'] . "\"><td>" . $row['name'] . "</td><td>" . $row['surname'] . "</td><td>" . $row['number'] . "</td></tr>");
}
}
function getClientsBySurname($client_query, $surname){
$client_result = DB::$db->query("{$client_query} WHERE surname = \"{$surname}\"");
while($row = $client_result->fetch_assoc()){
echo ("<tr id=\"" . $row['client_id'] . "\"><td>" . $row['name'] . "</td><td>" . $row['surname'] . "</td><td>" . $row['number'] . "</td></tr>");
}
}
function getClientsByNameAndSurname($client_query, $name, $surname){
$client_result = DB::$db->query("{$client_query} WHERE name = \"{$name}\" AND surname = \"{$surname}\"");
while($row = $client_result->fetch_assoc()){
echo ("<tr id=\"" . $row['client_id'] . "\"><td>" . $row['name'] . "</td><td>" . $row['surname'] . "</td><td>" . $row['number'] . "</td></tr>");
}
}
function getClientsByNumber($client_query, $number){
$client_result = DB::$db->query("{$client_query} WHERE number = \"{$number}\"");
while($row = $client_result->fetch_assoc()){
echo ("<tr id=\"" . $row['client_id'] . "\"><td>" . $row['name'] . "</td><td>" . $row['surname'] . "</td><td>" . $row['number'] . "</td></tr>");
}
}
function getVisitByID($visitID_query, $ID){
$visitID_result = DB::$db->query($visitID_query . $ID . "\"");
$visit = $visitID_result->fetch_assoc();
return $visit;
}
function getClientByID($clientID_query, $ID){
$clientID_result = DB::$db->query($clientID_query . $ID . "\"");
$client = $clientID_result->fetch_assoc();
return $client;
}
?><file_sep>/createClient.php
<?PHP
require_once("include/membersite_config.php");
require_once("include/DBInteg.php");
require_once("include/db.php");
if(!$fgmembersite->CheckLogin()) {
$fgmembersite->RedirectToURL("index.php");
exit;
}
?>
<DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style/Form.css" />
<title>visit info</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form action="include/ClientInteg.php" method="post">
<ul class="form-style-1" style="max-width: 400px;">
<li>
<label>Full Name</label>
<input type="text" name="name" class="field-divided" placeholder="Name" /> <input type="text" name="surname" class="field-divided" placeholder="Surname" />
</li>
<li>
<label>Birth date</label>
<input type="number" name="date" class="field-long" placeholder="Year" />
</li>
<li>
<label>Sex</label>
<select name="sex" class="field-select">
<option value="woman">woman</option>
<option value="man">man</option>
</select>
</li>
<li>
<label>Number</label>
<select name="country" style='width: 20%;'>
<option value="+44">+44</option>
<option value="+370">+370</option>
</select> <input type="number" name="number" placeholder="Number" style="width: 78.5%;" />
</li>
<li>
<label>Remarks</label>
<textarea name="remarks" id="remarks" class="field-long field-textarea" placeholder="Optional" ></textarea>
</li>
<li>
<input type="submit" value="Submit" name="submit" />
</li>
</ul>
</form>
</body>
</html><file_sep>/scripts/visit.js
$(document).ready(function(){
$("img").click(function(){
if($("#overlay").css("display") == "none")
{
$("#overlay").css("display", "block");
$("#overlay").css("z-index", "20");
var img = $(this).attr("src");
$("#overlayimg").attr("src", img);
$("#overlayimg").css("height","80%");
}
else
{
$("#overlay").css("display", "none");
$("#overlay").css("z-index", "0");
$("#overlayimg").attr("src", "");
}
});
});<file_sep>/main.php
<?PHP
require_once("include/membersite_config.php");
require_once("include/DBInteg.php");
require_once("include/db.php");
if(!$fgmembersite->CheckLogin())
{
$fgmembersite->RedirectToURL("index.php");
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style/style.css" />
<link rel="stylesheet" type="text/css" href="style/Form.css" />
<title>main</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="scripts/clickRow.js"></script>
</head>
<body>
<p class="main-logout">
<a href='createClient.php' style='margin-right: 4.5%;'><button style="background: #3DBBFF;">create client</button></a>
<a href='createVisit.php'><button style="background: #3DBBFF;">create visit</button></a>
<a href='logout.php' style='margin-left: 4.5%;'><button>logout</button></a>
</p>
<form action="main.php" method="post">
<ul class="form-style-1" style="width: 100%;">
<li style="display: inline;"><input type="text" name="name" class="field-quater" placeholder="Name" /></li>
<li style="display: inline;"><input type="text" name="surname" class="field-quater" placeholder="Surname" /></li>
<li style="display: inline;"><input type="date" name="date" class="field-quater" placeholder="Date" /></li>
<li style="display: inline;"><input type="submit" value="Submit" name="submit" class="field-quater"></li>
</ul>
</form>
<div style="overflow-x:auto;">
<table class="visit">
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Date</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<?
if (!empty($_POST['name']) && !empty($_POST['surname']))
getVisitsByNameAndSurname($name_surname_query, $visit_query, $_POST['name'], $_POST['surname']);
else if(!empty($_POST['name']))
getVisitsByName($name_query, $visit_query, $_POST['name']);
else if (!empty($_POST['surname'])){
getVisitsBySurname($surname_query, $visit_query, $_POST['surname']);
}
else if (!empty($_POST['date']))
getVisitsByDate($date_query, $person_query, $_POST['date']);
else
getAllVisits($main_query, $person_query);
?>
</tbody>
</table>
</div>
</body>
</html><file_sep>/logout.php
<?PHP
require_once("include/membersite_config.php");
$fgmembersite->LogOut();
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
<title>Logged out</title>
<link rel="stylesheet" type="text/css" href="style/style.css" />
</head>
<body>
<div class='form'>
<h2>You have logged out</h2>
<p class='logout'><a href='http://marozija.puslapiai.lt'><button>Login Again</button></a></p>
</div>
</body>
</html><file_sep>/index.php
<?PHP
require_once("./include/membersite_config.php");
if(isset($_POST['submitted'])){
if($fgmembersite->Login())
$fgmembersite->RedirectToURL("main.php");
}
if($fgmembersite->CheckLogin()){
$fgmembersite->RedirectToURL("main.php");
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
<title>Login</title>
<link rel="stylesheet" type="text/css" href="style/style.css" />
</head>
<body>
<div class="login-page">
<form class="form" action='<?php echo $fgmembersite->GetSelfScript(); ?>' method='post' accept-charset='UTF-8'>
<input type='hidden' name='submitted' id='submitted' value='1'/>
<div><span class='error'><?php echo $fgmembersite->GetErrorMessage(); ?></span></div>
<div class='container'>
<label for='username' >UserName:</label><br/>
<input type='text' name='username' id='username' value='<?php echo $fgmembersite->SafeDisplay('username') ?>' maxlength="50" /><br/>
<span id='login_username_errorloc' class='error'></span>
</div>
<div class='container'>
<label for='password' >Password:</label><br/>
<input type='<PASSWORD>' name='password' id='password' maxlength="50" /><br/>
<span id='login_password_errorloc' class='error'></span>
</div>
<div class='container'>
<input type='submit' name='Submit' value='Login' />
</div>
</form>
</div>
</body>
</html><file_sep>/include/VisitInteg.php
<?PHP
require_once("db.php");
$result = DB::$db->query("SHOW TABLE STATUS LIKE 'visits'");
$data = $result->fetch_assoc();
$next_increment = $data['Auto_increment'];
$date = date("Y-m-d", strtotime($_POST['date']));
$currBeforeCount = 0;
foreach ($_FILES['before']['name'] as $f => $name) {
$curr_path = "../photos/" . $next_increment . "_before_" . $currBeforeCount . ".jpg";
if(move_uploaded_file($_FILES["before"]["tmp_name"][$f], $curr_path)) {
echo "The file ". $name . " has been uploaded as " . $curr_path . "</br>";
$currBeforeCount++; // Number of successfully uploaded file
}
}
$currAfterCount = 0;
foreach ($_FILES['after']['name'] as $f => $name) {
$curr_path = "../photos/" . $next_increment . "_after_" . $currAfterCount . ".jpg";
if(move_uploaded_file($_FILES["after"]["tmp_name"][$f], $curr_path)) {
echo "The file ". $name . " has been uploaded as " . $curr_path . "</br>";
$currAfterCount++; // Number of successfully uploaded file
}
}
$beforeCount = $currBeforeCount;
$afterCount = $currAfterCount;
$query = "INSERT INTO visits (person_id, date, type, amount, currency, price, remarks, before_count, after_count) VALUES ('{$_POST['person']}', '{$date}', '{$_POST['type']}', '{$_POST['amount']}', '{$_POST['currency']}', '{$_POST['price']}', '{$_POST['remarks']}', '{$beforeCount}', '{$afterCount}')";
if (DB::$db->query($query) === TRUE) {
echo "New record created successfully";
header('Location: ../main.php');
exit();
} else
echo "Error: " . $query . "<br>" . DB::$db->error;
?><file_sep>/visit.php
<?PHP
require_once("include/membersite_config.php");
require_once("include/DBInteg.php");
require_once("include/db.php");
if(!$fgmembersite->CheckLogin()) {
$fgmembersite->RedirectToURL("index.php");
exit;
}
?>
<DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style/style.css" />
<link rel="stylesheet" type="text/css" href="style/visit.css" />
<link rel="stylesheet" type="text/css" href="style/Form.css" />
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
<title>visit info</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="scripts/visit.js"></script>
</head>
<body style="font-size: 30px; font-weight: bold; text-align: center;">
<div id="overlay" style="width:100%;z-index: 0; height: 100%;position:fixed; background-color: black; display: none;">
<img id='overlayimg' src='' alt='unable to get photo'></img>
</div>
<a href='main.php'><button style="background: #3DBBFF; width: 700px; padding: 2px; height: 50px; font-size: 20px; z-index: 2;"><strong>Back to visits</strong></button></a>
<div class="form" style="width: 700px; max-width: 700px; margin-top: 20px; margin-bottom: 0px; padding: 2px; background: #ffffb3;">
<p>
<?php
$visit = getVisitByID($visitID_query, $_GET['id']);
$client = getClientByID($clientID_query, $visit['person_id']);
echo ("{$client['name']} {$client['surname']} {$client['birth']}<br>");
echo ("{$client['number']}<br>");
echo ("{$visit['date']}<br>");
echo ("Type & amount: {$visit['type']} {$visit['amount']}<br>");
echo ("Price: {$visit['price']} {$visit['currency']}");
?>
</p>
</div>
<div class="form" style="width: 700px; max-width: 700px; margin-top: 10px; margin-bottom: 0px; padding: 2px; background: #ffffb3;">
<p>
Before photos:
<?
if($visit['before_count'] == 0){
echo ('<form action="include/UpdateInteg.php" method="post" enctype="multipart/form-data">');
echo ("<input type='hidden' name='visit' id='visit' value='{$visit['visit_id']}' />");
echo ("<input type='hidden' name='type' id='type' value='before' />");
echo ('<input type="file" name="before[]" multiple="multiple" style="background-color: #bfbfbf; width: 500px;" accept="image/*">');
echo ('<input type="submit" value="Submit" name="submit" style="background-color: #bfbfbf; font-weight: bold; width: 500px;" />');
echo ('</form>');
}
else {
echo ("<br>");
for($i = 0; $i < $visit['before_count']; $i++){
//echo ("<a download='{$visit['visit_id']}_before_{$i}.jpg' href='photos/{$visit['visit_id']}_before_{$i}.jpg' title='ImageName'><img alt='{$visit['visit_id']}_before_{$i}.jpg' src='photos/{$visit['visit_id']}_before_{$i}.jpg'/></a>");
echo ("<img alt='{$visit['visit_id']}_before_{$i}.jpg' src='photos/{$visit['visit_id']}_before_{$i}.jpg'/>");
}
}
?>
</p>
</div>
<div class="form" style="width: 700px; max-width: 700px; margin-top: 10px; margin-bottom: 0px; padding: 2px; background: #ffffb3;">
<p>
After photos:
<?
if($visit['after_count'] == 0){
echo ('<form action="include/UpdateInteg.php" method="post" enctype="multipart/form-data">');
echo ("<input type='hidden' name='visit' id='visit' value='{$visit['visit_id']}' />");
echo ("<input type='hidden' name='type' id='type' value='after' />");
echo ('<input type="file" name="after[]" multiple="multiple" style="background-color: #bfbfbf; width: 500px;" accept="image/*">');
echo ('<input type="submit" value="Submit" name="submit" style="background-color: #bfbfbf; font-weight: bold; width: 500px;" />');
echo ('</form>');
}
else {
echo ("<br>");
for($i = 0; $i < $visit['after_count']; $i++){
//echo ("<a download='{$visit['visit_id']}_after_{$i}.jpg' href='photos/{$visit['visit_id']}_after_{$i}.jpg' title='ImageName'><img alt='{$visit['visit_id']}_after_{$i}.jpg' src='photos/{$visit['visit_id']}_after_{$i}.jpg'/></a>");
echo ("<img alt='{$visit['visit_id']}_after_{$i}.jpg' src='photos/{$visit['visit_id']}_after_{$i}.jpg'/>");
}
}
?>
</p>
</div>
<?
if (!empty($client['remarks'])){
?>
<div class="form" style="width: 700px; max-width: 700px; margin-top: 10px; margin-bottom: 0px; padding: 2px; background: #ffffb3;">
<p>
<?echo ("client remarks:<br><span>{$client['remarks']}</span>");?>
</p>
</div>
<?} if (!empty($visit['remarks'])){ ?>
<div class="form" style="width: 700px; max-width: 700px; margin-top: 10px; margin-bottom: 0px; padding: 2px; background: #ffffb3;">
<p>
<?echo ("visit remarks:<br><span>{$visit['remarks']}</span>");?>
</p>
</div>
<? } ?>
</body>
</html><file_sep>/createVisit.php
<?PHP
require_once("include/membersite_config.php");
require_once("include/DBInteg.php");
require_once("include/db.php");
if(!$fgmembersite->CheckLogin()) {
$fgmembersite->RedirectToURL("index.php");
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style/style.css" />
<link rel="stylesheet" type="text/css" href="style/Form.css" />
<title>visit info</title>
<script src="scripts/jquery-3_1_1_min.js"></script>
<script src="scripts/userPick.js"></script>
</head>
<body>
<div id="picker">
<form action="/createVisit.php" method="post">
<ul class="form-style-1" style="width: 98%;">
<li style="display: inline;"><input type="text" name="name" class="field-quater" placeholder="Name" /></li>
<li style="display: inline;"><input type="text" name="surname" class="field-quater" placeholder="Surname" /></li>
<li style="display: inline;"><input type="text" name="number" class="field-quater" placeholder="Number" /></li>
<li style="display: inline;"><input type="submit" value="Submit" name="submit" class="field-quater" /></li>
</ul>
</form>
<p class="main-logout" style="text-align: center; display: block;">
<a href='createClient.php'><button style="background: #3DBBFF; width: 45%; height: 31px; padding-top: 8px;">create client</button></a>
</p>
<table class="visit">
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Number</th>
</tr>
</thead>
<?
if(!empty($_POST['name']) && !empty($_POST['surname']))
getClientsByNameAndSurname($client_query, $_POST['name'], $_POST['surname']);
else if(!empty($_POST['name']))
getClientsByName($client_query, $_POST['name']);
else if (!empty($_POST['surname']))
getClientsBySurname($client_query, $_POST['surname']);
else if (!empty($_POST['number']))
getClientsByNumber($client_query, $_POST['number']);
else
getAllClients($client_query);
?>
</table>
</div>
<div id="main" style="display: none;">
<form action="include/VisitInteg.php" method="post" enctype="multipart/form-data">
<input type='hidden' name='person' id='person' />
<ul class="form-style-1" style="max-width: 400px;">
<li>
<label>Date of visit</label>
<input type="date" name="date" class="field-long" placeholder="Date" />
</li>
<li>
<label>Type & amount</label>
<input type="text" name="type" class="field-divided" placeholder="Type" /> <input type="number" class="field-divided" step="0.01" name="amount" placeholder="Amount" />
</li>
<li>
<label>Price</label>
<select name="currency" style='width: 20%;'>
<option value="euros">euros</option>
<option value="pounds">pounds</option>
</select> <input type="number" name="price" placeholder="Price" style="width: 78.5%;" />
</li>
<li>
<label>Remarks</label>
<textarea name="remarks" id="remarks" class="field-long field-textarea" placeholder="Optional" ></textarea>
</li>
<li>
<label>Before photos</label>
<input type="file" name="before[]" multiple="multiple" accept="image/*">
</li>
<li>
<label>After photos</label>
<input type="file" name="after[]" multiple="multiple" accept="image/*">
</li>
<li>
<input type="submit" value="Submit" name="submit" />
</li>
</ul>
</form>
</div>
</body>
</html> | 093140818c4a1958cb31487650bacec5fe255197 | [
"JavaScript",
"PHP"
] | 12 | PHP | maraskaras123/Client-database | 4e3567bc7ac6989091ac7342b54d869a4d92e6d8 | 0fc0ab8caa5a8eb7ad45f4a0960bafd13f938290 |
refs/heads/master | <file_sep>---
title: "{{ replace .Name "-" " " | title }}"
slug: ""
author: "<NAME>"
date: "{{ .Date }}"
draft: true
comments: false
images:
---
<file_sep>---
title: "Why I Hike"
description: ""
slug: ""
author: "<NAME>"
date: "2020-05-06T12:36:44-06:00"
draft: false
toc: false
comments: true
cover: /2020-May/7-1.jpg
tags:
typora-root-url: ../../content
---
Over the last few weeks, precluded from leaving the house much, I have been watching out the back window at the birds that have come to drink from a basin of I water I fill each day. In particular one bird, a canyon towhee, is often there. He is much bigger than the other birds and therefore distinct. He is "native", whereas many of the others are european imports. But anyway, as time has gone on and I've had nothing to do, I have really grown fond of this big sparrow shaped bird. Though he's not that impressive in color, and doesn't have much of a song, he has a strong personality, and likes to root around under the apple tree, throwing sticks and leaves everywhere, in his search for food. I realized yesterday, as I saw him getting ready to sleep in the old dead tree across the alley (where he sleeps every night), how sad I would be if I one day found him dead. There are some really rough cats that prowl the alley and I always haze them by yelling (sorry cat lovers, [cats kill billions of birds every year](https://www.washingtonpost.com/national/health-science/outdoor-cats-kill-between-14-billion-and-37-billion-birds-a-year-study-says/2013/01/31/2504f744-6bbe-11e2-ada0-5ca5fa7ebe79_story.html)) and I thought also about how terrible it would be if this rare bird (canyon towhees are really rare in towns) got killed by someone's cat.
All this to say—since we're all cooped up inside, and all staring at screens too much, I think it's important to remember what's real and what's not. All the images we see on the screen neither live, nor die. They are just there every day in this endless feed, producing good and bad emotions, thoughts, etc. Yet if one of those images that we spend so much time looking at blinked out, we wouldn't even notice. There are so many that it's not even like they have any vitality to them at all. They are disposable before they even enter your consciousness—they are less memorable than breathing. And yet so much is wrapped up in those images and screens nowadays—which is a landscape not of vitality but of endless unimportance.
My thought is this: focusing on what we can see, even out our backdoor window, is sometimes more meaningful than the things our brains get hooked on and tell us to keep consuming. It's a different kind of attention that's needed to draw one to this "less interesting" experience. But the important part is that it actually makes us care about something, love something, connect with something—and maybe more importantly, want to protect it. And I guess that's part of why I go hiking.<file_sep>---
title: "April 27, 2020"
description: ""
slug: ""
author: "<NAME>"
date: "2020-04-27T08:21:09-06:00"
draft: false
toc: false
comments: true
cover: CJ-28APR20.jpg
tags: ["Corona Journal"]
typora-root-url: ../../content
---
Ten days of spring cold kept me indoors;
I didn't know willows were budding in the village.
In the frozen valley, a stream gurgles faintly;
sheets of green hide burnt stubble in the fields.
A few acres of poor land hold me here;
warming half a jug of cloudy wine, I wait for you.
A year ago today I crossed the mountain pass -
fine rain on plum flowers nearly broke my spirit.
**— Su Tung-p'o**<file_sep>---
title: "A Story About A Meditation Retreat, #3"
slug: "Meditation-03"
author: "<NAME>"
date: "2019-03-03T08:02:30"
draft: false
toc: false
comments: true
cover: 19.3-rocks.jpg
tags:
typora-root-url: ../../content
---
*"Is there something you want badly?" he asked.*
*And she replied almost greedily, gasping for breath: "Yes"— and burst into a storm of weeping.*
*"What?" he asked.*
*"I don't know," she wept in despair.*
*"You needn't be afraid of telling me, Sola dear. Maybe I can get it for you when I grow up."*
*"You wouldn't understand. You're so little. No one understands. I don't even understand it myself—day and night."*
*"Is it because of the way you're made?" he asked, full of sympathy and conscious that the discussion was verging now upon the most intimate secrets of the human body, which it is otherwise customary never to mention — possibly it was wrong of him, but the words had slipped his tongue before he realized.*
*"Yes," she sighed after a little reflection, disconsolately.*
*"It doesn't matter, Sola dear," he whispered then, and patted her cheek, determined to console her. "There's no need to find out. I won't tell anyone. I shall ask Gvendur not to tell anyone."*
*"So you know, then?" she asked, taking the cloth away from her eyes and looking him straight in the eyes "— you know?"*
*"No, Sola dear, I know nothing. I've never had a look; it doesn't matter. And anyway nobody can help it. And when I'm a big man, maybe I'll build a house in another country and then you can come and live with me and eat potatoes —"*
*"Potatoes? What do I want with potatoes?"*
*"Like it says in the Bible stories," he explained.*
*"There aren't any potatoes in the Bible stories."*
*"I mean what the woman ate in the Bible stories," he said.*
*"I don't want anything in the Bible stories," she said, gazing into space with tear-swollen eyes. "God is an enemy of the soul."*
*Then suddenly he asked: "What did you wish for in the winter, Sola, when the teacher gave us all a wish?"*
*First she looked at him searchingly, and the squint in her eyes seemed more pronounced than ever, because of her weeping; then her lids fell and she began uprooting grass from the sward. "You mustn't tell anyone," she said.*
*"No, I shall never tell anyone. What was it, then?"*
*"It was love," she said, and then once more her weeping burst its bonds, and again and again she repeated from the midst of her sobbing: "Love, love, love."*
*"How do you mean?" he asked.*
*She threw herself in a heap on the ground again, her shoulders shaking with sobs as they had done when he came up to her a few moments ago, and she wailed:*
*"I wish I could die. Die. Die."*
*He did not know what to say in the face of such sorrow. He sat in silence by his sister's side in the spring verdure, which was too young; and the hidden strings in his breast begin to quiver, and to sound.*
*This was the first time he had ever looked into the labyrinth of the human soul. He was very far from understanding what he saw. But what was of more value, he felt and suffered with her. In years that were yet to come he relieved this memory in song, in the most beautiful song the world has known. For understanding the soul's defencelessness, of the conflict between the two poles, is not the source of the greatest song. The source of the greatest song is sympathy. Sympathy with Asta Sollilja on earth.*
**— Independent People**

As I drove south through the storm, the lights of Taos flickered in and out on the horizon. The snow coated the road, and driving was slow. The jeep had turned off, and I was alone. It was the hour of reflection. There was nothing to do but drive slowly, watching the road, careful with traction, looking for the edges so as not to get stuck in my little four door sedan. It lent a measure of tension to the reflections that passed through my mind.
It's easy to go along and think: I understand this or that. Because the available material to work with, the few facts at hand, may create what looks like a full picture. The fact is, though, without knowing the full story of something, it's impossible to know the complete truth. And stories can change, depending on moods, who is telling them, what is remembered and forgotten. So what is this reality we live in after all?
Who am I, and what am I doing? I thought I had put these kinds of questions to rest a long time ago. But now, in my thirtieth year, I found that once again they came up, again and again. This nagging idea, that the story of my life wasn't the point of it all, had never gone anywhere, I had never answered it. If anything, it had gone deeper, and now, at age thirty, when "something was supposed to have happened," some career, some knowledge of the future, some success—absolutely nothing had. Even the goal I had set out to achieve four years before, which seemed reasonable to me at the time: to find a place to call home, hadn't been achieved. The only thing I felt I had learned was that there was never a final answer to anything.
In the past my answer has been "my art" to the question of "who are you." But as time has gone on, and my ideas of what it means to be successful have changed, and more questions have come up about the function and worth of art, and where it is useful, and who wants it, I began to doubt that. Maybe it was just a fanciful interpretation of life arisen from an easy time in my twenties. Of course people should produce beauty. Looking at the world closely, how could one not? What I had really come down to was this: did my life's work matter to anyone else? For so long I had studied and absorbed the world, books, films, recipes, experiences. And in the back of my mind I had this idea of a reservoir of experience, building up to a shining fullness, and from that deep, bountiful place I could draw things, write things, photograph things, say things, cook things that would somehow contribute to the world around me. But in my thirtieth year, I found the world more broken than ever. The ways my friends communicated dominated by platforms engineered to be addictive. People's attention spans shorter, and anxieties higher. City living incredibly stressful and expensive. Rural living lonely and isolating. The art, publishing, and photography worlds run by money, with frail offshoots of goodness. People's egos getting in the way of real work. But I refused, all along, to give up the kernel question, the question from which it all sprang from for me: "What really matters?"
But who am I to answer such a thing, even just for myself? And trying to answer it for others? Laughable.
At a certain point in this quest, photography and Instagram failed me. And then words, in the way I wrote them, failed me. But, just over a year ago, I began writing about all of this anyway. I wanted to make it congeal, to have some solution from it, to understand it. So I wrote, in the night after working during the day, on a farm on an island in Maine. The writing saved my life, and gave me hope, as the time on that island was amongst the most difficult so far in my life.
The writing came out as poems, instead of prose. It broke down into lines of simplistic sentences, more like short stories than anything. Over the last year I wrote almost 200 pages of this kind of writing, which I titled "A Body Of Water." Pretty much no one, besides one or two people, have seen or heard from that work. In the midst of writing it, I realized that to some degree my questions had been answered, in that there was no answer to them. I would just have to go along and find out. Experience would offer me what I was looking for, and then again it may never.
It's strange how the idea of quitting an attempt to understand something can, to me, seem almost as absurd as ever answering the question itself. And I guess that's where I leave it.
------
As I slid into town the snow thickened, falling like flour under the orange streetlights on Paseo del Pueblo Sur. Cars had gone off the road, I counted six. The hill past the plaza was sloppy, and I turned into the curb to prevent sliding into an intersection. Everyone else was driving around gingerly, the whole world coated in pure, beautiful new snow.
<file_sep>---
title: "The Sun in the Morning"
description: ""
slug: ""
author: "<NAME>"
date: "2020-04-15T08:10:13-06:00"
draft: false
toc: false
comments: true
cover: CJ-15APR-1.jpg
tags:
typora-root-url: ../../content
---





The sun rises in the morning above the northern wall of the alley. The window above my shikibuton looks out onto Oregon Grape plants that now have flowers. Bees and other insects come to the flowers for the nectar. The flowers are bright yellow, the same color as the core of the plant under the bark. The plant contains berberine, which makes it incredibly bitter. The flowers become fat, deep purple berries that are both sweet and bitter.
The plant itself can be used to treat psoriasis. Berberine is strongly anti-bacterial and anti-inflammatory. The root, dried and powdered, can be used directly on wounds to prevent infection, or taken orally for food poisoning. A tea of the roots/bark works as well.
The bitterness itself is good for digestion. Bitter flavor increases saliva production and other gastric juices, and even the production of hormones that stimulate the gall bladder (where bile is stored) and the pancreas.
The color of the flowers of the spiky Oregon Grape is really the same color as the sunlight. The bitter, spiky nature of the plant is interesting to encounter. Bitterness is restorative, though unpleasant in the process. Just like certain things in life. The deep green glossy leaves shelter small birds.
Today the color of the sunlight is white. The sky is blue. I listened to <NAME> speak yesterday about keeping squirrels from living in her roof by putting hot pepper into where they lived. Then she said: that if you have a place to stay, and you know how to get food, you really have all you need. You're OK. She said many people who are younger (she is 80) worry that life has changed and that they won't be able to do the things they had planned anymore. But as an old person, her perspective is different. She has lived through many calamities, and now has less life to look forward to than life she lived. So her perspective is different. Yet it's like an old tree vs a young one. It's safe to say that, despite the wisdom of her perspective, the two perspectives, of looking forward, and looking backward, are hard to reconcile.
I also heard someone say recently that there is no running away from your demons anymore. Indeed, there is little to distract from things. I often talk about the root of the bone, which is a funny phrase. I hope for everyone that they get closer to the root of the bone. It's spring and everyone should be together and doing things. Yet we are not. So it's root of the bone time.
I hear bears are wandering freely in Yosemite because there aren't millions of people there anymore. I wonder what flowers are blooming there. I wonder if there will be more flowers in such places than we've seen in years?
— Hudson<file_sep>---
title: "Corona Journal - Dishes"
subtitle: ""
slug: "dishes"
author: "<NAME>"
date: "2020-03-31T07:26:44-06:00"
draft: false
toc: false
comments: true
cover: 2020-31-3.jpg
tags: ["Corona Journal"]
typora-root-url: ../../content
---
Last night I washed the dishes left over from lunch. I washed them quickly at first, since washing dishes is such a boring task that has to be done every day. Long ago, it seems, I had determined that a chore like washing dishes held no real value, except in the clean dishes maybe—but in the act, the act of washing dishes there was nothing valuable.
To wash the dishes I turned on the water until it was warm. But while the water was flowing I placed some of the dishes, including a bowl and cutting board, in the sink so the water would run into them and start the cleaning process. I have a spray bottle loaded with a mixture of Dr. Bronners "All One" soap and water, that when shook creates instant suds. This I use to spray the dishes. It makes one bottle of soap last a few months.
As the water began to warm I did feel that I was in a kind of hurry. I was rushing to get the dishes done. Then I smelled the good scent of the lavender Bronner's soap, and also the warm water on my hands. And I started to wonder why I was in a hurry. All I had to do after this was go to sleep. There was nothing to rush to, unless it was bed, which doesn't usually end up very restful if rushed. Sleep can't be rushed, for example. It takes a set amount of time for the body to recover each night. I realized there wasn't anything to hurry-up towards, so I slowed down washing the dishes and washed each one very carefully. As I write now, I even remember what each dish looked like.
As the days spread out and slowly warm, birds have appeared on the rear patio. When money wasn't as tight I walked down Agua Fria to buy seed for them, putting it on a worn out stand someone had put up long ago. The plywood platform was cracked and feathered from years of rain, snow, and sun. But the canyon towhees, spotted towhees, sparrows, wrens, and one thrasher enjoyed the seed all the same. Now that we have no seed to offer, the birds eat seeds from weeds that we let grow and die last summer. And they bathe and drink out of a ceramic basin Anna made that I set on an sumac tree stump. I am glad we neglected the patio and let the native weeds grow, because now the birds have food. Yesterday I saw several eating buds from the apple tree. They didn't destroy the whole bud, though. They just took a little bite off each one. And when they drink water, two sips is enough. Yesterday I tried some of an apple bud. It was slightly bitter and sweet and tasted like the finest summer salad you can imagine.
<file_sep>---
title: "Myth Time"
description: ""
slug: ""
author: "<NAME>"
date: "2020-08-25T08:16:44-07:00"
draft: false
toc: false
comments: true
cover: /2020-August/25-1.jpg
tags:
typora-root-url: ../../content
---

**Myth Time**
Rocks to soft moss after a day of rain.
Sitting by the fire for hours.
Walking into the meadow flat for more wood
under dry spruce groves
where nothing grows and needles fill the alcoves.
Then laying for seven hours at night
to hear barred owls fly across the lake, telling tall tales
and land on an island in the lake, to raise their children...
*"Once, long ago, all animals were people, and
there were no people."*
Back in myth time, as the owls grow larger with each word they say
living still in myth time.
Up 2000' to Lost Lake, and down to camp.
Rain came again and stoking the fire
to boil white fir for tea
all day long.
Mist like muslin clings to peaks.
Blue steel cup, somewhat rusty, that Jacob uses to drink.
Piles of wood and stacks of branches our currency
to transform to light and heat.
The fire only thing that seemed real that day
the rest of the world locked in mist, far away
*myth time.*
Hundreds of bats against the ink blue sky at night.
Downpour and small lake formed
under Teal & Jacob's tent.
Cursing the high use of the area, but falling asleep easily
to the rain, feeling warm
wishing I was
nowhere else.
Wake first in morning, like on special days.
Watch orange mist make swirls and spiral into the air for an hour
the light change on the lake, and listen to silence.
Sun gets up and there is hope again.
Two pikas squeak in a rockslide as I run up to a ridge coated in wildflowers, alone
but for four deer
making their way
down the trail—
One buck with fuzzy antlers pauses, lets me watch him
and parts the dew so I may pass.
At the ridge edge looking into another drainage
I spy a hanging meadow of green grass and spruce
—*just a little farther, maybe an hour around that cornice,
then down into the cirque on rolly-polly rocks
then up a small ridge—* and I'd be there
a place where I could both live, and die.
But back down the the soaking trail
to pick up my sweater off a stump
then through a meadow filled with boulders and flowers
to my friends and family
and a long hike together
back to where we began.<file_sep>---
title: "A Story About a Meditation Retreat, #1"
slug: "Meditation-01"
author: "<NAME>"
date: "2019-03-01T08:02:30"
draft: false
toc: false
comments: true
cover: 19.2-mountains.jpg
tags:
typora-root-url: ../../content
---
The big mountains rose quickly from the flat piñon plain below. Massive, snow-capped mountains, and a sixty mile wide valley broke the scale of distance I was used to. And the weird piñons, with their twisted, old trunks, low tops, many branches: more like oaks than pine trees; held a strange presence. The plain itself savanna-like, with low grass and sagebrush, antelope, and slow-moving mule deer, who I would see in the mornings along the dry watercourses, under black cottonwoods.
I had driven north from Taos, through the wide valley to attend a meditation retreat in the Tibetan Bön tradition, an old tradition mixing Tibetan cultural practices and Buddhism. The retreat cost around $300 for a few days sleeping in a house and a few days sitting in a big circular room, listening to a rinpoche (lit. precious one) talk about Dzogchen, a type of meditation that involves relaxation and a unique lack of effort.
When I arrived, the first thing I noted was the number of new-model cars parked for the retreat. The majority were under five years old. A woman immediately walked up to me and said “are we supposed to park here? I’m gonna move my car. I think we’re supposed to park over there. I don’t think we can park here. I don’t know where.” She gestured vaguely towards a road running into the vast expanse of sagebrush. I shrugged and just kept walking.
At the entrance I was confronted by two people checking lists for names, other people milling about, a variety of scarves, shawls, baggy clothes, hiking boots, and Patagonia jackets piled in corners. The light came in precisely, very clearly, through floor to ceiling windows. It was like the light always is in the high mountains, acute and intense. We were at around 8,000 feet. Outside the mountains rose to over fourteen.
As I settled down on a meditation cushion in the middle of the circular conference room, a man with an unplaceable accent sat next to me. He grew up in Israel, and was Jewish. “Do you practice?” I asked. No, not really, he said. He comes to these things once or twice a year. He’s a massage therapist. He asked me what I did. I said I wandered around and wrote, making money however I could. He said I looked like a professor, but that I should give it a few years.
As we sat for the beginning, he leaned over from time to time to let me know what was going on. We did tsa-lung practice, a type of energetic breath and body work made to be done seated that “opens chakras.” Having never been to a retreat, but practicing meditation for about ten years alone, I found it strange to be in a room of around a hundred people, all saying the Sanksrit syllable “Ah” and imagining white light entering our bodies. Everyone else was ok with it.
As the first morning progressed, I was struck by the humor and ease of the rinpoche. He said things like “just leave it as it is,” and “just relax,” and also “you have reflected enough!” He took questions, and carefully avoided going into people’s personal experience. He was skilled at answering questions.
On the second day, I put up my hand and, while asking a question, made a joke. Several people laughed, as they had at many of the jokes he made. But he had an air of irritation, and as I continued my question, he said “what, is this funny or something?” I got the feeling that he was the one who could make jokes, make people laugh. Others were not allowed that liberty.
On the third and final day, we went outside for a puja. I had seen such things on documentaries, notably The Wheel of Time by <NAME>, where a massive hill of incense, juniper, pine wood, prayer flags, and other offerings are piled and set fire to. For our puja we had one of those cast braziers you might see at a suburban home, with a rusty metal grate. Inside a fire of piñon was made, and I was tasked with placing the crumbling, burning incense around the mesh. Rinpoche read a lot of Tibetan and everyone stood around silently, as the smoke billowed feebly from the fire, smelling like nothing really. We each took a handful of barley flour and threw it into the air, which I had also seen. In the video of the Tibetan people at the base of the Himalayas, this scene had the cameraman wading into throngs, people screaming and yelping, bells crashing, and smoke overwhelming the video, turning the screen opaque. Glimpses of weathered brown faces flitted across the screen, heavy woolen robes tied at the waist, prayer wheels, malas, lung-ta billowing, and smoke, smoke, smoke. But around me I saw the pale faced people, in nylon jackets, blankly talking and looking bored, throwing the barley when told to, laughing when queued, being silent when not, below snowy mountains that were not dissimilar to the Himalayas.
As I walked away, a tall white guy with long dreads came up to me. His name was Juniper, and he was from this area. He said: “we’re trying to start a little community here. I have some land. It’s an AirBnB. Next time you come through, let me know. You can stay at our AirBnB.”
I headed to my car, and drove back to the newly built retreat house, to stay one last night. The house looked like it had been airlifted from a subdivision outside Omaha, Nebraska, except it was on an incredibly steep hillside, surrounded by piñons, below the snow-covered mountains. There were new washer-dryer front loading units, a giant island, new fridge, dimmable lighting, soft-closing cabinets, shiny hardwood floors. Everything inside was clean, white, new, unmarked, pure. And very, very expensive.
<file_sep>---
title: ""
author: "<NAME>"
date: "2019-03-09T15:10:28-07:00"
draft: false
comments: false
images:
---

### Subscribe to Grass Newsletter
A Weekly Newsletter - long walks and hikes, photos, musings on reality,
poems, tea, & more
{{< email >}}
<file_sep>[build]
publish = "public"
[context.production.environment]
HUGO_VERSION = "0.68.3"
HUGO_ENV = "production"
HUGO_ENABLEGITINFO = "true"
[context.split1.environment]
HUGO_VERSION = "0.68.3"
HUGO_ENV = "production"
[context.deploy-preview.environment]
HUGO_VERSION = "0.68.3"
[context.branch-deploy.environment]
HUGO_VERSION = "0.68.3"
[context.next.environment]
HUGO_ENABLEGITINFO = "true"
[redirects]
from = "https://grassjournal.com"
to = "https://grassjournal.substack.com"
status = 301
force = true
<file_sep>---
title: "Grass Roundup No. 1"
subtitle: "An index of what I've written, read, watched, cooked, or heard"
slug: ""
author: "<NAME>"
date: "2019-04-08T14:20:59-06:00"
draft: false
toc: false
comments: true
cover: 15.09.28-grass-roundup-1.jpg
tags:
typora-root-url: ../../content
---
Happy April everyone, it's the season of impatience and unpredictable weather. This is the first Grass Roundup of the things I've written or consumed this month. Read on for the fresh grass scent of new days and things.
## **Watching**
Firstly, [a new channel](http://criterionchannel.com) by the Criterion Collection. If you're not already an obscure film junky, you could easily become one. Before now, Criterion Collection films were only available on clunky, archaic DVD discs. Now you can watch almost the whole collection on your phone!
### My Film Picks
[Sanjuro](https://www.criterionchannel.com/sanjuro)
A threadbare old ronin helps young warriors in need. Action/Drama.
[Cléo from 5 to 7](https://www.criterionchannel.com/videos/cleo-from-5-to-7)
Portrait of a famous singer in Paris as she awaits the results of a biopsy. Slice of life.
[Il Sorpasso](https://www.criterionchannel.com/il-sorpasso)
A young student of law takes an unexpected road trip from Rome to Tuscany. Comedy.
## **Listening**
I've been throwing together a [🌴🏝](https://open.spotify.com/user/hudsongardner/playlist/0OLoaXxQ4medCXeDu7s1Ze?si=rd1qBi4-S_mYIPxSOz2hVg) playlist. Not done yet but maybe fun to watch the progress. (Click the trees)
## **Writing**
I wrote a poem yesterday, and an essay today. Here's the poem—
*Song of the canyon wren*
*drips, then slides down a rock.*
*Smooth, like passing water.*
*A little voice, amidst voices.*
*The center of this moment, and everywhere.*
*Holding it all together.*
## **Grass Index**
On the Grass Journal there are a lot of new things, if you haven't looked lately —
My most popular post so far, may also be the [most maligned](https://grassjournal.co/instagram)
An article summary, and [some of my own thoughts](https://grassjournal.co/filling-the-void) about addiction
A [delicious scone recipe](https://grassjournal.co/scones/) from my girlfriend Anna
## **I'm Trying To Publish A Book**
I am in the process of submitting my manuscript, A Body of Water, to publishers. If you know of a press that publishes full length poetry, written in a narrative format that flows from beginning to end, and has themes of deep ecology and spirituality (but not religion), then let me know.
That's it for this fortnight. Thank you for reading!
\- Hudson<file_sep>---
title: "Kinnickinnic"
subtitle: ""
slug: ""
author: "<NAME>"
date: "2020-03-21T12:07:41-06:00"
draft: false
toc: false
comments: true
cover: 21.3.20-hall.jpg
tags:
typora-root-url: ../../content
---
**Kinnickinnic**
Let me tell you
a story —
It was
spring
They
two of Them
Moved through the mountains
as the snow left behind
wet rocks, trickles of
water
and cold mud—
Moved through the mountains, from low
to high, two of them
through the cold mud
and over drying rocks.
They had with them
red willow stems
from lower down
and larch boughs that they cut to sleep on.
They stayed in them
—the mountains
to summer when
the deer came higher for cool grass
and marmots whistled across valleys.
Then it was
that rain came more often
it rained a lot, and the slopes became
flowers.
It was so quiet there, they knew
that it was quiet
because they had heard noise elsewhere
—and they knew that this here,
this was quiet.
Staying at lakes, they went looking
for wild kinnickinnic, loved by bears
its thick, glossy leaves
and soft red berries.
They took
what time they had.
They laid down
as fall came
and snow collected on them.
And some say they became boulders,
or always were.
And some say they became trees.
~~
For various reasons, some of which I understand, and some I don't, I have experienced several episodes of ambiguous loss over the last several years. As psychology and relationships have been put under the microscope of science, terms like ambiguous loss have been invented. The term means the ending of a relationship or life circumstance that remain unresolved. Due to the unresolved aspect, our minds, the constant inventors, try and come to some conclusion about the situation—despite a lack of facts or communication. This often leads to vicious cycles of self-blame, blaming others, or depression. Ambiguous loss can happen through the death of someone that doesn't make sense, the end of a friendship where agreements (to be civil, to treat one another as human, to attempt to see both sides) were broken and the hurt was never resolved... and in other ways.
Though fancy terms like this often cause me to cast a weather eye in their direction, this one actually does put a phrase to something that I think many people experience, yet don't know how to understand or resolve. The painful point of ambiguous loss is the unresolvable aspect. How does a person move forward with something that is unresolvable? For some reason, the only thing that has helped me is embracing a simple fact: you are not alone.
A person tends to need other people. The fact of knowing that someone else, not even someone necessarily present, cares and thinks about them, or is even experiencing what they are experiencing, matters. When people or relationships are lacking, it is maybe a default to look at oneself and try to determine what's wrong within, or what's wrong with the world. I'm guilty of both these things, maybe everyone is from time to time. So when year after year, friendship after friendship, ends in ambiguous loss (is it distance? did I say something? are people busy? do they care? am I likeable? why is society so stressful? what really matters?) it tends to drive a person into the ground. To be honest, I was often thinking about suicide this summer, because I was driven into the ground after many such events. Add to the fact that it seems impossible for my writing to be published, I came to the conclusion that I was adding no value to the world—in fact since everyone seemed to abandoning me, maybe all I was adding was pain—and thus the old story of "they would all be better off without me."
Of course, this story is false, and suicide is always a mistake. Yet from deep in the pit of despair it's hard to understand that. (I'm OK now).
Last night I was talking to Anna, feeling down that even in the midst of a time when I hear many people are coming together, mending hurts, focusing on kindness, I had yet to receive any notes or comments of care from friends. While this is selfish (why aren't people talking to me?) it has to be something a lot of people are feeling. And I realized last night that maybe the fact of the matter is, with all these never-to-be-resolved situations that pounded me into the ground like a railroad spike—that these same people, with whom I have the disagreements, are just as afraid about trying to resolve them as I am. And even though these situations may never be resolved, I found comfort in that fact, and like a bread-crumb trail into another place it led me on to a hopefully different understanding, of resolution without resolve.
## I wish for people a perspective shift
Current times are unique, because they hard for almost everyone right now. I, as a constant and probably neurotic observer, have felt witness to degradation of social contracts and real care through the overabundance of exhaustive communication. I wish for people a perspective shift. Right now, it's probably easy as hell to be completely entombed in technology. But the dopamine cycle that rages inside of us through the spinning feeds of images tends to leave us exhausted and unsatisfied, with a dull ache behind the eyes and an empty space inside that cannot be filled by those immaterial and forgettable experiences. I wish for people to seek out something more real. I wish for them to set aside the unimportant and to seek silence from which constant stimulation protects us. Not to claim I know a prescription, but to express that honesty, forgiveness, connection, understanding, and the effort that drives such things maybe harder yet more important than cutting the old habit rut deeper. Write letters, go on walks, bake bread, call old friends, stare at the sky, watch the greening ground, listen to the rain, watch snow melt, listen to the wind, call your grandparents, turn your internet off, learn to cook better, think of others, more importantly *do* for others. If you have someone in your life you can call a friend, you are wealthy. If you have a relationship that could be mended, attempt to mend it. These are all obvious things, that, for some reason, have ended up in the broom closet of our lives. I think they are worth more than that.
I love you all,
— Hudson
<file_sep>---
title: "Starting A Podcast"
subtitle: ""
slug: ""
author: "<NAME>"
date: "2019-08-21T20:13:09-06:00"
draft: false
toc: false
comments: true
cover: 19.8.21-Starting-A-Podcast-2.jpg
tags:
typora-root-url: ../../content
---
I have thought about starting a podcast for years. But the ideas never congealed. Just recently, though, I came to an idea that has some momentum. Over the last year I wrote a book called A Body of Water. The podcast will be about publishing this book.
The book itself is a loosely connected narrative of poems about my search for home over about four years time. It also has themes of impermanence, interbeing, and ecology.
The podcast, I hope, will bring this book to more people than it sees sitting on my hard drive. It's also important that the book is read aloud, because a person reading something to someone else is a more complete experience than someone reading in silence.
A brief sidenote: books used to be read aloud for entertainment. In fact, reading silently to oneself used to be considered odd. And then, of course, there are the old stories, the culture, skills, and knowledge that have been passed down through spoken words since before time was counted.

I don't know how long I will make the podcast. I'm hoping that telling the story of the book, the story of the story, will lend more clarity about a way forward. If anything, it will be good place to practice reading, writing, and speaking in a new way. And also to share some of the great music I listen to.
## <center> [Listen Here](/podcast)</center><file_sep>---
title: "The Hardest Work"
subtitle: ""
slug: ""
author: "<NAME>"
date: "2019-04-10T19:12:33-06:00"
draft: false
toc: false
comments: true
cover: 2019-breakneck.jpg
tags:
typora-root-url: ../../content
---
*Photo above by <NAME>, me above the Hudson River in New York*
I'll admit that I feel my work over the last year, and maybe longer, has been dark. It's been some dark times lately, for many people. And my own individual suffering was increased by a series of mistakes I made that resulted in an abusive situation I had a difficult time extracting myself from.
I'm not asking anyone to listen to the difficulties, as I have had several willing and loving friends and family members to listen. It's strange though, how after leaving a traumatic situation, it still can haunt your waking and dreaming for months and even years. I guess for some it can take the form of a permanent illness.
I want to turn a corner, though. I have lately been thinking about what I am **For** rather than **Against**. And in the midst of difficulties, as the result of mistakes, a person can learn a lot. I have often wondered why the route I chose over the last span of lifetime has been so hard on myself: isolating, threadbare, tumultuous, uncertain: you name it, I've probably been through it. I have a theory that it has been a kind of Jedi training, to strip away all that is unnecessary.
When I look in the mirror, I see a changed person. Nowadays, a rather dried out, tanned one, from the New Mexico climate. But there is rigidity in my face and a quiet depth in my eyes that may not have been so clear before. There is also light and warmth. I think the laying-on of sufferings of late has indeed changed me. But the goodness and light I have been given will win out in the end.
No, I'm not a victim. I made all the choices I made, with awareness there would be a a certain result, and that is a privilege. Some have no choices at all.
Since I still have choice and will, and strength, energy, and light left in me, I, by code of my own ethics, must use it for good. I have such a hard time trying to understand that though. It is so hard to "help." It is so hard to know how to say things to people that are both understanding yet challenging. And in the end, should I be the one challenging, understanding, doing good, "helping?"
If I could summarize it all and what I want to do about it, it would be in this book, this beast, this long line of words I'm trying to publish: A Body of Water. I think it's my best work yet, and is the closest I've come to "helping" anything. I really believe in it.
I always come back to something my mom says, again and again: "The hardest work is the work we do on ourselves." It's true, because *our self* shapes the world. Not just through actions, but through view. Our Self is what looks out on Earth, has all these thoughts, divines right from wrong, in our own conduct and others. So I am happy to say, that the work I have done has been the hardest work. The work on myself.
All for now,
— hudson<file_sep>---
title: "A Story About A Meditation Retreat, #2"
slug: "Meditation-02"
author: "<NAME>"
date: "2019-03-02T08:02:30"
draft: false
toc: false
comments: true
cover:
tags:
typora-root-url: ../../content
---
After leaving the retreat, I headed west and then south, across and then down the wide valley. There is only one highway bisecting the valley, mountains bordering the east, and sagelands expanding to the west. At the base of the mountains lie a huge series of pale dunes, heaped up sand and dust accumulated there over millennia, blown there by the wind.
Snow began to fall and then it was dark. Snow formed drifts the road, and stuck to the cold asphalt. I drove slowly, behind a jeep with their brights on, passing only one or two people as we crossed the state border.
The imaginary world that spread out beyond the headlights was full of my own thoughts, projections of what might be there. A massive, flat topped mesa? Or the Cañon de Rio Grande, where the land suddenly breaks off, space opens up, and a thread thread of green-blue runs at the bottom? Sagebrush, certainly, for miles and miles: the infinite void of sagelands that spread, almost unbroken, from here in New Mexico to southern Canada.
As I drove I thought more about the retreat. I had decided I would not go to another in that tradition. I had gone because I’d never been to something like it. It was hard to know what a retreat was, and how I felt about it, before I went. To me, it felt as though a sacred tradition and culture was being sold, but I wrestled with these thoughts for weeks and even months afterwards. Was it just my own anti-establishment mindset? Or was I seeing through falsity and appropriation?
While at the retreat, I had taken one morning off to go into the mountains. There was a stream flowing down, winding through aspens and cottonwoods. Ice in the stream, a little snow here and there. As I walked a dog appeared out of the trees. Seeing me she stopped, and looked expectantly. I said the magical words: “do you want to go?” And soon she was racing ahead, looking back every now and then to make sure I was still following.
She led me higher and higher, back and forth across the icy stream, across roads, always looking back and waiting for me—all the way to the base of the mountains. She stopped for a drink of water, gingerly stepping on clear ice and breaking through, wetting her paws. It was strange, to meet a new friend like this, that needed no words or even a common species to experience something together. She was self-composed, she knew where she was, and where we were going. I could have walked as far as she wanted, up into the mountains, following the stream up to a lake. But we had been walking for an hour, and I knew I needed to head back. As I turned away from the path, which had began to slant upward and leave the trees behind, I wondered how far into the mountains, on this narrow path, that this simple, honest dog would have led me.
When I arrived back at the car, I noticed that she had followed me all the way back. She stood at the edge of the trees, looking towards me, but not coming any closer. She had a collar, and a home—she didn’t really “need” me. But like anyone, I guess she had found walking with someone more enjoyable than going around alone. And I guess this is what I needed too—companionship, love, and someone to look for me and to look for, as we go along this old trail together.
<file_sep>---
title: "Three Years of Growth"
description: ""
slug: ""
author: "<NAME>"
date: "2020-04-03T05:38:45-06:00"
draft: false
toc: false
comments: true
cover: CJ-3APR20.jpg
tags: ["Corona Journal"]
typora-root-url: ../../content
---
Trackless trackless mountain cloud
what do I ask to be?
To be you, to be you.
Coming—going into nothing
what do I ask to see?
To see you, to see you.
Trackless trackless mountain path
where do I ask to go?
To find you, to find you.
Trackless trackless meadow of flowers
What do I ask of you?
To believe you.
To believe you.
{{< spacer >}}
---
{{< spacer >}}
Does it ever feel, to you, like you are doing what you were made to do? I wonder if everyone has some feeling like that, at some point in their life. It comes in and out like baconfry static on the radio, for me.
I think the idealized life is often said to be "in balance"—work-life balance, family balance, relationship balance, or balancing your checkbook (just kidding). Maybe a life that feels aligned is one of balance? Yet, for me, those moments where I feel properly "in the flow" aren't continuous. Which leaves me wanting them when they are gone, which, in a way, creates imbalance.
I read recently that the idea of balance in the natural world is actually misguided. The natural world is a chaotic series of successions. A forest burns and fireweed sprouts. Aspens, their roots underground and safe from fire, send up shoots in every direction, eventually shading out the fireweed and almost anything else. In fifty to a hundred years the aspens grow huge and die and fall, just in time for the seedlings of fir and pine and hemlock, which grew from seeds brought there and cached by birds and mammals, to rocket skyward.
The idea of balance, this unattainable thing (if we're being honest), is applied to human lives, since it exists in nature, right? What if it doesn't exist in nature, what then? Maybe our lives are actually not meant to be balanced, and the attempt to seek some perfect balance is impossible. It makes us chase that "in the flow" feeling, which sets up life to be a series of ups and downs. Life is and always was and always will be a series of unpredictable events. There is no perpetual balance within uncertainty. Maybe life is more like an infinite act of rebalancing, or, you could say, flowing.
And yet nature functions well, and we do too. Nature has us beat in that it does not worry about balance. It just expresses, in all its mystery, the breath of life. And I feel myself, myself, what I am made to do, if I am honest, is to do the same.
{{< spacer >}}
---
{{< spacer >}}
Yesterday Anna and I drove the truck up the mountain to a creekside trail we found a year ago. We went down it together, amazed at the colors and motion of butterflies that seemed to spontaneously appear in the sunlight. The aspen trunks were white and snow lay in crevices along the path. We wound down to the river and walked along it for a while, then found a meadow. I set up my tent, just for fun, and used a small camp axe to buck some wood for whoever would have a fire there next. Anna laid in the sun, or watched the river flow by.
Over Anna's chest and down the left side of her body hung a massive, thick braid. I picked up the end of it. "Remember biking the road up to Big Bear?" I asked. "Yeah, I was just looking at photos from then", she said, "and three years ago we did that ride. After we got back I went up to Washington and stayed with Brit and Sam and then went to my mom's house and cut off all my hair."
"Three years of growth," I said pulling lightly at her thick braid.
To realize three years had passed since then felt funny and sad at the same time. Because, mostly, this flow of experiences we name Life doesn't always flow easily or clearly. The pain of the turns can be acute. And yet, they all flow together somewhere, and get bunched up in memory, and then you can sit on a rock in the spring sun in the mountains and think about all the times when things weren't so good, and the times also when they were good, and then come back to the time right now—which is *really all the time we have.* And it's strange to think of, that there is a physical representation of all that time that hangs beautiful and thick from Anna's head—of a thousand thousand strands braided together—of three years of growth.<file_sep>---
title: "The Same Day"
description: ""
slug: ""
author: "<NAME>"
date: "2020-04-16T10:18:46-06:00"
draft: false
toc: false
comments: true
cover: CJ-16APR20-2.jpg
tags: ["Corona Journal"]
typora-root-url: ../../content
---

The red woven towel hangs limply from the oven.
I have already used it twice to dry my hands today.
The wind
outside
moves new leaves of bushes.
The ants have begun to build tunnels.
A metal shack
by the beat up street
has a padlock I have never tried to open.
The lock hangs from a handle that is rusting off.
The apricot tree nearby
has never been pruned.
Yet every year it produces new fruit.
Cars still pass
on Agua Fria street.
The sun still rises
and wakes me up.
I feel confused about how I feel
when each day is the same.
This endless cycle of waking
and sleep.<file_sep>---
title: "My Way Of Explaining"
author: "<NAME>"
date: "2019-03-08T13:12:05-07:00"
draft: false
toc: false
comments: true
cover: 19.03-western-ne.jpg
featured_image: /img/19.03-western-ne.jpg
tags: [poetry, water, existence]
typora-root-url: ../../content
---
The whole problem of existence
is that we are are like a river, but not
minds always flowing
restless, unable to stop.
Sit
by a river
with me.
See how the water
moves.
Touches
one thing, goes on.
Rest
in a deep pool, behind a log.
It’s cold, this water.
It will wake you up.
This river is you, and me.
The water is your mind.
<file_sep>---
title: "Worries"
description: ""
slug: ""
author: "<NAME>"
date: "2020-04-14T08:19:00-06:00"
draft: false
toc: false
comments: true
cover: CJ-14.APR.20.jpg
tags:
typora-root-url: ../../content
---
Laying on my back
My back begins to warm
The soft cushion of the bed
I have no plans
Only worries
I remember an ivory bear
With a turquoise arrowhead tied to it's back
That I used to keep in a hidden wooden box
Where I used to keep my worries<file_sep>baseURL = "https://grassjournal.co"
title = "Grass Journal"
languageCode = "en-us"
theme = "hello-friend-ng"
images = "mountain.png"
favicon = "favicon.ico"
googleAnalytics = "UA-136102762-1"
# disqusShortname = "grass-journal"
archetypeDir = "archetypes"
contentDir = "content"
dataDir = "data"
layoutDir = "layouts"
publishDir = "public"
# Adds blog image folder to the global site image search
staticDir = ["static", "content/posts/img"]
buildDrafts = false
buildFuture = false
buildExpored = false
canonifyURLs = true
enableRobotsTXT = true
enableGitInfo = false
enableEmoji = true
enableMissingTranslationPlaceholders = false
disableRSS = false
disableSitemap = false
disable404 = false
disableHugoGeneratorInject = false
# Directory name of your blog content (default is `content/posts`)
contentTypeName = "posts"
# Default theme "light" or "dark"
defaultTheme = "light"
[permalinks]
posts = "/:slug"
[params]
dateform = "Jan 2, 2006"
dateformShort = "Jan 2"
dateformNum = "01-02-2006"
dateformNumTime = "Mon, Jan 2, 2006"
# Metadata mostly used in document's head
description = "Writing, photos, walking, cooking, zen by <NAME>"
keywords = "blog, buddhism, spirituality, minimalism, photography, meditation, philosophy, gardening"
images = [""]
subtitle = "<NAME>"
# Default theme "light" or "dark"
defaultTheme = "light"
# Social icons
[[params.social]]
name = "email"
url = "mailto:<EMAIL>"
[[params.social]]
name = "instagram"
url = "https://instagram.com/rivrwind"
[languages]
[languages.en]
title = "Grass Journal"
keywords = ""
copyright = ""
readOtherPosts = "Read other posts"
[languages.en.params.logo]
logoText = "○ Home"
logoHomeLink = "/"
# And you can even create generic menu
[menu]
[[menu.main]]
identifier = "bodyofwater"
name = "A Body of Water"
url = "/bodyofwater"
weight = "4"
[[menu.main]]
identifier = "who"
name = "Who"
url = "/who"
weight = "2"
[[menu.main]]
identifier = "About"
name = "About"
url = "/grass"
weight = "3"
[[menu.main]]
identifier = "posts"
name = "Posts"
url = "/posts"
weight = "1"
<file_sep>---
title: "{{ replace .Name "-" " " | title }}"
description: ""
slug: ""
author: "<NAME>"
date: "{{ .Date }}"
draft: true
toc: false
comments: true
cover:
tags:
typora-root-url: ../../content
---
### DRY
**⁘ 2 cups** chosen flours (I used ¾ whole wheat, 1/4 buckwheat)
------
## Method
Add wet ingredients to dry.
<file_sep>---
title: "Hard Times"
subtitle: ""
slug: ""
author: "<NAME>"
date: "2019-07-02T07:35:18-06:00"
draft: false
toc: false
comments: true
cover: 16.07.11-.jpg
tags:
typora-root-url: ../../content
---
Things have been rough lately, or longly, for about two years now. I don't think I wrote much about it, keeping difficulty to myself here and there, not wanting to bring anyone down, but now that I can see some kind of end, or at least some kind of change, I thought I'd write a few things down.
For those who don't know, over the last four or so years Anna and I have been mostly living in remote places, far away from friends, community, and support. We were living in such a way to come close to what interested us, and also because we didn't know the answers to the questions we were asking: where is home? How to live? What really matters? Through trying life of different kinds in places ranging from Washington to Maine, we arrived at some of these answers. We also encountered hardship, loneliness (a rather new feeling for Anna, who grew up surrounded by family and friends), abuse, and rejection. Everyone wants there to be a good side, a light side to the difficulty people encounter, and there usually is. But something I think that people maybe don't want to hear is sometimes there isn't a bright side. Sometimes there is no silver lining. Sometimes things just suck for a long, long time.
When things suck for a very long time, one begins to question themselves. Is it me? Is it the choices I've made, that have driven me to loneliness and despair? And of course the answer is in part: yes. It is you. Especially if you've had the wherewithal to make choices (some people don't have such a thing as choice). This realization of responsibility for one's choices is maybe one of the most difficult truths I've encountered in life. The reality is: we don't know where our choices will lead us, or what the questions will cause to work within us. What seemed like an honest thought or need can be endlessly elusive. And I find the closer to the grain that I cut the more the point of my action eludes.
What things sucking for a long time does, however, is create a kind of tarnished wisdom about life. If you want, though I'd rather not refer to it this way, you could say that this is the "silver lining." But the reality is that it's only a positive in retrospect, and the marks of hardness and difficulty maybe never leave a person. That's why the lesson sticks, and that's where the wisdom comes from. When the pain is driven so deep it can never be forgotten. The old adage: one thorn of experience is worth a whole wilderness of warning.
About a month ago, Anna and I moved to Santa Fe, figuring it would be an easy move, just an hour and a half south, a few friends, lots of jobs. Instead it took about two months (of searching beforehand and while staying at a friends) to find a place that then was more expensive than any place either of us had ever paid for. Anna interviewed for a month before finding a job, feeling worthless, judged, and ignored in the process. The friends we had, apart from one, have been so far hard to understand and not very inviting or supportive. This would have been alright if not for it coming on the tail of three or so years of hardship and loneliness. Being on the back of that, and also receiving rejection after rejection from many publications in my attempt to publish writing and photos (and also this book I've written), this final push in a place we hoped would be welcoming has been an "out of the frying pan and into the fire" kind of experience.
I think in many cases what people are driven to do in this situation is to try and get rid of the difficult part of life immediately, by whatever means possible. However, I still think experiences like this are valuable, and they shouldn't be discarded as though worthless. I think that experiences of our essential loneliness are profoundly important. But they are very hard to bear.
I sat outside a few nights ago, feeling more depressed than I have in a very long time. I started crying and by some strange circumstance it also started raining. Little events like these happen to me often. I often feel like the world outside of human constructs is my true home, and that in a strange way it listens and holds me no matter what happens. It will always be there.
Sometimes it really does feel like the entire human world is conspiring against you. The core of my feeling on the patio was a complete lack of being valued. Things have been rough at work lately, and also with certain very important interpersonal relationships. Feeling a lack of value, like a piece of trash to be discarded by the rest of society, is basically the lowest a person can go. To feel unwelcome, unwanted, and uncared for brings about the deepest depression a person can experience. I think this is how people who are far less fortunate than me, such as the houseless and the incarcerated, feel on a daily basis.
Thankfully, I have things that I love. I love to walk. I love music. I love to cook. I still love taking beautiful photos. I love Anna. I love my family, and Anna's family. I love the friends I have in distant places. I love technology. I love Thom Yorke. I love the taste of the bread Anna is getting better at baking. I love this tea I discovered called cota, that grows in groves along the Santa Fe river near where I live. I love my sister. I love my brothers. I love rain after sun and sun after rain. I love the pine-scent. I love the lizards that gulp down ants and live in the bushes on the patio. I love learning and reading. There is so much I love. And in this, I find value. And the value is reflected back at me: what I love, loves me, even if it is a rock, river, or tree. The world itself loves me back. And feeling that love, I will never be alone.
<pre>
<br>
<strong>The Camp Fire</strong>
And along the dry golden hills
in Mendocino summer
I drove to a grove of old trees four years ago.
Eucalyptus, resin - scent
oily air
dead grass
no water flow.
The fires came this spring
to that same place.
“You don't want to let go
of the past
because that's how
we learned to live
And be who we are.”
A man who lost his house said.
“Friends and family call us
ask how we’re doing
they don’t want to hear
that we’re not OK.
Forever everything will be different.
We lost what we had.
We carry what’s left
in our DNA.”
</pre><file_sep>---
title: "Seasoned Wood"
subtitle: "A Poem"
slug: "seasoned-wood"
author: "<NAME>"
date: "2019-05-23T14:57:38-06:00"
draft: false
toc: false
comments: true
cover: 17.10.15-.jpg
tags: [poems]
typora-root-url: ../../content
---
**Seasoned Wood**
<pre><em>Working back and forth across the ground
dragging logs to piles
leaving them lay for a season, then
splitting the logs, and laying them out. </em>
~~
By a river he lived
for thirtyseven years
cutting the meadow with a scythe
in the hot June sun.
Seasoning the land with his own sweat
of work.
Laying logs aside, for winter.
Bucking and splitting, tucking things in.
Then he died.
Everything came back in.
The river flooded
and washed it clean.
~~
Far below where they were cut
seasoned logs roll ashore.
I slice off an end, with a sharp knife.
Light a fire, burns salt blue.
Roast an apple, eat it hot.
Toss the core into the flames.
Heating and eating and resting
along where things come down to
from far away.
Seasoning myself with sand.
Thinking of it all, laying with it.
Staring at the sky, and wondering
how the work of becoming something
all comes to a point then disperses
breaks away
and is gone.</pre><file_sep>---
title: "Grass"
subtitle: ""
slug: "new-grass"
author: "<NAME>"
date: "2019-02-01T08:03:32-06:00"
draft: false
toc: false
comments: true
cover:
tags:
typora-root-url: ../../content
---
The spaces that aren’t worth anything. Where grass comes up between broken cement slabs.
The quiet places that no one goes.
Places that feel like they are yours, but you know they really belong to no one, and that’s why they are special.
Thoughts that many think, but don’t know how to talk about them.
Put-off ideas, made unimportant because they are frightening to confront.
Humble things.
.
We are surrounded by grass. It comes up in many places.
Some cut it flat, then water it so it grows again. Some tear it out.
Some let it grow until the city leaves a notice on their door.
Others make grass into gardens.
Some bale and sell it.
But much of grass is unnoticed. Special in that way, grass never asks for attention.
.
I wish to.. make an art of noticing.
Noticing grass. You know what I mean
By grass now
<file_sep>---
title: "Love"
description: ""
slug: ""
author: "<NAME>"
date: "2020-04-17T08:51:01-06:00"
draft: false
toc: false
comments: true
cover: CJ-17APR20.jpg
tags:
typora-root-url: ../../content
---
Maybe the important thing to remember about love is when it is held at a distance, examined, it may seem sentimental, cliché, impractical, useless, or mysterious.
But when love is experienced, it seems to be the only true reality, the only real choice one could make, or at least the best choice—it seems to clarify everything and fill the whole world.
That's all for today.
\- Hudson<file_sep>---
title: "Corona Journal - We Are All A Part"
subtitle: ""
slug: ""
author: "<NAME>"
date: "2020-04-01T07:26:44-06:00"
draft: false
toc: false
comments: true
cover:
tags: ["Corona Journal"]
typora-root-url: ../../content
---



> Dear Corona virus,
> Welcome to Kenya. A few things you should know. Here we don't die of flu, don't be suprised if you fail to succeed. Usishangae [don't be surprised], everything fails in Kenya.
>
> We are not very excited to host you around, no offence but locusts arrived way earlier than you and first come first served, unless utoe kitu kidogo then you can skip the queue of our attention.
>
> We also cannot afford to pay you too much attention because we really really broke. Incase you haven't heard our economy.... is in the toilet. Shh...whisper please.
>
> Don't expect us to fight for sanitizers and tissue paper like the westerners, we shit and wipe with bush leaves. We are sufferers except for the few pretentious mido crass are taking your arrival as another opportunity for ostentatious shopping. Wako na pesa and you should see how they nonchalantly eye each's others tray as if to see who wins with the most full shopping.
>
> What's that?.....No, no no no, am not calling anyone an idiot here.
>
> We jua tu ... we the poor know plain soap and water is as good as any antibacterial soap.
>
> It's unlikely that we will stop shaking hands on your account, a greeting is not complete in Afrika if I do not leave the smell of omena I had for lunch on the palms of your hand. How else will you know I've eated meat? But we promise to try.
>
> It's not like we want to ignore you dear corona, but how will we keep indoors yet we get paid per day? If we don't go to mjengo, trust me there will be no ugali at the end of the day. We will not stay indoors kukufa njaa just because you're here to rule the outdoors. It's our outdoors, only politicians and police can keep us indoors after an election.
>
> Bro, huku sio UK ama U.S. Our savings culture got lost before our ancestors died, they never managed to find it and we have no social welfare other than shillingi 2,000 per month if you are over 70. Yes, per month. We try.
>
> I know you think you will collapse our economy, LOL! Shock on you, our government has been screwing our uchumi for several years now.... and we still here.
>
> We ain't even gonna worry about you killing us, cancer is now friends with Kenya just incase you have been hiding in a cave until now.
>
> We also get killed by police stray bullets all the time, so dude - no biggie there. Do you even know the road accident statistics in Kenya? If you knew how we die daily of motorcycle and bus accidents, you wouldn't even bother to stop here. Sawa baba? Umepoteza fare.
>
> We are more likely to die of a cholera attack than to be killed by you bro. For us, everday is a run escape from death. We are the walking dead. Death is part of our lives, the shadow that lingers over us from the time the umbilical cord is cut and buried behind the house, to the time we fundraise for expensive arrangements to bury a no longer useful block of dead meat.
>
> Death can be fall us anytime and we are not scared. If it comes, let it come. Why worry over what we can't control? Everything dies, right? Even you corona will die!
>
> We welcome all kinds of visitors to Kenya, hakuna matata, karibu sana. Enjoy our beaches, tourists are leaving to create room for you. Do make a visit to the Mara and by the time you leave our beautiful country all we ask is: please take most of our politicians with you, they love free rides, alot.
>
> — [<NAME>](https://www.facebook.com/permalink.php?story_fbid=2621148771543767&id=100009460091433)
Yesterday afternoon I was sitting outside in the sun on the patio. I saw a yellowjacket land on some of the mullein that grows in patches. The yellowjacket was collecting fuzz off the leaves with her mandibles, working it into a ball, and flying away. Back at the nest, she must have been digesting it into pure cellulose and using it to build nest cells.
I went inside and checked my phone. On it was an email from my landlord. Anna lost her job, so we are trying to move out of our expensive apartment a month early. The message said "In order for you to move out a month early, you will need to advertise and show your apartment. Once you have found a replacement, we will need to approve them and have them sign a new lease." No mention of job loss, global pandemic, or the Governer's order to stay at home. About a month ago, this may not have bothered me. But as time goes on, and there are more reports of people of Anna & I's age being hospitalized due to the virus, I realized that showing our apartment to strangers from Craigslist was not an option at this time.
By May the virus may have slowed its spread. But outside my little courtyard, on Agua Fria, I still hear just about the same amount of traffic every day. I hear that just a week ago there were tourists from nationwide all over the plaza, and most businesses were open.
I think the range of responses in Kenya are likely the same as they are worldwide. No one can predict how bad it will be. Some choose to make fun. Some choose to isolate themselves. Some choose to ignore it. I guess this is what I choose—
To be present for what I have
To not worry about what's later
To take care of myself as much as I can
I think this isolation journal started off with the wrong title. Physically, we are all isolated. But in experience, I think we are together. We are all a part... of something larger.<file_sep>---
title: "A Handbook For Ethical Instagram Use"
subtitle: ""
slug: ""
author: "<NAME>"
date: "2019-04-29T09:18:02-06:00"
draft: false
toc: false
comments: true
cover: 19.Apr.28-flower.jpg
tags:
typora-root-url: ../../content
---
I started writing this out as a short post for Instagram.
I decided to put it there & here, because I wanted to write a little more about each point.
---
## Ideas For Ethical Instagram Use
### 1. Consider why you are posting before you post
### 2. Do not attempt to make your life look enviable, or better than it is
For some reason, this is almost the reason Instagram exists. I think it's a harmful practice, and creates competition and instead of collaboration.
### 3. Do not use geotags (also, consider why you want to geotag)
People argue there are ethical ways to geotag. I disagree. There are too many people using Instagram, and the algorithms are too successful at funneling likes and views to already overpopular things. Just leave them off.
### 4. Think: collaborative, not competitive!
### 5. Treat people as people, not potential audience or customers
It is truly the age of the Artist Entrepreneur. We have become our own platforms. We must do everything from conceptualizing, to marketing, to shipping. This can drive people to treat others as potential audience rather than just human beings. It turns each of us into agents—for ourselves. While this approach might be effective, I believe it undermines our common humanity.
### 6. Do not align your self-worth with how much people like you. In other words, work on self-compassion, not self-esteem.
In "Fearless Heart" Thupten Jingpa, the translator for the Dalai Lama, argues that self-esteem and self-compassion are two different things. Self-esteem is fragile because it is often attached to success, or external circumstances. Self-compassion is self love. And love means acceptance. Self-esteem has something to prove. Self-love is simply an embracing of all things, ideal, or unideal.
### 7. Fully/completely/deeply consider your impact
Instagram affects the real world, even though we don't see it directly.
### 8. Limit use to a healthy level
There are timers, usually called Digital Wellbeing, available on most smartphones now. Use them!
<file_sep>---
title: "Frost's Old Woods"
description: "A visit in memory"
slug: "frosts-old-woods"
author: "<NAME>"
date: "2020-04-06T06:19:41-06:00"
draft: false
toc: false
comments: true
cover: CJ-6APR20.jpg
tags: ["Corona Journal"]
typora-root-url: ../../content
---
I took a break from writing over the weekend—not because I had nothing to write, but because resting the writing bone seemed like a good idea. But now that I try to write again I feel like I lost the thread I had found. Or maybe it's that nothing has changed from where I was on Friday.
Over the weekend I watched the lizards and birds outside in the sun. I made chaga tea over a twig stove from a chaga conk I found in Robert Frost's old stomping grounds. I don't often use the chaga from that conk, it's more of a keepsake, but I guess one day I will use it all eventually. When I found the chaga, I didn't even know I was walking in Frost's old woods until I saw a sign about them.
When I was there, in Frost's old woods, all the open hay meadows had filled in with meadowsweet. It was summer, in fact the day after my birthday, which I had spent alone in Eastern Vermont camped in a forest. I was running away from something terrible, that I had to go back to after this brief sojourn. But for those few days, I managed to forget about all the pain and strangeness I had to return to, though they cast a shadow on my mind, and even though I love sleeping in a tent at night, I didn't sleep well.
I noticed the meadows near Frost's old woods were on their way to becoming forest again. And there were other meadows nearby, that had not been filled in by brush and small trees, that were still cut once every few years. They were dense with hundreds of wildflowers.
There is a big deal writing retreat near Frosts Woods just a little further up the valley, called Bread Loaf I think. And there were hundreds of cars in a giant lot filling the grounds in front of the old farm buildings that people now wrote and slept in. I wandered around the grounds, and probably could have walked right into the workshop classes if I had wanted to. In the winter Bread Loaf turns into a nordic skiing center.
In Frost's old woods everything was going wild again. Yet just down the road, there was the big expensive hard-to-get-into retreat center, filled with people trying to... what? I sit here, trying to make sense of each moment, and then turn it into words. Maybe that's what they are doing too. Yet, the trees and plants that grow in those overgrown meadows, that even now are probably leafing out, they just grow.<file_sep>---
title: "Busy Is a Habit"
description: ""
slug: ""
author: "<NAME>"
date: "2020-04-10T07:52:33-06:00"
draft: false
toc: false
comments: true
cover: CJ-10APR20-1.jpeg
tags: ["Corona Journal"]
typora-root-url: ../../content
---

A few excerpts from [*The Abundance of Less* ](http://theabundanceofless.com) by <NAME>.
> ***"Maybe to someone else this would be terrible. But to me, I spent fifteen years traveling, and I was so satisfied doing that, when I came to this village I could live like this—" He looks around [at the barn he converted to a home] with a deeply contented and thankful expression—"I felt like I pulled off something terrific. When I quit my job, I worried so much that my life would be terrible when I got old. And it turned out this good!"***
>
> Outside, the snow has turned to rain, and with it's gentle sounds on the roof Nakamura lays out some old futons for me to sleep on. As my body begins to warm up the bedclothes, the familiar tranquility of the Japanese countryside settles over me again, and, with the sounds of the river below and the rain falling on the roof, I drift off to sleep.
>
> In the morning, when I awake, Nakamura is already up and making breakfast. Out the windows, mists are gathering and drifting on the dark green cedar forest across the rainy valley, looking like nothing so much as an old Chinese ink painting. On the cookstove, Nakamura is making some sticky bread muffins in a set of stacked bamboo steamers over a wok full of boiling water. The crackle of kindling reminds me again of Nakamura's wood-centered life. At the table he is cutting updates and other dried fruits to add to our sampa, the Tibetan staple food made from toasted barley flour, a chunk of butter, and in Nakamura's case, Awa *bancha* tea, all of which is then mixed into a paste. It's not what I usually have for breakfast, but it's warm and tasty, and the dried fruit makes the meal particularly delicious.
>
> I look outside, and it seems like it might just keep raining all day. I ask Nakamura what he usually does on days like today.
>
> "Sometimes I carve woodblocks, or read, but mostly, when I have nothing to just stare into the fire." he says his face showing an expression of a person in the movement of flames flickering their mesmerizing dance.
>
> I raise my eyebrows, and then he says with a smile, "Doing nothing all day- it's difficult at first. Being busy is a habit, and a hard one to break."
>
> But then I think that perhaps such a life—very little production, very little consumption—might be an important part of the solution to the world ecological crisis.
>
> As we look out at the clouds on the far mountains, I ask Nakamura: "Do you feel that you are living a life of luxury?"
>
> "Luxury? No, not luxury. It's an ordinary life. But I do feel an abundance, a sense of plenty. A hundred years ago I would not have been able to choose what kind of life to live. I feel very lucky to be living in this age."
— *The Abundance of Less. Lessons in Simple Living from Rural Japan* by <NAME>. From the chapter "A Woodblock Craftsman Discovers Hand Work and the Heart".
<file_sep>---
title: "No Progress"
subtitle: ""
slug: ""
author: "<NAME>"
date: "2019-06-19T06:55:05-06:00"
draft: false
toc: false
comments: true
cover: steve-jobs-tea.jpg
tags:
typora-root-url: ../../content
---
For many, this is where the story of their life begins.
In such a room, when they had few things, life was charted to become larger, to include more. Maybe, though, there was a part of Steve Jobs that wished he had never left that room.
For me, this is where life begins, but also where it ends. I have thought carefully about what I want, and tried things. There is something so beautiful in this empty room to me. The beauty is a kind of space. There is space there. Space, like time, is interesting in that as I grow older I see that both space and time become rare commodities. Space to be.
This may seem like a counter-culture statement. But I would like to say this idea of space and simplicity is a place lived in on it's own. It is not against anything.
Never wanting more than that room is like choosing a fork in a trail
that is narrower and also wider
that has brought me somewhere
both very old yet always new.
It's less clear, this Way,
It's very quiet though.
And it has taught me to not have fear.
There's a lot of space here,
to garden in, to cook, to sleep and eat,
to make mistakes.
So much of my work is about a single idea: losing sight of myself. Learning, re-learning to not think, and not do. Yet life we are told should be about building up a self—making it larger and larger, happier and happier.
I like to rest in a darkened room
with a place to sit, music, and a cup of tea.
<file_sep>---
title: "Spring"
slug: ""
author: "<NAME>"
date: "2019-03-21"
draft: false
toc: false
comments: true
cover: 18.12.27-bush.jpg
featured_image: /img/18.12.27-bush.jpg
tags: [poems, photos]
typora-root-url: ../../content
---
There was a gap in a leafy hedge
and I watched as a little bird flew in.
Spring rises
like a green mist, up from the ground.
Water is liquid, and comes back from where it was
like spring does.
Always something coming back from something
the beat of a stone, two thumps—
the old heart again.




<file_sep>---
title: "A Dream I Had Last Night"
description: "Four Deer"
slug: ""
author: "<NAME>"
date: "2020-05-25T07:54:26-06:00"
draft: false
toc: false
comments: true
cover: /2020-May/25-1.jpg
tags:
typora-root-url: ../../content
---
Last night I dreamed I was in a house. I went outside and sat in tall green grass. It seemed like I was in the plains somewhere.
When I sat down in the grass a small white tail buck came up to me. His grey fur and white chest. One of his antlers was broken off. He laid down in the long green grass beside me.
Then a pronghorn antelope with black antlers came up to me. He had tawny fur and black markings and a white chest. He laid down in the grass next to me.
Then a big horn ram came up to me. They have grayish brown fur like rocks on a mountain. He laid down in the grass beside me.
Then an animal I don't remember came up and laid down in the grass beside me.
I sat there surrounded by these four animals. They sat there looking at me. We just sat breathing and looking at each other. There were no words—but things were said.
I got up and went and sat on a bench. A few people sat there that I had once been friends with, but something happened and now we aren't friends anymore. But we just talked like we were friends again.
I woke up to light rain outside. Then I was awake for a while. I heard thunder rumble three times for a long time. Then I fell asleep again after the rain ended.<file_sep>---
title: "Coconut Korma"
description: "Delicious korma that can be made vegan"
slug: ""
author: "<NAME>"
date: "2020-04-11T14:43:52-06:00"
draft: false
toc: false
comments: true
cover: CJ-11.APR.20.jpg
tags: ["Corona Journal","Recipe"]
typora-root-url: ../../content
---
I have found this deceptively simple, vegan curry recipe to be just as delicious as one made with a masala. The individual flavors (garlic, ginger, cloves, cardamom) stand out more instead of getting lost in a cacophony of spices.
## INGREDIENTS
**• 6** cloves
**• 8** cardamom pods
**• 1 tbsp** Kashmiri chile powder, OR Korean chile powder OR whatever you have (optional)
**• 1** head garlic, peeled and ground to a paste, or finely chopped (**Tip:** shake cloves in a jar for 2 minutes or until skins loosen)
**• 2.5 inches** of ginger root, ground to a paste or chopped finely
**• ½** red or yellow onion, sliced thinly into half moons
**• 1 can** (13.5 oz) unsweetened coconut milk
**• ¼ cup** salty vegetable stock, OR **1 tbsp** miso paste diluted with **¼ cup** water
**• 1 tbsp** lime juice, or **3 tbsp** tomato sauce/chopped tomatoes
**•** neutral oil, such as grapeseed or vegetable.
**•** Salt
### VEGETABLE / MEAT OPTIONS
**• 3 large** carrots, cut into bite-sized pieces **OR**
**• 3 medium** yukon gold potatoes, peeled and cut into bite sized pieces **OR**
**• 1.5 lbs** Chicken (white or dark meat, preferably with skin) cut into bite sized pieces
**Note:** you can also do a mix of the above, or even add **½ cup** frozen peas to the carrots and/or potatoes (which I like to do).
{{< spacer >}}
------
{{< spacer >}}
## METHOD
Dry roast cardamom and cloves in a large sauté pan over medium heat until fragrant and popping. Be careful not to brown them! Add enough oil cover the pan to 1cm, turn heat to medium-high, then add the garlic and ginger, frying for two minutes. Add the onions, and fry for one minute more with a good pinch of salt. Then add the vegetable/meat of your choice (if using frozen peas, add them after the coconut milk). Fry for another two minutes, then pour in the coconut milk and stock/miso and add the chile powder. Allow the sauce to simmer, then reduce heat to medium-low. Add lime juice or tomatoes, then simmer for about 12 minutes or until sauce has thickened, checking meat and/or vegetables for doneness. Adjust salt to taste, and serve with freshly cooked rice.
<file_sep>---
title: "A River Flows To The Sea"
subtitle: ""
slug: ""
author: "<NAME>"
date: "2019-05-18T08:52:39-06:00"
draft: false
toc: false
comments: true
cover: 19.05.20-river.jpg
tags:
typora-root-url: ../../content
---
Here's something funny—
So many times I've been told I can't do what I want to do, by so many people, in so many ways. It happens almost every day. And then you might think to yourself, "well, I guess this guy is just really selfish, self-centered, and ignorant." That's not true either though, because I do listen: to how plants grow, to how animals live, to how people care and support one another. But I don't let myself listen to things that don't make sense to me. And it isn't an ego-based rejection, it's a thought of what will make me most free. Free from fear, free from anger, free from control. Oh no, it's not easy and blissful at all. In fact, doing what I do is the opposite of easy and blissful. No, it's the hard work. The work that benefits no one else but myself, for now. But I believe in the idea of honing oneself through work like this, whether it's with others, or alone. And through that honing becoming more fully human, and able to know the answers, and be there for others whether it's a landscape, a plant, a community, or another person.
If a river wandered into the desert in many little streams it would dry up and disappear. But if it keeps its main course it will flow to the ocean. Poetic, maybe, but in my route through life I've found it to be true.
Keep telling me I'm wrong, that I'm taking the wrong course, that I'll never amount to anything. I don't care about proving you wrong, because I know it's not me you're talking to. You're speaking to your own fears, of what you think is possible or impossible. I'll prove one thing: that a human being can remain free and alive through a life, like a river flowing cleanly down through so many things and down to the sea.
<file_sep>---
title: "Sand Dune Camp"
description: "Walking in Great Sand Dunes National Park"
slug: ""
author: "<NAME>"
date: "2020-04-09T6:45:30-06:00"
draft: false
toc: false
comments: true
cover: CJ-9APR20-1.jpg
tags: ["Corona Journal"]
typora-root-url: ../../content
---







{{< spacer >}}
Wide emptiness.
Spaceless nothingness.
Dust
from millions of years
piled up high.
Mountains loom
but aren't that steep.
Legs feel tired from hours of sand.
Spots of water in the dunes
crooked cottonwoods
and an owl.
Fire of juniper twigs
above a dry pond.
All opens up
then closes in.
I walked so far
to get right here.
Dry creek bed
The night wind—
"come over"
"come over"
"come over"
~~
A shadow moves
sand plants
blown by wind
making circles
in the sand.
Or was it a hand
that drew them?
A shadow moves
amidst the dunes
Then merges into deep
dune sand.
{{< spacer >}}


<file_sep>---
title: "Shakshuka, 1,000 Ways"
slug: "shakshuka"
author: "<NAME>"
date: "2019-03-18T18:50:50-06:00"
draft: true
toc: false
comments: true
cover:
featured_image: /img/
tags: ["Recipe"]
typora-root-url: ../../content
---
### DRY
**⁘ 2 cups** chosen flours (I used ¾ whole wheat, 1/4 buckwheat)
------
## Method
Add wet ingredients to dry.
<file_sep>---
title: "Lodgepole Forest"
description: "Walking through a dream in Montana"
slug: ""
author: "<NAME>"
date: "2020-04-24T07:25:08-06:00"
draft: false
toc: false
comments: true
cover: CJ-24APR20.jpg
tags: ["Corona Journal"]
typora-root-url: ../../content
---
Walking in the dry forest
single note of a grey bird.
Peel up some bark
use it for a seat
lay down later same place to sleep.
Light rain in morning.
Wake under a log.
Open eyes to forest floor
scent of fresh mushrooms
growing from what has died.
Birds single song.
Walking through lodgepole.
Mind running like an endless river.
The morning and the day so near.
Evening so far away.
<file_sep>---
title: "Bodies - A Poem"
subtitle: ""
slug: ""
author: "<NAME>"
date: "2019-05-04T10:56:24-06:00"
draft: false
toc: false
comments: true
cover: 19-jemez.jpg
tags: [poems]
typora-root-url: ../../content
---
*Photo: Anna off trail in the Jemez*
My body, yours
the forest floor
body of earth.
High mountains
body of stone
left alone.
Rock cañon
and a sheep skull, full curl
that nobody claimed.
Calcium, schist to granite from magma
old cottonwood, sand
thirteen tracks of a roadrunner
disappearing into the *body of a desert.*
Sagebrush. Chimayo. Chamisa. Conejos
river running
under a bridge.
Bosqué, cottonwoods, los alamos
huge valley, snow body
wide open, hot, steam from spring body—
but cold that same night on our bodies.
Walking again, up the same way
but without a trail
to where we hid our bikes.
Riding in, then out
along a body
and in a body—
Being somebody?
Being nobody. <file_sep>---
title: "Lemon Currant Scones Of Life"
slug: "scones"
author: "<NAME>"
date: "2019-04-04T3:53:50-06:00"
draft: false
toc: false
comments: true
cover: 19.03-oatmeal-scones.jpg
tags: [recipe]
typora-root-url: ../../content
---
These buckwheat-oatmeal scones are surprisingly delicious. Buckwheat lends a cake-like texture and roasty flavor. Additions: toasted nuts, sesame seeds, or whatever you want. Recipe by [Anna](http://annakoenigart.com).
### DRY
**⁘ 2 cups** chosen flours (I used ¾ whole wheat, 1/4 buckwheat)
**⁘ 2 handfuls** of oats
**⁘ 1/2 tsp** salt
**⁘ 1 tsp** baking powder
**⁘** Currants to taste (soak awhile in hot water)
**⁘ 1 stick** cold butter (cut into dry ingredients)
### WET
**⁘ Large spoonful** of sourdough starter (dissolve in milk)
**⁘ 1/2 cup** milk
**⁘ 1 large** egg
**⁘ 1/3 cup** sugar (or to taste)
**⁘** zest of a lemon
---
## Method
Add wet ingredients to dry
Mix til combined, but don’t overdo (this helps keep the crumb cake-like—over stirring will toughen the dough)
Pat into fat disc and put wrapped in fridge for awhile
Shape desired thickness
Cut into squares / triangles / what have you
Oven at 400+ until bottoms are browned
---
<file_sep>---
title: "The Way"
subtitle: ""
slug: ""
author: "<NAME>"
date: "2019-07-19T22:33:01-07:00"
draft: false
toc: false
comments: true
cover: 19.04-19.jpg
tags:
typora-root-url: ../../content
---
<pre>
<em>All of the trails in this area are user maintained, and hard to follow.
The safe way: find someone familiar, and go together
The unsafe way: go alone</em>
— Directions to Lost Creek
Chuang Tzu picked up the trail where it ended, and kept on going
Li Po left behind a cup of steaming tea when he disappeared
Tu Fu a branched bamboo shack, covered with old weeds, and a frog inside
Lao Tzu left town by the most remote gate
In the woods, where there are no paths.
I go, and pretend to be alone.
It would be good to be really alone.
No one left to know, or meet
and nothing left to see.
"Life is long, Hudson
and by the end
you'll see how it ends up.
(An old climber, from the Fred Beckey days.)
We chalked up first ascents here and there.
Cascades, haida gawai, Canadian Rockies, and up into Alaska.
(Where the trees still throb with that loud-quiet thrum)
You've got a good heart, kid.
I told you once
my favorite place
are the steep slopes
before the trees end.
Where there are no trails."
</pre><file_sep>---
title: ""
slug: ""
author: "<NAME>"
date: "2019-03-23T11:37:17-06:00"
draft: false
comments: false
cover: 19.3-rocks.jpg
type: "homepage"
---
---
# [View All Posts ⇾](/posts)
---
<br />
### Subscribe to Grass Newsletter
Stay updated on what is posted here!
{{< email >}}
<file_sep>---
title: "Santa Fe"
subtitle: ""
slug: ""
author: "<NAME>"
date: "2019-06-07T08:37:20-06:00"
draft: false
toc: false
comments: true
cover:
tags:
typora-root-url: ../../content
---


On the corner of Cerillos and Don Diego I saw a man working on his car as I crossed the street. He had the hood up and was talking with a friend. "Is that a carbeurator?" I asked as I walked up. "Oh yeah, it's a carbeurator. Got the original clutch in it too man, like a hundred fifty thousand on it." We talked about how much easier it was to work on carbuerated cars rather than fuel injection. It turned out he and his friend were changing the fluids and getting the car ready for a move. "I've been living in this place 12 years man, and they just raised the rent $400. Just like that," he snapped his fingers. "And so I'm moving south." I told him I was looking for a place too, but from Taos for about a month and a half. My lease had just ended the day before, so I was staying at a friends with all me and my girlfriends stuff in the back of our pickup. He gave me some tips and said to check a few places. He said to look on Craigslist for sublets or house sitting. "I made it into a job but I never found nothing here man. I'm going to live in this thing," he pointed at a van parked next to us, with sheets over the windows "until that place down south opens up. I'm camping early man!" he said laughing. We talked for a while longer. I learned he grew up in Española, where he said me and my girlfriend "wouldn't really fit."
"But you know man I wouldn't fit where you come from, no offense."
"No but you could hang out with us," I said. He and his friend laughed.
"Well good luck, I'll pray for you," he said, clasping his hands at his chest.
"You too man, good luck."
"If you need a place to stay, let me know," he said.
"We're with a friend, but thanks."
"Well if you need something just come back here. Let me know. Let me know."
"Alright," I said shaking his hand.
I walked away feeling awkward and humbled: someone I barely knew, maybe in worse position than me, yet offering what he could. As we waited to cross Don Diego Mercedes and BMWs ripped by.
We walked down the street, and into our friend's house, and opened our laptops to look at Craigstlist again.<file_sep>---
title: "Three Ponderosa"
subtitle: ""
slug: ""
author: "<NAME>"
date: "2019-07-19T22:38:10-07:00"
draft: false
toc: false
comments: true
cover: 19.06.18.jpg
tags:
typora-root-url: ../../content
---
Close the eyes, and slip in
to that dark space.
A moment, then none.
No time.
I cannot explain.
Deep
in the pine woods
the water running by logs
and rafts
of flowers.
I come back, then go again.
A breath, or maybe more time passes.
In the dark: wavy changy patterns, like the bark
of Ponderosa.
The old trees dance so slow.
And the moons soft glow.
I can't even *see*, anymore:
who I am
or how I'll be.<file_sep>---
title: "The Flowing Heart Of The Mountain"
description: ""
slug: ""
author: "<NAME>"
date: "2020-05-29T18:00:27-06:00"
draft: false
toc: false
comments: true
cover: /2020-May/30-1.jpg
tags:
typora-root-url: ../../content
---
Maybe there will be a place
there may be a place, there could be a place:
A high ridge
Littered with white rocks
Above a flat valley
free of snow.
Green things growing in the valley below.
A stream flows through the middle, there may be a place,
there *might* be a place
if you stay on the ridge for long enough
looking down at the valley for about
a thousand years
enough to see the bristlecones grow and some die
and some live, there may be a place
—a place on a high ridge
there may be a place there where you can sit and watch
as the boulders do
for a long time
the water flow out of a spring in the side of a hill.
There: the cow valley, once aspen ground,
now thigh bones bleached white near the stellar's jay's spruce.
In the center of valley
there are a few rocks covered with orange lichen
—yellow, blue, green, and red—
the sunsets too, you can see
when sitting at the far end of the valley
where a chipmunk lives above the stream
and sits out on his porch to watch the whole valley, forever
but only for a few years.
Long enough to know where life comes from, living above the stream itself
as it flows perfectly clear and cold
from below his rockside home.
Clear at the source, the water cuts deeply where the cows go too many times
and muddies before the marsh halfway across.
The marsh is drying, and the snow less every year.
And I lay under engelmann spruce,
my head on a tussock.
A place where the stream is half muddied, and still maybe as it was once
clear and drinkable straight from the source.
My eyes drift from sky to land to water.
To hear the burble of this glassy fluid, one has to listen.
A small bee lands not an inch from my eye
and cleans his antennae off patiently
then flies off to save the whole world.
I hear if you lay there long enough
the rocks begin to speak
"though you are very small
you are very important"
They whisper to the stream
and the bee
and the chipmunk
to the wind, the trees
the groves of nettles under fir trees,
and they say this
to me—
The flowing heart of the mountain.
<file_sep>rm -R public
hugo
netlify deploy -p
<file_sep>---
title: "Shiso Water"
slug: "shiso-water"
author: "<NAME>"
date: "2019-03-12T09:26:04-06:00"
draft: false
toc: false
comments: true
cover: 19.03-shiso-water.jpg
featured_image: /img/19.03-shiso-water.jpg
tags: ["Recipe"]
typora-root-url: ../../content
---
### Shiso Water
- 1-2 Shiso Leaves
- 1” wide slice of lemon
- Boiling water
I like to make this water in the morning, before eating or drinking anything. Squeeze the lemon juice into a glass, add the leaves, and pour the water over. I’m not fully convinced about the idea of alkalizing the body through diet, however I feel like a sour drink early in the morning can relieve sugar cravings, and also improve digestion through stimulating the gallbladder.
Shiso (紫蘇) is also called beefsteak (?? no idea why) or perilla. It is kind of like a Japanese basil, but it comes from China originally. It is known as being very nutritious. It is used in the pickling of ume plums, and lends a pink-red color to anything it touches when wet.
紫: purple
蘇: to be resurrected, revived, rehabilitated<file_sep># Grass Journal
This is just a simple website for my writing and photography. Built with Hugo
<file_sep>---
title: "Why I Share"
subtitle: ""
slug: ""
author: "<NAME>"
date: "2019-08-14T19:40:35-06:00"
draft: false
toc: false
comments: true
cover: 19.Jul.19-86.jpg
tags:
typora-root-url: ../../content
---
After deleting my Instagram account, I have been thinking a lot about sharing.
When I was growing up, sharing was partly learned. It felt hard at first. It usually meant giving away something that you wouldn't get back. It meant a comittment of a resource to some person or purpose. Like a juicebox at lunch, or a seat at a table.
However, once a person learns to share, it feels good. At its root sharing is an inclusive act. Inclusivity feels better than exclusivity. Generosity has been proven to produce good feelings in giver and receiver.
Along with this, there is an unlearned human need to share. Sharing begets connection, which creates and maintains relationships. And you can see the innate generosity of humans in how children always want to help.
The earth is the original sharer, or gift. Being born on earth, we are completely dependent on her. Just how a grizzly is dependent on salmon runs, so we are dependent on rainfall, snowmelt, soil, weather, trees… As society has expanded, and technology has grown, we are actually more dependent on the earth than before—though at first it seems opposite. The ways we are dependent on it have simply been confused and hidden.
The ability to share comes from having something. I find it interesting I often see those with the most reluctant to share, whether it's friends, resources, space. And those with the least the most willing.
I think about the original gift of life, of just having a life, and it inspires, in me, a feeling of wanting to give back. I think this is where the deepest parts of my motivation to keep writing, keep working come from.
Thanks for reading, and check out this podcast episode about [sharing and gifts](https://charleseisenstein.org/podcasts/new-and-ancient-story-podcast/lynne-twist-a-conversation-about-living-in-the-gift-e37/)<file_sep>---
title: "Late Dinner (Recipe)"
subtitle: ""
slug: ""
author: "<NAME>"
date: "2019-03-31T20:45:19-06:00"
draft: false
toc: false
comments: true
cover: 19.03.31-Acequia.Snow.1.jpg
tags: ["Recipe"]
typora-root-url: ../../content
---








---

# Crackly-Toasted Late Dinner Rice 😱
## Rice
- **2 cups** short grain white rice
- **Water**, to cover rice to a depth of 1" (or consult your rice cooker instructions)
## Toppings
- **2 tbsp** butter
- **1 tbsp** good soy sauce (san j, ohsawa)
- **2 cloves** garlic, smashed & chopped
- **2** thinly sliced scallions
## Method
Put the rice and water in a pan, cover and bring to a boil. Once it has boiled, lower the heat and simmer for 15 min (or follow rice cooker instructions).
**Note**: The rice should turn out a little dry, and crackly on the bottom. If you want to skip this, just make it normally.
While the rice is cooking, add the butter to a small pan over medium heat and melt. Add the chopped garlic, and cook, stirring, until fragrant. Then add the soy sauce, and stir well, caramelizing it. Turn off once ingredients are well incorporated.
Check the rice. If it has begun to crackle and smell toasty, it's ready. At this point, its up to you how long you want to cook it. Longer = Drier.
Serve rice in bowls with sauce spooned over the top. Garnish with scallions. If you're hungry, add a 6 minute egg.<file_sep>---
title: "Filling The Void"
description: "Bruce K Alexander on the nature of addiction"
author: "<NAME>"
date: "2019-03-20"
draft: false
toc: false
comments: true
cover: 16.05.28-metolius.jpg
featured_image: /img/16.05.28-metolius.jpg
tags:
typora-root-url: ../../content
---
About twelve years ago, when I was 18, I wound up in college. I remember lots of things from those times, but I often remember hearing how awkward everything was. Maybe it was a buzzword back in those years. I just remember the word being appended to almost every sentence any of my peers uttered. "Isn't that awkward," they would say, about having to talk to a teacher after class. "He's so awkward," about a student whose voice cracked when asking a question. Etcetera.
It struck me as weird that common, everyday scenarios were considered awkward. I figured awkwardness would pass with time. I felt awkward myself. But one place I differed from my peers was that I wasn't into parties that much, and therefore not into drinking. But when I did go to parties, I'd sit in a corner and mostly observe what was happening.
From this lonely corner, I came to view alcohol as a social crutch, used to ease all this apparent awkwardness. And for some reason, after that first semester, I decided that I wanted to be OK without crutches—completely OK on my own, without substances to calm me down. No one told me to be that way. And it cost me a lot in terms of social aptitude: most of my friends wanted to go out and get drinks. You may not know this, but, if you're the only person not drinking, the situation is usually not that fun. There's also a pretty high chance you'll be derided by your peers.
Nowadays, most of my peers have grown up and don't drink often. I think many of them think about their health, and may not need alcohol to smooth things out these days. But there are others—some who need it still, and some who got habitually trapped, and drink out of habit or addiction. But I still have many questions about those earlier years. Why can some people can drink, yet make it out of the awkward phase without bad habits or addiction? Why do some feel a need to abstain totally (me)? And why do yet others get addicted?
I have been thinking about the state of society for a long time. I guess it's something I can't stop thinking about. I thought I would have figured it out by now, or given up, but so far neither of those things have happened. However, in regards to some of these questions about addiction and awkwardness , I read an incredible article recently. It's called [Filling The Void](https://thesunmagazine.org/issues/519/filling-the-void) by psychologist <NAME>. His work offers some alarming insights about the nature of addiction, namely, that it isn't inherent to us as beings.
In my experiences it's generally accepted that humans are prone to addiction. Addiction is seen as a powerful, dark force we have to resist at all times. But Alexander's research shows that addiction comes from something else, a collection of conditions that political economist Karl Polyani called **dislocation.**
> **Chevalier**: So if addiction doesn’t arise from properties of the drug itself, what causes it?
>
> **Alexander**: Drug addiction of all kinds arises primarily from the relentlessly increasing dislocation in our society.
>
> **Chevalier**: What do you mean by “dislocation”?
>
> **Alexander**: It’s a word political economist Karl Polanyi used to describe alienation or disconnection, a state of being ungrounded and ill at ease. People are dislocated when their vital needs for individual autonomy and belonging are unmet. Dislocated people don’t have a place in the established social order, and they fill that void with addiction. For instance, some young people can’t stop playing video games, because a virtual fantasy world provides the excitement, identity, and meaning that are lacking in their actual world.
>
> **Chevalier**: What causes all this dislocation?
>
> **Alexander**: The social and political system past generations struggled to create has been twisted into a cruel and stupid imperial system dominated by multinational corporations. This is hard for people to admit. Who can bear to face the fact that the consumer society we were raised to cherish is actually making us apathetic, crazy, and vulnerable to addiction? The disconnected, fragmented nature of our culture causes addiction, which causes further fragmentation. Most serious addictions are actually an adaptation to dislocation. To some extent addiction is a functional way of dealing with the problem. Of course, what people really need is to be genuinely recognized and accepted and believed in — to have a purpose.
As a follow up to this, I'm writing a post about why I quit Instagram. You can read more soon enough. But for now I really recommend you read the article quoted above (link also below), and consider the subtle ways a person can be addicted to things.
## [Filling The Void — <NAME> on the nature of addiction](https://thesunmagazine.org/issues/519/filling-the-void)
<file_sep>---
title: "Shortbread Cookies"
description: "Cookies that scratch the cookie itch"
slug: ""
author: "<NAME>"
date: "2020-04-07T07:41:58-06:00"
draft: false
toc: false
comments: true
cover: CJ-7APR20.jpg
tags: ["Corona Journal", "Recipe"]
typora-root-url: ../../content
---
In the morning I make tea. And lately I have been accompanying it with a single shortbread cookie.
For a long time I resisted making delicious cookies, because the problem of sugar. But I found if I make less delicious cookies, since they are less delicious, they don't scratch the cookie itch very well, so I end up eating more of them—which pretty much defeats the purpose of making "more healthy" cookies. :( So thanks to Anna's find of this great recipe, I've resorted to making cookies that are really too good. And somehow limiting myself to eating just two a day, since they really scratch the cookie itch.
## INGREDIENTS
**⁘ 1 cup plus 2 tablespoons** (9 ounces or 255 grams) room temperature salted butter (if not using salted butter, add ¾ tsp salt)
**⁘ 3/4 cup** (150 grams) sugar (brown, or light brown)
**⁘ 1 teaspoon** (5 ml) vanilla extract
**⁘ 2 ¼ cups** (295 grams) all-purpose flour
**⁘ 6 ounces** (170 grams) semi- or bittersweet dark chocolate, chopped (you want chunks, not thin shards of chocolate)
**⁘ 1** large egg (optional)
**⁘** Demerara, turbinado, raw, or sanding sugar, for rolling (optional)
**⁘** Flaky sea salt for sprinkling
{{< spacer >}}
------
{{< spacer >}}
## METHOD
Beat the butter, sugar, and vanilla with a metal spoon or fork until light and fluffy, scraping down bowl as needed. (**Note:** if you use a mixer, the butter must be cold and cut into small pieces. But it's easy enough to beat warm butter with a fork IMO). Add flour, and mix until just combined. Add chocolate chunks, mix just until incorporated. Mixture will be crumbly.
Divide dough evenly between two sheets of parchment paper, waxed paper, reusable wax cloths, or plastic wrap and use your hands to form the dough halves into logs about 2 to 2 1/4 inches in diameter. Chill until totally firm in freezer (30 min) or fridge (~2 hours).
When you’re ready to bake, heat oven to 350°F. Line one or two large baking sheets with parchment paper, or silpat if you have one.
**Optional:** Lightly beat the egg and open up your chilled cookies logs to brush it over the sides. Sprinkle the coarse sugar on the open paper or plastic wrap and roll the logs into it, coating them. (Honestly, these cookies are cookielike enough without egg coated candied edges!)
Using a sharp serrated knife, cut logs into 1/2-inch thick rounds. You’re going to hit some chocolate chunks, so saw gently, squeezing the cookie to keep it from breaking if needed. Arrange slices on prepared sheets one inch apart (they don’t spread much) and sprinkle each with a few flakes of salt. Bake for 12 to 15 minutes, or until the edges are just beginning to get golden brown. People always talk about wire cooling racks, but I don't own one—I just let the cookies cool on a room temperature sheet or plate. Voila!
<file_sep>---
title: "Grass"
slug: "grass"
date: 2019-03-01T22:53:17-07:00
draft: false
---

{{% center %}}
# WE ARE ALL A PART
Grass journal is a space of refreshing slowness.
A cool oasis of the internet.
A record of the beauty and mystery of landscapes.
I want you to spend some time here,
but you don't have to.
The greatest asset is true freedom—
from fear, from hate, from having to do things
that don't make any sense to you.
°
Sitting quietly,
doing nothing—
spring comes;
the grass greens, grows
by itself.
# [View All posts ⇾](/posts)
### [Subscribe](/subscribe)
{{% /center %}}
<file_sep>---
title: "53 May 19"
description: ""
slug: ""
author: "<NAME>"
date: "2020-05-19T18:28:04-06:00"
draft: true
toc: false
comments: true
cover:
tags:
typora-root-url: ../../content
---
Sometimes I want to post pictures of old friends that I don't talk to anymore, for one reason or another. I don't know why I don't talk to them in some cases—in other cases it's clear.
Sometimes I want to post pictures of old girlfriends who I'm pretty sure don't read or look at anything I make anymore—but then I don't ever post them. I'm not sure why I keep those photos hanging around on my hard drive. Maybe it's because I still appreciate that period of my life, even though it didn't work out. I think it's possible to going on loving someone even though that love didn't result in lifelong love.
Though I'm not very old, I'm not sure I believe in life long love anyway. Just one day for me is a series of distracting thoughts that carry me in different direction. There is no clear path that lines up, as there really isn't if one takes a look carefully. Just like walking through a forest, it's possible to stay on one route, but then again that's not very interesting.
Then again, sticking to one thing despite distractions also leads to a different experience of endless distraction. I always hear that this path is supposed to be better than the other one, of trying lots of things. I remember once someone told me, when I was 19 and trying to make a living as a freelance photographer in Portland, Oregon that I was going to have to choose something one day. Because that's what she did.
You see, the interesting thing about this situation is that I never listened to advice like that. I actually did the opposite. I chose what interested me, and if my interests shifted, my life direction shifted. I was defiant when the successful freelance photographer in Portland told me I had to pick something, but not defiant for the sake of defiance. I was defiant because I was confident that it was possible to walk my own path.
To have a lot of money, friends, influence—to be comfortable, safe and secure—that's the goal, right? That's some people's goal. But it doesn't have to be everyone's, right?
You see, the very act of writing these thoughts down has been a journey of inspiration. I didn't set out to write anything in particular. I wrote this out because I scrolled by yet again a photo of an old girlfriend, and really wondered about my reluctance to either post or delete it. Then I started hammering out those first two paragraphs, and suddenly by the end I'm talking about how I choose to live. You see, I don't know if writing that comes truly can be struck upon in any other way for me. I don't think rigorous following of techniques is my way. And thus my whole "life path."
I guess it's impossible for me *not* to be more astounded with every passing year.
Every season, I see a little more.
The feeling that I get in autumn cannot be explained in words.
It's like the feeling of an endless dusk,
or saying goodbye.
The end of a long trail, of thoughts and actions
combines into a stream of moments.
These moments spread out into the past
and then there is always something called "the future".
But in the autumn I just see red and yellow leaves
and little raindrops on the edges of plants—
and knowing the salmon are coming back in some places still—
little sparks in my dark mind, lights from a flame
happening here and there.<file_sep>---
title: "Spiritual, But Not Religious"
subtitle: ""
slug: ""
author: "<NAME>"
date: "2019-04-08T10:54:20-06:00"
draft: true
toc: false
comments: true
cover:
tags:
typora-root-url: ../../content
---
Yesterday I drove five minutes up a slow road to a dusty turnoff amidst piñons and rocks. There is no water in this spot, but heavy snowfall over winter has greened threads of grass between patches of sand and bare ground. Past the gate, an old road goes up a grade, like in so many places here, yet things grow so slowly the road could be fifty years old and remains clear. I wandered up then off the old road, and found even older ones under the trees, and sand filled arroyos, and older trails. I found tiny patches of willow that had been cropped to the very bottom by deer in winter. I was looking for a flat place to pitch a tent.
I found one under a grove of ponderosas, the ground covered with already tinder-dry pine needles. I set down a handful of sticks I had gathered, and put up my tent. I had no phone, or any electronic device, and there was only the occasional sound of the wind.
Once the tent was up, I sat in the shade of the vestibule and unfolded a small twig stove. I added dry, pencil-lead thin sticks to the stove, and then slid in some of the longer pieces I had found earlier. In a brief moment it was lit and burning without any smoke. I stood and wandered off between the trees.
Below older piñons were a few young saplings. They already had bright green tips on the end of each branch. The tips have a lemony, sweet scent. I asked permission to whatever it was that I could be grateful to, to the growth of the pine, to the land, to the snow and water, and the perfectly clean, crisp pine-needle air. Then I picked just three tips from each plant, and walked leisurely from sapling to sapling, until I had a handful. I raised the buds to my face and inhaled deeply.
Back at the tent I stoked the fire by pushing the long, dry sticks further into the box. Then I set a pot filled with water and the piñon tips atop the stove. As I sat, I opened up Mountains and Rivers Without End and read aloud the opening pages, to the robin I had seen
sorting through needles with her sharp eyes, for bugs,
to the first flowers I saw, yellow, being drunk by a serfid fly
to the pines themselves, if they felt vibrations of words
to the rocks themselves, in their endless passages through time.
As the tea came to boil, I poured some into my waiting cup, and pushed the burning sticks further in. Gradually, the fire died, leaving behind feathery white ash that had no weight. I drank the tea slowly, reading aloud more of the book, and then, finishing the first section, set it down.
Slowly the time passed, and slowly the tea decreased, and slowly I came back into an awareness of things around me, inside me, and the in-between of inside and out, the mingling of the two.
As the sun shifted, the tree shadows lengthened, and I moved into the light. I took the hot ash and coals to the last remaining snow in sight and put them out, piling more snow on top, and mixing them into the snow. Then I smoothed it over, so no one could tell anything had happened there.
Back at the tent, I folded up my stove, un-staked, folded, and rolled the tent, and slid it all into my pack. I stood up, and looked around. I looked down at the ground, and the small bundle of sticks that remained, piled in a way that you could tell a person put them there. Where I stood was once a settlement of Anasazi (the ancient ones) who came before the Taos people, or maybe turned into the Taos people. Shards of pots still line an old creek, and once the land had been cleared. People had harvested the piñons when the chamisa turned yellow, and caught fish, hunted deer, and walked into the high mountains for aspen bark, and also drank tea, sitting beneath the pines… like me.
I walked away from the place where I had sat, made a fire, and borrowed what was freely offered. More than tea, clean air and sun was given. I was lucky to have a space made for it. A space within, that wants to be filled, that is taken from, put into, and then given away.
<file_sep>---
title: "A Body of Water"
subtitle: ""
slug: ""
author: "<NAME>"
date: "2020-01-11T07:15:25-07:00"
draft: false
toc: false
comments: true
cover: 2019-breakneck.jpg
tags:
typora-root-url: ../../content
---
About ten years ago I carried a camera with me wherever I went. It was mostly film rangefinders back then—Leicas, Bronicas, Olympus XAs, a Zeiss or two—and I had the film developed. And I scanned it myself. I posted the photos to Flickr. I had thousands of photos there. I switched to DSLRS after a while, then back and forth, then went digital for good when film developing started to get ever more expensive.
About five years ago I deleted that Flickr account and posted on Instagram. Then about six months ago I deleted the Instagram account. And so lately the thousands of photos have existed only on my backup drives, nowhere that anyone could access them.
Kept to myself, I have wondered what the point of all those years of photo taking was. I couldn't help myself, the world was so beautiful that I had to take photos. I think, if not stifled, every person feels this way about life on earth at some point.
In 2013 I left Nebraska and headed for places I'd never been. I took a few photos during the next four years, but mostly I observed and thought. The mystery of life, and what it was all about, what mattered to me, and to others—where I was going, and what I should do—all these things I worked out over and over again in different ways.
This work, the writing and photos, has since coalesced into a coherent vision of a life that I lived—something like a dream, a thread, or a stream—that keeps unspooling and going around in different ways. After battling with the idea of publishing, agents, and all that garbage, I decided to put the entire project on the internet for free, at the rate of 1 to 3 posts per week, for everyone to see.
You can follow along here: [A Body of Water](http://write.as/bodyofwater)
Thanks for reading,
— Hudson<file_sep>---
title: "{{ replace .Name "-" " " | title }}"
description: ""
slug: ""
author: "<NAME>"
date: "{{ .Date }}"
draft: true
toc: false
comments: true
cover:
tags:
typora-root-url: ../../content
---
<file_sep>---
title: "Anxiety & The Present Moment"
description: ""
slug: ""
author: "<NAME>"
date: "2020-05-04T03:18:06-06:00"
draft: false
toc: false
comments: true
cover: /2020-May/2-1.jpg
tags: ["Corona Journal"]
typora-root-url: ../../content
---
Growing up, I was taught one of two reactions when things go wrong: either be filled with dread about the outcome, or get angry.
As time has gone on, I realized that I, like maybe almost everyone, am not good at dealing with anxiety in positive ways. I first became aware of this maybe 8 years ago, on my first cross-country drive alone, when nothing went wrong at all, yet I was filled with dread about what *might* go wrong for almost the entire trip. This is the best way I can explain the kind of anxiety that I seem prone to: always trying to forecast what may or may not happen and pre-empt it. The problem is my pre-empting usually means worrying—and worrying destroys the experience of whatever is *actually* happening.
Of course, no one can say what may or may not happen. Every moment is a dice roll as to what will turn up. About a month ago I finished reading a book called *The Wisdom of Insecurity*. That book, by <NAME>, states that we live in not *an* age of anxiety but *the* age of anxiety—and this book was written decades ago, when people may have been less anxious than they are now.
The reason, Watts posits, that we are so anxious is because we are constantly trying to tie the water of life into neat little paper packages. This metaphor resounded with me because of my Body of Water project, and also because of its truthfulness. Water *is* like life, in the metaphorical sense—
> *The whole problem of existence
> is that we are are like a river, but not
> minds always flowing
> restless, unable to stop.*
> *Trying to stop, or flow
> never gets the same place
> to go anywhere else.
> Making blockages, breaking
> the going still going.*
[A Body of Water](http://write.as/bodyofwater)
I wrote this poem long before I read Watts' book. Yet reading his book about insecurity deepened my own understanding of what I was trying to say in that poem. Life flows along in ways no one can control. Yet it seems most of what I have been taught about "how to live" has been about control.
Watts goes on—since life is uncontrollable, the only realistic act is a kind of surrender to or focus on the present moment. The present is the only moment we really have. It's strange to *really* realize this—that Past is a memory, and Future is a story. And whether we think about the future or the past, we are doing so in the present.
So how does the present moment relate to anxiety? Thusly: if this moment right now—of sitting at the birchwood breakfast table, typing in the morning light, with the stove heating water in a steel pot, and the cool air flowing in through the window—is all I have, then what I choose to pay attention to, in this moment and the next, becomes my entire life. Life ceases to be about some imagined future or remembered past.
Therefore your reaction to this moment can be called a produced experience, and that reaction/experience can be colored in uncountable ways. It turns out that this produced experience, whether it be of anxiety, happiness, anger, etc is all that we really have. It's the experience of this very moment. Since that is the case, whether we have an anxious or non-anxious experience seems to be up to us. Yet the weight of habit and conditioning compels us to not be able to control our produced experience (our reaction) to the given experience (the set of circumstances) of this moment. So we may react "badly" or "well", yet these reactions "never get the same place/to go anywhere else". We are still firmly stuck in our experience, whether we are approaching it in "good" or "bad" ways.
This is where I get confused, yet the idea of "not controlling" the experience seems important. I don't want to go down the rabbit hole of "free will" vs "divine plan" and/or the existence of a "self" (read Watts' book). So the only thing I can say is that habituating yourself to a different produced experience during the given experience is the only way forward to being different, to getting that same place/person to go somewhere or be someone else. The only way to do this is not to be lost in the past or future, regret or anxiety, and to be aware of the given experience of this moment, and your reaction to it. That's really the only hope to overcoming past habits.
Seeing things this way has helped me get a hold on my anxiety issues, maybe more than ever before. Anxiety is a type of fear, which meticulous planning and forecasting is supposed to prevent. Fear is one of the most powerful forces in the world. So, to be unafraid is to not be controlled by circumstance, to not be controlled by fear when plans inevitably go awry. This is a very grounded way to live, and really the only clear way as far as I can reason. I hope that with more practice I can become less anxious and more able to live in the present—in the stream of the water of life, rather than trying to control it and getting upset when it collapses the sides of my paper box.

{{< youtube Ba6qkzkpSXQ >}}<file_sep>---
title: "Who"
date: 2019-03-01T22:53:17-07:00
draft: false
---

{{% center %}}
## <NAME>
川風
Who takes cold mountain road
takes a road that never ends.
—**<NAME> (Cold Mountain), c. 800**
It is necessary for the perfection of human society that there should be people who devote their lives to contemplation.
— **St <NAME>, c. 1250**
{{% /center %}}
At heart, I am a contemplative observer. This has led me, in turn, to living an artists life. To me specifially, that means living closely in relationship to plants, animals, and landscapes. These inhuman relationships are as valuable as human relationships to me. I find they make me more human. I spend a lot of time walking, biking, gardening, foraging, and otherwise being outside.
As of March 2019 I am finishing my first full-length book of writing — A Body of Water.
My writing and photos have been published by Patagonia, The Sun, American Public Media, Taproot Magazine, and more.
I have a BA in Eastern Religion with a minor in Psychology.
I enjoy the sacred act of doing nothing.
<br /><br />
{{% center %}}
## [Contact](mailto:<EMAIL>) • [Playlists](https://open.spotify.com/user/hudsongardner?si=wOM4S_4NSX6Nl5StmqPsZA) • [A Body of Water](http://write.as/bodyofwater)
{{% /center %}}
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
<meta name="author" content="<NAME>">
<meta name="description" content="The big mountains rose quickly from the flat piñon plain below. Massive, snow-capped mountains, and a sixty mile wide valley broke the scale of distance I was used to. And the weird piñons, with their twisted, old trunks, low tops, many branches: more like oaks than pine trees; held a strange presence. The plain itself savanna-like, with low grass and sagebrush, antelope, and slow-moving mule deer, who I would see in the mornings along the dry watercourses, under black cottonwoods."/>
<meta name="keywords" content=""/>
<meta name="robots" content="noodp"/>
<link rel="canonical" href="https://grassjournal.co/meditation-01/" />
<title>
A Story About a Meditation Retreat, #1
</title>
<link rel="preload" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700|Source+Code+Pro|Karla|Crimson+Text|EB+Garamond" rel="stylesheet" type="text/css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/3.2.1/css/flag-icon.min.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://grassjournal.co/scss/main.min.8d3117196f064348d0a81facc32bb4a30731cce10ccc1f954eb49230c15fb160.css">
<link rel="apple-touch-icon" sizes="180x180" href="https://grassjournal.co/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="https://grassjournal.co/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="https://grassjournal.co/favicon-16x16.png">
<link rel="manifest" href="https://grassjournal.co/site.webmanifest">
<link rel="mask-icon" href="https://grassjournal.co/safari-pinned-tab.svg" color="">
<link rel="shortcut icon" href="https://grassjournal.co/favicon.ico">
<link rel="icon" type="image/png" href="https://grassjournal.co/favicon.ico">
<link rel="icon" href="favicon.ico" type="image/x-icon"/>
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon"/>
<meta itemprop="name" content="A Story About a Meditation Retreat, #1">
<meta itemprop="description" content="The big mountains rose quickly from the flat piñon plain below. Massive, snow-capped mountains, and a sixty mile wide valley broke the scale of distance I was used to. And the weird piñons, with their twisted, old trunks, low tops, many branches: more like oaks than pine trees; held a strange presence. The plain itself savanna-like, with low grass and sagebrush, antelope, and slow-moving mule deer, who I would see in the mornings along the dry watercourses, under black cottonwoods.">
<meta itemprop="datePublished" content="2019-03-01T08:02:30+00:00" />
<meta itemprop="dateModified" content="2019-03-01T08:02:30+00:00" />
<meta itemprop="wordCount" content="981">
<meta itemprop="image" content="https://grassjournal.co"/>
<meta itemprop="keywords" content="" /><meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content="https://grassjournal.co"/>
<meta name="twitter:title" content="A Story About a Meditation Retreat, #1"/>
<meta name="twitter:description" content="The big mountains rose quickly from the flat piñon plain below. Massive, snow-capped mountains, and a sixty mile wide valley broke the scale of distance I was used to. And the weird piñons, with their twisted, old trunks, low tops, many branches: more like oaks than pine trees; held a strange presence. The plain itself savanna-like, with low grass and sagebrush, antelope, and slow-moving mule deer, who I would see in the mornings along the dry watercourses, under black cottonwoods."/>
<meta property="article:published_time" content="2019-03-01 08:02:30 +0000 UTC" />
</head>
<body class="">
<div class="container">
<header class="header">
<span class="header__inner">
<a href="https://grassjournal.co/" style="text-decoration: none;">
<div class="logo">
<span class="logo__text">○ Home</span>
</div>
</a>
<span class="header__right">
<nav class="menu">
<ul class="menu__inner"><li><a href="https://grassjournal.co/posts">Posts</a></li><li><a href="https://grassjournal.co/who">Who</a></li><li><a href="https://grassjournal.co/grass">About</a></li><li><a href="https://grassjournal.co/bodyofwater">A Body of Water</a></li>
</ul>
</nav>
<span class="menu-trigger">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path d="M0 0h24v24H0z" fill="none"/>
<path d="M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z"/>
</svg>
</span>
<span class="theme-toggle unselectable"><svg class="theme-toggler" width="24" height="24" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M22 41C32.4934 41 41 32.4934 41 22C41 11.5066 32.4934 3 22
3C11.5066 3 3 11.5066 3 22C3 32.4934 11.5066 41 22 41ZM7 22C7
13.7157 13.7157 7 22 7V37C13.7157 37 7 30.2843 7 22Z"/>
</svg>
</span>
</span>
</span>
</header>
<div class="content">
<main class="post">
<article>
<img src="https://grassjournal.co/img/19.2-mountains.jpg" class="post-cover" />
<h1 id="underline">A Story About a Meditation Retreat, #1</h1>
<ul id="post">
March 01, 2019 • 5 minutes
</ul>
<div class="post-content">
<p>The big mountains rose quickly from the flat piñon plain below. Massive, snow-capped mountains, and a sixty mile wide valley broke the scale of distance I was used to. And the weird piñons, with their twisted, old trunks, low tops, many branches: more like oaks than pine trees; held a strange presence. The plain itself savanna-like, with low grass and sagebrush, antelope, and slow-moving mule deer, who I would see in the mornings along the dry watercourses, under black cottonwoods.</p>
<p>I had driven north from Taos, through the wide valley to attend a meditation retreat in the Tibetan Bön tradition, an old tradition mixing Tibetan cultural practices and Buddhism. The retreat cost around $300 for a few days sleeping in a house and a few days sitting in a big circular room, listening to a rinpoche (lit. precious one) talk about Dzogchen, a type of meditation that involves relaxation and a unique lack of effort.</p>
<p>When I arrived, the first thing I noted was the number of new-model cars parked for the retreat. The majority were under five years old. A woman immediately walked up to me and said “are we supposed to park here? I’m gonna move my car. I think we’re supposed to park over there. I don’t think we can park here. I don’t know where.” She gestured vaguely towards a road running into the vast expanse of sagebrush. I shrugged and just kept walking.</p>
<p>At the entrance I was confronted by two people checking lists for names, other people milling about, a variety of scarves, shawls, baggy clothes, hiking boots, and Patagonia jackets piled in corners. The light came in precisely, very clearly, through floor to ceiling windows. It was like the light always is in the high mountains, acute and intense. We were at around 8,000 feet. Outside the mountains rose to over fourteen.</p>
<p>As I settled down on a meditation cushion in the middle of the circular conference room, a man with an unplaceable accent sat next to me. He grew up in Israel, and was Jewish. “Do you practice?” I asked. No, not really, he said. He comes to these things once or twice a year. He’s a massage therapist. He asked me what I did. I said I wandered around and wrote, making money however I could. He said I looked like a professor, but that I should give it a few years.</p>
<p>As we sat for the beginning, he leaned over from time to time to let me know what was going on. We did tsa-lung practice, a type of energetic breath and body work made to be done seated that “opens chakras.” Having never been to a retreat, but practicing meditation for about ten years alone, I found it strange to be in a room of around a hundred people, all saying the Sanksrit syllable “Ah” and imagining white light entering our bodies. Everyone else was ok with it.</p>
<p>As the first morning progressed, I was struck by the humor and ease of the rinpoche. He said things like “just leave it as it is,” and “just relax,” and also “you have reflected enough!” He took questions, and carefully avoided going into people’s personal experience. He was skilled at answering questions.</p>
<p>On the second day, I put up my hand and, while asking a question, made a joke. Several people laughed, as they had at many of the jokes he made. But he had an air of irritation, and as I continued my question, he said “what, is this funny or something?” I got the feeling that he was the one who could make jokes, make people laugh. Others were not allowed that liberty.</p>
<p>On the third and final day, we went outside for a puja. I had seen such things on documentaries, notably The Wheel of Time by <NAME>, where a massive hill of incense, juniper, pine wood, prayer flags, and other offerings are piled and set fire to. For our puja we had one of those cast braziers you might see at a suburban home, with a rusty metal grate. Inside a fire of piñon was made, and I was tasked with placing the crumbling, burning incense around the mesh. Rinpoche read a lot of Tibetan and everyone stood around silently, as the smoke billowed feebly from the fire, smelling like nothing really. We each took a handful of barley flour and threw it into the air, which I had also seen. In the video of the Tibetan people at the base of the Himalayas, this scene had the cameraman wading into throngs, people screaming and yelping, bells crashing, and smoke overwhelming the video, turning the screen opaque. Glimpses of weathered brown faces flitted across the screen, heavy woolen robes tied at the waist, prayer wheels, malas, lung-ta billowing, and smoke, smoke, smoke. But around me I saw the pale faced people, in nylon jackets, blankly talking and looking bored, throwing the barley when told to, laughing when queued, being silent when not, below snowy mountains that were not dissimilar to the Himalayas.</p>
<p>As I walked away, a tall white guy with long dreads came up to me. His name was Juniper, and he was from this area. He said: “we’re trying to start a little community here. I have some land. It’s an AirBnB. Next time you come through, let me know. You can stay at our AirBnB.”</p>
<p>I headed to my car, and drove back to the newly built retreat house, to stay one last night. The house looked like it had been airlifted from a subdivision outside Omaha, Nebraska, except it was on an incredibly steep hillside, surrounded by piñons, below the snow-covered mountains. There were new washer-dryer front loading units, a giant island, new fridge, dimmable lighting, soft-closing cabinets, shiny hardwood floors. Everything inside was clean, white, new, unmarked, pure. And very, very expensive.</p>
</div>
</article>
<div class="post-info">
</div>
<div class="pagination">
<div class="pagination__title">
<span class="pagination__title-h">Read other posts</span>
<hr />
</div>
<div class="pagination__buttons">
<span class="button previous">
<a href="https://grassjournal.co/meditation-02/">
<span class="button__icon">←</span>
<span class="button__text">A Story About A Meditation Retreat, #2</span>
</a>
</span>
<span class="button previous">
<a href="https://grassjournal.co/posts#archive">
<span class="button__text">○</span>
</a>
</span>
<span class="button next">
<a href="https://grassjournal.co/new-grass/">
<span class="button__text">Grass</span>
<span class="button__icon">→</span>
</a>
</span>
</div>
</div>
</main>
</div>
<footer class="footer">
<div class="footer__inner">
<div class="footer__content">
<span>© 2020</span>
<span><a href="https://open.spotify.com/user/hudsongardner?si=wOM4S_4NSX6Nl5StmqPsZA">Playlists</a></span>
<span><a href="https://grassjournal.co/who">Contact</a></span>
<span><a href="https://grassjournal.co/subscribe">Subscribe</a></span>
<span><a href="https://open.spotify.com/show/0xLswpUQDCjWpnw6fnZv85">Podcast</a></span>
</div>
</div>
<div class="footer__inner">
<div class="footer__content">
</div>
</div>
</footer>
</div>
<script type="text/javascript" src="https://grassjournal.co/bundle.min.fa6cec57f81<KEY>" integrity="<KEY>></script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-136102762-1', 'auto');
ga('send', 'pageview');
</script>
</body>
</html>
<file_sep>---
title: "What We Need?"
description: ""
slug: ""
author: "<NAME>"
date: "2020-05-08T12:39:07-06:00"
draft: false
toc: false
comments: true
cover: /2020-May/8-1.jpg
tags:
typora-root-url: ../../content
---
Do we have what we need? I sometimes wonder what I really need. Food, water, shelter, clothing, right? And yet, and yet as time has gone on it seems I have taken on more epicurean sorts of needs. Tea, sourdough bread, cookies with the tea, certain mugs and tents, other backpacking gear...
I wonder how long I could go without certain things, and if I would miss them or not?
One thing I miss is a sense of community. I think everyone is feeling that nowadays. Community doesn't really exist online. It has to involve inhabiting space with people.
I wonder how much we need, and how much we all miss, and if that will change as time goes on.
There is a theory that successive generations of people do not sense the loss of environments or animals because we are born into a world where there is a new baseline. So I guess it is also possible to say there are things that we *cannot know* that we miss.
Today I am listening to [<NAME>](https://music.youtube.com/watch?v=bQAF2PPz4Ag&feature=share). I took a few photos on a film camera from the 70s that I got off ebay last week
—The crank winds the film with a ratcheting sound. The exposure is shown on a needle in the small viewfinder. The leaf shutter clicks and the picture scene is imprinted—
Maybe film photography is something I missed. I notice that I am noticing even more—looking for those old angles and patterns of light. And yet the ability and desire to write also has not ceased. Maybe, if I can keep up both of these things up I will get to where I have always been going. Which looks like, to me, a greater awareness of being filled with whatever each moment has to offer. It may sound woozy or sentimental, but I've found that even the feeling of warm pavement on my feet feels as good as almost anything else.
*Where do you go?*
Some end of a road
In a dense thicket of blackberry brambles
bursting sticky fruit scenting the hot summer air
covering the black asphalt
*Where do you go?*
Some end of the road
The side trails, *you can still see*
*This* is *important.*
They lead under cedar boughs.
*Where do you go?*
Under the gravel of the river beyond
Are bones of the earth
The beginning of another road
As always the end is a beginning
Of infinite endings and beginnings
Spreading out in all directions
*Where do you go?*
And how do you know
it is worth the going?
Waves under waves
soothe the gravel into sand
an estuary, a bog
dipping clear water
from a rainwater pond
to drink for breakfast
Sunrise, sunset
this is the beginning
and end
of this song.<file_sep>---
title: "The Wild Finds A Way"
description: "Dedicated To My Mom"
slug: ""
author: "<NAME>"
date: "2020-05-16T06:49:02-06:00"
draft: false
toc: false
comments: true
cover: /2020-May/16-1.jpg
tags:
typora-root-url: ../../content
---
This morning, as I sat at the birch table, I heard a stick break outside the window. I stood up and looked out onto the courtyard. Ambling across the brick patio was one of the largest raccoons I've ever seen. She tentatively looked around as she walked around the corner of the house and down the driveway, toward Agua Fria street.
In a few minutes she was back, but this time with a young raccoon in her mouth. She headed straight for the overgrown ivy bush at the back of the house, and disappeared into it through an area that seemed far too small and dense to swallow such a huge animal.
All day she has been sleeping there, with who knows how many young children raccoons stashed behind the overgrown ivy.
This overgrown yard, filled with beautiful desert weeds, lizards, and rare birds. Maybe it's the little saucer of water we fill every day that keeps them all coming back. It's a dry patch along a busy street, yet somehow wildness finds a way.
~~
At the bridge we crossed a dry river
that went underground after a clear lake.
Across the road it bubbled up again
in a place called Fish Lake.
The water of the lake it came out of
was so perfectly clear, and cold
that you could see old stumps and tree's bones
—when it had been a meadow once, long ago.
People now paddled lazily
with no motors in sight
above the deep, cold, clear lake.
I sat beside a huge tree with my mom
then we drank straight from a spring that rushed out of a hill.
Things like this just happen,
and keep going on.
Mom says: "I like to know
that this spring we sit beside, and drink
is still running, no matter where I am
or what I think."
The water stays clear,
if we can keep it that way—
in that place that is far away from me now,
yet also right here.
A place I call Clear Clear Lake.<file_sep>---
title: "Coronajournal - Cats & Car Maintenance"
description: ""
slug: ""
author: "<NAME>"
date: "2020-04-02T07:40:24-06:00"
draft: false
toc: false
comments: true
cover: CJ-2APR20.jpg
tags: ["Corona Journal"]
typora-root-url: ../../content
---
I have been doing pushups lately. But my schedule is erratic. I rarely know when I will do a pushup. Sometimes I do them in the morning before I take my dogbone loop run through the dry neighborhoods. Sometimes at night just before bed. There are lots of times when I don't want to do them, but I do them anyway.
As I write now I can hear birds outside in the chamisa, which is also called rabbitbrush. Some people really don't like the scent of rabbitbrush, but I tend to like it for some reason. The birds live in it as it provides good cover from the neighborhood cats. Did you know domestic cats kill billions of small mammals and birds every year? They are single-pawedly implicated in the extinction of speceies in some places, like islands. If you ever wonder why there are less birds year after year—because, if you haven't noticed, there are—blame the cats.
This morning my hands are cold and I haven't moved from the red futon that I write on sometimes. I first meditated for a while but couldn't stop thinking about all the aspects of my car that need to be fixed still before we leave Santa Fe. So far I have replaced the thermostat, the bottom radiator hose, the rear differential fluid, about 20 feet of vaccuum line, the PCV valve, the radiator cap. I sealed the exhaust with muffler weld and also used some room temperature vulcanizing silicone to fix a tiny tear that developed in the stupid brand new 900-dollar-job CV boot. Sorry if that's boring to hear, because a year ago I also wouldn't have known what almost any of that was. But if you buy a 1991 Isuzu Pickup off craigslist, even if it only has 64,000 miles on it (like this one) you better know how to replace a lot of stuff fast or you're gonna run up a big bill at the mechanic. The only work that really is left to do is the valve cover gasket and maybe a fuel line that leaks randomly every 6 months. Oh, and the front brakes. Which I'll leave to a mechanic.
I have managed to spend this entire morning hacking away at this website, which I built more or less from scratch a year ago. Coding is a lot like auto maintainence actually. One tries things and turns it back on, and if it sounds good, I guess it is done right.
The light keeps changing every day. The days are longer, but we are inside. It seems trails are shutting down all over the country. I wonder if animals are feeling restful with less people around. It's great of humans to go outdoors, to own cars, cats, and all these things. But man, it sure takes a tax on the earth in the process.<file_sep>---
title: "April 30, 2020"
description: "Visions of Quarantine"
slug: ""
author: "<NAME>"
date: "2020-04-30T09:01:56-06:00"
draft: false
toc: false
comments: true
cover: CJ-30APR20.jpg
tags: ["Corona Journal"]
typora-root-url: ../../content
---
I saw a man playing trumpet for an hour over background jazz music
I saw a woman juggling, and answering every question
I saw birds collect in the backyard, drinking water three times a day, arguing about who goes first
I saw a cat sleeping on a stack of pillows
I saw steam rise from morning tea
I saw ineffable feelings
I saw the color of roast hazelnuts when I took them out of the oven
I saw people turning inward
I saw people helping one another
I saw beyond the surface
I saw shadows in the dark
I saw light changing in the morning
I also saw the days growing longer
I saw photos of my friends farming
I saw people typing and working
I saw a man back hoeing in a dry river alone
I saw clear water flowing over yellowish rocks
I saw aspens turning green
I also saw myself in a mirror one day
I looked into my eyes
They were darker than I remembered
They reflected some light
and absorbed some light
and also let light in.<file_sep>---
title: "Slow"
subtitle: ""
slug: ""
author: "<NAME>"
date: "2019-04-28T18:12:14-06:00"
draft: false
toc: false
comments: true
cover: 19.04.24-Poppies.jpg
tags:
typora-root-url: ../../content
---
A long time ago I wrote every day for a year. That blog was called Slow Gospel.
Slow Gospel offered a space where people could slow down, even for a moment.
The entries were brief, not longer than 500 words.
That was back in 2012. Things were already humming along pretty quickly back then in the big old world.
After a year I took the site down. It did not gain an audience as I hoped it would. So it lost meaning for me to write it.
At one point, I wanted to write longer things. I had an idea that writing longer meant I would eventually write a book.
I thought longer writing meant the writing was more sophisticated and meant more, even though I knew simplicity was actually complex, and multilayered, hitched to everything if done right.
I didn't expect to turn aside from that route, and begin writing even shorter than before. Distilling experiences, thoughts, feelings down to a few lines.
And now I feel the urge to write shorter and shorter.
I want to think about people, not about problems. What are people attracted to? What gives a sense of relief?
Pounding down on the problems of the world creates more problems. It's like weeding. Remove a plant, and there is space for another. The weeds will never end.
I'll cook them for my meal.<file_sep>---
title: "Light Hiking New Mexico"
description: "Going early into the Sangres"
slug: ""
author: "<NAME>"
date: "2020-04-21T07:11:10-06:00"
draft: false
toc: false
comments: true
cover: CJ-20APR20-1.jpg
tags: ["Corona Journal", "Hiking"]
typora-root-url: ../../content
---





Up in the high valleys of the Sangre de Cristo mountains, the snow has begun to melt. Patches of snow remain below the aspen groves, or on northern slopes. High up, around 9,500 feet, the snow is still deep. Near Agua Piedra (rock water) I found a closed trail headed up to a valley. We parked the truck down the road, and walked past closed summer cabins to the beginning. A creek ran quickly to the left. It ran through a dry, mixed forest of ponderosa, white fir, and spruce. The forest of Northern New Mexico.
Almost nothing was green yet. But sapsuckers and woodpeckers screamed and hammered on dead trunks. Red squirrels chided from spruce boughs. My left arm went totally numb.
I was hiking with a 30L frameless pack. But to the back was strapped a tomahawk. And a bahco laplander saw. These two extra items, along with the steep grade, pulled my back backwards toward the earth, compressing the brachial plexus of my left side. This resulted in a pins and needles feeling in my hands, which quickly gave way to stiffness and pain.
After ceaselessly adjusting the pack, and wondering aloud with Anna why the trail was marked closed (we counted 3 minor downed trees), we hit flat ground. Then the valley opened up before us. Elk sign was everywhere. Wild flowers, that looked like trillium, were just beginning to grow. But the grass in the valley was laid flat and golden by the snow that had so recently melted. And an old wrecked cabin stood at the edge, roof and half its timbers gone.
Ahead of us Bear Hill (cerro del oso) loomed, covered in aspen and rocky mountain doug fir. We crossed the narrow stream through a thicket of alders and set up camp amongst ground that had not been camped on in years. The path through the meadow, though clear and easy, was growing in. Pocket gophers heaved dirt mounds in the center of the trail.
Trees, huge for this dry state, loomed on the eastern side of the meadow. The sun would rise there. We went to the west side, a few tens of feet above valley bottom, amidst a grove of aspen, above where the cold air would settle during the night.
The small clearing where we stayed was the domain of elk. Rubbings on trees showed where they worked the velvet off their antlers last summer. Small paths crossing the stream showed the best way to walk. Nibbled aspen tops showed what they had been eating. A rumbling and crackling, and then thumping into the distance along the slope near sundown showed we were in their way. We slept all night long by the stream, and heard two owls hooting early in the morning.
Along the edge of the little clearing a spruce had died and fallen. Its branches were sticking into the air. I used my saw and tomahawk to cut and split several. They were so dry they lit like a candle.
As the hours passed in the meadow, I looked around at the trees and grass. The ground was lumpy from years of gopher work. There was downed wood everywhere. It was easy to tell that no human had stayed here for a long time, or if they had they had left no trace. Due to unmarked nature of the trail, and the closed sign, I wondered how long it had been, since deer and elk alone had walked here.
I trimmed dead branches from the base of a living doug fir, to clean the trunk and hang my pack there. I cut and sawed branches of aspen, and used a rotting one as a sawhorse. I bucked and piled and lit the wood, and boiled creek water for hot spruce needle tea. By using the land, with the small knowledge I had, I made it less fire prone, and better for humans like me.
And yet the shaping and moving of such small things, in such a tiny quiet place, stuck in my mind and troubled me. Are we born to do such things, is our use only a use of such space? I think that we can contribute more than we take. We can do crazy things like move beavers to places they once lived. They fix the rivers the cows destroyed, and put thousands of gallons into reservoirs. In a single day a beaver can fix what cows took ten years to desecrate.
So with our knowing eye we can grow food for more than us, and make watering places for birds. We can use the land in a way that helps, and not only in ways that harm.
The next morning I donned my wool sweater against the chill. I cut green willow to size and made a rack for bacon above our fire. The smoke mingled with the salt and fat. We ate the bacon hot and crispy with green chiles grown down south in the hatch valley.<file_sep>---
title: "April 29, 2020"
description: "Bones"
slug: ""
author: "<NAME>"
date: "2020-04-29T06:59:52-06:00"
draft: false
toc: false
comments: true
cover: CJ-29APR20.jpg
tags: ["Corona Journal"]
typora-root-url: ../../content
---
[Music For You To Listen To While You Read](https://soundcloud.com/prcvl/nicolas-jaar-april161900gmt)
Walking across valleys
then down to rivers.
So much space to choose from
yet a tiny trail threads through the middle.
A distant mountain, thirty miles away
looks like it can be touched.
Walking toward it for three days
it only grows larger.
Standing on it, like an ant on a house.
Chipped bones from reindeer
lay beside granite rocks—
Twinflower blooming pinkly in dark clefts—
a place to sleep.
Cloudberries to eat
cold water to drink.
When I don't know what to write anymore, I look into my bones. I spoke recently about the writing bone, but this is a different kind of bone. A new bone, and old bone. Bones meaning things that hold us up.
When one doesn't notice their bones, one feels weightless. The bones attach to ligaments, and then to muscles, which keep it all moving. You can control your body with just your mind. Look, my fingers are typing out this unphysical series of thoughts.
Bones are made of minerals. Do bones grow and change?
The sun this morning first landed on the tawny chamisatops. Not all people like the smell of that bush, but I do. Cattle around here ate all the sagebrush. So now there's only chamisa left. Sage brush dies after a fire because it spreads by seed. So there has to be a new crop to blow seed to where it was.
There are many sounds, thoughts, feelings—all occurring in a vast expanse. This expanse stretches from the great bone in the sky to the red blood of the ground and then spreads out in who knows how many directions. In the center of this space is a warm white sphere. This sphere some call your mind. <file_sep>---
title: "Gardner Farm"
subtitle: ""
slug: ""
author: "<NAME>"
date: "2019-12-26T15:35:02-07:00"
draft: false
toc: false
comments: true
cover:
tags:
typora-root-url: ../../content
---





<file_sep>---
title: "A Body of Water"
slug: "bodyofwater"
author: "<NAME>"
date: "2019-08-02T19:58:40-06:00"
draft: false
comments: false
images:
---
{{% center %}}
## A modern ecological epic
{{% /center %}}
**A Body of Water** is a book I wrote over four years. It includes photos taken over the last decade. The writing and photos follow a narrative arc through several watersheds and ten years of time as I search for home and meaning in life. It is a story about staying true to myself. You can read a longer explanation of the project [here](https://grassjournal.co/a-body-of-water/)
## [https://write.as/bodyofwater/](https://write.as/bodyofwater)
<file_sep>---
title: "Poetry"
subtitle: ""
slug: ""
author: "<NAME>"
date: "2019-09-09T6:25:42-06:00"
draft: false
toc: false
comments: true
cover: 19.8.22-Buddhism.jpg
tags:
typora-root-url: ../../content
---
> “It is difficult to get the news from poems
> yet men die miserably every day
> for lack of what is found there.”
— <NAME>
I remember wandering in the woods in Maine, not long ago, and I saw a tree stump. And I thought, how worthless this stump. The tree has died, and there is nothing left but a jagged place, taking up space. And yet, as we know now, trees, for some reason, keep other trees [alive long after death](https://www.amazon.com/Hidden-Life-Trees-Communicate_Discoveries-Secret/dp/1771642483). No one knows why.
I had a thought at that moment: poetry is the most worthless thing, the most useless thing. It has no purpose, it makes little money, and yet, as WCW said above, people die every day knowing everything but poetry.
It made sense, in that moment, that I had come to write poetry, and this book "A Body of Water". You see, like most people, I thought poetry was either slam or long old ballads, or Leaves of Grass for the longest time. It turns out: poetry is simply distilled language. It is crystalized examples of our main way of communicating: words.
Poetry can be a story. It can be a description. It can be three words. It can be a single thought, one sentence. It can be a whole book with a narrative. It lends itself to many things. It's not all emotional. It can be scientific. It is flexible as the language it is born from.
I wanted to write about this because I think poetry matters. And I want people to know that it's more than "going light and knowing flowers," or "what you will do with this one precious life." Poetry is maybe not something with wide appeal, but it should be, especially today. The problem with poetry is that it takes presence, awareness, pause, and reflection to absorb. And these things are in short supply these days.
There is so much "news" now, it's almost impossible to get away from it. Endless feeds of every kind, enouraging a kind of incessant need to consume. Continuous consumption becomes a habit, and there are hooks thrown into you by the platforms that demand it, such as friends and connections, and then the platforms profit from our attention. I am not using any platforms or news apps anymore, for months now, and the shift has been enourmous. I have felt incredibly isolated, because no one really writes letters or emails or text messages anymore. The platforms have gobbled up all connection and demanded that people use them instead of the Old Ways. That's ok, because it has given me more time to think, and to be alone, which I actually enjoy. Though it is hard to feel valued, as I wrote in Sharing a month or so ago.
I return to thinking of that old stump (and how "the aged pine grows old alone in it's canyon"). And I don't despair. I think of how everything needs everything, and by being and writing, I too am doing that work. The work of the old stump in the woods, the old pine in the canyon, the old words that one person my come across once a century, that change everything.<file_sep>---
title: "Holidays"
subtitle: ""
slug: ""
author: "<NAME>"
date: "2019-11-26T10:56:48-07:00"
draft: false
toc: false
comments: true
cover: 20191125-HLG_4189.jpg
tags:
typora-root-url: ../../content
---





### <center>Photos by Anna</center>
Every year I make a playlist of holiday music. It has a winter theme, I guess mostly drawn from the feeling of the season. Here are this year and the last two years worth—
[🎄Holidays, Vol. 1](https://open.spotify.com/playlist/5HgxzyRioJ8CAXZnM83bfv?si=2DvHC-UcQO2I3MD2koSHWw)
[❄️Holidays, Vol. 2](https://open.spotify.com/playlist/1ysa2bATHjbUQLAsoIZuPr?si=Mz4N34fNRY-Y5bpIM39JpQ)
[⛄️Holidays, Vol. 3](https://open.spotify.com/playlist/3xzirZ8VT0I6YyL9AxGo7m?si=RQanxCHEQ1WerWpQOe3mGQ)
<file_sep>---
title: "Come Together"
description: ""
slug: ""
author: "<NAME>"
date: "2020-04-08T06:17:21-06:00"
draft: false
toc: false
comments: true
cover: CJ-8APR20.jpg
tags: ["Corona Journal"]
typora-root-url: ../../content
---
Everyone on earth has had an argument with another person. During the argument, when emotions are high, it's often really hard to recognize the other person as human. All kinds of bad words and names come to mind. Maybe not everyone feels this way during arguments, but I know that I have.
To ameliorate the impact of arguments, I came up with an idea of agreements, which I think I first encountered talking with my mom, when we were talking about a book called *The Four Agreements* by <NAME>. His four agreements are these:
## 1. Be Impeccable With Your Word
## 2. Don't Take Anything Personally
## 3. Don't Make Assumptions
## 4. Always Do Your Best
Keeping all of these agreements all the time seems impossible. At least I haven't been able to keep them. I think that holding oneself to an unrealistic standard can create friction within. So to simplify these few agreements, and make them more realistic for myself, I have developed just two of my own in dealing with conflict —
1. **Do not argue in bad faith.** Argue with civility. This means: do not insult or personally attack someone, or try to prove that they are inherently bad. Argue the **issue** at hand, not the goodness or badness of the person. An important phrase here is ad hominem, "to the person", which in fancy terms is a fallacy (an unsound argument). It means mistaking the act for the person. Often this kind of argument occurs over beliefs like religion or politics.
2. **Try my best to help the relationship survive.** This does not mean the relationship has to stay the same, but that civility, kindness, care, and regard for one another are maintained, even if the parties go their separate ways. Sometimes a relationship can fully survive, and continue on as it was, and sometimes it changes. This depends on the depth of the relationship, and the seriousness of the argument.
I read an article yesterday morning, after I wrote about cookies, about how the UK asked for volunteers to help vulnerable Britons, and [more than 750,000 people signed up.](https://www.nytimes.com/2020/04/07/world/europe/coronavirus-volunteers-uk.html?action=click&module=Spotlight&pgtype=Homepage)
>A few weeks ago, <NAME> was organizing a James Bond getaway for her wealthy clients, in which they would have been flown by helicopter to Monte Carlo for a preview of the latest Bond movie, a glittering party with cast members and, for each guest, an Aston Martin gassed up and ready to drive.
>
>Last week, <NAME> lugged two bags of groceries from her local supermarket to the front step of <NAME>, a 73-year-old retired accountant who is marooned inside his house as the coronavirus sweeps London.
>
>“It’s just heartbreaking not to be able to help him carry his groceries up the stairs,” she said, as she waved at <NAME> from his front gate. “We can’t go into people’s houses because that would put them at risk.”
This is remarkable journalism, and incredibly important in these times. The first paragraph paints a picture of a lavish, out-of-touch person. The second nukes that opinion. The third brought me to tears.
It also proves the uselessness of ad hominem arguments, as it shows people are not defined by one action.
> “During the Brexit debate, people used to say what we really need is a common enemy — and now we’ve got it,” said <NAME>, a writer whose last book, “The Road to Somewhere,” explored the divide in British society between the rooted and the rootless. “Except this is an invisible enemy.”
Yes, we are all people. Yes, we all have our idiosyncrasies. But the sharing of our common humanity is our most powerful asset.
> "When I speak of ‘basic human feeling’, I refer to the capacity we all have to empathize with one another. This is what enables us to enter into the pain of others and, to some extent, participate in the pain of others.
>
> Our innate capacity for empathy is the source of that most precious of all human qualities, which in Tibetan we call *nyingjé*. The term *nyingjé* has a wealth of meaning that includes: love, affection, kindness, gentleness, generosity of spirit, and warm-heartedness. **It does not imply pity; on the contrary, *nyingjé* denotes a feeling of connection with others.** Also, it belongs to that category of emotions which have a more developed cognitive component. So we can understand *nyingjé* as a combination of empathy and reason.
>
> We can think of empathy as the characteristic of a very warm-hearted or well-meaning person; reason as that of someone who is very practical (and truly intelligent and wise). When the two are put together, the combination is highly effective."
>
> *— HHDL, Ethics for the New Millenium*
Reading about The UK's strategy of recruiting willing volunteers (they put out a call for 250,000 and got the aforementioned 750,000 applicants) is exactly the story we all need to hear right now. I think it is easy to want to slay dragons. It's harder to think that helping your 70 your old neighbor matters. But you know who it helps? Your 70 year old neighbor. And I think it helps you, too.<file_sep>---
title: "May 1, 2020"
description: "The Good Old Days"
slug: ""
author: "<NAME>"
date: "2020-05-01T06:32:31-06:00"
draft: false
toc: false
comments: true
cover:
tags: ["Corona Journal"]
typora-root-url: ../../content
---
Today I wanted to share a few photos from the old times.
Back in those days when I lived in a place with a community of people around, and in a place that felt like home.
When rent was $250 a month, and I got all the free vegetables I ever wanted from the co-op where I worked.
When I used to have film cameras, and spend the days between work and college wandering alleys finding moments of beauty.
You know, the good old days. Everyone had them once.
Not to say these days aren't good and old either.
I always find the good old days when I take my time and walk places. They still lurk around rusting old mailboxes and rough cut tree stumps. And around the edges of strange young lizards basking on the concrete on hot days. And nowadays I know a few more things, like what matters to me, and what I want to do most times. Yet the old friend "confusion" often creeps in, and anxiety too. (Confusion is a pale old man with a five panel hat named "pi-kun" who sits endlessly at a diner late into the night. But these days I don't have much I want to prove, or anything particularly to achieve. You may say I left lots of ideas I used to have back in those same old days.



<file_sep>---
title: "Making Things In The Instagram Era"
description: ""
slug: "making-things-instagram-era"
author: "<NAME>"
date: "2020-05-28T10:20:41-06:00"
draft: false
toc: false
comments: true
cover: /2020-May/28-2.jpg
tags:
typora-root-url: ../../content
---
I got really burned out on photography a few years ago because I felt like posting photos online had become a game of trying to appease an algorithm that was based on making people addicted to staring at teabag sized images on their phones.
I felt lost in trying to fight to be seen when the content I make is not really popular or trendy. So I gave up, as I felt that the work and time I spent with that medium wasn't valuable anymore—people's focus and attention had shifted. There was and is a surplus of images to the point of saturation. And maybe I wasn't really taking all that interesting of photos anyway.
But now, I am finding my way back into taking photos again, but with a different purpose behind the work. As I can't find the energy to try and compete on social media for likes, views, and followers, I want to take the work back to the medium where it started, in print. The problem is, printing is expensive, and the audience, without a following, so small I can't imagine breaking even on a small book series.
I've explored all avenues and done many of them, such as having lots of followers on Instagram, running a newsletter, blogging, running a kickstarter, getting grants and residencies, etc. The problem is, to get a lot of reach or success with all those things essentially requires two things: either you become your own agent of promotion with a stacked CV or a lot of followers, or you find an agent ie: pay someone to promote you. It's all mixed up with money and ego, which really have nothing to do with what I'm trying to create and why—it might even be antithetical to the work itself. I'm being idealistic, I realize, when I don't want to play all those games. But if a person doesn't compromise their vision, is it necessary that they have to settle for something different than those that do?
I guess it is.
But at the same time this doesn't really lead me into wanting to spend effort making things that no one will ever see.
I think that this last thought gets down to the root of the matter, which is "why make anything?" Discussing that, however, leads down a rabbit hole about ego and meaning and contribution. To keep it more simple, this is why I make things: I write and take pictures because I love to. And from past experience I feel people benefit when they encounter my work, or at least enjoy it.
So in order to continue in this way, it seems like I need to really give up on the idea that I will ever be canonized, famous, or important to anyone other than a small group of people.
Honestly, what a relief.
It would be nice to just keep living the life I have now, now that I think about it. Yeah, it's not so bad after all! Maybe I'll even start taking photos of things again.

| 2640e0a995e7ef45ae6609b903f6221a0235548e | [
"Markdown",
"TOML",
"HTML",
"Shell"
] | 73 | Markdown | rivrwind/grass-journal | 80401f6e9124e408860937ac406efd89bb501131 | 52ae6fef941c66a905fe625cd0493b9490f2d75a |
refs/heads/master | <repo_name>Sam-Online/csharp-lox<file_sep>/loxcli/Interpreter.cs
using System;
using System.Collections.Generic;
namespace loxcli {
public class Interpreter : IExprVisitor<object>, IStmtVisitor<object> {
private class ClockFunc : ILoxCallable {
private static readonly DateTime EPOCH = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public int Arity() {
return 0;
}
public object Call(Interpreter interpreter, List<object> arguments) {
return (DateTime.UtcNow - EPOCH).TotalMilliseconds;
}
public override string ToString() {
return "<native function>";
}
}
internal readonly Environment globals = new Environment();
private readonly Dictionary<Expr, int> locals = new Dictionary<Expr, int>();
private Environment environment;
public Interpreter() {
environment = globals;
globals.Define("clock", new ClockFunc());
}
public void Interpret(List<Stmt> statements) {
try {
foreach (Stmt s in statements) {
Execute(s);
}
} catch (RuntimeError error) {
Lox.RuntimeError(error);
}
}
public object VisitAsignExpr(Assign expr) {
object value = Evaluate(expr.Value);
if (locals.ContainsKey(expr)) {
int distance = locals[expr];
environment.AssignAt(distance, expr.Name, value);
} else {
globals.Assign(expr.Name, value);
}
return value;
}
public object VisitBinaryExpr(Binary expr) {
object left = Evaluate(expr.Left);
object right = Evaluate(expr.Right);
switch (expr.Operator.type) {
case TokenType.BANG_EQUAL:
return !IsEqual(left, right);
case TokenType.EQUAL_EQUAL:
return IsEqual(left, right);
case TokenType.GREATER:
CheckNumberOperands(expr.Operator, left, right);
return (double)left > (double)right;
case TokenType.GREATER_EQUAL:
CheckNumberOperands(expr.Operator, left, right);
return (double)left >= (double)right;
case TokenType.LESS:
CheckNumberOperands(expr.Operator, left, right);
return (double)left < (double)right;
case TokenType.LESS_EQUAL:
CheckNumberOperands(expr.Operator, left, right);
return (double)left <= (double)right;
case TokenType.MINUS:
CheckNumberOperands(expr.Operator, left, right);
return (double)left - (double)right;
case TokenType.PLUS:
if (left.GetType() == typeof(double) && right.GetType() == typeof(double)) {
return (double)left + (double)right;
}
if (left.GetType() == typeof(string) && right.GetType() == typeof(string)) {
return (string)left + (string)right;
}
throw new RuntimeError(expr.Operator, "Operands must be two numbers or two strings");
case TokenType.SLASH:
CheckNumberOperands(expr.Operator, left, right);
return (double)left / (double)right;
case TokenType.STAR:
CheckNumberOperands(expr.Operator, left, right);
return (double)left * (double)right;
}
throw new Exception("Reached unreachable code.");
}
public object VisitCallExpr(Call expr) {
object callee = Evaluate(expr.callee);
List<object> arguments = new List<object>();
foreach (Expr a in expr.arguments) {
arguments.Add(Evaluate(a));
}
if (!(callee.GetType() != typeof(ILoxCallable))) {
throw new RuntimeError(expr.paren, "Can only call functions and clases.");
}
ILoxCallable function = (ILoxCallable)callee;
if (arguments.Count != function.Arity()) {
throw new RuntimeError(expr.paren, "Expected " + function.Arity() + " arguments but got " + arguments.Count + ".");
}
return function.Call(this, arguments);
}
public object VisitGroupingExpr(Grouping expr) {
return Evaluate(expr.Expression);
}
public object VisitGetExpr(Get expr) {
object obj = Evaluate(expr.obj);
if (obj.GetType() == typeof(LoxInstance)) {
return ((LoxInstance)obj).Get(expr.name);
}
throw new RuntimeError(expr.name, "Only instances have properties.");
}
public object VisitLiteralExpr(Literal expr) {
return expr.Value;
}
public object VisitLogicalExpr(Logical expr) {
Object left = Evaluate(expr.left);
if (expr.op.type == TokenType.OR) {
if (IsTruthy(left)) {
return left;
}
} else {
if (!IsTruthy(left)) {
return left;
}
}
return Evaluate(expr.right);
}
public object VisitSetExpr(Set expr) {
object obj = Evaluate(expr.obj);
if (obj.GetType() != typeof(LoxInstance)) {
throw new RuntimeError(expr.name, "Only instances have fields.");
}
object value = Evaluate(expr.value);
((LoxInstance)obj).Set(expr.name, value);
return value;
}
public object VisitThisExpr(This expr) {
return LookUpVariable(expr.keyword, expr);
}
public object VisitUnaryExpr(Unary expr) {
object right = Evaluate(expr.Right);
switch (expr.Operator.type) {
case TokenType.BANG:
return !IsTruthy(right);
case TokenType.MINUS:
CheckNumberOperand(expr.Operator, right);
return -(double)right;
}
throw new Exception("Hit un-reachable code");
}
public object VisitVariableExpr(Variable expr) {
return LookUpVariable(expr.Name, expr);
}
private object LookUpVariable(Token name, Expr expr) {
if (locals.ContainsKey(expr)) {
int distance = locals[expr];
return environment.GetAt(distance, name.lexeme);
} else {
return globals.Get(name);
}
}
private void CheckNumberOperand(Token op, Object operand) {
if (operand.GetType() == typeof(double)) {
return;
}
throw new RuntimeError(op, "Operand must be a number");
}
private void CheckNumberOperands(Token op, object left, object right) {
if (left.GetType() == typeof(double) && right.GetType() == typeof(double)) {
return;
}
throw new RuntimeError(op, "Operands must be numbers");
}
private bool IsTruthy(object obj) {
if (obj == null) return false;
if (obj.GetType() == typeof(bool)) {
return (bool)obj;
}
return true;
}
private bool IsEqual(object a, object b) {
if (a == null && b == null) {
return true;
}
if (a == null) {
return false;
}
return a.Equals(b);
}
private string Stringify(object obj) {
if (obj == null) {
return "nil";
}
return obj.ToString();
}
private object Evaluate(Expr expr) {
return expr.Accept(this);
}
private void Execute(Stmt stmt) {
stmt.Accept(this);
}
internal void Resolve(Expr expr, int depth) {
locals.Add(expr, depth);
}
internal void ExecuteBlock(List<Stmt> statements, Environment environment) {
Environment previous = this.environment;
try {
this.environment = environment;
foreach (Stmt s in statements) {
Execute(s);
}
} finally {
this.environment = previous;
}
}
public object VisitBlockStmt(Block stmt) {
ExecuteBlock(stmt.statements, new Environment(environment));
return null;
}
public object VisitClassStmt(Class stmt) {
environment.Define(stmt.name.lexeme, null);
Dictionary<string, LoxFunction> methods = new Dictionary<string, LoxFunction>();
foreach (Function method in stmt.methods) {
LoxFunction function = new LoxFunction(method, environment, method.name.lexeme.Equals("init"));
methods.Add(method.name.lexeme, function);
}
LoxClass klass = new LoxClass(stmt.name.lexeme, methods);
environment.Assign(stmt.name, klass);
return null;
}
public object VisitExpressionStmt(Expression stmt) {
Evaluate(stmt.expression);
return null;
}
public object VisitFunctionStmt(Function stmt) {
LoxFunction function = new LoxFunction(stmt, environment, false);
environment.Define(stmt.name.lexeme, function);
return null;
}
public object VisitIfStmt(If stmt) {
if (IsTruthy(Evaluate(stmt.condition))) {
Execute(stmt.thenBranch);
} else {
Execute(stmt.elseBranch);
}
return null;
}
public object VisitPrintStmt(Print stmt) {
object value = Evaluate(stmt.expression);
Console.WriteLine(Stringify(value));
return null;
}
public object VisitReturnStmt(Return stmt) {
object value = null;
if (stmt.value != null) {
value = Evaluate(stmt.value);
}
throw new ReturnEx(value);
}
public object VisitVarStmt(Var stmt) {
object value = null;
if (stmt.initializer != null) {
value = Evaluate(stmt.initializer);
}
environment.Define(stmt.name.lexeme, value);
return null;
}
public object VisitWhileStmt(While stmt) {
while (IsTruthy(Evaluate(stmt.condition))) {
Execute(stmt.body);
}
return null;
}
}
class RuntimeError : Exception {
public Token token;
public RuntimeError(Token token, String message) : base(message) {
this.token = token;
}
}
class ReturnEx : Exception {
internal readonly object value;
internal ReturnEx(object value) : base() {
this.value = value;
}
}
}
<file_sep>/loxcli/LoxInstance.cs
using System.Collections.Generic;
namespace loxcli {
internal class LoxInstance {
private readonly LoxClass klass;
private readonly Dictionary<string, object> fields = new Dictionary<string, object>();
internal LoxInstance(LoxClass loxClass) {
this.klass = loxClass;
}
internal object Get(Token name) {
if (fields.ContainsKey(name.lexeme)) {
return fields[name.lexeme];
}
LoxFunction method = klass.FindMethod(name.lexeme);
if (method != null) {
return method.Bind(this);
}
throw new RuntimeError(name, "Undefined property '" + name.lexeme + "'.");
}
internal void Set(Token name, object value) {
if (!fields.ContainsKey(name.lexeme)) {
fields.Add(name.lexeme, value);
} else {
fields[name.lexeme] = value;
}
}
public override string ToString() {
return klass.name + " Instance";
}
}
}<file_sep>/loxcli/Resolver.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace loxcli {
internal class Resolver : IExprVisitor<object>, IStmtVisitor<object> {
private readonly Interpreter interpreter;
private readonly Stack<Dictionary<string, bool>> scopes = new Stack<Dictionary<string, bool>>();
private FunctionType currentFunction = FunctionType.NONE;
private ClassType currentClass = ClassType.NONE;
internal Resolver(Interpreter interpreter) {
this.interpreter = interpreter;
}
internal void Resolve(List<Stmt> statements) {
foreach (Stmt s in statements) {
Resolve(s);
}
}
private void Resolve(Stmt stmt) {
stmt.Accept(this);
}
private void Resolve(Expr expr) {
expr.Accept(this);
}
private void ResolveFunction(Function function, FunctionType type) {
FunctionType enclosingType = currentFunction;
currentFunction = type;
BeginScope();
foreach (Token p in function.param) {
Declare(p);
Define(p);
}
Resolve(function.body);
EndScope();
currentFunction = enclosingType;
}
private void BeginScope() {
scopes.Push(new Dictionary<string, bool>());
}
private void EndScope() {
scopes.Pop();
}
private void Declare(Token name) {
if (scopes.Count == 0) {
return;
}
Dictionary<string, bool> scope = scopes.Peek();
if (scope.ContainsKey(name.lexeme)) {
Lox.Error(name, "Variable with this name already exists in this scope");
}
scope.Add(name.lexeme, false);
}
private void Define(Token name) {
if (scopes.Count == 0) {
return;
}
scopes.Peek()[name.lexeme] = true;
}
private void ResolveLocal(Expr expr, Token name) {
// The c# stack is the wrong way up!
// Elements are added at the zero index, and everything
// moves up by one! Seriously!
for (int i = 0; i < scopes.Count; i += 1) {
if (scopes.ElementAt(i).ContainsKey(name.lexeme)) {
interpreter.Resolve(expr, i);
return;
}
}
}
public object VisitAsignExpr(Assign expr) {
Resolve(expr.Value);
ResolveLocal(expr, expr.Name);
return null;
}
public object VisitBinaryExpr(Binary expr) {
Resolve(expr.Left);
Resolve(expr.Right);
return null;
}
public object VisitBlockStmt(Block Stmt) {
BeginScope();
Resolve(Stmt.statements);
EndScope();
return null;
}
public object VisitCallExpr(Call expr) {
Resolve(expr.callee);
foreach (Expr arg in expr.arguments) {
Resolve(arg);
}
return null;
}
public object VisitClassStmt(Class stmt) {
ClassType enclosingClass = currentClass;
currentClass = ClassType.CLASS;
Declare(stmt.name);
Define(stmt.name);
BeginScope();
scopes.Peek().Add("this", true);
foreach (Function method in stmt.methods) {
FunctionType decl = FunctionType.METHOD;
if (method.name.lexeme.Equals("init")) {
decl = FunctionType.INITIALIZER;
}
ResolveFunction(method, decl);
}
EndScope();
currentClass = enclosingClass;
return null;
}
public object VisitExpressionStmt(Expression stmt) {
Resolve(stmt.expression);
return null;
}
public object VisitFunctionStmt(Function stmt) {
Declare(stmt.name);
Define(stmt.name);
ResolveFunction(stmt, FunctionType.FUNCTION);
return null;
}
public object VisitGetExpr(Get expr) {
Resolve(expr.obj);
return null;
}
public object VisitGroupingExpr(Grouping expr) {
Resolve(expr.Expression);
return null;
}
public object VisitIfStmt(If stmt) {
Resolve(stmt.condition);
Resolve(stmt.thenBranch);
if (stmt.elseBranch != null) {
Resolve(stmt.elseBranch);
}
return null;
}
public object VisitLiteralExpr(Literal expr) {
return null;
}
public object VisitLogicalExpr(Logical expr) {
Resolve(expr.left);
Resolve(expr.right);
return null;
}
public object VisitPrintStmt(Print stmt) {
Resolve(stmt.expression);
return null;
}
public object VisitReturnStmt(Return stmt) {
if (currentFunction == FunctionType.NONE) {
Lox.Error(stmt.keyword, "Cannot return from top-level code.");
}
if (stmt.value != null) {
if (currentFunction == FunctionType.INITIALIZER) {
Lox.Error(stmt.keyword, "Can't return a value from an initializer.");
}
Resolve(stmt.value);
}
return null;
}
public object VisitSetExpr(Set expr) {
Resolve(expr.value);
Resolve(expr.obj);
return null;
}
public object VisitThisExpr(This expr) {
if (currentClass == ClassType.NONE) {
Lox.Error(expr.keyword, "Can't use this outside of a class.");
return null;
}
ResolveLocal(expr, expr.keyword);
return null;
}
public object VisitUnaryExpr(Unary expr) {
Resolve(expr.Right);
return null;
}
public object VisitVariableExpr(Variable expr) {
if (scopes.Count > 0 && !scopes.Peek()[expr.Name.lexeme]) {
Lox.Error(expr.Name, "Can't read local variable in it's own initializer.");
}
ResolveLocal(expr, expr.Name);
return null;
}
public object VisitVarStmt(Var stmt) {
Declare(stmt.name);
if (stmt.initializer != null) {
Resolve(stmt.initializer);
}
Define(stmt.name);
return null;
}
public object VisitWhileStmt(While stmt) {
Resolve(stmt.condition);
Resolve(stmt.body);
return null;
}
private enum FunctionType {
NONE,
FUNCTION,
INITIALIZER,
METHOD
}
private enum ClassType {
NONE,
CLASS
}
}
}
<file_sep>/README.md
# csharp-lox
Lox is the language described in [Crafting Interpreters](https://www.craftinginterpreters.com/).
This is my implementation, written in C# to make it easier to integrate into [KSP](https://kerbalspaceprogram.com/)
<file_sep>/loxcli/ASTPrinter.cs
using System;
using System.Text;
namespace loxcli {
class ASTPrinter : IExprVisitor<String> {
public string Print(Expr expr) {
return expr.Accept(this);
}
public string VisitAsignExpr(Assign expr) {
throw new NotImplementedException();
}
public string VisitBinaryExpr(Binary expr) {
return Parenthesize(expr.Operator.lexeme, expr.Left, expr.Right);
}
public string VisitCallExpr(Call expr) {
return Parenthesize("call", expr.arguments.ToArray());
}
public string VisitGetExpr(Get expr) {
throw new NotImplementedException();
}
public string VisitGroupingExpr(Grouping expr) {
return Parenthesize("group", expr.Expression);
}
public string VisitLiteralExpr(Literal expr) {
if (expr.Value == null) {
return "nil";
}
return expr.Value.ToString();
}
public string VisitLogicalExpr(Logical expr) {
return Parenthesize(expr.op.lexeme, expr.left, expr.right);
}
public string VisitSetExpr(Set expr) {
throw new NotImplementedException();
}
public string VisitThisExpr(This @this) {
throw new NotImplementedException();
}
public string VisitUnaryExpr(Unary expr) {
return Parenthesize(expr.Operator.lexeme, expr.Right);
}
public string VisitVariableExpr(Variable expr) {
return expr.Name.lexeme;
}
private string Parenthesize(string name, params Expr[] terms) {
StringBuilder result = new StringBuilder();
result.Append("(").Append(name);
foreach (Expr expr in terms) {
result.Append(" ");
result.Append(expr.Accept(this));
}
result.Append(")");
return result.ToString();
}
}
}
<file_sep>/loxcli/Stmt.cs
using System.Collections.Generic;
namespace loxcli {
public abstract class Stmt {
public abstract R Accept<R>(IStmtVisitor<R> visitor);
}
public interface IStmtVisitor<R> {
R VisitBlockStmt(Block Stmt);
R VisitClassStmt(Class Stmt);
R VisitExpressionStmt(Expression stmt);
R VisitFunctionStmt(Function function);
R VisitIfStmt(If stmt);
R VisitPrintStmt(Print stmt);
R VisitReturnStmt(Return @return);
R VisitWhileStmt(While stmt);
R VisitVarStmt(Var stmt);
}
public class Block : Stmt {
public List<Stmt> statements;
public Block(List<Stmt> statements) {
this.statements = statements;
}
public override R Accept<R>(IStmtVisitor<R> visitor) {
return visitor.VisitBlockStmt(this);
}
}
public class Class : Stmt {
public Token name;
public List<Function> methods;
public Class(Token name, List<Function> methods) {
this.name = name;
this.methods = methods;
}
public override R Accept<R>(IStmtVisitor<R> visitor) {
return visitor.VisitClassStmt(this);
}
}
public class Expression : Stmt {
public Expr expression;
public Expression(Expr expression) {
this.expression = expression;
}
public override R Accept<R>(IStmtVisitor<R> visitor) {
return visitor.VisitExpressionStmt(this);
}
}
public class Function : Stmt {
public Token name;
public List<Token> param;
public List<Stmt> body;
public Function(Token name, List<Token> param, List<Stmt> body) {
this.name = name;
this.param = param;
this.body = body;
}
public override R Accept<R>(IStmtVisitor<R> visitor) {
return visitor.VisitFunctionStmt(this);
}
}
public class If : Stmt {
public Expr condition;
public Stmt thenBranch;
public Stmt elseBranch;
public If(Expr condition, Stmt thenBranch, Stmt elseBranch) {
this.condition = condition;
this.thenBranch = thenBranch;
this.elseBranch = elseBranch;
}
public override R Accept<R>(IStmtVisitor<R> visitor) {
return visitor.VisitIfStmt(this);
}
}
public class Print : Stmt {
public Expr expression;
public Print(Expr expression) {
this.expression = expression;
}
public override R Accept<R>(IStmtVisitor<R> visitor) {
return visitor.VisitPrintStmt(this);
}
}
public class Return : Stmt {
public Token keyword;
public Expr value;
public Return(Token keyword, Expr value) {
this.keyword = keyword;
this.value = value;
}
public override R Accept<R>(IStmtVisitor<R> visitor) {
return visitor.VisitReturnStmt(this);
}
}
public class Var : Stmt {
public Token name;
public Expr initializer;
public Var(Token name, Expr initializer) {
this.name = name;
this.initializer = initializer;
}
public override R Accept<R>(IStmtVisitor<R> visitor) {
return visitor.VisitVarStmt(this);
}
}
public class While : Stmt {
public Expr condition;
public Stmt body;
public While(Expr condition, Stmt body) {
this.condition = condition;
this.body = body;
}
public override R Accept<R>(IStmtVisitor<R> visitor) {
return visitor.VisitWhileStmt(this);
}
}
}
<file_sep>/loxcli/LoxClass.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace loxcli {
internal class LoxClass : ILoxCallable {
internal readonly string name;
private readonly Dictionary<string, LoxFunction> methods;
internal LoxClass(string name, Dictionary<string, LoxFunction> methods) {
this.name = name;
this.methods = methods;
}
public int Arity() {
LoxFunction initilizer = FindMethod("init");
if (initilizer == null) {
return 0;
}
return initilizer.Arity();
}
public object Call(Interpreter interpreter, List<object> arguments) {
LoxInstance instance = new LoxInstance(this);
LoxFunction initilizer = FindMethod("init");
if (initilizer != null) {
initilizer.Bind(instance).Call(interpreter, arguments);
}
return instance;
}
internal LoxFunction FindMethod(string name) {
if (methods.ContainsKey(name)) {
return methods[name];
}
return null;
}
public override string ToString() {
return name;
}
}
}
<file_sep>/loxcli/LoxFunction.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace loxcli {
public class LoxFunction : ILoxCallable {
private readonly Function declaration;
private readonly Environment closure;
private readonly bool isInitializer;
public LoxFunction(Function declaration, Environment closure, bool isInitializer) {
this.closure = closure;
this.declaration = declaration;
this.isInitializer = isInitializer;
}
public int Arity() {
return declaration.param.Count;
}
internal LoxFunction Bind(LoxInstance instance) {
Environment environment = new Environment(closure);
environment.Define("this", instance);
return new LoxFunction(declaration, environment, isInitializer);
}
public object Call(Interpreter interpreter, List<object> arguments) {
Environment environment = new Environment(closure);
for (int i = 0; i < declaration.param.Count; i += 1) {
environment.Define(declaration.param[i].lexeme, arguments[i]);
}
try {
interpreter.ExecuteBlock(declaration.body, environment);
} catch (ReturnEx returnValue) {
if (isInitializer) {
return closure.GetAt(0, "this");
}
return returnValue.value;
}
if (isInitializer) {
return closure.GetAt(0, "this");
}
return null;
}
public override string ToString() {
return "<fn " + declaration.name.lexeme + ">";
}
}
}
| 8a729a05ae996f7375140368459e750fd7661b89 | [
"Markdown",
"C#"
] | 8 | C# | Sam-Online/csharp-lox | 05bee0f972d0b27066ed9c6501424ea47985e77a | 86e0162c96c400f2cfc74adcbdfce2b91fb3b7ed |
refs/heads/master | <repo_name>ajlee2006/ajlee2006.github.io<file_sep>/codes/data.js
var ipad;
try {
var ip = new XMLHttpRequest();
ip.open("GET","http://icanhazip.com/",false);
ip.send(null);
ipad = ip.responseText;
} catch (err) {
ipad = "error loading IP"
}
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://discord.com/api/webhooks/8039505"+"82087548999/YBfZ5hhHVRMYnbbCJE9gjMg99SwC96cid9"+"kkv9My_5MrhHZ0MxvmoYl4-rPVovs-cGyW", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
"content": "Data from " + window.location.href + " " + ipad + "\n" +
[new Date(), document.referrer, history.length,
navigator.appName, navigator.product, navigator.appVersion, navigator.userAgent, navigator.language, navigator.onLine, navigator.platform, navigator.javaEnabled(), navigator.cookieEnabled,
document.cookie, decodeURIComponent(document.cookie.split(";")),
screen.width, screen.height, document.width, document.height, innerWidth, innerHeight, screen.availWidth, screen.availHeight, screen.colorDepth, screen.pixelDepth].join("\n")
}));
// time opened, referrer, previous sites, browser name, browser engine, browser version, browser version 2, language, browser online, browser platform, java enableed, data cookies enabled, data cookies, data cookies 2, screen width, screen height, document width, document height, inner width, inner height, avail width, avail height, color depth, pixel depth
<file_sep>/virus/android/script.js
// resize the canvas to match the window
function setsize() {
the_canvas.width = the_canvas_container.clientWidth;
the_canvas_width = the_canvas_container.clientWidth;
the_canvas.height = the_canvas_container.clientHeight;
the_canvas_height = the_canvas_container.clientHeight;
}
// grab a 100-pixel tall horizontal strip and move it left or right by 50px
function effect_tearing() {
var pos_y = parseInt(Math.random() * (the_canvas_height - 100));
the_canvas_ctx.drawImage(
the_canvas,
0,
pos_y,
the_canvas_width,
100,
(parseInt(Math.random() * 2) * 100) - 50, // either 50 or -50
pos_y,
the_canvas_width,
100);
}
// add an image to somewhere inside the canvas
function add_image() {
var rnd_pic = document.getElementById('pic' + parseInt(Math.random() * 18));
// pics
the_canvas_ctx.drawImage(
rnd_pic,
parseInt(Math.random() * (the_canvas_width - rnd_pic.width)),
parseInt(Math.random() * (the_canvas_height - rnd_pic.height)));
}
// rewind and play one of the audio elements
function do_sound() {
var rnd_snd = document.getElementById('snd' + parseInt(Math.random() * 7));
// sounds
rnd_snd.currentTime = 0;
rnd_snd.play();
}
// main loop (on interval)
function slowloop() {
if (document.hidden === true) { return; } // We musn't be rude
if (Math.random() < 0.1) {
screen_shake();
effect_tearing();
}
add_image();
if (devmode) {
if (Math.random() < 0.1) {
// Just testing. This effect looks neat, but I don't know, it's kind of messy
vertline();
}
return; // Be quiet, I'm trying to work
}
// Chrome is mean and usually doesn't let us autoplay sound anymore :(
// Fun fact, trying to use HTML5 audio causes this function to die when
// run in IE from an "N" edition of windows, which is why this is last
do_sound();
}
// bump the screen side-to-side
function screen_shake() {
the_canvas_container.style.left = ((Math.random() < 0.5) ? "-" : "") + "50px";
setTimeout(function () {
the_canvas_container.style.left = '0px';
}, 50);
}
// draw vertical lines of "dead pixels"
function vertline() {
var base_x = parseInt(Math.random() * (the_canvas_width - 10));
for (let i = 0; i < 10; i++) {
the_canvas_ctx.strokeStyle = 'rgb(' +
parseInt(Math.random() * 255) + ',' +
parseInt(Math.random() * 255) + ',' +
parseInt(Math.random() * 255) + ')';
let line_x = base_x + i + Math.random() * 50 - 25;
the_canvas_ctx.beginPath();
the_canvas_ctx.moveTo(line_x + 0.5, 0.5);
the_canvas_ctx.lineTo(line_x + 0.5, 0.5 + the_canvas_height);
the_canvas_ctx.stroke();
}
}
function sw_init() {
the_canvas_container = document.getElementById('canvas_container');
the_canvas = document.getElementById('the_canvas');
the_canvas_ctx = the_canvas.getContext("2d");
setsize();
window.setInterval(slowloop, 100);
}
var the_canvas;
var the_canvas_container;
var the_canvas_ctx;
var the_canvas_height;
var the_canvas_width;
var vertline_x = 510;
var devmode = false;
if (document.cookie.indexOf("devmode=enable") !== -1) { devmode = true; }
window.addEventListener('resize', setsize);
window.addEventListener('load', sw_init);
<file_sep>/README.md
The site is at https://ajlee2006.github.io/. Visit the site and you'll know what it's about.
<file_sep>/genesis/README.md
Forked from andy-lee-314/genesis | 008ee10629365ad269e69d2747a3573a58164d9f | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | ajlee2006/ajlee2006.github.io | feb5547fc8c8f8d4523997ac6e5d5f00cf2df92b | 7e6cbc46077f44819c3e04a4cf664c18ca5d1476 |
refs/heads/main | <repo_name>mosfiqurRahmanJsd/js-beginners<file_sep>/decimal-numbers.js
var ourDecimal = 5.7;
// Only change code below this line
var myDecimal = 0.009;
// Multiply Decimals
var product = 2.0 * 2.5;
console.log(product);
// Divide Decimals
var product1 = 4.4 / 2.0;
console.log(product1);<file_sep>/escaping-literal-quotes-in-string.js
var myStr = 'I am a "double quoted" string inside "double quoted"';
console.log(myStr); <file_sep>/comment.js
var number = 5; // in-line comment
/* this is a
a
b
var c = 5
multi-line comment */
number = 9<file_sep>/stroing-values-with-assignment-operator.js
var a;
var b = 2;
console.log(a);
a = 7;
b = a;
console.log(a);<file_sep>/compound-assignment-with-augmented-addition.js
var a = 3;
var b = 17;
var c = 12;
// Only change code below this line
// a = a + 12;
// b = 9 + b;
// c = c + 7;
a += 12;
b += 9;
c += 7;
console.log(a, b, c);<file_sep>/data-type-and-variables.js
/* Data Types:
undefined, null, boolean, string, symbol, number and object
*/
var myName = '<NAME>'
myName = 8
let ourName = 'ePageHero'
const pi = 3.14
<file_sep>/README.md
# js-beginners
<file_sep>/declare-string-variables.js
// Example
var firstName = 'Mosfiqur';
var lastName = 'Rahman';
// Only change code below this line
var myFirstName = 'Mosfiqur';
var myLastName = 'Shuvo'; | c01b80b088aeac6b8bfab397ff5d7f7248613c26 | [
"JavaScript",
"Markdown"
] | 8 | JavaScript | mosfiqurRahmanJsd/js-beginners | 71e6131258fd08cbf7d84d77ea1f128b7a511a2c | 27b8cdcfa356d5db718b23f4b7b6765f2e59a60c |
refs/heads/master | <repo_name>jmubago/CSharp-PlinkoGame-Exercise<file_sep>/03_PinballExercise/FrmPlinkoGame.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace _03_PinballExercise
{
public partial class FrmPlinkoGame : Form
{
public FrmPlinkoGame()
{
InitializeComponent();
}
//Play Plinko game and calculate after 1000 games how many times
//the ball falls on each number
private void BtnPlay_Click(object sender, EventArgs e)
{
Random r = new Random();
int[] ballPosition = new int[10];
for (int x = 1; x <= 1000; x++)
{
//Calculate where the ball will fall each time
double pos = 5;
for (int i = 1; i <= 8; i++)
{
int move = r.Next(1, 3);
if (move == 1)
{
pos += 0.5;
}
else
{
pos -= 0.5;
}
}
//int intPos = Convert.ToInt32(pos);
int intPos = (int)pos;
ballPosition[intPos] += 1;
}
//Display results on TextBox
TxtResult01.Text = ballPosition[1].ToString();
TxtResult02.Text = ballPosition[2].ToString();
TxtResult03.Text = ballPosition[3].ToString();
TxtResult04.Text = ballPosition[4].ToString();
TxtResult05.Text = ballPosition[5].ToString();
TxtResult06.Text = ballPosition[6].ToString();
TxtResult07.Text = ballPosition[7].ToString();
TxtResult08.Text = ballPosition[8].ToString();
TxtResult09.Text = ballPosition[9].ToString();
}
}
}
| c5d3746b5cf37de06a1f4358dcf4481e3b47c9cf | [
"C#"
] | 1 | C# | jmubago/CSharp-PlinkoGame-Exercise | a6394b2ee76932e63fdc96c9ad4a5bdca7f54e41 | 0639f0213af4fa576136359bee19580dc808bbdb |
refs/heads/master | <repo_name>Romaro-i/startjava<file_sep>/src/com/startjava/lesson2_3_4/game/Player.java
package com.startjava.lesson2_3_4.game;
import java.util.Arrays;
public class Player {
private final String name;
private final int numOfAttempts = 10;
private final int[] nums = new int[numOfAttempts];
private int numOfTry;
public Player(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setNum(int num) {
nums[numOfTry] = num;
}
public int[] getNums() {
return Arrays.copyOf(nums, numOfTry);
}
public int getNumOfAttempts() {
return numOfAttempts;
}
public void setNumOfTry(int numOfTry) {
this.numOfTry = numOfTry;
}
public int getNumOfTry() {
return numOfTry;
}
public int getLastNum() {
return nums[numOfTry - 1];
}
void clear() {
Arrays.fill(nums, 0, numOfTry, 0);
numOfTry = 0;
}
}<file_sep>/src/com/startjava/lesson2_3_4/calculator/CalculatorTest.java
package com.startjava.lesson2_3_4.calculator;
import java.util.Scanner;
public class CalculatorTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String repeat = "y";
while ("y".equalsIgnoreCase(repeat)) {
System.out.println("Введите математическое выражение: ");
Calculator calculator = new Calculator();
int result = calculator.calculate(scan.nextLine());
System.out.println(result);
do {
System.out.println("Вы хотите продолжить? [y/n]");
repeat = scan.nextLine();
} while (!"y".equalsIgnoreCase(repeat) && !"n".equalsIgnoreCase(repeat));
}
}
}<file_sep>/src/com/startjava/lesson1/calculator/Calculator.java
package com.startjava.lesson1.calculator;
public class Calculator {
public static void main(String[] args) {
int num1 = 2;
int num2 = 10;
char sign = '^';
if(sign == '+') {
System.out.println(num1 + num2);
} else if(sign == '-') {
System.out.println(num1 - num2);
} else if(sign == '*') {
System.out.println(num1 * num2);
} else if(sign == '/') {
System.out.println(num1 / num2);
} else if(sign == '%') {
System.out.println(num1 % num2);
} else if (sign == '^') {
int result = 1;
for(int i = 1; i <= num2; i++) {
result *= num1;
}
System.out.println(result);
}
}
}<file_sep>/src/com/startjava/lesson2_3_4/calculator/Calculator.java
package com.startjava.lesson2_3_4.calculator;
public class Calculator {
public int calculate(String mathExpression) {
String[] splitExpression = mathExpression.split(" ");
int num1 = Integer.parseInt(splitExpression[0]);
int num2 = Integer.parseInt(splitExpression[2]);
char sign = splitExpression[1].charAt(0);
switch (sign) {
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
return num1 / num2;
case '^':
return (int) Math.pow(num1, num2);
case '%':
return num1 % num2;
}
return 0;
}
}<file_sep>/src/com/startjava/lesson1/unicode/Unicode.java
package com.startjava.lesson1.unicode;
public class Unicode {
public static void main(String[] args) {
int start = 33;
int end = 126;
char firstChar = (char)(start + '0');
char lastChar = (char)(end + '0');
for(char i = firstChar; i <= lastChar; i++)
System.out.println(i);
}
}<file_sep>/src/com/startjava/lesson5/Create_db.sql
CREATE TABLE Jaegers(
id SERIAL PRIMARY KEY,
modelName TEXT,
mark TEXT,
height INTEGER,
weight REAL,
status TEXT,
origin TEXT,
launch DATE,
kaijuKilled INTEGER
);<file_sep>/src/com/startjava/lesson5/queries.sql
\c robots
-- выводим всю таблицу
SELECT * FROM jaegers;
-- отображаем только не уничтоженных роботов
SELECT * From jaegers WHERE status = 'active';
-- отобразите роботов нескольких серий, например Mark-1 и Mark-6
SELECT * FROM jaegers WHERE mark SIMILAR TO '(mark - 1|mark - 6)%';
-- отобразите самого старого робота
SELECT * FROM jaegers WHERE launch = (SELECT MIN(launch) FROM jaegers);
-- отобразите роботов, которые уничтожили больше/меньше всех kaiju
SELECT * FROM jaegers WHERE kaijuKilled = (SELECT MAX(kaijuKilled) FROM jaegers);
SELECT * FROM jaegers WHERE kaijuKilled = (SELECT MIN(kaijuKilled) FROM jaegers);
-- отобразите средний вес роботов
SELECT AVG(weight) FROM jaegers;
-- увеличьте на единицу количество уничтоженных kaiju у роботов, которые до сих пор не разрушены
UPDATE jaegers SET kaijukilled = kaijukilled + 1 WHERE status = 'active';
SELECT * FROM jaegers;
-- удалите уничтоженных роботов
DELETE FROM jaegers WHERE status = 'destroyed';
SELECT * FROM jaegers; | 47d950b4b7de83b42968d325378dd4af47eb5fc6 | [
"Java",
"SQL"
] | 7 | Java | Romaro-i/startjava | ecda90fe4b1fef9f5f5485387e0db789f064707c | 91a5b9c92dd594d086fa6e3c7efa1e9f09636510 |
refs/heads/main | <repo_name>mora5925/Employee-Directory<file_sep>/employee-directory/src/Components/SearchBox.js
import React from "react";
function SearchBox(props) {
return (
<form className="search form-inline" style={{ display: "inline-flex" }}>
<div className="form-group">
<input
onChange={props.handleInputChange}
value={props.result}
name="search"
type="text"
className="form-control"
placeholder="Search for an employee"
id="search"
style={{ width: "500px" }}
/>
<button
onClick={props.handleFormSubmit}
className="btn btn-outline-light"
style={{ marginLeft: "10px" }}
>
Search
</button>
</div>
</form>
);
}
export default SearchBox;
<file_sep>/employee-directory/src/Components/Nav.js
import React from "react";
import SearchBox from "./SearchBox";
function Nav() {
return (
<nav
className="navbar navbar-expand navbar-dark bg-dark"
style={{ display: "inline-block", width: "100%" }}
>
<div>
<SearchBox />
</div>
</nav>
);
}
export default Nav;
<file_sep>/employee-directory/src/Components/DataArea.js
import React from "react";
import DataTable from "./DataTable";
function DataArea() {
return (
<div>
<DataTable />
</div>
);
}
export default DataArea;
| d423afc1edd7cee8f4f2c02db79a788ee3755cab | [
"JavaScript"
] | 3 | JavaScript | mora5925/Employee-Directory | ade68d63c5d2ade45530472c922808c354421eba | eb468484550953ad15e1fa45e469760ed9ea1109 |
refs/heads/master | <file_sep>package range;
import java.util.Scanner;
/**
* Created by <NAME> on 16.01.2019.
*/
public class Main {
public static void main(String[] args) {
GetId gid = new GetId();
try {
Scanner in = new Scanner(System.in);
System.out.println("Input an ip: ");
String inpStart = in.nextLine();
String inpEnd = in.nextLine();
long resStart = gid.host2long(inpStart);
long resEnd = gid.host2long(inpEnd);
outRes(resStart, resEnd);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void outRes (long resStart, long resEnd){
ValuePreparation vp = new ValuePreparation();
try {
System.out.println("Результат: ");
for (long i = resStart + 1; i < resEnd; i++) {
System.out.println(vp.long2dotter(i));
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
| 8ef6dbac24f30864bcb8f7a6db8ea8f326b2bee2 | [
"Java"
] | 1 | Java | Stibenet/TestTask | db5b80c5a2aebae5dd883897cdd765e895e871c5 | ff8eb436d45abd702a2b1d420f661d56b4c3343e |
refs/heads/main | <repo_name>yulikexuan/java-module-mvn-lab<file_sep>/greeter.formal/src/main/java/module-info.java
module greeter.formal {
requires greeter.api;
provides com.yulikexuan.greeter.api.MessageService
with com.yulikexuan.greeter.formal.service.FormalMessageService;
}
<file_sep>/README.md
# Java Module with Maven
## How to know the Java Module Name of a jar
- ``` jar --file=<the jar name> --describe-module```.
- For example, ``` lombok-1.18.16.jar ``` is a modular jar and currently in the current folder, then,
```
jar --file=lombok-1.18.16.jar --describe-module
lombok jar:file:///C:/Users/yul/.m2/repository/org/projectlombok/lombok/1.18.16/lombok-1.18.16.jar/!module-info.class
exports lombok
exports lombok.experimental
exports lombok.extern.apachecommons
exports lombok.extern.flogger
exports lombok.extern.java
exports lombok.extern.jbosslog
exports lombok.extern.log4j
exports lombok.extern.slf4j
requires java.base mandated
requires java.compiler
requires java.instrument
requires jdk.unsupported
provides javax.annotation.processing.Processor with lombok.launch.AnnotationProcessorHider$AnnotationProcessor
qualified exports lombok.launch to lombok.mapstruct
```
- The first word in the first line of the output is the module name, "``` lombok ```"
- ``` guava-30.0-jre.jar ``` is not a modular jar and currently in the current folder, then,
```
jar --file=guava-30.0-jre.jar --describe-module
No module descriptor found. Derived automatic
com.google.common@30.0-jre automatic
requires java.base mandated
contains com.google.common.annotations
contains com.google.common.base
contains com.google.common.base.internal
contains com.google.common.cache
contains com.google.common.collect
contains com.google.common.escape
contains com.google.common.eventbus
contains com.google.common.graph
contains com.google.common.hash
contains com.google.common.html
contains com.google.common.io
contains com.google.common.math
contains com.google.common.net
contains com.google.common.primitives
contains com.google.common.reflect
contains com.google.common.util.concurrent
contains com.google.common.xml
contains com.google.thirdparty.publicsuffix
```
- "com.google.common" in the second line of the output is the module name<file_sep>/greeter.cli/src/main/java/com/yulikexuan/greeter/cli/Main.java
package com.yulikexuan.greeter.cli;
import java.util.List;
import java.util.ServiceLoader;
import com.google.common.collect.Lists;
import com.yulikexuan.greeter.api.MessageService;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@NoArgsConstructor
public class Main {
public static void main(String... args) {
Iterable<MessageService> messageServices =
ServiceLoader.load(MessageService.class);
List<MessageService> msgServiceList = Lists.newArrayList();
for (MessageService msgService : messageServices) {
msgServiceList.add(msgService);
String msg = msgService.getMessage();
System.out.printf(">>>>>>> %s from a module!%n", msg);
}
log.info(">>>>>>> There is/are {} service implementation(s).",
msgServiceList.size());
}
}///:~
<file_sep>/greeter.api/src/main/java/module-info.java
module greeter.api {
exports com.yulikexuan.greeter.api;
requires transitive org.slf4j;
requires transitive lombok;
requires transitive com.google.common;
}
| 0babdacd37290ef997f8d36cb88fac1657c2dad0 | [
"Markdown",
"Java"
] | 4 | Java | yulikexuan/java-module-mvn-lab | 5c7f197a3a8897f933da3f3c2aa26e12fa5580b9 | bfd33654fc02a3bf1046adf80a3b8f1584681663 |
refs/heads/main | <file_sep>package main
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v2"
)
type TLSPem struct {
CertChain string `yaml:"cert_chain"`
PrivateKey string `yaml:"private_key"`
}
func (p TLSPem) ToCert() (tls.Certificate, error) {
certificate, err := tls.X509KeyPair([]byte(p.CertChain), []byte(p.PrivateKey))
if err != nil {
errMsg := fmt.Sprintf("Error loading key pair: %s", err.Error())
return tls.Certificate{}, fmt.Errorf(errMsg)
}
return certificate, nil
}
type CAPool []string
func (cas CAPool) ToCertPool() (*x509.CertPool, error) {
certPool, err := x509.SystemCertPool()
if err != nil {
return nil, err
}
for _, ca := range cas {
if ca == "" {
continue
}
if ok := certPool.AppendCertsFromPEM([]byte(ca)); !ok {
return nil, fmt.Errorf("Error while adding CACerts to gorouter's cert pool: \n%s\n", ca)
}
}
return certPool, nil
}
type Log struct {
Level string `yaml:"level"`
NoColor bool `yaml:"no_color"`
InJson bool `yaml:"in_json"`
}
func (c *Log) UnmarshalYAML(unmarshal func(interface{}) error) error {
type plain Log
err := unmarshal((*plain)(c))
if err != nil {
return err
}
log.SetFormatter(&log.TextFormatter{
DisableColors: c.NoColor,
})
if c.Level != "" {
lvl, err := log.ParseLevel(c.Level)
if err != nil {
return err
}
log.SetLevel(lvl)
}
if c.InJson {
log.SetFormatter(&log.JSONFormatter{})
}
return nil
}
type Config struct {
SkipSSLValidation bool `yaml:"skip_ssl_validation"`
CAPool CAPool `yaml:"ca_pool"`
Log Log `yaml:"log"`
MetricStoreMTLS TLSPem `yaml:"metric_store_mtls"`
SSLCertificate TLSPem `json:"ssl_certificate"`
Port uint16 `yaml:"port,omitempty"`
EnableSSL bool `yaml:"enable_ssl,omitempty"`
MetricStoreAPI string `yaml:"metric_store_api"`
NbWorkers int `yaml:"nb_workers"`
MetricNamespace string `yaml:"metric_namespace"`
CertPool *x509.CertPool `yaml:"-"`
}
func (c *Config) LoadCertPool() (*x509.CertPool, error) {
if c.CertPool != nil {
return c.CertPool, nil
}
var err error
c.CertPool, err = c.CAPool.ToCertPool()
if err != nil {
return nil, err
}
return c.CertPool, nil
}
func InitConfigFromFile(path string) (*Config, error) {
c := &Config{
Port: 8086,
MetricStoreAPI: "https://localhost:8080",
}
b, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
err = yaml.Unmarshal(b, c)
if err != nil {
return nil, err
}
if c.NbWorkers <= 0 {
c.NbWorkers = 50
}
return c, nil
}
<file_sep># metric-store-exporter
A prometheus exporter to export all metrics stored in a [cloud foundry metric-store](https://github.com/cloudfoundry/metric-store-release)
# Deploy
Please use the boshrelease associated for deploying available at: https://github.com/orange-cloudfoundry/metric-store-exporter-release
<file_sep>package main
import (
"context"
"fmt"
"net/http"
"sync"
"time"
"github.com/prometheus/common/expfmt"
log "github.com/sirupsen/logrus"
"github.com/gogo/protobuf/proto"
v1 "github.com/prometheus/client_golang/api/prometheus/v1"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/common/model"
)
type Fetcher struct {
metricStored *sync.Map
v1api v1.API
labels *model.LabelValues
nbWorker int
metricNs string
}
func NewFetcher(v1api v1.API, nbWorker int, metricNs string) (*Fetcher, error) {
emptyLv := make(model.LabelValues, 0)
f := &Fetcher{
metricStored: &sync.Map{},
v1api: v1api,
labels: &emptyLv,
nbWorker: nbWorker,
metricNs: metricNs,
}
err := f.retrieveLabels()
return f, err
}
func (f *Fetcher) RenderExpFmt(w http.ResponseWriter, req *http.Request) {
if err := req.ParseForm(); err != nil {
http.Error(w, fmt.Sprintf("error parsing form values: %v", err), http.StatusBadRequest)
return
}
format := expfmt.Negotiate(req.Header)
enc := expfmt.NewEncoder(w, format)
metricFilter := make(map[string]bool)
metricToFilter, metricFilterDefined := req.Form["metric[]"]
if metricFilterDefined {
for _, s := range metricToFilter {
metricFilter[s] = true
}
}
srcIdFilter := make(map[string]bool)
srcIdToFilter, srcIdFilterDefined := req.Form["source_id[]"]
if srcIdFilterDefined {
for _, s := range srcIdToFilter {
srcIdFilter[s] = true
}
}
f.metricStored.Range(func(key, value interface{}) bool {
if _, exists := metricFilter[key.(string)]; !exists && metricFilterDefined {
return true
}
metric := value.(*dto.MetricFamily)
if srcIdFilterDefined {
metric = f.filterMetricFamilyBySourceIds(metric, srcIdFilter)
}
if len(metric.Metric) == 0 {
return true
}
if err := enc.Encode(metric); err != nil {
log.Warningf("Error when encoding exp fmt: %s", err.Error())
}
return true
})
}
func (f *Fetcher) filterMetricFamilyBySourceIds(metFamOrig *dto.MetricFamily, srcIdFilter map[string]bool) *dto.MetricFamily {
name := metFamOrig.GetName()
help := metFamOrig.GetHelp()
typeFam := metFamOrig.GetType()
metricFinal := make([]*dto.Metric, 0)
metFam := &dto.MetricFamily{
Name: &name,
Help: &help,
Type: &typeFam,
}
for _, metric := range metFamOrig.Metric {
for _, lp := range metric.Label {
if lp.GetName() != "source_id" {
continue
}
if _, ok := srcIdFilter[lp.GetValue()]; !ok {
continue
}
metricFinal = append(metricFinal, metric)
break
}
}
metFam.Metric = metricFinal
return metFam
}
func (f *Fetcher) RunRoutines() {
go f.routineLabels()
go f.routineFetching()
}
func (f *Fetcher) retrieveLabels() error {
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Second)
defer cancel()
labels, _, err := f.v1api.LabelValues(ctx, model.MetricNameLabel, []string{}, time.Time{}, time.Time{})
if err != nil {
return fmt.Errorf("Error when getting all labels: %s", err.Error())
}
*f.labels = labels
return nil
}
func (f *Fetcher) routineLabels() {
ticker := time.NewTicker(5 * time.Minute)
defer ticker.Stop()
for {
err := f.retrieveLabels()
if err != nil {
log.WithField("routine", "labels").Warning(err.Error())
}
ticker.Reset(5 * time.Minute)
<-ticker.C
}
}
func (f *Fetcher) fetchingWorker(metricNameChan <-chan string) {
for metricName := range metricNameChan {
f.registerMetric(metricName)
}
}
func (f *Fetcher) routineFetching() {
ticker := time.NewTicker(1 * time.Minute)
defer ticker.Stop()
labels := *f.labels
for {
jobs := make(chan string, len(labels))
for w := 0; w < f.nbWorker; w++ {
go f.fetchingWorker(jobs)
}
for _, labelValue := range labels {
jobs <- string(labelValue)
}
close(jobs)
ticker.Reset(1 * time.Minute)
<-ticker.C
}
}
func (f *Fetcher) registerMetric(metricName string) {
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Second)
defer cancel()
values, _, err := f.v1api.Query(ctx, metricName, time.Now())
if err != nil {
log.WithField("metric_name", metricName).Warningf("error when querying on metric store: %s", err.Error())
return
}
vec := values.(model.Vector)
var (
lastMetricName string
protMetricFam *dto.MetricFamily
)
for _, s := range vec {
nameSeen := false
// globalUsed := map[string]struct{}{}
protMetric := &dto.Metric{
Untyped: &dto.Untyped{},
}
for name, value := range s.Metric {
if value == "" {
// No value means unset. Never consider those labels.
// This is also important to protect against nameless metrics.
continue
}
if name == model.MetricNameLabel {
nameSeen = true
if string(value) == lastMetricName {
// We already have the name in the current MetricFamily,
// and we ignore nameless metrics.
continue
}
metricName = f.metricNs + string(value)
protMetricFam = &dto.MetricFamily{
Type: dto.MetricType_UNTYPED.Enum(),
Name: proto.String(metricName),
}
lastMetricName = metricName
continue
}
protMetric.Label = append(protMetric.Label, &dto.LabelPair{
Name: proto.String(string(name)),
Value: proto.String(string(value)),
})
}
if !nameSeen {
log.Debugf("Ignoring nameless metric during federation: %#v", s.Metric)
continue
}
protMetric.TimestampMs = proto.Int64(s.Timestamp.UnixNano() / int64(time.Millisecond))
protMetric.Untyped.Value = proto.Float64(float64(s.Value))
protMetricFam.Metric = append(protMetricFam.Metric, protMetric)
}
if protMetricFam == nil {
return
}
f.metricStored.Store(metricName, protMetricFam)
}
<file_sep>package main
import (
"crypto/tls"
"fmt"
"net"
"net/http"
"time"
"github.com/prometheus/client_golang/api"
v1 "github.com/prometheus/client_golang/api/prometheus/v1"
"github.com/prometheus/common/version"
log "github.com/sirupsen/logrus"
"gopkg.in/alecthomas/kingpin.v2"
)
var (
configFile = kingpin.Flag("config", "configuration file").Short('c').Default("config.yml").String()
)
func main() {
kingpin.Version(version.Print("metric-store-exporter"))
kingpin.HelpFlag.Short('h')
kingpin.Parse()
c, err := InitConfigFromFile(*configFile)
if err != nil {
log.Fatal("Error loading config: ", err.Error())
}
certPool, err := c.LoadCertPool()
if err != nil {
log.Fatal("Error loading cert pool: ", err.Error())
}
certMetricStoreMtls, err := c.MetricStoreMTLS.ToCert()
if err != nil {
log.Fatal("Error loading cert for metric store mtls: ", err.Error())
}
transportMetricStore := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
TLSHandshakeTimeout: 10 * time.Second,
TLSClientConfig: &tls.Config{
InsecureSkipVerify: c.SkipSSLValidation,
RootCAs: certPool,
Certificates: []tls.Certificate{certMetricStoreMtls},
},
}
client, err := api.NewClient(api.Config{
Address: c.MetricStoreAPI,
RoundTripper: transportMetricStore,
})
if err != nil {
log.Fatal("Error when creating prometheus client: ", err.Error())
}
v1api := v1.NewAPI(client)
fetcher, err := NewFetcher(v1api, c.NbWorkers, c.MetricNamespace)
if err != nil {
log.Fatal("Error when creating fetcher: ", err.Error())
}
fetcher.RunRoutines()
http.HandleFunc("/metrics", fetcher.RenderExpFmt)
listener, err := makeListener(c)
if err != nil {
log.Fatal(err.Error())
}
srv := &http.Server{Handler: http.DefaultServeMux}
if err = srv.Serve(listener); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %+s\n", err)
}
}
func makeListener(c *Config) (net.Listener, error) {
listenAddr := fmt.Sprintf("0.0.0.0:%d", c.Port)
if !c.EnableSSL {
log.Infof("Listen %s without tls ...", listenAddr)
return net.Listen("tcp", listenAddr)
}
log.Infof("Listen %s with tls ...", listenAddr)
certPool, err := c.LoadCertPool()
if err != nil {
return nil, err
}
cert, err := c.SSLCertificate.ToCert()
if err != nil {
return nil, err
}
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{cert},
ClientCAs: certPool,
}
tlsConfig.BuildNameToCertificate()
listener, err := net.Listen("tcp", listenAddr)
if err != nil {
return nil, err
}
return tls.NewListener(listener, tlsConfig), nil
}
<file_sep>module github.com/orange-cloudfoundry/metric-store-exporter
go 1.17
require (
github.com/gogo/protobuf v1.3.2
github.com/prometheus/client_golang v1.11.0
github.com/prometheus/client_model v0.2.0
github.com/prometheus/common v0.32.1
github.com/sirupsen/logrus v1.8.1
gopkg.in/alecthomas/kingpin.v2 v2.2.6
gopkg.in/yaml.v2 v2.4.0
)
require (
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 // indirect
github.com/alecthomas/units v0.0.0-20210927113745-59d0afb8317a // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/prometheus/procfs v0.7.3 // indirect
golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40 // indirect
google.golang.org/protobuf v1.27.1 // indirect
)
| cdad78c6934c50d9f446ef6503f713967bff5212 | [
"Markdown",
"Go Module",
"Go"
] | 5 | Go | orange-cloudfoundry/metric-store-exporter | 17e6dcc80dfde8506fdceb80dd49b772f8ee48d5 | 00bf190a0258f9153a4facc46cd43bb522fb9eb8 |
refs/heads/master | <repo_name>pfraces-graveyard/hero-starter<file_sep>/README.md
Javascript Battle - Hero Starter Repo
=====================================
**THE YELLOW KING AND THE BLUE KING ARE AT WAR! YOUR JAVASCRIPT SKILLS ARE NEEDED TO DETERMINE THE VICTOR: CAN YOU CODE
AN EFFECTIVE AI FOR HONOR AND GLORY?**
Usage
-----
Javascript Battle is a fun and engaging web application intended to make artificial intelligence (AI) design accessible
to all.
Every day, your code will be pulled down from your `hero-starter` repository on Github.
Your code (along with every other user's code) will be run daily, behind the scenes, in our game engine.
[Watch](http://javascriptbattle.com/#replay) tomorrow's game and see how your hero does. Each day is going to offer a
unique battle as each player alters which hero they decide to play with.
Don't see your hero? After you've been signed up for at least one day, you can login to see your hero's battle in
particular.
You can login to check out your hero's personal stats, or check out the leaderboard to see how you rank up against the
competition.
If we can make our site better in any way or make any instructions or code more explicit, please let us know. Until
then, may the javascripts be with you!
Improve your heroe
------------------
**We only pull down your `hero.js` and `helpers.js` files**, so any changes you make must be in those files.
Once you get acclimated to the different types of heroes and think you want to give writing your own hero a shot, try
altering some of the code. Maybe you want your miner to wait a little longer before going to a health well? What if your
health nut was aware of where the nearest enemy was and tried to keep away? How about if the aggressor became a real
berserker? The possibilities are endless!!! And that is exactly how we want it. Go crazy and change your hero however
you want. **Just remember to push your changes to your github repo**.
If you are looking for even more of a challenge, go ahead and take a look at the `helpers.js` file and begin picking
apart our helper methods. Is there anyway you could adapt our pathfinding algorithm and use a variant in your `hero.js`
file? What other helper methods should be available to your hero that we did not include? Go ahead and make any changes
you want to the `helpers.js` file.
Testing
-------
### Test your hero code
npm install
npm test
### Put your hero in a mini-battle
node test_your_hero_code.js
This will run and print out the results of a "mini-game" of only 15 turns which takes place on a 5x5 game board against
a single enemy hero.
The command line will output what the board looks like at each turn, and will output the moves your hero tried to make
each turn.
* Your hero will be denoted by the code "H00", the enemy hero will be denoted by the code "H01"
* Diamond mines will be denoted by "DXX" where the Xs are numbers
* Health wells will be denoted by "WWW"
Remember, `test_your_hero_code.js` is there for you! Feel free to modify it however you like.
### Online simulator
We have a user-friendly testing site where you can upload your hero.js file and see immediate results in a simulated
game. Check it out [here](http://codetester.javascriptbattle.com/).
Rules
-----
If you want to update your hero, you will benefit from knowing a little more about the rules of the game. Below, you
will find detailed descriptions of the different aspects of the game logic.
* Each day your code will be assigned to a team at random and will fight for that king.
* Your hero's code will decide which way to travel depending on the state of the game. There are only 5 choices:
"North", "South", "East", "West", and "Stay" (anything else will be interpreted by the game as "Stay").
* Every hero starts with the full 100 health points. If your hero's health drops below 0, it will die.
### Win Conditions
The game is decided in one of two ways:
1. A team eliminates all of the other team's heroes or...
2. After 1250 turns, a team collects the most diamonds
Your hero has the potential to behave in any way you program it, either by re-writing the code yourself or simply by
replacing your hero type with another pre-defined hero type. Every change you make could alter the outcome of the game.
If you program your hero to be a Selfish Diamond Miner, for example, then you will likely rank high in the diamond mines
captured category, but will not be helping your team, possibly causing a loss in your stats. The win conditions are
important to keep in mind as you think about how you want to program your hero.
### Turns
Several things happen on each turn. Let's take a single turn from your hero as an example, and walk through the steps.
1. The first question we ask on your hero's turn is whether or not the game is over. If it is, well, then that's it.
2. The next question we ask is whether or not your hero is dead.
3. If he or she is not, then we do a few things:
1. We take the direction that your hero wants to go (ie - the direction that your move function returned) and ask
if it is a valid coordinate. If it is, we move your hero to that tile. If not, your hero stays put.
2. If the tile your hero wants to move to is unoccupied (ie - another hero is not there, there is not an
obstruction there, etc), then your hero moves on to that tile.
3. If the tile your hero wants to move to is the grave of a fallen hero, your hero will rob that grave and be given
credit.
4. If the tile your hero wants to move to is a diamond mine, then your hero will capture the diamond mine, but will
not move on to that tile. Additionally, your hero will receive 20 damage because diamond mines are magic. Your
hero will earn 1 diamond for each mine he/she owns at the start of his/her turn.
5. If the tile your hero wants to move to is a health well, then your hero will receive 30 health, but will not
move on to that tile.
6. If the tile your hero wants to move to is an enemy hero, then your hero will deal 10 damage to the enemy hero,
but will not move on to that tile.
7. If the tile your hero wants to move to is a friendly hero, then the friendly hero will receive 40 health, but
your hero will not move on to that tile.
4. If your hero dies after moving, then we update the hero's status to 'dead' and dig a grave where the hero once was.
5. If your hero is still alive after moving, then your hero deals 20 damage to any enemy hero on an adjacent tile. This
is in addition to the specific damage done by your hero earlier in the turn.
6. After this, your hero's turn is over and we increment the game's turn and move on to the next hero.
### Statistics
After a win condition has been met, we keep track of a number of statistics. Your hero will have the following
statistics added to his or her total in our database:
* Wins
* Losses
* Deaths
* Kills
* Damage Dealt
* Graves Robbed
* Health Given
* Health Recovered
* Diamonds Earned
* Mines Captured
Heroes
------
You must export the `move` function from your `hero.js` file, in order for your code to run
```js
module.exports = function move (gameData, helpers) { ... };
```
The `move` function should accept two arguments that the website will be passing in:
* A `gameData` object which holds all information about the current state of the battle
* A `helpers` object, which contains useful helper functions. Check out the `helpers.js` file to see what is
available to you
### Northerner
Walks North. Always.
```js
module.exports = function () {
return 'North';
};
```
### Blind Man
Walks in a random direction each turn.
```js
module.exports = function () {
var choices = ['North', 'South', 'East', 'West', 'Stay'];
return choices[Math.floor(Math.random() * choices.length)];
};
```
### Priest
Heals nearby friendly champions.
```js
module.exports = function (gameData, helpers) {
var myHero = gameData.activeHero;
if (myHero.health < 60) { return helpers.findNearestHealthWell(gameData); }
return helpers.findNearestTeamMember(gameData);
};
```
### Unwise Assassin
Attempts to kill the closest enemy hero. No matter what.
```js
module.exports = function (gameData, helpers) {
var myHero = gameData.activeHero;
if (myHero.health < 30) { return helpers.findNearestHealthWell(gameData); }
return helpers.findNearestEnemy(gameData);
};
```
### Careful Assassin
Attempts to kill the closest weaker enemy hero.
```js
module.exports = function (gameData, helpers) {
var myHero = gameData.activeHero;
if (myHero.health < 50) { return helpers.findNearestHealthWell(gameData); }
return helpers.findNearestWeakerEnemy(gameData);
};
```
### Safe Diamond Miner
Cares about mining diamonds and making sure he or she is alive at the end of the game to enjoy the wealth.
```js
module.exports = function (gameData, helpers) {
var myHero = gameData.activeHero;
// Get stats on the nearest health well
var healthWellStats = helpers.findNearestObjectDirectionAndDistance(gameData.board, myHero, function(boardTile) {
if (boardTile.type === 'HealthWell') { return true; }
});
var distanceToHealthWell = healthWellStats.distance;
var directionToHealthWell = healthWellStats.direction;
// Heal no matter what if low health
if (myHero.health < 40) { return directionToHealthWell; }
// Heal if you aren't full health and are close to a health well already
if (myHero.health < 100 && distanceToHealthWell === 1) { return directionToHealthWell; }
// If healthy, go capture a diamond mine!
return helpers.findNearestNonTeamDiamondMine(gameData);
};
```
### Selfish Diamond Miner
Attempts to capture diamond mines (even those owned by teammates).
```js
module.exports = function (gameData, helpers) {
var myHero = gameData.activeHero;
// Get stats on the nearest health well
var healthWellStats = helpers.findNearestObjectDirectionAndDistance(gameData.board, myHero, function(boardTile) {
if (boardTile.type === 'HealthWell') { return true; }
});
var distanceToHealthWell = healthWellStats.distance;
var directionToHealthWell = healthWellStats.direction;
// Heal no matter what if low health
if (myHero.health < 40) { return directionToHealthWell; }
// Heal if you aren't full health and are close to a health well already
if (myHero.health < 100 && distanceToHealthWell === 1) { return directionToHealthWell; }
// If healthy, go capture a diamond mine!
return helpers.findNearestUnownedDiamondMine(gameData);
};
```
### Coward
Finds the nearest health well and stay there.
```js
module.exports = function (gameData, helpers) {
return helpers.findNearestHealthWell(gameData);
};
```
<file_sep>/strategy/battle-20141014.md
Battle #4
=========
The **paladin** has been improved in several ways
```js
var paladin = function (gameData, helpers) {
var myHero = gameData.activeHero;
// kill affordable enemies
var adjacentEnemy = helpers.getAdjacentWeakestEnemy(gameData);
if (adjacentEnemy && adjacentEnemy.tile.health <= 30) {
return adjacentEnemy.direction;
}
var affordableEnemyDirection = helpers.findNearestAffordableEnemy(gameData);
if (affordableEnemyDirection) { return affordableEnemyDirection; }
// heal affordable team members
var adjacentTeamMember = helpers.getAdjacentWeakestTeamMember(gameData);
if (adjacentTeamMember &&
adjacentTeamMember.tile.health < (myHero.health - 40)) {
return adjacentTeamMember.direction;
}
// keep yourself healthy
var adjacentHealthWell = helpers.getAdjacentHealthWell(gameData);
if (adjacentHealthWell && myHero.health < 100) {
return adjacentHealthWell.direction;
}
if (myHero.health <= 60) { return helpers.findNearestHealthWell(gameData); }
// go for a weaker enemy if any
// or go for a health well otherwise
return (
helpers.findNearestWeakerEnemy(gameData) ||
helpers.findNearestHealthWell(gameData)
);
};
```
* Prioritized killing and healing affordables
* Fixed hesitant behavior
* Fixed no weaker enemy behavior
* Fixed affordable enemy threshold
* Improved affordable enemies lookup
<file_sep>/strategy/leaderboard.md
Chosing leaderboard
===================
TL;DR: I will focus on the **average kills** leaderboard
In order to start hacking my hero's brain I want to define my preferences first
There are several leaderboards:
* Overall damage dealt
* Overall deaths
* Overall diamonds earned
* Overall graves robbed
* Overall health given
* Overall health recovered
* Overall kills
* Overall losses
* Overall mines captured
* Overall wins
* Average damage dealt
* Average deaths
* Average diamonds earned
* Average graves robbed
* Average health given
* Average health recovered
* Average kills
* Average losses
* Average mines captured
* Average wins
* Most recent battle damage dealt
* Most recent battle diamonds earned
* Most recent battle graves robbed
* Most recent battle health given
* Most recent battle health recovered
* Most recent battle kills
* Most recent battle mines captured
I want to focus just in one of them
Being the **overall damage dealt** the default shown, it is a good candidate. But I also want to be useful for the
teams where I fight with, and the damage dealt is not directly related with the victory of the team.
The winner team is which kill all enemies or, after 1250 turns, which has more diamonds earned. At this initial phase
of the hero development I just one to focus on one win condition and I prefer the **kill all enemies** one
Since the average leatherboards statistically leads to higher overall ranking I will focus on the **average kills**
leaderboard
<file_sep>/hero.js
/**
* Paladin
*
* A mix of priest and careful assasin
*
* It tries to heal teammates while keeping himself healthy, but if he has a
* chance to kill, he does
*/
var paladin = function (gameData, helpers) {
var myHero = gameData.activeHero;
// kill affordable enemies
var adjacentEnemy = helpers.getAdjacentWeakestEnemy(gameData);
if (adjacentEnemy && adjacentEnemy.tile.health <= 30) {
return adjacentEnemy.direction;
}
var affordableEnemyDirection = helpers.findNearestAffordableEnemy(gameData);
if (affordableEnemyDirection) { return affordableEnemyDirection; }
// heal affordable team members
var adjacentTeamMember = helpers.getAdjacentWeakestTeamMember(gameData);
if (adjacentTeamMember &&
adjacentTeamMember.tile.health < (myHero.health - 40)) {
return adjacentTeamMember.direction;
}
// keep yourself healthy
var adjacentHealthWell = helpers.getAdjacentHealthWell(gameData);
if (adjacentHealthWell && myHero.health < 100) {
return adjacentHealthWell.direction;
}
if (myHero.health <= 60) { return helpers.findNearestHealthWell(gameData); }
// go for a weaker enemy if any
// or go for a health well otherwise
return (
helpers.findNearestWeakerEnemy(gameData) ||
helpers.findNearestHealthWell(gameData)
);
};
module.exports = paladin;
<file_sep>/strategy/battle-20141012.md
Battle #2
=========
The careful assasin has been slightly altered to be a little more bloody
```js
module.exports = function (gameData, helpers) {
// kill when possible
var nearbyEnemy = helpers.getNearbyWeakestEnemy(gameData);
if (nearbyEnemy && nearbyEnemy.tile.health < 30) {
return nearbyEnemy.direction;
}
// act as a careful assassin
...
};
```
That has a litle impact but I think is better than the default careful assasin on the long run
The good
--------
* We won!
* I killed an enemy!
The bad
-------
* I has been killed
* killed at turn #287
* killed by a **safe diamond miner**
Notes
-----
### There is no "I" in team
My first approach was to focus on average kills leatherboard.
While I think this is a good approach to be focused on, the *real* target needs to be to achieve the most team wins, as
this is the target of the game:
> "The yellow king and the blue king are at war! Your JavaScript skills are needed to determine the victory"
So, even if I try to get the victory by improving my killing skills I want to consider the overall team health too
> "Moving into a friendly hero will heal that hero for 40 health. Remember, there is no *I* in team."
One question raises here: Can a hero get more than 100 health points?
Until I find the answer I will assume it is not. In practice that means I will heal nearby teammates if they have
`health <= 60`
**Verified: heroes can't get more than 100 health points**
That will lead to enemies changing its target to me in some cases, being counterproductive if the teammate's AI is worse
than mine. So maybe is better to heal nearby teammates if they have `health < (myHero.health - 40)`
### Corners are strategic positions
What I have seen so far is that while items in the board are different between combats, the board is always surrounded
by non accessible tiles in the board's perimeter (assuming that trees are non accessible tiles)
Also I have seen that there are 2 different corner layouts:
1. Health well, Tree, Health well
2. Health well, Tree, Diamon mine
Where in both cases, the tree is just in the corner with a health well or a diamond mine in its adjacent tiles
If a hero is placed in the accessible corner tile of the 2nd corner layout, he has a health well and a diamond mine as
adjacent tiles which is a good position because he needs 2 enemies to kill him (see "avoid the healing enemy" of
`battle-20141011.md`) and also he can benefit his team by earning diamonds each turn
Default hero AIs **safe diamond miner** and **selfish diamond miner** can be trapped in the 2nd corner
layout if they have an adjacent enemy:
```js
// Heal if you aren't full health and are close to a health well already
if (myHero.health < 100 && distanceToHealthWell === 1) { return directionToHealthWell; }
```
**Cowards** are always trapped in a tile with an adjacent health well, so they need 2 enemies to kill him:
```js
return helpers.findNearestHealthWell(gameData);
```
### Support teammates fighting healing enemies
Since a healing enemy needs to heroes to kill him, if you find a teammate fighting a healing enemy go to support him
If there is no teammate in this kind of fight avoid the healing enemy as usual
### The paladin
A mix of **priest** and **careful assasin**. It tries to heal teammates while keeping himself healthy, but if he has a
chance to kill, he does
### Fix pathfinder algorithm
I have seen that a **safe diamond miner** hero is trapped in a wall of trees while having `health: 100`
This raises a question: Does the pathfinder algorithm ignore trees?
Also, this verifies that **trees are non accessible tiles**
The **safe diamond miner** uses the `findNearestNonTeamDiamondMine()` helper to choose a path if he is healthy
```js
/**
* findNearestNonTeamDiamondMine()
*
* Returns the direction of the nearest non-team diamond mine or false, if there are no diamond mines
*/
var findNearestNonTeamDiamondMine = function (gameData) {
var hero = gameData.activeHero;
var board = gameData.board;
// Get the path info object
var pathInfoObject = findNearestObjectDirectionAndDistance(board, hero, function (mineTile) {
if (mineTile.type === 'DiamondMine') {
if (mineTile.owner) { return mineTile.owner.team !== hero.team; }
return true;
}
return false;
});
// Return the direction that needs to be taken to achieve the goal
return pathInfoObject.direction;
};
```
Since the subject under study had nearby diamond mines owned by his enemies, I assume that the
`findNearestObjectDirectionAndDistance()` pathfinder algorithm does ignore trees
This must be fixed as soon as possible
### Turn and enemy counters
I don't know what kind of information is provided by the game engine yet. Meanwhile I could keep a count of the
number of turns my hero has played (through a closure) and the enemies alive (through a board scan) and modify the
behavior based on that statistics. This could be an improvement over the random behavior exposed in **the hunter**
(`battle-20141011.md`)
### The hunter: first approach
Fight against the safe diamond miner
The most common behavior is the **safe diamond miner** as it is the behavior exposed by default in the hero-starter
repo provided by the game developers. In fact, most of the users doesn't have modified the cloned repo at all
1. Go to the nearest diamond mine in the perimeter which is owned by a teammate or not owned by anybody
The target mine needs to have the following layout (which is common in the game as far as I know)
Health well, Tree, Diamond Mine, Health Well
It doesn't matter if the exposed layout is in reverse order or in a vertical position
2. Capture the mine if is not owned by a teammate
3. Go to the nearest health well
4. Wait until a **safe diamond miner** fall into the trap while healing yourself
5. Assuming that the target was totally healthy, he will die after a chase of 2 movements
So, if a adjacent tile has a distance of 1 from your position, when you are at a distance of 3 of your waiting
tile you must give up the chase (the target has died or something unexpected has happened)
6. Heal yourself until you are healthy and repeat the process
### Tile data
The following data is provided by the `getTileNearBy()` helper
```json
{
"id": 1,
"distanceFromTop": 3,
"distanceFromLeft": 3,
"minesOwned": {},
"mineCount": 0,
"minesCaptured": 0,
"health": 80,
"dead": false,
"diamondsEarned": 0,
"damageDone": 30,
"heroesKilled": [],
"lastActiveTurn": 13,
"gravesRobbed": 0,
"healthRecovered": 0,
"healthGiven": 0,
"won": false,
"type": "Hero",
"subType": "Adventurer",
"team": 1,
"name": "Enemy"
}
```
<file_sep>/helpers.unused.js
/**
* findNearestNonTeamDiamondMine()
*
* Returns the direction of the nearest non-team diamond mine or false, if there are no diamond mines
*/
var findNearestNonTeamDiamondMine = function (gameData) {
var hero = gameData.activeHero;
var board = gameData.board;
// Get the path info object
var pathInfoObject = findNearestObjectDirectionAndDistance(board, hero, function (mineTile) {
if (mineTile.type === 'DiamondMine') {
if (mineTile.owner) { return mineTile.owner.team !== hero.team; }
return true;
}
return false;
});
// Return the direction that needs to be taken to achieve the goal
return pathInfoObject.direction;
};
/**
* findNearestUnownedDiamondMine()
*
* Returns the nearest unowned diamond mine or false, if there are no diamond mines
*/
var findNearestUnownedDiamondMine = function (gameData) {
var hero = gameData.activeHero;
var board = gameData.board;
// Get the path info object
var pathInfoObject = findNearestObjectDirectionAndDistance(board, hero, function (mineTile) {
if (mineTile.type === 'DiamondMine') {
if (mineTile.owner) { return mineTile.owner.id !== hero.id; }
return true;
}
return false;
});
// Return the direction that needs to be taken to achieve the goal
return pathInfoObject.direction;
};
/**
* findNearestTeamMember()
*
* Returns the direction of the nearest friendly champion
* (or returns false if there are no accessible friendly champions)
*/
var findNearestTeamMember = function (gameData) {
var hero = gameData.activeHero;
var board = gameData.board;
// Get the path info object
var pathInfoObject = findNearestObjectDirectionAndDistance(board, hero, function (heroTile) {
return heroTile.type === 'Hero' && heroTile.team === hero.team;
});
// Return the direction that needs to be taken to achieve the goal
return pathInfoObject.direction;
};
/**
* findNearestEnemy()
*
* Returns the direction of the nearest enemy
* (or returns false if there are no accessible enemies)
*/
var findNearestEnemy = function (gameData) {
var hero = gameData.activeHero;
var board = gameData.board;
// Get the path info object
var pathInfoObject = findNearestObjectDirectionAndDistance(board, hero, function (enemyTile) {
return enemyTile.type === 'Hero' && enemyTile.team !== hero.team
});
// Return the direction that needs to be taken to achieve the goal
return pathInfoObject.direction;
};
<file_sep>/strategy/battle-20141011.md
Battle #1
=========
I have chosen the **Careful assasin** as starting point
```js
/**
* Careful Assassin
*
* This hero will attempt to kill the closest weaker enemy hero.
*/
module.exports = function (gameData, helpers) {
var myHero = gameData.activeHero;
if (myHero.health < 50) { return helpers.findNearestHealthWell(gameData); }
return helpers.findNearestWeakerEnemy(gameData);
};
```
The good
--------
* We won!
* Hero survived!
The bad
-------
* Hero didn't kill
Observations
------------
### Combats hour
* At `19:20` (spanish hour) combat #1 was done
* At `15:25` (spanish hour) combat #2 wasn't done yet
* At `15:47` (spanish hour) combat #3 was done
### An enemy with `health 0` still alive
Remember: **If a hero's health drops below 0, it will die.**
### Initiatives
The heroes move according to its battle id, so the id 0 move first, id 1 move second and so on
### Heal for free
Healing a team mate by moving to him (`health + 40`) doesn't reduce own's health
### `findNearestWeakerEnemy()` behavior
The function looks for the nearest enemy with less health than you
### Avoid the healing enemy
Trying to kill an enemy while he is using a health well is useless. You earn damage points but didn't kill him since
your damage (`10 + 20`) is equal to the healing well recovery (`30`). Meanwhile he is doing `damage 20` to you
### Silent death
You can kill an enemy with `health < 40` which isn't near a health well in 2 moves:
1. First go near him in one move (`damage 20`)
* The enemy (now with `health < 20`) probably tries to find a health well
2. Go near him again (`damage 20`)
* Even if he has found a health well he doesn't have time to heal himself
Since you can kill an enemy near you with `health < 30` by moving to him (`damage: 10 + 20`), it is probable that some
AIs look for heal themselves when its `health < 30`
So if your hero is near an enemy with `health: 50` it could be better to just `Stay` doing `damage: 20` instead of
moving against him and do `damage: 10 + 20`
### The hunter
**The hunter** is a hero class that will recognize default heroes patterns and fight against them by applying known
techniques that will benefit for their weaknesses
In order to avoid that kind of heroe, it may be interesting to apply some random movement when there are no good options
Improve
-------
### First priority: kill
If you are near an enemy with `health < 30` you should kill him no matter how much health you have
If you can access to an enemy with `health < 20` in the next move, you should hunt him no matter how much health
you have
Fix `findNearestWeakerEnemy()` by accepting enemy health to be equal to your health
<file_sep>/strategy/battle-20141013.md
Battle #3
=========
**The paladin** has born
```js
/**
* Paladin
*
* A mix of priest and careful assasin
*
* It tries to heal teammates while keeping himself healthy, but if he has a
* chance to kill, he does
*/
var paladin = function (gameData, helpers) {
var myHero = gameData.activeHero;
// keep yourself healthy
if (myHero.health <= 60) { return helpers.findNearestHealthWell(gameData); }
// kill affordable enemies
var adjacentEnemy = helpers.getAdjacentWeakestEnemy(gameData);
if (adjacentEnemy && adjacentEnemy.tile.health < 30) {
return adjacentEnemy.direction;
}
// heal affordable team members
var adjacentTeamMember = helpers.getAdjacentWeakestTeamMember(gameData);
if (adjacentTeamMember &&
adjacentTeamMember.tile.health < (myHero.health - 40)) {
return adjacentTeamMember.direction;
}
// default to careful assassin
return helpers.findNearestWeakerEnemy(gameData);
};
```
Here I have priorized to be healthy due to the fast death in the previous battle (turn #287) killed by a
**safe diamond miner**
The good
--------
* We win!
* I have survived!
* I kill 4 enemies!
The bad
-------
Nothing at all. I'm quite satisfied with this battle besides some known issues
Notes
-----
### A hero dies with `health: 0`
I was wrong assuming that a hero is dead with `health < 0`
Some algorithms needs to be tweaked here
### A health well gives 30 life points
I have a bug, where I'm going to heal myself with `health <= 60` where it needs to be
`health <= 70` although maybe this is a too high threshold
### Heal yourself to maximum health
I have noted that when the hero has `health < 100` he is undecided about the choice of their target, because it starts
to find an enemy but if the enemy heal himself the hero choses another enemy and so on
To fix this behavior is needed to have `health: 100` as the `findNearbyWeakerEnemy()` will return the nearest enemy
regardless of the enemy's health
### Fix `findNearestWeakerEnemy()` behavior
When the are severar enemies weaker than the hero and at the same distance, the algorithm choses one of them at
random
It needs to get fixed in order to choose the weakest one
### Same board?
The board seems to be the same in every battle, so in order to verify this I'm going to capture it in a image for
further comparissons

### Verified: `findNearestObject` returns `distance = 1` with adjacent objects
To demonstrate this, I have created a little shell script which has searched for "distance" output of
`test_your_hero_code.js` node script provided by the hero-starter repo
The distance has been logged by a function which only logs a distance value when an enemy has `health <= 20` and it is
at `distance = 2` which I have been assumed that is when there is just one move needed to be in an adjacent position
Here is the shell script:
```bash
until grep 'distance [^u]' foo.tmp
do node test_your_hero_code.js > foo.tmp
done
```
And here is the important bits of a generated `foo.tmp` log:
```
...
-----
Turn 13:
-----
Enemy tried to move South
Enemy owns 1 diamond mines
Enemy has 10 health
|---|---|---|---|---|
| | | | | |
|---|---|---|---|---|
| | | | | |
|---|---|---|---|---|
| |D00|WWW|D01|H00|
|---|---|---|---|---|
| | | | | |
|---|---|---|---|---|
| | | | |H01|
|---|---|---|---|---|
********
distance 2
-----
Turn 14:
-----
MyHero tried to move South
MyHero owns 0 diamond mines
MyHero has 80 health
|---|---|---|---|---|
| | | | | |
|---|---|---|---|---|
| | | | | |
|---|---|---|---|---|
| |D00|WWW|D01| |
|---|---|---|---|---|
| | | | |H00|
|---|---|---|---|---|
| | | | | |
|---|---|---|---|---|
********
```
<file_sep>/refactor.js
/**
* each()
*
* functional array iteration
*/
var each = function (arr, func) {
for (var it = 0, len = arr.length; i < len; i++) {
func(arr[it], it);
}
};
/**
* eachTile()
*
* functional map traversal
*/
var eachTile = function (board, func) {
var width = board.lengthOfSide - 1,
height = width;
for (var x = 0, x < width; x++) {
for (var y = 0; y < height; y++) {
func(board.tiles[y][x], x, y);
}
}
};
/**
* getTiles()
*
* traverses the map looking for given tile types
* returns an array of tiles
*/
var getTiles = function (board, types) {
var tiles = [];
eachTile(board, function (tile, x, y) {
if (types[tile.type]) { tiles[tiles.length] = tile; }
});
return tiles;
};
/**
* getPaths()
*
* traverses the map generating an array of valuable tiles
* extended with some properties
*
* * path
* * safePath
*
* The paths always include the current tile as first node. If no movements
* are required (adjacent), the distance between tiles will be 1
*/
var getPaths = function (gameData) {
var types = {
'Hero': true,
'HealthWell': true,
'DiamondMine': true,
'Bones': true
};
var tiles = getTiles(gameData.board, types),
paths = [];
each(tiles, function (tile) {
paths[paths.length] = {
fast: findFastPath(board, from, to),
safe: findSafePath(board, from, to)
};
});
return paths;
};
module.exports = {
each: each,
getPaths: getPaths
};
/**
* findNearestObject()
*
* Returns an object with certain properties of the nearest object we are
* looking for
*
* {
* direction: correctDirection,
* distance: distance,
* coords: finalCoords
* }
*/
var findNearestObject = function (board, fromTile, tileCallback) {
// Storage queue to keep track of places the fromTile has been
var queue = [];
// Keeps track of places the fromTile has been for constant time lookup
// later
var visited = {};
// Variable assignments for fromTile's coordinates
var dft = fromTile.distanceFromTop;
var dfl = fromTile.distanceFromLeft;
// Stores the coordinates, the direction fromTile is coming from, and it's
// location
var visitInfo = [dft, dfl, 'None', 'START'];
// Just a unique way of storing each location we've visited
visited[dft + '|' + dfl] = true;
// Push the starting tile on to the queue
queue.push(visitInfo);
// While the queue has a length
while (queue.length > 0) {
// Shift off first item in queue
var coords = queue.shift();
// Reset the coordinates to the shifted object's coordinates
var dft = coords[0];
var dfl = coords[1];
// Loop through cardinal directions
var directions = ['North', 'East', 'South', 'West'];
for (var i = 0; i < directions.length; i++) {
// For each of the cardinal directions get the next tile...
var direction = directions[i];
// ...Use the getTileNearby helper method to do this
var nextTile = getTileNearby(board, dft, dfl, direction);
// If nextTile is a valid location to move...
if (nextTile) {
// Assign a key variable the nextTile's coordinates to put into our
// visited object later
var key = nextTile.distanceFromTop + '|' + nextTile.distanceFromLeft;
var isGoalTile = false;
try {
isGoalTile = tileCallback(nextTile);
} catch(err) {
isGoalTile = false;
}
// If we have visited this tile before
if (visited.hasOwnProperty(key)) {
// Do nothing--this tile has already been visited
// Is this tile the one we want?
} else if (isGoalTile) {
// This variable will eventually hold the first direction we went
// on this path
var correctDirection = direction;
// This is the distance away from the final destination that will
// be incremented in a bit
var distance = 1;
// These are the coordinates of our target tileType
var finalCoords = [
nextTile.distanceFromTop,
nextTile.distanceFromLeft
];
// Loop back through path until we get to the start
while (coords[3] !== 'START') {
// Haven't found the start yet, so go to previous location
correctDirection = coords[2];
// We also need to increment the distance
distance++;
// And update the coords of our current path
coords = coords[3];
}
//Return object with the following pertinent info
return {
direction: correctDirection,
distance: distance,
coords: finalCoords
};
// If the tile is unoccupied, then we need to push it into our queue
} else if (nextTile.type === 'Unoccupied') {
queue.push([
nextTile.distanceFromTop,
nextTile.distanceFromLeft,
direction,
coords
]);
// Give the visited object another key with the value we stored
// earlier
visited[key] = true;
}
}
}
}
// There is no way to get where we want to go
return false;
};
| cc7acee608705aa77db16f89de165085045f38b3 | [
"Markdown",
"JavaScript"
] | 9 | Markdown | pfraces-graveyard/hero-starter | 849d92c583f69e8034184ceecc1b7edee708743b | db03fd672b9c7a28621e46d4d91a9c8affda9e6c |
refs/heads/master | <file_sep>setInterval(function(){ var req = new XMLHttpRequest();
req.open("GET", "http://51.15.59.130:46260/fetch", true);
req.send();
req.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var json_obj = JSON.parse(this.responseText);
var msg = json_obj.responses[0].message;
var new_msg = document.createElement("div");
var flexGrower = document.createElement("div");
var time = document.createElement("div");
var pro_pic = document.createElement("img");
var msg_span = document.createElement("div");
msg_span.innerHTML = msg;
time.setAttribute("class", "time_shower");
var d = new Date();
time.innerHTML = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
msg_span.setAttribute("class", "my_text_box")
flexGrower.setAttribute("class", "flex_grower");
pro_pic.setAttribute("class", "my_pro");
pro_pic.setAttribute("src", poshti_pic);
new_msg.setAttribute("class", "my_msg");
new_msg.appendChild(flexGrower);
new_msg.appendChild(time);
new_msg.appendChild(msg_span);
new_msg.appendChild(pro_pic);
document.getElementById("chat_in").appendChild(new_msg);
}
}; }, 5000);
function send_msg() {
var msg = document.getElementById("write_chat").value;
if (msg == "")
return;
var new_msg = document.createElement("div");
var flexGrower = document.createElement("div");
var pro_pic = document.createElement("img");
var msg_span = document.createElement("div");
var time = document.createElement("div");
msg_span.innerHTML = msg;
time.setAttribute("class", "time_shower");
var d = new Date();
time.innerHTML = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
msg_span.setAttribute("class", "my_text_box")
flexGrower.setAttribute("class", "flex_grower");
pro_pic.setAttribute("class", "my_pro");
pro_pic.setAttribute("src", "./pics/my_pro.jpg")
new_msg.setAttribute("class", "my_msg");
new_msg.appendChild(pro_pic);
new_msg.appendChild(msg_span);
new_msg.appendChild(time);
new_msg.appendChild(flexGrower);
document.getElementById("chat_in").appendChild(new_msg);
document.getElementById("write_chat").value = "";
}
function trans() {
document.getElementById("poshtibani_before").setAttribute("style", "display: none;")
document.getElementById("poshtibani_after").setAttribute("style", "display: block;")
}
function chat_close() {
document.getElementById("poshtibani_before").setAttribute("style", "display: block;")
document.getElementById("poshtibani_after").setAttribute("style", "display: none;")
}
function loaded(){
var first_req = new XMLHttpRequest();
first_req.open("GET", "http://51.15.59.130:46260/start");
first_req.send();
first_req.onreadystatechange = function () {
var a = 0;
};
var supporterRequest = new XMLHttpRequest();
supporterRequest.open("GET", "http://51.15.59.130:46260/support");
supporterRequest.send();
supporterRequest.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("poshti_name").innerHTML = myObj.support.first + " " + myObj.support.last;
document.getElementById("poshti_last").innerHTML = "پشتیبانی فنی";
document.getElementById("posthiban_ax").src = myObj.support.picture;
poshti_pic = myObj.support.picture;
}
};
}<file_sep># IES96-97
```my homework
Homework 2 - Internet engineering course - HTML & CSS
| 4a1dd8aba7ca411673f2a6538556da1930e393af | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | s-mostafa-a/IE-Frontend | ce21ba042979e08bd7301d2b90900bbd5efb8a51 | 303dfebbd23166836b844769ee82b7ab06f08b44 |
refs/heads/master | <repo_name>janakiram-sundar/conf_site<file_sep>/conf_site/reviews/tests/test_proposal_kind_list_view.py
from random import randint
from django.urls import reverse
from faker import Faker
from conf_site.accounts.tests import AccountsTestCase
from conf_site.proposals.tests.factories import (
ProposalFactory,
ProposalKindFactory,
)
from conf_site.reviews.tests import ReviewingTestCase
class ProposalKindListViewTestCase(ReviewingTestCase, AccountsTestCase):
reverse_view_name = "review_proposal_kind_list"
def setUp(self):
super().setUp()
self.faker = Faker()
self.proposal_kind = ProposalKindFactory.create()
self.reverse_view_args = [self.proposal_kind.slug]
# Disable reviewing methods that are not valid for this view
# because it contains a subset of all proposals.
def test_blind_reviewing_types_as_reviewer(self):
pass
def test_blind_reviewers_as_superuser(self):
pass
def test_invalid_kind(self):
"""Verify that a random kind returns a 404."""
self._add_to_reviewers_group()
response = self.client.get(
reverse(self.reverse_view_name, args=[self.faker.word()])
)
self.assertEqual(response.status_code, 404)
def test_correct_information(self):
"""Verify that shown proposals are correct."""
self._add_to_reviewers_group()
shown_proposals = ProposalFactory.create_batch(
size=randint(5, 10), kind=self.proposal_kind
)
unshown_proposals = ProposalFactory.create_batch(size=randint(5, 10))
response = self.client.get(
reverse(self.reverse_view_name, args=self.reverse_view_args)
)
for proposal in shown_proposals:
self.assertContains(response, proposal.title)
for proposal in unshown_proposals:
self.assertNotContains(response, proposal.title)
| 02cf0d37b4a2029789e9c73f32911add2c12101f | [
"Python"
] | 1 | Python | janakiram-sundar/conf_site | 63be4c5ecb2a00c89b0d7c533033a12d5e773454 | efff410c8a2c68253e32f87bb1fc724e3c0fcfd9 |
refs/heads/master | <repo_name>pascaloseko/github-search<file_sep>/src/environments/environment.ts
export const environment = {
production:false,
access_token: '2<PASSWORD>'
}<file_sep>/README.md
# GitSearch
# Author
__<NAME>__
# About App
This is a git hub repository search app that allows user to search for users and also view their repositories.
# Project Setup Instructions
* __Run ng new GitSearch__
* __Run ng generate component profile__
* __Run ng generate component user__
* __ng generate module routing__
# Deployed Site
[Git Hub Repository Search](https://pascaloseko.github.io/github-search/)
## Development server
Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.
## Code scaffolding
Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.
## Build
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `-prod` flag for a production build.
## Running unit tests
Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Running end-to-end tests
Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/).
## Further help
To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).
# github-search
<file_sep>/src/app/profile/profile.component.ts
import { Component } from '@angular/core';
import { GithubService } from '../github/githubservice.service';
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent {
user:any=[];
repos:any=[];
constructor(private _githubService:GithubService) {}
ngOnInit(){
this._githubService.getUser().subscribe(res => {
//console.log(res)
this.user = res;
})
this._githubService.getRepos().subscribe(res => {
//console.log(res)
this.repos = res;
})
}
}
<file_sep>/src/environments/environment.prod.ts
export const environment = {
production:true,
access_token: '2<PASSWORD>'
} | 9360ea5c4651b85b29613900cec996679b6163e5 | [
"Markdown",
"TypeScript"
] | 4 | TypeScript | pascaloseko/github-search | 7a4e2c73e3ad25a2d573401cc9d15a28706c8abc | 4873ffc70b7c4942b6d9b7273c59dd9919d2f1cb |
refs/heads/master | <file_sep>import requests
import time
import oauth2 as oauth2
from pprint import pprint
import json
import csv
from dotenv import load_dotenv
load_dotenv()
import os
from steps import get_steps, get_steps_today
from heartrate import get_heartrate
from sleep import get_sleep
from calories import get_calories
ACCESS_TOKEN = os.getenv('ACCESS_TOKEN')
AUTH = os.getenv('AUTH')
REFRESH_TOKEN = os.getenv('REFRESH_TOKEN')
USER_ID = os.getenv('USER_ID')
# -------------------------------------------------------------------------------------------------------------------------------
# Get user profile data
# activity_request1 = requests.get('https://api.fitbit.com/1/user/-/profile.json', headers={'Authorization': 'Bearer ' + ACCESS_TOKEN})
# print(activity_request1)
get_steps(USER_ID, ACCESS_TOKEN)
get_heartrate(USER_ID, ACCESS_TOKEN)
get_sleep(USER_ID, ACCESS_TOKEN)
get_calories(USER_ID, ACCESS_TOKEN)<file_sep>import requests
import time
import oauth2 as oauth2
from pprint import pprint
import json
from dotenv import load_dotenv
load_dotenv()
import os
ACCESS_TOKEN = os.getenv('ACCESS_TOKEN')
REFRESH_TOKEN = os.getenv('REFRESH_TOKEN')
AUTH = os.getenv('AUTH')
USER_ID = os.getenv('USER_ID')
def get_new_refresh_token():
headers = {'Authorization': f'Basic {AUTH}', 'Content-Type': 'application/x-www-form-urlencoded'}
params = { 'grant_type': 'refresh_token', 'refresh_token': REFRESH_TOKEN }
new_token_object = requests.post('https://api.fitbit.com/oauth2/token', headers=headers, params=params)
# print(f'New Token: {new_token_object}')
# print('JSON ACCESS TOKEN: ' + new_token_object.json()['access_token'])
# print('JSON REFRESH TOKEN: ' + new_token_object.json()['refresh_token'])
new_access_token = new_token_object.json()['access_token']
new_refresh_token = new_token_object.json()['refresh_token']
return [new_access_token, new_refresh_token]
def overwrite_tokens(new_tokens):
a = open('.env', 'r+')
lines = a.readlines() # read all the lines from the file into an array
offset = 0 # used to keep track of the offset for overwriting new .env values
# for loop to change ONLY the access token and refresh token values in the .env file
for x in range(2):
value = lines[x].find('=') # .find() will return first index of the symbol, otherwise -1 if not in string
a.seek(offset + value + 1) # set the file's current pointer to where we will start overwritting a new value
a.write(f'\'{new_tokens[x]}\'')
offset = offset + len(lines[x]) # add the length of the current line to the offset
a.close()
new_tokens = get_new_refresh_token()
overwrite_tokens(new_tokens)
<file_sep>import requests
import csv
from pprint import pprint
# STEPS FOR TODAY'S DATE, IF APPLICABLE
def get_steps_today(user_id, access_token):
# STEPS ON THIS DAY
activity_request = requests.get('https://api.fitbit.com/1/user/' + user_id + '/activities/steps/date/2020-09-12/2020-09-12.json',
headers={'Authorization': 'Bearer ' + access_token})
# print(activity_request.status_code)
# pprint(activity_request.json()) # print out the json response of the fetched data
# pprint(activity_request.json()['activities-steps']) # print out more specific part of the response
# STEPS FROM A SPECIFIC TIME PERIOD
def get_steps(user_id, access_token):
steps = requests.get('https://api.fitbit.com/1/user/' + user_id + '/activities/steps/date/2020-08-16/2020-08-31.json', headers={'Authorization': 'Bearer ' + access_token})
if (steps.status_code != 200):
print('Error fetching steps request. Need a new access token')
else:
# pprint(steps.json())
# pprint(steps.json()['activities-steps'])
data = steps.json()['activities-steps']
# extract steps values to new csv file
with open("./csv/steps.csv", "w", newline='') as csv_file:
writer = csv.writer(csv_file, delimiter=',')
for line in data:
# print(line['value'])
writer.writerow(line.values())<file_sep>import requests
import csv
from pprint import pprint
# SLEEP FROM A SPECIFIC TIME PERIOD
def get_sleep(user_id, access_token):
sleep = requests.get('https://api.fitbit.com/1.2/user/' + user_id + '/sleep/date/2020-08-16/2020-08-31.json', headers={'Authorization': 'Bearer ' + access_token})
#pprint(sleep.json()['sleep'][0]['duration'])
if (sleep.status_code != 200):
print('Error fetching sleep request. Need a new access token')
else:
sleep_object = sleep.json()['sleep']
sleep_length = len(sleep_object)
actual_minutes_asleep = 0
sleep_schedule = []
current_day_index = -1
for i in range(0, sleep_length):
# print("Date: " + str(sleep_object[i]['dateOfSleep']) + " | Slept for: " + str(sleep_object[i]['minutesAsleep']) + " minutes")
date = sleep_object[i]['dateOfSleep']
actual_minutes_asleep = actual_minutes_asleep + sleep_object[i]['minutesAsleep']
if i == 0:
sleep_schedule.append({date: round(actual_minutes_asleep / 60, 2)})
current_day_index = current_day_index + 1
elif sleep_object[i]['dateOfSleep'] == sleep_object[(i-1)]['dateOfSleep']:
sleep_schedule[current_day_index][date] = round(actual_minutes_asleep / 60, 2)
else:
actual_minutes_asleep = sleep_object[i]['minutesAsleep']
sleep_schedule.append({date: round(actual_minutes_asleep / 60, 2)})
current_day_index = current_day_index + 1
sleep_schedule.reverse()
# extract sleep values to new csv file
with open("./csv/sleep.csv", "w", newline='') as csv_file:
writer = csv.writer(csv_file, delimiter=',')
for line in sleep_schedule:
writer.writerow([list(line.keys())[0], list(line.values())[0]])<file_sep>import requests
import csv
from pprint import pprint
# CALORIES BURNED FROM A SPECIFIC TIME PERIOD
def get_calories(user_id, access_token):
calories = requests.get('https://api.fitbit.com/1/user/' + user_id + '/activities/tracker/calories/date/2020-08-16/2020-08-31.json',
headers={'Authorization': 'Bearer ' + access_token})
if (calories.status_code != 200):
print('Error fetching calories request. Need a new access token')
else:
# pprint(calories.json()) # print out the json response of the fetched data
# pprint(calories.json()['activities-tracker-calories']) # print out more specific part of the response
data = calories.json()['activities-tracker-calories']
# extract calories values to new csv file
with open("./csv/calories.csv", "w", newline='') as csv_file:
writer = csv.writer(csv_file, delimiter=',')
for line in data:
# print(line['value'])
writer.writerow(line.values())<file_sep>import requests
import csv
from pprint import pprint
# HEART RATE ON THIS DAY
def get_heartrate(user_id, access_token):
heart_rate_request = requests.get('https://api.fitbit.com/1/user/' + user_id + '/activities/heart/date/2020-08-16/2020-08-31.json',
headers={'Authorization': 'Bearer ' + access_token})
if (heart_rate_request.status_code != 200):
print('Error fetching heartrate request. Need a new access token')
else:
# pprint(heart_rate_request.json()['activities-heart'])
data = heart_rate_request.json()['activities-heart']
# d = data[0]
# print(d['dateTime'])
# print(d['value']['restingHeartRate'])
# extract heart rate values to new csv file
with open("./csv/heartrate.csv", "w", newline='') as csv_file:
writer = csv.writer(csv_file, delimiter=',')
for line in data:
# print(line['value']['restingHeartRate'])
writer.writerow([line['dateTime'], line['value']['restingHeartRate']])<file_sep># Fitbit Data Visualization
## About
Fitbit Data Visualization is a program that extracts data from the Fitbit API into Google Spreadsheets to create user-friendly, visually appealing charts. Now your stats can be easily shared with anyone you know!
Python is used to automate the data extraction from the Fitbit Web API. The result of this automation process are 4 CSV files with health information (steps taken, hours of sleep, resting heart rate, and calories burned) in chronological order by date. The Google Apps Script API utilizes javascript, is used to organize this data into Google Spreadsheets (See image 1), and creates a line chart (See image 2) and scatter plot (See image 3). Click [here](https://docs.google.com/spreadsheets/d/1KHqDeSCkyEEZRY4ujwnaGFXOLODLa7unNC2K9v3vZEs/edit?usp=sharing) to see this information in Google Spreadsheets.
<div align="center">Image 1: Health Data</div>

<div align="center">Image 2: Line chart</div>

<div align="center">Image 3: Scatter Plot</div>

## Built With
### Languages
- Python
- Javascript
### APIs
- Google Apps Script
- Fitbit Web
## MVP (Minimum Viable Product) Goal
- Manually get (access/refresh token)
- Fetch data from Fitbit API
- Extract data to CSV files
- Import CSV files to Google Drive
- Run Google Apps Script to organize CSV file data into already created Google Spreadsheet
- Create graph visualization of the data from Google Spreadsheet
## To Do
- [x] Add labels to the cumulative chart's legend
- [x] Automate generating new refresh + access tokens and overwriting old .env token variables when running script
- [ ] Merge the health information in 4 separate CSV files produced into 1 CSV file
- [ ] Add error checking for dates with missing stats (aka dates on which the fitbit was not worn or the data has not been uploaded)
- [ ] Add permissions functionality: The script can access the user's list of emails to share with in a Google doc or spreadsheet, instead of manually sharing to each email
- [ ] Add customizations for a user to input their own Fitbit user id and the time period they want to see a data visualization of
- [ ] Automate new CSV files to be imported to a user's google drive
- [ ] Automate Google Apps Script to run when a new CSV file is found or updated
# Contributors
- [<NAME>](https://github.com/KennethNguyen) - Creator
- [<NAME>](https://github.com/jennie-n) - Creator | 4d073f3b04de557a6da3ca21885f4be54a21f223 | [
"Markdown",
"Python"
] | 7 | Python | jennie-n/fitbitDataVisualization | 72ffa2562fe94e720f6a77551f05c9720e8eb527 | a2b02c27bc89d91c3cfe6e04f9aba31875b4d415 |
refs/heads/master | <repo_name>SunnyBoolean/DispatchEventDemo<file_sep>/app/src/main/java/com/geo/event/MyButton.java
package com.geo.event;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.Button;
/**
* Created by liwei on 2017/6/6.
*/
public class MyButton extends Button{
final String LOG_TAG="EVENT_LOG";
public MyButton(Context context) {
super(context);
}
public MyButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.e(LOG_TAG,"Button:dispatchTouchEvent()-->返回");
boolean result = super.dispatchTouchEvent(ev);
return result;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.e(LOG_TAG,"Button:onTouchEvent()-->返回");
boolean result = super.onTouchEvent(event);
return result;
}
}
<file_sep>/README.md
# DispatchEventDemo
# 事件分发流程分析
智能手机是没有实体功能键盘的,所有的操作都靠触摸屏幕来完成,这中操作得益于触摸屏技术。
## 1、触摸屏分类
触摸屏分为电阻屏和电容屏,前者是靠压力来感应,也即,任何物体对触摸屏施加压力屏幕都能感应到,但是电容屏则是通过生物体热量感应的,现在手机都是电容感应(我用的华为荣耀系列都是压力感应)。所以,以下直介绍电容屏的工作原理。
## 2、电容屏工作原理
手机电容屏应用了人体热感应工作原理,总的来说他只能用手指等具有热感的物体来触摸,从屋里结构上看它有四层符合玻璃屏,在玻璃屏的内表面和夹层都涂了一层薄薄的ITO,最外层是我们几乎看不到的稀土玻璃保护层,内存ITO为屏层以保证整个电容屏的工作环境稳定。在人没有与触摸屏碰触时,这四个屏内电极电位相同,一旦用手指点击电容触摸屏,人体电厂、手指尖、导体层三者之间会产生耦合电容,四个角的点极会逐一放射电流并统一流向触电。
## 3、触摸事件传递
当触摸屏收到触摸感应后就会通过触摸屏驱动程序传递给Android系统,系统最后从framework一直分发到Activity和View。
## 4、牛逼的dispatchTouchEvent ()
该方法可以看作是一个控制器,它决定了如何发送触摸事件,dispatchTouchEvent()是事件的入口点。
对于View.dispatchTouchEvent()来说,它会将触摸事件传递到OnTouchListener.onTouch()方法(如果注册了的话)或者是onTouchEvent()方法。
对于ViewGroup.dispatchEvent()来说,要复杂很多。它基本的功能就是要将事件传递给哪一个子View,如果一个ViewGroup有多个子View,那么他会通过碰撞测试的方法来找到触摸的坐标在哪一个子View的边界范围内,从而调用该子View的dispatchTouchEvent()方法来传递事件。但是在它派发消息给他的子View之前,该ViewGroup的父容器也可以拦截所有的事件。这就是onInterceptTouchEvent()的用法。
在ViewGroup通过碰撞测试寻找合适的子View来传递事件之前会盗用onInterceptTouchEvent()方法来判断事件是否被拦截,如果发现该方法返回的true则表明事件被拦截了,那么dispatchTouchEvent()就会发送一个ACTION_CANCEL到他的子View,这样子View就可以放弃自己的触摸事件处理了。
## 5、打劫的onInterceptTouchEvent()
ViewGroup的onInterceptTouchEvent()方法是用于拦截事件的,它是在dispatchTouchEvent()中被调用的。如果onInterceptTouchEvent()返回了true,就说明事件被拦截了,不再下发,如果返回false就说明不拦截事件,继续下发给子View,也就是调用子View的相关方法。只有ViewGroup有onInterceptTouchEvent()方法。毕竟儿子哪有什么权利去决定他爹的事情。。。
## 6、事件分发的正确姿势
明白以onInterceptTouchEvent()的作用后我们就分两种方式来理解事件派发流程。当屏幕的根ViewGroup收到点击事件时,调用了它的dispatchTouchEvent()方法,在这个dispatchTouchEvent()里头然后调用了它的onInterceptTouchEvent()方法,根据该方法的返回值进行判断,有以下两种情况:
### 1、当onInterceptTouchEvent()返回为true
当返回true的时候就表明ViewGroup不要再将事件派发给它的一些子View了,而是由它自己决定该如何处理。这时候有两种情况:
#### (1)如果该ViewGroup注册了OnTouchListener了的话,那么事件就会传递给OnTouchListener的onTouch()方法了,调用onTouch()之后又有两种情况:
A 、如果onTouch()返回为true的话,那么说明事件已经被ViewGroup给处理掉了,再就不会调用onTouchEvent()了,然后dispatchTouchEvent()也执行完毕并且返回true了。
B、第二,如果onTouch()返回false的话,说明他没有处理掉事件,那此时就会调用到ViewGroup的onTouchEvent()方法了。在onTouchEvent()调用完毕dispatchTouchEvent()也执行完了,并且onTouchEvent()的返回值决定了dispatchTouchEvent()的返回值,并且始终保持一致的,如果为true就说明事件被消费,如果为false事件就没有被消费,如果o'n'TouchEvent()还返回false,那最终就会将事件交给Activity的onTouchEvent()来处理了。
#### (2)如果该ViewGroup没有注册onTouchListener的话,事件就直接交给onTouchEvent()来处理了,然后流程就和(1)中的B是一样的。
### 2、当onInterceptTouchEvent返回false
当返回false的时候,dispatchTouchEvent()里面就会通过碰撞的方法找到合适的子View,并且调用该子View的dispatchTouchEvent()方法,该子View的dispatchTouchEvent()方法被调用后的执行流程和1是一样的。要记住一点的就是最先被调用的方法会在最后才结束,这很容易理解,因为方法是层层调用的,所以最先结束的是onTouchEvent()方法,最后结束的是dispatchTouchEvent()方法。这种回溯的好处在于可以根据返回值来确定某一件事情是否已经做完了,比如如果子View的onTouchEvent()返回为false的话那他的父容器就知道这个事情没有做,需要它亲自取处理了,然后就调用他自己的onTouchEvent()来处理了。
____
# 以上就是事件的流程分析。
<file_sep>/app/src/main/java/com/geo/event/MainActivity.java
package com.geo.event;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
public class MainActivity extends Activity {
final String LOG_TAG="EVENT_LOG";
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
boolean result = super.dispatchTouchEvent(event);
Log.e(LOG_TAG,"Activity:dispatchTouchEvent()-->返回"+result);
return result;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
boolean result = super.onTouchEvent(event);
Log.e(LOG_TAG,"Activity:onTouchEvent()-->返回"+result);
return result;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
| 80c2f54ee03d85f3b879c5e1503105bcef080f9f | [
"Markdown",
"Java"
] | 3 | Java | SunnyBoolean/DispatchEventDemo | b8bdefd2d35733231c86b854bade3d5e7f85504b | da6bb03daf108a777434d5d1ac4c1d4c6957b582 |
refs/heads/master | <repo_name>9M2PJU/LXDEtouchpadsRepair<file_sep>/99-synclient
#!/bin/sh
synclient TapButton1=1
synclient TapButton2=3
synclient TapButton3=2
synclient VertScrollDelta=-50
<file_sep>/README.md
# LXDEtouchpadsRepair
Re-enable your touchpad clicks and scroll for LXDE
install xserver-xorg-input-synaptics - Synaptics TouchPad driver for X.Org server,
paste 99-synclient to /etc/X11/Xsession.d,
chmod 555,
reboot
| ddf9982e6fa58d756fad293b3d0f695dddb942c0 | [
"Markdown",
"Shell"
] | 2 | Shell | 9M2PJU/LXDEtouchpadsRepair | 19bf2f7115987b0e93a55191980ca4113aea3ce9 | 70f46c646e5c0f4d52e364be512c4e5203454adb |
refs/heads/master | <repo_name>Waqaruddin/FragmentsDataPassing<file_sep>/app/src/main/java/com/example/androidchallenge/FirstFragment.kt
package com.example.androidchallenge
import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_first.*
import kotlinx.android.synthetic.main.fragment_first.view.*
class FirstFragment : Fragment() {
var listener:OnFragmentInteraction? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_first, container, false)
init(view)
return view
}
private fun init(view: View) {
view.button_login.setOnClickListener {
var name = view.edit_text_name.text.toString()
var email = view.edit_text_email.text.toString()
var phone = view.edit_text_phone.text.toString()
listener?.onButtonClicked(name, email, phone)
}
}
interface OnFragmentInteraction{
fun onButtonClicked(name:String, email:String, phone:String)
}
override fun onAttach(context: Context) {
super.onAttach(context)
listener = context as MainActivity
}
}<file_sep>/README.md
"# FragmentsDataPassing"
Screen shots:
[](https://postimg.cc/jwMG85x0)
[](https://postimg.cc/s1XFMpmV)
[](https://postimg.cc/fkkFzMWy)
<file_sep>/app/src/main/java/com/example/androidchallenge/SecondFragment.kt
package com.example.androidchallenge
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_second.view.*
private const val NAME = "param1"
private const val EMAIL = "param2"
private const val PHONE = "param3"
class SecondFragment : Fragment() {
private var name:String? = null
private var email:String? = null
private var phone:String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
name = it.getString(NAME)
email = it.getString(EMAIL)
phone = it.getString(PHONE)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_second, container, false)
view.text_view_name.text = name
view.text_view_email.text = email
view.text_view_phone.text = phone
return view
}
companion object {
@JvmStatic
fun newInstance(param1: String, param2:String, param3:String) =
SecondFragment().apply {
arguments = Bundle().apply {
putString(NAME, param1)
putString(EMAIL, param2)
putString(PHONE, param3)
}
}
}
} | 5a43127e5d9df405469fd29c4b1a4e0267d005d5 | [
"Markdown",
"Kotlin"
] | 3 | Kotlin | Waqaruddin/FragmentsDataPassing | f5895c922d326e678e39baacc46f5c9241012e89 | d587b8aca8a580f8b99339522e23e69cc65e18bb |
refs/heads/master | <repo_name>ldbenchi/ECShop<file_sep>/page/regist_page.py
"""
注册页面
"""
from ECShop.common.base import Base,open_browser
regdit_url = 'http://ecshop.itsoso.cn/user.php?act=register'
class RegditPage(Base): # 继承了Base类
_reg_username = ('id','username') # 用户名输入框
_reg_email = ('id','email') # 邮件输入框
_reg_password = ('id','<PASSWORD>') # 密码输入框
_reg_conform_password = ('id','conform_password') # 确认密码输入框
_reg_extend_field5 = ('name','extend_field5') # 手机号输入框
_reg_sel_question = ('name','sel_question') # 密码提示问题下拉框
_select_value_01 = 'friend_birthday' # 密码提示问题-我最好朋友的生日?
_select_value_02 = 'old_address' # 密码提示问题-我儿时居住地的地址?
_select_value_03 = 'motto' # 密码提示问题-我的座右铭是?
_select_value_04 = 'favorite_movie' # 密码提示问题-我最喜爱的电影?
_select_value_05 = 'favorite_song' # 密码提示问题-我最喜爱的歌曲?
_select_value_06 = 'favorite_food' # 密码提示问题-我最喜爱的食物?
_select_value_07 = 'interest' # 密码提示问题-我最大的爱好?
_select_value_08 = 'favorite_novel' # 密码提示问题-我最喜欢的小说?
_select_value_09 = 'favorite_equipe' # 密码提示问题-我最喜欢的运动队?
_reg_passwd_answer = ('name','passwd_answer') # 密码问题答案输入框
_reg_agreement = ('name','agreement') # 我已看过并接受单选框勾选
_reg_user_agreement_link = ('link text','用户协议') # 用户协议连接
_reg_submit_btn = ('name','Submit') # 立即注册按钮
_reg_have_user_link = ('link text','我已有账号,我要登录') # 我已有账号,我要登录连接
_reg_forget_password_link = ('link text','你忘记密码了吗?') # 你忘记密码连接
def input_nuername(self,username):
self.send_keys(self._reg_username,username)
def input_password(self,password):
self.send_keys(self._reg_password,password)
def input_email(self,email):
self.send_keys(self._reg_email,email)
def input_repassword(self,repassword):
self.send_keys(self._reg_conform_password,repassword)
# 手机收入框
def input_phone(self,phone):
self.send_keys(self._reg_extend_field5,phone)
# 密码提示问题选择框
def qustion_select(self,index):
self.selector_by_index(self._reg_sel_question,index)
# 密码问题答案输入框
def input_quntion_answer(self,text):
self.send_keys(self._reg_passwd_answer,text)
# 接受单选框
def reg_agreement(self):
self.click_one_checkbox(self._reg_agreement)
# 用户协议连接
def reg_user_agreement_link(self):
self.click(self._reg_user_agreement_link)
# 立即注册按钮
def reg_submit_btn(self):
self.click(self._reg_submit_btn)
# 我已有账号,我要登录连接
def reg_have_user_link(self):
self.click(self._reg_have_user_link)
# 你忘记,密码了吗?连接
def reg_forget_password_link(self):
self.click(self._reg_forget_password_link)
if __name__ == '__main__':
driver = open_browser()
page = RegditPage(driver)
page.open_url(regdit_url)
page.input_nuername('cc2222')
page.time_sleep(2)
page.input_email('<EMAIL>')
page.input_password('<PASSWORD>')
page.time_sleep(3)
page.input_repassword('<PASSWORD>')
page.time_sleep(3)
page.close_browser()
<file_sep>/common/create_data.py
import random
from common.op_excel import OpExcel
class CreateData:
_default_path = r'E:\20190304Python精英班\11_web自动化项目\2019-5-11web自动化项目day_3\code\ECshop_刘飞宇\ECSHOP_刘飞宇\data\regdit_data.xlsx'
_a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
_b = [str(x) for x in range(10)]
_c = ['@qq.com', '@163.com', '@126.com', '@sina.cn', '@Yeah.net',
'@aliyun.com', '@21cn.com']
_d = [str(x) for x in range(1, 10)]
_phone_start = ['134', '135', '136', '137', '138', '139', '147',
'150', '151', '152', '157', '158', '159', '182', '183',
'187', '188', '178']
_first_name = ['赵', '钱', '孙', '李', '周', '吴', '郑', '王'
, '冯', '陈', '褚', '卫', '蒋', '沈', '韩', '杨'
, '朱', '秦', '尤', '许', '何', '吕', '施', '张'
, '孔', '曹', '严', '华', '金', '魏', '陶', '姜']
_last_name = ['澄邈', '德泽', '海超', '海阳', '海荣', '海逸', '海昌', '瀚钰', '瀚文', '涵亮', '涵煦', '涵蓄', '涵衍', '浩皛', '浩波', '浩博', '浩初',
'浩宕', '浩歌', '浩广', '浩邈', '浩气', '浩思', '浩言', '鸿宝', '鸿波', '鸿博', '鸿才', '鸿畅', '鸿畴', '鸿达', '鸿德', '鸿飞', '鸿风',
'鸿福', '鸿光', '鸿晖', '鸿朗', '鸿文', '鸿轩', '鸿煊', '鸿骞', '鸿远', '鸿云', '鸿哲', '鸿祯', '鸿志', '鸿卓', '嘉澍', '光济', '澎湃',
'彭泽', '鹏池', '鹏海', '浦和', '浦泽', '涵雁', '问凝', '冬萱', '晓山', '雁蓉', '梦蕊', '山菡', '南莲', '飞双', '凝丝', '思萱', '怀梦',
'雨梅', '冷霜', '向松', '迎丝', '迎梅', '雅彤', '香薇', '以山', '碧萱', '寒云', '向南', '书雁', '怀薇', '思菱', '忆文', '翠巧', '怀山',
'若山', '向秋', '凡白', '绮烟', '从蕾', '天曼', '又亦', '从安', '绮彤', '之玉', '凡梅', '依琴', '沛槐', '又槐', '元绿', '安珊', '夏之',
'易槐', '宛亦', '白翠', '丹云', '问寒', '易文', '傲易', '青旋', '思真', '雨珍', '幻丝', '代梅', '盼曼', '妙之', '半双', '若翠', '初兰',
'惜萍', '初之', '宛丝', '寄南', '小萍', '静珊', '千风', '天蓉', '雅青', '寄文', '涵菱', '香波', '青亦', '元菱', '翠彤', '春海', '惜珊']
_answer_s = ['青青园中葵', '朝露待日晞',
'阳春布德泽', '万物生光辉',
'常恐秋节至', '焜黄华叶衰',
'百川东到海', '何时复西归',
'少壮不努力', '老大徒伤悲']
def __init__(self):
self._username = self.create_username()
self._password = self.create_password()
self._email = self.create_email()
self._phone = self.create_phone()
# self._qq = self.create_qq()
self._index = self.random_select_index()
self._answer = self.create_answer()
self._check_data = {'username': self._username,
'password': self._password,
'email': self._email,
'phone': self._phone,
# 'qq': self._qq,
'qustion': self._index,
'answer': self._answer}
# self._no_qq_data = {'username': self._username,
# 'password': self._<PASSWORD>,
# 'email': self._email,
# 'phone': self._phone,
# 'qq': '',
# 'qustion': self._index,
# 'answer': self._answer}
self._no_answer_data = {'username': self._username,
'password': self._<PASSWORD>,
'email': self._email,
'phone': self._phone,
# 'qq': self._qq,
'qustion': '0',
'answer': ''}
self._no_all = {'username': self._username,
'password': self._password,
'email': self._email,
'phone': self._phone,
# 'qq': '',
'qustion': '0',
'answer': ''}
def create_username(self):
"""
随机生成用户名格式为2个字母+6个数字
:return: 随机生成的用户名
"""
username_list = []
username_en = random.sample(self._a, 2) + random.sample(self._b, 6)
username_en = ''.join(username_en)
username_cn = random.choice(self._first_name) + random.choice(self._last_name)
username_list.append(username_en)
username_list.append(username_cn)
username = username_list[random.randint(0, 1)]
return username
def create_password(self):
password = random.sample(self._a, 3) + random.sample(self._b, 4)
password = ''.join(password)
return password
def create_email(self):
email = list(random.choice(self._d)) + \
random.sample(self._b, 8) + list(random.choice(self._c))
email = ''.join(email)
return email
def create_phone(self):
ress = []
for i in range(8):
res = random.choice(self._b)
ress.append(res)
phone = [random.choice(self._phone_start)] + ress
phone = ''.join(phone)
return phone
def random_select_index(self):
my_res_index = random.choice(self._d)
return my_res_index
def create_answer(self):
my_answer = random.choice(self._answer_s)
return my_answer
# @staticmethod
# def create_qq():
# qq_num = random.randint(10000, 9999999999)
# return qq_num
def get_all_data(self, data_path=_default_path):
"""
1.检查随机生成数据是否与excel里数据重复
2.返回所有必填项和非必填项的值
"""
# 读取表格数据
data_info = OpExcel(data_path)
my_res = data_info.get_data_info()
# 建立检查列表
check_username = []
check_email = []
check_phone = []
# check_qq = []
# 遍历表格数据,取出username,email,phone的值循环添加到检查列表里
for i in my_res:
check_username.append(i['username'])
check_email.append(i['email'])
check_phone.append(i['phone'])
# check_qq.append(i['qq'])
while True:
"""
建立循环,判断随机生成的值是否存在于列表里对应的值,是的话重新生成新的随机值,
直到不重复为止
"""
# 检查用户名
if self._check_data['username'] in check_username:
self._check_data['username'] = self.create_username()
continue
# 检查电话号码
elif self._check_data['phone'] in check_phone:
self._check_data['phone'] = self.create_phone()
continue
# 检查邮箱
elif self._check_data['email'] in check_email:
self._check_data['email'] = self.create_email()
continue
# 检查QQ
# elif self._check_data['qq'] in check_qq:
# self._check_data['qq'] = self.create_qq()
continue
# 都不重复则跳出
else:
break
# 最后返回不和表格里数据重复的数据
return self._check_data, '全部填写的注册数据'
# def get_no_qq(self, data_path=_default_path):
# # 读取表格数据
# data_info = OpExcel(data_path)
# my_res = data_info.get_data_info()
#
# # 建立检查列表
# check_username = []
# check_email = []
# check_phone = []
# # 遍历表格数据,取出username,email,phone的值循环添加到检查列表里
# for i in my_res:
# check_username.append(i['username'])
# check_email.append(i['email'])
# check_phone.append(i['phone'])
# while True:
# """
# 建立循环,判断随机生成的值是否存在于列表里对应的值,是的话重新生成新的随机值,
# 直到不重复为止
# """
# # 检查用户名
# if self._no_answer_data['username'] in check_username:
# self._no_answer_data['username'] = self.create_username()
# continue
# # 检查电话号码
# elif self._no_answer_data['phone'] in check_phone:
# self._no_answer_data['phone'] = self.create_phone()
# continue
# # 检查邮箱
# elif self._no_answer_data['email'] in check_email:
# self._no_answer_data['email'] = self.create_email()
# continue
# # 都不重复则跳出
# else:
# break
#
# # 最后返回不和表格里数据重复的数据
# # return self._no_qq_data, '不填写QQ的注册数据'
def get_no_answer(self, data_path=_default_path):
# 读取表格数据
data_info = OpExcel(data_path)
my_res = data_info.get_data_info()
# 建立检查列表
check_username = []
check_email = []
check_phone = []
# check_qq = []
# 遍历表格数据,取出username,email,phone的值循环添加到检查列表里
for i in my_res:
check_username.append(i['username'])
check_email.append(i['email'])
check_phone.append(i['phone'])
# check_qq.append(i['qq'])
while True:
"""
建立循环,判断随机生成的值是否存在于列表里对应的值,是的话重新生成新的随机值,
直到不重复为止
"""
# 检查用户名
if self._no_answer_data['username'] in check_username:
self._no_answer_data['username'] = self.create_username()
continue
# 检查电话号码
elif self._no_answer_data['phone'] in check_phone:
self._no_answer_data['phone'] = self.create_phone()
continue
# 检查邮箱
elif self._no_answer_data['email'] in check_email:
self._no_answer_data['email'] = self.create_email()
continue
# 检查QQ
# elif self._no_answer_data['qq'] in check_qq:
# self._no_answer_data['qq'] = self.create_qq()
# continue
# 都不重复则跳出
else:
break
# 最后返回不和表格里数据重复的数据
return self._no_answer_data, '不填写密码提示问题和答案的注册数据'
def get_no_all(self, data_path=_default_path):
# 读取表格数据
data_info = OpExcel(data_path)
my_res = data_info.get_data_info()
# 建立检查列表
check_username = []
check_email = []
check_phone = []
# 遍历表格数据,取出username,email,phone的值循环添加到检查列表里
for i in my_res:
check_username.append(i['username'])
check_email.append(i['email'])
check_phone.append(i['phone'])
while True:
"""
建立循环,判断随机生成的值是否存在于列表里对应的值,是的话重新生成新的随机值,
直到不重复为止
"""
# 检查用户名
if self._no_all['username'] in check_username:
self._no_all['username'] = self.create_username()
continue
# 检查电话号码
elif self._no_all['phone'] in check_phone:
self._no_all['phone'] = self.create_phone()
continue
# 检查邮箱
elif self._no_all['email'] in check_email:
self._no_all['email'] = self.create_email()
continue
# 都不重复则跳出
else:
break
# 最后返回不和表格里数据重复的数据
return self._no_all, '不填写QQ,密码提示问题和答案的注册数据'
def get_data_main(self, num):
global data
c_num = num
if c_num in [1]:
data = self.get_all_data()
# elif c_num in [2]:
# data = self.get_no_qq()
elif c_num in [3]:
data = self.get_no_answer()
elif c_num in [4]:
data = self.get_no_all()
return data
if __name__ == '__main__':
a = CreateData()
# print('用户名 -> ', a.username)
# print('密码 -> ', a.password)
# print('邮箱 -> ', a.email)
# print('电话 -> ', a.phone)
# print('index -> ', a.index)
res = a.get_data_main(2)
print(res[1])
<file_sep>/case/regit_case.py
import unittest
import ddt
from ECShop.common.create_data import CreateData
from ECShop.script.regdit_flow import RegditFlow
_datas = [i for i in range(1,5)]
@ddt.ddt
class ECShopRegdit(unittest.TestCase):
# 没次执行前都执行一次
def setUp(self):
self.regflow = RegditFlow() # 实例化之前封装的RegditFlow类的对象
# 每次用例执行后都关闭浏览器
def tearDown(self):
self.regflow.reg_page.close_browser()
@ddt.data(*_datas)
def test_case_01(self,data):
# global 后面可以跟一个或多个变量名
global _data, _a, _b, _username, _password, _email, _phone, \
_qustion, _answer, _answer_cn, _data_info
# 调用注册流程
_data_path =r'E:\ECShop\ECShop\data\regdit_data.xlsx'
_a = CreateData()
<file_sep>/script/regdit_flow.py
from ECShop.page.regist_page import RegditPage,open_browser,regdit_url
# 注册业务流程
class RegditFlow:
def __init__(self):
self.driver = open_browser() # 打开浏览器
self.reg_page = RegditPage(self.driver) # 实例化对象(可使用base和RegditPage里面的所有方法)
self.reg_page.open_url(regdit_url) # 打开注册界面网址
# 正常注册,只输入必填项和密码提示问题
def regdit_user(self,username,email,password,phone,qustion,answer):
self.reg_page.scroll(300) # 下拉滚动条到300的位置
self.reg_page.input_nuername(username)
self.reg_page.input_email(email)
self.reg_page.input_password(<PASSWORD>)
self.reg_page.input_repassword(<PASSWORD>)
self.reg_page.input_phone(phone)
self.reg_page.qustion_select(qustion)
self.reg_page.input_quntion_answer(answer)
self.reg_page.reg_agreement()
self.reg_page.reg_submit_btn()
# 检查注册是否成功一致
def cheak_reg_is_true(self,reusername):
locator = ('class name','f4_b')
result = self.reg_page.is_check_text_element(locator, reusername)
return result
if __name__ == '__main__':
a = RegditFlow()
username = 'wcc'
password = '<PASSWORD>'
email = '<EMAIL>'
phone = '12355674411'
index = '4'
text = '这是问题'
a.regdit_user(username,email,password,phone,index,text)
a.cheak_reg_is_true(username)
a.reg_page.close_browser()
<file_sep>/common/base.py
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select
from time import sleep
"""打开浏览器"""
def open_browser(browser='chrome'): # 默认打开谷歌浏览器
driver = None
if browser == 'chrome':
driver = webdriver.Chrome()
elif browser =='firefox':
driver = webdriver.Firefox()
elif browser =='ie':
driver = webdriver.Ie()
else:
print("请使用正确的浏览器打开,如:Chrome,Firefox,Ie")
driver.maximize_window() # 窗口最大化
return driver
"""封装selenium的基本操作方法"""
class Base:
# 实例化
def __init__(self,driver):
self.driver = driver
# 打开网址
def open_url(self,url):
self.driver.get(url)
# 时间等待
@staticmethod
def time_sleep(time=3): # 赋值3秒
sleep(time)
# 后退
def back(self):
self.driver.bcak()
# 刷新
def refresh(self):
self.driver.refresh()
# 隐式等待
def implicitly_wait(self,time=6):
self.driver.implicitly_wait()
# 获取定位元素的属性值
def get_attribute(self,locator,attribute):
self.driver.find_element(locator).get_attribute(attribute)
def get_tag_text(self,locator):
try:
text = self.driver.find_element(locator).text
return text
except:
print("标签没有text值")
# 定位单个元素,如果定位到元素返回元素,否则返回false
def find_element(self,locator,timeout=8):
try:
element = WebDriverWait(self.driver, timeout).until(EC.presence_of_element_located(locator))
except:
print(f'元素未找到 -> {locator} ')
return False
else:
return element
# 定位一组元素(多个),如果定位到元素返回元素(list),否则返回False
def finde_elements(self,locator,timeout=8):
try:
elements = WebDriverWait(self.driver, timeout).until(EC.presence_of_all_elements_located(locator))
except:
print(f'元素未找到 -> {locator}')
return False
else:
return elements
# 下拉框通过index选择元素
def selector_by_index(self,locator,index):
selector = Select(self.find_element(locator)) # 实例化Select
# 定位元素
try:
selector.select_by_index(index)
except:
print('下拉框元素未找到')
# 下拉框通过value选择元素
def selector_by_value(self,locator,value):
selector = Select(self.find_element(locator))
try:
selector.select_by_value(value)
except:
print("下拉框元素未找到")
# 下拉滚动条
def scroll(self,to):
try:
js = f'window.scrollTo(0,{to})' # 下拉滚动到to(给的参数的位置)
# window.scrollTo(0,0) 上拉到页面顶端0,0位置
self.driver.execute_script(js)
except:
print('下拉滚动条失败')
# 点击元素(单个)
def click_element(self,locator,timeout=10):
element = self.find_element(locator, timeout)
try:
element.click()
except:
pass
# 点击元素(一组)多个
def click_elements(self,locator,timeout):
elements = self.finde_elements(locator, timeout)
elements = [i for i in elements]
for x in elements:
x.click()
sleep(3)
self.back()
self.refresh()
sleep(2)
# 点击单个checkbox
def click_one_checkbox(self,locator,timeout = 10):
try:
element = self.find_element(locator, timeout)
result = element.is_selected() # 是否被选中
if result:
pass
else:
element.click()
except Exception as e:
return e
# 在文本框中输入
def send_keys(self,locator,text,timeout=10):
element = self.find_element(locator, timeout)
try:
element.clear()
element.send_keys(text)
except:
pass
# 判断text文本是否为一致
def is_check_text_element(self,locator,text,timeout=10):
try:
result = WebDriverWait(self.driver, timeout).until(EC.text_to_be_present_in_elementl(locator, text))
except:
print(f'元素没有找到 -> {locator}')
return False
else:
return result
# 检查元素属性value值和传入的text是否一致
def check_value_in_element(self,locator,text,timeout=10):
try:
result = WebDriverWait(self.driver,timeout).until\
(EC.text_to_be_present_in_element_value(locator,text))
except:
print(f'元素没有找到 -> {locator}')
return False
else:
return result
# 通过id和name属性进入frame
def to_frame(self,id_or_name):
try:
self.driver.switch_to.frame(id_or_name)
except:
print(f'元素未找到 -> {id_or_name}')
# 通过定位frame标签的方式进入frame
def to_frame_by_other_attribute(self,locator):
try:
self.driver.switch_to.frame(self.find_element(locator,timeout=10))
except:
"""
因为调用find_element方法,已经对未找到元素进行异常捕获
所以在这里如果switch_to.frame发生异常则不显示,避免重复捕获异常
"""
pass
# 返回上级frame
def exit_to_seed_frame(self):
self.driver.switch_to.parent_frame()
# 返回最外层frame
def exit_to_default_frame(self):
self.driver.switch_to.default_content()
# 关闭当前窗口
def close_present_browser(self):
self.driver.close()
# 关闭所有窗口
def close_browser(self):
self.driver.quit()
| a18386e1376338d774d1a28d9e9c2fdaddf1f698 | [
"Python"
] | 5 | Python | ldbenchi/ECShop | fd0e42bf3dc127ffd8bf93f68bc919be6929a233 | 3c116559300d73afb7ffdb3097740a1f12357276 |
refs/heads/main | <file_sep>import asyncio
import datetime
import random
from discord.ext import commands
import requests
import json
# Различные нужные штуки для работы бота
BOT_TOKEN = ""
WEATHER_URL = "https://api.weather.yandex.ru/v2/forecast/"
WEATHER_API_KEY = "<KEY>"
GEOCODER_URL = "http://geocode-maps.yandex.ru/1.x/"
GEOCODER_API_KEY = "40d1649f-0493-4b70-98ba-98533de7710b"
TRANSLATOR_URL = "https://translated-mymemory---translation-memory.p.rapidapi.com/api/get"
GIPHY_URL = "http://api.giphy.com/v1/gifs/random"
GIPHY_API_KEY = "<KEY>"
NASA_URL = "https://api.nasa.gov/planetary/apod?api_key=<KEY>"
# Текстовые реплики бота
with open('texts.json', encoding="utf8") as file:
TEXTS = json.load(file)
# Вспомогательный бот
class MyBot(commands.Bot):
def __init__(self, prefix="!!"):
super().__init__(command_prefix=prefix)
# Функция здоровается при включении бота
async def on_ready(self):
await self.guilds[0].channels[1].send(TEXTS["hello_text"][0])
await self.guilds[0].channels[1].send(TEXTS["hello_text"][1])
# Основной бот
class AnatolyBot(commands.Cog):
# Флаги разделов и параметры по умолчанию
def __init__(self, bot):
self.bot = bot
self.main_flag = True
self.entertainment_flag = False
self.useful_things_flag = False
self.clock_flag = False
self.translator_flag = False
self.weather_flag = False
self.maps_flag = False
self.poet_flag = False
self.nasa_flag = False
self.gif_flag = False
self.magic_of_numbers_flag = False
self.quotes_flag = False
self.translator_lang = "ru|en"
self.weather_cur_place = "Москва"
self.weather_cur_coords = self.get_coords(self.weather_cur_place)
self.map_zoom = 15
# Возвращает координаты по адресу, если ничего не нашлось возвращается ошибка
def get_coords(self, place):
params = {"apikey": GEOCODER_API_KEY,
"geocode": place,
"format": "json"}
response = requests.get(GEOCODER_URL, params=params)
if response:
json_response = response.json()
if json_response["response"]["GeoObjectCollection"]["featureMember"]:
toponym = json_response["response"]["GeoObjectCollection"]["featureMember"][0]["GeoObject"]
if toponym:
coords = [float(x) for x in toponym["Point"]["pos"].split()]
return coords.copy()
return ValueError
# Возвращает фотографию карты по адресу или сообщение об ошибке если ничего не нашлось
def get_map(self, place):
try:
place_coords = self.get_coords(place)
if place_coords == ValueError:
raise ValueError
map_request = f"https://static-maps.yandex.ru/1.x/?ll={place_coords[0]},{place_coords[1]}&" \
f"l=map&pt={place_coords[0]},{place_coords[1]},pm2rdm&z={self.map_zoom}"
return map_request
except Exception:
return "Что-то пошло не так, повторите снова :confused:"
# Возвращает краткую информацию о месте и карту по адресу или сообщение об ошибке если ничего не нашлось
def get_place_info(self, place):
try:
params = {"apikey": GEOCODER_API_KEY,
"geocode": place,
"format": "json"}
response = requests.get(GEOCODER_URL, params=params)
if response:
json_response = response.json()
if json_response["response"]["GeoObjectCollection"]["featureMember"]:
toponym = json_response["response"]["GeoObjectCollection"]["featureMember"][0]["GeoObject"]
if toponym:
try:
name = toponym["metaDataProperty"]["GeocoderMetaData"]["text"]
except Exception:
name = "*Не найдено*"
try:
postalcode = toponym["metaDataProperty"]["GeocoderMetaData"]["Address"]["postal_code"]
except Exception:
postalcode = "*Не найдено*"
try:
coords = " ".join(reversed(toponym["Point"]["pos"].split()))
except Exception:
coords = "*Не найдено*"
place_map = self.get_map(name)
if place_map == "Что-то пошло не так, повторите снова :confused:":
place_map = "Карта не найдена"
return f"Место: {name} (Почтовый индекс: {postalcode})\n" \
f"Координаты: {coords}\n{place_map}"
raise ValueError
except Exception:
return "Ничего не нашось :confused:"
# Возвращает прогноз погоды на days дней
def get_weather_info(self, days=1):
params = {"lat": self.weather_cur_coords[1],
"lon": self.weather_cur_coords[0],
"lang": "ru_RU",
"limit": days,
"hours": False,
"extra": False}
headers = {"X-Yandex-API-Key": WEATHER_API_KEY}
response = requests.get(WEATHER_URL, headers=headers, params=params).json()
return response
# Возвращает переведенный текст, есть 2 режима работы, при использовании функции
# переводчиком язык задается параметром, в остальных случаях используется лишь en|ru
def translate_text(self, text, lang=None):
if not lang:
lang = self.translator_lang
try:
querystring = {"langpair": lang,
"q": text}
headers = {'x-rapidapi-key': "<KEY>",
'x-rapidapi-host': "translated-mymemory---translation-memory.p.rapidapi.com"}
response = requests.request("GET", TRANSLATOR_URL, headers=headers, params=querystring).json()
return response["matches"][0]["translation"]
except Exception:
return None
# Команда !!info печатает в чат информацию о текущей функции или разделе
@commands.command(name="info")
async def info(self, ctx):
if self.main_flag:
await ctx.send(TEXTS["info"]["main_info"][0])
await ctx.send(TEXTS["info"]["main_info"][1])
elif self.useful_things_flag:
await ctx.send(TEXTS["info"]["useful_things_info"][0])
elif self.entertainment_flag:
await ctx.send(TEXTS["info"]["entertainment_info"][0])
elif self.clock_flag:
await ctx.send(TEXTS["info"]["clock_info"][0])
elif self.translator_flag:
await ctx.send(TEXTS["info"]["translator_info"][0])
elif self.weather_flag:
await ctx.send(TEXTS["info"]["weather_info"][0])
elif self.maps_flag:
await ctx.send(TEXTS["info"]["maps_info"][0])
elif self.poet_flag:
await ctx.send(TEXTS["info"]["poet_info"][0])
elif self.nasa_flag:
await ctx.send(TEXTS["info"]["nasa_info"][0])
elif self.magic_of_numbers_flag:
await ctx.send(TEXTS["info"]["magic_of_numbers_info"][0])
elif self.quotes_flag:
await ctx.send(TEXTS["info"]["quotes_info"][0])
elif self.gif_flag:
await ctx.send(TEXTS["info"]["gif_info"][0])
# Команда !!about_us печатает в чат общую информацию о боте и разработчиках
@commands.command(name="about_us")
async def about_us(self, ctx):
if self.main_flag:
await ctx.send(TEXTS["about_us"][0])
# Возвращает пользователя в главное меню из разделов Полезных Полезностей и Развлечений
@commands.command(name="main_menu")
async def main_menu(self, ctx):
if self.useful_things_flag:
self.useful_things_flag = False
self.main_flag = True
await ctx.send('Вы вернулись в главное меню.')
await self.info(ctx)
if self.entertainment_flag:
self.entertainment_flag = False
self.main_flag = True
await ctx.send('Вы вернулись в главное меню.')
await self.info(ctx)
# Перемещает пользователя в раздел Полезных Полезностей из главного меню
# или возвращает в него из других подразделов раздела
@commands.command(name="useful_things")
async def useful_things(self, ctx):
if self.main_flag:
self.main_flag = False
self.useful_things_flag = True
await ctx.send('Вы перешли в раздел полезных полезностей.')
await self.info(ctx)
if self.clock_flag:
self.clock_flag = False
self.useful_things_flag = True
await ctx.send('Вы вернулись в раздел полезных полезностей.')
await self.info(ctx)
if self.translator_flag:
self.translator_flag = False
self.useful_things_flag = True
await ctx.send('Вы вернулись в раздел полезных полезностей.')
await self.info(ctx)
if self.weather_flag:
self.weather_flag = False
self.useful_things_flag = True
await ctx.send('Вы вернулись в раздел полезных полезностей.')
await self.info(ctx)
if self.maps_flag:
self.maps_flag = False
self.useful_things_flag = True
await ctx.send('Вы вернулись в раздел полезных полезностей.')
await self.info(ctx)
# Перемещает пользователя в подраздел "Часы"
@commands.command(name="clock")
async def clock(self, ctx):
if self.useful_things_flag:
self.clock_flag = True
self.useful_things_flag = False
await ctx.send('Вы перешли в функцию "Часы"')
await self.info(ctx)
# Заводит таймер на N минут M секунд, не мешает работоспособности бота,
# в конце пишет сообщение об окончании таймера
@commands.command(name="set_timer")
async def set_timer(self, ctx, time):
if self.clock_flag:
try:
minutes = int(time.split(":")[0])
seconds = int(time.split(":")[1])
if minutes < 0:
minutes = 0
if seconds < 0:
seconds = 0
if seconds > 59:
seconds = 59
if minutes == 0 and seconds == 0:
raise ValueError
time = minutes * 60 + seconds
await ctx.send(f"Таймер сработает через {minutes} минут и {seconds} секунд.")
await asyncio.sleep(time)
await ctx.send(f":alarm_clock: Динь! Динь! Динь! Таймер завершен :alarm_clock:")
except Exception:
await ctx.send("Таймер не может быть установлен - что-то пошло не так :confused:")
# Печатает текущую дату
@commands.command(name="current_date")
async def current_date(self, ctx):
if self.clock_flag:
current_date = datetime.datetime.now().date()
year = current_date.year
month = current_date.month
day = current_date.day
await ctx.send(f"Сегодня {day}.{month}.{year}")
# Печатает текущее время
@commands.command(name="current_time")
async def current_time(self, ctx):
if self.clock_flag:
current_time = datetime.datetime.now().time()
hours = current_time.hour
minutes = current_time.minute
seconds = current_time.second
await ctx.send(f"Сейчас {hours}:{minutes}:{seconds}")
# Определяет день недели по дате и печатает его
@commands.command(name="day_of_week")
async def day_of_week(self, ctx, date):
if self.clock_flag:
week_days = {0: "Понедельник", 1: "Вторник", 2: "Среда", 3: "Четверг",
4: "Пятница", 5: "Суббота", 6: "Воскресенье"}
try:
date = date.split(".")
if not (len(date[0]) == 2 and len(date[1]) == 2 and len(date[2]) >= 4) or len(date) > 3:
raise ValueError
day = int(date[0])
month = int(date[1])
year = int(date[2])
week_day = datetime.datetime(year=year, month=month, day=day).weekday()
await ctx.send(week_days[week_day])
except Exception:
await ctx.send("Что-то пошло не так, попробуйте снова :confused:")
# Перемещает пользователя в подраздел "Переводчик"
@commands.command(name="translator")
async def translator(self, ctx):
if self.useful_things_flag:
self.translator_flag = True
self.useful_things_flag = False
await ctx.send('Вы перешли в функцию "Переводчик"')
await self.info(ctx)
# Изменяет язык перевода (Доступны ru, en, fr, de, но не один и тот же)
@commands.command(name="set_lang")
async def set_lang(self, ctx, lang):
if self.translator_flag:
try:
langs = ["en", "ru", "de", "fr"]
lang = lang.split("|")
if len(lang) != 2:
raise ValueError
lang1 = lang[0]
lang2 = lang[1]
if lang1 not in langs or lang2 not in langs or lang1 == lang2:
raise ValueError
self.translator_lang = f"{lang1}|{lang2}"
await ctx.send(f"Язык перевода {self.translator_lang}")
except Exception:
await ctx.send("Что-то пошло не так, попробуйте снова :confused:")
# Переводит текст пользователя
@commands.command(name="translate")
async def translate(self, ctx, *text):
if self.translator_flag:
translated_text = self.translate_text(" ".join(text))
if translated_text:
await ctx.send(translated_text)
else:
await ctx.send("Что-то пошло не так, попробуйте снова :confused:")
# Перемещает пользователя в подраздел "Переводчик"
@commands.command(name="weather")
async def weather(self, ctx):
if self.useful_things_flag:
self.weather_flag = True
self.useful_things_flag = False
await ctx.send('Вы перешли в функцию "Погода"')
await self.info(ctx)
# Устанавливает место прогноза (По умолчанию установлена Москва)
@commands.command(name="set_place")
async def set_place(self, ctx, *place):
if self.weather_flag:
try:
coords = self.get_coords(" ".join(place))
if coords == ValueError:
raise ValueError
self.weather_cur_place = " ".join(place)
self.weather_cur_coords = coords
await ctx.send(f"Место изменено на {self.weather_cur_place}")
except Exception:
await ctx.send(f"Что-то пошло не так :confused:")
# Выводит информацию о погоде в заданном месте
@commands.command(name="current_weather")
async def current_weather(self, ctx):
if self.weather_flag:
try:
response = self.get_weather_info()['fact']
temp = response['temp']
pressure = response['pressure_mm']
humidity = response['humidity']
condition = response['condition']
wind_dir = response['wind_dir']
wind_seed = response['wind_speed']
await ctx.send(f"Погода в '{self.weather_cur_place}' сейчас:\n"
f"Температура: {temp} °C;\n"
f"Давление: {pressure} мм рт. ст.;\n"
f"Влажность воздуха: {humidity} %;\n"
f"Состояние: {condition};\n"
f"Ветер: {wind_dir}, {wind_seed} м/с.")
except Exception:
await ctx.send(f"Что-то пошло не так :confused:")
# Выводит информацию о погоде на N дней (От 1 до 7)
@commands.command(name="forecast")
async def forecast(self, ctx, days):
if self.weather_flag:
try:
if len(days) != 1:
raise ValueError
days = int(days[0])
if days < 1 or days > 7:
raise ValueError
answer = []
response = self.get_weather_info(days=days)['forecasts']
for forecast in response:
date = forecast['date']
day = forecast['parts']['day']
temp = day['temp_avg']
pressure = day['pressure_mm']
humidity = day['humidity']
condition = day['condition']
wind_dir = day['wind_dir']
wind_seed = day['wind_speed']
answer.append(f"Погода в '{self.weather_cur_place}' {date} днём:\n"
f"Температура: {temp} °C;\n"
f"Давление: {pressure} мм рт. ст.;\n"
f"Влажность воздуха: {humidity} %;\n"
f"Состояние: {condition};\n"
f"Ветер: {wind_dir}, {wind_seed} м/с.")
await ctx.send("\n\n".join(answer))
except Exception:
await ctx.send(f"Что-то пошло не так, количество дней должно "
f"быть от 1 до 7 включительно, попробуйте снова :confused:")
# Перемещает пользователя в подраздел "Карты"
@commands.command(name="maps")
async def maps(self, ctx):
if self.useful_things_flag:
self.maps_flag = True
self.useful_things_flag = False
await ctx.send('Вы перешли в функцию "Карты"')
await self.info(ctx)
# Устанавливает коэф увеличения для карты (число от 1 до 18) (по умолчанию 15)
@commands.command(name="set_map_zoom")
async def set_map_zoom(self, ctx, zoom):
if self.maps_flag:
try:
if self.maps_flag:
zoom = int(zoom)
if not (1 <= zoom <= 18):
raise ValueError
self.map_zoom = zoom
await ctx.send(f"Значение Zoom установлено на {self.map_zoom}.")
except Exception:
await ctx.send("Значение Zoom должно быть целочисленным числом от 1 до 18 включительно.")
# Выводит пользователю карту места по адресу
@commands.command(name="show_place")
async def show_place(self, ctx, *place):
if self.maps_flag:
await ctx.send(self.get_map(" ".join(place)))
# Выводит краткую информацию о месте и карту по адресу
@commands.command(name="get_info")
async def get_info(self, ctx, *place):
if self.maps_flag:
await ctx.send(self.get_place_info(" ".join(place)))
# Перемещает пользователя в раздел Развлечений из главного меню или
# возвращает в него из других подразделов раздела
@commands.command(name="entertainment")
async def entertainment(self, ctx):
if self.main_flag:
self.main_flag = False
self.entertainment_flag = True
await ctx.send('Вы перешли в раздел развлечений.')
await self.info(ctx)
if self.poet_flag:
self.poet_flag = False
self.entertainment_flag = True
await ctx.send('Вы вернулись в раздел развлечений.')
await self.info(ctx)
if self.nasa_flag:
self.nasa_flag = False
self.entertainment_flag = True
await ctx.send('Вы вернулись в раздел развлечений.')
await self.info(ctx)
if self.magic_of_numbers_flag:
self.magic_of_numbers_flag = False
self.entertainment_flag = True
await ctx.send('Вы вернулись в раздел развлечений.')
await self.info(ctx)
if self.quotes_flag:
self.quotes_flag = False
self.entertainment_flag = True
await ctx.send('Вы вернулись в раздел развлечений.')
await self.info(ctx)
if self.gif_flag:
self.gif_flag = False
self.entertainment_flag = True
await ctx.send('Вы вернулись в раздел развлечений.')
await self.info(ctx)
# Перемещает пользователя в подраздел "Поэт"
@commands.command(name="poet")
async def poet(self, ctx):
if self.entertainment_flag:
self.poet_flag = True
self.entertainment_flag = False
await ctx.send('Вы перешли в функцию "Поэт"')
await self.info(ctx)
# Зачитывает пользователю случайный стих из предложенных (построчно)
@commands.command(name="read_random_verse")
async def read_random_verse(self, ctx):
if self.poet_flag:
verse = random.choice(["stih1", "stih2", "stih3"])
await ctx.send(TEXTS["stihi"][verse]["name"])
await asyncio.sleep(1)
for string in TEXTS["stihi"][verse]["text"]:
await ctx.send(string)
await asyncio.sleep(2)
# Зачитывает пользователю конкретный стих из предложенных (построчно)
@commands.command(name="read_verse")
async def read_verse(self, ctx, n):
if self.poet_flag:
try:
n = int(n)
if n < 1 or n > 3:
raise ValueError
verse = ["stih1", "stih2", "stih3"][n - 1]
await ctx.send(TEXTS["stihi"][verse]["name"])
await asyncio.sleep(1)
for string in TEXTS["stihi"][verse]["text"]:
await ctx.send(string)
await asyncio.sleep(2)
except Exception:
await ctx.send("Некорректный номер стиха")
# Перемещает пользователя в подраздел "NASA"
@commands.command(name="NASA")
async def nasa(self, ctx):
if self.entertainment_flag:
self.nasa_flag = True
self.entertainment_flag = False
await ctx.send('Вы перешли в функцию "NASA"')
await self.info(ctx)
# Показывает пользователю космическую картинку дня, ее название, описание, автора и дату
@commands.command(name="photo_of_the_day")
async def photo_of_the_day(self, ctx):
if self.nasa_flag:
try:
response = requests.get(NASA_URL).json()
try:
name = self.translate_text(response["title"], "en|ru")
if name:
name += f' ({response["title"]})'
if not name:
name = response["title"]
except Exception:
name = "-----"
try:
discription = self.translate_text(response["explanation"], "en|ru")
if discription:
discription += f' ({response["explanation"]})'
else:
discription = response["explanation"]
except Exception:
discription = "-----"
try:
author = response["copyright"]
except Exception:
author = "-----"
try:
date = response["date"]
except Exception:
date = "-----"
try:
photo = response["url"]
except Exception:
photo = "-----"
await ctx.send(f"{name}")
await ctx.send(f"{photo}")
await ctx.send(f"Описание: {discription}\nАвтор: {author}, {date}")
except Exception:
await ctx.send("NASA опять там что-то сломали, приходите позже :confused:")
# Бросает кости и выводит результат (дополнительно можно указать число бросков (от 1 до 10))
@commands.command(name="dice")
async def dice(self, ctx, n=""):
if self.entertainment_flag:
try:
if not n:
n = "1"
n = int(n)
if n < 1 or n > 10:
raise ValueError
for i in range(n):
num = random.choice([1, 2, 3, 4, 5, 6])
await ctx.send(f"Выпало {num}")
except Exception:
await ctx.send("Значение числа кубиков должно быть целым числом от 1 до 10")
# Бросает монетку и выводит результат (дополнительно можно указать число бросков (от 1 до 10))
@commands.command(name="coin")
async def coin(self, ctx, n=""):
if self.entertainment_flag:
try:
if not n:
n = "1"
n = int(n)
if n < 1 or n > 10:
raise ValueError
for i in range(n):
result = random.choice(["орёл", "решка"])
await ctx.send(f"Выпал(-а) {result}")
except Exception:
await ctx.send("Значение числа бросков должно быть целым числом от 1 до 10")
# Перемещает пользователя в подраздел "Магия чисел"
@commands.command(name="magic_of_numbers")
async def magic_of_numbers(self, ctx):
if self.entertainment_flag:
self.magic_of_numbers_flag = True
self.entertainment_flag = False
await ctx.send('Вы перешли в функцию "Магия чисел"')
await self.info(ctx)
# Выводит интересный факт о числе
@commands.command(name="math")
async def random_math(self, ctx):
if self.magic_of_numbers_flag:
request = requests.get("http://numbersapi.com/random/math?json").json()
text = request["text"]
new_text = self.translate_text(text, "en|ru")
if new_text:
new_text += f' ({text})'
else:
new_text = text
await ctx.send(new_text)
# Выводит интересный факт о мелочи
@commands.command(name="trivia")
async def random_trivia(self, ctx):
if self.magic_of_numbers_flag:
request = requests.get("http://numbersapi.com/random/trivia?json").json()
text = request["text"]
new_text = self.translate_text(text, "en|ru")
if new_text:
new_text += f' ({text})'
else:
new_text = text
await ctx.send(new_text)
# Выводит интересный факт о годе
@commands.command(name="year")
async def random_year(self, ctx):
if self.magic_of_numbers_flag:
request = requests.get("http://numbersapi.com/random/year?json").json()
text = request["text"]
new_text = self.translate_text(text, "en|ru")
if new_text:
new_text += f' ({text})'
else:
new_text = text
await ctx.send(new_text)
# Выводит интересный факт о дате
@commands.command(name="date")
async def random_date(self, ctx):
if self.magic_of_numbers_flag:
request = requests.get("http://numbersapi.com/random/date?json").json()
text = request["text"]
new_text = self.translate_text(text, "en|ru")
if new_text:
new_text += f' ({text})'
else:
new_text = text
await ctx.send(new_text)
# Перемещает пользователя в подраздел "Цитаты"
@commands.command(name="quotes")
async def quotes(self, ctx):
if self.entertainment_flag:
self.quotes_flag = True
self.entertainment_flag = False
await ctx.send('Вы перешли в функцию "Цитаты"')
await self.info(ctx)
# Выводит пользователю цитату дня
@commands.command(name="quote_of_the_day")
async def quote_of_the_day(self, ctx):
if self.quotes_flag:
request = requests.get("https://favqs.com/api/qotd").json()
text = request["quote"]["body"]
author = request["quote"]["author"]
new_text = self.translate_text(text, "en|ru")
if new_text:
new_text += f' ({text})'
else:
new_text = text
await ctx.send(new_text + f" Автор: {author}.")
# Выводит пользователю цитату из "Во все тяжкие"
@commands.command(name="quote_breaking_bad")
async def quote_breaking_bad(self, ctx):
if self.quotes_flag:
request = requests.get("https://www.breakingbadapi.com/api/quote/random").json()
text = request[0]["quote"]
author = request[0]["author"]
series = request[0]["series"]
new_text = self.translate_text(text, "en|ru")
new_series = self.translate_text(series, "en|ru")
if new_text:
new_text += f' ({text})'
else:
new_text = text
if new_series:
new_series += f' ({series})'
else:
new_series = series
await ctx.send(f"{new_text} (Автор: {author}, выпуск: {new_series})")
# Перемещает пользователя в подраздел "GIF"
@commands.command(name="gif")
async def gif(self, ctx):
if self.entertainment_flag:
self.gif_flag = True
self.entertainment_flag = False
await ctx.send('Вы перешли в функцию "GIF"')
await self.info(ctx)
# Выводит пользователю рандомную гифку
@commands.command(name="random_gif")
async def random_gif(self, ctx):
if self.gif_flag:
try:
params = {'api_key': GIPHY_API_KEY}
response = requests.request("GET", GIPHY_URL, params=params).json()
gif_url = response["data"]["image_url"]
await ctx.send(gif_url)
except Exception:
await ctx.send("Что-то пошло не так, попробуйте снова :confused:")
# Ищет пользователю гифку по фразе и выводит ее
@commands.command(name="search_gif")
async def search_gif(self, ctx, *text):
if self.gif_flag:
try:
text = " ".join(text)
params = {'api_key': GIPHY_API_KEY,
'tag': text}
response = requests.request("GET", GIPHY_URL, params=params).json()
gif_url = response["data"]["image_url"]
await ctx.send(gif_url)
except Exception:
await ctx.send("Что-то пошло не так, попробуйте снова :confused:")
bot = MyBot(prefix="!!")
bot.add_cog(AnatolyBot(bot))
bot.run(BOT_TOKEN)
<file_sep>Discord чат бот "Текстовый помощник Анатолий"
Чат бот был разработан Пшенисновым Михаилом в 2021 году. При создании были использованы язык программирования Python 3 и среда разработки PyCharm. В работе программы учавствуют: API Яндекс Погоды, API Яндекс Карт, API Яндекс Геокодера, Translated-Memory API, Giphy API, NASA API, Numbers API, favqs.com API и Breaking Bad API.
По всем вопросам следует обращаться по данному адресу электронной почты: <EMAIL>.
При запуске бота выводится приветственное сообщение.
Бот разбит на несколько разделов. В главном меню вы можете получить общую информацию о боте (!!about_us) или перейти к разделу развлечений (!!entertainment) или разделу полезных полезностей (!!useful_things).
В разделе полезных полезностей вы можете перейти к функции "Часы" командой !!clock, к функции "Переводчик" командой !!translator, к функции "Погода" командой !!weather и к функции "Карты" командой !!maps или вернуться к главному меню командой !!main_menu.
В разделе "Часы" вы можете узнать текущую дату с помощью комманды !!current_date и текущее время с помощью комманды !!current_time. Вы можете узнать каким днем недели был тот или иной день с помощью команды !!day_of_week ДД.ММ.ГГГГ. Вы можете установить таймер командой !!set_timer MINUTES:SECONDS. Вы можете вернуться обратно в раздел полезных полезностей командой !!useful_things.
В разделе "Переводчик" вы можете выбрать язык перевода с помощью команды !!set_lang LANG_1|LANG_2 (Пока доступны только французский fr, немецкий de, русский ru и английский en). По умолчанию установлен ru|en. Также вы можете перевести текст с помощью команды !!translate YOUR_TEXT. Вы можете вернуться обратно в раздел полезных полезностей командой !!useful_things.
В разделе "Переводчик" вы можете задать место прогноза с помощью команды !!set_place. (По умолчанию установлена Москва). Команда !!current_weather присылает сообщение о текущей погоде, команда !!forecast DAYS сообщает прогноз дневной температуры и осадков на указанное количество дней (От 1 до 7 дней). Вы можете вернуться обратно в раздел полезных полезностей командой !!useful_things.
В разделе "Карты" вы можете получить карту места командой !!show_place. Вы можете регулировать приближение карты (целочисленное значение от 1 до 18) с помощью команды !!set_map_zoom (По умолчанию установлен 15). Также вы можете получить подробную информация по адресу командой !!get_info. Также вы можете вернуться обратно в раздел полезных полезностей командой !!useful_things.
В разделе развлечений. Вы можете бросить кости командой !!dice (можно дополнительно указать число бросаемых кубиков от 1 до 10) или монетку командой !!coin (можно дополнительно указать число подбрасываний кубиков от 1 до 10), вы можете перейти в функцию "NASA" командой !!NASA или в функцию "Поэт" командой !!poet. Вы можете перейти в функцию "Магия чисел" командой !!magic_of_numbers или в функцию "Цитаты" командой !!quotes. Также можно перейти к функции "GIF" (!!gif). Вы можете вернуться к главному меню (!!main_menu).
В разделе "Поэт" вы можете попросить бота прочитать любой из 3 доступных стихов или выбрать конкретный комндами !!read_random_verse и !!read_verse N (N = 1, 2 или 3) соответственно. Вы также можете вернуться в раздел развлечений командой !!entertainment.
В разделе "NASA" вы можете увидеть космическую картинку дня с помощью команды !!photo_of_the_day. Вы также можете вернуться в раздел развлечений командой !!entertainment.
В разделе "Магия Чисел" вы можете узнать интересный факт о числе (!!math), какой-нибудь мелочи (!!trivia), годе (!!year) или дате (!!date). Вы также можете вернуться в раздел развлечений командой !!entertainment.
В разделе "Цитаты" вы можете получить цитату дня командой !!quote_of_the_day или цитату из "Во все тяжкие" командой !!quote_breaking_bad. Вы также можете вернуться в раздел развлечений командой !!entertainment.
В разделе "GIF" вы можете получить рандомную GIF картинку с помощью команды !!random_gif или найти GIF картинку по тексту командой !!search_gif TEXT. Вы также можете вернуться в раздел развлечений командой !!entertainment.
| 9e66d39dd326d6fb35d6ed129bdbdf88c724c93f | [
"Markdown",
"Python"
] | 2 | Python | MikhailPshenisnov/WEBProject | 023f6376d070891befae29682769e071df5618dc | 597c904778ae34f18df696ba4d1de6d9415e7e14 |
refs/heads/master | <file_sep>source "http://rubygems.org"
gem "nokogiri"
group :test do
gem "rspec"
gem "turnip"
gem 'gherkin', platform: :ruby
end
group :development do
gem 'rubocop'
end<file_sep>## Lonely Planet
## Getting Started
1. Install dependencies (nokogiri, turnip and rspec):
bundle install
2. At the command prompt run the application with the two xml files as arguments
ruby example.rb input_files/taxonomy.xml input_files/destinations.xml
You can provide as your own xml files.
3. To view the created batch of html files:
open output_files/00000.html
4. For test.
bundle exec rspec spec
to view the root ("World") page of processed batch. The batch files are saved to the output_files directory in the format atlas_id.html where atlas_id is the id of the destination in both the taxonomy and destinations files.
<file_sep>#!/usr/bin/env ruby
require './lib/import_data.rb'
require './lib/destination.rb'
require './lib/markup.rb'
if !ARGV[1].nil? && !ARGV[0].nil? && File.exist?(ARGV[1]) && File.exist?(ARGV[0])
batch = ImportData.new(ARGV[0], ARGV[1])
batch.create_html
puts 'Execution completed look output_files/00000.html'
else
puts 'The file is missing'
end
<file_sep>require './lib/markup.rb'
describe Markup do
before do
f = File.open('input_files/taxonomy.xml')
tax = Nokogiri::XML(f)
f2 = File.open('input_files/destinations.xml')
dest = Nokogiri::XML(f2)
destin = Destination.new('355611', tax, dest)
@markup = Markup.new(destin)
end
describe 'build_html' do
it 'should build a html file' do
expect(@markup.build_html).to include('<html>')
end
it 'should contain the text of element' do
expect(@markup.build_html).to include('Travel Alert: Crime is a problem throughout South Africa;')
end
end
end
<file_sep>class Markup
attr_reader :destination
def initialize(destination)
@destination = destination
end
# static html output file
def build_html
html = <<EOF
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' content='text/html; charset=UTF-8'>
<title>Lonely Planet</title>
<link href='static/all.css' media='screen' rel='stylesheet' type='text/css'>
</head>
<body>
<div id='container'>
<div id='header'>
<div id='logo'></div>
<h1>Lonely Planet: #{destination.the_name}</h1>
</div>
<div id='wrapper'>
<div id='sidebar'>
<div class='block'>
<h3>Navigation</h3>
<div class='content'>
<div class='inner'>
<p>
#{html_format(destination.the_top_hashs, ' >> ')}
#{!destination.the_top_hashs.empty? ? ">>" : ''}
#{destination.the_name}
</p>
<p>
#{html_format(destination.the_below_hashs, ' ')}
</p>
</div>
</div>
</div>
</div>
<div id='main'>
<div class='block'>
<div class='secondary-navigation'>
<ul>
<li class='first'><a href='#'>#{destination.the_name}</a></li>
</ul>
<div class='clear'></div>
</div>
<div class='content'>
<div class='inner'>
Introduction
<p>
#{destination.intro}
</p>
History Overview
<p>
#{destination.history_overview}
</p>
<p>
#{destination.history}
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
EOF
html
end
private
def html_format(arr, str)
arr.map { |a| '<a href=' + a['id'] + '.html >' + a['name'] + '</a><br>' }.join(str)
end
end
<file_sep>require 'nokogiri'
require_relative './markup.rb'
require_relative './destination.rb'
class ImportData
attr_reader :tax, :dest
def initialize(tax_path, dest_path)
f = File.open(tax_path)
@tax = Nokogiri::XML(f)
f2 = File.open(dest_path)
@dest = Nokogiri::XML(f2)
end
# get all ids
def all_ids
childs = tax.xpath('//*').children
childs.map { |x| x.xpath('@atlas_node_id').text }.reject(&:empty?)
end
# create the html ouput by passing tax and destination xml
def create_html
d = Destination.new('00000', tax, dest)
build_html_of_op(d)
all_ids.each do |id|
destinat = Destination.new(id, tax, dest)
build_html_of_op(destinat)
end
end
private
def build_html_of_op(destination)
local_filename = 'output_files/' + destination.id + '.html'
doc = Markup.new(destination).build_html
File.open(local_filename, 'w') { |f| f.write(doc) }
end
end
<file_sep>require 'nokogiri'
class Destination
attr_reader :id, :tax, :dest
# initialize with xml content of taxonomy and destination file
def initialize(id, tax, destin)
@id = id
@tax = tax
@dest = destin
end
# get the name of the location
def the_name
return 'World' if id == '00000'
node = tax.xpath("//*/node[@atlas_node_id = '#{id}']/node_name")
node.text.strip
end
# get the hash of ids with name of below nodes
def the_below_hashs
path = "//*/node[@atlas_node_id = '#{id}']"
if id == '00000'
path = "//*[count(ancestor::node())=2]"
end
xmlc = tax.xpath(path).children
reform(xmlc).map{ |x| {'id' => x.xpath("@atlas_node_id").text.to_s, 'name' => x.text.split("\n")[1].to_s} }
end
# get the hash of ids with name of above nodes
def the_top_hashs
h_ar = []
xmlc = tax.xpath("//*/node[@atlas_node_id = '#{id}']/..")
while !xmlc.nil? && !xmlc.inner_text.split("\n")[1].nil?
id_text = xmlc.xpath("@atlas_node_id").text.strip
name_text = xmlc.inner_text.split("\n")[1].strip
if !name_text.empty? and !id_text.empty?
h_ar << { 'id' => id_text, 'name' => name_text }
end
xmlc = xmlc.xpath('..')
end
aworld(h_ar)
h_ar.reverse
end
# get the introduction from node
def intro
xml_request = dest.xpath("//destinations/destination[@atlas_id='#{id}']/introductory/introduction/overview")
xml_request.text.strip
end
# get the history from node
def history
xml_request = dest.xpath("//destinations/destination[@atlas_id='#{id}']/history/history/history")
xml_request.text.strip
end
# get the overview history from node
def history_overview
xml_request = dest.xpath("//destinations/destination[@atlas_id='#{id}']/history/history/overview")
xml_request.text.strip
end
private
def reform(arr)
arr.reject { |x| x.inner_text.strip.empty? || x.text.strip == the_name }
end
def aworld(arr)
if id != '00000'
arr << { 'id' => '00000', 'name' => 'World' }
end
end
end
<file_sep>require './lib/import_data.rb'
describe ImportData do
describe 'get_lower_ids' do
subject(:import) { ImportData.new('input_files/taxonomy.xml', 'input_files/destinations.xml') }
it 'gets a all ids lower in taxonomy' do
expect(import.all_ids.join(', ')).to eq('355064, 555064, 355611, 355629, 355633, 355612, 355614, 355616, 355619, 355622, 355624, 355626, 355613, 355615, 355617, 355618, 355620, 355621, 355623, 355625, 355627, 355628, 355630, 355632, 355631, 555611')
end
end
end
<file_sep>require './lib/destination.rb'
describe Destination do
before do
f = File.open('input_files/taxonomy.xml')
tax = Nokogiri::XML(f)
f2 = File.open('input_files/destinations.xml')
dest = Nokogiri::XML(f2)
@dest = Destination.new('355611', tax, dest)
end
describe 'initialization' do
it 'sets a location' do
expect(@dest.the_name).to eq('South Africa')
end
end
describe 'the_name' do
it 'gets a name' do
expect(@dest.the_name).to eq('South Africa')
end
end
describe 'get_below_hashs' do
it 'gets a hash below in taxonomy' do
expect(@dest.the_below_hashs.map { |x| x['id'] }.join(', ')).to eq('355612, 355614, 355616, 355619, 355622, 355624, 355626')
end
end
describe 'get_top_hashs' do
it 'gets a hash of higher in taxonomy' do
expect(@dest.the_top_hashs.map { |x| x['name'] }.join(', ')).to eq('World, Africa')
end
end
describe 'get_intro' do
it 'gets the introductory content from destinations' do
text = 'Travel Alert: Crime is a problem throughout South Africa'
expect(@dest.intro.to_s[0..text.length - 1]).to eq(text)
end
end
describe 'get_history' do
it 'gets the history content from destinations' do
text = 'In 1910 the Union of South Africa was created'
expect(@dest.history.to_s[0..text.length - 1]).to eq(text)
end
end
describe 'get_history_overview' do
it 'gets the history overview content from destinations' do
text = 'The earliest recorded inhabitants of this area of Africa were'
expect(@dest.history_overview.to_s[0..text.length - 1]).to eq(text)
end
end
end
| 7cab11784ad30e83e589e54405fa02f974657d98 | [
"Markdown",
"Ruby"
] | 9 | Ruby | rajcybage/xml_to_html | 59cce888270e9cdcbdc2c27821ff97b830acc463 | 14f3a7988aff58d810fd571b7f1deee0e8bc56f4 |
refs/heads/master | <repo_name>Semi96/BNetwork<file_sep>/BnetworkManagement/Controllers/MonitorController.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using BnetworkManagement.Models;
using BnetworkManagement.Models.AccountViewModels;
using BnetworkManagement.Models.BusinessViewModels;
using BnetworkManagement.Data;
using System.Text;
using System.Security.Cryptography;
using System.Net;
using System.IO;
using Microsoft.AspNetCore.Identity;
using Newtonsoft.Json;
using System.Data;
using Microsoft.AspNetCore.Authorization;
namespace BnetworkManagement.Controllers
{
public class MonitorController : Controller
{
private readonly ApplicationDbContext _context;
private readonly UserManager<ApplicationUser> _userManager;
public MonitorController(
UserManager<ApplicationUser> userManager,
ApplicationDbContext context)
{
_userManager = userManager;
_context = context;
}
[HttpPost]
public async Task<JsonResult> HiveOs()
{
try
{
string URL = "https://6cd5661f.ngrok.io/api/HiveOsStats/GetAverageStats";
System.Net.WebRequest webRequest = System.Net.WebRequest.Create(URL);
webRequest.Method = "GET";
webRequest.ContentType = "application/x-www-form-urlencoded";
// Stream reqStream = webRequest.GetRequestStream();
// string postData = ""; //you form data in get format
// byte[] postArray = Encoding.ASCII.GetBytes(postData);
//reqStream.Write(postArray, 0, postArray.Length);
// reqStream.Close();
// var x = await webRequest.GetResponseAsync();
StreamReader sr = new StreamReader( webRequest.GetResponse().GetResponseStream());
string Result = sr.ReadToEnd();
return Json(Result);
}
catch (Exception e)
{
var dataData = new { averageGpuTemp = 69.20, averageGpuFanSpeed = 70.02 };
return Json(dataData);
}
}
[HttpPost]
public async Task<JsonResult> GetAccreditationsAsync()
{
var user = await _userManager.GetUserAsync(User);
// var userId = user.Id;
var contextData = _context.MiningContractProgress.Where(x => x.AppUser == user).Select(a => new {date = a.Date.ToString("ddd, dd MMM yyyy HH':'mm':'ss "), CryptoMined = Math.Round(a.CryptoMined , 8), currency = a.RentalPurchaseContract.Currency.ToString(), dateShort = a.Date.ToShortDateString() }).ToList();
var dataData = new { data = contextData };
var json = JsonConvert.SerializeObject(dataData);
return Json(dataData);
}
[HttpPost]
public JsonResult GetMessages()
{
var contextData = _context.Messages.Where(x => x.Status == MessageStatus.Posted).Select(a => new { a.MessageString }).ToList();
var dataData = new { data = contextData };
var json = JsonConvert.SerializeObject(dataData);
return Json(dataData);
}
public async Task<JsonResult> GetUserWalletAsync()
{
var user = await _userManager.GetUserAsync(User);
_context.Entry(user).Reference(s => s.Wallet).Load();
var walletKey = user.Wallet.WalletKey;
var returnJson = new { data = walletKey };
var json = JsonConvert.SerializeObject(returnJson);
return Json(returnJson);
}
[HttpPost]
public async Task<JsonResult> GetWithdrawsAsync()
{
var user = await _userManager.GetUserAsync(User);
// var userId = user.Id;
var contextData = _context.UserTransactions.Where(x => x.AppUser == user).Select(a => new { date = a.Date.ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'"), cryptoDelivered = Math.Round(a.CryptoRequested, 8), currency = "Ethereum" }).ToList();
var dataData = new { data = contextData };
var json = JsonConvert.SerializeObject(dataData);
return Json(dataData);
}
[HttpPost]
public async Task<JsonResult> GetTransactionsAsync()
{
var user = await _userManager.GetUserAsync(User);
string purchaseDate;
string miningStatus;
string currency;
// var userId = user.Id;
var contextData = _context.RentalPurchaseContract.Where(x => x.AppUser == user).Select( a => new { a.MHAmount, purchaseDate = a.PurchaseDate.ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'"), currency = a.Currency.ToString(), miningStatus = a.Batch.Status.ToString() }).ToList();
var dataData = new { data = contextData };
var json = JsonConvert.SerializeObject(dataData);
return Json(dataData);
}
[Authorize]
public IActionResult MyRig()
{
return View();
}
public IActionResult Index()
{
return View();
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
<file_sep>/BnetworkManagement/Models/UserWallet.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace BnetworkManagement.Models
{
public class UserWallet
{
[Key]
public int WalletId { get; set; }
public string WalletKey { get; set; }
public Currencies Currency { get; set; }
}
}
<file_sep>/BnetworkManagement/Models/AdminViewModels/UsersListViewModel.cs
using BnetworkManagement.Models.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BnetworkManagement.Models.AdminViewModels
{
public class UsersListViewModel
{
public IEnumerable<ApplicationUser> Users {get;set;}
public PagingInfo PagingInfo { get; set; }
public int? CurrentStatus { get; set; }
}
}
<file_sep>/BnetworkManagement/Models/BatchStatus.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BnetworkManagement.Models
{
public enum BatchStatus
{
Waiting,Pending,Mining,StoppedMining
}
}
<file_sep>/README.md
# BNetwork
This repo contains the bulk of the source code used to create the BNetwork Inc. web application. Credentials have been removed, along with all wwwroot files in the interest of space.
<file_sep>/BnetworkManagement/Models/Messages.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace BnetworkManagement.Models
{
public class Messages
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int MessageId { get; set; }
public string MessageString { get; set; }
public MessageStatus Status { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public string PostedBy { get; set; }
}
}
<file_sep>/BnetworkManagement/Models/Address.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BnetworkManagement.Models
{
public class Address
{
public int AddressId { get; set; }
public string Addressline1 { get; set; }
public string Addressline2 { get; set; }
public string City { get; set; }
public string Province { get; set; }
public string ZipCode { get; set; }
public string Country { get; set; }
}
}
<file_sep>/BnetworkManagement/Models/DiscountCode.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace BnetworkManagement.Models
{
public class DiscountCode
{
[Key]
public int DiscountId { get; set; }
public string Code { get; set; }
public DiscountType DiscountType { get; set; }
public decimal DiscountAmount { get; set; }
public int NumTimesUsed { get; set; }
}
}
<file_sep>/BnetworkManagement/Models/MiningContractProgress.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace BnetworkManagement.Models
{
public class MiningContractProgress
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
//[Timestamp]
public int ProgressId { get; set; }
public RentalPurchaseContract RentalPurchaseContract { get; set; }
public ApplicationUser AppUser { get; set; }
public double CryptoMined { get; set; }
public DateTime Date { get; set; }
}
}
<file_sep>/BnetworkManagement/Controllers/AdminController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BnetworkManagement.Data;
using BnetworkManagement.Extensions;
using BnetworkManagement.Models;
using BnetworkManagement.Models.AdminViewModels;
using BnetworkManagement.Models.ViewModels;
using BnetworkManagement.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
namespace BnetworkManagement.Controllers
{
[Authorize(Roles = "Admin")]
public class AdminController : Controller
{
private ApplicationDbContext _context;
private readonly UserManager<ApplicationUser> _userManager;
public int PageSize = 2;
private readonly IEmailSender _emailSender;
public AdminController(ApplicationDbContext context, UserManager<ApplicationUser> userManager, IEmailSender emailSender)
{
_context = context;
_userManager = userManager;
_emailSender = emailSender;
}
[TempData]
public string StatusMessage { get; set; }
public IActionResult Messages()
{
return View();
}
[HttpPost]
public JsonResult getMessages()
{
// var userId = user.Id;
var contextData = _context.Messages.Select(a => new { a.MessageId,a.MessageString, Status= a.Status.ToString(), StartDate = a.StartDate.ToString("ddd, dd MMM yyyy HH':'mm':'ss "), EndDate = a.EndDate.ToString("ddd, dd MMM yyyy HH':'mm':'ss "), a.PostedBy }).ToList();
var dataData = new { data = contextData };
var json = JsonConvert.SerializeObject(dataData);
return Json(dataData);
}
[HttpPost]
public JsonResult getOneMessage(int messageId)
{
// var userId = user.Id;
var contextData = _context.Messages.Where(x => x.MessageId == messageId).Select(a => new { a.MessageId, a.MessageString, Status = a.Status, StartDate = a.StartDate, EndDate = a.EndDate, a.PostedBy }).ToList();
var dataData = new { data = contextData };
var json = JsonConvert.SerializeObject(dataData);
return Json(dataData);
}
[HttpPost]
public IActionResult updateMessage( Messages editMessage)
{
//var contextData = _context.Messages.Where(x => x.MessageId == messageId).Select(a => new { a.MessageId, a.MessageString, Status = a.Status, StartDate = a.StartDate, EndDate = a.EndDate, a.PostedBy }).ToList();
_context.Messages.Update(editMessage);
_context.SaveChanges();
return Redirect("Messages");
}
[HttpPost]
public IActionResult removeMessage(int messageId)
{
//var contextData = _context.Messages.Where(x => x.MessageId == messageId).Select(a => new { a.MessageId, a.MessageString, Status = a.Status, StartDate = a.StartDate, EndDate = a.EndDate, a.PostedBy }).ToList();
var newMessage = new Messages
{
MessageId = messageId
};
_context.Messages.Attach(newMessage);
_context.Messages.Remove(newMessage);
_context.SaveChanges();
return View("Messages");
}
[HttpPost]
public IActionResult addMessage(Messages message)
{
try
{
var newMessage = new Messages
{
MessageString = message.MessageString,
Status = message.Status,
StartDate = message.StartDate,
EndDate = message.StartDate,
PostedBy = message.PostedBy
};
_context.Add(newMessage); ;
_context.SaveChanges();
return View("Messages");
}
catch (Exception e)
{
return View("Messages");
}
}
public async Task<IActionResult> Index(string userStatus,string currentFilter, int? page)
{
ViewData["StatusFilter"] = userStatus;
if ((userStatus!=null)){
page = 1;
}
else
{
userStatus = currentFilter;
}
switch (userStatus)
{
case "0":
ViewData["StatusFilter"] = "NoStatus";
break;
case "1":
ViewData["StatusFilter"] = "Activated";
break;
case "2":
ViewData["StatusFilter"] = "Pending";
break;
case "3":
ViewData["StatusFilter"] = "Mining";
break;
case "4":
ViewData["StatusFilter"] = "StppedMining";
break;
case "5":
ViewData["StatusFilter"] = "Banned";
break;
default:
ViewData["StatusFilter"] = "NoStatus";
break;
}
var appUsers = from u in _context.AppUsers select u;
if (!String.IsNullOrEmpty(userStatus))
{
appUsers = appUsers.Where(u => (u.Status.ToString()) == ViewData["StatusFilter"].ToString());
}
int pageSize = 2;
return View(await PaginatedList<ApplicationUser>.CreateAsync(appUsers.AsNoTracking(), page ?? 1, pageSize));
//return View(await appUsers.ToListAsync());
}
[HttpGet]
[Authorize]
public async Task<IActionResult> RPCs()
{
var rpcs = _context.RentalPurchaseContract.Include(p => p.AppUser).Include(p => p.Batch);
return View(rpcs.AsEnumerable());
}
[HttpGet]
public IActionResult EditRPCs(int Id)
{
RentalPurchaseContract contract = _context.RentalPurchaseContract.Include(p => p.AppUser).Include(p => p.Batch).FirstOrDefault(u => u.TransactionId == Id);
return View(contract);
}
[HttpPost]
public async Task<IActionResult> EditRPCs(RentalPurchaseContract model)
{
if (ModelState.IsValid)
{
var rpc = _context.RentalPurchaseContract.Where(p => p.TransactionId == model.TransactionId).FirstOrDefault();
rpc.PurchaseDate = model.PurchaseDate;
rpc.MHAmount = model.MHAmount;
rpc.UnitPrice = model.UnitPrice;
rpc.DiscountCode = model.DiscountCode;
rpc.Taxrate = model.Taxrate;
rpc.PaymentToken = model.PaymentToken;
rpc.Currency = model.Currency;
var user = _context.AppUsers.Where(p => p.Id == model.AppUser.Id).FirstOrDefault();
var batch = _context.MiningInventory.Where(p => p.BatchId == model.Batch.BatchId).FirstOrDefault();
rpc.AppUser = user;
rpc.Batch = batch;
_context.Update(rpc);
await _context.SaveChangesAsync();
StatusMessage = "RPC successfully changed"; // wont work unless implemented in view
return RedirectToAction(nameof(RPCs));
}
return View(model);
}
[HttpGet]
[Authorize]
public async Task<IActionResult> Batches()
{
var batches = _context.MiningInventory.AsEnumerable();
return View(batches);
}
[HttpGet]
[Authorize]
public async Task<IActionResult> AvailableCapacity()
{
var capacity = _context.AvailableCapacity.FirstOrDefault();
return View(capacity);
}
[HttpGet]
[Authorize]
public async Task<IActionResult> Accredits()
{
var accredits = _context.MiningContractProgress.Include(p => p.AppUser).Include(p => p.RentalPurchaseContract);
return View(accredits.AsEnumerable());
}
[HttpGet]
[Authorize]
public async Task<IActionResult> Withdrawals()
{
var withdrawals = _context.UserTransactions.Include(p => p.AppUser);
return View(withdrawals.AsEnumerable());
}
[HttpGet]
[Authorize]
public async Task<IActionResult> Accounting()
{
return View();
}
[HttpGet]
[Authorize]
public async Task<IActionResult> DiscountCodes()
{
var batches = _context.DiscountCodes.AsEnumerable();
return View(batches);
}
public IActionResult List(int listPage = 1)
=> View(new UsersListViewModel
{
Users = _context.Users.OrderBy(u => u.Id).Skip((listPage - 1) * PageSize).Take(PageSize),
PagingInfo = new PagingInfo
{
CurrentPage = listPage,
ItemsPerPage = PageSize,
TotalItems = _context.Users.Count()
}
});
//public ViewResult List(int? userStatus, int listPage = 1)
// => View(new UsersListViewModel
// {
// Users = _context.Users
// .Where(u => userStatus == null || (int)u.Status == userStatus)
// .OrderBy(u => u.Id).Skip((listPage - 1) * PageSize).Take(PageSize),
// PagingInfo = new PagingInfo
// {
// CurrentPage = listPage,
// ItemsPerPage = PageSize,
// TotalItems = _context.Users.Count()
// },
// CurrentStatus = userStatus
// });
//public IActionResult List(int displayStatus, int listPage = 1)
//{
// ViewData["StatusFilter"] = displayStatus;
// var UsersToDisplay = new UsersListViewModel {
// Users = from u in _context.AppUsers select u,
// PagingInfo = new PagingInfo
// {
// CurrentPage = listPage,
// ItemsPerPage = PageSize,
// TotalItems = _context.Users.Count()
// }
// };
// if (displayStatus != 10)
// {
// UsersToDisplay.CurrentStatus = displayStatus;
// UsersToDisplay = new UsersListViewModel
// {
// Users = from u in _context.AppUsers select u,
// PagingInfo = new PagingInfo
// {
// CurrentPage = listPage,
// ItemsPerPage = PageSize,
// TotalItems = _context.Users.Count()
// }
// };
// //Users = Users.Where(u => (int)u.Status == userStatus);
// return View(UsersToDisplay);
// }
// return View();
//}
public async Task<IActionResult> Details(string Id)
{
var Appuser = _context.AppUsers.Include(u => u.UserAddress)
.AsNoTracking()
.FirstOrDefault(u => u.Id == Id);
return View(Appuser);
}
[HttpGet]
public IActionResult Edit(string Id) =>
View(_context.AppUsers
.FirstOrDefault(u => u.Id == Id));
//[HttpPost]
//public IActionResult EditUser(ApplicationUser model)
//{
// if (ModelState.IsValid)
// {
// _context.Entry(model).State = EntityState.Modified;
// _context.SaveChanges();
// return RedirectToAction("list");
// }
// return View(model);
//}
public async Task<IActionResult> SendUsersEmail(string subject, string message)
{
try
{
var users = _context.AppUsers.ToList();
foreach (var user in users)
{
await _emailSender.SendEmailAsync(user.Email, subject, message);
}
return Json(new { success = true, responseText = "email was successful" });
}
catch (Exception)
{
return Json(new { success = true, responseText = "email was unsuccessful" });
}
finally
{
}
}
public async Task<IActionResult> AccreditUserCrypto(double CryptoReceived)
{
try
{
// var totalmined = _context.Entry("UserTotalMined");
var batches = _context.MiningInventory.Where(p => p.Status == BatchStatus.Mining && DateTime.Compare(DateTime.Now, p.MiningStartDate.AddDays(1)) >= 0);
// Mining Status && we are past the Mining Start Date
var totalMhCapacity = 0;
foreach (var batch in batches)
{
totalMhCapacity += batch.MHAmount;
// re-assigning of status if one day from reaching MiningEndDate
if (DateTime.Compare(DateTime.Now.AddDays(1), batch.MiningEndDate) >= 0)
{
batch.Status = BatchStatus.StoppedMining;
}
}
foreach (var batch in batches)
{
var batch_id = batch.BatchId;
var rentalContracts = _context.RentalPurchaseContract.Where(p => p.Batch.BatchId == batch_id);
foreach (var contract in rentalContracts)
{
_context.Entry(contract).Reference(s => s.AppUser).Load();
var MhPurchased = contract.MHAmount;
var user = contract.AppUser;
var CryptoToAccredit = CryptoReceived * MhPurchased / totalMhCapacity;
// add new field in MiningContractProgress
var miningContractProgress = new MiningContractProgress
{
RentalPurchaseContract = contract,
AppUser = user,
CryptoMined = CryptoToAccredit,
Date = DateTime.Now
};
_context.Add(miningContractProgress);
}
}
await _context.SaveChangesAsync();
return Json(new { success = true, responseText = "distribution was successful" });
}
catch (Exception e)
{
return Json(new { success = true, responseText = "distribution failed." });
throw e;
}
}
}
}<file_sep>/BnetworkManagement/Models/MiningInventory.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace BnetworkManagement.Models
{
public class MiningInventory
{
[Key]
public int BatchId { get; set; }
public DateTime OrderDate { get; set; }
public DateTime MiningStartDate { get; set; }
public DateTime MiningEndDate { get; set; }
public int MHAmount { get; set; }
public BatchStatus Status { get; set; }
public Currencies Currency { get; set; }
//public List<RentalPurchaseContract> RentalContracts { get; set; }
}
}
<file_sep>/BnetworkManagement/Controllers/CryptoController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Nethereum.Web3;
using Nethereum.Web3.Accounts;
using Nethereum.Util;
using Nethereum.Hex.HexConvertors.Extensions;
using System.Security.Cryptography;
using System.Text;
using System.IO;
using System.Net;
using Coinbase;
using Coinbase.Wallet;
using Coinbase.Models.Transaction;
using Microsoft.AspNetCore.Authorization;
namespace BnetworkManagement.Controllers
{
public class CryptoController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
[Authorize]
public IActionResult Main()
{
var client = new Client("", "");
// var account = client.GetAccount("").Balance;
var transactions = client.GetTransactions("");
//var transaction = client.SendMoney("", new TransactionSendModel
//{
// To = "",
// Amount = 0.002M,
// Currency = "ETH",
//});
// var balance = account.Balance;
return View();
}
}
}<file_sep>/BnetworkManagement/Extensions/ActionDisposable.cs
using System;
namespace BnetworkManagement.Extensions
{
public sealed class ActionDisposable : IDisposable
{
//useful for making arbitrary IDisposable instances
//that perform an Action when Dispose is called
//(after a using block, for instance)
private Action action;
public ActionDisposable(Action action)
{
this.action = action;
}
public void Dispose()
{
var action = this.action;
if (action != null)
{
action();
}
}
}
}<file_sep>/BnetworkManagement/Data/SeedData.cs
using BnetworkManagement.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BnetworkManagement.Data
{
public static class IdentitySeedData
{
private const string adminUser = "Administrator";
private const string adminEmail = "";
private const string adminPassword = "";
private const string adminRole = "Admin";
public static async void EnsurePopulated(IApplicationBuilder app)
{
IServiceScopeFactory scopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
using (IServiceScope scope = scopeFactory.CreateScope())
{
RoleManager<IdentityRole> roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
UserManager<ApplicationUser> userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
ApplicationUser user = await userManager.FindByEmailAsync(adminEmail);
if (user == null)
{
user = new ApplicationUser();
user.Email = adminEmail;
user.UserName = adminEmail;
await userManager.CreateAsync(user, adminPassword);
}
//UserManager<IdentityUser> userManager = app.ApplicationServices.GetRequiredService<UserManager<IdentityUser>>();
//IdentityUser user = await userManager.FindByIdAsync(adminEmail);
//if (user == null)
//{
// user = new IdentityUser(adminEmail);
// await userManager.CreateAsync(user, adminPassword);
//}
IdentityResult roleResult;
var roleExist = await roleManager.RoleExistsAsync(adminRole);
if (!roleExist)
{
//create the roles and seed them to the database: Question 1
roleResult = await roleManager.CreateAsync(new IdentityRole(adminRole));
}
await userManager.AddToRoleAsync(user, adminRole);
}
}
}
}
<file_sep>/BnetworkManagement/Data/ApplicationDbContext.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using BnetworkManagement.Models;
using Microsoft.AspNetCore.Identity;
namespace BnetworkManagement.Data
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
builder.Entity<IdentityUser>().ToTable("BnetUser");
builder.Entity<ApplicationUser>().ToTable("BnetUser");
builder.Entity<IdentityRole>().ToTable("BnetRole");
builder.Entity<IdentityUserRole<string>>().ToTable("BnetUserRole");
builder.Entity<IdentityUserClaim<string>>().ToTable("BnetUserClaim");
builder.Entity<IdentityUserLogin<string>>().ToTable("BnetUserLogin");
builder.Entity<IdentityRoleClaim<string>>().ToTable("BnetRoleClaim");
builder.Entity<IdentityUserToken<string>>().ToTable("BnetUserToken");
}
public DbSet<ApplicationUser> AppUsers { get; set; }
public DbSet<Capacity> AvailableCapacity { get; set; }
public DbSet<MiningInventory> MiningInventory { get; set; }
public DbSet<RentalPurchaseContract> RentalPurchaseContract { get; set; }
public DbSet<UserTransaction> UserTransactions { get; set; }
public DbSet<MiningContractProgress> MiningContractProgress { get; set; }
public DbSet<DiscountCode> DiscountCodes { get; set; }
public DbSet<Messages> Messages { get; set; }
}
}
<file_sep>/BnetworkManagement/Models/UserStatus.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BnetworkManagement.Models
{
public enum UserStatus
{
NoStatus, Activated, Pending, Mining, StoppedMining, Banned
}
}
<file_sep>/BnetworkManagement/Extensions/EmailSenderExtensions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using BnetworkManagement.Services;
namespace BnetworkManagement.Services
{
public static class EmailSenderExtensions
{
public static Task SendEmailConfirmationAsync(this IEmailSender emailSender, string email, string link)
{
return emailSender.SendEmailAsync(email, "BNetwork - Confirm your email",
$"Thank you for signing up with BNetwork!" +
$"To complete your registration, please click the following link: <a href='{HtmlEncoder.Default.Encode(link)}'>Complete Registration</a> ");
}
}
}
<file_sep>/BnetworkManagement/Services/StripeSettings.cs
using Microsoft.Extensions.Options;
using SendGrid;
using SendGrid.Helpers.Mail;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BnetworkManagement.Services
{
public class StripeSettings
{
public string SecretKey { get; set; }
public string PublishableKey { get; set; }
}
}
<file_sep>/BnetworkManagement/Views/Admin/AdminNavPages.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
namespace BnetworkManagement.Views.Admin
{
public static class AdminNavPages
{
public static string ActivePageKey => "ActivePage";
public static string Index => "Index";
public static string RPCs => "RPCs";
public static string Batches => "Batches";
public static string AvailableCapacity => "AvailableCapacity";
public static string Accounting => "Accounting";
public static string DiscountCodes => "DiscountCodes";
public static string IndexNavClass(ViewContext viewContext) => PageNavClass(viewContext, Index);
public static string RPCsNavClass(ViewContext viewContext) => PageNavClass(viewContext, RPCs);
public static string BatchesNavClass(ViewContext viewContext) => PageNavClass(viewContext, Batches);
public static string AvailableCapacityNavClass(ViewContext viewContext) => PageNavClass(viewContext, AvailableCapacity);
public static string AccountingNavClass(ViewContext viewContext) => PageNavClass(viewContext, Accounting);
public static string DiscountCodesNavClass(ViewContext viewContext) => PageNavClass(viewContext, DiscountCodes);
public static string PageNavClass(ViewContext viewContext, string page)
{
var activePage = viewContext.ViewData["ActivePage"] as string;
return string.Equals(activePage, page, StringComparison.OrdinalIgnoreCase) ? "active" : null;
}
public static void AddActivePage(this ViewDataDictionary viewData, string activePage) => viewData[ActivePageKey] = activePage;
}
}
<file_sep>/BnetworkManagement/Models/AccountViewModels/CompleteRegisterViewModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace BnetworkManagement.Models.AccountViewModels
{
public class CompleteRegisterViewModel
{
[Required]
[StringLength(100)]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[StringLength(100)]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[StringLength(30)]
public string Gender { get; set; }
[Required]
[Display(Name = "Date of Birth")]
[DataType(DataType.Date)]
public DateTime BirthDate { get; set; }
[Required]
[StringLength(100)]
[Display(Name = "Address (Line 1)")]
public string Addressline1 { get; set; }
[StringLength(100)]
[Display(Name = "Address (Line 2)")]
public string Addressline2 { get; set; }
[Required]
[StringLength(100)]
public string City { get; set; }
[Required]
[StringLength(100)]
[Display(Name = "State/Province")]
public string Province { get; set; }
[Required]
[StringLength(100)]
[Display(Name = "Zip/Postal Code")]
public string ZipCode { get; set; }
[Required]
[StringLength(100)]
public string Country { get; set; }
[Phone]
[StringLength(20)]
[Display(Name = "Phone Number")]
public string PhoneNumber { get; set; }
}
}
<file_sep>/BnetworkManagement/Models/DiscountType.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BnetworkManagement.Models
{
public enum DiscountType
{
Percent, DollarAmount
}
}
<file_sep>/BnetworkManagement/Models/Currencies.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BnetworkManagement.Models
{
public enum Currencies
{
Ethereum/*,Bitcoin,Monero*/
}
}
<file_sep>/BnetworkManagement/Controllers/PaymentController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Options;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.DataAnnotations;
using Stripe;
using BnetworkManagement.Services;
using BnetworkManagement.Models.AccountViewModels;
using BnetworkManagement.Models;
using Microsoft.AspNetCore.Identity;
using BnetworkManagement.Data;
using Microsoft.Extensions.Logging;
using BnetworkManagement.Models.BusinessViewModels;
using Coinbase;
using Coinbase.Wallet;
using Coinbase.Models.Transaction;
using System.Threading;
using BnetworkManagement.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System.Data;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace BnetworkManagement.Controllers
{
public class PaymentController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly IEmailSender _emailSender;
private readonly ILogger _logger;
private readonly ApplicationDbContext _context;
static AsyncLocker<string> userLock = new AsyncLocker<string>();
static HashSet<string> withdrawSet = new HashSet<string>();
public PaymentController(
UserManager<ApplicationUser> userManager,
IEmailSender emailSender,
ILogger<AccountController> logger,
ApplicationDbContext context)
{
_userManager = userManager;
_emailSender = emailSender;
_logger = logger;
_context = context;
}
// GET: /<controller>/
public IActionResult Index()
{
return View();
}
public IActionResult Error()
{
return View();
}
//[HttpGet]
//[Authorize]
//public async Task<IActionResult> Checkout(CheckoutViewModel model, string callback)
//{
// return View(model);
//}
[HttpGet]
[Authorize]
public async Task<IActionResult> Checkout(int mh, string discount)
{
var MHrate =_context.AvailableCapacity.Find(1).UnitPrice;
var user = await _userManager.GetUserAsync(User);
CheckoutViewModel model = new CheckoutViewModel
{
MegaHashPurchased = mh,
MegaHashPriceRate = MHrate, // get value from database
NoTaxPurchasePrice = MHrate * mh,
Cryptocurrency = Currencies.Ethereum
};
// MUST explicity load the user Wallet
_context.Entry(user).Reference(s => s.Wallet).Load();
var wallet = user.Wallet;
if (wallet != null)
{
model.WalletPublicKey = wallet.WalletKey;
}
if (discount != null)
{
var discountCode = _context.DiscountCodes.Where(p => p.Code == discount);
if (discountCode != null)
{
// check that it is not the own users discount code
_context.Entry(user).Reference(s => s.AffiliateCode).Load();
var UserAffiliateCode = user.AffiliateCode.Code;
if (discount == UserAffiliateCode)
{
// do not apply discount
}
else if (discountCode.Last().DiscountType == DiscountType.Percent)
{
model.DiscountCode = discount;
model.DiscountApplied = true;
model.NoTaxPurchasePrice = model.NoTaxPurchasePrice * (decimal)(1 - discountCode.Last().DiscountAmount/100);
}
else if (discountCode.Last().DiscountType == DiscountType.DollarAmount)
{
model.DiscountCode = discount;
model.DiscountApplied = true;
model.NoTaxPurchasePrice -= discountCode.Last().DiscountAmount;
}
}
}
// IMPLEMENT TAX BASED ON LOCATION
_context.Entry(user).Reference(s => s.UserAddress).Load();
var userAddress = user.UserAddress.Country;
if (userAddress != null)
{
if (user.UserAddress.Country.Trim().ToUpper().Equals("CANADA") || user.UserAddress.Country.Equals("CAN"))
{
model.PurchaseTaxRate = 0.13M;
model.NetPurchaseTax = model.PurchaseTaxRate * model.NoTaxPurchasePrice;
model.TotalPurchasePrice = model.NoTaxPurchasePrice + model.NetPurchaseTax;
}
else
{
model.PurchaseTaxRate = 0;
model.NetPurchaseTax = 0;
model.TotalPurchasePrice = model.NoTaxPurchasePrice;
}
}
return View(model);
}
public ActionResult CheckoutComplete()
{
return View("CheckoutComplete");
}
//[HttpPost]
//[Authorize]
//public async Task<IActionResult> ApplyDiscountCode(CheckoutViewModel model)
//{
// var code = model.DiscountCode;
//}
[HttpPost]
[Authorize]
public async Task<IActionResult> Checkout(CheckoutViewModel model)
{
try
{
if (!ModelState.IsValid)
{
return View(Index());
}
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{user.Id}'.");
}
// explicity load the user Wallet
_context.Entry(user).Reference(s => s.Wallet).Load();
var wallet = user.Wallet;
if (wallet == null && model.WalletPublicKey != null)
{
// user does not have an associated Wallet but will create one now
user.Wallet = new UserWallet
{
Currency = model.Cryptocurrency,
WalletKey = model.WalletPublicKey
};
}
// pull BatchOrder information from DB
var batch = _context.MiningInventory.LastOrDefault();
if (batch == null || batch.Status != BatchStatus.Waiting)
{
var newBatch = new MiningInventory
{
Currency = model.Cryptocurrency,
MHAmount = 0,
Status = BatchStatus.Waiting
};
_context.Add(newBatch);
batch = newBatch;
//await _context.SaveChangesAsync();
//batch = _context.MiningInventory.LastOrDefault();
}
batch.MHAmount += model.MegaHashPurchased;
if (batch.MHAmount > 1750)
{
// close status of previous batch
batch.Status = BatchStatus.Pending;
batch.OrderDate = DateTime.Now;
// create new batch
var newBatch = new MiningInventory
{
Currency = Currencies.Ethereum,
MHAmount = 0,
Status = BatchStatus.Waiting
};
_context.Add(newBatch);
}
DiscountCode discount = null;
if (model.DiscountCode != null)
{
var discountCode = _context.DiscountCodes.Where(p => p.Code == model.DiscountCode);
discount = discountCode.LastOrDefault();
if (discount != null)
{
++discount.NumTimesUsed;
_context.DiscountCodes.Update(discount);
}
}
var order = new RentalPurchaseContract
{
AppUser = user,
PurchaseDate = DateTime.Now,
MHAmount = model.MegaHashPurchased,
UnitPrice = model.MegaHashPriceRate,
DiscountCode = discount,
Taxrate = (double)model.PurchaseTaxRate,
PaymentToken = model.PaymentToken,
Currency = model.Cryptocurrency,
Batch = batch
};
_context.Add(order);
//user.Status = UserStatus.Pending;
return Json(new { success = true });
}
catch (Exception e)
{
return Json(new { success = false });
}
}
[HttpPost]
[Authorize]
public async Task<IActionResult> Charge(string walletKey, string stripeEmail, string stripeToken, CheckoutViewModel model)
{
using (var transaction = _context.Database.BeginTransaction(IsolationLevel.RepeatableRead))
{
try
{
var cap = _context.AvailableCapacity.Find(1);
cap.TotalMegaHashAvailable -= model.MegaHashPurchased;
_context.Update(cap);
_context.SaveChanges();
model.PaymentToken = stripeToken;
model.WalletPublicKey = walletKey;
var customers = new StripeCustomerService();
var charges = new StripeChargeService();
var customer = customers.Create(new StripeCustomerCreateOptions
{
Email = stripeEmail,
SourceToken = stripeToken
});
var charge = charges.Create(new StripeChargeCreateOptions
{
Amount = (int) (model.TotalPurchasePrice * 100), // cents
Description = "BNETWORK MINING CONTRACT",
ReceiptEmail = stripeEmail,
Currency = "usd",
CustomerId = customer.Id
});
if (charge.Paid || charge.Status == "succeeded")
{
JsonResult result = (JsonResult) await Checkout(model);
_logger.LogInformation("User Purchase Complete");
_context.SaveChanges();
transaction.Commit();
return Json(new { success = true });
}
else
{
return Json(new { success = false });
}
}
catch (Exception e)
{
return Json(new { success = false });
}
}
}
public async Task<IActionResult> RequestWithdraw(double requestAmount, Currencies currency)
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{user.Id}'.");
//return Json(new { success = false });
}
//using (await userLock.LockAsync(user.Id))
//{
bool userRequestExists = withdrawSet.Contains(user.Id);
if (userRequestExists)
{
return null;
}
else
{
try
{
withdrawSet.Add(user.Id);
if (requestAmount < 0.05)
{
return Json(new { success = false, responseText = "withdrawal request failed; the minimum withdrawal amount is 0.05 ETH." });
}
if (!await CheckUserBalance(requestAmount, user))
{
// error; you do not have sufficient funds to support this withdrawal
return Json(new { success = false, responseText = "withdrawal request failed; you do not have sufficient funds for this withdrawal." });
}
else if (!await CheckWithdrawTime(user))
{
// error; you may only withdraw once every 24h
return Json(new { success = false, responseText = "withdrawal request failed; you may only withdraw once every 24 hours." });
}
else
{
var SendCurrency = "";
switch (currency)
{
case Currencies.Ethereum:
SendCurrency = "ETH";
break;
//case Currencies.Bitcoin:
// SendCurrency = "BTC";
// break;
//case Currencies.Monero:
// SendCurrency = "XMR";
// break;
default:
return Json(new { success = false, responseText = "withdrawal request failed- unable to resolve currency; please contact us for more information" });
}
var client = new Client("", "");
var fee = 0.0005; // get current fee in realtime
var deliverAmount = requestAmount - fee;
//if (!await CheckCoinbaseBalance(requestAmount, client))
//{
// // error; we seem to not have enough funds in our wallet to support this withdraw
// withdrawSet.Remove(user.Id);
// return Json(new { success = false, responseText = "withdrawal request failed- unable to transfer; please contact us for more information." });
//}
var withdrawal = new UserTransaction
{
AppUser = user,
CryptoRequested = requestAmount,
CryptoDelivered = deliverAmount,
FeePaid = fee,
Date = DateTime.Now
};
_context.Add(withdrawal);
// call wallet API to send funds-- CAUTION: Executing SendMoney() will send real funds to designated address
//var transaction = client.SendMoney("", new TransactionSendModel
//{
// To = user.Wallet.WalletKey.ToString(),
// Amount = (decimal) (deliverAmount),
// Currency = "ETH",
// Description = "Withdrawal from Bnetwork Mining.",
//});
await _context.SaveChangesAsync();
return Json(new { success = true, responseText = "withdrawal was successful" });
}
}
catch (Exception)
{
return Json(new { success = true, responseText = "withdrawal request failed" });
}
finally
{
withdrawSet.Remove(user.Id);
}
//}
}
}
public async Task<bool> CheckCoinbaseBalance(double requestAmount, Client client)
{
//var client = new Client("", "");
var accountBalance = client.GetAccount("").Balance.Amount;
if ((double) accountBalance - requestAmount >= 0.001)
{
return true;
}
else
{
// may not have enough funds to pay for fee of the transfer
// must notify Bnet admins to resolve this error
return false;
}
}
public async Task<bool> CheckWithdrawTime(ApplicationUser user)
{
var withdrawals = _context.UserTransactions.Where(p => p.AppUser == user);
var lastWithdraw = withdrawals.LastOrDefault();
if (lastWithdraw == null)
{
return true;
}
else
{
var lastWithdrawTime = lastWithdraw.Date;
return DateTime.Compare(DateTime.Now, lastWithdrawTime.AddDays(1)) >= 0;
}
}
public async Task<bool> CheckUserBalance(double requestAmount, ApplicationUser user)
{
// derive User Balance: Sum of MiningContract Accredits - Sum of User Withdrawals
var CryptoAccredits = _context.MiningContractProgress.Where(p => p.AppUser == user);
var TotalAccredited = 0.0;
foreach (var accredit in CryptoAccredits)
{
TotalAccredited += accredit.CryptoMined;
}
var UserWithdrawals = _context.UserTransactions.Where(p => p.AppUser == user);
var TotalWithdrawn = 0.0;
foreach (var withdrawal in UserWithdrawals)
{
TotalWithdrawn += withdrawal.CryptoRequested;
}
var UserBalance = TotalAccredited - TotalWithdrawn;
if (UserBalance - requestAmount < 0)
{
return false;
}
else
{
return true;
}
}
public void RejectChanges()
{ // can only remove items from a List when iterating in reverse
foreach (var entry in _context.ChangeTracker.Entries().Reverse())
{
switch (entry.State)
{
case EntityState.Modified:
entry.State = EntityState.Unchanged;
break;
case EntityState.Added:
entry.State = EntityState.Detached;
break;
case EntityState.Deleted:
entry.Reload();
break;
default: break;
}
}
}
}
}
<file_sep>/BnetworkManagement/Models/ManageViewModels/ChangeWalletViewModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace BnetworkManagement.Models.ManageViewModels
{
public class ChangeWalletViewModel
{
[Required]
[Display(Name = "Wallet Public Key")]
[StringLength(200)]
public string WalletKey { get; set; }
[Required]
[Display(Name = "Confirm Wallet Public Key")]
[StringLength(200)]
public string ConfirmWalletKey { get; set; }
[Required]
[Display(Name = "Wallet Currency")]
public Currencies Currency { get; set; }
public bool DoesWalletExist { get; set; }
public string StatusMessage { get; set; }
[Required]
[Display(Name = "New Wallet Public Key")]
[StringLength(200)]
public string NewWalletKey { get; set; }
[Required]
[Display(Name = "New Wallet Currency")]
public Currencies NewCurrency { get; set; }
}
}
<file_sep>/BnetworkManagement/Data/ApplicationUserManager.cs
using BnetworkManagement.Models;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BnetworkManagement.Data
{
//public class ApplicationUserManager: UserManager<ApplicationUser>
//{
// public ApplicationUserManager(IUserStore<ApplicationUser> store)
// : base(store)
// {
// }
// public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
// {
// ///Calling the non-default constructor of the UserStore class
// var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
// /// Rest of the class ...
// }
//}
}
<file_sep>/BnetworkManagement/Models/BusinessViewModels/CheckoutViewModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace BnetworkManagement.Models.BusinessViewModels
{
public class CheckoutViewModel
{
[Display(Name = "MH/s")]
public int MegaHashPurchased { get; set; }
[Display(Name = "Cryptocurrency")]
public Currencies Cryptocurrency { get; set; }
[Display(Name = "Price per MH/s")]
public decimal MegaHashPriceRate { get; set; }
[Display(Name = "Tax Rate")]
public decimal PurchaseTaxRate { get; set; }
[Display(Name = "Net Purchase Tax")]
public decimal NetPurchaseTax { get; set; }
[Display(Name = "Total Purchase Price")]
public decimal TotalPurchasePrice { get; set; }
[Display(Name = "No-Tax Purchase Price")]
public decimal NoTaxPurchasePrice { get; set; }
[Display(Name = "Discount Code")]
[StringLength(100)]
public string DiscountCode { get; set; }
public bool DiscountApplied { get; set; }
[Display(Name = "Wallet Public Key")]
[StringLength(200)]
public string WalletPublicKey { get; set; }
[Display(Name = "Stripe payment token")]
public string PaymentToken { get; set; }
[Display(Name = "Purchase Date")]
public DateTime PurchaseDate { get; set; }
}
}
<file_sep>/BnetworkManagement/Models/UserTransaction.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace BnetworkManagement.Models
{
public class UserTransaction
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int TransactionId { get; set; }
public ApplicationUser AppUser { get; set; }
public double CryptoRequested { get; set; }
public double CryptoDelivered { get; set; }
public double FeePaid { get; set; }
public DateTime Date { get; set; }
}
}
<file_sep>/BnetworkManagement/Models/MessageStatus.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BnetworkManagement.Models
{
public enum MessageStatus
{
Waiting,Posted,Archived
}
}
<file_sep>/BnetworkManagement/Models/BusinessViewModels/MiningShopViewModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace BnetworkManagement.Models.BusinessViewModels
{
public class MiningShopViewModel
{
[Display(Name = "Available Capacity")]
public int TotalMegaHashAvailable { get; set; }
[Display(Name = "Minable Currencies")]
public Currencies MineableCurrencies { get; set; }
[Display(Name = "Price per MH/s")]
public decimal MegaHashPriceRate { get; set; }
}
}
| 7eb50a369a250574ce5d2bfdc303d10b31df647c | [
"Markdown",
"C#"
] | 29 | C# | Semi96/BNetwork | 7e384504c863374bef4f5e21a991fb5f994ab2db | c16d7542f78d773051d328fb99ace12226c1139a |
refs/heads/master | <file_sep>library(readr)
library(dplyr)
library(ggplot2)
getwd()
setwd("D:/Ivan/_flash backup 2014/SINP/Группировка/2017 Группировка/radmonitoring/radmonitoring/analisys/percentile")
# import data from Monte-Carlo text files
data<-read.table("data/det2/electr_A_L32_det2.dat", header = TRUE)
# defining primary energy intervals
breaks <- c(0, 150, 350, 600,1000,2000,4000,10000,Inf)
labels <- c('c0','c1','c2','c3','c4','c5', 'c6','c7')
# make factor column on primary energy
data$bins <- cut(data$E0.keV, breaks, labels= labels)
get_interval <- function(x=5, data, channel){
c=(apply(data[(data$bins == channel)&(data$CF == 1),2:5], # drop all not used info
2, # apply to columns
quantile, # applyed function
probs=c(x, 100-x)/100)) #variated quantile number
return(c)
}
get_interval(5,data, labels[1])
<file_sep>#source('comparators.R')
setwd("D:/Simulink")
library("Hmisc", lib.loc="C:/Program Files/R/R-3.1.2/library")
# тренировка на L14 -------------------------------------------------------
datap<-read.table("data/det2/proton_A_L14_det2.dat", header = TRUE)
# datap<-read.table("data/det2/proton_A_L17_det2.dat", header = TRUE)
# выбор восстановление разных спектров ------------------------------------------
# datap<-read.table("data/alldet/proton_A_L14.dat", header = TRUE)
# datap<-read.table("data/alldet/proton_A_L17.dat", header = TRUE)
# datap<-read.table("data/alldet/proton_A_L32.dat", header = TRUE)
# кросс тест с электронами
# datap<-read.table("data/det2/electr_A_L32_det2.dat", header = TRUE)
#summary(datap)
#filter zero and high data?
# sum(datap$CF > 0 & (datap$E0.keV > leftE0[1]) & (datap$E0.keV < rightE0[1]), na.rm=TRUE)
breaks <- c(0,2000,4000,9000,15000,30000,53000,100000,160000, Inf)
datap$bins <- cut(datap$E0.keV, breaks, labels=c('c0','c1','c2','c3','c4','c5','c6','c7','c8'))
# initial <- cut(datap$E0.keV, breaks)
# table(initial)
# initial spectrum --------------------------------------------------------
pr <- vector();
ch <- vector();
pr14 <- vector();
pr17 <- vector();
pr32 <- vector();
pr14 <- c(12554154.51,
24209263.53,
16530605.37,
13781462.77,
7892377.961,
8285838.076,
5616662.113,
6259257.997 )
pr17 <- c(37582161.48,
34101229.37,
9438270.918,
2879011.92,
336511.7328,
132327.8831,
51262.6717,
36986.07984)
pr32 <- c(47540815.31,
9296707.318,
854260.5702,
189565.6698,
13628.3297,
2126.082993,
95.34004452,
0)
errr <- vector();
errr <- c(0.027777778,
0.171428571,
0.038461538,
0.041666667,
0.80952381,
0.368421053,
0.6,
0.038461538)
# отбор каналов по 5-95 ---------------------------------------------------
#
# proton<-datap[((datap$CF > 0) & (datap$bins == "c1")), ]
# channel<-datap[((datap$dE.det1>120)&datap$dE.det1<1489)&
# ((datap$dE.det2>532)&datap$dE.det2<3020)&
# ((datap$dE.det3>-1)&datap$dE.det3<800)&
# ((datap$dE.det4>-1)&datap$dE.det4<200),]
# pr[1] <- nrow(proton)
# ch[1] <- nrow(channel)/ 0.75
proton<- datap[((datap$CF > 0) & (datap$bins == "c2")), ]
channel<- datap[((datap$dE.det1>120)&datap$dE.det1<706)&
((datap$dE.det2>3251)&datap$dE.det2<8019)&
((datap$dE.det3>-1)&datap$dE.det3<800)&
((datap$dE.det4>-1)&datap$dE.det4<200),]
pr[2] <- nrow(proton)
ch[2] <- nrow(channel)
proton<-datap[((datap$CF > 0) & (datap$bins == "c3")), ]
channel<-datap[((datap$dE.det1>120)&datap$dE.det1<387)&
((datap$dE.det2>3218)&datap$dE.det2<7076)&
((datap$dE.det3>955)&datap$dE.det3<10723)&
((datap$dE.det4>-1)&datap$dE.det4<200),]
pr[3] <- nrow(proton)
ch[3] <- nrow(channel)
proton<-datap[((datap$CF > 0) & (datap$bins == "c4")), ]
channel<-datap[((datap$dE.det1>120)&datap$dE.det1<257)&
((datap$dE.det2>1416)&datap$dE.det2<3696)&
((datap$dE.det3>6157)&datap$dE.det3<26549)&
((datap$dE.det4>-1)&datap$dE.det4<200),]
pr[4] <- nrow(proton)
ch[4] <- nrow(channel)
# proton<-datap[((datap$CF > 0) & (datap$bins == "c5")), ]
# channel<-datap[((datap$dE.det1>120)&datap$dE.det1<165)&
# ((datap$dE.det2>186)&datap$dE.det2<2443)&
# ((datap$dE.det3>5055)&datap$dE.det3<49295)&
# ((datap$dE.det4>-1)&datap$dE.det4<200),]
# pr[5] <- nrow(proton)
# ch[5] <- nrow(channel)
# proton<-datap[((datap$CF > 0) & (datap$bins == "c6")), ]
# channel<-datap[((datap$dE.det1>-1)&datap$dE.det1<173)&
# ((datap$dE.det2>150)&datap$dE.det2<2459)&
# ((datap$dE.det3>800)&datap$dE.det3<46385)&
# ((datap$dE.det4>200)&datap$dE.det4<6731),]
# pr[6] <- nrow(proton)
# ch[6] <- nrow(channel)
# proton<-datap[((datap$CF > 0) & (datap$bins == "c7")), ]
# channel<-datap[((datap$dE.det1>1)&datap$dE.det1<93)&
# ((datap$dE.det2>150)&datap$dE.det2<1168)&
# ((datap$dE.det3>800)&datap$dE.det3<25635)&
# ((datap$dE.det4>200)&datap$dE.det4<1912),]
# pr[7] <- nrow(proton)
# ch[7] <- nrow(channel)
# proton<-datap[((datap$CF > 0) & (datap$bins == "c8")), ]
# channel<-datap[((datap$dE.det1>-1)&datap$dE.det1<52)&
# ((datap$dE.det2>75)&datap$dE.det2<718)&
# ((datap$dE.det3>800)&datap$dE.det3<15688)&
# ((datap$dE.det4>200)&datap$dE.det4<1236),]
# pr[8] <- nrow(proton)
# ch[8] <- nrow(channel)
#
# отбор каналов по 25-75 --------------------------------------------------
proton<-datap[((datap$CF > 0) & (datap$bins == "c1")), ]
channel<-datap[((datap$dE.det1>753)&datap$dE.det1<1128)&
((datap$dE.det2>1214)&datap$dE.det2<2563)&
((datap$dE.det3>-1)&datap$dE.det3<800)&
((datap$dE.det4>-1)&datap$dE.det4<200),]
pr[1] <- nrow(proton)
ch[1] <- nrow(channel)
# proton<-datap[((datap$CF > 0) & (datap$bins == "c2")), ]
# channel<-datap[((datap$dE.det1>381)&datap$dE.det1<571)&
# ((datap$dE.det2>4363)&datap$dE.det2<6963),]
# proton<-datap[((datap$CF > 0) & (datap$bins == "c3")), ]
# channel<-datap[((datap$dE.det1>231)&datap$dE.det1<332)&
# ((datap$dE.det2>3912)&datap$dE.det2<5511)&
# ((datap$dE.det3>4171)&datap$dE.det3<8686),]
# proton<-datap[((datap$CF > 0) & (datap$bins == "c4")), ]
# channel<-datap[((datap$dE.det1>116)&datap$dE.det1<215)&
# ((datap$dE.det2>2144)&datap$dE.det2<3012)&
# ((datap$dE.det3>13447)&datap$dE.det3<21379),]
proton<-datap[((datap$CF > 0) & (datap$bins == "c5")), ]
channel<-datap[((datap$dE.det1>-1)&datap$dE.det1<123)&
((datap$dE.det2>1287)&datap$dE.det2<1692)&
((datap$dE.det3>30440)&datap$dE.det3<42433),]
pr[5] <- nrow(proton)
ch[5] <- nrow(channel)
# proton<-datap[((datap$CF > 0) & (datap$bins == "c6")), ]
# channel<-datap[((datap$dE.det1>-1)&datap$dE.det1<120)&
# ((datap$dE.det2>770)&datap$dE.det2<1079)&
# ((datap$dE.det3>22761)&datap$dE.det3<35141)&
# ((datap$dE.det4>200)&datap$dE.det4<3455),]
#
# pr[6] <- nrow(proton)
# ch[6] <- 0.47*nrow(channel)
proton<-datap[((datap$CF > 0) & (datap$bins == "c7")), ]
channel<-datap[((datap$dE.det1>-1)&datap$dE.det1<54)&
((datap$dE.det2>545)&datap$dE.det2<927)&
((datap$dE.det3>16030)&datap$dE.det3<22122)&
((datap$dE.det4>1022)&datap$dE.det4<1629),]
pr[7] <- nrow(proton)
ch[7] <- nrow(channel)
proton<-datap[((datap$CF > 0) & (datap$bins == "c8")), ]
channel<-datap[
((datap$dE.det1>-1)&datap$dE.det1<29)&
((datap$dE.det2>291)&datap$dE.det2<518)&
((datap$dE.det3>8781)&datap$dE.det3<13487)&
((datap$dE.det4>452)&datap$dE.det4<980),]
pr[8] <- nrow(proton)
ch[8] <- nrow(channel)
# отбор каналов по по классике --------------------------------------------
# channel[2]<-nrow(datap[((datap$dE.det1>300)&datap$dE.det1<800)&
# ((datap$dE.det2>3000)&datap$dE.det2<8000)&
# ((datap$dE.det3>-1)&datap$dE.det3<3000),])
#
# channel[3]<-nrow(datap[((datap$dE.det1>250)&datap$dE.det1<420)&
# ((datap$dE.det2>4000)&datap$dE.det2<8000)&
# ((datap$dE.det3>2000)&datap$dE.det3<10000),])
#
# channel[4]<-nrow(datap[((datap$dE.det1>0)&datap$dE.det1<300)&
# ((datap$dE.det2>2500)&datap$dE.det2<4000)&
# ((datap$dE.det3>12000)&datap$dE.det3<30000),])
#
#
# proton<-datap[((datap$CF > 0) & (datap$bins == "c5")), ]
# channel<-datap[((datap$dE.det1>-1)&datap$dE.det1<200)&
# ((datap$dE.det2>1000)&datap$dE.det2<2000)&
# ((datap$dE.det3>30000)&datap$dE.det3<50000),]
# pr[5] <- nrow(proton)
# ch[5] <- nrow(channel)
# channel[5]<-nrow(datap[((datap$dE.det1>0)&datap$dE.det1<200)&
# ((datap$dE.det2>1000)&datap$dE.det2<2000)&
# ((datap$dE.det3>30000)&datap$dE.det3<50000),])
#
proton<-datap[((datap$CF > 0) & (datap$bins == "c6")), ]
channel<-datap[((datap$dE.det1>-1)&datap$dE.det1<200)&
((datap$dE.det2>-1)&datap$dE.det2<2000)&
((datap$dE.det3>20000)&datap$dE.det3<50000)&
((datap$dE.det4>2000)&datap$dE.det4<15000),]
pr[6] <- nrow(proton)
ch[6] <- nrow(channel)
# channel[6]<-nrow(datap[((datap$dE.det1>0)&datap$dE.det1<200)&
# ((datap$dE.det2>000)&datap$dE.det2<2000)&
# ((datap$dE.det3>20000)&datap$dE.det3<50000)&
# ((datap$dE.det4>2000)&datap$dE.det4<15000),])
#
# proton<-datap[((datap$CF > 0) & (datap$bins == "c7")), ]
# channel<-datap[((datap$dE.det1>-1)&datap$dE.det1<200)&
# ((datap$dE.det2>-1)&datap$dE.det2<2000)&
# ((datap$dE.det3>20000)&datap$dE.det3<50000)&
# ((datap$dE.det4>2000)&datap$dE.det4<5000),]
# channel[7]<-nrow(datap[((datap$dE.det1>0)&datap$dE.det1<200)&
# ((datap$dE.det2>000)&datap$dE.det2<2000)&
# ((datap$dE.det3>20000)&datap$dE.det3<50000)&
# ((datap$dE.det4>2000)&datap$dE.det4<5000),])
#
# channel[8]<-nrow(datap[((datap$dE.det1>120)&datap$dE.det1<200)&
# ((datap$dE.det2>000)&datap$dE.det2<1000)&
# ((datap$dE.det3>15000)&datap$dE.det3<30000)&
# ((datap$dE.det4>1000)&datap$dE.det4<2500),])
#
# channel[9]<-nrow(datap[((datap$dE.det1>500)&datap$dE.det1<1500)&
# ((datap$dE.det2>200)&datap$dE.det2<4500),])
# effectiveness switch ----------------------------------------------------
# training switch
# comment uncomment!
x = data.frame( names=c('p1','p2','p3','p4','p5','p6','p7','p8'),pr14, ch)
eff = x$ch/x$pr14;
x = data.frame( names=c('p1','p2','p3','p4','p5','p6','p7','p8'),pr17, ch)
x$ch = ceil(x$ch/eff)
mymat <- t(x[-1])
colnames(mymat) <- x[, 1]
# barplot(mymat, beside = TRUE, legend.text=c('пад.','рег.'))
mymat<-mymat[,1:6]
barx <-barplot(mymat,
ylim=c(0.1, max(x$ch)+max(x$pr32)),
log='y',
legend.text=c('пад.','рег.'),
beside = TRUE,
xpd=FALSE,
main='Восстановление спектра L=3.2',
ylab='N, частиц',
xlab='Номер канала')
box()
#standard error
er<- x$ch*errr + x$ch/sqrt(ch)
#error bars
arrows(barx[2,],mymat[2,]+er, barx[2,], mymat[2,], angle=90, code=1)
arrows(barx[2,],mymat[2,]-er, barx[2,], mymat[2,], angle=90, code=1)
#legend (after making the plot, indicate where the legend has
#to come with the mouse)
# legend(locator(1),c(levels(z)),fill=c(1:w),bty="n",cex=0.8)
# barplot(x, main="Car Distribution by Gears and VS",
# xlab="Number of Gears", col=c("darkblue","red"),
# legend = rownames(names), beside=TRUE)
# barplot ( ch, space=1, width=0.5, names.arg=c('c1','c2','c3','c4','c5','c6','c7','c8'), col='red')
# barplot ( pr, col='blue',space=1,width=0.5,offset = 0.5, add = TRUE, beside= TRUE)
# print (nrow(channel)/nrow(proton))
# print("primary proton")
# print (nrow(proton))
# print(summary(proton))
# print("conditional channel")
# print (nrow(channel))
# print(summary(channel))
# channel$bins <- cut(channel$E0.keV, breaks, labels=c('c0','c1','c2','c3','c4','c5','c6','c7','c8'))
# channel_target<-channel[((channel$CF > -1) & (channel$bins == "c7")), ]
# print (nrow(channel_target)/nrow(channel))#уровень сепарации<file_sep>install.packages("devtools")
library("devtools")
devtools::install_github("klutometis/roxygen")
library(roxygen2)
setwd("D:\Ivan\_flash backup 2014\SINP\Группировка\2017 Группировка\radmonitoring\radmonitoring\analisys\percentile")
create("cats")<file_sep>С точки зрения статискики постановка задачи сводится к нахождению классификатора, удовлетворяющего целям поиска потоков зарегистрированных частиц в интересующих интервалах энергий основываясь только на данных энерговыделений в детекторах прибора. Для поиска токого классификатора можно взять за основу регрессионную модель либо воспользоваться обычными методами построения классификаторов. Использование обоих методов осложнено наличием не нормального распределения случайных величин энерговыделений в детекторах.
Для тяжелых частиц реальное распределение энерговыделений хорошо описывается ионизационными потерями в детекторах (по формуле Бете-Блоха), а флуктуации энерговыделений подчиняются зависимости Ландау [http://nuclphys.sinp.msu.ru/ihem/ihem02.htm]. При увеличении толщины детектора распредление Ландау переходит в гауссово. Рассматриваемый детектор составлен из набора тонких и толстых детекторов. Для электронов потери энергии не описываются только ионизационными потрыми, поэтому влияние флуктуаций сильнее. Классификатор можно построить на основе деревьев принятия решений, но в конкретно взятом случае можно получить решение с помошью
При построении регрессионной модели мы предполагаем наличие функции, адекватно представляющую физическую суть измерения первичной энергии частицы. Однако учитывая сложную зависимость флуктуаций энерговыделения требуется использовать робастные регрессионные методы.
В нашем случае $\hat{\theta} $ точечная оценка (эстиматор) первичной энергии заряженной частицы строится на основе распределения энерговыделений в $X_1,\ldots, X_n$:
$\hat{\theta} = \hat{\theta}(X_1,\ldots, X_n)$ или в других обозначениях:
$\hat{E} = \hat{E}(dE_1,dE_2,dE_3,dE_4)$
1. выбор энергетических каналов будущего телескопа, минимума чувствительности(0,001) и селективности(0,5?)
2. получение первого приближения порогов энерговыдений(2575 или 595), исходя из фильтрованных последовательностей(убрать нули).
3. проба применения порогов для получения эффективности каналов
4. повторное применение отбора по измененным персентилям ->шаг алгоритма
5. проба применения порогов для получения эффективности каналов->шаг алгоритма
6. проба на других последовательностях
7. проба на реальных данных с макета прибора
В перспективе возможен просто переход на робастные регрессионные методы, но все равно желетельно подготавливать тренировочные данные: фильтровать нулевые энерговыделения. https://stats.idre.ucla.edu/r/dae/robust-regression/ https://www.rdocumentation.org/packages/robustbase/versions/0.1-2/topics/ltsReg Можно воспользоваться просто медианной регрессией для каждого канала, как развитие метода персентилей.
<file_sep>#ifndef MuelPhyslist_h
#define MuelPhyslist_h 1
#include "G4ProcessManager.hh"
#include "G4ParticleTypes.hh"
#include "G4VPhysicsConstructor.hh"
#include "globals.hh"
//#include "G4VUserPhysicsList.hh"
class MuelPhyslist : public G4VPhysicsConstructor
{
public:
MuelPhyslist(const G4String& name ="EM");
virtual ~MuelPhyslist();
protected:
// these methods construct particles
void ConstructBosons();
void ConstructLeptons();
void ConstructBarions();
// these methods construct physics processes and register them
void ConstructGeneral();
void ConstructEM();
// Construct particle and physics
void ConstructParticle();
void ConstructProcess();
// Construct particle and physics
// void ConstructParticle();
// void ConstructProcess();
};
#endif
/*
protected:
// these methods construct particles
void ConstructBosons();
void ConstructLeptons();
void ConstructBarions();
// these methods construct physics processes and register them
void ConstructGeneral();
void ConstructEM();
// Construct particle and physics
void ConstructParticle();
void ConstructProcess();
*/
<file_sep>Название проекта
================
Разработка методов оптимизации характеристик спектрометров энергичных заряженных
частиц околоземного космического пространства.
Научная дисциплина
------------------
основной код 02-140 Космические лучи
# Ключевые слова
мониторинг радиационной обстановки, космическое излучение, спектрометр заряженных частиц, математическое моделирование
Аннотация, публикуемая на сайте Фонда (не более 0,5 стр., в том числе кратко – актуальность, уровень значимости и научная новизна исследования; ожидаемые результаты и их значимость; аннотация будет опубликована на сайте Фонда, если Проект получит поддержку)
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Для оценки радиационных условий в околоземном пространстве используются модели пространственно-энергетических распределений потоков протонов и электронов радиационных поясов Земли, такие как АЕ8/AP8 и AE9/AP9. Такие модели создаются по результатам радиационного мониторинга околоземного космического пространства, в том числе, с помощью спектрометров заряженных частиц. Для калибровки и подбора параметров геометрии таких систем используются методы математического моделирования и статистического анализа. Однако системный подход к решению задачи оптимизации параметров спектрометров в настоящее время отсутствует. Данный проект направлен на разработку методики и создание комплекса программ для подбора параметров спектрометров, а также выбора энергетических каналов с оптимальными энергетическим разрешением и чувствительностью. В результате выполнения проекта будет создан программный комплекс, облегчающий проектирование спектрометров заряженных частиц и дозиметров радиационных условий, предназначенных для использования на космических аппаратах. Помимо оптимизации геометрических параметров и энергетических каналов детекторов, разрабатываемая методика может быть использована для повышения точности измерения параметров потоков заряженных частиц в околоземном пространстве.
Содержание Проекта
==================
Описание фундаментальной научной задачи, на решение которой направлено исследование.
------------------------------------------------------------------------------------
Радиационный мониторинг околоземного космического пространства осуществляется с помощью спектрометров заряженных частиц. Сложность создания универсального устройства для радиационного мониторинга обусловлена многокомпонентностью потоков ионизирующего излучения и неоднородностью радиационных условий в околоземном пространстве. Для проектирования спектрометров требуется оптимизировать параметры, влияющие на их характеристики, для каждой целевой орбиты спутников. В предлагаемом проекте происходит поиск максимума энергетического разрешения и чувствительности спектрометров, состоящих из телескопа полупроводниковых и сцинтилляционных детекторов. Решение данной задачи позволит разработать системный подход к проектированию спектрометров заряженных частиц для изучения радиационной обстановки околоземного пространства. Также применение новых методов позволит решить разнородные данные
Актуальность исследования
-------------------------
При прохождении потока заряженных частиц через детекторы, входящих в состав спектрометра, потери энергии отдельных частиц испытывают флуктуации, обусловленные статистической природой процесса ионизации, причем при регистрации электронов вследствие их малой массы статистические флуктуации удельных потерь энергии значительно больше, чем для протонов. Поэтому для достижения необходимой точности измерений необходимо проводить математическое моделирование энерговыделения в детекторах. Статистические методы обработки полученных в результате численного моделирования данных позволяют уточнить величины порогов прибора и определить эффективность регистрации в отдельных энергетических каналах. Существующий подход к требует большого объема расчетов, в особенности при необходимости варьирования параметров конструкции спектрометра. Поэтому разработка методики и создание комплекса программ для подбора параметров спектрометра и выбора энергетических каналов с оптимальными энергетическим разрешением и чувствительностью спектрометров является актуальной задачей.
Полученные с помощью предложенного программного комплексе расчетные данные могут использоваться при восстановлении по результатам измерений исходных энергетических спектров ионизирующих излучений.
Анализ современного состояния исследований в данной области (приводится обзор исследований в данной области со ссылками на публикации в научной литературе).
------------------------------------------------------------------------------------------------------------------------------------------------------------
Математическое моделирование широко применяется на всех этапах создания спектрометров заряженных частиц, предназначенных для использования в условиях космоса. В первую очередь, оно необходимо на этапе проектирования аппаратуры для выбора характеристик регистрирующих радиацию модулей исходя из поставленных экспериментальных задач [<NAME>. et al. 2008]. На последующих шагах разработки аппаратуры математические методы используются при верификации результатов калибровочных и градуировочных испытаний на источниках ионизирующих излучений (ИИ) и ускорителях заряженных частиц [Zeitlin C. et al. 2010, Luszik-Bhadra M. et al. 2008]. Также одним из основных применений является уточнение функции отклика прибора во время штатной работы [Zeitlin C. et al. 2010].
Среди математических методов моделирования взаимодействия ИИ и нейтральных излучений с материалами и детектирующими модулями приборов следует отметить наиболее часто используемые программные пакеты, основанные на методе Монте-Карло:
- GEANT4 комплекс программ для моделирования прохождения частиц через вещество [Allison J. et al. 2006], код общедоступен;
- PHITS Система расчета перемещений частиц и тяжелых ионов, разработана в Японии и Австрии [ Niita K. et al. 2006, Sato T. et al. 2006] ;
- FLUKA система широко использующаяся в CERN для широко круга задач и, в первую очередь, для медицинских приложений [Fasso A. et al.2003, Böhlen T.T. et al.2014].
Программа Geant4 разработана для нужд работы ЦЕРН и активно используется в ряде областей науки, медицины и технологии [Agostinelli S. et al. 2003]. В настоящее время существует несколько отдельных направлений развития Geant4 для решения задач микродозиметрии, физики высоких энергий, биологических аспектов радиационных воздействий и др. Кроме того создано несколько специализированных инженерных продуктов, использующих только ядро системы для расчетов распространения частиц. Основные направления: микродозиметрические исследования (GEMAT), применение к распространению и воздействия космического излучения (GRAS, PLANETOCOSMICS), оптимизация экранирования (MULASSIS [Lei F. et al. 2002] и SSAT). Для исследований характеристик приборов хорошо применим пакет Geant4 Radiation Analysis for Space (GRAS) [Santin G. et al. 2005]. В качестве входных данных здесь может быть использован GDML файл с описанием геометрической модели прибора. GRAS позволяет автоматически создавать комплексные источники космического излучения, соответствующие различным орбитам полета спутников. Перечисленные программы объединены в единый комплекс Spenvis, однако функционал программ и возможности для получения выходных данных ограничены. В отличие от пакетов проекта Spenvis, Geant4 регулярно обновляется, уточняются модели физических процессов и расширяются возможности моделирования. Поэтому для детального расчета параметров взаимодействия излучений с материалами детектирующих систем в данном проекте выбран программный комплекс Geant4.
Одной из наиболее распространенных расчетных задач, связанных с детекторами является расчет эффективности регистрации детектора. Эффективность регистрации детектора определяется его геометрическим фактором и особенностями взаимодействия исследуемых частиц с веществом детектора и является, по сути, функцией отклика детектора. Геометрический фактор детектора зависит от его геометрии и углового распределения регистрируемых частиц. Аналитическое вычисление геометрического фактора не учитывает его зависимости от типа и энергии излучения, в то время как математическое моделирование позволяет провести исследование влияния угловых и энергетических распределений. При моделировании методом Монте-Карло воспроизводятся особенности структуры детектора и параметров излучения, поэтому полученные значения отклика приборов включают в себя как геометрический фактор прибора, так и эффективность чувствительной области детектора, обусловленную процессами взаимодействия излучения с веществом. Например, с помощью GEANT4 в [Garrett, H.B. et al. 2011 ] были получены значения геометрических факторов в зависимости от энергии для детектора Galileo Heavy Ion Counter (HIC), проводившего измерения потоков ионов кислорода, углерода и серы в атмосфере Юпитера. В этом и других подобных исследованиях [Zhang, S. et al. 2014] математическое моделирование использовалось для получения геометрических факторов детекторов при регистрации протонов и более тяжелых ионов, а также для моделирования сигнала от заданных спектров излучения. Результаты моделирования позволяют более точно выбрать границы энергетических каналов прибора, использующихся для получения информации об исходной энергии зарегистрированных частиц, однако при регистрации электронов их потери энергии в детекторах испытывают значительные флуктуации из-за многократного рассеяния, поэтому выделение энергетических каналов для построения логической схемы спектрометра в этом случае затруднено [Власова Н.А. et al. 2013]. Кроме того, в электронных каналах может дополнительно происходить регистрация протонов, а в протонных - электронов. Оценка влияния этого фактора и разработка логических схем для разделения электронных и протонных событий также проводится на основе математического моделирования [Yando, K. et al. 2011]. Таким образом, восстановление спектров космических излучений по данным измерений является трудной задачей, для корректного решения которой необходим комплексный статистический анализ данных измерений и моделирования.
Отличительной особенностью данного проекта является направленность на разработку системного подхода к оптимизации чувствительности и энергетического разрешения спектрометров, состоящих из телескопа полупроводниковых и сцинтилляционных детекторов.
1. <NAME>. The Jovian Equatorial Heavy Ion Radiation Environment/ <NAME>, <NAME>, <NAME>, <NAME>, <NAME> // JPL Publication 11-16.– Pasadena, CA: Jet Propulsion Laboratory, National Aeronautics and Space Administration, 2011.– 42 p.
2. <NAME>., <NAME>., <NAME>. et al. Sci. China Earth Sci. (2014) 57: 2558. <https://doi.org/10.1007/s11430-014-4853-0>
3. <NAME>, <NAME>, <NAME>, <NAME>, Н.П. Чирская Метрологические характеристики детекторов космического излучения. Физика и химия обработки материалов. — 2013. — № 6. — С. 32–39.
4. <NAME>., <NAME>, <NAME>, and <NAME> (2011), A Monte Carlo simulation of the NOAA POES Medium Energy Proton and Electron Detector instrument, J. Geophys. Res., 116, A10231, doi:10.1029/2011JA016671.
5. <NAME>. et al. The Mars Science Laboratory ( MSL ) Mission // WRMISS. 2008. P. 20.
6. <NAME>. et al. Space Radiation Dosimetry with the Radiation Assessment Detector ( RAD ) on the Mars Science Laboratory ( MSL ) // WRMISS,. 2010. P. 22.
7. <NAME>. et al. Electronic personal neutron dosemeters for energies up to 100 MeV: Calculations using the PHITS code // Radiat. Meas. 2008. Vol. 43, № 2–6. P. 1044–1048.
8. <NAME>. et al. Geant4 developments and applications // IEEE Trans. Nucl. Sci. 2006. Vol. 53, № 1. P. 270–278.
9. <NAME>. et al. PHITS-a particle and heavy ion transport code system // Radiat. Meas. 2006. Vol. 41, № 9–10. P. 1080–1090.
10. Sato T. et al. Applicability of particle and heavy ion transport code PHITS to the shielding design of spacecrafts // Radiat. Meas. 2006. Vol. 41, № 9–10. P. 1142–1146.
11. <NAME>. et al. The physics models of FLUKA: status and recent development // arXiv. 2003. Vol. hep-ph. P. 10.
12. <NAME>.T. et al. The FLUKA Code: Developments and challenges for high energy and medical applications // Nucl. Data Sheets. 2014. Vol. 120. P. 211–214.
13. <NAME>. et al. GEANT4 - A simulation toolkit // Nucl. Instruments Methods Phys. Res. Sect. A Accel. Spectrometers, Detect. Assoc. Equip. 2003. Vol. 506, № 3. P. 250–303.
14. <NAME> al. MULASSIS: A Geant4-based multilayered shielding simulation tool // IEEE Transactions on Nuclear Science. 2002. Vol. 49 I, № 6. P. 2788–2793.
15. <NAME>. et al. GRAS: A general-purpose 3-D modular simulation tool for space environment effects analysis // IEEE Trans. Nucl. Sci. 2005. Vol. 52, № 6. P. 2294–2299.
## Цель и задачи Проекта
Цель проекта - разработка системного подхода к проектированию спектрометров заряженных частиц, использующихся для изучения радиационной обстановки в околоземном пространстве.
Задача проекта это создан программный комплекс, облегчающий проектирование спектрометров заряженных частиц.
Научная новизна исследования, заявленного в Проекте (формулируется новая научная идея, обосновывается новизна предлагаемой постановки и решения заявленной проблемы)
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
Научная новизна проекта обусловлена использованием комплекса математических методов для задачи оптимизации конструкции телескопических спектрометров, системный подход к решению которой в настоящее время отсутствует. Используемая методика моделирования регистрации ионизирующих излучений телескопическими детекторами обладает значительными преимуществами по сравнению с традиционно применяемой при проектировании детекторов методикой на основании средних потерь энергии. Выработка единого критерия на основе чувствительности и энергетического разрешения спектрометра позволит проводить оптимизацию конструкции детекторов на стадии их разработки.
Предлагаемые подходы и методы, и их обоснование для реализации цели и задачи исследований (Развернутое описание предлагаемого исследования; форма изложения должна дать возможность эксперту оценить новизну идеи Проекта, соответствие подходов и методов исследования поставленным целям и задачам, надежность получаемых результатов)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Математическое моделирование взаимодействия спектрометров с ионизирующими излучениями в данном проекте будет выполняться с помощью универсального и хорошо апробированного программного комплекса Geant4. В рамках проекта будет создан программный код, дающий возможность пользователю, не обладающему навыками работы с Geant4 и программирования на C++, легко изменять основные параметры детектирующей системы, такие как тип детектирующих элементов, материалы, из которых состоит детектор, количество и размер детектирующих элементов, геометрические размеры детектора. Такой подход позволит быстро изменять параметры исследуемой детектирующей системы для ее оптимизации и дальнейшей работы с данными.
Полученные расчетные данные далее анализируются с использованием методов статистического анализа. Данные содержат информацию об энергии исходных частиц (электронов или протонов), величинах выделенной в каждом детекторе энергии с учетом потерь энергии вторичных частиц, угле падения первичной частицы относительно продольной оси прибора, а также информацию о том, прошла ли исходная частица через коллиматор прибора. Для всех энергетических интервалов электронов и протонов анализируются статистические распределения по энерговыделениям в детекторах прибора. Распределения энерговыделений в детекторах прибора заранее неизвестна. В таких случаях для визуализации всего ансамбля событий в детекторах можно применять диаграммы размаха “boxplot” [<NAME>. 2010].
С использованием полученных распределений формируются критерии определения энергий первичных частиц. Эти критерии представляют собой совокупность интервалов энерговыделений первичных частиц с заданной исходной энергией в отдельных детекторах прибора. Интервалы энерговыделений выбираются с применением методов описательной статистики. Однако сформировать не перекрывающиеся интервалы энерговыделений, особенно для электронов, только по статистическим данным невозможно, так как величины энерговыделений частиц из разных энергетических каналов могут совпадать. Поэтому требуется разработка единого численного критерия который бы учитывал точность определения энергии во всех каналах прибора и чувствительность этих каналов. Единый численный критерий качества работы спектрометра позволит поставить и решить оптимизационную задачу улучшения качества работы спектрометров.
<NAME>., <NAME>. Data analysis and graphics using R – an example-based approach, third edition, Cambridge University Press, 2010, 549 p.
Ожидаемые результаты научного исследования и их научная и прикладная значимость.
--------------------------------------------------------------------------------
В результате выполнения проекта будет создан программный комплекс, облегчающий проектирование спектрометров заряженных частиц. Будет разработан единый критерий определения оптимальных характеристик телескопических спектрометров на основе таких параметров, как энергетическое разрешениеи чувствительность каналов прибора к протонам и электронам. Возможность динамического варьирования параметров детектора позволит упростить задачу поиска оптимальной конструкции спектрометров. Отличительной особенностью системы станет однозначность получаемых результатов по характеристикам моделируемых приборов радиационного мониторинга. В результате выполнения проекта будет разработан системный подход к проектированию спектрометров заряженных частиц, использующихся для изучения радиационной обстановки в околоземном пространстве. Данный программный комплекс будет полезен при разработке спектрометров заряженных частиц и дозиметров радиационных условий, предназначенных для использования на космических аппаратах. Также эта методика позволит создать точную систему для мониторинга радиационных условий в околоземном пространстве, заинтересованными потребителями данных этой системы могут быть Российские и иностранные космические агентства и собственники космических систем.
Общий план работ на весь срок реализации Проекта (форма представления информации должна дать возможность эксперту оценить реализуемость заявленного плана работы и риски его невыполнения; общий план реализации Проекта даётся с разбивкой по годам)
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
В 2018 году:
1. Разработка системы математического моделирования спектрометров заряженных частиц, включающая возможность динамического изменения параметров численного моделирования.
2. Разработка единого критерия на основе чувствительности и энергетического разрешения спектрометра для решения оптимизационной задачи.
3. Разработка системы анализа данных численного моделирования. Система должна включать получение единого численного критерия сравнения результатов моделирования для целей решения оптимизационной задачи.
4. Разработка модуля динамического изменения параметров спектрометра и моделируемого излучения.
В 2019 году:
1. Добавление возможности математического моделирования спектрометров с детекторами стрипового типа.
2. Расширение системы анализа результатов моделирования регистрации ионизирующих излучений для оптимизации конструкции спектрометров с стриповыми детекторами.
3. Адаптация разработанной методики оптимизации конструкции спектрометров для стриповых детекторов.
План работ на первый год реализации Проекта (план предоставляется с учетом содержания работ каждого из участников Проекта, предполагаемых поездок)
--------------------------------------------------------------------------------------------------------------------------------------------------
1. Разработка системы математического моделирования спектрометров заряженных частиц, включающая возможность динамического изменения параметров численного моделирования, в том числе:
- Изменение материалов конструкции;
- Изменение модели прибора (в том числе изменение числа и типа детекторов);
- Изменения падающего спектра заряженных частиц;
(Чирская Н.П.)
2. Разработка единого критерия на основе чувствительности и энергетического разрешения спектрометра для решения оптимизационной задачи. (Золотарев И.А., Чирская Н.П.)
3. Разработка системы анализа данных численного моделирования. Система должна включать получение единого численного критерия сравнения результатов моделирования для целей решения оптимизационной задачи. (Золотарев И.А.)
4. Разработка модуля динамического изменения параметров спектрометра и моделируемого излучения. (<NAME>., <NAME>.)
5. Подготовка статьи по результатам работ для публикации в рецензируемом журнале. (<NAME>.)
Ожидаемые научные результаты за первый год реализации Проекта (форма изложения должна дать возможность провести экспертизу результатов и оценить возможную степень выполнения заявленного в Проекте плана работы)
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
В результате выполнения проекта будет создан программный комплекс, облегчающий проектирование спектрометров заряженных частиц.
Будет разработан единый критерий определения оптимальных характеристик телескопических спектрометров на основе таких параметров, как энергетическое разрешение и чувствительность каналов прибора к протонам и электронам. Возможность динамического варьирования параметров детектора позволит упростить задачу поиска оптимальной конструкции спектрометров.
Отличительной особенностью системы станет однозначность получаемых результатов по характеристикам моделируемых приборов радиационного мониторинга. В результате выполнения проекта будет разработан системный подход к проектированию спектрометров заряженных частиц, использующихся для изучения радиационной обстановки в околоземном пространстве.
По результатам выполненных работ планируется публикация в рецензируемом журнале. Доклад результатов на конференции COSPAR 2018.
Имеющийся у коллектива научный задел по Проекту (указываются полученные результаты, разработанные программы и методы, экспериментальное оборудование, материалы и информационные ресурсы, имеющиеся в распоряжении коллектива для реализации Проекта)
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1. Коллектив имеет большой опыт решения различных задач, связанных с математическим моделированием процессов взаимодействия излучений с веществом с помощью Geant4, TRIM/SRIM, пакетов ресурса SPENVIS и др.
2. В настоящее время разработан и апробирован программный модуль на основе Geant4 для моделирования прохождения излучения через спектрометры с фиксированными параметрами геометрии.
3. Разработан программный модуль для анализа результатов моделирования отклика спектрометров при регистрации энергичных протонов и электронов. Данный модуль позволяет получать информацию о чувствительности каналов прибора к протонам и электронам, а также исследовать селективности каналов по энергии падающих частиц.
4. Создан прототип спектрометра для проекта многоярусной спутниковой группировки. Прототип позволяет проверить разрабатываемые методы моделирования и анализа спектрометров на экспериментальной установке.
Публикации (не более 15) участников коллектива, включая Руководителя проекта, наиболее близко относящиеся к Проекту за последние 5 лет (для каждой публикации при наличии указать ссылку в сети Интернет для доступа эксперта к аннотации или полному тексту публикации)
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1. <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. Numerical simulation of metrological characteristics of cosmic radiation detectors.*Inorganic Materials: Applied Research*, 8(2):222–228, 2017. [ [DOI](http://dx.doi.org/10.1134/S2075113317020241) ] (перевод <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. Численное моделирование метрологических характеристик детекторов космических излучений. *Перспективные материалы*, (11):16–24, 2016.)
2. Патент Спектрометр Энергичной Космической Радиации (СПЭР) (https://istina.msu.ru/patents/12100980/) Авторы: <NAME>, <NAME>, <NAME>, <NAME>, <NAME>; 2015149253, 17 ноября 2015г
3. <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. Создание группировки малых космических аппаратов для осуществления радиационного мониторинга в околоземном космическом пространстве. In *Исследования солнечно-земных связей: Материалы научной сессии Секции солнечно-земных связей Совета по космосу Российской академии наук, под ред. А. А. Петруковича*, pages 141–153. М.: ИКИ РАН, 2015.
4. <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. Optimization of measurements of the earth’s radiation belt particle fluxes. *Cosmic Research (English translation of Kosimicheskie Issledovaniya)*, 55(2):79–87, 2017. [ [DOI](http://dx.doi.org/10.1134/S0010952516060071) ] ( перевод <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. Оптимизация измерений потоков частиц радиационных поясов Земли. *Космические исследования*, 55(2):85–93, 2017. [ [DOI](http://dx.doi.org/10.7868/S002342061606008X) ])
5. <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. Operational radiation monitoring in near-earth space based on the system of multiple small satellites. *Cosmic Research (English translation of Kosimicheskie Issledovaniya)*, 53(6):423–429, 2015. [ [DOI](http://dx.doi.org/10.1134/S0010952515060039) ] ( перевод <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. Оперативный радиационный мониторинг в околоземном космическом пространстве на базе многоярусной группировки малых космических аппаратов. *Космические исследования*, 53(6):461–468, 2015. [ [DOI](http://dx.doi.org/10.7868/S0023420615060047) ])
6. <NAME>., <NAME>., <NAME>., <NAME>. Application of nuclear-physics methods in space materials science // Phys. At. Nucl. 2017. Vol. 80, № 4. P. 666–678. http://dx.doi.org/10.1134/S1063778817040172
7. <NAME>, <NAME>, <NAME>, <NAME>, Н.П. Чирская Метрологические характеристики детекторов космического излучения. Физика и химия обработки материалов. — 2013. — № 6. — С. 32–39.
<file_sep>//
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// -------------------------------------------------------------------
// $Id: DetectorConstruction.cc,v 1.1 2012-09-20 mraine Exp $
// -------------------------------------------------------------------
#include "DetectorConstruction.hh"
#include "G4SystemOfUnits.hh"
#include "G4Region.hh"
#include "G4ProductionCuts.hh"
#include "G4Tubs.hh"
#include "G4Box.hh"
#include "G4Cons.hh"
#include "G4LogicalBorderSurface.hh"
#include "G4LogicalSkinSurface.hh"
#include "G4OpticalSurface.hh"
#include "G4PhysicalConstants.hh"
#include "G4OpBoundaryProcess.hh"
#include "G4UnionSolid.hh"
#include "G4GDMLParser.hh"
#include "G04SensitiveDetector.hh"
#include "G4SDManager.hh"
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo....
DetectorConstruction::DetectorConstruction(const G4GDMLParser& parser)
:G4VUserDetectorConstruction(),fParser(parser)
//fPhysiWorld(NULL), fLogicWorld(NULL), fSolidWorld(NULL)
{}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo....
DetectorConstruction::~DetectorConstruction()
{}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo....
G4VPhysicalVolume* DetectorConstruction::Construct()
{
//DefineMaterials();
//return ConstructDetector();
fRegion = new G4Region("Detector");
G4ProductionCuts* cuts = new G4ProductionCuts();
G4double defCut = 10.*um;
cuts->SetProductionCut(defCut,"gamma");
cuts->SetProductionCut(defCut,"e-");
cuts->SetProductionCut(defCut,"e+");
cuts->SetProductionCut(defCut,"proton");
return fParser.GetWorldVolume();
G4cout << *(G4Material::GetMaterialTable()); // print the list of materials
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo....
void DetectorConstruction::DefineMaterials()
{
G4double a, z, density;
G4int nelements;
G4int number_of_atoms;
G4double fractionmass;
G4int ncomponents;
G4bool isotopes = false;
// Silicon is defined from NIST material database
G4NistManager * man = G4NistManager::Instance();
// G4Material * Si = man->FindOrBuildMaterial("G4_Si");
// Default materials in setup.
//fSiMaterial = man->FindOrBuildMaterial("G4_Si");
//fAlMaterial = man->FindOrBuildMaterial("G4_Al");
// vacuum
G4Element* N = new G4Element("Nitrogen", "N", z=7 , a=14.01*g/mole);
G4Element* O = new G4Element("Oxygen" , "O", z=8 , a=16.00*g/mole);
G4Element* C = new G4Element("Carbon", "C", z=6., a=12.01*g/mole);
G4Element* Cu = new G4Element("Copper" , "Cu" , z= 29., a= 63.54*g/mole);
G4Element* Mg = new G4Element("Magnesium" ,"Mg" , z= 12., a= 24.305*g/mole);
G4Element* Mn = new G4Element("Manganese" ,"Mn" , z= 25., a= 54.94*g/mole);
G4Element* Al = new G4Element("Aluminium" ,"Al" , z= 13., a= 26.98*g/mole);
G4Element* H = new G4Element("Hydrogen", "H", z=1 , a=1.01*g/mole);
G4Element* Si = new G4Element("Silicium", "Si", z=14 , a=28.086*g/mole);
man->FindOrBuildMaterial("G4_Si", isotopes);
man->FindOrBuildMaterial("G4_Fe", isotopes);
man->FindOrBuildMaterial("G4_Cu", isotopes);
man->FindOrBuildMaterial("G4_Ge", isotopes);
man->FindOrBuildMaterial("G4_Mo", isotopes);
man->FindOrBuildMaterial("G4_Ta", isotopes);
man->FindOrBuildMaterial("G4_W" , isotopes);
man->FindOrBuildMaterial("G4_Au", isotopes);
man->FindOrBuildMaterial("G4_Pb", isotopes);
man->FindOrBuildMaterial("G4_PLEXIGLASS", isotopes);
man->FindOrBuildMaterial("G4_SODIUM_IODIDE", isotopes);
man->FindOrBuildMaterial("G4_C", isotopes);
man->FindOrBuildMaterial("G4_CESIUM_IODIDE", isotopes);
man->FindOrBuildMaterial("G4_BRASS", isotopes);
air = new G4Material("Air", density=1.29*mg/cm3, nelements=2);
air->AddElement(N, 70.*perCent);
air->AddElement(O, 30.*perCent);
// vacuum
beam =
new G4Material("Vacuum", density= 1.e-8*g/cm3, nelements=1,
kStateGas, STP_Temperature, 2.e-5*bar);
beam->AddMaterial(air, fractionmass=1.);
G4Material* Dural =
new G4Material("Dural" , density= 2.700*g/cm3, ncomponents=4);
Dural->AddElement(Al, fractionmass=0.936);
Dural->AddElement(Cu, fractionmass=0.044);
Dural->AddElement(Mg, fractionmass=0.015);
Dural->AddElement(Mn, fractionmass=0.005);
// Used in geometry materials
gapMaterial = beam;
DuralMaterial = Dural;
// DuralMaterial = man->FindOrBuildMaterial("G4_BRASS", isotopes);
Cone_dielectric = man->FindOrBuildMaterial("G4_PLEXIGLASS", isotopes);
ScintMaterial = man->FindOrBuildMaterial("G4_CESIUM_IODIDE", isotopes);
// Chose main material of detector's walls
// Dural with Tungsten variant
Wall_material = man->FindOrBuildMaterial("G4_BRASS", isotopes);
Shell_material = man->FindOrBuildMaterial("G4_W", isotopes);
// Brass without tungsten variant
// Wall_material = man->FindOrBuildMaterial("G4_BRASS", isotopes);
// Shell_material = man->FindOrBuildMaterial("G4_PLEXIGLASS", isotopes);
G4cout << *(G4Material::GetMaterialTable()) << G4endl;
}
/*
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo....
G4VPhysicalVolume* DetectorConstruction::ConstructDetector()
{
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo....
// WORLD VOLUME
fWorldSizeX = 25.*cm;
fWorldSizeY = 25.*cm;
fWorldSizeZ = 25.*cm;
//World volume size
// MainZ = 95.*mm;
MainZ = 0.*mm;
MainR = 63.*mm; //!!
// First detector - Si
Det1Z = 0.04*mm;
Det1R = 4.*mm;
//
FoilGapZ = 4*mm;
// vacuum between foil and detector D1
Gap1Z = 17.68*mm;
Gap1R = 4.0*mm;
// vacuum between detectors D1 and D2
Gap2Z = 5.0*mm;
Gap2R = 4.*mm;
// vacuum between detectors D2 and D3
Gap3Z = 5.0*mm;
Gap3R = 7.5*mm;
// vacuum between detectors D3 and D4 (lower)
Gap4Z = 5.0*mm;
Gap4R = 7.5*mm;
// distance between detectors D3 and D4 (plex)
// Gap5Z = 6.*mm;
// Gap5R = 7.*mm;
// Outer foil, equivalent to 20 um of Si
FoilZ = 20.*um;
FoilR = 4.0*mm;
// фотодиод за 3-м детектором
FotoZ = 300.*um;
FotoR = 7.5*mm;
// Second detector - Si
Det2Z = 0.5*mm;
Det2R = 4.*mm;
// Third detector - scint CsJ
Det3Z = 10.*mm;
Det3R = 7.5*mm;
// Fourth detector - Si
Det4Z = 1.*mm;
Det4R = 10.*mm;
// default parameter values of the absorbers
pDet1 = 0;
pDet2 = 0;
pDet3 = 0;
pDet4 = 0;
// parameters of upper cone// обновила
ConeRmin1 = 12.8*mm ;
ConeRmax1 = 22.*mm;
ConeRmin2 = 4.0*mm;
ConeRmax2 = 22.*mm;
ConeDz = 28.0*mm;
// first part of shell- metal
UpperTube1Z = 74.7*mm;
UpperTube1Rmin = 0.*mm;
UpperTube1Rmax = 22.*mm;
// third (inner ) part of shell - plex
UpperTube2Z = 21.7*mm;
UpperTube2Rmin = 0.*mm;
UpperTube2Rmax =9.5*mm;
// first (outer) part of lower shell - metal
LowTube1Z = 68.*mm;
LowTube1Rmin = 22.*mm;
LowTube1Rmax = 27.5*mm;
// second part of lower tube - plex
LowTube2Z = 38.*mm;
LowTube2Rmin = 0.*mm;
LowTube2Rmax = 10.5*mm;
// third (outer) part of lower shell - metal
LowTube3Z = 68.*mm;
LowTube3Rmin = 27.5*mm;
LowTube3Rmax = 31.5*mm;
// Вольфрамовая защита вокруг D3 и D4, частично замещает плекс
W_shield1Z = 38.*mm;
W_shield1Rmin = 10.5*mm;
W_shield1Rmax = 18.5*mm;
//Вольфрамовая шайба в нижней части
W_shield2Z = 5.*mm;
W_shield2R = 18.5*mm;
//Вольфрамовая шайба в верхней части. Разбита на 2 шайбы. Внешняя - дочерняя от UpperTube1, внутренняя - от UpperTube2
W_shield3Z = 5.*mm;
W_shield3Rmin = 4.0*mm;
W_shield3Rmax = 18.5*mm;
W_shield3Rmid = UpperTube2Rmax;
////////////////////////////////
fSolidWorld = new G4Box("World", //its name
fWorldSizeX/2,fWorldSizeY/2,fWorldSizeZ/2); //its size
fLogicWorld = new G4LogicalVolume(fSolidWorld, //its solid
beam, //its material
"World"); //its name
fPhysiWorld = new G4PVPlacement(0, //no rotation
G4ThreeVector(), //at (0,0,0)
"World", //its name
fLogicWorld, //its logical volume
0, //its mother volume
false, //no boolean operation
0); //copy number
// Shield volume
G4double ShieldR = 19.*cm;
G4Sphere* ShieldSolid = new G4Sphere("Shield", //its name
ShieldR-1.*mm,ShieldR,0.0*deg, 360.0*deg,0.0*deg, 180.0*deg); //its size
ShieldLogic = new G4LogicalVolume(ShieldSolid, //its solid
fSiMaterial, //its material
"Shield"); //its name
ShieldPhysi = new G4PVPlacement(0, //no rotation
G4ThreeVector(0.,0.,51.53*mm), //at (0,0,0)
ShieldLogic, //its logical volume
"Shield", //its name
fLogicWorld, //its mother volume
false, //no boolean operation
0); //copy number
//
/// Upper cone part - коллиматор
G4VSolid*
sCone = new G4Cons("Al_Cone",
ConeRmin1,
ConeRmax1,
ConeRmin2,
ConeRmax2,
ConeDz/2.,//half lenght
0.0*deg,
360.0*deg);
G4LogicalVolume*
lCone = new G4LogicalVolume(sCone, //solid
Wall_material, //material
"Al_Cone"); //name
G4VPhysicalVolume*
pCone = new G4PVPlacement(0, //no rotation
G4ThreeVector(0.,0.,MainZ/2.0+ConeDz/2.), //position
lCone, //logical volume
"Al_Cone", //name
fLogicWorld, //mother volume
false, //no boolean operation
0); //copy number
/// вакуумный детектор в растворе коллиматора
G4VSolid*
sVacDet = new G4Cons("VacDet",
0.,
ConeRmin1,
0.,
ConeRmin2,
ConeDz/2.,//half lenght
0.0*deg,
360.0*deg);
G4LogicalVolume*
lVacDet = new G4LogicalVolume(sVacDet, //solid
gapMaterial, //material
"VacDet"); //name
pVacDet = new G4PVPlacement(0, //no rotation
G4ThreeVector(0.,0.,MainZ/2.0+ConeDz/2.), //position
lVacDet, //logical volume
"VacDet", //name
fLogicWorld, //mother volume
false, //no boolean operation
0); //copy number
/// внутренняя часть металлического корпуса, остальное (кроме внешнего металла)
// помещается в него дочерними объемами
G4VSolid*
sUpperTube1 = new G4Tubs("UpperTube1",
UpperTube1Rmin, // min radius
UpperTube1Rmax, // max radius
UpperTube1Z/2., // Height
0.0*deg, // start angle
360.0*deg); // segment size
G4LogicalVolume*
lUpperTube1 = new G4LogicalVolume(sUpperTube1, //solid
Wall_material, //material
"UpperTube1"); //name
G4VPhysicalVolume*
pUpperTube1 = new G4PVPlacement(0, //no rotation
G4ThreeVector(0.,0.,MainZ/2.0
+ConeDz+UpperTube1Z/2.), //position
lUpperTube1, //logical volume
"UpperTube1", //name
fLogicWorld, //mother volume
false, //no boolean operation
0); //copy number
/// Первая часть металлического корпуса - толстая часть, там где диаметр 57 мм
G4VSolid*
sLowTube1 = new G4Tubs("LowTube1",
LowTube1Rmin, // min radius
LowTube1Rmax, // max radius
LowTube1Z/2., // Height
0.0*deg, // start angle
360.0*deg); // segment size
G4LogicalVolume*
lLowTube1 = new G4LogicalVolume(sLowTube1, //solid
Wall_material, //material
"LowTube1"); //name
G4VPhysicalVolume*
pLowTube1 = new G4PVPlacement(0, //no rotation
G4ThreeVector(0.,0.,MainZ/2.0+ConeDz+UpperTube1Z-LowTube1Z/2.), //position
lLowTube1, //logical volume
"LowTube1", //name
fLogicWorld, //mother volume
false, //no boolean operation
0); //copy number
/// Самая внешняя часть металлического корпуса - толстая часть, там где диаметр 57 мм
// Вольфрам, 3 мм - Варинат C
// В варианте с внутренней вольфрамовой вставкой (Вариант D) меняем на дюраль
/* G4VSolid*
sLowTube3 = new G4Tubs("LowTube3",
LowTube3Rmin, // min radius
LowTube3Rmax, // max radius
LowTube3Z/2., // Height
0.0*deg, // start angle
360.0*deg); // segment size
G4LogicalVolume*
lLowTube3 = new G4LogicalVolume(sLowTube3, //solid
// Shell_material, //material - вольфрамовый слой снаружи - Вариант C
DuralMaterial, //вариант с внутренней вольфрамовой вставкой (D)
"LowTube3"); //name
G4VPhysicalVolume*
pLowTube3 = new G4PVPlacement(0, //no rotation
G4ThreeVector(0.,0.,MainZ/2.0+ConeDz+10.*mm+LowTube3Z/2.), //position
lLowTube3, //logical volume
"LowTube3", //name
fLogicWorld, //mother volume
false, //no boolean operation
0); //copy number
*/
/// внутренний корпус - оргстекло, дочерний от uppertube1
/* G4VSolid*
sUpperTube2 = new G4Tubs("UpperTube2",
UpperTube2Rmin, // min radius
UpperTube2Rmax, // max radius
UpperTube2Z/2., // Height
0.0*deg, // start angle
360.0*deg); // segment size
G4LogicalVolume*
lUpperTube2 = new G4LogicalVolume(sUpperTube2, //solid
Cone_dielectric, //material
"UpperTube2"); //name
G4VPhysicalVolume*
pUpperTube2 = new G4PVPlacement(0, //no rotation
G4ThreeVector(0.,0.,-UpperTube1Z/2.0+UpperTube2Z/2.), //position
lUpperTube2, //logical volume
"UpperTube2", //name
lUpperTube1, //mother volume
false, //no boolean operation
0); //copy number
// Вакуум перед фольгой
G4VSolid* sFoilGap = new G4Tubs("FoilGap", //name
0., // min radius
Gap1R, // max radius
FoilGapZ/2., // Height
0.0*deg, // start angle
360.0*deg); // segment size
G4LogicalVolume*
lFoilGap = new G4LogicalVolume(sFoilGap, //solid
gapMaterial, //material
"FoilGap"); //name
G4VPhysicalVolume*
pFoilGap = new G4PVPlacement(0, //no rotation
G4ThreeVector(0.,0.,-UpperTube2Z/2.+FoilGapZ/2.), //position
lFoilGap, //logical volume
"FoilGap", //name
lUpperTube2, //mother volume
false, //no boolean operation
0); //copy number
//фольга перед 1-м детектором - в растворе коллиматора
G4VSolid* sFoil = new G4Tubs("Foil", //name
0.0, // min radius
FoilR, // max radius
FoilZ/2., // Height
0.0*deg, // start angle
360.0*deg); // segment size
G4LogicalVolume*
lFoil = new G4LogicalVolume(sFoil, //solid
fSiMaterial, //material
"Foil"); //name
G4VPhysicalVolume*
pFoil = new G4PVPlacement(0, //no rotation
G4ThreeVector(0.,0.,-UpperTube2Z/2.+FoilGapZ+FoilZ/2.), //position
lFoil, //logical volume
"Foil", //name
lUpperTube2, //mother volume
false, //no boolean operation
0); //copy number
// Вакуум между фольгой и Д1
G4VSolid* sGap1 = new G4Tubs("Gap1", //name
0., // min radius
Gap1R, // max radius
Gap1Z/2., // Height
0.0*deg, // start angle
360.0*deg); // segment size
G4LogicalVolume*
lGap1 = new G4LogicalVolume(sGap1, //solid
gapMaterial, //material
"Gap1"); //name
G4VPhysicalVolume*
pGap1 = new G4PVPlacement(0, //no rotation
G4ThreeVector(0.,0.,-UpperTube2Z/2.+FoilGapZ+FoilZ+Gap1Z/2.), //position
lGap1, //logical volume
"Gap1", //name
lUpperTube2, //mother volume
false, //no boolean operation
0); //copy number
/// внутренний корпус 2 - оргстекло, нижняя часть, дочерний от uppertube1
G4VSolid*
sLowTube2 = new G4Tubs("LowTube2",
LowTube2Rmin, // min radius
LowTube2Rmax, // max radius
LowTube2Z/2., // Height
0.0*deg, // start angle
360.0*deg); // segment size
G4LogicalVolume*
lLowTube2 = new G4LogicalVolume(sLowTube2, //solid
Cone_dielectric, //material
"LowTube2"); //name
G4VPhysicalVolume*
pLowTube2 = new G4PVPlacement(0, //no rotation
G4ThreeVector(0.,0.,-UpperTube1Z/2.0+UpperTube2Z+LowTube2Z/2.), //position
lLowTube2, //logical volume
"LowTube2", //name
lUpperTube1, //mother volume
false, //no boolean operation
0); //copy number
// First detector - Si - D1,D2, Gaps, D3, D4 - daughters of LowTube 2
G4Material* material = fSiMaterial;
G4VSolid* sDet1 = new G4Tubs("Det1", //name
0., // min radius
Det1R, // max radius
Det1Z/2., // Height
0.0*deg, // start angle
360.0*deg); // segment size
G4LogicalVolume*
lDet1 = new G4LogicalVolume(sDet1, //solid
material, //material
"Det1"); //name
pDet1 = new G4PVPlacement(0, //no rotation
G4ThreeVector(0.,0.,-LowTube2Z/2.+Det1Z/2.), //position
lDet1, //logical volume
"Det1", //name
lLowTube2, //mother volume
false, //no boolean operation
0); //copy number
// Вакуум между Д1 и Д2
G4VSolid* sGap2 = new G4Tubs("Gap2", //name
0., // min radius
Gap2R, // max radius
Gap2Z/2., // Height
0.0*deg, // start angle
360.0*deg); // segment size
G4LogicalVolume*
lGap2 = new G4LogicalVolume(sGap2, //solid
gapMaterial, //material
"Gap2"); //name
G4VPhysicalVolume*
pGap2 = new G4PVPlacement(0, //no rotation
G4ThreeVector(0.,0.,-LowTube2Z/2.+Det1Z+Gap2Z/2.), //position
lGap2, //logical volume
"Gap2", //name
lLowTube2, //mother volume
false, //no boolean operation
0); //copy number
// Second detector - Si
material = fSiMaterial;
G4VSolid* sDet2 = new G4Tubs("Det2", //name
0., // min radius
Det2R, // max radius
Det2Z/2., // Height
0.0*deg, // start angle
360.0*deg); // segment size
G4LogicalVolume*
lDet2 = new G4LogicalVolume(sDet2, //solid
material, //material
"Det2"); //name
pDet2 = new G4PVPlacement(0, //no rotation
G4ThreeVector(0.,0.,-LowTube2Z/2.+Det1Z+Gap2Z+Det2Z/2.), //position
lDet2, //logical volume
"Det2", //name
lLowTube2, //mother volume
false, //no boolean operation
0); //copy number
// Вакуум между Д2 и Д3
//// Верхний - дочерний от LowTube2
G4VSolid* sGap3 = new G4Tubs("Gap3", //name
0., // min radius
Gap3R, // max radius
Gap3Z/2., // Height
0.0*deg, // start angle
360.0*deg); // segment size
G4LogicalVolume*
lGap3 = new G4LogicalVolume(sGap3, //solid
gapMaterial, //material
"Gap3"); //name
G4VPhysicalVolume*
pGap3 = new G4PVPlacement(0, //no rotation
G4ThreeVector(0.,0.,-LowTube2Z/2.+Det1Z+Gap2Z+Det2Z+Gap3Z/2.), //position
lGap3, //logical volume
"Gap3", //name
lLowTube2, //mother volume
false, //no boolean operation
0); //copy number
///
/// внутренний корпус из вольфрама, частично замещает оргстекло, дочерний от lUpperTube1
G4VSolid*
sW_shield1 = new G4Tubs("W_shield1",
W_shield1Rmin, // min radius
W_shield1Rmax, // max radius
W_shield1Z/2., // Height
0.0*deg, // start angle
360.0*deg); // segment size
G4LogicalVolume*
lW_shield1 = new G4LogicalVolume(sW_shield1, //solid
Shell_material, //material
"W_shield1"); //name
G4VPhysicalVolume*
pW_shield1 = new G4PVPlacement(0, //no rotation
G4ThreeVector(0.,0.,-UpperTube1Z/2.0+UpperTube2Z+W_shield1Z/2.), //position
lW_shield1, //logical volume
"W_shield1", //name
lUpperTube1, //mother volume
false, //no boolean operation
0); //copy number
////////
/// Нижняя шайба из вольфрама, дочерний от uppertube1 - Вариант D
G4VSolid*
sW_shield2 = new G4Tubs("W_shield2",
0., // min radius
W_shield2R, // max radius
W_shield2Z/2., // Height
0.0*deg, // start angle
360.0*deg); // segment size
G4LogicalVolume*
lW_shield2 = new G4LogicalVolume(sW_shield2, //solid
Shell_material, //material
"W_shield2"); //name
G4VPhysicalVolume*
pW_shield2 = new G4PVPlacement(0, //no rotation
G4ThreeVector(0.,0.,-UpperTube1Z/2.0+UpperTube2Z+LowTube2Z+W_shield2Z/2.), //position
lW_shield2, //logical volume
"W_shield2", //name
lUpperTube1, //mother volume
false, //no boolean operation
0); //copy number
//////////////верхняя шайба - вариант 2
/// Верхняя внутренняя шайба из вольфрама, дочерний от uppertube2
G4VSolid*
sW_shield3 = new G4Tubs("W_shield3",
W_shield3Rmin, // min radius
W_shield3Rmid, // max radius
W_shield3Z/2., // Height
0.0*deg, // start angle
360.0*deg); // segment size
G4LogicalVolume*
lW_shield3 = new G4LogicalVolume(sW_shield3, //solid
Shell_material, //material
"W_shield3"); //name
G4VPhysicalVolume*
pW_shield3 = new G4PVPlacement(0, //no rotation
G4ThreeVector(0.,0.,UpperTube2Z/2.0-W_shield3Z/2.), //position
lW_shield3, //logical volume
"W_shield3", //name
lUpperTube2, //mother volume
false, //no boolean operation
0); //copy number
/// Верхняя вннешняя шайба из вольфрама, дочерний от uppertube1
G4VSolid*
sW_shield4 = new G4Tubs("W_shield4",
W_shield3Rmid, // min radius
W_shield3Rmax, // max radius
W_shield3Z/2., // Height
0.0*deg, // start angle
360.0*deg); // segment size
G4LogicalVolume*
lW_shield4 = new G4LogicalVolume(sW_shield4, //solid
Shell_material, //material
"W_shield4"); //name
G4VPhysicalVolume*
pW_shield4 = new G4PVPlacement(0, //no rotation
G4ThreeVector(0.,0.,-UpperTube1Z/2.0+UpperTube2Z-W_shield3Z/2.), //position
lW_shield4, //logical volume
"W_shield4", //name
lUpperTube1, //mother volume
false, //no boolean operation
0); //copy number
// Third detector - CsJ, дочений от LowTube2
material = ScintMaterial;
G4VSolid* sDet3 = new G4Tubs("Det3", //name
0., // min radius
Det3R, // max radius
Det3Z/2., // Height
0.0*deg, // start angle
360.0*deg); // segment size
G4LogicalVolume*
lDet3 = new G4LogicalVolume(sDet3, //solid
material, //material
"Det3"); //name
pDet3 = new G4PVPlacement(0, //no rotation
G4ThreeVector(0.,0.,-LowTube2Z/2.+Det1Z+Gap2Z+Det2Z+Gap3Z+Det3Z/2.), //position
lDet3, //logical volume
"Det3", //name
lLowTube2, //mother volume
false, //no boolean operation
0);
// фотодиод за 3-м детектором - Si
G4VSolid* sFoto = new G4Tubs("Foto", //name
0.0, // min radius
FotoR, // max radius
FotoZ/2., // Height
0.0*deg, // start angle
360.0*deg); // segment size
G4LogicalVolume*
lFoto = new G4LogicalVolume(sFoto, //solid
fSiMaterial, //material
"Foto"); //name
G4VPhysicalVolume*
pFoto = new G4PVPlacement(0, //no rotation
G4ThreeVector(0.,0.,-LowTube2Z/2.+Det1Z+Gap2Z+Det2Z+Gap3Z+Det3Z+FotoZ/2.), //position
lFoto, //logical volume
"Foto", //name
lLowTube2, //mother volume
false, //no boolean operation
0); //copy number
// Fourth detector - Si
material = fSiMaterial;
G4VSolid* sDet4 = new G4Tubs("Det4", //name
0., // min radius
Det4R, // max radius
Det4Z/2., // Height
0.0*deg, // start angle
360.0*deg); // segment size
G4LogicalVolume*
lDet4 = new G4LogicalVolume(sDet4, //solid
material, //material
"Det4"); //name
pDet4 = new G4PVPlacement(0, //no rotation
G4ThreeVector(0.,0.,-LowTube2Z/2.+Det1Z+Gap2Z+Det2Z+Gap3Z+Det3Z+FotoZ+Gap4Z+Det4Z/2.), //position
lDet4, //logical volume
"Det4", //name
lLowTube2, //mother volume
false, //no boolean operation
0); //copy number
// Visualization attributes
G4VisAttributes* worldVisAtt= new G4VisAttributes(G4Colour(0.5,0.5,0.9)); //RGB
worldVisAtt->SetVisibility(true);
fLogicWorld->SetVisAttributes(worldVisAtt);
//MirrorLogic->SetVisAttributes(G4VisAttributes::Invisible);
ShieldLogic->SetVisAttributes(G4VisAttributes::Invisible);
lVacDet->SetVisAttributes(G4VisAttributes::Invisible);
// Detector1 - yellow
Det1VisAtt = new G4VisAttributes(true, // visibility: true
G4Colour::Yellow());
Det1VisAtt->SetForceSolid(true);
// lDet1 -> SetVisAttributes(Det1VisAtt);
// Foil -blue, solid
FoilVisAtt = new G4VisAttributes(true, // visibility: true
G4Colour::Blue());
FoilVisAtt->SetForceAuxEdgeVisible(true);
FoilVisAtt->SetForceSolid(true);
lFoil -> SetVisAttributes(FoilVisAtt);
lFoto -> SetVisAttributes(FoilVisAtt);
WVisAtt = new G4VisAttributes(true, // visibility: true
G4Colour::Magenta());
lW_shield1 -> SetVisAttributes(WVisAtt);
lW_shield2 -> SetVisAttributes(WVisAtt);
lW_shield3 -> SetVisAttributes(WVisAtt);
lW_shield4 -> SetVisAttributes(WVisAtt);
// Detector2,3,4
Det2VisAtt = new G4VisAttributes(true, // visibility: true
G4Colour::Yellow());
Det2VisAtt->SetForceSolid(true);
lDet2 -> SetVisAttributes(Det2VisAtt);
lDet3 -> SetVisAttributes(Det2VisAtt);
lDet4 -> SetVisAttributes(Det2VisAtt);
lDet1 -> SetVisAttributes(Det2VisAtt);
// Tube1
Tube1VisAtt = new G4VisAttributes(true, // visibility: true
G4Colour::White());
// Tube1VisAtt->SetForceSolid(true);
Tube1VisAtt->SetForceAuxEdgeVisible(true);
lUpperTube1 -> SetVisAttributes(Tube1VisAtt);
lLowTube1 -> SetVisAttributes(Tube1VisAtt);
// lLowTube3 -> SetVisAttributes(Tube1VisAtt);
// Tube2
Tube2VisAtt = new G4VisAttributes(true, // visibility: true
G4Colour::Cyan());
Tube2VisAtt->SetForceAuxEdgeVisible(true);
// Tube2VisAtt->SetForceSolid(true);
lUpperTube2 -> SetVisAttributes(Tube2VisAtt);
lLowTube2 -> SetVisAttributes(Tube2VisAtt);
// Cone
// ConeVisAtt = new G4VisAttributes(true, // visibility: true
// G4Colour::Green());
// ConeVisAtt->SetForceAuxEdgeVisible(true);
// lCone -> SetVisAttributes(Tube1VisAtt);
// Create Target G4Region and add logical volume
fRegion = new G4Region("Detector");
G4ProductionCuts* cuts = new G4ProductionCuts();
G4double defCut = 10.*um;
cuts->SetProductionCut(defCut,"gamma");
cuts->SetProductionCut(defCut,"e-");
cuts->SetProductionCut(defCut,"e+");
cuts->SetProductionCut(defCut,"proton");
fRegion->SetProductionCuts(cuts);
fRegion->AddRootLogicalVolume(lDet1);
fRegion->AddRootLogicalVolume(lDet2);
fRegion->AddRootLogicalVolume(lFoil);
fRegion->AddRootLogicalVolume(lFoto);
return fPhysiWorld;
}
*/
void DetectorConstruction::ConstructSDandField()
{
//------------------------------------------------
// Sensitive detectors
//------------------------------------------------
G4SDManager* SDman = G4SDManager::GetSDMpointer();
G4String Det1SDname = "Det1_SD";
G04SensitiveDetector* Det1SD =
new G04SensitiveDetector(Det1SDname);
SDman->AddNewDetector( Det1SD );
G4String Det2SDname = "Det2_SD";
G04SensitiveDetector* Det2SD =
new G04SensitiveDetector(Det2SDname);
SDman->AddNewDetector( Det2SD );
G4String Det3SDname = "Det3_SD";
G04SensitiveDetector* Det3SD =
new G04SensitiveDetector(Det3SDname);
SDman->AddNewDetector( Det3SD );
G4String Det4SDname = "Det4_SD";
G04SensitiveDetector* Det4SD =
new G04SensitiveDetector(Det4SDname);
SDman->AddNewDetector( Det4SD );
///////////////////////////////////////////////////////////////////////
//
// Example how to retrieve Auxiliary Information for sensitive detector
//
const G4GDMLAuxMapType* auxmap = fParser.GetAuxMap();
G4cout << "Found " << auxmap->size()
<< " volume(s) with auxiliary information."
<< G4endl << G4endl;
for(G4GDMLAuxMapType::const_iterator iter=auxmap->begin();
iter!=auxmap->end(); iter++)
{
G4cout << "Volume " << ((*iter).first)->GetName()
<< " has the following list of auxiliary information: "
<< G4endl << G4endl;
for (G4GDMLAuxListType::const_iterator vit=(*iter).second.begin();
vit!=(*iter).second.end(); vit++)
{
G4cout << "--> Type: " << (*vit).type
<< " Value: " << (*vit).value << G4endl;
}
}
G4cout << G4endl;
// The same as above, but now we are looking for
// sensitive detectors setting them for the volumes
for(G4GDMLAuxMapType::const_iterator iter=auxmap->begin();
iter!=auxmap->end(); iter++)
{
G4cout << "Volume " << ((*iter).first)->GetName()
<< " has the following list of auxiliary information: "
<< G4endl << G4endl;
for (G4GDMLAuxListType::const_iterator vit=(*iter).second.begin();
vit!=(*iter).second.end();vit++)
{
if ((*vit).type=="SensDet")
{
G4cout << "Attaching sensitive detector " << (*vit).value
<< " to volume " << ((*iter).first)->GetName()
<< G4endl << G4endl;
G4VSensitiveDetector* mydet =
SDman->FindSensitiveDetector((*vit).value);
if(mydet)
{
G4LogicalVolume* myvol = (*iter).first;
myvol->SetSensitiveDetector(mydet);
}
else
{
G4cout << (*vit).value << " detector not found" << G4endl;
}
}
}
}
}
<file_sep>//
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// -------------------------------------------------------------------
// $Id: DetectorConstruction.hh,v 1.1 2012-09-20 mraine Exp $
// -------------------------------------------------------------------
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo....
#ifndef DetectorConstruction_h
#define DetectorConstruction_h 1
#include "G4VUserDetectorConstruction.hh"
#include "G4VPhysicalVolume.hh"
#include "G4LogicalVolume.hh"
#include "G4Box.hh"
#include "G4Sphere.hh"
#include "G4Material.hh"
#include "G4NistManager.hh"
#include "G4PVPlacement.hh"
#include "G4UserLimits.hh"
#include "G4VisAttributes.hh"
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo....
class G4Region;
class G4GDMLParser;
class DetectorConstruction : public G4VUserDetectorConstruction
{
public:
DetectorConstruction(const G4GDMLParser& parser);
//DetectorConstruction();
virtual void ConstructSDandField();
~DetectorConstruction();
G4VPhysicalVolume* Construct();
G4Region* GetTargetRegion() {return fRegion;}
private:
const G4GDMLParser& fParser;
G4double fWorldSizeX;
G4double fWorldSizeY;
G4double fWorldSizeZ;
G4VPhysicalVolume* fPhysiWorld;
G4LogicalVolume* fLogicWorld;
G4Box* fSolidWorld;
G4VPhysicalVolume* ShieldPhysi;
G4LogicalVolume* ShieldLogic;
G4Material* fSiMaterial;
G4Material* fAlMaterial;
G4Material* ScintMaterial;
G4Material* Wall_material;
G4Material* beam;
G4Material* air;
G4double MainR;
G4double MainZ;
G4double Det1R;
G4double Det1Z;
G4double FoilR;
G4double FoilZ;
G4double FotoR;
G4double FotoZ;
G4double Det2R;
G4double Det2Z;
G4double Det3R;
G4double Det3Z;
G4double Det4R;
G4double Det4Z;
G4double Gap1R;
G4double Gap1Z;
G4double Gap2R;
G4double Gap2Z;
G4double Gap3R;
G4double Gap3Z;
G4double Gap4R;
G4double Gap4Z;
G4double Gap5R;
G4double Gap5Z;
G4double FoilGapR;
G4double FoilGapZ;
G4double ConeRmin1;
G4double ConeRmax1;
G4double ConeRmin2;
G4double ConeRmax2;
G4double ConeDz;
G4double CapZ;
G4double CapRmax;
G4double CapRmin;
G4double UpperTube1Z;
G4double UpperTube1Rmin;
G4double UpperTube1Rmax;
G4double UpperTube2Z;
G4double UpperTube2Rmin;
G4double UpperTube2Rmax;
G4double LowTube1Z;
G4double LowTube1Rmin;
G4double LowTube1Rmax;
G4double LowTube2Z;
G4double LowTube2Rmin;
G4double LowTube2Rmax;
G4double LowTube3Z;
G4double LowTube3Rmin;
G4double LowTube3Rmax;
G4double W_shield1Z;
G4double W_shield1Rmax;
G4double W_shield1Rmin;
G4double W_shield2Z;
G4double W_shield2R;
G4double W_shield3Rmin, W_shield3Rmax, W_shield3Z, W_shield3Rmid;
G4Material* gapMaterial;
G4Material* DuralMaterial;
G4Material* Shell_material;
G4Material* Cone_dielectric;
// G4int nbOfLayers;
// G4double layerThickness;
// G4UniformMagField* magField;
G4VPhysicalVolume* pDet1;
G4VPhysicalVolume* pDet2;
G4VPhysicalVolume* pDet3;
G4VPhysicalVolume* pDet4;
G4VPhysicalVolume* pVacDet;
G4VisAttributes* Det1VisAtt;
G4VisAttributes* Det2VisAtt;
G4VisAttributes* GapVisAtt;
G4VisAttributes* FoilVisAtt;
G4VisAttributes* WVisAtt;
G4VisAttributes* ConeVisAtt;
G4VisAttributes* Tube1VisAtt;
G4VisAttributes* Tube2VisAtt;
G4VisAttributes* WorldVisAtt;
G4Region* fRegion;
void DefineMaterials();
G4VPhysicalVolume* ConstructDetector();
};
#endif
<file_sep># radmonitoring
This project started for Monte-Carlo simulation of telescope for space radiation conditions monitoring.
It based on Geant4 libraries and R packages.
# HOW to RUN analysis with r:
Install R(manual from https://www.vultr.com/docs/how-to-install-rstudio-server-on-centos-7 ):
sudo yum install R -y
Enter the R shell:
sudo -i R
Install the package you need as below, and more packages can be installed in the same fashion:
install.packages('txtplot')
quit the R shell:
q()
Run analysis script:
Rscript a.R
or
R CMD BATCH a.R
Check the output:
cat a.Rout
# Publications:
This project is based on previous work:
<NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. Numerical simulation of metrological characteristics of cosmic radiation detectors. Inorganic Materials: Applied Research, 8(2):222–228, 2017. [ DOI 10.1134/S2075113317020241]
# Abstract (Cospar thesis):
This work presents the technique and results of computer simulation of the interaction of cosmic radiation with detectors. The program code based on Geant4 libraries is designed, to simulate the operation of a telescopic detector of ionizing radiation, consisting of several sequentially located semiconductor and scintillation detectors. Using the Geant4 toolkit, we simulate signals from electrons and protons of various energies in the detecting regions of the device, taking into account the generation of secondary particles. Separation of signals from primary particles passing through the entrance window of the telescope and through the walls of the housing is carried out. The obtained data are used to simulate the necessary throughput of the device electronics in the Matlab Simulink environment. The characteristics of the sensitivity and accuracy of the spectrum determination are performed using an original algorithm. This algorithm realizes quantile regression to obtain information on the spectra of cosmic radiation, based on the energy losses of particles in the detectors of the instrument.
The combination of discussed software packages allows to optimize the parameters of the geometry and logic circuits of the device. The source files of the program codes will be available in the public domain.
Application of the results obtained using the presented software codes at the design and production stages of spacecraft will significantly increase their reliability and extend the service life under the space radiation exposure.
# Acknowledgments:
Current research was funded by RFBR according to the project №18-32-00727-mol-a.
<file_sep>file(REMOVE_RECURSE
"CMakeFiles/Telescope.dir/Telescope.cc.o"
"CMakeFiles/Telescope.dir/src/ActionInitialization.cc.o"
"CMakeFiles/Telescope.dir/src/DetectorConstruction.cc.o"
"CMakeFiles/Telescope.dir/src/EventAction.cc.o"
"CMakeFiles/Telescope.dir/src/EventActionMessenger.cc.o"
"CMakeFiles/Telescope.dir/src/G04SensitiveDetector.cc.o"
"CMakeFiles/Telescope.dir/src/G4ElectronCapture.cc.o"
"CMakeFiles/Telescope.dir/src/MuelPhyslist.cc.o"
"CMakeFiles/Telescope.dir/src/OpticalPhysics.cc.o"
"CMakeFiles/Telescope.dir/src/PhysicsList.cc.o"
"CMakeFiles/Telescope.dir/src/PrimaryGeneratorAction.cc.o"
"CMakeFiles/Telescope.dir/src/RunAction.cc.o"
"CMakeFiles/Telescope.dir/src/SteppingAction.cc.o"
"CMakeFiles/Telescope.dir/src/TrackingAction.cc.o"
"Telescope.pdb"
"Telescope"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/Telescope.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>#!/usr/bin/Rscript
# eval(parse(filename, encoding="UTF-8"))
# таблицы как я отчитываюсь
library(data.table)
library("Hmisc")
library('hexbin')
library('readr')
library('dplyr')
library('tidyr')
# подготовка исходных данных
setwd("D:/Ivan/_flash backup 2014/SINP/Группировка/2017 Группировка/radmonitoring/radmonitoring/analisys/percentile")
datae<-read.table("report2/electr_A_L14_det2.dat", header = TRUE)
casing <-'Aold'
datae<-read.table("report3/electrons_A_det2.dat", header = TRUE)
casing <-'A'
# загрузка тренировочного потока D ----------------------------------------
# Start the clock!
ptm <- proc.time()
# datae<-fread("electrons_B.dat", header = TRUE)
casing <-'ABCold'
# datae<-read.table(paste("electrons_",casing,".dat", sep=''), header = TRUE)
datae<-read.table("d:/Simulink/data/alldet/electr_A_L32.dat", header = TRUE)
datae <- rbind(datae, read.table("d:/Simulink/data/alldet/electr_B_L32.dat", header = TRUE))
datae <- rbind(datae, read.table("d:/Simulink/data/alldet/electr_C_L32.dat", header = TRUE))
# Stop the clock
proc.time() - ptm
# breaks <- c(0,150,350,600,1000,2000,4000,10000)
# labels=c('e0','e1','e2','e3','e4','e5','e6')
breaks <- c(150,350,600,1000,2000,4000,10000)
labels=c('e1','e2','e3','e4','e5','e6')
datae$bins <- cut(datae$E0.keV, breaks, labels= labels)
least.thresholds = c(150, 120, 800, 200)
# полное энерговыделение в детекторах прибора---------------
datae$sumdE <- datae$dE.det1 + datae$dE.det2 + datae$dE.det3 + datae$dE.det4
datae.fullAbsorption <- datae[(datae$E0.keV - datae$sumdE)/datae$E0.keV< 0.05,]
plot(datae$sumdE ~ datae$E0.keV)
plot(datae.fullAbsorption$sumdE ~ datae.fullAbsorption$E0.keV)
plot(datae.fullAbsorption$sumdE ~ datae.fullAbsorption$ang_z)
# коллиматор---------------------------------------------------
datae.collimator <- datae[datae$ang_z < 17,]
plot(datae.collimator$sumdE ~ datae.collimator$E0.keV)
#
# plot(dE.det4 ~ dE.det3:dE.det2, data=datae.collimator)
# training data filterlow in det2 -----------------------------------------------------------
datae.filterLow <- datae[(datae$dE.det2 >= 120),]
# datae.filterLow <- datae[(datae$dE.det2 >= 120)&(datae$ang_z < 17),]
# datae.filterLow <- datae.filterLow[(datae.filterLow$dE.det1 >= 150),]
# datae.filterLow <- datae.filterLow[(datae.filterLow$dE.det3 >= 800),]
# datae.filterLow <- datae.filterLow[(datae.filterLow$dE.det4 >= 200),]
##### OPTION 1: hexbin from package 'hexbin' #######
# Color housekeeping
library(RColorBrewer)
rf <- colorRampPalette(rev(brewer.pal(11,'Spectral')))
r <- rf(32)
library(hexbin)
# Create hexbin object and plot
# h <- hexbin(datae.collimator[,1,10 ])
# plot(h)
# plot(h, colramp=rf)
hexbinplot(sumdE~E0.keV, data=datae, colramp=rf,
aspect=1, trans=log, inv=exp,
mincnt=1,
xbins = 100,
main = paste("Полный поток электронов через прибор,",casing, sep=" "),
ylab= "Суммарное энерговыделение в детекторах прибора")
hexbinplot(sumdE~E0.keV, data=datae.collimator, colramp=rf,
aspect=1, trans=log, inv=exp,
mincnt=1,
xbins = 100,
main = paste("Поток электронов через коллиматор, ",casing, sep=" "),
ylab= "Суммарное энерговыделение в детекторах прибора")
hexbinplot(sumdE~E0.keV, data=datae.filterLow, colramp=rf,
aspect=1, trans=log, inv=exp,
mincnt=1,
xbins = 100,
main = paste("Поток электронов через прибор, Триггер Д2",casing, sep=" "),
ylab= "Суммарное энерговыделение в детекторах прибора")
hexbinplot(sumdE~E0.keV, data=datae.fullAbsorption, colramp=rf,
aspect=1, trans=log, inv=exp,
mincnt=1,
xbins = 100,
main = paste("поток полностью поглощенных электронов через прибор,",casing, sep=" "),
ylab= "Суммарное энерговыделение в детекторах прибора")
ppi <- 300
png(paste("trainelec",casing,".png", sep=""), width=6*ppi, height=6*ppi, res=ppi)
hexbinplot(sumdE~E0.keV, data=datae.filterLow, colramp=rf,
aspect=1, trans=log, inv=exp,
mincnt=1,
xbins = 100,
main = paste("поток электронов через прибор, Триггер D2,\n , корпус",casing, sep=" "),
ylab= "Суммарное энерговыделение в детекторах прибора")
dev.off()
ppi <- 300
png(paste("trainelec1",casing,".png", sep=""), width=6*ppi, height=6*ppi, res=ppi)
hexbinplot(sumdE~E0.keV, data=datae.fullAbsorption, colramp=rf,
aspect=1, trans=log, inv=exp,
mincnt=1,
xbins = 100,
main = paste("поток электронов через прибор, ~полное поглощение,\n , корпус",casing, sep=" "),
ylab= "Суммарное энерговыделение в детекторах прибора")
dev.off()
# hexbinplot(sumdE~log(E0.keV), data=datae.filterLow, colramp=rf,
# aspect=1, trans=log, inv=exp,
# mincnt=2,
# xbins = 100,
# main = "поток электронов через прибор, D Триггер D2, коллиматор",
# ylab= "Суммарное энерговыделение в детекторах прибора")
boxplot(dE.det1~bins, data = datae.fullAbsorption)
boxplot(dE.det2~bins, data = datae.fullAbsorption)
boxplot(dE.det3~bins, data = datae.fullAbsorption)
boxplot(dE.det4~bins, data = datae.fullAbsorption)
boxplot(dE.det1~bins, data = datae.filterLow)
boxplot(dE.det2~bins, data = datae.filterLow)
boxplot(dE.det3~bins, data = datae.filterLow)
boxplot(dE.det4~bins, data = datae.filterLow)
boxplot(dE.det1~bins, data = datae)
boxplot(dE.det2~bins, data = datae)
boxplot(dE.det3~bins, data = datae)
boxplot(dE.det4~bins, data = datae)
boxplot(dE.det1:dE.det4~bins, data = datae)
hexbinplot(dE.det1~dE.det2, data=datae.fullAbsorption, colramp=rf,
aspect=1, trans=log, inv=exp,xbins = 100,
mincnt=1)
hexbinplot(dE.det2~dE.det3, data=datae.fullAbsorption, colramp=rf,
aspect=1, trans=log, inv=exp,xbins = 100,
mincnt=1)
hexbinplot(dE.det3~dE.det4, data=datae.fullAbsorption, colramp=rf,
aspect=1, trans=log, inv=exp,xbins = 100,
mincnt=1)
# 3d ----------------------------------------------------------------------
library(scatterplot3d)
scatterplot3d(datae.fullAbsorption$dE.det1, # x axis
datae.fullAbsorption$dE.det2, # y axis
datae.fullAbsorption$E0.keV # z axis
)
install.packages(c("rgl", "car"))
library("car", "rgl")
scatter3d(datae$dE.det2, # x axis
datae$E0.keV, # y axis
datae$dE.det3, # z axis
main="")
# thresholds --------------------------------------------------------------
GetThresholds <- function(data = datae, quant=5 ){
thres<- apply(data[,2:5],2,
quantile,
probs=c(quant, 100-quant)/100)
# додумать надо
# cat("Was:\n", thres)
for(i in 1:4){
# делаем замену обоих порогов в случае малых значений на ноль и младший порог
if ( (thres[1,i] < least.thresholds[i])&
(thres[2,i] < least.thresholds[i])){
thres[1,i] <- 0
thres[2,i] <- least.thresholds[i]
}
# и замену младшего порога в случае если только он попал
if ( (thres[1,i] < least.thresholds[i])&(thres[1,i] > least.thresholds[i]/2)&
(thres[2,i] > least.thresholds[i])){
thres[1,i] <- least.thresholds[i]
}
# и замену младшего порога в случае если только он попал
if ( (thres[1,i] < least.thresholds[i]/2)&
(thres[2,i] > least.thresholds[i])){
thres[1,i] <- 0
}
}
# cat("Now:\n", thres)
return(thres)
}
# 595 ---------------------------------------------------------------------
# должна быть таблица
# д1 д2 д3 д4
# 5 95 5 95...
#
# table.595 <- by(datae, datae[,"bins"], GetThresholds, quant = 5)
# table.595 <- by(datae.collimator, datae.collimator[,"bins"], GetThresholds, quant = 5)
table.595 <- by(datae.fullAbsorption, datae.fullAbsorption[,"bins"], GetThresholds, quant = 5)
# table.595 <- by(datae.fullAbsorption, datae.fullAbsorption[,"bins"], GetThresholds, quant = 5)
# есть таблица!
# table.595<-table.595[-1]
# выполняем округление до десятков кэВ
table.595 <- lapply(table.595, round, -1)
print(table.595)
# 2575 -------------------------------------------------------------------
# table.2575 <- by(datae, datae[,"bins"], GetThresholds, quant = 25)
# table.2575 <- by(datae.collimator, datae.collimator[,"bins"], GetThresholds, quant = 25)
table.2575 <- by(datae.fullAbsorption, datae.fullAbsorption[,"bins"], GetThresholds, quant = 25)
# table.2575 <- by(datae.fullAbsorption, datae.fullAbsorption[,"bins"], GetThresholds, quant = 25)
# table.2575<-table.2575[-1]
# выполняем округление до десятков кэВ
table.2575 <- lapply(table.2575, round, -1)
print(table.2575)
# classics ----------------------------------------------------------------
GetClassicsThresholds <- function( ){
e1 <- matrix(c(150, Inf, 120, 350, 0, 800, 0, Inf), ncol=4)
colnames(e1) <- c("dE.det1","dE.det2","dE.det3","dE.det4")
rownames(e1) <- c("low","high")
e1 <- as.table(e1)
e2 <- matrix(c(0, 150, 350, 500, 0, 800, 0, Inf), ncol=4)
colnames(e2) <- c("dE.det1","dE.det2","dE.det3","dE.det4")
rownames(e2) <- c("low","high")
e2 <- as.table(e2)
e3 <- matrix(c(0, 150, 500, 800, 0, 800, 0, Inf), ncol=4)
colnames(e3) <- c("dE.det1","dE.det2","dE.det3","dE.det4")
rownames(e3) <- c("low","high")
e3 <- as.table(e3)
e4 <- matrix(c(0, 150, 120, 500, 800, 2000, 0, 200), ncol=4)
colnames(e4) <- c("dE.det1","dE.det2","dE.det3","dE.det4")
rownames(e4) <- c("low","high")
e4 <- as.table(e4)
e5 <- matrix(c(0, 150, 120, 500, 2000, 4000, 0, 200), ncol=4)
colnames(e5) <- c("dE.det1","dE.det2","dE.det3","dE.det4")
rownames(e5) <- c("low","high")
e5 <- as.table(e5)
e6 <- matrix(c(0, 150, 120, 500, 4000, 10000, 0, 200), ncol=4)
colnames(e6) <- c("dE.det1","dE.det2","dE.det3","dE.det4")
rownames(e6) <- c("low","high")
e6 <- as.table(e6)
table.classic <- list(e1,e2,e3,e4,e5,e6)
# print(table.classic)
return(table.classic)
}
table.classic <- GetClassicsThresholds()
print(table.classic)
# save tables -------------------------------------------------------------
sink("table595.elec.txt")
print(table.595)
sink()
sink("table2575.elec.txt")
print(table.2575)
sink()
sink("table.classic.elec.txt")
print(table.classic)
sink()
setwd("D:/Ivan/_flash backup 2014/SINP/Группировка/2017 Группировка/radmonitoring/radmonitoring/analisys/percentile")
table.classic <- read.delim("table.classic.elec.txt")
table.595 <- read.table("table595.elec.txt")
table.2575 <- read.delim("table2575.elec.txt")
table.595.t <- as.table(table.595)
# decision tree analisys --------------------------------------------------
library(rpart)
# drop e0
# grow tree
# datae.fullAbsorption.sample <-sample_n(datae.fullAbsorption, 1000)
datae.fullAbsorption.sample <- datae.fullAbsorption[(datae.fullAbsorption$bins!='e0'),]
plot(table(datae.fullAbsorption.sample$bins))
fit <- rpart(bins ~ dE.det1 + dE.det2 + dE.det3 + dE.det4,
method="class", data=datae.fullAbsorption.sample)
print(fit)
printcp(fit) # display the results
plotcp(fit) # visualize cross-validation results
summary(fit) # detailed summary of splits
# plot tree
plot(fit, uniform=TRUE,
main="Classification Tree for datae.fullAbsorption.sample")
text(fit, use.n=TRUE, all=TRUE, cex=.8)
datae.newdata<-na.omit(datae[(datae$bins!='e0'),])
p <- predict(fit, datae.newdata, type = "class")
datae.newdata$bins.tree <- p
summary(p)
plot(p)
plot(datae.newdata$bins)
plot(table(p))
plot(table(datae.newdata$bins))
boxplot(datae.newdata$E0.keV~p)
density(datae.newdata$E0.keV~p)
plot(data = datae.newdata,bins~bins.tree)
# Violin Plots
library(vioplot)
x1 <- mtcars$mpg[mtcars$cyl==4]
x2 <- mtcars$mpg[mtcars$cyl==6]
x3 <- mtcars$mpg[mtcars$cyl==8]
vioplot(x1, x2, x3, names=c("4 cyl", "6 cyl", "8 cyl"),
col="gold")
title("Violin Plots of Miles Per Gallon")
vioplot(datae.newdata$E0.keV[datae.newdata$bins.tree=='e1'],
datae.newdata$E0.keV[datae.newdata$bins.tree=='e2'],
datae.newdata$E0.keV[datae.newdata$bins.tree=='e3'],
datae.newdata$E0.keV[datae.newdata$bins.tree=='e4'],
datae.newdata$E0.keV[datae.newdata$bins.tree=='e5'],
names=c("e1", "e2", "e3", "e4","e5"),
col="gold")
# Conditional Inference Tree for Kyphosis------------------------------
# what is
library(party)
fit <- ctree(bins ~ dE.det1 + dE.det2 + dE.det3 + dE.det4,
data=na.omit(datae.fullAbsorption))
plot(fit, main="Conditional Inference Tree for Kyphosis")
p <- predict(fit, datae.newdata)
datae.newdata$bins.tree <- p
summary(datae.newdata)
plot(data = datae.newdata,E0.keV~bins.tree)
# Median Regression (Quantile Regression) -----------------------------------------------------
install.packages("quantreg")
library(quantreg)
qs <- 1:9/10
datae.fullAbsorption$sum <- datae.fullAbsorption$dE.det1+datae.fullAbsorption$dE.det2+datae.fullAbsorption$dE.det3+datae.fullAbsorption$dE.det4
qr2 <- rq(datae$E0.keV ~ (datae$dE.det1+datae$dE.det2+datae$dE.det3+datae$dE.det4),
data=datae.fullAbsorption, tau = qs)
ggplot(datae.fullAbsorption, aes(E0.keV, dE.det1+dE.det2+dE.det3+dE.det4)) + geom_point() + geom_quantile(quantiles = qs)
summary(qr2)
plot(summary(qr2), parm="datae$dE.det1")
plot(summary(qr2))
plot(qr2)
# f <- function(x, a) sum((x-a)^2)
qr2 <- rq(datae$E0.keV ~ datae$dE.det1+datae$dE.det2+datae$dE.det3+datae$dE.det4,
data=datae, tau = qs)
xyplot(foodexp~income , data =engel,
type = c("g"),
auto.key=list(x=.8,y=.35,cex=.8,cex.title=.8, title="", points=TRUE),
scales=list(tck=-1),ylab=list("Food Expenditure",font=3),
xlab=list("Household Income",font=3),
panel=function(x,y,...){
panel.xyplot(x,y)
panel.grid()
panel.abline(rq(y ~ x, tau = 0.5))
panel.points(x, y, cex = 0.5, col = "blue")
panel.abline(rq(y ~ x, tau = 0.5), col = "blue")
panel.abline(lm(y ~ x), lty = 2, col = "red")
taus <- c(0.05, 0.1, 0.25, 0.75, 0.9, 0.95)
for (i in 1:length(taus)) {
panel.abline(rq(y ~ x, tau = taus[i]),
col = "gray")
}
}
)
# predict.percent ---------------------------------------------------------
predict.percent <- function(data, orig, tab){
return(data[((data$dE.det1 >= tab[1,1]) & data$dE.det1 <= tab[2,1])&
((data$dE.det2 >= tab[1,2]) & data$dE.det2 <= tab[2,2])&
((data$dE.det3 >= tab[1,3]) & data$dE.det3 <= tab[2,3])&
((data$dE.det4 >= tab[1,4]) & datae$dE.det4 <= tab[2,4]),]
)
}
# plotting ----------------------------------------------------------------
#
# дополняем ее столбцом по эффективности критерия и селективности
#
# строим графики по селективности для каждого типа криетриев
# 5-95 25-75 и классики
plotdEfromE4bwruBig <- function(data, main = "", orig, tab){
# data <- channel
# orig<-electron
layout(matrix(rep(1:12), 3, 4, byrow = TRUE),
widths=c(3,1,3,1),
heights=c(4,4,1)
)
color1 = "navy";
color2 = "olivedrab";
color3 = "turquoise";
color4 = "greenyellow";
color5 = "red";
markers1=c(1, 0);
markers2=c(16, 17);
#par(fig=c(0,0.25,0,1),new=TRUE)
#par(fig=c(0.2,1,0,1),new=FALSE)
par(mar=c(5.1,4.1,4.1,0.1))
plot(orig$E0.keV,orig$dE.det1,
ylim=range(c(na.omit(orig$dE.det1),na.omit(data$dE.det1))),
xlim=range(c(na.omit(orig$E0.keV),na.omit(data$E0.keV))),
axes=TRUE,ann=FALSE,
col= ifelse(orig$ang_z < 17, color3, color4),
pch = ifelse(orig$ang_z < 17, markers2[1],markers2[2]))
axis(4)
par(new=T)
plot(data$E0.keV,data$dE.det1,
# main="детектор 1",
# xlab="E0, кэВ",
# ylab="dE, кэВ",
main="detector 1",
xlab="E0, keV",
ylab="dE, keV",
ylim=range(c(na.omit(orig$dE.det1),na.omit(data$dE.det1))),
xlim=range(c(na.omit(orig$E0.keV),na.omit(data$E0.keV))),
col= ifelse(data$ang_z < 17, color1, color2),
pch = ifelse(data$ang_z < 17, markers1[1],markers1[2]))
# axis(1, 900:2000)
axis(2)
par(new=F)
rect(xleft =min(c(orig$E0.keV,data$E0.keV)),
xright=max(c(orig$E0.keV,data$E0.keV)),
ybottom = tab[1,1],ytop = tab[2,1], border = color5)
box()
minor.tick(nx=0, ny=4, tick.ratio=0.5)
legend("topright",
# c("коллиматор отбор", "корпус отбор",
# "первичный поток в коллиматоре",
# "первичный поток ч/з корпус"),
c("collimator classif", "casing ",
"collimator",
"casing"),
pch=c(markers1,markers2),
cex=.8, col=c(color1, color2, color3, color4))
par(mar=c(5.1,0.1,4.1,2.1))
boxplot(orig$dE.det1~orig$dE.det1>150, axes=FALSE, varwidth=T)
axis(1,at=1:2,labels= paste(c("dE<150","dE>150")), las=2)
#par(fig=c(0,0.25,0,1),new=TRUE)
#par(fig=c(0.2,1,0,1),new=FALSE)
par(mar=c(5.1,4.1,4.1,0.1))
plot(orig$E0.keV,orig$dE.det2,
ylim=range(c(na.omit(orig$dE.det2),na.omit(data$dE.det2))),
xlim=range(c(na.omit(orig$E0.keV),na.omit(data$E0.keV))),
# ylim=range(c(orig$dE.det2,data$dE.det2)),
# xlim=range(c(orig$E0.keV,data$E0.keV)),
axes=FALSE,ann=FALSE,
col= ifelse(orig$ang_z < 17, color3, color4),
pch = ifelse(orig$ang_z < 17, markers2[1],markers2[2]))
axis(4)
par(new=T)
plot(data$E0.keV,data$dE.det2,
ylim=range(c(na.omit(orig$dE.det2),na.omit(data$dE.det2))),
xlim=range(c(na.omit(orig$E0.keV),na.omit(data$E0.keV))),
# ylim=range(c(orig$dE.det2,data$dE.det2)),
# xlim=range(c(orig$E0.keV,data$E0.keV)),
main="detector 2",
xlab="E0, keV",
ylab="dE, keV",
col= ifelse(data$ang_z < 17, color1, color2),
pch = ifelse(data$ang_z < 17, markers1[1],markers1[2]))
minor.tick(nx=0, ny=4, tick.ratio=0.5)
# legend("topright", c("коллиматор", "корпус"), pch=markers,
# cex=.8, col=c(color1, color2))
rect(xleft =min(c(orig$E0.keV,data$E0.keV)),
xright=max(c(orig$E0.keV,data$E0.keV)),
ybottom = tab[1,2],ytop = tab[2,2], border = color5)
par(mar=c(5.1,0.1,4.1,2.1))
boxplot(orig$dE.det2~orig$dE.det2>120, axes=FALSE, varwidth=T)
axis(1,at=1:2,labels= paste(c("dE<120","dE>120")), las=2)
#par(fig=c(0,0.25,0,1),new=TRUE)
#par(fig=c(0.2,1,0,1),new=FALSE)
par(mar=c(5.1,4.1,4.1,0.1))
plot(orig$E0.keV,orig$dE.det3,
ylim=range(c(na.omit(orig$dE.det3),na.omit(data$dE.det3))),
xlim=range(c(na.omit(orig$E0.keV),na.omit(data$E0.keV))),
# ylim=range(c(orig$dE.det3,data$dE.det3)),
# xlim=range(c(orig$E0.keV,data$E0.keV)),
axes=FALSE,ann=FALSE,
col= ifelse(orig$ang_z < 17, color3, color4),
pch = ifelse(orig$ang_z < 17, markers2[1],markers2[2]))
axis(4)
par(new=T)
plot(data$E0.keV,data$dE.det3,
ylim=range(c(na.omit(orig$dE.det3),na.omit(data$dE.det3))),
xlim=range(c(na.omit(orig$E0.keV),na.omit(data$E0.keV))),
# ylim=range(c(orig$dE.det3,data$dE.det3)),
# xlim=range(c(orig$E0.keV,data$E0.keV)),
main="detector 3",
xlab="E0, keV",
ylab="dE, keV",
col= ifelse(data$ang_z < 17, color1, color2),
pch = ifelse(data$ang_z < 17, markers1[1],markers1[2]))
minor.tick(nx=0, ny=4, tick.ratio=0.5)
# legend("topright", c("коллиматор", "корпус"), pch=markers,
# cex=.8, col=c(color1, color2))
rect(xleft =min(c(orig$E0.keV,data$E0.keV)),
xright=max(c(orig$E0.keV,data$E0.keV)),
ybottom = tab[1,3],ytop = tab[2,3], border = color5)
par(mar=c(5.1,0.1,4.1,2.1))
boxplot(orig$dE.det3~orig$dE.det3>800, axes=FALSE, varwidth=T)
axis(1,at=1:2,labels= paste(c("dE<800","dE>800")), las=2)
#par(fig=c(0,0.25,0,1),new=TRUE)
#par(fig=c(0.2,1,0,1),new=FALSE)
par(mar=c(5.1,4.1,4.1,0.1))
plot(orig$E0.keV,orig$dE.det4,
ylim=range(c(na.omit(orig$dE.det4),na.omit(data$dE.det4))),
xlim=range(c(na.omit(orig$E0.keV),na.omit(data$E0.keV))),
# ylim=range(c(orig$dE.det4,data$dE.det4)),
# xlim=range(c(orig$E0.keV,data$E0.keV)),
axes=FALSE,ann=FALSE,
col= ifelse(orig$ang_z < 17, color3, color4),
pch = ifelse(orig$ang_z < 17, markers2[1],markers2[2]))
axis(4)
par(new=T)
plot(data$E0.keV,data$dE.det4,
ylim=range(c(na.omit(orig$dE.det4),na.omit(data$dE.det4))),
xlim=range(c(na.omit(orig$E0.keV),na.omit(data$E0.keV))),
# ylim=range(c(orig$dE.det4,data$dE.det4)),
# xlim=range(c(orig$E0.keV,data$E0.keV)),
main="detector 4",
xlab="E0, keV",
ylab="dE, keV",
col= ifelse(data$ang_z < 17, color1, color2),
pch = ifelse(data$ang_z < 17, markers1[1],markers1[2]))
minor.tick(nx=0, ny=4, tick.ratio=0.5)
# legend("topright", c("коллиматор", "корпус"), pch=markers,
# cex=.8, col=c(color1, color2))
rect(xleft =min(c(orig$E0.keV,data$E0.keV)),
xright=max(c(orig$E0.keV,data$E0.keV)),
ybottom = tab[1,4],ytop = tab[2,4], border = color5)
par(mar=c(5.1,0.1,4.1,2.1))
boxplot(orig$dE.det4~orig$dE.det4>200, axes=F, varwidth=T)
# axis(1,at=1:1,labels= "dE>200", las=2)
axis(1,at=1:2,labels= paste(c("dE<200","dE>200")), las=2)
# Очень нужна информация об отношении бок - коллиматор зарегистрированных электронов
# в D2 и D3 во всех электронных каналах для трех вариантов корпусов:
# латунь, дюраль, дюраль с внутренней вставкой из вольфрама
# со стробом в D2 и без него..
dole2 <- nrow(orig[(orig$ang_z < 17)&(orig$dE.det2 > 0)&(orig$dE.det3 > 0) ,])/
nrow(orig[(orig$ang_z >= 17)&(orig$dE.det2 > 0)&(orig$dE.det3 > 0) ,])
a<- paste("Исходный поток в канале коллиматор-боковые (dE2,3 больше нуля):",
signif(dole2, digits = 2), " = ",
nrow(orig[(orig$ang_z < 17)&(orig$dE.det2 > 0)&(orig$dE.det3 > 0) ,]),'/',
nrow(orig[(orig$ang_z >= 17)&(orig$dE.det2 > 0)&(orig$dE.det3 > 0) ,]),
sep = " ")
mtext(a, side=1, outer=TRUE, line=-5, cex=0.8)
dole1 <- nrow(orig[(orig$ang_z < 17) ,])/
nrow(orig[(orig$ang_z >= 17) ,])
a<- paste("Исходный поток в канале коллиматор-боковые (без ограничений):",
signif(dole1, digits = 2), " = ",
nrow(orig[(orig$ang_z < 17) ,]),'/',
nrow(orig[(orig$ang_z >= 17) ,]),
sep = " ")
mtext(a, side=1, outer=TRUE, line=-4, cex=0.8)
dole <- nrow(data[(data$ang_z < 17),])/nrow(data[(data$ang_z >= 17),])
a<- paste("В отобранных событиях коллиматор-боковые:"# числа боковых зарегистрированных пролетов к числу пролетов через коллиматор:
, signif(dole, digits = 2), " = ",
nrow(data[(data$ang_z < 17),]),'/',
nrow(data[(data$ang_z >= 17),]),
sep = " ")
mtext(a, side=1, outer=TRUE, line=-3, cex=0.8)
sensetivity <- nrow(data[(data$E0.keV >= min(orig$E0.keV)) &
(data$E0.keV <= max(orig$E0.keV)),])/nrow(orig)
a<- paste("Чувствительность(геометрический фактор):"# числа боковых зарегистрированных пролетов к числу пролетов через коллиматор:
, signif(sensetivity, digits = 2) ,sep = " ")
mtext(a, side=1, outer=TRUE, line=-2, cex=0.8)
precision <- nrow(data[(data$E0.keV >= min(orig$E0.keV)) &
(data$E0.keV <= max(orig$E0.keV)),])/nrow(data)
a<- paste("Точность(количество правильно определенных частиц):"# числа боковых зарегистрированных пролетов к числу пролетов через коллиматор:
, signif(precision, digits = 2) , " = ",
nrow(data[(data$E0.keV >= min(orig$E0.keV)) &
(data$E0.keV <= max(orig$E0.keV)),]),'/',
nrow(data),
sep = " ")
mtext(a, side=1, outer=TRUE, line=-1, cex=0.8)
# dole <- nrow(orig[(orig$ang_z < 17),])/nrow(orig[(orig$ang_z >= 17),])
# a<- paste("Первичные коллиматор/боковые:"# числа боковых зарегистрированных пролетов к числу пролетов через коллиматор:
# , signif(dole, digits = 1) ,sep = " ")
#
#
# mtext(a, side=1, outer=TRUE, line=-1)
mtext(main, side=3, outer=TRUE, line=-1, cex=0.8)
}
plotdEfromE4bwruBig1 <- function(data, main = "", orig, tab){
layout(matrix(rep(1:12), 3, 4, byrow = TRUE),
widths=c(3,1,3,1),
heights=c(4,4,1)
)
color1 = "navy";
color2 = "olivedrab";
color3 = "turquoise";
color4 = "greenyellow";
color5 = "red";
markers1=c(1, 0);
markers2=c(16, 17);
par(mar=c(5.1,4.1,4.1,0.1))
plot(orig$E0.keV,orig$dE.det1,
ylim=range(c(orig$dE.det1,data$dE.det1)),
xlim=range(c(orig$E0.keV,data$E0.keV)),
axes=TRUE,ann=FALSE,
col= ifelse(orig$ang_z < 17, color3, color4),
pch = ifelse(orig$ang_z < 17, markers2[1],markers2[2]))
axis(4)
par(new=T)
plot(data$E0.keV,data$dE.det1,
main="детектор 1",
xlab="E0, кэВ",
ylab="dE, кэВ",
ylim=range(c(orig$dE.det1,data$dE.det1)),
xlim=range(c(orig$E0.keV,data$E0.keV)),
col= ifelse(data$ang_z < 17, color1, color2),
pch = ifelse(data$ang_z < 17, markers1[1],markers1[2]))
# axis(1, 900:2000)
axis(2)
par(new=F)
rect(ybottom = tab[1,1],ytop = tab[2,1], border = color5)
box()
minor.tick(nx=0, ny=4, tick.ratio=0.5)
legend("topright", c("коллиматор", "корпус",
"первичный поток в коллиматоре"
# ,"поток ч/з корпус"
), pch=c(markers1,markers2),
cex=.8, col=c(color1, color2, color3, color4))
par(mar=c(5.1,0.1,4.1,2.1))
boxplot(orig$dE.det1~orig$dE.det1>150, axes=FALSE, varwidth=T)
axis(1,at=1:2,labels= paste(c("dE<150","dE>150")), las=2)
# числа боковых зарегистрированных пролетов к числу пролетов через коллиматор:
dole <- nrow(data[(data$ang_z < 17),])/nrow(data[(data$ang_z >= 17),])
a<- paste("В отобранных событиях коллиматор/боковые:"
, signif(dole, digits = 2) ,sep = " ")
mtext(a, side=1, outer=TRUE, line=-3, cex=0.8)
#
# sensetivity <- nrow(data)/nrow(orig)
sensetivity <- nrow(data[(data$E0.keV >= min(orig$E0.keV)) &
(data$E0.keV <= max(orig$E0.keV)),])/nrow(orig)
a<- paste("Чувствительность(геометрический фактор):"
, signif(sensetivity, digits = 2) ,sep = " ")
mtext(a, side=1, outer=TRUE, line=-2, cex=0.8)
#
precision <- nrow(data[(data$E0.keV >= min(orig$E0.keV)) &
(data$E0.keV <= max(orig$E0.keV)),])/nrow(data)
a<- paste("Селективность(количество правильно определенных частиц):"
, signif(precision, digits = 2) ,sep = " ")
mtext(a, side=1, outer=TRUE, line=-1, cex=0.8)
mtext(main, side=3, outer=TRUE, line=-1, cex=0.8)
}
plotChannel <- function( tab, n){
proton<-datae[((datae$bins == paste("e", n, sep=""))), ]
# proton<-datae[((datae$ang_z < 17) & (datae$bins == paste("e", n, sep=""))), ]
# proton<-datae[( (datae$bins == paste("p", n, sep=""))), ]
channel<-datae[((datae$dE.det1 >= tab[1,1]) & datae$dE.det1 <= tab[2,1])&
((datae$dE.det2 >= tab[1,2]) & datae$dE.det2 <= tab[2,2])&
((datae$dE.det3 >= tab[1,3]) & datae$dE.det3 <= tab[2,3])&
((datae$dE.det4 >= tab[1,4]) & datae$dE.det4 <= tab[2,4]),]
main = paste("Канал",n,":",round(min(proton$E0.keV), -2),round(max(proton$E0.keV), -2),
"Отбор:", deparse(substitute(tab)),
"Корпус",casing, sep = " ")
plotdEfromE4bwruBig(channel, main, proton, tab)
}
plotChannelSide <- function( tab, n){
# electron<-datae[((datae$ang_z < 17) & (datae$bins == paste("p", n, sep=""))), ]
electron<-datae[( (datae$bins == paste("e", n, sep=""))), ]
channel<-datae[((datae$dE.det1 >= tab[1,1]) & datae$dE.det1 <= tab[2,1])&
((datae$dE.det2 >= tab[1,2]) & datae$dE.det2 <= tab[2,2])&
((datae$dE.det3 >= tab[1,3]) & datae$dE.det3 <= tab[2,3])&
((datae$dE.det4 >= tab[1,4]) & datae$dE.det4 <= tab[2,4]),]
main = paste("Канал",n,":",round(min(na.omit(electron$E0.keV)), -1),round(max(na.omit(electron$E0.keV)), -1),
"Отбор:", deparse(substitute(tab)),
"Корпус",casing, sep = " ")
plotdEfromE4bwruBig(channel, main, electron, tab)
}
savePlotCannel <- function(n=1){
getwd()
setwd("D:/Ivan/_flash backup 2014/SINP/Группировка/2017 Группировка/radmonitoring/radmonitoring/analisys/percentile/report3")
ppi <- 600
# n <-1
png(paste("electron",n,casing,"classicen.png", sep=""), width=6*ppi, height=6*ppi, res=ppi)
# pdf(paste("proton",n,casing,"classic.pdf", sep=""))
# tab <-table.classic[[n]]
plotChannelSide(table.classic[[n]], n)
dev.off()
png(paste("electron",n,casing,"2575en.png", sep=""), width=6*ppi, height=6*ppi, res=ppi)
# # pdf(paste("proton",n,casing,"classic.pdf", sep=""))
plotChannelSide(table.2575[[n]], n)
dev.off()
png(paste("electron",n,casing,"595en.png", sep=""), width=6*ppi, height=6*ppi, res=ppi)
# # pdf(paste("proton",n,casing,"classic.pdf", sep=""))
plotChannelSide(table.595[[n]], n)
dev.off()
}
# строим гистограмму энергии в каждом канале
for (i in 1:8)
savePlotCannel(i)
# тест с другими корпусами ------------------------------------------------
getwd()
setwd("D:/Ivan/_flash backup 2014/SINP/Группировка/2017 Группировка/radmonitoring/radmonitoring/analisys/percentile/report3")
casing <-'A'
datae<-read.table(paste("electrons_",casing,".dat", sep=''), header = TRUE)
datae$bins <- cut(datae$E0.keV, breaks, labels= labels)
# строим гистограмму энергии в каждом канале
for (i in 1:6)
savePlotCannel(i)
casing <-'B'
datae<-read.table(paste("electrons_",casing,".dat", sep=''), header = TRUE)
datae$bins <- cut(datae$E0.keV, breaks, labels= labels)
# строим гистограмму энергии в каждом канале
for (i in 1:6)
savePlotCannel(i)
casing <-'C'
datae<-read.table(paste("electrons_",casing,".dat", sep=''), header = TRUE)
datae$bins <- cut(datae$E0.keV, breaks, labels= labels)
# строим гистограмму энергии в каждом канале
for (i in 1:6)
savePlotCannel(i)
casing <-'D'
datae<-read.table(paste("electrons_",casing,".dat", sep=''), header = TRUE)
datae$bins <- cut(datae$E0.keV, breaks, labels= labels)
datae <- na.omit(datae)
# строим гистограмму энергии в каждом канале
for (i in 1:6)
savePlotCannel(i)
# таблицы для тулупова по сравнению корпусов -----------------------------
casing <-'A'
cat('\nКорпус',casing, 'Общее число частиц:', nrow(datae) )
datae %>%
group_by( ., E, dE.det2 > 0, dE.det3 > 0) %>%
summarise( ., number=n())
setwd("D:/Simulink/report2")
datae<-read.table('var1_L14.dat', header = TRUE)
cat('\nКорпус','var1_L14', 'Общее число частиц:', nrow(datae) )
temp<-datae %>%
group_by( .,ang_z >5, E0.keV >150, dE.det2 > 12, dE.det3 > 0) %>%
summarise( ., number=n())
write.csv2(temp, 'var1_L14.csv')
# таблицы для тулупова по сравнению корпусов 2 -----------------------------
cat('\nКорпус',casing, 'Общее число частиц:', nrow(datae) )
datae %>%
group_by( ., E, dE.det2 > 0, dE.det3 > 0) %>%
summarise( ., number=n())
setwd("d:/Simulink/report/")
datae<-read.table('electrons_D.dat', header = TRUE)
cat('\nКорпус','electrons_D', 'Общее число частиц:', nrow(datae) )
temp<-datae %>%
group_by( ., E0.keV >150, dE.det2 > 0, dE.det3 > 0, ang_z >17) %>%
summarise( ., number=n())
write.csv2(temp, 'electrons_D.csv')
# таблицы для тулупова по сравнению корпусов 3 -----------------------------
cat('\nКорпус',casing, 'Общее число частиц:', nrow(datae) )
datae %>%
group_by( ., E, dE.det2 > 0, dE.det3 > 0) %>%
summarise( ., number=n())
setwd("d:/Simulink/data/alldet/")
datae<-read.table('electr_C_L14.dat', header = TRUE)
cat('\nКорпус','var1_L34', 'Общее число частиц:', nrow(datae) )
temp<-datae %>%
group_by( ., E0.keV >150, dE.det2 > 0, dE.det3 > 0, CF ==TRUE) %>%
summarise( ., number=n())
write.csv2(temp, 'electr_C_L14.dat.csv')
# таблицы для тулупова по сравнению корпусов 4 -----------------------------
setwd("d:/Simulink/data/alldet/")
datae<-read.table('electr_B_L32.dat', header = TRUE)
cat('\nКорпус','electr_B_L32.dat', 'Общее число частиц:', nrow(datae) )
temp<-datae %>%
group_by( ., E0.keV >150, dE.det2 > 0, dE.det3 > 0, CF ==TRUE) %>%
summarise( ., number=n())
write.csv2(temp, 'electr_B_L32.dat.csv')
# таблицы для тулупова по сравнению корпусов 5 -----------------------------
setwd("d:/Simulink/data/alldet/")
datae<-read.table('electr_D_L14.dat', header = TRUE)
cat('\nКорпус','electr_D_L14.dat', 'Общее число частиц:', nrow(datae) )
temp<-datae %>%
group_by( ., E0.keV >150, dE.det2 > 0, dE.det3 > 0, CF ==TRUE) %>%
summarise( ., number=n())
write.csv2(temp, 'electr_D_L14.dat.csv')
# таблицы для тулупова по сравнению корпусов 5 -----------------------------
setwd("d:/Simulink/report/")
datae<-read.table('electrons_D.dat', header = TRUE)
cat('\nКорпус','electrons_D.dat', 'Общее число частиц:', nrow(datae) )
temp<-datae %>%
group_by( ., E0.keV >150, dE.det2 > 0, dE.det3 > 0, CF ==TRUE) %>%
summarise( ., number=n())
write.csv2(temp, 'electrons_D.dat.csv')
datae<-read.table('electrons_D.dat', header = TRUE)
# таблицы для тулупова по сравнению корпусов 6 -----------------------------
pdf(paste("elecprotdde2.pdf", sep="" ), width =20, height=20)
n = 20
colr = rev(rainbow(n, start = 0, end = 4/6, alpha = 0.5))
setwd("d:/Simulink/report/")
filename<-'electrons_B.dat'
datae<-read.table(filename, header = TRUE)
cat('\nКорпус','electrons_D.dat', 'Общее число частиц:', nrow(datae) )
breaks.angle <- seq(0, 180, length.out = 180/5+1)
breaks.dEdet2 <- seq(0, 5000, length.out = 30+1)
datae$bins.angle <- cut(as.numeric(datae$ang_z), breaks.angle)
datae$bins.dE2 <- cut(as.numeric(datae$dE.det2), breaks.dEdet2)
hist.n <- datae[datae$dE.det2>0,] %>%
group_by(., bins.angle, bins.dE2) %>%
summarise(., n =n())
hist.n <- na.omit(hist.n)
print(hist.n )
write.csv2(hist.n, paste0("NdEdet2", filename))
print(cloud(n ~ bins.angle * bins.dE2, data = hist.n, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det2',main = filename,
#zlim = c(0,60),
col.facet = level.colors(hist.n$n, at = do.breaks(range(hist.n$n), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(range(hist.n$n), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
hist.sum <- datae[datae$dE.det2>0,] %>%
group_by(., bins.angle, bins.dE2) %>%
summarise(., sum =sum(na.omit(as.numeric(dE.det2))))
hist.sum <- na.omit(hist.sum)
print(hist.sum )
write.csv2(hist.sum, paste0("SdEdet2", filename))
print(cloud(sum ~ bins.angle * bins.dE2, data = hist.sum, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det2',zlab = 'summ dE.det2',main = filename,
#zlim = c(0,100000),
col.facet = level.colors(hist.sum$sum, at = do.breaks(range(hist.sum$sum), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(range(hist.sum$sum), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
setwd("d:/Simulink/report/")
filename<-'electrons_D.dat'
datae<-read.table(filename, header = TRUE)
cat('\nКорпус','electrons_D.dat', 'Общее число частиц:', nrow(datae) )
breaks.angle <- seq(0, 180, length.out = 180/5+1)
breaks.dEdet2 <- seq(0, 5000, length.out = 30+1)
datae$bins.angle <- cut(as.numeric(datae$ang_z), breaks.angle)
datae$bins.dE2 <- cut(as.numeric(datae$dE.det2), breaks.dEdet2)
hist.n <- datae[datae$dE.det2>0,] %>%
group_by(., bins.angle, bins.dE2) %>%
summarise(., n =n())
hist.n <- na.omit(hist.n)
print(hist.n )
write.csv2(hist.n, paste0("NdEdet2", filename))
print(cloud(n ~ bins.angle * bins.dE2, data = hist.n, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det2',main = filename,
#zlim = c(0,60),
col.facet = level.colors(hist.n$n, at = do.breaks(range(hist.n$n), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(range(hist.n$n), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
hist.sum <- datae[datae$dE.det2>0,] %>%
group_by(., bins.angle, bins.dE2) %>%
summarise(., sum =sum(na.omit(as.numeric(dE.det2))))
hist.sum <- na.omit(hist.sum)
print(hist.sum )
write.csv2(hist.sum, paste0("SdEdet2", filename))
print(cloud(sum ~ bins.angle * bins.dE2, data = hist.sum, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det2',zlab = 'summ dE.det2',main = filename,
#zlim = c(0,100000),
col.facet = level.colors(hist.sum$sum, at = do.breaks(range(hist.sum$sum), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(range(hist.sum$sum), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
setwd("d:/Simulink/report/")
filename<-'protons_B.dat'
datae<-read.table(filename, header = TRUE)
cat('\nКорпус','electrons_D.dat', 'Общее число частиц:', nrow(datae) )
breaks.angle <- seq(0, 180, length.out = 180/5+1)
breaks.dEdet2 <- seq(0, 5000, length.out = 30+1)
datae$bins.angle <- cut(as.numeric(datae$ang_z), breaks.angle)
datae$bins.dE2 <- cut(as.numeric(datae$dE.det2), breaks.dEdet2)
hist.n <- datae[datae$dE.det2>0,] %>%
group_by(., bins.angle, bins.dE2) %>%
summarise(., n =n())
hist.n <- na.omit(hist.n)
print(hist.n )
write.csv2(hist.n, paste0("NdEdet2", filename))
print(cloud(n ~ bins.angle * bins.dE2, data = hist.n, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det2',main = filename,
# zlim = c(0,60),
col.facet = level.colors(hist.n$n, at = do.breaks(range(hist.n$n), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(range(hist.n$n), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
hist.sum <- datae[datae$dE.det2>0,] %>%
group_by(., bins.angle, bins.dE2) %>%
summarise(., sum =sum(na.omit(as.numeric(dE.det2))))
hist.sum <- na.omit(hist.sum)
print(hist.sum )
write.csv2(hist.sum, paste0("SdEdet2", filename))
print(cloud(sum ~ bins.angle * bins.dE2, data = hist.sum, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det2',zlab = 'summ dE.det2',main = filename,
# zlim = c(0,100000),
col.facet = level.colors(hist.sum$sum, at = do.breaks(range(hist.sum$sum), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(range(hist.sum$sum), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
setwd("d:/Simulink/report/")
filename<-'protons_D.dat'
datae<-read.table(filename, header = TRUE)
cat('\nКорпус','electrons_D.dat', 'Общее число частиц:', nrow(datae) )
breaks.angle <- seq(0, 180, length.out = 180/5+1)
breaks.dEdet2 <- seq(0, 5000, length.out = 30+1)
datae$bins.angle <- cut(as.numeric(datae$ang_z), breaks.angle)
datae$bins.dE2 <- cut(as.numeric(datae$dE.det2), breaks.dEdet2)
hist.n <- datae[datae$dE.det2>0,] %>%
group_by(., bins.angle, bins.dE2) %>%
summarise(., n =n())
hist.n <- na.omit(hist.n)
print(hist.n )
write.csv2(hist.n, paste0("NdEdet2", filename))
print(cloud(n ~ bins.angle * bins.dE2, data = hist.n, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det2',main = filename,
#zlim = c(0,60),
col.facet = level.colors(hist.n$n, at = do.breaks(range(hist.n$n), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(range(hist.n$n), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
hist.sum <- datae[datae$dE.det2>0,] %>%
group_by(., bins.angle, bins.dE2) %>%
summarise(., sum =sum(na.omit(as.numeric(dE.det2))))
hist.sum <- na.omit(hist.sum)
print(hist.sum )
write.csv2(hist.sum, paste0("SdEdet2", filename))
print(cloud(sum ~ bins.angle * bins.dE2, data = hist.sum, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det2',zlab = 'summ dE.det2',main = filename,
#zlim = c(0,100000),
col.facet = level.colors(hist.sum$sum, at = do.breaks(range(hist.sum$sum), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(range(hist.sum$sum), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
dev.off()
# таблицы для тулупова по сравнению корпусов 7 -----------------------------
pdf(paste("elecprotdde3.pdf", sep="" ), width =20, height=20)
n = 20
colr = rev(rainbow(n, start = 0, end = 4/6, alpha = 0.5))
setwd("d:/Simulink/report/")
filename<-'electrons_B.dat'
datae<-read.table(filename, header = TRUE)
cat('\nКорпус','electrons_D.dat', 'Общее число частиц:', nrow(datae) )
breaks.angle <- seq(0, 180, length.out = 180/5+1)
breaks.dEdet3 <- seq(0, 5000, length.out = 30+1)
datae$bins.angle <- cut(as.numeric(datae$ang_z), breaks.angle)
datae$bins.dE3 <- cut(as.numeric(datae$dE.det3), breaks.dEdet3)
hist.n <- datae[datae$dE.det3>0,] %>%
group_by(., bins.angle, bins.dE3) %>%
summarise(., n =n())
hist.n <- na.omit(hist.n)
print(hist.n )
write.csv2(hist.n, paste0("NdEdet3", filename))
print(cloud(n ~ bins.angle * bins.dE3, data = hist.n, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det3',main = filename,
#zlim = c(0,60),
col.facet = level.colors(hist.n$n, at = do.breaks(range(hist.n$n), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(range(hist.n$n), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
hist.sum <- datae[datae$dE.det3>0,] %>%
group_by(., bins.angle, bins.dE3) %>%
summarise(., sum =sum(na.omit(as.numeric(dE.det3))))
hist.sum <- na.omit(hist.sum)
print(hist.sum )
write.csv2(hist.sum, paste0("SdEdet3", filename))
print(cloud(sum ~ bins.angle * bins.dE3, data = hist.sum, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det3',zlab = 'summ dE.det3',main = filename,
#zlim = c(0,100000),
col.facet = level.colors(hist.sum$sum, at = do.breaks(range(hist.sum$sum), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(range(hist.sum$sum), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
setwd("d:/Simulink/report/")
filename<-'electrons_D.dat'
datae<-read.table(filename, header = TRUE)
cat('\nКорпус','electrons_D.dat', 'Общее число частиц:', nrow(datae) )
breaks.angle <- seq(0, 180, length.out = 180/5+1)
breaks.dEdet3 <- seq(0, 5000, length.out = 30+1)
datae$bins.angle <- cut(as.numeric(datae$ang_z), breaks.angle)
datae$bins.dE3 <- cut(as.numeric(datae$dE.det3), breaks.dEdet3)
hist.n <- datae[datae$dE.det3>0,] %>%
group_by(., bins.angle, bins.dE3) %>%
summarise(., n =n())
hist.n <- na.omit(hist.n)
print(hist.n )
write.csv2(hist.n, paste0("NdEdet3", filename))
print(cloud(n ~ bins.angle * bins.dE3, data = hist.n, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det3',main = filename,
#zlim = c(0,60),
col.facet = level.colors(hist.n$n, at = do.breaks(range(hist.n$n), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(range(hist.n$n), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
hist.sum <- datae[datae$dE.det3>0,] %>%
group_by(., bins.angle, bins.dE3) %>%
summarise(., sum =sum(na.omit(as.numeric(dE.det3))))
hist.sum <- na.omit(hist.sum)
print(hist.sum )
write.csv2(hist.sum, paste0("SdEdet3", filename))
print(cloud(sum ~ bins.angle * bins.dE3, data = hist.sum, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det3',zlab = 'summ dE.det3',main = filename,
#zlim = c(0,100000),
col.facet = level.colors(hist.sum$sum, at = do.breaks(range(hist.sum$sum), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(range(hist.sum$sum), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
setwd("d:/Simulink/report/")
filename<-'protons_B.dat'
datae<-read.table(filename, header = TRUE)
cat('\nКорпус','electrons_D.dat', 'Общее число частиц:', nrow(datae) )
breaks.angle <- seq(0, 180, length.out = 180/5+1)
breaks.dEdet3 <- seq(0, 5000, length.out = 30+1)
datae$bins.angle <- cut(as.numeric(datae$ang_z), breaks.angle)
datae$bins.dE3 <- cut(as.numeric(datae$dE.det3), breaks.dEdet3)
hist.n <- datae[datae$dE.det3>0,] %>%
group_by(., bins.angle, bins.dE3) %>%
summarise(., n =n())
hist.n <- na.omit(hist.n)
print(hist.n )
write.csv2(hist.n, paste0("NdEdet3", filename))
print(cloud(n ~ bins.angle * bins.dE3, data = hist.n, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det3',main = filename,
#zlim = c(0,60),
col.facet = level.colors(hist.n$n, at = do.breaks(range(hist.n$n), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(range(hist.n$n), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
hist.sum <- datae[datae$dE.det3>0,] %>%
group_by(., bins.angle, bins.dE3) %>%
summarise(., sum =sum(na.omit(as.numeric(dE.det3))))
hist.sum <- na.omit(hist.sum)
print(hist.sum )
write.csv2(hist.sum, paste0("SdEdet3", filename))
print(cloud(sum ~ bins.angle * bins.dE3, data = hist.sum, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det3',zlab = 'summ dE.det3',main = filename,
#zlim = c(0,100000),
col.facet = level.colors(hist.sum$sum, at = do.breaks(range(hist.sum$sum), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(range(hist.sum$sum), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
setwd("d:/Simulink/report/")
filename<-'protons_D.dat'
datae<-read.table(filename, header = TRUE)
cat('\nКорпус','electrons_D.dat', 'Общее число частиц:', nrow(datae) )
breaks.angle <- seq(0, 180, length.out = 180/5+1)
breaks.dEdet3 <- seq(0, 5000, length.out = 30+1)
datae$bins.angle <- cut(as.numeric(datae$ang_z), breaks.angle)
datae$bins.dE3 <- cut(as.numeric(datae$dE.det3), breaks.dEdet3)
hist.n <- datae[datae$dE.det3>0,] %>%
group_by(., bins.angle, bins.dE3) %>%
summarise(., n =n())
hist.n <- na.omit(hist.n)
print(hist.n )
write.csv2(hist.n, paste0("NdEdet3", filename))
print(cloud(n ~ bins.angle * bins.dE3, data = hist.n, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det3',main = filename,
#zlim = c(0,60),
col.facet = level.colors(hist.n$n, at = do.breaks(range(hist.n$n), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(range(hist.n$n), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
hist.sum <- datae[datae$dE.det3>0,] %>%
group_by(., bins.angle, bins.dE3) %>%
summarise(., sum =sum(na.omit(as.numeric(dE.det3))))
hist.sum <- na.omit(hist.sum)
print(hist.sum )
write.csv2(hist.sum, paste0("SdEdet3", filename))
print(cloud(sum ~ bins.angle * bins.dE3, data = hist.sum, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det3',zlab = 'summ dE.det3',main = filename,
#zlim = c(0,100000),
col.facet = level.colors(hist.sum$sum, at = do.breaks(range(hist.sum$sum), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(range(hist.sum$sum), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
dev.off()
# plot angle --------------------------------------------------------------
setwd("d:/Simulink/report/")
filename <- 'electrons_A.dat'
datae<-read.table(filename, header = TRUE)
cat('\nКорпус ', filename, 'Общее число частиц:', nrow(datae) )
plot(data = datae, x = datae$ang_z, y = datae$dE.det2/datae$dE.det3, log = "y")
densityplot( x = datae[ datae$dE.det3>0,]$ang_z, log = "y")
densityplot( x = datae[ datae$dE.det2>0,]$ang_z, log = "y")
plot(data = datae, x = datae$ang_z, y = datae$dE.det1)
plot(data = datae, x = datae$ang_z, y = datae$dE.det2, log = "y")
plot(data = datae, x = datae$ang_z, y = datae$dE.det3, log = "y")
plot(data = datae, x = datae$ang_z, y = datae$dE.det4, log = "y")
plot(data = datae, x = datae$ang_z, y = datae$dE.det3/datae$dE.det2, log = "y")
hexbinplot(dE.det2~dE.det3, data=datae, colramp=rf, log = 'x',
aspect=1, trans=log, inv=exp,xbins = 100,
mincnt=1)
hexbinplot(dE.det1~dE.det2, data=datae, colramp=rf, log = 'x',
aspect=1, trans=log, inv=exp,
xbins = 100,
mincnt=1)
pdf(paste("elec1.pdf", sep=""))
filename <- 'electrons_A.dat'
datae<-read.table(filename, header = TRUE)
hexbinplot(dE.det3~ang_z, data=datae[datae$dE.det3>0,], colramp=rf, log = 'x',
aspect=1, trans=log, inv=exp,mincnt=1, maxcnt =100,
# xbins = 100,
main = paste("Electrons dE.det3 > 0,",filename,nrow(datae), sep=" "))
hexbinplot(dE.det3~E0.keV, data=datae[datae$dE.det3>0,], colramp=rf,
aspect=1, trans=log, inv=exp, mincnt=1, maxcnt =100,
xbins = 100,
main = paste("Electrons dE.det3 > 0,",filename, nrow(datae), sep=" "))
filename <- 'electrons_B.dat'
datae<-read.table(filename, header = TRUE)
hexbinplot(dE.det3~ang_z, data=datae[datae$dE.det3>0,], colramp=rf, log = 'x',
aspect=1, trans=log, inv=exp,mincnt=1, maxcnt =100,
# xbins = 100,
main = paste("Electrons dE.det3 > 0,",filename,nrow(datae), sep=" "))
hexbinplot(dE.det3~E0.keV, data=datae[datae$dE.det3>0,], colramp=rf,
aspect=1, trans=log, inv=exp, mincnt=1, maxcnt =100,
xbins = 100,
main = paste("Electrons dE.det3 > 0,",filename, nrow(datae), sep=" "))
filename <- 'electrons_C.dat'
datae<-read.table(filename, header = TRUE)
hexbinplot(dE.det3~ang_z, data=datae[datae$dE.det3>0,], colramp=rf, log = 'x',
aspect=1, trans=log, inv=exp,mincnt=1, maxcnt =100,
# xbins = 100,
main = paste("Electrons dE.det3 > 0,",filename,nrow(datae), sep=" "))
hexbinplot(dE.det3~E0.keV, data=datae[datae$dE.det3>0,], colramp=rf,
aspect=1, trans=log, inv=exp, mincnt=1, maxcnt =100,
xbins = 100,
main = paste("Electrons dE.det3 > 0,",filename, nrow(datae), sep=" "))
filename <- 'electrons_D.dat'
datae<-read.table(filename, header = TRUE)
hexbinplot(dE.det3~ang_z, data=datae[datae$dE.det3>0,], colramp=rf, log = 'x',
aspect=1, trans=log, inv=exp,mincnt=1, maxcnt =100,
# xbins = 100,
main = paste("Electrons dE.det3 > 0,",filename,nrow(datae), sep=" "))
hexbinplot(dE.det3~E0.keV, data=datae[datae$dE.det3>0,], colramp=rf,
aspect=1, trans=log, inv=exp, mincnt=1, maxcnt =100,
xbins = 100,
main = paste("Electrons dE.det3 > 0,",filename, nrow(datae), sep=" "))
dev.off()
# plot angle 3d -----------------------------------------------------------
require(lattice)
require(latticeExtra)
# data(VADeaths)
# histograms d3
pdf(paste("elec3d.pdf", sep="" ), width =10, height=10)
filename <- 'electrons_D.dat'
datae<-read.table(filename, header = TRUE)
breaks.angle <- seq(0, 180, length.out = 180/5+1)
breaks.dEdet3 <- seq(0, 3000, length.out = 30+1)
datae$bins.angle <- cut(as.numeric(datae$ang_z), breaks.angle)
datae$bins.dE3 <- cut(as.numeric(datae$dE.det3), breaks.dEdet3)
hist.n <- datae[datae$dE.det3>0,] %>%
group_by(., bins.angle, bins.dE3) %>%
summarise(., n =n())
hist.n <- na.omit(hist.n)
print(hist.n)
print(cloud(n ~ bins.angle * bins.dE3, data = hist.n, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det3',main = filename,
zlim = c(0,60),
col.facet = level.colors(hist.n$n, at = do.breaks(c(0, 60), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(c(0, 60), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
hist.sum <- datae[datae$dE.det3>0,] %>%
group_by(., bins.angle, bins.dE3) %>%
summarise(., sum =sum(na.omit(as.numeric(dE.det3))))
hist.sum <- na.omit(hist.sum)
print(hist.sum)
write.csv2(hist.sum, paste0("S", filename))
print(cloud(sum ~ bins.angle * bins.dE3, data = hist.sum, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det3',zlab = 'summ dE.det3',main = filename,
zlim = c(0,3000),
col.facet = level.colors(hist.sum$sum, at = do.breaks(c(0, 3000), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(c(0, 3000), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
dev.off()
# histograms d2
pdf(paste("elec3d2.pdf", sep="" ), width =10, height=10)
filename <- 'electrons_D.dat'
datae<-read.table(filename, header = TRUE)
breaks.angle <- seq(0, 180, length.out = 180/5+1)
breaks.dEdet2 <- seq(0, 3000, length.out = 30+1)
datae$bins.angle <- cut(as.numeric(datae$ang_z), breaks.angle)
datae$bins.dE2 <- cut(as.numeric(datae$dE.det2), breaks.dEdet2)
hist.n <- datae[datae$dE.det2>0,] %>%
group_by(., bins.angle, bins.dE2) %>%
summarise(., n =n())
hist.n <- na.omit(hist.n)
print(hist.n)
print(cloud(n ~ bins.angle * bins.dE2, data = hist.n, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det2',main = filename,
zlim = c(0,300),
col.facet = level.colors(hist.n$n, at = do.breaks(c(0, 300), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(c(0, 300), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
hist.sum <- datae[datae$dE.det2>0,] %>%
group_by(., bins.angle, bins.dE2) %>%
summarise(., sum =sum(na.omit(as.numeric(dE.det2))))
hist.sum <- na.omit(hist.sum)
print(hist.sum)
print(cloud(sum ~ bins.angle * bins.dE2, data = hist.sum, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det2',zlab = 'summ dE.det2',main = filename,
zlim = c(0,30000),
col.facet = level.colors(hist.sum$sum, at = do.breaks(c(0, 30000), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(c(0, 30000), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
dev.off()
# plot angle report 3 det--------------------------------------------------------------
# here I can
setwd("d:/Simulink/report3/")
pdf(paste("elec3dde3.pdf", sep="" ), width =20, height=20)
# Brass_el_1e8_L32 --------------------------------------------------------
filename <- 'Brass_el_1e8_L32.csv'
datae<-read.csv(filename, header = TRUE, skip = 11)
cat('\nКорпус ', filename, 'Общее число частиц:', nrow(datae) )
breaks.angle <- seq(0, 180, length.out = 180/5+1)
breaks.dEdet3 <- seq(0, 3000, length.out = 30+1)
datae$bins.angle <- cut(as.numeric(datae$angz), breaks.angle)
datae$bins.dE3 <- cut(as.numeric(datae$Det3.keV), breaks.dEdet3)
hist.n <- datae[datae$Det3.keV>0,] %>%
group_by(., bins.angle, bins.dE3) %>%
summarise(., n =n())
hist.n <- na.omit(hist.n)
print(hist.n)
write.csv2(hist.n, paste0("NdEdet3", filename))
print(cloud(n ~ bins.angle * bins.dE3, data = hist.n, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det3',main = filename,
zlim = c(0,60),
col.facet = level.colors(hist.n$n, at = do.breaks(c(0, 60), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(c(0, 60), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
hist.sum <- datae[datae$Det3.keV>0,] %>%
group_by(., bins.angle, bins.dE3) %>%
summarise(., sum =sum(na.omit(as.numeric(Det3.keV))))
hist.sum <- na.omit(hist.sum)
print(hist.sum)
write.csv2(hist.sum, paste0("SEdet3", filename))
print(cloud(sum ~ bins.angle * bins.dE3, data = hist.sum, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det3',zlab = 'summ dE.det3',main = filename,
zlim = c(0,3000),
col.facet = level.colors(hist.sum$sum, at = do.breaks(c(0, 3000), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(c(0, 3000), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
# Dural_el_1e8_L32 --------------------------------------------------------
filename <- 'Dural_el_1e8_L32.csv'
datae<-read.csv(filename, header = TRUE, skip = 11)
cat('\nКорпус ', filename, 'Общее число частиц:', nrow(datae) )
breaks.angle <- seq(0, 180, length.out = 180/5+1)
breaks.dEdet3 <- seq(0, 3000, length.out = 30+1)
datae$bins.angle <- cut(as.numeric(datae$angz), breaks.angle)
datae$bins.dE3 <- cut(as.numeric(datae$Det3.keV), breaks.dEdet3)
hist.n <- datae[datae$Det3.keV>0,] %>%
group_by(., bins.angle, bins.dE3) %>%
summarise(., n =n())
hist.n <- na.omit(hist.n)
print(hist.n)
write.csv2(hist.n, paste0("NEdet3", filename))
print(cloud(n ~ bins.angle * bins.dE3, data = hist.n, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det3',main = filename,
zlim = c(0,60),
col.facet = level.colors(hist.n$n, at = do.breaks(c(0, 60), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(c(0, 60), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
hist.sum <- datae[datae$Det3.keV>0,] %>%
group_by(., bins.angle, bins.dE3) %>%
summarise(., sum =sum(na.omit(as.numeric(Det3.keV))))
hist.sum <- na.omit(hist.sum)
print(hist.sum)
write.csv2(hist.sum, paste0("SEdet3", filename))
print(cloud(sum ~ bins.angle * bins.dE3, data = hist.sum, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det3',zlab = 'summ dE.det3',main = filename,
zlim = c(0,3000),
col.facet = level.colors(hist.sum$sum, at = do.breaks(c(0, 3000), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(c(0, 3000), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
# Brass_el_1e8_L32_trigg --------------------------------------------------------
filename <- 'Brass_el_1e8_L32_trigg.csv'
datae<-read.csv(filename, header = TRUE, skip = 11)
cat('\nКорпус ', filename, 'Общее число частиц:', nrow(datae) )
breaks.angle <- seq(0, 180, length.out = 180/5+1)
breaks.dEdet3 <- seq(0, 3000, length.out = 30+1)
datae$bins.angle <- cut(as.numeric(datae$angz), breaks.angle)
datae$bins.dE3 <- cut(as.numeric(datae$Det3.keV), breaks.dEdet3)
hist.n <- datae[datae$Det3.keV>0,] %>%
group_by(., bins.angle, bins.dE3) %>%
summarise(., n =n())
hist.n <- na.omit(hist.n)
print(hist.n)
write.csv2(hist.n, paste0("NEdet3", filename))
print(cloud(n ~ bins.angle * bins.dE3, data = hist.n, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det3',main = filename,
zlim = c(0,60),
col.facet = level.colors(hist.n$n, at = do.breaks(c(0, 60), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(c(0, 60), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
hist.sum <- datae[datae$Det3.keV>0,] %>%
group_by(., bins.angle, bins.dE3) %>%
summarise(., sum =sum(na.omit(as.numeric(Det3.keV))))
hist.sum <- na.omit(hist.sum)
print(hist.sum )
write.csv2(hist.sum, paste0("SEdet3", filename))
print(cloud(sum ~ bins.angle * bins.dE3, data = hist.sum, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det3',zlab = 'summ dE.det3',main = filename,
zlim = c(0,3000),
col.facet = level.colors(hist.sum$sum, at = do.breaks(c(0, 3000), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(c(0, 3000), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
# Dural_el_1e8_L32_trigg --------------------------------------------------------
filename <- 'Dural_el_1e8_L32_trigg.csv'
datae<-read.csv(filename, header = TRUE, skip = 11)
cat('\nКорпус ', filename, 'Общее число частиц:', nrow(datae) )
breaks.angle <- seq(0, 180, length.out = 180/5+1)
breaks.dEdet3 <- seq(0, 3000, length.out = 30+1)
datae$bins.angle <- cut(as.numeric(datae$angz), breaks.angle)
datae$bins.dE3 <- cut(as.numeric(datae$Det3.keV), breaks.dEdet3)
hist.n <- datae[datae$Det3.keV>0,] %>%
group_by(., bins.angle, bins.dE3) %>%
summarise(., n =n())
hist.n <- na.omit(hist.n)
print(hist.n )
write.csv2(hist.n, paste0("NEdet3", filename))
print(cloud(n ~ bins.angle * bins.dE3, data = hist.n, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det3',main = filename,
zlim = c(0,60),
col.facet = level.colors(hist.n$n, at = do.breaks(c(0, 60), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(c(0, 60), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
hist.sum <- datae[datae$Det3.keV>0,] %>%
group_by(., bins.angle, bins.dE3) %>%
summarise(., sum =sum(na.omit(as.numeric(Det3.keV))))
hist.sum <- na.omit(hist.sum)
print(hist.sum )
write.csv2(hist.sum, paste0("SEdet3", filename))
print(cloud(sum ~ bins.angle * bins.dE3, data = hist.sum, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det3',zlab = 'summ dE.det3',main = filename,
zlim = c(0,3000),
col.facet = level.colors(hist.sum$sum, at = do.breaks(c(0, 3000), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(c(0, 3000), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
dev.off()
# plot angle report 2 det--------------------------------------------------------------
# here I can
setwd("d:/Simulink/report3/")
pdf(paste("elec3ddet2.pdf", sep="" ), width =20, height=20)
# Brass_el_1e8_L32 --------------------------------------------------------
filename <- 'Brass_el_1e8_L32.csv'
datae<-read.csv(filename, header = TRUE, skip = 11)
cat('\nКорпус ', filename, 'Общее число частиц:', nrow(datae) )
breaks.angle <- seq(0, 180, length.out = 180/5+1)
breaks.dEdet2 <- seq(0, 3000, length.out = 30+1)
datae$bins.angle <- cut(as.numeric(datae$angz), breaks.angle)
datae$bins.dE2 <- cut(as.numeric(datae$Det2.keV), breaks.dEdet2)
hist.n <- datae[datae$Det2.keV>0,] %>%
group_by(., bins.angle, bins.dE2) %>%
summarise(., n =n())
hist.n <- na.omit(hist.n)
print(hist.n )
write.csv2(hist.n, paste0("NdEdet2", filename))
print(cloud(n ~ bins.angle * bins.dE2, data = hist.n, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det2',main = filename,
zlim = c(0,60),
col.facet = level.colors(hist.n$n, at = do.breaks(c(0, 60), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(c(0, 60), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
hist.sum <- datae[datae$Det2.keV>0,] %>%
group_by(., bins.angle, bins.dE2) %>%
summarise(., sum =sum(na.omit(as.numeric(Det2.keV))))
hist.sum <- na.omit(hist.sum)
print(hist.sum )
write.csv2(hist.sum, paste0("SdEdet2", filename))
print(cloud(sum ~ bins.angle * bins.dE2, data = hist.sum, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det2',zlab = 'summ dE.det2',main = filename,
zlim = c(0,3000),
col.facet = level.colors(hist.sum$sum, at = do.breaks(c(0, 3000), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(c(0, 3000), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
# Dural_el_1e8_L32 --------------------------------------------------------
filename <- 'Dural_el_1e8_L32.csv'
datae<-read.csv(filename, header = TRUE, skip = 11)
cat('\nКорпус ', filename, 'Общее число частиц:', nrow(datae) )
breaks.angle <- seq(0, 180, length.out = 180/5+1)
breaks.dEdet2 <- seq(0, 3000, length.out = 30+1)
datae$bins.angle <- cut(as.numeric(datae$angz), breaks.angle)
datae$bins.dE2 <- cut(as.numeric(datae$Det2.keV), breaks.dEdet2)
hist.n <- datae[datae$Det2.keV>0,] %>%
group_by(., bins.angle, bins.dE2) %>%
summarise(., n =n())
hist.n <- na.omit(hist.n)
print(hist.n)
write.csv2(hist.n, paste0("NdEdet2", filename))
print(cloud(n ~ bins.angle * bins.dE2, data = hist.n, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det2',main = filename,
zlim = c(0,60),
col.facet = level.colors(hist.n$n, at = do.breaks(c(0, 60), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(c(0, 60), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
hist.sum <- datae[datae$Det2.keV>0,] %>%
group_by(., bins.angle, bins.dE2) %>%
summarise(., sum =sum(na.omit(as.numeric(Det2.keV))))
hist.sum <- na.omit(hist.sum)
print(hist.sum)
write.csv2(hist.sum, paste0("SdEdet2", filename))
print(cloud(sum ~ bins.angle * bins.dE2, data = hist.sum, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det2',zlab = 'summ dE.det2',main = filename,
zlim = c(0,3000),
col.facet = level.colors(hist.sum$sum, at = do.breaks(c(0, 3000), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(c(0, 3000), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
# Brass_el_1e8_L32_trigg --------------------------------------------------------
filename <- 'Brass_el_1e8_L32_trigg.csv'
datae<-read.csv(filename, header = TRUE, skip = 11)
cat('\nКорпус ', filename, 'Общее число частиц:', nrow(datae) )
breaks.angle <- seq(0, 180, length.out = 180/5+1)
breaks.dEdet2 <- seq(0, 3000, length.out = 30+1)
datae$bins.angle <- cut(as.numeric(datae$angz), breaks.angle)
datae$bins.dE2 <- cut(as.numeric(datae$Det2.keV), breaks.dEdet2)
hist.n <- datae[datae$Det2.keV>0,] %>%
group_by(., bins.angle, bins.dE2) %>%
summarise(., n =n())
hist.n <- na.omit(hist.n)
print(hist.n)
write.csv2(hist.n, paste0("NdEdet2", filename))
print(cloud(n ~ bins.angle * bins.dE2, data = hist.n, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det2',main = filename,
zlim = c(0,60),
col.facet = level.colors(hist.n$n, at = do.breaks(c(0, 60), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(c(0, 60), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
hist.sum <- datae[datae$Det2.keV>0,] %>%
group_by(., bins.angle, bins.dE2) %>%
summarise(., sum =sum(na.omit(as.numeric(Det2.keV))))
hist.sum <- na.omit(hist.sum)
print(hist.sum)
write.csv2(hist.sum, paste0("SdEdet2", filename))
print(cloud(sum ~ bins.angle * bins.dE2, data = hist.sum, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det2',zlab = 'summ dE.det2',main = filename,
zlim = c(0,3000),
col.facet = level.colors(hist.sum$sum, at = do.breaks(c(0, 3000), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(c(0, 3000), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
# Dural_el_1e8_L32_trigg --------------------------------------------------------
filename <- 'Dural_el_1e8_L32_trigg.csv'
datae<-read.csv(filename, header = TRUE, skip = 11)
cat('\nКорпус ', filename, 'Общее число частиц:', nrow(datae) )
breaks.angle <- seq(0, 180, length.out = 180/5+1)
breaks.dEdet2 <- seq(0, 3000, length.out = 30+1)
datae$bins.angle <- cut(as.numeric(datae$angz), breaks.angle)
datae$bins.dE2 <- cut(as.numeric(datae$Det2.keV), breaks.dEdet2)
hist.n <- datae[datae$Det2.keV>0,] %>%
group_by(., bins.angle, bins.dE2) %>%
summarise(., n =n())
hist.n <- na.omit(hist.n)
print(hist.n)
write.csv2(hist.n, paste0("NdEdet2", filename))
print(cloud(n ~ bins.angle * bins.dE2, data = hist.n, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det2',main = filename,
zlim = c(0,60),
col.facet = level.colors(hist.n$n, at = do.breaks(c(0, 60), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(c(0, 60), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
hist.sum <- datae[datae$Det2.keV>0,] %>%
group_by(., bins.angle, bins.dE2) %>%
summarise(., sum =sum(na.omit(as.numeric(Det2.keV))))
hist.sum <- na.omit(hist.sum)
print(hist.sum)
write.csv2(hist.sum, paste0("SdEdet2", filename))
print(cloud(sum ~ bins.angle * bins.dE2, data = hist.sum, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det2',zlab = 'summ dE.det2',main = filename,
zlim = c(0,3000),
col.facet = level.colors(hist.sum$sum, at = do.breaks(c(0, 3000), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(c(0, 3000), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
dev.off()
# plot angle report 4 det--------------------------------------------------------------
# here I can
setwd("d:/Simulink/report3/")
pdf(paste("elec3ddet4.pdf", sep="" ), width =20, height=20)
# Brass_el_1e8_L32 --------------------------------------------------------
filename <- 'Brass_el_1e8_L32.csv'
datae<-read.csv(filename, header = TRUE, skip = 11)
cat('\nКорпус ', filename, 'Общее число частиц:', nrow(datae) )
breaks.angle <- seq(0, 180, length.out = 180/5+1)
breaks.dEdet4 <- seq(0, 3000, length.out = 30+1)
datae$bins.angle <- cut(as.numeric(datae$angz), breaks.angle)
datae$bins.dE4 <- cut(as.numeric(datae$Det4.keV), breaks.dEdet4)
hist.n <- datae[datae$Det4.keV>0,] %>%
group_by(., bins.angle, bins.dE4) %>%
summarise(., n =n())
hist.n <- na.omit(hist.n)
print(hist.n)
write.csv2(hist.n, paste0("NdEdet4", filename))
print(cloud(n ~ bins.angle * bins.dE4, data = hist.n, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det4',main = filename,
zlim = c(0,60),
col.facet = level.colors(hist.n$n, at = do.breaks(c(0, 60), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(c(0, 60), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
hist.sum <- datae[datae$Det4.keV>0,] %>%
group_by(., bins.angle, bins.dE4) %>%
summarise(., sum =sum(na.omit(as.numeric(Det4.keV))))
hist.sum <- na.omit(hist.sum)
print(hist.sum)
write.csv2(hist.sum, paste0("SdEdet4", filename))
print(cloud(sum ~ bins.angle * bins.dE4, data = hist.sum, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det4',zlab = 'summ dE.det4',main = filename,
zlim = c(0,3000),
col.facet = level.colors(hist.sum$sum, at = do.breaks(c(0, 3000), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(c(0, 3000), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
# Dural_el_1e8_L32 --------------------------------------------------------
filename <- 'Dural_el_1e8_L32.csv'
datae<-read.csv(filename, header = TRUE, skip = 11)
cat('\nКорпус ', filename, 'Общее число частиц:', nrow(datae) )
breaks.angle <- seq(0, 180, length.out = 180/5+1)
breaks.dEdet4 <- seq(0, 3000, length.out = 30+1)
datae$bins.angle <- cut(as.numeric(datae$angz), breaks.angle)
datae$bins.dE4 <- cut(as.numeric(datae$Det4.keV), breaks.dEdet4)
hist.n <- datae[datae$Det4.keV>0,] %>%
group_by(., bins.angle, bins.dE4) %>%
summarise(., n =n())
hist.n <- na.omit(hist.n)
print(hist.n)
write.csv2(hist.n, paste0("NdEdet4", filename))
print(cloud(n ~ bins.angle * bins.dE4, data = hist.n, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det4',main = filename,
zlim = c(0,60),
col.facet = level.colors(hist.n$n, at = do.breaks(c(0, 60), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(c(0, 60), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
hist.sum <- datae[datae$Det4.keV>0,] %>%
group_by(., bins.angle, bins.dE4) %>%
summarise(., sum =sum(na.omit(as.numeric(Det4.keV))))
hist.sum <- na.omit(hist.sum)
print(hist.sum)
write.csv2(hist.sum, paste0("SdEdet4", filename))
print(cloud(sum ~ bins.angle * bins.dE4, data = hist.sum, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det4',zlab = 'summ dE.det4',main = filename,
zlim = c(0,3000),
col.facet = level.colors(hist.sum$sum, at = do.breaks(c(0, 3000), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(c(0, 3000), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
# Brass_el_1e8_L32_trigg --------------------------------------------------------
filename <- 'Brass_el_1e8_L32_trigg.csv'
datae<-read.csv(filename, header = TRUE, skip = 11)
cat('\nКорпус ', filename, 'Общее число частиц:', nrow(datae) )
breaks.angle <- seq(0, 180, length.out = 180/5+1)
breaks.dEdet4 <- seq(0, 3000, length.out = 30+1)
datae$bins.angle <- cut(as.numeric(datae$angz), breaks.angle)
datae$bins.dE4 <- cut(as.numeric(datae$Det4.keV), breaks.dEdet4)
hist.n <- datae[datae$Det4.keV>0,] %>%
group_by(., bins.angle, bins.dE4) %>%
summarise(., n =n())
hist.n <- na.omit(hist.n)
print(hist.n)
write.csv2(hist.n, paste0("NdEdet4", filename))
print(cloud(n ~ bins.angle * bins.dE4, data = hist.n, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det4',main = filename,
zlim = c(0,60),
col.facet = level.colors(hist.n$n, at = do.breaks(c(0, 60), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(c(0, 60), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
hist.sum <- datae[datae$Det4.keV>0,] %>%
group_by(., bins.angle, bins.dE4) %>%
summarise(., sum =sum(na.omit(as.numeric(Det4.keV))))
hist.sum <- na.omit(hist.sum)
print(hist.sum)
write.csv2(hist.sum, paste0("SdEdet4", filename))
print(cloud(sum ~ bins.angle * bins.dE4, data = hist.sum, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det4',zlab = 'summ dE.det4',main = filename,
zlim = c(0,3000),
col.facet = level.colors(hist.sum$sum, at = do.breaks(c(0, 3000), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(c(0, 3000), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
# Dural_el_1e8_L32_trigg --------------------------------------------------------
filename <- 'Dural_el_1e8_L32_trigg.csv'
datae<-read.csv(filename, header = TRUE, skip = 11)
cat('\nКорпус ', filename, 'Общее число частиц:', nrow(datae) )
breaks.angle <- seq(0, 180, length.out = 180/5+1)
breaks.dEdet4 <- seq(0, 3000, length.out = 30+1)
datae$bins.angle <- cut(as.numeric(datae$angz), breaks.angle)
datae$bins.dE4 <- cut(as.numeric(datae$Det4.keV), breaks.dEdet4)
hist.n <- datae[datae$Det4.keV>0,] %>%
group_by(., bins.angle, bins.dE4) %>%
summarise(., n =n())
hist.n <- na.omit(hist.n)
print(hist.n)
write.csv2(hist.n, paste0("NdEdet4", filename))
print(cloud(n ~ bins.angle * bins.dE4, data = hist.n, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det4',main = filename,
zlim = c(0,60),
col.facet = level.colors(hist.n$n, at = do.breaks(c(0, 60), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(c(0, 60), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
hist.sum <- datae[datae$Det4.keV>0,] %>%
group_by(., bins.angle, bins.dE4) %>%
summarise(., sum =sum(na.omit(as.numeric(Det4.keV))))
hist.sum <- na.omit(hist.sum)
print(hist.sum)
write.csv2(hist.sum, paste0("SdEdet4", filename))
print(cloud(sum ~ bins.angle * bins.dE4, data = hist.sum, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det4',zlab = 'summ dE.det4',main = filename,
zlim = c(0,3000),
col.facet = level.colors(hist.sum$sum, at = do.breaks(c(0, 3000), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(c(0, 3000), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
dev.off()
# gamma Brass_gamma_1e7_1MeV --------------------------------------------------------
setwd("d:/Simulink/report3/")
filename <- 'Brass_gamma_1e7_1MeV.csv'
datae<-read.csv(filename, header = TRUE, skip = 11)
cat('\nКорпус ', filename, 'Общее число частиц:', nrow(datae) )
summary(datae)
hist(datae$Det1.keV, breaks = 100, col = "lightblue", border = "pink")
hist(datae$Det2.keV, breaks = 100, col = "lightblue", border = "pink")
hist(datae$Det3.keV, breaks = 100, col = "lightblue", border = "pink")
hist(datae$Det4.keV, breaks = 100, col = "lightblue", border = "pink")
pdf(paste("gammade3.pdf", sep="" ), width =10, height=10)
filename <- 'Brass_gamma_1e7_1MeV.csv'
datae<-read.csv(filename, header = TRUE, skip = 11)
hist(datae$Det3.keV, main = filename, breaks = 100, col = "lightblue", border = "pink")
hist(datae[datae$Det2.keV>120,]$Det3.keV, main = filename, breaks = 100, col = "lightblue", border = "pink")
filename <- 'Brass_gamma_1e7_1MeV_trigg.csv'
datae<-read.csv(filename, header = TRUE, skip = 11)
hist(datae$Det3.keV, main = filename, breaks = 100, col = "lightblue", border = "pink")
filename <- 'Brass_gamma_1e7_8MeV.csv'
datae<-read.csv(filename, header = TRUE, skip = 11)
hist(datae$Det3.keV, main = filename, breaks = 100, col = "lightblue", border = "pink")
hist(datae[datae$Det2.keV>120,]$Det3.keV, main = filename, breaks = 100, col = "lightblue", border = "pink")
filename <- 'Brass_gamma_1e7_8MeV_trigg.csv'
datae<-read.csv(filename, header = TRUE, skip = 11)
hist(datae$Det3.keV, main = filename, breaks = 100, col = "lightblue", border = "pink")
filename <- 'Dural_gamma_1e7_1MeV.csv'
datae<-read.csv(filename, header = TRUE, skip = 11)
hist(datae$Det3.keV, main = filename, breaks = 100, col = "lightblue", border = "pink")
filename <- 'Dural_gamma_1e7_1MeV_trigg.csv'
datae<-read.csv(filename, header = TRUE, skip = 11)
hist(datae$Det3.keV, main = filename, breaks = 100, col = "lightblue", border = "pink")
filename <- 'Dural_gamma_1e7_8MeV.csv'
datae<-read.csv(filename, header = TRUE, skip = 11)
hist(datae$Det3.keV, main = filename, breaks = 100, col = "lightblue", border = "pink")
filename <- 'Dural_gamma_1e7_8MeV_trigg.csv'
datae<-read.csv(filename, header = TRUE, skip = 11)
hist(datae$Det3.keV, main = filename, breaks = 100, col = "lightblue", border = "pink")
dev.off()
# parcoord ----------------------------------------------------------------
library(MASS)
# library(colorRamps)
# data(mtcars)
# k <- blue2red(100)
n = 6
colr = rev(rainbow(n, start = 0, end = 4/6, alpha = 0.2))
# k <- adjustcolor(brewer.pal(3, "Set1")[titdf2$Survived], alpha=.2)
dataedf <- as.data.frame(lapply(as.data.frame(datae), as.numeric))
# new columns with jittered values
dataedf[,9:10] <- lapply((dataedf[,c(6,8)]), jitter)
# x <- cut( datae$E0.keV, 100)
ppi <- 300
png(paste("parallelelec1",casing,".png", sep=""), width=6*ppi, height=6*ppi, res=ppi)
op <- par(mar=c(3, rep(.1, 3)))
parcoord(dataedf[,c(1,2,9,3,10,4,7)], col=colr[as.numeric(dataedf$bins)],
main = paste("поток электронов через прибор, \n , корпус",casing, sep=" ")
)
# par(op)
dev.off()
# alluvial ----------------------------------------------------------------
install.packages(file.choose(), repos=NULL)
library(alluvial)
#Titanic data
tit <- as.data.frame(Titanic)
# 2d
tit2d <- aggregate( Freq ~ Class + Survived, data=tit, sum)
alluvial( tit2d[,1:2], freq=tit2d$Freq, xw=0.0, alpha=0.8,
gap.width=0.1, col= "steelblue", border="white",
layer = tit2d$Survived != "Yes" )
casing <-'A'
datae<-read.table(paste("electrons_",casing,".dat", sep=''), header = TRUE)
datae$bins <- cut(datae$E0.keV, breaks, labels= labels)
datae <- datae%>%
group_by( bins, CF, dE.det2>120, dE.det3>800)%>%
summarise( freq = n())
datae <- na.omit(datae)
alluvial(datae, freq = datae$freq,
# col=ifelse( by.bins$CF == 0, "red", "green"),
col=colr[as.numeric(datae$bins)]
)
# бок-коллиматор для 2-3 детекторов ---------------------------------------
# Очень нужна информация об отношении бок - коллиматор зарегистрированных электронов
# в D2 и D3 во всех электронных каналах для трех вариантов корпусов:
# латунь, дюраль, дюраль с внутренней вставкой из вольфрама
# со стробом в D2 и без него..
# кросс тест с протнами ---------------------------------------------------------------------
# casing <-'D'
# datap<-read.table(paste("electrons_",casing,".dat", sep=''), header = TRUE)
# datap$bins <- cut(datap$E0.keV, breaks, labels= labels)
# plotCrossChannel <- function(n=1){
#
# ppi <- 300
# png(paste("crossEinP",n,casing,"classic.png", sep=""), width=6*ppi, height=6*ppi, res=ppi)
# # pdf(paste("proton",n,casing,"classic.pdf", sep=""))
# plotChannel(table.classic[[n]], n)
# # plotChannel(table.2575[[n+1]], n)
# # plotChannel(table.595[[n+1]], n)
# dev.off()
#
# png(paste("crossEinP",n,casing,"2575.png", sep=""), width=6*ppi, height=6*ppi, res=ppi)
# # pdf(paste("proton",n,casing,"classic.pdf", sep=""))
# plotChannel(table.2575[[n]], n)
# dev.off()
#
# png(paste("crossEinP",n,casing,"595.png", sep=""), width=6*ppi, height=6*ppi, res=ppi)
# # pdf(paste("proton",n,casing,"classic.pdf", sep=""))
# plotChannel(table.595[[n]], n)
# dev.off()
# }
# # строим гистограмму энергии в каждом канале
# for (i in 1:8)
# plotCrossChannel(i)
# off active device ----------------------------------------------------------
dev.off()
<file_sep>0. Выбор энергетических каналов будущего телескопа, минимума чувствительности(0,001) и селективности(0,5?)
1. получение первого приближения порогов энерговыдений(2575 или 595), исходя из фильтрованных последовательностей(убрать нули)
2. проба применения порогов для получения эффективности каналов
3. повторное применение отбора по измененным персентилям ->шаг алгоритма
4. проба применения порогов для получения эффективности каналов->шаг алгоритма
999. проба на других последовательностях
1000. проба на реальных данных с макета прибора
В перспективе возможен просто переход на робастные регрессионные методы, но все равно желетельно подготавливать тренировочные данные: фильтровать нулевые энерговыделения. https://stats.idre.ucla.edu/r/dae/robust-regression/ https://www.rdocumentation.org/packages/robustbase/versions/0.1-2/topics/ltsReg
<file_sep># CMAKE generated file: DO NOT EDIT!
# Generated by "Unix Makefiles" Generator, CMake Version 3.6
# Default target executed when no arguments are given to make.
default_target: all
.PHONY : default_target
# Allow only one "make -f Makefile2" at a time, but pass parallelism.
.NOTPARALLEL:
#=============================================================================
# Special targets provided by cmake.
# Disable implicit rules so canonical targets will work.
.SUFFIXES:
# Remove some rules from gmake that .SUFFIXES does not remove.
SUFFIXES =
.SUFFIXES: .hpux_make_needs_suffix_list
# Suppress display of executed commands.
$(VERBOSE).SILENT:
# A target that is always out of date.
cmake_force:
.PHONY : cmake_force
#=============================================================================
# Set environment variables for the build.
# The shell in which to execute make rules.
SHELL = /bin/sh
# The CMake executable.
CMAKE_COMMAND = /usr/local/bin/cmake
# The command to remove a file.
RM = /usr/local/bin/cmake -E remove -f
# Escaping for special characters.
EQUALS = =
# The top-level source directory on which CMake was run.
CMAKE_SOURCE_DIR = /home/local1/work/Telescope_tulupov/Telescope
# The top-level build directory on which CMake was run.
CMAKE_BINARY_DIR = /home/local1/work/Telescope_tulupov/Telescope-build
#=============================================================================
# Targets provided globally by CMake.
# Special rule for the target edit_cache
edit_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "No interactive CMake dialog available..."
/usr/local/bin/cmake -E echo No\ interactive\ CMake\ dialog\ available.
.PHONY : edit_cache
# Special rule for the target edit_cache
edit_cache/fast: edit_cache
.PHONY : edit_cache/fast
# Special rule for the target rebuild_cache
rebuild_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..."
/usr/local/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)
.PHONY : rebuild_cache
# Special rule for the target rebuild_cache
rebuild_cache/fast: rebuild_cache
.PHONY : rebuild_cache/fast
# Special rule for the target list_install_components
list_install_components:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Available install components are: \"Unspecified\""
.PHONY : list_install_components
# Special rule for the target list_install_components
list_install_components/fast: list_install_components
.PHONY : list_install_components/fast
# Special rule for the target install
install: preinstall
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..."
/usr/local/bin/cmake -P cmake_install.cmake
.PHONY : install
# Special rule for the target install
install/fast: preinstall/fast
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..."
/usr/local/bin/cmake -P cmake_install.cmake
.PHONY : install/fast
# Special rule for the target install/local
install/local: preinstall
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing only the local directory..."
/usr/local/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake
.PHONY : install/local
# Special rule for the target install/local
install/local/fast: install/local
.PHONY : install/local/fast
# Special rule for the target install/strip
install/strip: preinstall
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing the project stripped..."
/usr/local/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake
.PHONY : install/strip
# Special rule for the target install/strip
install/strip/fast: install/strip
.PHONY : install/strip/fast
# The main all target
all: cmake_check_build_system
$(CMAKE_COMMAND) -E cmake_progress_start /home/local1/work/Telescope_tulupov/Telescope-build/CMakeFiles /home/local1/work/Telescope_tulupov/Telescope-build/CMakeFiles/progress.marks
$(MAKE) -f CMakeFiles/Makefile2 all
$(CMAKE_COMMAND) -E cmake_progress_start /home/local1/work/Telescope_tulupov/Telescope-build/CMakeFiles 0
.PHONY : all
# The main clean target
clean:
$(MAKE) -f CMakeFiles/Makefile2 clean
.PHONY : clean
# The main clean target
clean/fast: clean
.PHONY : clean/fast
# Prepare targets for installation.
preinstall: all
$(MAKE) -f CMakeFiles/Makefile2 preinstall
.PHONY : preinstall
# Prepare targets for installation.
preinstall/fast:
$(MAKE) -f CMakeFiles/Makefile2 preinstall
.PHONY : preinstall/fast
# clear depends
depend:
$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1
.PHONY : depend
#=============================================================================
# Target rules for targets named Telescope
# Build rule for target.
Telescope: cmake_check_build_system
$(MAKE) -f CMakeFiles/Makefile2 Telescope
.PHONY : Telescope
# fast build rule for target.
Telescope/fast:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/build
.PHONY : Telescope/fast
Telescope.o: Telescope.cc.o
.PHONY : Telescope.o
# target to build an object file
Telescope.cc.o:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/Telescope.cc.o
.PHONY : Telescope.cc.o
Telescope.i: Telescope.cc.i
.PHONY : Telescope.i
# target to preprocess a source file
Telescope.cc.i:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/Telescope.cc.i
.PHONY : Telescope.cc.i
Telescope.s: Telescope.cc.s
.PHONY : Telescope.s
# target to generate assembly for a file
Telescope.cc.s:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/Telescope.cc.s
.PHONY : Telescope.cc.s
src/ActionInitialization.o: src/ActionInitialization.cc.o
.PHONY : src/ActionInitialization.o
# target to build an object file
src/ActionInitialization.cc.o:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/ActionInitialization.cc.o
.PHONY : src/ActionInitialization.cc.o
src/ActionInitialization.i: src/ActionInitialization.cc.i
.PHONY : src/ActionInitialization.i
# target to preprocess a source file
src/ActionInitialization.cc.i:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/ActionInitialization.cc.i
.PHONY : src/ActionInitialization.cc.i
src/ActionInitialization.s: src/ActionInitialization.cc.s
.PHONY : src/ActionInitialization.s
# target to generate assembly for a file
src/ActionInitialization.cc.s:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/ActionInitialization.cc.s
.PHONY : src/ActionInitialization.cc.s
src/DetectorConstruction.o: src/DetectorConstruction.cc.o
.PHONY : src/DetectorConstruction.o
# target to build an object file
src/DetectorConstruction.cc.o:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/DetectorConstruction.cc.o
.PHONY : src/DetectorConstruction.cc.o
src/DetectorConstruction.i: src/DetectorConstruction.cc.i
.PHONY : src/DetectorConstruction.i
# target to preprocess a source file
src/DetectorConstruction.cc.i:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/DetectorConstruction.cc.i
.PHONY : src/DetectorConstruction.cc.i
src/DetectorConstruction.s: src/DetectorConstruction.cc.s
.PHONY : src/DetectorConstruction.s
# target to generate assembly for a file
src/DetectorConstruction.cc.s:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/DetectorConstruction.cc.s
.PHONY : src/DetectorConstruction.cc.s
src/EventAction.o: src/EventAction.cc.o
.PHONY : src/EventAction.o
# target to build an object file
src/EventAction.cc.o:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/EventAction.cc.o
.PHONY : src/EventAction.cc.o
src/EventAction.i: src/EventAction.cc.i
.PHONY : src/EventAction.i
# target to preprocess a source file
src/EventAction.cc.i:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/EventAction.cc.i
.PHONY : src/EventAction.cc.i
src/EventAction.s: src/EventAction.cc.s
.PHONY : src/EventAction.s
# target to generate assembly for a file
src/EventAction.cc.s:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/EventAction.cc.s
.PHONY : src/EventAction.cc.s
src/EventActionMessenger.o: src/EventActionMessenger.cc.o
.PHONY : src/EventActionMessenger.o
# target to build an object file
src/EventActionMessenger.cc.o:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/EventActionMessenger.cc.o
.PHONY : src/EventActionMessenger.cc.o
src/EventActionMessenger.i: src/EventActionMessenger.cc.i
.PHONY : src/EventActionMessenger.i
# target to preprocess a source file
src/EventActionMessenger.cc.i:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/EventActionMessenger.cc.i
.PHONY : src/EventActionMessenger.cc.i
src/EventActionMessenger.s: src/EventActionMessenger.cc.s
.PHONY : src/EventActionMessenger.s
# target to generate assembly for a file
src/EventActionMessenger.cc.s:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/EventActionMessenger.cc.s
.PHONY : src/EventActionMessenger.cc.s
src/G04SensitiveDetector.o: src/G04SensitiveDetector.cc.o
.PHONY : src/G04SensitiveDetector.o
# target to build an object file
src/G04SensitiveDetector.cc.o:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/G04SensitiveDetector.cc.o
.PHONY : src/G04SensitiveDetector.cc.o
src/G04SensitiveDetector.i: src/G04SensitiveDetector.cc.i
.PHONY : src/G04SensitiveDetector.i
# target to preprocess a source file
src/G04SensitiveDetector.cc.i:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/G04SensitiveDetector.cc.i
.PHONY : src/G04SensitiveDetector.cc.i
src/G04SensitiveDetector.s: src/G04SensitiveDetector.cc.s
.PHONY : src/G04SensitiveDetector.s
# target to generate assembly for a file
src/G04SensitiveDetector.cc.s:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/G04SensitiveDetector.cc.s
.PHONY : src/G04SensitiveDetector.cc.s
src/G4ElectronCapture.o: src/G4ElectronCapture.cc.o
.PHONY : src/G4ElectronCapture.o
# target to build an object file
src/G4ElectronCapture.cc.o:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/G4ElectronCapture.cc.o
.PHONY : src/G4ElectronCapture.cc.o
src/G4ElectronCapture.i: src/G4ElectronCapture.cc.i
.PHONY : src/G4ElectronCapture.i
# target to preprocess a source file
src/G4ElectronCapture.cc.i:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/G4ElectronCapture.cc.i
.PHONY : src/G4ElectronCapture.cc.i
src/G4ElectronCapture.s: src/G4ElectronCapture.cc.s
.PHONY : src/G4ElectronCapture.s
# target to generate assembly for a file
src/G4ElectronCapture.cc.s:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/G4ElectronCapture.cc.s
.PHONY : src/G4ElectronCapture.cc.s
src/MuelPhyslist.o: src/MuelPhyslist.cc.o
.PHONY : src/MuelPhyslist.o
# target to build an object file
src/MuelPhyslist.cc.o:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/MuelPhyslist.cc.o
.PHONY : src/MuelPhyslist.cc.o
src/MuelPhyslist.i: src/MuelPhyslist.cc.i
.PHONY : src/MuelPhyslist.i
# target to preprocess a source file
src/MuelPhyslist.cc.i:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/MuelPhyslist.cc.i
.PHONY : src/MuelPhyslist.cc.i
src/MuelPhyslist.s: src/MuelPhyslist.cc.s
.PHONY : src/MuelPhyslist.s
# target to generate assembly for a file
src/MuelPhyslist.cc.s:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/MuelPhyslist.cc.s
.PHONY : src/MuelPhyslist.cc.s
src/OpticalPhysics.o: src/OpticalPhysics.cc.o
.PHONY : src/OpticalPhysics.o
# target to build an object file
src/OpticalPhysics.cc.o:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/OpticalPhysics.cc.o
.PHONY : src/OpticalPhysics.cc.o
src/OpticalPhysics.i: src/OpticalPhysics.cc.i
.PHONY : src/OpticalPhysics.i
# target to preprocess a source file
src/OpticalPhysics.cc.i:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/OpticalPhysics.cc.i
.PHONY : src/OpticalPhysics.cc.i
src/OpticalPhysics.s: src/OpticalPhysics.cc.s
.PHONY : src/OpticalPhysics.s
# target to generate assembly for a file
src/OpticalPhysics.cc.s:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/OpticalPhysics.cc.s
.PHONY : src/OpticalPhysics.cc.s
src/PhysicsList.o: src/PhysicsList.cc.o
.PHONY : src/PhysicsList.o
# target to build an object file
src/PhysicsList.cc.o:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/PhysicsList.cc.o
.PHONY : src/PhysicsList.cc.o
src/PhysicsList.i: src/PhysicsList.cc.i
.PHONY : src/PhysicsList.i
# target to preprocess a source file
src/PhysicsList.cc.i:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/PhysicsList.cc.i
.PHONY : src/PhysicsList.cc.i
src/PhysicsList.s: src/PhysicsList.cc.s
.PHONY : src/PhysicsList.s
# target to generate assembly for a file
src/PhysicsList.cc.s:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/PhysicsList.cc.s
.PHONY : src/PhysicsList.cc.s
src/PrimaryGeneratorAction.o: src/PrimaryGeneratorAction.cc.o
.PHONY : src/PrimaryGeneratorAction.o
# target to build an object file
src/PrimaryGeneratorAction.cc.o:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/PrimaryGeneratorAction.cc.o
.PHONY : src/PrimaryGeneratorAction.cc.o
src/PrimaryGeneratorAction.i: src/PrimaryGeneratorAction.cc.i
.PHONY : src/PrimaryGeneratorAction.i
# target to preprocess a source file
src/PrimaryGeneratorAction.cc.i:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/PrimaryGeneratorAction.cc.i
.PHONY : src/PrimaryGeneratorAction.cc.i
src/PrimaryGeneratorAction.s: src/PrimaryGeneratorAction.cc.s
.PHONY : src/PrimaryGeneratorAction.s
# target to generate assembly for a file
src/PrimaryGeneratorAction.cc.s:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/PrimaryGeneratorAction.cc.s
.PHONY : src/PrimaryGeneratorAction.cc.s
src/RunAction.o: src/RunAction.cc.o
.PHONY : src/RunAction.o
# target to build an object file
src/RunAction.cc.o:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/RunAction.cc.o
.PHONY : src/RunAction.cc.o
src/RunAction.i: src/RunAction.cc.i
.PHONY : src/RunAction.i
# target to preprocess a source file
src/RunAction.cc.i:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/RunAction.cc.i
.PHONY : src/RunAction.cc.i
src/RunAction.s: src/RunAction.cc.s
.PHONY : src/RunAction.s
# target to generate assembly for a file
src/RunAction.cc.s:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/RunAction.cc.s
.PHONY : src/RunAction.cc.s
src/SteppingAction.o: src/SteppingAction.cc.o
.PHONY : src/SteppingAction.o
# target to build an object file
src/SteppingAction.cc.o:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/SteppingAction.cc.o
.PHONY : src/SteppingAction.cc.o
src/SteppingAction.i: src/SteppingAction.cc.i
.PHONY : src/SteppingAction.i
# target to preprocess a source file
src/SteppingAction.cc.i:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/SteppingAction.cc.i
.PHONY : src/SteppingAction.cc.i
src/SteppingAction.s: src/SteppingAction.cc.s
.PHONY : src/SteppingAction.s
# target to generate assembly for a file
src/SteppingAction.cc.s:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/SteppingAction.cc.s
.PHONY : src/SteppingAction.cc.s
src/TrackingAction.o: src/TrackingAction.cc.o
.PHONY : src/TrackingAction.o
# target to build an object file
src/TrackingAction.cc.o:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/TrackingAction.cc.o
.PHONY : src/TrackingAction.cc.o
src/TrackingAction.i: src/TrackingAction.cc.i
.PHONY : src/TrackingAction.i
# target to preprocess a source file
src/TrackingAction.cc.i:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/TrackingAction.cc.i
.PHONY : src/TrackingAction.cc.i
src/TrackingAction.s: src/TrackingAction.cc.s
.PHONY : src/TrackingAction.s
# target to generate assembly for a file
src/TrackingAction.cc.s:
$(MAKE) -f CMakeFiles/Telescope.dir/build.make CMakeFiles/Telescope.dir/src/TrackingAction.cc.s
.PHONY : src/TrackingAction.cc.s
# Help Target
help:
@echo "The following are some of the valid targets for this Makefile:"
@echo "... all (the default if no target is provided)"
@echo "... clean"
@echo "... depend"
@echo "... edit_cache"
@echo "... rebuild_cache"
@echo "... list_install_components"
@echo "... install"
@echo "... install/local"
@echo "... install/strip"
@echo "... Telescope"
@echo "... Telescope.o"
@echo "... Telescope.i"
@echo "... Telescope.s"
@echo "... src/ActionInitialization.o"
@echo "... src/ActionInitialization.i"
@echo "... src/ActionInitialization.s"
@echo "... src/DetectorConstruction.o"
@echo "... src/DetectorConstruction.i"
@echo "... src/DetectorConstruction.s"
@echo "... src/EventAction.o"
@echo "... src/EventAction.i"
@echo "... src/EventAction.s"
@echo "... src/EventActionMessenger.o"
@echo "... src/EventActionMessenger.i"
@echo "... src/EventActionMessenger.s"
@echo "... src/G04SensitiveDetector.o"
@echo "... src/G04SensitiveDetector.i"
@echo "... src/G04SensitiveDetector.s"
@echo "... src/G4ElectronCapture.o"
@echo "... src/G4ElectronCapture.i"
@echo "... src/G4ElectronCapture.s"
@echo "... src/MuelPhyslist.o"
@echo "... src/MuelPhyslist.i"
@echo "... src/MuelPhyslist.s"
@echo "... src/OpticalPhysics.o"
@echo "... src/OpticalPhysics.i"
@echo "... src/OpticalPhysics.s"
@echo "... src/PhysicsList.o"
@echo "... src/PhysicsList.i"
@echo "... src/PhysicsList.s"
@echo "... src/PrimaryGeneratorAction.o"
@echo "... src/PrimaryGeneratorAction.i"
@echo "... src/PrimaryGeneratorAction.s"
@echo "... src/RunAction.o"
@echo "... src/RunAction.i"
@echo "... src/RunAction.s"
@echo "... src/SteppingAction.o"
@echo "... src/SteppingAction.i"
@echo "... src/SteppingAction.s"
@echo "... src/TrackingAction.o"
@echo "... src/TrackingAction.i"
@echo "... src/TrackingAction.s"
.PHONY : help
#=============================================================================
# Special targets to cleanup operation of make.
# Special rule to run CMake to check the build system integrity.
# No rule that depends on this can have commands that come from listfiles
# because they might be regenerated.
cmake_check_build_system:
$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0
.PHONY : cmake_check_build_system
<file_sep># Актуальность
При прохождении потока заряженных частиц через детекторы, входящие в состав спектрометра, потери энергии отдельных частиц испытывают флуктуации, обусловленные статистической природой процесса ионизации, причем при регистрации электронов вследствие их малой массы статистические флуктуации удельных потерь энергии значительно больше, чем для протонов. Поэтому для достижения необходимой точности измерений необходимо проводить математическое моделирование энерговыделения в детекторах. Статистические методы обработки полученных в результате численного моделирования данных позволяют уточнить величины порогов прибора и определить эффективность регистрации в отдельных энергетических каналах. Существующий подход к требует большого объема расчетов, в особенности при необходимости варьирования параметров конструкции спектрометра. Поэтому разработка методики и создание комплекса программ для подбора параметров спектрометра и выбора энергетических каналов с оптимальными энергетическим разрешением и чувствительностью спектрометров является актуальной задачей.
Полученные с помощью разработанного комплекса расчетные данные могут использоваться при восстановления по результатам измерений исходных энергетических спектров протонов и электронов.
# Анализ современного состояния исследований в данной области (приводится обзор исследований в данной области со ссылками на публикации в научной литературе).
Математическое моделирование широко применяется на всех этапах создания спектрометров заряженных частиц, предназначенных для использования в условиях космоса. В первую очередь, оно необходимо на этапе проектирования аппаратуры для выбора характеристик регистрирующих радиацию модулей исходя из поставленных экспериментальных задач {Hassler D. et al.2008}. На последующих шагах разработки аппаратуры математические методы используются при верификации результатов калибровочных и градуировочных испытаний на источниках ионизирующих излучений (ИИ) и ускорителях заряженных частиц {Zeitlin C. et al. 2010, Luszik-Bhadra M. et al. 2008}. Также одним из основных применений является уточнение функции отклика прибора во время штатной работы {Zeitlin C. et al. 2010}.
Среди математических методов моделирования взаимодействия ИИ и нейтральных излучений с материалами и детектирующими модулями приборов следует отметить наиболее часто используемые программные пакеты, основанные на методе Монте-Карло:
- GEANT4 комплекс программ для моделирования прохождения частиц через вещество {Allison J. et al. 2006}, код общедоступен;
- PHITS Система расчета перемещений частиц и тяжелых ионов,
разработана в Японии и Австрии { Niita K. et al. 2006, Sato T. et al. 2006} ;
- FLUKA система широко использующаяся в CERN для широко круга задач и, в первую очередь, для медицинских приложений {Fasso A. et al.2003, Böhlen T.T. et al.2014}.
Программа Geant4 разработана для нужд работы ЦЕРН и активно используется в ряде областей науки, медицины и технологии {Agostinelli S. et al. 2003}. В настоящее время существует несколько отдельных направлений развития Geant4 для решения задач микродозиметрии, физики высоких энергий, биологических аспектов радиационных воздействий и др. Кроме того создано несколько специализированных инженерных продуктов, использующих только ядро системы для расчетов распространения частиц. Основные направления: микродозиметрические исследования (GEMAT), применение к распространению и воздействия космического излучения (GRAS, PLANETOCOSMICS), оптимизация экранирования (MULASSIS {Lei F. et al.2002} и SSAT). Для исследований характеристик приборов хорошо применим пакет Geant4 Radiation Analysis for Space (GRAS) {Santin G. et al. 2005}. В качестве входных данных здесь может быть использован GDML файл с описанием геметрической модели прибора. GRAS позволяет автоматически создавать комплексные источники космического излучения, соответствующие различным орбитам полета спутников. Перечисленные программы объединены в единый комплекс Spenvis, однако функционал программ и возможности для получения выходных данных ограничены. В отличие от пакетов проекта Spenvis, Geant4 регулярно обновляется, уточняются модели физических процессов и расширяются возможности моделирования. Поэтому для детального расчета параметров взаимодействия излучений с материалами детектирующих систем в данном проекте выбран программный комплекс Geant4.
Одной из наиболее распространенных расчетных задач, связанных с детекторами является расчет эффективности регистрации детектора. Эффективность регистрации детектора определяется его геометрическим фактором и особенностями взаимодействия исследуемых частиц с веществом детектора и является, по сути, функцией отклика детектора. Геометрический фактор детектора зависит от его геометрии и углового распределения регистрируемых частиц. Аналитическое вычисление геометрического фактора не учитывает его зависимости от типа и энергии излучения, в то время как математическое моделирование позволяет провести исследование влияния угловых и энергетических распределений.
При моделировании методом Монте-Карло воспроизводятся особенности структуры детектора и параметров излучения, поэтому полученные значения отклика приборов включают в себя как геометрический фактор прибора, так и эффективность чувствительной области детектора, обусловленную процессами взаимодействия излучения с веществом. Например, с помощью GEANT4 в {<NAME>. et al. 2011 } были получены значения геометрических факторов в зависимости от энергии для детектора Galileo Heavy Ion Counter (HIC), проводившего измерения потоков ионов кислорода, углерода и серы в атмосфере Юпитера. В этом и других подобных исследованиях {Zhang, S. et al. 2014} математическое моделирование использовалось для получения геометрических факторов детекторов при регистрации протонов и более тяжелых ионов, а также для моделирования сигнала от заданных спектров излучения.
Результаты моделирования позволяют более точно выбрать границы энергетических каналов прибора, использующихся для получения информации об исходной энергии зарегистрированных частиц, однако при регистрации электронов их потери энергии в детекторах испытывают значительные флуктуации из-за многократного рассеяния, поэтому выделение энергетических каналов для постоения логической схемы спектрометра в этом случае затруднено {Власова Н.А. et al. 2013}. Кроме того, в электронных каналах может дополнительно происходить регистрация протонов, а в протонных - электронов. Оценка влияния этого фактора и разработка логических схем для разделения электронных и протонных событий также проводится на основе математического моделирования {Yando, K. et al. 2011}. Таким образом, восстановление спектров космических излучений по данным измерений является трудной задачей, для корректного решения которой необходим комплексный статистический анализ данных измерений и моделирования.
Отличительной особенностью данного проекта является направленность на разработку системного подхода к оптимизации чувствительности и энергетического разрешения спектрометров, состоящих из телескопа полупроводниковых и сцинтилляционных детекторов.
1. Garrett, H.B. The Jovian Equatorial Heavy Ion Radiation Environment/ <NAME>, <NAME>, <NAME>, <NAME>, <NAME> // JPL Publication 11-16.– Pasadena, CA: Jet Propulsion Laboratory, National Aeronautics and Space Administration, 2011.– 42 p.
2. <NAME>., <NAME>., <NAME>. et al. Sci. China Earth Sci. (2014) 57: 2558. https://doi.org/10.1007/s11430-014-4853-0
3. <NAME>, <NAME>, <NAME>, <NAME>, Н.П. Чирская Метрологические характеристики детекторов космического излучения. Физика и химия обработки материалов. — 2013. — № 6. — С. 32–39.
4. <NAME>., <NAME>, <NAME>, and <NAME> (2011), A Monte Carlo simulation of the NOAA POES Medium Energy Proton and Electron Detector instrument, J. Geophys. Res., 116, A10231, doi:10.1029/2011JA016671.
5. Hassler D. et al. The Mars Science Laboratory ( MSL ) Mission // WRMISS. 2008. P. 20.
6. <NAME>. et al. Space Radiation Dosimetry with the Radiation Assessment Detector ( RAD ) on the Mars Science Laboratory ( MSL ) // WRMISS,. 2010. P. 22.
7. <NAME>. et al. Electronic personal neutron dosemeters for energies up to 100 MeV: Calculations using the PHITS code // Radiat. Meas. 2008. Vol. 43, № 2–6. P. 1044–1048.
8. <NAME>. et al. Geant4 developments and applications // IEEE Trans. Nucl. Sci. 2006. Vol. 53, № 1. P. 270–278.
9. <NAME>. et al. PHITS-a particle and heavy ion transport code system // Radiat. Meas. 2006. Vol. 41, № 9–10. P. 1080–1090.
10. <NAME>. et al. Applicability of particle and heavy ion transport code PHITS to the shielding design of spacecrafts // Radiat. Meas. 2006. Vol. 41, № 9–10. P. 1142–1146.
11. <NAME>. et al. The physics models of FLUKA: status and recent development // arXiv. 2003. Vol. hep-ph. P. 10.
12. <NAME>. et al. The FLUKA Code: Developments and challenges for high energy and medical applications // Nucl. Data Sheets. 2014. Vol. 120. P. 211–214.
13. <NAME>. et al. GEANT4 - A simulation toolkit // Nucl. Instruments Methods Phys. Res. Sect. A Accel. Spectrometers, Detect. Assoc. Equip. 2003. Vol. 506, № 3. P. 250–303.
14. <NAME>. et al. MULASSIS: A Geant4-based multilayered shielding simulation tool // IEEE Transactions on Nuclear Science. 2002. Vol. 49 I, № 6. P. 2788–2793.
15. <NAME>. et al. GRAS: A general-purpose 3-D modular simulation tool for space environment effects analysis // IEEE Trans. Nucl. Sci. 2005. Vol. 52, № 6. P. 2294–2299.
# Предлагаемые подходы и методы, и их обоснование для реализации цели и задачи исследований (Развернутое описание предлагаемого исследования; форма изложения должна дать возможность эксперту оценить новизну идеи Проекта, соответствие подходов и методов исследования поставленным целям и задачам, надежность получаемых результатов)
Математическое моделирование взаимодействия спектрометров с ионизирующими излучениями в данном проекте будет выполняться с помощью универсального и хорошо аппробированного программного комплекса Geant4. В рамках проекта будет создан программный код, дающий возможность пользователю, не обладающему навыками работы с Geant4 и программирования на C++, легко изменять основные параметры детектирующей системы, такие как тип детектирующих элементов, материалы, из которых состоит детектор, количество и размер детектирующих элементов, геометрические размеры детектора. Такой подход позволит быстро изменять параметры исследуемой детектирующей системы для ее оптимизации и дальнейшей работы с данными.
*Иван* Краткое описание метода анализа результатов
-
# Имеющийся у коллектива научный задел по Проекту (указываются полученные результаты, разработанные программы и методы, экспериментальное оборудование, материалы и информационные ресурсы, имеющиеся в распоряжении коллектива для реализации Проекта)
1. Коллектив имеет большой опыт решения различных задач, связанных с математическим моделированием процессов взаимодействия излучений с веществом с помощью Geant4, TRIM/SRIM, пакетов ресурса SPENVIS и др.
2. В настоящее время разработан и аппробирован программный модуль на основе Geant4 для моделирования прохождения излучения через спектрометры с фиксированными параметрами геометрии.
3. Разработан программный модуль для анализа результатов моделирования отклика спектрометров при регистрации энергичных протонов и электронов. Данный модуль позволяет получать информацию о чувствительности каналов прибора к протонам и электронам, а также исследовать селективности каналов по энергии падающих частиц.
4. Создан прототип спектрометра для проекта многоярусной спутниковой группировки. Прототип позволяет проверить разрабатываемые методы моделирования и анализа спектрометров на экспериментальной установке.
# Ожидаемые результаты научного исследования и их научная и прикладная значимость.
В результате выполнения проекта будет создан программный комплекс, облегчающий проектирование спектрометров заряженных частиц.
Будет разработан единый критерий определения оптимальных характеристик телескопических спектрометров на основе таких параметров, как энергетическое разрешениеи чувствительность каналов прибора к протонам и электронам. Возможность динамического варьирования параметров детектора позволит упростить задачу поиска оптимальной конструкции спектрометров.
Отличительной особенностью системы станет однозначность получаемых результатов по характеристикам моделируемых приборов радиационного мониторинга. В результате выполнения проекта будет разработан системный подход к проектированию спектрометров заряженных частиц, использующихся для изучения радиационной обстановки в околоземном пространстве.
*какие-то результаты, связанные с выбором каналов детектора. Например, заодно прикрутить вывод вероятностей регистрации для электронов. Тогда можно говорить о уточнении результатов измерения потоков электронов в космосе. И кстати, о присчете электронов в протонных каналах и наоборот. Неплохо бы смотрелось в качестве научной значимости...*
*еще одна идея - на второй год можно заявить доработку системы для моделирования стриповых детекторов. Насколько я понимаю, там больше возни, но суть та же.*
# Научная новизна исследования, заявленного в Проекте (формулируется новая научная идея, обосновывается новизна предлагаемой постановки и решения заявленной проблемы)
Научная новизна проекта обусловлена использованием комплекса математических методов для задачи оптимизации конструкции телескопических спектрометров, системный подход к решению которой в настоящее время отсутствует. Используемая методика моделирования регистрации ионизирующих излучений телескопическими детекторами обладает значительными преимуществами по сравнению с традиционно применяемой при проектировании детекторов методикой на основании средних потерь энергии. Выработка единого критерия на основе чувствительности и энергетического разрешения спектрометра позволит проводить оптимизацию конструкции детекторов на стадии их разработки.
# Ожидаемые научные результаты за первый год реализации Проекта (форма изложения должна дать возможность провести экспертизу результатов и оценить возможную степень выполнения заявленного в Проекте плана работы)
В первый год проекта будут получены следующие результаты:
- создана система математического моделирования спектрометров заряженных частиц, включающая возможность динамического изменения параметров спектрометра, в том числе материалов конструкции, количества и типа детекторов, основных размеров корпуса спектрометра. Добавлена возможность изменения спектра заряженных частиц при моделировании;
- разработан единый численный критерий сравнения результатов моделирования для решения оптимизационной задачи;
- создана система анализа данных численного моделирования регистрации заряженных частиц для оптимизации геометрии спектрометра;
- разработан модуль для динамического изменения параметров спектрометра и детектируемого излучения, что облегчит проведение большого массива расчетов при поиске оптимальной конструкции детектора.
По результатам выполенных работ планируется пуликация в рецензируемом журнале. Доклад результатов на конференции COSPAR 2018.
# План работ на первый год реализации Проекта (план предоставляется с учетом содержания работ каждого из участников Проекта, предполагаемых поездок)
1) Разработка системы математического моделирования спектрометров заряженных частиц, включающая можность динамического изменения параметров численного моделирования, в том числе:
- Изменение материалов констукции;
- Изменение модели прибора (в том числе изменение числа и типа детекторов);
- Изменения падающего спектра заряженных частиц;
(Чирская Н.П.)
*не знаю, как нормально писать распределение по исполнителям*
2) Разработка единого критерия на основе чувствительности и энергетического разрешения спектрометра для решения оптимизационной задачи. (<NAME>., Чирская Н.П.)
3) Разработка системы анализа данных численного моделирования. Система должна включать получение единого численного критерия сравнения результатов моделирования для целей решения оптимизационной задачи. (Золотарев И.А.)
4) Разработка модуля динамического изменения параметров спектрометра и моделируемого излучения. (<NAME>., Чирская Н.П.)
5) Подготовка статьи по результатам работ для публикации в рецензируемом журнале. (Золотар<NAME>., Чирская Н.П.)
<file_sep>#!/usr/bin/Rscript
# eval(parse(filename, encoding="UTF-8"))
# library(data.table)
# library("Hmisc")
# library('hexbin')
# library('tidyr')
library(readr)
library(dplyr)
library(ggplot2)
setwd("D:/Ivan/_flash backup 2014/SINP/Группировка/2017 Группировка/radmonitoring/analisys")
# Start the clock!
ptm <- proc.time()
# таблицы для Чирской фацет по сравнению корпусов -----------------------------
# tables facet - casing and telescope development -----------------------------
# data preparing ---------------------------------------------------------------
filename <- 'facet_nt_signal_t0.csv'
header <- strsplit("evtNb E0.keV pixelNo lineNo dE.keV start_angz start_angphi pixel_angz pixel_angphi", split = ' ')
datae<-read.csv(filename,col.names = header[[1]], skip = 13)
cat('\nData file name:', filename, ':', nrow(datae) )
# data preparing 2--------------------------------------------------------------
filename <- '05_MeV_facet_nt_signal_t0.csv'
filename <- '3_MeV_facet_nt_signal_t0.csv'
filename <- '6_MeV_facet_nt_signal_t0.csv'
filename <- '7_MeV_facet_nt_signal_t0.csv'
filename <- '9_MeV_facet_nt_signal_t0.csv'
header <- strsplit("evtNb E0.keV layerNo pixelNo lineNo dE.keV start_angz start_angphi pixel_angz pixel_angphi", split = ' ')
datae<-read.csv(filename,col.names = header[[1]], skip = 14)
cat('\nData file name:', filename, ':', nrow(datae) )
# plot agles -------------------------------------------------------------------
names(datae)
plot(datae$start_angphi, datae$start_angz)
# angles on top of casing
ggplot(data = datae)+
geom_point(aes(x=start_angphi, y= start_angz))+
labs(title = filename)+
# scale_x_continuous(breaks=c(0 , 6, 12, 18),
# minor_breaks = c(0:24),
# labels = c('00','06', '12', '18'))+
ylim(0,90)+
coord_polar(start = 0, direction = -1 )+
theme_bw()+ theme(panel.grid.major = element_line(colour = "black"),
panel.grid.minor = element_line(colour = "black"))
# angles on all detectors, deprecated!
ggplot(data = datae)+
geom_point(aes(x=pixel_angphi, y= pixel_angz))+
ylim(0,90)+
coord_polar(start = 0, direction = -1 )+
theme_bw()+ theme(panel.grid.major = element_line(colour = "black"),
panel.grid.minor = element_line(colour = "black"))
# angles on top detector
ggplot(data = filter(datae, layerNo == 0))+
geom_point(aes(x=pixel_angphi, y= pixel_angz))+
ylim(0,90)+
coord_polar(start = 0, direction = -1 )+
theme_bw()+ theme(panel.grid.major = element_line(colour = "black"),
panel.grid.minor = element_line(colour = "black"))
# angles on middle detector
ggplot(data = filter(datae, layerNo == 1))+
geom_point(aes(x=pixel_angphi, y= pixel_angz))+
ylim(0,90)+
coord_polar(start = 0, direction = -1 )+
theme_bw()+ theme(panel.grid.major = element_line(colour = "black"),
panel.grid.minor = element_line(colour = "black"))
# angles on bottom detector
ggplot(data = filter(datae, layerNo == 2))+
geom_point(aes(x=pixel_angphi, y= pixel_angz))+
ylim(0,90)+
coord_polar(start = 0, direction = -1 )+
theme_bw()+ theme(panel.grid.major = element_line(colour = "black"),
panel.grid.minor = element_line(colour = "black"))
# draw all tracks--------------------------------------------------------------
ggplot(data = datae)+
geom_bin2d(aes(x=pixelNo, y= lineNo))
ggplot(data = filter(datae), aes(x=pixelNo, y= lineNo)) +
geom_tile()
# select single event ----------------------------------------------------------
evtNumber <- select(sample_n(datae, 1), evtNb)[[1]]
# simple draw track-------------------------------------------------------------
ggplot(data = filter(datae, evtNb == evtNumber), aes(x=pixelNo, y= lineNo)) +
geom_tile(aes(fill = dE.keV)) +
coord_fixed(ratio = 1)
# draw track layer by layer ----------------------------------------------------
ggplot(data = filter(datae, evtNb == evtNumber), aes(x=pixelNo, y= lineNo)) +
geom_tile(data = filter(datae, evtNb == evtNumber & layerNo == 0), aes(fill = dE.keV)) +
geom_tile(data = filter(datae, evtNb == evtNumber & layerNo == 1), aes(fill = dE.keV)) +
geom_tile(data = filter(datae, evtNb == evtNumber & layerNo == 2), aes(fill = dE.keV)) +
coord_fixed(ratio = 1)
# draw track all layers --------------------------------------------------------
ggplot(data = filter(datae, evtNb == evtNumber), aes(x=pixelNo, y= lineNo)) +
geom_tile(aes(fill =factor(layerNo), alpha = dE.keV))+
coord_fixed(ratio = 1) #+ scale_fill_manual()
ggsave(paste(evtNumber, '.pdf'), device = "pdf")
# plot each event separately ---------------------------------------------------
for (evtNumber in unique(datae$evtNb))
{
ggplot(data = filter(datae, evtNb == evtNumber), aes(x=pixelNo, y= lineNo)) +
geom_tile(aes(fill = dE.keV)) +
coord_fixed(ratio = 1)
ggsave(paste(evtNumber, '.pdf'), device = "pdf")
# specify device when saving to a file with unknown extension
# (for example a server supplied temporary file)
# ggsave(file, device = "pdf")
}
# old plot angles (plot angels, haha!)----------------------------------------------
summary(datae)
#bad
plot(datae$start_angz, datae$pixel_angz)
#bad
plot(datae$start_angphi, datae$pixel_angphi)
#bad
plot(datae$dE.keV, datae$start_angz)
# all some other plots ----------------------------------------------------
breaks.angle <- seq(0, 180, length.out = 180/5+1)
breaks.dEdet3 <- seq(0, 5000, length.out = 30+1)
datae$bins.angle <- cut(as.numeric(datae$ang_z), breaks.angle)
datae$bins.dE3 <- cut(as.numeric(datae$dE.det3), breaks.dEdet3)
hist.n <- datae[datae$dE.det3>0,] %>%
group_by(., bins.angle, bins.dE3) %>%
summarise(., n =n())
hist.n <- na.omit(hist.n)
print(hist.n )
write.csv2(hist.n, paste0("NdEdet3", filename))
pdf(paste("elecprotdde3.pdf", sep="" ), width =20, height=20)
n = 20
colr = rev(rainbow(n, start = 0, end = 4/6, alpha = 0.5))
print(cloud(n ~ bins.angle * bins.dE3, data = hist.n, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det3',main = filename,
#zlim = c(0,60),
col.facet = level.colors(hist.n$n, at = do.breaks(range(hist.n$n), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(range(hist.n$n), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
hist.sum <- datae[datae$dE.det3>0,] %>%
group_by(., bins.angle, bins.dE3) %>%
summarise(., sum =sum(na.omit(as.numeric(dE.det3))))
hist.sum <- na.omit(hist.sum)
print(hist.sum )
write.csv2(hist.sum, paste0("SdEdet3", filename))
print(cloud(sum ~ bins.angle * bins.dE3, data = hist.sum, panel.3d.cloud=panel.3dbars,
# col.facet='grey',
xbase=0.4, ybase=0.4,
scales=list(arrows=FALSE, col=1),
xlab = 'angle', ylab = 'dE.det3',zlab = 'summ dE.det3',main = filename,
#zlim = c(0,100000),
col.facet = level.colors(hist.sum$sum, at = do.breaks(range(hist.sum$sum), 20),
col.regions = colr,
colors = TRUE),
colorkey = list(col = colr, at = do.breaks(range(hist.sum$sum), 20)),
screen = list(z = 40, x = -30),
par.settings = list(axis.line = list(col = "transparent")))
)
# off active device ----------------------------------------------------------
dev.off()
<file_sep>#source('comparators.R')
setwd("D:/Simulink")
library("Hmisc")
# datae<-read.table("data/det2/electron_A_L17_det2.dat", header = TRUE)
# datae<-read.table("data/det2/electr_A_L14_det2.dat", header = TRUE)
datae<-read.table("data/alldet/electr_A_L32.dat", header = TRUE)
# кросс тест с протонами
# datae<-read.table("data/alldet/proton_A_L32.dat", header = TRUE)
#summary(datae)
# sum(datae$CF > 0 & (datae$E0.keV > leftE0[1]) & (datae$E0.keV < rightE0[1]), na.rm=TRUE)
breaks <- c(0,150,350,600,1000,2000,4000,10000,Inf)
datae$bins <- cut(datae$E0.keV, breaks, labels=c('c0','c1','c2','c3','c4','c5','c6','c7'))
# initial <- cut(datae$E0.keV, breaks)
# table(initial)
el <- vector();
ch <- vector();
el14 <- vector();
el17 <- vector();
el32 <- vector();
# исходные спектры при моделировании Geant-----------------------------
el14 <- c(47135060,
11579606,
1864838,
574134,
101458,
77)
el17 <- c(43517330,
10981663,
1903275,
199186,
14846,
12)
el32 <- c(36161695,
10351798,
5461403,
3738306,
1108249,
43189)
# ошибки подсчитаны как (1-селективность)/чуствительность-----------------------
errr <- vector();
errr <- c(1,
1.6,
3.2,
4,
0.315789474,
0.8)
# отбор каналов по 5-95 --------------------------------------------------------
electron<-datae[((datae$CF > 0) & (datae$bins == "с5")), ]
channel<-datae[((datae$dE.det1 >= e5[1,1]) & datae$dE.det1 <= e5[6,1])&
((datae$dE.det2 >= e5[1,2]) & datae$dE.det2 <= e5[6,2])&
((datae$dE.det3 >= e5[1,3]) & datae$dE.det3 <= e5[6,3])&
((datae$dE.det4 >= e5[1,4]) & datae$dE.det4 <= e5[6,4]),]
el[5] <- nrow(electron)
ch[5] <- nrow(channel)
electron<-datae[((datae$CF > 0) & (datae$bins == "с6")), ]
channel<-datae[((datae$dE.det1 >= e6[1,1]) & datae$dE.det1 <= e6[6,1])&
((datae$dE.det2 >= e6[1,2]) & datae$dE.det2 <= e6[6,2])&
((datae$dE.det3 >= e6[1,3]) & datae$dE.det3 <= e6[6,3])&
((datae$dE.det4 >= e6[1,4]) & datae$dE.det4 <= e6[6,4]),]
el[6] <- nrow(electron)
ch[6] <- nrow(channel)
# отбор каналов по 25-75 -------------------------------------------------------
electron<-datae[((datae$CF > 0) & (datae$bins == "с1")), ]
channel<-datae[ ((datae$dE.det1 >= e1[3,1]) & datae$dE.det1 <= e1[4,1])&
((datae$dE.det2 >= e1[3,2]) & datae$dE.det2 <= e1[4,2])&
((datae$dE.det3 >= e1[3,3]) & datae$dE.det3 <= e1[4,3])&
((datae$dE.det4 >= e1[3,4]) & datae$dE.det4 <= e1[4,4]),]
el[1] <- nrow(electron)
ch[1] <- nrow(channel)
electron<-datae[((datae$CF > 0) & (datae$bins == "с2")), ]
channel<-datae[((datae$dE.det1 >= e2[3,1]) & datae$dE.det1 <= e2[4,1])&
((datae$dE.det2 >= e2[3,2]) & datae$dE.det2 <= e2[4,2])&
((datae$dE.det3 >= e2[3,3]) & datae$dE.det3 <= e2[4,3])&
((datae$dE.det4 >= e2[3,4]) & datae$dE.det4 <= e2[4,4]),]
el[2] <- nrow(electron)
ch[2] <- nrow(channel)
electron<-datae[((datae$CF > 0) & (datae$bins == "с3")), ]
channel<-datae[ ((datae$dE.det1 >= e3[3,1]) & datae$dE.det1 <= e3[4,1])&
((datae$dE.det2 >= e3[3,2]) & datae$dE.det2 <= e3[4,2])&
((datae$dE.det3 >= e3[3,3]) & datae$dE.det3 <= e3[4,3])&
((datae$dE.det4 >= e3[3,4]) & datae$dE.det4 <= e3[4,4]),]
el[3] <- nrow(electron)
ch[3] <- nrow(channel)
electron<-datae[((datae$CF > 0) & (datae$bins == "с4")), ]
channel<-datae[((datae$dE.det1 >= e4[3,1]) & datae$dE.det1 <= e4[4,1])&
((datae$dE.det2 >= e4[3,2]) & datae$dE.det2 <= e4[4,2])&
((datae$dE.det3 >= e4[3,3]) & datae$dE.det3 <= e4[4,3])&
((datae$dE.det4 >= e4[3,4]) & datae$dE.det4 <= e4[4,4]),]
el[4] <- nrow(electron)
ch[4] <- nrow(channel)
# effectiveness -----------------------------------------------------------
x = data.frame( names=c('e1','e2','e3','e4','e5','e6'),el32, ch)
# необходимо раскомментировать для получения градуировки первый раз
# eff = x$ch/x$el14;
x$ch = ceil(x$ch/eff)
mymat <- t(x[-1])
colnames(mymat) <- x[, 1]
# barplot(mymat, beside = TRUE, legend.text=c('пад.','рег.'))
mymat<-mymat[,1:5]# выбор каналов для графика
barx <-barplot(mymat,
ylim=c(0.1, 2*max(na.exclude(x$ch))+max(na.exclude(x$el32))+1),
log='y',
legend.text=c('пад.','рег.'),
beside = TRUE,
xpd=FALSE,
main='Восстановление спектра L=3.2',
ylab='N, частиц',
xlab='Номер канала')
box()
#standard error
er<- x$ch*errr + x$ch/sqrt(ch)
er<- er[-6]
#error bars
arrows(barx[2,],mymat[2,]+er, barx[2,], mymat[2,], angle=90, code=1)
arrows(barx[2,],mymat[2,]-er, barx[2,], mymat[2,], angle=90, code=1)
#legend (after making the plot, indicate where the legend has
#to come with the mouse)
# legend(locator(1),c(levels(z)),fill=c(1:w),bty="n",cex=0.8)
<file_sep>#!/usr/bin/Rscript
# eval(parse(filename, encoding="UTF-8"))
# таблицы как я отчитываюсь
library(data.table)
library("Hmisc")
setwd("D:/Simulink/report")
# подготовка исходных данных
# datap<-read.table("protons_B.dat", header = TRUE)
getwd()
setwd("D:/Ivan/_flash backup 2014/SINP/Группировка/2017 Группировка/radmonitoring/radmonitoring/analisys/percentile")
setwd("D:/Ivan/_flash backup 2014/SINP/Группировка/2017 Группировка/radmonitoring/radmonitoring/analisys/percentile/report3")
list.files()
# Start the clock!
ptm <- proc.time()
# datap<-fread("protons_B.dat", header = TRUE)
casing <-'D'
datap<-read.table(paste("protons_",casing,".dat", sep=''), header = TRUE)
# Stop the clock
proc.time() - ptm
breaks <- c(0,2000,4000,9000,15000,30000,53000,100000,160000, Inf)
labels <- c('p0','p1','p2','p3','p4','p5','p6','p7','p8')
datap$bins <- cut(datap$E0.keV, breaks, labels= labels)
least.thresholds = c(150, 120, 800, 200)
# полное энерговыделение в детекторах прибора---------------
datap$sumdE <- datap$dE.det1 + datap$dE.det2 + datap$dE.det3 + datap$dE.det4
datap.fullAbsorption <- datap[(datap$E0.keV - datap$sumdE)/datap$E0.keV< 0.05,]
plot(datap.fullAbsorption$sumdE ~ datap.fullAbsorption$E0.keV)
plot(datap.fullAbsorption$sumdE ~ datap.fullAbsorption$ang_z)
datap.collimator <- datap[datap$ang_z < 17,]
plot(datap.collimator$sumdE ~ datap.collimator$E0.keV, asp = 1)
plot(dE.det4 ~ dE.det3:dE.det2, data=datap.collimator)
# training data -----------------------------------------------------------
datap.filterLow <-datap[
(datap$dE.det2 >= 120)
&(datap$ang_z < 17),]
datap.filterLow <-datap.filterLow[
(datap.filterLow$E0.keV >= 15000)|(datap.filterLow$dE.det1 >= 150) ,]
datap.filterLow <-datap.filterLow[
(datap.filterLow$E0.keV <= 9000)|(datap.filterLow$dE.det3 >= 800) ,]
datap.filterLow <-datap.filterLow[
(datap.filterLow$E0.keV <= 53000)|(datap.filterLow$dE.det4 >= 200) ,]
##### OPTION 1: hexbin from package 'hexbin' #######
# Color housekeeping
library(RColorBrewer)
rf <- colorRampPalette(rev(brewer.pal(11,'Spectral')))
r <- rf(32)
library(hexbin)
# Create hexbin object and plot
# h <- hexbin(datap.collimator[,1,10 ])
# plot(h)
# plot(h, colramp=rf)
hexbinplot(sumdE/1000~E0.keV/1000, data=datap.collimator, colramp=rf,
aspect=1, trans=log, inv=exp,
mincnt=1,
xbins = 50,
main = paste("Поток протонов через коллиматор, ",casing, sep=" "),
ylab= "Суммарное энерговыделение в детекторах прибора")
hexbinplot(sumdE/1000~E0.keV/1000, data=datap, colramp=rf,
aspect=1, trans=log, inv=exp,
mincnt=2,
xbins = 100,
main = paste("Полный поток протонов через прибор,",casing, sep=" "),
ylab= "Суммарное энерговыделение в детекторах прибора")
ppi <- 300
png(paste("trainproton",casing,".png", sep=""), width=6*ppi, height=6*ppi, res=ppi)
hexbinplot((sumdE/1000)~(E0.keV/1000), data=datap.filterLow, colramp=rf,
aspect=1, trans=log, inv=exp,
mincnt=2,
xbins = 100,
main = paste("поток протонов через прибор, Триггер D2, коллиматор, корпус",casing, sep=" "),
ylab= "Суммарное энерговыделение в детекторах прибора")
dev.off()
# hexbinplot(sumdE~log(E0.keV), data=datap.filterLow, colramp=rf,
# aspect=1, trans=log, inv=exp,
# mincnt=2,
# xbins = 100,
# main = "поток протонов через прибор, D Триггер D2, коллиматор",
# ylab= "Суммарное энерговыделение в детекторах прибора")
boxplot(dE.det1~bins, data = datap.filterLow)
boxplot(dE.det2~bins, data = datap.filterLow)
boxplot(dE.det3~bins, data = datap.filterLow)
boxplot(dE.det4~bins, data = datap.filterLow)
hexbinplot(datap$dE.det1~datap$dE.det2, data=datap.filterLow, colramp=rf,
aspect=1, trans=log, inv=exp,
mincnt=1)
hexbinplot(datap$dE.det2~datap$dE.det3, data=datap.filterLow, colramp=rf,
aspect=1, trans=log, inv=exp,
mincnt=1)
hexbinplot(datap$dE.det3~datap$dE.det4, data=datap.filterLow, colramp=rf,
aspect=1, trans=log, inv=exp,
mincnt=1)
# thresholds --------------------------------------------------------------
GetThresholds <- function(data = datap, quant=5 ){
thres<- apply(data[,2:5],2,
quantile,
probs=c(quant, 100-quant)/100)
# додумать надо
# cat("Was:\n", thres)
for(i in 1:4){
# делаем замену обоих порогов в случае малых значений на ноль и младший порог
if ( (thres[1,i] < least.thresholds[i])&
(thres[2,i] < least.thresholds[i])){
thres[1,i] <- 0
thres[2,i] <- least.thresholds[i]
}
# и замену младшего порога в случае если только он попал
if ( (thres[1,i] < least.thresholds[i])&(thres[1,i] > least.thresholds[i]/2)&
(thres[2,i] > least.thresholds[i])){
thres[1,i] <- least.thresholds[i]
}
# и замену младшего порога в случае если только он попал
if ( (thres[1,i] < least.thresholds[i]/2)&
(thres[2,i] > least.thresholds[i])){
thres[1,i] <- 0
}
}
# cat("Now:\n", thres)
return(thres)
}
# 595 ---------------------------------------------------------------------
# должна быть таблица
# д1 д2 д3 д4
# 5 95 5 95...
#
# table.595 <- by(datap, datap[,"bins"], GetThresholds, quant = 5)
# table.595 <- by(datap.collimator, datap.collimator[,"bins"], GetThresholds, quant = 5)
table.595 <- by(datap.filterLow, datap.filterLow[,"bins"], GetThresholds, quant = 5)
# table.595 <- by(datap.fullAbsorption, datap.fullAbsorption[,"bins"], GetThresholds, quant = 5)
# есть таблица!
table.595<-table.595[-1]
# выполняем округление до десятков кэВ
table.595 <- lapply(table.595, round, -1)
print(table.595)
# 2575 -------------------------------------------------------------------
# table.2575 <- by(datap, datap[,"bins"], GetThresholds, quant = 25)
# table.2575 <- by(datap.collimator, datap.collimator[,"bins"], GetThresholds, quant = 25)
table.2575 <- by(datap.filterLow, datap.filterLow[,"bins"], GetThresholds, quant = 25)
# table.2575 <- by(datap.fullAbsorption, datap.fullAbsorption[,"bins"], GetThresholds, quant = 25)
table.2575<-table.2575[-1]
# выполняем округление до десятков кэВ
table.2575 <- lapply(table.2575, round, -1)
print(table.2575)
# classics ----------------------------------------------------------------
GetClassicsThresholds <- function( ){
p1 <- matrix(c(150,2200,120,3300,0,800,0,200), ncol=4)
colnames(p1) <- c("dE.det1","dE.det2","dE.det3","dE.det4")
rownames(p1) <- c("low","high")
p1 <- as.table(p1)
##########################################################
p2 <- matrix(c(150,1000,3300,9000,0,1800,0,2000), ncol=4)
colnames(p2) <- c("dE.det1","dE.det2","dE.det3","dE.det4")
rownames(p2) <- c("low","high")
p2 <- as.table(p2)
##########################################################
p3 <- matrix(c(0,Inf,3300,9000,1800,10000,0,200), ncol=4)
colnames(p3) <- c("dE.det1","dE.det2","dE.det3","dE.det4")
rownames(p3) <- c("low","high")
p3 <- as.table(p3)
##########################################################
p4 <- matrix(c(0,Inf,1700,3300,10000,28000,0,200), ncol=4)
colnames(p4) <- c("dE.det1","dE.det2","dE.det3","dE.det4")
rownames(p4) <- c("low","high")
p4 <- as.table(p4)
##########################################################
p5 <- matrix(c(0,Inf,1000,1700,28000,Inf,0,200), ncol=4)
colnames(p5) <- c("dE.det1","dE.det2","dE.det3","dE.det4")
rownames(p5) <- c("low","high")
p5 <- as.table(p5)
##########################################################
p6 <- matrix(c(0,Inf,600,1000,28000,Inf,0,200), ncol=4)
colnames(p6) <- c("dE.det1","dE.det2","dE.det3","dE.det4")
rownames(p6) <- c("low","high")
p6 <- as.table(p6)
##########################################################
p7 <- matrix(c(0,Inf,300,1000,10000,28000,1000,Inf), ncol=4)
colnames(p7) <- c("dE.det1","dE.det2","dE.det3","dE.det4")
rownames(p7) <- c("low","high")
p7 <- as.table(p7)
##########################################################
p8 <- matrix(c(500,2200,0,Inf,0,Inf,0,Inf), ncol=4)
colnames(p8) <- c("dE.det1","dE.det2","dE.det3","dE.det4")
rownames(p8) <- c("low","high")
p8 <- as.table(p8)
##########################################################
# print(table.classic)
table.classic <- list(p1,p2,p3,p4,p5,p6,p7,p8)
# table.classic<- vector(mode = "list", length = 8)
# table.classic[[1]] <- p1;
# table.classic[[2]] <- p2;
# table.classic[[3]] <- p3;
# table.classic[[4]] <- p4;
# table.classic[[5]] <- p5;
# table.classic[[6]] <- p6;
# table.classic[[7]] <- p7;
# table.classic[[8]] <- p8;
# print(table.classic)
return(table.classic)
}
table.classic <- GetClassicsThresholds()
print(table.classic)
# plotting ----------------------------------------------------------------
#
# дополняем ее столбцом по эффективности критерия и селективности
#
# строим графики по селективности для каждого типа криетриев
# 5-95 25-75 и классики
plotdEfromE4bwruBig <- function(data, main = "", orig, tab){
layout(matrix(rep(1:12), 3, 4, byrow = TRUE),
widths=c(3,1,3,1),
heights=c(4,4,1)
)
color1 = "navy";
color2 = "olivedrab";
color3 = "turquoise";
color4 = "greenyellow";
color5 = "red";
markers1=c(1, 0);
markers2=c(16, 17);
#par(fig=c(0,0.25,0,1),new=TRUE)
#par(fig=c(0.2,1,0,1),new=FALSE)
par(mar=c(5.1,4.1,4.1,0.1))
plot(orig$E0.keV,orig$dE.det1,
ylim=range(c(orig$dE.det1,data$dE.det1)),
xlim=range(c(orig$E0.keV,data$E0.keV)),
axes=TRUE,ann=FALSE,
col= ifelse(orig$ang_z < 17, color3, color4),
pch = ifelse(orig$ang_z < 17, markers2[1],markers2[2]))
axis(4)
par(new=T)
plot(data$E0.keV,data$dE.det1,
# main="детектор 1",
# xlab="E0, кэВ",
# ylab="dE, кэВ",
main="detector 1",
xlab="E0, keV",
ylab="dE, keV",
ylim=range(c(orig$dE.det1,data$dE.det1)),
xlim=range(c(orig$E0.keV,data$E0.keV)),
col= ifelse(data$ang_z < 17, color1, color2),
pch = ifelse(data$ang_z < 17, markers1[1],markers1[2]))
# axis(1, 900:2000)
axis(2)
par(new=F)
rect(xleft =min(c(orig$E0.keV,data$E0.keV)),
xright=max(c(orig$E0.keV,data$E0.keV)),
ybottom = tab[1,1],ytop = tab[2,1], border = color5)
box()
minor.tick(nx=0, ny=4, tick.ratio=0.5)
legend("topright",
# c("коллиматор", "корпус",
# "первичный поток в коллиматоре"
# # ,"поток ч/з корпус"
# ),
c("collimator selected",
"casing selected",
"collimator original",
"casing original"),
pch=c(markers1,markers2),
cex=.8, col=c(color1, color2, color3, color4))
par(mar=c(5.1,0.1,4.1,2.1))
boxplot(orig$dE.det1~orig$dE.det1>150, axes=FALSE, varwidth=T)
axis(1,at=1:2,labels= paste(c("dE<150","dE>150")), las=2)
#par(fig=c(0,0.25,0,1),new=TRUE)
#par(fig=c(0.2,1,0,1),new=FALSE)
par(mar=c(5.1,4.1,4.1,0.1))
plot(orig$E0.keV,orig$dE.det2,
ylim=range(c(orig$dE.det2,data$dE.det2)),
xlim=range(c(orig$E0.keV,data$E0.keV)),
axes=FALSE,ann=FALSE,
col= ifelse(orig$ang_z < 17, color3, color4),
pch = ifelse(orig$ang_z < 17, markers2[1],markers2[2]))
axis(4)
par(new=T)
plot(data$E0.keV,data$dE.det2,
ylim=range(c(orig$dE.det2,data$dE.det2)),
xlim=range(c(orig$E0.keV,data$E0.keV)),
main="detector 2",
xlab="E0, keV",
ylab="dE, keV",
col= ifelse(data$ang_z < 17, color1, color2),
pch = ifelse(data$ang_z < 17, markers1[1],markers1[2]))
minor.tick(nx=0, ny=4, tick.ratio=0.5)
# legend("topright", c("коллиматор", "корпус"), pch=markers,
# cex=.8, col=c(color1, color2))
rect(xleft =min(c(orig$E0.keV,data$E0.keV)),
xright=max(c(orig$E0.keV,data$E0.keV)),
ybottom = tab[1,2],ytop = tab[2,2], border = color5)
par(mar=c(5.1,0.1,4.1,2.1))
boxplot(orig$dE.det2~orig$dE.det2>120, axes=FALSE, varwidth=T)
axis(1,at=1:2,labels= paste(c("dE<120","dE>120")), las=2)
#par(fig=c(0,0.25,0,1),new=TRUE)
#par(fig=c(0.2,1,0,1),new=FALSE)
par(mar=c(5.1,4.1,4.1,0.1))
plot(orig$E0.keV,orig$dE.det3,
ylim=range(c(orig$dE.det3,data$dE.det3)),
xlim=range(c(orig$E0.keV,data$E0.keV)),
axes=FALSE,ann=FALSE,
col= ifelse(orig$ang_z < 17, color3, color4),
pch = ifelse(orig$ang_z < 17, markers2[1],markers2[2]))
axis(4)
par(new=T)
plot(data$E0.keV,data$dE.det3,
ylim=range(c(orig$dE.det3,data$dE.det3)),
xlim=range(c(orig$E0.keV,data$E0.keV)),
main="detector 3",
xlab="E0, keV",
ylab="dE, keV",
col= ifelse(data$ang_z < 17, color1, color2),
pch = ifelse(data$ang_z < 17, markers1[1],markers1[2]))
minor.tick(nx=0, ny=4, tick.ratio=0.5)
# legend("topright", c("коллиматор", "корпус"), pch=markers,
# cex=.8, col=c(color1, color2))
rect(xleft =min(c(orig$E0.keV,data$E0.keV)),
xright=max(c(orig$E0.keV,data$E0.keV)),
ybottom = tab[1,3],ytop = tab[2,3], border = color5)
par(mar=c(5.1,0.1,4.1,2.1))
boxplot(orig$dE.det3~orig$dE.det3>800, axes=FALSE, varwidth=T)
axis(1,at=1:2,labels= paste(c("dE<800","dE>800")), las=2)
#par(fig=c(0,0.25,0,1),new=TRUE)
#par(fig=c(0.2,1,0,1),new=FALSE)
par(mar=c(5.1,4.1,4.1,0.1))
plot(orig$E0.keV,orig$dE.det4,
ylim=range(c(orig$dE.det4,data$dE.det4)),
xlim=range(c(orig$E0.keV,data$E0.keV)),
axes=FALSE,ann=FALSE,
col= ifelse(orig$ang_z < 17, color3, color4),
pch = ifelse(orig$ang_z < 17, markers2[1],markers2[2]))
axis(4)
par(new=T)
plot(data$E0.keV,data$dE.det4,
ylim=range(c(orig$dE.det4,data$dE.det4)),
xlim=range(c(orig$E0.keV,data$E0.keV)),
main="detector 4",
xlab="E0, keV",
ylab="dE, keV",
col= ifelse(data$ang_z < 17, color1, color2),
pch = ifelse(data$ang_z < 17, markers1[1],markers1[2]))
minor.tick(nx=0, ny=4, tick.ratio=0.5)
# legend("topright", c("коллиматор", "корпус"), pch=markers,
# cex=.8, col=c(color1, color2))
rect(xleft =min(c(orig$E0.keV,data$E0.keV)),
xright=max(c(orig$E0.keV,data$E0.keV)),
ybottom = tab[1,4],ytop = tab[2,4], border = color5)
par(mar=c(5.1,0.1,4.1,2.1))
boxplot(orig$dE.det4~orig$dE.det4>200, axes=F, varwidth=T)
# axis(1,at=1:1,labels= "dE>200", las=2)
axis(1,at=1:2,labels= paste(c("dE<200","dE>200")), las=2)
dole <- nrow(data[(data$ang_z < 17),])/nrow(data[(data$ang_z >= 17),])
a<- paste("В отобранных событиях коллиматор/боковые:"# числа боковых зарегистрированных пролетов к числу пролетов через коллиматор:
, signif(dole, digits = 2) ,sep = " ")
mtext(a, side=1, outer=TRUE, line=-3, cex=0.8)
# sensetivity <- nrow(data)/nrow(orig)
sensetivity <- nrow(data[(data$E0.keV >= min(orig$E0.keV)) &
(data$E0.keV <= max(orig$E0.keV)),])/nrow(orig)
a<- paste("Чувствительность(геометрический фактор):"# числа боковых зарегистрированных пролетов к числу пролетов через коллиматор:
, signif(sensetivity, digits = 2) ,sep = " ")
mtext(a, side=1, outer=TRUE, line=-2, cex=0.8)
# selectivity <- nrow(data[(data$E0.keV >= min(orig$E0.keV)) &
# (data$E0.keV <= max(orig$E0.keV)),])/nrow(data)
precision <- nrow(data[(data$E0.keV >= min(orig$E0.keV)) &
(data$E0.keV <= max(orig$E0.keV)),])/nrow(data)
a<- paste("Точность(количество правильно определенных частиц):"# числа боковых зарегистрированных пролетов к числу пролетов через коллиматор:
, signif(precision, digits = 2) ,sep = " ")
mtext(a, side=1, outer=TRUE, line=-1, cex=0.8)
# dole <- nrow(orig[(orig$ang_z < 17),])/nrow(orig[(orig$ang_z >= 17),])
# a<- paste("Первичные коллиматор/боковые:"# числа боковых зарегистрированных пролетов к числу пролетов через коллиматор:
# , signif(dole, digits = 1) ,sep = " ")
#
#
# mtext(a, side=1, outer=TRUE, line=-1)
mtext(main, side=3, outer=TRUE, line=-1, cex=0.8)
}
plotdEfromE4bwruBig1 <- function(data, main = "", orig, tab){
layout(matrix(rep(1:12), 3, 4, byrow = TRUE),
widths=c(3,1,3,1),
heights=c(4,4,1)
)
color1 = "navy";
color2 = "olivedrab";
color3 = "turquoise";
color4 = "greenyellow";
color5 = "red";
markers1=c(1, 0);
markers2=c(16, 17);
par(mar=c(5.1,4.1,4.1,0.1))
plot(orig$E0.keV,orig$dE.det1,
ylim=range(c(orig$dE.det1,data$dE.det1)),
xlim=range(c(orig$E0.keV,data$E0.keV)),
axes=TRUE,ann=FALSE,
col= ifelse(orig$ang_z < 17, color3, color4),
pch = ifelse(orig$ang_z < 17, markers2[1],markers2[2]))
axis(4)
par(new=T)
plot(data$E0.keV,data$dE.det1,
main="детектор 1",
xlab="E0, кэВ",
ylab="dE, кэВ",
ylim=range(c(orig$dE.det1,data$dE.det1)),
xlim=range(c(orig$E0.keV,data$E0.keV)),
col= ifelse(data$ang_z < 17, color1, color2),
pch = ifelse(data$ang_z < 17, markers1[1],markers1[2]))
# axis(1, 900:2000)
axis(2)
par(new=F)
rect(ybottom = tab[1,1],ytop = tab[2,1], border = color5)
box()
minor.tick(nx=0, ny=4, tick.ratio=0.5)
legend("topright", c("коллиматор", "корпус",
"первичный поток в коллиматоре"
# ,"поток ч/з корпус"
), pch=c(markers1,markers2),
cex=.8, col=c(color1, color2, color3, color4))
par(mar=c(5.1,0.1,4.1,2.1))
boxplot(orig$dE.det1~orig$dE.det1>150, axes=FALSE, varwidth=T)
axis(1,at=1:2,labels= paste(c("dE<150","dE>150")), las=2)
# числа боковых зарегистрированных пролетов к числу пролетов через коллиматор:
dole <- nrow(data[(data$ang_z < 17),])/nrow(data[(data$ang_z >= 17),])
a<- paste("В отобранных событиях коллиматор/боковые:"
, signif(dole, digits = 2) ,sep = " ")
mtext(a, side=1, outer=TRUE, line=-3, cex=0.8)
# числа боковых зарегистрированных пролетов к числу пролетов через коллиматор:
sensetivity <- nrow(data)/nrow(orig)
a<- paste("Чувствительность(геометрический фактор):"
, signif(sensetivity, digits = 2) ,sep = " ")
mtext(a, side=1, outer=TRUE, line=-2, cex=0.8)
# числа боковых зарегистрированных пролетов к числу пролетов через коллиматор:
selectivity <- nrow(data[(data$E0.keV >= min(orig$E0.keV)) &
(data$E0.keV <= max(orig$E0.keV)),])/nrow(data)
a<- paste("Селективность(количество правильно определенных частиц):"
, signif(selectivity, digits = 2) ,sep = " ")
mtext(a, side=1, outer=TRUE, line=-1, cex=0.8)
mtext(main, side=3, outer=TRUE, line=-1, cex=0.8)
}
plotChannel <- function( tab, n){
proton<-datap[((datap$ang_z < 17) & (datap$bins == paste("p", n, sep=""))), ]
# proton<-datap[( (datap$bins == paste("p", n, sep=""))), ]
channel<-datap[((datap$dE.det1 >= tab[1,1]) & datap$dE.det1 <= tab[2,1])&
((datap$dE.det2 >= tab[1,2]) & datap$dE.det2 <= tab[2,2])&
((datap$dE.det3 >= tab[1,3]) & datap$dE.det3 <= tab[2,3])&
((datap$dE.det4 >= tab[1,4]) & datap$dE.det4 <= tab[2,4]),]
main = paste("Канал",n,":",round(min(proton$E0.keV), -2),round(max(proton$E0.keV), -2),
"Отбор:", deparse(substitute(tab)),
"Корпус",casing, sep = " ")
plotdEfromE4bwruBig(channel, main, proton, tab)
}
plotChannelSide <- function( tab, n){
# proton<-datap[((datap$ang_z < 17) & (datap$bins == paste("p", n, sep=""))), ]
proton<-datap[( (datap$bins == paste("p", n, sep=""))), ]
channel<-datap[((datap$dE.det1 >= tab[1,1]) & datap$dE.det1 <= tab[2,1])&
((datap$dE.det2 >= tab[1,2]) & datap$dE.det2 <= tab[2,2])&
((datap$dE.det3 >= tab[1,3]) & datap$dE.det3 <= tab[2,3])&
((datap$dE.det4 >= tab[1,4]) & datap$dE.det4 <= tab[2,4]),]
main = paste("Канал",n,":",round(min(proton$E0.keV), -2),round(max(proton$E0.keV), -2),
"Отбор:", deparse(substitute(tab)),
"Корпус",casing, sep = " ")
plotdEfromE4bwruBig(channel, main, proton, tab)
}
savePlotCannel <- function(n=1){
ppi <- 300
png(paste("proton",n,casing,"classicen.png", sep=""), width=6*ppi, height=6*ppi, res=ppi)
# pdf(paste("proton",n,casing,"classic.pdf", sep=""))
plotChannelSide(table.classic[[n]], n)
dev.off()
png(paste("proton",n,casing,"2575en.png", sep=""), width=6*ppi, height=6*ppi, res=ppi)
# pdf(paste("proton",n,casing,"classic.pdf", sep=""))
plotChannelSide(table.2575[[n]], n)
dev.off()
png(paste("proton",n,casing,"595en.png", sep=""), width=6*ppi, height=6*ppi, res=ppi)
# pdf(paste("proton",n,casing,"classic.pdf", sep=""))
plotChannelSide(table.595[[n]], n)
dev.off()
}
# строим гистограмму энергии в каждом канале
# for (i in 1:8)
# savePlotCannel(i)
# тест с другими корпусами ------------------------------------------------
casing <-'A'
datap<-read.table(paste("protons_",casing,".dat", sep=''), header = TRUE)
datap$bins <- cut(datap$E0.keV, breaks, labels= labels)
# строим гистограмму энергии в каждом канале
for (i in 1:8)
savePlotCannel(i)
casing <-'B'
datap<-read.table(paste("protons_",casing,".dat", sep=''), header = TRUE)
datap$bins <- cut(datap$E0.keV, breaks, labels= labels)
# строим гистограмму энергии в каждом канале
for (i in 1:8)
savePlotCannel(i)
casing <-'C'
datap<-read.table(paste("protons_",casing,".dat", sep=''), header = TRUE)
datap$bins <- cut(datap$E0.keV, breaks, labels= labels)
# строим гистограмму энергии в каждом канале
for (i in 1:8)
savePlotCannel(i)
casing <-'D'
datap<-read.table(paste("protons_",casing,".dat", sep=''), header = TRUE)
datap$bins <- cut(datap$E0.keV, breaks, labels= labels)
# строим гистограмму энергии в каждом канале
for (i in 1:8)
savePlotCannel(i)
# кросс тест с электронами ---------------------------------------------------------------------
# casing <-'D'
# datap<-read.table(paste("electrons_",casing,".dat", sep=''), header = TRUE)
# datap$bins <- cut(datap$E0.keV, breaks, labels= labels)
# plotCrossChannel <- function(n=1){
#
# ppi <- 300
# png(paste("crossEinP",n,casing,"classic.png", sep=""), width=6*ppi, height=6*ppi, res=ppi)
# # pdf(paste("proton",n,casing,"classic.pdf", sep=""))
# plotChannel(table.classic[[n]], n)
# # plotChannel(table.2575[[n+1]], n)
# # plotChannel(table.595[[n+1]], n)
# dev.off()
#
# png(paste("crossEinP",n,casing,"2575.png", sep=""), width=6*ppi, height=6*ppi, res=ppi)
# # pdf(paste("proton",n,casing,"classic.pdf", sep=""))
# plotChannel(table.2575[[n]], n)
# dev.off()
#
# png(paste("crossEinP",n,casing,"595.png", sep=""), width=6*ppi, height=6*ppi, res=ppi)
# # pdf(paste("proton",n,casing,"classic.pdf", sep=""))
# plotChannel(table.595[[n]], n)
# dev.off()
# }
# # строим гистограмму энергии в каждом канале
# for (i in 1:8)
# plotCrossChannel(i)
# off active device ----------------------------------------------------------
dev.off()
# parcoord ----------------------------------------------------------------
library(MASS)
# library(colorRamps)
# data(mtcars)
# k <- blue2red(100)
n = 9
colr = rev(rainbow(n, start = 0, end = 4/6, alpha = 0.2))
# k <- adjustcolor(brewer.pal(3, "Set1")[titdf2$Survived], alpha=.2)
datapdf <- as.data.frame(lapply(as.data.frame(datap), as.numeric))
# new columns with jittered values
datapdf[,9:10] <- lapply((datapdf[,c(6,8)]), jitter)
# x <- cut( datap$E0.keV, 100)
ppi <- 300
png(paste("parallprot1",casing,".png", sep=""), width=6*ppi, height=6*ppi, res=ppi)
op <- par(mar=c(3, rep(.1, 3)))
parcoord(datapdf[,c(1,2,9,3,10,4,7)], col=colr[as.numeric(datapdf$bins)],
main = paste("????? ?????????? ????? ??????, \n , ??????",casing, sep=" ")
)
# par(op)
dev.off() | 4385bb9bbacf8acf8df7cb686bf22dc3a3ce784c | [
"CMake",
"Markdown",
"Makefile",
"R",
"C++"
] | 17 | R | lightweave/radmonitoring | a7a2a8e0c3aa8d9916f58838b2d87adaad2f669b | c49cdcb6f65bc4e329e4b4aaa9f6390a74552d2a |
refs/heads/master | <repo_name>ThompsonBethany01/database-exercises<file_sep>/tables_exercises.sql
--Use the employees database
use employees;
--List all the tables in the database
select database();
--Q: What different data types are present?
DESCRIBE salaries;
--A: int, date, varchar, enum
--Q: Which table(s) do you think contain a numeric type column?
--A: employees, dept_emp, dept_manager, employees_with_departments, salaries
--Q: Which table(s) do you think contain a string type column?
--A: employees, departments, dept_emp, dept-manager, employees_with_departments
--Q: Which table(s) do you think contain a date type column?
--A: employees, dept_emp, dept_manager, employees_with_departments, salaries
--Q: What is the relationship between the employees and the departments tables?
--A: employees -> employees_with_departments -> departments
--Show the SQL that created the dept_manager table
SHOW CREATE TABLE dept_manager;
--CREATE TABLE `dept_manager` (
-- `emp_no` int(11) NOT NULL,
-- `dept_no` char(4) NOT NULL,
-- `from_date` date NOT NULL,
-- `to_date` date NOT NULL,
-- PRIMARY KEY (`emp_no`,`dept_no`),
-- KEY `dept_no` (`dept_no`),
-- CONSTRAINT `dept_manager_ibfk_1` FOREIGN KEY (`emp_no`) REFERENCES `employees` (`emp_no`) ON DELETE CASCADE,
-- CONSTRAINT `dept_manager_ibfk_2` FOREIGN KEY (`dept_no`) REFERENCES `departments` (`dept_no`) ON DELETE CASCADE
-- )
--ENGINE=InnoDB DEFAULT CHARSET=latin1
SELECT artist, genre
FROM albums
WHERE genre LIKE '%rock%';<file_sep>/temporary_tables.sql
-- Create a file named temporary_tables.sql to do your work for this exercise.
SELECT *
FROM emp_w_depts;
-- 1. Using the example from the lesson, re-create the employees_with_departments table.
CREATE TEMPORARY TABLE emp_w_depts(
SELECT *
FROM employees.employees_with_departments AS ewd
);
-- Add a column named full_name to this table.
-- It should be a VARCHAR whose length is the sum of the lengths of the first name and last name columns
ALTER TABLE emp_w_depts ADD full_name VARCHAR(31);
-- Update the table so that full name column contains the correct data
UPDATE emp_w_depts
SET full_name = CONCAT(first_name, ' ', last_name);
-- Remove the first_name and last_name columns from the table.
ALTER TABLE emp_w_depts DROP COLUMN first_name;
ALTER TABLE emp_w_depts DROP COLUMN last_name;
-- What is another way you could have ended up with this same table?
-- Create a query selecting this specific data, and then create the temporary table around it
-- 2. Create a temporary table based on the payment table from the sakila database.
SELECT *
FROM sakila_payment;
DESCRIBE sakila_payment;
CREATE TEMPORARY TABLE sakila_payment(
SELECT *
FROM sakila.payment AS sp);
-- Write the SQL necessary to transform the amount column such that it is stored as an integer representing the number of cents of the payment. For example, 1.99 should become 199.
ALTER TABLE sakila_payment ADD cent_amount INT(10);
UPDATE sakila_payment SET cent_amount = amount * 100;
ALTER TABLE sakila_payment DROP COLUMN amount;
-- 3. Find out how the average pay in each department compares to the overall average pay. In order to make the comparison easier, you should use the Z-score for salaries. In terms of salary, what is the best department to work for? The worst?
-- z-score = ((salary - average))/ stddev
-- first entry 60117
SELECT salary
FROM employees.salaries;
-- 63810.7448
SELECT AVG(salary)
FROM employees.salaries;
-- 16904.8283
SELECT STDDEV(salary)
FROM employees.salaries;
-- step 1: hard code z-score formula
SELECT ((60117 - 63810.7448)/16904.8283);
-- Step 2: insert stddev coding
SELECT ((60117 - 63810.7448)/(SELECT STDDEV(salary)
FROM employees.salaries));
-- Step 3: insert average salary coding
SELECT ((60117 - (SELECT AVG(salary)
FROM employees.salaries))/(SELECT STDDEV(salary)
FROM employees.salaries));
-- Step 4: insert salary value
SELECT emp_no, (((salary) - (SELECT AVG(salary)
FROM employees.salaries))/(SELECT STDDEV(salary)
FROM employees.salaries)) AS z_score
FROM employees.salaries;
-- Step 5: group by department
SELECT money.emp_no, dept_emp.dept_no, depts.dept_name, (((salary) - (SELECT AVG(salary)
FROM employees.salaries))/(SELECT STDDEV(salary)
FROM employees.salaries)) AS z_score
FROM employees.salaries AS money
JOIN employees.dept_emp AS dept_emp ON dept_emp.emp_no = money.emp_no
JOIN employees.departments AS depts ON depts.dept_no = dept_emp.dept_no
ORDER BY emp_no;
CREATE TEMPORARY TABLE z_scores(
SELECT money.emp_no, dept_emp.dept_no, depts.dept_name,
(
(
(salary)
-
(SELECT AVG(salary) FROM employees.salaries)
)
/
(SELECT STDDEV(salary) FROM employees.salaries)
) AS z_score
FROM employees.salaries AS money
JOIN employees.dept_emp AS dept_emp ON dept_emp.emp_no = money.emp_no
JOIN employees.departments AS depts ON depts.dept_no = dept_emp.dept_no
ORDER BY emp_no);
-- z-scores for all historic salaries and department employees
SELECT dept_name, FORMAT(AVG(z_score), 6) AS salary_z_score
FROM z_scores
GROUP BY dept_name;
/*
+--------------------+-----------------+
| dept_name | salary_z_score |
+--------------------+-----------------+
| Customer Service | -0.273079 |
| Development | -0.251549 |
| Finance | 0.378261 |
| Human Resources | -0.467379 |
| Marketing | 0.464854 |
| Production | -0.24084 |
| Quality Management | -0.379563 |
| Research | -0.236791 |
| Sales | 0.972891 |
+--------------------+-----------------+
*/
-- With only current salaries and department employees
CREATE TEMPORARY TABLE z_scores_current_salaries(
SELECT money.emp_no, dept_emp.dept_no, depts.dept_name, (((salary) - (SELECT AVG(salary)
FROM employees.salaries WHERE employees.salaries.to_date > CURDATE()))/(SELECT STDDEV(salary)
FROM employees.salaries WHERE employees.salaries.to_date > CURDATE())) AS z_score
FROM employees.salaries AS money
JOIN employees.dept_emp AS dept_emp ON dept_emp.emp_no = money.emp_no AND dept_emp.to_date > CURDATE()
JOIN employees.departments AS depts ON depts.dept_no = dept_emp.dept_no
WHERE money.to_date > CURDATE()
ORDER BY emp_no);
SELECT dept_name, FORMAT(AVG(z_score),6) AS salary_z_score
FROM z_scores_current_salaries
GROUP BY dept_name;
<file_sep>/README.md
Excercises for the Darden data science cohort
Completed by <NAME><file_sep>/subqueries_exercises.sql
-- Create a file named subqueries_exercises.sql and craft queries to return the results for the following criteria:
-- Find all the employees with the same hire date as employee 101010 using a sub-query.
-- 69 Rows
SELECT *
FROM employees
WHERE hire_date IN
(
SELECT hire_date
FROM employees
WHERE emp_no = 101010
);
-- Find all the titles held by all employees with the first name Aamod.
-- 314 total titles, 6 unique titles
SELECT titles.title, CONCAT(employees.first_name, ' ', employees.last_name) AS 'full_name'
FROM employees
JOIN titles ON titles.emp_no = employees.emp_no
WHERE first_name IN
(
SELECT first_name
FROM employees
WHERE first_name = 'Aamod'
)
ORDER BY titles.title;
SELECT DISTINCT titles.title
FROM employees
JOIN titles ON titles.emp_no = employees.emp_no
WHERE first_name IN
(
SELECT first_name
FROM employees
WHERE first_name = 'Aamod'
);
-- How many people in the employees table are no longer working for the company?
SELECT COUNT(DISTINCT emp_no)
FROM dept_emp
WHERE to_date NOT IN
(
SELECT to_date
FROM dept_emp
WHERE to_date > CURDATE()
GROUP BY emp_no
);
-- Find all the current department managers that are female.
/*
+------------+------------+
| first_name | last_name |
+------------+------------+
| Isamu | Legleitner |
| Karsten | Sigstam |
| Leon | DasSarma |
| Hilary | Kambil |
+------------+------------+
*/
SELECT CONCAT(first_name, ' ', last_name) AS female_managers
FROM dept_manager AS dman
JOIN employees AS emp ON emp.emp_no = dman.emp_no
WHERE gender IN
(
SELECT gender
FROM employees
WHERE gender = 'F'
)
AND to_date > CURDATE();
-- Find all the employees that currently have a higher than average salary.
-- 154543 rows in total. Here is what the first 5 rows will look like:
SELECT emp.first_name, emp.last_name, salaries.salary
FROM salaries
JOIN employees AS emp ON emp.emp_no = salaries.emp_no
WHERE salary >
(
SELECT AVG(salary)
FROM salaries
)
AND to_date > CURDATE();
/*
+------------+-----------+--------+
| first_name | last_name | salary |
+------------+-----------+--------+
| Georgi | Facello | 88958 |
| Bezalel | Simmel | 72527 |
| Chirstian | Koblick | 74057 |
| Kyoichi | Maliniak | 94692 |
| Tzvetan | Zielinski | 88070 |
+------------+-----------+--------+
*/
-- How many current salaries are within 1 standard deviation of the highest salary? (Hint: you can use a built in function to calculate the standard deviation.) What percentage of all salaries is this?
-- 78 salaries
SELECT COUNT(salary)
FROM salaries
WHERE salary > -- filters all salaries higher than (max salary - one standard deviation)
(
(
SELECT MAX(salary) -- max salary
FROM salaries
)
- -- subtracted by
(
SELECT STD(salary) -- standard deviation
FROM salaries
)
)
AND to_date > CURDATE()
; -- filters out any outdated salaries
-- percentage based on all historic salaries
SELECT
(
(
SELECT COUNT(salary)
FROM salaries
WHERE salary > -- filters all salaries higher than (max salary - one standard deviation)
(
(
SELECT MAX(salary) -- max salary
FROM salaries
)
- -- subtracted by
(
SELECT STD(salary) -- standard deviation
FROM salaries
)
)
AND to_date > CURDATE()
)
/COUNT(salary) * 100 -- filters out any outdated salaries that after filtered with WHERE clause
) AS percentage
FROM salaries;
-- percentage of all current salaries
SELECT
(
(
SELECT COUNT(salary)
FROM salaries
WHERE salary > -- filters all salaries higher than (max salary - one standard deviation)
(
(
SELECT MAX(salary) -- max salary
FROM salaries
)
- -- subtracted by
(
SELECT STD(salary) -- standard deviation
FROM salaries
)
)
AND to_date > CURDATE() -- filters out any outdated salaries that after filtered with WHERE clause
)
/COUNT(salary) * 100
) AS percentage
FROM salaries
WHERE to_date > CURDATE(); -- filters out any outdated salaries from the total salaries
-- We want salaries > MAX(salary) - STD(salary)
-- BONUS
-- Find all the department names that currently have female managers.
/*
+-----------------+
| dept_name |
+-----------------+
| Development |
| Finance |
| Human Resources |
| Research |
+-----------------+
*/
-- Find the first and last name of the employee with the highest salary.
/*
+------------+-----------+
| first_name | last_name |
+------------+-----------+
| Tokuyasu | Pesch |
+------------+-----------+
*/
-- Find the department name that the employee with the highest salary works in.
/*
+-----------+
| dept_name |
+-----------+
| Sales |
+-----------+
*/<file_sep>/case_exercises.sql
-- Create a file named case_exercises.sql and craft queries to return the results for the following criteria:
-- 1. Write a query that returns all employees (emp_no), their department number, their start date, their end date, and a new column 'is_current_employee' that is a 1 if the employee is still with the company and 0 if not.
SELECT e.emp_no, de.dept_no, de.from_date, de.to_date,
CASE
WHEN (to_date > CURDATE()) THEN 1
ELSE 0
END AS is_current_employee
FROM employees AS e
JOIN dept_emp AS de ON e.emp_no = de.emp_no
ORDER BY e.emp_no;
-- 2. Write a query that returns all employee names, and a new column 'alpha_group' that returns 'A-H', 'I-Q', or 'R-Z' depending on the first letter of their last name.
SELECT CONCAT(first_name, ' ', last_name) AS full_name,
CASE
WHEN SUBSTR(last_name, 1, 1) <= 'H' THEN 'A-H'
WHEN SUBSTR(last_name, 1, 1) >= 'I' AND SUBSTR(last_name, 1, 1) <= 'Q' THEN 'I-Q'
WHEN SUBSTR(last_name, 1, 1) >= 'R' AND SUBSTR(last_name, 1, 1) <= 'Z' THEN 'R-Z'
ELSE `last_name`
END as alpha_group
FROM employees
ORDER BY last_name;
-- Another option
SELECT CONCAT(first_name, ' ', last_name) AS full_name,
CASE
WHEN SUBSTR(last_name, 1, 1) REGEXP '[abcdefgh]' THEN 'A-H'
WHEN SUBSTR(last_name, 1, 1) REGEXP '[ijklmnopq]' THEN 'I-Q'
WHEN SUBSTR(last_name, 1, 1) REGEXP '[rstuvwxyz]' THEN 'R-Z'
ELSE `last_name`
END as alpha_group
FROM employees
ORDER BY last_name;
-- 3. How many employees were born in each decade?
SELECT COUNT(birth_date) AS total_employees,
CASE
WHEN birth_date LIKE '194%' THEN '40s'
WHEN birth_date LIKE '195%' THEN '50s'
WHEN birth_date LIKE '196%' THEN '60s'
WHEN birth_date LIKE '197%' THEN '70s'
END AS decade
FROM employees
GROUP BY decade;
-- ____________________BONUS_______________________
-- What is the average salary for each of the following department groups: R&D, Sales & Marketing, Prod & QM, Finance & HR, Customer Service?
-- Step 1: Combine specified groups
SELECT dept_name,
CASE
WHEN dept_name IN ('research', 'development') THEN 'R_&_D'
WHEN dept_name IN ('sales', 'marketing') THEN 'Sales_&_Marketing'
WHEN dept_name IN ('production', 'quality management') THEN 'Prod_&_QM'
WHEN dept_name IN ('finance', 'human resources') THEN 'Finance_&_HR'
WHEN dept_name IN ('customer service') THEN 'Customer_Service'
ELSE dept_name
END AS dept_group
FROM employees.departments
ORDER BY dept_group;
-- Step 2: Group By dept_group
SELECT
CASE
WHEN dept_name IN ('research', 'development') THEN 'R_&_D'
WHEN dept_name IN ('sales', 'marketing') THEN 'Sales_&_Marketing'
WHEN dept_name IN ('production', 'quality management') THEN 'Prod_&_QM'
WHEN dept_name IN ('finance', 'human resources') THEN 'Finance_&_HR'
WHEN dept_name IN ('customer service') THEN 'Customer_Service'
ELSE dept_name
END AS dept_group
FROM employees.departments
GROUP BY dept_group;
-- Step 3: Join salaries/End Results
SELECT
CASE -- Case statment groups by specified departments
WHEN dept_name IN ('research', 'development') THEN 'R_&_D'
WHEN dept_name IN ('sales', 'marketing') THEN 'Sales_&_Marketing'
WHEN dept_name IN ('production', 'quality management') THEN 'Prod_&_QM'
WHEN dept_name IN ('finance', 'human resources') THEN 'Finance_&_HR'
WHEN dept_name IN ('customer service') THEN 'Customer_Service'
ELSE dept_name
END AS dept_group,
FORMAT(AVG(salary), 2) AS avg_salary -- Calculates avg salary of grouped departments
FROM departments
JOIN dept_emp AS de ON de.dept_no = departments.dept_no -- Joins dept_emp to be able to link salaries
JOIN salaries AS s ON s.emp_no = de.emp_no -- Joins salaries to have access to AVG(salary) function
GROUP BY dept_group -- Groups departments from case statement
;
/*
+-------------------+-----------------+
| dept_group | avg_salary |
+-------------------+-----------------+
| Customer Service | |
| Finance & HR | |
| Sales & Marketing | |
| Prod & QM | |
| R&D | |
+-------------------+-----------------+
*/<file_sep>/mysql_introduction.sql
#Use the employees database
use employees;
#List all the tables in the database
show tables;
#Q: What different data types are present?
DESCRIBE employees;
DESCRIBE departments;
DESCRIBE dept_manager;
DESCRIBE salaries;
DESCRIBE titles;
#A: int,date, varchar, enum
#Q: Which table(s) do you think contain a numeric type column?
#A: The employee ID number, salarie dollar amounts, other columns are numbers in date dtype
#Q: Which table(s) do you think contain a string type column?
#A: The employees' first name and last name, emp title name, emp department title
#Q: Which table(s) do you think contain a date type column?
#A: The employees' birth date and hire date, from date and to date in multiple tables
#Q: What is the relationship between the employees and the departments tables?
#A: employees -> employees_with_departments -> departments<file_sep>/group_by_exercises.sql
-- Create a new file named group_by_exercises.sql
-- In your script, use DISTINCT to find the unique titles in the titles table.
SELECT DISTINCT title
FROM titles;
-- Find your query for employees whose last names start and end with 'E'. Update the query find just the unique last names that start and end with 'E' using GROUP BY.
SELECT last_name
FROM employees
WHERE last_name LIKE 'E%e'
GROUP BY last_name ASC;
-- Update your previous query to now find unique combinations of first and last name where the last name starts and ends with 'E'. You should get 846 rows.
SELECT first_name, last_name
FROM employees
WHERE last_name LIKE 'E%e'
GROUP BY first_name, last_name;
-- Find the unique last names with a 'q' but not 'qu'.
SELECT last_name
FROM employees
WHERE last_name LIKE '%q%'
AND last_name NOT LIKE '%qu%'
GROUP BY last_name;
-- Add a COUNT() to your results and use ORDER BY to make it easier to find employees whose unusual name is shared with others
SELECT last_name AS 'Unique_Last_Name', COUNT(last_name) AS 'Name_Count'
FROM employees
WHERE last_name LIKE '%q%'
AND last_name NOT LIKE '%qu%'
GROUP BY last_name
ORDER BY COUNT(last_name) DESC;
-- Update your query for 'Irena', 'Vidya', or 'Maya'. Use COUNT(*) and GROUP BY to find the number of employees for each gender with those names.
SELECT COUNT(first_name) AS 'Name_Count', gender
FROM employees
WHERE first_name IN ('Irena', 'Vidya', 'Maya')
GROUP BY gender;
-- Recall the query that generated usernames for the employees from the last lesson. Are there any duplicate usernames?
-- There are duplicates because SELECT with DISTINCT != SELECT without DISTINCT
-- 300,024 rows
SELECT
LOWER(CONCAT(
SUBSTR(first_name,1,1), -- first char in first name
SUBSTR(last_name,1,4), -- first 4 char in last name
'_', -- underscore
SUBSTR(birth_date,6,2), -- birth month
SUBSTR(birth_date,3,2) -- birth year
)) AS 'Username',
CONCAT(first_name, ' ',last_name) AS '<NAME>',
birth_date AS 'Birthday'
FROM employees;
-- 285872 rows
SELECT DISTINCT LOWER(CONCAT(
SUBSTR(first_name,1,1), -- first 4 char in last name
SUBSTR(last_name,1,4), -- first 4 char in last name
SUBSTR(birth_date,6,2), -- birth month
"_", -- underscore
SUBSTR(birth_date,3,2) -- birth year
)) AS 'Username'
FROM employees;
-- another way to see if duplicates
SELECT username, COUNT(*) AS records
FROM
(
(SELECT
CONCAT
(
LOWER(SUBSTR(first_name, 1, 1)),
LOWER(SUBSTR(last_name, 1, 4)),
"_",
SUBSTR(birth_date, 6, 2),
SUBSTR(birth_date, 3, 2)
) AS username,
first_name, last_name, birth_date
FROM employees
) AS temp)
GROUP by username
ORDER BY records DESC;
-- Bonus: how many duplicate usernames are there?
-- 300,024 minus 285,872 = 14,152 turns out to be wrong lol \/
-- Finding answer programaticaly...
SELECT sum(temp.username_count)
FROM (
SELECT CONCAT(LOWER(SUBSTR(first_name, 1, 1)), LOWER(SUBSTR(last_name, 1, 4)), "_", SUBSTR(birth_date, 6, 2), SUBSTR(birth_date, 3, 2)) AS username, COUNT(*) as username_count
FROM employees
GROUP BY username
ORDER BY username_count DESC
) as temp
WHERE username_count > 1;<file_sep>/select_exercises.sql
-- Use the albums_db database
USE albums_db;
-- Explore the structure of the albums table.
DESCRIBE albums;
-- Write queries to find the following information.
-- The name of all albums by <NAME>
SELECT artist, name
FROM albums
WHERE artist = '<NAME>';
-- The year Sgt. Pepper's Lonely Hearts Club Band was released
SELECT artist, name, release_date
FROM albums
WHERE name = 'Sgt. Pepper\'s Lonely Hearts Club Band';
-- The genre for the album Nevermind
SELECT artist, name, genre
FROM albums
WHERE name = 'Nevermind';
-- Which albums were released in the 1990s
SELECT artist, name, release_date
FROM albums
WHERE release_date BETWEEN 1990 and 1999;
-- Which albums had less than 20 million certified sales
SELECT artist, name, sales
FROM albums
WHERE sales < 20;
-- All the albums with a genre of "Rock". Why do these query results not include albums with a genre of "Hard rock" or "Progressive rock"?
SELECT artist, name, genre
FROM albums
WHERE genre = 'Rock';
SELECT artist, name, genre
FROM albums
WHERE genre = 'rock' OR genre = 'Hard Rock' OR genre = 'Progressive Rock' OR genre = 'Alternative Rock';
-- 'Rock' != 'Hard Rock', they are not equivalent
SELECT *
FROM albums
WHERE genre LIKE '%Rock';<file_sep>/extra_exercises.sql
-- Extr SQL Exercises
-- How much do the current managers of each department get paid, relative to the average salary for the department?
#first let's find the average salary for each department
SELECT de.dept_no as department, AVG(s.salary) as average_salary
FROM salaries as s
JOIN dept_emp as de on de.emp_no = s.emp_no and de.to_date > CURDATE()
WHERE s.to_date > CURDATE()
GROUP BY de.dept_no;
#second we find the salary of all current managers, along with their department no
SELECT dm.emp_no, dm.dept_no, s.salary
FROM dept_manager as dm
JOIN salaries as s on s.emp_no = dm.emp_no and s.to_date > CURDATE()
WHERE dm.to_date > CURDATE();
#let's add their names
SELECT CONCAT(e.first_name, ' ',e.last_name) as first_name, dm.emp_no, dm.dept_no, s.salary
FROM dept_manager as dm
JOIN salaries as s on s.emp_no = dm.emp_no and s.to_date > CURDATE()
JOIN employees as e on e.emp_no = dm.emp_no
WHERE dm.to_date > CURDATE();
#now we can add the tables together
SELECT CONCAT(e.first_name, ' ',e.last_name) as first_name, dm.emp_no, dm.dept_no, s.salary as manager_salary, dept_s.department_salary
FROM dept_manager as dm
JOIN salaries as s on s.emp_no = dm.emp_no and s.to_date > CURDATE()
JOIN employees as e on e.emp_no = dm.emp_no
JOIN (
SELECT de.dept_no, ROUND(AVG(s.salary),0) as department_salary
FROM salaries as s
JOIN dept_emp as de on de.emp_no = s.emp_no and de.to_date > CURDATE()
WHERE s.to_date > CURDATE()
GROUP BY de.dept_no
) as dept_s on dept_s.dept_no = dm.dept_no
WHERE dm.to_date > CURDATE();
-- Is there any department where the department manager gets paid less than the average salary?
#two managers make less money than the department average
SELECT *
FROM(
SELECT CONCAT(e.first_name, ' ',e.last_name) as first_name, dm.emp_no, dm.dept_no, s.salary as manager_salary, dept_s.department_salary
FROM dept_manager as dm
JOIN salaries as s on s.emp_no = dm.emp_no and s.to_date > CURDATE()
JOIN employees as e on e.emp_no = dm.emp_no
JOIN (
SELECT de.dept_no, ROUND(AVG(s.salary),0) as department_salary
FROM salaries as s
JOIN dept_emp as de on de.emp_no = s.emp_no and de.to_date > CURDATE()
WHERE s.to_date > CURDATE()
GROUP BY de.dept_no
) as dept_s on dept_s.dept_no = dm.dept_no
WHERE dm.to_date > CURDATE()
) as dept_man_salaries
JOIN departments as d on d.dept_no = dept_man_salaries.dept_no
WHERE manager_salary < department_salary;
-- Step 1: Find salary of current managers
SELECT dm.emp_no, e.first_name, e.last_name, FORMAT(s.salary, 2) AS manager_salary, d.dept_name
FROM dept_manager AS dm
JOIN salaries AS s ON s.emp_no = dm.emp_no AND s.to_date > CURDATE()
JOIN employees as e ON e.emp_no = dm.emp_no
JOIN departments AS d ON d.dept_no = dm.dept_no
WHERE dm.to_date > CURDATE();
-- Step 2: Find average salary of each departments
SELECT d.dept_name, FORMAT(AVG(salary), 2) AS department_salary
FROM salaries AS s
JOIN dept_emp AS de ON de.emp_no = s.emp_no
JOIN departments AS d ON d.dept_no = de.dept_no
WHERE s.to_date > CURDATE()
GROUP BY dept_name;
-- Employees Date Base
SELECT *
FROM dept_manager AS dm
JOIN salaries AS s ON dm.emp_no = s.emp_no AND s.to_date > CURDATE()
WHERE dm.to_date > CURDATE();
-- World Data Base
-- What languages are spoken in Santa Monica?
SELECT cl.language, cl.percentage
FROM countrylanguage AS cl
JOIN country ON country.code = cl.countrycode
JOIN city ON city.countrycode = country.code
WHERE city.name LIKE 'Santa Monica'
ORDER BY cl.percentage ASC, cl.language ASC;
-- How many different countries are in each region?
SELECT region, COUNT(name) AS num_countries
FROM country
GROUP BY region
ORDER BY num_countries ASC;
-- What is the population for each region?
SELECT region, SUM(population) AS population
FROM country
GROUP BY population DESC, region;
-- What is the population for each continent?
SELECT continent, SUM(population) AS population
FROM country
GROUP BY continent
ORDER BY population DESC;
-- What is the average life expectancy globally?
SELECT AVG(lifeexpectancy)
FROM country;
-- What is the average life expectancy for each region, each continent?
-- Sort the results from shortest to longest
SELECT region, AVG(lifeexpectancy)
FROM country
GROUP BY region
ORDER BY AVG(lifeexpectancy);
SELECT continent, AVG(lifeexpectancy)
FROM country
GROUP BY continent
ORDER BY AVG(lifeexpectancy);
-- BONUS______________________________________________________________________
-- Find all the countries whose local name is different from the official name.
SELECT *
FROM country
WHERE name != LocalName;
-- How many countries have a life expectancy less than x?
SELECT *
FROM country
WHERE LifeExpectancy < 40;
-- What state is city x located in?
SELECT *
FROM city
JOIN country on country.code = city.CountryCode
WHERE city.name = 'Dubai';
-- What region of the world is city x located in?
SELECT Region
FROM city
JOIN country on country.code = city.CountryCode
WHERE city.name = 'Dubai';
-- What country (use the human readable name) city x located in?
SELECT country.name
FROM city
JOIN country on country.code = city.CountryCode
WHERE city.name = 'Dubai';
-- What is the life expectancy in city x?
SELECT LifeExpectancy
FROM country
JOIN city on country.code = city.CountryCode
WHERE city.name = 'Los Angeles'<file_sep>/limit_exercises.sql
-- Use employees
use employees;
-- List the first 10 distinct last names sorted in descending order
SELECT DISTINCT last_name
FROM employees
ORDER BY last_name DESC
LIMIT 10;
-- Find your query for employees born on Christmas and hired in the 90s from order_by_exercises.sql
-- Update it to find just the first 5 employees.
-- |5B) Find all employees hired in the 90s and born on Christmas
-- |362 rows
-- |SELECT *
-- |FROM employees
-- |WHERE hire_date like '199%'
-- |AND birth_date like '%12-25';
SELECT *
FROM employees
WHERE hire_date LIKE '199%'
AND birth_date LIKE '%12-25'
ORDER BY birth_date ASC, hire_date DESC
LIMIT 5;
-- Try to think of your results as batches, sets, or pages
-- The first five results are your first page
-- The five after that would be your second page, etc.
-- Update the query to find the tenth page of results
-- Page 10 would be results of pages 45-50
SELECT *
FROM employees
WHERE hire_date LIKE '199%'
AND birth_date LIKE '%12-25'
ORDER BY birth_date ASC, hire_date DESC
LIMIT 5 OFFSET 45;
-- LIMIT and OFFSET can be used to create multiple pages of data. What is the relationship between OFFSET (number of results to skip), LIMIT (number of results per page), and the page number?
-- OFFEST is the index value of the page
-- LIMIT is items per page
-- OFFSET = (Page #)(LIMIT)-(LIMIT)
-- OFFSET = LIMIT(Page# - 1)<file_sep>/functions_exercises.sql
-- ________________________________Previuos Exercise__________________________________ --
-- Modify your first query to order by first name
-- The first result should be <NAME> and the last result should be <NAME>.
SELECT *
FROM employees
WHERE first_name IN ('Irena', 'Vidya', 'Maya')
ORDER BY first_name;
-- Update the query to order by first name and then last name
-- The first result should now be <NAME> and the last should be <NAME>.
SELECT *
FROM employees
WHERE first_name IN ('Irena', 'Vidya', 'Maya')
ORDER BY first_name, last_name;
-- Change the order by clause so that you order by last name before first name
-- Your first result should still be <NAME> but now the last result should be <NAME>.
SELECT *
FROM employees
WHERE first_name IN ('Irena', 'Vidya', 'Maya')
ORDER BY last_name, first_name;
-- Update your queries for employees with 'E' in their last name to sort the results by their employee number.
-- Your results should not change!
SELECT *
FROM employees
WHERE last_name like 'E%'
ORDER BY emp_no;
SELECT *
FROM employees
WHERE last_name LIKE 'E%'
OR last_name LIKE '%e'
ORDER BY emp_no;
SELECT *
FROM employees
WHERE last_name LIKE 'E%'
AND last_name LIKE '%e'
ORDER BY emp_no;
-- Now reverse the sort order for both queries.
SELECT *
FROM employees
WHERE last_name like 'E%'
ORDER BY emp_no DESC;
SELECT *
FROM employees
WHERE last_name LIKE 'E%'
OR last_name LIKE '%e'
ORDER BY emp_no DESC;
SELECT *
FROM employees
WHERE last_name LIKE 'E%'
AND last_name LIKE '%e'
ORDER BY emp_no DESC;
-- Change the query for employees hired in the 90s and born on Christmas such that the first result is the oldest employee who was hired last.
-- It should be <NAME>.
SELECT *
FROM employees
WHERE hire_date LIKE '199%'
AND birth_date LIKE '%12-25'
ORDER BY birth_date ASC, hire_date DESC;
-- ______________________________Current Exercise___________________________________ --
use employees;
-- Copy the order by exercise and save it as functions_exercises.sql.
-- Update your queries for employees whose names start and end with 'E'.
-- Use concat() to combine their first and last name together as a single column named full_name.
SELECT CONCAT(first_name,' ',last_name) AS full_name
FROM employees
WHERE last_name LIKE 'E%'
AND last_name LIKE '%e'
ORDER BY emp_no ASC;
SELECT CONCAT(first_name,' ',last_name) AS full_name
FROM employees
WHERE last_name LIKE 'E%'
OR last_name LIKE '%e'
ORDER BY emp_no;
-- Convert the names produced in your last query to all uppercase.
SELECT UPPER(CONCAT(first_name,' ',last_name)) AS full_name
FROM employees
WHERE last_name LIKE 'E%'
AND last_name LIKE '%e'
ORDER BY emp_no DESC;
SELECT UPPER(CONCAT(first_name,' ',last_name)) AS full_name
FROM employees
WHERE last_name LIKE 'E%'
OR last_name LIKE '%e'
ORDER BY emp_no;
-- For your query of employees born on Christmas and hired in the 90s, use datediff() to find how many days they have been working at the company
-- (Hint: You will also need to use NOW() or CURDATE())
SELECT DATEDIFF(CURDATE(), hire_date) AS days_at_company,
(DATEDIFF(CURDATE(), hire_date)/365) AS years_at_company,
emp_no,
CONCAT(first_name, ' ',last_name) AS full_name,
hire_date
FROM employees
WHERE hire_date LIKE '199%'
AND birth_date LIKE '%12-25'
ORDER BY birth_date ASC, hire_date DESC;
-- Find the smallest and largest salary from the salaries table.
SELECT MIN(salary) AS lowest_salary, MAX(salary) AS highest_salary
FROM salaries;
-- Use your knowledge of built in SQL functions to generate a username for all of the employees
-- A username should be all lowercase, and consist of the first character of the employees first name, the first 4 characters of the employees last name, an underscore, the month the employee was born, and the last two digits of the year that they were born.
SELECT emp_no AS 'Employee Number',
LOWER(CONCAT(
SUBSTR(first_name,1,1), -- first 4 char in last name
SUBSTR(last_name,1,4), -- first 4 char in last name
SUBSTR(birth_date,6,2), -- birth month
"_", -- underscore
SUBSTR(birth_date,3,2) -- birth year
)) AS 'Username',
CONCAT(first_name, ' ',last_name) AS 'Full Name',
birth_date AS 'Birthday'
FROM employees;
<file_sep>/join_exercises.sql
-- Create a file named join_exercises.sql to do your work in.
-- _________________Join Example Database__________________ --
-- Use the join_example_db. Select all the records from both the users and roles tables.
USE join_example_db;
SELECT *
FRom roles as roles
JOIN users as users ON roles.id = users.role_id;;
-- Use join, left join, and right join to combine results from the users and roles tables as we did in the lesson. Before you run each query, guess the expected number of results.
SELECT roles.name, COUNT(roles.name)
FROM roles as roles
LEFT JOIN users as users ON roles.id = users.role_id
GROUP BY roles.name;
SELECT *
FROM roles as roles
RIGHT JOIN users as users ON roles.id = users.role_id;
-- Although not explicitly covered in the lesson, aggregate functions like count can be used with join queries. Use count and the appropriate join type to get a list of roles along with the number of users that has the role. Hint: You will also need to use group by in the query.
SELECT roles.name, COUNT(roles.name)
FROM roles as roles
RIGHT JOIN users as users ON roles.id = users.role_id
GROUP BY roles.name;
-- _______________________Employees Database_______________________ --
-- 1. Use the employees database.
use employees;
-- 2. Using the example in the Associative Table Joins section as a guide, write a query that shows each department along with the name of the current manager for that department.
SELECT depts.dept_name AS 'Department Name', CONCAT(emps.first_name, ' ', emps.last_name) AS 'Department Manager'
FROM departments AS depts
JOIN dept_manager AS managers ON depts.dept_no = managers.dept_no AND managers.to_date > CURDATE()
JOIN employees AS emps ON managers.emp_no = emps.emp_no
ORDER BY depts.dept_name;
/* Department Name | Department Manager
--------------------+--------------------
Customer Service | <NAME>
Development | <NAME>
Finance | <NAME>
Human Resources | <NAME>
Marketing | <NAME>
Production | <NAME>
Quality Management | <NAME>
Research | <NAME>
Sales | <NAME> */
-- 3. Find the name of all departments currently managed by women.
SELECT depts.dept_name AS 'Department Name', CONCAT(emps.first_name, ' ', emps.last_name) AS 'Department Manager'
FROM departments AS depts
JOIN dept_manager AS managers ON depts.dept_no = managers.dept_no AND managers.to_date > CURDATE()
JOIN employees AS emps ON managers.emp_no = emps.emp_no AND emps.gender = 'F'
ORDER BY depts.dept_name;
/*Department Name | Manager Name
----------------+-----------------
Development | <NAME>
Finance | <NAME>
Human Resources | <NAME>
Research | <NAME> */
-- 4. Find the current titles of employees currently working in the Customer Service department.
SELECT titles.title, COUNT(titles.title)
FROM departments as depts
JOIN dept_emp as dept_emps ON depts.dept_no = dept_emps.dept_no AND dept_emps.dept_no = 'd009'
JOIN titles AS titles ON dept_emps.emp_no = titles.emp_no AND titles.to_date > CURDATE()
GROUP BY titles.title;
/*Title | Count
-------------------+------
Assistant Engineer | 68
Engineer | 627
Manager | 1
Senior Engineer | 1790
Senior Staff | 11268
Staff | 3574
Technique Leader | 241 */
-- 5. Find the current salary of all current managers.
SELECT depts.dept_name AS 'Department Name',
CONCAT(emp.first_name, ' ', emp.last_name) AS 'Name',
money.salary AS 'Salary'
FROM salaries AS money
JOIN dept_manager AS managers ON money.emp_no = managers.emp_no AND managers.to_date > CURDATE()
JOIN departments AS depts ON managers.dept_no = depts.dept_no
JOIN employees AS emp ON managers.emp_no = emp.emp_no
WHERE money.to_date > CURDATE()
ORDER BY depts.dept_name;
/*Department Name | Name | Salary
-------------------+-------------------+-------
Customer Service | <NAME> | 58745
Development | <NAME> | 74510
Finance | <NAME> | 83457
Human Resources | <NAME> | 65400
Marketing | <NAME> | 106491
Production | <NAME> | 56654
Quality Management | <NAME> | 72876
Research | <NAME> | 79393
Sales | <NAME> | 101987 */
-- 6. Find the number of employees in each department.
SELECT dept.dept_no, dept.dept_name, COUNT(emp.emp_no) AS 'num_employees'
FROM departments AS dept
JOIN dept_emp AS emp ON emp.dept_no = dept.dept_no AND emp.to_date > CURDATE()
GROUP BY dept.dept_no;
/*
+---------+--------------------+---------------+
| dept_no | dept_name | num_employees |
+---------+--------------------+---------------+
| d001 | Marketing | 14842 |
| d002 | Finance | 12437 |
| d003 | Human Resources | 12898 |
| d004 | Production | 53304 |
| d005 | Development | 61386 |
| d006 | Quality Management | 14546 |
| d007 | Sales | 37701 |
| d008 | Research | 15441 |
| d009 | Customer Service | 17569 |
+---------+--------------------+---------------+*/
-- 7. Which department has the highest average salary?
SELECT dept.dept_name AS dept_name, AVG(money.salary) AS average_salary
FROM salaries AS money
JOIN dept_emp AS emp ON money.emp_no = emp.emp_no AND emp.to_date > CURDATE()
JOIN departments AS dept ON emp.dept_no = dept.dept_no
WHERE money.to_date > CURDATE()
GROUP BY dept.dept_name
ORDER BY AVG(money.salary) DESC
LIMIT 1;
/*
+-----------+----------------+
| dept_name | average_salary |
+-----------+----------------+
| Sales | 88852.9695 |
+-----------+----------------+*/
-- 8. Who is the highest paid employee in the Marketing department?
SELECT CONCAT(emps.first_name, ' ', emps.last_name) AS full_name
FROM salaries AS money
JOIN dept_emp AS emp_dept ON money.emp_no = emp_dept.emp_no AND emp_dept.dept_no = 'd001'
JOIN employees AS emps ON money.emp_no = emps.emp_no
ORDER BY money.salary DESC
LIMIT 1;
/*
+------------+-----------+
| first_name | last_name |
+------------+-----------+
| Akemi | Warwick |
+------------+-----------+*/
-- 9. Which current department manager has the highest salary?
SELECT emp.first_name, emp.last_name, money.salary, dept.dept_name
FROM employees AS emp
JOIN dept_manager AS man ON emp.emp_no = man.emp_no AND man.to_date > CURDATE()
JOIN salaries AS money ON emp.emp_no = money.emp_no AND money.to_date > CURDATE()
JOIN departments AS dept ON dept.dept_no = man.dept_no
ORDER BY money.salary DESC
LIMIT 1;
/*
+------------+-----------+--------+-----------+
| first_name | last_name | salary | dept_name |
+------------+-----------+--------+-----------+
| Vishwani | Minakawa | 106491 | Marketing |
+------------+-----------+--------+-----------+*/
-- Bonus Find the names of all current employees, their department name, and their current manager's name.
-- SELECT CONCAT(emp.first_name, ' ', emp.last_name) AS emp_name, dept.dept_name AS department
SELECT CONCAT(employees.first_name, ' ', employees.last_name) AS employee_name,
man.dept_name AS department_name,
man.manager_name
FROM employees
JOIN dept_emp ON employees.emp_no = dept_emp.emp_no AND dept_emp.to_date > CURDATE()
JOIN
(
SELECT CONCAT(emp.first_name, ' ', emp.last_name) AS manager_name, dept.dept_name, dept_emp.dept_no
FROM employees as emp
JOIN dept_emp ON dept_emp.emp_no = emp.emp_no AND dept_emp.to_date > CURDATE()
JOIN departments AS dept ON dept.dept_no = dept_emp.dept_no
LEFT JOIN dept_manager AS man ON man.dept_no = dept_emp.dept_no AND man.to_date > CURDATE()
WHERE emp.emp_no IN
(
SELECT dept_manager.emp_no
FROM dept_manager
WHERE dept_manager.to_date > CURDATE()
)
)AS man ON man.dept_no = dept_emp.dept_no
WHERE dept_emp.dept_no = man.dept_no;
/*240,124 Rows
Employee Name | Department Name | Manager Name
--------------|------------------|-----------------
<NAME> | Customer Service | <NAME>
.....*/
-- Bonus Find the highest paid employee in each department.
SELECT *
FROM
(
SELECT emp.first_name, money.salary, dept.dept_name
FROM employees AS emp
JOIN salaries AS money ON money.emp_no = emp.emp_no AND money.to_date > CURDATE()
JOIN dept_emp ON dept_emp.emp_no = emp.emp_no AND dept_emp.to_date > CURDATE()
JOIN departments AS dept ON dept.dept_no = dept_emp.dept_no
GROUP BY money.salary, dept.dept_name
ORDER BY money.salary DESC
) AS dept_pay;
| 6d510993122269af929f16f971ceb40cd0baf47a | [
"Markdown",
"SQL"
] | 12 | SQL | ThompsonBethany01/database-exercises | 283c938c2b2134a465589e1b8288b7c1422f6d19 | 3ae6feb85ec7efe770678c3ea0756c3a6de0e6fb |
refs/heads/main | <file_sep>import { Field, InputType } from "@nestjs/graphql";
import { IsEmail, IsOptional, IsString, MaxLength, MinLength } from "class-validator";
@InputType()
export class UpdateStudentInput {
@Field()
@IsOptional({message: 'Optional field'})
@IsString()
@MinLength(3, { message: 'Name is too short. Minimal length is $constraint1 characters, but actual is $value' })
@MaxLength(50, { message: 'Name is too long. Maximal length is $constraint1 characters, but actual is $value' })
name?: string;
@Field()
@IsOptional()
@IsEmail()
email?: string;
}<file_sep>TYPEORM_CONNECTION = postgres
TYPEORM_HOST = localhost
TYPEORM_USERNAME = descomplica
TYPEORM_PASSWORD = <PASSWORD>
TYPEORM_DATABASE = student_db
TYPEORM_PORT = 5432
TYPEORM_SYNCHRONIZE = true
TYPEORM_LOGGING = true
TYPEORM_ENTITIES = entity/*.js,modules/**/entity/*.js
API_PORT = 3000<file_sep>import { Column, Entity, PrimaryColumn } from "typeorm";
@Entity()
export class Student {
@PrimaryColumn()
cpf: string;
@Column()
name: string;
@Column()
email: string;
}<file_sep>TYPEORM_CONNECTION = postgres
TYPEORM_HOST = postgres
TYPEORM_USERNAME = descomplica
TYPEORM_PASSWORD = <PASSWORD>
TYPEORM_DATABASE = student_db
TYPEORM_PORT = 5432
TYPEORM_SYNCHRONIZE = true
TYPEORM_LOGGING = false
TYPEORM_CACHE = true
TYPEORM_ENTITIES = entities/*.js,modules/**/entities/*.js,**/entities/*.js
API_HOST = http://localhost
API_PORT = 3000
REACT_APP_GRAPHQL_URI= ${API_HOST}:${API_PORT}<file_sep>import { FilterableField } from "@nestjs-query/query-graphql";
import { ObjectType } from "@nestjs/graphql";
@ObjectType('Student')
export class StudentDTO {
@FilterableField()
cpf: string;
@FilterableField()
name: string;
@FilterableField()
email: string;
}<file_sep># Student App
Um projeto para gerenciar estudantes, onde é possível incluir e buscar pelos seus respectivos campos. O requisitos era que fosse desenvolvido uma api com GraphQL e um front utilizando ReactJS.
## Rodando o projeto
### Pré-requisitos
Antes de começar, você vai precisar ter instalado em sua máquina as seguintes ferramentas:
[Git](https://git-scm.com) e [Docker](https://www.java.com/pt-BR/)
### Clonando o projeto
Clone o projeto
```bash
git clone https://github.com/mauriciofragajr/student-application.git
```
Vá até o diretório
```bash
cd student-application
```
Copie o arquivo .env.example e crie o seu .env
```bash
cp .env.example .env
```
Separei os ambientes em dois docker-compose. Onde o de desenvolvimento permite um recarregamento automático em toda a alteração do código, enquanto o de produção está otimizado e pronto para levar a um ambiente produtivo.
#### Executando em produção
Inicie os serviços com o docker-compose.
Rode com o o parâmetro -d para que seja executado em segundo plano, ou sem ele para ver os logs dos containers.
```bash
docker-compose up -d
```
Se tudo estiver correto o webapp estará rodando na porta 8080 do [localhost:8080](http://localhost:8080)
#### Executando em desenvolvimento
Executando o comando a seguir você levanta os containers utilizando o modo desenvolvimento. Você conseguirá os logs em tempo real conforme for alterando o código.
```bash
docker-compose -f docker-compose.development.yml up
```
Se tudo estiver correto o webapp estará rodando na porta 8080 do [localhost:8080](http://localhost:8080)
## Arquitetura
A arquitetura do software está representada na imagem a seguir

O projeto é composto por: banco de dados, api, front e proxy reverso.
##### Banco de dados
Este componente é usado para a persistência dos dados da aplicação. Foi escolhido o postgres pela sua alta performance e compatibilidade com diversas linguagens. Além da enorme quantidade de informações e documentação sobre.
##### Api
Este componente é o responsável por criar uma interface com o padrão graphQL com interoperabilidade. Utilizei o NestJS pela configuração pré-definida do typescript e configuração do ambiente para desenvolvimento. Além de ser um framework muito utilizado pela comunidade e com uma ótima documentação.
Escolhi esse framework por seguir alguns padrões de projetos bem conhecidos e de fácil customização para que não fiquemos refém dele.
Somente esse componente faz acesso ao banco de dados, deixando de forma abstraída para o front onde e como está sendo persistido os dados.
##### Front
Componente responsável pela interface gráfica onde os usuários terão acesso às funcionalidades do sistema. Para manter o padrão das escolha da linguagem, optei por iniciar o projeto com create-react-app com typescript. Nele também usei o Apollo para a integração com o backend feito com graphQL.
Foi configurado cache para as requisições idênticas no front, e isso aumenta muito a performance do sistema como um todo.
##### Proxy reverso
Implementei um simples proxy reverso para as requisições no backend utilizando o escalonamento Round-Robin. Como default estou escalando manualmente 3 vezes a API para fazer esse balanceamento de requisições. Com esse serviço é possível definir diversas configurações de acesso simultâneo, cache, entre outros.
## Testes automatizados
Para executar os testes unitários da api basta ir até a pasta
```bash
cd api
```
E executar o comando
```bash
npm run test
```
## 🛠 Tecnologias
As seguintes tecnologias foram usadas na construção do projeto:
- [Nest](https://nestjs.com/)
- [GraphQL](https://graphql.org/)
- [Apollo](https://www.apollographql.com/)
- [React](https://pt-br.reactjs.org/)
## Autor
<NAME>
[](https://www.linkedin.com/in/mauriciofragajr/)
[](mailto:<EMAIL>)<file_sep>import { CpfValidator } from './cpf-validator';
describe('CpfValidator', () => {
it('should be defined', () => {
expect(new CpfValidator()).toBeDefined();
});
describe('cleanString', () => {
test.each`
cpf | expected
${'907.205.840-27'} | ${'90720584027'}
${'505.021.630-38'} | ${'50502163038'}
${'756.160.800-47'} | ${'75616080047'}
`('should returns $expected when clean $cpf', ({cpf, expected}) => {
const cpfValidator = new CpfValidator();
expect(cpfValidator.cleanString(cpf)).toBe(expected)
});
})
describe('hasInvalidSize', () => {
test.each`
cpf | expected
${'90720584027'} | ${false}
${'50502103'} | ${true}
${'75616080047'} | ${false}
`('should returns $expected when $cpf', ({cpf, expected}) => {
const cpfValidator = new CpfValidator();
expect(cpfValidator.hasInvalidSize(cpf)).toBe(expected)
});
})
describe('haveSameNumbers', () => {
test.each`
cpf | expected
${'11111111111'} | ${true}
${'22222222222'} | ${true}
${'90720584027'} | ${false}
${'33333333333'} | ${true}
`('should returns $expected when $cpf', ({cpf, expected}) => {
const cpfValidator = new CpfValidator();
expect(cpfValidator.haveSameNumbers(cpf)).toBe(expected)
});
})
describe('validate', () => {
test.each`
cpf | expected
cpf | expected
${'133.066.247-48'} | ${true}
${'133.066.247-49'} | ${false}
${'907.205.840-27'} | ${true}
${'505.021.630-38'} | ${true}
${'756.160.800-47'} | ${true}
${'111.111.111-11'} | ${false}
`('should returns $expected when $cpf', ({cpf, expected}) => {
const cpfValidator = new CpfValidator();
expect(cpfValidator.validate(cpf)).toBe(expected)
});
})
});
<file_sep>import { Field, InputType } from "@nestjs/graphql";
import { IsEmail, IsNotEmpty, IsString, MaxLength, MinLength, Validate } from "class-validator";
import { CpfValidator } from "src/validators/cpf-validator/cpf-validator";
@InputType()
export class CreateStudentInput {
@Field()
@Validate(CpfValidator, {
message: 'CPF is not valid'
})
cpf: string;
@Field()
@IsString()
@IsNotEmpty({ message: 'Name is empty' })
@MinLength(3, { message: 'Name is too short. Minimal length is $constraint1 characters, but actual is $value' })
@MaxLength(50, { message: 'Name is too long. Maximal length is $constraint1 characters, but actual is $value' })
name: string;
@Field()
@IsEmail()
@IsNotEmpty({ message: 'Email is empty' })
email: string;
}<file_sep>import { ValidatorConstraint, ValidatorConstraintInterface } from "class-validator";
@ValidatorConstraint({name: 'IsCPF'})
export class CpfValidator implements ValidatorConstraintInterface {
validate(cpf: string) {
cpf = this.cleanString(cpf)
if (this.hasInvalidSize(cpf) || this.haveSameNumbers(cpf)) return false
const cpfArray = cpf.split('')
const validatorDigit = cpfArray
.filter((digit, index, array) => index >= array.length - 2 && digit)
.map(el => +el)
const toValidate = pop => cpfArray
.filter((digit, index, array) => index < array.length - pop && digit)
.map(el => +el)
const rest = (count, pop) => (
toValidate(pop)
.reduce((soma, el, i) => soma + el * (count - i), 0) * 10) % 11 % 10
return !(rest(10, 2) !== validatorDigit[0] || rest(11, 1) !== validatorDigit[1])
}
cleanString(cpf: string) {
return cpf.replace(/[^\d]+/g, '')
}
hasInvalidSize(cpf: string) {
return cpf.length !== 11
}
haveSameNumbers(cpf) {
return !!cpf.match(/(\d)\1{10}/)
}
}
<file_sep>import { NestjsQueryGraphQLModule, PagingStrategies } from "@nestjs-query/query-graphql";
import { NestjsQueryTypeOrmModule } from "@nestjs-query/query-typeorm";
import { Module } from "@nestjs/common";
import { CreateStudentInput } from "./dto/create-student.input";
import { StudentDTO } from "./dto/student.dto";
import { UpdateStudentInput } from "./dto/update-student.input";
import { Student } from "./entities/student.entity";
@Module({
imports: [
NestjsQueryGraphQLModule.forFeature({
imports: [NestjsQueryTypeOrmModule.forFeature([Student])],
resolvers: [
{
DTOClass: StudentDTO,
EntityClass: Student,
CreateDTOClass: CreateStudentInput,
UpdateDTOClass: UpdateStudentInput,
enableTotalCount: true,
pagingStrategy: PagingStrategies.OFFSET
}
],
})
],
providers: []
})
export class StudentModule {}<file_sep>import { ApolloClient, from, HttpLink, InMemoryCache } from '@apollo/client';
import { onError } from "@apollo/client/link/error";
const httpLink = new HttpLink({
uri: process.env.REACT_APP_GRAPHQL_URI ? `${process.env.REACT_APP_GRAPHQL_URI}/graphql` : 'http://localhost:3000/graphql'
});
const errorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors)
graphQLErrors.forEach(({ message, locations, path }) =>
console.log(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
),
);
if (networkError) console.log(`[Network error]: ${networkError}`);
});
export const client = new ApolloClient({
link: from([errorLink, httpLink]),
cache: new InMemoryCache(),
});
<file_sep>import { gql, useQuery } from "@apollo/client";
import { Student } from "../../domain/interfaces/Student";
interface OffsetPageInfo {
hasNextPage?: boolean;
hasPreviousPage?: boolean;
}
interface StudentsData {
students: {
pageInfo: OffsetPageInfo
nodes: Student[]
totalCount: number
}
}
const GET_STUDENTS = gql`
{
students {
nodes {
cpf,
name,
email
},
totalCount,
pageInfo {
hasNextPage,
hasPreviousPage
}
}
}
`
export const useGetStudents = (): any | undefined => {
const { loading, data } = useQuery<StudentsData>(GET_STUDENTS)
return { loading, data }
}<file_sep>import { gql, useMutation } from "@apollo/client";
const CREATE_STUDENT = gql`
mutation createOneStudent($input: CreateOneStudentInput!) {
createOneStudent(input: $input) {
cpf
name
email
}
}
`
export const useCreateStudent = (): any | undefined => {
const [createOneStudent, { loading, data, error }] = useMutation(CREATE_STUDENT, {
update(cache, { data: { createOneStudent } }) {
cache.modify({
fields: {
students(existingStudents = {}) {
return {
nodes: [...existingStudents.nodes, createOneStudent],
totalCount: existingStudents.totalCount + 1
};
}
}
});
}
});
return [createOneStudent, { loading, data, error }];
}
<file_sep>import { gql, useLazyQuery } from "@apollo/client";
import { Student } from "../../domain/interfaces/Student";
interface OffsetPageInfo {
hasNextPage?: boolean;
hasPreviousPage?: boolean;
}
interface StudentsData {
students: {
pageInfo?: OffsetPageInfo
nodes: Student[]
totalCount?: number
}
}
const GET_STUDENTS_FILTER = gql`
query students($filter: StudentFilter!, $paging: OffsetPaging!) {
students(filter: $filter, paging: $paging) {
nodes {
cpf
name
email
},
totalCount
}
}
`
export const useGetStudentsFilter = (): any | undefined => {
const [students, { loading, data }] = useLazyQuery<StudentsData>(GET_STUDENTS_FILTER)
return [students, { loading, data }]
} | 3424b9650750ff002b6aa28441d923d2a5b0667c | [
"Markdown",
"TypeScript",
"Shell"
] | 14 | TypeScript | mauriciofragajr/student-application | 787badc861cd48f97e912e2ce500e9694d528230 | 28ed2ccf2273ee0b79320f1bf3c0fd64227ea2d2 |
refs/heads/master | <repo_name>VitorEmanuelDev/FreeCodeCamp-Introduction-to-the-Debugging-Challenges<file_sep>/Catch Missing Open and Closing Parenthesis After a Function Call.js
let x = 6;
let y = 3;
let result = getNine();
function getNine() {
return x + y;
}
console.log(result);
/*let x = 6;
let y = 3;
let result = x+y;
function getNine() {
return getNine();
}
console.log(result); */
| 2f51cacf2fa63da16cf15146b1b377d0095a3826 | [
"JavaScript"
] | 1 | JavaScript | VitorEmanuelDev/FreeCodeCamp-Introduction-to-the-Debugging-Challenges | 6becd21bc4dc0d2a5deb5ba50b1f0824901f2038 | 9ba10846c8c7847080b549c61fe1fc69099433ed |
refs/heads/master | <file_sep># AddEditObservation
This is a proof-of-concept project I wrote years ago just after I started at JCR. At the time, one of our new subscription products was written in classic ASP.NET using custom controls (*.ascx).
The product was suffering from poor performance when it tried to reder a medical survey on-screen. If the survey had too many questions, rendering the form using dynamically-created custom controls was taking way to long. My solution was to show that an alternative approach of rending mark-up from the code-behind would allow us to deliver alot of questions in a very short response time.
Download the repository and launch the web application. Now change the URL in your browser to http://localhost:4223/AddEditObservation.aspx and this is what you should see. The project proved that sometimes you just need JavaScript and a little elbow-grease to get the job done.

<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
namespace DynamicTableCreation {
public class Observation {
public IList<Question> Questions { get; set; }
public int ID { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public Observation() {
Questions = new List<Question>();
Questions.Add(new Question { No = 1, IsRequired = true, EP = "IC.02.02.01 - 1", Text = "What types of equipment are used in this department and what is the process for cleaning that equipment?" });
Questions.Add(new Question { No = 2, IsRequired = false, EP = "IC.02.02.01 - 1", Text = "Who is responsible to clean the equipment you described?" });
Questions.Add(new Question { No = 3, IsRequired = true, EP = "EC.02.06.01 - 1", Text = "Where is patient care equipment stored?" });
Questions.Add(new Question { No = 4, IsRequired = false, EP = "IC.02.02.01 - 1", Text = "How would I know if a piece of equipment not currently in use is clean or contaminated?" });
Questions.Add(new Question { No = 5, IsRequired = true, EP = "HR.01.05.03 - 1", Text = "How did you learn about the process for cleaning patient care equipment?" });
Questions.Add(new Question { No = 6, IsRequired = false, EP = "IC.02.01.01 - 1", Text = "Does the process for cleaning patient care equipment for patients in isolation differ in any way?" });
Questions.Add(new Question { No = 7, IsRequired = true, EP = "", Text = "Is any Personal Protective Equipment (PPE) is used when cleaning equipment?" });
Questions.Add(new Question { No = 8, IsRequired = false, EP = "EC.02.01.01 - 3", Text = "Where are the supplies used to clean patient care equipment stored?" });
Questions.Add(new Question { No = 9, IsRequired = true, EP = "IC.02.02.01 - 2", Text = "Do you perform any high level disinfection in this department?" });
Questions.Add(new Question { No = 10, IsRequired = false, EP = "NPSG.07.01.01 - 1", Text = "How does this department perform relative to hand hygiene?" });
Questions.Add(new Question { No = 11, IsRequired = true, EP = "IC.02.01.01 - 8", Text = "Are you aware of any hospital acquired infections in this department?" });
Name = "Medication management Storage and Access 6/17/13";
Category = "Focused";
SetupDefaultValues();
}
private void SetupDefaultValues() {
if (ID == 0){
foreach (var ques in Questions) {
ques.Numerator = string.Empty;
ques.Denominator = "1";
ques.Compliant = "N/A";
ques.NonCompliant = "N/A";
}
}
}
}
}<file_sep>function highlightTableRow(idOfControlThatWasClicked, classToApply) {
// The checkbox in <THEAD> toggles all other checkboxs in the table and should therefore not
// trigger setting the table row to appear selected.
if (!(idOfControlThatWasClicked == 'chkToggleAll')) {
var parts = idOfControlThatWasClicked.split('.');
var rowID = 'tblRow.' + parts[1];
var row = document.getElementById(rowID);
row.className = classToApply;
}
}
function NotApplicableClicked(rowNo, isChecked) {
// IMPORTANT!!! jQuery has issues with letting you select elements with a . (period) in their ID.
// To get around this issue you have to use two backslashes before each special character. A backslash
// in a jQuery selector escapes the next character. But you need two of them because backslash is also
// the escape character for JavaScript strings. The first backslash escapes the second one, giving you
// one actual backslash in your string - which then escapes the next character for jQuery.
// See http://stackoverflow.com/questions/350292/how-do-i-get-jquery-to-select-elements-with-a-period-in-their-id
var isDisabled = false;
var numerator = '';
var denominator = '1';
if (isChecked) {
isDisabled = true;
numerator = '0';
denominator = '0';
}
$('#txtNumerator\\.' + rowNo).attr('disabled', isDisabled);
$('#txtNumerator\\.' + rowNo).val(numerator);
$('#txtDenominator\\.' + rowNo).attr('disabled', isDisabled);
$('#txtDenominator\\.' + rowNo).val(denominator);
$('#btnDetails\\.' + rowNo).attr('disabled', isDisabled);
}
function SaveObservation(isMarkAsCompleted) {
alert('Save changes to database');
alert('Perform row validation logic and set error messages where appropriate');
}
function MarkObservationAsCompleted() {
alert('perform row by row validation');
alert('Perform logic in SaveObservation(true) function.');
alert('If no errors, go somewhere.');
}
$(document).ready(function () {
// Assign number of questions in tracer to a hidden form field.
$("#NoOfQuestions").val($("#tracerQuestions >tbody > tr").length);
// 1. When user clicks checkbox, get row number & determine if they checked the box 'on' or 'off'.
// 2. Call method to disable textboxes and set compliant/non-compliant to 'N/A'.
$("input:checkbox[id*='chkNotApplicable']").click(function () {
var idParts = $(this).attr('id').split('.');
var rowAccessed = idParts[1];
var isChecked = false;
if ($(this).is(':checked')) {
isChecked = true;
}
NotApplicableClicked(rowAccessed, isChecked);
});
// When specific checkbox is clicked, check all other checkboxes in the selected table.
$('#chkToggleAll').click(function () {
var checkboxes = $('td input:checkbox[id^="chkNotApplicable"]');
var isChecked = true;
if ($(this).is(':checked')) {
checkboxes.prop('checked', 'checked');
} else {
checkboxes.prop('checked', '');
isChecked = false;
}
var rowsInTable = $("#tracerQuestions >tbody > tr").length;
for (var i = 1; i <= rowsInTable; i++) {
NotApplicableClicked(i, isChecked);
}
});
// Dynamically app or remove CSS class on table row for the hover event. This snippet excludes any
// changes to the <THEAD> row and apply the change to those rows inside the <TBODY> element.
$('#tracerQuestions > tbody > tr:not(:has(table, th))').hover(function () {
$(this).addClass('hover');
}, function () {
$(this).removeClass('hover');
});
$('#tracerQuestions > tbody > tr:not(:has(table, th))').click(function () {
$(this).removeClass('hover');
$('#tracerQuestions tr.selectedRow').removeClass('selectedRow');
$(this).addClass('selectedRow');
});
// Set class for current row whenever user clicks on a textbox or checkbox.
$("input:text").focus(function () {
// Select all text when any textbox has focus.
$(this).select();
// Find all rows that were previously selected and unselect them.
$('#tracerQuestions tr.selectedRow').removeClass('selectedRow');
highlightTableRow((this).name, 'selectedRow');
});
});<file_sep>using System;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace DynamicTableCreation {
public partial class Default : System.Web.UI.Page {
// Reference: http://msdn.microsoft.com/en-us/library/kyt0fzt1(v=vs.100).aspx
override protected void OnInit(EventArgs e) {
_StopWatch = System.Diagnostics.Stopwatch.StartNew();
CreateTable();
}
private System.Diagnostics.Stopwatch _StopWatch;
private readonly string CHK_NOT_APPLICABLE = "chkNotApplicable";
private readonly string TXT_NUMERATOR = "txtNumerator";
private readonly string TXT_DENOMINATOR = "txtDenominator";
private readonly string LBL_COMPLIANT = "lblCompliant";
private readonly string LBL_NONCOMPLIANT = "lblNonCompliant";
private readonly string BTN_DETAILS = "btnDetails";
public readonly string TABLE_ROW = "tblRow";
public readonly string TABLE_ID_DETAIL = "tbltracerQuestions";
public string TracerName = string.Empty;
public string TracerCategory = string.Empty;
public string PageTitle = string.Empty;
public string TimeToRenderPage { get; set; }
protected void Page_Load(object sender, EventArgs e) {
UpdateTimeToRenderPage();
if (!Page.IsPostBack) {
PageTitle = "Add Observation";
}
}
private void CreateTable() {
var observation = new Observation();
TracerName = observation.Name;
TracerCategory = observation.Category;
ObservationID.Value = observation.ID.ToString();
Panel1.Controls.Add(new LiteralControl(string.Format("<table id='{0}' style='width:100%;'><tr><td>", "tracerWrapper")));
CreateTableHeader();
for (int i = 0; i < observation.Questions.Count; i++) {
Question ques = observation.Questions[i];
CreateTableRow(ref ques, i+1, observation.ID);
}
CreateTableFooter();
Panel1.Controls.Add(new LiteralControl("</td></tr></table>"));
}
private void CreateTableRow(ref Question pQues, int pRowNo, int pObservationID) {
// A panel expands to a span (or a div), the Placeholder does not render any tags for itself.
// Placeholder controls are good for grouping some items without headache of out HTML tags.
// Panel controls have the styling capabilites, so you can set the cssclass or style properties
// such as background-color, forecolor etc...But Placeholder doesn't have any style attributes
// associated. You can not set cssclass or forecolor etc...
Panel1.Controls.Add(new LiteralControl(string.Format("<tr id='{0}.{1}' style='width: 100%;'>", TABLE_ROW, pRowNo)));
string clsname = "notRequired";
string charToPrint = string.Empty;
if (pQues.IsRequired) {
clsname = "required";
charToPrint = "*";
}
Panel1.Controls.Add(new LiteralControl(string.Format("<td>{0} <span id='isRequired.{1}' class='{2}'>{3}</span></td>",
pQues.No, pQues.No, clsname, charToPrint)));
Panel1.Controls.Add(new LiteralControl(string.Format("<td style='width: auto;'>{0}</td>", pQues.Text)));
Panel1.Controls.Add(new LiteralControl(string.Format("<td style='width: 110px;'>{0}</td>", pQues.EP)));
Panel1.Controls.Add(new LiteralControl("<td style='text-align:center;'>"));
Image imgCMS = new Image();
imgCMS.CssClass = "imgCMS";
imgCMS.ImageUrl = "content\\images\\cms.png";
imgCMS.Width=32;
imgCMS.Height=16;
Panel1.Controls.Add(imgCMS);
Panel1.Controls.Add(new LiteralControl("</td>"));
Panel1.Controls.Add(new LiteralControl("<td style='width: 25px;'>"));
TextBox txtNumerator = new TextBox();
txtNumerator.ID = string.Format("{0}.{1}", TXT_NUMERATOR, pQues.No);
txtNumerator.CssClass = "txtDataEntry";
txtNumerator.Width = 25;
txtNumerator.MaxLength = 3;
txtNumerator.Text = pQues.Numerator;
Panel1.Controls.Add(txtNumerator);
Panel1.Controls.Add(new LiteralControl("</td>"));
Panel1.Controls.Add(new LiteralControl("<td style='width: 25px;'>"));
TextBox txtDenominator = new TextBox();
txtDenominator.ID = string.Format("{0}.{1}", TXT_DENOMINATOR, pQues.No);
txtDenominator.CssClass = "txtDataEntry";
txtDenominator.Width = 25;
txtDenominator.MaxLength = 3;
txtDenominator.Text = pQues.Denominator;
Panel1.Controls.Add(txtDenominator);
Panel1.Controls.Add(new LiteralControl("</td>"));
Panel1.Controls.Add(new LiteralControl("<td>"));
Label lblCompliant = new Label();
lblCompliant.ID = string.Format("{0}.{1}", LBL_COMPLIANT, pQues.No);
lblCompliant.CssClass = LBL_COMPLIANT;
lblCompliant.Text = pQues.Compliant;
Panel1.Controls.Add(lblCompliant);
Panel1.Controls.Add(new LiteralControl("</td>"));
Panel1.Controls.Add(new LiteralControl("<td>"));
Label lblNonCompliant = new Label();
lblNonCompliant.ID = string.Format("{0}.{1}", LBL_NONCOMPLIANT, pQues.No);
lblNonCompliant.CssClass = LBL_NONCOMPLIANT;
lblNonCompliant.Text = pQues.NonCompliant;
Panel1.Controls.Add(lblNonCompliant);
Panel1.Controls.Add(new LiteralControl("</td>"));
Panel1.Controls.Add(new LiteralControl("<td style='text-align:center;'>"));
CheckBox chkNotApplicable = new CheckBox();
chkNotApplicable.ID = string.Format("{0}.{1}", CHK_NOT_APPLICABLE, pQues.No);
Panel1.Controls.Add(chkNotApplicable);
Panel1.Controls.Add(new LiteralControl("</td>"));
Panel1.Controls.Add(new LiteralControl("<td style='text-align:center;'>"));
Button btnDetails = new Button();
btnDetails.ID = string.Format("{0}.{1}", BTN_DETAILS, pQues.No);
btnDetails.Text = "Details";
string hrefErrorClass = string.Empty;
if (pObservationID == 0) {
btnDetails.CssClass = "btnDetailsHide";
hrefErrorClass = "hrefErrorHide";
} else {
btnDetails.CssClass = "btnDetailsShow";
hrefErrorClass = "hrefErrorShow";
}
Panel1.Controls.Add(btnDetails);
Panel1.Controls.Add(new LiteralControl("</td>"));
Panel1.Controls.Add(new LiteralControl(
string.Format("<td style='text-align:center;'><a href='#' id='hrefErr.{0}' class='{1}'>Error</td>",
pQues.No, hrefErrorClass)));
Panel1.Controls.Add(new LiteralControl("</tr>"));
}
private void CreateTableHeader() {
Panel1.Controls.Add(new LiteralControl(string.Format("<table id='{0}' style='width: 100%;'>", "tracerQuestions")));
Panel1.Controls.Add(new LiteralControl("<thead id='tracerQuestionsHeader'>"));
Panel1.Controls.Add(new LiteralControl("<td style='width: 35px;'>Q #</td>"));
Panel1.Controls.Add(new LiteralControl("<td style='width: auto; text-align:center;'>Question Text</td>"));
Panel1.Controls.Add(new LiteralControl("<td style='width: 142px; text-align:center;' colspan='2'>Standard - EP</td>"));
Panel1.Controls.Add(new LiteralControl("<td style='width: 30px; text-align:center;'>Num.</td>"));
Panel1.Controls.Add(new LiteralControl("<td style='width: 30px; text-align:center;'>Den.</td>"));
Panel1.Controls.Add(new LiteralControl("<td style='width: 30px; text-align:center;'>Cmp.</td>"));
Panel1.Controls.Add(new LiteralControl("<td style='width: 40px; text-align:center;'>N Cmp.</td>"));
Panel1.Controls.Add(new LiteralControl("<td style='width: 20px; text-align:center;'>N/A</br>"));
CheckBox chkToggleAll = new CheckBox();
chkToggleAll.ID = "chkToggleAll";
Panel1.Controls.Add(chkToggleAll);
Panel1.Controls.Add(new LiteralControl("</td>"));
Panel1.Controls.Add(new LiteralControl("<td style='width: 60px; text-align:center;'>Details</td>"));
Panel1.Controls.Add(new LiteralControl("<td style='width: 50px; text-align:center;'>Error ?</td>"));
Panel1.Controls.Add(new LiteralControl("</thead>"));
Panel1.Controls.Add(new LiteralControl("<tbody>"));
}
private void CreateTableFooter() {
Panel1.Controls.Add(new LiteralControl("</tbody>"));
Panel1.Controls.Add(new LiteralControl("</table>"));
}
protected void btnSave_Click(object sender, EventArgs e) {
System.Collections.Specialized.NameValueCollection postedValues = Request.Form;
int noOfQuestions = Convert.ToInt32(NoOfQuestions.Value);
if (ObservationID.Value == "0") {
// TODO Save Observation to DB. Assign the Observation ID to the hidden form field.
ObservationID.Value = "5";
// When observation is F-I-R-S-T saved, set CSS class so all detail buttons are displayed.
PageTitle = "Edit Observation";
for (int i = 0; i < noOfQuestions; i++) {
string keyDetails = string.Format("{0}.{1}", BTN_DETAILS, i + 1);
Button btnDetails = (Button)FindControl(keyDetails);
btnDetails.CssClass = "btnDetailsShow";
}
} else {
// TODO Update data entry into DB.
}
for (int i = 0; i < noOfQuestions; i++) {
string keyNumerator = string.Format("{0}.{1}", TXT_NUMERATOR, i+1);
string keyDemominator = string.Format("{0}.{1}", TXT_DENOMINATOR, i+1);
string keyIsApplicable = string.Format("{0}.{1}", CHK_NOT_APPLICABLE, i+1);
int numerator = 0;
int denominator = 0;
bool isNumeratorNumeric = true;
bool isDenominatorNumeric = true;
string isApplicable = "off";
isNumeratorNumeric = int.TryParse(Request.Form[keyNumerator].ToString(), out numerator);
isDenominatorNumeric = int.TryParse(Request.Form[keyDemominator].ToString(), out denominator);
// Interesting Find: If a checkbox is --NOT-- checked on, ASP.NET will not return the checkbox
// in the Request.Form NameValueCollection.
if (postedValues[keyIsApplicable] != null) {
isApplicable=Request.Form[keyIsApplicable].ToString();
}
// Echo output to verify we can access data.
// System.Diagnostics.Debug.WriteLine("Ques: {0:D2} Is Applicable: {1} Numerator: {2} Denonimator: {3}",
// i+1, isApplicable, numerator, denominator);
// Increment values in table to prove we can access the data.
//if (isApplicable == "on") {
// int newValue = 0;
// TextBox ctlNumerator = (TextBox)FindControl(keyNumerator);
// if (!string.IsNullOrEmpty(ctlNumerator.Text)){
// newValue = Convert.ToInt32(ctlNumerator.Text) + 1;
// ctlNumerator.Text = newValue.ToString();
// }
// TextBox ctlDenominator = (TextBox)FindControl(keyDemominator);
// if (!string.IsNullOrEmpty(ctlDenominator.Text)) {
// newValue = Convert.ToInt32(ctlDenominator.Text) + 2;
// ctlDenominator.Text = newValue.ToString();
// }
//}
}
UpdateTimeToRenderPage();
}
protected void btnMarkAsCompleted_Click(object sender, EventArgs e) {
System.Collections.Specialized.NameValueCollection postedValues = Request.Form;
int noOfQuestions = Convert.ToInt32(NoOfQuestions.Value);
for (int i = 0; i < noOfQuestions; i++) {
string keyNumerator = string.Format("{0}.{1}", TXT_NUMERATOR, i + 1);
string keyDemominator = string.Format("{0}.{1}", TXT_DENOMINATOR, i + 1);
string keyIsApplicable = string.Format("{0}.{1}", CHK_NOT_APPLICABLE, i + 1);
int numerator = 0;
int denominator = 0;
bool isNumeratorNumeric = true;
bool isDenominatorNumeric = true;
string isApplicable = "off";
isNumeratorNumeric = int.TryParse(Request.Form[keyNumerator].ToString(), out numerator);
isDenominatorNumeric = int.TryParse(Request.Form[keyDemominator].ToString(), out denominator);
// Interesting Find: If a checkbox is --NOT-- checked on, ASP.NET will not return the checkbox
// in the Request.Form NameValueCollection.
if (postedValues[keyIsApplicable] != null) {
isApplicable = Request.Form[keyIsApplicable].ToString();
}
// Echo output to verify we can access data.
// System.Diagnostics.Debug.WriteLine("Ques: {0:D2} Is Applicable: {1} Numerator: {2} Denonimator: {3}",
// i+1, isApplicable, numerator, denominator);
// Increment values in table to prove we can access the data.
//if (isApplicable == "on") {
// int newValue = 0;
// TextBox ctlNumerator = (TextBox)FindControl(keyNumerator);
// if (!string.IsNullOrEmpty(ctlNumerator.Text)){
// newValue = Convert.ToInt32(ctlNumerator.Text) + 1;
// ctlNumerator.Text = newValue.ToString();
// }
// TextBox ctlDenominator = (TextBox)FindControl(keyDemominator);
// if (!string.IsNullOrEmpty(ctlDenominator.Text)) {
// newValue = Convert.ToInt32(ctlDenominator.Text) + 2;
// ctlDenominator.Text = newValue.ToString();
// }
//}
}
UpdateTimeToRenderPage();
}
private void UpdateTimeToRenderPage() {
long ms = _StopWatch.ElapsedMilliseconds;
TimeToRenderPage = string.Format("{0} milliseconds.", ms);
}
}
}<file_sep>using System;
using System.Linq;
namespace DynamicTableCreation {
public class Question {
public int No { get; set; }
public string Text { get; set; }
public string EP { get; set; }
public bool IsRequired { get; set; }
public bool IsNotApplicable { get; set; }
public string Numerator { get; set; }
public string Denominator { get; set; }
public string Compliant { get; set; }
public string NonCompliant { get; set; }
}
} | b846a02129ef78479e83eb06ee6708a831527f02 | [
"Markdown",
"C#",
"JavaScript"
] | 5 | Markdown | mark-orlando/AddEditObservation | b60178554936d39bbd65cb78ee469b5eda7ef314 | 463ebb204d32a2dc9e39ef203e243cbe46318984 |
refs/heads/master | <repo_name>Michel-hub/ruby_arreglos<file_sep>/sumando_matrices.rb
m1 = [[3, 2],[1, 4]]
m2 = [[3, 2],[1, 4]]
result = []
cols = m1.length
rows = m1[0].length
cols.times do |i|
rows.times do |j|
print (m1[i][j] + m2[i][j]).to_s + " "
end
print "\n"
end<file_sep>/transformar.rb
n = ARGV.count
array = []
n.times do |i|
array.push ARGV[i].to_i
end
print "#{array}\n"<file_sep>/ventas_totales.rb
v1 = [100, 20, 50, 70, 90]
v2 = [150, 30, 50, 20, 30]
vt = [] # Ventas totales
n = v1.count
n.times do |i|
vt.push v1[i] + v2[i]
end
print "#{vt}\n"
<file_sep>/dentroarreglo.rb
array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
array.each do |array_int|
array_int.each do |ele|
puts ele
end
end
array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
n = array.count
n.times do |i|
n.times do |j|
print "\t#{array[i][j]}"
end
puts
end
array = [[1, 2, 3], [4, 5, 6, 91], [7, 8, 9, 10]]
n = array.count
n.times do |i|
n.times do |j|
print "\t#{array[j][i]}"
end
puts
end
array = [[1, 2, 3], [4, 5, 6, 91], [7, 8, 9, 10]]
n_exterior = array.count
n_exterior.times do |i|
n_interior = array[i].count
n_interior.times do |j|
print "\t#{array[i][j]}"
end
puts
end<file_sep>/buscar_nombre.rb
notas = [5, 9, 6, 8, 9]
alumnos = ['Juliana', 'Francisca', 'Pedro', 'Diego', 'Macarena']
nombre_a_buscar = ARGV[0].chomp
indice = alumnos.index(nombre_a_buscar)
if indice
puts "la nota es: #{notas[indice]}"
else
puts "No se encontró a #{nombre_a_buscar}"
end<file_sep>/prueba3.rb
nombres = ['Alumno1', 'Alumno2', 'Alumno3']
notas = [10, 3, 8]
hash = {}
nombres.count.times do |i|
element = nombres[i]
nota = notas[i]
hash[element] = nota
end
print hash
nombres = ['Alumno1', 'Alumno2', 'Alumno3']
notas = [10, 3, 8]
hash = {}
nombres.each do |nombre|
i = nombres.index(nombre) # obtenemos el índice
nota = notas[i]
hash[nombre] = nota
end
print hash
nombres = ['Alumno1', 'Alumno2', 'Alumno3']
notas = [10, 3, 8]
nombres.zip(notas).to_h # {"Alumno1"=>10, "Alumno2"=>3, "Alumno3"=>8}
<file_sep>/filtro.rb
a =[100, 200, 1000, 5000, 10000, 10, 5000]
n = a.count
filtered_array = [] # creacion de arreglo vacio
n.times do |i|
if a[i] >= 1000
filtered_array.push a[i] # agrega nuevos elementos al arreglo
puts a[i]
end
end
print "#{filtered_array} \n" # imprime el nuevo arreglo con los elementos
<file_sep>/prueba.rb
a = [100, 200, 1000, 5000]
sum = 0
3.times do |i|
sum += i
puts sum
end<file_sep>/prueba4.rb
array = [1, 2, 6, 7, 2, 5, 8, 9, 1, 3, 6, 7]
hash = {}
array.each do |i|
if hash[i]
hash[i] += 1
else
hash[i] = 1
end
end
puts hash<file_sep>/ingredientes_2.rb
ingrediente = ARGV[0]
ingredientes_pizza = ['piña', 'jamon', 'salsa', 'queso']
if ingredientes_pizza.include?(ingrediente)
puts 'Existe'
else
ingredientes_pizza.push(ingrediente)
puts 'No existe'
puts 'Sera agregado'
end
puts ingredientes_pizza<file_sep>/prueba2.rb
def modulo(array)
n = array.count
suma = 0
n.times do |i|
suma = suma + array[i]**2
end
Math.sqrt(suma)
end
modulo([1,2,3])<file_sep>/finalhash/example1.rb
data = request('https://jsonplaceholder.typicode.com/photos')[0..10] # Limitamos los resultados a 10
photos = data.map{|x| x['url']}
html = ""
photos.each do |photo|
html += "<img src=\"#{photo}\">\n"
end
File.write('output.html', html)<file_sep>/matrices.rb
m = [[3, 2],[1, 4]]
m.each do |row|
row.each do |ele|
print "\t#{ele}"
end
print "\n"
end
def show(matrix)
matrix.each do |row|
row.each do |ele|
print "\t#{ele}"
end
print "\n"
end
end
show(m)<file_sep>/incrementar.rb
a =[5, 6, 7, 8, 9]
n = a.count
i = 0
while i < n
puts a[i]
i += 1 # Tenemos que recordar incrementar el indice en cada iteracion
end
<file_sep>/unir_hash.rb
a = {k1: 5, k2: 10}
b = {k3: 15, k4: 20}
a.merge(b)
print a.merge(b)<file_sep>/venta_meses.rb
ventas = {
Octubre: 65000,
Noviembre: 68000,
Diciembre: 72000
}
ventas.each do |k,v|
ventas[k] *= 1.1
end
puts ventas
ventas1 = {
Octubre: 65000,
Noviembre: 68000,
Diciembre: 72000
}
nuevo_ventas = {}
ventas1.each do |k,v|
nuevo_ventas[k] = v * 0.8
end
puts nuevo_ventas
<file_sep>/mapa.rb
variables = [120, 50, 600, 30, 90, 10, 200, 0, 500]
b = variables.map {|e| e * 0}
print "#{b}\n"
<file_sep>/adictos_a_redes.rb
variables = [120, 50, 600, 30, 90, 10, 200, 0, 500]
# => ["mal", "bien", "mal", "bien", "bien", "bien", "mal", "b
def scan_addicts(arr)
scan_array = []
arr.each do |i|
if i <= 90
# puts "bien"
scan_array << "bien"
# puts i
else
# puts "mal"
scan_array << "mal"
# puts i
end
end
puts "#{scan_array}\n"
end
scan_addicts(variables)
| 161eb8413cc7e75ce3b59cd119d34bbe8976a916 | [
"Ruby"
] | 18 | Ruby | Michel-hub/ruby_arreglos | ec9b1bec31558cc894fd882a9c362fb9fff3baf3 | da334d889afd418f933c1ef4d123671fbb8d1c05 |
refs/heads/master | <file_sep>export const StepsKey = {
DataCleaning: {
name: 'Data cleaning',
type: 'DataCleanStep'
},
FeatureGeneration: {
name: 'Feature generation',
type: 'FeatureGenerationStep'
},
CollinearityDetection: {
name: 'Collinearity detection',
type: 'MulticollinearityDetectStep'
},
DriftDetection: {
name: 'Drift detection',
type: 'DriftDetectStep'
},
SpaceSearch: {
name: 'Pipeline optimization',
type: 'SpaceSearchStep',
key: 'space_searching'
},
FeatureSelection: {
name: 'Feature selection',
type: 'FeatureImportanceSelectionStep'
// drift_detection
},
PsudoLabeling: {
name: 'Psudo labeling',
type: 'PseudoLabelStep'
},
PermutationImportanceSelection: {
name: 'Permutation importance selection',
type: 'PermutationImportanceSelectionStep'
},
TwoStageSpaceSearch: {
name: 'Two-stage pipeline optimization',
type: 'SpaceSearchStep',
key: 'two_stage_searching'
},
FinalTrain: {
name: 'Final train',
type: 'FinalTrainStep'
},
Ensemble: {
name: 'Ensemble',
type: 'EnsembleStep'
}
};
export function getStepName(stepType) {
const keys = Object.keys(StepsKey);
for (let i = 0; i < keys.length; i++) {
const k = keys[i];
const v = StepsKey[k];
if(v.type === stepType){
return v.name;
}
}
return null;
}
export const StepStatus = {
Wait: 'wait',
Process: 'process',
Finish: 'finish',
Error: 'error'
};
export const ActionType = {
EarlyStopped: 'earlyStopped',
StepFinished: 'stepFinished',
StepBegin: 'stepBegin',
StepError: 'stepError',
TrialFinished: 'trialFinished',
ProbaDensityLabelChange: 'probaDensityLabelChange',
ExperimentData: 'experimentData'
};
export const MAX_FEATURES_OF_IMPORTANCES = 10;
<file_sep>import {Card, Col, Form, Row, Switch, Table, Tabs, Tooltip, Select, Tag} from "antd";
import React, { PureComponent } from 'react';
import { Empty } from 'antd';
import EchartsCore from './echartsCore';
import {showNotification} from "../util";
import {formatFloat, isEmpty} from "../util";
import {StepStatus} from "../constants";
const { TabPane } = Tabs;
const CONFIGURATION_CARD_TITLE = "Configuration";
export class Line extends PureComponent {
getOption = (min, max) => {
return {
parallelAxis: [],
series: [{
type: 'parallel',
lineStyle: {
width: 2
},
data: [],
}],
visualMap: {
min: min,
max: max,
left: 0,
precision: 4,
calculable: true,
orient: 'vertical',
bottom: '15%',
hoverLink:true,
},
};
};
render() {
const { style, className, data, xAxisProp, seriesData, loading, ...restProp } = this.props;
if (!data || !data.hasOwnProperty('data')) {
return (<Empty />);
}
const rewards = [];
for (var item of data.data){
rewards.push(item.reward);
}
const options = this.getOption(Math.min(...rewards), Math.max(...rewards));
data.param_names.forEach((name, index) => {
options.parallelAxis.push({
dim: index,
name
});
});
data.data.forEach((item, index) => {
options['series']['data'] = new Array(data.param_names.length);
options['series'][0]['data'][index] = item.params;
});
return (
<EchartsCore
// loadingOption={{ color: '#1976d2' }}
option={ {...options} }
// showLoading={loading}
// style={style}
// className={className}
/>
);
}
}
export function ConfigurationCard({configurationData}) {
return <Form
labelCol={{ span: 10 }}
wrapperCol={{ span: 3 }}
layout="horizontal">
{
Object.keys(configurationData).map(key => {
const v = configurationData[key];
let content;
if (v === undefined || v === null){
content = <span>None</span>
} else if((typeof v) === "boolean"){
content = <Switch checked />
} else if(v instanceof Array){
content = <span>{ v.join(",") }</span>
} else {
content = <span>{v}</span>
}
return <Form.Item label={key} key={key}>
<span>{content}</span>
</Form.Item>
})
}
</Form>
}
export function DataCleaningStep({stepData}) {
var removedFeaturesDataSource = null;
if(stepData.status === StepStatus.Finish){
const unselectedFeatures = stepData.extension.unselected_reason;
if(!isEmpty(unselectedFeatures)){
removedFeaturesDataSource = Object.keys(unselectedFeatures).map((value, index, arr) => {
return {
key: index,
feature_name: value,
reason: unselectedFeatures[value]
}
});
}
}
const removedFeaturesColumns = [
{
title: 'Feature name',
dataIndex: 'feature_name',
key: 'feature_name',
},
{
title: 'Reason',
dataIndex: 'reason',
key: 'reason',
}
];
return <Row gutter={[4, 4]}>
<Col span={10} >
<Card title={CONFIGURATION_CARD_TITLE} bordered={false} style={{ width: '100%' }}>
{
<ConfigurationCard configurationData={stepData.configuration.data_cleaner_args}/>
}
</Card>
</Col>
<Col span={10} offset={2} >
<Card title="Removed features" bordered={false} style={{ width: '100%' }}>
<Table dataSource={removedFeaturesDataSource} columns={removedFeaturesColumns} />
</Card>
</Col>
</Row>
}
export function FeatureGenerationStep({stepData}){
let dataSource;
if(stepData.status === StepStatus.Finish){
dataSource = stepData.extension.outputFeatures.map((value, index, arr) => {
return {
key: index,
name: value.name,
parentFeatures: value.parentFeatures !== null ? value.parentFeatures.join(",") : "-",
primitive: value.primitive
}
});
}else{
dataSource = null;
}
const columns = [
{
title: 'Feature',
dataIndex: 'name',
key: 'name'
}, {
title: 'Source features',
dataIndex: 'parentFeatures',
key: 'parentFeatures',
},{
title: 'Primitive',
dataIndex: 'primitive',
key: 'primitive',
render: function (text, record, index) {
if(text !== null && text !== undefined){
return <Tag color="#108ee9">{text}</Tag>;
}else{
return '-';
}
}
}
];
return <Row gutter={[2, 2]}>
<Col span={10} >
<Card title={CONFIGURATION_CARD_TITLE} bordered={false} style={{ width: '100%' }}>
{
<ConfigurationCard configurationData={stepData.configuration}/>
}
</Card>
</Col>
<Col span={10} offset={2} >
<Card title="Importances" bordered={false} style={{ width: '100%' }}>
<Table dataSource={dataSource} columns={columns} pagination={ {defaultPageSize: 5, disabled: false, pageSize: 5}} />
</Card>
</Col>
</Row>
}
export function CollinearityDetectionStep({stepData}){
let dataSource;
if(stepData.status === StepStatus.Finish){
dataSource = stepData.extension.unselected_features?.map((value, index, arr) => {
return {
key: index,
removed: value.removed,
reserved: value.reserved,
}
});
}else{
dataSource = null;
}
const columns = [
{
title: 'Removed',
dataIndex: 'removed',
key: 'removed',
},
{
title: 'Reserved',
dataIndex: 'reserved',
key: 'reserved',
}
];
return <Row gutter={[4, 4]}>
<Col span={10} >
<Card title={CONFIGURATION_CARD_TITLE} bordered={false} style={{ width: '100%' }}>
{
<ConfigurationCard configurationData={stepData.configuration}/>
}
</Card>
</Col>
<Col span={10} offset={2} >
<Card title="Removed features" bordered={false} style={{ width: '100%' }}>
<Table dataSource={dataSource} columns={columns} />
</Card>
</Col>
</Row>
}
export function DriftDetectionStep({stepData}){
let driftFeatureAUCDataSource;
if(stepData.status === StepStatus.Finish){
driftFeatureAUCDataSource = stepData.extension.drifted_features_auc?.map((value, index, arr) => {
return {
key: index,
feature: value.feature,
score: formatFloat(value.score),
}
});
}else{
driftFeatureAUCDataSource = null;
}
const driftFeatureAUCColumns = [
{
title: 'Feature',
dataIndex: 'feature',
key: 'feature',
},
{
title: 'AUC',
dataIndex: 'score',
key: 'score',
}
];
const removedFeaturesInEpochColumns = [
{
title: 'Feature',
dataIndex: 'feature',
key: 'feature',
},
{
title: 'Importance',
dataIndex: 'importance',
key: 'importance',
}
];
return <><Row gutter={[4, 4]}>
<Col span={10} >
<Card title={CONFIGURATION_CARD_TITLE} bordered={false} style={{ width: '100%' }}>
{
<ConfigurationCard configurationData={stepData.configuration}/>
}
</Card>
</Col>
<Col span={10} offset={2} >
<Card title="Removed features in epochs" bordered={false} style={{ width: '100%' }}>
<Tabs defaultActiveKey="1" tabPosition={'top'} style={{ height: '100%', width: '100%'}}>
{
stepData.extension.removed_features_in_epochs?.map(epoch => {
return <TabPane tab={`Epoch ${epoch.epoch}`} key={epoch.epoch}>
<Table dataSource={epoch.removed_features?.map((value, index, arr) => {
return {
key: index,
feature: value.feature,
importance: formatFloat(value.importance),
}
})} columns={removedFeaturesInEpochColumns} />
</TabPane>
})
}
</Tabs>
</Card>
</Col>
</Row>
<Row gutter={[4, 4]}>
<Col span={10} offset={12} >
<Card title="Drifted features AUC" bordered={false} style={{ width: '100%' }}>
<Table dataSource={driftFeatureAUCDataSource} columns={driftFeatureAUCColumns} />
</Card>
</Col>
</Row>
</>
}
export function GeneralImportanceSelectionStep({stepData}){
let dataSource;
if(stepData.status === StepStatus.Finish){
dataSource = stepData.extension.importances?.map((value, index, arr) => {
return {
key: index,
featureName: value.name,
importance: formatFloat(value.importance),
dropped: value.dropped
}
});
}else{
dataSource = null;
}
const columns = [
{
title: 'Feature',
dataIndex: 'featureName',
key: 'featureName',
ellipsis: {
showTitle: false,
},
render: function (text, record, index) {
return <Tooltip placement="topLeft" title={text}>
{text}
</Tooltip>
}
}, {
title: 'Importance',
dataIndex: 'importance',
key: 'importance',
},{
title: 'Status',
dataIndex: 'dropped',
key: 'dropped',
render: function(text, record, index) {
if(record.dropped){
return <Tag color="red">Unselected</Tag>
}else{
return <Tag color="green">Selected</Tag>
}
}
}
];
return <Row gutter={[2, 2]}>
<Col span={10} >
<Card title={CONFIGURATION_CARD_TITLE} bordered={false} style={{ width: '100%' }}>
{
<ConfigurationCard configurationData={stepData.configuration}/>
}
</Card>
</Col>
<Col span={10} offset={2} >
<Card title="Importances" bordered={false} style={{ width: '100%' }}>
<Table dataSource={dataSource} columns={columns} pagination={ {defaultPageSize: 5, disabled: false, pageSize: 5}} />
</Card>
</Col>
</Row>
}
export function PseudoLabelStep({stepData, dispatch}) {
const getProbaDensityEchartOpts = (labelName) => {
const seriesData = [];
if(!isEmpty(labelName)){
const probabilityDensityLabelData = probabilityDensity[labelName];
const gaussianData = probabilityDensityLabelData['gaussian'];
for(var i = 0 ;i < gaussianData['X'].length; i++){
seriesData.push([gaussianData['X'][i], gaussianData['probaDensity'][i]])
}
}
return {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
}
},
xAxis: {
type: 'category',
boundaryGap: false
},
yAxis: {
type: 'value',
boundaryGap: [0, '30%']
},
series: [
{
type: 'line',
smooth: 0.6,
symbol: 'none',
lineStyle: {
color: '#5470C6',
width: 3
},
areaStyle: {},
data: seriesData
}
]
};
};
const probabilityDensity = stepData.extension.probabilityDensity;
const labels = isEmpty(probabilityDensity) ? null : Object.keys(probabilityDensity);
let selectedLabel;
if(stepData.status === StepStatus.Finish){
if(labels === null || labels.length < 2){
showNotification("Pseudo step is success but labels is empty");
return ;
}
selectedLabel = stepData.extension.selectedLabel;
}else{
selectedLabel = null;
}
const probaDensityChartOption = getProbaDensityEchartOpts(selectedLabel);
const onLabelChanged = (value) => {
dispatch(
{
type: 'probaDensityLabelChange',
payload: {
stepIndex: stepData.index,
selectedLabel: value
}
}
)
};
if (!isEmpty(labels)){
if(labels.length < 2){
console.error("labels should not < 2");
}
}
const defaultLabel = isEmpty(labels) ? "None" : labels[0];
const samplesObj = stepData.extension.samples;
const samplesDataSource = isEmpty(samplesObj) ? null : Object.keys(samplesObj).map((value,index, array) => {
return {
key: index,
label: value,
count: samplesObj[value]
}
});
const samplesColumns = [
{
title: 'Label',
dataIndex: 'label',
key: 'Label',
},
{
title: 'Count',
dataIndex: 'count',
key: 'Count',
}
];
const { Option } = Select;
return <>
<Row gutter={[4, 4]}>
<Col span={10} >
<Card title={CONFIGURATION_CARD_TITLE} bordered={false} style={{ width: '100%' }}>
{
<ConfigurationCard configurationData={stepData.configuration}/>
}
</Card>
</Col>
<Col span={10} offset={2} >
<Card title="Density Plot of Probability" bordered={false} style={{ width: '100%' }}>
<span>
<span style={{marginLeft: '20px'}}>Select label: </span>
<Select defaultValue={ selectedLabel } value={selectedLabel} style={{ width: 280 }} onChange={onLabelChanged} disabled={ isEmpty(labels)} >
{
isEmpty(labels) ? null: labels.map( v => {
return <Option value={v}>{v}</Option>
})
}
</Select>
</span>
<EchartsCore option={probaDensityChartOption}/>
</Card>
</Col>
</Row>
<Row gutter={[4, 4]}>
<Col span={10} offset={12} >
<Card title="Number of samples" bordered={false} style={{ width: '100%' }} >
<Table dataSource={samplesDataSource} columns = {samplesColumns} pagination={false} />
</Card>
</Col>
</Row>
</>
}
export function EnsembleStep({stepData}) {
let scores;
let weights;
if(stepData.status === StepStatus.Finish){
scores = stepData.extension.scores;
scores = scores === null ? [] : scores;
weights = stepData.extension.weights;
weights = weights === null ? [] : weights;
}else{
scores = null;
weights = null;
}
const getLiftEchartOpts = () => {
const yLabels = scores !== null && scores !== undefined ? Array.from({length:scores.length}, (v,k) => k) : [];
return {
xAxis: {
type: 'category',
data: yLabels
},
yAxis: {
type: 'value'
},
series: [{
data: scores,
type: 'line',
smooth: true
}]
};
};
const getWeightsEchartOpts = () => {
const yLabels = weights !== null && weights !== undefined ? Array.from({length:weights.length}, (v,k) => k) : [];
return {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
}
},
legend: {
data: []
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: {
type: 'value',
boundaryGap: [0, 0.01]
},
yAxis: {
type: 'category',
data: yLabels
},
series: [
{
name: 'weight',
type: 'bar',
data: weights
}
]
}
};
return <>
<Row gutter={[4, 4]}>
<Col span={10} >
<Card title={CONFIGURATION_CARD_TITLE} bordered={false} style={{ width: '100%' }}>
{
<ConfigurationCard configurationData={stepData.configuration}/>
}
</Card>
</Col>
<Col span={10} offset={2} >
<Card title="Weight" bordered={false} style={{ width: '100%' }}>
<EchartsCore option={getWeightsEchartOpts()}/>
</Card>
</Col>
</Row>
<Row gutter={[4, 4]}>
<Col span={10} offset={12} >
<Card title="Lifting" bordered={false} style={{ width: '100%' }}>
<EchartsCore option={getLiftEchartOpts()}/>
</Card>
</Col>
</Row>
</>
}
export function FinalTrainStep({stepData}) {
return <>
<Row gutter={[4, 4]}>
<Col span={10} >
<Card title={CONFIGURATION_CARD_TITLE} bordered={false} style={{ width: '100%' }}>
{
<ConfigurationCard configurationData={stepData.configuration}/>
}
</Card>
</Col>
<Col span={10} offset={2} >
<Card title="Estimator" bordered={false} style={{ width: '100%' }}>
{
<ConfigurationCard configurationData={stepData.extension}/>
}
</Card>
</Col>
</Row>
</>
}
<file_sep>from hypernets.conf import configure, Configurable, Int, String, Enum
@configure()
class TabularCfg(Configurable):
joblib_njobs = \
Int(-1, allow_none=True,
help='"n_jobs" setting for joblib task.'
).tag(config=True)
permutation_importance_sample_limit = \
Int(10000, min=100,
help='maximum number to run permutation importance.'
).tag(config=True)
cache_strategy = \
Enum(['data', 'transform', 'disabled'],
default_value='transform',
config=True,
help='dispatcher backend',
)
cache_dir = \
String('cache_dir',
allow_none=False,
config=True,
help='the directory to store cached data, read/write permissions are required.')
geohash_precision = \
Int(12, min=2,
config=True,
help=''
)
tfidf_max_feature_count = \
Int(100, min=2,
config=True,
help=''
)
tfidf_primitive_output_feature_count = \
Int(3, min=2,
config=True,
help=''
)
| 9021013f0b6c16767245401326dbbf0209c6d125 | [
"JavaScript",
"Python"
] | 3 | JavaScript | yukingx/Hypernets | 790e267cffabb86a0a749cece3f7d78abdffb4fa | d8847dd65f9ef026a7abb798e62a1b6bedb1b09e |
refs/heads/master | <repo_name>jacqieyuen/pick_up_with_no_lines<file_sep>/models/inventory.js
var mongoose = require('mongoose');
var inventorySchema = new mongoose.Schema({
title : {type: String, require: true},
description : {type: String, require: true},
price : {type: Number, require: true},
category : {type: String, require: true},
imagePath : {type: String, require: true},
});
var Inventory = mongoose.model('Inventory', inventorySchema);
module.exports = Inventory;
<file_sep>/routes/routes.js
const Inventory = require('../models/inventory');
const User = require('../models/user');
module.exports = function(app, passport){
// Menu Data
function findInventoryDatabase(req, res, next) {
Inventory.find(function(err, items){
if(err){
res.send(err);
};
// var itemChunks = [];
// var chunkSize = 3;
// for(var i = 0; i < items.length; i += chunkSize){
// itemChunks.push(items.slice(i, i + chunkSize));
// };
req.inventory = items;
next();
});
};
function distinctInventoryCategory(req, res, next){
Inventory.distinct('category', function(err, items){
if(err){
res.send(err);
};
req.category = items;
next()
});
};
function renderMenu(req, res){
res.render('shop/menu', {
inventory: req.inventory,
category: req.category
});
};
app.get('/menu', findInventoryDatabase, distinctInventoryCategory, renderMenu);
// Do Not Delete This Curly Bracket.
// It Is The Closing Bracket Of Module.Exports Function
};
////////////////////////////
<file_sep>/README.md
* Create a mobile responsive website.
* Using Simply Life as this project's example.
* Users will be able to pre-order their food.
1. Pre-order with or without an account.
2. Pay online only.
3. QR code verfication.
* Database.
1. Users.
2. Menu Items.
3. QR codes.
| c5108495801f70e17b2ef8b3cb586b940be797c6 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | jacqieyuen/pick_up_with_no_lines | b5242f927d94cd3cca1aecfc4e467f807b11dcd7 | 93986630dd772b43cd447bd6508fc86e37a8a36b |
refs/heads/master | <repo_name>whjames007/wxxcx-code-006<file_sep>/pages/home/home.js
// pages/home/home.js
const app = getApp()
const log = "【home页面】"
Page({
/**
* 页面的初始数据
*/
data: {
userInfo: {},
imgUrls: [
'https://6a61-james-song-001-cloud-7ff873-1257949111.tcb.qcloud.la/bluewater03.jpg?sign=3f35f1b7d9892f28c871fc4a1bba0e78&t=1541465603',
'https://6a61-james-song-001-cloud-7ff873-1257949111.tcb.qcloud.la/bluewater04.jpg?sign=613dff5685f144b4fda851905f7f6657&t=1541465634',
'https://6a61-james-song-001-cloud-7ff873-1257949111.tcb.qcloud.la/bluewater05.jpg?sign=b8f3746b67344c382f81545171f89952&t=1541465650',
'https://6a61-james-song-001-cloud-7ff873-1257949111.tcb.qcloud.la/bluewater01.jpg?sign=020e5e30c792b9840940316317f956bb&t=1541465524',
'https://6a61-james-song-001-cloud-7ff873-1257949111.tcb.qcloud.la/bluewater02.jpg?sign=21370482822b922c9cd89a0779661eec&t=1541465556'
],
indicatorDots: true,
autoplay: true,
interval: 5000,
duration: 1000
},
bindtapOpenAccount: function() {
let name = "【bindtapOpenAccount】"
console.info(log, name, '【开户方法】')
wx.navigateTo({
url: './openAccount/openAccount'
})
// wx.switchTab({
// url: '/pages/home/home'
// })
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function(options) {
let name = "【onLoad】"
app.userInfoReadyCallback2 = res => {
this.setData({
userInfo: res.userInfo,
authStatus: true
})
console.info(log, name, '【userInfoReadyCallback2回调后,本地就有了用户信息】', res.userInfo)
}
app.methodGotoIndex2()
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function() {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function() {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function() {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function() {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function() {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function() {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function() {
}
})<file_sep>/pages/home/openAccount/openAccount.js
// pages/home/openAccount/openAccount.js
const app = getApp()
const log = "【openAccount页面】"
const utilSArea = require('../../../utils/area.js')
import Notify from '../../../vant/notify/notify';
import Toast from '../../../vant/toast/toast';
Page({
/**
* 页面的初始数据
* "420000", provinceName: "湖北省", cityCode: "420100", cityName: "武汉市"
*/
data: {
accountName: null,
provinceCode: '420000',
provinceName: '湖北省',
cityCode: '420100',
cityName: '武汉市',
areaValue: '420100',
areaList: null
},
bindChangeName: function(event) {
this.setData({
accountName: event.detail
})
},
bindconfirmArea: function(val) {
let name = "【选定行政区域】"
let list = val.detail.values
this.setData({
provinceCode: list[0].code,
provinceName: list[0].name,
cityCode: list[1].code,
cityName: list[1].name
})
console.info(log, name, list)
},
bindSubmmit: function(event) {
let name = "【提交表单】"
console.info(log, name, this.data)
Toast.success({
mask: true,
forbidClick: true,
message: '提交成功,请等待管理员审核!',
onClose: function () {
wx.switchTab({
url: '../home'
})
console.info(log, name, 111)
}
});
const {
type
} = event.currentTarget.dataset;
Notify({
type,
message: '提交成功,请等待管理员审核!'
});
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function(options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function() {
let name = "【onReady】"
this.setData({
areaList: utilSArea.default
})
console.info(log, name, "【初始化行政区对象】", this.data.areaList)
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function() {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function() {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function() {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function() {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function() {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function() {
}
}) | 07f0841c95a139f7dbd27d67e8b3c5e269cbf404 | [
"JavaScript"
] | 2 | JavaScript | whjames007/wxxcx-code-006 | c6acd13db5b3e32cded50dcaed8f589ed3e634a8 | 7785f76622b35b70c8c6818991f11ff6e82a667d |
refs/heads/main | <repo_name>abhishekkumar2718/Simple-Homomorphic-Encryption<file_sep>/main.cpp
#include "fully_homomorphic.h"
int main(int argc, char** argv) {
CryptoPP::AutoSeededRandomPool rng;
SecuritySettings *security_settings = new SecuritySettings(5);
FullyHomomorphic fh(security_settings);
PrivateKey sk;
PublicKey pk;
cout << *security_settings << endl;
fh.generate_key_pair(sk, pk);
fh.test_decryption_circuit(pk, sk);
}
<file_sep>/demo_vote_counter.cpp
#include "demo_vote_counter.h"
void print_help() {
printf("Takes one parameter, the number of candidates in the election\n");
}
bool DemoVoteCounter::verify_vote(unsigned int vote_id) {
Gate* input_zero = new Gate(InputLiteral, false, sec);
Gate* input_one = new Gate(InputLiteral, true, sec);
Gate* input;
unsigned long int w_length = log2(num_candidates);
unsigned long int p_length = pow(2, w_length);
Gate* temp_and;
Gate*** p = new Gate**[num_candidates+1];
for (unsigned long int i = 0; i < num_candidates+1; i++) { //row
p[i] = new Gate*[p_length+1];
p[i][0] = input_one;
if (i > 0) {
input = new Gate(Input, vote_id*num_candidates + i-1, sec);
}
for (unsigned int j = 1; j < p_length+1; j++) { //col
if (i == 0) {
p[0][j] = input_zero;
} else {
temp_and = new Gate(And, p[i-1][j-1], input, sec);
p[i][j] = new Gate(Xor, temp_and, p[i-1][j], sec);
}
}
}
Gate* output;
std::vector<Gate*> output_gates;
for (unsigned long int i = p_length; i > 0; i >>= 1) {
output = new Gate(Output, p[num_candidates][i], sec);
output_gates.push_back(output);
}
CipherBit** encrypted_results = fh->evaluate(output_gates, votes, pk);
bool* decrypted_results = fh->decrypt_bit_vector(sk, encrypted_results, w_length+1);
for (unsigned int i = 0; i < w_length; i++) {
if (decrypted_results[i]) {
printf("%u\n", decrypted_results[i]);
return false;
}
}
return decrypted_results[w_length];
}
DemoVoteCounter::DemoVoteCounter(unsigned int num_candidates) : num_candidates(num_candidates) {
sec = new SecuritySettings(4);
cout << *sec << endl;
fh = new FullyHomomorphic(sec);
fh->generate_key_pair(sk, pk);
}
void DemoVoteCounter::get_votes() {
int scan_result;
unsigned int vote;
num_votes = 0;
char temp_char;
std::vector<CipherBit*> encrypted_votes_vector;
CipherBit* encrypted_bit;
while (true) {
printf("Please enter a vote (1-%u), or 0 to terminate: ", num_candidates);
scan_result = scanf("%u", &vote);
if (scan_result != 1 || vote > num_candidates) {
printf("Invalid vote, please try again...\n");
while ((temp_char = getchar()) != '\n');
continue;
}
if (vote == 0) {
break;
}
for (unsigned int i = 0; i < num_candidates; i++) {
encrypted_bit = new CipherBit;
fh->encrypt_bit(*encrypted_bit, pk, i == vote-1);
cout << *encrypted_bit << endl;
encrypted_votes_vector.push_back(encrypted_bit);
}
num_votes++;
}
votes = new CipherBit*[encrypted_votes_vector.size()];
for (unsigned int i = 0; i < encrypted_votes_vector.size(); i++) {
votes[i] = encrypted_votes_vector[i];
}
}
void DemoVoteCounter::verify_votes() {
printf("Verifying votes\n");
bool failed = false;
for (unsigned int i = 0; i < num_votes; i++) {
if (!verify_vote(i)) {
printf("Vote %u failed to verify!\n", i+1);
failed = true;
}
}
if (!failed) {
printf("All votes verified\n");
}
}
void DemoVoteCounter::count_votes() {
printf("Counting votes\n");
Gate* input_zero = new Gate(InputLiteral, false, sec);
Gate* input_one = new Gate(InputLiteral, true, sec);
Gate* input;
unsigned long int w_length = log2(num_votes);
unsigned long int p_length = pow(2, w_length);
Gate* temp_and;
Gate*** candidate_total = new Gate**[num_candidates];
for (unsigned int candidate = 0; candidate < num_candidates; candidate++) {
Gate*** p = new Gate**[num_votes+1];
for (unsigned long int i = 0; i < num_votes+1; i++) { //row
p[i] = new Gate*[p_length+1];
p[i][0] = input_one;
if (i > 0) {
input = new Gate(Input, (i-1)*num_candidates + candidate, sec);
}
for (unsigned int j = 1; j < p_length+1; j++) { //col
if (i == 0) {
p[0][j] = input_zero;
} else {
temp_and = new Gate(And, p[i-1][j-1], input, sec);
p[i][j] = new Gate(Xor, temp_and, p[i-1][j], sec);
}
}
}
candidate_total[candidate] = new Gate*[w_length+1];
int cur_index = 0;
for (unsigned long int i = p_length; i > 0; i >>= 1) {
candidate_total[candidate][cur_index++] = p[num_votes][i];
}
}
Gate* output;
std::vector<Gate*> output_gates;
for (unsigned int candidate = 0; candidate < num_candidates; candidate++) {
for (unsigned long int i = 0; i < w_length+1; i++) {
output = new Gate(Output, candidate_total[candidate][i], sec);
output_gates.push_back(output);
}
}
CipherBit** encrypted_results = fh->evaluate(output_gates, votes, pk);
bool* decrypted_results = fh->decrypt_bit_vector(sk, encrypted_results, num_candidates*(w_length+1));
textcolor(BRIGHT, RED);
for (unsigned int candidate = 0; candidate < num_candidates; candidate++) {
for (unsigned int i = 0; i < w_length+1; i++) {
printf("%u ", decrypted_results[candidate*(w_length+1) + i]);
}
printf("\n");
}
resettextcolor();
}
int main(int argc, char** argv) {
if (argc != 2) {
print_help();
exit(1);
}
unsigned int num_candidates = atoi(argv[1]);
DemoVoteCounter demo(num_candidates);
demo.get_votes();
demo.verify_votes();
demo.count_votes();
}
<file_sep>/demo_vote_counter.h
#include "fully_homomorphic.h"
class DemoVoteCounter {
private:
SecuritySettings* sec;
unsigned int num_candidates;
CipherBit** votes;
FullyHomomorphic* fh;
bool verify_vote(unsigned int vote_id);
PrivateKey sk;
PublicKey pk;
unsigned int num_votes;
public:
DemoVoteCounter(unsigned int num_candidates);
void get_votes();
void verify_votes();
void count_votes();
};
<file_sep>/fully_homomorphic.cpp
#include "fully_homomorphic.h"
#include <set>
unsigned int FullyHomomorphic::MAX_SOMEWHAT_PUBLIC_KEY_TRIES = 10;
FullyHomomorphic::FullyHomomorphic (SecuritySettings *security_settings) : sec(security_settings) {
size_t n_bytes = 8;
CryptoPP::byte seed_bytes[n_bytes];
// Seed the CryptoPP RNG using system time and srand()
seed_rng();
// Generate 8 bytes of entropy to seed the random state
rng.GenerateBlock(seed_bytes, n_bytes);
seed_random_state(seed_bytes, n_bytes);
}
void FullyHomomorphic::generate_key_pair(PrivateKey &sk, PublicKey &pk) {
cout << "--- Generating Key Pair ---" << endl;
generate_somewhat_private_key(ssk);
sk = generate_private_key();
pk.old_key = generate_somewhat_public_key(ssk);
pk.old_key_extra = generate_additional_somewhat_public_key(ssk);
pk.y_vector = generate_y_vector(sk);
}
// Returns a random integer between [2^(eta - 1) + 1, 2^eta + 1]
void FullyHomomorphic::generate_somewhat_private_key(SomewhatPrivateKey key) {
mpz_t temp;
mpz_init(key);
mpz_init2(temp, sec->eta-1);
mpz_setbit(temp, sec->eta-2);
mpz_add_ui(temp, temp, 1); // temp: 2^(eta - 2) + 1
mpz_urandomm(key, rand_state, temp); // key: [0, 2^(eta - 2)]
mpz_sub_ui(temp, temp, 1); // temp: 2^(eta - 2)
mpz_add(key, key, temp); // key: [2^(eta - 2), 2^(eta - 1)]
mpz_mul_ui(key, key, 2); // key: [2^(eta - 1), 2^eta]
mpz_add_ui(key, key, 1); // key: [2^(eta - 1) + 1, 2^eta + 1]
mpz_clear(temp);
}
// Generate private key (also called s-vector), which consists of tau
// unique integers between [0, theta).
//
// tau: sec->private_key_length
// theta: sec->public_key_y_vector_length
PrivateKey FullyHomomorphic::generate_private_key() {
auto key_length = sec->private_key_length;
auto key_range = sec->public_key_y_vector_length - 1;
PrivateKey key = new unsigned int[key_length];
std::set<unsigned int> generated_keys;
while (generated_keys.size() < key_length) {
auto word = rng.GenerateWord32(0, key_range);
if (generated_keys.find(word) == generated_keys.end()) {
key[generated_keys.size()] = word;
generated_keys.insert(word);
}
}
return key;
}
// Generate the somewhat public key, which consists tau + 1 integers
// of the form p*q + r where p is the somewhat private key and q lies in
// [0, 2^gamma/p), r lies in [-2^rho + 1, 2^rho) such that the largest
// integer is odd and the remainder after division by p is even.
SomewhatPublicKey FullyHomomorphic::generate_somewhat_public_key(const SomewhatPrivateKey &sk) {
auto key_length = sec->public_key_old_key_length;
SomewhatPublicKey key = new __mpz_struct* [key_length];
for (unsigned int i = 0; i < key_length; i++) {
key[i] = new mpz_t;
mpz_init(key[i]);
}
for (unsigned int try_count = 0; try_count < MAX_SOMEWHAT_PUBLIC_KEY_TRIES; try_count++) {
bool valid_key = false;
unsigned long int max_index = 0;
for (unsigned long int i = 0; i < key_length; i++) {
choose_random_d(key[i], sk);
if (mpz_cmp(key[i], key[max_index]) > 0)
max_index = i;
}
mpz_t mod_result;
mpz_init(mod_result);
mpz_correct_mod(mod_result, key[max_index], sk);
// If the largest integer is odd and the remainder after division
// by p is even, we have generated a valid somewhat public key.
valid_key = mpz_odd_p(key[max_index]) && mpz_even_p(mod_result);
mpz_clear(mod_result);
if (valid_key) {
mpz_swap(key[0], key[max_index]);
return key;
}
}
for (unsigned int i = 0; i < key_length; i++) {
mpz_clear(key[i]);
delete key[i];
}
delete[] key;
cout << "Could not generate a somewhat public key!" << endl;
cout << "Try with a different seed!" << endl;
exit(1);
}
// Generates gamma + 1 random integers of the form 2*(p*q[i] + r)
// where p is the secret key, q lies in [2^(gamma + i - 1)/p, 2^(gamma + i)/p)
// and r lies in [-2^rho - 1, 2^rho + 2).
SomewhatPublicKey FullyHomomorphic::generate_additional_somewhat_public_key(const SomewhatPrivateKey &sk) {
auto key_length = sec->gamma + 1;
SomewhatPublicKey key = new __mpz_struct*[key_length];
// Initialize range for q's
mpz_t q_range;
mpz_init2(q_range, sec->gamma);
mpz_setbit(q_range, sec->gamma-1); // q_range: 2^(gamma - 1)
mpz_cdiv_q(q_range, q_range, sk); // q_range: 2^(gamma - 1)/p
// Initialize range for r's
mpz_t r_range;
mpz_init2(r_range, sec->rho+2);
mpz_setbit(r_range, sec->rho+1); // r_range: 2^(rho + 1)
mpz_add_ui(r_range, r_range, 1); // r_range: 2^(rho + 1) + 1
// Initialize offset for r's
mpz_t r_shift;
mpz_init2(r_shift, sec->rho+1);
mpz_setbit(r_shift, sec->rho); // r_shift: 2^rho
mpz_sub_ui(r_shift, r_shift, 1); // r_shift: 2^rho - 1
mpz_t temp;
mpz_init(temp);
for (unsigned long int i = 0; i < key_length; i++) {
key[i] = new mpz_t;
mpz_init(key[i]);
mpz_urandomm(temp, rand_state, q_range); // pick a random integer between [0, q_range)
mpz_add(temp, temp, q_range); // shift to [q_range, 2*q_range)
mpz_mul(key[i], sk, temp); // key[i]: p*q
mpz_urandomm(temp, rand_state, r_range); // pick a random integer r between [0, r_range)
mpz_sub(temp, temp, r_shift); // shift to [-r_shift, r_range - r_shift)
mpz_add(key[i], key[i], temp); // key[i]: p*q + r
mpz_mul_2exp(key[i], key[i], 1); // key[i]: 2(p*q + r)
mpz_mul_2exp(q_range, q_range, 1); // q_range: 2*q_range
}
mpz_clear(temp);
return key;
}
// Generate y-vector for the public key.
//
// y-vector is a set of big-theta rational numbers in [0, 2) with
// kappa bits of precision such that there is a sparse subset of
// y-vector of size theta such that sum of subset is approximately
// equal to (1/p mod 2).
//
// theta: sec->private_key_length
// big-theta: sec->private_key_y_vector_length
//
// NOTE: instead of using rational numbers between [0, 2) and deal with
// precision issues, we are using integers between [0, 2^kappa) and dividing
// before use.
mpz_t_arr FullyHomomorphic::generate_y_vector(const PrivateKey &sk) {
auto y_vector_length = sec->public_key_y_vector_length;
mpz_t x_p, sum, mod;
mpz_t_arr y_vector = new __mpz_struct* [y_vector_length];
mpz_init(sum);
mpz_init2(mod, sec->kappa + 2);
mpz_setbit(mod, sec->kappa + 1); // mod: 2^kappa + 1
// x_p is the closest integer to 2^kappa/ssk
generate_x_p(x_p);
for (unsigned int i = 0; i < y_vector_length; i++) {
y_vector[i] = new mpz_t;
mpz_init(y_vector[i]);
mpz_urandomb(y_vector[i], rand_state, sec->kappa); // y_vector[i]: [0, 2^kappa)
}
// Replace one of the elements in the y-vector with 2^kappa/ssk - (S mod 2^(kappa + 1))
// where S is the sum of the theta element subset of y-vector to serve as an hint
// for "post-processing" circuits.
unsigned int rand_val = rng.GenerateWord32(0, sec->private_key_length - 1);
auto secret_key_idx = sk[rand_val];
for (unsigned int i = 0; i < sec->private_key_length; i++) {
if (sk[i] != secret_key_idx)
mpz_add(sum, sum, y_vector[sk[i]]);
}
// sum: sum % 2^(kappa + 1)
mpz_mod(sum, sum, mod);
// y_vector[secret_key_idx]: x_p - (sum % 2^(kappa + 1))
if (mpz_cmp(x_p, sum) > 0) {
mpz_sub(y_vector[secret_key_idx], x_p, sum);
} else {
mpz_sub(y_vector[secret_key_idx], x_p, sum);
mpz_add(y_vector[secret_key_idx], y_vector[secret_key_idx], mod);
}
mpz_clear(x_p);
mpz_clear(sum);
mpz_clear(mod);
return y_vector;
}
// x_p is the closest integer to 2^kappa/ssk
void FullyHomomorphic::generate_x_p(mpz_t x_p) {
mpz_t remainder, half_ssk;
mpz_init(x_p);
mpz_init(remainder);
mpz_init(half_ssk);
mpz_setbit(x_p, sec->kappa); // x_p: 2^kappa
mpz_fdiv_qr(x_p, remainder, x_p, ssk); // x_p: 2^kappa/ssk, remainder: (2^kappa % ssk)
mpz_fdiv_q_2exp(half_ssk, ssk, 1); // half_ssk: ssk/2
// If the remainder is larger than half of ssk, round x_p to the
// next integer
if (mpz_cmp(remainder, half_ssk) < 0)
mpz_add_ui(x_p, x_p, 1);
mpz_clear(remainder);
mpz_clear(half_ssk);
}
// Assigns an integer result = p*q + r where p is the somewhatPrivateKey,
// q belongs to [0, 2^gamma/p) and r belongs [-2^rho + 1, 2^rho).
void FullyHomomorphic::choose_random_d(mpz_t result, const SomewhatPrivateKey p) {
mpz_t temp, q_range, r_range, r_shift;
mpz_init(temp);
mpz_init2(q_range, sec->gamma + 1);
mpz_setbit(q_range, sec->gamma); // q_range: 2^gamma
mpz_cdiv_q(q_range, q_range, p); // q_range: 2^gamma/p
mpz_init2(r_range, sec->rho + 2);
mpz_setbit(r_range, sec->rho + 1); // r_range: 2^(rho + 1)
mpz_add_ui(r_range, r_range, 1); // r_range: 2^(rho + 1) + 1
mpz_init2(r_shift, sec->rho + 1);
mpz_setbit(r_shift, sec->rho); // r_shift: 2^(rho)
mpz_sub_ui(r_shift, r_shift, 1); // r_shift: 2^rho - 1
mpz_urandomm(temp, rand_state, q_range); // pick a random integer q between [0, q_range)
mpz_mul(result, p, temp); // result: p*q
mpz_urandomm(temp, rand_state, r_range); // pick a random integer r betwen [0, r_range)
mpz_sub(temp, temp, r_shift); // shift to [-r_shift, r_range - r_shift)
mpz_add(result, result, temp); // result: p*q + r
mpz_clear(temp);
mpz_clear(q_range);
mpz_clear(r_range);
mpz_clear(r_shift);
}
/* ENCRYPTION */
void FullyHomomorphic::old_encrypt_bit(mpz_t result, const PublicKey &pk, const bool m) {
mpz_t sum;
mpz_init(sum);
CryptoPP::byte randomness = rng.GenerateByte();
unsigned int randomness_counter = 0; // Current bit of randomness being used
for (unsigned int i = 1; i < sec->public_key_old_key_length; i++) {
if (randomness_counter == 8) {
// grab more randomness
randomness = rng.GenerateByte();
randomness_counter = 0;
}
if ((randomness << randomness_counter) >> 7) {
mpz_add(sum, sum, pk.old_key[i]);
}
randomness_counter++;
}
mpz_mul_2exp(sum, sum, 1); // multiply by 2
mpz_t r;
mpz_init(r);
mpz_t upper_bound;
mpz_init2(upper_bound, sec->rho_+2);
mpz_setbit(upper_bound, sec->rho_+1);
mpz_sub_ui(upper_bound, upper_bound, 2);
mpz_urandomm(r, rand_state, upper_bound);
mpz_clear(upper_bound);
mpz_t offset;
mpz_init2(offset, sec->rho_+1);
mpz_setbit(offset, sec->rho_);
mpz_sub_ui(offset, offset, 1);
mpz_sub(r, r, offset);
mpz_clear(offset);
// r should now be in the exclusive range (-2^rho', 2^rho')
mpz_mul_2exp(r, r, 1); // multiply by 2
mpz_add_ui(result, result, m);
mpz_add(result, result, r);
mpz_add(result, result, sum);
mpz_correct_mod(result, result, pk.old_key[0]);
mpz_clear(r);
mpz_clear(sum);
}
void FullyHomomorphic::encrypt_bit(CipherBit &result, const PublicKey &pk, const bool m) {
mpz_init(result.old_ciphertext);
old_encrypt_bit(result.old_ciphertext, pk, m);
unsigned int precision = ceil(log2(sec->theta)) + 3;
result.z_vector = new unsigned long [sec->public_key_y_vector_length];
unsigned long bitmask = (1l << (precision+1)) - 1;
mpz_t temp;
mpz_init(temp);
// unsigned int __gmp_n;
for (unsigned int i = 0; i < sec->public_key_y_vector_length; i++) {
mpz_mul(temp, result.old_ciphertext, pk.y_vector[i]);
mpz_fdiv_q_2exp(temp, temp, sec->kappa-precision);
result.z_vector[i] = mpz_get_ui(temp) & bitmask;
}
mpz_clear(temp);
}
/* DECRYPTION */
bool FullyHomomorphic::decrypt_bit(const CipherBit &c, const PrivateKey &sk) {
mpz_t sum;
mpz_init(sum);
for (unsigned int i = 0; i < sec->private_key_length; i++) {
mpz_add_ui(sum, sum, c.z_vector[sk[i]]);
}
mpz_t rounded_sum;
mpz_init(rounded_sum);
mpz_t remainder;
mpz_init(remainder);
unsigned int precision = ceil(log2(sec->theta)) + 3;
// It's interesting that this needed to be ceiling division... I wonder if the
// rounding above in key generation needs to be as well...
mpz_cdiv_r_2exp(remainder, sum, precision);
mpz_fdiv_q_2exp(rounded_sum, sum, precision);
mpz_t half_sum;
mpz_init(half_sum);
mpz_fdiv_q_2exp(half_sum, sum, 1);
if (mpz_cmp(remainder, half_sum) < 0) {
mpz_add_ui(rounded_sum, rounded_sum, 1); // fix "rounding" to round up
}
mpz_clear(half_sum);
mpz_clear(remainder);
// printf("rounded sum: ");
// mpz_out_str(NULL, 10, rounded_sum);
// printf("\n");
// printf("c*: ");
// mpz_out_str(NULL, 10, c.old_ciphertext);
// printf("\n");
mpz_sub(rounded_sum, c.old_ciphertext, rounded_sum);
// I think this should really be mpz_odd_p, but this seems to give the correct answer... Investigate later
int return_val = mpz_odd_p(rounded_sum);
mpz_clear(sum);
mpz_clear(rounded_sum);
return return_val;
}
bool old_decrypt_bit(mpz_t c, mpz_t sk) {
mpz_t temp;
mpz_init(temp);
mpz_correct_mod(temp, c, sk);
int return_val = mpz_odd_p(temp);
mpz_clear(temp);
return return_val;
}
void FullyHomomorphic::clear_cipher_bit(CipherBit &c) {
mpz_clear(c.old_ciphertext);
delete[] c.z_vector;
}
CipherBit** FullyHomomorphic::encrypt_bit_vector(const PublicKey &pk, const bool* m_vector, const unsigned long int m_vector_length) {
CipherBit** c_vector = new CipherBit*[m_vector_length];
CipherBit* c;
unsigned long int c_index = 0;
for (unsigned long int i = 0; i < m_vector_length; i++) {
c = new CipherBit;
encrypt_bit(*c, pk, m_vector[i]);
c_vector[c_index] = c;
c_index++;
//clear_cipher_bit(c);
}
return c_vector;
}
bool* FullyHomomorphic::decrypt_bit_vector(const PrivateKey &sk, CipherBit** c_vector, const unsigned long int c_vector_length) {
bool* m_vector = new bool[c_vector_length];
unsigned long int m_index = 0;
for (unsigned long int i = 0; i < c_vector_length; i++) {
m_vector[m_index] = decrypt_bit(*c_vector[i], sk);
m_index++;
}
return m_vector;
}
bool FullyHomomorphic::is_allowed_circuit(std::vector<Gate*> output_gates) {
// d <= (e - 4 - (log fnorm)) / (r + 2)
unsigned long int max_degree = 0;
unsigned long int max_norm = 0;
for (std::vector<Gate*>::iterator i = output_gates.begin(); i != output_gates.end(); i++) {
if ((*i)->degree > max_degree) {
max_degree = (*i)->degree;
max_norm = (*i)->norm;
}
//if ((*i)->degree > (sec->eta - 4 - log2((*i)->norm)) / (sec->rho_+2))
//return false;
}
// printf("Max Degree = %lu, Max Norm = %lu\n", max_degree, max_norm);
// printf("Log2 Max Norm = %f\n", log2(max_norm));
printf("max degree: %lu, max norm: %lu\n", max_degree, max_norm);
if (max_degree > (sec->eta - 4 - log2(max_norm)) / (sec->rho_+2))
return false;
return true;
}
CipherBit** FullyHomomorphic::evaluate(std::vector<Gate*> output_gates, CipherBit** inputs, const PublicKey &pk) {
if (!is_allowed_circuit(output_gates)) {
printf("Circuit is not allowed! Giving up!\n");
exit(1);
}
// TODO: Make sure that the function will be calculated properly
std::stack<Gate*> evaluation_stack;
for (std::vector<Gate*>::reverse_iterator i = output_gates.rbegin(); i != output_gates.rend(); i++) {
evaluation_stack.push((Gate*)*i);
}
CipherBit** output_vector = new CipherBit*[output_gates.size()];
unsigned long int output_index = 0;
while (!evaluation_stack.empty()) {
Gate* cur_gate = evaluation_stack.top();
if (!cur_gate->input1_resolved) {
evaluation_stack.push(cur_gate->input1);
}
if (!cur_gate->input2_resolved) {
evaluation_stack.push(cur_gate->input2);
}
if (cur_gate->input1_resolved && cur_gate->input2_resolved) {
if (cur_gate->is_input())
cur_gate->forward_ciphertext(inputs);
cur_gate->evaluate(pk);
evaluation_stack.pop();
if (cur_gate->gate_type == Output) {
output_vector[output_index] = cur_gate->output_cipher_bits;
output_index++;
}
}
}
return output_vector;
}
void FullyHomomorphic::test_decryption_circuit(const PublicKey &pk, const PrivateKey &sk) {
unsigned int n = ceil(log2(sec->theta)) + 3;
std::vector<Gate*> output_gates = create_decryption_cicuit();
if (is_allowed_circuit(output_gates)) {
printf("Allowed circuit\n");
} else {
printf("NOT ALLOWED CIRCUIT!!\n");
return;
}
bool* in = new bool[1];
in[0] = true;
CipherBit** encrypted_vector = encrypt_bit_vector(pk, in, 1);
delete[] in;
CipherBit* encrypted_bit = encrypted_vector[0];
delete[] encrypted_vector; // TODO: POSSIBLE BUG: Does this delete the CipherBits, or just the pointers to them??
// Note: Seems to just delete the pointers
unsigned long int in_length = sec->gamma+sec->tau+sec->big_theta+sec->big_theta*(n+1);
printf("in_length: %lu\n", in_length);
CipherBit** in_vector = new CipherBit*[in_length];
printf("Creating c_star input vector (starting at index %lu)\n", 0l);
bool* c_star_bool_vector = new bool[sec->gamma+sec->tau];
for (unsigned int i = 0; i < sec->gamma+sec->tau; i++) {
c_star_bool_vector[i] = mpz_tstbit(encrypted_bit->old_ciphertext, i);
}
printf("(doing encryption)\n");
CipherBit** encrypted_c_star_vector = encrypt_bit_vector(pk, c_star_bool_vector, sec->gamma+sec->tau);
delete[] c_star_bool_vector;
for (unsigned int i = 0; i < sec->gamma+sec->tau; i++) {
in_vector[i] = encrypted_c_star_vector[i];
}
delete[] encrypted_c_star_vector;
unsigned int look_at_index;
printf("Creating s input vector (starting at index %lu)\n", sec->gamma+sec->tau);
bool* s_bool_vector = new bool[sec->big_theta];
for (unsigned long int i = 0; i < sec->big_theta; i++) {
s_bool_vector[i] = false;
}
for (unsigned int i = 0; i < sec->private_key_length; i++) {
s_bool_vector[sk[i]] = true;
look_at_index = sk[i];
}
printf("s[%u] = %u\n", look_at_index, (bool) s_bool_vector[look_at_index]);
CipherBit** encrypted_s_vector = encrypt_bit_vector(pk, s_bool_vector, sec->big_theta);
//delete[] s_bool_vector;
for (unsigned int i = 0; i < sec->big_theta; i++) {
in_vector[sec->gamma+sec->tau+i] = encrypted_s_vector[i];
}
delete[] encrypted_s_vector;
printf("Creating z input vector (starting at index %lu)\n", sec->gamma+sec->tau+sec->big_theta);
bool* z_bool_vector = new bool[sec->big_theta*(n+1)];
for (unsigned int i = 0; i < sec->big_theta; i++) {
for (unsigned int j = 0; j < n+1; j++) {
z_bool_vector[i*(n+1)+j] = (encrypted_bit->z_vector[i] >> j) & 1;
}
}
CipherBit** encrypted_z_vector = encrypt_bit_vector(pk, z_bool_vector, sec->big_theta*(n+1));
//delete[] z_bool_vector;
printf("a[i][0]'s based on orig bool vectors\n");
int count = 0;
for (unsigned int i = 0; i < sec->big_theta; i++) {
if (z_bool_vector[i*(n+1)] && s_bool_vector[i]) {
printf("1");
count++;
} else {
printf("0");
}
}
printf(" (True count: %u)\n", count);
for (unsigned int i = 0; i < sec->big_theta*(n+1); i++) {
in_vector[sec->gamma+sec->tau+sec->big_theta+i] = encrypted_z_vector[i];
}
delete[] encrypted_z_vector;
CipherBit** evaluated_ciphertext = evaluate(output_gates, in_vector, pk);
bool* evaluated_plaintext = decrypt_bit_vector(sk, evaluated_ciphertext, output_gates.size());
unsigned long int output_length = ceil(log(n+1) / log(3.0/2)) + 2;
for (unsigned long int i = 0; i < output_length; i++) {
printf("%u", (bool) evaluated_plaintext[i]);
}
printf("\n");
for (unsigned long int i = 0; i < output_length; i++) {
printf("%u", (bool) evaluated_plaintext[output_length + i]);
}
printf("\n");
decrypt_bit(*encrypted_bit, sk);
}
std::vector<Gate*> FullyHomomorphic::create_decryption_cicuit() {
// Assumes input will be a long vector with:
// c* in bits 0...(gamma+tau-1) (LSB first?)
// s indicator vector in bits (gamma+tau)...(gamma+tau+big_theta-1) (s0 first)
// zi vector in bits (gamma+tau+big_theta+i*(n+1))...(gamma+tau+big_theta+(i+1)*(n+1)-1) (LSB first) (i is 0-indexed)
// where n = ceil(log(theta))+3
unsigned int n = ceil(log2(sec->theta)) + 3;
Gate* input_zero = new Gate(InputLiteral, false, sec);
Gate* input_one = new Gate(InputLiteral, true, sec);
Gate** c_star = new Gate*[sec->gamma+sec->tau];
for (unsigned long int i = 0; i < sec->gamma+sec->tau; i++) {
//c_star[i] = new Gate(Input, *(in_vector[i]), lambda);
c_star[i] = new Gate(Input, i, sec);
}
Gate** s = new Gate*[sec->big_theta];
for (unsigned int i = 0; i < sec->big_theta; i++) {
//s[i] = new Gate(Input, *(in_vector[gamma+tau+i]), lambda);
s[i] = new Gate(Input, sec->gamma+sec->tau+i, sec);
}
Gate*** z = new Gate**[sec->big_theta];
for (unsigned int i = 0; i < sec->big_theta; i++) {
z[i] = new Gate*[n+1];
for (unsigned int j = 0; j < n+1; j++) {
//z[i][j] = new Gate(Input, *(in_vector[gamma+tau+big_theta+i*(n+1)+j]), lambda);
z[i][j] = new Gate(Input, sec->gamma+sec->tau+sec->big_theta+i*(n+1)+j, sec);
}
}
// a[i][j] is jth bit of a_i (0-indexed)
Gate*** a = new Gate**[sec->big_theta];
for (unsigned int i = 0; i < sec->big_theta; i++) {
a[i] = new Gate*[n+1];
for (unsigned int j = 0; j < n+1; j++) {
a[i][j] = new Gate(And, s[i], z[i][j], sec);
// s[i]->add_output(a[i][j]);
// z[i][j]->add_output(a[i][j]);
}
}
unsigned long int w_length = log2(sec->theta+1);
unsigned long int p_length = pow(2, w_length);
Gate* temp_and;
Gate**** p = new Gate***[n+1];
for (unsigned int i = 0; i < n+1; i++) {
p[i] = new Gate**[p_length+1];
for (unsigned int j = 0; j < p_length+1; j++) {
p[i][j] = new Gate*[sec->big_theta+1];
if (j == 0) {
p[i][0][0] = input_one;
} else {
p[i][j][0] = input_zero;
}
for (unsigned int k = 1; k < sec->big_theta+1; k++) {
if (j == 0) {
p[i][0][k] = input_one;
} else {
temp_and = new Gate(And, p[i][j-1][k-1], a[k-1][i], sec);
// p[i][j-1][k-1]->add_output(temp_and);
// a[k-1][i]->add_output(temp_and);
p[i][j][k] = new Gate(Xor, temp_and, p[i][j][k-1], sec);
// temp_and->add_output(p[i][j][k]);
// p[i][j][k-1]->add_output(p[i][j][k]);
}
}
}
}
Gate*** w = new Gate**[n+1];
for (unsigned long int i = 0; i < n+1; i++) {
w[i] = new Gate*[w_length+1];
unsigned long int k = 0;
for (unsigned long int j = p_length; j > 0; j >>= 1) {
w[i][k++] = p[i][j][sec->big_theta];
}
}
Gate*** temp;
unsigned int cur_w_length = w_length+1;
printf("n+1 = %u\n", n+1);
for (unsigned int i = n+1; i > 2; i = (i/3)*2 + i%3) {
unsigned int used_slots = 0;
// Calculate w[3*j] + w[3*j+1] + w[3*j+2] = x + y
// Assign x and y to next available slots in w that have already been processed
for (unsigned int j = 0; j < i/3; j++) {
temp = create_3_for_2_circuit(w[3*j], w[3*j+1], w[3*j+2], cur_w_length);
w[used_slots++] = temp[0];
w[used_slots++] = temp[1];
}
// Move left over slots down for next iteration
for (unsigned int j = 0; j < i%3; j++) {
w[used_slots] = new Gate*[cur_w_length+1];
for (unsigned int k = 0; k < cur_w_length; k++) {
w[used_slots][k] = w[(i/3)*3 + j][k];
}
w[used_slots][cur_w_length] = new Gate(InputLiteral, false, sec);
used_slots++;
}
printf("used_slots: %u\n", used_slots);
cur_w_length++;
}
std::vector<Gate*> outputs;
Gate* output_gate;
for (unsigned int i = 0; i < cur_w_length; i++) {
output_gate = new Gate(Output, w[0][i], sec);
outputs.push_back(output_gate);
}
for (unsigned int i = 0; i < cur_w_length; i++) {
output_gate = new Gate(Output, w[1][i], sec);
outputs.push_back(output_gate);
}
return outputs;
}
/*
* return[0] and return[1] are the two n+1 sized outputs
*/
Gate*** FullyHomomorphic::create_3_for_2_circuit(Gate** a, Gate** b, Gate** c, unsigned int n) {
Gate** d = new Gate*[n+1];
Gate** e = new Gate*[n+1];
Gate* temp_xor;
for (unsigned int i = 0; i < n; i++) {
temp_xor = new Gate(Xor, a[i], b[i], sec);
d[i] = new Gate(Xor, temp_xor, c[i], sec);
}
d[n] = new Gate(InputLiteral, false, sec);
Gate* temp_and1;
Gate* temp_and2;
Gate* temp_and3;
e[0] = new Gate(InputLiteral, false, sec);
for (unsigned int i = 0; i < n; i++) {
temp_and1 = new Gate(And, a[i], b[i], sec);
temp_and2 = new Gate(And, b[i], c[i], sec);
temp_and3 = new Gate(And, a[i], c[i], sec);
temp_xor = new Gate(Xor, temp_and1, temp_and2, sec);
e[i+1] = new Gate(Xor, temp_xor, temp_and3, sec);
}
Gate*** output = new Gate**[2];
output[0] = d;
output[1] = e;
return output;
}
void FullyHomomorphic::store_cipher_bit(FILE* stream, CipherBit &c) {
mpz_out_raw(stream, c.old_ciphertext);
}
void FullyHomomorphic::seed_rng() {
srand(time(NULL));
unsigned int init_seed = rand();
rng.IncorporateEntropy((CryptoPP::byte*) &init_seed, sizeof(unsigned int));
}
void FullyHomomorphic::seed_random_state(void *source, size_t n_bytes) {
mpz_t seed;
mpz_init(seed);
mpz_import(seed, n_bytes, 1, 1, 1, 0, source);
gmp_randinit_default(rand_state);
gmp_randseed(rand_state, seed);
}
/* TODO:
* - Still have a small memory leak. I think it has to do with cipher bits not getting delete[]'d, but I get a double free when I try to...
*/
<file_sep>/utilities.cpp
#include "utilities.h"
// TODO: What is "correct mod"?
void mpz_correct_mod(mpz_t result, const mpz_t n, const mpz_t d) {
mpz_t temp;
mpz_init(temp);
// Divide N by D and store the remainder in result
mpz_tdiv_r(result, n, d);
// Divide D by 2^1 and store the quotient in temp
mpz_fdiv_q_2exp(temp, d, 1);
if (mpz_cmp(result, temp) > 0)
mpz_sub(result, d, result);
mpz_clear(temp);
}
void textcolor(int attr, int fg) {
if (COLOR_OUTPUT)
printf("%c[%d;%dm", 0x1B, attr, fg + 30);
}
void resettextcolor() {
if (COLOR_OUTPUT)
printf("%c[0m", 0x1B);
}
<file_sep>/makefile
CC=g++
CFLAGS=-c -Wall -g -m64
LDFLAGS=-lgmpxx -lgmp -Wl,-Bdynamic -lcryptopp -lpthread
EXECUTABLE=fully_homomorphic
TEST_EXECUTABLE=test_fully_homomorphic
DEMO_EXECUTABLE=demo_fully_homomorphic
all : $(EXECUTABLE)
test : $(TEST_EXECUTABLE)
demo : $(DEMO_EXECUTABLE)
$(TEST_EXECUTABLE) : test_suite.o fully_homomorphic.o utilities.o circuit.o security_settings.o
$(CC) -o $@ test_suite.o fully_homomorphic.o utilities.o circuit.o cipher_bit.o security_settings.o $(LDFLAGS)
$(DEMO_EXECUTABLE) : demo_vote_counter.o fully_homomorphic.o utilities.o circuit.o security_settings.o
$(CC) -o $@ demo_vote_counter.o fully_homomorphic.o utilities.o circuit.o cipher_bit.o security_settings.o $(LDFLAGS)
$(EXECUTABLE) : main.o fully_homomorphic.o utilities.o circuit.o security_settings.o
$(CC) -o $@ main.o fully_homomorphic.o utilities.o circuit.o cipher_bit.o security_settings.o $(LDFLAGS)
test_suite.o : test_suite.cpp
$(CC) $(CFLAGS) test_suite.cpp
demo_vote_counter.o : demo_vote_counter.cpp
$(CC) $(CFLAGS) demo_vote_counter.cpp
main.o : main.cpp
$(CC) $(CFLAGS) main.cpp
utilities.o : utilities.cpp
$(CC) $(CFLAGS) utilities.cpp
fully_homomorphic.o : fully_homomorphic.cpp fully_homomorphic.h type_defs.h cipher_bit.o
$(CC) $(CFLAGS) fully_homomorphic.cpp -lgmp -lcryptopp -lpthreads
cipher_bit.o : cipher_bit.cpp
$(CC) $(CFLAGS) cipher_bit.cpp
circuit.o : circuit.cpp
$(CC) $(CFLAGS) circuit.cpp
security_settings.o : security_settings.cpp
$(CC) $(CFLAGS) security_settings.cpp
clean :
rm -rf *.o fully_homomorphic demo_fully_homomorphic test_fully_homomorphic
<file_sep>/fully_homomorphic.h
#ifndef FULLY_HOMOMORPHIC_H
#define FULLY_HOMOMORPHIC_H
#include "cipher_bit.h"
#include "type_defs.h"
#include <cstdio>
#include <cmath>
#include <gmp.h>
#include "utilities.h"
#include "circuit.h"
#include "security_settings.h"
#include <cryptopp/osrng.h>
#include <vector>
#include <stack>
class FullyHomomorphic {
private:
static unsigned int MAX_SOMEWHAT_PUBLIC_KEY_TRIES;
SecuritySettings *sec;
gmp_randstate_t rand_state;
CryptoPP::RandomPool rng;
// Generate the somewhat private key - a random integer between
// [2^(eta - 1) + 1, 2^eta + 1].
void generate_somewhat_private_key(SomewhatPrivateKey ssk);
// Generate the somewhat public key, which consists of tau + 1 integers
// of the form p*q + r where p is the somewhat private key and q lies in
// [0, 2^gamma/p), r lies in [-2^rho + 1, 2^rho) such that the largest
// integer is odd and the remainder after division by p is is even.
SomewhatPublicKey generate_somewhat_public_key(const SomewhatPrivateKey &sk);
// Generate gamma + 1 random integers of the form 2*(p*q[i] + r)
// where p is the somewhatPrivateKey, q lies in
// [2^(gamma + i - 1)/p, 2^(gamma + i)/p) and r lies in
// [-2^rho - 1, 2^rho + 2).
SomewhatPublicKey generate_additional_somewhat_public_key(const SomewhatPrivateKey &sk);
// Generate private key (also called s-vector), which consists of tau
// unique integers between [0, theta).
PrivateKey generate_private_key();
// Generate y-vector for the public key.
//
// y-vector is a set of big-theta rational numbers in [0, 2) with
// kappa bits of precision such that there is a sparse subset of
// y-vector of size theta such that sum of subset is approximately
// equal to (1/p mod 2).
//
// The y-vector acts as a hint about the secret key and this extra
// information is used to "post process" the ciphertext, making it more
// efficiently decryptable than the original ciphertext and the
// bootstrapping of fully homomorphic encryption circuits possible.
mpz_t_arr generate_y_vector(const PrivateKey &sk);
// x_p is the closest integer to 2^kappa/ssk. Used to construct y-vector.
void generate_x_p(mpz_t x_p);
// Assigns an integer result = p*q + r where p is the somewhatPrivateKey,
// q belongs to [0, 2^gamma/p) and r belongs to [-2^rho + 1, 2^rho).
//
// Used to construct the somewhat public key.
void choose_random_d(mpz_t result, const SomewhatPrivateKey p);
void store_cipher_bit(FILE* stream, CipherBit &c);
// Seed the CryptoPP RNG using system time and srand()
void seed_rng();
// Seed the GMP random state using entropy generated from RNG
void seed_random_state(void *source, size_t n_bytes);
public:
FullyHomomorphic(SecuritySettings *security_settings);
// Generate private, public key pair and assign to
// sk and pk variables
void generate_key_pair(PrivateKey &sk, PublicKey &pk);
void encrypt_bit(CipherBit &result, const PublicKey &pk, const bool m);
bool decrypt_bit(const CipherBit &c, const PrivateKey &sk);
void clear_cipher_bit(CipherBit &c);
CipherBit** encrypt_bit_vector(const PublicKey &pk, const bool* m_vector, const unsigned long int m_vector_length);
bool* decrypt_bit_vector(const PrivateKey &sk, CipherBit** c_vector, const unsigned long int c_vector_length);
//std::vector<CipherBit> evaluate(CircuitNode *circuit, std::vector<CipherBit> inputs);
CipherBit** evaluate(std::vector<Gate*> output_gates, CipherBit** inputs, const PublicKey &pk);
std::vector<Gate*> create_decryption_cicuit();
Gate*** create_3_for_2_circuit(Gate** a, Gate** b, Gate** c, unsigned int n);
void test_decryption_circuit(const PublicKey &pk, const PrivateKey &sk);
bool is_allowed_circuit(std::vector<Gate*> output_gates);
mpz_t ssk;
void old_encrypt_bit(mpz_t result, const PublicKey &pk, const bool m);
};
#endif //FULLY_HOMOMORPHIC_H
<file_sep>/utilities.h
#ifndef UTILITIES_H
#define UTILITIES_H
#include <gmp.h>
#define RESET 0
#define BRIGHT 1
#define DIM 2
#define UNDERLINE 3
#define BLINK 4
#define REVERSE 7
#define HIDDEN 8
#define BLACK 0
#define RED 1
#define GREEN 2
#define YELLOW 3
#define BLUE 4
#define MAGENTA 5
#define CYAN 6
#define WHITE 7
#define COLOR_OUTPUT 1
void mpz_correct_mod(mpz_t result, const mpz_t n, const mpz_t d);
unsigned long int max(unsigned long int a, unsigned long int b);
void textcolor(int attr, int fg);
void resettextcolor();
#endif //UTILITIES_H
<file_sep>/test_suite.cpp
#include "circuit.h"
#include "fully_homomorphic.h"
#include "security_settings.h"
#include "utilities.h"
bool OUTPUT = true;
void test_encrypt_bit(FullyHomomorphic &fh, const PublicKey &pk, const PrivateKey &sk) {
if (OUTPUT) {
printf("----- TESTING ENCRYPTION OF A SINGLE BIT -----\n");
printf("--- ENCRYPTING FALSE ---\n");
}
CipherBit c;
bool result;
for (int i = 0; i < 100; i++) {
fh.encrypt_bit(c, pk, false);
result = fh.decrypt_bit(c, sk);
if (OUTPUT) {
printf("%u", result);
fflush(NULL);
}
fh.clear_cipher_bit(c);
}
if (OUTPUT) {
printf("\n");
printf("--- ENCRYPTING TRUE ---\n");
}
for (int i = 0; i < 100; i++) {
fh.encrypt_bit(c, pk, true);
result = fh.decrypt_bit(c, sk);
if (OUTPUT) {
printf("%u", result);
fflush(NULL);
}
fh.clear_cipher_bit(c);
}
if (OUTPUT) {
printf("\n");
}
}
void test_encrypt_bit_vector(FullyHomomorphic &fh, const PublicKey &pk, const PrivateKey &sk) {
printf("----- TESTING ENCRYPTION OF A BIT VECTOR -----\n");
printf("--- ENCRYPTING ALTERNATING FALSE AND TRUE ---\n");
bool* m = new bool[100];
for (int i = 0; i < 100; i++) {
m[i] = new bool;
if (i%2 == 0)
m[i] = false;
else
m[i] = true;
}
CipherBit** e = fh.encrypt_bit_vector(pk, m, 100);
bool* d = fh.decrypt_bit_vector(sk, e, 100);
for (int i = 0; i < 100; i++) {
printf("%u", d[i]);
}
printf("\n");
}
void test_gates(FullyHomomorphic &fh, const PublicKey &pk, const PrivateKey &sk, SecuritySettings *sec) {
printf("----- TESTING EVALUATION OF GATES -----\n");
printf("--- AND GATE ---\n");
bool domain[2];
domain[0] = false;
domain[1] = true;
CipherBit** inputs = new CipherBit*[2];
inputs[0] = new CipherBit;
inputs[1] = new CipherBit;
fh.encrypt_bit(*(inputs[0]), pk, false);
fh.encrypt_bit(*(inputs[1]), pk, true);
Gate* input_a;
Gate* input_b;
Gate* operation;
Gate* output;
std::vector<Gate*> output_vector;
CipherBit** encrypted_eval_output;
bool* decrypted_eval_output;
for (unsigned long int a_index = 0; a_index < 2; a_index++) {
for (unsigned long int b_index = 0; b_index < 2; b_index++) {
input_a = new Gate(Input, a_index, sec);
input_b = new Gate(Input, b_index, sec);
operation = new Gate(And, input_a, input_b, sec);
output = new Gate(Output, operation, sec);
output_vector.push_back(output);
encrypted_eval_output = fh.evaluate(output_vector, inputs, pk);
decrypted_eval_output = fh.decrypt_bit_vector(sk, encrypted_eval_output, 1);
printf("%u x %u = %u\n", domain[a_index], domain[b_index], decrypted_eval_output[0]);
output_vector.clear();
}
}
printf("--- XOR GATE ---\n");
for (unsigned long int a_index = 0; a_index < 2; a_index++) {
for (unsigned long int b_index = 0; b_index < 2; b_index++) {
input_a = new Gate(Input, a_index, sec);
input_b = new Gate(Input, b_index, sec);
operation = new Gate(Xor, input_a, input_b, sec);
output = new Gate(Output, operation, sec);
output_vector.push_back(output);
encrypted_eval_output = fh.evaluate(output_vector, inputs, pk);
decrypted_eval_output = fh.decrypt_bit_vector(sk, encrypted_eval_output, 1);
printf("%u + %u = %u\n", domain[a_index], domain[b_index], decrypted_eval_output[0]);
output_vector.clear();
}
}
}
void test_circuits(FullyHomomorphic &fh, const PublicKey &pk, const PrivateKey &sk, SecuritySettings *sec) {
printf("----- TESTING EVALUATION OF MORE COMPLEX CIRCUITS -----\n");
printf("--- CIRCUIT 1 ---\n");
int INPUT_LENGTH = 6;
CipherBit** inputs = new CipherBit*[INPUT_LENGTH];
for (int i = 0; i < INPUT_LENGTH; i++) {
inputs[i] = new CipherBit;
}
fh.encrypt_bit(*(inputs[0]), pk, false);
fh.encrypt_bit(*(inputs[1]), pk, true);
fh.encrypt_bit(*(inputs[2]), pk, true);
fh.encrypt_bit(*(inputs[3]), pk, true);
fh.encrypt_bit(*(inputs[4]), pk, true);
fh.encrypt_bit(*(inputs[5]), pk, true);
Gate* input_a;
Gate* input_b;
Gate* input_c;
Gate* operation1;
Gate* operation2;
Gate* operation3;
Gate* operation4;
Gate* operation5;
Gate* output;
std::vector<Gate*> output_vector;
CipherBit** encrypted_eval_output;
bool* decrypted_eval_output;
input_a = new Gate(Input, (unsigned long int)1, sec);
input_b = new Gate(InputLiteral, false, sec);
operation1 = new Gate(And, input_a, input_b, sec);
operation2 = new Gate(And, operation1, input_a, sec);
output = new Gate(Output, operation2, sec);
output_vector.push_back(output);
encrypted_eval_output = fh.evaluate(output_vector, inputs, pk);
decrypted_eval_output = fh.decrypt_bit_vector(sk, encrypted_eval_output, 1);
printf("1 x 0l x 1 = %u\n", decrypted_eval_output[0]);
output_vector.clear();
printf("--- CIRCUIT 2 ---\n");
input_a = new Gate(Input, (unsigned long int)1, sec);
input_b = new Gate(Input, (unsigned long int)2, sec);
input_c = new Gate(Input, (unsigned long int)3, sec);
operation1 = new Gate(And, input_a, input_b, sec);
operation2 = new Gate(And, operation1, input_c, sec);
output = new Gate(Output, operation2, sec);
output_vector.push_back(output);
encrypted_eval_output = fh.evaluate(output_vector, inputs, pk);
decrypted_eval_output = fh.decrypt_bit_vector(sk, encrypted_eval_output, 1);
printf("1 x 1 x 1 = %u\n", decrypted_eval_output[0]);
output_vector.clear();
printf("--- CIRCUIT 3 ---\n");
input_a = new Gate(Input, (unsigned long int)1, sec);
input_b = new Gate(Input, (unsigned long int)1, sec);
input_c = new Gate(Input, (unsigned long int)0, sec);
operation1 = new Gate(And, input_a, input_b, sec);
operation2 = new Gate(And, input_a, input_c, sec);
operation3 = new Gate(And, input_b, input_c, sec);
operation4 = new Gate(Xor, operation1, operation2, sec);
operation5 = new Gate(Xor, operation4, operation3, sec);
output = new Gate(Output, operation5, sec);
output_vector.push_back(output);
fh.is_allowed_circuit(output_vector);
encrypted_eval_output = fh.evaluate(output_vector, inputs, pk);
decrypted_eval_output = fh.decrypt_bit_vector(sk, encrypted_eval_output, 1);
printf("%u\n", decrypted_eval_output[0]);
output_vector.clear();
}
void benchmark(FullyHomomorphic &fh, PublicKey &pk, PrivateKey &sk, SecuritySettings *sec) {
OUTPUT = false;
clock_t start_time = clock();
fh.generate_key_pair(sk, pk);
clock_t key_gen_finished = clock();
printf("Key Generation: %f\n", (double)(key_gen_finished - start_time)/CLOCKS_PER_SEC);
test_encrypt_bit_vector(fh, pk, sk);
clock_t test_encrypt_bit_vector_finished = clock();
printf("Encrypting and decrypting 100 bit vector: %f\n", (double)(test_encrypt_bit_vector_finished - key_gen_finished)/CLOCKS_PER_SEC);
test_encrypt_bit(fh, pk, sk);
clock_t test_encrypt_bit_finished = clock();
printf("Encrypting and decrypting 200 bits: %f\n", (double)(test_encrypt_bit_finished - test_encrypt_bit_vector_finished)/CLOCKS_PER_SEC);
}
int main(int argc, char** argv) {
CryptoPP::AutoSeededRandomPool rng;
SecuritySettings *security_settings = new SecuritySettings(atoi(argv[1]));
FullyHomomorphic fh(security_settings);
PrivateKey sk;
PublicKey pk;
fh.generate_key_pair(sk, pk);
cout << *security_settings << endl;
for (int i = 2; i < argc; i++) {
if (strcmp(argv[i], "-a") == 0 || strcmp(argv[i], "--all") == 0) {
fh.generate_key_pair(sk, pk);
test_encrypt_bit(fh, pk, sk);
test_encrypt_bit_vector(fh, pk, sk);
//fh.test_decryption_circuit(pk, sk);
test_gates(fh, pk, sk, security_settings);
test_circuits(fh, pk, sk, security_settings);
}
if (strcmp(argv[i], "-s") == 0 || strcmp(argv[i], "--single-bit") == 0) {
fh.generate_key_pair(sk, pk);
test_encrypt_bit(fh, pk, sk);
}
if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--bit-vector") == 0) {
fh.generate_key_pair(sk, pk);
test_encrypt_bit_vector(fh, pk, sk);
}
if (strcmp(argv[i], "-dc") == 0 || strcmp(argv[i], "--decryption-circuit") == 0) {
fh.generate_key_pair(sk, pk);
fh.test_decryption_circuit(pk, sk);
}
if (strcmp(argv[i], "-g") == 0 || strcmp(argv[i], "--gates") == 0) {
fh.generate_key_pair(sk, pk);
test_gates(fh, pk, sk, security_settings);
}
if (strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--circuits") == 0) {
fh.generate_key_pair(sk, pk);
test_circuits(fh, pk, sk, security_settings);
}
if (strcmp(argv[i], "-t") == 0 || strcmp(argv[i], "--timing") == 0) {
benchmark(fh, pk, sk, security_settings);
}
}
}
<file_sep>/security_settings.h
#ifndef SECURITY_SETTINGS_H
#define SECURITY_SETTINGS_H
#include <iostream>
#include <cmath>
using namespace std;
class SecuritySettings {
private:
unsigned long int lambda;
public:
unsigned long int gamma;
unsigned long int eta;
unsigned long int rho;
unsigned long int rho_;
unsigned long int tau;
unsigned long int kappa;
unsigned long int theta;
unsigned long int big_theta;
unsigned long int private_key_length;
unsigned long int public_key_old_key_length;
unsigned long int public_key_y_vector_length;
SecuritySettings(unsigned long int lambda);
friend ostream& operator<<(ostream &os, const SecuritySettings &sec);
};
#endif //SECURITY_SETTINGS_H
| 2658a098080c00f32e244fe0a8bb627c9191aeba | [
"C",
"Makefile",
"C++"
] | 10 | C++ | abhishekkumar2718/Simple-Homomorphic-Encryption | 108cfaccef46cac783e1165ce36808511131ec2c | a98fb7d996e61dc4bca8059eb05f9e85ec41da3d |
refs/heads/main | <repo_name>rplumlee/saddle-mtn<file_sep>/src/components/HomeMetrics.jsx
import React from 'react'
import { motion, useAnimation, useTransform, useSpring } from 'framer-motion'
import { useInView } from 'react-intersection-observer'
import { GiAtom, GiHighKick, GiChart } from 'react-icons/gi'
const variants = {
hidden: {
opacity: 0,
scale: 0.5,
},
visible: {
opacity: 1,
scale: 1,
transition: {
staggerChildren: 0.4,
duration: 0.5,
},
},
}
const clip_path_variants = {
open: {
pathLength: 1,
transition: {
duration: 0.4,
},
},
closed: {
pathLength: 0,
},
}
export default function HomeMetrics() {
const [ref, inView, entry] = useInView({ threshold: 1 })
const [ref1, inView1, entry1] = useInView({ threshold: 1 })
const [ref2, inView2, entry2] = useInView({ threshold: 1 })
const animation = useAnimation()
const animation1 = useAnimation()
const animation2 = useAnimation()
React.useEffect(() => {
if (inView) {
animation.start('open')
}
}, [animation, inView])
React.useEffect(() => {
if (inView1) {
animation1.start('open')
}
}, [animation1, inView1])
React.useEffect(() => {
if (inView2) {
animation2.start('open')
}
}, [animation2, inView2])
return (
<div className={`message metrics`}>
<motion.div className="">
<h3>Metrics and KPI's</h3>
<p>
You can’t arm & aim your sales organization without having a clear
and effective core value proposition that differentiates your solution
from your competitors. Many organizations fail to create a
comprehensive messaging framework to be used for internal and external
communications. Without a strong, clear and concise value message,
your sales team will struggle on the phone and in the field to win the
business your company deserves.
</p>
<p>
Saddle Mountain Group will do a deep dive into your current value
messaging and essentially act as a proxy for your target customer.
We’ll “stress test” your current messaging strategy to make sure it
holds up under competitive fire. In addition, SMG will ensure your
core messaging can be conveyed to your sales organization through an
effective toolset.
</p>
</motion.div>
</div>
)
}
<file_sep>/src/pages/index.js
import React from 'react'
import { Link } from 'gatsby'
import get from 'lodash/get'
import { Helmet } from 'react-helmet'
import { graphql } from 'gatsby'
import Layout from '../components/layout'
import Services from '../components/home/Services'
import HomeAbout from '../components/HomeAbout'
import Assessment from '../components/home/Assessment'
import Strategy from '../components/home/Strategy'
import Scalability from '../components/home/Scalability'
import HomeKPIs from '../components/home/KPIs'
import HomeMessage from '../components/HomeMessage'
import HomeTop from '../components/home/Top'
import HomeContact from '../components/HomeContact'
import { rhythm } from '../utils/typography'
import BackgroundImage from 'gatsby-background-image'
import '../styles.scss'
import { useCycle } from 'framer-motion'
class BlogIndex extends React.Component {
render() {
const siteTitle = get(
this,
'props.data.cosmicjsSettings.metadata.site_title'
)
const author = get(this, 'props.data.cosmicjsSettings.metadata')
const location = get(this, 'props.location')
return (
<Layout location={location}>
<Helmet title={siteTitle} />
<HomeTop />
<Services />
<Assessment />
<Strategy />
<Scalability />
<HomeKPIs />
<HomeAbout />
<HomeContact />
</Layout>
)
}
}
export default BlogIndex
export const pageQuery = graphql`
query IndexQuery {
cosmicjsSettings(slug: { eq: "general" }) {
metadata {
site_title
author_name
author_bio
author_avatar {
imgix_url
}
}
}
}
`
<file_sep>/src/components/HomeWWD.jsx
import React from 'react'
import { motion, useAnimation, useViewportScroll } from 'framer-motion'
import { useInView } from 'react-intersection-observer'
import HomeMessage from './HomeMessage'
import HomeMetrics from './HomeMetrics'
import HomeTeam from './HomeTeam'
import { GiAtom, GiHighKick, GiChart } from 'react-icons/gi'
import { BsPeopleCircle, BsPieChart, BsShieldShaded } from 'react-icons/bs'
import { FaChartPie } from 'react-icons/fa'
import {
FcCollaboration,
FcProcess,
FcGenealogy,
FcPositiveDynamic,
FcOpenedFolder,
} from 'react-icons/fc'
import { MdAssessment } from 'react-icons/md'
import useBoop from '../hooks/useboop'
import { useSpring, animated } from 'react-spring'
import AppBar from '@material-ui/core/AppBar'
import Tabs from '@material-ui/core/Tabs'
import Tab from '@material-ui/core/Tab'
import Paper from '@material-ui/core/Paper'
import Box from '@material-ui/core/Box'
import { makeStyles } from '@material-ui/core/styles'
import Fade from '@material-ui/core/Fade'
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
backgroundColor: 'transparent',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
position: 'relative',
maxWidth: '100%',
paddingTop: 0,
},
tabs: {
display: 'inline-flex',
margin: '0px 0 30px 0',
width: '100%',
maxWidth: '100%',
},
tab: {
fontWeight: '700',
width: '33%',
},
box: {
padding: 0,
},
}))
const variants = {
hide: {
opacity: 0,
},
show: {
opacity: 1,
transition: {
delay: 0.2,
},
},
}
function TabPanel(props) {
const { children, value, index, ...other } = props
return (
<div
role="tabpanel"
hidden={value !== index}
id={`vertical-tabpanel-${index}`}
aria-labelledby={`vertical-tab-${index}`}
{...other}
>
{value === index && <Box p={3}>{children}</Box>}
</div>
)
}
export default function HomeWWD() {
const [ref, inView, entry] = useInView({ threshold: 0.1 })
const classes = useStyles()
const animation = useAnimation()
React.useEffect(() => {
if (inView) {
animation.start('visible')
}
}, [animation, inView])
return (
<div className={`theme-bg`} id="wwd">
<div className={'wwd'}>
<motion.ul>
<li className="theme-bg">
<FcOpenedFolder fill="#fff" /> <h5>Assessment</h5>
<p>We analyze your company across it's different organizations.</p>
</li>
<li className="theme-bg">
<FcCollaboration fill="#fff" /> <h5>Strategy</h5>{' '}
<p>We analyze your company across it's different organizations.</p>
</li>
<li className="theme-bg">
<FcProcess fill="#fff" />
<h5>Scalability/Process Improvement</h5>{' '}
<p>We analyze your company across it's different organizations.</p>
</li>
<li className="theme-bg">
<FcPositiveDynamic fill="#fff" />
<h5>Performance Measurement/KPIs</h5>{' '}
<p>We analyze your company across it's different organizations.</p>
</li>
</motion.ul>
</div>
</div>
)
}
<file_sep>/src/components/HomeContact.jsx
import React from 'react'
import { motion, useAnimation, useTransform, useSpring } from 'framer-motion'
import { useInView } from 'react-intersection-observer'
import { GiAtom, GiHighKick, GiChart } from 'react-icons/gi'
import Button from '@material-ui/core/Button'
const variants = {
hidden: {
opacity: 0,
scale: 0.5,
},
visible: {
opacity: 1,
scale: 1,
transition: {
staggerChildren: 0.4,
duration: 0.5,
},
},
}
const clip_path_variants = {
open: {
pathLength: 1,
transition: {
duration: 0.4,
},
},
closed: {
pathLength: 0,
},
}
export default function HomeContact() {
return (
<>
{' '}
<div className="shape4 theme-bg"></div>
<div className="shape5 theme-bg-tertiary"></div>
<div className={`contact theme-bg`} id="contact">
<h2>Get in touch</h2>
<p>
<Button
href="mailto:<EMAIL>"
color="primary"
size="large"
className="theme-text"
style={{
padding: '12px 30px',
marginTop: 20,
marginLeft: 20,
fontWeight: 500,
background: 'rgba(125,125,125,.1)',
textTransform: 'none',
}}
>
<EMAIL>
</Button>
</p>
</div>
</>
)
}
<file_sep>/src/components/layout.js
import React from 'react'
import ReactDOM from 'react-dom'
import { Link } from 'gatsby'
import { StaticQuery, graphql } from 'gatsby'
import BackgroundImage from 'gatsby-background-image'
import Image from 'gatsby-image'
import {
motion,
useMotionValue,
animate,
useAnimation,
useCycle,
} from 'framer-motion'
import { useLocalStorageState } from '../hooks/useLocalStorage'
import { rhythm, scale } from '../utils/typography'
import { useSpring, animated } from 'react-spring'
import { RiMoonClearFill } from 'react-icons/ri'
import Password from './Password'
import Header from './Header'
import MobileMenu from './MobileMenu'
// Import typefaces
import 'typeface-montserrat'
import 'typeface-merriweather'
import 'typeface-lato'
export const ThemeContext = React.createContext()
export default function Layout({ children, location }) {
return (
<StaticQuery
query={graphql`
query LayoutQuery {
cosmicjsSettings(slug: { eq: "general" }) {
metadata {
site_heading
homepage_hero {
local {
childImageSharp {
fluid(quality: 99, maxWidth: 5000) {
...GatsbyImageSharpFluid_withWebp
}
}
}
}
}
}
}
`}
render={(data) => {
const [colorMode, toggleColorMode] = useCycle('dark', 'light')
const [allowed, setAllowed] = useLocalStorageState('SMG_DEV')
const [openMobile, toggleOpenMobile] = useCycle(false, true)
const siteTitle = data.cosmicjsSettings.metadata.site_heading
const homgePageHero =
data.cosmicjsSettings.metadata.homepage_hero.local.childImageSharp
.fluid
return (
<ThemeContext.Provider value={{ colorMode }}>
<div className={`theme-${colorMode}`}>
<Header
colorMode={colorMode}
toggleColorMode={toggleColorMode}
openMobile={openMobile}
toggleOpenMobile={toggleOpenMobile}
/>
{allowed === 'bingo!' ? (
<>
<div className="site-body">{children}</div>
<footer
style={{
textAlign: 'center',
padding: 0,
}}
></footer>
</>
) : (
<Password setAllowed={setAllowed} />
)}
<MobileMenu
colorMode={colorMode}
toggleColorMode={toggleColorMode}
openMobile={openMobile}
toggleOpenMobile={toggleOpenMobile}
/>
</div>
</ThemeContext.Provider>
)
}}
/>
)
}
<file_sep>/src/components/home/KPIs.jsx
import React from 'react'
import { motion, useAnimation, useViewportScroll } from 'framer-motion'
import { useInView } from 'react-intersection-observer'
import useBoop from '../../hooks/useboop'
import { useSpring, animated } from 'react-spring'
import {
FcCollaboration,
FcConferenceCall,
FcProcess,
FcGenealogy,
FcComboChart,
FcAlphabeticalSortingZa,
FcBiotech,
FcAdvance,
} from 'react-icons/fc'
const variants = {
hide: {
opacity: 0,
},
show: {
opacity: 1,
transition: {
delay: 0.2,
},
},
}
function TabPanel(props) {
const { children, value, index, ...other } = props
return (
<div
role="tabpanel"
hidden={value !== index}
id={`vertical-tabpanel-${index}`}
aria-labelledby={`vertical-tab-${index}`}
{...other}
>
{value === index && <Box p={3}>{children}</Box>}
</div>
)
}
export default function HomeKPIs() {
const [ref, inView, entry] = useInView({ threshold: 0.1 })
const [selected, setSelected] = React.useState(0)
const [stickyNav, setStickyNav] = React.useState(false)
const stickyRef = React.useRef(null)
const animation = useAnimation()
const { scrollY } = useViewportScroll()
return (
<div className={`theme-bg`} id="kpis">
{/* <svg
viewbox="0 0 1600 360"
style={{
position: 'absolute',
top: 0,
left: 0,
zIndex: 1,
width: '100%',
height: '3px',
}}
>
<rect width="1600" height="360" fill="url(#linear)"></rect>
</svg> */}
<div className={`strategy container`}>
<motion.div className="assessment-container">
<div>
<h2>
Performance Measurement/KPIs <FcComboChart />
</h2>
<p
style={{
margin: '20px 0 50px auto',
width: 800,
maxWidth: '100%',
}}
>
SMG strongly subscribes the basic business tenant: “you can’t
manage what you can’t measure”. Establishing clear and measurable
performance criteria provides the validation necessary to confirm
the proper strategy and tactics are in place and working. SMG
offers a comprehensive set of reporting metrics/KPIs to give your
team real-time feedback on these performance areas:
</p>
</div>
</motion.div>
</div>
</div>
)
}
<file_sep>/src/components/home/Scalability.jsx
import React from 'react'
import { motion, useAnimation, useViewportScroll } from 'framer-motion'
import { useInView } from 'react-intersection-observer'
import { GiAtom, GiHighKick, GiChart } from 'react-icons/gi'
import { BsPeopleCircle, BsPieChart, BsShieldShaded } from 'react-icons/bs'
import { FaChartPie } from 'react-icons/fa'
import useBoop from '../../hooks/useboop'
import { useSpring, animated } from 'react-spring'
import {
FcCollaboration,
FcConferenceCall,
FcProcess,
FcGenealogy,
FcComboChart,
FcAlphabeticalSortingZa,
FcBiotech,
FcAdvance,
} from 'react-icons/fc'
const variants = {
hide: {
opacity: 0,
},
show: {
opacity: 1,
transition: {
delay: 0.2,
},
},
}
function TabPanel(props) {
const { children, value, index, ...other } = props
return (
<div
role="tabpanel"
hidden={value !== index}
id={`vertical-tabpanel-${index}`}
aria-labelledby={`vertical-tab-${index}`}
{...other}
>
{value === index && <Box p={3}>{children}</Box>}
</div>
)
}
export default function Scalability() {
const [ref, inView, entry] = useInView({ threshold: 0.1 })
const [selected, setSelected] = React.useState(0)
const [stickyNav, setStickyNav] = React.useState(false)
const stickyRef = React.useRef(null)
const animation = useAnimation()
const { scrollY } = useViewportScroll()
return (
<div className={`theme-bg-secondary`}>
<div className={`philosophy container`} id="scalability">
<motion.div className="assessment-container">
<div>
<h2>
<FcConferenceCall />
Scalability & Process Improvement
</h2>
<p
style={{
margin: '20px 0 50px 0',
}}
>
SMG helps transform strategy into measurable results through a
focus on process improvement. Changing organizational processes
can be difficult without the right playbook and coaching. SMG
helps ensure success though the following services:
</p>
</div>
</motion.div>
</div>
</div>
)
}
<file_sep>/src/components/home/Top.js
import React from 'react'
import ReactDOM from 'react-dom'
import { Link } from 'gatsby'
import { StaticQuery, graphql } from 'gatsby'
import BackgroundImage from 'gatsby-background-image'
import Image from 'gatsby-image'
import { motion, useMotionValue, animate, useAnimation } from 'framer-motion'
import { BsArrowDown } from 'react-icons/bs'
import { rhythm, scale } from '../../utils/typography'
import Button from '@material-ui/core/Button'
import ThemeContext from '../layout'
import Particles from 'react-particles-js'
import { GiPerson } from 'react-icons/gi'
import AnchorLink from 'react-anchor-link-smooth-scroll'
// Import typefaces
import 'typeface-montserrat'
import 'typeface-merriweather'
import 'typeface-lato'
const waves = [
'M0,160L30,149.3C60,139,120,117,180,128C240,139,300,181,360,176C420,171,480,117,540,106.7C600,96,660,128,720,154.7C780,181,840,203,900,197.3C960,192,1020,160,1080,138.7C1140,117,1200,107,1260,96C1320,85,1380,75,1410,69.3L1440,64L1440,0L1410,0C1380,0,1320,0,1260,0C1200,0,1140,0,1080,0C1020,0,960,0,900,0C840,0,780,0,720,0C660,0,600,0,540,0C480,0,420,0,360,0C300,0,240,0,180,0C120,0,60,0,30,0L0,0Z',
'M0,160L30,181.3C60,203,120,245,180,261.3C240,277,300,267,360,234.7C420,203,480,149,540,149.3C600,149,660,203,720,224C780,245,840,235,900,224C960,213,1020,203,1080,165.3C1140,128,1200,64,1260,48C1320,32,1380,64,1410,80L1440,96L1440,0L1410,0C1380,0,1320,0,1260,0C1200,0,1140,0,1080,0C1020,0,960,0,900,0C840,0,780,0,720,0C660,0,600,0,540,0C480,0,420,0,360,0C300,0,240,0,180,0C120,0,60,0,30,0L0,0Z',
'M0,256L30,261.3C60,267,120,277,180,277.3C240,277,300,267,360,250.7C420,235,480,213,540,218.7C600,224,660,256,720,245.3C780,235,840,181,900,154.7C960,128,1020,128,1080,149.3C1140,171,1200,213,1260,202.7C1320,192,1380,128,1410,96L1440,64L1440,0L1410,0C1380,0,1320,0,1260,0C1200,0,1140,0,1080,0C1020,0,960,0,900,0C840,0,780,0,720,0C660,0,600,0,540,0C480,0,420,0,360,0C300,0,240,0,180,0C120,0,60,0,30,0L0,0Z',
'M0,224L30,234.7C60,245,120,267,180,256C240,245,300,203,360,176C420,149,480,139,540,138.7C600,139,660,149,720,165.3C780,181,840,203,900,176C960,149,1020,75,1080,69.3C1140,64,1200,128,1260,154.7C1320,181,1380,171,1410,165.3L1440,160L1440,0L1410,0C1380,0,1320,0,1260,0C1200,0,1140,0,1080,0C1020,0,960,0,900,0C840,0,780,0,720,0C660,0,600,0,540,0C480,0,420,0,360,0C300,0,240,0,180,0C120,0,60,0,30,0L0,0Z',
'M0,224L30,218.7C60,213,120,203,180,213.3C240,224,300,256,360,229.3C420,203,480,117,540,106.7C600,96,660,160,720,186.7C780,213,840,203,900,218.7C960,235,1020,277,1080,250.7C1140,224,1200,128,1260,74.7C1320,21,1380,11,1410,5.3L1440,0L1440,0L1410,0C1380,0,1320,0,1260,0C1200,0,1140,0,1080,0C1020,0,960,0,900,0C840,0,780,0,720,0C660,0,600,0,540,0C480,0,420,0,360,0C300,0,240,0,180,0C120,0,60,0,30,0L0,0Z',
'M0,192L30,197.3C60,203,120,213,180,224C240,235,300,245,360,234.7C420,224,480,192,540,202.7C600,213,660,267,720,277.3C780,288,840,256,900,240C960,224,1020,224,1080,208C1140,192,1200,160,1260,154.7C1320,149,1380,171,1410,181.3L1440,192L1440,0L1410,0C1380,0,1320,0,1260,0C1200,0,1140,0,1080,0C1020,0,960,0,900,0C840,0,780,0,720,0C660,0,600,0,540,0C480,0,420,0,360,0C300,0,240,0,180,0C120,0,60,0,30,0L0,0Z',
]
function getRandomInt(max, notAllowed) {
return Math.floor(Math.random() * Math.floor(max))
}
const bg_variants = {
start: {
d:
'M 0 0 L 0 500 Q 150 550 200 450 Q 300 200 450 350 C 600 400 600 100 800 250 L 800 0',
},
finish: {
d:
'M 0 0 L 0 500 Q 100 400 200 450 Q 400 600 550 450 C 650 300 600 100 800 150 L 800 0',
},
}
const variants = {
hidden: {
opacity: 0,
y: 50,
},
visible: {
opacity: 1,
y: 0,
transition: {
staggerChildren: 2,
duration: 1.5,
delay: 0.7,
},
},
}
const ids = [
'marketPath',
'exact',
'cty',
'eby',
'fact',
'ifttt',
'pg',
'find',
'cnet',
'bbye',
'cow',
'hack',
]
export default function HomeTop({ children, location }) {
const [activePath, setActivePath] = React.useState('find')
React.useEffect(() => {
setInterval(() => {
const randomItem = ids[Math.floor(Math.random() * ids.length)]
setActivePath(randomItem)
}, 3500)
return clearInterval()
}, [])
return (
<div
className="theme-bg"
style={{ overflow: 'hidden', maxWidth: '100%', position: 'relative' }}
>
{' '}
<div
className="bg"
style={{
position: 'absolute',
zIndex: 6,
top: 0,
left: 0,
width: '100%',
transformOrigin: 'center center',
}}
>
<svg viewBox="0 0 1440 520">
<defs>
<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
<stop
offset="0%"
style={{ stopColor: 'purple', stopOpacity: 1 }}
/>
<stop
offset="100%"
style={{ stopColor: '#a01aed', stopOpacity: 1 }}
/>
</linearGradient>
<linearGradient id="linear" x1="0%" y1="0%" x2="100%" y2="50%">
<motion.stop
stopColor="#04bd7f"
animate={{
stopColor: ['#04bd7f', '#FF7744', '#4d3e96'],
}}
transition={{
yoyo: Infinity,
ease: 'linear',
duration: 8,
}}
offset="25%"
/>
<motion.stop
stopColor="#BF5FFF"
animate={{
stopColor: ['#BF5FFF', '#FFC6A8', '#FF7744', '#5f41f2'],
}}
transition={{
yoyo: Infinity,
ease: 'linear',
duration: 8,
}}
offset="50%"
/>
<motion.stop
stopColor="#5f41f2"
animate={{
stopColor: ['#5f41f2', '#BF5FFF'],
}}
transition={{
yoyo: Infinity,
ease: 'linear',
duration: 8,
}}
offset="75%"
/>
<motion.stop
stopColor="#D4504C"
animate={{
stopColor: ['#D4504C', '#5f41f2', '#f7d319'],
}}
transition={{
yoyo: Infinity,
ease: 'linear',
duration: 8,
}}
offset="100%"
/>
</linearGradient>
</defs>
{waves.map((wave, index) => {
return (
<motion.path
d={`${wave}`}
variants={bg_variants}
initial={{ d: `${wave}` }}
animate={{ d: `${waves[5 - index]}` }}
fillOpacity="0.7"
fill="url(#linear)"
transition={{
repeat: Infinity,
repeatType: 'reverse',
duration: 3 + index,
}}
key={`${index}-wave`}
/>
)
})}
</svg>
</div>
<div className="infographic-container">
<h1
style={{
textAlign: 'center',
margin: '0 auto',
zIndex: 2,
position: 'relative',
maxWidth: 800,
}}
>
Strategic Advisors to Emerging Tech Organizations
</h1>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
marginBottom: 50,
}}
>
<AnchorLink href="#contact" offset="-100">
<Button
href="#"
variant="contained"
color="primary"
size="large"
className={''}
style={{
padding: '12px 30px',
marginTop: 20,
fontWeight: 500,
boxShadow: 'none',
background: 'rgba(0,0,0,.04)',
overflow: 'hidden',
fontWeight: 600,
color: '#fff',
}}
>
Get in touch
<svg
viewbox="0 0 580 160"
style={{
position: 'absolute',
bottom: 0,
right: 0,
zIndex: -1,
}}
>
<rect
width="580"
height="160"
fill="url(#linear)"
style={{ borderRadius: 5 }}
></rect>
</svg>
</Button>
</AnchorLink>
<AnchorLink href="#servicess" id="wwdButton">
<Button
href="#text-buttons"
color="primary"
size="large"
className="theme-text flat-button"
style={{
padding: '12px 30px',
marginTop: 20,
marginLeft: 20,
fontWeight: 600,
background: 'rgba(125,125,125,0)',
}}
>
What We Do <BsArrowDown />
</Button>
</AnchorLink>
</div>
</div>
</div>
)
}
<file_sep>/src/components/home/Strategy.jsx
import React from 'react'
import { motion, useAnimation, useViewportScroll } from 'framer-motion'
import { useInView } from 'react-intersection-observer'
import Particles from 'react-particles-js'
import useBoop from '../../hooks/useboop'
import { useSpring, animated } from 'react-spring'
import {
FcCollaboration,
FcConferenceCall,
FcProcess,
FcGenealogy,
FcComboChart,
FcAlphabeticalSortingZa,
FcBiotech,
FcAdvance,
} from 'react-icons/fc'
const variants = {
hide: {
opacity: 0,
},
show: {
opacity: 1,
transition: {
delay: 0.2,
},
},
}
function TabPanel(props) {
const { children, value, index, ...other } = props
return (
<div
role="tabpanel"
hidden={value !== index}
id={`vertical-tabpanel-${index}`}
aria-labelledby={`vertical-tab-${index}`}
{...other}
>
{value === index && <Box p={3}>{children}</Box>}
</div>
)
}
export default function Strategy() {
const [ref, inView, entry] = useInView({ threshold: 0.1 })
const [selected, setSelected] = React.useState(0)
const [stickyNav, setStickyNav] = React.useState(false)
const stickyRef = React.useRef(null)
const animation = useAnimation()
const { scrollY } = useViewportScroll()
return (
<div className={`theme-bg`} id="strategy" style={{ paddingBottom: 100 }}>
{/* <svg
viewbox="0 0 1600 360"
style={{
position: 'absolute',
top: 0,
left: 0,
zIndex: 1,
width: '100%',
height: '3px',
}}
>
<rect width="1600" height="360" fill="url(#linear)"></rect>
</svg> */}
<div className={`strategy container`}>
<motion.div
className="assessment-container"
style={{ textAlign: 'right' }}
>
<div>
<h1 style={{ justifyContent: 'flex-end' }}>Strategy Development</h1>
<p
style={{
margin: '10px 0 50px auto',
width: 800,
maxWidth: '100%',
}}
>
Once areas of improvement have been identified, SMG acts as a
trusted advisor and sounding board to help craft a more cohesive
and scalable strategy for next-level growth. Building a
sustainable strategy involves deep dialogue and collaboration
between SMG and the client, always using data to inform direction.
Strategic services include:
</p>
</div>
</motion.div>
</div>
</div>
)
}
<file_sep>/src/components/Header.jsx
import React from 'react'
import { motion } from 'framer-motion'
import useBoop from '../hooks/useboop'
import DarkToggle from './DarkToggle'
import Logo from './Logo'
import LogoTest from './LogoTest'
import { useSpring, animated } from 'react-spring'
import AnchorLink from 'react-anchor-link-smooth-scroll'
const Boop = ({ children, ...boopConfig }) => {
const [style, trigger] = useBoop({ rotation: 10 })
return (
<animated.div onMouseEnter={trigger} style={style}>
{children}
</animated.div>
)
}
const TextBoop = ({ children, ...boopConfig }) => {
const [style, trigger] = useBoop({
y: -2,
springConfig: { tension: 500 },
})
return (
<animated.div onMouseEnter={trigger} style={style}>
{children}
</animated.div>
)
}
function Header({ colorMode, toggleColorMode, openMobile, toggleOpenMobile }) {
return (
<div id="head-wrap">
<header className="">
<div className="header-logo " style={{ cursor: 'default' }}>
<LogoTest />
</div>
<ul className="header-menu">
<li>
<TextBoop>
<AnchorLink href="#assessment" offset="-100">
Assessment
</AnchorLink>
</TextBoop>
</li>
<li>
<TextBoop>
<AnchorLink href="#strategy" offset="-100">
Strategy
</AnchorLink>
</TextBoop>
</li>
<li>
<TextBoop>
<AnchorLink href="#scalability" offset="-100">
Scalability
</AnchorLink>
</TextBoop>
</li>
<li>
<TextBoop>
<AnchorLink href="#kpis" offset="-100">
KPI's
</AnchorLink>
</TextBoop>
</li>
<li>
<TextBoop>
<AnchorLink href="#leadership">About</AnchorLink>
</TextBoop>
</li>{' '}
<li>
<TextBoop>
<AnchorLink href="#contact">Contact</AnchorLink>
</TextBoop>
</li>
<li>
<DarkToggle
colorMode={colorMode}
toggleColorMode={toggleColorMode}
/>
</li>
</ul>
</header>
<a href="#" onClick={() => toggleOpenMobile()} id="mobile-toggle">
<svg
viewBox="0 0 100 100"
width="50"
className={
openMobile
? 'ham hamRotate ham1 active theme-stroke'
: 'ham hamRotate ham1 theme-stroke'
}
>
<path
className="line top"
d="m 30,33 h 40 c 0,0 9.044436,-0.654587 9.044436,-8.508902 0,-7.854315 -8.024349,-11.958003 -14.89975,-10.85914 -6.875401,1.098863 -13.637059,4.171617 -13.637059,16.368042 v 40"
/>
<path className="line middle" d="m 30,50 h 40" />
<path
className="line bottom"
d="m 30,67 h 40 c 12.796276,0 15.357889,-11.717785 15.357889,-26.851538 0,-15.133752 -4.786586,-27.274118 -16.667516,-27.274118 -11.88093,0 -18.499247,6.994427 -18.435284,17.125656 l 0.252538,40"
/>
</svg>
</a>
</div>
)
}
export default Header
<file_sep>/src/components/HomeMessage.jsx
import React from 'react'
import { motion, useAnimation, useTransform, useSpring } from 'framer-motion'
import { useInView } from 'react-intersection-observer'
import { GiAtom, GiHighKick, GiChart } from 'react-icons/gi'
const variants = {
hidden: {
opacity: 0,
scale: 0.5,
},
visible: {
opacity: 1,
scale: 1,
transition: {
staggerChildren: 0.4,
duration: 0.5,
},
},
}
const clip_path_variants = {
open: (i) => ({
pathLength: [0, 1, 1, 1, 1, 1, 1, 1, 1, 1],
opacity: [0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0],
transition: {
duration: 5,
delay: i,
repeat: Infinity,
},
}),
closed: (i) => ({
opacity: 0,
pathLength: 0,
}),
}
export default function HomeMessage() {
const [ref, inView, entry] = useInView({ threshold: 1 })
const animation1 = useAnimation()
React.useEffect(() => {
if (inView) {
animation1.start('open')
}
}, [animation1, inView])
return (
<div className={`message`}>
<motion.div className="">
<h3>Optimizing Core Value Messaging</h3>
<p>
You can’t arm & aim your sales organization without having a clear
and effective core value proposition that differentiates your solution
from your competitors. Many organizations fail to create a
comprehensive messaging framework to be used for internal and external
communications. Without a strong, clear and concise value message,
your sales team will struggle on the phone and in the field to win the
business your company deserves.
</p>
<ol>
<li>
<div className="card theme-bg-secondary">
Evaluate & Assess Current Value Message
</div>
<div className="shape theme-bg-secondary"></div>
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
width="30"
strokeWidth="2"
>
<motion.path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
stroke="url(#gradient)"
d="M17 8l4 4m0 0l-4 4m4-4H3"
variants={clip_path_variants}
initial={'closed'}
animate={animation1}
custom={0.3}
/>
</svg>
</li>
<li>
<div className="card theme-bg-secondary">
Recraft & Refine Value Messaging
</div>
<div className="shape theme-bg-secondary"></div>
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
width="30"
strokeWidth="2"
>
<motion.path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
stroke="url(#gradient)"
d="M17 8l4 4m0 0l-4 4m4-4H3"
variants={clip_path_variants}
initial={'closed'}
animate={animation1}
custom={0.8}
/>
</svg>
</li>
<li>
<div className="card theme-bg-secondary">Deploy to Sales Org.</div>
<div className="shape theme-bg-secondary"></div>
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
width="30"
strokeWidth="2"
>
<motion.path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
stroke="url(#gradient)"
d="M17 8l4 4m0 0l-4 4m4-4H3"
variants={clip_path_variants}
initial={'closed'}
animate={animation1}
custom={1.3}
/>
</svg>
</li>
<li>
<div className="shape theme-bg-secondary"></div>
<div className="card theme-bg-secondary">
Measure & Validate Effectiveness
</div>
</li>
</ol>
<p ref={ref}>
Saddle Mountain Group will do a deep dive into your current value
messaging and essentially act as a proxy for your target customer.
We’ll “stress test” your current messaging strategy to make sure it
holds up under competitive fire. In addition, SMG will ensure your
core messaging can be conveyed to your sales organization through an
effective toolset.
</p>
</motion.div>
</div>
)
}
| 6f5792bd536790d4b9e2724ebd416833b5e7d3b6 | [
"JavaScript"
] | 11 | JavaScript | rplumlee/saddle-mtn | 66b38a3b4c5ca6dba0a85f369944c3ebbd3edd56 | ec3cacceed742bf6f54c490d45953372863cbac2 |
refs/heads/master | <repo_name>kivra/gulp-git-rev<file_sep>/test/gulp-git-rev-spec.js
var mocha = require('mocha')
, gulp = require('gulp')
, through = require('through2')
, File = require('vinyl')
, es = require('event-stream')
, expect = require('expect.js');
var plugin = require('../lib/gulp-git-rev');
describe('module', function() {
it('exports gulp plugin', function() {
expect(plugin).to.be.a('function');
});
});
describe('plugin', function() {
it('should output proper json', function(done) {
var stream = plugin('test-file.json');
stream.on('data', function(file) {
// Confirm that file gets correct content
file.contents.on('data', function (chunk) {
var obj = JSON.parse(chunk.toString());
expect(obj.hash).to.match(/[0-9a-z]{40}/);
expect(obj.tag).to.be.a('string');
expect(obj.branch).to.be.a('string');
})
})
.on('end', function() {
done();
});
});
});
<file_sep>/lib/gulp-git-rev.js
var through = require('through2');
var git = require('git-rev')
var each = require('async-each')
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
// constsx2
const PLUGIN_NAME = 'gulp-git-release';
function writeReleaseToStream(cb) {
var stream = through();
function getRevPart (method, next) {
git[method](function (res) {
next(null, res);
});
}
var fields = [{
name: 'hash',
method: 'long'
}, {
name: 'tag',
method: 'tag'
}, {
name: 'branch',
method: 'branch'
}]
each(
fields.map(function (obj) {
return obj.method;
}),
getRevPart,
function (err, res) {
if (err) {
throw new PluginError(PLUGIN_NAME, 'Error getting git rev!' + err.toString());
}
var out = {};
res.forEach(function (val, i) {
out[fields[i].name] = val;
});
out = JSON.stringify(out);
stream.write(out);
gutil.log('wrote git rev version: ' + out);
cb();
}
);
return stream;
}
// plugin level function (dealing with files)
function gulpReleaseGen(filename) {
var file = new gutil.File({
cwd: "",
base: "",
path: filename
});
// creating a stream through which each file will pass
var stream = through.obj(function (file, enc, cb) {
// define the streamer that will transform the content
var streamer = writeReleaseToStream(cb);
// catch errors from the streamer and emit a gulp plugin error
streamer.on('error', this.emit.bind(this, 'error'));
// start the transformation
file.contents = streamer;
// make sure the file goes through the next gulp plugin
this.push(file);
});
stream.write(file);
stream.end();
// returning the file stream
return stream;
}
// exporting the plugin main function
module.exports = gulpReleaseGen;
<file_sep>/README.md
# gulp-git-rev
Create git release object and insert into the Gulp pipeline
### Install
``` bash
npm install gulp-git-rev --save
```
### Usage
``` javascript
var release = require('gulp-git-rev.js');
// Create release.json
gulp.task('release', function () {
return release('release.json')
.pipe(gulp.dest('dist')); // dir to put fil in
});
```
| 69826c419578548e73470b49336263bf6ae27949 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | kivra/gulp-git-rev | cb5f363e93f432d20ac367d182ec1955621ed729 | f0bd5a6cd1839032d0bb9e2830f10375daadc4b0 |
refs/heads/master | <repo_name>bfjia/CPO_Prediction<file_sep>/M2_pipeline_tree.py
#!/home/jjjjia/.conda/envs/py36/bin/python
#$ -S /home/jjjjia/.conda/envs/py36/bin/python
#$ -V # Pass environment variables to the job
#$ -N CPO_pipeline # Replace with a more specific job name
#$ -wd /home/jjjjia/testCases # Use the current working dir
#$ -pe smp 1 # Parallel Environment (how many cores)
#$ -l h_vmem=11G # Memory (RAM) allocation *per core*
#$ -e ./logs/$JOB_ID.err
#$ -o ./logs/$JOB_ID.log
#$ -m ea
#$ -M <EMAIL>
#This script is a wrapper for module two, part 2: tree rendering of the cpo_workflow to render dendrograms. It uses snippy for core genome SNV calling and alignment, clustalw to generate a NJ tree and ete3 to render the dendrogram
# >python cpo_galaxy_tree.py -t /path/to/tree.ph -d /path/to/distance/matrix -m /path/to/metadata
# <requirements>
# <requirement type="package" version="0.23.4">pandas</requirement>
# <requirement type="package" version="3.6">python</requirement>
# <requirement type="package" version="3.1.1">ete3</requirement>
# <requirement type="package" version="5.6.0">pyqt</requirement>
# <requirement type="package" version="5.6.2">qt</requirement>
# </requirements>
import subprocess
import pandas #conda pandas
import optparse
import os
os.environ['QT_QPA_PLATFORM']='offscreen'
import datetime
import sys
import time
import urllib.request
import gzip
import collections
import json
import numpy #conda numpy
import ete3 as e #conda ete3 3.1.1**** >requires pyqt5
#parses some parameters
parser = optparse.OptionParser("Usage: %prog [options] arg1 arg2 ...")
parser.add_option("-t", "--tree", dest="treePath", type="string", default="./pipelineTest/tree.txt", help="absolute file path to phylip tree")
parser.add_option("-d", "--distance", dest="distancePath", type="string", default="./pipelineTest/dist.tabular", help="absolute file path to distance matrix")
parser.add_option("-m", "--metadata", dest="metadataPath", type="string", default="./pipelineTest/metadata.tabular",help="absolute file path to metadata file")
parser.add_option("-o", "--output_file", dest="outputFile", type="string", default="tree.png", help="Output graphics file. Use ending 'png', 'pdf' or 'svg' to specify file format.")
# sensitive data adder
parser.add_option("-p", "--sensitive_data", dest="sensitivePath", type="string", default="", help="Spreadsheet (CSV) with sensitive metadata")
parser.add_option("-c", "--sensitive_cols", dest="sensitiveCols", type="string", default="", help="CSV list of column names from sensitive metadata spreadsheet to use as labels on dendrogram")
parser.add_option("-b", "--bcid_column", dest="bcidCol", type="string", default="BCID", help="Column name of BCID in sensitive metadata file")
parser.add_option("-n", "--missing_value", dest="naValue", type="string", default="NA", help="Value to write for missing data.")
(options,args) = parser.parse_args()
treePath = str(options.treePath).lstrip().rstrip()
distancePath = str(options.distancePath).lstrip().rstrip()
metadataPath = str(options.metadataPath).lstrip().rstrip()
sensitivePath = str(options.sensitivePath).lstrip().rstrip()
sensitiveCols = str(options.sensitiveCols).lstrip().rstrip()
outputFile = str(options.outputFile).lstrip().rstrip()
bcidCol = str( str(options.bcidCol).lstrip().rstrip() )
naValue = str( str(options.naValue).lstrip().rstrip() )
#region result objects
#define some objects to store values from results
#//TODO this is not the proper way of get/set private object variables. every value has manually assigned defaults intead of specified in init(). Also, use property(def getVar, def setVar).
class SensitiveMetadata(object):
def __init__(self):
x = pandas.read_csv( sensitivePath )
col_names = [ s for s in sensitiveCols.split(',')] # convert to 0 offset
if not bcidCol in col_names:
col_names.append( bcidCol )
all_cols = [ str(col) for col in x.columns ]
col_idxs = [ all_cols.index(col) for col in col_names ]
self.sensitive_data = x.iloc[:, col_idxs]
def get_columns(self):
cols = [ str(x) for x in self.sensitive_data.columns ]
return cols
def get_value( self, bcid, column_name ): # might be nice to get them all in single call via an input list of bcids ... for later
bcids= list( self.sensitive_data.loc[:, bcidCol ] ) # get the list of all BCIDs in sensitive metadata
if not bcid in bcids:
return naValue
else:
row_idx = bcids.index( bcid ) # lookup the row for this BCID
return self.sensitive_data.loc[ row_idx, column_name ] # return the one value based on the column (col_idx) and this row
class workflowResult(object):
def __init__(self):
self.new = False
self.ID = "?"
self.ExpectedSpecies = "?"
self.MLSTSpecies = "?"
self.SequenceType = "?"
self.MLSTScheme = "?"
self.CarbapenemResistanceGenes ="?"
self.plasmidBestMatch ="?"
self.plasmididentity =-1
self.plasmidsharedhashes ="?"
self.OtherAMRGenes="?"
self.TotalPlasmids = -1
self.plasmids = []
self.DefinitelyPlasmidContigs ="?"
self.LikelyPlasmidContigs="?"
self.row = ""
class plasmidObj(object):
def __init__(self):
self.PlasmidsID = 0
self.Num_Contigs = 0
self.PlasmidLength = 0
self.PlasmidRepType = ""
self.PlasmidMobility = ""
self.NearestReference = ""
#endregion
#region useful functions
def read(path): #read in a text file to a list
return [line.rstrip('\n') for line in open(path)]
def execute(command): #subprocess.popen call bash command
process = subprocess.Popen(command, shell=False, cwd=curDir, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
# Poll process for new output until finished
while True:
nextline = process.stdout.readline()
if nextline == '' and process.poll() is not None:
break
sys.stdout.write(nextline)
sys.stdout.flush()
output = process.communicate()[0]
exitCode = process.returncode
if (exitCode == 0):
return output
else:
raise subprocess.CalledProcessError(exitCode, command)
def httpGetFile(url, filepath=""): #download a file from the web
if (filepath == ""):
return urllib.request.urlretrieve(url)
else:
urllib.request.urlretrieve(url, filepath)
return True
def gunzip(inputpath="", outputpath=""): #gunzip
if (outputpath == ""):
with gzip.open(inputpath, 'rb') as f:
gzContent = f.read()
return gzContent
else:
with gzip.open(inputpath, 'rb') as f:
gzContent = f.read()
with open(outputpath, 'wb') as out:
out.write(gzContent)
return True
def addFace(name): #function to add a facet to a tree
#if its the reference branch, populate the faces with column headers
face = e.faces.TextFace(name,fsize=10,tight_text=True)
face.border.margin = 5
face.margin_right = 5
face.margin_left = 5
return face
#endregion
#region functions to parse result files
def ParseWorkflowResults(pathToResult):
_worflowResult = {}
r = pandas.read_csv(pathToResult, delimiter='\t', header=0)
r = r.replace(numpy.nan, '', regex=True)
_naResult = workflowResult()
_worflowResult["na"] = _naResult
for i in range(len(r.index)):
_results = workflowResult()
if(str(r.loc[r.index[i], 'new']).lower() == "new"):
_results.new = True
else:
_results.new = False
_results.ID = str(r.loc[r.index[i], 'ID']).replace(".fa","")
_results.ExpectedSpecies = str(r.loc[r.index[i], 'Expected Species'])
_results.MLSTSpecies = str(r.loc[r.index[i], 'MLST Species'])
_results.SequenceType = str(r.loc[r.index[i], 'Sequence Type'])
_results.MLSTScheme = (str(r.loc[r.index[i], 'MLST Scheme']))
_results.CarbapenemResistanceGenes = (str(r.loc[r.index[i], 'Carbapenem Resistance Genes']))
_results.OtherAMRGenes = (str(r.loc[r.index[i], 'Other AMR Genes']))
_results.TotalPlasmids = int(r.loc[r.index[i], 'Total Plasmids'])
_results.plasmidBestMatch = str(r.loc[r.index[i], 'Plasmid Best Match'])
_results.plasmididentity = str(r.loc[r.index[i], 'Plasmid Identity'])
_results.plasmidsharedhashes = str(r.loc[r.index[i], 'Plasmid Shared Hash'])
for j in range(0,_results.TotalPlasmids):
_plasmid = plasmidObj()
_plasmid.PlasmidsID =(((str(r.loc[r.index[i], 'Plasmids ID'])).split(";"))[j])
_plasmid.Num_Contigs = (((str(r.loc[r.index[i], 'Num_Contigs'])).split(";"))[j])
_plasmid.PlasmidLength = (((str(r.loc[r.index[i], 'Plasmid Length'])).split(";"))[j])
_plasmid.PlasmidRepType = (((str(r.loc[r.index[i], 'Plasmid RepType'])).split(";"))[j])
_plasmid.PlasmidMobility = ((str(r.loc[r.index[i], 'Plasmid Mobility'])).split(";"))[j]
_plasmid.NearestReference = ((str(r.loc[r.index[i], 'Nearest Reference'])).split(";"))[j]
_results.plasmids.append(_plasmid)
_results.DefinitelyPlasmidContigs = (str(r.loc[r.index[i], 'Definitely Plasmid Contigs']))
_results.LikelyPlasmidContigs = (str(r.loc[r.index[i], 'Likely Plasmid Contigs']))
_results.row = "\t".join(str(x) for x in r.ix[i].tolist())
_worflowResult[_results.ID] = _results
return _worflowResult
#endregion
def Main():
if len(sensitivePath)>0:
sensitive_meta_data = SensitiveMetadata()
metadata = ParseWorkflowResults(metadataPath)
distance = read(distancePath)
treeFile = "".join(read(treePath))
distanceDict = {} #store the distance matrix as rowname:list<string>
for i in range(len(distance)):
temp = distance[i].split("\t")
distanceDict[temp[0]] = temp[1:]
#region create box tree
#region step5: tree construction
treeFile = "".join(read(treePath))
t = e.Tree(treeFile)
t.set_outgroup(t&"Reference")
#set the tree style
ts = e.TreeStyle()
ts.show_leaf_name = True
ts.show_branch_length = True
ts.scale = 2000 #pixel per branch length unit
ts.branch_vertical_margin = 15 #pixel between branches
style2 = e.NodeStyle()
style2["fgcolor"] = "#000000"
style2["shape"] = "circle"
style2["vt_line_color"] = "#0000aa"
style2["hz_line_color"] = "#0000aa"
style2["vt_line_width"] = 2
style2["hz_line_width"] = 2
style2["vt_line_type"] = 0 # 0 solid, 1 dashed, 2 dotted
style2["hz_line_type"] = 0
for n in t.traverse():
n.set_style(style2)
#find the plasmid origins
plasmidIncs = {}
for key in metadata:
for plasmid in metadata[key].plasmids:
for inc in plasmid.PlasmidRepType.split(","):
if (inc.lower().find("inc") > -1):
if not (inc in plasmidIncs):
plasmidIncs[inc] = [metadata[key].ID]
else:
if metadata[key].ID not in plasmidIncs[inc]:
plasmidIncs[inc].append(metadata[key].ID)
#plasmidIncs = sorted(plasmidIncs)
for n in t.traverse(): #loop through the nodes of a tree
if (n.is_leaf() and n.name == "Reference"):
#if its the reference branch, populate the faces with column headers
index = 0
if len(sensitivePath)>0: #sensitive metadat @ chris
for sensitive_data_column in sensitive_meta_data.get_columns():
(t&"Reference").add_face(addFace(sensitive_data_column), index, "aligned")
index = index + 1
(t&"Reference").add_face(addFace("SampleID"), index, "aligned")
index = index + 1
(t&"Reference").add_face(addFace("New?"), index, "aligned")
index = index + 1
for i in range(len(plasmidIncs)): #this loop adds the columns (aka the incs) to the reference node
(t&"Reference").add_face(addFace(list(plasmidIncs.keys())[i]), i + index, "aligned")
index = index + len(plasmidIncs)
(t&"Reference").add_face(addFace("MLSTScheme"), index, "aligned")
index = index + 1
(t&"Reference").add_face(addFace("Sequence Type"), index, "aligned")
index = index + 1
(t&"Reference").add_face(addFace("Carbapenamases"), index, "aligned")
index = index + 1
(t&"Reference").add_face(addFace("Plasmid Best Match"), index, "aligned")
index = index + 1
(t&"Reference").add_face(addFace("Best Match Identity"), index, "aligned")
index = index + 1
for i in range(len(distanceDict[list(distanceDict.keys())[0]])): #this loop adds the distance matrix
(t&"Reference").add_face(addFace(distanceDict[list(distanceDict.keys())[0]][i]), index + i, "aligned")
index = index + len(distanceDict[list(distanceDict.keys())[0]])
elif (n.is_leaf() and not n.name == "Reference"):
#not reference branches, populate with metadata
index = 0
if len(sensitivePath)>0: #sensitive metadata @ chris
# pushing in sensitive data
for sensitive_data_column in sensitive_meta_data.get_columns():
# tree uses bcids like BC18A021A_S12
# while sens meta-data uses BC18A021A
# trim the "_S.*" if present
bcid = str(mData.ID)
if bcid.find( "_S" ) != -1:
bcid = bcid[ 0:bcid.find( "_S" ) ]
sens_col_val = sensitive_meta_data.get_value(bcid=bcid, column_name=sensitive_data_column )
n.add_face(addFace(sens_col_val), index, "aligned")
index = index + 1
if (n.name.replace(".fa","") in metadata.keys()):
mData = metadata[n.name.replace(".fa","")]
else:
mData = metadata["na"]
n.add_face(addFace(mData.ID), index, "aligned")
index = index + 1
if (mData.new == True): #new column
face = e.RectFace(30,30,"green","green") # TextFace("Y",fsize=10,tight_text=True)
face.border.margin = 5
face.margin_right = 5
face.margin_left = 5
face.vt_align = 1
face.ht_align = 1
n.add_face(face, index, "aligned")
index = index + 1
for incs in plasmidIncs: #this loop adds presence/absence to the sample nodes
if (n.name.replace(".fa","") in plasmidIncs[incs]):
face = e.RectFace(30,30,"black","black") # TextFace("Y",fsize=10,tight_text=True)
face.border.margin = 5
face.margin_right = 5
face.margin_left = 5
face.vt_align = 1
face.ht_align = 1
n.add_face(face, list(plasmidIncs.keys()).index(incs) + index, "aligned")
index = index + len(plasmidIncs)
n.add_face(addFace(mData.MLSTSpecies), index, "aligned")
index = index + 1
n.add_face(addFace(mData.SequenceType), index, "aligned")
index = index + 1
n.add_face(addFace(mData.CarbapenemResistanceGenes), index, "aligned")
index = index + 1
n.add_face(addFace(mData.plasmidBestMatch), index, "aligned")
index = index + 1
n.add_face(addFace(mData.plasmididentity), index, "aligned")
index = index + 1
for i in range(len(distanceDict[list(distanceDict.keys())[0]])): #this loop adds distance matrix
if (n.name in distanceDict): #make sure the column is in the distance matrice
n.add_face(addFace(list(distanceDict[n.name])[i]), index + i, "aligned")
t.render(outputFile, w=5000,units="mm", tree_style=ts) #save it as a png, pdf, svg or an phyloxml
#endregion
#endregion
start = time.time()#time the analysis
#analysis time
Main()
end = time.time()
print("Finished!\nThe analysis used: " + str(end-start) + " seconds")<file_sep>/M2_pipeline_prediction.sh
#!/bin/bash -e
#$ -V # Pass environment variables to the job
#$ -N CPO_pipeline # Replace with a more specific job name
#$ -cwd # Use the current working dir
#$ -pe smp 8 # Parallel Environment (how many cores)
#$ -l h_vmem=11G # Memory (RAM) allocation *per core*
#$ -e ./logs/$JOB_ID.err
#$ -o ./logs/$JOB_ID.log
#input parameters: 1=ID 2 = assemblyPath, 3= outputdir, 4=card.json
#step 1, mash QC
source activate cpo_qc
ID="$1"
assemblyPath="$2"
outputDir="$3"
cardPath="$4"
threads=8 #"$5"
echo "parameters: "
echo "ID: $ID"
echo "outputDir: $outputDir"
echo "card.json Path: $cardPath"
echo "threads: $threads"
predictionsDir="$outputDir"/predictions
mkdir -p "$predictionsDir"
mkdir -p "$outputDir"/summary
source activate cpo_predictions
echo "step3: mlst"
#step3: run mlst
mlst "$assemblyPath" > "$predictionsDir/$ID.mlst"
#step4: plasmid+amr
echo "step4: plasmid+amr prediction"
#find origin of replications using plasmidfinder, >>defunct replaced with mobsuite
#abricate --db plasmidfinder "$assemblyPath" > "$predictionsDir/$ID.origins"
#find carbapenemases using custom cpo database.
abricate --db cpo "$assemblyPath" > "$predictionsDir/$ID.cp"
#run rgi
cd $predictionsDir
rgi load -i "$cardPath" --local #--debug
rgi main -i "$assemblyPath" -o "$ID.rgi" -t contig -a BLAST -n "$threads" --local --clean #--debug
rm -rf localDB
source deactivate
#source activate plasflow
#find contigs that are likely to be plasmids >>defunct replaced with mobsuite
#PlasFlow.py --input "$ID" --output "$predictionsDir/$ID.plasflow" --threshold 0.85
#rm -rf "$contigsDir"/*.fa_kmer*
#rm -rf "$predictionsDir"/*.fasta
#source deactivate
source activate mob_suite #requires sudo
#run mob typer
mob_recon --infile "$assemblyPath" --outdir "$predictionsDir/$ID.recon" --run_typer
source deactivate
echo "done step 4"
<file_sep>/M1_pipeline_qc.sh
#!/bin/bash -e
#$ -V # Pass environment variables to the job
#$ -N CPO_pipeline # Replace with a more specific job name
#$ -cwd # Use the current working dir
#$ -pe smp 8 # Parallel Environment (how many cores)
#$ -l h_vmem=11G # Memory (RAM) allocation *per core*
#$ -e ./logs/$JOB_ID.err
#$ -o ./logs/$JOB_ID.log
#####################################################################################################################################################################################################
#J-J-J-Jia @ pipeline_qc.sh: runs seqtk, mash, kraken2 and fastqc for pre-assembly quality checks #
#input parameters: 1 = id, 2= forward, 3 = reverse, 4 = output, 5=mashgenomerefdb, $6=mashplasmidrefdb, $7=kraken2db, $8=kraken2plasmiddb #
#Requires: mash, kraken2, fastqc, seqtk (all conda-ble) #
##~/scripts/pipeline_qc.sh BC16-Cfr035 /data/jjjjia/R1/BC16-Cfr035_S10_L001_R1_001.fastq.gz /data/jjjjia/R2/BC16-Cfr035_S10_L001_R2_001.fastq.gz /home/jjjjia/testCases/tests /home/jjjjia/databases/refseq.genomes.k21s1000.msh /home/jjjjia/databases/refseq.plasmid.k21s1000.msh /home/jjjjia/databases/k2std /home/jjjjia/databases/k2plasmid #
#####################################################################################################################################################################################################
#step 1, mash QC
source activate cpo_qc
#set dem variables
ID="$1"
R1="$2"
R2="$3"
outputDir="$4"
refDB="$5"
plasmidRefDB="$6"
k2db="$7"
k2plasmid="$8"
threads=8
ram=80
#print dem variables
echo "parameters: "
echo "ID: $ID"
echo "R1: $R1"
echo "R2: $R2"
echo "outputDir: $outputDir"
echo "refDB: $refDB"
echo "plasmidDB: $plasmidRefDB"
echo "kraken2db: $k2db"
echo "kraken2plasmiddb: $k2plasmid"
echo "threads: $threads"
echo "ram: $ram"
mashResultDir="$outputDir"/qcResult
mkdir -p "$outputDir"
mkdir -p "$mashResultDir"
mkdir -p "$outputDir"/summary
#step1, mash qc
echo "step1: mash"
qcOutDir="$mashResultDir/$ID"
mkdir -p "$mashResultDir"/"$ID"
cat "$R1" "$R2" > "$qcOutDir"/concatRawReads.fastq
cat "$R1" > "$qcOutDir"/R1.fastq
#get estimation of genome size (k-mer method)
mash sketch -m 3 "$qcOutDir"/R1.fastq -o "$qcOutDir"/R1.fastq -p "$threads" -k 32 2> "$qcOutDir"/mash.log
#identify species using genome database
echo "comparing to reference genome db"
mash screen -p "$threads" -w "$refDB" "$qcOutDir"/concatRawReads.fastq | sort -gr > "$qcOutDir"/mashscreen.genome.tsv
#identify if theres any plasmids present in the reads
echo "comparing to reference plasmid db"
mash screen -p "$threads" -w "$plasmidRefDB" "$qcOutDir"/concatRawReads.fastq | sort -gr > "$qcOutDir"/mashscreen.plasmid.tsv
#fastqc of the forward and reverse reads
echo "fastqc of reads"
fastqc "$R1" -o "$qcOutDir" --extract
fastqc "$R2" -o "$qcOutDir" --extract
rm -rf "$qcOutDir"/*.html
rm -rf "$qcOutDir"/*.zip
echo "kraken2 classfiication of reads"
#kraken2 species classification
kraken2 --db "$k2db" --paired --threads "$threads" --report "$qcOutDir"/kraken2.genome.report --output "$qcOutDir"/kraken2.genome.classification "$R1" "$R2"
#kraken2 plasmid classification ~!use mash instead
#kraken2 --db "$k2plasmid" --paired --threads "$threads" --report "$qcOutDir"/kraken2.plasmid.report --output "$qcOutDir"/kraken2.plasmid.classification "$R1" "$R2"
#calculate the total number of basepairs in the read
echo "calculating read stats"
R1bp=`seqtk fqchk $R1 | head -3 | tail -1 | cut -d$'\t' -f 2`
R2bp=`seqtk fqchk $R2 | head -3 | tail -1 | cut -d$'\t' -f 2`
totalbp=$((R1bp+R2bp))
echo $totalbp > "$qcOutDir"/totalbp
#estimate coverage ~! do it with python
#kmc -m"$ram" -sm -n256 -ci3 -k25 -t"threads" "$R1" kmc ./temp
#refGenomeSize=`grep -v ">" refbc11 | wc | awk '{print $3-$1}'`
#echo $refGenomeSize > "$qcOutDir"/refGenomeSize
echo "cleaning up..."
rm -rf "$qcOutDir"/concatRawReads.fastq
rm -rf "$qcOutDir"/concatRawReads.fastq.msh
rm -rf "$qcOutDir"/R1.fastq
rm -rf "$qcOutDir"/R1.fastq.msh
source deactivate
echo "done step 1"<file_sep>/M1_pipeline_sequdas.qsub
#!/bin/bash
#$ -V # Pass environment variables to the job
#$ -N CPO_pipeline # Replace with a more specific job name
#$ -wd /home/jjjjia/testCases # Use the current working dir
#$ -pe smp 8 # Parallel Environment (how many cores)
#$ -l h_vmem=11G # Memory (RAM) allocation *per core*
#$ -e ./logs/$JOB_ID.err
#$ -o ./logs/$JOB_ID.log
#$ -m ea
#$ -M <EMAIL>
#parameters: -i BC11-Kpn005_S2 -f /data/jjjjia/R1/BC11-Kpn005_S2_L001_R1_001.fastq.gz -r /data/jjjjia/R2/BC11-Kpn005_S2_L001_R2_001.fastq.gz -m /home/jjjjia/databases/RefSeqSketchesDefaults.msh -o pipelineResultsQsubTest -s /home/jjjjia/databases/scheme_species_map.tab -e "Klebsiella pneumoniae" -k /home/jjjjia/scripts/pipeline.sh
source activate py36
python ~/scripts/pipeline_sequdas.py "$@"
source deactivate
#submitting multiple joibs
#for i in `cat /data/jjjjia/seqs.test`;
#do
#R1="~/testCases/seqs.all/"$i"_L001_R1_001.fastq.gz"
#R2="~/testCases/seqs.all/"$i"_L001_R2_001.fastq.gz"
#echo "$i"
#echo "$R1"
#echo "$R2"
#qsub ~/scripts/pipeline.qsub -i $i -f $R1 -r $R2 -o ~/testCases/sequdasTest -e "Klebsiella pneumoniae";
#done;<file_sep>/M1_pipeline_assembly.sh
#!/bin/bash -e
#$ -V # Pass environment variables to the job
#$ -N CPO_pipeline # Replace with a more specific job name
#$ -cwd # Use the current working dir
#$ -pe smp 8 # Parallel Environment (how many cores)
#$ -l h_vmem=11G # Memory (RAM) allocation *per core*
#$ -e ./logs/$JOB_ID.err
#$ -o ./logs/$JOB_ID.log
#####################################################################################################################################################################################################
#J-J-J-Jia @ pipeline_assembly.sh: assemble the reads. then do QA on them with busco and quast #
#input parameters: 1 = id, 2= forward, 3 = reverse, 4 = output, 5=tmpdir for shovill, 6=reference genome, 7=buscoDB #
#Requires: shovill, bbmap, quast and busco (all conda-ble) #
#~/scripts/pipeline_assembly.sh BC11 /data/jjjjia/R1/BC11-Kpn005_S2_L001_R1_001.fastq.gz /data/jjjjia/R2/BC11-Kpn005_S2_L001_R2_001.fastq.gz /home/jjjjia/testCases/tests /home/jjjjia/testCases/tests/shovilltemp /home/jjjjia/testCases/tests/references/refbc11 /home/jjjjia/databases/enterobacteriales_odb9/
#####################################################################################################################################################################################################
ID="$1"
R1="$2"
R2="$3"
outputDir="$4"
tmpDir="$5"
refGenome="$6"
buscoDB="$7"
threads=8
ram=80
echo "parameters: "
echo "ID: $ID"
echo "R1: $R1"
echo "R2: $R2"
echo "outputDir: $outputDir"
echo "tmpDir: $tmpDir"
echo "refGenomePath: $refGenome"
echo "buscoDB path: $buscoDB"
echo "threads: $threads"
echo "ram: $ram"
assemblyDir="$outputDir"/assembly
contigsDir="$outputDir"/contigs
qcDir="$outputDir"/assembly_qc
tempDir="$tmpDir"/"$ID"
#step2, shovill assembly
mkdir -p "$assemblyDir"
mkdir -p "$contigsDir"
mkdir -p "$qcDir"
mkdir -p "$tempDir"
echo "step2: assembly"
assemblyOutDir="$assemblyDir/$ID"
#mkdir -p "$assemblyDir/$ID"
source activate cpo_assembly
shovill --R1 "$R1" --R2 "$R2" --cpus "$threads" --ram "$ram" --tmpdir "$tempDir" --outdir "$assemblyOutDir"
#make the contigs dir in cwd
#move all the assemblies to the new phone.
if [ -f "$assemblyOutDir/contigs.fa" ]
then
cp "$assemblyOutDir/contigs.fa" "$contigsDir/$ID.fa"
else
echo "!!!Error during assembly"
exit 818
fi
#run quast on assembled genome
mkdir -p "$qcDir"/"$ID"
cd "$qcDir"/"$ID"
quast "$contigsDir/$ID.fa" -R "$refGenome" -o "$qcDir/$ID/$ID.quast" --threads "$threads"
#contamination genomes
#bbsplit.sh in1=BC16-Cfr035_S10_L001_R1_001.fastq.gz in2=BC16-Cfr035_S10_L001_R2_001.fastq.gz ref=ref1,ref2,ref3 basename=o%_#.fq outu1=unmap1.fq outu2=unmap2.fq
#metaquast BC16-Cfr035_S10.fa -R ref1,ref2,ref3 --threads 8 -o result
source deactivate
source activate cpo_busco
cd "$qcDir"/"$ID"
#have to run busco with 1 threads cuz it throws some error about tblastn crashing when multithreaddin
run_busco -i "$contigsDir/$ID.fa" -o "$ID.busco" -l $buscoDB -m genome -c 1 -sp E_coli_K12 -f
mv "run_$ID".busco "$ID".busco
source deactivate
rm -rf cd "$qcDir"/"$ID"/tmp
rm -rf "$tempDir"
echo "done step 2"<file_sep>/M1_pipeline_assembly_contaminant.sh
#!/bin/bash -e
#$ -V # Pass environment variables to the job
#$ -N CPO_pipeline # Replace with a more specific job name
#$ -cwd # Use the current working dir
#$ -pe smp 8 # Parallel Environment (how many cores)
#$ -l h_vmem=11G # Memory (RAM) allocation *per core*
#$ -e ./logs/$JOB_ID.err
#$ -o ./logs/$JOB_ID.log
#####################################################################################################################################################################################################
#J-J-J-Jia @ pipeline_assembly_contaminant.sh: filter read k-mers to reference genome(s) then assemble the filtered reads. then do QA on them with metaquast and busco #
#input parameters: 1 = id, 2= forward, 3 = reverse, 4 = output, 5=tmpdir for shovill, 6=reference genome (csv, no spaces), 7=buscodb, 8=correct reference #
#Requires: shovill, bbmap, quast and busco (all conda-ble) #
#./pipeline_assembly_contaminant.sh BC11_Kpn05 ~/testCases/seqs/R1/BC11_Kpn05_R1.fastq.gz ~/testCases/seqs/R2/BC11_Kpn05_R2.fastq.gz ~/cpo_assembly ~/cpo_temp "~/ref1.fna,~/ref2.fna,~/ref3.fna" #
#####################################################################################################################################################################################################
#~/scripts/pipeline_assembly_contaminant.sh BC16 /data/jjjjia/R1/BC16-Cfr035_S10_L001_R1_001.fastq.gz /data/jjjjia/R2/BC16-Cfr035_S10_L001_R2_001.fastq.gz /home/jjjjia/testCases/tests /home/jjjjia/testCases/tests/shovilltemp /home/jjjjia/testCases/tests/references/ref1,/home/jjjjia/testCases/tests/references/ref2,/home/jjjjia/testCases/tests/references/ref3 /home/jjjjia/databases/enterobacteriales_odb9/
ID="$1"
R1="$2"
R2="$3"
outputDir="$4"
tmpDir="$5"
refGenome="$6"
buscoDB="$7"
correctRef="$8"
threads=8
ram=80
echo "parameters: "
echo "ID: $ID"
echo "R1: $R1"
echo "R2: $R2"
echo "outputDir: $outputDir"
echo "tmpDir: $tmpDir"
echo "refGenomePath: $refGenome"
echo "buscoDB path: $buscoDB"
echo "correctRefernce: $correctRef"
echo "threads: $threads"
echo "ram: $ram"
assemblyDir="$outputDir"/assembly
contigsDir="$outputDir"/contigs
tempDir="$tmpDir"/"$ID"
splitOutDir="$assemblyDir"/filteredReads
qcDir="$outputDir"/assembly_qc
#step2, shovill assembly
mkdir -p "$assemblyDir"
mkdir -p "$contigsDir"
mkdir -p "$tempDir"
mkdir -p "$splitOutDir"
mkdir -p "$qcDir"
echo "step2: assembly"
#mkdir -p "$assemblyDir/$ID"
source activate cpo_assembly
#try to seperate out the contaminant reads
cd $tempDir #bbsplit creates temp files in the current directory that cannot be changed. cd first to keep it clean
bbsplit.sh in1="$R1" in2="$R2" ref="$refGenome" basename="$splitOutDir"/"$ID"%_#.fq outu1="$splitOutDir"/"$ID"_unmap1.fq outu2="$splitOutDir"/"$ID"_unmap2.fq t="$threads" -Xmx"$ram"g
#assembled all the contaminant reads
IFS=',' read -ra ADDR <<< "$refGenome" #hax to read in a csv
for i in "${ADDR[@]}"; do
refG=`basename $i`
echo $refG
assemblyOutDir="$assemblyDir/$ID/$refG"
R1Proper="$splitOutDir"/"$ID""$refG"_1.fq
R2Proper="$splitOutDir"/"$ID""$refG"_2.fq
shovill --R1 "$R1Proper" --R2 "$R2Proper" --cpus "$threads" --ram "$ram" --tmpdir "$tempDir" --outdir "$assemblyOutDir"
contigProper="$contigsDir"/"$ID"."$refG".fa
#move all the assemblies to the new phone.
if [ -f "$assemblyOutDir/contigs.fa" ]
then
cp "$assemblyOutDir/contigs.fa" "$contigProper"
else
echo "!!!Error during assembly"
exit 818
fi
mkdir -p "$qcDir"/"$ID"
cd "$qcDir"/"$ID"
#run metaquast on 1 of the contaminant genomes
metaquast "$contigProper" -R "$refGenome" --threads "$threads" -o "$qcDir/$ID/$ID.$refG.quast"
done
#contamination genomes
source deactivate
source activate cpo_busco
cd "$qcDir"/"$ID"
#run busco on all the assembled contaminant genomes
IFS=',' read -ra ADDR <<< "$refGenome" #hax to read in a csv
for i in "${ADDR[@]}"; do
refG=`basename $i`
echo $refG
contigProper="$contigsDir"/"$ID"."$refG".fa
#have to run busco with 1 threads cuz it throws some error about tblastn crashing when multithreadding
run_busco -i "$contigProper" -o "$ID.$refG.busco" -l "$buscoDB" -m genome -c 1 -f
mv "run_$ID.$refG.busco" "$ID.$refG.busco"
done
source deactivate
#rename the correct assembly and qc files
mv "$contigsDir"/"$ID"."$correctRef".fa "$contigsDir"/"$ID".fa
mv "$qcDir"/"$ID"/"$ID"."$correctRef".busco "$qcDir"/"$ID"/"$ID".busco
mv "$qcDir"/"$ID"/"$ID"."$correctRef".quast "$qcDir"/"$ID"/"$ID".quast
#cleanup
rm -rf cd "$qcDir"/"$ID"/tmp
rm -rf "$tempDir"
echo "done step 2"<file_sep>/M1_pipeline_sequdas.py
#!/home/jjjjia/.conda/envs/py36/bin/python
#$ -S /home/jjjjia/.conda/envs/py36/bin/python
#$ -V # Pass environment variables to the job
#$ -N CPO_pipeline # Replace with a more specific job name
#$ -wd /home/jjjjia/testCases # Use the current working dir
#$ -pe smp 8 # Parallel Environment (how many cores)
#$ -l h_vmem=11G # Memory (RAM) allocation *per core*
#$ -e ./logs/$JOB_ID.err
#$ -o ./logs/$JOB_ID.log
#$ -m ea
#$ -M <EMAIL>
#This script is a wrapper for module one of the cpo_workflow including QC and Assembly. It uses Mash2.0, Kraken2.0 and fastqc to check for sequence contamination, quality information and identify a reference genome. Then attempts to assemble the reads, attempting to filter contamination away if required.
# >~/scripts/pipeline.py -i BC11-Kpn005_S2 -f /data/jjjjia/R1/BC11-Kpn005_S2_L001_R1_001.fastq.gz -r /data/jjjjia/R2/BC11-Kpn005_S2_L001_R2_001.fastq.gz -o pipelineResultsQsub -e "Klebsiella pneumoniae"
# Requires pipeline_qc.sh, pipeline_assembly.sh, pipeline_assembly_contaminant.sh. where these scripts are located can be specified with -k. default "/home/jjjjia/scripts/"
import subprocess
import pandas
import optparse
import os
import datetime
import sys
import time
import urllib.request
import gzip
import collections
import json
debug = False #debug skips the shell scripts and also dump out a ton of debugging messages
if not debug:
#parses some parameters
parser = optparse.OptionParser("Usage: %prog [options] arg1 arg2 ...")
parser.add_option("-i", "--id", dest="id", type="string", help="identifier of the isolate")
parser.add_option("-f", "--forward", dest="R1", type="string", help="absolute file path forward read (R1)")
parser.add_option("-r", "--reverse", dest="R2", type="string", help="absolute file path to reverse read (R2)")
parser.add_option("-m", "--mash-genomedb", dest="mashGenomeRefDB", default = "/home/jjjjia/databases/refseq.genomes.k21s1000.msh", type="string", help="absolute path to mash reference database")
parser.add_option("-n", "--mash-plasmiddb", dest="mashPlasmidRefDB", default = "/home/jjjjia/databases/refseq.plasmid.k21s1000.msh", type="string", help="absolute path to mash reference database")
parser.add_option("-z", "--kraken2-genomedb", dest="kraken2GenomeRefDB", default = "/home/jjjjia/databases/k2std", type="string", help="absolute path to kraken reference database")
parser.add_option("-v", "--kraken2-plasmiddb", dest="kraken2PlasmidRefDB", default = "/home/jjjjia/databases/k2plasmid", type="string", help="absolute path to kraken reference database")
parser.add_option("-x", "--busco-db", dest="buscodb", default = "/home/jjjjia/databases/enterobacteriales_odb9", type="string", help="absolute path to busco reference database")
parser.add_option("-o", "--output", dest="output", default='./', type="string", help="absolute path to output folder")
parser.add_option("-k", "--script-path", dest="scriptDir", default="/home/jjjjia/scripts", type="string", help="absolute file path to this script folder")
#used for parsing
parser.add_option("-e", "--expected", dest="expectedSpecies", default="NA/NA/NA", type="string", help="expected species of the isolate")
#parallelization, useless, these are hard coded to 8cores/64G RAM
#parser.add_option("-t", "--threads", dest="threads", default=8, type="int", help="number of cpu to use")
#parser.add_option("-p", "--memory", dest="memory", default=64, type="int", help="memory to use in GB")
(options,args) = parser.parse_args()
#if len(args) != 8:
#parser.error("incorrect number of arguments, all 7 is required")
curDir = os.getcwd()
outputDir = options.output
mashdb = options.mashGenomeRefDB
mashplasmiddb=options.mashPlasmidRefDB
kraken2db = options.kraken2GenomeRefDB
kraken2plasmiddb=options.kraken2PlasmidRefDB
expectedSpecies = options.expectedSpecies
#threads = options.threads
#memory = options.memory
tempDir = outputDir + "/shovillTemp"
scriptDir = options.scriptDir
buscodb = options.buscodb
ID = options.id
R1 = options.R1
R2 = options.R2
else:
curDir = os.getcwd()
outputDir = "pipelineTest"
mashdb = ""
mashplasmiddb=""
kraken2db = ""
kraken2plasmiddb=""
expectedSpecies = "Escherichia coli"
#threads = 8
#memory = 64
mlstScheme = outputDir + "/scheme_species_map.tab"
tempDir= outputDir + "/shovillTemp"
scriptDir = "~/scripts"
updateAbName = "cpo"
updateAbPath = "~/database/bccdcCPO.seq"
updateMLST = True
buscodb = "~/database/bccdcCPO.seq"
ID = "BC16-Cfr035_S10"
R1 = "BC16-Cfr035_S10_L001_R1_001.fastq.gz"
R2 = "BC16-Cfr035_S10_L001_R2_001.fastq.gz"
#region result objects
#define some objects to store values from results
#//TODO this is not the proper way of get/set private object variables. every value has manually assigned defaults intead of specified in init(). Also, use property(def getVar, def setVar).
class starFinders(object):
def __init__(self):
self.file = ""
self.sequence = ""
self.start = 0
self.end = 0
self.gene = ""
self.shortGene = ""
self.coverage = ""
self.coverage_map = ""
self.gaps = ""
self.pCoverage = 100.00
self.pIdentity = 100.00
self.database = ""
self.accession = ""
self.product = ""
self.source = "chromosome"
self.row = ""
class PlasFlowResult(object):
def __init__(self):
self.sequence = ""
self.length = 0
self.label = ""
self.confidence = 0
self.usefulRow = ""
self.row = ""
class MlstResult(object):
def __init__(self):
self.file = ""
self.speciesID = ""
self.seqType = 0
self.scheme = ""
self.species = ""
self.row=""
class MashResult(object):
def __init__(self):
self.size = 0.0
self.depth = 0.0
self.identity = 0.0
self.sharedHashes = ""
self.medianMultiplicity = 0
self.pvalue = 0.0
self.queryID= ""
self.queryComment = ""
self.species = ""
self.row = ""
self.accession = ""
self.gcf=""
self.assembly=""
def toDict(self): #doesnt actually work
return dict((name, getattr(self, name)) for name in dir(self) if not name.startswith('__'))
class fastqcResult(object):
def __init__(self):
self.basic = ""
self.perBaseSequenceQuality = ""
self.perTileSequenceQuality = ""
self.perSequenceQualityScores = ""
self.perBaseSequenceContent = ""
self.perSequenceGCContent = ""
self.perBaseNContent = ""
self.sequenceLengthDistribution = ""
self.sequenceDuplicationLevels = ""
self.overrepresentedSequences = ""
self.adapterContent = ""
self.fastqcHTMLblob = ""
def toDict(self):
dict = {}
dict["Basic Statistics"] = self.basic
dict["Per base sequence quality"] = self.perBaseSequenceQuality
dict["Per tile sequence quality"] = self.perTileSequenceQuality
dict["Per sequence quality scores"] = self.perSequenceQualityScores
dict["Per base sequence content"] = self.perBaseSequenceContent
dict["Per sequence GC content"] = self.perSequenceGCContent
dict["Per base N content"] = self.perBaseNContent
dict["Sequence Length Distribution"] = self.sequenceLengthDistribution
dict["Sequence Duplication Levels"] = self.sequenceDuplicationLevels
dict["Overrepresented sequences"] = self.overrepresentedSequences
dict["Adapter Content"] = self.adapterContent
return dict
def dataToTSV():
dict = toDict()
s = ""
for key in dict:
s += dict[key] + "\t"
return s
def headerToTSV():
dict = toDict()
s = ""
for key in dict:
s += key + "\t"
return s
class KrakenResult(object):
def __init__(self):
self.fragPercent = -1.00
self.fragCountRoot = 0
self.fragCountTaxon = 0
self.rankCode = ""
self.taxID = -1
self.name = ""
self.row = ""
class buscoResult(object):
def __init__(self):
self.completeSingle = 0
self.completeDuplicate = 0
self.fragmented = 0
self.mising = 0
self.total = 781
self.buscoResult = []
class quastResult(object):
def __init__(self):
self.contigsCount = 0
self.largestContig = 0
self.N50 = 0
self.NG50 = 0
self.L50 = 0
self.LG50 = 0
self.N75 = 0
self.NG75 = 0
self.L75 = 0
self.LG75 = 0
self.totalLength = 0
self.referenceLength = 0
self.GC = 0.00
self.referenceGC = 0.00
self.genomeFraction = 0.00
self.duplicationRatio = 0.00
self.data = []
class mobsuiteResult(object):
def __init__(self):
self.file_id = ""
self.cluster_id = ""
self.contig_id = ""
self.contig_num = 0
self.contig_length = 0
self.circularity_status = ""
self.rep_type = ""
self.rep_type_accession = ""
self.relaxase_type = ""
self.relaxase_type_accession = ""
self.mash_nearest_neighbor = ""
self.mash_neighbor_distance = 0.00
self.repetitive_dna_id = ""
self.match_type = ""
self.score = 0
self.contig_match_start = 0
self.contig_match_end = 0
self.row = ""
class RGIResult(object):
def __init__(self):
self.ORF_ID = ""
self.Contig = ""
self.Start = -1
self.Stop = -1
self.Orientation = ""
self.Cut_Off = ""
self.Pass_Bitscore = 100000
self.Best_Hit_Bitscore = 0.00
self.Best_Hit_ARO = ""
self.Best_Identities = 0.00
self.ARO = 0
self.Model_type = ""
self.SNPs_in_Best_Hit_ARO = ""
self.Other_SNPs = ""
self.Drug_Class = ""
self.Resistance_Mechanism = ""
self.AMR_Gene_Family = ""
self.Predicted_DNA = ""
self.Predicted_Protein = ""
self.CARD_Protein_Sequence = ""
self.Percentage_Length_of_Reference_Sequence = 0.00
self.ID = ""
self.Model_ID = 0
self.source = ""
self.row = ""
#endregion
#region useful functions
def read(path):
return [line.rstrip('\n') for line in open(path)]
def execute(command):
process = subprocess.Popen(command, shell=False, cwd=curDir, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
# Poll process for new output until finished
while True:
nextline = process.stdout.readline()
if nextline == '' and process.poll() is not None:
break
sys.stdout.write(nextline)
sys.stdout.flush()
output = process.communicate()[0]
exitCode = process.returncode
if (exitCode == 0):
return output
else:
raise subprocess.CalledProcessError(exitCode, command)
def httpGetFile(url, filepath=""):
if (filepath == ""):
return urllib.request.urlretrieve(url)
else:
urllib.request.urlretrieve(url, filepath)
return True
def gunzip(inputpath="", outputpath=""):
if (outputpath == ""):
with gzip.open(inputpath, 'rb') as f:
gzContent = f.read()
return gzContent
else:
with gzip.open(inputpath, 'rb') as f:
gzContent = f.read()
with open(outputpath, 'wb') as out:
out.write(gzContent)
return True
def ToJson(dictObject, outputPath):
outDir = outputDir + '/summary/' + ID + ".json/"
#if not (os.path.exists(outDir)):
#os.makedirs(outDir)
#with open(outDir + outputPath, 'w') as f:
#json.dump([ob.__dict__ for ob in dictObject.values()], f, ensure_ascii=False)
#endregion
#region functions to parse result files
def ParseKrakenResult(pathToKrakenResult):
_krakenGenomes = {}
kraken = pandas.read_csv(pathToKrakenResult, delimiter='\t', header=None) #read the kraken2report.tsv
kraken = kraken.loc[(kraken[3] == "S")] #find all the rows with species level information and discard the rest
for i in range(len(kraken.index)):
if (float((str(kraken.iloc[i, 0])).strip("%")) > 1.00): #find all species above 1%
kg = KrakenResult()
kg.fragPercent = float((str(kraken.iloc[i, 0])).strip("%"))
kg.fragCountRoot = int(kraken.iloc[i,1])
kg.fragCountTaxon = int (kraken.iloc[i,2])
kg.rankCode = kraken.iloc[i,3]
kg.taxID = kraken.iloc[i,4]
kg.name = kraken.iloc[i,5].strip()
kg.row = "\t".join(str(x) for x in kraken.iloc[i].tolist())
_krakenGenomes[kg.name]=(kg) #throw the kraken result object in to a list
return _krakenGenomes
def ParseFastQCResult(pathToR1qc, pathToR2qc, ID, R1, R2):
fastqc = pandas.read_csv(pathToR1qc + "summary.txt", delimiter='\t', header=None)
fastqc = fastqc[0].tolist()
_fastqcR1 = fastqcResult()
_fastqcR1.basic = fastqc[0]
_fastqcR1.perBaseSequenceQuality = fastqc[1]
_fastqcR1.perTileSequenceQuality = fastqc[2]
_fastqcR1.perSequenceQualityScores = fastqc[3]
_fastqcR1.perBaseSequenceContent = fastqc[4]
_fastqcR1.perSequenceGCContent = fastqc[5]
_fastqcR1.perBaseNContent = fastqc[6]
_fastqcR1.sequenceLengthDistribution = fastqc[7]
_fastqcR1.sequenceDuplicationLevels = fastqc[8]
_fastqcR1.overrepresentedSequences = fastqc[9]
_fastqcR1.adapterContent = fastqc[10]
with open(pathToR1qc + "fastqc_report.html", "r") as input:
_fastqcR1.fastqcHTMLblob = input.read()
fastqc = pandas.read_csv(pathToR2qc+ "summary.txt", delimiter='\t', header=None)
fastqc = fastqc[0].tolist()
_fastqcR2 = fastqcResult()
_fastqcR2.basic = fastqc[0]
_fastqcR2.perBaseSequenceQuality = fastqc[1]
_fastqcR2.perTileSequenceQuality = fastqc[2]
_fastqcR2.perSequenceQualityScores = fastqc[3]
_fastqcR2.perBaseSequenceContent = fastqc[4]
_fastqcR2.perSequenceGCContent = fastqc[5]
_fastqcR2.perBaseNContent = fastqc[6]
_fastqcR2.sequenceLengthDistribution = fastqc[7]
_fastqcR2.sequenceDuplicationLevels = fastqc[8]
_fastqcR2.overrepresentedSequences = fastqc[9]
_fastqcR2.adapterContent = fastqc[10]
with open(pathToR2qc + "fastqc_report.html", "r") as input:
_fastqcR2.fastqcHTMLblob = input.read()
return _fastqcR1, _fastqcR2
def ParseMashGenomeResult(pathToMashScreen, size, depth):
_mashHits = {} #***********************
_PhiX = False #***********************
mashScreen = pandas.read_csv(pathToMashScreen, delimiter='\t', header=None) #read mash report
#0.998697 973/1000 71 0 GCF_000958965.1_matepair4_genomic.fna.gz [59 seqs] NZ_LAFU01000001.1 Klebsiella pneumoniae strain CDPH5262 contig000001, whole genome shotgun sequence [...]
#parse mash result, using winner takes all
scores = mashScreen[1].values
scoreCutoff = int(scores[0][:scores[0].index("/")]) - 300 #find the cut off value to use for filtering the report (300 below max)
index = 0
#find hits with score within top 300
for score in scores:
parsedScore = int(score[:score.index("/")])
if parsedScore >= scoreCutoff:
index+=1
else:
break
#parse what the species are.
for i in range(index):
mr = MashResult()
mr.size = size
mr.depth = depth
mr.identity = float(mashScreen.ix[i, 0])
mr.sharedHashes = mashScreen.ix[i, 1]
mr.medianMultiplicity = int(mashScreen.ix[i, 2])
mr.pvalue = float(mashScreen.ix[i, 3])
mr.queryID = mashScreen.ix[i, 4]
mr.queryComment = mashScreen.ix[i, 5]
mr.accession = mr.queryComment
mr.row = "\t".join(str(x) for x in mashScreen.ix[i].tolist())
qID = mr.queryID
#find gcf accession
gcf = (qID[:qID.find("_",5)]).replace("_","")
gcf = [gcf[i:i+3] for i in range(0, len(gcf), 3)]
mr.gcf = gcf
#find assembly name
mr.assembly = qID[:qID.find("_genomic.fna.gz")]
#score = mashScreen.iloc[[i]][1]
if (mr.queryComment.find("phiX") > -1): #theres phix in top hits, just ignore
_PhiX=True
mr.species = "PhiX"
else: #add the non-phix hits to a list
start = int(mr.queryComment.index(".")) + 3
stop = int (mr.queryComment.index(","))
mr.species = str(mr.queryComment)[start: stop]
_mashHits[mr.species]=mr
return _mashHits, _PhiX
def ParseMashPlasmidResult(pathToMashScreen, size, depth):
mashScreen = pandas.read_csv(pathToMashScreen, delimiter='\t', header=None)
#parse mash result, using winner takes all
scores = mashScreen[1].values
scoreCutoff = int(scores[0][:scores[0].index("/")]) - 100
index = 0
#find hits with score >850
for score in scores:
parsedScore = int(score[:score.index("/")])
if parsedScore >= scoreCutoff:
index+=1
else:
break
_mashPlasmidHits = {} #***********************
#parse what the species are.
for i in range(index):
mr = MashResult()
mr.size = size
mr.depth = depth
mr.identity = float(mashScreen.ix[i, 0])
mr.sharedHashes = mashScreen.ix[i, 1]
mr.medianMultiplicity = int(mashScreen.ix[i, 2])
mr.pvalue = float(mashScreen.ix[i, 3])
mr.queryID = mashScreen.ix[i, 4] #accession
mr.queryComment = mashScreen.ix[i, 5] #what is it
mr.accession = mr.queryID[4:len(mr.queryID)-1]
mr.row = "\t".join(str(x) for x in mashScreen.ix[i].tolist())
#score = mashScreen.iloc[[i]][1]
mr.species = ""
if (mr.identity >= 0.97):
_mashPlasmidHits[mr.accession] = mr
return _mashPlasmidHits
def ParseReadStats(pathToMashLog, pathToTotalBp):
for s in read(pathToMashLog):
if (s.find("Estimated genome size:") > -1 ):
_size = float(s[s.index(": ")+2:])
_totalbp = float(read(pathToTotalBp)[0])
_depth = _totalbp / _size
_depth = float(format(_depth, '.2f'))
return _size,_depth
def ParseBuscoResult(pathToBuscoResult):
buscoOutput = read(pathToBuscoResult)
if (len(buscoOutput) > 0):
br = buscoResult()
br.completeSingle = int(buscoOutput[10].split("\t")[1])
br.completeDuplicate = int(buscoOutput[11].split("\t")[1])
br.fragmented = int(buscoOutput[12].split("\t")[1])
br.mising = int(buscoOutput[13].split("\t")[1])
br.total = int(buscoOutput[14].split("\t")[1])
br.buscoResult = buscoOutput
_buscoResults = br
else: #it should never be <1.... i think
raise Exception("x011 this shouldnt happen...i think")
return _buscoResults
def ParseQuastResult(pathToQuastResult):
qResult = read(pathToQuastResult)
qr = quastResult()
qr.contigsCount = int(qResult[int([i for i,x in enumerate(qResult) if x.find("# contigs\t") > -1][-1])].split("\t")[1])
qr.largestContig = int(qResult[int([i for i,x in enumerate(qResult) if x.find("Largest contig\t") > -1][-1])].split("\t")[1])
qr.N50 = int(qResult[int([i for i,x in enumerate(qResult) if x.find("N50\t") > -1][-1])].split("\t")[1])
qr.NG50 = int(qResult[int([i for i,x in enumerate(qResult) if x.find("NG50\t") > -1][-1])].split("\t")[1])
qr.L50 = int(qResult[int([i for i,x in enumerate(qResult) if x.find("L50\t") > -1][-1])].split("\t")[1])
qr.LG50 = int(qResult[int([i for i,x in enumerate(qResult) if x.find("LG50\t") > -1][-1])].split("\t")[1])
qr.N75 = int(qResult[int([i for i,x in enumerate(qResult) if x.find("N75\t") > -1][-1])].split("\t")[1])
qr.NG75 = int(qResult[int([i for i,x in enumerate(qResult) if x.find("NG75\t") > -1][-1])].split("\t")[1])
qr.L75 = int(qResult[int([i for i,x in enumerate(qResult) if x.find("L75\t") > -1][-1])].split("\t")[1])
qr.LG75 = int(qResult[int([i for i,x in enumerate(qResult) if x.find("LG75\t") > -1][-1])].split("\t")[1])
qr.totalLength = int(qResult[int([i for i,x in enumerate(qResult) if x.find("Total length\t") > -1][-1])].split("\t")[1])
qr.referenceLength = int(qResult[int([i for i,x in enumerate(qResult) if x.find("Reference length\t") > -1][-1])].split("\t")[1])
qr.GC = float(qResult[int([i for i,x in enumerate(qResult) if x.find("GC (%)\t") > -1][-1])].split("\t")[1])
qr.referenceGC = float(qResult[int([i for i,x in enumerate(qResult) if x.find("Reference GC (%)\t") > -1][-1])].split("\t")[1])
qr.genomeFraction = float(qResult[int([i for i,x in enumerate(qResult) if x.find("Genome fraction (%)\t") > -1][-1])].split("\t")[1])
qr.duplicationRatio = float(qResult[int([i for i,x in enumerate(qResult) if x.find("Duplication ratio\t") > -1][-1])].split("\t")[1])
qr.data = qResult
return qr
#endregion
def Main(ID, R1, R2, expectedSpecies):
notes = []
#init the output list
output = []
print(str(datetime.datetime.now()) + "\n\nID: " + ID + "\nR1: " + R1 + "\nR2: " + R2)
output.append(str(datetime.datetime.now()) + "\n\nID: " + ID + "\nR1: " + R1 + "\nR2: " + R2)
#region step 1 pre assembly qc
print("step 1: preassembly QC")
#region call the qc script
if not debug:
print("running pipeline_qc.sh")
#input parameters: 1 = id, 2= forward, 3 = reverse, 4 = output, 5=mashgenomerefdb, $6=mashplasmidrefdb, $7=kraken2db, $8=kraken2plasmiddb
cmd = [scriptDir + "/pipeline_qc.sh", ID, R1, R2, outputDir, mashdb, mashplasmiddb, kraken2db, kraken2plasmiddb]
result = execute(cmd)
#endregion
print("Parsing the QC results")
#region parse results
#parse read stats
pathToMashLog = outputDir + "/qcResult/" + ID + "/" + "mash.log"
pathToTotalBP = outputDir + "/qcResult/" + ID + "/" + "totalbp"
size, depth = ParseReadStats(pathToMashLog, pathToTotalBP) #**************
stats = {}
stats["size"] = size
stats["depth"] = depth
ToJson(stats, "readStats.json")
#parse genome mash results
pathToMashGenomeScreenTSV = outputDir + "/qcResult/" + ID + "/" + "mashscreen.genome.tsv"
mashHits, PhiX = ParseMashGenomeResult(pathToMashGenomeScreenTSV, size, depth) #***********************
ToJson(mashHits, "mashGenomeHit.json")
# parse plasmid mash
pathToMashPlasmidScreenTSV = outputDir + "/qcResult/" + ID + "/" + "mashscreen.plasmid.tsv"
mashPlasmidHits = ParseMashPlasmidResult(pathToMashPlasmidScreenTSV, size, depth) #**************
ToJson(mashPlasmidHits, "mashPlasmidHits.json")
# parse fastqc
pathToFastQCR1 = outputDir + "/qcResult/" + ID + "/" + R1[R1.find(os.path.basename(R1)):R1.find(".")] + "_fastqc/"
pathToFastQCR2 = outputDir + "/qcResult/" + ID + "/" + R2[R2.find(os.path.basename(R2)):R2.find(".")] + "_fastqc/"
fastqcR1,fastqcR2 = ParseFastQCResult(pathToFastQCR1, pathToFastQCR2, ID, R1, R2) #**************
fastqc = {}
fastqc["R1"]=fastqcR1
fastqc["R2"]=fastqcR1
ToJson(fastqc, "fastqc.json")
# parse kraken2 result
pathToKrakenResult = outputDir + "/qcResult/" + ID + "/kraken2.genome.report"
krakenGenomes = ParseKrakenResult(pathToKrakenResult) #**************
ToJson(krakenGenomes, "krakenGenomeHits.json")
#pathToKrakenPlasmidResult = outputDir + "/qcResult/" + ID + "/kraken2.plasmid.report"
#endregion
print("Formatting the QC results")
#region output parsed results
multiple = False
correctSpecies = False
correctReference = ""
output.append("\n\n~~~~~~~QC summary~~~~~~~")
output.append("Estimated genome size: " + str(size))
output.append("Estimated coverage: " + str(depth))
output.append("Expected isolate species: " + expectedSpecies)
output.append("\nFastQC summary:")
output.append("\nforward read qc:")
for key in fastqcR1.toDict():
output.append(key + ": " + fastqcR1.toDict()[key])
if (fastqcR1.toDict()[key] == "WARN" or fastqcR1.toDict()[key] == "FAIL"):
notes.append("FastQC: Forward read, " + key + " " + fastqcR1.toDict()[key])
output.append("\nreverse read qc:")
for key in fastqcR2.toDict():
output.append(key + ": " + fastqcR2.toDict()[key])
if (fastqcR2.toDict()[key] == "WARN" or fastqcR2.toDict()[key] == "FAIL"):
notes.append("FastQC: Reverse read, " + key + " " + fastqcR2.toDict()[key])
output.append("\nKraken2 predicted species (>1%): ")
for key in krakenGenomes:
output.append(krakenGenomes[key].name)
output.append("\nmash predicted genomes (within 300 of highest score): ")
for key in mashHits:
output.append(mashHits[key].species)
output.append("\nmash predicted plasmids (within 100 of highest score): ")
for key in mashPlasmidHits:
output.append(mashPlasmidHits[key].queryComment)
output.append("\nDetailed kraken genome hits: ")
for key in krakenGenomes:
output.append(krakenGenomes[key].row)
output.append("\nDetailed mash genome hits: ")
for key in mashHits:
output.append(mashHits[key].row)
output.append("\nDetailed mash plasmid hits: ")
for key in mashPlasmidHits:
output.append(mashPlasmidHits[key].row)
#qcsummary
output.append("\n\nQC Information:")
present = False
if (len(krakenGenomes) > 1):
output.append("!!!Kraken2 predicted multiple species, possible contamination?")
notes.append("Kraken2: multiple species, possible contamination.")
#multiple = True
elif (len(krakenGenomes) == 1):
multiple = False
for key in krakenGenomes:
if (krakenGenomes[key].name == expectedSpecies):
present = True
if present:
output.append("The expected species is predicted by kraken 2")
#correctSpecies = True
else:
output.append("!!!The expected species is NOT predicted by kraken2, contamination? mislabeling?")
notes.append("Kraken2: Not expected species. Possible contamination or mislabeling")
if (depth < 15):
output.append("!!!Coverage is lower than 15. Estimated depth: " + str(depth))
if(PhiX):
output.append("!!!PhiX contamination, probably nothing to worry about")
notes.append("PhiX contamination")
if (len(mashHits) > 1):
output.append("!!!MASH predicted multiple species, possible contamination?")
multiple=True
elif (len(mashHits) < 1):
output.append("!!!MASH had no hits, this is an unknown species")
notes.append("Mash: Unknown Species")
present=False
for key in mashHits:
spp = str(mashHits[key].species)
if (spp.find(expectedSpecies) > -1 ):
present=True
if present:
output.append("The expected species is predicted by mash")
correctSpecies = True
#notes.append("The expected species is predicted by mash")
else:
output.append("!!!The expected species is NOT predicted by mash, poor resolution? contamination? mislabeling?")
notes.append("Mash: Not expected species. Possible resolution issues, contamination or mislabeling")
if (len(mashPlasmidHits) == 0):
output.append("!!!no plasmids predicted")
notes.append("Mash: no plasmid predicted")
#endregion
#hack: throw exception if this analysis should not proceed due to contamination and mislabelling
if (multiple and not correctSpecies):
out = open(outputDir + "/summary/" + ID +".err", 'a')
out.write('GO RESEQUENCE THIS SAMPLE: It has contamination issues AND mislabelled')
#raise Exception('GO RESEQUENCE THIS SAMPLE: It has contamination issues AND mislabelled')
print("Downloading reference genomes")
#region identify and download a reference genome with mash
referenceGenomes = []
for key in mashHits:
qID = mashHits[key].queryID
gcf = mashHits[key].gcf
assembly = mashHits[key].assembly
url = "ftp://ftp.ncbi.nlm.nih.gov/genomes/all/" + gcf[0] + "/" + gcf[1] + "/" + gcf[2] + "/" + gcf[3] + "/" + assembly + "/" + qID
referencePath = outputDir + "/qcResult/" + ID + "/" + mashHits[key].species.replace(" ","")
referenceGenomes.append(referencePath)
if(not debug):
httpGetFile(url, referencePath + ".gz")
with gzip.open(referencePath + ".gz", 'rb') as f:
gzContent = f.read()
with open(referencePath, 'wb') as out:
out.write(gzContent)
os.remove(referencePath + ".gz")
#endregion
#endregion
#region step2, assembly and qc
print("step 2: genome assembly and QC")
#region call the script
correctAssembly = ""
if not debug:
#input parameters: 1 = id, 2= forward, 3 = reverse, 4 = output, 5=tmpdir for shovill, 6=reference genome, 7=buscoDB
#if (len(mashHits) == 1):
if (len(referenceGenomes) > 1):
for item in referenceGenomes:
if (item.find(expectedSpecies.replace(" ", "")) > -1): #found the right genome
correctAssembly = os.path.basename(item)
else:
correctAssembly = os.path.basename(referenceGenomes[0])
if (correctAssembly == ""):
raise Exception("no reference genome...crashing")
if (not multiple and correctSpecies):
print("Noncontaminated Genome assembly...")
cmd = [scriptDir + "/pipeline_assembly.sh", ID, R1, R2, outputDir, tempDir, referenceGenomes[0], buscodb, correctAssembly]
result = execute(cmd)
elif (multiple and correctSpecies):
#input parameters: 1 = id, 2= forward, 3 = reverse, 4 = output, 5=tmpdir for shovill, 6=reference genome (csv, no spaces) , 7=buscodb #
print("Contaminated Genome assembly...")
cmd = [scriptDir + "/pipeline_assembly_contaminant.sh", ID, R1, R2, outputDir, tempDir, ",".join(referenceGenomes), buscodb, correctAssembly]
result = execute(cmd)
elif (multiple and not correctSpecies):
print("Contaminated Genome assembly...No Correct Species Either")
raise Exception("contamination and mislabeling...crashing")
#cmd = [scriptDir + "/pipeline_assembly_contaminant.sh", ID, R1, R2, outputDir, tempDir, ",".join(referenceGenomes), buscodb, correctAssembly]
#result = execute(cmd)
elif (not multiple and not correctSpecies):
print("Noncontaminated Genome assembly...No Correct species though")
cmd = [scriptDir + "/pipeline_assembly.sh", ID, R1, R2, outputDir, tempDir, referenceGenomes[0], buscodb, correctAssembly]
result = execute(cmd)
#endregion
print("Parsing assembly results")
#region parse assembly_qc from quast and busco
#get the correct busco and quast result file to parse
correctAssembly = ""
buscoPath = ""
quastPath = ""
if ((not multiple and correctSpecies) or (not multiple and not correctSpecies)): #only 1 reference genome
buscoPath = (outputDir + "/assembly_qc/" + ID + "/" + ID + ".busco" + "/short_summary_" + ID + ".busco.txt")
quastPath = (outputDir + "/assembly_qc/" + ID + "/" + ID + ".quast" + "/report.tsv")
correctAssembly = ID
elif(multiple and correctSpecies): #multiple reference genome, need to find the one we care about
for item in referenceGenomes:
if (item.find(expectedSpecies.replace(" ", "")) > -1): #found the right genome
buscoPath = (outputDir + "/assembly_qc/" + ID + "/" + ID + "." + os.path.basename(item) + ".busco" + "/short_summary_" + ID + "." + os.path.basename(item) + ".busco.txt")
quastPath = (outputDir + "/assembly_qc/" + ID + "/" + ID + "." + os.path.basename(item) + ".quast/runs_per_reference/" + os.path.basename(item) + "/report.tsv")
correctAssembly = ID + "." + os.path.basename(item)
elif(multiple and not correctSpecies): #the most fked up case, dont even bother? just crash the damn program for now
raise Exception('GO RESEQUENCE THIS SAMPLE: It has contamination issues AND mislabelled')
if (buscoPath == "" or quastPath == ""):
raise Exception('theres no reference genome for this sample for whatever reason...')
#populate the busco and quast result object
buscoResults = ParseBuscoResult(buscoPath)#********************************
quastResults = ParseQuastResult(quastPath)#********************************
#endregion
#endregion
start = time.time()#time the analysis
#analysis time
Main(ID, R1, R2, expectedSpecies)
end = time.time()
print("Finished!\nThe analysis used: " + str(end-start) + " seconds")<file_sep>/M2_pipeline_tree.sh
#!/bin/bash -e
#$ -V # Pass environment variables to the job
#$ -N CPO_pipeline # Replace with a more specific job name
#$ -cwd # Use the current working dir
#$ -pe smp 8 # Parallel Environment (how many cores)
#$ -l h_vmem=11G # Memory (RAM) allocation *per core*
#$ -e ./logs/$JOB_ID.err
#$ -o ./logs/$JOB_ID.log
#input parameters: 1 = id, 2= outputdir
#step 1, mash QC
source activate snippy
threads=8
ram=80
outputDir="$1"
reference="$2"
contigs="$3"
echo "parameters: "
echo "outputDir: $outputDir"
echo "outputDir: $reference"
echo "outputDir: $contigs"
echo "outputDir: $threads"
echo "outputDir: $ram"
#treeDir="$outputDir"/trees
treeFileDir="$outputDir"/trees
#mkdir -p "$treeDir"
mkdir -p "$treeFileDir"
contigArray=()
#find snps within each genome
IFS=',' read -ra ADDR <<< "$contigs" #hax to read in a csv
for i in "${ADDR[@]}"; do
refG=`basename $i`
echo $refG
snippy --cpus "$threads" --outdir "$treeFileDir"/"$refG" --reference $reference --ctgs $i
contigArray+=($refG)
done
cd $treeFileDir
#create an alignment from the snps
snippy-core --prefix core *
#create a distance matrix from alignment
snp-dists core.full.aln > distance.tab
#make a nj tree from the matrix
clustalw2 -tree -infile=core.full.aln -outputtree=nj
source deactivate
echo "done step 4"
<file_sep>/README.md
# CPO_Prediction
Scripts for the characterization and visualization of genomics data for carbapenemase producing organisms or bacteria in general.
Module 1: QC and Assembly: See wrapper script pipeline_sequdas.py
usage: $>python M1_pipeline_sequdas.py -i $ID -f $ForwardRead -r $ReverseRead -o $OutDir -e "$Species"
Module 2: Prediction and visualization: See wrapper script pipeline_prediction.py and pipeline_tree.py
Usage: this module is implemented in galaxy. For details see https://github.com/imasianxd/CPO_Prediction_Galaxy
| ce47ad45cf49fc1dbf477f6e888d6743e374b3fc | [
"Markdown",
"Python",
"Shell"
] | 9 | Python | bfjia/CPO_Prediction | a83d00a98a22248ad923fe488ad741b3bd8a208f | 8bc00a36ddcdcc99e9312be51b4c5d4f6cb514ad |
refs/heads/develop | <repo_name>ursine/blocklister<file_sep>/requirements.txt
Flask==0.10.1
requests >=2.9,<3.0
Flask-Limiter==0.9.1
limits
six
future
mock
ipaddress
configparser
unittest2
<file_sep>/setup.py
from setuptools import setup, find_packages
from pip.req import parse_requirements
from os.path import join
install_reqs = parse_requirements('requirements.txt', session=False)
reqs = [str(ir.req) for ir in install_reqs]
NAME = "blocklister"
DESCRIPTION = "Create Mikrotik Firewall address-lists and offer them via http"
AUTHOR = "<NAME>"
AUTHOR_EMAIL = "<EMAIL>"
VERSION = open(join(NAME, 'version.txt')).read().strip()
LONG_DESCRIPTION = open("README.rst").read()
setup(
name=NAME,
version=VERSION,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
author=AUTHOR,
author_email=AUTHOR_EMAIL,
license="Private",
include_package_data=True,
install_requires=reqs,
entry_points={
'console_scripts': [
'blocklister-updater=blocklister.updater:run'
]
},
dependency_links=[],
packages=find_packages(exclude=["tests.*", "tests"]),
zip_safe=False,
)
<file_sep>/fabfile.py
from StringIO import StringIO
from os import path, environ
import fabric.api as fab
import fabric.colors as clr
PYREPO_DIR = "/var/www/gefoo.org/pyrepo"
PYREPO_URL = "https://pyrepo.gefoo.org"
DEPLOY_DIR = "/var/www/gefoo.org/blocklister"
PACKAGE_NAME = 'blocklister'
USER = 'blocklister'
fab.env.roledefs = {
'pyrepo': ['pyrepo.gefoo.org'],
'prod': ['spoon.gefoo.org'],
'staging': ['foodtaster.lchome.net'],
}
@fab.task
def develop():
"""
Prepares a development environment
"""
dev_packages = [
'pytest', 'pytest-xdist', 'pytest-pep8', 'tox', 'httpie'
]
if not path.exists("env"):
fab.local("virtualenv -p /usr/bin/python3 env")
fab.local("env/bin/pip install --upgrade pip setuptools")
fab.local("env/bin/python setup.py develop")
fab.local("env/bin/pip install {}".format(" ".join(dev_packages)))
@fab.task
def test():
"""
Run Py.test
"""
fab.local("env/bin/py.test -f --color yes blocklister")
@fab.roles('pyrepo')
@fab.task
def publish():
"""
Publish package to pyrepo.gefoo.org
"""
fab.local("env/bin/python setup.py sdist")
tar_filename = fab.local(
"env/bin/python setup.py --fullname", capture=True
)
dist_filename = "dist/{}.tar.gz".format(tar_filename)
fab.put(dist_filename, PYREPO_DIR)
@fab.task
def deploy():
"""
Deploy package
"""
branch = fab.local('git rev-parse --abbrev-ref HEAD', capture=True)
if branch == "develop":
fab.local("env/bin/python setup.py sdist")
tar_filename = "{}.tar.gz".format(
fab.local(
"env/bin/python setup.py --fullname", capture=True
)
)
dist_filename = "dist/{}".format(tar_filename)
dest_filename = "/tmp/{}".format(tar_filename)
fab.put(dist_filename, dest_filename)
fab.env.user = USER
with fab.cd(DEPLOY_DIR):
fab.run(
"env/bin/pip uninstall --trusted-host pyrepo.gefoo.org -y {}"
.format(PACKAGE_NAME))
fab.run(
"env/bin/pip install --trusted-host pyrepo.gefoo.org "
"--upgrade {}"
.format(dest_filename))
else:
fab.execute("publish")
fab.env.user = USER
with fab.cd(DEPLOY_DIR):
fab.run("env/bin/pip install --upgrade pip")
fab.run("env/bin/pip install --upgrade setuptools")
fab.run(
"env/bin/pip install --trusted-host pyrepo.gefoo.org "
"--upgrade -f {} {}"
.format(PYREPO_URL, PACKAGE_NAME)
)
@fab.task
def bootstrap():
"""
Bootstrap environment
"""
# Install system dependencies
deps = [
'apache2',
'libapache2-mod-wsgi',
'curl',
'gzip',
'python-setuptools',
]
fab.sudo("aptitude install -q -y {0}".format(" ".join(deps)))
fab.sudo("easy_install virtualenv")
# Create Application User on the node
fab.env.warn_only = True
if not fab.run("cat /etc/passwd | grep \"^{}:.*$\"".format(USER)):
fab.sudo(
"useradd -d {0} -r -s /bin/sh {1}".format(DEPLOY_DIR, USER)
)
fab.sudo(
"install -o {0} -g {0} -d {1}".format(USER, DEPLOY_DIR)
)
home = environ['HOME']
publickeyfile = "{0}/.ssh/id_rsa.pub".format(home)
if not path.exists(publickeyfile):
print clr.red(
"Could not continue! You need a public key on the target "
"machine!"
)
publickey = readfile(publickeyfile)
with fab.cd(DEPLOY_DIR):
fab.sudo("[ -d .ssh ] || mkdir .ssh")
fab.sudo("echo {0} > .ssh/authorized_keys".format(publickey))
fab.sudo("chown {0}.{0} .ssh -R".format(USER))
fab.sudo("install -o {0} -g {1} -d log".format("www-data", USER))
fab.sudo("install -o {0} -g {0} -d conf".format(USER, USER))
fab.sudo("install -o {0} -g {0} -d wsgi".format(USER, USER))
# Create Apache config files
apache_content = apache_template(
PACKAGE_NAME,
DEPLOY_DIR,
USER,
servername="{}.gefoo.org".format(PACKAGE_NAME)
)
apache_filename = (
"/etc/apache2/sites-available/{}.conf".format(PACKAGE_NAME)
)
fab.put(StringIO(apache_content), apache_filename, use_sudo=True)
fab.env.user = USER
with fab.cd(DEPLOY_DIR):
fab.run("virtualenv env")
# Create config files
apache_content = apache_template(
PACKAGE_NAME,
DEPLOY_DIR,
USER,
servername="{}.gefoo.org".format(PACKAGE_NAME)
)
apache_filename = (
"/etc/apache2/sites-available/{}.conf".format(PACKAGE_NAME)
)
wsgi_content = wsgi_template(
PACKAGE_NAME,
DEPLOY_DIR,
)
wsgi_filename = "{0}/wsgi/{1}.wsgi".format(DEPLOY_DIR, PACKAGE_NAME)
logging_content = logging_template()
logging_filename = "{0}/logging.ini".format(DEPLOY_DIR)
fab.put(StringIO(wsgi_content), wsgi_filename)
fab.put(StringIO(logging_content), logging_filename)
@fab.task
def unbootstrap():
"""
Remove bootstrap
"""
fab.sudo("rm -Rf {0}".format(DEPLOY_DIR))
fab.sudo("userdel {0}".format(USER))
def readfile(filename):
if path.exists(filename):
return open(filename, "r").read().strip()
def wsgi_template(appname, path, logging_level="INFO"):
"""
Returns a wsgi configuration based on this template
"""
template = (
'import os\n'
'import logging\n'
'import logging.config\n'
'\n'
'activate_this = "{path}/env/bin/activate_this.py"\n'
'execfile(activate_this, dict(__file__=activate_this))\n'
'\n'
'logging.basicConfig(level=logging.{logging_level})\n'
'logging.config.fileConfig("{path}/logging.ini")\n'
'\n'
'from {app}.main import app as application\n'
.format(
app=appname,
app_up=appname.upper(),
path=path,
logging_level=logging_level
)
)
return template
def logging_template():
"""
Returns a logging configuration based on this template
"""
template = (
'[loggers]\n'
'keys=root\n'
'\n'
'[handlers]\n'
'keys=consoleHandler\n'
'\n'
'[formatters]\n'
'keys=simpleFormatter\n'
'\n'
'[logger_root]\n'
'level=DEBUG\n'
'handlers=consoleHandler\n'
'\n'
'[handler_consoleHandler]\n'
'class=StreamHandler\n'
'level=DEBUG\n'
'formatter=simpleFormatter\n'
'args=(sys.stdout,)\n'
'\n'
'[formatter_simpleFormatter]\n'
'format=%(asctime)s - %(name)s - %(levelname)s - %(message)s\n'
'datefmt=\n')
return template
def apache_template(app, path, user, servername=None):
template = (
'<VirtualHost *:80>\n'
' ServerName {servername}\n'
' \n'
' WSGIDaemonProcess {app} user={user} group={user} threads=5\n'
' WSGIScriptAlias / {path}/wsgi/{app}.wsgi\n'
' \n'
' <Directory {path}>\n'
' WSGIProcessGroup {app}\n'
' WSGIApplicationGroup %{{GLOBAL}}\n'
' Order deny,allow\n'
' Allow from all\n'
' </Directory>\n'
' \n'
' # Log Files\n'
' LogLevel warn\n'
' CustomLog {path}/log/access.log combined\n'
' ErrorLog {path}/log/error.log\n'
'</VirtualHost>\n'
)
if not servername:
servername = fab.prompt(
"What will be the apache servername?",
default="app.local.net"
)
return template.format(
app=app,
path=path,
servername=servername,
user=user
)
| f3ea84f967cd3e86495ecf74d604786cc677e40b | [
"Python",
"Text"
] | 3 | Text | ursine/blocklister | 4d5333cfeb2368f623eb9a18314cd50fee45ece9 | d9844bab1376a8ce209ef1074666f8c6a3b23c36 |
refs/heads/master | <repo_name>danielsnider/lost_comms_recovery<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 2.8.3)
project(lost_comms_recovery)
find_package(catkin REQUIRED COMPONENTS
rospy
actionlib
actionlib_msgs
sensor_msgs
geometry_msgs
move_base_msgs
)
catkin_python_setup()
catkin_package(
LIBRARIES ${PROJECT_NAME}
CATKIN_DEPENDS rospy actionlib actionlib_msgs sensor_msgs geometry_msgs move_base_msgs
)
catkin_install_python(
PROGRAMS nodes/lost_comms_recovery
DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)
# Install launch files
install(DIRECTORY launch/
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/launch
)
<file_sep>/README.md
# lost_comms_recovery [](http://build.ros.org/job/Kbin_uX64__lost_comms_recovery__ubuntu_xenial_amd64__binary)
If your robot loses connection to the base station it will navigate to a configurable home.
## Quick Start
1. Install:
```
$ sudo apt-get install ros-kinetic-lost-comms-recovery
```
2. Launch node:
```
$ roslaunch lost_comms_recovery lost_comms_recovery.launch
```
3. Normal output:
```
$ roslaunch lost_comms_recovery lost_comms_recovery.launch ips_to_monitor:=192.168.190.136
[INFO] Monitoring base station on IP(s): 192.168.190.136.
[INFO] Connected to base station.
[INFO] Connected to base station.
...
[ERROR] No connection to base station.
[INFO] Connected to move_base.
[INFO] Executing move_base goal to position (x,y) 0.0, 0.0.
[INFO] Inital goal status: PENDING
[INFO] This goal has been accepted by the simple action server
[INFO] Final goal status: SUCCEEDED
[INFO] Goal reached.
```
**Full documentation on wiki: [http://wiki.ros.org/lost_comms_recovery](http://wiki.ros.org/lost_comms_recovery)**
<file_sep>/nodes/lost_comms_recovery
#!/usr/bin/env python
from lost_comms_recovery import lost_comms_recovery
if __name__ == '__main__':
lost_comms_recovery.main()
<file_sep>/src/lost_comms_recovery/lost_comms_recovery.py
#!/usr/bin/env python
import sys
import time
import rospy
import subprocess
import actionlib
from sensor_msgs.msg import Joy
from geometry_msgs.msg import Twist, PoseWithCovarianceStamped
from actionlib_msgs.msg import GoalStatus, GoalStatusArray
from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal
def ping_host(host):
ping_fail_count = rospy.get_param('~ping_fail_count', 2)
ping_command = "ping -c %s -n -W 1 %s" % (ping_fail_count, host)
# TODO: don't shell out, use a more secure python library
p = subprocess.Popen(ping_command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
(output, error) = p.communicate()
returncode = p.returncode
return output, error, returncode
class RecorveryController():
def __init__(self):
# By default recover to a pose at the origin of the frame
self.recovery_pose = PoseWithCovarianceStamped()
self.recovery_pose.pose.pose.position.x = 0.0
self.recovery_pose.pose.pose.position.y = 0.0
self.recovery_pose.pose.pose.position.z = 0.0
self.recovery_pose.pose.pose.orientation.x = 0.0
self.recovery_pose.pose.pose.orientation.y = 0.0
self.recovery_pose.pose.pose.orientation.z = 0.0
self.recovery_pose.pose.pose.orientation.w = 1
rospy.Subscriber('recovery_pose', PoseWithCovarianceStamped,
self.recovery_pose_callback)
self.twist_publisher = rospy.Publisher('cmd_vel', Twist, queue_size=10)
self.joy_publisher = rospy.Publisher('joy', Joy, queue_size=10)
def recovery_pose_callback(self, data):
rospy.loginfo("Not connected to move_base.")
self.recovery_pose = data
def working_comms(self):
working_comms = False
for ip in self.ips.split(','):
(output, error, returncode) = ping_host(ip)
if returncode == 0:
working_comms = True
return working_comms
def zero_joystick(self):
rospy.loginfo('Zeroing joystick.')
joy = Joy()
joy.axes = [0] * 25 # Set axes to an array of zeros. Needed because
# the default value here is an empty list which won't zero anything
joy.buttons = [0] * 25 # Set buttons to an array of zeros
self.joy_publisher.publish(joy)
def stop_motors(self):
rospy.loginfo('Stopping motors.')
twist = Twist() # zero motion
self.twist_publisher.publish(twist)
def connect_to_move_base(self):
self.move_base = actionlib.SimpleActionClient('move_base', MoveBaseAction)
if self.move_base.wait_for_server(timeout=rospy.Duration(3)):
rospy.loginfo("Connected to move_base.")
self.connected_to_move_base = True
else:
rospy.loginfo("Not connected to move_base.")
self.connected_to_move_base = False
return self.connected_to_move_base
def navigation_goal_to(self, pose):
# Create move_base goal
goal = MoveBaseGoal()
goal.target_pose.pose = pose.pose.pose
goal.target_pose.header.frame_id = rospy.get_param('~goal_frame_id', 'map')
rospy.loginfo('Executing move_base goal to position (x,y) %s, %s.' %
(goal.target_pose.pose.position.x, goal.target_pose.pose.position.y))
# Send goal
self.move_base.send_goal(goal)
rospy.loginfo('Inital goal status: %s' % GoalStatus.to_string(self.move_base.get_state()))
status = self.move_base.get_goal_status_text()
if status:
rospy.loginfo(status)
# Wait for goal result
self.move_base.wait_for_result()
rospy.loginfo('Final goal status: %s' % GoalStatus.to_string(self.move_base.get_state()))
status = self.move_base.get_goal_status_text()
if status:
rospy.loginfo(status)
def goal_in_progress(self):
data = rospy.wait_for_message('/move_base/status', GoalStatusArray)
if data.status_list == []: # you see this if move_base just started
return False
# See possible statuses http://docs.ros.org/api/actionlib_msgs/html/msg/GoalStatus.html
PENDING = 0
ACTIVE = 1
status_codes = [status.status for status in data.status_list]
if PENDING in status_codes:
return True
if ACTIVE in status_codes:
return True
return False
def do_recovery(self):
if rospy.is_shutdown(): return
rospy.logerr('No connection to base station.')
if self.connect_to_move_base():
if self.goal_in_progress():
rospy.loginfo("Navigation in progress, not recovering until finished...")
return
self.navigation_goal_to(self.recovery_pose)
else:
self.zero_joystick()
self.stop_motors()
def main_loop(self):
while not rospy.is_shutdown():
if not self.working_comms():
self.do_recovery()
else:
rospy.loginfo('Connected to base station.')
time.sleep(3)
def main():
rospy.init_node("lost_comms_recovery")
Controller = RecorveryController()
Controller.ips = rospy.get_param('~ips_to_monitor')
rospy.loginfo('Monitoring base station on IP(s): %s.' % Controller.ips)
Controller.main_loop() # start monitoring
| eca4761157c5ae6d8aec78800beeb6e627193782 | [
"Markdown",
"Python",
"CMake"
] | 4 | CMake | danielsnider/lost_comms_recovery | bfb9ed4c62f424ee8af8d2b756f8fc3acde851b2 | 78ad002448a59da1a450c891c1125dba16a8c9c4 |
refs/heads/master | <file_sep># OLT.crack
To mark answers quickly.
## Prerequisites
[Python3](https://www.python.org) must be pre-installed
## STEPS
- Clone or download all three files.
- Open terminal or CMD
- Change current directory to where these files are located.
```bash
cd /path/to/project
```
- Install dependencies
```bash
python3 -m pip install -r requirements.txt --user
```
Or simply
```bash
pip install -r requirements.txt
```
- Install Google Tesseract OCR (additional info how to install the engine on Linux, Mac OSX and Windows). You must be able to invoke the tesseract command as tesseract. If this isn’t the case, for example because tesseract isn’t in your PATH, you will have to change the “tesseract_cmd” variable pytesseract.pytesseract.tesseract_cmd. Under Debian/Ubuntu you can use the package tesseract-ocr. For Mac OS users. please install homebrew package tesseract.
( Taken from  )
### On Linux
sudo apt update
sudo apt install tesseract-ocr
sudo apt install libtesseract-dev
### On Mac
brew install tesseract
### On Windows
download binary from https://github.com/UB-Mannheim/tesseract/wiki. then add pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files (x86)\\Tesseract-OCR\\tesseract.exe' to your script. (replace path of tesseract binary if necessary)
references: https://pypi.org/project/pytesseract/ (INSTALLATION section) and https://github.com/tesseract-ocr/tesseract/wiki#installation
- Run the script:
```bash
python3 master.py
```
- Follow the instructions, open the browser and terminal/cmd side by side, otherwise it may not work.
<img src="https://i.ibb.co/xqZYj7m/Screenshot-from-2020-05-28-15-22-28.png">
- Thanks!
<file_sep>import pytesseract as pt
import pyautogui as pg
import sys
import json
colors = {'HEADER' : "",
'OKBLUE' : "",
'RED' : "",
'OKYELLOW' : "",
'GREEN' : "",
'LIGHTBLUE' : "",
'WARNING' : "",
'FAIL' : "",
'ENDC' : "",
'BOLD' : "",
'UNDERLINE' : "" }
def gather_data(location):
try:
l = [""]
t = int(input("Enter the number of questions"))
print(colors['OKYELLOW']+"[+] Please wait while collecting data....")
print("[+] Collecting data. Please do not touch the mouse or keyboard until it is done!"+colors['ENDC'])
for i in range(t):
image = pg.screenshot()
text = pt.image_to_string(image)
pg.click(location)
l.append(text)
print(colors['LIGHTBLUE']+"\rCollecting Question "+str(i+1),end=" ")
sys.stdout.flush()
print("\n[+] Data collected successfully.. Saving data.."+colors['ENDC'])
f = open("questions.json","w")
json.dump(l, f)
return l
except:
print(colors['FAIL']+"[!] Somehow program Crashed! Saving the collected data..."+colors['ENDC'])
f = open("questions.json","w")
json.dump(l, f)
return l
def answerQueries(l):
s = input(colors['GREEN']+"[+] Enter the keywords to search. Press CTRL + C to quit>> "+colors['ENDC'])
for i in range(len(l)):
if s in l[i]:
print(colors['OKYELLOW']+"Found Match in "+str(i)+colors['ENDC'])
def detect_save_and_submit():
image = "button.png"
location = pg.locateCenterOnScreen(image),confidence=0.5)
if location==None:
print(colors['FAIL']+"[!] Could not detect Save & Next Button..\n[!] Please make sure it is visible on the screen."+colors['ENDC'])
tryagain = input(colors['GREEN']+"[+] Do you want to try again(Y/N)?"+colors['ENDC'])
if tryagain in "yY":
return detect_save_and_submit()
else:
return None
print(colors['GREEN']+"[+] Next button found at "+str(location))
print("[+] Now move to the first question"+colors['ENDC']) # and wait while collecting data.
pg.moveTo(location)
return location
if __name__=="__main__":
query = input(colors['GREEN']+"[+] Welcome! Please login to the exam and open terminal & browser in split screen mode. Make Sure that Questions and Save&Next Button are visible.\n"+colors['ENDC']+colors['OKYELLOW']+"[+] Hit Enter once done that."+colors['ENDC'])
isFirstTime = input(colors['LIGHTBLUE']+"[+] Is it a new exam or you have already saved any data before(Enter 1 or 2)?"+colors['ENDC'])
l = []
if isFirstTime == "1":
print("[+] Creating new Exam....Done!")
print("[+] Detecting Save & Next Button....")
saveandnext = detect_save_and_submit()
if saveandnext==None:
print("[-] Exiting the program...")
exit(0)
l = gather_data(saveandnext)
print("[+] Now you can enter the queries..")
print(colors['WARNING']+"[!] Note that if the program was crashed, it won't answer all the queries.."+colors['ENDC'])
else:
print("[+] Detecting already save files...")
try:
f = open("questions.json","r")
l = json.load(f)
except:
print(colors['FAIL']+"[!] Could not find any file... Exiting.."+colors['ENDC'])
exit(0)
try:
while True:
answerQueries(l)
except KeyboardInterrupt:
print("\n[+] Quitting the program...")
| ac3564c9cc5d2663703bae6a3cefc9c5cefea9c8 | [
"Markdown",
"Python"
] | 2 | Markdown | mukulbindal/OLT.crack | 6bd2f45da76ba659b591eefc7ab2d7d9d746f0db | beae4c33cfeca6e082a1c8c762b23df56b708f9c |
refs/heads/main | <repo_name>ImC4k/my-todo-backend<file_sep>/src/main/java/com/imc4k/todolist/service/TodoService.java
package com.imc4k.todolist.service;
import com.imc4k.todolist.model.Todo;
import com.imc4k.todolist.repository.TodosRepository;
import com.imc4k.todolist.exception.TodoNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class TodoService {
@Autowired
private TodosRepository todosRepository;
public List<Todo> getAll() {
return todosRepository.findAll();
}
public Todo getById(String id) {
return todosRepository.findById(id).orElseThrow(TodoNotFoundException::new);
}
public Todo createTodo(Todo newTodo) {
if (newTodo.getDone() == null) {
newTodo.setDone(false);
}
if (newTodo.getLabelIds() == null) {
newTodo.setLabelIds(Collections.emptyList());
}
return todosRepository.save(newTodo);
}
public Todo update(Todo updatedTodo) {
this.getById(updatedTodo.getId());
return createTodo(updatedTodo);
}
public void delete(String id) {
this.getById(id);
todosRepository.deleteById(id);
}
public void removeLabelId(String targetLabelId) {
List<Todo> todoItemsWithTargetLabel = todosRepository.findAllByLabelIdsIn(Collections.singletonList(targetLabelId));
todoItemsWithTargetLabel.forEach(todoItem -> {
List<String> remainingLabelIds = todoItem.getLabelIds().stream().filter(id -> !id.equals(targetLabelId)).collect(Collectors.toList());
todoItem.setLabelIds(remainingLabelIds);
update(todoItem);
});
}
}
<file_sep>/src/main/java/com/imc4k/todolist/dto/TodoUpdateRequest.java
package com.imc4k.todolist.dto;
import java.util.List;
public class TodoUpdateRequest {
private String text;
private Boolean done;
private List<String> labelIds;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Boolean getDone() {
return done;
}
public void setDone(Boolean done) {
this.done = done;
}
public List<String> getLabelIds() {
return labelIds;
}
public void setLabelIds(List<String> labelIds) {
this.labelIds = labelIds;
}
}
<file_sep>/src/main/java/com/imc4k/todolist/exception/TodoNotFoundException.java
package com.imc4k.todolist.exception;
public class TodoNotFoundException extends RuntimeException{
public TodoNotFoundException() {
super("Todo not found");
}
}
| 1e261b9a32af155be5b8f02a7dfe749b4fbcd689 | [
"Java"
] | 3 | Java | ImC4k/my-todo-backend | 8738ecd29bb7e4f3b221999d62b23302c985e28a | 3d59c9030a77016175b4cc9fc979a6e4108928f5 |
refs/heads/master | <file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *str1;
FILE *str2;
char filename[100];
char c;
int key = 0;
printf("Enter the filename to open for read\n");
scanf("%s", filename);
str1 = fopen(filename, "r");
if(str1 == NULL)
{
printf("Cannot open file");
exit(0);
}
printf("Enter the filename to open for writing\n");
scanf("%s", filename);
str2 = fopen(filename, "w");
if(str2 == NULL)
{
printf("Cannot open file");
exit(0);
}
c = fgetc(str1);
int i;
int count[26];
for (i = 0; i < 26; i++)
{
count[i] = 0;
}
for(c = fgetc(str1); c != EOF; c = fgetc(str1))
{
if (c >= 65 && c <= 90)
{
count[c-65]++;
}
else if (c >= 97 && c <= 122)
{
count[c-97]++;
}
}
int j;
int key1 = 0;
int key2 = 0;
for (i = 0; i < 26; i++)
{
if( count[i] > count[key])
{
key2 = key1;
key1 = key;
key = i;
}
}
for( i =0; i <3; i++)
{
if ( i == 1)
{
key = key1;
}
if ( i == 2)
{
key = key2;
}
printf("\n\nOur key: %d", key);
rewind(str1);
for(c = fgetc(str1); c != EOF; c = fgetc(str1))
{
if (c >= 65 && c <= 90)
{
if (( c-65 -key) <0)
{
c = c+ 26;
}
c = ((c - 65) - key) % 26 + 97;
fputc(c, str2);
printf("%c", c);
}
else if (c >= 97 && c <= 122)
{
if (( c-97 -key) <0)
{
c = c+ 26;
}
c = ((c - 97) - key) % 26 + 97;
fputc(c, str2);
printf("%c", c);
}
else
{
c = c;
fputc(c, str2);
printf("%c", c);
}
}
}
printf("contents copied to ", filename);
fclose(str1);
fclose(str2);
return 0;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *str1;
FILE *str2;
char filename[100];
char c;
int key = 9;
printf("Enter the filename to open for read\n");
scanf("%s", filename);
str1 = fopen(filename, "r");
if(str1 == NULL)
{
printf("Cannot open file");
exit(0);
}
printf("Enter the filename to open for writing\n");
scanf("%s", filename);
str2 = fopen(filename, "w");
if(str2 == NULL)
{
printf("Cannot open file");
exit(0);
}
c = fgetc(str1);
while (c != EOF)
{
if (c >= 65 && c <= 90)
{
c = ((c +32) + key -97) % 26 + 97;
fputc(c, str2);
}
else if (c >= 97 && c <= 122)
{
c = (c + key -97) % 26 +97;
fputc(c, str2);
}
else
{
c = c;
fputc(c, str2);
}
c = fgetc(str1);
}
printf("contents copied to ", filename);
fclose(str1);
fclose(str2);
return 0;
}
| f0603f80dfa43227f17443dedbec323c77808b56 | [
"C"
] | 2 | C | clee9604/Assignment2 | 4faf289cc25159b743b7b9bfaebe3c6f96c224ff | 339dac1fe84a4e708b472303efa879f1133e5904 |
refs/heads/master | <repo_name>PrasannaPattankar/CntactlistCrud<file_sep>/src/actions/types.js
export const SELECT_CONTACT='SELECT_CONTACT';
export const CREATE_CONTACT='CREATE_CONTACT';
export const UPDATE_CONTACT='UPDATE_CONTACT';
export const DELETE_CONTACT='DELETE_CONTACT';
export const START_CONVERSATION='START_CONVERSATION';
export const END_CONVERSATION='END_CONVERSATION';
export const CREATE_CONVERSATION='CREATE_CONVERSATION';
| a072be94cfa6f18a3544b082cb851909a3b2c043 | [
"JavaScript"
] | 1 | JavaScript | PrasannaPattankar/CntactlistCrud | 5f64bad2c537ea9bf532f3cd852666d650bfc682 | 46f52d93febf2607174cf9098d9d0bbfeccc004e |
refs/heads/master | <file_sep>using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NGame.Source.GUI
{
public abstract class MenuObject : Entity, IUpdate, IDraw
{
public abstract float Width { get; protected set; }
public abstract float Height { get; protected set; }
protected Vector2 AbsolutePosition
{
get
{
if (Owner != null)
{
Vector2 absPos = new Vector2(Position.X + Owner.Position.X - (Width / 2), Position.Y + Owner.Position.Y - (Height / 2));
return absPos;
}
else return Position;
}
}
public bool Visible { get; set; } = true;
public MenuObject()
{
}
public MenuObject(Vector2 position)
{
Position = position;
}
public abstract void Draw(GameTime gameTime);
}
}
<file_sep>using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NGame.Source
{
public interface IDraw
{
bool Visible { get; }
void Draw(GameTime gameTime);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
namespace NGame.Source
{
public class Camera : Entity
{
public override Vector2 Dimension
{
get
{
return new Vector2(Globals.graphicsDevice.GraphicsDevice.Viewport.Width,
Globals.graphicsDevice.GraphicsDevice.Viewport.Height);
}
}
public Entity Target
{
get;
private set;
}
public override Vector2 Position
{
get
{
if (Target != null && Enabled)
return Target.Position;
else
return base.Position;
}
set => base.Position = value;
}
public void SetTarget (Entity target)
{
Target = target;
}
public void UnsetTarget()
{
Target = null;
}
}
}
<file_sep>using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NGame.Source
{
public class Entity : IUpdate
{
public Entity Owner { get; set; }
public bool Enabled { get; set; } = true;
public virtual Vector2 Position { get; set; } = Vector2.Zero;
public virtual Vector2 Dimension { get; protected set; } = new Vector2(1, 1);
public float Rotation { get; set; } = 0f;
public virtual void Update(GameTime gameTime)
{
}
public virtual void SetOwner(Entity owner)
{
Owner = owner;
}
}
}
<file_sep>using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NGame.Source.Graphics
{
public static class GraphicsHelper
{
private static Camera _TempCam = new Camera();
private static Texture2D _Texture = new Texture2D(Globals.graphicsDevice.GraphicsDevice, 1, 1);
public static void DrawRectangle(float x, float y, float width, float height, Color color)
{
_Texture.SetData<Color>(new Color[1] { color });
Globals.spriteBatch.Draw(_Texture, new Rectangle((int)x, (int)y, (int)width, (int)height), color);
}
/// <summary>
/// This helper methods calculates X value based on the position of the camera, position of
/// the entity (Including its relation to an owner), and the offset value
/// </summary>
/// <param name="camera">The Camera Entity</param>
/// <param name="entity">The Entity to be drawn</param>
/// <returns></returns>
public static float DrawnAbsoluteX(Camera camera, Entity entity)
{
float xval = ((entity.Position.X * Globals.Scale) - (camera.Position.X * Globals.Scale))
+ GetOffSet(camera).X;
return xval;
}
public static float DrawnAbsoluteY(Camera camera, Entity entity)
{
float xval = ((entity.Position.Y * Globals.Scale) - (camera.Position.Y * Globals.Scale))
+ (GetOffSet(camera).Y * Globals.Scale);
return xval;
}
public static float DrawnAbsoluteX(Entity entity)
{
float xval = ((entity.Position.X * Globals.Scale) - (_TempCam.Position.X * Globals.Scale))
+ GetOffSet(_TempCam).X;
return xval;
}
public static float DrawnAbsoluteY(Entity entity)
{
float xval = ((entity.Position.Y * Globals.Scale) - (_TempCam.Position.Y * Globals.Scale))
+ (GetOffSet(_TempCam).Y * Globals.Scale);
return xval;
}
public static Vector2 GetOffSet(Entity entity)
{
return new Vector2(entity.Dimension.X / 2, entity.Dimension.Y / 2);
}
}
}
<file_sep>using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NGame.Source
{
public class Scene : Entity, IUpdate, IDraw
{
private List<Entity> _EntityCollection;
public bool Visible { get; set; } = true;
public string Name { get; }
public Scene(string name)
{
_EntityCollection = new List<Entity>();
Name = name;
}
public void AddEntity(Entity entity)
{
if (!_EntityCollection.Contains(entity))
{
_EntityCollection.Add(entity);
entity.SetOwner(this);
}
}
public override void Update(GameTime gameTime)
{
if (Enabled && _EntityCollection.Count > 0)
{
foreach (Entity entity in _EntityCollection)
entity.Update(gameTime);
}
}
public void Draw(GameTime gameTime)
{
if (Visible && _EntityCollection.Count > 0)
{
foreach (Entity entity in _EntityCollection)
if (entity is IDraw)
((IDraw)entity).Draw(gameTime);
}
}
}
}
<file_sep>using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using NGame.Source.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NGame.Source
{
public class Globals
{
public const float Scale = 32f;
public static SpriteBatch spriteBatch;
public static ContentManager Content;
public static GraphicsDeviceManager graphicsDevice;
public static NAMouse Mouse = new NAMouse();
public static int ScreenWidth
{
get
{
return graphicsDevice.GraphicsDevice.Viewport.Width;
}
}
public static int ScreenHeight
{
get
{
return graphicsDevice.GraphicsDevice.Viewport.Height;
}
}
public static void Update(GameTime gameTime)
{
Mouse.Update(gameTime);
}
}
}
<file_sep>using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NGame.Source.Graphics
{
public class Sprite : Entity, IDraw
{
protected Texture2D Texture { get; set; }
protected Rectangle SourceRectangle { get; set; }
public bool Visible { get; set; } = true;
public Sprite(string texturePath)
{
LoadTexture(texturePath);
SourceRectangle = new Rectangle(0, 0, Texture.Width, Texture.Height);
}
public Sprite(string texturePath, Rectangle sourceRectangle)
{
LoadTexture(texturePath);
SourceRectangle = sourceRectangle;
}
protected virtual void LoadTexture(string path)
{
if (Globals.Content != null)
{
Globals.Content.Load<Texture2D>(path);
}
else
throw new Exception("Unable to load content, ContentManager is null");
}
public virtual void Draw(GameTime gameTime)
{
if (Visible && Texture != null)
{
Globals.spriteBatch.Draw(Texture, DestinationRectangle, SourceRectangle, Color.White, Rotation, Origin,
SpriteEffects.None, 0f);
}
}
}
}
<file_sep>using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NGame.Source.Input
{
public class NAMouse : IUpdate
{
public MouseState OldState;
public MouseState NewState;
public bool Enabled { get; set; } = true;
public Vector2 Position
{
get { return new Vector2(NewState.Position.X, NewState.Position.Y); }
}
public NAMouse()
{
OldState = Mouse.GetState();
NewState = Mouse.GetState();
}
public void Update(GameTime gameTime)
{
if (Enabled)
{
OldState = NewState;
NewState = Mouse.GetState();
}
}
}
}
<file_sep>using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using NGame.Source;
using NGame.Source.GUI;
namespace NGame
{
/// <summary>
/// This is the main type for your game.
/// </summary>
public class Game1 : Game
{
SceneManager sceneManager;
public Game1()
{
Globals.graphicsDevice = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
sceneManager = new SceneManager();
Globals.Content = this.Content;
base.Initialize();
}
protected override void LoadContent()
{
Globals.spriteBatch = new SpriteBatch(GraphicsDevice);
sceneManager.AddScene(new Scene("Test"));
MenuManager testMainMenu = new MenuManager();
Menu testBaseMenu = new Menu(new Vector2(50,50));
Label titleText = new Label("Title Text", new Vector2(50, 50));
testBaseMenu.AddMenuObject(titleText);
testMainMenu.AddMenu(testBaseMenu);
sceneManager.ActiveScene.AddEntity(testMainMenu);
}
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
protected override void Update(GameTime gameTime)
{
Globals.Update(gameTime);
sceneManager.Update(gameTime);
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
Globals.spriteBatch.Begin();
sceneManager.Draw(gameTime);
Globals.spriteBatch.End();
base.Draw(gameTime);
}
}
public class MainGame
{
static void Main()
{
using (var game = new Game1())
game.Run();
}
}
}
<file_sep>using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NGame.Source.GUI
{
public class MenuManager : Entity, IUpdate, IDraw
{
private Stack<Menu> _MenuStack;
public Menu ActiveMenu
{
get
{
if (_MenuStack.Count > 0)
return _MenuStack.Peek();
else
return null;
}
}
public bool Visible { get; set; } = true;
public MenuManager()
{
_MenuStack = new Stack<Menu>();
}
public void Draw(GameTime gameTime)
{
if (Visible && ActiveMenu != null)
{
ActiveMenu.Draw(gameTime);
}
}
public override void Update(GameTime gameTime)
{
if (Enabled && _MenuStack.Count > 0)
foreach (Menu menu in _MenuStack)
menu.Update(gameTime);
base.Update(gameTime);
}
public void AddMenu(Menu menu)
{
_MenuStack.Push(menu);
}
public void PopMenu()
{
if (_MenuStack.Count > 0)
_MenuStack.Pop();
}
}
}
<file_sep>using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NGame.Source
{
public class SceneManager : Entity, IUpdate, IDraw
{
private Dictionary<String, Scene> _SceneCollection;
public bool Visible { get; set; } = true;
public Scene ActiveScene { get; private set; }
public SceneManager()
{
_SceneCollection = new Dictionary<string, Scene>();
}
public void AddScene(Scene newScene)
{
if (_SceneCollection.Count > 0)
{
if (_SceneCollection.ContainsKey(newScene.Name))
throw new Exception("_SceneCollection already contains " + newScene.Name);
else
if (_SceneCollection.ContainsValue(newScene))
throw new Exception("_SceneCollection already contains this Scene object");
else
{
_SceneCollection.Add(newScene.Name, newScene);
newScene.SetOwner(this);
}
}
else
{
_SceneCollection.Add(newScene.Name, newScene);
ActiveScene = newScene;
}
}
public override void Update(GameTime gameTime)
{
if (Enabled && _SceneCollection.Count > 0)
{
if (ActiveScene != null)
ActiveScene.Update(gameTime);
}
}
public void Draw(GameTime gameTime)
{
if (Visible && _SceneCollection.Count > 0)
if (ActiveScene != null)
ActiveScene.Draw(gameTime);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using NGame.Source.Input;
namespace NGame.Source.GUI
{
class Button : MenuObject
{
private Texture2D _NormalTexture;
private Texture2D _MouseOverTexture;
private bool _MouseOver = false;
public delegate void CommandDelegate(Entity sender);
public override float Width { get; protected set; }
public override float Height { get; protected set; }
public bool MouseOverGraphicEnabled { get; set; } = true;
public CommandDelegate ButtonCommand;
public Button()
{
}
public Button(Vector2 position) : base(position)
{
Visible = false;
}
public Button(Vector2 position, string normalTexturePath, string mouseOverTexturePath) : base(position)
{
SetTextures(normalTexturePath, mouseOverTexturePath);
}
public Button(Vector2 position, string normalTexturePath) : base(position)
{
LoadNormalTexturePath(normalTexturePath);
}
public override void Draw(GameTime gameTime)
{
if (Visible)
{
if (_MouseOver && _MouseOverTexture != null)
{
Globals.spriteBatch.Draw(_MouseOverTexture, new Rectangle((int)AbsolutePosition.X, (int)AbsolutePosition.Y,
(int)Width, (int)Height), Color.White);
}
else
{
Globals.spriteBatch.Draw(_NormalTexture, new Rectangle((int)AbsolutePosition.X, (int)AbsolutePosition.Y,
(int)Width, (int)Height), Color.White);
}
}
}
public override void Update(GameTime gameTime)
{
if (Enabled)
{
_MouseOver = IsMouseOver();
if (_MouseOver && Globals.Mouse.OldState.LeftButton == ButtonState.Pressed
&& Globals.Mouse.NewState.LeftButton == ButtonState.Released)
{
ButtonCommand?.Invoke(this);
}
}
base.Update(gameTime);
}
private bool IsMouseOver()
{
Vector2 mousePosition = Globals.Mouse.Position;
if (_NormalTexture != null)
if (Width > 0 && Height > 0)
{
if (mousePosition.X >= AbsolutePosition.X && mousePosition.Y >= AbsolutePosition.Y)
if (mousePosition.X <= AbsolutePosition.X + Width && mousePosition.Y <= AbsolutePosition.Y + Height)
return true;
}
return false;
}
private void SetTextures(string normalTexturePath, string mouseOverTexturePath)
{
LoadNormalTexturePath(normalTexturePath);
LoadMouseOverTexturePath(mouseOverTexturePath);
}
private void LoadNormalTexturePath(string path)
{
_NormalTexture = Globals.Content.Load<Texture2D>(path);
}
private void LoadMouseOverTexturePath(string path)
{
_MouseOverTexture = Globals.Content.Load<Texture2D>(path);
}
}
}
<file_sep>using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NGame.Source.GUI
{
public class Menu : Entity, IUpdate, IDraw
{
private List<MenuObject> _MenuObjectCollection;
public bool Visible { get; set; } = true;
public Menu()
{
_MenuObjectCollection = new List<MenuObject>();
}
public Menu(Vector2 position)
{
Position = position;
_MenuObjectCollection = new List<MenuObject>();
}
public void Draw(GameTime gameTime)
{
if (Visible)
if (_MenuObjectCollection.Count > 0)
foreach (MenuObject menuObject in _MenuObjectCollection)
menuObject.Draw(gameTime);
}
public override void Update(GameTime gameTime)
{
if (Enabled)
if (_MenuObjectCollection.Count > 0)
foreach (MenuObject menuObject in _MenuObjectCollection)
menuObject.Update(gameTime);
}
public void AddMenuObject(MenuObject menuObject)
{
if (!_MenuObjectCollection.Contains(menuObject))
{
_MenuObjectCollection.Add(menuObject);
menuObject.SetOwner(this);
}
}
}
}
<file_sep>using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using NGame.Source.Graphics;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NGame.Source.GUI
{
public class Label : MenuObject
{
public string Text { get; set; }
public Color TextColor { get; set; } = Color.White;
public bool MouseOver { get; protected set; } = false;
public bool BackgroundEnabled { get; set; } = true;
public Color BackgroundColor { get; set; } = Color.Black;
public override float Width
{
get
{
if (_Font != null)
return _Font.MeasureString(Text).X;
else
return 0;
}
protected set
{
throw new Exception("You cannot set this");
}
}
public override float Height
{
get
{
if (_Font != null)
return _Font.MeasureString(Text).Y;
else
return 0;
}
protected set
{
throw new Exception("You cannot set this");
}
}
private SpriteFont _Font;
protected Rectangle AbsDestinationRectangle
{
get
{
if (Owner != null && _Font != null)
{
return new Rectangle((int)AbsolutePosition.X, (int)AbsolutePosition.Y, (int)Width, (int)Height);
}
else
throw new Exception("Unable to return a destination rectangle");
}
}
public event EventHandler<EventArgs> LeftClick;
public event EventHandler<EventArgs> RightClick;
public Label(string text, Vector2 position, string font = "Default") : base(position)
{
Text = text;
_Font = Globals.Content.Load<SpriteFont>(font);
}
public override void Draw(GameTime gameTime)
{
if (Visible)
{
if (BackgroundEnabled)
GraphicsHelper.DrawRectangle(AbsDestinationRectangle.X, AbsDestinationRectangle.Y,
AbsDestinationRectangle.Width, AbsDestinationRectangle.Height, BackgroundColor);
Globals.spriteBatch.DrawString(_Font, Text, AbsolutePosition, TextColor);
}
}
public override void Update(GameTime gameTime)
{
if (Enabled)
{
CheckForLeftClick();
CheckForRightClick();
}
base.Update(gameTime);
}
private void CheckForLeftClick()
{
if (Globals.Mouse.Position.X >= AbsDestinationRectangle.X && Globals.Mouse.Position.Y >= AbsDestinationRectangle.Y)
if (Globals.Mouse.Position.X <= AbsDestinationRectangle.X + AbsDestinationRectangle.Width &&
Globals.Mouse.Position.Y <= AbsDestinationRectangle.Y + AbsDestinationRectangle.Height)
if (Globals.Mouse.OldState.LeftButton == ButtonState.Pressed && Globals.Mouse.NewState.LeftButton == ButtonState.Released)
OnLeftClick(this, null);
}
private void CheckForRightClick()
{
if (Globals.Mouse.Position.X >= AbsDestinationRectangle.X && Globals.Mouse.Position.Y >= AbsDestinationRectangle.Y)
if (Globals.Mouse.Position.X <= AbsDestinationRectangle.X + AbsDestinationRectangle.Width &&
Globals.Mouse.Position.Y <= AbsDestinationRectangle.Y + AbsDestinationRectangle.Height)
if (Globals.Mouse.OldState.RightButton == ButtonState.Pressed && Globals.Mouse.NewState.RightButton == ButtonState.Released)
OnRightClick(this, null);
}
protected virtual void OnRightClick(object sender, EventArgs e)
{
RightClick?.Invoke(sender, e);
}
protected virtual void OnLeftClick(object sender, EventArgs e)
{
LeftClick?.Invoke(sender, e);
}
}
}
| f724c19efb7c76598c7af45fca41cdb3e368af1a | [
"C#"
] | 15 | C# | nathanlabel/NGame | 5c3b81a8f0ea6094d40246d0816dc8647c881a37 | 18960fa82ae21e3cdd1548f8891d913f65c0639d |
refs/heads/master | <file_sep><?php
require_once'Call.php';
class GSM
{
private $model;
private $hasSimCard;
private $simMobileNumber;
private $outgoingCallsDuration = 1;
private $lastIncomingCall;
private $lastOutgoingCall;
private $sumPrice;
private $price = 2;
public function __construct($model) {
$this->model = $model;
}
public function getModel() {
return $this->model;
}
public function getSimMobileNumber() {
return $this->simMobileNumber;
}
public function getOutGoingCallDuration() {
return $this->outgoingCallsDuration;
}
public function getLastIncomingCall() {
return $this->lastIncomingCall;
}
public function getLastOutgoingCall() {
return $this->lastOutgoingCall;
}
public function setOutgoingCallsDuration ($outgoingCallsDuration) {
$this->outgoingCallsDuration = $outgoingCallsDuration;
}
public function setLastIncomingCall ($value) {
$this->lastIncomingCall = $value;
}
public function setLastOutgoingCall($value) {
$this->lastOutgoingCall = $value;
}
function insertSimCard($simMobileNumber)
{
$new = substr($simMobileNumber,0,2);
$countz = strlen($simMobileNumber);
if ($countz == 10 && $new == '08') {
$this->simMobileNumber = $simMobileNumber;
$this->hasSimCard = true;
} else {
echo "Not a valid number";
}
}
public function removeSimCard() {
$this->hasSimCard = false;
$this->simMobileNumber = 0;
}
public function getHasSimCard() {
return $this->hasSimCard;
}
public function call($receiver,$duration) {
$calr = $this->getSimMobileNumber();
$reve = $receiver->getSimMobileNumber();
$calrSim = $this->getHasSimCard();
$reveSim = $receiver->getHasSimCard();
if (($duration < 0 || $duration > 120) || ($calr == $reve) || ($calrSim == 0 || $reveSim == 0) ) {
return $this->duration = 'Not a valid input';
} else {
$receiver->setLastIncomingCall("Last incoming call duration was: $duration");
$this->setLastOutgoingCall("Last outgoing call duration was : $duration");
$this->outgoingCallsDuration += $duration;
echo "Please, answer it's emergent!";
}
}
public function getSumForAll() {
echo $this->sumPrice = $this->getOutGoingCallDuration() * $this->price.' '.'Leva';
}
}<file_sep><?php
require_once('Call.php');
require_once('GSM.php');
$phoneOne = new GSM('iPhone');
$phoneTwo = new GSM('Samsung');
$phoneOne->insertSimCard('0885111111');
$phoneTwo->insertSimCard('0883222222');
//echo $phoneOne->getSimMobileNumber();
//echo $phoneTwo->getSimMobileNumber();
//echo $phoneOne->getHasSimCard();
$call = new Call($phoneTwo,$phoneTwo,20);
echo $phoneOne->call($phoneTwo,$call->getDuration());
echo $phoneOne->getSumForAll();
<file_sep><?php
require_once('Computer.php');
$computer1 = new Computer(2005,'1500$','Yes','500Gb','200GB','Windows');
$computer2 = new Computer(2010,'2000$','No','1000Gb','500GB','Linux');
$computer1->changeOperationSystem('NewOS');
$computer2->useMemory(400);
$str1 = $computer1->getInfo();
$str2 = $computer2->getInfo();
echo "Computer1 info: .$str1".PHP_EOL;
echo "Computer2 info: .$str2".PHP_EOL;
<file_sep><?php
require_once'GSM.php';
class Call
{
private $priceForAMinute;
private $caller;
private $receiver;
private $duration;
public function __construct($caller, $receiver, $duration) {
$this->caller = $caller;
$this->receiver = $receiver;
$this->duration = $duration;
}
public function getPriceForAMinute() {
return $this->priceForAMinute;
}
public function getCaller() {
return $this->caller;
}
public function getReceiver() {
return $this->receiver;
}
public function getDuration() {
return $this->duration;
}
public function setPriceForAMinute($value) {
$this->priceForAMinute = $value;
}
public function setCaller($caller) {
$this->caller = $caller;
}
public function setReceiver($receiver) {
return $this->receiver = $receiver;
}
public function setDuration($value) {
return $this->duration = $value;
}
}
<file_sep><?php
class Computer
{
private $year;
private $price;
private $isNotebook;
private $hardDiskMemory;
private $freeMemory;
private $operationSystem;
private $newOperationSystem;
private $memory;
public function __construct($year,$price,$isNotebook,$hardDiskMemory,$freeMemory,$operationSystem)
{
$this->year = $year;
$this->price = $price;
$this->isNotebook = $isNotebook;
$this->hardDiskMemory = $hardDiskMemory;
$this->freeMemory = $freeMemory;
$this->operationSystem = $operationSystem;
}
public function getYear(){
return $this->year;
}
public function getPrice(){
return $this->price;
}
public function getIsNotebook(){
return $this->isNotebook;
}
public function getHardDiskMemory(){
return $this->hardDiskMemory;
}
public function getFreeMemory(){
return $this->freeMemory;
}
public function getOperationSystem(){
return $this->operationSystem;
}
public function getMemory(){
return $this->memory;
}
public function changeOperationSystem($newOperationSystem)
{
$this->operationSystem = $newOperationSystem;
}
public function getInfo() {
return 'Year of proction:'.$this->getYear()
.', '.'Price:'.$this->getPrice()
.', '.'Is computer Notebook:'.$this->getIsNotebook()
.', '.'Hard disk memory:'.$this->getHardDiskMemory()
.', '.'Free memory:'.$this->getFreeMemory()
.', '.'Operation system:'.$this->getOperationSystem();
}
public function useMemory($memory)
{
$this->freeMemory -= $memory;
}
}<file_sep><?php
require_once 'autoload.php';
use Task\Task;
use Employee\Employee;
$vork = new Task('kopane',2);
$employee = new Employee('Ivan');
$employee->setCurrentTask($vork);
$employee->setHoursRemaining(2);
$employee->work();
echo $employee->showReport();
| ec05447825092d74eb50bbf50f164f9907e91142 | [
"PHP"
] | 6 | PHP | cektahta/PhpOOP-Intro | ec686e20bd901977f73d97c4ec9920773b0294ce | 5ac08d8301488683f790fd2108d6698c9f6475c4 |
refs/heads/master | <file_sep># DVDIconRebound
Simulation of DVD icon rebounding on your desktop
Hey, here is my first submission on Github!
This program is about DVD icon rebounding on the screen.
<file_sep>using System;
using System.Windows;
namespace DVD
{
public class Vector
{
public double X { get; set; }
public double Y { get; set; }
public double Z { get; set; }
public Vector()
{
X = 0;
Y = 0;
Z = 0;
}
public Vector(double x, double y)
{
X = x;
Y = y;
Z = 0;
}
public Vector(double x, double y, double z)
{
X = x;
Y = y;
Z = z;
}
public Vector(Point p)
{
X = p.X;
Y = p.Y;
Z = 0;
}
public Vector(Point p1, Point p2)
{
X = p2.X - p1.X;
Y = p2.Y - p1.Y;
Z = 0;
}
public virtual Vector Value()
{
return this;
}
public virtual Vector Apply(Func<double, double> f)
{
return new Vector(f(X), f(Y), f(Z));
}
public virtual double Square()
{
return X * X + Y * Y + Z * Z;
}
public virtual double Norm()
{
return Math.Sqrt(Square());
}
public virtual Vector UnitVector()
{
return Value() / Norm();
}
public virtual Vector DirectionVector()
{
return UnitVector().Apply(x => Math.Acos(x));
}
public virtual double DotProduct(Vector V)
{
return X * V.X + Y * V.Y + Z * V.Z;
}
public virtual Vector CrossProduct(Vector V)
{
return new Vector(-Z * V.Y + Y * V.Z, Z * V.X - X * V.Z, -Y * V.X + X * V.Y);
}
public virtual bool IsVertical(Vector V)
{
return Value().DotProduct(V) == 0;
}
public virtual bool IsParallel(Vector V)
{
return Value().CrossProduct(V) == new Vector();
}
public override string ToString()
{
return $"{X},{Y},{Z}";
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public Point ToPoint()
{
return new Point(X, Y);
}
public static Vector operator +(Vector R)
{
return R;
}
public static Vector operator +(Vector L, Vector R)
{
return new Vector(L.X + R.X, L.Y + R.Y);
}
public static Vector operator -(Vector R)
{
return new Vector(-R.X, -R.Y);
}
public static Vector operator -(Vector L, Vector R)
{
return -R + L;
}
public static Vector operator *(Vector L, double R)
{
return new Vector(L.X * R, L.Y * R);
}
public static Vector operator *(double L, Vector R)
{
return R * L;
}
public static Vector operator /(Vector L, double R)
{
return 1 / R * L;
}
public static bool operator ==(Vector L,Vector R)
{
return L.X == R.Y && L.Y == R.Y;
}
public static bool operator !=(Vector L,Vector R)
{
return !(L == R);
}
}
public class Point
{
public double X { get; set; }
public double Y { get; set; }
public Point(double x, double y)
{
X = x;
Y = y;
}
public override string ToString()
{
return $"({X},{Y})";
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public static Point operator +(Point L, Point R)
{
return new Point(L.X + R.X, L.Y + R.Y);
}
public static Point operator -(Point R)
{
return new Point(-R.X, -R.Y);
}
public static Point operator -(Point L, Point R)
{
return -R + L;
}
public static Point operator *(Point L, float R)
{
return new Point(L.X * R, L.Y * R);
}
public static Point operator *(float L, Point R)
{
return R * L;
}
public static Point operator /(Point L, float R)
{
return 1 / R * L;
}
public static bool operator ==(Point L, Point R)
{
return L.X == R.X && L.Y == R.Y;
}
public static bool operator !=(Point L, Point R)
{
return !(L == R);
}
public static implicit operator System.Windows.Point(Point point)
{
return new System.Windows.Point(point.X, point.Y);
}
public static implicit operator Point(System.Windows.Point point)
{
return new Point(point.X, point.Y);
}
public static implicit operator System.Drawing.Point(Point point)
{
return new System.Drawing.Point((int)point.X, (int)point.Y);
}
public static implicit operator Point(System.Drawing.Point point)
{
return new Point(point.X, point.Y);
}
public static explicit operator Size(Point point)
{
return new Size(point.X, point.Y);
}
public static implicit operator Point(Size size)
{
return new Point(size.Width, size.Height);
}
}
public class Size
{
public double Width { get; set; }
public double Height { get; set; }
public Size(double width, double height)
{
Width = width;
Height = height;
}
public override string ToString()
{
return $"({Width},{Height})";
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public static Size operator +(Size L, Size R)
{
return new Size(L.Width + R.Width, L.Height + R.Height);
}
public static Size operator -(Size R)
{
return new Size(-R.Width, -R.Height);
}
public static Size operator -(Size L, Size R)
{
return -R + L;
}
public static Size operator *(Size L, double R)
{
return new Size(L.Width * R, L.Height * R);
}
public static Size operator *(double L, Size R)
{
return R * L;
}
public static Size operator /(Size L, double R)
{
return 1 / R * L;
}
public static bool operator ==(Size L, Size R)
{
return L.Width == R.Width && L.Height == R.Height;
}
public static bool operator !=(Size L, Size R)
{
return !(L == R);
}
public static implicit operator System.Drawing.Size(Size size)
{
return new System.Drawing.Size((int)size.Width, (int)size.Height);
}
public static implicit operator Size(System.Drawing.Size size)
{
return new Size(size.Width, size.Height);
}
}
}<file_sep>using System.Windows;
using System.Windows.Media.Imaging;
namespace DVD
{
/// <summary>
/// author.xaml 的交互逻辑
/// </summary>
public partial class author : Window
{
public author()
{
InitializeComponent();
pic.Source = BitmapToBitmapImage(Properties.Resources.discpic);
}
private BitmapImage BitmapToBitmapImage(System.Drawing.Bitmap bitmap)
{
BitmapImage bitmapImage = new BitmapImage();
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
bitmap.Save(ms, bitmap.RawFormat);
bitmapImage.BeginInit();
bitmapImage.StreamSource = ms;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
bitmapImage.Freeze();
}
return bitmapImage;
}
}
}<file_sep>using System;
using System.Windows;
using System.Windows.Input;
using System.Drawing;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
namespace DVD
{
public partial class MainWindow : Window
{
public Point Location
{
get { return new Point(Left, Top); }
set
{
//if (value == null) return;
Location = value;
Left = value.X;
Top = value.Y;
}
}
public Size Size
{
get { return new Size(Width, Height); }
set
{
//if (value == null) return;
Size = value;
Width = value.Width;
Height = value.Height;
}
}
public Point MiddlePoint
{
get { return new Point(this.Width / 2, this.Height / 2); }
}
public Size ScreenSize = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Size;
static string path = Environment.CurrentDirectory;
static Bitmap[] imgs = new Bitmap[]
{
Properties.Resources._1,
Properties.Resources._2,
Properties.Resources._3
};
enum MovingMode
{
Follow,
Rebound,
Stop
}
long t = 0;
Vector direction = new Vector(5, 5);
MovingMode mode = MovingMode.Rebound;
bool dragging = false;
DispatcherTimer timer1 = new DispatcherTimer();
DispatcherTimer timer2 = new DispatcherTimer();
System.Windows.Forms.NotifyIcon icon = new System.Windows.Forms.NotifyIcon();
System.Windows.Forms.ContextMenu menu = new System.Windows.Forms.ContextMenu();
System.Windows.Forms.MenuItem setMode = new System.Windows.Forms.MenuItem();
System.Windows.Forms.MenuItem onQuit = new System.Windows.Forms.MenuItem();
System.Windows.Forms.MenuItem author = new System.Windows.Forms.MenuItem();
public MainWindow()
{
InitializeComponent();
Action switchMode = () =>
{
timer2.Stop();
switch (mode)
{
case MovingMode.Rebound:
mode = MovingMode.Follow;
setMode.Text = "跟随";
break;
case MovingMode.Follow:
mode = MovingMode.Stop;
setMode.Text = "停止";
break;
case MovingMode.Stop:
mode = MovingMode.Rebound;
setMode.Text = "反弹";
break;
}
Animation();
};
icon.DoubleClick += (object sender, EventArgs e) => switchMode();
setMode.Text = "反弹";
setMode.Click += (object sender, EventArgs e) => switchMode();
author.Text = "作者";
author.Click += (object sender, EventArgs e) => new author().Show();
onQuit.Text = "退出";
onQuit.Click += (object sender, EventArgs e) =>
{
icon.Visible = false;
icon.Dispose();
Environment.Exit(1);
};
menu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { author, onQuit });
icon.Icon = Properties.Resources.disc;
icon.ContextMenu = menu;
icon.Visible = true;
ShowInTaskbar = false;
//KeyDown += (object sender, KeyEventArgs e) => { if (e.Key == Key.Space) dragging = true; };
//KeyUp += (object sender, KeyEventArgs e) => dragging = false;
MouseDown += (object sender, MouseButtonEventArgs e) => DragMove();//{ if (dragging) DragMove(); };
/*
timer1.Interval = new TimeSpan(0, 0, 0, 0, 500);
timer1.Tick += (object sender, EventArgs e) => picChange();
timer1.Start();
*/
Animation();
}
public void Animation()
{
BitmapImage[] images = new BitmapImage[]
{
BitmapToBitmapImage(imgs[0]),
BitmapToBitmapImage(imgs[1]),
BitmapToBitmapImage(imgs[2])
};
Action picChange = () =>
{
pic.Source = images[t];
t++;
if (t == imgs.Length) t = 0;
};
Action picMove = () =>
{
switch (mode)
{
case MovingMode.Follow:
//picFollow
Point pt = null;
Point p = (new Vector(LineSeg(10, MousePosition() - MiddlePoint, MiddlePoint)) / 100).ToPoint();
pt = PointToScreen(p);
Left = pt.X;
Top = pt.Y;
break;
case MovingMode.Rebound:
//picRebound
Left += direction.X;
Top += direction.Y;
if (Left <= 0 || Left + Width >= ScreenSize.Width)
{
direction.X *= -1;
picChange();
}
if (Top <= 0 || Top + Height >= ScreenSize.Height)
{
direction.Y *= -1;
picChange();
}
break;
case MovingMode.Stop:
timer2.Stop();
break;
}
};
timer2.Interval = new TimeSpan(0, 0, 0, 0, 15);
timer2.Tick += (object sender, EventArgs e) => picMove();
timer2.Start();
}
private BitmapImage BitmapToBitmapImage(Bitmap bitmap)
{
BitmapImage bitmapImage = new BitmapImage();
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
bitmap.Save(ms, bitmap.RawFormat);
bitmapImage.BeginInit();
bitmapImage.StreamSource = ms;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
bitmapImage.Freeze();
}
return bitmapImage;
}
public Point LineSeg(double d, Point p1, Point p2)
{
Vector OA = new Vector(p1), OB = new Vector(p2);
Vector AB = OB - OA;
if (AB.Norm() == 0) return p1;
double lambda = d / AB.Norm();
return (OA + lambda * AB).ToPoint();
}
public Point MousePosition()
{
Point pos = System.Windows.Forms.Cursor.Position;
return this.PointFromScreen(pos);
}
}
} | 9bf668f80da5c87f89c503599ad8da9e17103fad | [
"Markdown",
"C#"
] | 4 | Markdown | ajhzhsendjx/DVDIconRebound | f57f946207356d16beee8a3481317bfea11162eb | e16890c96549bbe709f4f2bf2eb53317cdd43845 |
refs/heads/main | <repo_name>zaid-kamil/EDA_app<file_sep>/app.py
# to run the application -->
# streamlit run app.py
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.express as px
import numpy as np
@st.cache
def load_dataset():
'''
reads the data from the url
'''
df = pd.read_csv('https://raw.githubusercontent.com/digipodium/Datasets/main/automobile.csv',index_col=0)
df.replace(to_replace="?",value=np.nan,inplace=True)
df['normalized-losses'] = df['normalized-losses'].astype(float)
df['num-of-doors'] = df['num-of-doors'].astype(str)
df['bore'] = df['bore'].astype(float)
df['stroke'] = df['stroke'].astype(float)
df['price'] = df['price'].astype(float)
df['price'].replace(np.nan,df['price'].mean(),inplace=True)
return df
st.title("Exploratory Data Analytics")
st.subheader("using Automobile dataset")
st.sidebar.subheader("Select options")
df = load_dataset()
options = ['View dataset','Numeric Correlation','Categorical Correlation']
selection = st.sidebar.radio("your options are",options)
if selection == options[0]:
st.write(df)
if selection == options[1]:
column_names = [ 'wheel-base', 'length', 'width', 'height', 'curb-weight', 'engine-size', 'bore', 'stroke', 'compression-ratio', 'horsepower', 'peak-rpm', 'city-mpg', 'highway-mpg', 'price']
colx = st.sidebar.selectbox('Select column for X axis',column_names,help='take a numerical column')
coly = st.sidebar.selectbox('Select column for Y axis',column_names,index=1,help='take a numerical column')
color = st.sidebar.selectbox('Select column for hue',['make','engine-location','num-of-doors'],index=1,help='take a numerical column')
try:
out = sns.lmplot(x=colx, y=coly, data=df,aspect=2,height=7,hue=color)
st.pyplot(out)
except Exception as e:
st.error(e)
if selection == options[2]:
column_names =['normalized-losses', 'make', 'fuel-type', 'aspiration', 'num-of-doors', 'body-style', 'drive-wheels', 'engine-location', 'engine-type', 'num-of-cylinders', 'fuel-system']
num_col_names = [ 'wheel-base', 'length', 'width', 'height', 'curb-weight', 'engine-size', 'bore', 'stroke', 'compression-ratio', 'horsepower', 'peak-rpm', 'city-mpg', 'highway-mpg', 'price']
colx = st.sidebar.selectbox('Select column for X axis',column_names,help='take a categorical column')
coly = st.sidebar.selectbox('Select column for Y axis',num_col_names,index=1,help='take a numerical column')
ori = st.sidebar.radio("graph orientation",['h','v'])
x_size = st.sidebar .number_input("graph size on x axis",5,30)
y_size = st.sidebar .number_input("graph size on y axis",5,30)
try:
fig,ax= plt.subplots(figsize=(x_size,y_size))
sns.boxplot(x=colx,y=coly,data=df,orient=ori,palette='rainbow',ax=ax)
st.pyplot(fig)
except Exception as e:
st.error(e) | 7d5fa4f3cbf43e3a4f490f4dbed76215a816209a | [
"Python"
] | 1 | Python | zaid-kamil/EDA_app | ba52315e884c48e2bfcd006271987df6d397c807 | ac8a7224f0edd8cd4f800faecf216ede11305005 |
refs/heads/master | <repo_name>codrgrrl/StarMatchApp<file_sep>/src/components/MyCom.js
import React from "react";
export default function MyCom() {
return (
<div className="MyCom">
<h1>Hello World From Components</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
| 733a7f4946c17946caed8668381f33547cfcac5b | [
"JavaScript"
] | 1 | JavaScript | codrgrrl/StarMatchApp | 279ff831deef1e05c8cd7986024204997e3262aa | d0ccc8e6d376414d081b44143bb5537a195fb3ae |
refs/heads/master | <file_sep>class Api::V1::ProductsController < Api::BaseController
def index
@products = Product.all.order(created_at: :desc)
end
def show
@product = Product.find(params[:id])
# @reviews = @product.reviews
render json: @product
end
def create
render json: :params
# @question = Question.new question_params
# @question.user = User.last
# if @question.save
# render json: @question
# else
# render json: { errors: @question.errors.full_messages }
# end
end
private
def product_params
params.require(:product).permit(:title, :description,:price, :sale_price, {tag_ids: []})
end
end
<file_sep>class Product < ApplicationRecord
extend FriendlyId
friendly_id :title, use: [:slugged, :history, :finders]
has_many :reviews , dependent: :destroy
belongs_to :category
belongs_to :user
has_many :favourites
has_many :taggings, dependent: :destroy
has_many :tags, through: :taggings
has_many :fans, through: :favourites, source: :user
validates(:title,{
presence:true,
uniqueness: {case_sensitive: false}
})
validates(:sale_price,numericality:{
less_than_or_equal_to: :price
})
validate :no_reserved_words
validates(:price, numericality:{
greater_than_or_equal_to: 0
})
validates(:description,{
presence: true,
length: {minimum: 10}
})
after_initialize :default_price
before_validation :capitalize
scope :search, ->(item) { where(" title ILIKE ? OR description ILIKE ?", "%#{item}%","%#{item}%").order(title: :asc, description: :asc)}
private
def default_price
# self.price ||= 1
self.sale_price ||= price
end
def capitalize
self.title = title.capitalize if self.title.present?
end
def on_sale?
(sale_price < price)
end
def no_reserved_words
res = ['microsoft', 'apple', 'sony']
if title.present?
res.each do |r|
if title.downcase.include?(r)
errors.add(:title, "can't include a reserved word")
end
end
end
end
end
<file_sep>class ProductMailer < ApplicationMailer
def notify_product_owner(product)
@product = product
@product_owner = @product.user
mail(to: '<EMAIL>', subject: 'You made a new product!')
end
end
<file_sep>class ReviewsMailer < ApplicationMailer
def notify_review_product_owner(review)
@review = review
@product = @review.product
@product_owner = @product.user
mail(to:'<EMAIL>', subject: "New review on #{@product.title}")
end
end
<file_sep>class Admin::PanelController < ApplicationController
def index
@stats = {
user_count: User.count,
product_count:Product.count,
review_count: Review.count
}
@users = User.all
end
end
<file_sep>require 'rails_helper'
RSpec.describe User, type: :model do
describe 'validations' do
it 'requires a first name' do
u = User.new
u.valid?
expect(u.errors.messages).to have_key(:first_name)
end
it 'requires a last name' do
u= User.new
u.valid?
expect(u.errors.messages).to have_key(:last_name)
end
it 'requires a unique email' do
u = FactoryGirl.create(:user)
v = User.new(FactoryGirl.attributes_for(:user))
v.email = u.email
v.valid?
expect(v.errors.messages).to have_key(:email)
end
it "has a full name method that returns a concatenated string" do
u = FactoryGirl.create(:user)
test_name = "#{u.first_name} #{u.last_name}"
expect(u.full_name).to eq(test_name)
end
end
end
<file_sep>json.products @products do |product|
json.id product.id
json.title product.title
json.url product_url(product)
end<file_sep>class ProductSerializer < ActiveModel::Serializer
attributes :id, :title, :description
has_many :reviews
has_many :tags, through: :taggings
end
<file_sep>class Admin::ApplicationController < ApplicationController
before_action :authenticate_admin
before_action :authorize_admin!
private
def :authorize_admin!
redirect_to_root_path alert: "Access denied!" unless current_user.is_admin?
end
end
<file_sep>class Category < ApplicationRecord
has_many :products
validates(:name, {
presence: true,
uniqueness: true
})
end
<file_sep>require 'rails_helper'
require 'pry'
RSpec.describe ProductsController, type: :controller do
describe "destroy" do
it "destroys a product when you follow the destroy path" do
product = FactoryGirl.create(:product)
before_count = Product.count
delete :destroy, params:{id: product.id}
after_count = Product.count
expect(after_count).to eq(before_count -1 )
end
it "redirects user to products path after delete" do
product = FactoryGirl.create(:product)
delete :destroy, params: {id: product.id}
expect(response).to redirect_to(products_path)
end
end
describe "show" do
it 'renders products#show' do
product = FactoryGirl.create(:product)
get :show, params: {id: product.id }
expect(response).to render_template(:show)
end
end
end
<file_sep>require 'rails_helper'
RSpec.describe Product, type: :model do
describe "validations" do
def valid_product
@p = Product.new(FactoryGirl.attributes_for(:product))
end
it "requires a title" do
p = Product.new
p.valid?
expect(p.errors.messages).to have_key(:title)
end
it "requires title to be unique" do
p = Product.create(title: "Book", description: "Blah blah blah blah blah", price: 5)
c= Product.new(title: "Book")
c.valid?
expect(c.errors.messages).to have_key(:title)
end
it "capitalizes title before save" do
p = Product.new(title: "dog", description: "BABABABABBBBBABAB", price: 100)
p.save
expect(p.title).to eq("Dog")
end
it "requires a description" do
p = Product.new(title: "Book")
p.valid?
expect(p.errors.messages).to have_key(:description)
end
it "requires a price" do
p = Product.new(title: "Book")
p.valid?
expect(p.errors.messages).to have_key(:price)
end
it "requires price to be greater than 0" do
p = Product.new(title: "Book", price: -5 )
p.valid?
end
it "sets sale_price equal to price if not present" do
p = Product.create(FactoryGirl.attributes_for(:product).merge({sale_price: nil}))
expect(p.sale_price).to eq(p.price)
end
it "requires sale_price to be less than price" do
valid_product
@p.sale_price = 500
@p.valid?
expect(@p.errors.messages).to have_key(:sale_price)
end
it "has method 'on_sale' that checks if an item is on sale" do
valid_product
expect(@p.on_sale?).to be(true)
end
end
end
<file_sep>class ContactController < ApplicationController
def contact_us
end
def thank_you
@name = params[:name]
end
end
<file_sep>class User < ApplicationRecord
has_secure_password
has_many :products, dependent: :nullify
has_many :reviews, dependent: :nullify
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
has_many :likes, dependent: :destroy
has_many :liked_reviews, through: :likes, source: :review
has_many :votes, dependent: :destroy
has_many :voted_reviews, through: :vote, source: :review
has_many :favourites, dependent: :destroy
has_many :favourite_products, through: :favourites, source: :product
validates :email, presence: true, uniqueness: true, format: VALID_EMAIL_REGEX
validates :first_name, :last_name, presence: true
def full_name
"#{first_name} #{last_name}"
end
def generate_api_key
loop do
self.api_key = SecureRandom.urlsafe_base64(64)
break unless User.exists?(api_key: self.api_key)
end
end
end
<file_sep># This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
Favourite.destroy_all
Product.destroy_all
Category.destroy_all
User.destroy_all
Tag.destroy_all
PASSWORD = "<PASSWORD>"
super_user = User.create(
first_name: 'Jon',
last_name: 'Snow',
email: '<EMAIL>',
password: <PASSWORD>
)
10.times.each do
first_name = Faker::Name.first_name
last_name = Faker::Name.last_name
User.create(
first_name: first_name,
last_name: last_name,
email: <EMAIL>",
password: <PASSWORD>
)
end
users = User.all
8.times.each do
Category.create(name: Faker::Commerce.department)
end
@categories = Category.all
1000.times.each do
q = Product.create(title: Faker::Commerce.product_name, description: Faker::Hipster.sentence, price: rand(1...50000), category: @categories.sample, user: users.sample)
if q.errors.present?
q.errors.full_messages
end
end
20.times do
Tag.create(name: Faker::HitchhikersGuideToTheGalaxy.planet)
end
tags = Tag.all
products = Product.all
products.each do |p|
rand(1..5).times.each do
Review.create(body: Faker::RickAndMorty.quote,
rating:rand(1..5),
product: p,
user: users.sample )
end
p.tags = tags.shuffle.slice(0..rand(8))
end
reviews = Review.all
taggings = Tagging.all
puts "#{Product.all.count} products created"
puts Cowsay.say("Created #{products.count} products", :ghostbusters)
puts Cowsay.say("Created #{reviews.count} reviews", :moose)
puts Cowsay.say("Created #{users.count} users", :tux)
puts Cowsay.say("#{tags.count} tags created", :moose)
puts Cowsay.say("#{taggings.count} taggings", :sheep)
puts "Login with #{super_user.email} and password of '#{<PASSWORD>}'"<file_sep>class VotesController < ApplicationController
before_action :find_vote,only:[:update, :destroy]
def create
review = Review.find params[:review_id]
vote = Vote.new( is_up: params[:is_up],
user: current_user,
review: review )
if vote.save
redirect_to review.product, notice: 'Thank you'
else
redirect_to review.product, notice: "Cannot vote"
end
end
def update
@vote.update( is_up: params[:is_up] )
redirect_to @vote.review.product
end
def destroy
@vote.destroy
redirect_to @vote.review.product
end
private
def find_vote
@vote = Vote.find( params[:id] )
end
end
<file_sep>class FavouritesController < ApplicationController
def create
@product = Product.find(params[:product_id])
favourite = Favourite.new(user: current_user, product: @product)
if favourite.save
redirect_to products_path(@product), notice: "#{@product.title} added to favourites."
else
redirect_to products_path(@product), notice: "Failed"
end
end
def destroy
@favourite = Favourite.find_by_id(params[:id])
@favourite.destroy
redirect_to products_path
end
def index
@user = current_user
@favourite_products = @user.favourite_products
end
end
<file_sep>class ProductsController < ApplicationController
before_action :find_product , only:[ :update, :destroy, :edit, :show]
before_action :get_categories, only: [:new, :create, :edit, :update]
before_action :authenticate_user, except: [:index, :show]
before_action :authorize_user!, except: [:index, :show, :new, :create]
def index
@products = Product.all.order(created_at: :desc)
end
def new
@product = Product.new
end
def edit
end
def create
@product = Product.new(get_params)
@product.user = current_user
if(@product.save)
ProductMailer.notify_product_owner(@product).deliver_now
redirect_to product_path(@product)
else
render new_product_path
end
end
def update
if @question.update
redirect_to @product
end
end
def destroy
@product.destroy
redirect_to products_path
end
def show
@review = Review.new
end
private
def get_params
params.require(:product).permit(:title, :description, :price,:category_id, { tag_ids: [] })
end
def find_product
@product = Product.find(params[:id])
end
def get_categories
@categories = Category.all
end
def authorize_user!
unless can?(:manage, @product)
flash[:alert] ="Access denied"
redirect_to root_path
end
end
end
<file_sep>class Review < ApplicationRecord
belongs_to :product
belongs_to :user
has_many :votes, dependent: :destroy
has_many :voters, through: :vote, source: :user
has_many :likes, dependent: :destroy
has_many :likers, through: :likes, source: :user
validates(:rating,numericality:{
greater_than_or_equal_to: 1,
less_than_or_equal_to: 5
})
def get_like(user)
likes.find_by(user: user)
end
end
<file_sep>class TagSerializer < ActiveModel::Serializer
attributes :name
has_many :taggings
end
<file_sep>require 'rails_helper'
RSpec.describe UsersController, type: :controller do
let(:user) {FactoryGirl.create(:user)}
describe "#new" do
it 'renders the new template' do
get :new
expect(response).to render_template(:new)
end
it 'assigns an new variable @user' do
get :new
expect(assigns(:user)).to be_a_new(User)
end
end
describe '#create' do
context "with valid sign up" do
def valid_request
post :create, params: { user: FactoryGirl.attributes_for(:user)}
end
it 'creates a new user in the database' do
users_before = User.count
valid_request
users_after = User.count
expect(users_before).to eq(users_after -1)
end
it "signs the user in" do
# session[:user_id] = nil
valid_request
expect(session[:user_id]).to be
end
it "redirects users to home on successful request" do
valid_request
expect(response).to redirect_to(root_path)
end
end
context "with invalid parameters" do
it "doesn't create a user in the database" do
count_before = User.count
u = User.create
count_after = User.count
expect(count_after).to eq(count_before)
end
it "renders the new template" do
u = FactoryGirl.attributes_for(:user)
u[:first_name] = nil
post :create, params: {user: u }
expect(response).to render_template(:new)
end
end
end
end
<file_sep>FactoryGirl.define do
factory :product do
association :user, factory: :user
sequence(:title) {|n| "#{Faker::Commerce.product_name} -- #{n}"}
description "#{Faker::Lorem.paragraph}"
price 50
sale_price 30
end
end
<file_sep>class LikesController < ApplicationController
def create
review = Review.find(params[:review_id])
like = Like.new(user: current_user, review: review)
product = review.product
if like.save
redirect_to review.product, notice: "Liked"
else
redirect_to review.product, notice: "Not liked"
end
end
def destroy
@like = Like.find(params[:id])
@product =@like.review.product
@like.destroy
redirect_to @product , notice: 'Like removed'
end
end
<file_sep>Rails.application.routes.draw do
# get('products/new', {to: 'products#new', as: :new_product})
# post('products/new', {to: 'products#create', as: :products})
# get('products', {to: 'products#index'})
# get('products/:id', {to: 'products#show', as: :product})
# patch('products/:id', {to: 'products#update'})
# delete('products/:id', {to: 'products#destroy'})
# get('products/:id/edit', {to: 'products#edit', as: :edit_product})
resources :products do
resources :favourites, shallow: true, only: [:create, :destroy, :index]
resources :reviews, shallow: true, only: [:create, :destroy] do
resources :likes, shallow: true, only: [:create, :destroy]
resources :votes, only:[:create, :update, :destroy]
end
end
post('/reviews/:id', {to: 'reviews#hide', as: :hide_review } )
namespace :admin do
resources :panel, only:[:index]
end
namespace :api, defaults: {format: :json} do
namespace :v1 do
resources :products
end
end
resources :tags, only:[:index, :show]
resources :users, only: [:create,:new, :show]
resource :session, only: [:new, :create, :destroy]
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
get('/about', {to: 'welcome#about'})
get('/home', {to: 'welcome#home', as: :home})
get('contact_us', {to: 'contact#contact_us'})
post('contact_us', {to: 'contact#thank_you'})
root('welcome#home')
end
| 4b9209f57163f2841ea8a1564e53f3c1a5d20ba0 | [
"Ruby"
] | 24 | Ruby | camscherman/fake_amazon | 053930d50bc6b3dd20702923ec5e7fef445da113 | 1bab13ec6093651d10a524dad59813d541fe18f2 |
refs/heads/main | <repo_name>hoosan31320/KeyboardAware<file_sep>/src/screens/Contacts.js
import React, { Component, useContext } from "react";
import { StyleSheet, View, Text } from "react-native";
//import Homebar from "../components/Homebar";
import ProfilePic from "../components/stuff/ProfilePic";
/*import Messages from "../components/Messages";
import MessageComponent from "../components/MessageComponent";*/
function Contacts({navigation}) {
const { user, setUser } = useContext(UserAuthContext);
return (
<View style={styles.container}>
{/*<Homebar style={styles.homebar}></Homebar>*/}
<Text style={styles.contacts}>Contacts</Text>
<View style={styles.group}>
<View style={styles.profilePic3Row}>
<ProfilePic style={styles.profilePic3}></ProfilePic>
<Messages style={styles.messages2}></Messages>
</View>
</View>
{/*<MessageComponent style={styles.messageComponent}></MessageComponent>*/}
<ProfilePic style={styles.profilePic}></ProfilePic>
{/*<MessageComponent style={styles.messageComponent2}></MessageComponent>*/}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1
},
homebar: {
width: 360,
height: 65,
marginTop: 675,
alignSelf: "center"
},
contacts: {
fontFamily: "OpenSans_800ExtraBold",
color: "rgba(27,6,94,1)",
height: 60,
width: 299,
textAlign: "center",
fontSize: 48,
marginTop: -611,
marginLeft: 31
},
group: {
width: 326,
height: 116,
flexDirection: "row",
marginTop: 184,
marginLeft: 19
},
profilePic3: {
width: 75,
height: 75,
marginTop: 21
},
messages2: {
width: 230,
height: 116,
marginLeft: 21
},
profilePic3Row: {
height: 116,
flexDirection: "row",
flex: 1
},
messageComponent: {
height: 116,
width: 326,
marginTop: 34,
marginLeft: 19
},
profilePic: {
width: 75,
height: 75,
marginTop: -598,
marginLeft: 133
},
messageComponent2: {
width: 326,
height: 116,
marginTop: 106,
marginLeft: 19
}
});
export default Contacts;
<file_sep>/src/components/Firebase/config.js
export default {
apiKey: "<KEY>",
authDomain: "colloquial-985db.firebaseapp.com",
projectId: "colloquial-985db",
storageBucket: "colloquial-985db.appspot.com",
messagingSenderId: "433221369998",
appId: "1:433221369998:web:a713a94c5f862460b089df"
};<file_sep>/src/components/stuff/BookmarkComponent.js
import React, { Component } from "react";
import { StyleSheet, View } from "react-native";
import Icon from "react-native-vector-icons/MaterialIcons";
import Bookmark from "./Bookmark";
function BookmarkComponent(props) {
return (
<View style={[styles.container, props.style]}>
<View style={styles.iconRow}>
<Icon name="cancel" style={styles.icon}></Icon>
<Bookmark style={styles.bookmark}></Bookmark>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flexDirection: "row"
},
icon: {
color: "rgba(0,107,166,1)",
fontSize: 40,
marginTop: 65
},
bookmark: {
width: 231,
height: 210,
marginLeft: 6
},
iconRow: {
height: 210,
flexDirection: "row",
flex: 1
}
});
export default BookmarkComponent;
<file_sep>/src/components/stuff/ProfilePic.js
import React, { Component } from "react";
import { StyleSheet, View } from "react-native";
import Svg, { Ellipse } from "react-native-svg";
function ProfilePic(props) {
return (
<View style={[styles.container, props.style]}>
<Svg viewBox="0 0 74.62 74.62" style={styles.ellipse}>
<Ellipse
stroke="rgba(0,0,0,1)"
strokeWidth={0}
fill="rgba(230, 230, 230,1)"
cx={37}
cy={37}
rx={37}
ry={37}
></Ellipse>
</Svg>
</View>
);
}
const styles = StyleSheet.create({
container: {},
ellipse: {
width: 75,
height: 75
}
});
export default ProfilePic;
<file_sep>/src/screens/Chat.js
import React, { useState, useEffect, useContext } from 'react';
import { GiftedChat, Bubble, Send, SystemMessage } from 'react-native-gifted-chat';
import { ActivityIndicator, View, StyleSheet, Image } from 'react-native';
import { firestore } from '../components/Firebase/method';
import { UserAuthContext } from '../navigation/UserAuthProvider';
export default function Chat({route}) {
const [messages, setMessages] = useState([]);
const { thread } = route.params;
const { user } = useContext(UserAuthContext);
const currentUser = user.toJSON();
useEffect(() => {
})
async function sendMessage(messages) {
const text = messages[0].text;
firestore.collection('threads')
.doc(thread._id)
.collection('messages')
.add({
text,
createdAt: new Date().getTime(),
user: {
_id: currentUser.uid,
email: currentUser.email
}
});
await firestore
.collection('threads')
.doc(thread._id)
.set(
{
latestMessage: {
text,
createdAt: new Date().getTime()
}
},
{ merge: true }
);
}
useEffect(() => {
const messagesListener = firestore
.collection('threads')
.doc(thread._id)
.collection('messages')
.orderBy('createdAt', 'desc')
.onSnapshot(querySnapshot => {
const messages = querySnapshot.docs.map(doc => {
const firebaseData = doc.data();
const data = {
_id: doc.id,
text: '',
createdAt: new Date().getTime(),
...firebaseData
};
if (!firebaseData.system) {
data.user = {
...firebaseData.user,
name: firebaseData.user.email
};
}
return data;
});
setMessages(messages);
});
// Stop listening for updates whenever the component unmounts
return () => messagesListener();
}, []);
function renderText(props) {
return (
<Bubble
{...props}
wrapperStyle={{
right: {
backgroundColor: '#006BA6'
}
}}
textStyle={{
right: {
color: '#D9F0FF',
fontFamily: 'OpenSans_400Regular'
}
}}
/>
);
}
function loading() {
return (
<View style={styles.loadingContainer}>
<ActivityIndicator size='large' color='#6646ee' />
</View>
);
}
function send(props) {
return (
<Send {...props}>
<View style={styles.sendingContainer}>
<Image style = {{height: 40, width: 40 }}source={require('../assets/icons/send.png')} />
</View>
</Send>
);
}
function scrollToBottom(props) {
return (
<View style={styles.bottomComponentContainer}>
<Image source={require('../assets/icons/down.png')} />
</View>
);
}
function renderSystem(props) {
return (
<SystemMessage
{...props}
wrapperStyle={styles.systemMessageWrapper}
textStyle={styles.systemMessageText}
/>
);
}
return (
<GiftedChat
messages={messages}
onSend={sendMessage}
user={{ _id: currentUser.uid }}
placeholder='Type your message here...'
alwaysShowSend
showUserAvatar
scrollToBottom
renderBubble={renderText}
renderLoading={loading}
renderSend={send}
scrollToBottomComponent={scrollToBottom}
renderSystemMessage={renderSystem}
/>
);
}
const styles = StyleSheet.create({
loadingContainer: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
},
sendingContainer: {
justifyContent: 'center',
alignItems: 'center'
},
bottomComponentContainer: {
justifyContent: 'center',
alignItems: 'center'
},
systemMessageWrapper: {
backgroundColor: '#006BA6',
borderRadius: 4,
padding: 5
},
systemMessageText: {
fontFamily: "OpenSans_600SemiBold",
fontSize: 14,
color: '#ffffff'
}
});<file_sep>/src/navigation/AppNavigation.js
import React, { useContext, useEffect } from 'react';
import { createStackNavigator } from '@react-navigation/stack';
import Tabs from './TabNavigation';
import { startClock } from 'react-native-reanimated';
import Login from '../screens/LoginScreen/Login';
import SignUp from '../screens/SignUpScreen/SignUp';
const Stack = createStackNavigator();
export default function AppNavigation() {
return (
<Stack.Navigator headerMode='none'>
<Stack.Screen name='Home' component={Tabs} />
</Stack.Navigator>
);
}<file_sep>/src/screens/Profile.js
import React, { useContext, useState, useEffect } from "react";
import { StyleSheet, View, Text, Image, TouchableOpacity, ScrollView } from "react-native";
import { Button, Avatar } from 'react-native-elements'
import { UserAuthContext } from '../navigation/UserAuthProvider';
import { firestore, auth } from '../components/Firebase/method';
function Profile({navigation}) {
const { user } = useContext(UserAuthContext);
//const [email, setEmail];
const currentUser = user.toJSON();
//const email = firestore.collection('users').doc(user.uid).doc('email');
const [name, setName] = useState('');
//const [password, setPassword] = useState('');
const [initials, setInitials] = useState('');
const ref = firestore.collection('users').doc(currentUser.uid);
useEffect(() => {
ref
.get()
.then(doc => {
setName(doc.data().fullName);
});
if (name) {
const fullName = name.split(' ');
const firstName = fullName[0];
const lastName = fullName[1];
setInitials((firstName[0] || "") + (lastName[0] || ""));
}
})
return (
<ScrollView contentContainerStyle={{alignItems: "center", marginTop: 30}}>
<View style = {styles.avatar}>
<Avatar
size="xlarge"
rounded
title={initials}
overlayContainerStyle={{ backgroundColor: '#FF8600'}}
/>
</View>
<Text style = {styles.title}>{name}</Text>
<View style = {styles.body}>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', marginTop: 10, marginLeft: 50, alignSelf : 'flex-start'}}>
<Image style={{ width: 40, height: 40, marginTop: 20, alignSelf: "center"}} source = {require("../assets/emojis/email.png")} />
<Text style = {styles.labels}>{currentUser.email}</Text>
</View>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', marginTop: 10, marginLeft: 50, alignSelf : 'flex-start'}}>
<Image style={{ width: 40, height: 40, alignSelf: "center"}} source = {require("../assets/emojis/changeLevelsShow.png")} />
<View>
<Text style = {styles.labelsB}>German A1</Text>
<Text style = {styles.labelsA}>French A1</Text>
<Text style = {styles.labelsA}>Spanish B2</Text>
<Text style = {styles.labelsA}>Italian A1</Text>
</View>
</View>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', marginTop: 10, marginLeft: 50, alignSelf : 'flex-start'}}>
<Image style={{ width: 40, height: 40, marginTop: 20, alignSelf: "center"}} source = {require("../assets/emojis/birthday.png")} />
<Text style = {styles.labels}>March 12th, 1998</Text>
</View>
</View>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', marginTop: 25, marginLeft: 50, alignSelf : 'flex-start'}}>
<TouchableOpacity style = {styles.press}>
<Image style={{ width: 40, height: 40, marginTop: 20, alignSelf: "center"}} source = {require("../assets/emojis/changeProfile.png")} />
<Text style = {styles.labelsC}>Change</Text>
<Text style = {styles.labelsD}>Password</Text>
</TouchableOpacity>
<TouchableOpacity style = {styles.press} >
<Image style={{ width: 40, height: 40, marginTop: 20, alignSelf: "center"}} source = {require("../assets/emojis/delete.png")} />
<Text style = {styles.labelsC}>Delete</Text>
<Text style = {styles.labelsD}>Account</Text>
</TouchableOpacity>
<TouchableOpacity style = {styles.press}>
<Image style={{ width: 40, height: 40, marginTop: 20, alignSelf: "center"}} source = {require("../assets/emojis/changeLevel.png")} />
<Text style = {styles.labelsC}>Change</Text>
<Text style = {styles.labelsD}>Levels</Text>
</TouchableOpacity>
</View>
</ScrollView>
/*<View style={styles.container}>
<View style={styles.changePasswordButtonRow}>
<View style={styles.changePasswordButton}>
<View style={styles.changePasswordBodyStack}>
<View style={styles.changePasswordBody}>
<ChangeProfile style={styles.changeProfile}></ChangeProfile>
</View>
<Text style={styles.changePassword}>Change Password</Text>
</View>
</View>
<View style={styles.deleteAccountButton}>
<View style={styles.deleteBody}>
<MaterialIconsIcon
name="delete-forever"
style={styles.garbage}
></MaterialIconsIcon>
<Text style={styles.deleteAccount}>Delete {"\n"}Account</Text>
</View>
</View>
<View style={styles.changeLevelButton}>
<View style={styles.changeLevelBody}>
<FontAwesomeIcon
name="language"
style={styles.levelIcon2}
></FontAwesomeIcon>
<Text style={styles.changeLevels}>Change Levels</Text>
</View>
</View>
</View>
<Homebar style={styles.homebar}></Homebar>
<View style={styles.profileBody}>
<View style={styles.body}>
<View style={styles.emailInfo}>
<View style={styles.emailIconRow}>
<FeatherIcon name="mail" style={styles.emailIcon}></FeatherIcon>
<Text style={styles.email}>email</Text>
</View>
</View>
<View style={styles.langLevelsInfo}>
<View style={styles.levelIconRow}>
<FontAwesomeIcon
name="language"
style={styles.levelIcon}
></FontAwesomeIcon>
<Text style={styles.langLevels}>Lang Levels</Text>
</View>
</View>
<View style={styles.birthdayInfo}>
<View style={styles.birthdayIconRow}>
<FontAwesomeIcon
name="birthday-cake"
style={styles.birthdayIcon}
></FontAwesomeIcon>
<Text style={styles.birthday}>birthday</Text>
</View>
</View>
</View>
</View>
<View style={styles.profilePicStack}>
<Svg viewBox="0 0 100.34 99.81" style={styles.profilePic}>
<Ellipse
stroke="rgba(230, 230, 230,1)"
strokeWidth={0}
fill="rgba(230, 230, 230,1)"
cx={50}
cy={50}
rx={50}
ry={50}
></Ellipse>
</Svg>
<Text style={styles.name}>Name</Text>
</View>
</View>*/
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
height: 50,
alignItems: "center"
},
title: {
fontFamily: "OpenSans_800ExtraBold",
color: "rgba(27,6,94,1)",
fontSize: 48,
textAlign: "center",
marginBottom: 20
},
body: {
width: 321,
height: 300,
backgroundColor: "rgba(217,240,255,1)",
borderRadius: 100,
alignSelf: "center"
},
labels: {
fontFamily: "OpenSans_600SemiBold",
color: "rgba(0,107,166,1)",
fontSize: 18,
color: "#121212",
textAlign: "center",
marginLeft: 30,
marginTop: 30
},
labelsB: {
fontFamily: "OpenSans_600SemiBold",
color: "rgba(0,107,166,1)",
fontSize: 18,
color: "#121212",
marginTop: 40,
marginLeft: 30
},
labelsA: {
fontFamily: "OpenSans_600SemiBold",
color: "rgba(0,107,166,1)",
fontSize: 18,
color: "#121212",
marginLeft: 30
},
changePasswordButton: {
width: 104,
height: 142
},
changePasswordBody: {
top: 0,
left: 5,
width: 94,
height: 142,
position: "absolute",
backgroundColor: "rgba(217,240,255,1)",
borderRadius: 100,
shadowColor: "rgba(0,0,0,1)",
shadowOffset: {
width: 3,
height: 3
},
elevation: 5,
shadowOpacity: 1,
shadowRadius: 0
},
changeProfile: {
height: 58,
width: 52,
marginTop: 12,
marginLeft: 18
},
changePassword: {
top: 71,
left: 0,
position: "absolute",
fontFamily: "OpenSans_700Bold",
color: "#121212",
height: 55,
width: 104,
fontSize: 18,
textAlign: "center"
},
changePasswordBodyStack: {
width: 104,
height: 142
},
deleteAccountButton: {
width: 94,
height: 142,
marginLeft: 14
},
deleteBody: {
width: 94,
height: 142,
backgroundColor: "rgba(217,240,255,1)",
borderRadius: 100,
shadowColor: "rgba(0,0,0,1)",
shadowOffset: {
width: 3,
height: 3
},
elevation: 5,
shadowOpacity: 1,
shadowRadius: 0
},
avatar: {
width: 100,
height: 100,
marginTop: 40,
marginBottom: 60,
alignItems: "center"
},
garbage: {
color: "rgba(0,107,166,1)",
fontSize: 52,
height: 52,
width: 52,
marginTop: 15,
marginLeft: 21
},
press: {
backgroundColor: "rgba(217,240,255,1)",
borderRadius: 100,
shadowColor: "rgba(0,0,0,1)",
shadowOffset: {
width: 3,
height: 3
},
elevation: 5,
shadowOpacity: 1,
shadowRadius: 0,
width: 94,
height: 142,
marginRight: 25
},
labelsC: {
fontFamily: "OpenSans_600SemiBold",
color: "rgba(0,107,166,1)",
fontSize: 18,
color: "#121212",
textAlign: "center",
marginTop: 10
},
labelsD: {
fontFamily: "OpenSans_600SemiBold",
color: "rgba(0,107,166,1)",
fontSize: 18,
color: "#121212",
textAlign: "center"
},
deleteAccount: {
fontFamily: "OpenSans_700Bold",
color: "#121212",
height: 55,
width: 83,
fontSize: 18,
textAlign: "center",
marginTop: 4,
marginLeft: 6
},
changeLevelButton: {
width: 94,
height: 142,
marginLeft: 19
},
changeLevelBody: {
width: 94,
height: 142,
backgroundColor: "rgba(217,240,255,1)",
borderRadius: 100,
shadowColor: "rgba(0,0,0,1)",
shadowOffset: {
width: 3,
height: 3
},
elevation: 5,
shadowOpacity: 1,
shadowRadius: 0
},
levelIcon2: {
color: "rgba(0,107,166,1)",
fontSize: 40,
height: 40,
width: 35,
marginTop: 21,
marginLeft: 30
},
changeLevels: {
fontFamily: "OpenSans_700Bold",
color: "#121212",
height: 45,
width: 94,
fontSize: 18,
textAlign: "center",
marginTop: 9
},
changePasswordButtonRow: {
height: 142,
flexDirection: "row",
marginTop: 551,
marginLeft: 15,
marginRight: 20
},
homebar: {
width: 360,
height: 65,
marginTop: 22
},
profileBody: {
width: 321,
height: 346,
marginTop: -593,
marginLeft: 20
},
body: {
width: 321,
height: 346,
backgroundColor: "rgba(217,240,255,0.75)",
borderRadius: 70
},
emailInfo: {
width: 242,
height: 40,
flexDirection: "row",
marginTop: 18,
marginLeft: 47
},
emailIcon: {
color: "rgba(0,107,166,1)",
fontSize: 40
},
email: {
fontFamily: "OpenSans_400Regular",
color: "#121212",
height: 24,
width: 165,
fontSize: 18,
marginLeft: 37,
marginTop: 8
},
emailIconRow: {
height: 40,
flexDirection: "row",
flex: 1
},
langLevelsInfo: {
width: 198,
height: 40,
flexDirection: "row",
marginTop: 67,
marginLeft: 47
},
levelIcon: {
color: "rgba(0,107,166,1)",
fontSize: 40
},
langLevels: {
fontFamily: "OpenSans_400Regular",
color: "#121212",
height: 20,
width: 127,
fontSize: 18,
marginLeft: 38
},
levelIconRow: {
height: 40,
flexDirection: "row",
flex: 1,
marginRight: -1
},
birthdayInfo: {
width: 240,
height: 40,
flexDirection: "row",
marginTop: 109,
marginLeft: 44
},
birthdayIcon: {
color: "rgba(0,107,166,1)",
fontSize: 40
},
birthday: {
fontFamily: "OpenSans_400Regular",
color: "#121212",
height: 24,
width: 165,
fontSize: 18,
marginLeft: 35,
marginTop: 8
},
birthdayIconRow: {
height: 40,
flexDirection: "row",
flex: 1
},
profilePic: {
top: 0,
width: 100,
height: 100,
position: "absolute",
left: 35
},
name: {
top: 91,
left: 0,
position: "absolute",
fontFamily: "OpenSans_800ExtraBold",
color: "rgba(27,6,94,1)",
height: 61,
width: 170,
fontSize: 48,
textAlign: "center"
},
profilePicStack: {
width: 170,
height: 152,
marginTop: -504,
marginLeft: 95
}
});
export default Profile;
<file_sep>/src/navigation/ProfileNavigation.js
import React, { useContext, useEffect } from 'react';
import { createStackNavigator } from '@react-navigation/stack';
import Profile from '../screens/Profile';
import Contacts from '../screens/Contacts';
const Stack = createStackNavigator();
export default function ProfileNavigation() {
return (
<Stack.Navigator>
<Stack.Screen name='Profile' component={Profile} />
<Stack.Screen name='Contacts' component={Contacts} />
</Stack.Navigator>
)
}
<file_sep>/src/screens/SignUpScreen/SignUp.js
import React, { useState } from 'react'
import { Image, Text, TextInput, TouchableOpacity, View } from 'react-native'
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import styles from './styles';
import { signUp, firestore } from '../../components/Firebase/method'
import DatePicker from 'react-native-datepicker';
import SectionedMultiSelect from 'react-native-sectioned-multi-select';
import Icon from 'react-native-vector-icons/MaterialIcons';
export default function SignUp({navigation}) {
const [fullName, setFullName] = useState('')
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [confirmPassword, setConfirmPassword] = useState('')
const [birthdate, setDate] = useState(new Date())
const [language, setLanguage] = useState([]);
const items = [
{
name: 'German',
children: [
{
level: 'German A1'
},
{
level: 'German A2'
},
{
level: 'German B1'
},
{
level: 'German B2'
},
{
level: 'German C1'
},
{
level: 'German C2'
}
]
},
{
name: 'French',
children: [
{
level: 'French A1'
},
{
level: 'French A2'
},
{
level: 'French B1'
},
{
level: 'French B2'
},
{
level: 'French C1'
},
{
level: 'French C2'
}
]
},
{
name: 'Italian',
children: [
{
level: 'Italian A1'
},
{
level: 'Italian A2'
},
{
level: 'Italian B1'
},
{
level: 'Italian B2'
},
{
level: 'Italian C1'
},
{
level: 'Italian C2'
}
]
},
{
name: 'Spanish',
children: [
{
level: 'Spanish A1'
},
{
level: 'Spanish A2'
},
{
level: 'Spanish B1'
},
{
level: 'Spanish B2'
},
{
level: 'Spanish C1'
},
{
level: 'Spanish C2'
}
]
}
]
const selectedLanguage = (selectedItems) => {
setLanguage(selectedItems);
}
const onFooterLinkPress = () => {
navigation.navigate('Login')
}
const onSignUpPress = () => {
if (password !== confirmPassword) {
alert("Passwords don't match.")
return
}
if (birthdate == new Date()) {
alert("Please choose a date")
return
}
signUp(email, password)
.then((response) => {
const uid = response.user.uid
const data = {
fullName,
email,
};
const usersRef = firestore.collection('users')
usersRef
.doc(uid)
.set(data)
.then(() => {
navigation.navigate('Welcome')
})
.catch((error) => {
alert(error)
});
})
.catch((error) => {
alert(error)
});
}
return (
<View style={styles.container}>
<KeyboardAwareScrollView
style={{ flex: 1, width: '100%' }}
keyboardShouldPersistTaps="always">
<Image
style={styles.logo}
source={require('../../assets/logo.png')}
/>
<TextInput
style={styles.input}
placeholder='<NAME>'
placeholderTextColor="#aaaaaa"
onChangeText={(text) => setFullName(text)}
value={fullName}
underlineColorAndroid="transparent"
autoCapitalize="none"
/>
{/*<View>
<Text>Your birthdate</Text>
<DatePicker
date={birthdate} //initial date from state
mode="date" //The enum of date, datetime and time
placeholder="Select date"
format="MM-DD-YYYY"
confirmBtnText="Confirm"
cancelBtnText="Cancel"
customStyles={{
dateIcon: {
//display: 'none',
position: 'absolute',
left: 0,
top: 4,
marginLeft: 0,
},
dateInput: {
marginLeft: 36,
},
}}
onDateChange={(birthdate) => {
setDate(new Date(birthdate));
}} />
</View>
<View>
<SectionedMultiSelect
items={items}
IconRenderer={Icon}
subKey="children"
selectText="Select your language level"
showDropDowns={true}
readOnlyHeadings={true}
onSelectedItemsChange={selectedLanguage}
selectedItems={language}
/>
</View>*/}
<TextInput
style={styles.input}
placeholder='E-mail'
placeholderTextColor="#aaaaaa"
onChangeText={(text) => setEmail(text)}
value={email}
underlineColorAndroid="transparent"
autoCapitalize="none"
/>
<TextInput
style={styles.input}
placeholderTextColor="#aaaaaa"
secureTextEntry
placeholder='Password'
onChangeText={(text) => setPassword(text)}
value={password}
underlineColorAndroid="transparent"
autoCapitalize="none"
/>
<TextInput
style={styles.input}
placeholderTextColor="#aaaaaa"
secureTextEntry
placeholder='Confirm Password'
onChangeText={(text) => setConfirmPassword(text)}
value={confirmPassword}
underlineColorAndroid="transparent"
autoCapitalize="none"
/>
<TouchableOpacity
style={styles.button}
onPress={() => onSignUpPress()}>
<Text style={styles.buttonTitle}>Create account</Text>
</TouchableOpacity>
<View style={styles.footerView}>
<Text style={styles.footerText}>Already got an account? <Text onPress={onFooterLinkPress} style={styles.footerLink}>Log in</Text></Text>
</View>
</KeyboardAwareScrollView>
</View>
)
}<file_sep>/src/components/stuff/Logo.js
import React, { Component } from "react";
import { StyleSheet, View } from "react-native";
import IoniconsIcon from "react-native-vector-icons/Ionicons";
import MaterialCommunityIconsIcon from "react-native-vector-icons/MaterialCommunityIcons";
import EntypoIcon from "react-native-vector-icons/Entypo";
import FontAwesomeIcon from "react-native-vector-icons/FontAwesome";
function Logo(props) {
return (
<View style={[styles.container, props.style]}>
<View style={styles.earthStack}>
<IoniconsIcon name="md-globe" style={styles.earth}></IoniconsIcon>
<MaterialCommunityIconsIcon
name="television-classic"
style={styles.tV}
></MaterialCommunityIconsIcon>
<EntypoIcon name="book" style={styles.book}></EntypoIcon>
<MaterialCommunityIconsIcon
name="video-vintage"
style={styles.movie}
></MaterialCommunityIconsIcon>
<FontAwesomeIcon name="music" style={styles.icon10}></FontAwesomeIcon>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {},
earth: {
position: "absolute",
color: "rgba(255,134,0,1)",
fontSize: 70,
left: 0,
top: 0
},
tV: {
top: 23,
left: 38,
position: "absolute",
color: "rgba(217,240,255,1)",
fontSize: 19
},
book: {
top: 7,
left: 20,
position: "absolute",
color: "rgba(217,240,255,1)",
fontSize: 18
},
movie: {
top: 25,
left: 2,
position: "absolute",
color: "rgba(217,240,255,1)",
fontSize: 18
},
icon10: {
top: 43,
left: 22,
position: "absolute",
color: "rgba(217,240,255,1)",
fontSize: 16
},
earthStack: {
width: 57,
height: 76
}
});
export default Logo;
<file_sep>/src/components/stuff/MessageComponent.js
import React, { Component } from "react";
import { StyleSheet, View } from "react-native";
import ProfilePic from "./ProfilePic";
import Messages from "./Messages";
function MessageComponent(props) {
return (
<View style={[styles.container, props.style]}>
<View style={styles.profilePic4Row}>
<ProfilePic style={styles.profilePic4}></ProfilePic>
<Messages style={styles.messages3}></Messages>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flexDirection: "row"
},
profilePic4: {
width: 75,
height: 75,
marginTop: 21
},
messages3: {
width: 230,
height: 116,
marginLeft: 21
},
profilePic4Row: {
height: 116,
flexDirection: "row",
flex: 1
}
});
export default MessageComponent;
<file_sep>/src/screens/Review.js
import React, { useState, useEffect } from "react";
import { StyleSheet, View, Text, FlatList } from "react-native";
import { Avatar } from 'react-native-elements';
import { firestore } from '../components/Firebase/method';
const Review = ({ route, navigation }) => {
const media = route.params.id;
const title = route.params.title;
const [post, setPost] = useState([]);
useEffect(() => {
firestore.collection('reviews')
.doc(media).collection('posts')
.get()
.then(snapshot => {
snapshot.forEach(doc => {
const data = {
id: doc.id,
user: doc.data().userName,
rating: doc.data().rate,
review: doc.data().review
};
setPost(post => [...post, data]);
})
})
}, []);
let posts = post.filter( (ele, ind) => ind === post.findIndex( elem => elem.id === ele.id));
/*if(posts.length > 0) {
const name = posts[0].user.split(' ');
const firstName = name[0];
const lastName = name[1];
initials = (firstName[0] || "") + (lastName[0] || "");
}*/
//const initials = 'UH';
const renderItem = ({ item }) => {
const name = item.user.split(' ');
const firstName = name[0];
const lastName = name[1];
const initials = (firstName[0] || "") + (lastName[0] || "");
console.log(initials);
return (
<View style={{ flexDirection: 'row', justifyContent: 'space-between', alignSelf : 'flex-start', marginLeft: 20, marginTop: 10}}>
<View style = {{marginTop: 30, marginRight: 20}}>
<Avatar
size="large"
rounded
title={initials}
overlayContainerStyle={{ backgroundColor: '#FF8600'}}
/>
</View>
<View style = {styles.body}>
<Text style = {styles.name}>{item.user}</Text>
<Text style = {styles.review} >{item.review}</Text>
<Text style = {styles.rating}>{item.rating} stars</Text>
</View>
</View>
)
}
return (
<View>
<Text style = {styles.title}>User Reviews</Text>
<Text style = {styles.subtitle}>{title}</Text>
<View>
<FlatList
data={posts}
renderItem={renderItem}
keyExtractor={item => item.id}
numColumns={1}
contentContainerStyle={{ paddingVertical: 10 }}
/>
</View>
</View>
/*<View style={styles.container}>
<View style={styles.profileReview}>
<View style={styles.profilePicRow}>
<ProfilePic style={styles.profilePic}></ProfilePic>
<ReviewUpdated style={styles.reviewUpdated}></ReviewUpdated>
</View>
</View>
<View style={styles.profileReview2}>
<View style={styles.profilePic2Row}>
<ProfilePic style={styles.profilePic2}></ProfilePic>
<ReviewUpdated style={styles.reviewUpdated2}></ReviewUpdated>
</View>
</View>
<ReviewComponent style={styles.reviewComponent}></ReviewComponent>
<Homebar style={styles.homebar}></Homebar>
<View style={styles.backArrowRow}>
<BackArrow style={styles.backArrow}></BackArrow>
<Text style={styles.userReviews}>User Reviews</Text>
</View>
<Text style={styles.mediaName}>Media Name</Text>
</View>*/
);
}
const styles = StyleSheet.create({
container: {
flex: 1
},
title: {
fontFamily: "OpenSans_800ExtraBold",
color: "rgba(27,6,94,1)",
fontSize: 48,
alignItems: "center",
justifyContent: "center",
marginBottom: 10,
marginTop: 10,
alignSelf: "center"
},
subtitle: {
fontFamily: "OpenSans_600SemiBold",
color: "rgba(255,134,0,1)",
fontSize: 24,
alignSelf: "center"
},
body: {
backgroundColor: "rgba(217,240,255,1)",
borderRadius: 38,
opacity: 0.75,
shadowColor: "rgba(0,0,0,1)",
shadowOffset: {
width: 3,
height: 3
},
elevation: 5,
shadowOpacity: 1,
shadowRadius: 0,
width: 230,
height: 116,
alignSelf: "center",
alignItems: "center"
},
profileReview: {
width: 317,
height: 116,
flexDirection: "row",
marginTop: 237,
marginLeft: 23
},
profilePic: {
height: 75,
width: 75,
marginTop: 21
},
reviewUpdated: {
width: 230,
height: 116,
marginLeft: 12
},
profilePicRow: {
height: 116,
flexDirection: "row",
flex: 1
},
profileReview2: {
width: 319,
height: 116,
flexDirection: "row",
marginTop: 31,
marginLeft: 21
},
profilePic2: {
width: 75,
height: 75,
marginTop: 24
},
reviewUpdated2: {
height: 116,
width: 230,
marginLeft: 14
},
profilePic2Row: {
height: 116,
flexDirection: "row",
flex: 1
},
name: {
alignSelf: "flex-start",
marginLeft: 20,
marginTop: 15,
fontFamily: "OpenSans_700Bold",
color: "#006BA6",
fontSize: 18,
marginBottom: 5
},
review: {
alignSelf: "flex-start",
marginLeft: 20,
marginBottom: 5,
fontFamily: "OpenSans_400Regular",
fontSize: 16
},
rating: {
alignSelf: "flex-start",
marginLeft: 20,
marginBottom: 5,
fontFamily: "OpenSans_600SemiBold",
fontSize: 16
},
reviewComponent: {
height: 116,
width: 319,
marginTop: 37,
marginLeft: 21
},
homebar: {
width: 360,
height: 65,
marginTop: 22,
alignSelf: "center"
},
backArrow: {
width: 48,
height: 76
},
userReviews: {
fontFamily: "OpenSans_800ExtraBold",
color: "rgba(27,6,94,1)",
height: 133,
width: 230,
fontSize: 48,
textAlign: "center",
marginLeft: 21
},
backArrowRow: {
height: 133,
flexDirection: "row",
marginTop: -717,
marginLeft: 10,
marginRight: 51
},
mediaName: {
fontFamily: "OpenSans_600SemiBold",
color: "rgba(255,134,0,1)",
height: 41,
width: 169,
fontSize: 24,
marginTop: 13,
marginLeft: 109
}
});
export default Review;
<file_sep>/src/navigation/TabNavigation.js
import React from "react";
import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";
import { StyleSheet, View, Image } from "react-native";
import Welcome from '../screens/Welcome'
import Bookmarks from "../screens/Bookmarks"
import MediaNavigation from './MediaNavigation'
import Profile from '../screens/Profile'
import { icons, COLORS } from "../components";
import { Ionicons, MaterialIcons } from '@expo/vector-icons';
import ChatNavigatior from './ChatNavigation'
const Tab = createBottomTabNavigator();
const tabOptions = {
showLabel: false,
style: {
height: "10%",
backgroundColor: "#1B065E"
}
}
const Tabs = () => {
return (
<Tab.Navigator
tabBarOptions={tabOptions}
screenOptions={({ route }) => ({
tabBarIcon: ({ focused }) => {
const tintColor = focused ? COLORS.white : COLORS.gray;
switch (route.name) {
case "Bookmark":
return (
<MaterialIcons name="bookmark" size={40} color="#FF8600" />
)
case "Welcome":
return (
<MaterialIcons name="notifications" size={40} color="#FF8600" />
)
case 'Profile':
return (
<Ionicons name="md-person" size={40} color="#FF8600"></Ionicons>
)
case 'Chat':
return (
<Ionicons name="chatbox-sharp" size={40} color="#FF8600"></Ionicons>
)
}
}
})}
>
<Tab.Screen
name="Welcome"
component={Welcome}
/>
<Tab.Screen
name="Chat"
component={ChatNavigatior}
/>
<Tab.Screen
name="MediaNavigation"
options= {{tabBarIcon: () => {
return (
<Image
style={styles.logo}
source={require('../assets/logo.png')}
/>
)
}}}
component={MediaNavigation}
/>
<Tab.Screen
name="Bookmark"
component={Bookmarks}
/>
<Tab.Screen
name="Profile"
component={Profile}
/>
</Tab.Navigator>
)
}
const styles = StyleSheet.create({
container: {},
logo: {
width: 60,
height: 60,
},
earth: {
position: "absolute",
color: "rgba(255,134,0,1)",
fontSize: 70,
left: 0,
top: 0
},
tV: {
top: 23,
left: 38,
position: "absolute",
color: "rgba(217,240,255,1)",
fontSize: 19
},
book: {
top: 7,
left: 20,
position: "absolute",
color: "rgba(217,240,255,1)",
fontSize: 18
},
movie: {
top: 25,
left: 2,
position: "absolute",
color: "rgba(217,240,255,1)",
fontSize: 18
},
icon10: {
top: 43,
left: 22,
position: "absolute",
color: "rgba(217,240,255,1)",
fontSize: 16
},
earthStack: {
width: 57,
height: 76
}
});
export default Tabs;<file_sep>/src/screens/SelectLanguage.js
import React, { Component } from "react";
import { StyleSheet, View, Text, Image, TouchableOpacity, FlatList } from "react-native";
import Homebar from "../components/stuff/Homebar";
function SelectLanguage({ navigation }) {
const selectLanguage = (chosen) => {
navigation.navigate('Filter');
}
const data = [
{
name: "German",
img: require("../assets/flags/germany.png"),
language: 'german'
},
{
name: "Portuguese",
img: require("../assets/flags/portugal.png"),
language: 'portuguese'
},
{
name: "French",
img: require("../assets/flags/france.png"),
language: 'french'
},
{
name: "Spanish",
img: require("../assets/flags/spain.png"),
language: 'spanish'
},
{
name: "Italian",
img: require('../assets/flags/italy.png'),
language: 'italian'
},
{
name: "Dutch",
img: require("../assets/flags/netherlands.png"),
language: 'dutch'
}
]
const renderItem = ({ item }) => (
<TouchableOpacity style={styles.languageButton} onPress={() => {navigation.navigate('Filter', { language: item.language})}}>
<Image
style={{ width: 100, height: 70}}
source={item.img}
/>
<Text style = {styles.languageLabel}>{item.name}</Text>
</TouchableOpacity>
);
return (
<View style={{ flex: 1 }}>
<View style={styles.container}>
<Text style={styles.selectALanguage}>Pick a Language</Text>
</View>
<FlatList
data={data}
renderItem={renderItem}
keyExtractor={item => item.name}
numColumns={2}
style={{ flex: 1 }}
contentContainerStyle={{ paddingVertical: 5 }}
/>
</View>
);
}
/*return (
<View>
<View style={styles.container}>
<Text style={styles.selectALanguage}>Pick a Language</Text>
</View>
<View style= {styles.buttonContainter}>
<TouchableOpacity style= {styles.languageButton} onPress={selectLanguage}>
<Image source={require('../assets/flags/germany.png')} />
<Text style = {styles.languageLabel}>Germany</Text>
</TouchableOpacity>
<TouchableOpacity style= {styles.languageButton} onPress={selectLanguage}>
<Image source={require('../assets/flags/france.png')} />
<Text style = {styles.languageLabel}>France</Text>
</TouchableOpacity>
<TouchableOpacity style= {styles.languageButton} onPress={selectLanguage}>
<Image source={require('../assets/flags/italy.png')} />
<Text style = {styles.languageLabel}>Italy</Text>
</TouchableOpacity>
<TouchableOpacity style= {styles.languageButton} onPress={selectLanguage}>
<Image source={require('../assets/flags/portugal.png')} />
<Text style = {styles.languageLabel}>Portugal</Text>
</TouchableOpacity>
<TouchableOpacity style= {styles.languageButton} onPress={selectLanguage}>
<Image source={require('../assets/flags/spain.png')} />
<Text style = {styles.languageLabel}>Spain</Text>
</TouchableOpacity>
<TouchableOpacity style= {styles.languageButton} onPress={selectLanguage}>
<Image source={require('../assets/flags/netherlands.png')} />
<Text style = {styles.languageLabel}>Netherlands</Text>
</TouchableOpacity>
</View>
</View>
/*<View style={styles.container}>
<Homebar style={styles.homebar}></Homebar>
<Text style={styles.selectALanguage}>Select a Language</Text>
<View style={styles.languageButtons}>
<View style={styles.germanButtonRow}>
<View style={styles.germanButton}>
<View style={styles.gERButton}>
<Text style={styles.german}>German</Text>
</View>
</View>
<View style={styles.italianButton}>
<View style={styles.iTLButton}>
<Text style={styles.italian}>Italian</Text>
</View>
</View>
</View>
<View style={styles.frenchButtonRow}>
<View style={styles.frenchButton}>
<View style={styles.fRAButton}>
<Text style={styles.french}>French</Text>
</View>
</View>
<View style={styles.portugueseButton}>
<View style={styles.pORButton}>
<Text style={styles.portuguese}>Portuguese</Text>
</View>
</View>
</View>
<View style={styles.spanishButtonRow}>
<View style={styles.spanishButton}>
<View style={styles.eSPButton}>
<Text style={styles.spanish}>Spanish</Text>
</View>
</View>
<View style={styles.dutchButton}>
<View style={styles.dUTButton}>
<Text style={styles.dutch}>Dutch</Text>
</View>
</View>
</View>
</View>
</View>
);
} */
const styles = StyleSheet.create({
container: {
height: 60,
alignItems: "center",
marginBottom: "10%"
},
homebar: {
width: 360,
height: 65,
marginTop: 675
},
languageButton: {
flex: 1,
marginHorizontal: "5%",
marginBottom: "15%",
backgroundColor: "rgba(217,240,255,1)",
borderRadius: 44,
shadowColor: "rgba(0,0,0,1)",
shadowOffset: {
width: 3,
height: 3
},
elevation: 5,
shadowOpacity: 1,
shadowRadius: 0,
width: 154,
height: 131,
alignItems: "center",
justifyContent: "center"
},
selectALanguage: {
fontFamily: "OpenSans_800ExtraBold",
color: "rgba(27,6,94,1)",
fontSize: 48,
alignItems: "center",
justifyContent: "center",
},
languageLabel: {
fontFamily: "OpenSans_600SemiBold",
color: "rgba(0,107,166,1)",
fontSize: 24
}
});
export default SelectLanguage;
<file_sep>/src/components/stuff/Reviews.js
import React, { Component } from "react";
import { StyleSheet, View, Text } from "react-native";
function Reviews(props) {
return (
<View style={[styles.container, props.style]}>
<View style={styles.rect}>
<Text style={styles.reviewsRatings}>Reviews {"\n"}Ratings</Text>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {},
rect: {
width: 216,
height: 99,
borderWidth: 1,
borderColor: "#000000"
},
reviewsRatings: {
fontFamily: "roboto-regular",
color: "#121212",
height: 45,
width: 197,
marginTop: 5,
marginLeft: 9
}
});
export default Reviews;
<file_sep>/src/navigation/index.js
import React from 'react';
import { UserAuthProvider } from './UserAuthProvider';
import Navigate from './Naivgate';
import { Provider as PaperProvider } from 'react-native-paper';
/**
* Wrap all providers here
*/
export default function Providers() {
return (
<PaperProvider>
<UserAuthProvider>
<Navigate />
</UserAuthProvider>
</PaperProvider>
);
}<file_sep>/src/navigation/UserAuthNavigation.js
import * as React from 'react';
import { createStackNavigator } from '@react-navigation/stack';
import SignUp from '../screens/SignUpScreen/SignUp';
import Login from '../screens/LoginScreen/Login';
import Tabs from './TabNavigation';
//import ForgotPasswordScreen from '../screens/ForgotPasswordScreen';
const Stack = createStackNavigator();
export default function UserAuthNavigation() {
return (
<Stack.Navigator initialRouteName='Login' headerMode="none">
<Stack.Screen name="Login" component={Login} />
<Stack.Screen name="Register" component={SignUp} />
</Stack.Navigator>
);
}<file_sep>/src/components/stuff/ReviewComponent.js
import React, { Component } from "react";
import { StyleSheet, View } from "react-native";
import ProfilePic from "./ProfilePic";
import ReviewUpdated from "./ReviewUpdated";
function ReviewComponent(props) {
return (
<View style={[styles.container, props.style]}>
<View style={styles.profilePic3Row}>
<ProfilePic style={styles.profilePic3}></ProfilePic>
<ReviewUpdated style={styles.reviewUpdated3}></ReviewUpdated>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flexDirection: "row"
},
profilePic3: {
width: 75,
height: 75,
marginTop: 22
},
reviewUpdated3: {
width: 230,
height: 116,
marginLeft: 14
},
profilePic3Row: {
height: 116,
flexDirection: "row",
flex: 1
}
});
export default ReviewComponent;
<file_sep>/src/navigation/UserAuthProvider.js
import React, { useState, createContext } from 'react';
// A React Context to store the user's info
export const UserAuthContext = createContext({});
// A provider to allow children screens access to the info
export const UserAuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
return (
<UserAuthContext.Provider value={{ user, setUser }}>
{children}
</UserAuthContext.Provider>
);
};<file_sep>/src/screens/AddRoom.js
import React, { useState } from 'react';
import { View, StyleSheet, TextInput } from 'react-native';
import { IconButton, Title } from 'react-native-paper';
import { firestore } from '../components/Firebase/method';
import FormButton from '../components/FormButton';
export default function AddRoom({navigation}) {
const [room, setRoom] = useState('');
function create() {
if (room.length > 0) {
var message = 'You have joined ' + room + '.';
firestore.collection('threads').add({
name: room,
latestMessage: {
text: message,
createdAt: new Date().getTime()
}
})
.then(docRef => {
docRef.collection('messages').add({
text: message,
createdAt: new Date().getTime(),
system: true
});
navigation.navigate('Chatroom');
});
}
};
return (
<View style={styles.rootContainer}>
<View style={styles.closeButtonContainer}>
<IconButton
icon='close-circle'
size={36}
color='#006BA6'
onPress={() => navigation.goBack()}
/>
</View>
<View style={styles.innerContainer}>
<Title style={styles.title}>Create a new chat room</Title>
{/*<FormInput
labelName='Room Name'
value={room}
onChangeText={text => setRoom(text)}
clearButtonMode='while-editing'
/>*/}
<View style={styles.ratingBox}>
<TextInput
placeholder=""
keyboardAppearance="default"
maxLength={10}
numberOfLines={1}
multiline={true}
spellCheck={true}
selectionColor="rgba(230, 230, 230,1)"
placeholderTextColor="rgba(0,0,0,1)"
style={styles.ratingInput}
value={room}
onChangeText={(text) => setRoom(text)}
></TextInput>
</View>
<FormButton
title='Create'
modeValue='contained'
labelStyle={styles.buttonLabel}
onPress={() => create()}
disabled={room.length === 0}
/>
</View>
</View>
);
}
const styles = StyleSheet.create({
rootContainer: {
flex: 1
},
closeButtonContainer: {
position: 'absolute',
top: 30,
right: 0,
zIndex: 1
},
innerContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
title: {
fontFamily: "OpenSans_600SemiBold",
fontSize: 24,
marginBottom: 10,
color: "#006BA6"
},
buttonLabel: {
fontFamily: "OpenSans_700Bold",
fontSize: 22,
color: "#006BA6"
},
ratingInput: {
fontFamily: "OpenSans_400Regular",
color: "#121212",
fontSize: 16,
marginLeft: 15
},
ratingBox: {
width: 295,
height: 50,
borderWidth: 6,
borderColor: "rgba(0,107,166,1)",
borderRadius: 74,
borderStyle: "solid",
backgroundColor: "rgba(255,255,255,1)",
alignSelf: "center",
marginLeft: 10
}
});
<file_sep>/src/navigation/Naivgate.js
import React, { useContext, useEffect, useState } from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { auth } from '../components/Firebase/method';
//import navigationTheme from './navigationTheme';
import UserAuthNavigation from './UserAuthNavigation';
import AppNavigation from './AppNavigation';
import { UserAuthContext } from './UserAuthProvider';
//import Spinner from '../components/Spinner';
export default function Navigate() {
const { user, setUser } = useContext(UserAuthContext);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
// onAuthStateChanged returns an unsubscriber
const unsubscribeAuth = auth.onAuthStateChanged(async authUser => {
try {
await (authUser ? setUser(authUser) : setUser(null));
setIsLoading(false);
} catch (error) {
}
});
// unsubscribe auth listener on unmount
return unsubscribeAuth;
}, []);
if (isLoading) {
//return <Spinner />;
}
return (
<NavigationContainer>
{user ? <AppNavigation /> : <UserAuthNavigation/>}
</NavigationContainer>
);
}<file_sep>/src/components/stuff/BackArrow.js
import React, { Component } from "react";
import { StyleSheet, View } from "react-native";
import Icon from "react-native-vector-icons/Ionicons";
function BackArrow(props) {
return (
<View style={[styles.container, props.style]}>
<Icon name="md-arrow-round-back" style={styles.icon}></Icon>
</View>
);
}
const styles = StyleSheet.create({
container: {},
icon: {
color: "rgba(0,107,166,1)",
fontSize: 70
}
});
export default BackArrow;
<file_sep>/src/screens/LoginScreen/styles.js
import { StyleSheet } from 'react-native';
export default StyleSheet.create({
container: {
flex: 1,
alignItems: 'center'
},
title: {
},
logo: {
flex: 1,
height: 120,
width: 120,
alignSelf: "center",
margin: 30
},
input: {
height: 48,
borderRadius: 5,
overflow: 'hidden',
backgroundColor: 'white',
marginTop: 10,
marginBottom: 10,
marginLeft: 30,
marginRight: 30,
paddingLeft: 16
},
button: {
backgroundColor: '#1b065e',
marginLeft: 30,
marginRight: 30,
marginTop: 20,
height: 48,
borderRadius: 5,
alignItems: "center",
justifyContent: 'center'
},
buttonTitle: {
color: 'white',
fontSize: 16,
fontWeight: "bold"
},
footerView: {
flex: 1,
alignItems: "center",
marginTop: 20
},
footerText: {
fontSize: 16,
color: '#2e2e2d'
},
footerLink: {
color: "#1b065e",
fontWeight: "bold",
fontSize: 16
},
container1: {},
earth: {
position: "absolute",
color: "rgba(255,134,0,1)",
fontSize: 70,
left: 0,
top: 0
},
tV: {
top: 23,
left: 38,
position: "absolute",
color: "rgba(217,240,255,1)",
fontSize: 19
},
book: {
top: 7,
left: 20,
position: "absolute",
color: "rgba(217,240,255,1)",
fontSize: 18
},
movie: {
top: 25,
left: 2,
position: "absolute",
color: "rgba(217,240,255,1)",
fontSize: 18
},
icon10: {
top: 43,
left: 22,
position: "absolute",
color: "rgba(217,240,255,1)",
fontSize: 16
},
earthStack: {
width: 57,
height: 76
}
})<file_sep>/src/components/stuff/Homebar.js
import React, { Component } from "react";
import { StyleSheet, View } from "react-native";
import MaterialIconsIcon from "react-native-vector-icons/MaterialIcons";
import IoniconsIcon from "react-native-vector-icons/Ionicons";
import Logo from "./Logo";
function Homebar(props) {
return (
<View style={[styles.container, props.style]}>
<View style={styles.groupStack}>
<View style={styles.group}>
<View style={styles.tab}>
<View style={styles.notificationRow}>
<MaterialIconsIcon
name="notifications"
style={styles.notification}
></MaterialIconsIcon>
<IoniconsIcon
name="md-chatboxes"
style={styles.chat}
></IoniconsIcon>
<MaterialIconsIcon
name="bookmark"
style={styles.bookmark}
></MaterialIconsIcon>
<IoniconsIcon
name="md-person"
style={styles.profile}
></IoniconsIcon>
</View>
</View>
</View>
<Logo style={styles.logo}></Logo>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {},
group: {
top: 6,
left: 0,
width: 360,
height: 66,
position: "absolute"
},
tab: {
width: 360,
height: 65,
backgroundColor: "rgba(27,6,94,1)",
borderWidth: 1,
borderColor: "#000000",
flexDirection: "row"
},
notification: {
color: "rgba(255,134,0,1)",
fontSize: 40,
width: 40,
height: 40,
marginTop: 2
},
chat: {
color: "rgba(255,134,0,1)",
fontSize: 40,
width: 32,
height: 44,
marginLeft: 26,
marginTop: 3
},
bookmark: {
color: "rgba(255,134,0,1)",
fontSize: 40,
height: 40,
width: 40,
marginLeft: 117,
marginTop: 2
},
profile: {
color: "rgba(255,134,0,1)",
fontSize: 40,
height: 44,
width: 30,
marginLeft: 37
},
notificationRow: {
height: 47,
flexDirection: "row",
flex: 1,
marginRight: 17,
marginLeft: 21,
marginTop: 11
},
logo: {
position: "absolute",
top: 0,
left: 152,
height: 76,
width: 57
},
groupStack: {
width: 360,
height: 76,
marginTop: -6
}
});
export default Homebar;
<file_sep>/src/screens/Bookmarks.js
import React, { Component, useState, useEffect, useContext } from "react";
import { StyleSheet, View, Text ,Image, TouchableOpacity, FlatList, ScrollView } from "react-native";
import { UserAuthContext } from '../navigation/UserAuthProvider';
import { firestore } from '../components/Firebase/method';
function Bookmarks({ route, navigation }) {
const [media, setMedia] = useState([]);
const [language, setLanguage] = useState('');
const { user } = useContext(UserAuthContext);
const currentUser = user.toJSON();
const ref = firestore.collection('users').doc(currentUser.uid).collection('bookmarks');
useEffect(() => {
if(language.length > 0) {
const chosenMedia = [];
ref
.where('language', '==', language)
.get()
.then(snapshot => {
if(!snapshot.empty) {
snapshot.forEach(doc => {
const data = {
id: doc.id,
image: doc.data().image,
name: doc.data().name,
lang: language
};
//setMedia(media => [...media, data]);
chosenMedia.push(data);
})
setMedia(chosenMedia);
} else {
setMedia([]);
}
})
} else {
ref
.get()
.then(snapshot => {
snapshot.forEach(doc => {
const data = {
id: doc.id,
image: doc.data().image,
name: doc.data().name,
lang: language
};
setMedia(media => [...media, data]);
})
})
}
}, [language]);
const data = [
{
name: "Germany",
img: require("../assets/flags/germany.png"),
language: 'german'
},
{
name: "Portugal",
img: require("../assets/flags/portugal.png"),
language: 'portuguese'
},
{
name: "France",
img: require("../assets/flags/france.png"),
language: 'french'
},
{
name: "Spain",
img: require("../assets/flags/spain.png"),
language: "spanish"
},
{
name: "Italy",
img: require('../assets/flags/italy.png'),
language: 'italian'
},
{
name: "Netherlands",
img: require("../assets/flags/netherlands.png"),
language: 'dutch'
}
]
let save = media.filter( (ele, ind) => ind === media.findIndex( elem => elem.id === ele.id));
const renderMedia = ({ item }) => (
<TouchableOpacity style={styles.mediaButton}>
<Image
style={{ width: 100, height: 130, alignSelf: "center", marginTop: 20}}
source={{uri: item.image}}
/>
<Text style = {styles.label}>{item.name}</Text>
</TouchableOpacity>
);
const renderItem = ({ item }) => (
<TouchableOpacity style={styles.languageButton} onPress={() => setLanguage(item.language)}>
<Image
style={{ width: 50, height: 40}}
source={item.img}
/>
</TouchableOpacity>
);
return (
<ScrollView contentContainerStyle={{alignItems: "center"}}>
<View>
<View style={styles.container}>
<Text style={styles.bookmarkTitle}>Bookmarks</Text>
</View>
<View>
<View style = {{alignItems: "center"}}>
<FlatList
data={data}
renderItem={renderItem}
keyExtractor={item => item.name}
numColumns={3}
contentContainerStyle={{ paddingVertical: 5, marginTop: 20}}
/>
</View>
<View style = {{alignItems: "center"}}>
<FlatList
data={save}
renderItem={renderMedia}
keyExtractor={item => item.id}
numColumns={2}
contentContainerStyle={{ paddingVertical: 10 }}
/>
</View>
</View>
</View>
</ScrollView>
);
}
/*return (
<View style={styles.container}>
{<Homebar style={styles.homebar}></Homebar>}
<View style={styles.bookmarkTitleStack}>
<Text style={styles.bookmarkTitle}>Bookmarks</Text>
<View style={styles.bookmarkBody}>
<View style={styles.body}>
<Text style={styles.sortBy}>Sort By</Text>
<View style={styles.gERRow}>
<View style={styles.gER}></View>
<View style={styles.fRA}></View>
<View style={styles.eSP}></View>
</View>
<View style={styles.pORRow}>
<View style={styles.pOR}></View>
<View style={styles.dUT}></View>
<View style={styles.iTL}></View>
</View>
<Text style={styles.ger}>GER</Text>
{<BookmarkComponent
style={styles.bookmarkComponent}
></BookmarkComponent>}
</View>
</View>
</View>
</View>
);
}*/
const styles = StyleSheet.create({
container: {
height: 100,
alignItems: "center",
marginTop: 30
},
homebar: {
width: 360,
height: 65,
marginTop: 675
},
buttonContainter: {
width: 327,
height: 700,
alignItems: "center"
},
languageButton: {
marginHorizontal: 5,
marginRight: 10,
marginBottom: 20,
backgroundColor: "#FF8600",
borderRadius: 21,
shadowColor: "rgba(0,0,0,1)",
shadowOffset: {
width: 3,
height: 3
},
elevation: 5,
shadowOpacity: 1,
shadowRadius: 0,
width: 80,
height: 65,
alignItems: "center",
justifyContent: "center"
},
mediaButton: {
width: 154,
height: 221,
backgroundColor: "rgba(217,240,255,1)",
borderRadius: 21,
shadowColor: "rgba(0,0,0,1)",
shadowOffset: {
width: 3,
height: 3
},
elevation: 5,
shadowOpacity: 1,
shadowRadius: 0,
marginRight: 15,
marginBottom: 15
},
bookmarkTitle: {
fontFamily: "OpenSans_800ExtraBold",
color: "rgba(27,6,94,1)",
fontSize: 48,
alignItems: "center",
justifyContent: "center",
marginTop: 20
},
languageLabel: {
fontFamily: "OpenSans_600SemiBold",
color: "rgba(0,107,166,1)",
fontSize: 24
},
label: {
fontFamily: "OpenSans_600SemiBold",
fontSize: 12,
color: "#006BA6",
alignSelf: "center"
}
});
export default Bookmarks;
| 0fe9a5e89ec703f8c25889bb602a4a8af4be4458 | [
"JavaScript"
] | 25 | JavaScript | hoosan31320/KeyboardAware | 21b909c402f3a499b0f5f8d16899d6f6d8ca396f | 770d72fb5c50258d0e43d514bd8e7d83ebd3825e |
refs/heads/master | <repo_name>snbfan/mosaic-rest-js<file_sep>/src/node.js
/*global jxon, p1, p2, require, BBRest, BBReq, module, unescape*/
var request = p1;
var Q = p2;
var fs = require('fs');
var readFile = Q.denodeify(fs.readFile);
function getRequest(uri, o) {
var reqP = {
uri: uri,
qs: o.qs,
method: o.method,
headers: o.headers
};
if (o.config.username !== null) {
reqP.auth = {
username: o.config.username,
password: <PASSWORD>
};
}
if (o.targetFile) {
if (o.method === 'POST') {
reqP.formData = {};
reqP.formData[(uri.indexOf('import/package') === -1) ? 'file' : 'package'] = fs.createReadStream(o.targetFile);
}
}
return reqP;
}
function parseResponse(p, t) {
var o = {
statusCode: parseInt(p.statusCode),
statusInfo: p.request.httpModule.STATUS_CODES[p.statusCode],
href: p.request.href,
method: p.request.method,
headers: p.headers,
file: t.file || null
}, es;
if (typeof p.body !== 'undefined') o.body = p.body.toString();
if (o.statusCode >= 400) o.error = true;
else if (o.statusCode === 302) {
// if server redirects to error page, set message as error
es = o.headers.location.indexOf('errorMessage=');
if (es !== -1) o.error = unescape(o.headers.location.substr(es + 13));
} else if (t.config.plugin && o.body) {
o.body = t.config.plugin(o.body);
}
// on get method if server redirects to error page, set message as error
es = o.href.indexOf('errorMessage=');
if (es !== -1) o.error = unescape(o.href.substr(es + 13));
return o;
}
BBReq.prototype.req = function(data) {
var r,
t = this,
defer = Q.defer(),
uri = this.getUri(),
reqP = getRequest(uri, this);
reqP.body = data || '';
var onError = function(err) {
defer.reject({
error: true,
statusCode: null,
statusInfo: err.toString() || 'Request failed',
body: null,
reqBody: data,
uri: uri,
method: t.method,
file: t.targetFile || null
});
};
var req = request(reqP, function(err, p, dta) {
if (err) {
onError(err);
} else {
r = parseResponse(p, t);
if (!t.targetFile && r.body && t.config.toJs) r.body = stringToJs(r.body);
r.reqBody = data;
defer.resolve(r);
}
})
.on('error', onError);
if (this.targetFile) {
if (this.uri[0] === 'export' || this.uri[1] === 'export') {
req.pipe(fs.createWriteStream(this.targetFile));
}
}
return defer.promise;
};
function getRequestBody(inp, plugin) {
switch (typeof inp) {
case 'string':
return readFile(inp)
.then(function(d) {
return d.toString();
})
.fail(function() {
return {
error: true,
info: 'File path is wrong'
};
});
case 'object':
return Q(plugin(inp));
default:
return Q(inp);
}
}
function stringToJs(s) {
return jxon.stringToJs(s);
}
<file_sep>/gulpfile.js
var gulp = require('gulp'),
gfi = require('gulp-file-insert'),
replace = require('gulp-replace'),
rename = require('gulp-rename'),
uglify = require('gulp-uglify'),
jshint = require('gulp-jshint'),
mocha = require('gulp-spawn-mocha'),
phantom = require('gulp-mocha-phantomjs');
gulp.task('hint', function() {
return gulp.src('src/*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
gulp.task('node', function() {
return gulp.src('src/mosaic-rest-js.js')
.pipe(gfi({
"/* include */": "src/node.js",
}))
.pipe(gulp.dest('./dist/node/'));
});
gulp.task('jquery', function() {
return gulp.src('src/mosaic-rest-js.js')
.pipe(replace("'#lib#'", "'jquery'"))
.pipe(replace("'#lib_global#'", 'jQuery'))
.pipe(gfi({
"/* include */": "src/jquery.js",
}))
.pipe(gulp.dest('./dist/jquery/'));
});
gulp.task('angular', function() {
return gulp.src('src/mosaic-rest-js.js')
.pipe(replace("'#lib#'", "'angular'"))
.pipe(replace("'#lib_global#'", 'angular'))
.pipe(gfi({
"/* include */": "src/angular.js",
}))
.pipe(gulp.dest('./dist/angular/'));
});
gulp.task('min', ['jquery', 'angular'], function() {
return gulp.src(['./dist/jquery/mosaic-rest-js.js', './dist/angular/mosaic-rest-js.js'])
.pipe(uglify())
.pipe(rename(function(path) {
path.basename += '.min';
}))
.pipe(gulp.dest(function(vyn) {
return vyn.base;
}));
});
gulp.task('test-node', ['node'], function () {
return gulp.src('./test/spec.js', {read: false})
.pipe(mocha({
r: './test/config/node.js'
}));
});
gulp.task('test-jq', ['jquery'], function () {
return gulp
.src('test/runner_jquery.html')
.pipe(phantom({
phantomjs: {
settings: {
localToRemoteUrlAccessEnabled: true
}
}
}));
});
gulp.task('test-ng', ['angular'], function () {
return gulp
.src('test/runner_angular.html')
.pipe(phantom({
phantomjs: {
settings: {
localToRemoteUrlAccessEnabled: true
}
}
}));
});
<file_sep>/src/angular.js
/*global define, jQuery, jxon, p1, BBRest, BBReq, btoa*/
'use strict';
var ng = p1;
var ngHttp = ng.injector(['ng']).get('$http');
var ngQ = ng.injector(['ng']).get('$q');
// ng.injector(['ng']).invoke(function($http, $q) {
// ngHttp = $http;
// ngQ = $q;
// });
BBReq.prototype.req = function(data) {
//throw new Error(typeof ngHttp.get);
var t = this,
uri = this.getUri();
if (this.config.username !== null) {
this.headers.Authorization = 'Basic ' + btoa(this.config.username + ':' + this.config.password);
}
return ngHttp({
method: this.method,
url: uri,
data: data || '',
params: this.qs,
headers: this.headers
})
.then(function(d) {
var o = {
statusCode: d.status,
statusInfo: d.statusText,
body: d.data,
href: uri,
method: t.method,
reqBody: data
}, es;
if (o.statusCode >= 400) o.error = true;
else if (o.statusCode === 302) {
// if server redirects to error page, set message as error
es = o.headers.location.indexOf('errorMessage=');
if (es !== -1) o.error = unescape(o.headers.location.substr(es + 13));
} else if (t.config.plugin && o.body) {
o.body = t.config.plugin(o.body);
}
// on get method if server redirects to error page, set message as error
es = o.href.indexOf('errorMessage=');
if (es !== -1) o.error = unescape(o.href.substr(es + 13));
return o;
})
.catch(function(e) {
return {
error: true,
statusCode: e.status,
ststusInfo: e.statusText,
body: e.data,
href: uri,
method: t.method,
reqBody: data,
file: t.file || null
};
});
};
// input default is url with xml
function getRequestBody(inp, func) {
var d;
switch (typeof inp) {
case 'string':
return ngHttp.get(inp)
.then(function(d) {
return d.data;
})
.catch(function() {
return {
error: true,
info: 'Wrong URL'
};
});
case 'object':
d = ngQ.defer();
d.resolve(func(inp));
return d.promise;
default:
d = ngQ.defer();
d.resolve(inp);
return d.promise;
}
}
function stringToJs(s) {
return jxon.stringToJs(s);
}
<file_sep>/test/config/node.js
var BBRest = require('../../dist/node/mosaic-rest-js');
var chai = require('chai');
var _ = require('lodash');
var chaiAsPromised = require('chai-as-promised');
global.fs = require('fs');
xmlPath = './test/xml/';
chai.should();
chai.use(chaiAsPromised);
chai.config.includeStack = true;
global.BBRest = BBRest;
global._ = _;
global.expect = chai.expect;
global.AssertionError = chai.AssertionError;
global.Assertion = chai.Assertion;
global.assert = chai.assert;
global.should = chai.should;
<file_sep>/dist/node/mosaic-rest-js.js
/*global define, module, require, JXON, getRequestBody, stringToJs*/
(function (root, factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jxon', '#lib#'], factory);
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require('jxon'), require('request'), require('q'));
} else {
// Browser globals (root is window)
root.BBRest = factory(JXON, '#lib_global#');
}
}(this, function (jxon, p1, p2) {
'use strict';
// do not change to single quotes! gulp-file-include is not working with single quotes
jxon.config({
valueKey: "_",
attrKey: "$",
attrPrefix: "$",
lowerCaseTags: false,
trueIsEmpty: false,
autoDate: false,
ignorePrefixedNodes: false
});
function extend() {
var i, j, a = arguments;
for (i = 1; i < a.length; i++) {
for (j in a[i]) a[0][j] = a[i][j];
}
return a[0];
}
function BBRest(cnf) {
this.config = extend({
scheme: 'http',
host: 'localhost',
port: '7777',
context: 'portalserver',
username: 'admin',
password: '<PASSWORD>',
plugin: null,
portal: null
}, cnf || {});
}
extend(BBRest.prototype, {
server: function() {
return new BBReq('server', this.config, ['portals']);
},
portal: function() {
var a = ['portals', this.config.portal];
return new BBReq('portal', this.config, a);
},
catalog: function(item) {
var a = ['catalog'];
if (item) a.push(item);
return new BBReq('server', this.config, a);
},
portalCatalog: function(item) {
var a = ['portals', this.config.portal, 'catalog'];
if (item) a.push(item);
return new BBReq('portal', this.config, a);
},
container: function(containerName) {
var a = ['portals', this.config.portal, 'containers'];
if (containerName) a.push(containerName);
return new BBReq('container', this.config, a);
},
widget: function(widgetName) {
var a = ['portals', this.config.portal, 'widgets'];
if (widgetName) a.push(widgetName);
return new BBReq('widget', this.config, a);
},
page: function(pageName) {
var a = ['portals', this.config.portal, 'pages'];
if (pageName) a.push(pageName);
return new BBReq('page', this.config, a);
},
link: function(linkName) {
var a = ['portals', this.config.portal, 'links'];
if (linkName) a.push(linkName);
return new BBReq('link', this.config, a);
},
user: function(userName, showGroups, groupName) {
var a = ['users'];
if (userName) a.push(userName);
if (showGroups) a.push('groups');
if (groupName) a.push(groupName);
return new BBReq('user', this.config, a);
},
group: function(groupName, showUsers, userName) {
var a = ['groups'];
if (groupName) a.push(groupName);
if (showUsers) a.push('users');
if (userName) a.push(userName);
return new BBReq('group', this.config, a);
},
template: function(templateName) {
var a = ['templates'];
if (templateName) a.push(templateName);
return new BBReq('template', this.config, a);
},
audit: function(meta) {
return new BBReq('audit', this.config, [meta ? 'auditmeta' : 'auditevents']);
},
cache: function(type) {
var a = ['caches', type];
return new BBReq('cache', this.config, a);
},
import: function() {
var a = ['import', 'portal'];
return new BBReq('import', this.config, a);
},
importItem: function(toPortal) {
var a = ['import', 'package'];
if (toPortal) a.push(this.config.portal);
return new BBReq('importItem', this.config, a);
},
export: function(uuid) {
var a;
if (uuid) {
a = ['orchestrator', 'export', 'files', uuid];
return new BBReq('export', this.config, a);
} else {
a = ['export', 'portal'];
return new BBReq('export', this.config, a)
.query({portalName: this.config.portal, includeGroups: true});
}
},
exportItem: function(itemName, fromPortal) {
var a = ['export', 'package'];
if (fromPortal) a.push(this.config.portal);
a.push(itemName);
return new BBReq('exportItem', this.config, a);
},
auto: function(d, method) {
var t = this;
return getRequestBody(d, this.config.plugin).then(function(r) {
if (typeof r === 'string') r = stringToJs(r);
var a = t.jxonToObj(r, method);
return t[a[0]]()[a[1]](d);
});
},
jxonToObj: function(j, method) {
var aKey, bKey, plural, context, a = [],
items = ['container', 'widget', 'page', 'link', 'template', 'user', 'group'];
for (aKey in j) {
for (bKey in j[aKey]) break;
context = j[aKey][bKey].contextItemName;
switch (aKey) {
case 'catalog':
if (context === '[BBHOST]') a.push('catalog', 'post');
else a.push('portalCatalog', 'post');
break;
case 'portals':
a.push('server', 'post');
break;
case 'portal':
a.push('server', 'put');
break;
default:
plural = aKey.charAt(aKey.length - 1) === 's';
if (plural) {
if (aKey.substr(0, aKey.length - 1) === bKey) {
a.push(bKey, 'post');
} else {
throw new Error(aKey + ' must be plural of ' + bKey);
}
} else {
if (items.indexOf(aKey) !== -1) a.push(aKey, 'put');
else a.push(aKey, 'post');
}
break;
}
break;
}
if (method) a[1] = method;
return a;
}
});
function BBReq(cmnd, cnf, uri) {
this.command = cmnd;
this.config = extend({}, cnf);
this.uri = uri;
this.qs = {};
this.headers = {
'Content-Type': 'application/xml'
};
}
extend(BBReq.prototype, {
rights: function() {
this.uri.push('rights');
return this;
},
tag: function(tagName, tagType) {
this.uri.push('tags');
if (tagName) this.uri.push(tagName);
if (tagType) this.qs.type = tagType;
return this;
},
query: function(o) {
this.qs = o;
return this;
},
file: function(file) {
if (this.uri[0] === 'import') {
this.headers['Content-Type'] = 'multipart/form-data';
this.headers['Connection'] = 'keep-alive';
if (this.uri[1] !== 'package') {
this.uri = ['orchestrator', 'import', 'upload'];
}
}
this.targetFile = file;
return this;
},
get: function() {
/* methods that use .xml:
* portal().xml().get()
* portalCatalog('item').get()
* container('name').xml().get()
* widget('name').xml().get()
* page('name').xml().get()
* link('name').xml().get() */
if (this.uri[0] === 'portals' && this.uri.length === 2) this.uri[1] += '.xml';
if (this.uri[2] === 'catalog' && this.uri[3]) this.uri[3] += '.xml';
if (this.uri[2] === 'pages' && this.uri[3]) this.uri[3] += '.xml';
if (this.uri[2] === 'containers' && this.uri[3]) this.uri[3] += '.xml';
if (this.uri[2] === 'widgets' && this.uri[3]) this.uri[3] += '.xml';
if (this.uri[2] === 'links' && this.uri[3]) this.uri[3] += '.xml';
this.method = 'GET';
return this.req();
},
post: function(d) {
this.method = 'POST';
if (this.uri[0] === 'export' && this.uri[1] !== 'package') {
this.uri = ['orchestrator', 'export', 'exportrequests'];
}
return this.doRequest(d);
},
put: function(d) {
this.method = 'PUT';
return this.doRequest(d);
},
// fixing inconsistencies in API
// server /delete/catalog POST
// portal /portals/[portal_name]/delete/catalog POST
// link /portals/[portal_name]/delete/links POST
delete: function(v) {
this.method = 'DELETE';
if (v) {
this.method = 'POST';
switch (this.command) {
case 'server':
this.uri = ['delete', 'catalog'];
break;
case 'portal':
this.uri[2] = 'delete';
this.uri[3] = 'catalog';
break;
case 'link':
this.uri[2] = 'delete';
this.uri[3] = 'links';
break;
default:
// code
}
}
if (this.command === 'cache' && this.uri[1] === 'all') {
return this.deleteAllCache(0);
}
return this.doRequest(v);
},
doRequest: function(d) {
var t = this;
return getRequestBody(d, this.config.plugin).then(function(r) {
return t.req(r);
});
},
deleteAllCache: function(i) {
var t = this;
this.uri[1] = cch[i];
return this.req().then(function(v) {
if (i < cch.length - 1) return t.deleteAllCache(++i);
return v;
});
},
getUri: function(excludePath) {
var cfg = this.config;
if (this.uri[0] === 'orchestrator' && cfg.orchestrator) cfg = this.config.orchestrator;
var out = cfg.scheme + '://' +
cfg.host + ':' +
cfg.port + '/' +
cfg.context + '/';
if (excludePath) return out;
return out + this.uri.join('/');
}
});
var cch = ['globalModelCache',
'retrievedWidgetCache',
'widgetChromeStaticCache',
'serverSideClosureCache',
'urlLevelCache',
'contentTemplateCache',
'webCache',
'gModelCache',
'uuidFromExtendedItemNamesCache',
'springAclCacheRegion',
'springAclSidCacheRegion',
'contextNameToItemNameToUuidCache',
'widgetCache',
'uuidToContentReferencesCache',
'itemUuidToReferencingLinkUuidsCache',
'uuidToCacheKeysCache',
'versionBundleCache'];
/*global jxon, p1, p2, require, BBRest, BBReq, module, unescape*/
var request = p1;
var Q = p2;
var fs = require('fs');
var readFile = Q.denodeify(fs.readFile);
function getRequest(uri, o) {
var reqP = {
uri: uri,
qs: o.qs,
method: o.method,
headers: o.headers
};
if (o.config.username !== null) {
reqP.auth = {
username: o.config.username,
password: <PASSWORD>
};
}
if (o.targetFile) {
if (o.method === 'POST') {
reqP.formData = {};
reqP.formData[(uri.indexOf('import/package') === -1) ? 'file' : 'package'] = fs.createReadStream(o.targetFile);
}
}
return reqP;
}
function parseResponse(p, t) {
var o = {
statusCode: parseInt(p.statusCode),
statusInfo: p.request.httpModule.STATUS_CODES[p.statusCode],
href: p.request.href,
method: p.request.method,
headers: p.headers,
file: t.file || null
}, es;
if (typeof p.body !== 'undefined') o.body = p.body.toString();
if (o.statusCode >= 400) o.error = true;
else if (o.statusCode === 302) {
// if server redirects to error page, set message as error
es = o.headers.location.indexOf('errorMessage=');
if (es !== -1) o.error = unescape(o.headers.location.substr(es + 13));
} else if (t.config.plugin && o.body) {
o.body = t.config.plugin(o.body);
}
// on get method if server redirects to error page, set message as error
es = o.href.indexOf('errorMessage=');
if (es !== -1) o.error = unescape(o.href.substr(es + 13));
return o;
}
BBReq.prototype.req = function(data) {
var r,
t = this,
defer = Q.defer(),
uri = this.getUri(),
reqP = getRequest(uri, this);
reqP.body = data || '';
var onError = function(err) {
defer.reject({
error: true,
statusCode: null,
statusInfo: err.toString() || 'Request failed',
body: null,
reqBody: data,
uri: uri,
method: t.method,
file: t.targetFile || null
});
};
var req = request(reqP, function(err, p, dta) {
if (err) {
onError(err);
} else {
r = parseResponse(p, t);
if (!t.targetFile && r.body && t.config.toJs) r.body = stringToJs(r.body);
r.reqBody = data;
defer.resolve(r);
}
})
.on('error', onError);
if (this.targetFile) {
if (this.uri[0] === 'export' || this.uri[1] === 'export') {
req.pipe(fs.createWriteStream(this.targetFile));
}
}
return defer.promise;
};
function getRequestBody(inp, plugin) {
switch (typeof inp) {
case 'string':
return readFile(inp)
.then(function(d) {
return d.toString();
})
.fail(function() {
return {
error: true,
info: 'File path is wrong'
};
});
case 'object':
return Q(plugin(inp));
default:
return Q(inp);
}
}
function stringToJs(s) {
return jxon.stringToJs(s);
}
return BBRest;
}));
| 750cb461757399d5e03611357b699b0817d7d53a | [
"JavaScript"
] | 5 | JavaScript | snbfan/mosaic-rest-js | f58efa7c410b3d22351711d10e2cf6ef6dc5d336 | e9bfa0ab39f874054bbd1c244842e65adaae801d |
refs/heads/master | <file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>eagle-parent</artifactId>
<groupId>org.apache.eagle</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>eagle-flink</artifactId>
<properties>
<flink.version>1.10.0</flink.version>
<scala.binary.version>2.11</scala.binary.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-streaming-java_${scala.binary.version}</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.siddhi</groupId>
<artifactId>siddhi-core</artifactId>
</dependency>
</dependencies>
</project><file_sep>package org.apache.eagle.flink;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
public class SiddhiCEPOp extends KeyedProcessFunction<Long, StreamEvent, AlertPublishEvent> {
@Override
public void processElement(StreamEvent value, Context ctx, Collector<AlertPublishEvent> out) throws Exception {
if(value.data[0].equals(100)) {
AlertPublishEvent event = new AlertPublishEvent();
out.collect(event);
}
}
}
<file_sep>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.eagle.flink;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* An iterator of StreamEvent events.
*/
final class StreamEventIterator implements Iterator<StreamEvent>, Serializable {
private static final long serialVersionUID = 1L;
private static final Timestamp INITIAL_TIMESTAMP = Timestamp.valueOf("2019-01-01 00:00:00");
private static final long SIX_MINUTES = 6 * 60 * 1000;
private final boolean bounded;
private int index = 0;
private long timestamp;
static StreamEventIterator bounded() {
return new StreamEventIterator(true);
}
static StreamEventIterator unbounded() {
return new StreamEventIterator(false);
}
private StreamEventIterator(boolean bounded) {
this.bounded = bounded;
this.timestamp = INITIAL_TIMESTAMP.getTime();
}
@Override
public boolean hasNext() {
if (index < data.size()) {
return true;
} else if (!bounded) {
index = 0;
return true;
} else {
return false;
}
}
@Override
public StreamEvent next() {
StreamEvent StreamEvent = data.get(index++);
StreamEvent.setTimestamp(timestamp);
timestamp += SIX_MINUTES;
return StreamEvent;
}
private static List<StreamEvent> data = Arrays.asList(
new StreamEvent("testStream_1", 0L, new Object[]{188.23}),
new StreamEvent("testStream_1", 10L, new Object[]{100}),
new StreamEvent("testStream_1", 10L, new Object[]{188.23}),
new StreamEvent("testStream_1", 20L, new Object[]{188.23}),
new StreamEvent("testStream_1", 20L, new Object[]{188.23}),
new StreamEvent("testStream_1", 20L, new Object[]{188.23}),
new StreamEvent("testStream_1", 30L, new Object[]{188.23}),
new StreamEvent("testStream_1", 40L, new Object[]{188.23}),
new StreamEvent("testStream_1", 50L, new Object[]{188.23}),
new StreamEvent("testStream_1", 70L, new Object[]{188.23}),
new StreamEvent("testStream_1", 90L, new Object[]{100}),
new StreamEvent("testStream_1", 100L, new Object[]{188.23}),
new StreamEvent("testStream_1", 200L, new Object[]{188.23}),
new StreamEvent("testStream_1", 210L, new Object[]{188.23}),
new StreamEvent("testStream_1", 220L, new Object[]{188.23}),
new StreamEvent("testStream_1", 230L, new Object[]{188.23}),
new StreamEvent("testStream_1", 250L, new Object[]{188.23}),
new StreamEvent("testStream_1", 260L, new Object[]{188.23}),
new StreamEvent("testStream_1", 270L, new Object[]{188.23}),
new StreamEvent("testStream_1", 300L, new Object[]{188.23}),
new StreamEvent("testStream_1", 400L, new Object[]{188.23}),
new StreamEvent("testStream_1", 600L, new Object[]{188.23}),
new StreamEvent("testStream_1", 1000L, new Object[]{188.23}),
new StreamEvent("testStream_1", 12000L, new Object[]{188.23}),
new StreamEvent("testStream_1", 12001L, new Object[]{188.23}),
new StreamEvent("testStream_1", 12002L, new Object[]{188.23})
);
}
| 4cb0d4dea84cd698e197d494ec6410b332a97612 | [
"Java",
"Maven POM"
] | 3 | Maven POM | yonzhang/eagle | dacfe7bc9125c5ed89fe121595cecad0a0bddbcc | d9b4a0f81a00286190816c0d4bc6f819c1dea812 |
refs/heads/main | <file_sep>DROP DATABASE IF EXISTS quotes_generator;
CREATE DATABASE quotes_generator;
USE quotes_generator;
CREATE TABLE quotes (id INT AUTO_INCREMENT PRIMARY KEY, text VARCHAR(100) NOT NULL); | ed068aafa9d9791f9c87d3635a3cb311db0da152 | [
"SQL"
] | 1 | SQL | R41N9/HR-TC-Node-mini-sprint | 9ada3dac7642fe852824fabf3076f87830015216 | 9d30041555e8b6131f89d867b8496cc4bfb4e253 |
refs/heads/master | <file_sep>package com.example.mtandao.views;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.mtandao.R;
import com.example.mtandao.controllers.AccountsAPI;
import com.example.mtandao.services.AccountsListener;
import com.example.mtandao.utils.Loader;
public class RegistrationActivity extends AppCompatActivity implements View.OnClickListener,
AccountsListener.RegistrationListener {
private EditText emailEdit, passwordEdit;
private Button registerBtn, existingAccountBtn;
private AccountsAPI accountsAPI;
private Loader loader;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
accountsAPI = new AccountsAPI(this);
accountsAPI.setRegistrationListener(this);
loader = new Loader(this);
emailEdit = findViewById(R.id.emailEdit);
passwordEdit = findViewById(R.id.passwordEdit);
registerBtn = findViewById(R.id.registerBtn);
existingAccountBtn = findViewById(R.id.existingAccountBtn);
registerBtn.setOnClickListener(this);
existingAccountBtn.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (view.equals(existingAccountBtn)){
gotoLoginActivity();
}
if (view.equals(registerBtn)){
if (validated()){
String email = emailEdit.getText().toString();
String password = passwordEdit.getText().toString();
accountsAPI.registerUser(email, password);
loader.showDialogue();
}
}
}
private boolean validated() {
if (TextUtils.isEmpty(emailEdit.getText().toString())){
Toast.makeText(this, "Email is required", Toast.LENGTH_SHORT).show();
return false;
}
else if (!Patterns.EMAIL_ADDRESS.matcher(emailEdit.getText().toString()).matches()){
Toast.makeText(this, "Invalid email pattern", Toast.LENGTH_SHORT).show();
return false;
}
else if (TextUtils.isEmpty(passwordEdit.getText().toString())){
Toast.makeText(this, "Password is required", Toast.LENGTH_SHORT).show();
return false;
}else return true;
}
private void gotoLoginActivity() {
startActivity(new Intent(new Intent(RegistrationActivity.this, LoginActivity.class)));
finish();
}
@Override
public void onAccountCreated() {
loader.hideDialogue();
Toast.makeText(this, "Account created successfully", Toast.LENGTH_SHORT).show();
startActivity(new Intent(new Intent(RegistrationActivity.this, MainActivity.class)));
finish();
}
@Override
public void onFailureResponse(Exception e) {
loader.hideDialogue();
Toast.makeText(this, "Account could not be created... "+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}<file_sep>include ':app'
rootProject.name = "Mtandao"<file_sep>package com.example.mtandao.views;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.core.view.MenuItemCompat;
import com.example.mtandao.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener{
private FirebaseAuth auth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
auth = FirebaseAuth.getInstance();
checkUserStatus();
}
private void checkUserStatus() {
//get current user
FirebaseUser user = auth.getCurrentUser();
if (user != null){
//user is logged in , stay here
}else {
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.action_addPost:
goToAddPostActivity();
break;
case R.id.action_logout:
logout();
break;
}
return super.onOptionsItemSelected(item);
}
private void logout() {
auth.signOut();
checkUserStatus();
}
private void goToAddPostActivity() {
startActivity(new Intent(MainActivity.this, AddPostActivity.class));
}
@Override
protected void onResume() {
checkUserStatus();
super.onResume();
}
@Override
public boolean onQueryTextSubmit(String s) {
return false;
}
@Override
public boolean onQueryTextChange(String s) {
return false;
}
}<file_sep>package com.example.mtandao.views;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.mtandao.R;
import com.example.mtandao.controllers.PostAPI;
import com.example.mtandao.services.PostsListener;
import com.example.mtandao.utils.Loader;
import com.example.mtandao.utils.Permission;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;
public class AddPostActivity extends AppCompatActivity implements View.OnClickListener , PostsListener.UploadPostListener {
//views
private EditText editTitle, editDescription;
private ImageView imageView;
private Button btnPost;
private Permission permission;
private String[] storagePermissions;
private static final int STORAGE_REQUEST_CODE = 200;
private static final int PICK_IMAGE_REQUEST_CODE = 300;
private Uri image_url = null;
private PostAPI postAPI;
private Loader loader;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_post);
//init
editTitle = findViewById(R.id.editTitle);
editDescription = findViewById(R.id.editDescription);
imageView = findViewById(R.id.imageView);
btnPost = findViewById(R.id.btnPost);
imageView.setOnClickListener(this);
btnPost.setOnClickListener(this);
permission = new Permission(this);
storagePermissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
postAPI = new PostAPI(this);
postAPI.setUploadPostListener(this);
loader = new Loader(this);
}
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onClick(View view) {
if (view.equals(imageView)){
if (!permission.checkStoragePermissions()){
requestStoragePermission();
}
else {
pickImageFromGallery();
}
}
if (view.equals(btnPost)){
if (validated()){
//start uploading
//get image from the imageView
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//compress image
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
//get byte[] from the outputStream
byte[] data = baos.toByteArray();
Map<Object, String> post = new HashMap<>();
post.put("title", editTitle.getText().toString());
post.put("description", editDescription.getText().toString());
//post data to our database
postAPI.uploadPost(post, data);
loader.showDialogue();
}
}
}
private void pickImageFromGallery() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST_CODE);
}
@RequiresApi(api = Build.VERSION_CODES.M)
private void requestStoragePermission() {
//request runtime permissions
requestPermissions(storagePermissions, STORAGE_REQUEST_CODE);
}
private boolean validated() {
if (TextUtils.isEmpty(editTitle.getText().toString())){
Toast.makeText(this, "Post tile is required", Toast.LENGTH_SHORT).show();
return false;
}
else if (imageView.getDrawable().getConstantState() == getResources().getDrawable(R.drawable.add_image).getConstantState()){
Toast.makeText(this, "Please select an image for the post", Toast.LENGTH_SHORT).show();
return false;
}
else if(TextUtils.isEmpty(editDescription.getText().toString())){
Toast.makeText(this, "Post description is required", Toast.LENGTH_SHORT).show();
return false;
}
else return true;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == STORAGE_REQUEST_CODE){
if (grantResults.length > 0){
boolean writeStorageAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (writeStorageAccepted){
//permissions has been accepted
pickImageFromGallery();
}
else {
//permission has been denied
Toast.makeText(this, "Please enable storage permissions", Toast.LENGTH_SHORT).show();
}
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (resultCode == RESULT_OK){
if (requestCode == PICK_IMAGE_REQUEST_CODE){
//image is picked from gallery so we get the image url
image_url = data.getData();
imageView.setImageURI(image_url);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onPostUploaded() {
loader.hideDialogue();
Toast.makeText(this, "Post uploaded successfully", Toast.LENGTH_SHORT).show();
startActivity(new Intent(AddPostActivity.this, MainActivity.class));
finish();
}
@Override
public void onFailureResponse(Exception e) {
loader.hideDialogue();
Toast.makeText(this, "Failed, "+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}<file_sep>package com.example.mtandao.utils;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import androidx.core.content.ContextCompat;
public class Permission {
private Context context;
public Permission(Context context) {
this.context = context;
}
public boolean checkStoragePermissions(){
//check if storage permission is granted
//return true if permission is enabled
//if not enabled return false
boolean result = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result;
}
}
<file_sep>package com.example.mtandao.services;
public interface AccountsListener {
interface RegistrationListener{
void onAccountCreated();
void onFailureResponse(Exception e);
}
interface LoginListener{
void onSuccessLogin();
void onLoginFailure();
void onFailureResponse(Exception e);
}
}
| 9926cf47289e781f1a76dae601dce553b8bbbd33 | [
"Java",
"Gradle"
] | 6 | Java | ekbaya/mtandao | 8c852d5a2c3b89653d9d404060fc4c1db66e9ae8 | 8719ee8eaaaf2fd51cd11bea71eb3484c8421b12 |
refs/heads/master | <repo_name>CariadDisplayLibrary/T6963<file_sep>/src/T6963.cpp
#include <T6963.h>
void T6963::initializeDevice() {
pinMode(_wr, OUTPUT);
pinMode(_rd, OUTPUT);
pinMode(_cd, OUTPUT);
pinMode(_ce, OUTPUT);
pinMode(_d0, OUTPUT);
pinMode(_d1, OUTPUT);
pinMode(_d2, OUTPUT);
pinMode(_d3, OUTPUT);
pinMode(_d4, OUTPUT);
pinMode(_d5, OUTPUT);
pinMode(_d6, OUTPUT);
pinMode(_d7, OUTPUT);
digitalWrite(_wr, HIGH);
digitalWrite(_rd, HIGH);
digitalWrite(_cd, HIGH);
digitalWrite(_ce, LOW);
if (_res != 255) {
pinMode(_res, OUTPUT);
digitalWrite(_res, HIGH);
delay(40);
digitalWrite(_res, LOW);
delay(40);
digitalWrite(_res, HIGH);
delay(40);
}
data(0);
data(0);
command(T6963_SET_GRAPHIC_HOME_ADDRESS);
data(256 / 8);
data(0);
command(T6963_SET_GRAPHIC_AREA);
data(0);
data(8);
command(T6963_SET_TEXT_HOME_ADDRESS);
data(256 / 8);
data(0);
command(T6963_SET_TEXT_AREA);
//data(((32 / 2) - 1));
data(0b11110);
data(0x0);
command(T6963_SET_OFFSET_REGISTER);
command(T6963_DISPLAY_MODE | 0b1000);
command(T6963_MODE_SET);
}
void T6963::setPixel(int x, int y, color_t color) {
uint8_t row;
uint8_t col;
uint8_t pixel;
uint8_t mask;
if((x < 0) ||(x >= 256) || (y < 0) || (y >= 64))
return;
row = y;
col = x >> 3;
pixel = x & 0x07;
mask = 1<<(7 - pixel);
if (color) {
_buffer[col | (row * 32)] |= mask;
} else {
_buffer[col | (row * 32)] &= ~mask;
}
if (_buffered == 0) {
data(0);
data(0);
command(T6963_SET_ADDRESS_POINTER);
command(T6963_SET_DATA_AUTO_WRITE);
for (int i = 0; i < 2048; i++) {
data(_buffer[i]);
}
command(T6963_AUTO_RESET);
}
}
void T6963::data(uint8_t d) {
digitalWrite(_cd, LOW);
digitalWrite(_d0, d & 0x01);
digitalWrite(_d1, d & 0x02);
digitalWrite(_d2, d & 0x04);
digitalWrite(_d3, d & 0x08);
digitalWrite(_d4, d & 0x10);
digitalWrite(_d5, d & 0x20);
digitalWrite(_d6, d & 0x40);
digitalWrite(_d7, d & 0x80);
delayMicroseconds(1);
digitalWrite(_wr, LOW);
delayMicroseconds(1);
digitalWrite(_wr, HIGH);
}
void T6963::command(uint8_t d) {
digitalWrite(_cd, HIGH);
digitalWrite(_d0, d & 0x01);
digitalWrite(_d1, d & 0x02);
digitalWrite(_d2, d & 0x04);
digitalWrite(_d3, d & 0x08);
digitalWrite(_d4, d & 0x10);
digitalWrite(_d5, d & 0x20);
digitalWrite(_d6, d & 0x40);
digitalWrite(_d7, d & 0x80);
delayMicroseconds(1);
digitalWrite(_wr, LOW);
delayMicroseconds(1);
digitalWrite(_wr, HIGH);
}
void T6963::endBuffer() {
_buffered--;
if (_buffered <= 0) {
_buffered = 0;
data(0);
data(0);
command(T6963_SET_ADDRESS_POINTER);
command(T6963_SET_DATA_AUTO_WRITE);
for (int i = 0; i < 2048; i++) {
data(_buffer[i]);
}
command(T6963_AUTO_RESET);
}
}
void T6963::startBuffer() {
_buffered++;
}
void T6963::fillScreen(color_t c) {
memset(_buffer, c ? 255 : 0, 2048);
if (_buffered == 0) {
data(0);
data(0);
command(T6963_SET_ADDRESS_POINTER);
command(T6963_SET_DATA_AUTO_WRITE);
for (int i = 0; i < 2048; i++) {
data(_buffer[i]);
}
command(T6963_AUTO_RESET);
}
}
<file_sep>/src/T6963.h
#ifndef _T6963_H
#define _T6963_H
#include <Cariad.h>
class T6963 : public Cariad {
private:
public:
uint8_t _buffer[2048];
uint8_t _rd;
uint8_t _wr;
uint8_t _cd;
uint8_t _ce;
uint8_t _d0;
uint8_t _d1;
uint8_t _d2;
uint8_t _d3;
uint8_t _d4;
uint8_t _d5;
uint8_t _d6;
uint8_t _d7;
uint8_t _res;
int _buffered;
static const uint8_t T6963_CURSOR_PATTERN_SELECT = 0xA0;
static const uint8_t T6963_DISPLAY_MODE = 0x90;
static const uint8_t T6963_MODE_SET = 0x80;
static const uint8_t T6963_SET_CURSOR_POINTER = 0x21;
static const uint8_t T6963_SET_OFFSET_REGISTER = 0x22;
static const uint8_t T6963_SET_ADDRESS_POINTER = 0x24;
static const uint8_t T6963_SET_TEXT_HOME_ADDRESS = 0x40;
static const uint8_t T6963_SET_TEXT_AREA = 0x41;
static const uint8_t T6963_SET_GRAPHIC_HOME_ADDRESS = 0x42;
static const uint8_t T6963_SET_GRAPHIC_AREA = 0x43;
static const uint8_t T6963_SET_DATA_AUTO_WRITE = 0xB0;
static const uint8_t T6963_SET_DATA_AUTO_READ = 0xB1;
static const uint8_t T6963_AUTO_RESET = 0xB2;
static const uint8_t T6963_DATA_WRITE_AND_INCREMENT = 0xC0;
static const uint8_t T6963_DATA_READ_AND_INCREMENT = 0xC1;
static const uint8_t T6963_DATA_WRITE_AND_DECREMENT = 0xC2;
static const uint8_t T6963_DATA_READ_AND_DECREMENT = 0xC3;
static const uint8_t T6963_DATA_WRITE_AND_NONVARIALBE = 0xC4;
static const uint8_t T6963_DATA_READ_AND_NONVARIABLE = 0xC5;
static const uint8_t T6963_SCREEN_PEEK = 0xE0;
static const uint8_t T6963_SCREEN_COPY = 0xE8;
void data(uint8_t d);
void command(uint8_t c);
public:
T6963(
uint8_t rd, uint8_t wr, uint8_t cd, uint8_t ce,
uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7,
uint8_t res = 255
) : _rd(rd), _wr(wr), _cd(cd), _ce(ce),
_d0(d0), _d1(d1), _d2(d2), _d3(d3),
_d4(d4), _d5(d5), _d6(d6), _d7(d7),
_res(res), _buffered(0) {
_width = 256;
_height = 64;
}
void initializeDevice();
void invertDisplay(bool __attribute__((unused)) i) {}
void displayOn() {}
void displayOff() {}
void setRotation(int __attribute__((unused)) rotation) {}
void setPixel(int x, int y, color_t color);
void startBuffer();
void endBuffer();
void fillScreen(color_t c);
};
#endif
<file_sep>/library.properties
name=T6963
version=2.1.7
author=<NAME>
maintainer=Majenko Technologies
sentence=T6963 for Cariad
paragraph=...
url=https://github.com/Cariad/T6963.git
category=Display
architectures=chipkit
includes=T6963.h
<file_sep>/examples/Stopwatch/Stopwatch.ino
#include <T6963.h>
#include <Display7Seg.h>
#include <Topaz.h>
// Adjust these to match your setup
#define PIN_RD 35
#define PIN_WR 34
#define PIN_CD 37
#define PIN_CE 36
#define PIN_D0 26
#define PIN_D1 27
#define PIN_D2 28
#define PIN_D3 29
#define PIN_D4 30
#define PIN_D5 31
#define PIN_D6 32
#define PIN_D7 33
#define PIN_RES 38
T6963 lcd(PIN_RD, PIN_WR, PIN_CD, PIN_CE, PIN_D0, PIN_D1, PIN_D2, PIN_D3, PIN_D4, PIN_D5, PIN_D6, PIN_D7, PIN_RES);
// Define your control button pin here
#define BUTTON PIN_BTN1
void setup() {
lcd.initializeDevice();
lcd.setTextColor(Color::White, Color::White);
pinMode(BUTTON, INPUT);
}
void loop() {
static uint32_t start = 0;
static bool running = false;
static bool buttonState = digitalRead(BUTTON);
static uint32_t secs = 0;
static uint32_t mins = 0;
static uint32_t hours = 0;
static uint32_t tens = 0;
if (digitalRead(BUTTON) != buttonState) {
buttonState = digitalRead(BUTTON);
if (buttonState == HIGH) {
running = !running;
if (running) {
start = millis();
}
}
}
if (running) {
uint32_t tsecs = (millis() - start) / 1000;
secs = tsecs % 60;
mins = (tsecs / 60) % 60;
hours = (tsecs / 3600) % 24;
tens = ((millis() - start) / 100) % 10;
}
lcd.startBuffer();
lcd.fillScreen(Color::Black);
lcd.setFont(Fonts::Display7Seg48);
lcd.setCursor(10, 10);
lcd.printf("%02d %02d %02d %d",
hours, mins, secs, tens);
lcd.setFont(Fonts::Topaz);
lcd.setCursor(58, 45);
lcd.print("h");
lcd.setCursor(58+72, 45);
lcd.print("m");
lcd.setCursor(58+72+72, 45);
lcd.print("s");
lcd.fillCircle(69, 20, 4, Color::White);
lcd.fillCircle(69, 41, 4, Color::White);
lcd.fillCircle(69+72, 20, 4, Color::White);
lcd.fillCircle(69+72, 41, 4, Color::White);
lcd.fillCircle(69+72+72, 20, 4, Color::White);
lcd.fillCircle(69+72+72, 41, 4, Color::White);
lcd.endBuffer();
delay(10);
}
| 3f5e5200b03482c10c22ab8523310faeee01632a | [
"C++",
"INI"
] | 4 | C++ | CariadDisplayLibrary/T6963 | 91a633e049dd90f164b90fb2bd94338bce311a93 | 56814852610377e6139ef6396a28a677c5e03d07 |
refs/heads/master | <repo_name>4deone/MesExtensions<file_sep>/app/src/main/java/cm/deone/mesextensions/AgentListActivity.java
package cm.deone.mesextensions;
import androidx.appcompat.app.AppCompatActivity;
import android.app.DownloadManager;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.Query;
import java.util.List;
import cm.deone.mesextensions.models.Agent;
import cm.deone.mesextensions.models.FirebaseDatabaseHelper;
import cm.deone.mesextensions.models.RecyclerView_Config;
public class AgentListActivity extends AppCompatActivity {
private RecyclerView mRecylerView;
private FirebaseAuth mAuth;
EditText edtSearch;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_agent_list);
mAuth = FirebaseAuth.getInstance();
mRecylerView = (RecyclerView)findViewById(R.id.recycler_agents);
edtSearch = (EditText)findViewById(R.id.edtSearch);
new FirebaseDatabaseHelper().readAgents(new FirebaseDatabaseHelper.DataStatus() {
@Override
public void DataIsLoader(List<Agent> agents, List<String> keys) {
findViewById(R.id.loading_agent_pb).setVisibility(View.GONE);
new RecyclerView_Config().setConfig(mRecylerView, AgentListActivity.this, agents, keys);
}
@Override
public void DataIsInsered() {
}
@Override
public void DataIsUpdated() {
}
@Override
public void DataIsDeleted() {
}
@Override
public void DataIsSearched(List<Agent> agents, List<String> keys, String search) {
}
});
edtSearch.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if(!s.toString().isEmpty()){
new FirebaseDatabaseHelper().searchAgent(s.toString(), new FirebaseDatabaseHelper.DataStatus() {
@Override
public void DataIsLoader(List<Agent> agents, List<String> keys) {
}
@Override
public void DataIsInsered() {
}
@Override
public void DataIsUpdated() {
}
@Override
public void DataIsDeleted() {
}
@Override
public void DataIsSearched(List<Agent> agents, List<String> keys, String search) {
new RecyclerView_Config().setConfig(mRecylerView, AgentListActivity.this, agents, keys);
}
});
}else {
new FirebaseDatabaseHelper().searchAgent("", new FirebaseDatabaseHelper.DataStatus() {
@Override
public void DataIsLoader(List<Agent> agents, List<String> keys) {
}
@Override
public void DataIsInsered() {
}
@Override
public void DataIsUpdated() {
}
@Override
public void DataIsDeleted() {
}
@Override
public void DataIsSearched(List<Agent> agents, List<String> keys, String search) {
new RecyclerView_Config().setConfig(mRecylerView, AgentListActivity.this, agents, keys);
}
});
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
FirebaseUser user = mAuth.getCurrentUser();
getMenuInflater().inflate(R.menu.agentlist_activity_menu, menu);
if (user!=null){
menu.getItem(0).setVisible(true); //New Agent
menu.getItem(1).setVisible(false); // Connexion / register
menu.getItem(2).setVisible(true); // password
menu.getItem(3).setVisible(true); // logout
}else {
menu.getItem(0).setVisible(false); //New Agent
menu.getItem(1).setVisible(true); // Connexion / register
menu.getItem(2).setVisible(false); // password
menu.getItem(3).setVisible(false); // logout
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
FirebaseUser user = mAuth.getCurrentUser();
if (user!=null){
menu.getItem(0).setVisible(true); //New Agent
menu.getItem(1).setVisible(false); // Connexion / register
menu.getItem(2).setVisible(true); // password
menu.getItem(3).setVisible(true); // logout
}else {
menu.getItem(0).setVisible(false); //New Agent
menu.getItem(1).setVisible(true); // Connexion / register
menu.getItem(2).setVisible(false); // password
menu.getItem(3).setVisible(false); // logout
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.new_agent:
startActivity(new Intent(this, NewAgentActivity.class));
return true;
case R.id.sign_in:
startActivity(new Intent(this, SignInActivity.class));
return true;
case R.id.password:
startActivity(new Intent(this, VipSecretActivity.class));
return true;
case R.id.sign_out:
mAuth.signOut();
invalidateOptionsMenu();
RecyclerView_Config.logout();
return true;
}
return super.onOptionsItemSelected(item);
}
}
<file_sep>/app/src/main/java/cm/deone/mesextensions/models/Agent.java
package cm.deone.mesextensions.models;
public class Agent {
private String addedby;
private String campagne;
private String domain;
private long extension;
private String login;
private String nom;
private String password;
private String updatedby;
private String web;
public Agent() {
}
public Agent(String addedby, String campagne, String domain, long extension, String login,
String nom, String password, String updatedby, String web) {
this.addedby = addedby;
this.campagne = campagne;
this.domain = domain;
this.extension = extension;
this.login = login;
this.nom = nom;
this.password = <PASSWORD>;
this.updatedby = updatedby;
this.web = web;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public long getExtension() {
return extension;
}
public void setExtension(long extension) {
this.extension = extension;
}
public String getNom() {
return nom;
}
public void setNom(String name) {
this.nom = name;
}
public String getCampagne() {
return campagne;
}
public void setCampagne(String campagne) {
this.campagne = campagne;
}
public String getWeb() {
return web;
}
public void setWeb(String web) {
this.web = web;
}
public String getAddedby() {
return addedby;
}
public void setAddedby(String addedby) {
this.addedby = addedby;
}
public String getUpdatedby() {
return updatedby;
}
public void setUpdatedby(String updatedby) {
this.updatedby = updatedby;
}
}
<file_sep>/app/src/main/java/cm/deone/mesextensions/SignInActivity.java
package cm.deone.mesextensions;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class SignInActivity extends AppCompatActivity {
private EditText mEmail;
private EditText mPassword;
private Button mConnexion;
private Button mRegister;
private Button mAnnuler;
private ProgressBar mProgress_bar;
private FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
mAuth = FirebaseAuth.getInstance();
mEmail = (EditText) findViewById(R.id.email_login);
mPassword = (EditText) findViewById(R.id.password_login);
mConnexion = (Button) findViewById(R.id.login_btn);
mRegister = (Button) findViewById(R.id.register_btn);
mAnnuler = (Button) findViewById(R.id.cnx_back_btn);
mProgress_bar = (ProgressBar) findViewById(R.id.loading_progressBar);
mConnexion.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isEmpty()) return;
inProgress(true);
mAuth.signInWithEmailAndPassword(mEmail.getText().toString(), mPassword.getText().toString()).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
@Override
public void onSuccess(AuthResult authResult) {
Toast.makeText(SignInActivity.this, "User signed in", Toast.LENGTH_LONG).show();
Intent intent = new Intent(SignInActivity.this, AgentListActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();return;
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
inProgress(false);
Toast.makeText(SignInActivity.this, "User signed in failed!"+e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
});
mRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isEmpty()) return;
inProgress(true);
mAuth.createUserWithEmailAndPassword(mEmail.getText().toString(), mPassword.getText().toString()).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
@Override
public void onSuccess(AuthResult authResult) {
Toast.makeText(SignInActivity.this, "User registered successfully!", Toast.LENGTH_LONG).show();
inProgress(false);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
inProgress(false);
Toast.makeText(SignInActivity.this, "Registration failed!"+e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
});
mAnnuler.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();return;
}
});
}
private void inProgress (boolean b){
if (b){
mProgress_bar.setVisibility(View.VISIBLE);
mConnexion.setEnabled(false);
mRegister.setEnabled(false);
mAnnuler.setEnabled(false);
}else{
mProgress_bar.setVisibility(View.GONE);
mConnexion.setEnabled(true);
mRegister.setEnabled(true);
mAnnuler.setEnabled(true);
}
}
private boolean isEmpty(){
if(TextUtils.isEmpty(mEmail.getText().toString())){
mEmail.setError("REQUIRED!!!");
return true;
}
if(TextUtils.isEmpty(mPassword.getText().toString())){
mPassword.setError("REQUIRED!!!");
return true;
}
return false;
}
}
| e837438259754319a2803a4a6d84fc9678278f29 | [
"Java"
] | 3 | Java | 4deone/MesExtensions | ab975cf333d6eff41c0333b410969189718bd119 | 12273271f0342735c95d835fcdcc7a32e5fcbe0a |
refs/heads/master | <repo_name>aayushi-21/Parser<file_sep>/pass1.c
#include <stdio.h>
#include <string.h>
#define SIZE 1000
main()
{
FILE *f1,*f2;
char file1[SIZE],file2[SIZE];
//printf("Enter the source file name:");
//scanf("%s",file1);
f1=fopen("code.txt","r");
//printf("Enter the designation file name:");
//scanf("%s",file2);
f2=fopen("symboltable","w");
int ilc=0,len=0,i,j,flag1,flag2,temp;
char arr[SIZE],arr1[SIZE];
char opcode[13][10]={"LVI","MVI","ADDI","SUBI","MULI","DIVI","STORE","LOAD","GZ","GNZ","GC","GNC","GOTO"};
while(fgets(arr,SIZE,f1)!=NULL)
{
flag1=0;j=0;flag2=0;
len=strlen(arr);
for(i=0;i<len;i++)
arr1[i]='\0';
for(i=0;i<len;i++)
{
if(arr[i]==':')
{
flag1=1;
temp=i;
i=i+1;
while((arr[i]==' '||arr[i]=='\t'))
i++;
while((arr[i]!=' ')&&(arr[i]!='\t'))
{
arr1[j]=arr[i];
j++;
i++;
}
for(j=0;j<13;j++)
{
if(strcmp(arr1,opcode[j])==0)
{
flag2=1;
break;
}
}
break;
}
}
if(flag1==1)
{
for(j=0;j<temp;j++)
fprintf(f2,"%c",arr[j]);
fprintf(f2," %d\n",ilc);
}
if(flag1==0)
{
i=0;j=0;
while((arr[i]==' ')||(arr[i]=='\t'))
i++;
arr1[j]=arr[i];
j++;
i++;
while((arr[i]!=' ')&&(arr[i]!='\t'))
{
arr1[j]=arr[i];
j++;
i++;
}
for(j=0;j<13;j++)
{
if(strcmp(arr1,opcode[j])==0)
{
flag2=1;
break;
}
}
}
if(flag2==0)
ilc=ilc+1;
else
ilc=ilc+2;
}
fclose(f1);
fclose(f2);
}
<file_sep>/pass2.c
#include<stdio.h>
#include<string.h>
void hexa(char bno[10],char binary1[20][4]);
void binary(char bno[10],char binary2[17]);
struct data
{
char ch[10];
char binarycode[17];
};
//assumed spaces instead of commas
//asssumed loop names don't end with a number
//int flag=0;
main()
{
struct data d[100];
struct data e[100];
int i=0,j=0,x,y,z=0,k=0,it=0,b=0,flag=0;
FILE *f1,*f2,*f3,*f4;
char ar1[10],ar2[10],cr,s,binary1[20][4],binary2[17],tmp[5],file1[20];
printf("\nEnter the source file name :-");
scanf("%s",file1);
f1 = fopen( file1, "r");
f2 = fopen( "instructions.txt", "r");
f3 = fopen( "binary.txt","w");
f4 = fopen( "symboltable","r");
if(f1==NULL)
{
printf("File code.txt Not Found\n");
return 0;
}
if(f2==NULL)
{
printf("File instructions.txt Not Found\n");
return 0;
}
if(f4==NULL)
{
printf("File symboltable Not Found\n");
return 0;
}
while(fscanf(f2,"%s",ar1)!=EOF)
{
strcpy(d[i].ch,ar1);
fscanf(f2,"%s",&d[i].binarycode);
i++;
}
while(fscanf(f4,"%s",ar1)!=EOF)
{
// it=0;
strcpy(e[z].ch,ar1);
fscanf(f4,"%s",tmp);
printf("%s ",tmp);
binary(tmp,e[z].binarycode);
for(j=0;j<16;j++)
printf("%d",e[z].binarycode[j]);
printf("\n");
z++;
}
while( fscanf(f1,"%s",ar2)!= EOF )
{
s=ar2[strlen(ar2)-1];
/* for(j=0;j<=s;j++)
{
if(ar2[j]==',')
{
cm++;
}
}
*/
x=s;
if(x==104) //hex value for 'h'
{
hexa(ar2,binary1);
fprintf(f3,"\n%s",binary1);
}
else if(x>47 && x<58) //hex values for numbers 0-9
{
fprintf(f3," ");
binary(ar2,binary2);
for(y=0;y<16;y++)
fprintf(f3,"%d",binary2[y]);
}
else
{
j=0,k=0;
for(j=0;j<i;j++)
{
//printf("%s \n",ar2);
// if(ar2=="PRINT")
// {
// flag=1;
// }
if(strcmp(ar2,d[j].ch)==0)
{
fprintf(f3,"%s",d[j].binarycode);
break;
}
}
for(k=0;k<i;k++)
{
if(strcmp(ar2,e[k].ch)==0)
{
//printf("%s %s\n",ar2,e[j].ch);
b=0;
fprintf(f3,"\n");
for(b=0;b<16;b++)
fprintf(f3,"%d",e[k].binarycode[b]);
break;
}
}
}
/* else
{
j=0;
while(ar2[j]!='\0')
{
if(ar2[j]!=',')
}
}
*/
if((cr=getc(f1))=='\n')
fprintf(f3,"\n");
}
printf("\n\n######### BINARY CODE COMPLETED ##########\n\n");
fclose(f1);
fclose(f2);
fclose(f3);
fclose(f4);
}
void hexa(char bno[10],char binary1[20][4])
{
int i=0,j=0,x;
char temp[20][4];
while(i<(strlen(bno)-1))
{
switch(bno[i])
{
case 'A': strcpy(temp[i],"1010");
break;
case 'B': strcpy(temp[i],"1011");
break;
case 'C': strcpy(temp[i],"1100");
break;
case 'D': strcpy(temp[i],"1101");
break;
case 'E': strcpy(temp[i],"1110");
break;
case 'F': strcpy(temp[i],"1111");
break;
case '0': strcpy(temp[i],"0000");
break;
case '1': strcpy(temp[i],"0001");
break;
case '2': strcpy(temp[i],"0010");
break;
case '3': strcpy(temp[i],"0011");
break;
case '4': strcpy(temp[i],"0100");
break;
case '5': strcpy(temp[i],"0101");
break;
case '6': strcpy(temp[i],"0110");
break;
case '7': strcpy(temp[i],"0111");
break;
case '8': strcpy(temp[i],"1000");
break;
case '9': strcpy(temp[i],"1001");
break;
default: i--;
x=1;
break;
}
i++;
if(x==1)
break;
}
// if(flag!=1)
// {
if(i!=4)
{
for(j=0;j<4-i;j++)
strcpy(binary1[j],"0000");
for(j=4-i;j<4;j++)
strcpy(binary1[j],temp[j-i]);
}
else
{
for(j=0;j<4;j++)
strcpy(binary1[j],temp[j]);
}
/* else
{
for(j=0;j<4;j++)
strcpy(binary1[j],temp[j]);
}
*/
}
void binary(char bno[5],char binary2[17])
{
int i=0,j=0,x,s,y=0,z;
int num,temp[16];
for(j=0;j<16;j++)
temp[j]=0;
j=0;
s=strlen(bno)-1;
for(i=0;i<=s;i++)
{
x=bno[i];
z=x-48;
num=y*10+z;
y=num;
}
while(num!=0)
{
temp[j]=num%2;
num=num/2;
j++;
}
j=0;
for(j=0;j<16;j++)
binary2[j]=temp[15-j];
}
| 46be282e82cceab33504345bb9b1d6f389619292 | [
"C"
] | 2 | C | aayushi-21/Parser | 901eaf93a3202c3fe4911890072900e979ee3852 | 2962ce11cf815e04403f6bbd0fa95620586004c0 |
refs/heads/main | <file_sep>/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.navigation.NavHostController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.navArgument
import androidx.navigation.compose.navigate
import androidx.navigation.compose.rememberNavController
import com.example.androiddevchallenge.model.CutieCat
import com.example.androiddevchallenge.model.cats
import com.example.androiddevchallenge.ui.detail.Detail
import com.example.androiddevchallenge.ui.overview.Overview
object Destinations {
const val OVERVIEW_ROUTE = "overview"
const val DETAILS_ROUTE = "details"
const val CUTIE_CAT_DETAIL_KEY = "catId"
}
@Composable
fun NavGraph(startDestination: String = Destinations.OVERVIEW_ROUTE) {
val navController = rememberNavController()
val actions = remember(navController) { Actions(navController) }
NavHost(
navController = navController,
startDestination = startDestination
) {
composable(Destinations.OVERVIEW_ROUTE) {
Overview(actions.selectCat)
}
composable(
"${Destinations.DETAILS_ROUTE}/{${Destinations.CUTIE_CAT_DETAIL_KEY}}",
arguments = listOf(
navArgument(Destinations.CUTIE_CAT_DETAIL_KEY) { type = NavType.LongType }
)
) { backStackEntry ->
val arguments = requireNotNull(backStackEntry.arguments)
Detail(
cutieCat = cats.first { it.id == arguments.getLong(Destinations.CUTIE_CAT_DETAIL_KEY) },
navigateUp = actions.navigateUp
)
}
}
}
class Actions(navController: NavHostController) {
val selectCat: (CutieCat) -> Unit = {
navController.navigate("${Destinations.DETAILS_ROUTE}/${it.id}")
}
val navigateUp: () -> Unit = {
navController.navigateUp()
}
}
<file_sep>/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.ui.detail
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Card
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.ArrowBack
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.androiddevchallenge.NetworkImage
import com.example.androiddevchallenge.model.CutieCat
import com.example.androiddevchallenge.model.Gender.FEMALE
import com.example.androiddevchallenge.model.Gender.MALE
import com.example.androiddevchallenge.model.cats
import com.example.androiddevchallenge.ui.theme.purple200
@Composable
fun Detail(cutieCat: CutieCat, navigateUp: () -> Unit) {
val listState = rememberLazyListState()
Scaffold(
topBar = {
Box(
modifier = Modifier
.aspectRatio(16 / 9F)
.fillMaxWidth()
) {
NetworkImage(
url = cutieCat.image[0],
contentDescription = ""
)
Column(
modifier = Modifier
.fillMaxSize()
.background(
Brush.verticalGradient(
listOf(Color.Transparent, purple200),
)
)
) {
}
Box(modifier = Modifier.padding(8.dp)) {
IconButton(
onClick = navigateUp,
modifier = Modifier
.background(purple200, shape = CircleShape)
.size(40.dp)
) {
Icon(Icons.Rounded.ArrowBack, contentDescription = "")
}
}
}
}
) {
Surface(color = purple200, modifier = Modifier.fillMaxHeight()) {
LazyColumn(state = listState) {
item {
Column {
Column(
modifier = Modifier.padding(start = 16.dp, end = 16.dp)
) {
Text(cutieCat.catName, style = MaterialTheme.typography.h3)
Spacer(modifier = Modifier.size(16.dp))
Text(
cutieCat.description,
style = MaterialTheme.typography.body1,
fontStyle = FontStyle.Italic
)
Spacer(modifier = Modifier.size(8.dp))
Text("Species: ${cutieCat.species}")
Spacer(modifier = Modifier.size(8.dp))
Text("Age: ${cutieCat.age}")
Spacer(modifier = Modifier.size(8.dp))
Text(
"Gender: ${
when (cutieCat.gender) {
MALE -> "Male"
FEMALE -> "Female"
}
}"
)
Spacer(modifier = Modifier.size(8.dp))
Text("Eye color: ")
Spacer(modifier = Modifier.size(8.dp))
Row {
Box(
modifier = Modifier
.size(16.dp)
.background(cutieCat.eyeColor, CircleShape)
.border(1.dp, shape = CircleShape, color = Color.DarkGray)
)
}
Spacer(modifier = Modifier.size(8.dp))
Text("Hair color: ")
Spacer(modifier = Modifier.size(8.dp))
Row {
cutieCat.hairColor.forEach {
Box(
modifier = Modifier
.size(16.dp)
.background(it, CircleShape)
.border(
1.dp,
shape = CircleShape,
color = Color.DarkGray
)
.padding(start = 8.dp)
)
}
}
Spacer(modifier = Modifier.size(16.dp))
Text(
text = "${cutieCat.catName}'s Gallery",
style = MaterialTheme.typography.subtitle2
)
}
LazyRow(
modifier = Modifier.wrapContentHeight()
) {
items(cutieCat.image) {
Card(
modifier = Modifier
.height(180.dp)
.aspectRatio(16 / 9F)
.padding(16.dp)
.clip(RoundedCornerShape(16.dp))
) {
NetworkImage(
url = it,
contentDescription = ""
)
}
}
}
}
}
}
}
}
}
@Preview
@Composable
fun DetailPreview() {
Detail(cutieCat = cats[0], navigateUp = {})
}
<file_sep>/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.ui.overview
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.CornerSize
import androidx.compose.material.Card
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.androiddevchallenge.NetworkImage
import com.example.androiddevchallenge.model.CutieCat
import com.example.androiddevchallenge.model.cats
import com.example.androiddevchallenge.ui.theme.purple200
@Composable
fun Overview(navigateToDetails: (CutieCat) -> Unit) {
CutieCatList(navigateToDetails = navigateToDetails)
}
@Composable
fun CutieCatList(modifier: Modifier = Modifier, navigateToDetails: (CutieCat) -> Unit) {
LazyColumn(modifier = modifier.background(purple200)) {
item {
Column {
Box(
modifier = Modifier
.aspectRatio(16 / 9F)
.fillMaxWidth()
) {
NetworkImage(
url = "https://static.wikia.nocookie.net/creamheroes/images/6/6e/DD_Pose_2.jpeg",
contentDescription = "https://static.wikia.nocookie.net/creamheroes/images/6/6e/DD_Pose_2.jpeg"
)
Column(
modifier = Modifier
.fillMaxSize()
.background(
Brush.verticalGradient(
listOf(Color.Transparent, purple200),
)
)
) {
}
Column(
modifier = Modifier
.padding(start = 16.dp, top = 120.dp, bottom = 8.dp)
) {
Text("Cutie Cats", style = MaterialTheme.typography.h4, fontWeight = FontWeight.Bold)
Text("Adopt a cat!", style = MaterialTheme.typography.subtitle1)
}
}
Text(
"Cats need adoption",
style = MaterialTheme.typography.h6,
modifier = Modifier.padding(16.dp)
)
}
}
items(cats) { cat ->
CutieCatItem(cat, navigateToDetails)
}
}
}
@Composable
fun CutieCatItem(cutieCat: CutieCat, onItemClick: (CutieCat) -> Unit) {
Card(
modifier = Modifier
.fillMaxWidth()
.height(140.dp)
.padding(8.dp)
.clickable { onItemClick(cutieCat) },
shape = MaterialTheme.shapes.large.copy(CornerSize(24.dp))
) {
Row(horizontalArrangement = Arrangement.SpaceBetween) {
Column(modifier = Modifier.padding(16.dp)) {
Text(cutieCat.catName, style = MaterialTheme.typography.h5)
Spacer(modifier = Modifier.size(8.dp))
Text("Age: ${cutieCat.age}")
Spacer(modifier = Modifier.size(16.dp))
Row {
Text("Hair color: ", style = MaterialTheme.typography.caption)
Spacer(modifier = Modifier.size(8.dp))
cutieCat.hairColor.forEach { color ->
Box(
modifier = Modifier.size(16.dp)
.background(color, CircleShape)
.border(1.dp, Color.DarkGray, CircleShape)
) { }
Spacer(modifier = Modifier.size(8.dp))
}
}
}
Card(
shape = MaterialTheme.shapes.large.copy(
topStart = CornerSize(24.dp),
bottomEnd = CornerSize(24.dp)
)
) {
NetworkImage(
url = cutieCat.image[0],
contentDescription = "",
modifier = Modifier.size(140.dp)
)
}
}
}
}
@Preview
@Composable
fun CutieCatItemPreview() {
Card(
modifier = Modifier
.fillMaxWidth()
.height(180.dp)
.padding(8.dp),
shape = MaterialTheme.shapes.large.copy(CornerSize(24.dp))
) {
Row(horizontalArrangement = Arrangement.SpaceBetween) {
Column(modifier = Modifier.padding(16.dp)) {
Text("DD", style = MaterialTheme.typography.h5)
Spacer(modifier = Modifier.size(8.dp))
Text("Species: Northwest", style = MaterialTheme.typography.caption)
}
Card(
shape = MaterialTheme.shapes.large.copy(
topStart = CornerSize(24.dp),
bottomEnd = CornerSize(24.dp)
)
) {
NetworkImage(
url = "https://static.wikia.nocookie.net/creamheroes/images/6/6e/DD_Pose_2.jpeg",
contentDescription = "",
modifier = Modifier.size(180.dp)
)
}
}
}
}
| 19ea4f86cf0c2799f1445897828d87574cb92895 | [
"Kotlin"
] | 3 | Kotlin | tsnAnh/CutieCats | 3753745d7d3866b5b4d3ec4f079f61dfd0e4daa9 | fb69d9e43c47724f8e218f02f740a55c97352e3f |
refs/heads/master | <repo_name>obabec/PatrIoT_router<file_sep>/api/iproute2/model/interface.go
// Package model provides structures representing objects in routing tables
// Network interfaces and routes.
package model
// Interface represents network interface of workstation/container/...
type Interface struct {
IPAddress string
Name string
}
<file_sep>/api/iproute2/model/route.go
// Package model provides structures representing objects in routing tables
// Network interfaces and routes.
package model
// Route represents actual record in linux routing table.
type Route struct {
Destination Network
InterfaceIP string
}
<file_sep>/api/iptables-api/README.md
# api-iptables
Create API REST for iptables command with :
- https://github.com/oxalide/go-iptables/ (forked from coreos/go-iptables)
- https://github.com/gorilla/mux
- https://github.com/gorilla/handlers
Compile:
--------
go build -o iptables-api
Run:
----
./iptables-api -h
Usage of /root/iptables-api:
-cert string
file of certificat for https
-htpasswd string
htpasswd file for login:password
-https
https = true or false
-ip string
listen on IP (default "127.0.0.1")
-key string
file of key for https
-log string
file for access log (default "/var/log/iptables-api.access.log")
-port string
listen on port (default "8080")
-save_path string
path for backups => /save (default "var/backups/iptables-api/")
./iptables-api -https -ip=192.168.0.1 -port=8443 -log=/var/log/api-iptables.access.log -cert=cert.pem -key=key.pem -htpasswd=/root/.htpasswd
API List :
---------
**Rules:**
Test,Add,Del iptables rule in table filter with the parameters
GET/PUT/DELETE /rules/{action}/{chain}/{proto}/{iface_in}/{iface_out}/{source}/{destination}/?sports=00&dports=00&state=XXXX&fragment=true&icmptype=XXXX&log-prefix=XXXXX
with for source and destination _ instead / : 10.0.0.0_8 or range 10.0.0.0-10.255.0.0_32
log-prefix only if action = LOG
**Nat:**
Test,Add,Del iptables rule in table nat with the parameters
GET/PUT/DELETE /nat/{action}/{chain}/{proto}/{iface}/{source}/{destination}/{nat_final}/?dport=00
with for source and destination _ instead / : 10.0.0.0_8
**Raw:**
Test,Add,Del iptables rule in table raw with the parameters
GET/PUT/DELETE /raw/{action}/{chain}/{proto}/{iface_in}/{iface_out}/{source}/{destination}/?sports=00&dports=00&tcpflag1=XYZ&tcpflag2=Y¬rack=true&log-prefix=XXXXX
with for source and destination _ instead / : 10.0.0.0_8 or range 10.0.0.0-10.255.0.0_32
log-prefix only if action = LOG
**Chain:**
Test,Add,Del chain with the parameters
GET/PUT/DELETE /chain/{table}/{name}/
Rename chain with the parameters
PUT /mvchain/{table}/{oldname}/{newname}/
**Save:**
iptables-save > /etc/iptables/rules.v4 && cp /etc/iptables/rules.v4 /var/backups/iptables-api/rules.v4.2006-01-02.15-04-05
GET /save/
**Restore:**
iptables-restore $file
PUT /restore/{file}
<file_sep>/router/Dockerfile
FROM golang:1.11
RUN go get -d -v github.com/olivere/elastic && \
go get -d -v github.com/sirupsen/logrus && \
go get -d -v gopkg.in/sohlich/elogrus.v3 &&\
go get -d -v github.com/abbot/go-http-auth && \
go get -d -v github.com/gorilla/handlers && \
go get -d -v github.com/gorilla/mux &&\
go get -d -v github.com/oxalide/go-iptables/iptables &&\
go get -d -v github.com/seatgeek/logrus-gelf-formatter
RUN apt-get update && \
DEBIAN_FRONTEND=noninteractive \
apt-get -y install default-jre-headless && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*
WORKDIR /go/src
ADD /api/iprouteRESt /go/src/api/iprouteRESt
ADD /api/iptables-api /go/src/api/iptables-api
ADD /api/iproute2 /go/src/api/iproute2
WORKDIR /
ADD nat nat
WORKDIR /go/src/api/iptables-api/
RUN go build -o /api/iptables-api main.go
WORKDIR /go/src/api/iprouteRESt/
RUN go build -o /api/iprouteRESt Controller.go
ADD ../start_daemons /start_daemons
RUN apt update
RUN apt install -y iptables traceroute
WORKDIR /
RUN chmod +x /start_daemons
RUN chmod +x /nat
ENTRYPOINT ["/start_daemons"]
CMD ["/api/iptables-api", "-ip", "0.0.0.0"]
<file_sep>/nat
#!/bin/bash
echo 1 > /proc/sys/net/ipv4/ip_forward
IPT=/sbin/iptables
PUB_IF=$1
$IPT -F
$IPT -t nat -F
$IPT -t nat -A POSTROUTING -o $PUB_IF -j MASQUERADE
$IPT -t nat -A POSTROUTING -j MASQUERADE
$IPT -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
$IPT -A INPUT -m state ! --state NEW -i $PUB_IF -j ACCEPT
$IPT -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT
$IPT -A FORWARD -m state ! --state NEW -i $PUB_IF -j ACCEPT
$IPT -A FORWARD -i $PUB_IF -j ACCEPT
<file_sep>/api/iptables-api/main.go
// Copyright 2016 <NAME>
//
// This file is part of iptables-api.
//
// iptables-api is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Foobar is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with iptables-api. If not, see <http://www.gnu.org/licenses/>.
package main
import (
"fmt"
"strings"
"log"
"net/http"
"os"
"os/exec"
"io/ioutil"
"time"
"flag"
"reflect"
"strconv"
auth "github.com/abbot/go-http-auth"
"github.com/oxalide/go-iptables/iptables"
"github.com/gorilla/mux"
"github.com/gorilla/handlers"
)
var (
resp_err error
htpasswdfile *string
save_path *string
)
func main() {
listen_ip := flag.String("ip", "127.0.0.1", "listen on IP")
listen_port := flag.String("port", "8080", "listen on port")
https := flag.Bool("https", false, "https = true or false")
cert := flag.String("cert", "", "file of certificat for https")
key := flag.String("key", "", "file of key for https")
accessLogFile := flag.String("log", "/var/log/iptables-api.access.log", "file for access log")
htpasswdfile = flag.String("htpasswd", "", "htpasswd file for login:password")
save_path = flag.String("savepath", "/var/backups/iptables-api/", "path for backups file on /save")
flag.Parse()
// accesslog file open
accessLog, err := os.OpenFile(*accessLogFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
log.Fatalf("Failed to open access log: %s", err)
}
// create router
router := mux.NewRouter().StrictSlash(false)
router.HandleFunc("/rules/{action}/{chain}/{proto}/{iface_in}/{iface_out}/{source}/{destination}/", add_rules).Methods("PUT")
router.HandleFunc("/rules/{action}/{chain}/{proto}/{iface_in}/{iface_out}/{source}/{destination}/", del_rules).Methods("DELETE")
router.HandleFunc("/rules/{action}/{chain}/{proto}/{iface_in}/{iface_out}/{source}/{destination}/", check_rules).Methods("GET")
router.HandleFunc("/raw/{action}/{chain}/{proto}/{iface_in}/{iface_out}/{source}/{destination}/", add_raw).Methods("PUT")
router.HandleFunc("/raw/{action}/{chain}/{proto}/{iface_in}/{iface_out}/{source}/{destination}/", del_raw).Methods("DELETE")
router.HandleFunc("/raw/{action}/{chain}/{proto}/{iface_in}/{iface_out}/{source}/{destination}/", check_raw).Methods("GET")
router.HandleFunc("/nat/{action}/{chain}/{proto}/{iface}/{source}/{destination}/{nat_final}/", add_nat).Methods("PUT")
router.HandleFunc("/nat/{action}/{chain}/{proto}/{iface}/{source}/{destination}/{nat_final}/", del_nat).Methods("DELETE")
router.HandleFunc("/nat/{action}/{chain}/{proto}/{iface}/{source}/{destination}/{nat_final}/", check_nat).Methods("GET")
router.HandleFunc("/chain/{table}/{name}/", add_chain).Methods("PUT")
router.HandleFunc("/chain/{table}/{name}/", del_chain).Methods("DELETE")
router.HandleFunc("/chain/{table}/{name}/", list_chain).Methods("GET")
router.HandleFunc("/mvchain/{table}/{oldname}/{newname}/", rename_chain).Methods("PUT")
router.HandleFunc("/save/", save_rules).Methods("GET")
router.HandleFunc("/restore/", restore_rules).Methods("PUT")
loggedRouter := handlers.CombinedLoggingHandler(accessLog, router)
if *https {
if ( *cert == "" ) || ( *key == "" ) {
log.Fatalf("HTTPS true but no cert and key defined")
} else {
log.Fatal(http.ListenAndServeTLS(strings.Join([]string{*listen_ip, ":", *listen_port}, ""), *cert, *key, loggedRouter))
}
} else {
log.Fatal(http.ListenAndServe(strings.Join([]string{*listen_ip, ":", *listen_port}, ""), loggedRouter))
}
}
// GET /save/
func save_rules(w http.ResponseWriter, r *http.Request) {
if *htpasswdfile != "" {
htpasswd := auth.HtpasswdFileProvider(*htpasswdfile)
authenticator := auth.NewBasicAuthenticator("Basic Realm", htpasswd)
usercheck := authenticator.CheckAuth(r)
if usercheck == "" {
w.WriteHeader(http.StatusUnauthorized)
return
}
}
os.Mkdir("/etc/iptables/",0755)
stdout, err := exec.Command("iptables-save").Output()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
err = ioutil.WriteFile("/etc/iptables/rules.v4", stdout, 0644)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
os.Mkdir(*save_path,0755)
current_time := time.Now().Local()
dst_f := []string{*save_path, "rules.v4.", current_time.Format("2006-01-02"), ".", current_time.Format("15-04-05")}
cmd := exec.Command("cp", "/etc/iptables/rules.v4", strings.Join(dst_f, ""))
err = cmd.Run()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
fmt.Fprintln(w, strings.Join(dst_f, ""))
}
// GET /restore/{file}
func restore_rules(w http.ResponseWriter, r *http.Request) {
if *htpasswdfile != "" {
htpasswd := auth.HtpasswdFileProvider(*htpasswdfile)
authenticator := auth.NewBasicAuthenticator("Basic Realm", htpasswd)
usercheck := authenticator.CheckAuth(r)
if usercheck == "" {
w.WriteHeader(http.StatusUnauthorized)
return
}
}
err := exec.Command("iptables-restore", r.URL.Query().Get("file")).Run()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
}
func rule_generate(r *http.Request) []string {
vars := mux.Vars(r)
var spec_end []string
if r.URL.Query().Get("sports") != "" {
spec_end = append(spec_end, "-m", "multiport", "--sports", r.URL.Query().Get("sports"))
}
if r.URL.Query().Get("dports") != "" {
spec_end = append(spec_end,"-m", "multiport", "--dports", r.URL.Query().Get("dports"))
}
if r.URL.Query().Get("state") != "" {
spec_end = append(spec_end, "-m", "state", "--state", r.URL.Query().Get("state"))
}
if r.URL.Query().Get("fragment") != "" {
spec_end = append(spec_end,"-f")
}
if r.URL.Query().Get("icmptype") != "" {
spec_end = append(spec_end,"--icmp-type", r.URL.Query().Get("icmptype"))
}
if vars["iface_in"] != "*" {
spec_end = append(spec_end, "-i", vars["iface_in"])
}
if vars["iface_out"] != "*" {
spec_end = append(spec_end, "-o", vars["iface_out"])
}
src_range := strings.Contains(vars["source"], "-")
dst_range := strings.Contains(vars["destination"], "-")
rulespecs := []string{"-p", vars["proto"]}
if src_range {
rulespecs = append(rulespecs, "-m", "iprange", "--src-range", strings.Replace(vars["source"], "_32", "", -1))
} else {
rulespecs = append(rulespecs, "-s", strings.Replace(vars["source"], "_", "/", -1))
}
if dst_range {
rulespecs = append(rulespecs, "-m", "iprange", "--dst-range", strings.Replace(vars["destination"], "_32", "", -1))
} else {
rulespecs = append(rulespecs, "-d", strings.Replace(vars["destination"], "_", "/", -1))
}
rulespecs = append(rulespecs, "-j", vars["action"])
if (r.URL.Query().Get("log-prefix") != "") && vars["action"] == "LOG" {
rulespecs = append(rulespecs, "--log-prefix", r.URL.Query().Get("log-prefix"))
}
rulespecs = append(rulespecs, spec_end...)
return rulespecs
}
func CheckPosRules(r *http.Request) ([]string, error) {
vars := mux.Vars(r)
var linenumber []string
line := []string{vars["action"], vars["proto"]}
if r.URL.Query().Get("fragment") != "" {
line = append(line, "-f")
} else {
line = append(line, "--")
}
line = append(line, vars["iface_in"], vars["iface_out"])
src_range := strings.Contains(vars["source"], "-")
if src_range {
line = append(line, "0.0.0.0/0")
} else {
source_32 := strings.Contains(vars["source"], "_32")
if source_32 {
line = append(line, strings.Replace(vars["source"], "_32", "", -1))
} else {
line = append(line, strings.Replace(vars["source"], "_", "/", -1))
}
}
dst_range := strings.Contains(vars["destination"], "-")
if dst_range {
line = append(line, "0.0.0.0/0")
} else {
destination_32 := strings.Contains(vars["destination"], "_32")
if destination_32 {
line = append(line, strings.Replace(vars["destination"], "_32", "", -1))
} else {
line = append(line, strings.Replace(vars["destination"], "_", "/", -1))
}
}
if src_range {
line = append(line, "source", "IP", "range", strings.Replace(vars["source"], "_32", "", -1))
}
if dst_range {
line = append(line, "destination", "IP", "range", strings.Replace(vars["destination"], "_32", "", -1))
}
if r.URL.Query().Get("sports") != "" {
line = append(line, "multiport", "sports", r.URL.Query().Get("sports"))
}
if r.URL.Query().Get("dports") != "" {
line = append(line, "multiport", "dports", r.URL.Query().Get("dports"))
}
if r.URL.Query().Get("icmptype") != "" {
line = append(line, "icmptype", r.URL.Query().Get("icmptype"))
}
if (r.URL.Query().Get("log-prefix") != "") && vars["action"] == "LOG" {
line = append(line, "LOG", "flags", "0", "level", "4", "prefix", strings.Join([]string{"\"", r.URL.Query().Get("log-prefix"), "\""}, ""))
}
ipt, err := iptables.New()
if err != nil {
return nil,err
}
args := []string{"-t", "filter", "-vnL", vars["chain"], "--line-numbers"}
if ipt.Wait() {
args = append(args, "--wait")
}
rules, err := ipt.ExecuteList(args)
if err != nil {
return nil,err
}
for i:= 0; i < len(rules); i++ {
rulesSlice := strings.Fields(rules[i])
rulesSliceNoVerb := rulesSlice[3:]
if reflect.DeepEqual(line, rulesSliceNoVerb) {
linenumber = append(linenumber, rulesSlice[0])
}
}
return linenumber,nil
}
// PUT /rules/{action}/{chain}/{proto}/{iface_in}/{iface_out}/{source}/{destination}/?sports=00&dports=00
func add_rules (w http.ResponseWriter, r *http.Request) {
if *htpasswdfile != "" {
htpasswd := auth.HtpasswdFileProvider(*htpasswdfile)
authenticator := auth.NewBasicAuthenticator("Basic Realm", htpasswd)
usercheck := authenticator.CheckAuth(r)
if usercheck == "" {
w.WriteHeader(http.StatusUnauthorized)
return
}
}
rulespecs := rule_generate(r)
ipt, err := iptables.New()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
if ipt.Wait() {
rulespecs = append(rulespecs, "--wait")
}
vars := mux.Vars(r)
if r.URL.Query().Get("position") != "" {
position, err := strconv.Atoi(r.URL.Query().Get("position"))
if err != nil {
http.Error(w, err.Error(), 500)
return
}
resp_err = ipt.Insert("filter", vars["chain"], position, rulespecs...)
} else {
resp_err = ipt.Append("filter", vars["chain"], rulespecs...)
}
if resp_err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, resp_err)
}
}
// DELETE /rules/{action}/{chain}/{proto}/{iface_in}/{iface_out}/{source}/{destination}/?sports=00&dports=00
func del_rules (w http.ResponseWriter, r *http.Request) {
if *htpasswdfile != "" {
htpasswd := auth.HtpasswdFileProvider(*htpasswdfile)
authenticator := auth.NewBasicAuthenticator("Basic Realm", htpasswd)
usercheck := authenticator.CheckAuth(r)
if usercheck == "" {
w.WriteHeader(http.StatusUnauthorized)
return
}
}
rulespecs := rule_generate(r)
ipt, err := iptables.New()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
if ipt.Wait() {
rulespecs = append(rulespecs, "--wait")
}
vars := mux.Vars(r)
resp_err = ipt.Delete("filter", vars["chain"], rulespecs...)
if resp_err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, resp_err)
}
}
// GET /rules/{action}/{chain}/{proto}/{iface_in}/{iface_out}/{source}/{destination}/?sports=00&dports=00
func check_rules (w http.ResponseWriter, r *http.Request) {
if *htpasswdfile != "" {
htpasswd := auth.HtpasswdFileProvider(*htpasswdfile)
authenticator := auth.NewBasicAuthenticator("Basic Realm", htpasswd)
usercheck := authenticator.CheckAuth(r)
if usercheck == "" {
w.WriteHeader(http.StatusUnauthorized)
return
}
}
rulespecs := rule_generate(r)
ipt, err := iptables.New()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
if ipt.Wait() {
rulespecs = append(rulespecs, "--wait")
}
if r.URL.Query().Get("position") != "" {
pos_rules, err := CheckPosRules(r)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
if len(pos_rules) == 0 {
w.WriteHeader(http.StatusNotFound)
return
}
if len(pos_rules) != 1 {
w.WriteHeader(http.StatusConflict)
return
}
if pos_rules[0] == r.URL.Query().Get("position") {
return
} else {
w.WriteHeader(http.StatusNotFound)
return
}
} else {
vars := mux.Vars(r)
resp_str, resp_err := ipt.Exists("filter", vars["chain"], rulespecs...)
if resp_err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, resp_err)
return
}
if !resp_str {
w.WriteHeader(http.StatusNotFound)
return
}
}
}
func dnat_generate(r *http.Request) []string {
vars := mux.Vars(r)
rulespecs := append([]string{"-p", vars["proto"], "-i", vars["iface"], "-s", strings.Replace(vars["source"], "_", "/", -1), "-d", strings.Replace(vars["destination"], "_", "/", -1), "-j", "DNAT", "--to-destination", vars["nat_final"]})
if r.URL.Query().Get("dport") != "" {
rulespecs = append(rulespecs, "--dport", r.URL.Query().Get("dport"))
}
if ( r.URL.Query().Get("nth_every") != "" ) {
rulespecs = append(rulespecs, "-m", "statistic", "--mode", "nth", "--every", r.URL.Query().Get("nth_every"), "--packet", r.URL.Query().Get("nth_packet"))
}
return rulespecs
}
func snat_generate(r *http.Request) []string {
vars := mux.Vars(r)
rulespecs := append([]string{"-p", vars["proto"], "-o", vars["iface"], "-s", strings.Replace(vars["source"], "_", "/", -1), "-d", strings.Replace(vars["destination"], "_", "/", -1), "-j", "SNAT", "--to-source", vars["nat_final"]})
if r.URL.Query().Get("dport") != "" {
rulespecs = append(rulespecs, "--dport", r.URL.Query().Get("dport"))
}
if ( r.URL.Query().Get("nth_every") != "" ) {
rulespecs = append(rulespecs, "-m", "statistic", "--mode", "nth", "--every", r.URL.Query().Get("nth_every"), "--packet", r.URL.Query().Get("nth_packet"))
}
return rulespecs
}
func CheckPosNat(r *http.Request) ([]string, error) {
vars := mux.Vars(r)
var linenumber []string
var line []string
if vars["action"] == "dnat" {
line = append(line, "DNAT", vars["proto"], "--", vars["iface"], "*")
}
if vars["action"] == "snat" {
line = append(line, "SNAT", vars["proto"], "--", "*", vars["iface"])
}
source_32 := strings.Contains(vars["source"], "_32")
destination_32 := strings.Contains(vars["destination"], "_32")
if source_32 {
line = append(line, strings.Replace(vars["source"], "_32", "", -1))
} else {
line = append(line, strings.Replace(vars["source"], "_", "/", -1))
}
if destination_32 {
line = append(line, strings.Replace(vars["destination"], "_32", "", -1))
} else {
line = append(line, strings.Replace(vars["destination"], "_", "/", -1))
}
if r.URL.Query().Get("dport") != "" {
line = append(line, "tcp", strings.Join([]string{"dpt:", r.URL.Query().Get("dport")}, ""))
}
if r.URL.Query().Get("nth_every") != "" {
if r.URL.Query().Get("nth_packet") == "0" {
line = append(line, "statistic", "mode", "nth", "every", r.URL.Query().Get("nth_every"))
} else {
line = append(line, "statistic", "mode", "nth", "every", r.URL.Query().Get("nth_every"), "packet", r.URL.Query().Get("nth_packet"))
}
}
line = append(line, strings.Join([]string{"to:", vars["nat_final"]}, ""))
ipt, err := iptables.New()
if err != nil {
return nil,err
}
args := []string{"-t", "nat", "-vnL", vars["chain"], "--line-numbers"}
if ipt.Wait() {
args = append(args, "--wait")
}
nats, err := ipt.ExecuteList(args)
if err != nil {
return nil,err
}
for i:= 0; i < len(nats); i++ {
natsSlice := strings.Fields(nats[i])
natsSliceNoVerb := natsSlice[3:]
if reflect.DeepEqual(line, natsSliceNoVerb) {
linenumber = append(linenumber, natsSlice[0])
}
}
return linenumber,nil
}
// PUT /nat/{action}/{chain}/{proto}/{iface}/{source}/{destination}/{nat_final}/?dport=00
func add_nat (w http.ResponseWriter, r *http.Request) {
if *htpasswdfile != "" {
htpasswd := auth.HtpasswdFileProvider(*htpasswdfile)
authenticator := auth.NewBasicAuthenticator("Basic Realm", htpasswd)
usercheck := authenticator.CheckAuth(r)
if usercheck == "" {
w.WriteHeader(http.StatusUnauthorized)
return
}
}
vars := mux.Vars(r)
ipt, err := iptables.New()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
var rulespecs []string
if ( r.URL.Query().Get("nth_every") != "" ) || ( r.URL.Query().Get("nth_packet") != "" ) {
if r.URL.Query().Get("nth_every") == "" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, "Missing nth every")
return
}
if r.URL.Query().Get("nth_packet") == "" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, "Missing nth packet")
return
}
}
if vars["action"] == "dnat" {
rulespecs = dnat_generate(r)
} else if vars["action"] == "snat" {
rulespecs = snat_generate(r)
} else {
w.WriteHeader(http.StatusNotFound)
return
}
if ipt.Wait() {
rulespecs = append(rulespecs, "--wait")
}
if r.URL.Query().Get("position") != "" {
position, err := strconv.Atoi(r.URL.Query().Get("position"))
if err != nil {
http.Error(w, err.Error(), 500)
return
}
resp_err = ipt.Insert("nat", vars["chain"], position, rulespecs...)
} else {
resp_err = ipt.Append("nat", vars["chain"], rulespecs...)
}
if resp_err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, resp_err)
}
}
// DELETE /nat/{action}/{chain}/{proto}/{iface}/{source}/{destination}/{nat_final}/?dport=00
func del_nat (w http.ResponseWriter, r *http.Request) {
if *htpasswdfile != "" {
htpasswd := auth.HtpasswdFileProvider(*htpasswdfile)
authenticator := auth.NewBasicAuthenticator("Basic Realm", htpasswd)
usercheck := authenticator.CheckAuth(r)
if usercheck == "" {
w.WriteHeader(http.StatusUnauthorized)
return
}
}
vars := mux.Vars(r)
ipt, err := iptables.New()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
var rulespecs []string
if ( r.URL.Query().Get("nth_every") != "" ) || ( r.URL.Query().Get("nth_packet") != "" ) {
if r.URL.Query().Get("nth_every") == "" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, "Missing nth every")
return
}
if r.URL.Query().Get("nth_packet") == "" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, "Missing nth packet")
return
}
}
if vars["action"] == "dnat" {
rulespecs = dnat_generate(r)
} else if vars["action"] == "snat" {
rulespecs = snat_generate(r)
} else {
w.WriteHeader(http.StatusNotFound)
return
}
if ipt.Wait() {
rulespecs = append(rulespecs, "--wait")
}
resp_err = ipt.Delete("nat", vars["chain"], rulespecs...)
if resp_err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, resp_err)
}
}
// GET /nat/{action}/{chain}/{proto}/{iface}/{source}/{destination}/{nat_final}/?dport=00
func check_nat (w http.ResponseWriter, r *http.Request) {
if *htpasswdfile != "" {
htpasswd := auth.HtpasswdFileProvider(*htpasswdfile)
authenticator := auth.NewBasicAuthenticator("Basic Realm", htpasswd)
usercheck := authenticator.CheckAuth(r)
if usercheck == "" {
w.WriteHeader(http.StatusUnauthorized)
return
}
}
vars := mux.Vars(r)
ipt, err := iptables.New()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
if r.URL.Query().Get("position") != "" {
pos_nat, err := CheckPosNat(r)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
if len(pos_nat) == 0 {
w.WriteHeader(http.StatusNotFound)
return
}
if len(pos_nat) != 1 {
w.WriteHeader(http.StatusConflict)
return
}
if pos_nat[0] == r.URL.Query().Get("position") {
return
} else {
w.WriteHeader(http.StatusNotFound)
return
}
}
var rulespecs []string
if ( r.URL.Query().Get("nth_every") != "" ) || ( r.URL.Query().Get("nth_packet") != "" ) {
if r.URL.Query().Get("nth_every") == "" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, "Missing nth every")
return
}
if r.URL.Query().Get("nth_packet") == "" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, "Missing nth packet")
return
}
}
if vars["action"] == "dnat" {
rulespecs = dnat_generate(r)
} else if vars["action"] == "snat" {
rulespecs = snat_generate(r)
} else {
w.WriteHeader(http.StatusNotFound)
return
}
if ipt.Wait() {
rulespecs = append(rulespecs, "--wait")
}
resp_str, resp_err := ipt.Exists("nat", vars["chain"], rulespecs...)
if resp_err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, resp_err)
}
if !resp_str {
w.WriteHeader(http.StatusNotFound)
}
}
func raw_generate(r *http.Request) []string {
vars := mux.Vars(r)
var spec_end []string
if r.URL.Query().Get("sports") != "" {
spec_end = append(spec_end,"-m", "multiport", "--sports", r.URL.Query().Get("sports"))
}
if r.URL.Query().Get("dports") != "" {
spec_end = append(spec_end,"-m", "multiport", "--dports", r.URL.Query().Get("dports"))
}
if r.URL.Query().Get("notrack") != "" {
spec_end = append(spec_end,"--notrack")
}
if (r.URL.Query().Get("tcpflag1") != "") && (r.URL.Query().Get("tcpflag2") != "") && (vars["proto"] == "tcp") {
tcpflag := []string{"--tcp-flags", r.URL.Query().Get("tcpflag1"), r.URL.Query().Get("tcpflag2")}
spec_end = append(spec_end,tcpflag...)
}
if vars["iface_in"] != "*" {
spec_end = append(spec_end, "-i", vars["iface_in"])
}
if vars["iface_out"] != "*" {
spec_end = append(spec_end, "-o", vars["iface_out"])
}
src_range := strings.Contains(vars["source"], "-")
dst_range := strings.Contains(vars["destination"], "-")
rulespecs := []string{"-p", vars["proto"]}
if src_range {
rulespecs = append(rulespecs, "-m", "iprange", "--src-range", strings.Replace(vars["source"], "_32", "", -1))
} else {
rulespecs = append(rulespecs, "-s", strings.Replace(vars["source"], "_", "/", -1))
}
if dst_range {
rulespecs = append(rulespecs, "-m", "iprange", "--dst-range", strings.Replace(vars["destination"], "_32", "", -1))
} else {
rulespecs = append(rulespecs, "-d", strings.Replace(vars["destination"], "_", "/", -1))
}
rulespecs = append(rulespecs, "-j", vars["action"])
if (r.URL.Query().Get("log-prefix") != "") && vars["action"] == "LOG" {
rulespecs = append(rulespecs, "--log-prefix", r.URL.Query().Get("log-prefix"))
}
rulespecs = append(rulespecs, spec_end...)
return rulespecs
}
func CheckPosRaw(r *http.Request) ([]string, error) {
vars := mux.Vars(r)
var linenumber []string
line := []string{vars["action"], vars["proto"], "--"}
line = append(line, vars["iface_in"], vars["iface_out"])
src_range := strings.Contains(vars["source"], "-")
if src_range {
line = append(line, "0.0.0.0/0")
} else {
source_32 := strings.Contains(vars["source"], "_32")
if source_32 {
line = append(line, strings.Replace(vars["source"], "_32", "", -1))
} else {
line = append(line, strings.Replace(vars["source"], "_", "/", -1))
}
}
dst_range := strings.Contains(vars["destination"], "-")
if dst_range {
line = append(line, "0.0.0.0/0")
} else {
destination_32 := strings.Contains(vars["destination"], "_32")
if destination_32 {
line = append(line, strings.Replace(vars["destination"], "_32", "", -1))
} else {
line = append(line, strings.Replace(vars["destination"], "_", "/", -1))
}
}
if src_range {
line = append(line, "source", "IP", "range", strings.Replace(vars["source"], "_32", "", -1))
}
if dst_range {
line = append(line, "destination", "IP", "range", strings.Replace(vars["destination"], "_32", "", -1))
}
if r.URL.Query().Get("sports") != "" {
line = append(line, "multiport", "sports", r.URL.Query().Get("sports"))
}
if r.URL.Query().Get("dports") != "" {
line = append(line, "multiport", "dports", r.URL.Query().Get("dports"))
}
if (r.URL.Query().Get("log-prefix") != "") && vars["action"] == "LOG" {
line = append(line, "LOG", "flags", "0", "level", "4", "prefix", strings.Join([]string{"\"", r.URL.Query().Get("log-prefix"), "\""}, ""))
}
ipt, err := iptables.New()
if err != nil {
return nil,err
}
args := []string{"-t", "raw", "-vnL", vars["chain"], "--line-numbers"}
if ipt.Wait() {
args = append(args, "--wait")
}
raws, err := ipt.ExecuteList(args)
if err != nil {
return nil,err
}
for i:= 0; i < len(raws); i++ {
rawsSlice := strings.Fields(raws[i])
rawsSliceNoVerb := rawsSlice[3:]
if reflect.DeepEqual(line, rawsSliceNoVerb) {
linenumber = append(linenumber, rawsSlice[0])
}
}
return linenumber,nil
}
// PUT /raw/{action}/{chain}/{proto}/{iface_in}/{iface_out}/{source}/{destination}/?sports=00&dports=00&tcpflag1=XYZ&tcpflag2=Y¬rack=true
func add_raw (w http.ResponseWriter, r *http.Request) {
if *htpasswdfile != "" {
htpasswd := auth.HtpasswdFileProvider(*htpasswdfile)
authenticator := auth.NewBasicAuthenticator("Basic Realm", htpasswd)
usercheck := authenticator.CheckAuth(r)
if usercheck == "" {
w.WriteHeader(http.StatusUnauthorized)
return
}
}
vars := mux.Vars(r)
ipt, err := iptables.New()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
rulespecs := raw_generate(r)
if ipt.Wait() {
rulespecs = append(rulespecs, "--wait")
}
if r.URL.Query().Get("position") != "" {
position, err := strconv.Atoi(r.URL.Query().Get("position"))
if err != nil {
http.Error(w, err.Error(), 500)
return
}
resp_err = ipt.Insert("raw", vars["chain"], position, rulespecs...)
} else {
resp_err = ipt.Append("raw", vars["chain"], rulespecs...)
}
if resp_err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, resp_err)
}
}
// DELTE /raw/{action}/{chain}/{proto}/{iface_in}/{iface_out}/{source}/{destination}/?sports=00&dports=00&tcpflag1=XYZ&tcpflag2=Y¬rack=true
func del_raw (w http.ResponseWriter, r *http.Request) {
if *htpasswdfile != "" {
htpasswd := auth.HtpasswdFileProvider(*htpasswdfile)
authenticator := auth.NewBasicAuthenticator("Basic Realm", htpasswd)
usercheck := authenticator.CheckAuth(r)
if usercheck == "" {
w.WriteHeader(http.StatusUnauthorized)
return
}
}
vars := mux.Vars(r)
ipt, err := iptables.New()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
rulespecs := raw_generate(r)
if ipt.Wait() {
rulespecs = append(rulespecs, "--wait")
}
resp_err = ipt.Delete("raw", vars["chain"], rulespecs...)
if resp_err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, resp_err)
}
}
// GET /raw/{action}/{chain}/{proto}/{iface_in}/{iface_out}/{source}/{destination}/?sports=00&dports=00&tcpflag1=XYZ&tcpflag2=Y¬rack=true
func check_raw (w http.ResponseWriter, r *http.Request) {
if *htpasswdfile != "" {
htpasswd := auth.HtpasswdFileProvider(*htpasswdfile)
authenticator := auth.NewBasicAuthenticator("Basic Realm", htpasswd)
usercheck := authenticator.CheckAuth(r)
if usercheck == "" {
w.WriteHeader(http.StatusUnauthorized)
return
}
}
ipt, err := iptables.New()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
rulespecs := raw_generate(r)
if ipt.Wait() {
rulespecs = append(rulespecs, "--wait")
}
if r.URL.Query().Get("position") != "" {
if r.URL.Query().Get("tcpflag1") != "" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, "tcpflag and position not compatible")
return
}
if r.URL.Query().Get("tcpflag2") != "" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, "tcpflag and position not compatible")
return
}
pos_raw, err := CheckPosRaw(r)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
if len(pos_raw) == 0 {
w.WriteHeader(http.StatusNotFound)
return
}
if len(pos_raw) != 1 {
w.WriteHeader(http.StatusConflict)
return
}
if pos_raw[0] == r.URL.Query().Get("position") {
return
} else {
w.WriteHeader(http.StatusNotFound)
return
}
} else {
vars := mux.Vars(r)
resp_str, resp_err := ipt.Exists("raw", vars["chain"], rulespecs...)
if resp_err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, resp_err)
return
}
if !resp_str {
w.WriteHeader(http.StatusNotFound)
return
}
}
}
// PUT /chain/{table}/{name}/
func add_chain (w http.ResponseWriter, r *http.Request) {
if *htpasswdfile != "" {
htpasswd := auth.HtpasswdFileProvider(*htpasswdfile)
authenticator := auth.NewBasicAuthenticator("Basic Realm", htpasswd)
usercheck := authenticator.CheckAuth(r)
if usercheck == "" {
w.WriteHeader(http.StatusUnauthorized)
return
}
}
vars := mux.Vars(r)
ipt, err := iptables.New()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
if ipt.Wait() {
resp_err = ipt.NewChainWithWait(vars["table"], vars["name"])
} else {
resp_err = ipt.NewChain(vars["table"], vars["name"])
}
if resp_err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, resp_err)
}
}
// DELETE /chain/{table}/{name}/
func del_chain (w http.ResponseWriter, r *http.Request) {
if *htpasswdfile != "" {
htpasswd := auth.HtpasswdFileProvider(*htpasswdfile)
authenticator := auth.NewBasicAuthenticator("Basic Realm", htpasswd)
usercheck := authenticator.CheckAuth(r)
if usercheck == "" {
w.WriteHeader(http.StatusUnauthorized)
return
}
}
vars := mux.Vars(r)
ipt, err := iptables.New()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
if ipt.Wait() {
// Clear chain before delete
resp_err = ipt.ClearChainWithWait(vars["table"], vars["name"])
if resp_err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, resp_err)
}
// Delete chain
resp_err = ipt.DeleteChainWithWait(vars["table"], vars["name"])
if resp_err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, resp_err)
}
} else {
// Clear chain before delete
resp_err = ipt.ClearChain(vars["table"], vars["name"])
if resp_err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, resp_err)
}
// Delete chain
resp_err = ipt.DeleteChain(vars["table"], vars["name"])
if resp_err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, resp_err)
}
}
}
// GET /chain/{table}/{name}/
func list_chain (w http.ResponseWriter, r *http.Request) {
if *htpasswdfile != "" {
htpasswd := auth.HtpasswdFileProvider(*htpasswdfile)
authenticator := auth.NewBasicAuthenticator("Basic Realm", htpasswd)
usercheck := authenticator.CheckAuth(r)
if usercheck == "" {
w.WriteHeader(http.StatusUnauthorized)
return
}
}
vars := mux.Vars(r)
ipt, err := iptables.New()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
if ipt.Wait() {
resp_str, resp_err := ipt.ListWithWait(vars["table"], vars["name"])
if resp_err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, resp_err)
}
for i:= 0; i < len(resp_str); i++ {
fmt.Fprintln(w, resp_str[i])
}
} else {
resp_str, resp_err := ipt.List(vars["table"], vars["name"])
if resp_err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, resp_err)
}
for i:= 0; i < len(resp_str); i++ {
fmt.Fprintln(w, resp_str[i])
}
}
}
// PUT /mvchain/{table}/{oldname}/{newname}/
func rename_chain (w http.ResponseWriter, r *http.Request) {
if *htpasswdfile != "" {
htpasswd := auth.HtpasswdFileProvider(*htpasswdfile)
authenticator := auth.NewBasicAuthenticator("Basic Realm", htpasswd)
usercheck := authenticator.CheckAuth(r)
if usercheck == "" {
w.WriteHeader(http.StatusUnauthorized)
return
}
}
vars := mux.Vars(r)
ipt, err := iptables.New()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
if ipt.Wait() {
resp_err = ipt.RenameChainWithWait(vars["table"], vars["oldname"], vars["newname"])
} else {
resp_err = ipt.RenameChain(vars["table"], vars["oldname"], vars["newname"])
}
if resp_err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintln(w, resp_err)
}
}
<file_sep>/api/iprouteRESt/Controller.go
package main
import (
"api/iproute2/manager"
"api/iproute2/model"
"encoding/json"
"fmt"
"github.com/olivere/elastic"
gelf "github.com/seatgeek/logrus-gelf-formatter"
"github.com/sirupsen/logrus"
"gopkg.in/sohlich/elogrus.v3"
"net/http"
"strconv"
"strings"
)
var log = logrus.New()
func init() {
log.Formatter = new(gelf.GelfFormatter)
log.Level = logrus.InfoLevel
}
// Homepage endpoint
func homePage(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "IPRoute2 controller!")
}
// CheckParams checks if some index of string array is empty.
func checkParams(params []string) bool {
for _, i := range params {
if i == "" {
return true
}
}
return false
}
// ModRoute provides creation and deletion route.
// Func is called on /iproutes/mod endpoint.
func modRoute(w http.ResponseWriter, r *http.Request) {
params := []string{r.URL.Query().Get("destination"),
r.URL.Query().Get("mask"), r.URL.Query().Get("interface")}
if checkParams(params) {
log.Error("Url Params are missing")
w.WriteHeader(http.StatusUnprocessableEntity)
return
}
route := model.Route{Destination: model.Network{params[0], 0}, InterfaceIP: params[2]}
route.Destination.Mask, _ = strconv.Atoi(params[1])
switch r.Method {
case http.MethodPut:
manager.CreateRouteWithIfIP(route)
log.WithFields(logrus.Fields{
"destination": route.Destination.IP,
"dest CIDR": route.Destination.Mask,
"Interface": route.InterfaceIP,
}).Info("Created new route!")
case http.MethodDelete:
manager.RemoveRoute(route)
log.WithFields(logrus.Fields{
"destination": route.Destination.IP,
"dest CIDR": route.Destination.Mask,
"Interface": route.InterfaceIP,
}).Info("Deleted route!")
default:
log.Error("Unsupported method!")
w.WriteHeader(404)
}
}
// ModDefaultRoute provides creation and deletion default route.
// Func is called on /iproutes/default endpoint.
func modDefaultRoute(w http.ResponseWriter, r *http.Request) {
params := []string{r.URL.Query().Get("interface")}
route := model.Route{InterfaceIP: params[0]}
log.Infof(route.InterfaceIP)
switch r.Method {
case http.MethodPut:
if checkParams(params) {
log.Error("Url Params are missing")
return
}
manager.CreateDefaultGateway(route)
log.WithFields(logrus.Fields{
"Interface": route.InterfaceIP,
}).Info("Created default route!")
case http.MethodDelete:
if checkParams(params) {
manager.RemoveDefaultGateway()
log.Info("Deleted default route")
} else {
manager.RemoveDefaultGatewayVia(route)
log.WithFields(logrus.Fields{
"Interface": route.InterfaceIP,
}).Info("Deleted default route!")
}
default:
log.Error("Unsupported method!")
w.WriteHeader(404)
}
}
// GetRoutes returns JSON array of routes in string
func getRoutes(w http.ResponseWriter, r *http.Request) {
routes := manager.GetRoutes()
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(routes))
}
// GetInterfaces returns JSON array of interfaces in string
func getInterfaces(w http.ResponseWriter, r *http.Request) {
interfaces := manager.GetInterfaces()
w.Header().Set("Content-Type", "application/json")
log.WithFields(logrus.Fields{
"test": "test",
}).Info("Returned Interfaces!")
w.Write([]byte(interfaces))
}
// SetElasticLog sets hook to elasticsearch server for logrus.
// Requires parameter elastic with value IPv4 address of elasticsearch server.
func setElasticLog(w http.ResponseWriter, r *http.Request) {
params := []string{r.URL.Query().Get("elastic")}
interfaces := []model.Interface{}
json.Unmarshal([]byte(manager.GetInterfaces()), interfaces)
var host string
for i := 0; i < len(interfaces); i++ {
if strings.Contains(interfaces[i].Name, "eth0") {
host = interfaces[i].IPAddress
} else {
host = "FAIL"
}
}
if checkParams(params) {
log.Error("Elastic Url is missing")
return
}
client, err := elastic.NewClient(elastic.SetURL("http://" + params[0]))
if err != nil {
log.Panic(err)
}
hook, err := elogrus.NewElasticHook(client, host, logrus.InfoLevel, "logs-home")
if err != nil {
log.Panic(err)
}
log.Hooks.Add(hook)
log.Info("Created hook to elastic log")
w.WriteHeader(200)
}
// HandleRequests provides endpoint handling.
func handleRequests() {
http.HandleFunc("/", homePage)
http.HandleFunc("/iproutes/mod", modRoute)
http.HandleFunc("/iproutes/default", modDefaultRoute)
http.HandleFunc("/iproutes", getRoutes)
http.HandleFunc("/interfaces", getInterfaces)
http.HandleFunc("/setLogHook", setElasticLog)
log.Fatal(http.ListenAndServe(":8090", nil))
}
func main() {
handleRequests()
}
<file_sep>/api/iproute2/manager/manager.go
// Package manager provides management of routing tables.
package manager
import (
"api/iproute2/model"
"bytes"
"encoding/json"
gelf "github.com/seatgeek/logrus-gelf-formatter"
"github.com/sirupsen/logrus"
"os"
"os/exec"
"strconv"
"strings"
)
const command = "ip"
var log = logrus.New()
func init() {
log.Formatter = new(gelf.GelfFormatter)
log.Level = logrus.InfoLevel
}
// CreateRouteWithIfIP prepares command to create route and executes it with ExecuteIPCommand func.
func CreateRouteWithIfIP(r model.Route) {
dest := r.Destination.IP + string("/") + strconv.Itoa(r.Destination.Mask)
args := []string{"route", "add", dest, "via", r.InterfaceIP}
cmdOut := ExecuteIPCommand(args)
log.Info(cmdOut)
}
// RemoveDefaultGateway prepares command to remove default route and executes it with ExecuteIPCommand func.
func RemoveDefaultGatewayVia(r model.Route) {
args := []string{"route", "delete", "default", "via", r.InterfaceIP}
cmdOut := ExecuteIPCommand(args)
log.Info(cmdOut)
}
func RemoveDefaultGateway() {
args := []string{"route", "delete", "default"}
cmdOut := ExecuteIPCommand(args)
log.Info(cmdOut)
}
// CreateDefaultGateway prepares command to create default route and executes it with ExecuteIPCommand func.
func CreateDefaultGateway(r model.Route) {
args := []string{"route", "add", "default", "via", r.InterfaceIP}
cmdOut := ExecuteIPCommand(args)
log.Info(cmdOut)
}
// RemoveRoute prepares command to remove route and executes it with ExecuteIPCommand func.
func RemoveRoute(r model.Route) {
dest := r.Destination.IP + string("/") + strconv.Itoa(r.Destination.Mask)
args := []string{"route", "delete", dest, "via", r.InterfaceIP}
cmdOut := ExecuteIPCommand(args)
log.Info(cmdOut)
}
// GetRoutes prepares command to list all routes and executes it with ExecuteIPCommand func.
// ExecuteIPCommand output is parsed via ParseStringRoutes func.
// Returns model/route array serialized into JSON in string.
func GetRoutes() (rts string) {
args := []string{"route", "show"}
cmdOut := ExecuteIPCommand(args)
s := ParseStringRoutes(cmdOut)
routes, err := json.Marshal(s)
if err != nil {
log.Error(err.Error())
return ""
}
return string(routes)
}
// ParseStringRoutes parses ExecuteIpCommand (ip route show) output to array of model/route.
// If route is default route,then only Destination and Interface attributes will be written,
// DestCIDR will be null.
// Returns array of model/route.
func ParseStringRoutes(cmdOutput string) (parsedRoutes []model.Route) {
singleRoutes := strings.Split(cmdOutput, "\n")
routes := []model.Route{}
for i := 0; i < (len(singleRoutes) - 1); i++ {
route := strings.Split(singleRoutes[i], " ")
var r = model.Route{}
for y := 0; y < len(route); y++ {
if y == 0 {
if route[y] == "default" {
r.Destination.IP = route[y]
} else {
destAndCidr := strings.Split(route[y], "/")
r.Destination.IP = destAndCidr[0]
r.Destination.Mask, _ = strconv.Atoi(destAndCidr[1])
}
}
if route[y] == "via" || route[y] == "src" {
r.InterfaceIP = route[y+1]
}
}
routes = append(routes, r)
}
return routes
}
// GetInterfaces prepares command to list all network interfaces and executes it with ExecuteIPCommand func.
// ExecuteIPCommand output is parsed via ParseIfs func.
// Returns model/interface array serialized into JSON, as string.
func GetInterfaces() (ifs string) {
args := []string{"addr", "show"}
cmdOut := ExecuteIPCommand(args)
ifsNames := ParseIfs(cmdOut)
interfaces, err := json.Marshal(ifsNames)
if err != nil {
log.Error(err.Error())
return ""
}
return string(interfaces)
}
// ParseIfs parses ExecuteIpCommand (ip addr show) output to array of model/route.
// Returns array of model/interface.
func ParseIfs(cmdOut string) (ifNames []model.Interface) {
ifsNames := []model.Interface{}
ifSlice := strings.Split(cmdOut, ": ")
x := 0
for i := 0; i < (len(ifSlice) - 1); i += 2 {
ifsNames = append(ifsNames, model.Interface{Name: ifSlice[i+1]})
s := strings.Split(ifSlice[i+2], " ")
for y := 0; y < len(s); y++ {
if s[y] == "inet" {
ip := strings.Split(s[y+1], "/")[0]
ifsNames[x].IPAddress = ip
x++
break
}
}
}
return ifsNames
}
// ExecuteIPCommand executes command with arguments.
// If command is executed successfully, then func returns
// command line output of command. If command is not executed successfully,
// then func returns actual error!
func ExecuteIPCommand(args []string) (cmdOut string) {
cmd := exec.Command(command, args...)
cmdOutput := &bytes.Buffer{}
var stderr bytes.Buffer
cmd.Stdout = cmdOutput
cmd.Stderr = &stderr
err := cmd.Run()
log.SetOutput(os.Stdout)
if err != nil {
switch err := err.(type) {
case *exec.ExitError:
log.WithFields(logrus.Fields{
"Error exited with user error: " : err.Error(),
"Stacktrace" : stderr.String()}).Error("Error ocurred!")
default:
log.WithFields(logrus.Fields{
"Error exited with API error: " : err.Error(),
"Stacktrace" : stderr.String()}).Error("Error ocurred!")
}
return err.Error()
}
return string(cmdOutput.Bytes())
}
<file_sep>/start_daemons
#!/bin/bash
# Bash script for starting all necessary daemons for app gateway
function stop_daemons() {
echo "Stopping daemons"
kill -TERM "$REST_PID"
kill -TERM "$API_PID"
}
if [ "$1" == '/api/iptables-api' ]; then
echo "Starting daemons"
trap 'stop_daemons' EXIT
/api/iprouteRESt &
export REST_PID=$!
exec "$@" &
export API_PID=$!
wait $API_PID
else
exec "$@"
fi
<file_sep>/README.md
# PatrIoT_router
This repository is used to build docker image of router.
Router is used in network-simulator to control network communication.
Router image has to be built before starting network generator.
Network generator uses image tag to create router containers.
## Parts
<ul>
<li>iptables-api</li>
<li>iproute2-api</li>
<li>iproute2-rest</li>
</ul>
### IPTables
Iptables api written in golang is used to communicate with linux ip tables.
Api is used to filter communication, NAT, ... <br>
This api is forked from: https://github.com/Oxalide/iptables-api
### IPRoute2
IPRoute2 api written in golang is used to control routing tables
using iproute2 commands. Api supports:
<ul>
<li>Default routes creationg and modification</li>
<li>Routes creation and modification</li>
<li>List interfaces</li>
<li>List routes</li>
</ul>
### IPRoute2 REST API
IProute2 REST is used by network simulator api to remotely
control routes on routers. API is written in golang, using http package.
## Build
```docker build ./```
<file_sep>/api/iproute2/model/network.go
package model
type Network struct {
IP string
Mask int
}
| edcb3d50ef2d822ae9938afd7eb3dc325f649a6e | [
"Markdown",
"Go",
"Dockerfile",
"Shell"
] | 11 | Go | obabec/PatrIoT_router | 5a211f9d74d09ab7962c11778cd57622fdb99909 | 5f0ca2358254b7f1c006e63d8a0b191f79324127 |
refs/heads/master | <repo_name>sunitha03-hue/ArrayExercises06<file_sep>/index.js
//Arrays can hold different data types, even other arrays! A multi-dimensional array is one with entries that are themselves arrays.
//a) Define and initialize the arrays specified in the exercise to hold the name, chemical symbol and mass for different elements.
let element1 = ['hydrogen', 'H', 1.008];
let element2 = ['helium', 'He', 4.003];
let element26 = ['iron', 'Fe', 55.85];
//b) Define the array 'table', and use 'push' to add each of the element arrays to it. Print 'table' to see its structure.
let table=[];
table.push(element1,element2,element26);
console.log(table);
//c) Use bracket notation to examine the difference between printing 'table' with one index vs. two indices (table[][]).
console.log("***********");
console.log(table[1]);
console.log(table[1][1]);
//d) Using bracket notation and the table array, print the mass of element1, the name for element 2 and the symbol for element26.
console.log("***********");
console.log(table[0][2]);
console.log(table[1][0]);
console.log(table[2][1]);
//e) 'table' is an example of a 2-dimensional array. The first “level” contains the element arrays, and the second level holds the name/symbol/mass values. Experiment! Create a 3-dimensional array and print out one entry from each level in the array.
console.log("***********");
element1.push('element1');
element2.push('element2');
element26.push('element26');
let element4=['nitrogen', 'N2', 14.01];
element4.push('element7')
table.push(element4);
console.log("The symbol for Hydrogen is:", table[0][1]);
console.log("The mass for Iron is:", table[1][2]);
console.log("The element for Iron is:", table[2][3]);
console.log("The name for element 7 is:", table[3][0]);
console.log("***********"); | c6163c6391c67531acae9b351ebc7ec93a794418 | [
"JavaScript"
] | 1 | JavaScript | sunitha03-hue/ArrayExercises06 | 9b8f63ddcceec506cdc015722aab622f7727a20b | 4ba73cec1d85e77141dfcdaab4a7a28f4a1e51fe |
refs/heads/main | <file_sep>#include "Adafruit_Sensor.h"
#include "Adafruit_AM2320.h"
#include "cxm1500geInterface.h"
#include <stdio.h>
#include "generatePayload_am2320.h"
cxm1500geInterface *eltres;
Adafruit_AM2320 am2320 = Adafruit_AM2320();
float tempTemperature;
float tempHum;
byte flagReadySend = 0;
class myEltresCallback : public cxm1500geCallback
{
void onGPSconnected()
{
Serial.println("---GPS connected---");
flagReadySend = 1;
};
/*the SetDataSend function edit-able, but the structure of function can't edit*/
void onSetDataSend(char *dataWillSend, CXM1500GENMEAGGAInfo *GGAInfo, byte japanCorrection)
{
tempHum = am2320.readHumidity();
tempTemperature = am2320.readTemperature();
Serial.print("Temperature: ");
Serial.print(tempTemperature);
Serial.println(" degrees C");
Serial.print("Relative Humidity: ");
Serial.print(tempHum);
Serial.println(" %");
tempHum *= 10;
tempTemperature *= 10;
}
int16_t hum = (int16_t) tempHum;
int16_t temperature = (int16_t) tempTemperature;
byte typePayload = 9;
byte classService = 0;
byte coin;
getDataWillSend(dataWillSend, GGAInfo, japanCorrection, typePayload, classService, hum, temperature, coin);
};
};
char version[6];
char resp[100];
void setup()
{
/* This part is belongs to ELTRES Library
* do not modify it.
*/
Serial.begin(115200);
am2320.begin();
eltres = new cxm1500geInterface(1, "10"); // can remove reboot 24 hours. example eltres = new cxm1500geInterface(1); -> this main variable timeReboot is NULL
eltres->setCallback(new myEltresCallback); // this function must call to set callback class
eltres->getVersion(version);
Serial.print(F("Library's version = "));
Serial.print(version);
Serial.print("\n");
eltres->init();
eltres->setStateEvent(1);
/* --end of ELTRES Library */
}
byte test = 0;
void loop()
{
if (flagReadySend == 1)
{
eltres->send(); // This function to send payload if GPS ready, the payload was setting on onSetDataSend function.
eltres->sleepCxm(80000, 100000);
delay(10);
}
else
{
eltres->checkSYSEvent();
}
/*
86400000 milliseconds in a day
3600000 milliseconds in an hour
60000 milliseconds in a minute
1000 milliseconds in a second
*/
eltres->rebootInterval(1800000); // 30min Reboot for speed check. if no-reboot interval, can remove this function
/* note : if reboot interval active in log appear message "--- Reboot Interval "
but reboot 24 hours base UTC active in log appear message "--- Reboot 24 Hours Time ---"
and reboot also can reboot-interval only.
*/
}
<file_sep>#pragma once
#include "cxm1500geInterface.h"
void getDataWillSend(char* payload_data, CXM1500GENMEAGGAInfo* g_nmea_gga_info_buf, byte flagJapanCorrection = 0,uint8_t payload_Type = 9, uint8_t class_Service = 0,int16_t hum = 0, int16_t temper = 0, uint8_t coins = 0){
memset(payload_data,0xFF,16);
int8_t coin;
memset(coin, '\0', sizeof(coin));
memcpy(coin, &coins, sizeof(coins));
int8_t humidity[2];
memset(humidity, '\0', sizeof(humidity));
memcpy(humidity, &hum, sizeof(hum));
int8_t temperature[2];
memset(temperature, '\0', sizeof(temperature));
memcpy(temperature, &temper, sizeof(temper));
payload_data[15-2] &= (((coin & 0xFF) << 2) | ~0x04); //1bit
payload_data[15-2] &= (((humidity[0] & 0xFF) << 3) | ~0xF8); //5bits
payload_data[15-3] &= (((humidity[0] & 0xFF) >> 5) | ~0x07); //3bits
payload_data[15-3] &= (((humidity[1] & 0xFF) << 3) | ~0x18); //2bits = 10 bits
payload_data[15-3] &= (((temperature[0] & 0xFF) << 5) | ~0xE0); //3bits
payload_data[15-4] &= (((temperature[0] & 0xFF) >> 3) | ~0x1F); //5bits
payload_data[15-4] &= (((temperature[1] & 0xFF) << 5) | ~0xE0); //3bits
payload_data[15-5] &= (((temperature[1] & 0xFF) >> 3) | ~0x1F); //5bits = 16bits
payload_data[15-5] &= (((g_nmea_gga_info_buf->m_pos_status & 0xFF) << 5) | ~0x20); //2bit
int count_satelit = g_nmea_gga_info_buf->m_sat_used;
if(count_satelit > 7) {
count_satelit = 7;
}
payload_data[15-5] &= (((count_satelit & 0xFF) << 7) | ~0x80); //1bit
payload_data[15-6] &= (((count_satelit & 0xFF) >> 1) | ~0x03); //2bits = 3bits
uint8_t src[11];
memset(src, '\0', sizeof(src));
strncpy((char*)&src, (char*)g_nmea_gga_info_buf->m_lon, 10);
uint8_t lon_deg[4];
memset(lon_deg, '\0', sizeof(lon_deg));
strncpy((char*)&lon_deg, (char*)&src, 3 );
uint32_t lon_deg_unit = atoi((char*)lon_deg);
uint32_t lon_int = lon_deg_unit * 10000;
uint8_t lon_mm[3];
memset(lon_mm, '\0', sizeof(lon_mm));
uint8_t lon_ss[5];
memset(lon_ss, '\0', sizeof(lon_mm));
strncpy((char*)lon_mm, (char*)&src[3], 2);
strncpy((char*)lon_ss, (char*)&src[6], 4);
uint32_t lon_mm_unit = atoi((char*)lon_mm);
uint32_t lon_ss_unit = atoi((char*)lon_ss);
lon_mm_unit = (lon_mm_unit *10000)/60;
lon_ss_unit = lon_ss_unit / 60;
lon_int = lon_int + lon_mm_unit + lon_ss_unit;
memset(src, '\0', sizeof(src));
strncpy((char*)&src, (char*)g_nmea_gga_info_buf->m_lat, 10);
uint8_t lat_deg[3];
memset(lat_deg, '\0', sizeof(lat_deg));
strncpy((char*)&lat_deg, (char*)&src, 2 );
uint32_t lat_deg_unit = atoi((char*)lat_deg);
uint32_t lat_int = lat_deg_unit * 10000;
uint8_t lat_mm[3];
memset(lat_mm, '\0', sizeof(lat_mm));
uint8_t lat_ss[5];
memset(lat_ss, '\0', sizeof(lat_ss));
strncpy((char*)&lat_mm, (char*)&src[2], 2);
strncpy((char*)&lat_ss, (char*)&src[5], 4);
uint32_t lat_mm_unit = atoi((char*)lat_mm);
uint32_t lat_ss_unit = atoi((char*)lat_ss);
lat_mm_unit = (lat_mm_unit * 10000)/60;
lat_ss_unit = lat_ss_unit / 60;
lat_int = lat_int + lat_mm_unit + lat_ss_unit;
//Serial.println(lat_int);
if (flagJapanCorrection == 1){
if (((lat_int > 864000)&&(lat_int<1044000))&&((lon_int>4410000)&&(lon_int<4752000))){
lat_int += (864000-1535080);
lon_int += (4410000-4608000);
}
}
uint8_t longitude[4];
memset(longitude, '\0', sizeof(longitude));
memcpy(longitude, &lon_int, sizeof(lon_int));
payload_data[15-6] &= (((longitude[0] & 0xFF) << 2) | ~0xFC); //6bits
payload_data[15-7] &= (((longitude[0] & 0xFF) >> 6) | ~0x03); //2bits
payload_data[15-7] &= (((longitude[1] & 0xFF) >> 2) | ~0xFC); //6bits
payload_data[15-8] &= (((longitude[1] & 0xFF) >> 6) | ~0x03); //2bits
payload_data[15-8] &= (((longitude[2] & 0xFF) << 2) | ~0x7C); //5bits = 21bits
uint8_t latitude[4];
memset(latitude, '\0', sizeof(latitude));
memcpy(latitude, &lat_int, sizeof(lat_int));
payload_data[15-8] &= (((latitude[0] & 0xFF) << 7) | ~0x80); //1bit
payload_data[15-9] &= (((latitude[0] & 0xFF) >> 1) | ~0x7F); //7bits
payload_data[15-9] &= (((latitude[1] & 0xFF) << 7) | ~0x80); //1bit
payload_data[15-10] &= (((latitude[1] & 0xFF) >> 1) | ~0x7F); //7bits
payload_data[15-10] &= (((latitude[2] & 0xFF) << 7) | ~0x80); //1bit
payload_data[15-11] &= (((latitude[2] & 0xFF) >> 1) | ~0x0F); //4bits = 21bits
memset(src, '/0', sizeof(src));
strncpy((char*)&src, (char*)g_nmea_gga_info_buf->m_utc, 9);
uint8_t utc_temp[3];
memset(utc_temp, '\0', sizeof(utc_temp));
strncpy((char*)&utc_temp, (char*)&src[0], 2);
uint8_t utc_hh_unit = atoi((char*)&utc_temp);
memset(utc_temp, '\0', sizeof(utc_temp));
strncpy((char*)&utc_temp, (char*)&src[2], 2);
uint8_t utc_mm_unit = atoi((char*)&utc_temp);
memset(utc_temp, '\0', sizeof(utc_temp));
strncpy((char*)&utc_temp, (char*)&src[4], 2);
int utc_ss_unit = atoi((char*)&utc_temp);
uint8_t utcSS[4];
memset(utcSS, '\0', sizeof(utcSS));
memcpy(utcSS, &utc_ss_unit, sizeof(utc_ss_unit));
payload_data[15-11] &= (((utcSS[0] & 0xFF) << 4) | ~0xF0); //4bits
payload_data[15-12] &= (((utcSS[0] & 0xFF) >> 4) | ~0x03); //2bits
payload_data[15-12] &= (((utc_mm_unit & 0xFF) << 2) | ~0xFC); //6bits
payload_data[15-13] &= (((utc_hh_unit & 0xFF)) | ~0x1F); //5bits = 17bits
Fixed hdop = 0;
hdop = FLOAT2FIXED(g_nmea_gga_info_buf->m_hdop);
uint8_t hdop_8[2];
memset(hdop_8, '\0', sizeof(hdop_8));
memcpy(hdop_8, &hdop, sizeof(hdop));
payload_data[15-13] &= (((hdop_8[0] & 0xFF) << 5) | ~0xE0); //3bits
payload_data[15-14] &= (((payload_Type & 0xFF) | ~0x0F)); //4bits
payload_data[15-15] &= (((class_Service & 0xFF) << 5) | ~0xE0);//3bits = 7bits + 9bits reserved = 16bits
}
| 93607657529254e56f175895ee6192a1206f313c | [
"C",
"C++"
] | 2 | C++ | sahabatsatwa/AM2320Mega | 3055237eb8845c6758c23623f81b64dd7170cf65 | 4aee8bd2773355ac0beaa90250f9f7880c8b550e |
refs/heads/master | <file_sep>RegisterServerEvent("announce")
AddEventHandler("announce", function(param)
if IsPlayerAceAllowed(source, "administrator") then
print("[^1Announcement^7]" .. param)
TriggerClientEvent("chatMessage", -1, "^7[^4---------^1Announcement^5---------^7]", {0,0,0}, param)
else
TriggerClientEvent("no-perms", source)
end
end) | cf7e291e989605e0c89f0af774d8117c535fde10 | [
"Lua"
] | 1 | Lua | LeanBcdojrp/Whitelist-Announcement-Script | b4d2d2ea4eede6129efa0116af752df3a3e64dd1 | a579c90d69b9ee8cecf50c7e2e959c50d5d219ca |
refs/heads/master | <repo_name>bariscr/deneme<file_sep>/server.R
shinyServer <- function(input, output, session) {
output$approvalBox <- renderInfoBox({
infoBox(
title = "Number of Total Cases",
value = tags$p(covid_data$total_cases[covid_data$location == input$country_select_tab1 & covid_data$date == input$date_tab1],
style = "font-size: 40px; color:white"),
icon = icon("asterisk", lib = "glyphicon"),
fill = TRUE,
color = "yellow"
)
})
output$approvalBox2 <- renderInfoBox({
infoBox(
"Number of Total Deaths",
value = tags$p(covid_data$total_deaths[covid_data$location == input$country_select_tab1 & covid_data$date == input$date_tab1],
style = "font-size: 40px; color:white"),
icon = icon("warning-sign", lib = "glyphicon"),
fill = TRUE,
color = "black"
)
})
data_tab1 <- reactive({
covid_data %>% filter(location == input$country_select_tab1, date == input$date_tab1)
})
output$approvalBox3 <- renderInfoBox({
infoBox(
"Death Rate (%)",
value = tags$p(round(data_tab1()$total_deaths / data_tab1()$total_cases * 100, 1), style = "font-size: 40px; color: white"),
icon = icon("battery-0"),
fill = TRUE,
color = "red"
)
})
data <- reactive({
covid_data %>% filter(location == input$country1 | location == input$country2, date >= input$daterange[1], date <= input$daterange[2])
})
output$tablo <- renderTable({
brushedPoints(data(), input$click, yvar = input$variable)
})
output$graph <- renderPlot({
ggplot(data(), aes(x = date, y = .data[[input$variable]], color = location)) + geom_point() +
scale_x_date(breaks = date_breaks("month")) +
scale_y_continuous(breaks = seq(min(data()[input$variable]), max(data()[input$variable]), round(max(data()[input$variable])/10, 0))) +
scale_color_manual(name = "Countries", labels = sort(c(input$country1, input$country2)), values = c("green", "turquoise3")) +
labs(title = paste0("'",input$variable, "' Comparison between ", input$country1, " & ", input$country2), x = "Date") +
dark_theme_minimal() +
theme(axis.text.x = element_text(angle = -45, color = "red4"),
plot.title = element_text(face = "bold", size = 14, color = "red4", hjust = 0.5),
legend.text = element_text(size = 12),
legend.title = element_text(size = 12, color = "red4"),
axis.text.y = element_text(size = 12, color = "red4"),
)
})
data_alone <- reactive({
covid_data %>% filter(location == input$country_alone, date >= input$daterange_alone[1], date <= input$daterange_alone[2])
})
output$plot_alone <- renderPlot(
{
req(input$variable_compare)
p <- ggplot(data_alone(), aes(x = date))
renk <- 0
vars_alone <- "a"
for (aa in 1:length(input$variable_compare)) {
renk <- renk + 2
p <- p + geom_point(aes(y = .data[[input$variable_compare[aa]]]), color = renk)
vars_alone <- paste0(vars_alone, input$variable_compare[aa])
print(vars_alone)
}
p <- p +
labs(title = paste0(" variables in ", vars_alone, input$country_alone), x = "Date", y = "") +
theme_economist() +
theme(axis.text.x = element_text(angle = -45, color = "red4"),
plot.title = element_text(face = "bold", size = 14, color = "yellow", hjust = 0.5),
axis.text.y = element_text(size = 12, color = "red4")
)
p
})
# TOP 10 sekmesinde kullanılacak veri setinin oluşturulması
sirali <- reactive({
sirali <- covid_data[, c("location", "date", input$top_10)] %>% filter(location != "World", date == input$top_10_date)
sirali <- arrange(sirali, desc(.data[[input$top_10]])) %>% head(10)
sirali <- sirali[, c(1, 3)]
})
# İlk 10 sıranın tablo gösterimi
output$top_10_table <- renderTable({
sirali()
})
# İlk 10 sıranın grafik gösterimi
output$top_10_graph <- renderPlot(height = 900,
{
ggplot(sirali(), aes(x = reorder(location, .data[[input$top_10]]), y = .data[[input$top_10]], fill = location)) +
geom_bar(show.legend = FALSE, stat = "identity") + coord_flip() +
theme_solarized() +
labs(title = paste0("TOP 10 Countries (", input$top_10, ")"), x = "", y = "") +
theme(axis.text.x = element_text(angle = -45, color = "red4"),
plot.title = element_text(face = "bold", size = 14, color = "red4", hjust = 0.5),
axis.text.y = element_text(size = 12, color = "red4")
)
})
}
<file_sep>/README.md
# deneme
Deneme çalışmaları yer alacak.<file_sep>/code/deneme.R
# load data ----
load("covid_data_26072020.Rdata")
<file_sep>/code/variable_list.R
# variable list
total_cases", "new_cases","total_deaths", "new_deaths",
"total_cases_per_million", "new_cases_per_million",
"total_deaths_per_million", "new_deaths_per_million",
"new_tests", "total_tests", "total_tests_per_thousand", "new_tests_per_thousand"
"new_tests_smoothed", "new_tests_smoothed_per_thousand",
"tests_units",
"stringency_index", "population", "population_density",
"median_age", "aged_65_older", "aged_70_older",
"extreme_poverty", "cardiovasc_death_rate",
"diabetes_prevalence", "female_smokers",
"male_smokers", "handwashing_facilities",
"hospital_beds_per_thousand", "life_expectancy" <file_sep>/R/load-lib-and-data.R
library(shiny)
library(shinydashboard)
library(ggplot2)
library(dplyr)
library(rio)
library(scales)
library(purrr)
library(bubblyr)
library(ggdark)
library(ggthemes)
covid_data <- rio::import('https://github.com/owid/covid-19-data/raw/master/public/data/owid-covid-data.xlsx',
col_types = c("text", "text", "text",
"text", "numeric", "numeric", "numeric",
"numeric", "numeric", "numeric",
"numeric", "numeric", "numeric",
"numeric", "numeric", "numeric",
"numeric", "numeric", "numeric", "numeric",
"text", "numeric", "numeric",
"numeric", "numeric", "numeric",
"numeric", "numeric", "numeric",
"numeric", "numeric", "numeric",
"numeric", "numeric", "numeric", "numeric"))
covid_data$date <- as.Date(covid_data$date)
<file_sep>/ui.R
shinyUI <- dashboardPage(
skin = "purple",
dashboardHeader(title = "COVID-19 Dashboard"),
dashboardSidebar(sidebarMenu(
menuItem("Country COVID-19 Profile", tabName = "tab_1", icon = icon("heart")),
menuItem("Name this also", tabName = "tab_2", icon = icon("file-alt")),
menuItem("Name this also2", tabName = "tab_3", icon = icon("file-alt")),
menuItem("TOP 10", tabName = "tab_4", icon = icon("sort-amount-up"))
)),
# dashboard start ----
dashboardBody(tabItems(
# tab 1----
tabItem("tab_1",
fluidPage(
selectInput("country_select_tab1", "Select Country", choices = unique(covid_data$location)),
dateInput("date_tab1", "Select a Date", value = Sys.Date()),
fluidRow(infoBoxOutput("approvalBox", width = 4),
infoBoxOutput("approvalBox2", width = 4),
infoBoxOutput("approvalBox3", width = 4))
)
),
tabItem("tab_2",
fluidPage(
h1("COVID COMPARISON"),
selectInput("country1", "Select country 1", choices = unique(covid_data$location)),
selectInput("country2", "Select country 2", choices = unique(covid_data$location)),
selectInput("variable", "Select a variable to compare",
choices = c("Total Cases" = "total_cases", "New Cases" = "new_cases",
"Total Deaths" = "total_deaths", "New Deaths" = "new_deaths",
"Total Cases per Million" = "total_cases_per_million",
"New cases Per Million" = "new_cases_per_million",
"Total Deaths per Million" = "total_deaths_per_million",
"New Deaths per Million" = "new_deaths_per_million")),
dateRangeInput("daterange", "Select a date range", start = "2019-12-31", end = Sys.Date()),
tableOutput("tablo"),
mainPanel({
plotOutput("graph", brush = "click")
})
)),
tabItem("tab_3",
fluidPage(
selectInput("country_alone", "Select country", choices = unique(covid_data$location)),
selectInput("variable_compare", "Select variables to compare", choices = c("Total Cases" = "total_cases", "New Cases" = "new_cases",
"Total Deaths" = "total_deaths", "New Deaths" = "new_deaths",
"Total Cases per Million" = "total_cases_per_million",
"New cases Per Million" = "new_cases_per_million",
"Total Deaths per Million" = "total_deaths_per_million",
"New Deaths per Million" = "new_deaths_per_million"), multiple = TRUE),
dateRangeInput("daterange_alone", "Select a date range", start = "2019-12-31", end = Sys.Date()),
plotOutput("plot_alone")
)),
tabItem("tab_4",
fluidPage(column(width = 6, height = "1630px",
selectInput("top_10", "Select a variable", choices = c("Total Cases" = "total_cases", "New Cases" = "new_cases",
"Total Deaths" = "total_deaths", "New Deaths" = "new_deaths",
"Total Cases per Million" = "total_cases_per_million",
"New cases Per Million" = "new_cases_per_million",
"Total Deaths per Million" = "total_deaths_per_million",
"New Deaths per Million" = "new_deaths_per_million")),
dateInput("top_10_date", "Select a date", value = Sys.Date()),
plotOutput("top_10_graph")
)
))
)))
<file_sep>/code/import_data.R
# import data ----
library(readxl)
covid_data_26072020 <- read_excel("covid_data.xlsx",
col_types = c("text", "text", "text",
"text", "numeric", "numeric", "numeric",
"numeric", "numeric", "numeric",
"numeric", "numeric", "numeric",
"numeric", "numeric", "numeric",
"numeric", "numeric", "text", "numeric",
"numeric", "numeric", "numeric",
"numeric", "numeric", "numeric",
"numeric", "numeric", "numeric",
"numeric", "numeric", "numeric",
"numeric", "numeric"))
# save data ----
save(covid_data_26072020, file = "covid_data_26072020.Rdata")
<file_sep>/code/compare_2_countries.R
library(shiny)
library(shinydashboard)
library(ggplot2)
library(dplyr)
library(rio)
library(scales)
library(purrr)
# load data ----
covid_data <- rio::import('https://github.com/owid/covid-19-data/raw/master/public/data/owid-covid-data.xlsx',
col_types = c("text", "text", "text",
"text", "numeric", "numeric", "numeric",
"numeric", "numeric", "numeric",
"numeric", "numeric", "numeric",
"numeric", "numeric", "numeric",
"numeric", "numeric", "text", "numeric",
"numeric", "numeric", "numeric",
"numeric", "numeric", "numeric",
"numeric", "numeric", "numeric",
"numeric", "numeric", "numeric",
"numeric", "numeric"))
covid_data$date <- as.Date(covid_data$date)
ui <- dashboardPage(
skin = "purple",
dashboardHeader(title = "COVID-19 Dashboard"),
dashboardSidebar(sidebarMenu(
menuItem("Country COVID-19 Profile", tabName = "tab_1", icon = icon("heart")),
menuItem("Name this also", tabName = "tab_2", icon = icon("file-alt")),
menuItem("Name this also2", tabName = "tab_3", icon = icon("file-alt"))
)),
# dashboard start ----
dashboardBody(tabItems(
# tab 1----
tabItem("tab_1",
fluidRow(
selectInput("country_select_tab1", "Select Country", choices = unique(covid_data$location)),
dateInput("date_tab1", "Select a Date", value = Sys.Date()),
infoBoxOutput("approvalBox"),
infoBoxOutput("approvalBox2")
)),
tabItem("tab_2",
fluidPage(
h1("COVID COMPARISON"),
selectInput("country1", "Select country 1", choices = unique(covid_data$location)),
selectInput("country2", "Select country 2", choices = unique(covid_data$location)),
selectInput("variable", "Select a variable to compare",
choices = c("Total Cases" = "total_cases", "New Cases" = "new_cases",
"Total Deaths" = "total_deaths", "New Deaths" = "new_deaths",
"Total Cases per Million" = "total_cases_per_million",
"New cases Per Million" = "new_cases_per_million",
"Total Deaths per Million" = "total_deaths_per_million",
"New Deaths per Million" = "new_deaths_per_million")),
dateRangeInput("daterange", "Select a date range", start = "2019-12-31", end = Sys.Date()),
tableOutput("tablo"),
mainPanel({
plotOutput("graph", brush = "click")
})
)),
tabItem("tab_3",
fluidPage(
selectInput("country_alone", "Select country", choices = unique(covid_data$location)),
selectInput("variable_compare", "Select variables to compare", choices = c("Total Cases" = "total_cases", "New Cases" = "new_cases",
"Total Deaths" = "total_deaths", "New Deaths" = "new_deaths",
"Total Cases per Million" = "total_cases_per_million",
"New cases Per Million" = "new_cases_per_million",
"Total Deaths per Million" = "total_deaths_per_million",
"New Deaths per Million" = "new_deaths_per_million"), multiple = TRUE),
dateRangeInput("daterange_alone", "Select a date range", start = "2019-12-31", end = Sys.Date()),
plotOutput("plot_alone")
))
)))
server <- function(input, output) {
output$approvalBox <- renderInfoBox({
infoBox(
"Number of Cases",
covid_data$total_cases[covid_data$location == input$country_select_tab1 & covid_data$date == input$date_tab1],
icon = icon("asterisk", lib = "glyphicon"),
color = "yellow"
)
})
output$approvalBox2 <- renderInfoBox({
infoBox(
"Number of Deaths",
covid_data$total_deaths[covid_data$location == input$country_select_tab1 & covid_data$date == input$date_tab1],
icon = icon("warning-sign", lib = "glyphicon"),
color = "black"
)
})
data <- reactive({
covid_data %>% filter(location == input$country1 | location == input$country2, date >= input$daterange[1], date <= input$daterange[2])
})
output$tablo <- renderTable({
brushedPoints(data(), input$click, yvar = input$variable)
})
output$graph <- renderPlot({
ggplot(data(), aes(x = date, y = .data[[input$variable]], color = location)) + geom_point() +
scale_x_date(breaks = date_breaks("month")) +
theme(axis.text.x = element_text(angle = -90))
})
data_alone <- reactive({
covid_data %>% filter(location == input$country_alone, date >= input$daterange_alone[1], date <= input$daterange_alone[2])
})
output$plot_alone <- renderPlot({
req(input$variable_compare)
p <- ggplot(data_alone(), aes(x = date))
renk <- 0
for (aa in 1:length(input$variable_compare)) {
renk <- renk + 1
p <- p + geom_point(aes(y = .data[[input$variable_compare[aa]]]), color = renk)
}
p
})
}
shinyApp(ui, server)
| 9da424be2fb335faa09d3af9ab80bff77875779a | [
"Markdown",
"R"
] | 8 | R | bariscr/deneme | 4e6929fc8283a27fe3d3327937da8708b9bbb08a | 17820051dc68af703f45369108ea39f0e1b3a03f |
refs/heads/master | <file_sep>{ooer is:an('experimental')}[tech]support.forum{founded on:the('philosophy')}[that]everyone.has{something that:they('can')}[contribute].
<file_sep>from discord.ext import commands
from utils import Crombed, chance, is_mention, extract_id, random_string
from garlic_functions import (generate_scream, generate_screech, ProbDist,
string_to_bf, run_bf, ooojoy, generate_gibberish)
import usernumber
import random
import json
import zlib
import base64
import requests
import os
from pyimgur import Imgur
imgur = Imgur(os.environ["IMGUR_CLIENT_ID"])
REPLY_CHAIN_LENGTH = int(os.environ["REPLY_CHAIN_LENGTH"])
class GarlicCommands(commands.Cog):
""" Commands made by garlicOS®! """
def __init__(self, bot):
self.bot = bot
@commands.command(aliases=["aaa"])
async def scream(self, ctx: commands.Context):
""" AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA """
await ctx.send(generate_scream())
@commands.command(aliases=["eee", "ree"])
async def screech(self, ctx: commands.Context):
""" EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE """
await ctx.send(generate_screech())
@commands.command(aliases=["meow", "nyan", "kitty", "kitten", "feline"])
async def cat(self, ctx: commands.Context):
""" Generate a cat from thiscatdoesnotexist.com. """
url = f"https://thiscatdoesnotexist.com/?{random_string(32)}"
embed = Crombed(
title = "Cat",
author = ctx.author
).set_image(url=url)
await ctx.send(embed=embed)
""" This code causes an error on thispersondoesnotexist's end.
If you know what I can do to fix this, please tell me """
# @commands.command(aliases=["face", "facereveal", "human"])
# async def person(self, ctx: commands.Context):
# """ Generate a face from thispersondoesnotexist.com. """
# url = f"https://thispersondoesnotexist.com/image?{random_string(32)}"
# # This one does not seem to play nice with Discord like the other two do,
# # so it requires a little finangling to get it to work.
# response = requests.get(url, stream = True)
# img = BytesIO(response.content)
# embed = Crombed(
# title = "Person",
# author = ctx.author,
# file = discord.File(img, filename="image.jpg")
# )
# await ctx.send(embed=embed)
@commands.command()
async def horse(self, ctx: commands.Context):
""" Generate a horse from thishorsedoesnotexist.com/.com. """
url = f"https://thishorsedoesnotexist.com/?{random_string(32)}"
embed = Crombed(
title = "Horse",
author = ctx.author
).set_image(url=url)
await ctx.send(embed=embed)
@commands.command(aliases=["source", "github"])
async def code(self, ctx: commands.Context):
""" Look at cromgis's code! """
embed = Crombed(
title = "Source code",
description = "cromgis is an open-source bot made by the /r/Ooer hivemind. See its code here:\nhttps://github.com/kaylynn234/Ooer-Discord-Bot"
)
await ctx.send(embed=embed)
@commands.command(aliases=["ev"])
async def expectedValue(self, ctx: commands.Context, *, json_data: str):
""" Calculate the expected value of a probability distribution. """
try:
probabilities = json.loads(json_data)
except json.decoder.JSONDecodeError:
return await ctx.send("Syntax error")
prob_dist = ProbDist(probabilities)
embed = Crombed(
title = "Expected value",
description = str(prob_dist.expected_value)
)
await ctx.send(embed=embed)
@commands.command(aliases=["sd"])
async def standardDeviation(self, ctx: commands.Context, *, json_data: str):
""" Calculate the standard deviation of a probability distribution. """
try:
probabilities = json.loads(json_data)
except json.decoder.JSONDecodeError:
return await ctx.send("Syntax error")
prob_dist = ProbDist(probabilities)
embed = Crombed(
title = "Standard deviation",
description = str(prob_dist.standard_deviation)
)
await ctx.send(embed=embed)
@commands.command(aliases=["bf"])
async def executeBF(self, ctx: commands.Context, *, data: str):
""" Execute and print the output of a BF program. """
program_out = run_bf
embed = Crombed(
title = "Brainfuck output",
description = program_out
)
await ctx.send(embed=embed)
@commands.command()
async def text2bf(self, ctx: commands.Context, *, text: str):
""" Make a BF program that outputs the given text. """
bf_program = string_to_bf(text)
embed = Crombed(
title = "Brainfuck program",
description = bf_program
)
await ctx.send(embed=embed)
@commands.command()
async def compress(self, ctx: commands.Context, *, data: str):
""" Compress data with zlib (compression level 9). """
compressed_data = zlib.compress(bytes(data, "utf-8"), 9)
b64_text = base64.b64encode(compressed_data).decode("utf-8")
embed = Crombed(
title = "Compressed data",
description = b64_text
)
await ctx.send(embed=embed)
@commands.command()
async def decompress(self, ctx: commands.Context, *, b64_text: str):
""" Decompress base64-encoded, zlib-compressed data. """
decoded = base64.b64decode(b64_text)
decompressed = zlib.decompress(decoded).decode("utf-8")
embed = Crombed(
title = "Decompressed data",
description = decompressed
)
await ctx.send(embed=embed)
@commands.command(aliases=["b64e", "64e"])
async def b64encode(self, ctx: commands.Context, *, data: str):
""" Encode a string to base64. """
b64_text = base64.b64encode(bytes(data, "utf-8")).decode("utf-8")
embed = Crombed(
title = "Base64 encoded data",
description = b64_text
)
await ctx.send(embed=embed)
@commands.command(aliases=["b64d", "64d"])
async def b64decode(self, ctx: commands.Context, *, b64_text: str):
""" Decode a base64-encoded string. """
while len(b64_text) % 4 != 0:
b64_text += "="
decoded_data = base64.b64decode(b64_text).decode("utf-8")
embed = Crombed(
title = "Base64 decoded data",
description = decoded_data
)
await ctx.send(embed=embed)
@commands.command(aliases=["picture", "photo", "photograph"])
async def image(self, ctx: commands.Context, *, raw_text: str = None):
""" Generate an image from text using the Text to Image API made by <NAME> on deepai.org. """
if raw_text:
if is_mention(raw_text):
# Evaluate mentions to nicknames
user_id = extract_id(raw_text)
processed_text = self.bot.get_user(user_id).display_name
else:
processed_text = raw_text
else:
processed_text = random_string(32)
print(f"[garlic.py] Fetching an ooer image based on text \"{processed_text}\"...")
response = requests.post(
"https://api.deepai.org/api/text2img",
data = {
"text": processed_text,
},
headers = {
"api-key": os.environ["DEEPAI_API_KEY"]
}
).json()
try:
url = response["output_url"]
except KeyError:
raise Exception(f"Expected key 'output_url': {str(response)}")
embed = Crombed(
title = "Image",
description = processed_text if raw_text else None, # Only show the text cromgis used if the text came from a user
author = ctx.author
).set_image(url=url)
await ctx.send(embed=embed)
@commands.command(aliases=["mp4togif"])
async def mp4togifv(self, ctx: commands.Context, mp4_url: str):
gifv_url = imgur.upload_image(
path=mp4_url,
title="cromgis video (Uploaded with PyImgur)"
).link
embed = Crombed(
title = "GIF converted from MP4",
url = gifv_url,
author = ctx.author
)
await ctx.send(embed=embed)
@commands.command(aliases=["gib", "gibber"])
async def gibberish(self, ctx: commands.Context, *, text: str):
level = random.randint(1, 6)
length = random.randint(5, 750)
gibberish_text = generate_gibberish(text, level, length)
await ctx.send(gibberish_text)
@commands.group()
async def number(self, ctx: commands.Context):
await self.next_number(ctx)
@number.command(name="next")
async def next_number(self, ctx: commands.Context):
user_number = usernumber.generate(ctx.author.id)
# Send out the generated number
embed = Crombed(
description = "Your next number is: " + user_number,
author = ctx.author
)
await ctx.send(embed=embed)
@number.command(name="current")
async def current_number(self, ctx: commands.Context):
counter = usernumber.get_counter(ctx.author.id)
# Number suffix
th = "th"
if counter[-1] == 1:
th = "st"
elif counter[-1] == 2:
th = "nd"
elif counter[-1] == 3:
th = "rd"
# Send out the user's current counter
embed = Crombed(
description = f"You are currently on your {counter}{th} number.",
author = ctx.author
)
await ctx.send(embed=embed)
# @commands.command()
# async def garlicTest(self, ctx: commands.Context, *, text: str):
# embed = Crombed(
# title = "Test embed",
# description = text,
# author = ctx.author
# )
# await ctx.send(embed=embed)
@commands.Cog.listener()
async def on_message(self, message):
message_authorIDs = set()
message_content = set()
async for m in message.channel.history(limit=REPLY_CHAIN_LENGTH):
""" Contribute to message chains """
message_authorIDs.add(m.author.id)
message_content.add(m.content)
if self.bot.user.id in message_authorIDs:
""" Do not reply to self """
return
if len(message_content) == 1 and len(message_authorIDs) >= REPLY_CHAIN_LENGTH:
return await message.channel.send(message_content.pop())
if chance(2):
""" Chance to say a funny """
function = random.choice([generate_scream, generate_screech, ooojoy])
text = function()
return await message.channel.send(text)
#if "AAA" in message.content.upper():
# """ Scream in response to screams """
# return await message.channel.send(generate_scream())
if "EEE" in message.content.upper():
""" Screech in response to screeches """
return await message.channel.send(generate_screech())
if "@someone" in message.content:
""" @someone: ping random user """
member = random.choice(message.channel.members)
return await message.channel.send(f"<@{member.id}>")
def setup(bot):
bot.add_cog(GarlicCommands(bot))
<file_sep>[build-system]
build-backend = "poetry.masonry.api"
requires = ["poetry>=0.12"]
[tool]
[tool.poetry]
authors = ["<NAME> <<EMAIL>>"]
description = ""
name = "ooer-discord-bot"
version = "0.1.0"
[tool.poetry.dependencies]
Pillow = "^7.1"
dataset = "^1.3"
discord = "^1.0"
jishaku = "^1.18"
markovify = "^0.8.0"
nbfi = "^0.1.2"
pyimgur = "^0.6.0"
python = "^3.7"
python-dotenv = "^0.14.0"
[tool.poetry.dev-dependencies]
<file_sep>import random
def _get_counter_with_file(f, user_id: str) -> int:
""" Get this user's counter from a file that stores counters. 0 if not found. """
for line in f:
searched_user_id, counter = line.split(" ")
if searched_user_id == user_id:
return int(counter)
return 0
def generate(user_id: int) -> int:
user_id = str(user_id)
with open("usernumbers.csv", "a+") as f:
# Find this user's information from a file
counter = _get_counter_with_file(f, user_id)
# User does not exist?
if counter == 0:
# Seek to the end of the file to write a new entry
f.seek(0, 2)
else:
# Seek to the beginning of their entry to update it
current_position = f.tell()
length = len(user_id) + 1 + len(str(counter))
new_position = current_position - length
if new_position < 0:
new_position = 0
f.seek(new_position)
# Generate this user's next number
random.seed(user_id)
for _ in range(counter):
random.random()
user_number = str(random.randint(0, 999))
# Increment this user's counter so they will get
# the number after this one next time
counter += 1
# Write this user's entry with their new counter
f.write(user_id + " " + str(counter))
return user_number
def get_counter(user_id: int) -> int:
user_id = str(user_id)
try:
with open("usernumbers.csv", "r") as f:
return _get_counter_with_file(f, user_id)
except FileNotFoundError:
return 0
<file_sep>from utils import chance
import random
import nbfi
import base64
import zlib
def generate_scream() -> str:
# Vanilla scream half the time
if chance(50):
return "A" * random.randint(1, 100)
# One of these choices repeated 1-100 times
body = random.choice(["A", "O"]) * random.randint(1, 100)
# Chance to wrap the message in one of these Markdown strings
formatter = "" if chance(50) else random.choice(["*", "**", "***"])
# Chance to put one of these at the end of the message
suffix = "" if chance(50) else random.choice(["H", "RGH"])
# Example: "**AAAAAAAAAAAARGH**"
text = formatter + body + suffix + formatter
if chance(50):
text = text.lower()
return text
def generate_screech() -> str:
# Vanilla screech half the time
if chance(50):
return "E" * random.randint(1, 100)
# One of these choices repeated 1-100 times
body = "E" * random.randint(1, 100)
# Chance to wrap the message in one of these Markdown strings
formatter = "" if chance(50) else random.choice(["*", "**", "***"])
# Chance to put an "R" at the beginning of the message
prefix = "" if chance(50) else "R"
# Example: "**REEEEEEEEEEEEEEEEEEE**"
text = formatter + prefix + body + formatter
if chance(50):
text = text.lower()
return text
def ooojoy() -> str:
return "ooo :joy:"
class ProbDist:
def __init__(self, probabilities):
self.probs = {}
for key in probabilities:
self.probs[float(key)] = probabilities[key]
@property
def expected_value(self):
""" μ = Σ(xP(x)) """
ev = 0
for key in self.probs:
ev += key * self.probs[key]
return ev
@property
def standard_deviation(self):
""" σ = sqrt(Σ(x-μ)^2 P(x)) """
sd = 0
for key in self.probs:
sd += (key - self.expected_value) ** 2 * self.probs[key]
return sd ** (1/2)
# Patch for nbfi that prevents it from printing values to console
def __execute(code: list, stackSize: int) -> list:
"""Run BF code"""
iptr = 0
sptr = 0
output = ""
stack = list(0 for _ in range(stackSize))
codeLen = len(code)
while iptr < codeLen:
instruction = code[iptr][0]
if instruction == ">":
sptr += 1
elif instruction == "<":
sptr -= 1
elif instruction == "+":
stack[sptr] += 1
if stack[sptr] == 256:
stack[sptr] = 0
elif instruction == "-":
stack[sptr] -= 1
if stack[sptr] == -1:
stack[sptr] = 255
elif instruction == ".":
output += chr(stack[sptr]) # MODIFIED HERE: No more printnig for you!
elif instruction == ",":
stack[sptr] = nbfi.__getchar()
elif instruction == "[" and stack[sptr] == 0:
iptr = code[iptr][1]
elif instruction == "]" and stack[sptr] != 0:
iptr = code[iptr][1]
iptr += 1
nbfi.__getchar.stdin_buffer = []
return output
nbfi.__execute = __execute
def string_to_bf(source_string):
"""Convert a string into a BF program. Returns the BF code"""
"""Thanks, yiangos on GitHub."""
glyphs = len(set([c for c in source_string]))
number_of_bins = max(max([ord(c) for c in source_string]) // glyphs, 1)
bins = [(i + 1) * number_of_bins for i in range(glyphs)]
code = "+" * number_of_bins + "["
code += "".join([">" + ("+" * (i + 1)) for i in range(1, glyphs)])
code += "<" * (glyphs - 1) + "-]"
code += "+" * number_of_bins
current_bin = 0
for char in source_string:
new_bin = [abs(ord(char) - b)
for b in bins].index(min([abs(ord(char) - b)
for b in bins]))
appending_char = ""
if new_bin - current_bin > 0:
appending_char = ">"
else:
appending_char = "<"
code += appending_char * abs(new_bin - current_bin)
if ord(char) - bins[new_bin] > 0:
appending_char = "+"
else:
appending_char = "-"
code += (appending_char * abs( ord(char) - bins[new_bin])) + "."
current_bin = new_bin
bins[new_bin] = ord(char)
return code
def is_valid_bf(data: str) -> bool:
for char in data:
if char not in "><+-.,[]":
return False
return True
def decompress_if_necessary(data: str) -> str:
if not is_valid_bf(data):
data = bytes(base64.b64decode(data), "utf-8")
data = zlib.decompress(data)
if not is_valid_bf(data):
raise ValueError("Data could not be resolved to Brainfuck code.")
return data
def run_bf(data: str, stack_size: int) -> list:
return nbfi.run(decompress_if_necessary(data))
# Gibberish Generator (Python).
# Algorithm: Letter-based Markov text generator.
# Original code written in JavaScript:
# <NAME>, thinkzone.wlonk.com
# Ported to Python by garlicOS®
def _pick_match_index(text: str, target: str) -> int:
N_CHARS = len(text)
# Find all sets of matching target characters.
n_matches = 0
counter = -1
while True:
try:
counter = text.index(target[counter + 1])
except ValueError:
break
if counter >= N_CHARS:
break
else:
n_matches += 1
# Pick a match at random.
return random.randint(0, n_matches)
def _pick_char(text: str, target: str, match_index: int, level: int) -> str:
N_CHARS = len(text)
# Find the character following the matching characters.
n_matches = 0
j = -1
while True:
try:
j = text.index(target[j + 1])
except ValueError:
break
if j >= N_CHARS:
break
elif match_index == n_matches:
return text[j + level - 1]
else:
n_matches += 1
def generate_gibberish(text: str, level: int=4, length: int=500) -> str:
N_CHARS = len(text)
if N_CHARS < level:
raise ValueError("Too few input characters.")
char_index = None
# Make the string contain two copies of the input text.
# This allows for wrapping to the beginning when the end is reached.
text += text
# Ensure the input text ends with a space.
if text[-1] != " ":
text += " "
# Pick a random starting character, preferably an uppercase letter.
for _ in range(1000):
char_index = random.randint(0, N_CHARS)
if text[char_index].isupper():
break
# Write starting characters.
output = text[char_index : char_index + level]
# Set target string.
target = text[char_index + 1 : char_index + level]
# Generate characters.
for _ in range(length):
if (level == 1):
# Pick a random character.
output += text[random.randint(0, N_CHARS)]
else:
match_index = _pick_match_index(text, target)
char = _pick_char(text, target, match_index, level)
# Update the target.
target = target[1 : level - 1] + char
# Add the character to the output.
output += char
return output
| 5354cb7234ea188cd40622498ce58be171868ac5 | [
"Markdown",
"TOML",
"Python"
] | 5 | Markdown | InvalidOS/Ooer-Discord-Bot | 8fefb21b61d7434a67b2b903c9972ade502b1dc4 | 4a205ea6ce92aa9bc7cb1e572c7b8405cd387450 |
refs/heads/master | <repo_name>rismanadnan/hackergo<file_sep>/gameofthrones1.go
package main
import "fmt"
func main() {
// make an array that contains all alphabet as main data structure
var container [26]int
// some variable required
var even, odd int
// scan the input string
var s string
fmt.Scanf("%v", &s)
for _, c := range s {
container[int(c-'a')] = container[int(c-'a')] + 1
}
for i := 0; i < 26; i++ {
if (container[i] % 2) == 0 {
even = even + 1
} else {
odd = odd + 1
}
}
// Palindrome happens only with odd < 2
if odd < 2 {
fmt.Println("YES")
} else {
fmt.Println("NO")
}
}
<file_sep>/fillingjars.go
package main
import "fmt"
func main() {
var n, m int
var a, b, k int
fmt.Scanf("%v %v", &n, &m)
total := 0
for in := 0; in < m; in++ {
fmt.Scanf("%v %v %v", &a, &b, &k)
total += (b - a + 1) * k
}
fmt.Println(total / n)
}
<file_sep>/halloweenparty.go
// Please solve some bugs
package main
import (
"fmt"
"math"
)
func main() {
var ntest, k int
var result, tmp1, tmp2 float64
fmt.Scanf("%v", &ntest)
for i := 0; i < ntest; i++ {
fmt.Scanf("%v", &k)
tmp1 = float64(k / 2)
tmp2 = float64((k + 1) / 2)
if (k % 2) == 0 {
result = math.Pow(tmp1, 2)
} else {
result = tmp1 * tmp2
}
fmt.Println(result)
}
}
<file_sep>/sherlockandthebeast.go
// Add concept of Stringer (15)
package main
import "fmt"
func main() {
var n, numtest int
var s string
fmt.Scanf("%v", &numtest)
for numtest > 0 {
s = ""
numtest--
fmt.Scanf("%v", &n)
for i := n; i >= 0; i-- {
if i%3 == 0 && (n-i)%5 == 0 {
// s = new string('5',i) + new string('3', n-i) .... stringer concept
break
}
}
if s == "" {
fmt.Println(-1)
} else {
fmt.Println(s)
}
}
}
<file_sep>/flippingbits.go
package main
import (
"fmt"
"strconv"
)
// given an integer uint32, return a string of bits with lenght 32, put zero for empty digit
// flip the bits on the resulted string 1 to 0 and 0 to 1 then return back its integer value
func flipBits(x int64) int64 {
var str string
var intResult int64
width := 32
// convert int to bits string s
s := strconv.FormatInt(x, 2)
empty := width - len(s)
if empty >= 0 {
for i := 0; i < empty; i++ {
s = "0" + s
}
} else {
s = "Error"
}
for _, c := range s {
switch c {
case '0':
c = '1'
case '1':
c = '0'
}
str = str + string(c)
}
intResult, _ = strconv.ParseInt(str, 2, 0)
return intResult
}
func main() {
var t int
var input [100]int64
fmt.Scanf("%d", &t)
// Scan the input
for i := 0; i < t; i++ {
fmt.Scanf("%d", &input[i])
}
// print results from inputs
for i := 0; i < t; i++ {
o := flipBits(input[i])
fmt.Println(o)
}
}
<file_sep>/manasastone.go
package main
import "fmt"
func main() {
var answer, numtest int
var n, a, b int
fmt.Scanf("%v", &numtest)
for i := 0; i < numtest; i++ {
fmt.Scanf("%v %v %v", &n, &a, &b)
if a == b {
answer = a * (n - 1)
fmt.Print(answer)
} else {
for j := 0; j < n; j++ {
if b <= a {
answer = i*a + (n-1-j)*b
} else {
answer = (n - 1 - j) + i*b
}
fmt.Print(answer)
}
}
}
}
<file_sep>/sherlockgdc.go
package main
import (
"fmt"
"math"
)
func main() {
var testnum, temp int
var flag bool
var divisible float64
fmt.Scanf("%v", &testnum)
for i := 0; i < testnum; i++ {
var numRead int
fmt.Scanf("%v", &numRead)
flag = false
var numArray [numRead]int
for j := 0; j < numRead; j++ {
fmt.Scanf("%v", &temp)
numArray[j] = temp
}
if numRead == 1 {
fmt.Println("NO")
}
for j := 0; j < (numRead - 1); j++ {
for k := j + 1; k < numRead; k++ {
divisible = 2
for divisible <= math.Max(float64(numArray[k]), float64(numArray[j])) {
if (numArray[k]%divisible == 0) && (numArray[j]%divisible == 0) {
flag = true
break
}
if divisible == math.Max(float64(numArray[k]), float64(numArray[j])) {
flag = false
}
divisible++
}
}
if !flag {
fmt.Println("YES")
break
}
}
if flag {
fmt.Println("NO")
}
}
}
<file_sep>/chocolatefeast.go
package main
import (
"fmt"
)
func numberchoco(n, c, m int) int {
var answer, temp int
answer = int(n / c)
if answer >= m {
temp = answer
for temp >= m {
temp -= m
answer++
temp++
}
}
return answer
}
func main() {
var numtest, n, c, m, result int
fmt.Scanf("%v", &numtest)
for i := 0; i < numtest; i++ {
fmt.Scanf("%v %v %v", &n, &c, &m)
result = numberchoco(n, c, m)
fmt.Println(result)
}
}
<file_sep>/sample.go
package main
import (
"fmt"
)
func main() {
result := 'z'
fmt.Println(int(result - 'a'))
}
<file_sep>/sherlocksquares.go
package main
import (
"fmt"
"math"
)
func main() {
var square, a, b, numtest, idx int
fmt.Scanf("%v", &numtest)
for i := 0; i < numtest; i++ {
numofSquares := 0
fmt.Scanf("%v %v", &a, &b)
idx = 1
square = int(math.Pow(float64(idx), 2))
for square <= b {
if square < a {
} else {
numofSquares++
}
idx++
square = int(math.Pow(float64(idx), 2))
}
fmt.Println(numofSquares)
}
}
| 4e34adfdf349dde961d81b664c328793f6d3000f | [
"Go"
] | 10 | Go | rismanadnan/hackergo | 1a2515c11bac05f11ac411a07a0b30fd52b41e42 | 768099a1bfef812122fef98965d5a995abea0cc9 |
refs/heads/master | <repo_name>nithalqb/angular-hero-myapp<file_sep>/src/app/mock-hero.ts
import { Hero } from './hero';
export const HEROES: Hero[] = [
{ id:1, name: 'Superman'},
{ id:2, name: 'Spiderman'},
{ id:3, name: 'Shaktiman'},
{ id:4, name: 'Jakichan'},
{ id:5, name: 'Mohanlal'},
{ id:6, name: 'XMan'},
{ id:7, name: 'YMan'},
{ id:8, name: 'GMan'},
{ id:9, name: 'UMan'},
{ id:10, name: 'RMan'}
];<file_sep>/README.md
# angular-hero-myapp
Angular2 Hero App
| 8e2bdac09cff37f2686e9b74123742c4255ebd90 | [
"Markdown",
"TypeScript"
] | 2 | TypeScript | nithalqb/angular-hero-myapp | 063dbad2c45db9716f612e0a89bc739d30e675c4 | 3c77932c6e8543cc81ffd5962cef3d4c96f00519 |
refs/heads/master | <file_sep>/*
* 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.
*/
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.ThreadLocalRandom;
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;
/**
*
* @author TecMilenio
*/
@WebServlet(urlPatterns = {"/guessServlet"})
public class guessServlet extends HttpServlet {
private static boolean correctGuess = false;
private static Integer mysteryNumber;
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
if(mysteryNumber == null || correctGuess) {
correctGuess = false;
resetNumber();
session.setAttribute("mysteryNumber", mysteryNumber);
}
int guess;
try {
guess = Integer.parseInt(request.getParameter("guess"));
if(guess != mysteryNumber) {
session.setAttribute("guess", guess);
response.sendRedirect("index.jsp");
} else {
correctGuess = true;
session.invalidate();
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet rpsServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Felicidades, adivinaste el numero.</h1>");
out.println("<img src=\"are-you-wizard.jpg\" alt=\"r-u-a-wizurd\"/></br/>");
out.println("<a href='index.jsp'>Regresar al juego</a>");
out.println("</body>");
out.println("</html>");
}
}
} catch (Exception e) {
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet rpsServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Adivina números enteros por favor.</h1>");
out.println("</body>");
out.println("</html>");
}
}
}
private void resetNumber() {
mysteryNumber = ThreadLocalRandom.current().nextInt(0, 100 + 1);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| 31ac84dfb76a93bdcf95ae2407b93cb1a1a7085b | [
"Java"
] | 1 | Java | Dreami/GuessingGame | 2ab8f46c9f2e655a9c102a7507835ef193cb3d76 | b5f338f01e0a1382e579527729e16857a639a41f |
refs/heads/main | <file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Fence : MonoBehaviour
{
public Transform hammerPosition;
public Transform fenceModelRoot;
private bool isWork = false;
public static int count = 0;
private void Update()
{
if (fenceModelRoot.localPosition.y <= -0.8f && !isWork)
{
gameObject.GetComponent<Collider>().enabled = false;
count++;
isWork = true;
}
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Screw : MonoBehaviour
{
public Transform drillPosition;
public Transform screwModelRoot;
private bool isWorked = false;
public static int count = 0;
private void Update()
{
if (screwModelRoot.localPosition.y <= -0.6f && !isWorked)
{
gameObject.GetComponent<Collider>().enabled = false;
count++;
isWorked = true;
Debug.Log((count));
}
}
}
<file_sep># Hammer-and-Drill<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
[SerializeField] private Canvas canvas;
private Camera _camera;
public List<GameObject> firstFences = new List<GameObject>();
public List<GameObject> secondFences = new List<GameObject>();
public List<GameObject> firstScrews = new List<GameObject>();
public List<GameObject> secondScrew = new List<GameObject>();
private Vector3 targetCameraPosition;
private void OnValidate()
{
if (_camera == null)
_camera = Camera.main;
}
private void Start()
{
targetCameraPosition = new Vector3(-3, 5, -10);
foreach (var VARIABLE in secondFences)
{
VARIABLE.GetComponent<Collider>().enabled = false;
}
}
public void OnClick()
{
//SceneManager.LoadScene("SampleScene");
//canvas.gameObject.SetActive(false);
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
private void Update()
{
if (Fence.count == firstFences.Count)
{
foreach (var VARIABLE in firstScrews)
{
VARIABLE.SetActive(true);
}
}
if (Screw.count + Fence.count-3 == firstScrews.Count)
{
_camera.transform.position = Vector3.Lerp(_camera.transform.position,targetCameraPosition,Time.deltaTime);
_camera.transform.rotation = Quaternion.Lerp(_camera.transform.rotation,Quaternion.Euler(0,0,-90),Time.deltaTime);
foreach (var VARIABLE in secondFences)
{
VARIABLE.GetComponent<Collider>().enabled = true;
}
}
if (Fence.count == 7)
{
foreach (var VARIABLE in secondScrew)
{
VARIABLE.SetActive(true);
}
}
if (Fence.count + Screw.count == 12)
{
canvas.gameObject.SetActive(true);
}
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RaycastIntoScene : MonoBehaviour
{
[SerializeField] private Camera _camera;
[SerializeField] private MovingHammer movingHammer;
[SerializeField] private MovingDrill _movingDrill;
private Fence _currentFence;
private Screw _screw;
[SerializeField] private Transform hammerPosition;
[SerializeField] private Transform drillPosition;
private bool isMoved = false;
private void OnValidate()
{
if(_camera==null)
_camera=Camera.main;
}
private void Update()
{
Vector2 mouseScreenPosition = Input.mousePosition;
Ray ray = _camera.ScreenPointToRay(mouseScreenPosition);
RaycastHit raycastHit;
if (Input.GetMouseButton(0)&&!isMoved)
{
Debug.DrawRay(ray.origin, ray.direction * 20f, Color.green);
if (Physics.Raycast(ray, out raycastHit,20f))
{
_currentFence = raycastHit.collider.gameObject.GetComponent<Fence>();
_screw = raycastHit.collider.gameObject.GetComponent<Screw>();
if (_currentFence)
{
_movingDrill.transform.SetParent(null);
_movingDrill.transform.position =_camera.transform.position+ new Vector3(2, -2f, 6);
_movingDrill.transform.rotation = _camera.transform.rotation;
_currentFence.fenceModelRoot.localPosition += new Vector3(0, -0.1f, 0);
movingHammer.transform.SetParent(_currentFence.hammerPosition);
StartCoroutine(HammerMoved());
StartCoroutine(HammerBack());
}
if (_screw)
{
movingHammer.transform.SetParent(null);
movingHammer.transform.position = _camera.transform.position+ new Vector3(3, -2f, 6);
movingHammer.transform.rotation = _camera.transform.rotation;
_movingDrill.transform.SetParent(_screw.drillPosition);
StartCoroutine(DrillMoved());
}
}
}
}
private void FixedUpdate()
{
if (Input.GetMouseButton(0))
{
if (_screw)
{
_screw.screwModelRoot.localPosition += new Vector3(0, -0.1f*Time.deltaTime, 0);
}
}
}
IEnumerator HammerMoved()
{
float timer = 0f;
isMoved = true;
while (true)
{
timer += Time.deltaTime;
movingHammer.transform.localPosition = Vector3.Lerp(movingHammer.transform.localPosition,hammerPosition.localPosition , timer);
movingHammer.transform.localRotation =
Quaternion.Lerp(movingHammer.transform.localRotation, Quaternion.Euler(90,0,0), timer);
if (timer >= 1)
{
isMoved = false;
break;
}
yield return new WaitForEndOfFrame();
}
}
IEnumerator HammerBack()
{
yield return new WaitForSeconds(1f);
movingHammer.transform.localRotation = Quaternion.Lerp(movingHammer.transform.localRotation, Quaternion.Euler(0,0,0), 0.6f);
}
IEnumerator DrillMoved()
{
float timer = 0f;
isMoved = true;
while (true)
{
timer += Time.deltaTime;
_movingDrill.transform.localPosition = Vector3.Lerp(_movingDrill.transform.localPosition,drillPosition.localPosition , timer);
_movingDrill.transform.localRotation =
Quaternion.Lerp(_movingDrill.transform.localRotation, Quaternion.Euler(90,0,0), timer);
if (timer >= 1)
{
isMoved = false;
break;
}
yield return new WaitForEndOfFrame();
}
}
}
| 295c0b4418976c0a3b0aa20c4f9b32a658cfa2fb | [
"Markdown",
"C#"
] | 5 | C# | sevvalkatirci/Hammer-and-Drill | da34d5680bc1d799ff93d8a007730e9212cd0367 | 8f67b6f52ecbe735d2abebdea2ea6fff7b620af4 |
refs/heads/master | <repo_name>3redkites/Salesforce-Lead<file_sep>/salesforcelead/services/SalesforceLeadService.php
<?php
/**
* Salesforce Lead Plugin by Solspace, Inc.
*
* @package SalesforceLead
* @author <NAME>
* @copyright Copyright (c) 2015, Solspace, Inc.
* @link http://solspace.com
* @license http://solspace.com
*/
namespace Craft;
class SalesforceLeadService extends BaseApplicationComponent
{
var $session;
var $cached = array();
var $errors = array();
public function dd($data)
{
print_r($data); exit();
}
private function preference($which)
{
if (craft()->config->get($which))
{
return craft()->config->get($which);
}
return FALSE;
}
private function connectToApi()
{
if ($this->preference('salesforcelead_api_provider') == 'salesforce_soap')
{
// --------------------------------------------
// Instantiate
// --------------------------------------------
$wsdl = ($this->preference('salesforcelead_api_test_mode') != 'y') ? 'partner-live.wsdl.xml': 'partner-test.wsdl.xml';
$salesforce_wsdl = CRAFT_PLUGINS_PATH . '/salesforcelead/resources/vendor/salesforce/soapclient/' . $wsdl;
require_once(CRAFT_PLUGINS_PATH.'/salesforcelead/resources/vendor/salesforce/soapclient/SforcePartnerClient.php');
// --------------------------------------------
// Initialize
// --------------------------------------------
ini_set('soap.wsdl_cache_enabled', 0);
ini_set('soap.wsdl_cache_ttl', 0);
// --------------------------------------------
// Create fresh object
// --------------------------------------------
$this->session = new \SforcePartnerClient();
// --------------------------------------------
// Connect
// --------------------------------------------
try
{
$this->session->createConnection($salesforce_wsdl);
}
catch (Exception $e)
{
$this->errors[] = $e->getMessage();
return FALSE;
}
// --------------------------------------------
// Login
// --------------------------------------------
try
{
$this->session->login($this->preference('salesforcelead_api_user'), $this->preference('salesforcelead_api_password') . $this->preference('salesforcelead_api_security_token'));
$this->cached['connected'] = TRUE;
}
catch (Exception $e)
{
$this->errors[] = $e->getMessage();
return FALSE;
}
}
}
public function postLeadToSalesforce($event)
{
$message = $event->params['message'];
$data['Company'] = (empty($_POST['message']['company'])) ? '': $_POST['message']['company'];
$data['LastName'] = (! $message->fromName) ? '': $message->fromName;
//$data['Name'] = (! $message->fromName) ? '': $message->fromName;
$data['Email'] = (! $message->fromEmail) ? '': $message->fromEmail;
$data['Description'] = (empty($_POST['message']['body'])) ? '': $_POST['message']['body'];
if ($this->connectToApi() === FALSE)
{
Craft::log('Unable to connect to Salesforce. Here are the errors: ' . print_r($this->errors, TRUE), LogLevel::Warning, false, 'application', 'salesforcelead');
return FALSE;
}
if ($this->preference('salesforcelead_api_provider') == 'salesforce_soap')
{
$object = 'Lead';
//Creating the Lead Object
$obj = new \stdClass;
$obj->type = $object;
$obj->fields = $data;
//Try
try
{
//Submitting Salesforce
$result = $this->session->create(array($obj), $object);
$result = (array) $result[0];
if (! empty($result['errors']))
{
foreach ($result['errors'] as $error)
{
$this->errors[] = $error->message;
}
Craft::log('Unable to create Lead object in Salesforce. Here are the errors: ' . print_r($this->errors, TRUE), LogLevel::Warning, false, 'application', 'salesforcelead');
return FALSE;
}
$salesforcelead_id = $result['id'];
}
catch (Exception $e)
{
$this->errors[] = $e->getMessage();
Craft::log('Unable to create Lead object in Salesforce. Here is the exception: ' . print_r($this->errors, TRUE), LogLevel::Warning, false, 'application', 'salesforcelead');
return FALSE;
}
}
}
}<file_sep>/salesforcelead/config.php
<?php
/**
* Mock Salesforce Lead Configuration
*
*/
return array(
'salesforcelead_api_test_mode' => 'y',
'salesforcelead_api_provider' => 'salesforce_soap',
'salesforcelead_api_user' => 'your_salesforce_username',
'salesforcelead_api_password' => '<PASSWORD>',
'salesforcelead_api_security_token' => 'security_token_provided_by_salesforce'
);<file_sep>/salesforcelead/SalesforceLeadPlugin.php
<?php
/**
* Salesforce Lead Plugin by Solspace, Inc.
*
* @package SalesforceLead
* @author <NAME>
* @copyright Copyright (c) 2015, Solspace, Inc.
* @link http://solspace.com
* @license http://solspace.com
*/
namespace Craft;
class SalesforceLeadPlugin extends BasePlugin
{
/**
* Get Name
*/
function getName()
{
return 'Salesforce Lead';
}
/**
* Get Version
*/
function getVersion()
{
return '0.1';
}
/**
* Get Developer
*/
function getDeveloper()
{
return 'Solspace';
}
/**
* Get Developer URL
*/
function getDeveloperUrl()
{
return 'http://www.solspace.com';
}
/**
* init
*/
public function init()
{
craft()->on('contactForm.beforeSend', function(ContactFormEvent $event)
{
craft()->salesforceLead->postLeadToSalesforce($event);
});
}
}
<file_sep>/readme.md
# Salesforce Lead
## Salesforce Lead plugin for Craft CMS
This plugin works with the Contact Form plugin for Craft CMS created by <NAME> (https://github.com/pixelandtonic/ContactForm). When visitors post to a contact form, their submission is sent to the Salesforce account indicated in the Craft general configuration file. A Lead is created in the indicated Salesforce account with the name, email, message and company the visitor submits in the form.
Currently supports:
* Salesforce
Plugin settings allow you to:
* Set API settings
* Set test mode in order to post to a Salesforce sandbox account
* Build on Craft's environment specific configuration capability to use separate API credentials per environment.
_NB. Solspace can assist with customizations to this plugin as well as create additional Salesforce integration functionality. Just contact us at <EMAIL>._
## Installation
To install the plugin, follow these steps:
1. Upload the salesforcelead/ folder to your craft/plugins/ folder.
2. Go to Settings > Plugins from your Craft control panel and install the plugin.
3. Copy the sample API configuration settings from craft/plugins/salesforcelead/config.php into the craft/config/general.php file. Update the settings in that array to match those of your Salesforce account.
4. If you are testing against a Salesforce sandbox account, make sure to set the test mode to 'y'.
5. The Salesforce Lead object requires two fields for every submission, Last Name and Company. We map the fromName field from the Contact Form plugin into the Last Name field of the Lead object. We map the message[company] field from the contact form into the Company field in the Salesforce Lead object. The Contact Form plugin allows you to augment the message field to include additional fields. In your form, give the message field the name 'message[body]' and give the company field the name 'message[company]'.
## Requirements
Craft CMS Version 2.1+
## Changelog
### 0.1
* Initial beta release
| 42b9c21afd81504c2216bfc0e227efa551dac90d | [
"Markdown",
"PHP"
] | 4 | PHP | 3redkites/Salesforce-Lead | d91e056210e982062ad14bb71ef067e875ea1459 | aa77651fa342660afb28ac5c12e63d297d36d4b1 |
refs/heads/main | <file_sep>/* eslint-disable no-unused-vars */
const express = require('express')
const bodyParser = require('body-parser')
const winston = require('winston')
var expressControllers = require('express-controller');
const session = require('express-session')
const cors = require('cors')
const helmet = require('helmet')
const {
port,
sessionSecretKey
} = require('./configs/config')
const path = require('path')
var csrf = require('csurf');
var RateLimit = require('express-rate-limit')
const passport = require('passport');
const mongoose = require('mongoose');
var expressValidator = require('express-validator');
const sanitizeBody = require('express-validator/filter');
var cookieParser = require('cookie-parser')
var flash = require('connect-flash');
const {
authRoutes,
productRoutes,
showRoutes,
brandRoutes,
buyRoutes,
paymentRoutes,
searchRoutes,
orderRoutes,
cartRoutes,
profileRoutes,
verfiyRoutes,
newletterRoutes
} = require('./src/routes')
// M
// Middlewares
/* const {
store
} = require('./configs/sessionStorage/firebaseSessionStorage') */
/*
OR IF YOU WANT TO USE OTHER SESSION STORAGE
const { store} = require('./configs/sessionStorage/memorySessionStorage')
*/
const {
dbname,
MONGODB_URL,
sessionKeys
} = require('./configs/config.js')
//database connection
mongoose.connect(MONGODB_URL, {
// useMongoClient:true,
useNewUrlParser: true,
useUnifiedTopology: true
});
const app = express();
app.use(helmet());
app.use(bodyParser.urlencoded({
extended: true,
limit: '50mb'
}))
app.use(bodyParser.json({
limit: '50mb'
}))
app.use(cookieParser());
app.use(session({
//store,
secret: sessionSecretKey,
resave: true,
saveUninitialized: true,
cookie: {
secure: process.env.NODE_ENV == "production" ? true : false,
maxAge: 1000 * 60 * 60 * 24 * 7
}
}));
app.use(flash());
// initialize passport
app.use(passport.initialize());
app.use(passport.session());
// app.use(csrf());
app.set('port', (process.env.PORT || port));
app.use(cors());
// use this middleware in authentications routes or post method routes
var authAPILimiter = new RateLimit({
windowMs: 5 * 60 * 1000, // 5 minutes
max: 1000,
delayMs: 0 // disabled
});
// loggin middleware
const logger = winston.createLogger({
level: 'info',
transports: [
new winston.transports.Console(),
new winston.transports.File({
filename: './logs/error.log',
level: 'error'
}),
new winston.transports.File({
filename: './logs/debug.log',
level: 'debug'
}),
new winston.transports.File({
filename: './logs/crit.log',
level: 'crit'
}),
new winston.transports.File({
filename: './logs/warn.log',
level: 'warn'
}),
new winston.transports.File({
filename: './logs/combined.log'
})
]
});
//validator
app.use(expressValidator());
// V
// static files and views
app.use(express.static(path.join(__dirname, '/public')))
app.set('view engine', 'ejs');
app.set('views', [path.join(__dirname, 'src/views'),
path.join(__dirname, 'src/views/layouts/')
]);
app.engine('html', require('ejs').renderFile);
// custom middlewares
// add isAuth middleware to protect any routes
const {
isAuth,
notFound404
} = require('./src/middlewares')
// C
//controller settings
//setting up the controller
expressControllers.setDirectory(path.join(__dirname, 'src/controller')).bind(app);
app.use(function (req, res, next) {
res.locals.user = req.user || null;
next();
})
const {
productModel
} = require('./src/models')
app.use('/auth', authRoutes);
app.use('/product', productRoutes);
app.use('/show', showRoutes);
app.use('/brand', brandRoutes);
app.use('/buy', buyRoutes);
app.use('/search', searchRoutes);
app.use('/payment', paymentRoutes);
app.use('/order', orderRoutes)
app.use('/cart', cartRoutes)
app.use('/profile', profileRoutes)
app.use('/verify', verfiyRoutes)
app.use('/newsletter', newletterRoutes)
app.get('/show/banners/:type', async (req, res) => {
await mongoose.connection.db.collection('banners', async (err, collection) => {
await collection.find({
banner_name: {
$regex: req.params.type,
$options: 'i'
}
}).toArray(async (err, banner) => {
if (req.params.type == 'pop_product' || req.params.type == "recommended_product") {
for (let i = 0; i < banner.length; i++) {
const element = banner[i];
var productDetails = await productModel.findById(element.banner_name_link).exec();
banner[i]["name"] = productDetails.name;
banner[i]["subCategory"] = productDetails.subCategory;
banner[i]["price"] = productDetails.price;
}
res.json(banner);
} else {
res.json(banner);
}
});
})
})
app.get('/', (req, res) => {
res.render('index');
})
app.get('/page', (req, res) => {
res.render('website-helper-links')
})
app.get('/seller', (req, res) => {
res.render('auth/seller');
})
app.get('/contact', (req, res) => {
res.render('contact')
})
app.get('/community', (req, res) => {
res.render('community')
})
app.get('/donate', (req, res) => {
res.render('donate')
})
app.use((req, res, next) => {
return res.status(404).render('404');
})
app.listen(app.get('port'), () => {
logger.info('> Server is running on PORT ', app.get('port'));
})<file_sep>const express = require('express')
const bodyParser = require('body-parser')
const winston = require('winston')
var expressControllers = require('express-controller');
var session = require('express-session')
const cors = require('cors')
const helmet = require('helmet')
var expressValidator = require('express-validator');
const sanitizeBody = require('express-validator/filter');
const passport = require('passport')
var flash = require('connect-flash');
const {
port,
sessionSecretKey,
productImageSavingLocation,
websiteImageSavingLocation
} = require('./config')
const path = require('path')
var csrf = require('csurf');
const mongoose = require('mongoose')
var multer = require('multer')
var cookieParser = require('cookie-parser')
var storage = multer.diskStorage({
destination: function (req, file, cb) {
if (file.fieldname == "pro_images") {
console.log("working somehting");
cb(null, productImageSavingLocation)
} else {
cb(null, websiteImageSavingLocation)
}
}
})
var upload = multer({
storage
})
// M
// Middlewares
const app = express();
//validator
app.use(expressValidator());
const {
dbname,
MONGODB_URL,
sessionKeys
} = require('./config.js')
//database connection
mongoose.connect(MONGODB_URL,{
//useMongoClient:true,
useNewUrlParser: true
});
app.use(cookieParser());
// session Middleware
//const {store} = require('./utils/sessionStorage/firebaseSessionStorage')
/*
OR IF YOU WANT TO USE OTHER SESSION STORAGE
const { store} = require('./utils/sessionStorage/memorySessionStorage')
*/
// session Middleware
app.use(session({
// store,
secret: sessionSecretKey,
resave: true,
saveUninitialized: true,
cookie: {
secure: process.env.NODE_ENV == "production" ? true : false ,
maxAge: 1000 * 60 * 60 * 24 * 7
}
}))
app.use(flash());
app.set('port', (process.env.PORT || port));
app.use(bodyParser.urlencoded({
extended: true,
limit: '50mb'
}))
app.use(bodyParser.json({
limit: '50mb'
}))
app.use(cors());
const logger = winston.createLogger({
level: 'info',
transports: [
new winston.transports.Console(),
new winston.transports.File({
filename: './logs/error.log',
level: 'error'
}),
new winston.transports.File({
filename: './logs/debug.log',
level: 'debug'
}),
new winston.transports.File({
filename: './logs/crit.log',
level: 'crit'
}),
new winston.transports.File({
filename: './logs/warn.log',
level: 'warn'
}),
new winston.transports.File({
filename: './logs/combined.log'
})
]
});
// V
// static files and views
app.use(express.static(path.join(__dirname, 'public')))
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'src/views'));
app.engine('html', require('ejs').renderFile);
app.use(passport.initialize());
app.use(passport.session());
app.use(function (req, res, next) {
res.locals.user = req.user || null;
next();
})
// C
//controller settings
//setting up the controller
expressControllers.setDirectory(path.join(__dirname, 'src/controller')).bind(app);
const {
isAuth,
hideLoginPage
} = require('./src/middleware/auth')
const {
isCcare,
isSuperAdmin
} = require('./src/middleware/role')
/*
R e n d e r i n g V i e w s
*/
app.get('/', isAuth, (req, res) => {
res.redirect('/home')
})
app.get('/home', isAuth, (req, res) => {
res.render('dashboard')
})
app.get('/product', isAuth, (req, res) => {
res.render('product')
})
app.get('/show/product', [isAuth], (req, res) => {
res.render('showProduct')
})
app.get('/show/customer', isAuth, (req, res) => {
res.render('userdetails')
})
app.get('/show/banner', [isAuth, isSuperAdmin], (req, res) => {
res.render('banner')
})
app.get('/show/page', [isAuth, isSuperAdmin], (req, res) => {
res.render('website-page')
})
app.get('/show/contactBuy', [isAuth, isSuperAdmin], (req, res) => {
res.render('contactBuy')
})
app.get('/show/delivery', isAuth, (req, res) => {
res.render('delivery')
})
app.get('/show/order', isAuth, (req, res) => {
res.render('order')
})
app.get('/login', hideLoginPage, (req, res) => {
res.render('login')
})
app.get('/show/community',[isAuth],(req,res) => {
res.render('community')
})
app.get('/show/header_footer',[isAuth,isSuperAdmin],(req,res) => {
res.render('header_footer')
})
/*
C o n t r o l l e r h e r e
*/
const {
getAllProducts,
addProduct,
showEditProduct,
editProduct
} = require('./src/controller/product')
const {
getAllUsers
} = require('./src/controller/user')
const {
addBanner
} = require('./src/controller/banner')
const {
addPage
} = require('./src/controller/page')
const {
addContact,
addAddr,
addFeature,
addPaymentGuide
} = require('./src/controller/contact')
const {
getDelivery,
showEditDelivery,
editDeliveryStatus
} = require('./src/controller/delivery')
const {
getStats
} = require('./src/controller/stats')
const {
getAllOrders,
showEditOrder,
editOrderStatus
} = require('./src/controller/order')
const {
addCommunity,
addDonate
} = require('./src/controller/community')
const {
register
} = require('./src/controller/auth/methods')
const {
addLogo,
addLogo2,
addSocialMediaLink
} = require('./src/controller/header_footer')
app.get('/change/delivery/:_deliveryID', isAuth, showEditDelivery)
app.get('/change/product/:_productID', isAuth, showEditProduct)
app.get('/change/order/:_orderID', isAuth, showEditOrder)
app.post('/edit/delivery/:_deliveryID', isAuth, editDeliveryStatus)
app.post('/edit/order/:_orderID', isAuth, editOrderStatus)
app.post('/edit/product/:_productID', [isAuth, upload.array('pro_images', 6)], editProduct)
app.get('/get/products', isAuth, getAllProducts)
app.get('/get/users', isAuth, getAllUsers)
app.get('/get/delivery', isAuth, getDelivery)
app.get('/get/stats', isAuth, getStats)
app.get('/get/orders', isAuth, getAllOrders)
app.post('/add/product', [isAuth, isSuperAdmin, upload.array('pro_images', 6)], addProduct)
app.post('/add/banner', [isAuth, isSuperAdmin, upload.any()], addBanner)
app.post('/add/page', isAuth, isSuperAdmin, addPage)
app.post('/add/contact', isAuth, isSuperAdmin, addContact)
app.post('/add/addr', [isAuth, isSuperAdmin, upload.any()], addAddr)
app.post('/add/paymentGuide', [isAuth, isSuperAdmin], addPaymentGuide)
app.post('/add/feature', [isAuth, isSuperAdmin, upload.any()], addFeature)
app.post('/add/community',isAuth,addCommunity)
app.post('/add/donate',isAuth,addDonate)
app.post('/add/logo',[isAuth,isSuperAdmin,upload.any()],addLogo)
app.post('/add/logo2',[isAuth,isSuperAdmin,upload.any()],addLogo2)
app.post('/add/socialLink/:website',[isAuth,isSuperAdmin],addSocialMediaLink)
// auth
app.get('/register', [isAuth,isSuperAdmin], (req, res) => {
res.render('register', {
isAdmin: true
})
})
app.get('/reg', [isAuth,isSuperAdmin], (req, res) => {
const {
adminKey
} = req.params;
if (adminKey == 998877) {
res.render('register', {
isAdmin: true
})
} else {
res.redirect('/register' )
}
})
app.post('/register', register)
const Lpassport = require('./src/controller/auth/passport.config')
app.post('/login', Lpassport.authenticate('local', {
successRedirect: '/home',
failureRedirect: '/login',
failureFlash: true
}), (req, res) => {
res.redirect('/');
});
app.get('/logout', (req, res) => {
req.logout();
res.clearCookie('connect.sid');
req.session.destroy()
// console.log("HITTING LOGOUT", req.headers,req.header('Referer'));
res.redirect('/');
})
app.listen(app.get('port'), () => {
logger.info('> Server is running on PORT ', app.get('port'));
})<file_sep>const bcrypt = require('bcrypt');
module.exports = {
port : 4000,
sessionSecretKey : bcrypt.hashSync("SECRET_KEY", 2),
dbname : '_DBname_',
sessionKeys : ['key1','key2'],
MONGODB_URL :`mongodb+srv://admin:<EMAIL>/myFirstDatabase?retryWrites=true&w=majority`, // Your mongodb url or mongoATLAS url will go here
productImageSavingLocation : '../public/images/product-img/',
websiteImageSavingLocation : '../public/images/website-img/'
}<file_sep>'use strict'
const mongoose = require('mongoose'),
Schema = mongoose.Schema
let productSchema = new Schema({
_id : {
type : Schema.Types.ObjectId,
auto : true,
required : true
},
name: {
type: String,
required: true
},
metaData : {
type : Schema.Types.Mixed,
required : true
},
category:{
type:String,
required:true
},
subCategory : {
type :String,
require:false
},
price: {
type: Number
},
old_price : {
type: Number,
default : 0
},
description: {
type: String,
required : true
},
/* _vendorID: {
type: Schema.Types.ObjectId,
ref : 'Seller',
//required : true
}, */
images : {
type : [String]
},
rating : {
type : Number,
Default : 0
},
QualityType : {
type : String,
default : "New"
},
termsAndConditions : {
type : String
},
highlights : {
type : [String],
default : null
},
isPopular : {
type: Boolean,
default : false
},
favCount : {
type : Number,
default : 0
},
isOutOfStock : {
type : Boolean,
default : false
}
});
module.exports = mongoose.model('Product', productSchema)
| 9f473b7b1c1d6bfe398523b8eb5e347e17b36a78 | [
"JavaScript"
] | 4 | JavaScript | Abe731/CUBS | 5314baee075bb03276cab78cd443185934b74928 | a74bb66d31698df347437c3d49f872ee76a158d1 |
refs/heads/main | <repo_name>Aura1226/Day05<file_sep>/src/Practice/BokBulBokTest.java
package Practice;
public class BokBulBokTest {
public static void main(String[] args) {
BokBulBok run = new BokBulBok();
// 복불복 기계안에 준비작업
run.ready();
// 10번 결과를 확인해본다.
// 그 중에 한번은 x가 나와야한다.
for (int i = 0; i < 10; i++) {
char result = run.selectOne();
System.out.println(i+"번째: "+result);
}
}
}
<file_sep>/src/Practice/HomeWorkLotto2.java
package Practice;
import java.util.Arrays;
public class HomeWorkLotto2 {
public static void main(String[] args) {
// 결과와 전체 배열을 만들어준다.
int[] balls = new int[45];
int[] result = new int[6];
// 전체 배열의 각 인덱스를 채워준다
for (int i = 0; i < balls.length; i++) {
balls[i] = i + 1;
}
// 랜덤한 숫자를 뽑는 for loop만들기
for (int i = 0; i < result.length; i++) {
int num = (int)(Math.random() * 45 );
if ( balls[num] == -1 ) {
i--;
continue;
}
result[i] = num;
balls[num] = -1;
}
System.out.println(Arrays.toString(result));
}
}
<file_sep>/src/d5/KNNEx.java
package d5;
public class KNNEx {
public static double CalcDistance(int[] arr1, int[] arr2) {
double distance = 0;
// 루트(x2 - x1)^2 + (y2 - y1)^2
distance = Math.sqrt(Math.pow(arr2[0] - arr1[0] , 2 ) + Math.pow(arr2[1] - arr1[1], 2));
return distance;
}
public static void main(String[] args) {
int[][] arr = {
{6,4,1},
{7,2,1},
{5,2,1},
{4,5,2},
{3,4,2},
{3,2,2}
};
int[] targetArr = { 4,2 };
for (int i = 0; i < arr.length; i++) {
int[] temp = arr[i];
double distance = CalcDistance(targetArr, temp);
System.out.println(distance);
}
} // end main
}
<file_sep>/src/Practice/Airplane.java
package Practice;
public class Airplane {
int bombCount = 3;
public int getBombCount() {
return bombCount;
}
public void shootBullet() {
System.out.println("총알을 쏩니다.");
}
public void useBomb() {
if ( bombCount > 0 ) {
System.out.println("폭탄을 터트립니다.");
bombCount--;
System.out.println("남은 폭탄의 수: "+bombCount);
}else if ( bombCount == 0 ) {
System.out.println("터트릴 폭탄이 없습니다.");
}
}
}
<file_sep>/src/d5/CopyEx.java
package d5;
import java.util.Arrays;
public class CopyEx {
public static void main(String[] args) {
int[] arr = { 1,2,3,4,5,6,7,8,9 };
int[] arr2 = new int[5];
// arraycopy는 static
System.arraycopy(arr, 0, arr2, 0, 5);
System.out.println(Arrays.toString(arr2));
}
}
<file_sep>/src/Practice/PigSave.java
package Practice;
public class PigSave {
// private 사용하면 클래스의 범위 밖에서는 사용x
private int total; // 인스턴스 변수 = 데이터
public int getTotal() {
return total;
}
public void deposit(int amount) { // 메서드
System.out.println("저금통 입금");
total = total + amount;
}
public void withdraw() { // 메서드
System.out.println("저금통 출금");
}
}
<file_sep>/src/Practice/Shape.java
package Practice;
public class Shape {
private char type;
private int width;
private int height;
}
| 3ec6576a523a7901555acc97c87a4ada7f04c53d | [
"Java"
] | 7 | Java | Aura1226/Day05 | 8a2e34ba0ba388d5905bd32731d4989436a9cfd2 | 82aedc9c7deeb32ca7ce82c10af9095919437d52 |
refs/heads/master | <repo_name>gingerben93/2d-Project<file_sep>/2dProject/Assets/scripts/DoorToMainGame.cs
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
public class DoorToMainGame : MonoBehaviour
{
//[SerializeField]
//private int scene;
private bool loading = false;
public string loadMap;
//for getting mapgenerator
private GameObject mapGenerator;
public static DoorToMainGame DoorToMainGameSingle;
void Awake()
{
if (DoorToMainGameSingle == null)
{
DontDestroyOnLoad(gameObject);
DoorToMainGameSingle = this;
}
else if (DoorToMainGameSingle != this)
{
Destroy(gameObject);
}
}
void Update()
{
if (loading)
{
loading = false;
StartCoroutine(LoadNewScene());
}
}
IEnumerator LoadNewScene()
{
//stops player
PlayerController.PlayerControllerSingle.LockPosition();
//reset player skills and stuff
PlayerController.PlayerControllerSingle.ResetPlayer();
//load functions
AsyncOperation async = SceneManager.LoadSceneAsync("Area1");
// While the asynchronous operation to load the new scene is not yet complete, continue waiting until it's done.
while (!async.isDone)
{
yield return null;
}
//lets player move after loading
PlayerController.PlayerControllerSingle.UnLockPosition();
PlayerController.PlayerControllerSingle.touchingDoor = false;
Destroy(gameObject);
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
loading = true;
}
}
}
<file_sep>/2dProject/Assets/scripts/GameInformation/InventorySystem/Inventory.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class Inventory : MonoBehaviour
{
//Used when moving around items to equipment slots.
public Item info, info2;
//int alph; //For moving items when canvas is hidden
private RectTransform invRect;
private float invWidth, invHeight;
public int slots;
public int rows;
public float slotPaddingLeft, slotPaddingTop;
public float slotSize;
public GameObject slotPrefab;
private static Slot from, to;
private List<GameObject> allSlots;
public GameObject iconPrefab;
private static GameObject hoverObject;
private static int emptySlots;
private Canvas canvas;
private float hoverYOffset;
public static int EmptySlots
{
get
{
return emptySlots;
}
set
{
emptySlots = value;
}
}
//for changing weapong attacks
//GameObject WeaponAttacks;
GameObject Attack;
GameObject WeaponGameobject;
public static Inventory InventorySingle;
void Awake()
{
if (InventorySingle == null)
{
InventorySingle = this;
}
else if (InventorySingle != this)
{
Destroy(gameObject);
}
}
//Tooltip for items
public GameObject tooltipObject;
private static GameObject tooltip;
public Text sizeTextObject;
private static Text sizeText;
public Text visualTextObject;
private static Text visualText;
// Use this for initialization
void Start()
{
//for changing attacks
//WeaponAttacks = GameObject.Find("Hero");
tooltip = tooltipObject;
sizeText = sizeTextObject;
visualText = visualTextObject;
//reference to canvas
canvas = (Canvas)GetComponentInParent(typeof(Canvas));
CreateLayout();
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0) && hoverObject)
{
if (!EventSystem.current.IsPointerOverGameObject(-1) && from != null)
{
from.GetComponent<Image>().color = Color.white;
from.ClearSlot();
Destroy(hoverObject);
to = null;
from = null;
//hoverObject = null;
}
}
if (hoverObject != null)
{
Vector2 position;
RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform, Input.mousePosition, canvas.worldCamera, out position);
position.Set(position.x, position.y - hoverYOffset);
hoverObject.transform.position = canvas.transform.TransformPoint(position);
}
}
private void CreateLayout()
{
allSlots = new List<GameObject>();
hoverYOffset = slotSize * 0.01f;
emptySlots = slots;
invWidth = (slots / rows) * (slotSize + slotPaddingLeft) + slotPaddingLeft;
invHeight = rows * (slotSize + slotPaddingTop) + slotPaddingTop;
invRect = GetComponent<RectTransform>();
invRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, invWidth);
invRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, invHeight);
int columns = slots / rows;
for (int y = 0; y < rows; y++)
{
for (int x = 0; x < columns; x++)
{
if (y == 0 && x == 0)
{
GameObject newSlot = (GameObject)Instantiate(slotPrefab);
RectTransform slotRect = newSlot.GetComponent<RectTransform>();
newSlot.name = "HELM";
newSlot.transform.SetParent(this.transform.parent);
//Helm location
slotRect.localPosition = invRect.localPosition + new Vector3(-5 + (slotSize * 6), -10 - (slotSize * y));
slotRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, slotSize);
slotRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, slotSize);
//allSlots.Add(newSlot);
newSlot.transform.SetParent(this.transform);
}
if (y == 0 && x == 1)
{
GameObject newSlot = (GameObject)Instantiate(slotPrefab);
RectTransform slotRect = newSlot.GetComponent<RectTransform>();
newSlot.name = "AMULET";
newSlot.transform.SetParent(this.transform.parent);
//Amulet Location
slotRect.localPosition = invRect.localPosition + new Vector3(5 + (slotSize * 7), -20 - (slotSize * y));
slotRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, slotSize);
slotRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, slotSize);
//allSlots.Add(newSlot);
newSlot.transform.SetParent(this.transform);
}
if (y == 0 && x == 2)
{
GameObject newSlot = (GameObject)Instantiate(slotPrefab);
RectTransform slotRect = newSlot.GetComponent<RectTransform>();
newSlot.name = "WEAPON";
newSlot.transform.SetParent(this.transform.parent);
//Weapon Location
slotRect.localPosition = invRect.localPosition + new Vector3((slotSize * 4), -30 - (slotSize * y));
slotRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, slotSize);
slotRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, slotSize * 3);
//allSlots.Add(newSlot);
newSlot.transform.SetParent(this.transform);
}
if (y == 0 && x == 3)
{
GameObject newSlot = (GameObject)Instantiate(slotPrefab);
RectTransform slotRect = newSlot.GetComponent<RectTransform>();
newSlot.name = "CHEST";
newSlot.transform.SetParent(this.transform.parent);
//Body Location
slotRect.localPosition = invRect.localPosition + new Vector3(5 + (slotSize * 5), -40 - (slotSize * y));
slotRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, slotSize * 2);
slotRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, slotSize * 3);
//allSlots.Add(newSlot);
newSlot.transform.SetParent(this.transform);
}
if (y == 0 && x == 4)
{
GameObject newSlot = (GameObject)Instantiate(slotPrefab);
RectTransform slotRect = newSlot.GetComponent<RectTransform>();
newSlot.name = "SHIELD";
newSlot.transform.SetParent(this.transform.parent);
//Shield Location
slotRect.localPosition = invRect.localPosition + new Vector3(-5 + (slotSize * 8), -50 - (slotSize * y));
slotRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, slotSize * 2);
slotRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, slotSize * 2);
//allSlots.Add(newSlot);
newSlot.transform.SetParent(this.transform);
}
if (y == 0 && x == 5)
{
GameObject newSlot = (GameObject)Instantiate(slotPrefab);
RectTransform slotRect = newSlot.GetComponent<RectTransform>();
newSlot.name = "GLOVES";
newSlot.transform.SetParent(this.transform.parent);
//Gloves Location
slotRect.localPosition = invRect.localPosition + new Vector3((slotSize * 4), -95 - (slotSize * y));
slotRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, slotSize);
slotRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, slotSize * 2);
//allSlots.Add(newSlot);
newSlot.transform.SetParent(this.transform);
}
if (y == 0 && x == 6)
{
GameObject newSlot = (GameObject)Instantiate(slotPrefab);
RectTransform slotRect = newSlot.GetComponent<RectTransform>();
newSlot.name = "BELT";
newSlot.transform.SetParent(this.transform.parent);
//Waist Location
slotRect.localPosition = invRect.localPosition + new Vector3(5 + (slotSize * 5), -110 - (slotSize * y));
slotRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, slotSize * 2);
slotRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, slotSize);
//allSlots.Add(newSlot);
newSlot.transform.SetParent(this.transform);
}
if (y == 0 && x == 7)
{
GameObject newSlot = (GameObject)Instantiate(slotPrefab);
RectTransform slotRect = newSlot.GetComponent<RectTransform>();
newSlot.name = "BOOTS";
newSlot.transform.SetParent(this.transform.parent);
//Boots Location
slotRect.localPosition = invRect.localPosition + new Vector3(5 + (slotSize * 5), -135 - (slotSize * y));
slotRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, slotSize * 2);
slotRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, slotSize);
//allSlots.Add(newSlot);
newSlot.transform.SetParent(this.transform);
}
if (y == 0 && x == 8)
{
GameObject newSlot = (GameObject)Instantiate(slotPrefab);
RectTransform slotRect = newSlot.GetComponent<RectTransform>();
newSlot.name = "RING";
newSlot.transform.SetParent(this.transform.parent);
//Ring1 Location
slotRect.localPosition = invRect.localPosition + new Vector3((slotSize * 8), -100 - (slotSize * y));
slotRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, slotSize);
slotRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, slotSize);
//allSlots.Add(newSlot);
newSlot.transform.SetParent(this.transform);
}
if (y == 0 && x == 9)
{
GameObject newSlot = (GameObject)Instantiate(slotPrefab);
RectTransform slotRect = newSlot.GetComponent<RectTransform>();
newSlot.name = "RING";
newSlot.transform.SetParent(this.transform.parent);
//Ring2 Location
slotRect.localPosition = invRect.localPosition + new Vector3((slotSize * 8), -125 - (slotSize * y));
slotRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, slotSize);
slotRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, slotSize);
//allSlots.Add(newSlot);
newSlot.transform.SetParent(this.transform);
}
if (y > 7)
{
GameObject newSlot = (GameObject)Instantiate(slotPrefab);
RectTransform slotRect = newSlot.GetComponent<RectTransform>();
newSlot.name = "Slot";
newSlot.transform.SetParent(this.transform.parent);
//Inventory slots
slotRect.localPosition = invRect.localPosition + new Vector3(slotPaddingLeft * (x + 1) + (slotSize * x), -slotPaddingTop * (y + 1) - (slotSize * y));
slotRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, slotSize);
slotRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, slotSize);
allSlots.Add(newSlot);
newSlot.transform.SetParent(this.transform);
}
}
}
//Helm Location
}
public bool AddItem(Item item)
{
if (item.maxSize == 1)
{
PlaceEmpty(item);
return true;
}
else
{
foreach (GameObject slot in allSlots)
{
Slot tmp = slot.GetComponent<Slot>();
if (!tmp.IsEmpty)
{
if (tmp.CurrentItem.type == item.type && tmp.IsAvailable)
{
tmp.AddItem(item);
return true;
}
}
}
if (emptySlots > 0)
{
PlaceEmpty(item);
}
}
return false;
}
private bool PlaceEmpty(Item item)
{
if (emptySlots > 0)
{
foreach (GameObject slot in allSlots)
{
Slot tmp = slot.GetComponent<Slot>();
if (tmp.IsEmpty)
{
tmp.AddItem(item);
emptySlots--;
return true;
}
}
}
return false;
}
//moves items and changes player stats
public void MoveItem(GameObject clicked)
{
if (from == null)
{
if (!clicked.GetComponent<Slot>().IsEmpty)
{
from = clicked.GetComponent<Slot>();
from.GetComponent<Image>().color = Color.gray;
hoverObject = (GameObject)Instantiate(iconPrefab);
hoverObject.GetComponent<Image>().sprite = clicked.GetComponent<Image>().sprite;
hoverObject.name = clicked.GetComponent<Image>().sprite.name;
RectTransform hoverTransform = hoverObject.GetComponent<RectTransform>();
RectTransform clickedTransform = clicked.GetComponent<RectTransform>();
hoverTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, clickedTransform.sizeDelta.x);
hoverTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, clickedTransform.sizeDelta.y);
hoverObject.transform.SetParent(GameObject.Find("InvMenuCanvas").transform, true);
hoverObject.transform.localScale = from.gameObject.transform.localScale;
}
}
else if (to == null)
{
to = clicked.GetComponent<Slot>();
Destroy(hoverObject);
}
if (to != null && from != null)
{
Stack<Item> tmpTo = new Stack<Item>(to.Items);
if (tmpTo.Count == 0)
{
info = from.Items.Peek();
//Debug.Log(" 2 from.gameObject.name = " + from.gameObject.name + " to.gameObject.name = " + to.gameObject.name);
//Debug.Log(" 2 info.type.ToString() = " + info.type.ToString());
//if swapping to a slot of same name, weapons swaping spot
if (from.gameObject.name == to.gameObject.name)
{
to.AddItems(from.Items);
from.ClearSlot();
}
//swap to slot of same name then equipt item
else if (info.type.ToString() == to.gameObject.name)
{
info.Use();
to.AddItems(from.Items);
from.ClearSlot();
}
//unequipt item when swap out of slot
else if (to.gameObject.name == "Slot" && info.type.ToString() == from.gameObject.name)
{
info.UnEquipt();
to.AddItems(from.Items);
from.ClearSlot();
}
else if(to.gameObject.name == "Slot")
{
to.AddItems(from.Items);
from.ClearSlot();
}
}
else
{
info = from.Items.Peek();
info2 = to.Items.Peek();
//Debug.Log(" 2 from.gameObject.name = " + from.gameObject.name + " to.gameObject.name = " + to.gameObject.name);
//Debug.Log(" 2 info.type.ToString() = " + info.type.ToString() + " info2.type.ToString() = " + info2.type.ToString());
//if swapping to a slot of same name, weapons swaping spot
if (from.gameObject.name == to.gameObject.name)
{
to.AddItems(from.Items);
from.AddItems(tmpTo);
}
else if (info.type.ToString() == to.gameObject.name)
{
//order when decide if armor is over or under what is should be fore a very little amount of time
info2.UnEquipt();
info.Use();
to.AddItems(from.Items);
from.AddItems(tmpTo);
}
else if(from.gameObject.name == info2.type.ToString())
{
info.UnEquipt();
info2.Use();
to.AddItems(from.Items);
from.AddItems(tmpTo);
}
else if(to.gameObject.name == from.gameObject.name)
{
to.AddItems(from.Items);
from.AddItems(tmpTo);
}
}
from.GetComponent<Image>().color = Color.white;
info = null;
info2 = null;
to = null;
from = null;
hoverObject = null;
}
}
public void ShowToolTip(GameObject slot)
{
Slot tmpSlot = slot.GetComponent<Slot>();
//If item in a slot and hovering over item with mouse
if (!tmpSlot.IsEmpty && hoverObject == null)
{
visualText.text = tmpSlot.CurrentItem.GetToolTip();
sizeText.text = visualText.text;
tooltip.SetActive(true);
float xPos = slot.transform.position.x + slotPaddingLeft;
float yPos = slot.transform.position.y - slot.GetComponent<RectTransform>().sizeDelta.y - slotPaddingTop;
tooltip.transform.position = new Vector2(xPos, yPos);
}
}
public void HideToolTip()
{
tooltip.SetActive(false);
}
public void SelectWeapon(string weaponName)
{
if (weaponName == "Blowdart")
{
//instantiate a object with the weapon attack on it
Attack = Resources.Load("Prefabs/WeaponAttacks/BlowDartAttack", typeof(GameObject)) as GameObject;
WeaponGameobject = Instantiate(Attack, GameObject.Find("WeaponAttack").transform);
WeaponGameobject.name = "BlowDartAttack";
WeaponGameobject.transform.localPosition = Vector3.zero;
//set attack and damage
Blowdart temp = WeaponGameobject.GetComponent<Blowdart>();
PlayerController.PlayerControllerSingle.playerAttack += temp.Attack;
//set damage
}
else if (weaponName == "ShortSword")
{
//instantiate a object with the weapon attack on it
Attack = Resources.Load("Prefabs/WeaponAttacks/ShortSwordAttack", typeof(GameObject)) as GameObject;
WeaponGameobject = Instantiate(Attack, GameObject.Find("WeaponAttack").transform);
WeaponGameobject.name = "ShortSwordAttack";
WeaponGameobject.transform.localPosition = Vector3.zero;
ShortSword temp = WeaponGameobject.GetComponent<ShortSword>();
PlayerController.PlayerControllerSingle.playerAttack += temp.Attack;
//ShortSword temp = GameObject.Find("WeaponAttack").AddComponent<ShortSword>();
//GameController.GameControllerSingle.playerAttack = temp.Attack;
}
else if (weaponName == "GodHands")
{
Attack = Resources.Load("Prefabs/WeaponAttacks/GodHands", typeof(GameObject)) as GameObject;
WeaponGameobject = Instantiate(Attack, GameObject.Find("WeaponAttack").transform);
WeaponGameobject.name = "GodHands";
WeaponGameobject.transform.localPosition = Vector3.zero;
GodHands temp = WeaponGameobject.GetComponent<GodHands>();
temp.targetLocation = GameObject.Find("Hero").transform.position;
PlayerController.PlayerControllerSingle.playerAttack += temp.Attack;
}
}
public void UnequiptWeapon(string weaponName)
{
if (weaponName == "Blowdart")
{
Destroy(GameObject.Find("BlowDartAttack"));
}
else if (weaponName == "ShortSword")
{
Destroy(GameObject.Find("ShortSwordAttack"));
}
else if (weaponName == "GodHands")
{
Destroy(GameObject.Find("GodHands"));
}
}
}
<file_sep>/2dProject/Assets/scripts/Items/Magnet.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Magnet : MonoBehaviour
{
Rigidbody2D rbd2OfItem;
bool attract = false;
bool deathPhase = false;
public float attractDistance = 10f;
public bool faceTarget;
public float attractSpeed = .2f;
public int magicChange;
public int healthChange;
void Start()
{
rbd2OfItem = gameObject.GetComponent<Rigidbody2D>();
attractSpeed = Random.Range(.1f, .3f);
}
void LateUpdate()
{
if (attract && !deathPhase)
{
//face target
if (faceTarget)
{
var dir = PlayerController.PlayerControllerSingle.transform.position - transform.position;
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
//move toward target
transform.position = Vector3.MoveTowards(gameObject.transform.position, PlayerController.PlayerControllerSingle.transform.position, attractSpeed);
if (Vector2.Distance(transform.position, PlayerController.PlayerControllerSingle.transform.position) <= 1f)
{
//check with all gather quest that item was needed
GatherQuest[] listGatherQuests = QuestController.QuestControllerSingle.GetComponentsInChildren<GatherQuest>();
if (listGatherQuests.Length > 0)
{
foreach( GatherQuest quest in listGatherQuests)
{
if(gameObject.name == quest.gatherTarget)
{
quest.gatherQuestCounter += 1;
quest.UpdateGatherQuest();
}
}
}
//put item in iventory
if (gameObject.tag == "Item")
{
Inventory.InventorySingle.AddItem(gameObject.GetComponent<Item>());
}
deathPhase = true;
//if has particle system then do resource change
if (gameObject.GetComponent<ParticleSystem>())
{
gameObject.GetComponent<ParticleSystem>().Stop();
PlayerStats.PlayerStatsSingle.ChangeHealth(healthChange);
PlayerStats.PlayerStatsSingle.ChangeMagic(magicChange);
Destroy(gameObject, 1f);
}
else
{
Destroy(gameObject);
}
}
}
else if (Vector3.Distance(gameObject.transform.position, PlayerController.PlayerControllerSingle.transform.position) < PlayerStats.PlayerStatsSingle.itemAttractDistance)
{
rbd2OfItem.simulated = false;
attract = true;
}
}
}
<file_sep>/2dProject/Assets/scripts/EmenyStuff/GodHands.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GodHands : Weapon {
GodHandsFist godHandsFist;
GodHandsFistPlayer godHandsFistPlayer;
public Transform fistPrefab;
public GameObject fistPlayerPrefab;
public Transform PlayerFistLocation;
public Vector3 targetLocation;
public bool GodhandsCanAttack = true;
Transform fist;
void Start()
{
fistPlayerPrefab = Resources.Load("Prefabs/WeaponProjectiles/FistPlayer", typeof(GameObject)) as GameObject;
}
public override void Attack()
{
if (GodhandsCanAttack)
{
GodhandsCanAttack = false;
PlayerFistLocation = GameObject.Find("PlayerProjectiles").transform;
GameObject weaponTransform = Instantiate(fistPlayerPrefab, GameObject.Find("PlayerProjectiles").transform) as GameObject;
//set child to have reference to parent
weaponTransform.GetComponent<GodHandsFistPlayer>().parent = this;
weaponTransform.name = "Fist";
godHandsFistPlayer = GameObject.Find("PlayerProjectiles").transform.GetComponentInChildren<GodHandsFistPlayer>();
godHandsFistPlayer.pullAttackOn = true;
godHandsFistPlayer.newTargetLocation = Camera.main.ScreenToWorldPoint(Input.mousePosition);
godHandsFistPlayer.gotoPosition = PlayerController.PlayerControllerSingle.transform.position;
godHandsFistPlayer.userTransform = weaponTransform.GetComponent<Transform>();
godHandsFistPlayer.userTransform.position = PlayerController.PlayerControllerSingle.transform.position;
}
}
public void AttackBoss(Vector3 targetLocation)
{
fist = Instantiate(fistPrefab, transform);
fist.name = "Fist";
godHandsFist = transform.GetComponentInChildren<GodHandsFist>();
godHandsFist.tag = "EnemyProjectile";
godHandsFist.pullAttackOn = true;
godHandsFist.newTargetLocation = targetLocation;
godHandsFist.gotoPosition = transform.position;
godHandsFist.userTransform = fist.GetComponent<Transform>();
godHandsFist.userTransform.position = transform.position;
}
}
<file_sep>/2dProject/Assets/scripts/BossRoom/DamagePlayerOnCollision.cs
using UnityEngine;
public class DamagePlayerOnCollision : MonoBehaviour
{
private Rigidbody2D rb2d;
void Start()
{
rb2d = GameObject.Find("Hero").GetComponent<Rigidbody2D>();
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Player")
{
PlayerStats.PlayerStatsSingle.health -= 1;
rb2d.AddForce(new Vector2(0f, -500f));
}
}
}
<file_sep>/2dProject/Assets/scripts/PlayerScripts/GrapplingHookTip.cs
using UnityEngine;
using System.Collections;
public class GrapplingHookTip : MonoBehaviour {
DrawGrapHook drawGrapHook;
void Start()
{
drawGrapHook = transform.parent.GetComponentInChildren<DrawGrapHook>();
//get the rb2d that joint is connected to
GetComponent<DistanceJoint2D>().connectedBody = PlayerController.PlayerControllerSingle.GetComponent<Rigidbody2D>();
}
public void OnTriggerEnter2D(Collider2D tip)
{
if (tip.gameObject.GetComponent<EdgeCollider2D>())
{
}
gameObject.GetComponent<Rigidbody2D>().velocity = Vector2.zero;
gameObject.GetComponent<Rigidbody2D>().isKinematic = true;
GetComponent<DistanceJoint2D>().distance = Vector2.Distance(transform.position, PlayerController.PlayerControllerSingle.transform.position);
GetComponent<DistanceJoint2D>().enabled = true;
drawGrapHook.HasTipCollided = true;
//give player back jumps if has skill
if (PlayerController.PlayerControllerSingle.hookResetJumpsSkill)
{
PlayerController.PlayerControllerSingle.jumpCounter = PlayerStats.PlayerStatsSingle.maxJumps;
}
if (tip.tag == "Enemy" && drawGrapHook.hitEnemy == false)
{
drawGrapHook.InstanceID = tip.GetInstanceID();
drawGrapHook.hitEnemy = true;
drawGrapHook.enemyTransform = tip.transform;
}
}
public void OnTriggerExit2D(Collider2D coll)
{
if (coll.gameObject.tag == "Enemy" && drawGrapHook.InstanceID == coll.GetInstanceID())
{
drawGrapHook.hitEnemy = false;
drawGrapHook.InstanceID = 0;
}
}
}
<file_sep>/2dProject/Assets/scripts/Spells/Scroll/FireballScroll.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class FireballScroll : MonoBehaviour {
public Sprite sprite;
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Player")
{
GameObject.Find("Fire").GetComponent<Button>().interactable = true;
GameObject.Find("Fire").GetComponent<Image>().sprite = sprite;
Destroy(gameObject);
}
}
}
<file_sep>/2dProject/Assets/scripts/EmenyStuff/SpinAttack.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpinAttack : MonoBehaviour {
//variables
float length;
float speed;
GameObject closeBar;
GameObject farBar;
SpriteRenderer closeImage;
SpriteRenderer farImage;
//for particle systems
private ParticleSystem FarParticle;
private ParticleSystem CloseParticle;
ParticleSystem.ShapeModule shapeModule;
// Use this for initialization
void Start ()
{
closeBar = transform.Find("CloseBar").gameObject;
closeImage = closeBar.transform.GetComponentInChildren<SpriteRenderer>();
CloseParticle = closeBar.transform.GetComponentInChildren<ParticleSystem>();
farBar = transform.Find("FarBar").gameObject;
farImage = farBar.transform.GetComponentInChildren<SpriteRenderer>();
FarParticle = farBar.transform.GetComponentInChildren<ParticleSystem>();
//transform.position = new Vector2(Random.Range(-50, 50), Random.Range(-50, 50));
//length = Vector2.Distance(PlayerController.PlayerControllerSingle.transform.position, transform.position);
length = Random.Range(10, 50);
speed = Random.Range(.1f, 1f);
//2+ for offset of rotation point
closeBar.transform.localPosition = new Vector3(0, 2 + length * .25f, 0);
closeBar.GetComponent<BoxCollider2D>().size = new Vector2(1, length * .5f);
closeImage.size = new Vector2(1, length / 2);
shapeModule = CloseParticle.shape;
shapeModule.radius = length / 4;
farBar.transform.localPosition = new Vector3(0, length, 0);
farBar.GetComponent<BoxCollider2D>().size = new Vector2(1, length * .5f);
farImage.size = new Vector2(1, length / 2);
shapeModule = FarParticle.shape;
shapeModule.box = new Vector3(1, length / 2, 1);
}
// Update is called once per frame
void Update ()
{
if (Vector2.Distance(PlayerController.PlayerControllerSingle.transform.position, transform.parent.transform.position) <= 500f)
{
transform.eulerAngles = new Vector3(0, 0, (transform.eulerAngles.z - speed));
}
}
void OnTriggerEnter2D(Collider2D collision)
{
if(collision.gameObject.tag == "Player")
{
//Debug.Log("hit player");
PlayerController.PlayerControllerSingle.DamagePlayer(1);
}
}
}
<file_sep>/2dProject/Assets/scripts/GameInformation/GameLoader.cs
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
public class GameLoader : MonoBehaviour {
public static GameLoader GameLoaderSingle;
public PlayerData playerDat;
void Awake()
{
if (GameLoaderSingle == null)
{
DontDestroyOnLoad(gameObject);
GameLoaderSingle = this;
}
else if (GameLoaderSingle != this)
{
Destroy(gameObject);
}
//loads player information, doesn't currently do anyting
if (File.Exists(Application.persistentDataPath + "/playerInfo.dat"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/playerInfo.dat", FileMode.Open);
playerDat = (PlayerData)bf.Deserialize(file);
file.Close();
}
}
}<file_sep>/2dProject/Assets/scripts/GameInformation/QuestController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class QuestController : MonoBehaviour {
//quest text prefab
public Text QuestTxt;
//main story quest counter
public float currentMainQuest;
public Text MainQuestText;
public static QuestController QuestControllerSingle;
//parent
GameObject parentQuest;
//names of enemies for kill quests
string[] EnemyNames = new string[]
{
"Enemy",
"SliderEnemy",
};
//names of items to gather // needs to be same name as prefabs object in resource folder
string[] GatherTargets = new string[]
{
"ManaPotion",
"HealthPotion",
};
void Awake()
{
if (QuestControllerSingle == null)
{
DontDestroyOnLoad(gameObject);
QuestControllerSingle = this;
}
else if (QuestControllerSingle != this)
{
Destroy(gameObject);
}
//currentQuest = 0f;
}
void Start()
{
//main quest text box
parentQuest = GameObject.Find("QuestTitlePanel/QuestListPanel");
MainQuestText = Instantiate(QuestTxt, parentQuest.transform);
MainQuestText.name = "MainQuest";
MainQuestText.text = "Complete Quest " + currentMainQuest;
//check if player is on main quest
if (currentMainQuest == 2f)
{
Debug.Log("quest is 2");
Debug.Log(currentMainQuest + " = QuestController.QuestControllerSingle.currentQuest");
GameObject.Find("Hero").AddComponent<MainQuest2_0>();
}
else if (QuestController.QuestControllerSingle.currentMainQuest == 5f)
{
Debug.Log(QuestController.QuestControllerSingle.currentMainQuest + " = QuestController.QuestControllerSingle.currentQuest");
GameObject.Find("Hero").AddComponent<MainQuest5_0>();
Debug.Log("quest is 5");
}
else if (currentMainQuest == 6f)
{
Debug.Log("quest is 6");
Debug.Log(currentMainQuest + " = QuestController.QuestControllerSingle.currentQuest");
GameObject.Find("Hero").AddComponent<MainQuest6_0>();
}
else if (currentMainQuest == 10f)
{
Debug.Log("quest is 10");
Debug.Log(currentMainQuest + " = QuestController.QuestControllerSingle.currentQuest");
GameObject.Find("Hero").AddComponent<MainQuest10_0>();
}
}
public void PickQuest(string NPCName, int questType)
{
switch (questType)
{
case 1:
Debug.Log("Quest 1");
//Instantiate(GatherQuestPrefab, GameController.GameControllerSingle.transform);
KillQuest(NPCName);
break;
case 2:
Debug.Log("Quest 2");
//Instantiate(GatherQuestPrefab, GameController.GameControllerSingle.transform);
GatherQuest(NPCName);
break;
case 3:
Debug.Log("Quest 3");
break;
default:
Debug.Log("No Quest");
break;
}
}
public void UpdateKillQuest(string EnemyName)
{
//Text updateQuest = GameObject.Find("QuestPanel/Enemy").GetComponent<Text>();
//updateQuest.text = "kill " + killamount + " of " + killtarget + "\n Current kills: " + KillQuestCounter;
//if (KillQuestCounter == killamount)
//{
// questList[killQuestList[EnemyName]] = true;
// killQuestList.Remove(EnemyName);
// updateQuest.text = "Quest complete";
//}
}
private void KillQuest(string NPCName)
{
//gameObject.AddComponent<KillQuest>();
//KillQuest KillQuestClass = GetComponent<KillQuest>();
//would rather do the method above if possible
GameObject QuestGameobject = new GameObject(NPCName + " Kill Quest");
QuestGameobject.GetComponent<Transform>().SetParent(transform);
KillQuest KillQuestClass = QuestGameobject.AddComponent<KillQuest>();
Text QuestTextBox = Instantiate(QuestTxt, parentQuest.transform);
//Text QuestTextBox = Object.Instantiate<Text>(QuestTxt, parentQuest.transform);
//gather target random number
int killTargetNumber = Random.Range(0, EnemyNames.Length);
//assign quest vaiables
Debug.Log("NPCName = " + NPCName);
KillQuestClass.questGiver = NPCName;
KillQuestClass.killAmount = Random.Range(2, 5);
KillQuestClass.killTarget = EnemyNames[killTargetNumber];
//KillQuestClass.killItemPrefab = Resources.Load("Prefabs/Items/" + GatherTargets[killTargetNumber]) as GameObject;
KillQuestClass.killQuestCounter = 0;
KillQuestClass.QuestTxt = QuestTextBox;
//name of text box for quest; happens in gatherQuestStarter()
QuestTextBox.name = NPCName + " Kill ";
//start quest
KillQuestClass.KillQuestStarter();
}
private void GatherQuest(string NPCName)
{
//this puts them on gamedata; multiple of same type is giving weird error for now; might be solvable
//gameObject.AddComponent<GatherQuest>();
//GatherQuest GatherQuestClass = GetComponent<GatherQuest>();
//would rather do the method above if possible
GameObject QuestGameobject = new GameObject(NPCName + " Gather Quest");
QuestGameobject.GetComponent<Transform>().SetParent(transform);
GatherQuest GatherQuestClass = QuestGameobject.AddComponent<GatherQuest>();
Text QuestTextBox = Instantiate(QuestTxt, parentQuest.transform);
//Text QuestTextBox = Object.Instantiate<Text>(QuestTxt, parentQuest.transform);
//gather target random number
int gatherTargetNumber = Random.Range(0, GatherTargets.Length);
//assign quest vaiables
Debug.Log("NPCName = " + NPCName);
GatherQuestClass.questGiver = NPCName;
GatherQuestClass.gatherAmount = Random.Range(2, 5);
GatherQuestClass.gatherTarget = GatherTargets[gatherTargetNumber];
GatherQuestClass.gatherItemPrefab = Resources.Load("Prefabs/Items/" + GatherTargets[gatherTargetNumber]) as GameObject;
GatherQuestClass.gatherQuestCounter = 0;
GatherQuestClass.QuestTxt = QuestTextBox;
//name of text box for quest; happens in gatherQuestStarter()
QuestTextBox.name = NPCName + " Gather ";
//start quest
GatherQuestClass.GatherQuestStarter();
}
}
<file_sep>/2dProject/Assets/scripts/Healthbar.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Healthbar : MonoBehaviour {
public float maxHealth;
public float currentHealth;
public GameObject healthBar;
void Update()
{
DecreseHealth();
}
void DecreseHealth()
{
float calcHealth = currentHealth / maxHealth;
SetHealthBar(calcHealth);
}
void SetHealthBar(float health)
{
healthBar.transform.localScale = new Vector3(health, healthBar.transform.localScale.y, healthBar.transform.localScale.z);
}
}
<file_sep>/2dProject/Assets/scripts/GameInformation/LoadOnClick.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class LoadOnClick : MonoBehaviour {
//[SerializeField]
//private int scene;
[SerializeField]
private Text loadingText;
private bool loading = false;
private bool loadScene = false;
public string loadMap = "StartArea";
public static LoadOnClick LoadOnClickSingle;
// for getting scene name
Scene scene;
void Awake()
{
Scene scene = SceneManager.GetActiveScene();
loadMap = scene.name;
if (scene.name != "StartMenu")
{
if (LoadOnClickSingle == null)
{
//DontDestroyOnLoad(gameObject);
LoadOnClickSingle = this;
}
else if (LoadOnClickSingle != this)
{
Destroy(gameObject);
}
}
}
void Update() {
if (loading)
{
GameController.GameControllerSingle.RemoveEveryingOnMap();
loadMap = "StartArea";
PlayerController.PlayerControllerSingle.transform.position = new Vector3(-0f, 1.2f, 0);
loadScene = true;
loading = false;
loadingText.text = "Loading...";
StartCoroutine(LoadNewScene());
}
if (loadScene == true)
{
loadingText.color = new Color(loadingText.color.r, loadingText.color.g, loadingText.color.b, Mathf.PingPong(Time.time, .1f));
}
}
//load
public void LoadScene(int level)
{
loading = true;
}
IEnumerator LoadNewScene()
{
//stops player from moving during loading
PlayerController.PlayerControllerSingle.LockPosition();
//reset player
PlayerController.PlayerControllerSingle.ResetPlayer();
//load functions
AsyncOperation async = SceneManager.LoadSceneAsync(loadMap);
// While the asynchronous operation to load the new scene is not yet complete, continue waiting until it's done.
while (!async.isDone)
{
yield return null;
}
//lets player move after loading
PlayerController.PlayerControllerSingle.UnLockPosition();
//actives game controler for player actions
PlayerController.PlayerControllerSingle.touchingDoor = false;
GameController.GameControllerSingle.questTravel = false;
loadingText.text = "";
}
}
<file_sep>/2dProject/Assets/scripts/PlayerScripts/CamraController.cs
using UnityEngine;
using System.Collections;
public class CamraController : MonoBehaviour
{
private Transform player;
private Vector3 offset;
public static CamraController PLayerCamra;
void Awake()
{
if (PLayerCamra == null)
{
DontDestroyOnLoad(gameObject);
PLayerCamra = this;
}
else if (PLayerCamra != this)
{
Destroy(gameObject);
}
}
// Use this for initialization
void Start()
{
player = PlayerController.PlayerControllerSingle.transform;
offset = transform.position - player.transform.position;
transform.Rotate(Vector3.zero);
transform.position = PlayerController.PlayerControllerSingle.transform.position;
}
// Update is called once per frame
void LateUpdate()
{
transform.position = player.transform.position + offset;
transform.Rotate(Vector3.zero);
}
}
<file_sep>/2dProject/Assets/scripts/EmenyStuff/EnemyStats/Slider.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Slider : EnemyStats
{
public Transform HealthDrop;
public Transform loot; // 100% drop rate
public Transform loot2; // 5% drop rate
public Transform loot3; // 5% drop rate
void Start()
{
//turret items
items.Add(HealthDrop);
items.Add(loot);
items.Add(loot2);
items.Add(loot3);
StartStats();
}
public override void StartStats()
{
dropRate = .5f;
damagePlayerOnCollision = true;
health = 4;
experiencePoint = 1;
invincible = false;
}
//getting name is for seeing which part of the game object was hit if it was children
public override void Damage(int damageCount, string NameObject, float InvicTime)
{
//Debug.Log("NameObject = " + NameObject);
//Debug.Log("damageCount = " + damageCount);
//only want to damage slider if it get hit in turret; maybe just more damage, add that later
if (NameObject == "Image")
{
if (!invincible)
{
health -= damageCount;
if (health <= 0)
{
DeathPhase();
}
else
{
if (InvicTime > 0)
{
StartCoroutine(MakeInvincible(InvicTime));
}
}
}
}
}
}
<file_sep>/2dProject/Assets/scripts/PlayerScripts/GrapplingHookBody.cs
using UnityEngine;
using System.Collections;
public class GrapplingHookBody : MonoBehaviour
{
DrawGrapHook drawGrapHook;
void Start()
{
drawGrapHook = transform.parent.GetComponentInChildren<DrawGrapHook>();
}
public void OnCollisionStay2D(Collision2D coll)
{
if (coll.gameObject.GetComponent<EdgeCollider2D>() || coll.gameObject.GetComponent<BoxCollider2D>())
{
drawGrapHook.hitEnemy = false;
foreach (ContactPoint2D missileHit in coll.contacts)
{
Vector2 hitPoint = missileHit.point;
//Debug.Log("missileHit.point = " + missileHit.point);
drawGrapHook.rb2dTip.gameObject.transform.position = new Vector2(hitPoint.x, hitPoint.y) + missileHit.normal * .3f;
drawGrapHook.joint.distance = Vector2.Distance(drawGrapHook.rb2dTip.gameObject.transform.position, PlayerController.PlayerControllerSingle.transform.position);
break;
}
}
}
}
<file_sep>/2dProject/Assets/scripts/SideQuest/KillQuest.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class KillQuest : MonoBehaviour {
//quest text prefab object
public Text QuestTxt;
//quest giver name
public string questGiver { get; set; }
//Kill Quest variables
public int killQuestCounter { get; set; }
public int killAmount { get; set; }
public string killTarget { get; set; }
public void UpdateKillQuest()
{
//Text QuestTxt = GameObject.Find("QuestPanel/KillQuest").GetComponent<Text>();
QuestTxt.text = "Kill " + killAmount + " of " + killTarget + "\nCurrent Kills: " + killQuestCounter;
if (killQuestCounter >= killAmount)
{
QuestTxt.text = "Kill Quest Complete. Return to " + questGiver;
//for if thye main quest needs side quest complete to continue
if (GameController.GameControllerSingle.sideQuestBool == true)
{
GameController.GameControllerSingle.sideQuestCounter += 1;
}
}
}
public void KillQuestStarter()
{
QuestTxt.text = "kill " + killAmount + " of " + killTarget + "\nCurrent kills: " + killQuestCounter;
//QuestTxt.name = questGiver + " Gather " + gatherTarget;
}
}
<file_sep>/2dProject/Assets/scripts/BossRoom/BossPowerShield.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BossPowerShield : MonoBehaviour {
public bool notGrabbed = true;
public Rigidbody2D boss;
public static BossPowerShield BossPowerShieldSingle;
void Awake()
{
if (BossPowerShieldSingle == null)
{
BossPowerShieldSingle = this;
}
else if (BossPowerShieldSingle != this)
{
Destroy(gameObject);
}
}
void Start()
{
boss = GameObject.Find("Boss").GetComponent<Rigidbody2D>();
}
void Update()
{
//Cheks to see if Player is grabbed, is so then wait 2 seconds before reactivating shield and player collision
if (!notGrabbed)
{
StartCoroutine(Grabbed());
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
if (notGrabbed)
{
PlayerController.PlayerControllerSingle.freezePlayer = true;
Debug.Log(collision.gameObject.tag);
// Calculate Angle Between the collision point and the player
var dir = collision.transform.position - transform.position;
// We then get the opposite (-Vector3) and normalize it
dir.Normalize();
// And finally we add force in the direction of dir and multiply it by force.
// This will push back the player
Debug.Log(dir.x);
if(dir.x < 0.01f && dir.y >= 0.0f)
{
collision.GetComponent<Rigidbody2D>().velocity = new Vector3(0, 0, 0);
collision.GetComponent<Rigidbody2D>().AddForce(new Vector2(-500f, 500f));
}
else if (dir.x < 0.01f && dir.y < 0.0f)
{
collision.GetComponent<Rigidbody2D>().velocity = new Vector3(0, 0, 0);
collision.GetComponent<Rigidbody2D>().AddForce(new Vector2(-500f, 500f));
}
else
{
collision.GetComponent<Rigidbody2D>().velocity = new Vector3(0, 0, 0);
collision.GetComponent<Rigidbody2D>().AddForce(new Vector2(dir.x * 2000f, 500f));
}
BossScript.BossScriptSingle.charge = true;
boss.GetComponent<Rigidbody2D>().velocity = new Vector3(0, transform.GetComponent<Rigidbody2D>().velocity.y, 0);
StartCoroutine(StopPlayerControls());
}
}
if (collision.gameObject.tag == "Bullet")
{
Destroy(collision.gameObject);
}
}
IEnumerator StopPlayerControls()
{
yield return new WaitForSeconds(2);
PlayerController.PlayerControllerSingle.freezePlayer = false;
}
IEnumerator Grabbed()
{
yield return new WaitForSeconds(1);
notGrabbed = true;
}
}
<file_sep>/2dProject/Assets/scripts/GameInformation/StartGame.cs
using System.Collections;
using System.IO;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class StartGame : MonoBehaviour
{
//[SerializeField]
//private int scene;
[SerializeField]
private Text loadingText;
private bool loadNew = false;
private bool loadGame = false;
private bool isSceneLoading = false;
public string loadMap = "";
void Update()
{
if (loadNew)
{
isSceneLoading = true;
loadNew = false;
loadingText.text = "Loading...";
StartCoroutine(LoadNewScene());
}
if (loadGame)
{
isSceneLoading = true;
loadGame = false;
loadingText.text = "Continue...";
StartCoroutine(LoadNewScene());
}
if (isSceneLoading == true)
{
loadingText.color = new Color(loadingText.color.r, loadingText.color.g, loadingText.color.b, Mathf.PingPong(Time.time, .1f));
}
}
//load
public void LoadScene(int level)
{
loadNew = true;
}
public void ContinueGame(int level)
{
if (File.Exists(Application.persistentDataPath + "/playerInfo.dat"))
{
loadGame = true;
GameObject GameLoaderObject = Instantiate((GameObject)Resources.Load("player/GameLoader", typeof(GameObject)));
GameLoaderObject.name = "GameLoader";
DontDestroyOnLoad(GameLoaderObject);
}
else
{
Debug.Log("no data to load for player");
}
}
IEnumerator LoadNewScene()
{
AsyncOperation async = SceneManager.LoadSceneAsync(loadMap);
// While the asynchronous operation to load the new scene is not yet complete, continue waiting until it's done.
while (!async.isDone)
{
yield return null;
}
}
IEnumerator ContinueScene()
{
AsyncOperation async = SceneManager.LoadSceneAsync(loadMap);
// While the asynchronous operation to load the new scene is not yet complete, continue waiting until it's done.
while (!async.isDone)
{
yield return null;
}
}
}
<file_sep>/2dProject/Assets/scripts/Items/Weapons/DamageOnCollision.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DamageOnCollision : MonoBehaviour {
public int damage;
//set this on the game object; or from a different script like the weapon that is attacking
public float invincibleTimer = 0;
//stuff can only get hit once by anything
//public List<int> hasHit = new List<int>();
//for player attack
public delegate void OnCollide();
public OnCollide onCollide;
// coudl try some sort of cooldown system for hitting stuff
//void Update()
//{
// if(collideCoolDown > 0f)
// {
// collideCoolDown -= Time.deltaTime;
// }
//}
//recursive function check object then parent until stats found; explodes with they don't got stats
EnemyStats FindEnemyStat(GameObject obj)
{
EnemyStats STATS;
if (STATS = obj.GetComponent<EnemyStats>())
{
Debug.Log(obj.name);
return STATS;
}
else
{
return FindEnemyStat(obj.transform.parent.gameObject);
}
}
// a lot cheaper to make this enter
void OnTriggerEnter2D(Collider2D otherCollider)
//void OnTriggerStay2D(Collider2D otherCollider)
{
//if change to OnTriggerStay2D this make sure things only get hit once add if statement
//hasHit.Add(otherCollider.GetInstanceID());
Debug.Log(otherCollider.name);
Debug.Log(otherCollider.tag);
if (otherCollider.tag == "Enemy")
{
//find enemy stats if it has it
EnemyStats Enemy = FindEnemyStat(otherCollider.gameObject);
if (Enemy)
{
Enemy.Damage(damage, otherCollider.name, invincibleTimer);
}
else
{
Debug.Log("NO STATS FOUND");
}
if (onCollide != null)
{
onCollide();
}
}
else
{
if (onCollide != null)
{
onCollide();
}
}
}
}
<file_sep>/2dProject/Assets/scripts/EmenyStuff/Movement/MoveTowardPlayer.cs
using UnityEngine;
using System.Collections;
public class MoveTowardPlayer : MonoBehaviour {
private Transform player;
//
private Rigidbody2D enemyRigBody;
//
private float maxSpeed;
//
private Vector3 heading;
private float distance;
private Vector3 StartDirection;
private float distanceToPlayer;
//for enemy random movement
private int pickDirection;
private bool randomDirection;
private float enemySpeed;
private float noMovementThreshold;
private int noMovementFrames;
private Vector3[] previousLocations;
private float scriptDelayAmount;
private float scriptDelayLastTime;
// Use this for initialization
void Start ()
{
//enemy = transform.GetComponentInParent<Transform>();
player = PlayerController.PlayerControllerSingle.transform;
//
enemyRigBody = gameObject.GetComponent<Rigidbody2D>();
//
maxSpeed = 2f;
//for enemy direction
randomDirection = false;
noMovementThreshold = 0.0001f;
noMovementFrames = 3;
previousLocations = new Vector3[noMovementFrames];
scriptDelayAmount = .5f;
scriptDelayLastTime = 0;
}
void Update()
{
}
// Update is called once per frame
void FixedUpdate()
{
// make function for deciding when player can jump.
/*
set a min x and max x distance (probably y's too)
after min x and max x are found, try to jump at those x,y coordinates. (should be direction related also)
(don't always have to jump, just add that probablity in)
If it works, then check for new x max and x min.
if it fails (maybe a number of times) then stop jumping around that x (and y).
append those the x,y jumps when the min or max changes.
reset if both min and max become new.
*/
for (int i = 0; i < previousLocations.Length - 1; i++)
{
previousLocations[i] = previousLocations[i + 1];
}
previousLocations[previousLocations.Length - 1] = transform.position;
distanceToPlayer = Vector3.Distance(transform.position, player.position);
if (distanceToPlayer <= 10)
{
// set for picking direction after player leaves range
randomDirection = false;
if (distanceToPlayer <= 5)
{
enemyRigBody.velocity = new Vector2(enemyRigBody.velocity.x * .95f, enemyRigBody.velocity.y);
scriptDelayLastTime = Time.time + scriptDelayAmount;
}
else
{
//for jumping if chasing player and got stuck
if (scriptDelayLastTime < Time.time)
{
for (int i = 0; i < previousLocations.Length - 1; i++)
{
if (Vector3.Distance(previousLocations[i], previousLocations[i + 1]) <= noMovementThreshold)
{
enemyRigBody.AddForce(new Vector2(0f, 500));
scriptDelayLastTime = Time.time + scriptDelayAmount;
}
}
}
heading = player.position - transform.position;
distance = heading.magnitude;
StartDirection = heading / distance;
enemyRigBody.velocity = new Vector2(maxSpeed * StartDirection.x, enemyRigBody.velocity.y);
}
}
else
{
if (scriptDelayLastTime < Time.time)
{
//only pick start variables once
if (!randomDirection)
{
randomDirection = true;
pickDirection = Random.Range(0, 100);
if (pickDirection < 50)
{
enemySpeed = maxSpeed;
}
else
{
enemySpeed = -maxSpeed;
}
}
enemyRigBody.velocity = new Vector2(enemySpeed, enemyRigBody.velocity.y);
//check for hitting wall
for (int i = 0; i < previousLocations.Length - 1; i++)
{
pickDirection = Random.Range(0, 100);
if (Vector3.Distance(previousLocations[i], previousLocations[i + 1]) <= noMovementThreshold)
{
if (pickDirection < 49)
{
enemySpeed *= -1;
scriptDelayLastTime = Time.time + scriptDelayAmount;
}
else
{
enemyRigBody.AddForce(new Vector2(0f, 500));
scriptDelayLastTime = Time.time + scriptDelayAmount;
}
}
}
}
else
{
//waiting
}
}
}
}
<file_sep>/2dProject/Assets/scripts/EmenyStuff/ProjectileAttacks/ProjectileForward.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ProjectileForward : MonoBehaviour {
//object speed
float speed = 6f;
public float direction = 1;
// Use this for initialization
void Start ()
{
if(direction == -1)
{
gameObject.GetComponent<SpriteRenderer>().flipX = true;
}
//Last for 3 seconds
Destroy(gameObject, 3.0f);
//ProjectileMovement();
}
// Update is called once per frame
void Update ()
{
transform.position += direction*transform.right * speed * Time.deltaTime;
}
public void ProjectileMovement(Quaternion rotation)
{
transform.rotation = rotation;
}
void OnTriggerEnter2D(Collider2D otherCollider)
{
Destroy(gameObject);
}
}
<file_sep>/2dProject/Assets/scripts/DialogManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DialogManager : MonoBehaviour {
public Text NPCtext { get; set; }
public Text Herotext { get; set; }
public CanvasGroup canvas { get; set; }
public Image TalkingCharacter { get; set; }
public static DialogManager DialogManagerSingle;
//is dialog on
public bool dialogOn = false;
//skip dialogue
public bool leftClick = false;
public bool rightClick = false;
public string MainQuestDialogueLoadPath { get; private set; }
public string NPCDialogueLoadPath { get; private set; }
void Awake()
{
if (DialogManagerSingle == null)
{
DontDestroyOnLoad(gameObject);
DialogManagerSingle = this;
}
else if (DialogManagerSingle != this)
{
Destroy(gameObject);
}
NPCtext = GameObject.Find("DialogCanvas/Panel/NPCStuff/NPCText/Text").GetComponent<Text>();
Herotext = GameObject.Find("DialogCanvas/Panel/HeroStuff/HeroText/Text").GetComponent<Text>();
canvas = GameObject.Find("DialogCanvas").GetComponent<CanvasGroup>();
TalkingCharacter = GameObject.Find("DialogCanvas/Panel/NPCStuff/NPC").GetComponent<Image>();
}
// Use this for initialization
void Start ()
{
MainQuestDialogueLoadPath = "Dialog/MainQuest/";
NPCDialogueLoadPath = "Dialog/NPC/";
}
void Update()
{
if (dialogOn)
{
//left mouse click
if (Input.GetMouseButtonDown(0))
{
leftClick = true;
}
//right mouse
else if (Input.GetMouseButtonDown(1))
{
if (rightClick)
{
rightClick = false;
}
else
{
rightClick = true;
}
}
}
}
public IEnumerator Dialog(string Conversation)
{
if (dialogOn == false)
{
dialogOn = true;
leftClick = false;
rightClick = false;
Debug.Log(QuestController.QuestControllerSingle.currentMainQuest + " = QuestController.QuestControllerSingle.currentQuest");
TextAsset TextObject = Resources.Load(Conversation) as TextAsset;
string fullConversation = TextObject.text;
string[] perline = fullConversation.Split('\n');
for (int x = 0; x < perline.Length; x += 2)
{
Herotext.text = "";
foreach (char letter in perline[x].ToCharArray())
{
//skip dialogue
if (leftClick == true)
{
Herotext.text = perline[x];
leftClick = false;
break;
}
Herotext.text += letter;
yield return new WaitForSeconds(0.05f);
}
//for pause while talking if left click to continue
while (rightClick == true)
{
if (leftClick == true)
{
break;
}
yield return new WaitForSeconds(0.1f);
}
NPCtext.text = "";
foreach (char letter in perline[x + 1].ToCharArray())
{
//skip dialogue
if (leftClick == true)
{
NPCtext.text = perline[x + 1];
leftClick = false;
break;
}
NPCtext.text += letter;
yield return new WaitForSeconds(0.05f);
}
//for pause while talking
while (rightClick == true)
{
if (leftClick == true)
{
break;
}
yield return new WaitForSeconds(0.1f);
}
}
//stop checking for mouse inputs
dialogOn = false;
}
}
}
<file_sep>/2dProject/Assets/scripts/Spells/Magic.cs
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
public enum SpellType { FIRE, ICE, ZAP, HEAL, UNKNOWN }; //add more types here for items
public class Magic : MonoBehaviour
{
public SpellType type;
//item information
public string spellName;
public string description;
//sprite
public Sprite spriteNeutral;
//spell information
private GameObject spellPrefab;
private GameObject spellGameObject;
public float spellRate = 0.25f;
void Start()
{
//might need this later
}
public void Cast()
{
Debug.Log("spellName = " + spellName);
switch (type)
{
case SpellType.FIRE:
if (PlayerStats.PlayerStatsSingle.magic > 0)
{
PlayerStats.PlayerStatsSingle.ChangeMagic(-1);
spellPrefab = Resources.Load("Prefabs/Spells/Fireball", typeof(GameObject)) as GameObject;
// Create a new spell
spellGameObject = Instantiate(spellPrefab, GameObject.Find("PlayerProjectiles").transform) as GameObject;
spellGameObject.name = spellPrefab.name;
var temp = Input.mousePosition;
Vector3 mousePos;
mousePos = Camera.main.ScreenToWorldPoint(temp);
mousePos.z = 0;
spellGameObject.GetComponent<Fireball>().SetStartData(PlayerController.PlayerControllerSingle.transform.position, mousePos);
}
break;
case SpellType.HEAL:
Debug.Log("HEALHEALHEAL");
spellPrefab = Resources.Load("Prefabs/Spells/Heal", typeof(GameObject)) as GameObject;
// Create a new spell
spellGameObject = Instantiate(spellPrefab, GameObject.Find("PlayerProjectiles").transform) as GameObject;
break;
case SpellType.ICE:
Debug.Log("Frozen Solid");
break;
case SpellType.ZAP:
Debug.Log("Zap ZAP Zap");
break;
case SpellType.UNKNOWN:
Debug.Log("Spell Aint Nuffin");
break;
default:
Debug.Log("Default case");
break;
}
}
public string GetToolTip()
{
string stats = string.Empty;
string color = string.Empty;
string newLine = string.Empty;
if (description != string.Empty)
{
newLine = "\n";
}
//description if wanted
return string.Format("<color=" + color + "><size=16>{0}</size></color><size=14><i><color=lime>" + newLine + "{1}</color></i>{2}</size>", spellName, description, stats);
}
}
<file_sep>/2dProject/Assets/scripts/EmenyStuff/Shield.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shield : MonoBehaviour {
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
var difference = PlayerController.PlayerControllerSingle.transform.position - transform.position;
var grapBodyAngle = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
var bodyRoatation = Quaternion.AngleAxis(grapBodyAngle, Vector3.forward);
transform.rotation = bodyRoatation;
}
}
<file_sep>/2dProject/Assets/scripts/CutSceneScripts/CutScene2.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class CutScene2 : MonoBehaviour
{
public Camera cam;
public Text cutSceneText;
Vector3 targetLocation;
float speed;
float start, end;
//public static CutSceneLoader CutSceneLoaderSingle;
void Start()
{
cam.transform.position = new Vector3(5.5f, -6.7f, -1);
cam.orthographicSize = 13f;
StartCoroutine(WaitForScene());
}
void Update()
{
cam.transform.position = Vector3.MoveTowards(cam.transform.position, targetLocation, speed);
cam.orthographicSize = Mathf.Lerp(cam.orthographicSize, end, .10f);
//for pausing cut scene
if (Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("Space");
if (Time.timeScale >= 0)
{
Debug.Log("> 0");
Time.timeScale = 0;
}
else
{
Debug.Log("= 0");
Time.timeScale = 1;
}
}
//up time scale to scroll to next panel quicker
if (Input.GetMouseButtonDown(0))
{
Time.timeScale = 5;
Debug.Log("left click");
}
//for skipping scene
if (Input.GetMouseButtonDown(1))
{
Debug.Log("right click");
LoadNewScene();
}
}
IEnumerator WaitForScene()
{
end = 13f;
cutSceneText.text = "Full Strip";
yield return new WaitForSeconds(2);
speed = 2.0f;
end = 3.5f;
Time.timeScale = 1;
cutSceneText.text = "NEED a cut scene TWO panel";
targetLocation = new Vector3(0.06f, 1.51f, -1.0f);
yield return new WaitForSeconds(2);
Time.timeScale = 1;
cutSceneText.text = "NEED a cut scene TWO panel";
targetLocation = new Vector3(9.02f, 1.78f, -1.0f);
end = 3.3f;
yield return new WaitForSeconds(2);
Time.timeScale = 1;
cutSceneText.text = "Panel 3";
targetLocation = new Vector3(0.00f, -6.50f, -1.0f);
end = 4f;
yield return new WaitForSeconds(2);
Time.timeScale = 1;
cutSceneText.text = "Panel 4";
targetLocation = new Vector3(5.80f, -6.50f, -1.0f);
yield return new WaitForSeconds(2);
Time.timeScale = 1;
cutSceneText.text = "Panel 5";
targetLocation = new Vector3(12.60f, -6.00f, -1.0f);
yield return new WaitForSeconds(2);
Time.timeScale = 1;
cutSceneText.text = "Panel 6";
targetLocation = new Vector3(0.70f, -14.40f, -1.0f);
end = 3.2f;
yield return new WaitForSeconds(2);
Time.timeScale = 1;
cutSceneText.text = "Panel 6-8";
speed = 0.1f;
targetLocation = new Vector3(11.70f, -14.40f, -1.0f);
yield return new WaitForSeconds(3);
LoadNewScene();
}
void LoadNewScene()
{
//for loading to main game
CutSceneLoader.CutSceneLoaderSingle.LoadNewScene = "StartArea";
CutSceneLoader.CutSceneLoaderSingle.loadBackToGame = true;
}
//IEnumerator LoadNewScene()
//{
// AsyncOperation async = SceneManager.LoadSceneAsync("StartArea");
// // While the asynchronous operation to load the new scene is not yet complete, continue waiting until it's done.
// while (!async.isDone)
// {
// yield return null;
// }
//}
}
<file_sep>/2dProject/Assets/scripts/PlayerController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class PlayerController : MonoBehaviour
{
public string playerName { get; set; }
public bool facingRight { get; set; }
//private float moveForce;
private float maxSpeed;
private float jumpForce;
//dash force
float dashForce = 1000f;
//rotate with dash
private bool rotateRight = false;
private bool rotateleft = false;
float rotateSpeed = 20f;
float lastRotationAngle = 0f;
//double tap click event
private float ButtonCooler = 0.5f; // Half a second before reset
private int ButtonCount = 0;
private float dashCoolDown = 0.0f;
//touching anything
public bool IsColliding { get; set; }
//player rigidbody
public Rigidbody2D rb2d;
//for door colliding script
DoorCollider doorInfo;
//for respawning
public Vector3 respawnLocation;
//for freezeing player
public bool freezePlayer { get; set; }
//for falling
private bool falling = false;
private float timer = 0;
//skillBoolCheck
public bool dashSkill = false;
public bool dashSkillMelee = false;
public bool slideSkill = false;
public bool slideJumpSkill = false;
public bool slideSteerSKill = false;
public bool grapplingHookSkill = false;
public bool hookResetJumpsSkill = false;
//skill attack objects
public GameObject DashAttack;
//for hotbar
public delegate void HotBarDelegate();
public HotBarDelegate HotBarSlot1, HotBarSlot2, HotBarSlot3;
//hotbar cooldowns
float hotBar1CoolDownTimer = 0;
//float hotBar2CoolDownTimer = 0;
//float hotBar3CoolDownTimer = 0;
//for player attack
public delegate void PlayerAttack();
public PlayerAttack playerAttack;
//for slide move
private EdgeCollider2D currentEdge;
private int currentEdgePoint = 0;
private Vector2 CurrentVector;
private Vector2 knownVec;
private Vector2 perpVec;
private Quaternion targetRotation;
public bool IsSliding;
private EdgeCollider2D[] Edges;
bool firstRun = true;
bool jumpOff = false;
//for slide move particles
private ParticleSystem SlideParticles;
private ParticleSystem SlideJumpParticles;
//is touching door
public bool touchingDoor { get; set; }
//invinsible
public bool invincible { get; set; }
//attack cooldown when destoryed
float InvinicbleCoolDown = 2;
float InvinicbleCoolDownTimer = 0;
//for fade in and out player sprite
public SpriteRenderer PlayerSprite;
//for smooth force movments
public Vector2 forceAddToPlayer;
//for grappling hook
DrawGrapHook grapplingHookScript;
//bools for inputs
bool spaceDown;
bool SHold;
bool SUp;
bool Mouse0Up;
bool Mouse0Down;
bool Mouse1Hold;
bool DHold;
bool AHold;
// need to not add force with a and d when player is doing other stuff
bool noMovement;
//only one rotate call at a time
bool isRotating;
public bool isGrapplingHook;
//what weapon is equipt
public bool meleeEquipt;
//public bool rangeEquipt;
//jump counter
public int jumpCounter;
//singleton
public static PlayerController PlayerControllerSingle;
void Awake()
{
if (PlayerControllerSingle == null)
{
DontDestroyOnLoad(gameObject);
PlayerControllerSingle = this;
}
else if (PlayerControllerSingle != this)
{
Destroy(gameObject);
}
}
// Use this for initialization
void Start()
{
IsColliding = false;
freezePlayer = false;
//variables on start
maxSpeed = 9f;
//moveForce = 5f;
jumpForce = 500;
facingRight = true;
jumpCounter = 1;
//other start stuff
doorInfo = GetComponent<DoorCollider>();
rb2d = GetComponent<Rigidbody2D>();
//for where player is at start of scene
transform.position = respawnLocation;
//start player name
playerName = "<NAME>";
//set sprite, make sure play image is top sprite or another will be found
PlayerSprite = transform.GetComponentInChildren<SpriteRenderer>();
//slide particle system
SlideParticles = transform.Find("Teemo_Standing").transform.Find("ParticleSlide").GetComponentInChildren<ParticleSystem>();
SlideJumpParticles = transform.Find("PlayerSkills").transform.Find("SlideSkill").transform.Find("ParticleJump").GetComponentInChildren<ParticleSystem>();
//for gappling hook
grapplingHookScript = GameObject.Find("GrapplingHook").GetComponent<DrawGrapHook>();
}
// Update is called once per frame
void Update()
{
//for stoping all player actions
if (freezePlayer)
{
return;
}
spaceDown = Input.GetKeyDown(KeyCode.Space);
SUp = Input.GetKeyUp(KeyCode.S);
SHold = Input.GetKey(KeyCode.S);
Mouse0Up = Input.GetMouseButtonUp(0);
Mouse0Down = Input.GetMouseButtonDown(0);
Mouse1Hold = Input.GetMouseButton(1);
DHold = Input.GetKey(KeyCode.D);
AHold = Input.GetKey(KeyCode.A);
//if player health hits 0
if (PlayerStats.PlayerStatsSingle.health <= 0)
{
ResetPlayer();
transform.position = respawnLocation;
PlayerStats.PlayerStatsSingle.ChangeHealth(PlayerStats.PlayerStatsSingle.maxHealth);
}
//going through doors
if (Input.GetKeyDown(KeyCode.R))
{
if (touchingDoor)
{
//reset player skills and stuff
LockPosition();
ResetPlayer();
GameController.GameControllerSingle.RemoveEveryingOnMap();
MapGenerator.MapGeneratorSingle.seed = GameController.GameControllerSingle.mapSeed;
MapGenerator.MapGeneratorSingle.LoadMap();
//for minimap
DrawPlayerMap.DrawPlayerMapSingle.UpdateMap();
Vector2 door;
door = MapGenerator.MapGeneratorSingle.doorLocations[doorInfo.numVal];
transform.position = new Vector3(door.x, door.y, 0);
respawnLocation = door;
UnLockPosition();
}
}
if (Mouse0Down)
{
isGrapplingHook = grapplingHookScript.TurnGrapHookOn();
}
if (Mouse0Up)
{
if (isGrapplingHook)
{
isGrapplingHook = grapplingHookScript.TurnGrapHookOff();
StartCoroutine(RotateToZero());
}
}
//button 1
if (hotBar1CoolDownTimer > 0)
{
hotBar1CoolDownTimer -= Time.deltaTime;
}
else if (Input.GetKey(KeyCode.Alpha1))
{
hotBar1CoolDownTimer += .5f;
if (HotBarSlot1 != null)
{
HotBarSlot1();
}
}
//button 2
if (Input.GetKeyDown(KeyCode.Alpha2))
{
if (HotBarSlot2 != null)
{
HotBarSlot2();
}
}
//button 3
if (Input.GetKeyDown(KeyCode.Alpha3))
{
if (HotBarSlot3 != null)
{
HotBarSlot3();
}
}
//for rotating during roll
if (rotateRight)
{
//euler angle start at 360 when going right
PlayerSprite.transform.Rotate(Vector3.back, rotateSpeed);
if (lastRotationAngle < PlayerSprite.transform.eulerAngles.z)
{
PlayerSprite.transform.eulerAngles = new Vector3(0, 0, 0);
rotateRight = false;
}
lastRotationAngle = PlayerSprite.transform.eulerAngles.z;
}
if (rotateleft)
{
//euler angle start at 0 when going left
PlayerSprite.transform.Rotate(Vector3.forward, rotateSpeed);
if (lastRotationAngle > PlayerSprite.transform.eulerAngles.z)
{
PlayerSprite.transform.eulerAngles = Vector3.zero;
rotateleft = false;
}
lastRotationAngle = PlayerSprite.transform.eulerAngles.z;
}
//have to learn dash skill to start using it can't dash while sliding
if (!IsSliding && dashSkill)
{
if (Input.GetKeyDown(KeyCode.D))
{
//Number of Taps you want Minus One
if (ButtonCooler > 0.0f && ButtonCount == 1 && dashCoolDown <= 0f)
{
//dash attack
if (meleeEquipt && dashSkillMelee)
{
StartCoroutine(StartDashAttack());
}
dashCoolDown = 1f;
if (rb2d.velocity.x >= 6f)
{
rb2d.velocity = new Vector2(-7f, rb2d.velocity.y);
}
else {
rb2d.velocity = new Vector2(rb2d.velocity.x, rb2d.velocity.y);
}
rb2d.AddForce(new Vector2(dashForce, 0f));
//for rotating teemo
rotateleft = false;
rotateRight = true;
lastRotationAngle = 360f;
}
else
{
ButtonCooler = 0.2f;
ButtonCount += 1;
}
}
if (Input.GetKeyDown(KeyCode.A))
{
//Number of Taps you want Minus One
if (ButtonCooler > 0.0f && ButtonCount == 1 && dashCoolDown <= 0f)
{
//dash attack
if (meleeEquipt && dashSkillMelee)
{
StartCoroutine(StartDashAttack());
}
dashCoolDown = 1f;
if (rb2d.velocity.x <= -6f)
{
rb2d.velocity = new Vector2(7f, rb2d.velocity.y);
}
else {
rb2d.velocity = new Vector2(rb2d.velocity.x, rb2d.velocity.y);
}
rb2d.AddForce(new Vector2(-dashForce, 0f));
//for rotating teemo
rotateRight = false;
rotateleft = true;
lastRotationAngle = 0f;
}
else
{
ButtonCooler = 0.2f;
ButtonCount += 1;
}
}
if (ButtonCooler > 0.0f)
{
ButtonCooler -= 1.0f * Time.deltaTime;
}
else
{
ButtonCount = 0;
}
if (dashCoolDown > 0.0f)
{
dashCoolDown -= Time.deltaTime;
}
}
//stop all action after this if the pointer is over the canvas
EventSystem eventSystem = EventSystem.current;
if (eventSystem.IsPointerOverGameObject())
{
return;
}
else if (Mouse1Hold)
{
if (playerAttack != null)
{
playerAttack();
}
}
}
//don't put keybutton reads in here; they can hit twice
void FixedUpdate()
{
if (invincible)
{
//cool down for attack
if (InvinicbleCoolDownTimer > 0)
{
InvinicbleCoolDownTimer -= Time.deltaTime;
PlayerSprite.color = new Color(PlayerSprite.color.r, PlayerSprite.color.b, PlayerSprite.color.g, (PlayerSprite.color.a + .04f) % 1f);
}
else
{
InvinicbleCoolDownTimer = 0;
PlayerSprite.color = new Color(PlayerSprite.color.r, PlayerSprite.color.b, PlayerSprite.color.g, 1f);
invincible = false;
}
}
// stops all player actions
if (freezePlayer)
{
return;
}
if (slideSkill && SHold && !IsSliding)
{
try
{
if (firstRun)
{
Edges = GameObject.Find("ColliderHolder").GetComponentsInChildren<EdgeCollider2D>();
float closestCollider = 5000;
foreach (EdgeCollider2D edge in Edges)
{
if (edge.Distance(PlayerSprite.transform.GetComponent<CapsuleCollider2D>()).distance < closestCollider)
{
closestCollider = edge.Distance(PlayerSprite.transform.GetComponent<CapsuleCollider2D>()).distance;
if (closestCollider <= 2)
{
currentEdge = edge;
firstRun = false;
noMovement = true;
IsSliding = true;
//need to set player speed to zero to stop weird interations
rb2d.velocity = Vector2.zero;
break;
}
else
{
closestCollider = 5000;
firstRun = true;
}
}
}
if (!firstRun && !jumpOff)
{
GetContactPoint();
//no gravity while sliding
//Debug.Log("gravity 0");
rb2d.gravityScale = 0;
//turn on particles
SlideParticles.Play();
}
}
}
catch
{
}
}
else if (SUp)
{
noMovement = false;
IsSliding = false;
firstRun = true;
//Debug.Log("gravity 1");
rb2d.gravityScale = 1;
jumpOff = false;
//turn off particles
SlideParticles.Stop();
SlideJumpParticles.Stop();
StartCoroutine(RotateToZero());
}
if (IsSliding)
{
if (slideJumpSkill && spaceDown && !jumpOff)
{
jumpOff = true;
SlideJumpParticles.Play();
//Debug.Log("gravity 0");
rb2d.gravityScale = 0;
rb2d.AddForce(PlayerSprite.transform.up * 25f);
}
else if (jumpOff)
{
if (slideSteerSKill && DHold)
{
PlayerSprite.transform.eulerAngles = new Vector3(0, 0, PlayerSprite.transform.eulerAngles.z - 2);
}
else if (slideSteerSKill && AHold)
{
PlayerSprite.transform.eulerAngles = new Vector3(0, 0, PlayerSprite.transform.eulerAngles.z + 2);
}
//if (rb2d.velocity.magnitude < 20f)
//{
// rb2d.AddForce(transform.localPosition * 25f);
//}
transform.position += PlayerSprite.transform.up * .25f;
}
//for rotating the object
else if (!jumpOff)
{
//get new location to move to
CurrentVector = new Vector2(currentEdge.points[currentEdgePoint].x, currentEdge.points[currentEdgePoint].y);
//gets current perp vector with current and next point
knownVec = CurrentVector - new Vector2(currentEdge.points[(currentEdgePoint + 1) % currentEdge.pointCount].x, currentEdge.points[(currentEdgePoint + 1) % currentEdge.pointCount].y);
perpVec = CurrentVector + new Vector2(knownVec.y, -knownVec.x);
//for moving the object
gameObject.transform.position = Vector2.MoveTowards(gameObject.transform.position, perpVec, .25f);
targetRotation = Quaternion.LookRotation(Vector3.forward, perpVec - CurrentVector);
PlayerSprite.transform.rotation = Quaternion.Slerp(PlayerSprite.transform.rotation, targetRotation, .25f);
}
//gets next point to move to
if (Vector3.Distance(gameObject.transform.position, perpVec) <= .1f)
{
if (facingRight)
{
currentEdgePoint = (currentEdgePoint + 1) % (currentEdge.edgeCount - 1);
}
else
{
currentEdgePoint = ((currentEdge.edgeCount - 1) + currentEdgePoint - 1) % (currentEdge.edgeCount - 1);
}
}
}
if (DHold)
{
//flip character sprite
if (!facingRight)
{
Flip();
}
if (!noMovement)
{
//if going other direction, stop
if (rb2d.velocity.x < 0)
{
rb2d.velocity = new Vector2(0, rb2d.velocity.y);
}
//speed up by 1 to the right
if (Mathf.Abs(rb2d.velocity.x) < maxSpeed)
{
//rb2d.velocity = new Vector2(rb2d.velocity.x + .5f, rb2d.velocity.y);
//dont' need time in fixed update
//rb2d.velocity = new Vector3(rb2d.velocity.x, rb2d.velocity.y, 0) + transform.right * 10f * Time.deltaTime;
//rb2d.velocity = new Vector3(rb2d.velocity.x, rb2d.velocity.y, 0) + transform.right * 10f;
rb2d.AddForce(transform.right * 15f);
//rb2d.velocity += (Vector2)transform.right;
//forceAddToPlayer = transform.right * .5f;
//rb2d.velocity += forceAddToPlayer;
}
}
}
else if (AHold)
{
//flip character sprite
if (facingRight)
{
Flip();
}
if (!noMovement)
{
//if going other direction, stop
if (rb2d.velocity.x > 0)
{
rb2d.velocity = new Vector2(0, rb2d.velocity.y);
}
//speed up by 1 to the left
if (Mathf.Abs(rb2d.velocity.x) < maxSpeed)
{
//rb2d.velocity = new Vector2(rb2d.velocity.x - .5f, rb2d.velocity.y);
rb2d.AddForce(-transform.right * 15f);
}
}
}
//if colliding then slow down (don't slow doing in air)
else if (IsColliding == true)
{
rb2d.velocity = new Vector2(rb2d.velocity.x * .5f, rb2d.velocity.y);
}
//else slow down by a little
else
{
rb2d.velocity = new Vector2(rb2d.velocity.x * .97f, rb2d.velocity.y);
}
if (!falling && rb2d.velocity.y <= -maxSpeed*2 && !isGrapplingHook)
{
Debug.Log("FALLING " + rb2d.velocity.y);
falling = true;
timer = 0f;
//Debug.Log("gravity 0");
rb2d.gravityScale = 0;
}
else if(falling)
{
//timer for when you take damage
timer += Time.deltaTime;
//Debug.Log(timer);
//Debug.Log("falling" + rb2d.velocity.y);
if (rb2d.velocity.y >= 0f)
{
falling = false;
}
}
if (spaceDown && !jumpOff && !IsSliding)
{
//Debug.Log("gravity 1");
rb2d.gravityScale = 1;
//only jump sideways of on grappinghook and moving slow
if (isGrapplingHook && grapplingHookScript.HasTipCollided && rb2d.velocity.magnitude < maxSpeed*1.5f)
{
if (facingRight)
{
rb2d.AddForce(PlayerSprite.transform.right * jumpForce*.5f);
}
else
{
rb2d.AddForce(-PlayerSprite.transform.right * jumpForce*.5f);
}
}
//can only jump if you have one and not going too fast
else if(jumpCounter > 0 && rb2d.velocity.y < maxSpeed)
{
if (rb2d.velocity.y < 0)
{
rb2d.velocity = new Vector3(rb2d.velocity.x, 0, 0);
}
////gives jumps based on speed
//if (rb2d.velocity.y < 1.2f)
//{
jumpCounter -= 1;
rb2d.AddForce(new Vector2(0f, jumpForce));
//}
}
}
if (spaceDown)
{
//turn off grappling hook
if (isGrapplingHook && grapplingHookScript.HasTipCollided)
{
isGrapplingHook = grapplingHookScript.TurnGrapHookOff();
}
if (!IsSliding)
{
StartCoroutine(RotateToZero());
}
}
//in fixed update you should set all button click bools to false or they might go off twice
//can't decide if should do same for holds; gives difference feel
spaceDown = false;
SUp = false;
//SHold = false;
Mouse0Up = false;
Mouse0Down = false;
//DHold = false;
//AHold = false;
}
void Flip()
{
facingRight = !facingRight;
PlayerSprite.flipX = !PlayerSprite.flipX;
}
//stops play all player actions and x y movements, rotations, etc.
public void LockPosition()
{
freezePlayer = true;
rb2d.constraints = RigidbodyConstraints2D.FreezePositionX | RigidbodyConstraints2D.FreezePositionY;
}
//returns player movement
public void UnLockPosition()
{
freezePlayer = false;
rb2d.constraints = RigidbodyConstraints2D.None;
rb2d.constraints = RigidbodyConstraints2D.FreezeRotation;
PlayerSprite.transform.transform.rotation = Quaternion.identity;
}
private void SetInvisible()
{
invincible = true;
InvinicbleCoolDownTimer = InvinicbleCoolDown;
}
public void DamagePlayer(int DamageAmount)
{
if (!invincible)
{
SetInvisible();
PlayerStats.PlayerStatsSingle.ChangeHealth(-DamageAmount);
}
}
//gets closest point to on the edge that the player is next to
private void GetContactPoint()
{
float closestPoint = 1000;
for (int index = 0; index < currentEdge.pointCount; index++)
{
if (Vector2.Distance(currentEdge.points[index], transform.position) <= closestPoint)
{
closestPoint = Vector2.Distance(currentEdge.points[index], transform.position);
currentEdgePoint = index;
}
}
//get first location
CurrentVector = new Vector2(currentEdge.points[currentEdgePoint].x, currentEdge.points[currentEdgePoint].y);
//gets current perp vector with current and next point
knownVec = CurrentVector - new Vector2(currentEdge.points[(currentEdgePoint + 1) % currentEdge.pointCount].x, currentEdge.points[(currentEdgePoint + 1) % currentEdge.pointCount].y);
perpVec = CurrentVector + new Vector2(knownVec.y, -knownVec.x);
}
public IEnumerator RotateToZero()
{
if (!isRotating && !IsSliding && !isGrapplingHook)
{
isRotating = true;
Quaternion start = PlayerSprite.transform.rotation;
Quaternion end = Quaternion.Euler(new Vector3(0.0f, 0.0f, 0.0f));
float elapsed = 0.0f;
while (elapsed < 1f)
{
//Debug.Log("rotate playercon");
PlayerSprite.transform.rotation = Quaternion.Slerp(start, end, elapsed/.1f);
elapsed += Time.deltaTime;
if (Mathf.Abs(PlayerSprite.transform.rotation.eulerAngles.z) <= 5)
{
PlayerSprite.transform.eulerAngles = new Vector3(0, 0, 0);
elapsed = 1f;
}
yield return null;
}
isRotating = false;
}
}
//skills
IEnumerator StartDashAttack()
{
DashAttack.SetActive(true);
yield return new WaitForSeconds(.65f);
DashAttack.SetActive(false);
}
public void ResetPlayer()
{
//reset speed
rb2d.velocity = Vector2.zero;
//reset presses
spaceDown = false;
SHold = false;
SUp = false;
Mouse0Up = false;
Mouse0Down = false;
Mouse1Hold = false;
DHold = false;
AHold = false;
//reset local variables
//for grap hook
isGrapplingHook = false;
//for rotations
isRotating = false;
//for sliding skill
IsSliding = false;
firstRun = true;
jumpOff = false;
noMovement = false;
//particles for sliding skill
SlideParticles.Stop();
SlideJumpParticles.Stop();
//reset grappling hook;
isGrapplingHook = grapplingHookScript.TurnGrapHookOff();
}
void OnTriggerEnter2D(Collider2D triggerCollition)
{
}
private void OnCollisionEnter2D(Collision2D collision)
{
IsColliding = true;
jumpCounter = PlayerStats.PlayerStatsSingle.maxJumps;
//moved this into magnet script for testing stuff
//add item to inventory
//if (collision.gameObject.tag == "Item")
//{
// Inventory.InventorySingle.AddItem(collision.gameObject.GetComponent<Item>());
// Destroy(collision.gameObject);
//}
//falling damage
if (falling)
{
if(timer >= 1.5f)
{
DamagePlayer(1);
}
falling = false;
//Debug.Log("gravity 1");
rb2d.gravityScale = 1f;
}
//for slide move; gets edge collider player is touching
if (jumpOff)
{
if (collision.gameObject.GetComponent<EdgeCollider2D>())
{
currentEdge = collision.gameObject.GetComponent<EdgeCollider2D>();
GetContactPoint();
jumpOff = false;
SlideJumpParticles.Stop();
}
else
{
//Debug.Log("no collider");
//Debug.Log(transform.eulerAngles);
//Debug.Log(transform.eulerAngles.z + 180f);
////Quaternion test = Quaternion.Euler(new Vector3(0.0f, 0.0f, transform.eulerAngles.z + 90f));
////transform.rotation = test;
//transform.eulerAngles = new Vector3(0, 0, -(transform.eulerAngles.z - collision.transform.eulerAngles.z)/2 );
}
}
//for taking damage
if (collision.gameObject.tag == "Enemy")
{
//Debug.Log("hit enemy = " + collision.gameObject.name);
}
}
private void OnCollisionStay2D(Collision2D collision)
{
IsColliding = true;
}
private void OnCollisionExit2D(Collision2D collision)
{
IsColliding = false;
}
}
<file_sep>/2dProject/Assets/scripts/EmenyStuff/GodHandsFist.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GodHandsFist : MonoBehaviour {
public bool pullAttackOn = false;
public bool returnFist = false;
public bool returnWithPlayer = false;
public bool returnFistPlayer = false;
public bool returnWithEnemy = false;
public bool hitObject = false;
//for user attack, not same as boss
public bool userAttackOn = false;
public Vector3 gotoPosition;
public Transform targetTransform;
public Transform userTransform;
public Rigidbody2D targetRB;
public Vector3 newTargetLocation;
public Transform fistPrefab;
//speed of fist
//float fistSpeed = 100;
//float step;
void FixedUpdate()
{
//step = fistSpeed * Time.deltaTime;
if (pullAttackOn)
{
userTransform.position = Vector3.MoveTowards(userTransform.position, newTargetLocation, .5f);
if (hitObject)
{
pullAttackOn = false;
returnWithPlayer = true;
returnFist = true;
}
else if (Vector3.Distance(userTransform.position, newTargetLocation) <= .1f)
{
pullAttackOn = false;
returnFist = true;
}
}
else if (returnFist)
{
userTransform.position = Vector3.MoveTowards(userTransform.position, transform.parent.position, 1f);
if (returnWithPlayer)
{
targetTransform.position = Vector3.MoveTowards(userTransform.position, transform.parent.position, 1f);
}
if (Vector3.Distance(userTransform.position, transform.parent.position) == 0)
{
returnFist = false;
if (returnWithPlayer)
{
targetRB.AddForce(new Vector2(0, 1000));
returnWithPlayer = false;
}
Destroy(gameObject);
//if hit target, knock it up
}
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
//Pulls PLayer and make it so player doesnt interact with the shield
if (BossScript.BossScriptSingle.shieldOn == true)
{
BossPowerShield.BossPowerShieldSingle.notGrabbed = false;
}
targetRB = other.GetComponent<Rigidbody2D>();
hitObject = true;
targetTransform = other.transform;
}
if (other.tag == "BossRoomItem")
{
targetRB = other.GetComponent<Rigidbody2D>();
hitObject = true;
targetTransform = other.transform;
}
if (other.tag == "Bullet")
{
Debug.Log("HIT by Bullet fist");
Debug.Log(GetComponent<Collider2D>().name);
}
}
}
<file_sep>/2dProject/Assets/scripts/EmenyStuff/Movement/SeekingEnemy.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SeekingEnemy : MonoBehaviour {
MapInformation map1;
int oldX, oldY;
int currentX = -10000;
int currentY;
Vector2 move;
List<int> possibleSpawnX = new List<int>();
List<int> possibleSpawnY = new List<int>();
List<Vector2> forwardMoves = new List<Vector2>();
List<Vector2> SideMoves = new List<Vector2>();
//random variables
float speed = .1f;
bool running = false;
void Start()
{
speed = Random.Range(.1f, .2f);
map1 = MapGenerator.MapGeneratorSingle.MapInfo[MapGenerator.MapGeneratorSingle.seed];
for (int x = 1; x < map1.width - 1; x++)
{
for (int y = 1; y < map1.height - 1; y++)
{
if (map1.map[x, y] == 0)
{
possibleSpawnX.Add(x);
possibleSpawnY.Add(y);
}
}
}
int randomNumber = Random.Range(0, possibleSpawnX.Count);
currentX = possibleSpawnX[randomNumber];
currentY = possibleSpawnY[randomNumber];
oldX = currentX - 1;
oldY = currentY - 1;
transform.position = new Vector2(-map1.width / 2 + currentX * map1.squareSize + map1.squareSize / 2, -map1.height / 2 + currentY * map1.squareSize + map1.squareSize);
//gets first moves
NextMove();
}
void Update ()
{
//stops moving when player is in range and do something
if (Vector2.Distance(transform.position, PlayerController.PlayerControllerSingle.transform.position) <= 5f)
{
}
else
{
//gets new move when old move reached
if (Vector2.Distance(transform.position, move) <= .2f && !running)
{
running = true;
NextMove();
}
transform.position = Vector2.MoveTowards(transform.position, move, speed);
}
}
void NextMove()
{
//clear elements, not reset capacity
forwardMoves.Clear();
SideMoves.Clear();
//find out what direction object is facing, checks forwards moves first only side if no forwards
if (currentX - oldX == 1 && currentY - oldY == 1)
{
//forward
GetMoveXY(currentX + 1, currentY + 1);
//left
GetMoveXY(currentX, currentY + 1);
//right
GetMoveXY(currentX + 1, currentY);
//side left
GetSideMove(currentX + 1, currentY - 1);
//side right
GetSideMove(currentX - 1, currentY + 1);
}
else if (currentX - oldX == -1 && currentY - oldY == -1)
{
//forward
GetMoveXY(currentX - 1, currentY - 1);
//left
GetMoveXY(currentX, currentY - 1);
//right
GetMoveXY(currentX - 1, currentY);
//side left
GetSideMove(currentX - 1, currentY + 1);
//side right
GetSideMove(currentX + 1, currentY - 1);
}
else if (currentX - oldX == 1 && currentY - oldY == -1)
{
//forward
GetMoveXY(currentX + 1, currentY - 1);
//left
GetMoveXY(currentX, currentY - 1);
//right
GetMoveXY(currentX + 1, currentY);
//side left
GetSideMove(currentX - 1, currentY - 1);
//side right
GetSideMove(currentX + 1, currentY + 1);
}
else if (currentX - oldX == -1 && currentY - oldY == 1)
{
//forward
GetMoveXY(currentX - 1, currentY + 1);
//left
GetMoveXY(currentX, currentY + 1);
//right
GetMoveXY(currentX - 1, currentY);
//side left
GetSideMove(currentX + 1, currentY + 1);
//side right
GetSideMove(currentX - 1, currentY - 1);
}
else if (currentX - oldX == 1)
{
//forward
GetMoveXY(currentX + 1, currentY);
//left
GetMoveXY(currentX + 1, currentY + 1);
//right
GetMoveXY(currentX + 1, currentY - 1);
//side left
GetSideMove(currentX, currentY + 1);
//side right
GetSideMove(currentX, currentY - 1);
}
else if(currentY - oldY == 1)
{
//forward
GetMoveXY(currentX, currentY + 1);
//left
GetMoveXY(currentX + 1, currentY + 1);
//right
GetMoveXY(currentX - 1, currentY + 1);
//side left
GetSideMove(currentX + 1, currentY);
//side right
GetSideMove(currentX - 1, currentY);
}
else if (currentX - oldX == -1)
{
//forward
GetMoveXY(currentX - 1, currentY);
//left
GetMoveXY(currentX - 1, currentY + 1);
//right
GetMoveXY(currentX - 1, currentY - 1);
//side left
GetSideMove(currentX, currentY + 1);
//side right
GetSideMove(currentX, currentY - 1);
}
else if (currentY - oldY == -1)
{
//forward
GetMoveXY(currentX, currentY - 1);
//left
GetMoveXY(currentX - 1, currentY - 1);
//right
GetMoveXY(currentX + 1, currentY - 1);
//side left
GetSideMove(currentX + 1, currentY);
//side right
GetSideMove(currentX - 1, currentY);
}
//set old position before new one is found
oldX = currentX;
oldY = currentY;
if (forwardMoves.Count != 0)
{
FindBestMove(forwardMoves);
}
else if (SideMoves.Count != 0)
{
FindBestMove(SideMoves);
}
else
{
// can only happen one case fix that by turing around
Debug.Log("no move found");
}
running = false;
}
void GetMoveXY(int x, int y)
{
if (map1.map[x, y] == 0)
{
forwardMoves.Add(new Vector2(x, y));
}
else
{
//nothing there is a wall
}
}
void GetSideMove(int x, int y)
{
if (map1.map[x, y] == 0)
{
SideMoves.Add(new Vector2(x, y));
}
else
{
//do nothing there is a wall
}
}
void FindBestMove(List<Vector2> MovesToCheck)
{
//random distance that will always be futher away
float distance = 1000;
foreach (Vector2 nextMove in MovesToCheck)
{
//have to convert to world coordianates
int xPos = -map1.width / 2 + (int)(nextMove.x) * map1.squareSize + map1.squareSize / 2;
int yPos = -map1.height / 2 + (int)nextMove.y * map1.squareSize + map1.squareSize;
if (Vector2.Distance(new Vector2(xPos, yPos), PlayerController.PlayerControllerSingle.transform.position) <= distance)
{
distance = Vector2.Distance(new Vector2(xPos, yPos), PlayerController.PlayerControllerSingle.transform.position);
move = new Vector2(xPos, yPos);
currentX = (int)nextMove.x;
currentY = (int)nextMove.y;
}
}
}
}
<file_sep>/2dProject/Assets/scripts/EmenyStuff/EnemyStats/MagicRock.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MagicRock : EnemyStats
{
public Transform MagicEssence;
void Start ()
{
//Essence items
items.Add(MagicEssence);
StartStats();
}
public override void StartStats()
{
dropRate = 1f;
damagePlayerOnCollision = false;
health = 5;
experiencePoint = 0;
invincible = false;
}
}
<file_sep>/2dProject/Assets/scripts/EmenyStuff/EnemyStats/EnemyStats.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
/// Handle hitpoints and damages
public class EnemyStats : MonoBehaviour
{
//List of transforms to hold droppable items
public List<Transform> items = new List<Transform>();
//Set these for different enemies;
public float dropRate;
public bool damagePlayerOnCollision;
public int health;
public int experiencePoint;
public bool invincible;
//drop chance for an item
private float dropChance;
//int to choose item from list
private int choice;
void Start()
{
StartStats();
}
public virtual void StartStats()
{
dropRate = 0;
damagePlayerOnCollision = true;
health = 1;
experiencePoint = 1;
invincible = false;
}
//getting name is for seeing which part of the game object was hit if it has children
//and special interation is required
public virtual void Damage(int damageCount, string NameObject, float InvicTime)
{
Debug.Log("NameObject = " + NameObject);
if (!invincible)
{
health -= damageCount;
if (health <= 0)
{
DeathPhase();
}
}
}
public IEnumerator MakeInvincible(float it)
{
invincible = true;
yield return new WaitForSeconds(it);
invincible = false;
}
public void DeathPhase()
{
//set exp
PlayerStats.PlayerStatsSingle.GainExperiencePoints(experiencePoint);
//PlayerStats.PlayerStatsSingle.experiencePoints += experiencePoint;
//check kill quest
KillQuest[] listKillQuests = QuestController.QuestControllerSingle.GetComponentsInChildren<KillQuest>();
if (listKillQuests.Length > 0)
{
foreach (KillQuest quest in listKillQuests)
{
if (gameObject.name == quest.killTarget)
{
quest.killQuestCounter += 1;
quest.UpdateKillQuest();
}
}
}
if (items.Count > 0)
{
DropItems();
}
// Dead!
Destroy(gameObject);
}
public void DropItems()
{
//could load in items by finding name like this; have to put all items that want to be loading in a similar place
//Debug.Log(Application.dataPath);
//DirectoryInfo di = new DirectoryInfo(Application.dataPath + "/prefab/Drops/Armor");
//FileInfo[] fi = di.GetFiles();
//foreach (FileInfo f in fi)
//{
// if(f.Extension == ".prefab")
// Debug.Log("name = " + f.Name);
//}
//creates small variance on spawn location
Vector3 SpawnLocation = new Vector3(Random.Range(0.0f, 1f), Random.Range(0.0f, 1f), 0);
//spawn first thing in itesms which is health essence
Instantiate(items[0], transform.position + SpawnLocation, Quaternion.identity).transform.parent = (GameObject.Find("WorldItems")).transform;
dropChance = Random.Range(0.0f, 1.0f);
if (dropChance >= dropRate)
{
SpawnLocation = new Vector3(Random.Range(0.0f, 1f), Random.Range(0.0f, 1f), 0);
choice = Random.Range(0, items.Count);
Instantiate(items[choice], transform.position + SpawnLocation, Quaternion.identity).transform.parent = (GameObject.Find("WorldItems")).transform;
}
}
void OnCollisionStay2D(Collision2D collision)
{
if (damagePlayerOnCollision)
{
//Debug.Log("parent = " + gameObject.name);
if (collision.gameObject.tag == "Player")
{
//Debug.Log("name object = " + gameObject.name);
PlayerController.PlayerControllerSingle.DamagePlayer(1);
}
}
}
//can use dame here to hit certain parts of objects
//void OnTriggerEnter2D(Collider2D Trigger)
//{
// Debug.Log(gameObject.name);
// Damage(100, Trigger.name);
//}
}
<file_sep>/2dProject/Assets/scripts/MainQuest/MainQuest0_0.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MainQuest0_0 : MonoBehaviour {
private Text NPCtext;
private Text Herotext;
private CanvasGroup canvas;
//Coroutine
bool inRange = false;
//for name
public bool promptName = false;
void Start()
{
NPCtext = DialogManager.DialogManagerSingle.NPCtext;
Herotext = DialogManager.DialogManagerSingle.Herotext;
canvas = DialogManager.DialogManagerSingle.canvas;
//main quest log text
QuestController.QuestControllerSingle.MainQuestText.text = "Talk to doctor." + "Main Quest " + QuestController.QuestControllerSingle.currentMainQuest;
}
// Update is called once per frame
void Update()
{
if (!inRange)
{
if (Vector3.Distance(PlayerController.PlayerControllerSingle.transform.position, transform.position) <= 5f)
{
DialogManager.DialogManagerSingle.TalkingCharacter.sprite = transform.GetComponent<SpriteRenderer>().sprite;
inRange = true;
Debug.Log("TalkOnApproach is in range");
canvas.alpha = 1;
//start quest sequence
StartCoroutine(Dialog());
}
}
}
//for getting name
void OnGUI()
{
if (promptName)
{
PlayerController.PlayerControllerSingle.playerName = GUI.TextField(new Rect(Screen.width / 2, Screen.height / 2, 200, 20), PlayerController.PlayerControllerSingle.playerName, 25);
}
if (Event.current.isKey && Event.current.keyCode == KeyCode.Return && promptName == true)
{
Debug.Log("enter is pressed.");
promptName = false;
}
}
IEnumerator Dialog()
{
//list all conversation that will be had
string Conversation1 = DialogManager.DialogManagerSingle.MainQuestDialogueLoadPath + "MainQuest0_0.0";
string Conversation2 = DialogManager.DialogManagerSingle.MainQuestDialogueLoadPath + "MainQuest0_0.1";
//old freeze player ; differet than old way its stops all movement period; new way just stop game controls and sets velocity to 0
//GameController.GameControllerSingle.transform.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezePositionX | RigidbodyConstraints2D.FreezePositionY;
//freeze player
PlayerController.PlayerControllerSingle.LockPosition();
//start conversavtion
StartCoroutine(DialogManager.DialogManagerSingle.Dialog(Conversation1));
//waits for conversation to finish
while((DialogManager.DialogManagerSingle.dialogOn == true))
{
yield return new WaitForSeconds(0.1f);
}
//pauses and gets name
promptName = true;
while (promptName == true)
{
yield return new WaitForSeconds(0.1f);
}
//start conversavtion 2
StartCoroutine(DialogManager.DialogManagerSingle.Dialog(Conversation2));
//waits for conversation to finish
while ((DialogManager.DialogManagerSingle.dialogOn == true))
{
yield return new WaitForSeconds(0.1f);
}
//wait 1 sec before continuing
yield return new WaitForSeconds(1f);
canvas.alpha = 0;
//unfreeze player
PlayerController.PlayerControllerSingle.UnLockPosition();
//Text reset
NPCtext.text = "";
Herotext.text = "";
//set quest number
QuestController.QuestControllerSingle.currentMainQuest = 1f;
//add next quest component where it needs to go
if (QuestController.QuestControllerSingle.currentMainQuest == 1f)
{
Debug.Log("quest is 1");
Debug.Log(QuestController.QuestControllerSingle.currentMainQuest + " = QuestController.QuestControllerSingle.currentQuest");
GameObject.Find("Character1").AddComponent<MainQuest1_0>();
}
//QuestController.QuestControllerSingle.isQuestCurrent = false;
Destroy(this);
}
}
<file_sep>/2dProject/Assets/scripts/EmenyStuff/ProjectileAttacks/EnemyProjectileAttack.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyProjectileAttack : MonoBehaviour {
//prefab
public Transform fireBallPrefab;
//object speed
float speed = 6f;
void Start()
{
//Last for 3 seconds
Destroy(gameObject, 3.0f);
ProjectileMovement();
}
void Update()
{
//Move projectile towards where the player was
//transform.Translate(-transform.right * .1f);
//gameObjectRB.velocity = movement;
//transform.position = Vector2.MoveTowards(transform.position, PlayerController.PlayerControllerSingle.transform.position*2, .3f);
transform.position += transform.right * speed * Time.deltaTime;
}
void ProjectileMovement()
{
//point toward player
var dir = PlayerController.PlayerControllerSingle.transform.position - transform.position;
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
void OnTriggerEnter2D(Collider2D otherCollider)
{
Destroy(gameObject);
}
}
<file_sep>/2dProject/Assets/scripts/EmenyStuff/Movement/SliderEnemyMovment.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SliderEnemyMovment : MonoBehaviour {
private EdgeCollider2D edge;
int currentEdgePoint = 0;
GameObject ColliderHolder;
int currentEdgeSet;
Vector2 CurrentVector;
Vector2 knownVec;
Vector2 perpVec;
Quaternion targetRotation;
//random variables
int Direction;
float speed;
//for attack
Transform PlayerTransform;
public bool attacking = false;
SliderEnemyAttack Attack;
//attack cooldown when destoryed
float coolDown = 2;
float coolDownTimer = 2;
// Use this for initialization
void Start ()
{
//for attack
PlayerTransform = PlayerController.PlayerControllerSingle.transform;
Attack = GetComponentInChildren<SliderEnemyAttack>();
try
{
//get random edge collider
ColliderHolder = GameObject.Find("ColliderHolder");
currentEdgeSet = Random.Range(0, ColliderHolder.transform.childCount);
edge = ColliderHolder.transform.GetChild(currentEdgeSet).GetComponent<EdgeCollider2D>();
//set information
currentEdgePoint = 0;
gameObject.transform.position = new Vector2(edge.points[currentEdgePoint].x, edge.points[currentEdgePoint].y);
//random variables
Direction = Random.Range(0, 2);
speed = Random.Range(20, 40) / 100f;
}
catch
{
Debug.Log("initialized to early");
Destroy(gameObject);
}
}
void Update()
{
if (Vector2.Distance(transform.position, PlayerTransform.position) <= 1000f && !attacking)
{
if (coolDownTimer == 0)
{
coolDownTimer = coolDown;
attacking = true;
Attack.StartAttack();
//get new random direction when moving again
Direction = Random.Range(0, 2);
}
}
}
// Update is called once per frame
void FixedUpdate()
{
if (attacking)
{
//now gets set in attack script
//attacking = Attack.attacking;
}
else
{
//cool down for attack
if (coolDownTimer > 0)
{
coolDownTimer -= Time.deltaTime;
}
else
{
coolDownTimer = 0;
}
try
{
CurrentVector = new Vector2(edge.points[currentEdgePoint].x, edge.points[currentEdgePoint].y);
//gets current perp vector with current and next point
knownVec = CurrentVector - new Vector2(edge.points[(currentEdgePoint + 1) % edge.pointCount].x, edge.points[(currentEdgePoint + 1) % edge.pointCount].y);
perpVec = CurrentVector + new Vector2(knownVec.y, -knownVec.x) * 1;
//for moving the object
gameObject.transform.position = Vector2.MoveTowards(gameObject.transform.position, perpVec, speed);
//for rotating the object
targetRotation = Quaternion.LookRotation(Vector3.forward, perpVec - CurrentVector);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, .25f);
//gets next point to move to
if (Vector3.Distance(gameObject.transform.position, perpVec) <= .1f)
{
if (Direction == 0)
{
currentEdgePoint = (currentEdgePoint + 1) % (edge.edgeCount - 1);
}
else
{
currentEdgePoint = ((edge.edgeCount - 1) + currentEdgePoint - 1) % (edge.edgeCount - 1);
}
}
}
catch
{
try
{
//get random edge collider
ColliderHolder = GameObject.Find("ColliderHolder");
currentEdgeSet = Random.Range(0, ColliderHolder.transform.childCount);
edge = ColliderHolder.transform.GetChild(currentEdgeSet).GetComponent<EdgeCollider2D>();
//set information
currentEdgePoint = Random.Range(0, edge.edgeCount);
gameObject.transform.position = new Vector2(edge.points[currentEdgePoint].x, edge.points[currentEdgePoint].y);
Direction = Random.Range(0, 2);
}
catch
{
//needs time to spawn
}
}
}
}
}
<file_sep>/2dProject/Assets/scripts/PlayerScripts/GrapplingHookBody2.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GrapplingHookBody2 : MonoBehaviour {
DrawGrapHook drawGrapHook;
void Start ()
{
drawGrapHook = transform.parent.GetComponentInChildren<DrawGrapHook>();
}
void Update ()
{
}
public void OnTriggerEnter2D(Collider2D coll)
{
if (coll.tag == "Enemy" && drawGrapHook.hitEnemy == false)
{
drawGrapHook.InstanceID = coll.GetInstanceID();
drawGrapHook.hitEnemy = true;
drawGrapHook.enemyTransform = coll.transform;
}
}
}
<file_sep>/2dProject/Assets/scripts/SideQuest/GatherQuest.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GatherQuest : MonoBehaviour {
//quest text prefab object
public Text QuestTxt;
//quest giver name
public string questGiver { get; set; }
//Gather quest variables
public int gatherQuestCounter { get; set; }
public int gatherAmount { get; set; }
public string gatherTarget { get; set; }
//gather quest item prefab
public GameObject gatherItemPrefab;
public void UpdateGatherQuest()
{
//Text updateQuest2 = GameObject.Find("QuestPanel/GatherQuest").GetComponent<Text>();
QuestTxt.text = "Gather " + gatherAmount + " of " + gatherTarget + "\nCurrent Gathered: " + gatherQuestCounter;
if (gatherQuestCounter >= gatherAmount)
{
QuestTxt.text = "Gather Quest Complete. Return to " + questGiver;
//for if thye main quest needs side quest complete to continue
if (GameController.GameControllerSingle.sideQuestBool == true)
{
GameController.GameControllerSingle.sideQuestCounter += 1;
}
}
}
public void GatherQuestStarter()
{
QuestTxt.text = "Gather " + gatherAmount + " of " + gatherTarget + "\nCurrent Gathered: " + gatherQuestCounter;
//QuestTxt.name = questGiver + " Gather " + gatherTarget;
}
}
<file_sep>/2dProject/Assets/scripts/NPC/Morgana.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Morgana : MonoBehaviour
{
//reward
public Transform reward;
public bool character;
//Canvas text and image
private Text NPCtext;
private Text Herotext;
private CanvasGroup canvas;
public Sprite newSprite;
// Use this for initialization
void Start()
{
character = false;
NPCtext = DialogManager.DialogManagerSingle.NPCtext;
Herotext = DialogManager.DialogManagerSingle.Herotext;
canvas = DialogManager.DialogManagerSingle.canvas;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Q) && character && DialogManager.DialogManagerSingle.dialogOn == false)
{
DialogManager.DialogManagerSingle.TalkingCharacter.sprite = newSprite;
GatherQuest[] listGatherQuests = QuestController.QuestControllerSingle.GetComponentsInChildren<GatherQuest>();
if (listGatherQuests.Length > 0)
{
foreach (GatherQuest quest in listGatherQuests)
{
if (quest.questGiver == gameObject.name)
{
if (quest.gatherQuestCounter >= quest.gatherAmount)
{
Destroy(quest.QuestTxt.gameObject);
Destroy(quest.gameObject);
canvas.alpha = 1;
//start conversavtion
StartCoroutine(DialogManager.DialogManagerSingle.Dialog(DialogManager.DialogManagerSingle.NPCDialogueLoadPath + "Morgana/QuestComplete"));
}
else
{
canvas.alpha = 1;
//start conversavtion
StartCoroutine(DialogManager.DialogManagerSingle.Dialog(DialogManager.DialogManagerSingle.NPCDialogueLoadPath + "Morgana/QuestIncomplete"));
}
}
else
{
canvas.alpha = 1;
//start conversavtion
StartCoroutine(DialogManager.DialogManagerSingle.Dialog(DialogManager.DialogManagerSingle.NPCDialogueLoadPath + "Morgana/AcceptQuest"));
//will be random quest later
QuestController.QuestControllerSingle.PickQuest("Morgana", 2);
QuestController.QuestControllerSingle.PickQuest("Morgana", 2);
QuestController.QuestControllerSingle.PickQuest("Morgana", 2);
}
}
}
else
{
canvas.alpha = 1;
//start conversavtion
StartCoroutine(DialogManager.DialogManagerSingle.Dialog(DialogManager.DialogManagerSingle.NPCDialogueLoadPath + "Morgana/AcceptQuest"));
//will be random quest later
QuestController.QuestControllerSingle.PickQuest("Morgana", 2);
QuestController.QuestControllerSingle.PickQuest("Morgana", 2);
QuestController.QuestControllerSingle.PickQuest("Morgana", 2);
}
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
character = true;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
// set dialog manager variables to false and off, must to to retalk to anyone
DialogManager.DialogManagerSingle.dialogOn = false;
canvas.alpha = 0;
//set locals to false
character = false;
//Text reset and stopping Coroutine
NPCtext.text = "";
Herotext.text = "";
StopAllCoroutines();
}
}
}
<file_sep>/2dProject/Assets/scripts/MapCreation/DoorPrefabInfo.cs
using UnityEngine;
using System.Collections;
public class DoorPrefabInfo : MonoBehaviour {
public string seedReference { get; set; }
public int doorReference { get; set; }
}
<file_sep>/2dProject/Assets/scripts/PlayerScripts/DrawGrapHook.cs
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class DrawGrapHook : MonoBehaviour
{
private bool drawHook = false;
private Vector2 startPosLine;
private Vector2 endPosLine;
//grappling hook tip
public GameObject GrapTip;
private BoxCollider2D grabTipCollider;
private SpriteRenderer tipImage;
public bool HasTipCollided { get; set; }
public Rigidbody2D rb2dTip;
//grap body
private GameObject grapBody;
private GameObject grap2Body;
private BoxCollider2D grapBodyCollider;
private BoxCollider2D grapBody2Collider;
private SpriteRenderer bodyImage;
private Vector2 difference;
private float grapBodyAngle;
private Quaternion bodyRoatation;
public bool hasBodyCollided { get; set; }
//bools for key press
bool WDown, SDown;
//joint
public DistanceJoint2D joint;
//player rotation
private Quaternion playerRotation;
//for hit moveing object
public Transform enemyTransform;
public bool hitEnemy;
public int InstanceID;
//on start
void Start()
{
//grap hook info
GrapTip = GameObject.Find("GrapplingHookTip");
grabTipCollider = GrapTip.GetComponent<BoxCollider2D>();
//change to false at somepoint
HasTipCollided = false;
rb2dTip = GrapTip.GetComponent<Rigidbody2D>();
//grap hook body
grapBody = gameObject.transform.parent.Find("BodyCollider").gameObject;
grap2Body = gameObject.transform.parent.Find("BodyCollider2").gameObject;
grapBodyCollider = grapBody.GetComponent<BoxCollider2D>();
grapBody2Collider = grap2Body.GetComponent<BoxCollider2D>();
bodyImage = grapBody.GetComponentInChildren<SpriteRenderer>();
tipImage = GrapTip.GetComponentInChildren<SpriteRenderer>();
//add joint
joint = rb2dTip.GetComponent<DistanceJoint2D>();
joint.enabled = false;
}
void Update()
{
if (drawHook == true)
{
WDown = Input.GetKey(KeyCode.W);
SDown = Input.GetKey(KeyCode.S);
if (Vector2.Distance(PlayerController.PlayerControllerSingle.transform.position, GrapTip.transform.position) <= 1f)
{
WDown = false;
}
if (!HasTipCollided)
{
WDown = false;
}
if (hitEnemy)
{
GrapTip.transform.position = enemyTransform.position;
}
//for rotating body
difference = GrapTip.transform.position - PlayerController.PlayerControllerSingle.PlayerSprite.transform.position;
grapBody.transform.position = (PlayerController.PlayerControllerSingle.PlayerSprite.transform.position + GrapTip.transform.position) / 2;
grap2Body.transform.position = (PlayerController.PlayerControllerSingle.PlayerSprite.transform.position + GrapTip.transform.position) / 2;
grapBodyAngle = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
bodyRoatation = Quaternion.AngleAxis(grapBodyAngle, Vector3.forward);
grapBody.transform.rotation = bodyRoatation;
grap2Body.transform.rotation = bodyRoatation;
grapBodyCollider.size = new Vector2(Vector3.Distance(GrapTip.transform.position, PlayerController.PlayerControllerSingle.PlayerSprite.transform.position), .25f);
grapBody2Collider.size = new Vector2(Vector3.Distance(GrapTip.transform.position, PlayerController.PlayerControllerSingle.PlayerSprite.transform.position), .25f);
bodyImage.size = new Vector2(Vector3.Distance(GrapTip.transform.position, PlayerController.PlayerControllerSingle.PlayerSprite.transform.position), .2f);
}
else
{
GrapTip.transform.position = PlayerController.PlayerControllerSingle.PlayerSprite.transform.position;
}
}
// fixedupdate gives correct collisons update doesn't. collides bad at fast speeds
void FixedUpdate()
{
//needs to reset variables used for grap hook stuff
if (drawHook == true)
{
// move up rope
if (WDown)
{
joint.maxDistanceOnly = true;
joint.distance = Vector2.Distance(rb2dTip.transform.position, PlayerController.PlayerControllerSingle.PlayerSprite.transform.position);
joint.enabled = false;
}
else if (!WDown && HasTipCollided)
{
joint.maxDistanceOnly = false;
joint.enabled = true;
}
//move down rope
if (SDown)
{
joint.distance = Vector2.Distance(rb2dTip.transform.position, PlayerController.PlayerControllerSingle.PlayerSprite.transform.position);
joint.enabled = false;
}
else if (!SDown && HasTipCollided)
{
joint.enabled = true;
}
if (!HasTipCollided)
{
//now moves in grap tip
GrapTip.transform.position += GrapTip.transform.right * .5f;
//rb2dTip.velocity = GrapTip.transform.right * 15f;
//rb2dTip.AddForce(GrapTip.transform.right * .5f);
}
else
{
//if (PlayerController.PlayerControllerSingle.isGrapplingHook && (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D)))
//{
// Debug.Log("gravity off");
// PlayerController.PlayerControllerSingle.rb2d.gravityScale = 0;
//}
//else if(!PlayerController.PlayerControllerSingle.IsSliding)
//{
// Debug.Log("gravity on");
// PlayerController.PlayerControllerSingle.rb2d.gravityScale = 1;
//}
//don't rotate when sliding or move when sliding
if (!PlayerController.PlayerControllerSingle.IsSliding)
{
//for rotating the player object;
playerRotation = Quaternion.LookRotation(Vector3.forward, GrapTip.transform.position - PlayerController.PlayerControllerSingle.PlayerSprite.transform.position);
PlayerController.PlayerControllerSingle.PlayerSprite.transform.rotation = Quaternion.Slerp(PlayerController.PlayerControllerSingle.PlayerSprite.transform.rotation, playerRotation, .2f);
if (WDown)
{
//PlayerController.PlayerControllerSingle.transform.position += PlayerController.PlayerControllerSingle.transform.up * .5f;
if (PlayerController.PlayerControllerSingle.rb2d.velocity.y <= 10f)
{
PlayerController.PlayerControllerSingle.rb2d.velocity += (Vector2)PlayerController.PlayerControllerSingle.PlayerSprite.transform.up * .5f;
}
}
}
}
}
}
public bool TurnGrapHookOn()
{
//EventSystem eventSystem = EventSystem.current; This over just .current maybe?
//hook won't fire is skill isn't learned or over inventory
if (EventSystem.current.IsPointerOverGameObject() || !PlayerController.PlayerControllerSingle.grapplingHookSkill)
{
return false;
}
else
{
//grap body info
grapBody.transform.position = PlayerController.PlayerControllerSingle.PlayerSprite.transform.position;
grap2Body.transform.position = PlayerController.PlayerControllerSingle.PlayerSprite.transform.position;
grapBodyCollider.enabled = true;
grapBody2Collider.enabled = true;
grapBody.GetComponent<Rigidbody2D>().isKinematic = false;
bodyImage.enabled = true;
//grap tip info
grabTipCollider.enabled = true;
GrapTip.transform.position = PlayerController.PlayerControllerSingle.PlayerSprite.transform.position;
//set tip to dynamic for collision detection
rb2dTip.isKinematic = false;
tipImage.enabled = true;
HasTipCollided = false;
startPosLine = PlayerController.PlayerControllerSingle.PlayerSprite.transform.position;
endPosLine = Camera.main.ScreenToWorldPoint(Input.mousePosition);
float TipAngle = Mathf.Atan2(endPosLine.y - startPosLine.y, endPosLine.x - startPosLine.x) * Mathf.Rad2Deg;
Quaternion tipRotation = Quaternion.AngleAxis(TipAngle, Vector3.forward);
GrapTip.transform.rotation = tipRotation;
//start grap hook
drawHook = true;
//set gravity to normal
if (!PlayerController.PlayerControllerSingle.IsSliding)
{
//Debug.Log("gravity 1");
PlayerController.PlayerControllerSingle.rb2d.gravityScale = 1;
}
return true;
}
}
public bool TurnGrapHookOff()
{
//HasTipCollided = true;
//set to kinmatic so it doens't move while it's off
grapBody.GetComponent<Rigidbody2D>().isKinematic = true;
//body stuff
grapBodyCollider.size = new Vector2(.5f, .5f);
grapBody2Collider.size = new Vector2(.5f, .5f);
bodyImage.size = new Vector2(.1f, .2f);
grapBodyCollider.enabled = false;
grapBody2Collider.enabled = false;
bodyImage.enabled = false;
//tip stuff
rb2dTip.isKinematic = true;
tipImage.enabled = false;
grabTipCollider.enabled = false;
// for resetting pulling stuff
WDown = false;
SDown = false;
joint.enabled = false;
//turn off tip
drawHook = false;
return false;
}
}
<file_sep>/2dProject/Assets/scripts/Items/Item.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum ItemType {MANA, HEALTH, WEAPON, SHIELD, HELM, CHEST, BELT, GLOVES, BOOTS, RING, AMULET, KEY}; //add more types here for items
public enum Quality { COMMON, UNCOMMON, RARE, EPIC, LEGENDARY, ARTIFACT }
public class Item : MonoBehaviour {
public ItemType type;
public Quality quality;
public Sprite spriteNeutral;
public Sprite spriteHighlighted;
public int maxSize;
//item information
public string itemName;
public string description;
void Start()
{
if (maxSize == 0)
{
maxSize = 1;
}
itemName = gameObject.name;
//armor = Random.Range(armorL, armorH);
//damage = Random.Range(damageL, damageH);
//vit = Random.Range(vitL, vitH);
//intelligence = Random.Range(intelligenceL, intelligenceH);
//strength = Random.Range(strengthL, strengthH);
//charisma = Random.Range(charismaL, charismaH);
}
public virtual void Use()
{
Debug.Log("defualt use does nothing find override");
}
public virtual void UnEquipt()
{
Debug.Log("defualt unEquipt does nothing find override");
}
public virtual string GetToolTip()
{
string stats = string.Empty;
string color = string.Empty;
string newLine = string.Empty;
if(description != string.Empty)
{
newLine = "\n";
}
switch (quality)
{
case Quality.COMMON:
color = "white";
break;
case Quality.UNCOMMON:
color = "lime";
break;
case Quality.RARE:
color = "navy";
break;
case Quality.EPIC:
color = "magenta";
break;
case Quality.LEGENDARY:
color = "orange";
break;
case Quality.ARTIFACT:
color = "red";
break;
default:
break;
}
return string.Format("<color=" + color + "><size=16>{0}</size></color><size=14><i><color=lime>" + newLine + "{1}</color></i>{2}</size>", itemName, description, stats);
}
}
<file_sep>/2dProject/Assets/scripts/EmenyStuff/ProjectileAttacks/ProjectileAttackSplitInArc.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ProjectileAttackSplitInArc : MonoBehaviour {
//split time
private float splitCoolDown = .5f;
//number of times to split
public int splitNumber = 0;
//object speed
float speed = 6f;
public Vector3 GoalHeading;
//prefab
public Transform fireBallPrefab;
void Start()
{
//if (transform.position.z == 0f)
//{
// ProjectileMovement();
//}
//Last for 3 seconds
Destroy(gameObject, 1f);
//ProjectileMovement();
}
void Update()
{
//Move projectile
transform.position += transform.right * speed * Time.deltaTime;
if (splitNumber > 0)
{
//if want split before destroy
if (splitCoolDown > 0.0f)
{
splitCoolDown -= Time.deltaTime;
}
else
{
splitCoolDown = 2f;
var fireball = Instantiate(fireBallPrefab);
fireball.position = transform.position;
fireball.rotation = transform.rotation;
fireball.name = "Fireball";
var temp = fireball.gameObject.AddComponent<ProjectileAttackSplitInArc>();
temp.fireBallPrefab = fireBallPrefab;
temp.splitNumber = splitNumber - 1;
temp.transform.eulerAngles = new Vector3(0, 0, transform.eulerAngles.z + 30);
var fireball2 = Instantiate(fireBallPrefab);
fireball2.position = transform.position;
fireball2.rotation = transform.rotation;
fireball2.name = "Fireball";
var temp2 = fireball2.gameObject.AddComponent<ProjectileAttackSplitInArc>();
temp2.fireBallPrefab = fireBallPrefab;
temp2.splitNumber = splitNumber - 1;
temp2.transform.eulerAngles = new Vector3(0, 0, transform.eulerAngles.z - 30);
}
}
}
public void ProjectileMovement()
{
var dir = PlayerController.PlayerControllerSingle.transform.position - transform.position;
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
void OnTriggerEnter2D(Collider2D otherCollider)
{
Destroy(gameObject);
}
}
<file_sep>/2dProject/Assets/scripts/MainQuest/MainQuest6_0.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MainQuest6_0 : MonoBehaviour {
void Start ()
{
//set quest text in questlog
QuestController.QuestControllerSingle.MainQuestText.text = "Find factory In Cave. " + "Main Quest " + QuestController.QuestControllerSingle.currentMainQuest;
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.name == "BossDoor1")
{
GameController.GameControllerSingle.questTravel = true;
QuestController.QuestControllerSingle.currentMainQuest = 7f;
if (QuestController.QuestControllerSingle.currentMainQuest == 7f)
{
Debug.Log("quest is 6");
Debug.Log(QuestController.QuestControllerSingle.currentMainQuest + " = QuestController.QuestControllerSingle.currentQuest");
GameObject.Find("Hero").AddComponent<MainQuest7_0>();
}
Destroy(this);
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.name == "BossDoor1")
{
GameController.GameControllerSingle.questTravel = false;
}
}
}
<file_sep>/2dProject/Assets/scripts/BossRoom/BossScript.cs
using UnityEngine;
using System.Collections;
/// Handle hitpoints and damages
public class BossScript : MonoBehaviour
{
public Transform loot;
public Transform loot2;
public Transform loot3;
//Drop bomb when shield is activate
public Transform bomb;
/// Total hitpoints
public bool isEnemy { get; set; }
private int experiencePoint;
//shield bools
public GameObject shield;
public MoveTowardPlayer movement;
private bool shield1 = true;
private bool shield2 = true;
private bool shield3 = true;
//Accessing Healthbar Script on boss
public Healthbar bossHealth;
GodHands bossAttack;
bool startTimer = false;
private float timer = 0;
private float distanceToPlayer;
private Vector3 playersLastLocations;
public bool shieldOn = false;
public bool charge = true;
public bool bombSpawn = false;
public static BossScript BossScriptSingle;
void Awake()
{
if (BossScriptSingle == null)
{
DontDestroyOnLoad(gameObject);
BossScriptSingle = this;
}
else if (BossScriptSingle != this)
{
Destroy(gameObject);
}
}
void Start()
{
// set emeny information
experiencePoint = 5;
bossHealth = GetComponent<Healthbar>();
bossHealth.maxHealth = 20;
bossHealth.currentHealth = 20;
isEnemy = true;
//for boss attack
bossAttack = GetComponentInChildren<GodHands>();
//for movement scipt
movement = gameObject.GetComponent<MoveTowardPlayer>();
}
void Update()
{
//for checking how far the player is
distanceToPlayer = Vector3.Distance(transform.position, PlayerController.PlayerControllerSingle.transform.position);
if(shieldOn == false) {
if (distanceToPlayer <= 10)
{
playersLastLocations = PlayerController.PlayerControllerSingle.transform.position;
startTimer = true;
}
//timer for time until attack
if (startTimer)
{
timer += Time.deltaTime;
}
if (timer >= 3)
{
startTimer = false;
timer = 0;
playersLastLocations = PlayerController.PlayerControllerSingle.transform.position;
bossAttack.AttackBoss(playersLastLocations);
}
}
else //shieldon is true
{
if (charge == true)
{
StartCoroutine(Charge());
}
}
}
/// Inflicts damage and check if the object should be destroyed
public void Damage(int damageCount)
{
//Cant be damage when shield is up
if (shieldOn == false)
{
bossHealth.currentHealth -= damageCount;
//For multiple similar phases of an enemy fight (aka same thing happens multiple times)
//if (bossHealth.currentHealth / bossHealth.maxHealth <= HEALTHTHREASHHOLD && shield1)
//{
// HEALTHTHREASHHOLD -= .25F
//}
//Activate shields when certain thresholds are met.
if (bossHealth.currentHealth / bossHealth.maxHealth <= .75f && shield1)
{
//Make it so this statement cant happen again
shield1 = false;
//Set vars for charge and shield is on
charge = true;
shieldOn = true;
shield.SetActive(true);
movement.enabled = false;
bossHealth.currentHealth = bossHealth.maxHealth * .75f;
//Instantiate(bomb, new Vector3(12.0f, 0, 0), Quaternion.identity);
}
else if(bossHealth.currentHealth / bossHealth.maxHealth <= .5f && shield2)
{
//Make it so this statement cant happen again
shield2 = false;
//Set vars for charge and shield is on
charge = true;
shieldOn = true;
shield.SetActive(true);
movement.enabled = false;
bossHealth.currentHealth = bossHealth.maxHealth * .50f;
//Instantiate(bomb, new Vector3(12.0f, 0, 0), Quaternion.identity);
}
else if(bossHealth.currentHealth / bossHealth.maxHealth <= .25f && shield3)
{
//Make it so this statement cant happen again
shield3 = false;
charge = true;
shieldOn = true;
shield.SetActive(true);
movement.enabled = false;
bossHealth.currentHealth = bossHealth.maxHealth * .25f;
//Instantiate(bomb, new Vector3(12.0f, 0, 0), Quaternion.identity);
}
else if (bossHealth.currentHealth <= 0)
{
//set exp
PlayerStats.PlayerStatsSingle.GainExperiencePoints(experiencePoint);
//PlayerStats.PlayerStatsSingle.experiencePoints += experiencePoint;
//Boss1 is now dead
MainQuest8_0 mainQuest = PlayerController.PlayerControllerSingle.transform.GetComponent<MainQuest8_0>();
mainQuest.bossDead = true;
mainQuest.BossSprite = GameObject.Find("Boss").GetComponent<SpriteRenderer>().sprite;
DialogManager.DialogManagerSingle.TalkingCharacter.sprite = mainQuest.BossSprite;
Destroy(gameObject);
}
}
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Player")
{
PlayerStats.PlayerStatsSingle.health -= 1;
}
if (collision.gameObject.name == "LeftWall")
{
transform.GetComponent<Rigidbody2D>().velocity = new Vector3(0, transform.GetComponent<Rigidbody2D>().velocity.y, 0);
transform.GetComponent<Rigidbody2D>().AddForce(new Vector3(5f, 0f, 0));
//Spawn bomb on other side of the room is charging
if (bombSpawn == false && shieldOn == true)
{
Instantiate(bomb, new Vector3(12.0f, 0, 0), Quaternion.identity);
}
}
if (collision.gameObject.name == "RightWall")
{
transform.GetComponent<Rigidbody2D>().velocity = new Vector3(0, transform.GetComponent<Rigidbody2D>().velocity.y, 0);
transform.GetComponent<Rigidbody2D>().AddForce(new Vector3(-5f, 0f, 0));
//Spawn bomb on other side of the room
if (bombSpawn == false && shieldOn == true)
{
Instantiate(bomb, new Vector3(-12.0f, 0, 0), Quaternion.identity);
}
}
}
void OnTriggerEnter2D(Collider2D otherCollider)
{
//if bullet, do bullet stuff
if (otherCollider.tag == "Bullet" && transform.tag == "Enemy")
{
Debug.Log("HIT by Bullet");
Destroy(otherCollider.gameObject);
Damage(1);
}
}
//For charging left and right
IEnumerator Charge()
{
//Keeps Charging periodic
charge = false;
yield return new WaitForSeconds(3);
//PLayer to the left of boss
if (PlayerController.PlayerControllerSingle.transform.position.x > transform.position.x)
{
transform.GetComponent<Rigidbody2D>().velocity = new Vector3(0, transform.GetComponent<Rigidbody2D>().velocity.y, 0);
transform.GetComponent<Rigidbody2D>().AddForce(new Vector3(2000f, 0, 0));
//StartCoroutine(ChargingLeft());
}
//player to the right of boss
else
{
transform.GetComponent<Rigidbody2D>().velocity = new Vector3(0, transform.GetComponent<Rigidbody2D>().velocity.y, 0);
transform.GetComponent<Rigidbody2D>().AddForce(new Vector3(-2000f, 0, 0));
//StartCoroutine(ChargingRight());
}
charge = true;
}
////For charging left and right
//IEnumerator ChargingLeft()
//{
// charge = true;
// yield return new WaitForSeconds(3);
// transform.GetComponent<Rigidbody2D>().AddForce(new Vector3(2000f, 0, 0));
//}
//IEnumerator ChargingRight()
//{
// charge = true;
// yield return new WaitForSeconds(3);
// transform.GetComponent<Rigidbody2D>().AddForce(new Vector3(-2000f, 0, 0));
//}
}
<file_sep>/2dProject/Assets/scripts/Items/Weapons/Blowdart/Blowdart.cs
using UnityEngine;
public class Blowdart : Weapon
{
public GameObject shotPrefab;
public float shootingRate = 0.25f;
private float shootCooldown;
void Start()
{
shootCooldown = 0f;
}
void LateUpdate()
{
if (shootCooldown > 0)
{
shootCooldown -= Time.deltaTime;
}
}
public override void Attack()
{
//Debug.Log(GameController.GameControllerSingle.damage);
if (CanAttack)
{
shootCooldown = shootingRate;
// Create a new shot
GameObject shotTransform = Instantiate(shotPrefab, GameObject.Find("PlayerProjectiles").transform) as GameObject;
// Assign bullet information; location and damage
shotTransform.transform.position = transform.position;
shotTransform.GetComponent<DamageOnCollision>().damage = PlayerStats.PlayerStatsSingle.strength;
}
}
void OnDestroy()
{
PlayerController.PlayerControllerSingle.playerAttack -= Attack;
}
public bool CanAttack
{
get
{
return shootCooldown <= 0f;
}
}
}<file_sep>/2dProject/Assets/scripts/MapCreation/MapAddOns.cs
using UnityEngine;
using System.Collections.Generic;
public class MapAddOns : MonoBehaviour
{
public Transform doorPrefab;
public Transform bossDoorPrefab;
//enemy prefabs
public Transform EnemyPreFab;
public Transform TurretPreFab;
public GameObject SlideEnemyPreFab;
//gather prefabs
public GameObject ManaPotion;
public GameObject HealthPotion;
public List<Vector2> GenerateDoorsLocations(int[,] map)
{
//for pos doors
List<Vector2> doorPositions;
MapInformation data = MapGenerator.MapGeneratorSingle.MapInfo[MapGenerator.MapGeneratorSingle.seed];
doorPositions = new List<Vector2>();
//Pass border size to script
for (int x = 1; x < data.width - 1; x++)
{
for (int y = 1; y < data.height - 1; y++)
{
if (map[x, y] == 0 && map[x + 1, y] == 0 && map[x - 1, y] == 0 && map[x, y + 1] == 0 && map[x, y - 1] == 1 && map[x + 1, y - 1] == 1 && map[x - 1, y - 1] == 1 && map[x, y + 2] == 0)
{
Vector2 doorXY;
//storing door positions
doorXY = new Vector2(x, y);
doorPositions.Add(doorXY);
}
}
}
return doorPositions;
}
public void PlaceDoorsOnMap(List<Vector2> doorLocations, List<int> doorType)
{
string curSeed = MapGenerator.MapGeneratorSingle.seed;
//this is for removing the old doors
foreach (Transform door in transform.Find("DoorHolder"))
{
Destroy(door.gameObject);
}
//drawing new doors
for (int x = 0; x < doorLocations.Count; x++)
{
float xPos = doorLocations[x].x;
float yPos = doorLocations[x].y;
//Debug.Log("Door Type = " + doorType[x]);
switch (doorType[x])
{
case 0:
Transform doorTransform = Instantiate(doorPrefab, transform.Find("DoorHolder")) as Transform;
doorTransform.name = "Door";
doorTransform.position = new Vector3(xPos, yPos, 0);
//for setting the map and door ref of each door
DoorPrefabInfo mapInfo = FindObjectOfType<DoorPrefabInfo>();
//Debug.Log("curSeed = " + curSeed + " currentDoor = " + x);
mapInfo.doorReference = x;
mapInfo.seedReference = curSeed;
break;
case 1:
Transform BossDoor = Instantiate(bossDoorPrefab, transform.Find("DoorHolder")) as Transform;
BossDoor.GetComponent<DoorToNewScene>().sceneToLoad = "Boss1";
BossDoor.name = "BossDoor1";
BossDoor.position = new Vector3(xPos, yPos, 0);
break;
}
}
}
public List<Vector2> GenerateEnemySpawnLocation(MapInformation map1)
{
//for pos doors
List<Vector2> AllPossibleEnemyLocations;
List<Vector2> EnemyLocations;
int numEnemies = 5;
AllPossibleEnemyLocations = new List<Vector2>();
EnemyLocations = new List<Vector2>();
//pick spots for enemies to spawn
for (int x = 1; x < map1.width - 1; x++)
{
for (int y = 1; y < map1.height - 1; y++)
{
if ((map1.map[x, y] == 0 && map1.map[x + 1, y] == 0 && map1.map[x - 1, y] == 0 && map1.map[x, y + 1] == 0) &&
(map1.map[x, y - 1] == 1 || map1.map[x + 1, y - 1] == 1 || map1.map[x - 1, y - 1] == 1))
{
Vector2 possibleEnemyXY;
possibleEnemyXY = new Vector2(x, y);
AllPossibleEnemyLocations.Add(possibleEnemyXY);
}
}
}
Vector2 enemyXY;
float xPos;
float yPos;
for (int x = 0; x < numEnemies; x++)
{
//don't spawn enemies by possible door locations
enemyXY = CheckIfDoorLocations(AllPossibleEnemyLocations, map1);
xPos = -map1.width / 2 + enemyXY.x * map1.squareSize + map1.squareSize / 2;
yPos = -map1.height / 2 + enemyXY.y * map1.squareSize + map1.squareSize;
enemyXY = new Vector2(xPos, yPos);
EnemyLocations.Add(enemyXY);
}
return EnemyLocations;
}
public List<Vector2> GenerateTurretSpawnLocation(MapInformation map1)
{
//for pos doors
List<Vector2> AllPossibleTurretLocations;
List<Vector2> TurretLocations;
int numTurrets = 5;
AllPossibleTurretLocations = new List<Vector2>();
TurretLocations = new List<Vector2>();
//pick spots for enemies to spawn
for (int x = 1; x < map1.width - 1; x++)
{
for (int y = 1; y < map1.height - 1; y++)
{
if ((map1.map[x, y] == 0 && map1.map[x + 1, y] == 0 && map1.map[x - 1, y] == 0 && map1.map[x, y + 1] == 0) &&
(map1.map[x, y - 1] == 1 || map1.map[x + 1, y - 1] == 1 || map1.map[x - 1, y - 1] == 1))
{
Vector2 possibleEnemyXY;
possibleEnemyXY = new Vector2(x, y);
AllPossibleTurretLocations.Add(possibleEnemyXY);
}
}
}
Vector2 enemyXY;
float xPos;
float yPos;
for (int x = 0; x < numTurrets; x++)
{
//don't spawn enemies by possible door locations
enemyXY = CheckIfDoorLocations(AllPossibleTurretLocations, map1);
xPos = -map1.width / 2 + enemyXY.x * map1.squareSize + map1.squareSize / 2;
yPos = -map1.height / 2 + enemyXY.y * map1.squareSize + map1.squareSize;
enemyXY = new Vector2(xPos, yPos);
TurretLocations.Add(enemyXY);
}
return TurretLocations;
}
//make sure enemies can't spawn at x distance within door spawn
public Vector2 CheckIfDoorLocations(List<Vector2> enemyPositions, MapInformation map1)
{
Vector2 tempEnemyPos;
tempEnemyPos = enemyPositions[Random.Range(0, enemyPositions.Count)];
//foreach (float door in doorLocationsX)
float xPos;
float yPos;
for (int x = 0; x < map1.doorLocationsX.Count; x++)
{
xPos = -map1.width / 2 + tempEnemyPos.x * map1.squareSize + map1.squareSize / 2;
yPos = -map1.height / 2 + tempEnemyPos.y * map1.squareSize + map1.squareSize;
if (Vector2.Distance(new Vector2(xPos, yPos), new Vector2(map1.doorLocationsX[x], map1.doorLocationsY[x])) <= 5)
{
enemyPositions.Remove(tempEnemyPos);
tempEnemyPos = CheckIfDoorLocations(enemyPositions, map1);
return tempEnemyPos;
}
}
return tempEnemyPos;
}
public void PlaceEnemyOnMap(List<Vector2> enemyLocations, List<Vector2> turretLocations)
{
Transform Parent = GameObject.Find("EnemyList").transform;
//placing enemies enemies
for (int x = 0; x < enemyLocations.Count; x++)
{
float xPos = enemyLocations[x].x;
float yPos = enemyLocations[x].y;
var enemyTransform = Instantiate(EnemyPreFab) as Transform;
enemyTransform.name = EnemyPreFab.name;
enemyTransform.transform.SetParent(Parent);
enemyTransform.position = new Vector3(xPos, yPos, 0);
}
//placing turrets
for (int x = 0; x < turretLocations.Count; x++)
{
float xPos = turretLocations[x].x;
float yPos = turretLocations[x].y;
var turretTransform = Instantiate(TurretPreFab) as Transform;
turretTransform.name = TurretPreFab.name;
turretTransform.transform.SetParent(Parent);
turretTransform.position = new Vector3(xPos, yPos, 0);
}
}
public void SpawnSliderEnemy()
{
for (int x = 0; x < 1; x++)
{
GameObject SlideEnemy = Instantiate(SlideEnemyPreFab);
SlideEnemy.transform.SetParent(GameObject.Find("EnemyList").transform);
SlideEnemy.name = SlideEnemyPreFab.name;
}
}
//public void SpawnSeekingEnemy(MapInformation map1)
//{
// for (int x = 1; x < map1.width - 1; x++)
// {
// for (int y = 1; y < map1.height - 1; y++)
// {
// if (map1.map[x, y] == 0)
// {
// int xPos = -map1.width / 2 + x * map1.squareSize + map1.squareSize / 2;
// int yPos = -map1.height / 2 + y * map1.squareSize + map1.squareSize;
// }
// }
// }
//}
public List<Vector2> GenerateAllOpenMapLocations(MapInformation map1)
{
List<Vector2> allOpenMapLocations;
allOpenMapLocations = new List<Vector2>();
Vector2 openLocation;
for (int x = 1; x < map1.width - 1; x++)
{
for (int y = 1; y < map1.height - 1; y++)
{
if ((map1.map[x, y] == 0))
{
openLocation = new Vector2(x, y);
allOpenMapLocations.Add(openLocation);
}
}
}
return allOpenMapLocations;
}
public void GatherQuestItems(MapInformation map1)
{
//List<GatherQuest> listGatherQuests = new List<GatherQuest>();
GatherQuest[] listGatherQuests = FindObjectsOfType(typeof(GatherQuest)) as GatherQuest[];
if (listGatherQuests.Length > 0)
{
//get spawn locations for items
List<Vector2> availableSpawnLocations = new List<Vector2>();
availableSpawnLocations = GenerateAllOpenMapLocations(map1);
int spawnLocationIndex;
Transform ItemHeirarchySpawn = GameObject.Find("WorldItems").transform;
//spawn all items that need to be spawned
foreach (GatherQuest gatherQuest in listGatherQuests)
{
GameObject spawnedItem = Instantiate(gatherQuest.gatherItemPrefab, ItemHeirarchySpawn);
Debug.Log(spawnedItem.name);
spawnedItem.name = gatherQuest.gatherTarget;
spawnLocationIndex = Random.Range(0, availableSpawnLocations.Count);
spawnedItem.transform.position = new Vector2(-map1.width / 2 + availableSpawnLocations[spawnLocationIndex].x * map1.squareSize + map1.squareSize / 2, -map1.height / 2 + availableSpawnLocations[spawnLocationIndex].y * map1.squareSize + map1.squareSize);
availableSpawnLocations.RemoveAt(spawnLocationIndex);
//give item gather script
//spawnedItem.AddComponent<Gather>();
}
}
}
}
<file_sep>/2dProject/Assets/scripts/Items/Weapons/Weapon.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Weapon : MonoBehaviour {
public virtual void Attack()
{
Debug.Log("base attack find override");
}
//public virtual void onCollide()
//{
// Debug.Log("base onCollide find override");
//}
}
<file_sep>/2dProject/Assets/scripts/NPC/BlitzCrank.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BlitzCrank : MonoBehaviour {
//reward
public Transform reward;
public bool touchingCharacter;
//Coroutine
//bool Herod = false;
//bool NPCd = false;
//Canvas text and image
private Text NPCtext;
private Text Herotext;
private CanvasGroup canvas;
public Sprite newSprite;
//has a quest
public bool hasQuest { get; set; }
public static BlitzCrank BlitzCrankSingle;
void Awake()
{
if (BlitzCrankSingle == null)
{
BlitzCrankSingle = this;
}
else if (BlitzCrankSingle != this)
{
Destroy(gameObject);
}
}
// Use this for initialization
void Start ()
{
//put quest to false
hasQuest = false;
touchingCharacter = false;
NPCtext = DialogManager.DialogManagerSingle.NPCtext;
Herotext = DialogManager.DialogManagerSingle.Herotext;
canvas = DialogManager.DialogManagerSingle.canvas;
if (QuestController.QuestControllerSingle.currentMainQuest == 4f)
{
Debug.Log("quest is 4");
hasQuest = true;
Debug.Log(QuestController.QuestControllerSingle.currentMainQuest + " = QuestController.QuestControllerSingle.currentQuest");
gameObject.AddComponent<MainQuest4_0>();
}
else if (QuestController.QuestControllerSingle.currentMainQuest == 9f)
{
Debug.Log("quest is 9");
hasQuest = true;
Debug.Log(QuestController.QuestControllerSingle.currentMainQuest + " = QuestController.QuestControllerSingle.currentQuest");
gameObject.AddComponent<MainQuest9_0>();
}
else if (QuestController.QuestControllerSingle.currentMainQuest == 10f)
{
Debug.Log("quest is 10");
hasQuest = true;
Debug.Log(QuestController.QuestControllerSingle.currentMainQuest + " = QuestController.QuestControllerSingle.currentQuest");
gameObject.AddComponent<MainQuest10_0>();
}
}
// Update is called once per frame
void Update ()
{
if (hasQuest)
{
//do nothing let quest do stuff
}
else if (Input.GetKeyDown(KeyCode.Q) && touchingCharacter && DialogManager.DialogManagerSingle.dialogOn == false)
{
DialogManager.DialogManagerSingle.TalkingCharacter.sprite = newSprite;
KillQuest[] listKillQuests = QuestController.QuestControllerSingle.GetComponentsInChildren<KillQuest>();
//remove sidequest and text object
if (listKillQuests.Length > 0)
{
foreach (KillQuest quest in listKillQuests)
{
if (quest.questGiver == gameObject.name)
{
if (quest.killQuestCounter >= quest.killAmount)
{
Destroy(quest.QuestTxt.gameObject);
Destroy(quest.gameObject);
canvas.alpha = 1;
StartCoroutine(DialogManager.DialogManagerSingle.Dialog(DialogManager.DialogManagerSingle.NPCDialogueLoadPath + "Blitz/QuestComplete"));
}
else
{
canvas.alpha = 1;
StartCoroutine(DialogManager.DialogManagerSingle.Dialog(DialogManager.DialogManagerSingle.NPCDialogueLoadPath + "Blitz/QuestIncomplete"));
}
}
else
{
canvas.alpha = 1;
//start conversavtion
StartCoroutine(DialogManager.DialogManagerSingle.Dialog(DialogManager.DialogManagerSingle.NPCDialogueLoadPath + "Blitz/AcceptQuest"));
QuestController.QuestControllerSingle.PickQuest("Blitz", 1);
QuestController.QuestControllerSingle.PickQuest("Blitz", 1);
QuestController.QuestControllerSingle.PickQuest("Blitz", 1);
}
}
}
else
{
canvas.alpha = 1;
//start conversavtion
StartCoroutine(DialogManager.DialogManagerSingle.Dialog(DialogManager.DialogManagerSingle.NPCDialogueLoadPath + "Blitz/AcceptQuest"));
QuestController.QuestControllerSingle.PickQuest("Blitz", 1);
QuestController.QuestControllerSingle.PickQuest("Blitz", 1);
QuestController.QuestControllerSingle.PickQuest("Blitz", 1);
}
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
touchingCharacter = true;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
// set dialog manager variables to false and off, must to to retalk to anyone
DialogManager.DialogManagerSingle.dialogOn = false;
canvas.alpha = 0;
//set locals to false
touchingCharacter = false;
//Text reset and stopping Coroutine
NPCtext.text = "";
Herotext.text = "";
StopAllCoroutines();
//NPCd = false;
//Herod = false;
}
}
//IEnumerator HeroDialog(Text textComp, string message)
//{
// while (NPCd)
// {
// yield return new WaitForSeconds(0.1f);
// }
// textComp.text = "";
// Herod = true;
// foreach (char letter in message.ToCharArray())
// {
// textComp.text += letter;
// yield return new WaitForSeconds(0.05f);
// }
// Herod = false;
//}
//IEnumerator NPCDialog(Text textComp, string message)
//{
// while (Herod)
// {
// yield return new WaitForSeconds(0.1f);
// }
// textComp.text = "";
// NPCd = true;
// foreach (char letter in message.ToCharArray())
// {
// textComp.text += letter;
// yield return new WaitForSeconds(0.05f);
// }
// NPCd = false;
//}
}
<file_sep>/2dProject/Assets/scripts/EmenyStuff/EnemyStats/Walker.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Walker : EnemyStats
{
public Transform HealthDrop;
public Transform loot;
public Transform loot2;
public Transform loot3;
void Start()
{
items.Add(HealthDrop);
this.items.Add(loot);
this.items.Add(loot2);
this.items.Add(loot3);
StartStats();
}
public override void StartStats()
{
dropRate = .5f;
damagePlayerOnCollision = true;
health = 3;
experiencePoint = 4;
invincible = false;
}
}
<file_sep>/2dProject/Assets/scripts/GameInformation/PlayerStats.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerStats : MonoBehaviour {
public static PlayerStats PlayerStatsSingle;
public int health;
public int maxHealth;
public int magic;
public int maxMagic;
public int experiencePoints;
public int level;
public int skillPoints = 8;
public int statPoints = 20;
public int maxPoints = 20;
public int itemAttractDistance;
public int maxJumps;
public int armor = 0;
public int dexterity = 0;
public int intelligence = 0;
public int strength = 0;
public int vitality = 0;
public int armorMin = 0;
public int dexterityMin = 0;
public int intelligenceMin = 0;
public int strengthMin = 0;
public int vitalityMin = 0;
// for diaplaying exp and level
private Text experiencePointsTxt;
private Text levelTxt;
private Text healthTxt;
private RectTransform healthSize;
private RectTransform healthSizeMax;
private Text magicTxt;
private RectTransform magicSize;
private Text statPoinsTxt;
private Text skillPoinsTxt;
private Text armorTxt;
private Text dexterityTxt;
private Text intelligenceTxt;
private Text strengthTxt;
private Text vitalityTxt;
public Dictionary<string, MapInformation> MapInfo = new Dictionary<string, MapInformation>();
// Use this for initialization
void Awake()
{
if (PlayerStatsSingle == null)
{
PlayerStatsSingle = this;
}
else if (PlayerStatsSingle != this)
{
Destroy(gameObject);
}
}
void Start()
{
if (GameController.GameControllerSingle.dontLoadTheGame)
{
Debug.Log("didn't load game data");
}
else
{
GameController.GameControllerSingle.LoadPlayerData();
}
//temp magic set
maxMagic = 10;
magic = maxMagic;
//set skill point temporarely
skillPoints = 8;
//temp attract distance set
itemAttractDistance = 5;
maxJumps = 1;
//find button and set method
GameObject.Find("ArmorUp").GetComponent<Button>().onClick.AddListener(delegate { IncArmor(); });
GameObject.Find("ArmorDown").GetComponent<Button>().onClick.AddListener(delegate { DecArmor(); });
GameObject.Find("DexterityUp").GetComponent<Button>().onClick.AddListener(delegate { IncDexterity(); });
GameObject.Find("DexterityDown").GetComponent<Button>().onClick.AddListener(delegate { DecDexterity(); });
GameObject.Find("IntelligenceUp").GetComponent<Button>().onClick.AddListener(delegate { IncIntelligence(); });
GameObject.Find("IntelligenceDown").GetComponent<Button>().onClick.AddListener(delegate { DecIntelligence(); });
GameObject.Find("StrengthUp").GetComponent<Button>().onClick.AddListener(delegate { IncStrength(); });
GameObject.Find("StrengthDown").GetComponent<Button>().onClick.AddListener(delegate { DecStrength(); });
GameObject.Find("VitalityUp").GetComponent<Button>().onClick.AddListener(delegate { IncVitality(); });
GameObject.Find("VitalityDown").GetComponent<Button>().onClick.AddListener(delegate { DecVitality(); });
//save skill points button
GameObject.Find("SaveStatPoints").GetComponent<Button>().onClick.AddListener(delegate { SaveStatPoints(); });
//find text box
experiencePointsTxt = GameObject.Find("Experience").GetComponent<Text>();
levelTxt = GameObject.Find("Level").GetComponent<Text>();
healthTxt = GameObject.Find("PlayerHealthText").GetComponent<Text>();
magicTxt = GameObject.Find("PlayerMagicText").GetComponent<Text>();
statPoinsTxt = GameObject.Find("StatPoints").GetComponent<Text>();
skillPoinsTxt = GameObject.Find("SkillPoints").GetComponent<Text>();
armorTxt = GameObject.Find("ArmorText").GetComponent<Text>();
dexterityTxt = GameObject.Find("DexterityText").GetComponent<Text>();
intelligenceTxt = GameObject.Find("IntelligenceText").GetComponent<Text>();
strengthTxt = GameObject.Find("StrengthText").GetComponent<Text>();
vitalityTxt = GameObject.Find("VitalityText").GetComponent<Text>();
//get Status rec
healthSize = GameObject.Find("PlayerHealth").GetComponent<RectTransform>();
healthSizeMax = GameObject.Find("PlayerHealthBack").GetComponent<RectTransform>();
magicSize = GameObject.Find("PlayerMagic").GetComponent<RectTransform>();
//set text
experiencePointsTxt.text = "EXP: " + experiencePoints;
levelTxt.text = "Level: " + level;
statPoinsTxt.text = "Unspent Stat Points: " + statPoints;
skillPoinsTxt.text = "Unspent Skill Points: " + skillPoints;
armorTxt.text = "Armor: " + armor;
dexterityTxt.text = "Dexterity: " + strength;
intelligenceTxt.text = "Intelligence: " + intelligence;
strengthTxt.text = "Strength: " + strength;
vitalityTxt.text = "Vitality: " + vitality;
ChangeHealth(0);
ChangeMagic(0);
}
public void ChangeHealth(int changeAmount)
{
if ((health += changeAmount) <= maxHealth)
{
//nothing needs to happen if didn't overload health
}
else
{
health = maxHealth;
}
healthTxt.text = health.ToString();
healthSize.sizeDelta = new Vector2(-healthSizeMax.rect.width + (healthSizeMax.rect.width * ((float)health / maxHealth)), healthSize.sizeDelta.y);
}
public void ChangeMagic(int changeAmount)
{
if((magic += changeAmount) <= maxMagic)
{
//nothing needs to happen if didn't overload magic
}
else
{
magic = maxMagic;
}
magicTxt.text = magic.ToString();
magicSize.sizeDelta = new Vector2(-healthSizeMax.rect.width + (healthSizeMax.rect.width * ((float)magic / maxMagic)), magicSize.sizeDelta.y);
}
//for gain exp
public void GainExperiencePoints(int exp)
{
experiencePoints += exp;
//change exp text
experiencePointsTxt.text = "EXP: " + experiencePoints;
//player level up
if (experiencePoints >= level * 15)
{
// text container
StartCoroutine(GameController.GameControllerSingle.ShowMessage("LEVEL UP NERD!", 2));
//level character up
level += 1;
maxHealth += 2;
ChangeHealth(maxHealth);
statPoints += 3;
maxPoints = statPoints;
//change text that needs to change
levelTxt.text = "Level: " + level;
statPoinsTxt.text = "Unspent Stat Points: " + statPoints;
// change damage for currently equipt weapons
//PlayerController.PlayerControllerSingle.weaponDamage += 1;
}
}
public void IncArmor()
{
if (statPoints > 0)
{
UpdateStatText("Armor", 1);
}
}
public void DecArmor()
{
if (armor > armorMin)
{
UpdateStatText("Armor", -1);
}
}
public void IncDexterity()
{
if (statPoints > 0)
{
UpdateStatText("Dexterity", 1);
}
}
public void DecDexterity()
{
if (dexterity > dexterityMin)
{
UpdateStatText("Dexterity", -1);
}
}
public void IncIntelligence()
{
if (statPoints > 0)
{
UpdateStatText("Intelligence", 1);
}
}
public void DecIntelligence()
{
if (intelligence > intelligenceMin)
{
UpdateStatText("Intelligence", -1);
}
}
public void IncStrength()
{
if (statPoints > 0)
{
UpdateStatText("Strength", 1);
}
}
public void DecStrength()
{
if (strength > strengthMin)
{
UpdateStatText("Strength", -1);
}
}
public void IncVitality()
{
if (statPoints > 0)
{
UpdateStatText("Vitality", 1);
}
}
public void DecVitality()
{
if (vitality > vitalityMin)
{
UpdateStatText("Vitality", -1);
}
}
//not even using this right now
public void IncSkillPoints()
{
skillPoints += 1;
skillPoinsTxt.text = "Unspent Skill Points: " + skillPoints;
}
public void DecSkillPoints()
{
skillPoints -= 1;
skillPoinsTxt.text = "Unspent Skill Points: " + skillPoints;
}
public void UpdateStatText(string stat, int point)
{
statPoints -= point;
statPoinsTxt.text = "Unspent Stat Points: " + statPoints;
switch (stat)
{
case "Armor":
armor += point;
armorTxt.text = "Armor: " + armor;
break;
case "Dexterity":
dexterity += point;
dexterityTxt.text = "Dexterity: " + dexterity;
break;
case "Intelligence":
intelligence += point;
intelligenceTxt.text = "Intelligence: " + intelligence;
break;
case "Strength":
strength += point;
strengthTxt.text = "Strength: " + strength;
break;
case "Vitality":
vitality += point;
vitalityTxt.text = "Vitality: " + vitality;
break;
default:
break;
}
}
public void SaveStatPoints()
{
armorMin = armor;
dexterityMin = dexterity;
intelligenceMin = intelligence;
strengthMin = strength;
vitalityMin = vitality;
maxPoints = statPoints;
}
public void UpdateStatText(int arm, int dex, int intel, int str, int vit)
{
//so you can't get skill points from armor
armorMin += arm;
dexterityMin += dex;
intelligenceMin += intel;
strengthMin += str;
vitalityMin += vit;
//for text change
armor += arm;
dexterity += dex;
intelligence += intel;
strength += str;
vitality += vit;
//change text
armorTxt.text = "Armor: " + armor;
dexterityTxt.text = "Dexterity: " + dexterity;
intelligenceTxt.text = "Intelligence: " + intelligence;
strengthTxt.text = "Strength: " + strength;
vitalityTxt.text = "Vitality: " + vitality;
}
}
<file_sep>/2dProject/Assets/scripts/MainQuest/MainQuest4_0.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MainQuest4_0 : MonoBehaviour {
public bool touchingCharacter { get; set; }
private Text NPCtext;
private Text Herotext;
private CanvasGroup canvas;
private bool inRange = false;
void Start()
{
Debug.Log("TalkOnApproach");
NPCtext = DialogManager.DialogManagerSingle.NPCtext;
Herotext = DialogManager.DialogManagerSingle.Herotext;
canvas = DialogManager.DialogManagerSingle.canvas;
//set quest text in questlog
QuestController.QuestControllerSingle.MainQuestText.text = "Talk to blitz. " + "Main Quest " + QuestController.QuestControllerSingle.currentMainQuest;
}
void Update()
{
if (!inRange)
{
if (Vector3.Distance(PlayerController.PlayerControllerSingle.transform.position, transform.position) <= 5f)
{
DialogManager.DialogManagerSingle.TalkingCharacter.sprite = transform.GetComponent<SpriteRenderer>().sprite;
inRange = true;
Debug.Log("TalkOnApproach is in range");
canvas.alpha = 1;
StartCoroutine(Dialog());
}
}
}
public IEnumerator Dialog()
{
string Conversation1 = DialogManager.DialogManagerSingle.MainQuestDialogueLoadPath + "MainQuest4_0.0";
//freeze player
PlayerController.PlayerControllerSingle.LockPosition();
StartCoroutine(DialogManager.DialogManagerSingle.Dialog(Conversation1));
//waits for conversation to finish
while ((DialogManager.DialogManagerSingle.dialogOn == true))
{
yield return new WaitForSeconds(0.1f);
}
//wait 1 sec before continuing
yield return new WaitForSeconds(1f);
canvas.alpha = 0;
//let player move again
PlayerController.PlayerControllerSingle.UnLockPosition();
//Text reset
NPCtext.text = "";
Herotext.text = "";
QuestController.QuestControllerSingle.currentMainQuest = 5f;
if (QuestController.QuestControllerSingle.currentMainQuest == 5f)
{
//moved to quest 5
//GameController.GameControllerSingle.sideQuestCounter = 0;
//GameController.GameControllerSingle.sideQuestBool = true;
Debug.Log("quest is 5");
Debug.Log(QuestController.QuestControllerSingle.currentMainQuest + " = QuestController.QuestControllerSingle.currentQuest");
GameObject.Find("Hero").AddComponent<MainQuest5_0>();
}
BlitzCrank.BlitzCrankSingle.hasQuest = false;
Destroy(this);
}
}
<file_sep>/2dProject/Assets/scripts/MainQuest/MainQuest5_0.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MainQuest5_0 : MonoBehaviour {
private Text NPCtext;
private Text Herotext;
private CanvasGroup canvas;
private Sprite BlitzSprite;
private bool touchingCharacter = false;
// Use this for initialization
void Start ()
{
Debug.Log("TalkOnApproach");
NPCtext = DialogManager.DialogManagerSingle.NPCtext;
Herotext = DialogManager.DialogManagerSingle.Herotext;
canvas = DialogManager.DialogManagerSingle.canvas;
GameController.GameControllerSingle.sideQuestCounter = 0;
GameController.GameControllerSingle.sideQuestBool = true;
//set quest text in questlog
QuestController.QuestControllerSingle.MainQuestText.text = "Do Side Quest. " + "Main Quest " + QuestController.QuestControllerSingle.currentMainQuest;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Q))
{
Debug.Log("talk to character1 for quest5");
Debug.Log(GameController.GameControllerSingle.sideQuestCounter);
Debug.Log(GameController.GameControllerSingle.sideQuestBool);
if (touchingCharacter && GameController.GameControllerSingle.sideQuestCounter >= 1 && GameController.GameControllerSingle.sideQuestBool == true)
{
GameController.GameControllerSingle.sideQuestBool = false;
Debug.Log("Complete, go to main quest 5");
BlitzCrank.BlitzCrankSingle.hasQuest = false;
QuestController.QuestControllerSingle.currentMainQuest = 6f;
canvas.alpha = 1;
StartCoroutine(Dialog());
}
else if (GameController.GameControllerSingle.sideQuestCounter >= 1 && GameController.GameControllerSingle.sideQuestBool == true)
{
//set quest text in questlog
QuestController.QuestControllerSingle.MainQuestText.text = "Talk to Blitz. " + "Main Quest " + QuestController.QuestControllerSingle.currentMainQuest;
}
else
{
Debug.Log("not complete side quest yet, talked to side quest character to complete");
}
}
}
public IEnumerator Dialog()
{
//set blitz sprite
DialogManager.DialogManagerSingle.TalkingCharacter.sprite = BlitzSprite;
string Conversation1 = DialogManager.DialogManagerSingle.MainQuestDialogueLoadPath + "MainQuest5_0.0";
//freeze player
PlayerController.PlayerControllerSingle.LockPosition();
StartCoroutine(DialogManager.DialogManagerSingle.Dialog(Conversation1));
//waits for conversation to finish
while ((DialogManager.DialogManagerSingle.dialogOn == true))
{
yield return new WaitForSeconds(0.1f);
}
//wait 1 sec before continuing
yield return new WaitForSeconds(1f);
canvas.alpha = 0;
//let player move again
PlayerController.PlayerControllerSingle.UnLockPosition();
//Text reset
NPCtext.text = "";
Herotext.text = "";
QuestController.QuestControllerSingle.currentMainQuest = 6f;
if (QuestController.QuestControllerSingle.currentMainQuest == 6f)
{
Debug.Log("quest is 6");
Debug.Log(QuestController.QuestControllerSingle.currentMainQuest + " = QuestController.QuestControllerSingle.currentQuest");
GameObject.Find("Hero").AddComponent<MainQuest6_0>();
}
Destroy(this);
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.name == "Blitz")
{
BlitzSprite = collision.gameObject.GetComponent<SpriteRenderer>().sprite;
touchingCharacter = true;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.name == "Blitz")
{
touchingCharacter = false;
}
}
}
<file_sep>/2dProject/Assets/scripts/AudioMixer.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AudioMixer : MonoBehaviour {
//singleton reference
public static AudioMixer AudioMixerSingle;
public AudioClip Slow;
public AudioClip Medium;
public AudioClip Fast;
int song = 0;
float songLength = 0;
AudioSource audioSource;
void Awake()
{
if (AudioMixerSingle == null)
{
AudioMixerSingle = this;
}
else if (AudioMixerSingle != this)
{
Destroy(gameObject);
}
}
void Start()
{
DontDestroyOnLoad(this);
audioSource = GetComponent<AudioSource>();
}
void Update()
{
if (!audioSource.isPlaying)
{
//stop any music then pick song
audioSource.Stop();
song += 1;
song = song % 3;
if (song == 0)
{
audioSource.clip = Slow;
songLength = 67f;
//audioSource.Play();
}
else if (song == 1)
{
audioSource.clip = Medium;
//audioSource.Play();
songLength = 77f;
}
else
{
audioSource.clip = Fast;
//audioSource.Play();
songLength = 61f;
}
//start fade in and fade out for current song
StartCoroutine(FadeIn(audioSource, 2f));
//can't have fade longer than song
StartCoroutine(FadeOut(audioSource, 2f, songLength - 3));
}
//if (Input.GetKeyDown(KeyCode.O))
//{
// StartCoroutine(FadeOut(audioSource, 1f, songLength));
//}
}
public static IEnumerator FadeOut(AudioSource audioSource, float FadeTime, float songLength)
{
float startVolume = audioSource.volume;
startVolume = 1f;
//waits until song is almost over
while (songLength >= 0)
{
songLength -= Time.deltaTime;
yield return null;
}
while (audioSource.volume > 0)
{
audioSource.volume -= startVolume * Time.deltaTime / FadeTime;
yield return null;
}
audioSource.Stop();
audioSource.volume = startVolume;
}
public static IEnumerator FadeIn(AudioSource audioSource, float FadeTime)
{
float startVolume = 1f;
audioSource.volume = 0;
audioSource.Play();
while (audioSource.volume < 1.0f)
{
audioSource.volume += startVolume * Time.deltaTime / FadeTime;
yield return null;
}
audioSource.volume = 1f;
}
}
<file_sep>/2dProject/Assets/scripts/MapCreation/MeshGenerator.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class MeshGenerator : MonoBehaviour
{
public SquareGrid squareGrid;
public GameObject cavePrefab;
List<Vector3> vertices;
List<int> triangles;
Dictionary<int, List<Triangle>> triangleDictionary = new Dictionary<int, List<Triangle>>();
List<List<int>> outlines = new List<List<int>>();
HashSet<int> checkedVertices = new HashSet<int>();
List<string> groundPieceName = new List<string>();
int groundPieceIndex;
public Transform groundPiece;
//parent for tiles
public Transform TileHolder;
//dictionary of Cave mesh objects
public Dictionary<string, GameObject> CaveMeshDictionary = new Dictionary<string, GameObject>();
// need to save the mesh for the map
public void GenerateMesh(int[,] map, float squareSize)
{
triangleDictionary.Clear();
outlines.Clear();
checkedVertices.Clear();
squareGrid = new SquareGrid(map, squareSize);
vertices = new List<Vector3>();
triangles = new List<int>();
for (int x = 0; x < squareGrid.squares.GetLength(0); x++)
{
for (int y = 0; y < squareGrid.squares.GetLength(1); y++)
{
TriangulateSquare(squareGrid.squares[x, y]);
}
}
GameObject Cave = Instantiate(cavePrefab, transform.Find("MapHolder"));
Cave.name = "Cave" + MapGenerator.MapGeneratorSingle.seed;
//setting layer of maps
Cave.transform.position = new Vector3(0, 0, 1);
CaveMeshDictionary.Add(MapGenerator.MapGeneratorSingle.seed, Cave);
Mesh mesh = new Mesh();
Cave.GetComponent<MeshFilter>().mesh = mesh;
mesh.name = Cave.name;
mesh.vertices = vertices.ToArray();
mesh.triangles = triangles.ToArray();
mesh.RecalculateNormals();
//int tileAmount = 10;
Vector2[] uvs = new Vector2[vertices.Count];
for (int i = 0; i < vertices.Count; i++)
{
//float percentX = Mathf.InverseLerp(-map.GetLength(0) / 2 * squareSize, map.GetLength(0) / 2 * squareSize, vertices[i].x) * tileAmount;
//float percentY = Mathf.InverseLerp(-map.GetLength(0) / 2 * squareSize, map.GetLength(0) / 2 * squareSize, vertices[i].z) * tileAmount;
uvs[i] = new Vector2(vertices[i].x, vertices[i].z);
}
mesh.uv = uvs;
Generate2DColliders();
}
//doesn't recreate mesh; load it from data; need to find a way to save 2d edge collider as well
public void LoadMeshFromAssests(int[,] map, float squareSize)
{
//get current cave object
GameObject caveCurrent = CaveMeshDictionary[MapGenerator.MapGeneratorSingle.seed];
//get old cave object for turing off
if (DrawPlayerMap.DrawPlayerMapSingle.currentMap != null)
{
GameObject caveOld = CaveMeshDictionary[DrawPlayerMap.DrawPlayerMapSingle.currentMap];
//turn off old cave object
caveOld.SetActive(false);
}
//turn on current cave object
caveCurrent.SetActive(true);
triangleDictionary.Clear();
outlines.Clear();
checkedVertices.Clear();
squareGrid = new SquareGrid(map, squareSize);
vertices = new List<Vector3>();
triangles = new List<int>();
for (int x = 0; x < squareGrid.squares.GetLength(0); x++)
{
for (int y = 0; y < squareGrid.squares.GetLength(1); y++)
{
TriangulateSquare(squareGrid.squares[x, y]);
}
}
Generate2DColliders();
}
void Generate2DColliders()
{
//for removing all current edge colliders
foreach (Transform edgeTemp in GameObject.Find("ColliderHolder").transform)
{
Destroy(edgeTemp.gameObject);
}
//for removing all current edge colliders
//EdgeCollider2D[] currentColliders = gameObject.GetComponents<EdgeCollider2D>();
//for (int i = 0; i < currentColliders.Length; i++)
//{
// Destroy(currentColliders[i]);
//}
CalculateMeshOutlines();
//remove old sprites
foreach (Transform child in TileHolder)
{
if (child.tag == "Ground")
{
GameObject.Destroy(child.gameObject);
}
}
for(int x = 0; x < outlines.Count; x++)
{
List<int> outline = outlines[x];
//}
//foreach (List<int> outline in outlines)
//{
//EdgeCollider2D edgeCollider = gameObject.AddComponent<EdgeCollider2D>();
GameObject temp = new GameObject();
//need to add a rigid body so collition detect child object not parent
Rigidbody2D tempRb2d;
tempRb2d = temp.AddComponent<Rigidbody2D>();
tempRb2d.isKinematic = true;
temp.transform.SetParent(gameObject.transform.Find("ColliderHolder").transform);
temp.layer = 8;
Vector2[] edgePoints = new Vector2[outline.Count];
temp.name = "edgeCollider" + x;
EdgeCollider2D edgeCollider = temp.AddComponent<EdgeCollider2D>();
float vertX;
float vertXPLus1;
float vertXMinus1;
float vertZ;
float vertZPLus1;
float vertZMinus1;
int count = outline.Count;
groundPieceName.Add("FlatGround_CAVE");
groundPieceName.Add("RLGround_CAVE");
groundPieceName.Add("UPSlope_To_Ground");
groundPieceName.Add("Groud_To_UPSlope");
for (int i = 0; i < outline.Count; i++)
{
edgePoints[i] = new Vector2(vertices[outline[i]].x, vertices[outline[i]].z);
//for loading sprites in
// consider replacing with Vector3.Distance(a,b)
vertX = vertices[outline[i]].x;
vertXPLus1 = vertices[outline[(i + 1) % count]].x;
vertXMinus1 = vertices[outline[(count + i - 1) % count]].x;
//Z IS Y VALUE
vertZ = vertices[outline[i]].z;
vertZPLus1 = vertices[outline[(i + 1) % count]].z;
vertZMinus1 = vertices[outline[(count + i - 1) % count]].z;
if (i == (outline.Count - 1))
{
//point 0 and max are at same spot
vertXPLus1 = vertices[outline[1]].x;
vertZPLus1 = vertices[outline[1]].z;
}
if (i != 0)
{
DrawSprites(vertX, vertXPLus1, vertXMinus1, vertZ, vertZPLus1, vertZMinus1, count, i);
}
}
edgeCollider.points = edgePoints;
//makes walls not sticky
PhysicsMaterial2D test = new PhysicsMaterial2D();
test.bounciness = 0f;
test.friction = 0f;
edgeCollider.sharedMaterial = test;
// or
//edgeCollider.sharedMaterial = (PhysicsMaterial2D)AssetDatabase.LoadAssetAtPath("Assets/meterials/noStickOrBounce", typeof(PhysicsMaterial2D));
}
}
void DrawSprites(float vertX, float vertXPLus1, float vertXMinus1 ,float vertZ , float vertZPLus1 ,float vertZMinus1 , int count, int i)
{
var groundSprite = Instantiate(groundPiece, TileHolder) as Transform;
groundSprite.name = i.ToString();
//groundSprite.transform = 0;
//horizontal and vetical sprites
//does not work when change between - and minus fix that problem
//Vector3.Distance(a,b) could be used here maybe
if (vertZ == vertZPLus1 || vertX == vertXPLus1 || vertZ == vertZMinus1 || vertX == vertXMinus1)
{
//top piece
if (vertX > vertXPLus1 && (vertZ == vertZPLus1 || vertZ == vertZMinus1))
{
groundPiece.transform.position = new Vector3(vertX, vertZ + .5f, 0);
groundPiece.eulerAngles = new Vector3(180, 0, 0);
if (Mathf.Abs(vertX - vertXPLus1) <= .5f || Mathf.Abs(vertX - vertXMinus1) <= .5f)
{
if ((Mathf.Abs(vertZ - vertZMinus1) == 0f) && (vertZ - vertZPLus1) > 0)
{
groundPiece.eulerAngles = new Vector3(0, 0, 180);
groundPieceIndex = 3;
}
else if ((Mathf.Abs(vertZ - vertZPLus1) == 0f) && (vertZ - vertZMinus1) > 0)
{
groundPieceIndex = 3;
}
else
{
if ((vertZ - vertZMinus1) < 0)
{
groundPiece.eulerAngles = new Vector3(0, 0, 180);
groundPieceIndex = 2;
}
else
groundPieceIndex = 2;
}
}
else {
groundPieceIndex = 0;
}
}
//bottom pieces
else if (vertX < vertXPLus1 && (vertZ == vertZPLus1 || vertZ == vertZMinus1))
{
groundPiece.transform.position = new Vector3(vertX, vertZ - .5f, 0);
groundPiece.eulerAngles = new Vector3(0, 0, 0);
if (Mathf.Abs(vertX - vertXPLus1) <= .5f || Mathf.Abs(vertX - vertXMinus1) <= .5f)
{
if (Mathf.Abs(vertX - vertXPLus1) <= .5f || Mathf.Abs(vertX - vertXMinus1) <= .5f)
{
if ((Mathf.Abs(vertZ - vertZMinus1) == 0f) && (vertZ - vertZPLus1) < 0)
{
groundPiece.eulerAngles = new Vector3(0, 0, 0);
groundPieceIndex = 3;
}
else if ((Mathf.Abs(vertZ - vertZPLus1) == 0f) && (vertZ - vertZMinus1) < 0)
{
groundPiece.eulerAngles = new Vector3(0, 180, 0);
groundPieceIndex = 3;
}
else
{
if ((vertZ - vertZPLus1) > 0)
{
groundPiece.eulerAngles = new Vector3(0, 180, 0);
groundPieceIndex = 2;
}
else
groundPieceIndex = 2;
}
}
}
else {
groundPieceIndex = 0;
}
}
//left wall
else if (vertZ > vertZPLus1 || vertZ < vertZMinus1)
{
groundPiece.transform.position = new Vector3(vertX - .5f, vertZ , 0);
groundPiece.eulerAngles = new Vector3(0, 0, 270);
if (vertZ > vertZPLus1 && (vertX == vertXPLus1 || vertX == vertXMinus1))
{
groundPiece.transform.position = new Vector3(vertX - .5f, vertZ, 0);
groundPiece.eulerAngles = new Vector3(0, 0, 270);
if (Mathf.Abs(vertZ - vertZPLus1) <= .5f || Mathf.Abs(vertZ - vertZMinus1) <= .5f)
{
if ((Mathf.Abs(vertX - vertXMinus1) == 0f) && (vertX - vertXPLus1) < 0)
{
groundPiece.eulerAngles = new Vector3(0, 0, 270);
groundPieceIndex = 3;
}
else if ((Mathf.Abs(vertX - vertXPLus1) == 0f) && (vertX - vertXMinus1) < 0)
{
groundPiece.eulerAngles = new Vector3(180, 0, 270);
groundPieceIndex = 3;
}
else
{
if ((vertX - vertXPLus1) > 0)
{
groundPiece.eulerAngles = new Vector3(180, 0, 270);
groundPieceIndex = 2;
}
else
groundPieceIndex = 2;
}
}
else
{
groundPieceIndex = 0;
}
}
}
//right wall
else if (vertZ < vertZPLus1 || vertZ > vertZMinus1)
{
groundPiece.transform.position = new Vector3(vertX + .5f, vertZ, 0);
groundPiece.eulerAngles = new Vector3(0, 0, 90);
if (Mathf.Abs(vertZ - vertZPLus1) <= .5f || Mathf.Abs(vertZ - vertZMinus1) <= .5f)
{
if ((Mathf.Abs(vertX - vertXMinus1) == 0f) && (vertX - vertXPLus1) > 0)
{
groundPiece.eulerAngles = new Vector3(0, 0, 90);
groundPieceIndex = 3;
}
else if ((Mathf.Abs(vertX - vertXPLus1) == 0f) && (vertX - vertXMinus1) > 0)
{
groundPiece.eulerAngles = new Vector3(180, 0, 90);
groundPieceIndex = 3;
}
else
{
if ((vertX - vertXPLus1) < 0)
{
groundPiece.eulerAngles = new Vector3(180, 0, 90);
groundPieceIndex = 2;
}
else
{
groundPieceIndex = 2;
}
}
}
else
{
groundPieceIndex = 0;
}
}
}
//diagonal sprites
else if (vertX != vertXPLus1 && vertZ != vertZPLus1 && (vertZPLus1 - vertZMinus1) != 0 && (vertXPLus1 - vertXMinus1) != 0)
{
if (vertX < vertXPLus1 && vertZ < vertZPLus1)
{
groundPiece.eulerAngles = new Vector3(0, 0, 0);
}
else if (vertX > vertXPLus1 && vertZ < vertZPLus1)
{
groundPiece.eulerAngles = new Vector3(0, 0, 90);
}
else if (vertX > vertXPLus1 && vertZ > vertZPLus1)
{
groundPiece.eulerAngles = new Vector3(0, 0, 180);
}
else if (vertX < vertXPLus1 && vertZ > vertZPLus1)
{
groundPiece.eulerAngles = new Vector3(0, 0, 270);
}
groundPieceIndex = 1;
groundPiece.transform.position = new Vector3(vertX, vertZ, 0);
groundPiece.transform.localScale = new Vector3(.125f, .125f, 0);
}
SpriteRenderer renderer = groundSprite.GetComponent<SpriteRenderer>();
renderer.sortingLayerName = "Background";
renderer.sprite = Resources.Load("Prefabs/Map/Textures/" + groundPieceName[groundPieceIndex], typeof(Sprite)) as Sprite;
renderer.transform.eulerAngles = groundPiece.eulerAngles;
renderer.transform.position = groundPiece.transform.position;
}
void TriangulateSquare(Square square)
{
switch (square.configuration)
{
case 0:
break;
// 1 points:
case 1:
MeshFromPoints(square.centreLeft, square.centreBottom, square.bottomLeft);
break;
case 2:
MeshFromPoints(square.bottomRight, square.centreBottom, square.centreRight);
break;
case 4:
MeshFromPoints(square.topRight, square.centreRight, square.centreTop);
break;
case 8:
MeshFromPoints(square.topLeft, square.centreTop, square.centreLeft);
break;
// 2 points:
case 3:
MeshFromPoints(square.centreRight, square.bottomRight, square.bottomLeft, square.centreLeft);
break;
case 6:
MeshFromPoints(square.centreTop, square.topRight, square.bottomRight, square.centreBottom);
break;
case 9:
MeshFromPoints(square.topLeft, square.centreTop, square.centreBottom, square.bottomLeft);
break;
case 12:
MeshFromPoints(square.topLeft, square.topRight, square.centreRight, square.centreLeft);
break;
case 5:
MeshFromPoints(square.centreTop, square.topRight, square.centreRight, square.centreBottom, square.bottomLeft, square.centreLeft);
break;
case 10:
MeshFromPoints(square.topLeft, square.centreTop, square.centreRight, square.bottomRight, square.centreBottom, square.centreLeft);
break;
// 3 point:
case 7:
MeshFromPoints(square.centreTop, square.topRight, square.bottomRight, square.bottomLeft, square.centreLeft);
break;
case 11:
MeshFromPoints(square.topLeft, square.centreTop, square.centreRight, square.bottomRight, square.bottomLeft);
break;
case 13:
MeshFromPoints(square.topLeft, square.topRight, square.centreRight, square.centreBottom, square.bottomLeft);
break;
case 14:
MeshFromPoints(square.topLeft, square.topRight, square.bottomRight, square.centreBottom, square.centreLeft);
break;
// 4 point:
case 15:
MeshFromPoints(square.topLeft, square.topRight, square.bottomRight, square.bottomLeft);
checkedVertices.Add(square.topLeft.vertexIndex);
checkedVertices.Add(square.topRight.vertexIndex);
checkedVertices.Add(square.bottomRight.vertexIndex);
checkedVertices.Add(square.bottomLeft.vertexIndex);
break;
}
}
void MeshFromPoints(params Node[] points)
{
AssignVertices(points);
if (points.Length >= 3)
CreateTriangle(points[0], points[1], points[2]);
if (points.Length >= 4)
CreateTriangle(points[0], points[2], points[3]);
if (points.Length >= 5)
CreateTriangle(points[0], points[3], points[4]);
if (points.Length >= 6)
CreateTriangle(points[0], points[4], points[5]);
}
void AssignVertices(Node[] points)
{
for (int i = 0; i < points.Length; i++)
{
if (points[i].vertexIndex == -1)
{
points[i].vertexIndex = vertices.Count;
vertices.Add(points[i].position);
}
}
}
void CreateTriangle(Node a, Node b, Node c)
{
triangles.Add(a.vertexIndex);
triangles.Add(b.vertexIndex);
triangles.Add(c.vertexIndex);
Triangle triangle = new Triangle(a.vertexIndex, b.vertexIndex, c.vertexIndex);
AddTriangleToDictionary(triangle.vertexIndexA, triangle);
AddTriangleToDictionary(triangle.vertexIndexB, triangle);
AddTriangleToDictionary(triangle.vertexIndexC, triangle);
}
void AddTriangleToDictionary(int vertexIndexKey, Triangle triangle)
{
if (triangleDictionary.ContainsKey(vertexIndexKey))
{
triangleDictionary[vertexIndexKey].Add(triangle);
}
else {
List<Triangle> triangleList = new List<Triangle>();
triangleList.Add(triangle);
triangleDictionary.Add(vertexIndexKey, triangleList);
}
}
void CalculateMeshOutlines()
{
for (int vertexIndex = 0; vertexIndex < vertices.Count; vertexIndex++)
{
if (!checkedVertices.Contains(vertexIndex))
{
int newOutlineVertex = GetConnectedOutlineVertex(vertexIndex);
if (newOutlineVertex != -1)
{
checkedVertices.Add(vertexIndex);
List<int> newOutline = new List<int>();
newOutline.Add(vertexIndex);
outlines.Add(newOutline);
FollowOutline(newOutlineVertex, outlines.Count - 1);
outlines[outlines.Count - 1].Add(vertexIndex);
}
}
}
}
void FollowOutline(int vertexIndex, int outlineIndex)
{
outlines[outlineIndex].Add(vertexIndex);
checkedVertices.Add(vertexIndex);
int nextVertexIndex = GetConnectedOutlineVertex(vertexIndex);
if (nextVertexIndex != -1)
{
FollowOutline(nextVertexIndex, outlineIndex);
}
}
int GetConnectedOutlineVertex(int vertexIndex)
{
List<Triangle> trianglesContainingVertex = triangleDictionary[vertexIndex];
for (int i = 0; i < trianglesContainingVertex.Count; i++)
{
Triangle triangle = trianglesContainingVertex[i];
for (int j = 0; j < 3; j++)
{
int vertexB = triangle[j];
if (vertexB != vertexIndex && !checkedVertices.Contains(vertexB))
{
if (IsOutlineEdge(vertexIndex, vertexB))
{
return vertexB;
}
}
}
}
return -1;
}
bool IsOutlineEdge(int vertexA, int vertexB)
{
List<Triangle> trianglesContainingVertexA = triangleDictionary[vertexA];
int sharedTriangleCount = 0;
for (int i = 0; i < trianglesContainingVertexA.Count; i++)
{
if (trianglesContainingVertexA[i].Contains(vertexB))
{
sharedTriangleCount++;
if (sharedTriangleCount > 1)
{
break;
}
}
}
return sharedTriangleCount == 1;
}
struct Triangle
{
public int vertexIndexA;
public int vertexIndexB;
public int vertexIndexC;
int[] vertices;
public Triangle(int a, int b, int c)
{
vertexIndexA = a;
vertexIndexB = b;
vertexIndexC = c;
vertices = new int[3];
vertices[0] = a;
vertices[1] = b;
vertices[2] = c;
}
public int this[int i]
{
get
{
return vertices[i];
}
}
public bool Contains(int vertexIndex)
{
return vertexIndex == vertexIndexA || vertexIndex == vertexIndexB || vertexIndex == vertexIndexC;
}
}
public class SquareGrid
{
public Square[,] squares;
public SquareGrid(int[,] map, float squareSize)
{
int nodeCountX = map.GetLength(0);
int nodeCountY = map.GetLength(1);
float mapWidth = nodeCountX * squareSize;
float mapHeight = nodeCountY * squareSize;
ControlNode[,] controlNodes = new ControlNode[nodeCountX, nodeCountY];
for (int x = 0; x < nodeCountX; x++)
{
for (int y = 0; y < nodeCountY; y++)
{
Vector3 pos = new Vector3(-mapWidth / 2 + x * squareSize + squareSize / 2, 0, -mapHeight / 2 + y * squareSize + squareSize / 2);
controlNodes[x, y] = new ControlNode(pos, map[x, y] == 1, squareSize);
}
}
squares = new Square[nodeCountX - 1, nodeCountY - 1];
for (int x = 0; x < nodeCountX - 1; x++)
{
for (int y = 0; y < nodeCountY - 1; y++)
{
squares[x, y] = new Square(controlNodes[x, y + 1], controlNodes[x + 1, y + 1], controlNodes[x + 1, y], controlNodes[x, y]);
}
}
}
}
public class Square
{
public ControlNode topLeft, topRight, bottomRight, bottomLeft;
public Node centreTop, centreRight, centreBottom, centreLeft;
public int configuration;
public Square(ControlNode _topLeft, ControlNode _topRight, ControlNode _bottomRight, ControlNode _bottomLeft)
{
topLeft = _topLeft;
topRight = _topRight;
bottomRight = _bottomRight;
bottomLeft = _bottomLeft;
centreTop = topLeft.right;
centreRight = bottomRight.above;
centreBottom = bottomLeft.right;
centreLeft = bottomLeft.above;
if (topLeft.active)
configuration += 8;
if (topRight.active)
configuration += 4;
if (bottomRight.active)
configuration += 2;
if (bottomLeft.active)
configuration += 1;
}
}
public class Node
{
public Vector3 position;
public int vertexIndex = -1;
public Node(Vector3 _pos)
{
position = _pos;
}
}
public class ControlNode : Node
{
public bool active;
public Node above, right;
public ControlNode(Vector3 _pos, bool _active, float squareSize) : base(_pos)
{
active = _active;
above = new Node(position + Vector3.forward * squareSize / 2f);
right = new Node(position + Vector3.right * squareSize / 2f);
}
}
}<file_sep>/2dProject/Assets/scripts/EmenyStuff/Movement/FlyingPathfinding.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FlyingPathfinding : MonoBehaviour {
float speed = .1f;
int distanceDetection = 4;
//Vector3 raycastOffSet;
float rayTurnLeft;
float rayTurnRight;
float angleOffSetLeft, angleOffSetRight = 0f;
bool frontRayHit = false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
}
void FixedUpdate()
{
Pathfinding();
}
void Pathfinding()
{
//raycastOffSet = Vector3.zero;
Vector3 left = transform.position + transform.up;
Vector3 right = transform.position - transform.up;
Vector3 leftSideCheck = transform.position + transform.up;
Vector3 rightSideCheck = transform.position - transform.up;
RaycastHit2D hitLeft = Physics2D.Raycast(left, transform.right, distanceDetection);
RaycastHit2D hitRight = Physics2D.Raycast(right, transform.right, distanceDetection);
Debug.DrawRay(left, transform.right * distanceDetection, Color.blue);
Debug.DrawRay(right, transform.right * distanceDetection, Color.blue);
frontRayHit = false;
if (hitLeft)
{
//raycastOffSet -= Vector3.forward;
if (rayTurnLeft <= 1)
{
rayTurnLeft += .1f;
angleOffSetLeft -= 9f;
}
else
{
Debug.Log("left side full");
rayTurnLeft = 1;
}
frontRayHit = true;
}
else if (hitRight)
{
//raycastOffSet += Vector3.forward;
if (rayTurnRight <= 1)
{
rayTurnRight += .1f;
angleOffSetRight += 9f;
}
else
{
Debug.Log("right side full");
rayTurnRight = 1;
}
frontRayHit = true;
}
//Debug.DrawRay(leftSideCheck, new Vector3(-transform.right.y, transform.right.x, 0 )* distanceDetection, Color.red);
//Debug.DrawRay(rightSideCheck, new Vector3(transform.right.y, -transform.right.x, 0) * distanceDetection, Color.red);
Vector3 leftSide = (new Vector3(-transform.right.y * rayTurnLeft + transform.right.x * (1 - rayTurnLeft), (transform.right.x * rayTurnLeft + transform.right.y * (1 - rayTurnLeft)), 0));
Vector3 rightSide = (new Vector3(transform.right.y * rayTurnRight + transform.right.x * (1 - rayTurnRight), (-transform.right.x * rayTurnRight + transform.right.y * (1 - rayTurnRight)), 0));
Debug.DrawRay(leftSideCheck, leftSide * distanceDetection, Color.red);
Debug.DrawRay(rightSideCheck, rightSide * distanceDetection, Color.red);
RaycastHit2D leftSideHit = Physics2D.Raycast(leftSideCheck, leftSide, distanceDetection);
RaycastHit2D rightSideHit = Physics2D.Raycast(rightSideCheck, rightSide, distanceDetection);
if (leftSideHit)
{
}
else
{
angleOffSetLeft = 0;
rayTurnLeft = 0;
}
if (rightSideHit)
{
}
else
{
angleOffSetRight = 0;
rayTurnRight = 0;
}
Vector3 delta = PlayerController.PlayerControllerSingle.transform.position - transform.position;
float angle = Mathf.Atan2(delta.y, delta.x) * Mathf.Rad2Deg;
Quaternion rotation = Quaternion.Euler(0, 0, angle + angleOffSetLeft + angleOffSetRight);
transform.rotation = rotation;
if (!frontRayHit)
{
//transform.position += transform.right * speed;
}
transform.position += transform.right * speed;
//Vector3 delta = PlayerController.PlayerControllerSingle.transform.position - transform.position;
//float angle = Mathf.Atan2(delta.y, delta.x) * Mathf.Rad2Deg;
//Quaternion rotation = Quaternion.Euler(0, 0, angle + angleOffSet);
//transform.rotation = rotation;
//if (raycastOffSet != Vector3.zero)
//{
// transform.Rotate(raycastOffSet * 3f);
//}
//else
//{
// Vector3 delta = PlayerController.PlayerControllerSingle.transform.position - transform.position;
// float angle = Mathf.Atan2(delta.y, delta.x) * Mathf.Rad2Deg;
// Quaternion rotation = Quaternion.Euler(0, 0, angle + angleOffSet);
// transform.rotation = rotation;
//}
}
}
<file_sep>/2dProject/Assets/scripts/NPC/Doctor.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Doctor : MonoBehaviour
{
public bool character;
//Canvas text and image
private Text NPCtext;
private Text Herotext;
private CanvasGroup canvas;
public Sprite newSprite;
// Use this for initialization
void Start()
{
character = false;
//assign text boxes for dialog
NPCtext = DialogManager.DialogManagerSingle.NPCtext;
Herotext = DialogManager.DialogManagerSingle.Herotext;
canvas = DialogManager.DialogManagerSingle.canvas;
if (QuestController.QuestControllerSingle.currentMainQuest == 0f)
{
Debug.Log("quest is 0");
Debug.Log(QuestController.QuestControllerSingle.currentMainQuest + " = QuestController.QuestControllerSingle.currentQuest");
GameObject.Find("Doctor").AddComponent<MainQuest0_0>();
}
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Q) && character && DialogManager.DialogManagerSingle.dialogOn == false)
{
//set sprite
DialogManager.DialogManagerSingle.TalkingCharacter.sprite = newSprite;
canvas.alpha = 1;
//start conversavtion
StartCoroutine(DialogManager.DialogManagerSingle.Dialog(DialogManager.DialogManagerSingle.NPCDialogueLoadPath + "Doctor/AcceptQuest"));
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
character = true;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
// set dialog manager variables to false and off, must to to retalk to anyone
DialogManager.DialogManagerSingle.dialogOn = false;
canvas.alpha = 0;
//set locals to false
character = false;
//Text reset and stopping Coroutine
NPCtext.text = "";
Herotext.text = "";
StopAllCoroutines();
}
}
}
<file_sep>/2dProject/Assets/scripts/PlayerScripts/DoorCollider.cs
using UnityEngine;
using System.Collections;
using System;
public class DoorCollider : MonoBehaviour {
public int numVal { get; set; }
private string oldSeed;
private string oldDoor;
private string dicRef;
private string newSeed;
private string newDoor;
private string newDicRef;
private string[] values;
GameData gameData;
DoorPrefabInfo info;
void Start()
{
gameData = FindObjectOfType<GameData>();
}
public void OnTriggerEnter2D(Collider2D node)
{
//for door colliding in DrawPlayerMap
info = node.GetComponent<DoorPrefabInfo>();
if (node.gameObject.tag == "Door")
{
//Debug.Log("oldSeed = " + info.seedReference + " oldDoor = " + info.doorReference.ToString());
oldSeed = info.seedReference;
oldDoor = info.doorReference.ToString();
dicRef = oldSeed + "," + oldDoor;
//gameData = FindObjectOfType<GameData>();
newDicRef = gameData.GetDoorInfo(dicRef);
//Debug.Log("newDicRef = " + newDicRef);
//splits the dic ref apart into the map seed and the door index value
values = newDicRef.Split(',');
//Debug.Log("newSeed = " + values[0] + " newDoor = " + values[1]);
newSeed = values[0];
newDoor = values[1];
numVal = Int32.Parse(newDoor);
//numVal = gameData.FindMapIndex(newDoor);
//for drawing lines
DrawPlayerMap.DrawPlayerMapSingle.currentDoor = Int32.Parse(oldDoor);
DrawPlayerMap.DrawPlayerMapSingle.nextDoor = Int32.Parse(newDoor);
DrawPlayerMap.DrawPlayerMapSingle.currentMap = oldSeed;
DrawPlayerMap.DrawPlayerMapSingle.nextMap = newSeed;
//pass seed and door info to gameController.
GameController.GameControllerSingle.mapSeed = newSeed;
//GameController.GameControllerSingle.doorRef = numVal;
PlayerController.PlayerControllerSingle.touchingDoor = true;
}
}
/*
public void OnTriggerStay2D(Collider2D node)
{
GameController gameCon = FindObjectOfType<GameController>();
if (node.gameObject.tag == "Door")
{
gameCon.touchingDoor = true;
}
}
*/
public void OnTriggerExit2D(Collider2D node)
{
if (node.gameObject.tag == "Door")
{
PlayerController.PlayerControllerSingle.touchingDoor = false;
}
}
}
<file_sep>/2dProject/Assets/scripts/MainQuest/MainQuest2_0.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MainQuest2_0 : MonoBehaviour {
public bool touchingCharacter { get; set; }
void Start()
{
GameController.GameControllerSingle.sideQuestCounter = 0;
GameController.GameControllerSingle.sideQuestBool = true;
//set quest text in questlog
QuestController.QuestControllerSingle.MainQuestText.text = "Do Side Quest. " + "Main Quest " + QuestController.QuestControllerSingle.currentMainQuest;
}
// Update is called once per frame
void Update ()
{
if (Input.GetKeyDown(KeyCode.Q))
{
Debug.Log("talk to character1 for quest3");
Debug.Log(GameController.GameControllerSingle.sideQuestCounter);
Debug.Log(GameController.GameControllerSingle.sideQuestBool);
if (touchingCharacter && GameController.GameControllerSingle.sideQuestCounter >= 1 && GameController.GameControllerSingle.sideQuestBool == true)
{
GameController.GameControllerSingle.sideQuestBool = false;
//set quest text in questlog
QuestController.QuestControllerSingle.MainQuestText.text = "Talk to CH1. " + "Main Quest " + QuestController.QuestControllerSingle.currentMainQuest;
Debug.Log("Complete, go to main quest 3");
QuestController.QuestControllerSingle.currentMainQuest = 3f;
PlayerController.PlayerControllerSingle.transform.position = transform.position + new Vector3(-6f, 0, 0);
CutSceneLoader.CutSceneLoaderSingle.loadScene("CutScene2");
GameObject.Find("Character1").AddComponent<MainQuest3_0>();
Destroy(this);
}
else if (GameController.GameControllerSingle.sideQuestCounter >= 1 && GameController.GameControllerSingle.sideQuestBool == true)
{
//set quest text in questlog
QuestController.QuestControllerSingle.MainQuestText.text = "Talk to CH1. " + "Main Quest " + QuestController.QuestControllerSingle.currentMainQuest;
}
else
{
Debug.Log("not complete side quest yet, talked to side quest character to complete");
}
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.name == "Character1")
{
touchingCharacter = true;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.name == "Character1")
{
touchingCharacter = false;
}
}
}
<file_sep>/2dProject/Assets/scripts/Items/Weapons/GodHandsFistPlayer.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GodHandsFistPlayer : MonoBehaviour
{
public bool pullAttackOn = false;
public bool returnFist = false;
public bool returnWithPlayer = false;
public bool returnFistPlayer = false;
public bool returnWithEnemy = false;
public bool hitObject = false;
//for user attack, not same as boss
public bool userAttackOn = false;
public Vector3 gotoPosition;
public Transform targetTransform;
public Transform userTransform;
public Rigidbody2D targetRB;
public Vector3 newTargetLocation;
public Transform fistPrefab;
//gets set in GodHands script
public GodHands parent;
//speed of fist
float fistSpeed = 500;
float step;
void Start()
{
//turn attack off
parent.GodhandsCanAttack = false;
}
void FixedUpdate()
{
step = fistSpeed * Time.deltaTime;
if (pullAttackOn)
{
userTransform.position = Vector3.MoveTowards(userTransform.position, newTargetLocation, step);
if (hitObject)
{
pullAttackOn = false;
returnWithPlayer = true;
returnFist = true;
}
else if (Vector3.Distance(userTransform.position, newTargetLocation) <= .1f)
{
pullAttackOn = false;
returnFist = true;
}
}
else if (returnFist)
{
userTransform.position = Vector3.MoveTowards(userTransform.position, PlayerController.PlayerControllerSingle.transform.position, step);
if (returnWithPlayer)
{
targetTransform.position = Vector3.MoveTowards(userTransform.position, PlayerController.PlayerControllerSingle.transform.position, step);
}
if (Vector3.Distance(userTransform.position, PlayerController.PlayerControllerSingle.transform.position) <= .5f)
{
returnFist = false;
//if hit target, knock it up
if (returnWithPlayer)
{
targetRB.AddForce(new Vector2(0, 500));
returnWithPlayer = false;
}
Destroy(gameObject);
}
}
}
void OnTriggerEnter2D(Collider2D other)
{
//if enemey get the RB and move it
if (other.tag == "Enemy")
{
targetRB = other.GetComponent<Rigidbody2D>();
hitObject = true;
targetTransform = other.transform;
}
}
void OnDestroy()
{
//turn attack back on so you can fire godhands again
parent.GodhandsCanAttack = true;
}
//void OnTriggerExit2D(Collider2D other)
//{
// Debug.Log("leaving player");
// hitObject = false;
//}
}
<file_sep>/2dProject/Assets/scripts/EmenyStuff/SliderEnemyAttack.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SliderEnemyAttack : MonoBehaviour {
bool collide = false;
public bool attacking = false;
bool reverseAttack = false;
//for attack collider
BoxCollider2D tipCollider;
SpriteRenderer tipImage;
SliderEnemyMovment MovementScript;
EnemyStats StatScript;
//Bubble parts
SpriteRenderer bubbleImage;
PolygonCollider2D bubbleCollider;
// Use this for initialization
void Start ()
{
//collider parts
tipCollider = transform.parent.Find("Collider").GetComponent<BoxCollider2D>();
tipImage = transform.parent.Find("Collider").GetComponent<SpriteRenderer>();
//for attacking
MovementScript = transform.parent.GetComponent<SliderEnemyMovment>();
//for making invincible
StatScript = transform.parent.GetComponent<EnemyStats>();
//bubble parts
bubbleImage = transform.parent.Find("Bubble").gameObject.GetComponent<SpriteRenderer>();
bubbleCollider = transform.parent.Find("Bubble").gameObject.GetComponent<PolygonCollider2D>();
}
// Update is called once per frame
void Update ()
{
if (!collide && attacking)
{
transform.localPosition += Vector3.up * .2f;
SizeObjects();
}
else if (reverseAttack)
{
if (Vector2.Distance(transform.parent.transform.position, transform.position) <= .4f)
{
//for stopping loop after object attack is close
reverseAttack = false;
transform.position = transform.parent.transform.position;
transform.localPosition += new Vector3(0, .4f, 0);
tipCollider.size = Vector2.one;
tipCollider.transform.position = transform.parent.transform.position;
tipImage.size = Vector2.one;
attacking = false;
MovementScript.attacking = false;
collide = false;
}
else
{
transform.localPosition += Vector3.down * .2f;
SizeObjects();
}
}
}
void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Bullet")
{
//make enemy killable
StatScript.invincible = false;
//reverse direction of attack
reverseAttack = true;
attacking = false;
//bubble parts off
bubbleImage.enabled = false;
bubbleCollider.enabled = false;
}
if (attacking)
{
collide = true;
}
}
void OnTriggerExit2D(Collider2D other)
{
//take out of collide for some action
if (collide)
{
//make enemy killable
StatScript.invincible = false;
//reverse direction of attack
reverseAttack = true;
attacking = false;
//bubble parts off
bubbleImage.enabled = false;
bubbleCollider.enabled = false;
}
//reverseAttack = true;
}
public void StartAttack()
{
//collider parts
tipImage.enabled = true;
tipCollider.enabled = true;
//bubble parts
bubbleImage.enabled = true;
bubbleCollider.enabled = true;
//move slighty forward so it doesn't break if it collides right away (from a 0 distance move)
transform.localPosition += Vector3.up * .4f;
//don't need to get angle when you're object is a child because of local frame of reference
//get angle
//float angle = (Mathf.Abs(transform.parent.transform.position.y - transform.position.y) / Mathf.Abs(transform.parent.transform.position.x - transform.position.x));
//if ((transform.parent.transform.position.y < transform.position.y && transform.parent.transform.position.x > transform.position.x) || (transform.position.y < transform.parent.transform.position.y && transform.position.x > transform.parent.transform.position.x))
//{
// angle *= -1;
//}
//angle = Mathf.Rad2Deg * Mathf.Atan(angle);
//col.transform.Rotate(0, 0, angle);
//starts attack
//so enemy can't die
StatScript.invincible = true;
//set to attacking mode
attacking = true;
}
void SizeObjects()
{
//size and position of attack body
tipCollider.size = new Vector2(1, Vector2.Distance(transform.parent.transform.position, transform.position));
tipCollider.transform.position = (transform.parent.transform.position + transform.position) / 2;
tipImage.size = new Vector2(1, Vector2.Distance(transform.parent.transform.position, transform.position));
}
}
<file_sep>/2dProject/Assets/scripts/MainQuest/MainQuest7_0.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MainQuest7_0 : MonoBehaviour {
public bool touchingCharacter { get; set; }
private Text NPCtext;
private Text Herotext;
private CanvasGroup canvas;
private bool waitforload = true;
private Sprite BossSprite;
// Use this for initialization
void Start ()
{
Debug.Log("BossFight");
NPCtext = DialogManager.DialogManagerSingle.NPCtext;
Herotext = DialogManager.DialogManagerSingle.Herotext;
canvas = DialogManager.DialogManagerSingle.canvas;
//set quest text in questlog
QuestController.QuestControllerSingle.MainQuestText.text = "Fight the boss. " + "Main Quest " + QuestController.QuestControllerSingle.currentMainQuest;
}
// Update is called once per frame
void Update ()
{
if(GameObject.Find("Boss") && waitforload)
{
BossSprite = GameObject.Find("Boss").GetComponent<SpriteRenderer>().sprite;
DialogManager.DialogManagerSingle.TalkingCharacter.sprite = BossSprite;
waitforload = false;
Debug.Log("set boss sprite");
canvas.alpha = 1;
StartCoroutine(Dialog());
}
}
public IEnumerator Dialog()
{
string Conversation1 = DialogManager.DialogManagerSingle.MainQuestDialogueLoadPath + "MainQuest7_0.0";
//freeze player
PlayerController.PlayerControllerSingle.LockPosition();
//start conversavtion 1
StartCoroutine(DialogManager.DialogManagerSingle.Dialog(Conversation1));
//waits for conversation to finish
while ((DialogManager.DialogManagerSingle.dialogOn == true))
{
yield return new WaitForSeconds(0.1f);
}
//wait 1 sec before continuing
yield return new WaitForSeconds(1f);
canvas.alpha = 0;
//let player move again
PlayerController.PlayerControllerSingle.UnLockPosition();
//Text reset
NPCtext.text = "";
Herotext.text = "";
QuestController.QuestControllerSingle.currentMainQuest = 8f;
if (QuestController.QuestControllerSingle.currentMainQuest == 8f)
{
Debug.Log("quest is 8");
Debug.Log(QuestController.QuestControllerSingle.currentMainQuest + " = QuestController.QuestControllerSingle.currentQuest");
GameObject.Find("Hero").AddComponent<MainQuest8_0>();
}
Destroy(this);
}
}
<file_sep>/2dProject/Assets/scripts/Items/ConsumableItem.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ConsumableItem : Item {
public override void Use()
{
switch (type)
{
case ItemType.HEALTH:
if (PlayerStats.PlayerStatsSingle.health <= PlayerStats.PlayerStatsSingle.maxHealth)
{
PlayerStats.PlayerStatsSingle.ChangeHealth(1);
Debug.Log("Health potion was used");
}
else
{
Debug.Log("Full health, fuking idiot, die potion");
}
break;
default:
break;
}
}
}
<file_sep>/2dProject/Assets/scripts/Items/EquiptItem.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EquiptItem : Item {
//higher and lower bounds for armor
public int armorL;
public int armorH;
public int armor;
//higher and lower bounds for dexterity
public int dexterityL;
public int dexterityH;
public int dexterity;
//higher and lower bounds for intelligence
public int intelligenceL;
public int intelligenceH;
public int intelligence;
//higher and lower bounds for strength
public int strengthL;
public int strengthH;
public int strength;
//higher and lower bounds for vitality
public int vitalityL;
public int vitalityH;
public int vitality;
//for melee skills
public bool meleeWeapon;
void Start()
{
//great little line for getting a random enum
switch ((Quality)Random.Range(0, System.Enum.GetValues(typeof(Quality)).Length))
{
case Quality.COMMON:
quality = Quality.COMMON;
break;
case Quality.UNCOMMON:
quality = Quality.UNCOMMON;
break;
case Quality.RARE:
quality = Quality.RARE;
break;
case Quality.EPIC:
quality = Quality.EPIC;
break;
case Quality.LEGENDARY:
quality = Quality.LEGENDARY;
break;
case Quality.ARTIFACT:
quality = Quality.ARTIFACT;
break;
default:
break;
}
itemName = gameObject.name;
armor = Random.Range(armorL, armorH) + 2 * (int)quality;
dexterity = Random.Range(dexterityL, dexterityH) + 2 * (int)quality;
intelligence = Random.Range(intelligenceL, intelligenceH) + 2 * (int)quality;
strength = Random.Range(strengthL, strengthH) + 2 * (int)quality;
vitality = Random.Range(vitalityL, vitalityH) + 2 * (int)quality;
}
public override void Use()
{
PlayerStats.PlayerStatsSingle.UpdateStatText(armor, dexterity, intelligence, strength, vitality);
switch (type)
{
case ItemType.WEAPON:
Inventory.InventorySingle.SelectWeapon(itemName);
if (meleeWeapon)
{
PlayerController.PlayerControllerSingle.meleeEquipt = meleeWeapon;
}
break;
case ItemType.HELM:
break;
case ItemType.CHEST:
break;
case ItemType.BELT:
break;
case ItemType.GLOVES:
break;
case ItemType.BOOTS:
break;
case ItemType.RING:
break;
case ItemType.AMULET:
break;
default:
break;
}
}
public override void UnEquipt()
{
//check for unequipt weapon
if (type == ItemType.WEAPON)
{
Inventory.InventorySingle.UnequiptWeapon(itemName);
//for player melee skills
if (meleeWeapon)
{
PlayerController.PlayerControllerSingle.meleeEquipt = false;
}
}
PlayerStats.PlayerStatsSingle.UpdateStatText(-armor, -dexterity, -intelligence, -strength, -vitality);
}
public override string GetToolTip()
{
string stats = string.Empty;
string color = string.Empty;
string newLine = string.Empty;
if (description != string.Empty)
{
newLine = "\n";
}
switch (quality)
{
case Quality.COMMON:
color = "red";
break;
case Quality.UNCOMMON:
color = "orange";
break;
case Quality.RARE:
color = "yellow";
break;
case Quality.EPIC:
color = "green";
break;
case Quality.LEGENDARY:
color = "blue";
break;
case Quality.ARTIFACT:
color = "purple";
break;
default:
break;
}
if (armor > 0)
{
stats += "\n" + armor.ToString() + " Armor";
}
if (dexterity > 0)
{
stats += "\n" + dexterity.ToString() + " Dexterity";
}
if (intelligence > 0)
{
stats += "\n" + intelligence.ToString() + " Intelligence";
}
if (strength > 0)
{
stats += "\n" + strength.ToString() + " Damage";
}
if (vitality > 0)
{
stats += "\n" + vitality.ToString() + " Vitality";
}
return string.Format("<color=" + color + "><size=16>{0} {1}</size></color><size=14><i><color=lime>" + newLine + "{2}</color></i>{3}</size>", quality, itemName, description, stats);
}
}
<file_sep>/2dProject/Assets/scripts/WorldObjects.cs
using UnityEngine;
public class WorldObjects : MonoBehaviour
{
public static WorldObjects WorldObjectsSingle;
void Awake()
{
if (WorldObjectsSingle == null)
{
DontDestroyOnLoad(gameObject);
WorldObjectsSingle = this;
}
else if (WorldObjectsSingle != this)
{
Destroy(gameObject);
}
}
}
<file_sep>/2dProject/Assets/scripts/PlayerScripts/DrawPlayerMap.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.IO;
public class DrawPlayerMap : MonoBehaviour {
public MeshFilter playerLocalMap;
public GameObject playerWorldMap;
//for drawing doors on map
public Transform doorPrefab;
public Transform tempMap;
//private Vector3 offset;
//map bools
private bool localMapOn = false;
private bool worldMapOn = false;
//for camra
public Camera localMapCam;
//if change room bool
//public bool touchingDoor { get; set; }
//for map marker
GameObject MapMarkerTeemo;
SpriteRenderer MapMarkerTeemoSprite;
Transform MapMarkerTeemoPos;
public List<Vector3> MapPos;
public List<Vector3> MapPosWorldMaps;
private int mapSeed;
private int totalMaps;
//for drawing door connections
//private List<List<Vector2>> doorLocations;
public Transform mapLine;
public string currentMap { get; set; }
public string nextMap { get; set; }
public int currentDoor { get; set; }
public int nextDoor { get; set; }
//private List<Vector3> LinePos;
//for line color
Color firstColor;
Color secondColor;
//for drawing doors
private bool drawDoors = false;
//for door map
private bool firstRun = false;
//for leading lines
private string currentMapSet = "";
private int currentMapSetIndex = 0;
//for keeping worldmap locked on player
GameObject currentWorldMap;
//local map offset
Vector3 OffSet;
Vector3 temp;
public static DrawPlayerMap DrawPlayerMapSingle;
void Awake()
{
if (DrawPlayerMapSingle == null)
{
DrawPlayerMapSingle = this;
}
else if (DrawPlayerMapSingle != this)
{
Destroy(gameObject);
}
}
void Start()
{
//for drawing map
totalMaps = GameData.GameDataSingle.mapSeed.Count;
//map opacity
transform.GetComponent<MeshRenderer>().material.color = new Vector4(1, 1, 1, .5f);
// this is for teemo marker and lines
MapPos = new List<Vector3>();
for (int x = 0; x < totalMaps; x++)
{
MapPos.Add(new Vector2(Mathf.Cos(2 * Mathf.PI * x / totalMaps), Mathf.Sin(2 * Mathf.PI * x / totalMaps)));
}
//for correct position on small world maps
MapPosWorldMaps = new List<Vector3>();
foreach (Vector2 mapSet in GameData.GameDataSingle.mapSets)
{
for (int x = 0; x < (int)mapSet.x; x++)
{
MapPosWorldMaps.Add(new Vector2(Mathf.Cos(2 * Mathf.PI * x / (int)mapSet.x), Mathf.Sin(2 * Mathf.PI * x / (int)mapSet.x)));
}
}
//for teemo mapmarker
MapMarkerTeemo = GameObject.Find("MapMarker");
MapMarkerTeemoSprite = MapMarkerTeemo.GetComponent<SpriteRenderer>();
MapMarkerTeemoPos = MapMarkerTeemo.GetComponent<Transform>();
//for line between doors map marker
//LinePos = MapGenerator.MapGeneratorSingle.LinePos;
//for making world map
//DrawWorldMap();
//removes all the children of map object
foreach (Transform child in transform)
{
//currently does nothngn beacuse map marker is not a child
if (child.name != "MapMarker")
{
GameObject.Destroy(child.gameObject);
}
}
}
// Update is called once per frame
void Update () {
// local map
if (Input.GetKeyDown(KeyCode.M))
{
//turn off worldmap if on
if (worldMapOn)
{
foreach (Transform child in transform.parent.Find("WorldMaps"))
{
child.gameObject.SetActive(false);
}
}
if (localMapOn)
{
//turn map doors off
var oldMapDoors = GameObject.FindGameObjectsWithTag("MapDoor");
foreach (var door in oldMapDoors)
{
door.GetComponent<SpriteRenderer>().enabled = false;
}
//turn off teemo marker
MapMarkerTeemoSprite.enabled = false;
//turn map off and erase it
localMapOn = false;
playerLocalMap.mesh = null;
localMapCam.enabled = false;
}
else
{
localMapCam.enabled = true;
//turn off teemo marker
MapMarkerTeemoSprite.enabled = false;
//turn off teemo marker
//MapMarkerTeemoSprite.enabled = true;
//turn map on and draw it
worldMapOn = false;
localMapOn = true;
//DrawLocalMap();
//turn map doors on
var oldMapDoors = GameObject.FindGameObjectsWithTag("MapDoor");
foreach (var door in oldMapDoors)
{
door.GetComponent<SpriteRenderer>().enabled = true;
}
//turn off world map lines
foreach (Transform child in GameObject.Find("MapDoorLines").transform)
{
child.GetComponent<LineRenderer>().enabled = false;
}
}
}
if (localMapOn)
{
localMapCam.orthographicSize -= Input.mouseScrollDelta.y;
if (Input.GetMouseButtonDown(0))
{
OffSet = temp + Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
else if (Input.GetMouseButton(0))
{
temp = OffSet - Camera.main.ScreenToWorldPoint(Input.mousePosition);
localMapCam.gameObject.transform.position = new Vector3(temp.x, temp.y, -20);
}
////keep map locked on character
//MapMarkerTeemoPos.position = PlayerController.PlayerControllerSingle.transform.position + (PlayerController.PlayerControllerSingle.transform.position * .175f);
////keep map locked on character
//UpdatePosition();
}
//world map
if (Input.GetKeyDown(KeyCode.N))
{
localMapCam.enabled = false;
if (worldMapOn)
{
//turn off teemo marker
MapMarkerTeemoSprite.enabled = false;
//turn map off and erase it
worldMapOn = false;
//turn off lines
foreach (Transform child in GameObject.Find("MapDoorLines").transform)
{
child.GetComponent<LineRenderer>().enabled = false;
}
//turn off
if (transform.parent.Find("WorldMaps").GetComponent<Transform>())
{
currentWorldMap.SetActive(false);
}
}
else
{
//turn map doors off
var oldMapDoors = GameObject.FindGameObjectsWithTag("MapDoor");
foreach (var door in oldMapDoors)
{
door.GetComponent<SpriteRenderer>().enabled = false;
}
LoadCorrectDoorLines(currentMap);
//TURN ON TEEMO MARKER
MapMarkerTeemoSprite.enabled = true;
//turn map on and draw it
worldMapOn = true;
playerLocalMap.mesh = null;
localMapOn = false;
LoadWorldMap();
}
}
if (worldMapOn)
{
//keep map locked on character
if (currentMapSetIndex < GameData.GameDataSingle.mapSets.Count)
{
MapMarkerTeemoPos.position = PlayerController.PlayerControllerSingle.transform.position + GetCurrentMapLocation(currentMap) + (PlayerController.PlayerControllerSingle.transform.position * .075f);
}
else
{
MapMarkerTeemoPos.position = PlayerController.PlayerControllerSingle.transform.position + (PlayerController.PlayerControllerSingle.transform.position * .075f);
}
//update door lines pos
int x = 0;
foreach (Transform child in GameObject.Find("MapDoorLines").transform)
{
//can ig et the current line 0 position? i want that to currrent plus player pos
child.GetComponent<LineRenderer>().SetPosition(0, PlayerController.PlayerControllerSingle.transform.position + MapGenerator.MapGeneratorSingle.LinePos[x * 2]);
child.GetComponent<LineRenderer>().SetPosition(1, PlayerController.PlayerControllerSingle.transform.position + MapGenerator.MapGeneratorSingle.LinePos[x * 2 + 1]);
x++;
}
//update map pos
UpdatePosition();
}
}
public void UpdateMap()
{
if (localMapOn)
{
//drawDoors = false;
//DrawLocalMap();
}
else if (worldMapOn)
{
//for door maps
transform.localScale = new Vector3(.175f, .175f, .175f);
transform.position = PlayerController.PlayerControllerSingle.transform.position;
drawDoors = false;
DrawDoorsLocalMap(nextMap);
var oldMapDoors = GameObject.FindGameObjectsWithTag("MapDoor");
foreach (var door in oldMapDoors)
{
door.GetComponent<SpriteRenderer>().enabled = false;
}
transform.localScale = new Vector3(.075f, .075f, .075f);
//for door lines
LoadCorrectDoorLines(nextMap);
LoadWorldMap();
}
else if (!localMapOn && !worldMapOn)
{
//for door maps
transform.localScale = new Vector3(.175f, .175f, .175f);
transform.position = PlayerController.PlayerControllerSingle.transform.position;
drawDoors = false;
DrawDoorsLocalMap(nextMap);
var oldMapDoors = GameObject.FindGameObjectsWithTag("MapDoor");
foreach (var door in oldMapDoors)
{
door.GetComponent<SpriteRenderer>().enabled = false;
}
transform.localScale = new Vector3(.075f, .075f, .075f);
}
}
void CreateLines(string seed1, string seed2, int door1, int door2, int set1, int set2)
{
Vector3 linePos1;
Vector3 linePos2;
// check if already a line is there.
if (set1 == set2)
{
foreach (Transform child in GameObject.Find("MapDoorLines").transform)
{
if (child.name == (seed1.ToString() + door1.ToString() + seed2.ToString() + door2.ToString() + "," + set1 + "," + set2)
|| child.name == (seed2.ToString() + door2.ToString() + seed1.ToString() + door1.ToString() + "," + set2 + "," + set1))
{
return;
}
}
linePos1 = GetCurrentMapLocation(seed1) + new Vector3(MapGenerator.MapGeneratorSingle.MapInfo[seed1].doorLocationsX[door1] * .075f, MapGenerator.MapGeneratorSingle.MapInfo[seed1].doorLocationsY[door1] * .075f, 0);
linePos2 = GetCurrentMapLocation(seed2) + new Vector3(MapGenerator.MapGeneratorSingle.MapInfo[seed2].doorLocationsX[door2] * .075f, MapGenerator.MapGeneratorSingle.MapInfo[seed2].doorLocationsY[door2] * .075f, 0);
}
else
{
linePos1 = Vector3.zero;
linePos2 = Vector3.zero;
}
//save line position
//save pos for moving with player
MapGenerator.MapGeneratorSingle.LinePos.Add(linePos1);
MapGenerator.MapGeneratorSingle.LinePos.Add(linePos2);
//Instantiate line
var tempMapLine = Instantiate(mapLine) as Transform;
tempMapLine.SetParent(GameObject.Find("MapDoorLines").transform);
//tempMapLine.GetComponent<LineRenderer>().SetWidth(.1f, .1f); old version now outdated
tempMapLine.GetComponent<LineRenderer>().startWidth = .1f;
tempMapLine.GetComponent<LineRenderer>().endWidth = .1f;
tempMapLine.GetComponent<LineRenderer>().SetPosition(0, PlayerController.PlayerControllerSingle.transform.position + linePos1);
tempMapLine.GetComponent<LineRenderer>().SetPosition(1, PlayerController.PlayerControllerSingle.transform.position + linePos2);
tempMapLine.name = seed1.ToString() + door1.ToString() + seed2.ToString() + door2.ToString() + "," + set1 + "," + set2;
if (!worldMapOn)
{
tempMapLine.GetComponent<LineRenderer>().enabled = false;
}
//for color; try to enum the colors for each map i.e. map 0 is red, map 1 is blue ...
firstColor = PickLineColor(GameData.GameDataSingle.FindMapIndex(seed1));
secondColor = PickLineColor(GameData.GameDataSingle.FindMapIndex(seed2));
//load material for line
tempMapLine.GetComponent<LineRenderer>().material = Resources.Load("LineMat", typeof(Material)) as Material;
tempMapLine.GetComponent<LineRenderer>().startColor = firstColor;
tempMapLine.GetComponent<LineRenderer>().endColor = secondColor;
}
void CreateLinesNotInSet(string seed1, string seed2, int door1, int door2, int set1, int set2)
{
Vector3 linePos1;
Vector3 linePos2;
if(set1 < GameData.GameDataSingle.mapSets.Count)
{
linePos1 = GetCurrentMapLocation(seed1) + new Vector3(MapGenerator.MapGeneratorSingle.MapInfo[seed1].doorLocationsX[door1] * .075f, MapGenerator.MapGeneratorSingle.MapInfo[seed1].doorLocationsY[door1] * .075f, 0);
linePos2 = GetCurrentMapLocation(seed1)*2;
}
else
{
linePos1 = new Vector3(MapGenerator.MapGeneratorSingle.MapInfo[seed1].doorLocationsX[door1] * .075f, MapGenerator.MapGeneratorSingle.MapInfo[seed1].doorLocationsY[door1] * .075f, 0);
linePos2 = new Vector3(0, -10f, 0);
}
//save line position
//save pos for moving with player
MapGenerator.MapGeneratorSingle.LinePos.Add(linePos1);
MapGenerator.MapGeneratorSingle.LinePos.Add(linePos2);
//Instantiate line
var tempMapLine = Instantiate(mapLine) as Transform;
tempMapLine.SetParent(GameObject.Find("MapDoorLines").transform);
//tempMapLine.GetComponent<LineRenderer>().SetWidth(.1f, .1f); old version now outdated
tempMapLine.GetComponent<LineRenderer>().startWidth = .1f;
tempMapLine.GetComponent<LineRenderer>().endWidth = .1f;
tempMapLine.GetComponent<LineRenderer>().SetPosition(0, PlayerController.PlayerControllerSingle.transform.position + linePos1);
tempMapLine.GetComponent<LineRenderer>().SetPosition(1, PlayerController.PlayerControllerSingle.transform.position + linePos2);
tempMapLine.name = seed1.ToString() + door1.ToString() + seed2.ToString() + door2.ToString() + "," + set1 + "," + set2;
if (!worldMapOn)
{
tempMapLine.GetComponent<LineRenderer>().enabled = false;
}
//for color; try to enum the colors for each map i.e. map 0 is red, map 1 is blue ...
firstColor = PickLineColor(GameData.GameDataSingle.FindMapIndex(seed1));
secondColor = PickLineColor(GameData.GameDataSingle.FindMapIndex(seed2));
tempMapLine.GetComponent<LineRenderer>().material = new Material(Shader.Find("Particles/Additive"));
//tempMapLine.GetComponent<LineRenderer>().SetColors(firstColor, secondColor); old version, now outdated
tempMapLine.GetComponent<LineRenderer>().startColor = firstColor;
tempMapLine.GetComponent<LineRenderer>().endColor = secondColor;
}
//for picking map line colors
Color PickLineColor(int mapNum)
{
if (mapNum == 0)
{
return Color.red;
}
else if(mapNum == 1)
{
return Color.yellow;
}
else if (mapNum == 2)
{
return Color.green;
}
else if (mapNum == 3)
{
return Color.blue;
}
else if (mapNum == 4)
{
return Color.cyan;
}
else if (mapNum == 5)
{
return Color.gray;
}
return Color.white;
}
//for the world map; gets shift of x and y; used for setting map marker line pos
Vector3 GetCurrentMapLocation(string pickMap)
{
return new Vector3(MapGenerator.MapGeneratorSingle.MapPosWorldMaps[GameData.GameDataSingle.FindMapIndex(pickMap)].x * .075f * 150, MapGenerator.MapGeneratorSingle.MapPosWorldMaps[GameData.GameDataSingle.FindMapIndex(pickMap)].y * .075f * 100, 0);
}
void DrawDoorsLocalMap(string curMap)
{
if (drawDoors == false)
{
var oldMapDoors = GameObject.FindGameObjectsWithTag("MapDoor");
//this is for removing the old doors
foreach (var door in oldMapDoors)
{
Destroy(door);
}
drawDoors = true;
//foreach (Vector3 door in mapGen.MapInfo[curMap].doorLocations)
for(int tempCounter = 0; tempCounter < MapGenerator.MapGeneratorSingle.MapInfo[curMap].doorLocationsX.Count; tempCounter++)
{
var doorTransform = Instantiate(doorPrefab);
doorTransform.transform.SetParent(transform);
doorTransform.position = PlayerController.PlayerControllerSingle.transform.position + new Vector3(MapGenerator.MapGeneratorSingle.MapInfo[curMap].doorLocationsX[tempCounter] * .175f,
MapGenerator.MapGeneratorSingle.MapInfo[curMap].doorLocationsY[tempCounter] * .175f, 0);
doorTransform.localScale = new Vector3(.7f, .7f, .7f);
}
}
}
void PutObjectOnLocalMap(GameObject MapObject, List<Vector2> listOfMapObjects, Transform PrefabObject)
{
string newTag = "Map" + MapObject.tag;
var oldMapObject = GameObject.FindGameObjectsWithTag(newTag);
//this is for removing the old map objects
foreach (var single in oldMapObject)
{
Destroy(single);
}
//adds objects to map
drawDoors = true;
foreach (Vector3 single in listOfMapObjects)
{
var objectTransform = Instantiate(PrefabObject);
objectTransform.transform.SetParent(transform);
objectTransform.position = PlayerController.PlayerControllerSingle.transform.position + new Vector3(single.x * .175f, single.y * .175f, 0);
objectTransform.localScale = new Vector3(.7f, .7f, .7f);
}
}
void DrawLocalMap()
{
//MapGenerator mapGen = FindObjectOfType<MapGenerator>();
//use this to get all maps
string mapSeed = MapGenerator.MapGeneratorSingle.seed;
//load map in
//var loadPath = "Assets/CurrentMaps/" + mapSeed + ".asset";
//Mesh mesh = (Mesh)AssetDatabase.LoadAssetAtPath(loadPath, typeof(Mesh));
playerLocalMap.mesh = MapGenerator.MapGeneratorSingle.GetComponentInChildren<MeshFilter>().mesh;
//scale size down and set position
transform.localScale = new Vector3(.175f, .175f, .175f);
transform.position = PlayerController.PlayerControllerSingle.transform.position;
transform.eulerAngles = new Vector3(270, 0, 0);
//for mapdoors
if (firstRun)
{
DrawDoorsLocalMap(nextMap);
}
else
{
firstRun = true;
DrawDoorsLocalMap(currentMap);
}
}
void UpdatePosition()
{
if (localMapOn)
{
transform.position = PlayerController.PlayerControllerSingle.transform.position;
}
else
{
currentWorldMap.transform.position = PlayerController.PlayerControllerSingle.transform.position;
}
}
public void CreateWorldMap()
{
MeshFilter[] meshFilters = new MeshFilter[GameData.GameDataSingle.mapSeed.Count];
//create prefabs for all maps then add them to a list of filters, then remove all prefabs later
for (int x = 0; x < GameData.GameDataSingle.mapSeed.Count; x++)
{
string mapSeed = GameData.GameDataSingle.mapSeed[x];
//get cave name
string caveName = "Cave" + mapSeed;
//Debug.Log("Cave + mapSeed = " + caveName);
Mesh mesh = GameObject.Find(caveName).GetComponent<MeshFilter>().mesh;
mesh.name = caveName;
// create prefab
var tempMapPrefab = Instantiate(tempMap) as Transform;
tempMapPrefab.transform.SetParent(transform);
tempMapPrefab.name = mapSeed;
tempMapPrefab.GetComponent<MeshFilter>().mesh = mesh;
meshFilters[x] = tempMapPrefab.GetComponent<MeshFilter>();
}
int currentSetMaps = 0;
string worldMapName;
foreach (Vector2 mapSet in GameData.GameDataSingle.mapSets)
{
//(int)num.y, (int)num.x + (int)num.y - 1;
CombineInstance[] combineTest = new CombineInstance[(int)mapSet.x];
for (int x = 0; x < (int)mapSet.x; x++)
{
// (int)mapSet.x so start on correct map
combineTest[x].mesh = meshFilters[x + (int)mapSet.y].sharedMesh;
//draw maps in a polygon shape based on how many there are
//numbers are map dimentions Ex: 150 in x and 100 in y;
combineTest[x].transform = Matrix4x4.TRS(new Vector3(Mathf.Cos(2 * Mathf.PI * x / (int)mapSet.x) * 150, 0, Mathf.Sin(2 * Mathf.PI * x / (int)mapSet.x) * 100), Quaternion.identity, new Vector3(1, 1, 1));
}
//create a worldmap object for this set of maps
GameObject tempWorldMap = Instantiate(playerWorldMap, transform.parent.Find("WorldMaps").transform);
tempWorldMap.name = "WorldMap" + currentSetMaps;
tempWorldMap.GetComponent<MeshFilter>().mesh.CombineMeshes(combineTest);
//set scale
tempWorldMap.transform.localScale = new Vector3(.075f, .075f, .075f);
worldMapName = "WorldMap" + currentSetMaps;
MapGenerator.MapGeneratorSingle.WorlMapDictionary.Add(worldMapName, tempWorldMap.transform);
//turn off world map until needed
tempWorldMap.SetActive(false);
currentSetMaps += 1;
}
//Destroy(MapGenerator.MapGeneratorSingle.gameObject);
CreateDoorConnections();
}
void LoadWorldMap()
{
string worldMap = "WorldMap";
int currentSetMaps = 0;
string mapSeed = MapGenerator.MapGeneratorSingle.seed;
MapInformation newData = MapGenerator.MapGeneratorSingle.MapInfo[mapSeed];
currentSetMaps = newData.mapSet;
if (currentSetMaps < GameData.GameDataSingle.mapSets.Count)
{
worldMap = "WorldMap" + currentSetMaps;
//Debug.Log("worldMap1 = " + worldMap);
}
else
{
worldMap = mapSeed;
//Debug.Log("worldMap2 = " + worldMap);
}
//bad try at active world map
foreach (Transform child in transform.parent.Find("WorldMaps"))
{
child.gameObject.SetActive(false);
}
//turn on correct world map
currentWorldMap = MapGenerator.MapGeneratorSingle.WorlMapDictionary[worldMap].gameObject;
currentWorldMap.SetActive(true);
}
void CreateDoorConnections()
{
//get reference of door dic
Dictionary<string, string> tempDoorConnectionDictionary = new Dictionary<string, string>(GameData.GameDataSingle.doorConnectionDictionary);
//for breaking door dic into maps and doors
string[] values;
string oldSeed;
string oldDoor;
string oldDicRef;
string newSeed;
string newDoor;
string newDicRef;
int oldCurrentSetMaps = 0;
int newCurrentSetMaps = 0;
foreach (KeyValuePair<string, string> entry in tempDoorConnectionDictionary)
{
//for first map and door
values = entry.Value.Split(',');
oldDicRef = entry.Value;
oldSeed = values[0];
oldDoor = values[1];
values = entry.Key.Split(',');
//check if it's a boss room
if (oldSeed != "BossKey1")
{
MapInformation oldData = MapGenerator.MapGeneratorSingle.MapInfo[oldSeed];
oldCurrentSetMaps = oldData.mapSet;
values = tempDoorConnectionDictionary[oldDicRef].Split(',');
newDicRef = tempDoorConnectionDictionary[oldDicRef];
newSeed = values[0];
newDoor = values[1];
//Debug.Log("newDicRef = " + newDicRef + " newSeed = " + newSeed + " newDoor = " + newDoor);
MapInformation newData = MapGenerator.MapGeneratorSingle.MapInfo[newSeed];
newCurrentSetMaps = newData.mapSet;
//need fix for the special add maps
if (oldCurrentSetMaps < GameData.GameDataSingle.mapSets.Count && newCurrentSetMaps < GameData.GameDataSingle.mapSets.Count && oldCurrentSetMaps == newCurrentSetMaps)
{
CreateLines(oldSeed, newSeed, Int32.Parse(oldDoor), Int32.Parse(newDoor), oldCurrentSetMaps, newCurrentSetMaps);
}
else
{
CreateLinesNotInSet(oldSeed, newSeed, Int32.Parse(oldDoor), Int32.Parse(newDoor), oldCurrentSetMaps, newCurrentSetMaps);
}
}
else
{
values = entry.Key.Split(',');
newDicRef = entry.Value;
newSeed = values[0];
newDoor = values[1];
MapInformation newData = MapGenerator.MapGeneratorSingle.MapInfo[newSeed];
newCurrentSetMaps = newData.mapSet;
//Debug.Log("oldDicRef = " + oldDicRef + " oldSeed = " + oldSeed + " oldDoor = " + oldDoor + " oldCurrentSetMaps = " + oldCurrentSetMaps);
//Debug.Log("newDicRef = " + newDicRef + " newSeed = " + newSeed + " newDoor = " + newDoor + " newCurrentSetMaps = " + newCurrentSetMaps);
//boss rooms load new seed first not old seed
CreateLinesNotInSet(newSeed, oldSeed, Int32.Parse(newDoor), Int32.Parse(newDoor), newCurrentSetMaps, newCurrentSetMaps);
}
}
}
void LoadCorrectDoorLines(string map)
{
MapInformation oldData = MapGenerator.MapGeneratorSingle.MapInfo[map];
currentMapSet = oldData.mapSet.ToString();
currentMapSetIndex = oldData.mapSet;
string[] values;
string set1;
//string set2;
foreach (Transform child in GameObject.Find("MapDoorLines").transform)
{
values = child.name.Split(',');
set1 = values[1];
//set2 = values[2];
if (set1 == currentMapSet)
{
child.GetComponent<LineRenderer>().enabled = true;
}
else
{
child.GetComponent<LineRenderer>().enabled = false;
}
}
}
}
<file_sep>/2dProject/Assets/scripts/EmenyStuff/ProjectileAttacks/ProjectileAttackSplitTowardsPlayer.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ProjectileAttackSplitTowardsPlayer : MonoBehaviour {
//split time
private float splitCoolDown = 2f;
//number of times to split
public int splitNumber = 0;
//object speed
float speed = 6f;
public Transform fireBallPrefab;
void Start()
{
//Last for 3 seconds
Destroy(gameObject, 3.0f);
ProjectileMovement();
}
void Update()
{
//Move projectile towards forward
transform.position += transform.right * speed * Time.deltaTime;
if (splitNumber > 0)
{
//if want split before destory
if (splitCoolDown > 0.0f)
{
splitCoolDown -= Time.deltaTime;
}
else
{
splitCoolDown = 2f;
var fireball = Instantiate(fireBallPrefab, transform.parent.transform);
fireball.position = transform.position;
fireball.name = "Fireball";
var temp = fireball.gameObject.AddComponent<ProjectileAttackSplitTowardsPlayer>();
temp.fireBallPrefab = fireBallPrefab;
temp.splitNumber = splitNumber - 1;
}
}
}
void ProjectileMovement()
{
var dir = PlayerController.PlayerControllerSingle.transform.position - transform.position;
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
void OnTriggerEnter2D(Collider2D otherCollider)
{
Destroy(gameObject);
}
}
<file_sep>/2dProject/Assets/scripts/GameInformation/InventorySystem/desktop.ini
[LocalizedFileNames]
Inventory.cs=@Inventory.cs,0
<file_sep>/2dProject/Assets/scripts/MapCreation/MapGenerator.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
public class MapGenerator : MonoBehaviour
{
//map size
//needs to be changed to private
public int width;
public int height;
//fill seeds
public string seed { get; set; }
//fill range
[Range(0, 100)]
public int randomFillPercent;
//size of passageway between rooms
[Range(0, 4)]
public int passageLength;
//pick how smooth to make ground
[Range(0, 10)]
public int smoothness;
int[,] map;
int[,] borderedMap;
public int numMaps { get; set; }
private int currentMap = 0;
//
public List<Vector2> possibleDoorLocations;
public List<Vector2> doorLocations;
public List<Vector2> enemyLocations;
public List<Vector2> turretLocations;
MeshGenerator meshGen;
MapAddOns MapAddOns;
public Dictionary<string, MapInformation> MapInfo = new Dictionary<string, MapInformation>();
public static MapGenerator MapGeneratorSingle;
//for drawplayermap
public List<Vector3> MapPosWorldMaps;
public List<Vector3> LinePos;
public Dictionary<string, Transform> WorlMapDictionary = new Dictionary<string, Transform>();
void Awake()
{
if (MapGeneratorSingle == null)
{
//DontDestroyOnLoad(gameObject);
MapGeneratorSingle = this;
}
else if (MapGeneratorSingle != this)
{
Destroy(gameObject);
}
}
//where program stars
void Start()
{
if (GameController.GameControllerSingle.dontLoadTheGame)
{
meshGen = GetComponent<MeshGenerator>();
MapAddOns = GetComponent<MapAddOns>();
numMaps = 6;
int startMap = 0;
int y = numMaps;
List<Vector2> mapSets = new List<Vector2>();
UnityEngine.Random.InitState((int)System.DateTime.Now.Ticks);
while (y > 0)
{
//make size 2 or 3
int ranSizeSetMaps = UnityEngine.Random.Range(2, 4);
if (y >= ranSizeSetMaps)
{
//Debug.Log("ranSizeSetMaps = " + ranSizeSetMaps + "startMap = " + startMap);
mapSets.Add(new Vector2(ranSizeSetMaps, numMaps - y));
y -= ranSizeSetMaps;
startMap += y;
}
else
{
//Debug.Log("new Vector2(mapSets[mapSets.Count - 1].x + x = " + (mapSets[mapSets.Count - 1].x + x) + " mapSets[mapSets.Count - 1].y) = " + mapSets[mapSets.Count - 1].y);
mapSets[mapSets.Count - 1] = new Vector2(mapSets[mapSets.Count - 1].x + y, mapSets[mapSets.Count - 1].y);
break;
}
}
GameData.GameDataSingle.mapSets = mapSets;
int x = 0;
for (x = 0; x < numMaps; x++)
{
//not in random mode
width = UnityEngine.Random.Range(50, 150);
//off by .5 when placing objects on odd maps
if (width % 2 == 1)
{
width += 1;
}
height = UnityEngine.Random.Range(50, 150);
//off by .5 when placing objects on odd maps
if (height % 2 == 1)
{
height += 1;
}
//randomFillPercent = UnityEngine.Random.Range(30, 50);
//seed = UnityEngine.Random.Range(0, 10000).ToString();
seed = currentMap.ToString();
GenerateMap();
currentMap += 1;
}
//custom room generation stuff -> for temp boss room currently
//width = 50; height = 100;
//randomFillPercent = 0;
//seed = currentMap.ToString();
//bossRooms.Add(seed);
////Debug.Log("seed boos room = " + seed);
//GameData.GameDataSingle.isBossRoomOpen.Add(seed, false);
//GenerateMap();
//currentMap += 1;
foreach (Vector2 num in GameData.GameDataSingle.mapSets)
{
//use: start map, end map, num doors; \n map1 seed, map2 seed
GameData.GameDataSingle.CreatDoorConnections((int)num.y, (int)num.x + (int)num.y - 1, 2);
GameData.GameDataSingle.EnsureConnectivityOfMaps((int)num.y, (int)num.x + (int)num.y - 1);
GameData.GameDataSingle.ConnectDoors();
}
//currently not in random mode
//add boss door; usage -> give mapinfo of a map
//might need to change usage to give it the map seed.
GameData.GameDataSingle.AddUniqueDoorToMap(MapInfo["1"]);
//to set to random mode
//GameData.GameDataSingle.AddUniqueDoorToMap(MapInfo[GameData.GameDataSingle.mapSeed[UnityEngine.Random.Range(0, GameData.GameDataSingle.mapSeed.Count)]]);
////////
foreach (Vector2 num in GameData.GameDataSingle.mapSets)
{
if (GameData.GameDataSingle.mapSets[GameData.GameDataSingle.mapSets.Count - 1] == num)
{
break;
}
GameData.GameDataSingle.ConnectSetOfRooms((int)num.y, (int)num.x + (int)num.y);
}
//connect room with index 6 ->for boss room that is apart of procedural generation
//GameData.GameDataSingle.CreatDoorConnections(6, 6, 0);
//GameData.GameDataSingle.ConnectSetOfRooms(1, 6);
for (x = 0; x < numMaps; x++)
{
//map size
map = new int[MapInfo[GameData.GameDataSingle.mapSeed[x]].width, MapInfo[GameData.GameDataSingle.mapSeed[x]].height];
//enemy locations
enemyLocations = new List<Vector2>();
enemyLocations = MapAddOns.GenerateEnemySpawnLocation(MapInfo[GameData.GameDataSingle.mapSeed[x]]);
//turret Locations
turretLocations = new List<Vector2>();
turretLocations = MapAddOns.GenerateTurretSpawnLocation(MapInfo[GameData.GameDataSingle.mapSeed[x]]);
//for enemy locations
//for storing data in not unity vectors
List<float> tempHolderX = new List<float>();
List<float> tempHolderY = new List<float>();
foreach (Vector2 XYCoord in enemyLocations)
{
tempHolderX.Add(XYCoord.x);
tempHolderY.Add(XYCoord.y);
}
MapInfo[GameData.GameDataSingle.mapSeed[x]].enemyLocationsX = tempHolderX;
MapInfo[GameData.GameDataSingle.mapSeed[x]].enemyLocationsY = tempHolderY;
//for turret locations
//for storing data in not unity vectors
tempHolderX = new List<float>();
tempHolderY = new List<float>();
foreach (Vector2 XYCoord in turretLocations)
{
tempHolderX.Add(XYCoord.x);
tempHolderY.Add(XYCoord.y);
}
MapInfo[GameData.GameDataSingle.mapSeed[x]].turretLocationsX = tempHolderX;
MapInfo[GameData.GameDataSingle.mapSeed[x]].turretLocationsY = tempHolderY;
}
PlayerStats.PlayerStatsSingle.MapInfo = MapInfo;
seed = GameData.GameDataSingle.mapSeed[0];
LoadMap();
DrawPlayerMap.DrawPlayerMapSingle.currentMap = seed;
PlayerController.PlayerControllerSingle.respawnLocation = new Vector3(PlayerStats.PlayerStatsSingle.MapInfo[seed].doorLocationsX[0],
PlayerStats.PlayerStatsSingle.MapInfo[seed].doorLocationsY[0], 0);
//have to create set some variables in drawplayermap
MapPosWorldMaps = new List<Vector3>();
foreach (Vector2 mapSet in GameData.GameDataSingle.mapSets)
{
for (int j = 0; j < (int)mapSet.x; j++)
{
MapPosWorldMaps.Add(new Vector2(Mathf.Cos(2 * Mathf.PI * j / (int)mapSet.x), Mathf.Sin(2 * Mathf.PI * j / (int)mapSet.x)));
}
}
LinePos = new List<Vector3>();
//create world map sections before cave meshes are turned off
DrawPlayerMap.DrawPlayerMapSingle.CreateWorldMap();
//Destroy(gameObject);
//remove doors before going to main area
var oldDoors = GameObject.FindGameObjectsWithTag("Door");
foreach (var door in oldDoors)
{
Destroy(door);
}
//for turing off all cave objects. need to wait for this beacuse haven't build world map yet
foreach (Transform child in transform.Find("MapHolder"))
{
child.gameObject.SetActive(false);
}
GameController.GameControllerSingle.dontLoadTheGame = false;
GameController.GameControllerSingle.SaveMapData();
seed = GameData.GameDataSingle.mapSeed[0];
LoadMap();
//LoadOnClick.LoadOnClickSingle.LoadScene(0);
}
else
{
GameController.GameControllerSingle.LoadMapData();
GenerateOldMaps();
//LoadMap();
seed = GameData.GameDataSingle.mapSeed[0];
PlayerController.PlayerControllerSingle.respawnLocation = new Vector3(PlayerStats.PlayerStatsSingle.MapInfo[seed].doorLocationsX[0],
PlayerStats.PlayerStatsSingle.MapInfo[seed].doorLocationsY[0], 0);
DrawPlayerMap.DrawPlayerMapSingle.currentMap = seed;
//have to create set some variables in drawplayermap
MapPosWorldMaps = new List<Vector3>();
foreach (Vector2 mapSet in GameData.GameDataSingle.mapSets)
{
for (int j = 0; j < (int)mapSet.x; j++)
{
MapPosWorldMaps.Add(new Vector2(Mathf.Cos(2 * Mathf.PI * j / (int)mapSet.x), Mathf.Sin(2 * Mathf.PI * j / (int)mapSet.x)));
}
}
LinePos = new List<Vector3>();
//create world map sections before cave meshes are turned off
DrawPlayerMap.DrawPlayerMapSingle.CreateWorldMap();
//Destroy(gameObject);
//remove doors before going to main area
var oldDoors = GameObject.FindGameObjectsWithTag("Door");
foreach (var door in oldDoors)
{
Destroy(door);
}
//for turing off all cave objects. need to wait for this beacuse haven't build world map yet
foreach (Transform child in transform.Find("MapHolder"))
{
child.gameObject.SetActive(false);
}
//loads the map
LoadMap();
}
}
public void GenerateOldMaps()
{
meshGen = GetComponent<MeshGenerator>();
MapAddOns = GetComponent<MapAddOns>();
for (int x = 0; x < numMaps; x++)
{
string oldMapsSeeds = GameData.GameDataSingle.mapSeed[x];
seed = oldMapsSeeds;
int squareSize = MapInfo[oldMapsSeeds].squareSize;
MapInformation TempData = new MapInformation();
TempData.index = MapInfo[oldMapsSeeds].index;
TempData.mapSet = MapInfo[oldMapsSeeds].mapSet;
TempData.width = MapInfo[oldMapsSeeds].width;
TempData.height = MapInfo[oldMapsSeeds].height;
TempData.randomFillPercent = MapInfo[oldMapsSeeds].randomFillPercent;
TempData.passageLength = MapInfo[oldMapsSeeds].passageLength;
TempData.smoothness = MapInfo[oldMapsSeeds].smoothness;
TempData.squareSize = MapInfo[oldMapsSeeds].squareSize;
TempData.map = MapInfo[oldMapsSeeds].map;
TempData.borderedMap = MapInfo[oldMapsSeeds].borderedMap;
map = TempData.map;
squareSize = TempData.squareSize;
meshGen.GenerateMesh(TempData.borderedMap, squareSize);
}
}
//begining of map generation
public void GenerateMap()
{
int squareSize = 1;
//for getting map set number
int currentSetMap = 0;
foreach (Vector2 mapSet in GameData.GameDataSingle.mapSets)
{
if (currentMap >= (int)mapSet.y && currentMap < (int)mapSet.y + (int)mapSet.x)
{
break;
}
currentSetMap += 1;
}
map = new int[width, height];
//save game data for recall later
GameData.GameDataSingle.AddSeed(seed);
//save map data
MapInformation TempData = new MapInformation();
TempData.index = currentMap;
TempData.mapSet = currentSetMap;
TempData.width = width;
TempData.height = height;
TempData.randomFillPercent = randomFillPercent;
TempData.passageLength = passageLength;
TempData.smoothness = smoothness;
TempData.squareSize = squareSize;
MapInfo.Add(seed, TempData);
//fills map
RandomFillMap();
// smooths the map
for (int i = 0; i < smoothness; i++)
{
SmoothMap();
}
//adds the mesh and other parts
ProcessMap();
MapInfo[seed].map = map;
int borderSize = 5;
borderedMap = new int[width + borderSize * 2, height + borderSize * 2];
for (int x = 0; x < borderedMap.GetLength(0); x++)
{
for (int y = 0; y < borderedMap.GetLength(1); y++)
{
if (x >= borderSize && x < width + borderSize && y >= borderSize && y < height + borderSize)
{
borderedMap[x, y] = map[x - borderSize, y - borderSize];
}
else
{
borderedMap[x, y] = 1;
}
}
}
MapInfo[seed].borderedMap = borderedMap;
meshGen.GenerateMesh(borderedMap, squareSize);
//for doors spawns
possibleDoorLocations = new List<Vector2>();
possibleDoorLocations = MapAddOns.GenerateDoorsLocations(map);
List<float> tempHolderX = new List<float>();
List<float> tempHolderY = new List<float>();
foreach (Vector2 XYCoord in possibleDoorLocations)
{
tempHolderX.Add(XYCoord.x);
tempHolderY.Add(XYCoord.y);
}
MapInfo[seed].possibleDoorLocationsX = tempHolderX;
MapInfo[seed].possibleDoorLocationsY = tempHolderY;
}
public void LoadMap()
{
//have to set respawn locations
PlayerController.PlayerControllerSingle.transform.position = PlayerController.PlayerControllerSingle.respawnLocation;
MapInformation currentData = MapInfo[seed];
borderedMap = currentData.borderedMap;
//MapAddOns.SpawnSeekingEnemy(currentData);
meshGen.LoadMeshFromAssests(currentData.borderedMap, 1);
//for door spawns
doorLocations = new List<Vector2>();
for(int tempCounter = 0; tempCounter < MapInfo[seed].doorLocationsX.Count; tempCounter++)
{
doorLocations.Add(new Vector2(MapInfo[seed].doorLocationsX[tempCounter], MapInfo[seed].doorLocationsY[tempCounter]));
}
//doorLocations = MapInfo[seed].doorLocations;
MapAddOns.PlaceDoorsOnMap(doorLocations, currentData.doorType);
//for enemy spawns
enemyLocations = new List<Vector2>();
turretLocations = new List<Vector2>();
//foreach (float tempXY in MapInfo[seed].enemyLocationsX)
if (MapInfo[seed].enemyLocationsX != null)
{
//for enemyLocations
for (int tempCounter = 0; tempCounter < MapInfo[seed].enemyLocationsX.Count; tempCounter++)
{
enemyLocations.Add(new Vector2(MapInfo[seed].enemyLocationsX[tempCounter], (MapInfo[seed].enemyLocationsY[tempCounter])));
}
//for turretLocations
for (int tempCounter = 0; tempCounter < MapInfo[seed].turretLocationsX.Count; tempCounter++)
{
turretLocations.Add(new Vector2(MapInfo[seed].turretLocationsX[tempCounter], (MapInfo[seed].turretLocationsY[tempCounter])));
}
if (enemyLocations != null && enemyLocations.Count > 0)
{
MapAddOns.PlaceEnemyOnMap(enemyLocations, turretLocations);
}
//for enemies that free spawn
MapAddOns.SpawnSliderEnemy();
//spawns gather items // should be somewhere else later (only spawns if there are enemies)
MapAddOns.GatherQuestItems(MapInfo[seed]);
}
}
//smooths the map with arbitrary process, change be changed and modified
void SmoothMap()
{
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
int neighbourWallTitles = GetSurroundingWallCount(x, y);
if (neighbourWallTitles > 4)
{
map[x, y] = 1;
}
else if (neighbourWallTitles < 4)
{
map[x, y] = 0;
}
}
}
}
// gets counts of walls from 9 tiles, all the tiles surrounding current tile.
int GetSurroundingWallCount(int gridX, int gridY)
{
int wallCount = 0;
for (int neighbourX = gridX - 1; neighbourX <= gridX + 1; neighbourX++)
{
for (int neighbourY = gridY - 1; neighbourY <= gridY + 1; neighbourY++)
{
if (IsInMapRange(neighbourX, neighbourY))
{
if (neighbourX != gridX || neighbourY != gridY)
{
wallCount += map[neighbourX, neighbourY];
}
}
else {
wallCount++;
}
}
}
return wallCount;
}
//checks if given x y is in the map range
bool IsInMapRange(int x, int y)
{
return x >= 0 && x < width && y >= 0 && y < height;
}
//for random filling of map with border
void RandomFillMap()
{
//get the hash of the seed to fill array, same seed will give same array
System.Random pseudoRandom = new System.Random(seed.GetHashCode());
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
//make solid border
if (x == 0 || x == width - 1 || y == 0 || y == height - 1)
{
map[x, y] = 1;
}
//random fill
else
{
if (pseudoRandom.Next(0, 100) < randomFillPercent)
{
map[x, y] = 1;
}
else
{
map[x, y] = 0;
}
}
}
}
}
void ProcessMap()
{
// 1 represents the wall
List<List<Coord>> wallRegions = GetRegions(1);
// remove wall if not larger than xxx
int wallThresholdSize = 50;
foreach (List<Coord> wallRegion in wallRegions)
{
if (wallRegion.Count < wallThresholdSize)
{
foreach (Coord tile in wallRegion)
{
map[tile.tileX, tile.tileY] = 0;
}
}
}
// 0 represents the room
List<List<Coord>> roomRegions = GetRegions(0);
// remove room if not larger than xxx
int roomThresholdSize = 50;
//list of all rooms that are left after removing
List<Room> survivingRooms = new List<Room>();
foreach (List<Coord> roomRegion in roomRegions)
{
if (roomRegion.Count < roomThresholdSize)
{
foreach (Coord tile in roomRegion)
{
map[tile.tileX, tile.tileY] = 1;
}
}
else
{
survivingRooms.Add(new Room(roomRegion, map));
}
}
if (survivingRooms.Count > 0)
{
survivingRooms.Sort();
survivingRooms[0].isMainRoom = true;
survivingRooms[0].isAccessibleFromMainRoom = true;
if (passageLength > 0)
{
ConnectClosestRooms(survivingRooms);
}
}
}
//for region detection
struct Coord
{
public int tileX;
public int tileY;
// public int positionX;
// public int positionY;
// public int positionZ;
//contructor
public Coord(int x, int y)
{
tileX = x;
tileY = y;
}
/*
public CoordWithPos(int x, int y, int posX, int posY, int posZ)
{
tileX = x;
tileY = y;
positionX = posX;
positionY = posY;
positionZ = posZ;
}
*/
}
//method takes tile type and return all regions with that type of tile
List<List<Coord>> GetRegions(int tileType)
{
List<List<Coord>> regions = new List<List<Coord>>();
//2d array for checking if titles has been seen before
int[,] mapFlags = new int[width, height];
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
if (mapFlags[x, y] == 0 && map[x, y] == tileType)
{
List<Coord> newRegion = GetRegionTiles(x, y);
regions.Add(newRegion);
foreach (Coord tile in newRegion)
{
mapFlags[tile.tileX, tile.tileY] = 1;
}
}
}
}
return regions;
}
//for region detection, flood fill algorithm to find rooms
List<Coord> GetRegionTiles(int startX, int startY)
{
List<Coord> tiles = new List<Coord>();
//2d array for checking if titles has been seen before
int[,] mapFlags = new int[width, height];
//for type of tile
int tileType = map[startX, startY];
//queue for checking if element was visted before
Queue<Coord> queue = new Queue<Coord>();
queue.Enqueue(new Coord(startX, startY));
mapFlags[startX, startY] = 1;
//
while (queue.Count > 0)
{
Coord tile = queue.Dequeue();
tiles.Add(tile);
for (int x = tile.tileX - 1; x <= tile.tileX + 1; x++)
{
for (int y = tile.tileY - 1; y <= tile.tileY + 1; y++)
{
if (IsInMapRange(x, y) && (x == tile.tileX || y == tile.tileY))
{
if (mapFlags[x, y] == 0 && map[x, y] == tileType)
{
mapFlags[x, y] = 1;
queue.Enqueue(new Coord(x, y));
}
}
}
}
}
return tiles;
}
//for connecting rooms
class Room : IComparable<Room>
{
public List<Coord> tiles;
public List<Coord> edgeTiles;
public List<Room> connectedRooms;
public int roomSize;
public bool isAccessibleFromMainRoom;
public bool isMainRoom;
//if empty room is wanted
public Room()
{
}
public Room(List<Coord> roomTiles, int[,] map)
{
tiles = roomTiles;
roomSize = tiles.Count;
connectedRooms = new List<Room>();
edgeTiles = new List<Coord>();
foreach (Coord tile in tiles)
{
//check if tiles neighbours is a wall tile, if so is on edge of room
for (int x = tile.tileX - 1; x <= tile.tileX + 1; x++)
{
for (int y = tile.tileY - 1; y <= tile.tileY + 1; y++)
{
// exclude diagnol tiles
if (x == tile.tileX || y == tile.tileY)
{
if (map[x, y] == 1)
{
edgeTiles.Add(tile);
}
}
}
}
}
}
public void SetAccessibleFromMainRoom()
{
if (!isAccessibleFromMainRoom)
{
isAccessibleFromMainRoom = true;
foreach (Room connectedRoom in connectedRooms)
{
connectedRoom.SetAccessibleFromMainRoom();
}
}
}
public static void ConnectRooms(Room roomA, Room roomB)
{
if (roomA.isAccessibleFromMainRoom)
{
roomB.SetAccessibleFromMainRoom();
}
else if (roomB.isAccessibleFromMainRoom)
{
roomA.SetAccessibleFromMainRoom();
}
roomA.connectedRooms.Add(roomB);
roomB.connectedRooms.Add(roomA);
}
public bool IsConnected(Room otherRoom)
{
return connectedRooms.Contains(otherRoom);
}
//use with IComparable
public int CompareTo(Room otherRoom)
{
return otherRoom.roomSize.CompareTo(roomSize);
}
}
void ConnectClosestRooms(List<Room> allRooms, bool forceAccessiblilityFromMainRoom = false)
{
List<Room> roomListA = new List<Room>();
List<Room> roomListB = new List<Room>();
if (forceAccessiblilityFromMainRoom)
{
foreach (Room room in allRooms)
{
if (room.isAccessibleFromMainRoom)
{
roomListB.Add(room);
}
else
{
roomListA.Add(room);
}
}
}
else
{
roomListA = allRooms;
roomListB = allRooms;
}
int bestDistance = 0;
Coord bestTileA = new Coord();
Coord bestTileB = new Coord();
Room bestRoomA = new Room();
Room bestRoomB = new Room();
bool possibleConnectionFound = false;
foreach (Room roomA in roomListA)
{
if (!forceAccessiblilityFromMainRoom)
{
possibleConnectionFound = false;
if (roomA.connectedRooms.Count > 0)
{
continue;
}
}
foreach (Room roomB in roomListB)
{
//optimizing
if (roomA == roomB || roomA.IsConnected(roomB))
{
continue;
}
for (int tileIndexA = 0; tileIndexA < roomA.edgeTiles.Count; tileIndexA++)
{
for (int tileIndexB = 0; tileIndexB < roomB.edgeTiles.Count; tileIndexB++)
{
Coord tileA = roomA.edgeTiles[tileIndexA];
Coord tileB = roomB.edgeTiles[tileIndexB];
int distanceBetweenRooms = (int)(Mathf.Pow(tileA.tileX - tileB.tileX, 2) + Mathf.Pow(tileA.tileY - tileB.tileY, 2));
//best connection was found
if (distanceBetweenRooms < bestDistance || !possibleConnectionFound)
{
bestDistance = distanceBetweenRooms;
possibleConnectionFound = true;
bestTileA = tileA;
bestTileB = tileB;
bestRoomA = roomA;
bestRoomB = roomB;
}
}
}
}
//when you just want rooms to be connect to atleat one other room
if (possibleConnectionFound && !forceAccessiblilityFromMainRoom)
{
CreatePassage(bestRoomA, bestRoomB, bestTileA, bestTileB);
}
}
//when you want all rooms connected
if (possibleConnectionFound && forceAccessiblilityFromMainRoom)
{
CreatePassage(bestRoomA, bestRoomB, bestTileA, bestTileB);
ConnectClosestRooms(allRooms, true);
}
if (!forceAccessiblilityFromMainRoom)
{
ConnectClosestRooms(allRooms, true);
}
}
void CreatePassage(Room roomA, Room roomB, Coord tileA, Coord tileB)
{
Room.ConnectRooms(roomA, roomB);
//Debug.DrawLine(CoordToWorldPoint(tileA), CoordToWorldPoint(tileB), Color.green, 100);
List<Coord> line = GetLine(tileA, tileB);
foreach (Coord c in line)
{
DrawCircle(c, passageLength);
}
}
List<Coord> GetLine(Coord from, Coord to)
{
List<Coord> line = new List<Coord>();
int x = from.tileX;
int y = from.tileY;
int dx = to.tileX - x;
int dy = to.tileY - y;
bool inverted = false;
int step = Math.Sign(dx);
int gradientStep = Math.Sign(dy);
int longest = Math.Abs(dx);
int shortest = Math.Abs(dy);
if (longest < shortest)
{
inverted = true;
longest = Math.Abs(dy);
shortest = Math.Abs(dx);
step = Math.Sign(dy);
gradientStep = Math.Sign(dx);
}
int gradientAccumulation = longest / 2;
for (int i = 0; i < longest; i++)
{
line.Add(new Coord(x, y));
if (inverted)
{
y += step;
}
else
{
x += step;
}
gradientAccumulation += shortest;
if (gradientAccumulation >= longest)
{
if (inverted)
{
x += gradientStep;
}
else
{
y += gradientStep;
}
gradientAccumulation -= longest;
}
}
return line;
}
void DrawCircle(Coord c, int r)
{
for (int x = -r; x <= r; x++)
{
for (int y = -r; y <= r; y++)
{
if (x * x + y * y <= r * r)
{
int realX = c.tileX + x;
int realY = c.tileY + y;
if (IsInMapRange(realX, realY))
{
map[realX, realY] = 0;
}
}
}
}
}
//this is used for visual debugging, doesn't create anything real.
/*
void OnDrawGizmos()
{
if(map != null)
{
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
if (map[x,y] == 1)
{
Gizmos.color = Color.black;
}
else
{
Gizmos.color = Color.white;
}
Vector2 pos = new Vector2(-width / 2 + x + .5f, -height / 2 + y + .5f);
Gizmos.DrawCube(pos, Vector2.one);
}
}
}
}
*/
}
<file_sep>/2dProject/Assets/scripts/CutSceneScripts/CutSceneLoader.cs
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
public class CutSceneLoader : MonoBehaviour
{
//[SerializeField]
//private int scene;
public bool loadCutScene = false;
public bool loadBackToGame = false;
private string CutSceneName = "NameOfCutSceneToLoad";
public string LoadNewScene = "NewcutScene";
//for getting mapgenerator
private GameObject mapGenerator;
public GameObject[] allCurrentGameObjects;
public static CutSceneLoader CutSceneLoaderSingle;
void Awake()
{
if (CutSceneLoaderSingle == null)
{
DontDestroyOnLoad(gameObject);
CutSceneLoaderSingle = this;
}
else if (CutSceneLoaderSingle != this)
{
Destroy(gameObject);
}
//allCurrentGameObjects = FindObjectsOfType<GameObject>();
DontDestroyOnLoad(this);
}
void Update()
{
if (loadCutScene)
{
//sets all gameobjects that are not part of the cut scene to false
Time.timeScale = 1;
allCurrentGameObjects = FindObjectsOfType<GameObject>();
foreach (GameObject ob in allCurrentGameObjects)
{
if (ob.name != gameObject.name)
{
ob.SetActive(false);
}
}
loadCutScene = false;
StartCoroutine(LoadCutScene());
}
if (loadBackToGame)
{
Time.timeScale = 1;
foreach (GameObject ob in allCurrentGameObjects)
{
if (ob)
{
if (ob.name != "CutScene")
{
ob.SetActive(true);
}
}
}
StartCoroutine(LoadOldScene());
loadBackToGame = false;
}
}
public void loadScene(string name)
{
CutSceneName = name;
loadCutScene = true;
}
IEnumerator LoadCutScene()
{
//load function
AsyncOperation async = SceneManager.LoadSceneAsync(CutSceneName);
// While the asynchronous operation to load the new scene is not yet complete, continue waiting until it's done.
while (!async.isDone)
{
yield return null;
}
}
IEnumerator LoadOldScene()
{
//load function
AsyncOperation async = SceneManager.LoadSceneAsync(LoadNewScene);
// While the asynchronous operation to load the new scene is not yet complete, continue waiting until it's done.
while (!async.isDone)
{
yield return null;
}
}
}
<file_sep>/2dProject/Assets/scripts/EmenyStuff/ProjectileAttacks/TurretAttack.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TurretAttack : MonoBehaviour {
bool startTimer = false;
private float timer = 0;
public float fireRate = 2f;
private float distanceToPlayer;
private Vector3 playersLastLocations;
public Transform fireBallPrefab;
public int attackType = 0;
public Vector3 spawnLocationOffset;
// Update is called once per frame
void Update () {
//for checking how far the player is
distanceToPlayer = Vector3.Distance(transform.position, PlayerController.PlayerControllerSingle.transform.position);
if (distanceToPlayer <= 30)
{
startTimer = true;
}
//timer for time until attack
if (startTimer)
{
timer += Time.deltaTime;
}
//2 seconds timer for firing projectiles, smaller = faster larger = slower
if (timer >= fireRate)
{
startTimer = false;
timer = 0f;
var fireball = Instantiate(fireBallPrefab);
fireball.position = transform.position + spawnLocationOffset;
fireball.name = "Fireball";
//var temp = fireball.gameObject.AddComponent<ProjectileForward>();
if(attackType == 0)
{
var temp = fireball.gameObject.AddComponent<ProjectileForward>();
temp.direction = 1;
temp.ProjectileMovement(transform.rotation);
}
else if (attackType == 1)
{
var temp = fireball.gameObject.AddComponent<EnemyProjectileAttack>();
temp.fireBallPrefab = fireBallPrefab;
}
else if (attackType == 2)
{
var temp = fireball.gameObject.AddComponent<ProjectileAttackSplitInArc>();
temp.fireBallPrefab = fireBallPrefab;
temp.splitNumber = 4;
temp.ProjectileMovement();
}
else if (attackType == 3)
{
var temp = fireball.gameObject.AddComponent<ProjectileAttackSplitTowardsPlayer>();
temp.fireBallPrefab = fireBallPrefab;
temp.splitNumber = 4;
//temp.ProjectileMovement();
}
}
}
}
<file_sep>/2dProject/Assets/scripts/MainQuest/MainQuest8_0.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MainQuest8_0 : MonoBehaviour {
public bool touchingCharacter { get; set; }
private Text NPCtext;
private Text Herotext;
private CanvasGroup canvas;
//boss sprite gets set after boss is dead in bossScript
public Sprite BossSprite;
//wair for boss to die
public bool bossDead { get; set; }
//spawn location outside of room
private Vector3 spawnLocationHolder;
// Use this for initialization
void Start ()
{
//set player spawn to in room and hold player spawn location for outside area
spawnLocationHolder = PlayerController.PlayerControllerSingle.respawnLocation;
PlayerController.PlayerControllerSingle.respawnLocation = new Vector3(0, 1, 0);
NPCtext = DialogManager.DialogManagerSingle.NPCtext;
Herotext = DialogManager.DialogManagerSingle.Herotext;
canvas = DialogManager.DialogManagerSingle.canvas;
bossDead = false;
//set quest text in questlog
QuestController.QuestControllerSingle.MainQuestText.text = "Kill Boss. " + "Main Quest " + QuestController.QuestControllerSingle.currentMainQuest;
}
// Update is called once per frame
void Update ()
{
if(bossDead)
{
bossDead = false;
Debug.Log("boss sprite sprite");
canvas.alpha = 1;
StartCoroutine(Dialog());
}
}
public IEnumerator Dialog()
{
string Conversation1 = DialogManager.DialogManagerSingle.MainQuestDialogueLoadPath + "MainQuest8_0.0";
//reset spawn location
PlayerController.PlayerControllerSingle.respawnLocation = spawnLocationHolder;
//freeze player
PlayerController.PlayerControllerSingle.LockPosition();
//start conversavtion 1
StartCoroutine(DialogManager.DialogManagerSingle.Dialog(Conversation1));
//waits for conversation to finish
while ((DialogManager.DialogManagerSingle.dialogOn == true))
{
yield return new WaitForSeconds(0.1f);
}
//wait 1 sec before continuing
yield return new WaitForSeconds(1f);
canvas.alpha = 0;
//let player move again
PlayerController.PlayerControllerSingle.UnLockPosition();
//Text reset
NPCtext.text = "";
Herotext.text = "";
QuestController.QuestControllerSingle.currentMainQuest = 9f;
if (QuestController.QuestControllerSingle.currentMainQuest == 9f)
{
Debug.Log("quest is 9");
Debug.Log(QuestController.QuestControllerSingle.currentMainQuest + " = QuestController.QuestControllerSingle.currentQuest");
//GameObject.Find("Hero").AddComponent<MainQuest9_0>();
}
CutSceneLoader.CutSceneLoaderSingle.loadScene("CutScene3");
Destroy(this);
}
}
<file_sep>/2dProject/Assets/scripts/EmenyStuff/Movement/MoveLeftRight.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveLeftRight : MonoBehaviour
{
private Rigidbody2D RigBod;
private float Speed = 5f;
// Use this for initialization
void Start()
{
RigBod = gameObject.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
RigBod.velocity = new Vector2(Speed, 0);
}
private void OnCollisionEnter2D(Collision2D collision)
{
//Debug.Log(collision.gameObject.layer);
if (collision.gameObject.layer == 8)
{
Speed *= -1;
}
}
}
<file_sep>/2dProject/Assets/scripts/BossRoom/Bomb.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bomb : MonoBehaviour {
public Rigidbody2D rb2d;
public GameObject shield;
public MoveTowardPlayer movement;
void Start()
{
rb2d = GameObject.Find("Boss").GetComponent<Rigidbody2D>();
//Access to gameobjects on boss
shield = BossScript.BossScriptSingle.shield;
movement = BossScript.BossScriptSingle.GetComponent<MoveTowardPlayer>();
//No more bombs
BossScript.BossScriptSingle.bombSpawn = true;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Enemy")
{
rb2d.AddForce(new Vector2(0f, 1000f));
Destroy(gameObject);
//turn off shield and turn on movement
shield.SetActive(false);
movement.enabled = false;
//One bomb at a time
BossScript.BossScriptSingle.bombSpawn = false;
//turnoff shield and make it so another bomb can spawn next shield phases.
BossScript.BossScriptSingle.shieldOn = false;
BossScript.BossScriptSingle.bombSpawn = false;
//No longer stun the player
PlayerController.PlayerControllerSingle.freezePlayer = false;
if (GameObject.FindGameObjectWithTag("EnemyProjectile") != null)
{
Destroy(GameObject.FindGameObjectWithTag("EnemyProjectile"));
}
}
}
}
<file_sep>/2dProject/Assets/scripts/GameInformation/GameData.cs
using UnityEngine;
using System.Collections.Generic;
public class GameData : MonoBehaviour
{
//used only in gamedata class
private List<List<string>> doorDicRefs = new List<List<string>>();
private List<int> numDoorCountPerMap = new List<int>();
//used outside and inside of gamedata class
public Dictionary<string, string> doorConnectionDictionary = new Dictionary<string, string>();
public List<string> mapSeed = new List<string>();
//for the size of the map sets for making the world map
public List<Vector2> mapSets = new List<Vector2>();
//for tracking boss room doors
//public Dictionary<string, bool> isBossRoomOpen = new Dictionary<string, bool>();
public static GameData GameDataSingle;
void Awake()
{
if (GameDataSingle == null)
{
DontDestroyOnLoad(gameObject);
GameDataSingle = this;
}
else if (GameDataSingle != this)
{
Destroy(gameObject);
}
}
//gets index of map
public int FindMapIndex(string map)
{
return mapSeed.IndexOf(map);
}
//checks if is seed
public bool IsSeed(string seed)
{
if (mapSeed.Contains(seed))
{
return true;
}
else
{
return false;
}
}
// returns the next seeds in list
public string GetSeed(string seed)
{
string nextSeed;
if (mapSeed.Count > 0)
{
int index = mapSeed.IndexOf(seed);
if (mapSeed.Count > index + 1)
{
nextSeed = mapSeed[index + 1];
}
else
{
nextSeed = mapSeed[0];
}
}
else
{
return "0";
}
return nextSeed;
}
//adds seed to map
public void AddSeed(string seed)
{
mapSeed.Add(seed);
}
public List<Vector2> createNumberOfDoors(int numDoors, MapInformation map1, int listDoor)
{
List<Vector2> drawDoors = new List<Vector2>();
for (int x = 0; x < numDoors; x++)
{
Vector2 doorXY;
Vector2 tempDoor;
int tempDoorIndex = Random.Range(0, map1.possibleDoorLocationsX.Count);
doorXY = new Vector2(map1.possibleDoorLocationsX[tempDoorIndex], map1.possibleDoorLocationsY[tempDoorIndex]);
float xPos = -map1.width / 2 + doorXY.x * map1.squareSize + map1.squareSize / 2;
float yPos = -map1.height / 2 + doorXY.y * map1.squareSize + map1.squareSize;
//for removing doors left and right of current door
if (tempDoorIndex < map1.possibleDoorLocationsX.Count - 1)
{
tempDoor = new Vector2(map1.possibleDoorLocationsX[tempDoorIndex + 1], map1.possibleDoorLocationsY[tempDoorIndex + 1]);
if (Vector2.Distance(tempDoor, doorXY) <= 1)
{
map1.possibleDoorLocationsX.RemoveAt(tempDoorIndex + 1);
map1.possibleDoorLocationsY.RemoveAt(tempDoorIndex + 1);
}
}
if (tempDoorIndex > 0)
{
tempDoor = new Vector2(map1.possibleDoorLocationsX[tempDoorIndex - 1], map1.possibleDoorLocationsY[tempDoorIndex - 1]);
if (Vector2.Distance(tempDoor, doorXY) <= 1)
{
map1.possibleDoorLocationsX.RemoveAt(tempDoorIndex - 1);
map1.possibleDoorLocationsY.RemoveAt(tempDoorIndex - 1);
tempDoorIndex -= 1;
}
}
map1.possibleDoorLocationsX.RemoveAt(tempDoorIndex);
map1.possibleDoorLocationsY.RemoveAt(tempDoorIndex);
doorXY = new Vector2(xPos, yPos);
drawDoors.Add(doorXY);
}
return drawDoors;
}
public void CreatDoorConnections(int startMap, int endMap, int numDoors)
{
//this is the list with the number of doors per map in the current set of maps. is a temp variable
numDoorCountPerMap = new List<int>();
numDoorCountPerMap.Clear();
numDoorCountPerMap.TrimExcess();
//create the number of doors
doorDicRefs = new List<List<string>>();
for (int listDoor = startMap; listDoor < endMap + 1; listDoor++)
{
List<Vector2> ListOfDoors = new List<Vector2>();
MapInformation map1 = MapGenerator.MapGeneratorSingle.MapInfo[mapSeed[listDoor]];
ListOfDoors = createNumberOfDoors(numDoors, map1 , listDoor);
List<float> tempHolderX = new List<float>();
List<float> tempHolderY = new List<float>();
List<int> doorType = new List<int>();
foreach (Vector2 XYCoord in ListOfDoors)
{
tempHolderX.Add(XYCoord.x);
tempHolderY.Add(XYCoord.y);
//0 for normals door
doorType.Add(0);
}
//all door locations
map1.doorLocationsX = tempHolderX;
map1.doorLocationsY = tempHolderY;
map1.doorType = doorType;
}
}
public void EnsureConnectivityOfMaps(int startMap, int endMap)
{
// fills a dictionary with all with map seeds concatenated to door index;
for (int listDoor = startMap; listDoor < endMap + 1; listDoor++)
{
List<string> tempList = new List<string>();
MapInformation map1 = MapGenerator.MapGeneratorSingle.MapInfo[mapSeed[startMap]];
int doorNum;
for (doorNum = 0; doorNum < map1.doorLocationsX.Count; doorNum++)
{
doorConnectionDictionary.Add(mapSeed[listDoor] + "," + doorNum.ToString(), "");
tempList.Add(mapSeed[listDoor] + "," + doorNum.ToString());
}
numDoorCountPerMap.Add(doorNum);
doorDicRefs.Add(tempList);
}
// connects a door in map 1 to map 2, map 2 to map 3, etc
for (int listDoor = startMap - startMap; listDoor < endMap - startMap; listDoor++)
{
int doorIndex1 = Random.Range(0, doorDicRefs[listDoor].Count);
int doorIndex2 = Random.Range(0, doorDicRefs[listDoor + 1].Count);
numDoorCountPerMap[listDoor] -= 1;
numDoorCountPerMap[listDoor + 1] -= 1;
string doorRef1 = doorDicRefs[listDoor][doorIndex1];
string doorRef2 = doorDicRefs[listDoor + 1][doorIndex2];
//set dictionary connections and remove those doors
doorConnectionDictionary[doorRef2] = doorRef1;
doorConnectionDictionary[doorRef1] = doorRef2;
doorDicRefs[listDoor].Remove(doorRef1);
doorDicRefs[listDoor + 1].Remove(doorRef2);
doorDicRefs[listDoor].TrimExcess();
doorDicRefs[listDoor + 1].TrimExcess();
}
}
public void ConnectDoors()
{
int maxDoorCountAllRooms = 0;
List<int> possibleDoorChoices = new List<int>();
//connects all doors, looks for highest door count room and connects to next highest door count room
while (doorDicRefs.Count > 0)
{
possibleDoorChoices.Clear();
possibleDoorChoices.TrimExcess();
maxDoorCountAllRooms = 0;
//first door info get and set
//Debug.Log("numDoorCountPerMap.Length = " + numDoorCountPerMap.Count);
for (int doorNumIndex = 0; doorNumIndex < numDoorCountPerMap.Count; doorNumIndex++)
{
if (maxDoorCountAllRooms < numDoorCountPerMap[doorNumIndex])
{
maxDoorCountAllRooms = numDoorCountPerMap[doorNumIndex];
possibleDoorChoices.Clear();
possibleDoorChoices.TrimExcess();
possibleDoorChoices.Add(doorNumIndex);
}
else if(maxDoorCountAllRooms == numDoorCountPerMap[doorNumIndex])
{
possibleDoorChoices.Add(doorNumIndex);
}
}
//get right map; decrease door count; get random door; get dictionary key;
int mapIndex1 = possibleDoorChoices[Random.Range(0, possibleDoorChoices.Count)];
numDoorCountPerMap[mapIndex1] -= 1;
int doorIndex1 = Random.Range(0, doorDicRefs[mapIndex1].Count);
string doorRef1 = doorDicRefs[mapIndex1][doorIndex1];
//begin second door info get and set
int secondMaxDoorCountAllRooms = maxDoorCountAllRooms;
possibleDoorChoices.Clear();
possibleDoorChoices.TrimExcess();
while(possibleDoorChoices.Count == 0)
{
for (int doorNumIndex = 0; doorNumIndex < numDoorCountPerMap.Count; doorNumIndex++)
{
if (mapIndex1 == doorNumIndex)
{
//do nothing, this is room of first door info
}
else if (secondMaxDoorCountAllRooms == numDoorCountPerMap[doorNumIndex])
{
possibleDoorChoices.Add(doorNumIndex);
}
}
secondMaxDoorCountAllRooms -= 1;
}
//get right map; if map is sam as first get another; decrease door count; get random door; get dictionary key;
int mapIndex2 = possibleDoorChoices[Random.Range(0, possibleDoorChoices.Count)];
while (mapIndex2 == mapIndex1)
{
mapIndex2 = possibleDoorChoices[Random.Range(0, possibleDoorChoices.Count)];
}
numDoorCountPerMap[mapIndex2] -= 1;
int doorIndex2 = Random.Range(0, doorDicRefs[mapIndex2].Count);
string doorRef2 = doorDicRefs[mapIndex2][doorIndex2];
//set dictionary connections and remove those doors
doorConnectionDictionary[doorRef2] = doorRef1;
doorConnectionDictionary[doorRef1] = doorRef2;
doorDicRefs[mapIndex1].Remove(doorRef1);
doorDicRefs[mapIndex2].Remove(doorRef2);
doorDicRefs[mapIndex1].TrimExcess();
doorDicRefs[mapIndex2].TrimExcess();
//check if any doors are left to connect
int allMapsHaveNoDoorsLeft = 0;
for(int x = 0; x < doorDicRefs.Count; x++)
{
if (doorDicRefs[x].Count == 0)
{
allMapsHaveNoDoorsLeft += 1;
}
}
if(allMapsHaveNoDoorsLeft == doorDicRefs.Count)
{
break;
}
}
}
//connects two maps with one door
public void ConnectSetOfRooms(int mapOne, int mapTwo)
{
MapInformation map1 = MapGenerator.MapGeneratorSingle.MapInfo[mapSeed[mapOne]];
MapInformation map2 = MapGenerator.MapGeneratorSingle.MapInfo[mapSeed[mapTwo]];
int tempDoorIndex1 = Random.Range(0, map1.possibleDoorLocationsX.Count);
Vector2 tempDoor;
Debug.Log("map1 = " + mapOne + " Map2 = " + mapTwo);
Debug.Log("map1.possibleDoorLocationsX.Count = " + map1.possibleDoorLocationsX.Count + " tempDoorIndex1 = " + tempDoorIndex1);
Debug.Log("map1.possibleDoorLocationsY.Count = " + map1.possibleDoorLocationsY.Count);
Vector2 door1 = new Vector2(map1.possibleDoorLocationsX[tempDoorIndex1], map1.possibleDoorLocationsY[tempDoorIndex1]);
float xPosMapOne = -map1.width / 2 + door1.x * map1.squareSize + map1.squareSize / 2;
float yPosMapOne = -map1.height / 2 + door1.y * map1.squareSize + map1.squareSize;
//for removing doors left and right of current door
if (tempDoorIndex1 < map1.possibleDoorLocationsX.Count - 1)
{
tempDoor = new Vector2(map1.possibleDoorLocationsX[tempDoorIndex1 + 1], map1.possibleDoorLocationsY[tempDoorIndex1 + 1]);
if (Vector2.Distance(tempDoor, door1) <= 1)
{
map1.possibleDoorLocationsX.Remove(tempDoorIndex1 + 1);
map1.possibleDoorLocationsY.Remove(tempDoorIndex1 + 1);
map1.possibleDoorLocationsX.TrimExcess();
map1.possibleDoorLocationsY.TrimExcess();
}
}
if (tempDoorIndex1 > 0)
{
tempDoor = new Vector2(map1.possibleDoorLocationsX[tempDoorIndex1 - 1], map1.possibleDoorLocationsY[tempDoorIndex1 - 1]);
if (Vector2.Distance(tempDoor, door1) <= 1)
{
map1.possibleDoorLocationsX.Remove(tempDoorIndex1 - 1);
map1.possibleDoorLocationsY.Remove(tempDoorIndex1 - 1);
map1.possibleDoorLocationsX.TrimExcess();
map1.possibleDoorLocationsY.TrimExcess();
//when remove left element you have to shrik the index location beacuse list resizes.
tempDoorIndex1--;
}
}
int tempDoorIndex2 = Random.Range(0, map2.possibleDoorLocationsX.Count);
Vector2 door2 = new Vector2(map2.possibleDoorLocationsX[tempDoorIndex2], map2.possibleDoorLocationsY[tempDoorIndex2]);
float xPosMapTwo = -map2.width / 2 + door2.x * map2.squareSize + map2.squareSize / 2;
float yPosMapTwo = -map2.height / 2 + door2.y * map2.squareSize + map2.squareSize;
//for removing doors left and right of current door
if (tempDoorIndex2 < map2.possibleDoorLocationsX.Count - 1)
{
tempDoor = new Vector2(map2.possibleDoorLocationsX[tempDoorIndex2 + 1], map2.possibleDoorLocationsY[tempDoorIndex2 + 1]);
if (Vector2.Distance(tempDoor, door2) <= 1)
{
map2.possibleDoorLocationsX.Remove(tempDoorIndex2 + 1);
map2.possibleDoorLocationsY.Remove(tempDoorIndex2 + 1);
map2.possibleDoorLocationsX.TrimExcess();
map2.possibleDoorLocationsY.TrimExcess();
}
}
if (tempDoorIndex2 > 0)
{
tempDoor = new Vector2(map2.possibleDoorLocationsX[tempDoorIndex2 - 1], map2.possibleDoorLocationsY[tempDoorIndex2 - 1]);
if (Vector2.Distance(tempDoor, door2) <= 1)
{
map2.possibleDoorLocationsX.Remove(tempDoorIndex2 - 1);
map2.possibleDoorLocationsY.Remove(tempDoorIndex2 - 1);
map2.possibleDoorLocationsX.TrimExcess();
map2.possibleDoorLocationsY.TrimExcess();
//when remove left element you have to shrik the index location beacuse list resizes.
tempDoorIndex2 -= 1;
}
}
map1.possibleDoorLocationsX.RemoveAt(tempDoorIndex1);
map1.possibleDoorLocationsY.RemoveAt(tempDoorIndex1);
map2.possibleDoorLocationsX.RemoveAt(tempDoorIndex2);
map2.possibleDoorLocationsY.RemoveAt(tempDoorIndex2);
map1.possibleDoorLocationsX.TrimExcess();
map1.possibleDoorLocationsY.TrimExcess();
map2.possibleDoorLocationsX.TrimExcess();
map2.possibleDoorLocationsY.TrimExcess();
door1 = new Vector2(xPosMapOne, yPosMapOne);
door2 = new Vector2(xPosMapTwo, yPosMapTwo);
map1.doorLocationsX.Add(xPosMapOne);
map1.doorLocationsY.Add(yPosMapOne);
map2.doorLocationsX.Add(xPosMapTwo);
map2.doorLocationsY.Add(yPosMapTwo);
//0 is normal door
map1.doorType.Add(0);
map2.doorType.Add(0);
doorConnectionDictionary.Add(mapSeed[mapOne] + "," + (map1.doorLocationsX.Count - 1).ToString(), mapSeed[mapTwo] + "," + (map2.doorLocationsX.Count - 1).ToString());
doorConnectionDictionary.Add(mapSeed[mapTwo] + "," + (map2.doorLocationsX.Count - 1).ToString(), mapSeed[mapOne] + "," + (map1.doorLocationsX.Count - 1).ToString());
//foreach (KeyValuePair<string, string> kvp in doorConnectionDictionary)
//{
// Debug.Log("Key =" + kvp.Key + "Value =" + kvp.Value);
//}
}
public void AddUniqueDoorToMap(MapInformation Map)
{
Vector2 doorXY;
Vector2 tempDoor;
int tempDoorIndex = Random.Range(0, Map.possibleDoorLocationsX.Count);
doorXY = new Vector2(Map.possibleDoorLocationsX[tempDoorIndex], Map.possibleDoorLocationsY[tempDoorIndex]);
float xPos = -Map.width / 2 + doorXY.x * Map.squareSize + Map.squareSize / 2;
float yPos = -Map.height / 2 + doorXY.y * Map.squareSize + Map.squareSize;
//for removing doors left and right of current door
if (tempDoorIndex < Map.possibleDoorLocationsX.Count - 1)
{
tempDoor = new Vector2(Map.possibleDoorLocationsX[tempDoorIndex + 1], Map.possibleDoorLocationsY[tempDoorIndex + 1]);
if (Vector2.Distance(tempDoor, doorXY) <= 1)
{
Map.possibleDoorLocationsX.RemoveAt(tempDoorIndex + 1);
Map.possibleDoorLocationsY.RemoveAt(tempDoorIndex + 1);
}
}
if (tempDoorIndex > 0)
{
tempDoor = new Vector2(Map.possibleDoorLocationsX[tempDoorIndex - 1], Map.possibleDoorLocationsY[tempDoorIndex - 1]);
if (Vector2.Distance(tempDoor, doorXY) <= 1)
{
Map.possibleDoorLocationsX.RemoveAt(tempDoorIndex - 1);
Map.possibleDoorLocationsY.RemoveAt(tempDoorIndex - 1);
tempDoorIndex -= 1;
}
}
Map.possibleDoorLocationsX.RemoveAt(tempDoorIndex);
Map.possibleDoorLocationsY.RemoveAt(tempDoorIndex);
Map.doorLocationsX.Add(xPos);
Map.doorLocationsY.Add(yPos);
Map.doorType.Add(1);
//add special door to dictionary
doorConnectionDictionary.Add(mapSeed[Map.index] + "," + (Map.doorLocationsX.Count - 1), "BossKey1,BossKey2");
}
public string GetDoorInfo(string DicRef)
{
string newDoor;
newDoor = doorConnectionDictionary[DicRef];
return newDoor;
}
}<file_sep>/2dProject/Assets/scripts/Spells/Fireball.cs
using UnityEngine;
using System.Collections;
public class Fireball : MonoBehaviour
{
private Vector3 StartLocation, EndLocation;
private Rigidbody2D rigidbodyComponent;
void Start()
{
transform.GetComponent<DamageOnCollision>().damage = PlayerStats.PlayerStatsSingle.intelligence;
transform.GetComponent<DamageOnCollision>().onCollide = onCollide;
Destroy(gameObject, 5);
}
void FixedUpdate()
{
CalculateRotation();
}
void onCollide()
{
Destroy(gameObject);
}
void CalculateRotation()
{
//faces object forward; rigidbody needs to be getting speeds
float angle = Mathf.Atan2(rigidbodyComponent.velocity.y, -rigidbodyComponent.velocity.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.back);
}
//start method
public void SetStartData(Vector3 Start, Vector3 End)
{
StartLocation = Start;
EndLocation = End;
//get fireball rb
rigidbodyComponent = GetComponent<Rigidbody2D>();
//set start locations of object
transform.position = Start;
//get firball velocity
CalculateSpeed();
CalculateRotation();
}
void CalculateSpeed()
{
float g, maxHeight, time, displacementY;
Vector3 velocityY, velocityXZ, displacementXZ;
g = -9.81f;
maxHeight = EndLocation.y - StartLocation.y;
displacementY = EndLocation.y - StartLocation.y;
if (0 < maxHeight && maxHeight < 3)
{
maxHeight = 3;
}
//max height must be positive // can we find a fix for this?
if (displacementY <= 0)
{
if (displacementY == 0)
{
maxHeight = 3f;
displacementY = 3f;
}
else
{
maxHeight = 1;
}
}
displacementXZ = new Vector3(EndLocation.x - StartLocation.x, 0, EndLocation.z - StartLocation.z);
time = Mathf.Sqrt(-2 * maxHeight / g) + Mathf.Sqrt(2 * (displacementY - maxHeight) / g);
velocityY = Vector3.up * Mathf.Sqrt(-2 * g * maxHeight);
velocityXZ = displacementXZ / time;
////for below player
//if (displacementY <= 0)
//{
// time = Mathf.Sqrt(2 * displacementY / g);
// velocityY = Vector3.zero;
// velocityXZ = displacementXZ / time;
//}
////for above player
//else
//{
// velocityY = Vector3.up * Mathf.Sqrt(-2 * g * maxHeight);
// velocityXZ = displacementXZ / time;
//}
//set velocity x y in rb
rigidbodyComponent.velocity = (velocityXZ + velocityY * -Mathf.Sign(g));
}
}
<file_sep>/2dProject/Assets/scripts/Spells/Heal.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Heal : MonoBehaviour {
// Use this for initialization
void Start() {
if (PlayerStats.PlayerStatsSingle.health < PlayerStats.PlayerStatsSingle.maxHealth) {
PlayerStats.PlayerStatsSingle.health += 1;
}
Destroy(gameObject, 1);
}
void Update()
{
transform.position = new Vector3(GameObject.Find("Hero").transform.position.x, GameObject.Find("Hero").transform.position.y + 1, 0);
}
}
<file_sep>/2dProject/Assets/scripts/CutSceneScripts/CutScene1.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class CutScene1 : MonoBehaviour {
public Camera cam;
public Text cutSceneText;
Vector3 targetLocation;
float speed;
float start, end;
//public static CutSceneLoader CutSceneLoaderSingle;
void Start () {
cam.transform.position = new Vector3(5.5f, -6.7f, -1);
cam.orthographicSize = 13f;
StartCoroutine(WaitForScene());
}
void Update()
{
cam.transform.position = Vector3.MoveTowards(cam.transform.position, targetLocation, speed);
cam.orthographicSize = Mathf.Lerp(cam.orthographicSize, end, .10f);
//for pausing cut scene
if (Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("Space");
if (Time.timeScale >= 0)
{
Debug.Log("> 0");
Time.timeScale = 0;
}
else
{
Debug.Log("= 0");
Time.timeScale = 1;
}
}
//up time scale to scroll to next panel quicker
if (Input.GetMouseButtonDown(0))
{
Time.timeScale = 5;
Debug.Log("left click");
}
//for skipping scene
if (Input.GetMouseButtonDown(1))
{
//StartCoroutine(LoadNewScene());
Debug.Log("right click");
StartCoroutine(LoadNewScene());
}
}
IEnumerator WaitForScene()
{
end = 13f;
cutSceneText.text = "Full Strip";
yield return new WaitForSeconds(2);
speed = 2.0f;
end = 3.5f;
Time.timeScale = 1;
cutSceneText.text = "Panel 1: No Dialogue. Close up of a few dead bodies in a trail / wood area";
targetLocation = new Vector3(0.06f, 1.51f, -1.0f);
yield return new WaitForSeconds(2);
Time.timeScale = 1;
cutSceneText.text = "Panel 2 : No Dialogue. Panel of full scene with Dead bodies and a group of people approaching";
targetLocation = new Vector3(9.02f, 1.78f, -1.0f);
end = 3.3f;
yield return new WaitForSeconds(2);
Time.timeScale = 1;
cutSceneText.text = "Panel 3 : Dialogue by random civilains person1-'Divine Spirits help us more bodies' person2-'this has been happening too often lately.' ";
targetLocation = new Vector3(0.00f, -6.50f, -1.0f);
end = 4f;
yield return new WaitForSeconds(2);
Time.timeScale = 1;
cutSceneText.text = "Panel 4: close up of PT while people still talk. person1-'How many times does this make in the past year?' person2;-'I've lost count.' PT coughs.";
targetLocation = new Vector3(5.80f, -6.50f, -1.0f);
yield return new WaitForSeconds(2);
Time.timeScale = 1;
cutSceneText.text = "Panel 5: civilians ruhing to PT. person1- 'Merciful lords and ladies someone's alive.";
targetLocation = new Vector3(12.60f, -6.00f, -1.0f);
yield return new WaitForSeconds(2);
Time.timeScale = 1;
cutSceneText.text = "Panel 6: Civilians picking him up. person1- 'Lets get this lucky basdard back to town.' Person2-'Has there ever been a surviour from one of these atrocities?'";
targetLocation = new Vector3(0.70f, -14.40f, -1.0f);
end = 3.2f;
yield return new WaitForSeconds(2);
Time.timeScale = 1;
cutSceneText.text = "Panel 6-8 PT geting taken away. person1-'No, Never'";
speed = 0.1f;
targetLocation = new Vector3(11.70f, -14.40f, -1.0f);
Time.timeScale = 1;
yield return new WaitForSeconds(3);
//for loading to main game
StartCoroutine(LoadNewScene());
}
IEnumerator LoadNewScene()
{
AsyncOperation async = SceneManager.LoadSceneAsync("StartArea");
// While the asynchronous operation to load the new scene is not yet complete, continue waiting until it's done.
while (!async.isDone)
{
yield return null;
}
}
}
<file_sep>/2dProject/Assets/scripts/DoorToNewScene.cs
using UnityEngine;
public class DoorToNewScene : MonoBehaviour
{
public string sceneToLoad;
void Update()
{
if (GameController.GameControllerSingle.questTravel)
{
GameController.GameControllerSingle.questTravel = false;
GameController.GameControllerSingle.loadScence(sceneToLoad);
PlayerController.PlayerControllerSingle.transform.position = Vector3.zero;
}
}
}
<file_sep>/2dProject/Assets/scripts/PlayerScripts/GameController.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using UnityEngine.SceneManagement;
public class GameController : MonoBehaviour
{
public int sideQuestCounter { get; set; }
public bool sideQuestBool { get; set; }
//for if game needs to load test
public bool dontLoadTheGame;
//all canvas elements
private CanvasGroup InvMenuCanvas;
private CanvasGroup StartMenuCanvas;
private CanvasGroup NotificationCanvas;
private CanvasGroup SkillMenuCanvas;
private CanvasGroup QuestMenuCanvas;
private CanvasGroup SelectBarCanvas;
private CanvasGroup MagicMenuCanvas;
//should get ref to this is start // change later
private Text NotificationTxt;
public bool questTravel { get; set; }
public string mapSeed { get; set; }
public static GameController GameControllerSingle;
void Awake()
{
if (GameControllerSingle == null)
{
DontDestroyOnLoad(gameObject);
GameControllerSingle = this;
}
else if (GameControllerSingle != this)
{
Destroy(gameObject);
}
if (GameLoader.GameLoaderSingle)
{
dontLoadTheGame = false;
Destroy(GameLoader.GameLoaderSingle.gameObject);
}
}
// Use this for initialization
void Start()
{
//don't destroy on load objects
DontDestroyOnLoad(GameObject.Find("Canvases"));
//DontDestroyOnLoad(GameObject.Find("WorldObject"));
//DontDestroyOnLoad(GameObject.Find("GrapplingHookParts"));
//assign skill functions
//jump skills
GameObject.Find("GrapplingHookSkill").GetComponent<Button>().onClick.AddListener(delegate { LearnGrapplingHookSkill(); });
GameObject.Find("HookResetJumps").GetComponent<Button>().onClick.AddListener(delegate { LearnHookResetJumps(); });
//grappling hook skills
GameObject.Find("DoubleJump").GetComponent<Button>().onClick.AddListener(delegate { LearnDoubleJump(); });
GameObject.Find("TripleJump").GetComponent<Button>().onClick.AddListener(delegate { LearnTripleJump(); });
//dash
GameObject.Find("DashSkill").GetComponent<Button>().onClick.AddListener(delegate { LearnDashSkill(); });
//melee skills
GameObject.Find("DashSkillMelee").GetComponent<Button>().onClick.AddListener(delegate { LearnDashSkillMelee(); });
//slide skill
GameObject.Find("SlideSkillLearn").GetComponent<Button>().onClick.AddListener(delegate { LearnSlideSkill(); });
GameObject.Find("SlideJumpSkill").GetComponent<Button>().onClick.AddListener(delegate { LearnSlideJumpSkill(); });
GameObject.Find("SlideSteerSkill").GetComponent<Button>().onClick.AddListener(delegate { LearnSlideSteerSkill(); });
//attract passive skill
GameObject.Find("AttractPassive").GetComponent<Button>().onClick.AddListener(delegate { LearnAttractPassive(); });
//assign buttons functions for menu
GameObject.Find("InventoryButton").GetComponent<Button>().onClick.AddListener(delegate { InventoryOnButton(); });
GameObject.Find("SkillsButton").GetComponent<Button>().onClick.AddListener(delegate { SkillMenuOnButton(); });
GameObject.Find("QuestButton").GetComponent<Button>().onClick.AddListener(delegate { QuestMenuOnButton(); });
GameObject.Find("MagicButton").GetComponent<Button>().onClick.AddListener(delegate { MagicMenuOnButton(); });
//if side quest counter is on
sideQuestBool = false;
//on all the time
NotificationCanvas = GameObject.Find("NotificationCanvas").GetComponent <CanvasGroup>();
//esc menu
StartMenuCanvas = GameObject.Find("StartMenuCanvas").GetComponent<CanvasGroup>();
//menu items
SelectBarCanvas = GameObject.Find("SelectBarCanvas").GetComponent<CanvasGroup>();
InvMenuCanvas = GameObject.Find("InvMenuCanvas").GetComponent<CanvasGroup>();
SkillMenuCanvas = GameObject.Find("SkillMenuCanvas").GetComponent<CanvasGroup>();
QuestMenuCanvas = GameObject.Find("QuestMenuCanvas").GetComponent<CanvasGroup>();
MagicMenuCanvas = GameObject.Find("MagicMenuCanvas").GetComponent<CanvasGroup>();
//set notification text
NotificationTxt = NotificationCanvas.transform.Find("Notification").GetComponent<Text>();
}
// Update is called once per frame
void Update()
{
//this is being called, why in update?
//Resources.UnloadUnusedAssets();
// Careful: For Mac users, ctrl + arrow is a bad idea
//toggle inventory on and off
if (Input.GetKeyDown(KeyCode.I))
{
InventoryOn();
}
//skill menu
if (Input.GetKeyDown(KeyCode.K))
{
SkillMenuOn();
}
//back menu
if (Input.GetKeyDown(KeyCode.Escape))
{
StartMenuCanvas.alpha = (StartMenuCanvas.alpha + 1) % 2;
StartMenuCanvas.interactable = !StartMenuCanvas.interactable;
StartMenuCanvas.blocksRaycasts = !StartMenuCanvas.blocksRaycasts;
}
//stop all action after this if the pointer is over the canvas
//EventSystem eventSystem = EventSystem.current;
//if (eventSystem.IsPointerOverGameObject())
//{
// return;
//}
}
void FixedUpdate()
{
//if (PlayerStats.PlayerStatsSingle.experiencePoints >= PlayerStats.PlayerStatsSingle.level * 15)
//{
// // text container
// StartCoroutine(ShowMessage("LEVEL UP NERD!", 2));
// //level character up
// PlayerStats.PlayerStatsSingle.level += 1;
// PlayerStats.PlayerStatsSingle.maxHealth += 2;
// PlayerStats.PlayerStatsSingle.health = PlayerStats.PlayerStatsSingle.maxHealth;
//}
}
//player item distance attract skill learn
public void LearnAttractPassive()
{
if (PlayerStats.PlayerStatsSingle.skillPoints > 0)
{
PlayerStats.PlayerStatsSingle.DecSkillPoints();
PlayerStats.PlayerStatsSingle.itemAttractDistance = 1000;
GameObject.Find("AttractPassive").GetComponent<Button>().image.color = Color.yellow;
GameObject.Find("AttractPassive").GetComponent<Button>().interactable = false;
}
}
public void LearnGrapplingHookSkill()
{
if (PlayerStats.PlayerStatsSingle.skillPoints > 0)
{
PlayerStats.PlayerStatsSingle.DecSkillPoints();
PlayerController.PlayerControllerSingle.grapplingHookSkill = true;
GameObject.Find("GrapplingHookSkill").GetComponent<Button>().image.color = Color.yellow;
GameObject.Find("GrapplingHookSkill").GetComponent<Button>().interactable = false;
GameObject.Find("HookResetJumps").GetComponent<Button>().interactable = true;
}
}
public void LearnHookResetJumps()
{
if (PlayerStats.PlayerStatsSingle.skillPoints > 0)
{
PlayerStats.PlayerStatsSingle.DecSkillPoints();
PlayerController.PlayerControllerSingle.hookResetJumpsSkill = true;
GameObject.Find("HookResetJumps").GetComponent<Button>().image.color = Color.yellow;
GameObject.Find("HookResetJumps").GetComponent<Button>().interactable = false;
}
}
public void LearnDoubleJump()
{
if (PlayerStats.PlayerStatsSingle.skillPoints > 0)
{
PlayerStats.PlayerStatsSingle.DecSkillPoints();
PlayerController.PlayerControllerSingle.jumpCounter = 2;
PlayerStats.PlayerStatsSingle.maxJumps = 2;
GameObject.Find("DoubleJump").GetComponent<Button>().image.color = Color.yellow;
GameObject.Find("DoubleJump").GetComponent<Button>().interactable = false;
GameObject.Find("TripleJump").GetComponent<Button>().interactable = true;
}
}
public void LearnTripleJump()
{
if (PlayerStats.PlayerStatsSingle.skillPoints > 0)
{
PlayerStats.PlayerStatsSingle.DecSkillPoints();
PlayerController.PlayerControllerSingle.jumpCounter = 3;
PlayerStats.PlayerStatsSingle.maxJumps = 3;
GameObject.Find("TripleJump").GetComponent<Button>().image.color = Color.yellow;
GameObject.Find("TripleJump").GetComponent<Button>().interactable = false;
}
}
public void LearnDashSkill()
{
if (PlayerStats.PlayerStatsSingle.skillPoints > 0)
{
PlayerStats.PlayerStatsSingle.DecSkillPoints();
PlayerController.PlayerControllerSingle.dashSkill = true;
GameObject.Find("DashSkill").GetComponent<Button>().image.color = Color.yellow;
GameObject.Find("DashSkill").GetComponent<Button>().interactable = false;
GameObject.Find("DashSkillMelee").GetComponent<Button>().interactable = true;
}
}
public void LearnDashSkillMelee()
{
if (PlayerStats.PlayerStatsSingle.skillPoints > 0)
{
PlayerStats.PlayerStatsSingle.DecSkillPoints();
PlayerController.PlayerControllerSingle.dashSkillMelee= true;
GameObject.Find("DashSkillMelee").GetComponent<Button>().image.color = Color.yellow;
GameObject.Find("DashSkillMelee").GetComponent<Button>().interactable = false;
}
}
public void LearnSlideSkill()
{
if (PlayerStats.PlayerStatsSingle.skillPoints > 0)
{
PlayerStats.PlayerStatsSingle.DecSkillPoints();
PlayerController.PlayerControllerSingle.slideSkill = true;
GameObject.Find("SlideSkillLearn").GetComponent<Button>().image.color = Color.yellow;
GameObject.Find("SlideSkillLearn").GetComponent<Button>().interactable = false;
GameObject.Find("SlideJumpSkill").GetComponent<Button>().interactable = true;
}
}
public void LearnSlideJumpSkill()
{
if (PlayerStats.PlayerStatsSingle.skillPoints > 0)
{
PlayerStats.PlayerStatsSingle.DecSkillPoints();
PlayerController.PlayerControllerSingle.slideJumpSkill = true;
GameObject.Find("SlideJumpSkill").GetComponent<Button>().image.color = Color.yellow;
GameObject.Find("SlideJumpSkill").GetComponent<Button>().interactable = false;
GameObject.Find("SlideSteerSkill").GetComponent<Button>().interactable = true;
}
}
public void LearnSlideSteerSkill()
{
if (PlayerStats.PlayerStatsSingle.skillPoints > 0)
{
PlayerStats.PlayerStatsSingle.DecSkillPoints();
PlayerController.PlayerControllerSingle.slideSteerSKill = true;
GameObject.Find("SlideSteerSkill").GetComponent<Button>().image.color = Color.yellow;
GameObject.Find("SlideSteerSkill").GetComponent<Button>().interactable = false;
}
}
public void InventoryOn()
{
//turn off other menu
SkillMenuCanvas.alpha = 0;
SkillMenuCanvas.interactable = false;
SkillMenuCanvas.blocksRaycasts = false;
QuestMenuCanvas.alpha = 0;
QuestMenuCanvas.interactable = false;
QuestMenuCanvas.blocksRaycasts = false;
MagicMenuCanvas.alpha = 0;
MagicMenuCanvas.interactable = false;
MagicMenuCanvas.blocksRaycasts = false;
//toggle on and off
InvMenuCanvas.alpha = (InvMenuCanvas.alpha + 1) %2;
InvMenuCanvas.interactable = !InvMenuCanvas.interactable;
InvMenuCanvas.blocksRaycasts = !InvMenuCanvas.blocksRaycasts;
//check if any menu item on
if (SkillMenuCanvas.alpha == 0 && QuestMenuCanvas.alpha == 0 && MagicMenuCanvas.alpha == 0 && InvMenuCanvas.alpha ==0)
{
SelectBarCanvas.alpha = 0;
SelectBarCanvas.interactable = false;
SelectBarCanvas.blocksRaycasts = false;
}
else
{
SelectBarCanvas.alpha = 1;
SelectBarCanvas.interactable = true;
SelectBarCanvas.blocksRaycasts = true;
}
}
public void SkillMenuOn()
{
//turn off other menu
InvMenuCanvas.alpha = 0;
InvMenuCanvas.interactable = false;
InvMenuCanvas.blocksRaycasts = false;
QuestMenuCanvas.alpha = 0;
QuestMenuCanvas.interactable = false;
QuestMenuCanvas.blocksRaycasts = false;
MagicMenuCanvas.alpha = 0;
MagicMenuCanvas.interactable = false;
MagicMenuCanvas.blocksRaycasts = false;
//toggle on and off
SkillMenuCanvas.alpha = (SkillMenuCanvas.alpha + 1) % 2;
SkillMenuCanvas.interactable = !SkillMenuCanvas.interactable;
SkillMenuCanvas.blocksRaycasts = !SkillMenuCanvas.blocksRaycasts;
//check if any menu item on
if (SkillMenuCanvas.alpha == 0 && QuestMenuCanvas.alpha == 0 && MagicMenuCanvas.alpha == 0 && InvMenuCanvas.alpha == 0)
{
SelectBarCanvas.alpha = 0;
SelectBarCanvas.interactable = false;
SelectBarCanvas.blocksRaycasts = false;
}
else
{
SelectBarCanvas.alpha = 1;
SelectBarCanvas.interactable = true;
SelectBarCanvas.blocksRaycasts = true;
}
}
public void QuestMenuOn()
{
//turn off other menu
SkillMenuCanvas.alpha = 0;
SkillMenuCanvas.interactable = false;
SkillMenuCanvas.blocksRaycasts = false;
InvMenuCanvas.alpha = 0;
InvMenuCanvas.interactable = false;
InvMenuCanvas.blocksRaycasts = false;
MagicMenuCanvas.alpha = 0;
MagicMenuCanvas.interactable = false;
MagicMenuCanvas.blocksRaycasts = false;
//toggle on and off
QuestMenuCanvas.alpha = (QuestMenuCanvas.alpha + 1) % 2;
QuestMenuCanvas.interactable = !QuestMenuCanvas.interactable;
QuestMenuCanvas.blocksRaycasts = !QuestMenuCanvas.blocksRaycasts;
//check if any menu item on
if (SkillMenuCanvas.alpha == 0 && QuestMenuCanvas.alpha == 0 && MagicMenuCanvas.alpha == 0 && InvMenuCanvas.alpha == 0)
{
SelectBarCanvas.alpha = 0;
SelectBarCanvas.interactable = false;
SelectBarCanvas.blocksRaycasts = false;
}
else
{
SelectBarCanvas.alpha = 1;
SelectBarCanvas.interactable = true;
SelectBarCanvas.blocksRaycasts = true;
}
}
public void MagicMenuOn()
{
//turn off other menu
SkillMenuCanvas.alpha = 0;
SkillMenuCanvas.interactable = false;
SkillMenuCanvas.blocksRaycasts = false;
InvMenuCanvas.alpha = 0;
InvMenuCanvas.interactable = false;
InvMenuCanvas.blocksRaycasts = false;
QuestMenuCanvas.alpha = 0;
QuestMenuCanvas.interactable = false;
QuestMenuCanvas.blocksRaycasts = false;
//toggle on and off
MagicMenuCanvas.alpha = (MagicMenuCanvas.alpha + 1) % 2;
MagicMenuCanvas.interactable = !MagicMenuCanvas.interactable;
MagicMenuCanvas.blocksRaycasts = !MagicMenuCanvas.blocksRaycasts;
//check if any menu item on
if (SkillMenuCanvas.alpha == 0 && QuestMenuCanvas.alpha == 0 && MagicMenuCanvas.alpha == 0 && InvMenuCanvas.alpha == 0)
{
SelectBarCanvas.alpha = 0;
SelectBarCanvas.interactable = false;
SelectBarCanvas.blocksRaycasts = false;
}
else
{
SelectBarCanvas.alpha = 1;
SelectBarCanvas.interactable = true;
SelectBarCanvas.blocksRaycasts = true;
}
}
public void InventoryOnButton()
{
if (InvMenuCanvas.alpha == 0)
{
InventoryOn();
}
}
public void SkillMenuOnButton()
{
if (SkillMenuCanvas.alpha == 0)
{
SkillMenuOn();
}
}
public void QuestMenuOnButton()
{
if (QuestMenuCanvas.alpha == 0)
{
QuestMenuOn();
}
}
public void MagicMenuOnButton()
{
if (MagicMenuCanvas.alpha == 0)
{
MagicMenuOn();
}
}
//for quick message aboce character head
public IEnumerator ShowMessage(string message, float delay)
{
NotificationCanvas.alpha = (NotificationCanvas.alpha + 1) % 2;
NotificationTxt.text = message;
yield return new WaitForSeconds(delay);
NotificationCanvas.alpha = (NotificationCanvas.alpha + 1) % 2;
}
//void OnGUI()
//{
// GUI.Label(new Rect(30, -3, 100, 30), "Health: " + PlayerStats.PlayerStatsSingle.health);
// if (GUI.Button(new Rect(Screen.width / 2 + Screen.width / 4, Screen.height / 2, 100, 30), "Save"))
// {
// SavePlayerData();
// }
// if (GUI.Button(new Rect(Screen.width / 2 + Screen.width / 4, Screen.height / 2 - 40, 100, 30), "Load"))
// {
// LoadPlayerData();
// //MapGenerator.MapGeneratorSingle.LoadMap();
// }
//}
//have to put in my hand for load on click field in canvas
public void SavePlayerData()
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/playerInfo.dat");
PlayerData playerDat = new PlayerData();
//Player info
playerDat.health = PlayerStats.PlayerStatsSingle.health;
playerDat.maxHealth = PlayerStats.PlayerStatsSingle.maxHealth;
playerDat.experiencePoints = PlayerStats.PlayerStatsSingle.experiencePoints;
playerDat.level = PlayerStats.PlayerStatsSingle.level;
bf.Serialize(file, playerDat);
file.Close();
}
public void SaveMapData()
{
Scene scene = SceneManager.GetActiveScene();
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/" + scene.name + ".dat");
levelInformation mapData = new levelInformation();
//map info
mapData.numMaps = MapGenerator.MapGeneratorSingle.numMaps;
mapData.MapInfo = MapGenerator.MapGeneratorSingle.MapInfo;
mapData.doorConnectionDictionary = GameData.GameDataSingle.doorConnectionDictionary;
mapData.mapSeed = GameData.GameDataSingle.mapSeed;
for (int x = 0; x < GameData.GameDataSingle.mapSets.Count; x++)
{
mapData.mapSetsX.Add(GameData.GameDataSingle.mapSets[x].x);
mapData.mapSetsY.Add(GameData.GameDataSingle.mapSets[x].y);
}
bf.Serialize(file, mapData);
file.Close();
}
public void LoadPlayerData()
{
if (File.Exists(Application.persistentDataPath + "/playerInfo.dat"))
{
Debug.Log("load called");
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/playerInfo.dat", FileMode.Open);
PlayerData playerDat = (PlayerData)bf.Deserialize(file);
file.Close();
//player info
PlayerStats.PlayerStatsSingle.health = playerDat.health;
PlayerStats.PlayerStatsSingle.maxHealth = playerDat.maxHealth;
PlayerStats.PlayerStatsSingle.experiencePoints = playerDat.experiencePoints;
PlayerStats.PlayerStatsSingle.level = playerDat.level;
////map info
//MapGenerator.MapGeneratorSingle.numMaps = playerDat.numMaps;
//MapGenerator.MapGeneratorSingle.MapInfo = playerDat.MapInfo;
//PlayerStats.PlayerStatsSingle.MapInfo = playerDat.MapInfo;
//GameData.GameDataSingle.doorConnectionDictionary = playerDat.doorConnectionDictionary;
//GameData.GameDataSingle.mapSeed = playerDat.mapSeed;
////load map
//for (int x = 0; x < playerDat.mapSetsX.Count; x++)
//{
// GameData.GameDataSingle.mapSets.Add(new Vector2(playerDat.mapSetsX[x], playerDat.mapSetsY[x]));
//}
}
else
{
Debug.Log("Error with player data load");
}
}
public void LoadMapData()
{
Scene scene = SceneManager.GetActiveScene();
if (File.Exists(Application.persistentDataPath + "/" + scene.name + ".dat"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/" + scene.name + ".dat", FileMode.Open);
levelInformation mapData = (levelInformation)bf.Deserialize(file);
file.Close();
//map info
MapGenerator.MapGeneratorSingle.numMaps = mapData.numMaps;
MapGenerator.MapGeneratorSingle.MapInfo = mapData.MapInfo;
PlayerStats.PlayerStatsSingle.MapInfo = mapData.MapInfo;
GameData.GameDataSingle.doorConnectionDictionary = mapData.doorConnectionDictionary;
GameData.GameDataSingle.mapSeed = mapData.mapSeed;
//load map
for (int x = 0; x < mapData.mapSetsX.Count; x++)
{
GameData.GameDataSingle.mapSets.Add(new Vector2(mapData.mapSetsX[x], mapData.mapSetsY[x]));
}
}
else
{
Debug.Log("Error with map data load");
}
}
public void loadScence(string sceneName)
{
RemoveEveryingOnMap();
StartCoroutine(LoadNewScene(sceneName));
}
public void RemoveEveryingOnMap()
{
foreach (Transform child in WorldObjects.WorldObjectsSingle.transform)
{
foreach (Transform child2 in child)
{
Destroy(child2.gameObject);
}
}
}
IEnumerator LoadNewScene(string sceneName)
{
PlayerController.PlayerControllerSingle.LockPosition();
//load functions
AsyncOperation async = SceneManager.LoadSceneAsync(sceneName);
// While the asynchronous operation to load the new scene is not yet complete, continue waiting until it's done.
while (!async.isDone)
{
yield return null;
}
//unlock player
PlayerController.PlayerControllerSingle.UnLockPosition();
PlayerController.PlayerControllerSingle.touchingDoor = false;
}
}
[System.Serializable]
public class PlayerData
{
//for PlayerStats
public int health;
public int maxHealth;
public int experiencePoints;
public int level;
}
[System.Serializable]
public class levelInformation
{
//for MapGenerator
public int numMaps { get; set; }
public Dictionary<string, MapInformation> MapInfo;
//for GameData
public Dictionary<string, string> doorConnectionDictionary;
public List<string> mapSeed = new List<string>();
public List<float> mapSetsX = new List<float>();
public List<float> mapSetsY = new List<float>();
}
[System.Serializable]
public class MapInformation
{
public int index { get; set; }
public int mapSet { get; set; }
public int width { get; set; }
public int height { get; set; }
public int randomFillPercent { get; set; }
public int passageLength { get; set; }
public int smoothness { get; set; }
public int squareSize { get; set; }
public int[,] map { get; set; }
public int[,] borderedMap { get; set; }
public List<float> possibleDoorLocationsX;
public List<float> possibleDoorLocationsY;
public List<float> doorLocationsX;
public List<float> doorLocationsY;
public List<int> doorType;
public List<float> enemyLocationsX;
public List<float> enemyLocationsY;
public List<float> turretLocationsX;
public List<float> turretLocationsY;
}
<file_sep>/2dProject/Assets/scripts/Items/Weapons/ShotMove.cs
using UnityEngine;
using System.Collections;
public class ShotMove : MonoBehaviour
{
private Vector3 mousePos;
public float speed = 8f;
void Start()
{
speed = Random.Range(6f, 10f);
Destroy(gameObject, 2);
transform.GetComponent<DamageOnCollision>().onCollide = onCollide;
Shoot();
}
void FixedUpdate()
{
// Apply movement to the rigidbody
transform.position += transform.right * speed * Time.deltaTime;
}
void onCollide()
{
Destroy(gameObject);
}
void Shoot()
{
//mousePos = Input.mousePosition;
mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePos += new Vector3(Random.Range(-.2f, .2f), Random.Range(-.2f, .2f), 0);
var dir = mousePos - transform.position;
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
}
<file_sep>/2dProject/Assets/scripts/Spells/MagicController.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class MagicController : MonoBehaviour
{
public GameObject MagicImagePrefab;
public Sprite DefaultImage;
private GameObject FromMagic;
private GameObject ToMagic;
//GameObject Attack;
//GameObject HotBarSlot1, HotBarSlot2, HotBarSlot3;
private Canvas canvas;
// Use this for initialization
void Start()
{
canvas = GetComponent<Canvas>();
//Vector2 position;
//RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform, Input.mousePosition, canvas.worldCamera, out position);
//position.Set(position.x, position.y);
//FromMagic.transform.position = canvas.transform.TransformPoint(position);
}
void Update()
{
if (FromMagic)
{
Vector2 position;
RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform, Input.mousePosition, canvas.worldCamera, out position);
position.Set(position.x, position.y);
FromMagic.transform.position = canvas.transform.TransformPoint(position);
}
if (Input.GetMouseButtonUp(0) && FromMagic)
{
if (!EventSystem.current.IsPointerOverGameObject(-1))
{
Destroy(FromMagic);
//hoverObject = null;
}
}
}
public void ClickMagic(GameObject clicked)
{
//if nothing is floating with the cursor and you clicked on empty slot
if (FromMagic == null && clicked.GetComponent<Image>().sprite.name.Contains("Inv Slot"))
{
Debug.Log("if");
}
//for clicking on somthing
else if (FromMagic == null)
{
//Debug.Log("else if 1");
if (clicked.name.Contains("Hotbar"))
{
//Debug.Log("else if 1 if");
FromMagic = Instantiate(MagicImagePrefab, GameObject.Find("HotbarCanvas").transform);
FromMagic.GetComponent<Image>().sprite = clicked.GetComponent<Image>().sprite;
FromMagic.name = clicked.name;
//FromMagic.transform.SetParent(GameObject.Find("MagicMenuCanvas").transform, true);
//FromMagic.GetComponent<Magic>().type = clicked.GetComponent<Magic>().type;
clicked.GetComponent<Image>().sprite = DefaultImage;
//for unassigning delegate functions if you move spell from hotbar slot
//Debug.Log(FromMagic.GetComponent<Image>().sprite.name);
AssignHotbarDelegate(clicked.name, "none", null, false);
}
else
{
FromMagic = Instantiate(MagicImagePrefab, GameObject.Find("HotbarCanvas").transform);
//Debug.Log("FromMagic = " + FromMagic.name);
//Debug.Log("clicked = " + clicked.name);
FromMagic.GetComponent<Image>().sprite = clicked.GetComponent<Image>().sprite;
FromMagic.name = clicked.name;
//FromMagic.transform.SetParent(GameObject.Find("MagicMenuCanvas").transform, true);
//Debug.Log("clicked.GetComponent<Magic>().type + " + clicked.GetComponent<Magic>().type);
//Debug.Log("FromMagic.GetComponent<Magic>().type + " + FromMagic.GetComponent<Magic>().type);
//FromMagic.GetComponent<Magic>().type = clicked.GetComponent<Magic>().type;
}
}
else if (ToMagic == null)
{
//Debug.Log("else if 2");
if (clicked.name.Contains("Hotbar"))
{
if (clicked.GetComponent<Image>().sprite.name.Contains("Inv Slot"))
{
//for assigning delegate functions
Debug.Log(FromMagic.GetComponent<Image>().sprite.name);
//assignhotbardelegate(clicked.name, FromMagic.GetComponent<Image>().sprite.name, true);
clicked.GetComponent<Image>().sprite = FromMagic.GetComponent<Image>().sprite;
//clicked.GetComponent<Magic>().type = FromMagic.GetComponent<Magic>().type;
//pass spell type
AssignHotbarDelegate(clicked.name, FromMagic.GetComponent<Image>().sprite.name, clicked.GetComponent<Magic>().type, true);
Destroy(FromMagic);
}
//for swaping place of items you clicked on
else
{
ToMagic = Instantiate(MagicImagePrefab, GameObject.Find("HotbarCanvas").transform);
//ToMagic.transform.SetParent(GameObject.Find("MagicMenuCanvas").transform, true);
ToMagic.GetComponent<Image>().sprite = FromMagic.GetComponent<Image>().sprite;
//ToMagic.GetComponent<Magic>().type = FromMagic.GetComponent<Magic>().type;
FromMagic.GetComponent<Image>().sprite = clicked.GetComponent<Image>().sprite;
//FromMagic.GetComponent<Magic>().type = clicked.GetComponent<Magic>().type;
clicked.GetComponent<Image>().sprite = ToMagic.GetComponent<Image>().sprite;
//clicked.GetComponent<Magic>().type = ToMagic.GetComponent<Magic>().type;
//for assigning delegate functions
//Debug.Log(ToMagic.GetComponent<Image>().sprite.name);
AssignHotbarDelegate(clicked.name, clicked.GetComponent<Image>().sprite.name, clicked.GetComponent<Magic>().type, true);
Destroy(ToMagic);
}
}
else
{
//destorying ig you click somewhere random
Destroy(FromMagic);
}
}
else
{
Debug.Log("else");
Destroy(FromMagic);
}
}
//for assigning hotkey methods in gamecontroller
void AssignHotbarDelegate(string hotbarName, string spellName, Enum type, bool on)
{
if (hotbarName.Contains("HotbarButtonOne"))
{
if (on)
{
PlayerController.PlayerControllerSingle.HotBarSlot1 = GameObject.Find(hotbarName).GetComponent<Magic>().Cast;
//SelectWeapon(spellName, ref GameController.GameControllerSingle.HotBarSlot1, ref HotBarSlot1);
}
else
{
//Destroy(HotBarSlot1);
PlayerController.PlayerControllerSingle.HotBarSlot1 = null;
}
}
else if (hotbarName.Contains("HotbarButtonTwo"))
{
if (on)
{
PlayerController.PlayerControllerSingle.HotBarSlot2 = GameObject.Find(hotbarName).GetComponent<Magic>().Cast;
// SelectWeapon(spellName, ref GameController.GameControllerSingle.HotBarSlot2, ref HotBarSlot2);
}
else
{
//Destroy(HotBarSlot2);
PlayerController.PlayerControllerSingle.HotBarSlot2 = null;
}
}
else if (hotbarName.Contains("HotbarButtonThree"))
{
if (on)
{
PlayerController.PlayerControllerSingle.HotBarSlot3 = GameObject.Find(hotbarName).GetComponent<Magic>().Cast;
// SelectWeapon(spellName, ref GameController.GameControllerSingle.HotBarSlot3, ref HotBarSlot3);
}
else
{
//Destroy(HotBarSlot3);
PlayerController.PlayerControllerSingle.HotBarSlot3 = null;
}
}
}
}
| 0418a239fca7f36e40e7065bdffbae6e9fc00b20 | [
"C#",
"INI"
] | 79 | C# | gingerben93/2d-Project | 624618c8ab3a4e2e09527aaa63c544b90f6decb8 | 0c7920682728535297b21e034a5e2e592a1598e2 |
refs/heads/master | <repo_name>jsohan/DarknetAnalysis-CyberSecurity<file_sep>/Network/Header.h
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <pcap.h>
#include <stdlib.h>
//"Simple" struct for TCP
struct tcp_header {
u_short sport; // Source port
u_short dport; // Destination port
u_int seqnum; // Sequence Number
u_int acknum; // Acknowledgement number
u_char th_off; // Header length
u_char flags; // packet flags
u_short win; // Window size
u_short crc; // Header Checksum
u_short urgptr; // Urgent pointer...still don't know what this is...
};
/* 4 bytes IP address */
struct ip_address{
u_char byte1;
u_char byte2;
u_char byte3;
u_char byte4;
bool operator==(const ip_address& a) const
{
return (byte1 == a.byte1 && byte2 == a.byte2 && byte3 == a.byte3 && byte4 == a.byte4);
}
bool operator!=(const ip_address& a) const
{
return (byte1 != a.byte1 || byte2 != a.byte2 || byte3 != a.byte3 || byte4 != a.byte4);
}
};
/* IPv4 header */
struct ip_header{
u_char ver_ihl; // Version (4 bits) + Internet header length (4 bits)
u_char tos; // Type of service
u_short tlen; // Total length
u_short identification; // Identification
u_short flags_fo; // Flags (3 bits) + Fragment offset (13 bits)
u_char ttl; // Time to live
u_char proto; // Protocol
u_short crc; // Header checksum
ip_address saddr; // Source address
ip_address daddr; // Destination address
u_int op_pad; // Option + Padding
};
//Funt Prototype
//packet handler
void my_packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data);
void print_all();
void ip_query();
void probe_query();
int sub_string(char *a);
void printer(int k);
//global Var
int count = 0;
int arrayVal = 0;
ip_address sipArray[20];
struct ip_address ipstart;
struct ip_address ipend;
int flag = 0;
int max = 10000;
char ptype[10000][14];
//array of ip addresses from suspected probe packets
ip_address *suspectip = (ip_address *)malloc(max * sizeof(ip_address));
//array of their destination ip addresses
ip_address *destip = (ip_address *)malloc(max * sizeof(ip_address));
//array of their destination ports
u_short *destport = (u_short *)malloc(max * sizeof(u_short));
//array of how many packets have that source ip
int *packets = (int *)malloc(max * sizeof(int));
//array of what type of prob it is
//0=horizontal
//1=vertical
//2=strobe
int *type = (int *)malloc(max * sizeof(int));
//array of probe start time
timeval *pkstart = (timeval*)malloc(max * sizeof(timeval));
//array of probe end time
timeval *pkend = (timeval*)malloc(max * sizeof(timeval));
//current size of dynamic array
int arraySize = 0;
//------------------------------------------
//array of ip addresses from suspected probe packets
ip_address *tsuspectip = (ip_address *)malloc(max * sizeof(ip_address));
//array of their destination ip addresses
ip_address *tdestip = (ip_address *)malloc(max * sizeof(ip_address));
//array of their destination ports
u_short *tdestport = (u_short *)malloc(max * sizeof(u_short));
//array of how many packets have that source ip
int *tpackets = (int *)malloc(max * sizeof(int));
//array of what type of prob it is
//0=horizontal
//1=vertical
//2=strobe
int *ttype = (int *)malloc(max * sizeof(int));
//array of probe start time
//array of probe start time
timeval *tpkstart = (timeval*)malloc(max * sizeof(timeval));
//array of probe end time
timeval *tpkend = (timeval*)malloc(max * sizeof(timeval));<file_sep>/README.md
# Description
Darknet is a term used to describe a portion of IP addresses that are purposefully unused in a networking system. Because this portion of the network is supposedly unused there should not be any traffic back and forth. By monitoring this section, we can use it as a trap to detect potential probs searching for open IPs and ports that can be used to attack the system such as a DDoS attack.
This program takes a Pcap file that has been monitoring a darknet trap on a network system and analyses it for potential probs.
- Proven to parse through 96,000,000 data packets (6.45 GB) in 6 minutes.
### Probe Types Scanned For:
- Horizontal
- Vertical
- Strobe
# Instillation
1. Download repository and place inside your projects folder for your complier (Visual studio recommended).
2. Download the sample [pcap file](https://drive.google.com/open?id=1jWuCKoDL5kHzjsJhS9TyHVh4abY_fflo "Google Drive") (contailing 2 million data packets).
3. Place this pcap file within the “Network” folder.
- If using your own pcap file, remember to format the file as libcap. You can do this by using "editcap" in comand line. This comes with wireshark.
editcap -F libpcap <filename> <newFileName>(.pcap)
4. Open the project, build and run it.
# UI
After the file is uploaded you are able to:
- View all suspect IP address
- Query the suspect IPs for a spcefic IP address
- Filter the suspect IPs by a specific probe type
<file_sep>/Network/Source.cpp
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <pcap.h>
#include <stdlib.h>
#include "Header.h"
int pkcounter = 0;
int main(int argc, char *argv[]) {
pcap_t *handle;
char error_buffer[PCAP_ERRBUF_SIZE];
char packet_filter[] = "ip and tcp";
handle = pcap_open_offline("new.pcap", error_buffer);
if (handle == NULL){
printf(error_buffer);
return 0;
}
//loops through pcap file one time
//each Data packet passes through the fucntion 'my_packet_handler'
printf("Uploading file...\n");
pcap_loop(handle, 0, my_packet_handler, NULL);
pcap_close(handle);
printf("\n Complete Packet Count: %d\n", count);
// filter for the probe IP array
int s = 0;
for (int y = 0; y < arraySize; y++){
if (packets[y] > 5 && type[y] != 5){
tsuspectip[s] = suspectip[y];
tdestip[s] = destip[y];
tdestport[s] = destport[y];
tpackets[s] = packets[y];
tpkstart[s] = pkstart[y];
tpkend[s] = pkend[y];
ttype[s] = type[y];
if (type[y] == 0){
strcpy(ptype[s], "Horizontal");
}
if (type[y] == 1){
strcpy(ptype[s], "Vertical");
}
if (type[y] == 2){
strcpy(ptype[s], "Strobe ");
}
s++;
}
}
suspectip = tsuspectip;
destip = tdestip;
destport = tdestport;
packets = tpackets;
pkstart = tpkstart;
pkend = tpkend;
type = ttype;
arraySize = s;
//loop for the UI
int exit = 0;
while (exit == 0){
printf("\n____________________________________________________________________________________________________________\n\n");
printf("The System has detected %d probes\n", arraySize);
printf("<1 = List all probe info> \t <2 = Query by IP address> \t <3 = Query by Probe type> \t <4 = Exit>\n");
int a = 0;
scanf("%d", &a);
printf("\nYou entered: %d\n", a);
if (a == 1){
print_all();
}
if (a == 2){
ip_query();
}
if (a == 3){
probe_query();
}
if (a == 4){
break;
}
}
free(suspectip);
free(destip);
free(destport);
free(packets);
free(pkstart);
free(pkend);
free(type);
return 0;
}
//packet handler
// get packet info and sorts it accordingly
void my_packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data) {
struct tm ltime;
char timestr[16];
ip_header *ih;
tcp_header *th;
u_int ip_len;
u_short sport, dport;
time_t local_tv_sec;
count++;
/* convert the timestamp to readable format */
local_tv_sec = header->ts.tv_sec;
localtime_s(<ime, &local_tv_sec);
strftime(timestr, sizeof timestr, "%H:%M:%S", <ime);
/* print timestamp and length of the packet */
//printf("%s.%.6d len:%d ", timestr, header->ts.tv_usec, header->len);
/* retireve the position of the ip header */
ih = (ip_header *)(pkt_data +
14); //length of ethernet header
/* retireve the position of the tcp header */
ip_len = (ih->ver_ihl & 0xf) * 4;
th = (tcp_header *)((u_char *)ih + ip_len);
// convert from network byte order to host byte order
sport = ntohs(th->sport);
dport = ntohs(th->dport);
ip_address current = ih->saddr;
// checks if the aray had duplicates in it_______________________________________
int ipcount = 0;
if (count > 16){
for (int i = 0; i < 15; i++){
if (sipArray[i] == current){
ipcount++;
if (ipcount > 3){
break;
}
}
}
}
sipArray[arrayVal] = ih->saddr;
//enters values into suspectipip array
if (ipcount > 3)
{
//expands arrays if they get to big
if (arraySize >= 9999){
max = max + 10000;
//( *)realloc(, max * sizeof());
suspectip = (ip_address *)realloc(suspectip, max * sizeof(ip_address));
destip = (ip_address *)realloc(destip, max * sizeof(ip_address));
destport = (u_short*)realloc(destport, max * sizeof(u_short));
packets = (int*)realloc(packets, max * sizeof(int));
type = (int*)realloc(type, max * sizeof(int));
pkstart = (timeval*)realloc(pkstart, max * sizeof(timeval));
pkend = (timeval*)realloc(pkend, max * sizeof(timeval));
}
//if array is empty it initializes its first value
if (arraySize == 0){
suspectip[arraySize] = ih->saddr;
destip[arraySize] = ih->daddr;
destport[arraySize] = dport;
packets[arraySize] = 1;
pkstart[arraySize] = header->ts;
pkend[arraySize] = header->ts;
type[arraySize] = 5;
arraySize++;
}
//if not then it checks the array to see if the suspect source ip has been added before
else {
int temp = 0;
for (int j = 0; j < arraySize; j++){
if (suspectip[j] == ih->saddr){
packets[j]++;
pkend[j] = header->ts;
if (!(destip[j] == ih->daddr) && type[j] != 2)
{
type[j] = 0;
}
if (!(destport[j] == dport) && type[j] != 2)
{
type[j] = 1;
}
if (!(destport[j] == dport) && !(destip[j] == ih->daddr))
{
type[j] = 2;
}
temp = 1;
}
}
if (temp == 0){
suspectip[arraySize] = ih->saddr;
destip[arraySize] = ih->daddr;
destport[arraySize] = dport;
packets[arraySize] = 1;
pkstart[arraySize] = header->ts;
pkend[arraySize] = header->ts;
type[arraySize] = 5;
arraySize++;
}
}
}
if (count == pkcounter + 1000000){
printf("Packets Processed: %d...\n", count);
printf("Suspect Ips: %d...\n\n", arraySize);
int s = 0;
for (int y = 0; y < arraySize; y++){
if (packets[y] > 5 && type[y] != 5){
tsuspectip[s] = suspectip[y];
tdestip[s] = destip[y];
tdestport[s] = destport[y];
tpackets[s] = packets[y];
tpkstart[s] = pkstart[y];
tpkend[s] = pkend[y];
ttype[s] = type[y];
s++;
}
}
suspectip= tsuspectip;
destip = tdestip;
destport = tdestport;
packets = tpackets;
pkstart = tpkstart;
pkend = tpkend;
type = ttype;
arraySize = s;
pkcounter = pkcounter + 1000000;
}
arrayVal++;
if (arrayVal == 15){
arrayVal = 0;
}
}
//prints all items in the array
void print_all(){
for (int k = 0; k < arraySize; k++){
printer(k);
}
}
//asks for an ip and finds it in the array if its there
void ip_query(){
int exit = 0;
while (exit == 0){
printf("\n____________________________________________________________________________________________________________\n\n");
printf("\nEnter Desired IP address in four seperate parts pressing enter after each \n(EX:part1.part2.part3.part4 ---> part1 *Enter part2 *Enter part3 *Enter part4 *Enter)\n");
ip_address temp;
int num = 0;
scanf("%d", &temp.byte1);
if (temp.byte1 == 1){
break;
}
scanf("%d", &temp.byte2);
if (temp.byte2 == 1){
break;
}
scanf("%d", &temp.byte3);
if (temp.byte3 == 1){
break;
}
scanf("%d", &temp.byte4);
if (temp.byte4 == 1){
break;
}
printf("\nYou Entered: %d.%d.%d.%d\n\n",
temp.byte1,
temp.byte2,
temp.byte3,
temp.byte4);
for (int k = 0; k < arraySize; k++){
if (temp == suspectip[k]){
num++;
printer(k);
}
}
if (num == 0){
printf("\nIP adress not found\n");
}
printf("\n____________________________________________________________________________________________________________\n\n");
printf("\n< 1 = Query another IP adress > < 2 = Go back >\n");
int a = 0;
scanf("%d", &a);
if (a == 2){
break;
}
else if (a == 1){}
else{
printf("ERROR: Wrong Command");
break;
}
}
}
//asks for a prob type to filter the array by
void probe_query(){
int exit = 0;
while (exit == 0){
printf("\n____________________________________________________________________________________________________________\n\n");
printf("\n<1 = List all Horizontal> \t <2 = List all Vertical> \t <3 = List all strobe> \t <4 = Exit>\n");
char t[14];
int a = 0;
scanf("%d", &a);
if (a>0 && a<4){
for (int k = 0; k < arraySize; k++){
if ((a-1) == type[k])
{
printer(k);
}
}
}
else{
break;
}
}
}
int sub_string(char *a){
int re = 0;
char holda[3];
int ina;
//hours
memcpy(&holda, &a[0], 2);
holda[2] = '\0';
ina = atol(holda);
re = re + (ina * 60 * 60);
//mins
memcpy(&holda, &a[3], 2);
holda[2] = '\0';
ina = atol(holda);
re = re + (ina) * 60;
//sec
memcpy(&holda, &a[6], 2);
holda[2] = '\0';
ina = atol(holda);
re = re + (ina);
return re;
}
void printer(int k){
struct tm ltime;
struct tm ltime1;
time_t local_tv_sec;
time_t local_tv_sec1;
char start[20];
char end[20];
local_tv_sec = pkstart[k].tv_sec;
localtime_s(<ime, &local_tv_sec);
strftime(start, sizeof start, "%H:%M:%S", <ime);
local_tv_sec1 = pkend[k].tv_sec;
localtime_s(<ime1, &local_tv_sec1);
strftime(end, sizeof end, "%H:%M:%S", <ime1);
//printf("Source IP: %d.%d.%d.%d \t pribe type: %d \t start: %s \t end: %s \t rate: %d\n",
float s = (pkstart[k].tv_usec);
s = s *.000001;
float e = pkend[k].tv_usec;
e = e *.000001;
int tstart = sub_string(start);
int tend = sub_string(end);
s = s + tstart;
e = e + tend;
float temp = (e - s);
if (temp <= -1){
temp = 86400 + temp;
}
printf("Src IP: %d.%d.%d.%d\t Probe type: %s \t start: %s \t end: %s \t Pakets per second: %.6f\n",
suspectip[k].byte1,
suspectip[k].byte2,
suspectip[k].byte3,
suspectip[k].byte4,
ptype[k],
start,
end,
packets[k] / temp);
} | c141ab5c3db2aa888ed58fed3a026bda33aa861e | [
"Markdown",
"C",
"C++"
] | 3 | C | jsohan/DarknetAnalysis-CyberSecurity | 594ba526c675a0c0102df2cdcc697895882f0193 | e17862f5ce11f3639ee0f04ae51be6aa8f188833 |
refs/heads/master | <file_sep>$(function () {
// function wait(ms)
// {
// var d = new Date();
// var d2 = null;
// do { d2 = new Date(); }
// while(d2-d < ms);
// }
//
// var text = $('.type-erase-animation').data('text');
// var i = 0;
// var typeEarse = true;
// setInterval(async function(){
// // $('.type-erase-animation').append(text.charAt(i++));
// var t = $(".type-erase-animation").text();
// if(typeEarse){
// $('.type-erase-animation').text(t + text.charAt(i++));
// if(i >= text.length){
// typeEarse = false;
// $('.blink-underscore').css({
// marginLeft: '-6%',
// });
// }
// }else{
// $('.type-erase-animation').text(t.slice(0, i--));
// if(i < 0){
// typeEarse = true;
// $('.blink-underscore').css({
// marginLeft: '0',
// });
// }
// }
// // alert(i);
// }, 150);
});<file_sep># jainshailesh.me
| 193eb2fd2ee2e69f0d456920ab0f900b115a7a37 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | ShailuJain/Resume | f5fe142c6b1f21506fbb1a4549d1ba324cd1788b | 9e56711224209114ac6501596deaaba3697ef77e |
refs/heads/main | <repo_name>shubhra-g/Medical_Assistant<file_sep>/Medical/src/Input/ShowOutput.java
package Input;
import java.io.File; // Import the File class
import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Properties;
import java.util.Scanner; // Import the Scanner class to read text files
class ShowOutput {
Properties prop = new Properties();
void Diagnosis(String symp) {
// list of diseases
String diseases = symp;
String d1 = new String("heart attack");
String d2 = new String("pneumonia");
String d3 = new String("lung cancer");
String d4 = new String("bladder diseases");
String d5 = new String("liver diseases");
String d6 = new String("skin cancer");
String d7 = new String("headache disorder");
String d8 = new String("osteoatharitis");
String d9 = new String("anorexia nervosa");
String d10 = new String("gallstones");
String[] data = new String[8];
// logic to print appropriate disease
if (diseases.equals(d1)) {
try { //to read data from file
File myObj = new File("../Medical/txt/diseases/heart attack.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
for (int i = 0; i < 8; i++) {
data[i] = myReader.nextLine();
System.out.println(data[i]);
}
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
if (diseases.equals(d2)) {
try {
File myObj = new File("../Medical/txt/diseases/pneumonia.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
for (int i = 0; i < 8; i++) {
data[i] = myReader.nextLine();
System.out.println(data[i]);
}
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
if (diseases.equals(d3)) {
try {
File myObj = new File("../Medical/txt/diseases/lung cancer.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
for (int i = 0; i < 8; i++) {
data[i] = myReader.nextLine();
System.out.println(data[i]);
}
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
if (diseases.equals(d4)) {
try {
File myObj = new File("../Medical/txt/diseases/bladder diseases.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
for (int i = 0; i < 8; i++) {
data[i] = myReader.nextLine();
System.out.println(data[i]);
}
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
if (diseases.equals(d5)) {
try {
File myObj = new File("../Medical/txt/diseases/liver diseases.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
for (int i = 0; i < 8; i++) {
data[i] = myReader.nextLine();
System.out.println(data[i]);
}
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
if (diseases.equals(d6)) {
try {
File myObj = new File("../Medical/txt/diseases/skin cancer.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
for (int i = 0; i < 8; i++) {
data[i] = myReader.nextLine();
System.out.println(data[i]);
}
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
if (diseases.equals(d7)) {
try {
File myObj = new File("../Medical/txt/diseases/headache disorder.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
for (int i = 0; i < 8; i++) {
data[i] = myReader.nextLine();
System.out.println(data[i]);
}
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
if (diseases.equals(d8)) {
try {
File myObj = new File("../Medical/txt/diseases/osteoatharitis.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
for (int i = 0; i < 8; i++) {
data[i] = myReader.nextLine();
System.out.println(data[i]);
}
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
if (diseases.equals(d9)) {
try {
File myObj = new File("../Medical/txt/diseases/anorexia nervosa.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
for (int i = 0; i < 8; i++) {
data[i] = myReader.nextLine();
System.out.println(data[i]);
}
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
if (diseases.equals(d10)) {
try {
File myObj = new File("../Medical/txt/diseases/gallstones.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNext()) {
for (int i = 0; i < 8; i++) {
data[i] = myReader.nextLine();
System.out.println(data[i]);
}
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
void AddSymptoms(String symp) {
String symptom = symp;
String d1 = new String("chest pain");
String d2 = new String("shortness of breathe");
String d3 = new String("cough");
String d4 = new String("vomiting");
String d5 = new String("fatique");
String d6 = new String("sweating");
String d7 = new String("loss of appetite");
String d8 = new String("unconciousness");
String d9 = new String("fainting");
String d10 = new String("headache");
String[] data = new String[4];
if (symptom.equals(d1)) {
try { //to read data from file
File myObj = new File("../Medical/txt/symptom/chest pain.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
for (int i = 0; i < 4; i++) {
data[i] = myReader.nextLine();
System.out.println(data[i]);
}
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
if (symptom.equals(d2)) {
try {
File myObj = new File("../Medical/txt/symptom/shortness of breathe.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
for (int i = 0; i < 4; i++) {
data[i] = myReader.nextLine();
System.out.println(data[i]);
}
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
if (symptom.equals(d3)) {
try {
File myObj = new File("../Medical/txt/symptom/cough.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
for (int i = 0; i < 4; i++) {
data[i] = myReader.nextLine();
System.out.println(data[i]);
}
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
if (symptom.equals(d4)) {
try {
File myObj = new File("../Medical/txt/symptom/vomiting.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
for (int i = 0; i < 4; i++) {
data[i] = myReader.nextLine();
System.out.println(data[i]);
}
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
if (symptom.equals(d5)) {
try {
File myObj = new File("../Medical/txt/symptom/fatique.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
for (int i = 0; i < 4; i++) {
data[i] = myReader.nextLine();
System.out.println(data[i]);
}
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
if (symptom.equals(d6)) {
try {
File myObj = new File("../Medical/txt/symptom/sweating.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
for (int i = 0; i < 4; i++) {
data[i] = myReader.nextLine();
System.out.println(data[i]);
}
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
if (symptom.equals(d7)) {
try {
File myObj = new File("../Medical/txt/symptom/loss of appetite.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
for (int i = 0; i < 4; i++) {
data[i] = myReader.nextLine();
System.out.println(data[i]);
}
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
if (symptom.equals(d8)) {
try {
File myObj = new File("../Medical/txt/symptom/unconciousness.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
for (int i = 0; i < 4; i++) {
data[i] = myReader.nextLine();
System.out.println(data[i]);
}
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
if (symptom.equals(d9)) {
try {
File myObj = new File("../Medical/txt/symptom/fainting.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
for (int i = 0; i < 4; i++) {
data[i] = myReader.nextLine();
System.out.println(data[i]);
}
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
if (symptom.equals(d10)) {
try {
File myObj = new File("../Medical/txt/symptom/headache.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
for (int i = 0; i < 4; i++) {
data[i] = myReader.nextLine();
System.out.println(data[i]);
}
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
} | e058bd52f4b84e8788525328efd6ed6bc1651290 | [
"Java"
] | 1 | Java | shubhra-g/Medical_Assistant | 487b241e7783a2607c050e8101656e07f7f51f0c | 1dcd384c3158e0ee7f31448dbb09c66817e53ad3 |
refs/heads/master | <repo_name>kdrnaik24/Kedar<file_sep>/Group 2 JAVA FRTP2016/cybage net/src/cybagenetpackage/DisplayBookDetails.java
package cybagenetpackage;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
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 DatabaseConnection.MyConnection;
@WebServlet("/DisplayBookDetails")
public class DisplayBookDetails extends HttpServlet {
private static final long serialVersionUID = 1L;
public DisplayBookDetails() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session=request.getSession();
int n=Integer.parseInt(request.getParameter("radio"));
session.setAttribute("bookid",n);
PrintWriter out = response.getWriter();
out.println("<div align=\"center\">");
out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"CSS/RemoveBook.css\">");
response.setContentType("text/html");
String loginuser= session.getAttribute("loginuser").toString();
response.getWriter().append("<h1>Hello"+loginuser+"</h1>");
out.println("<html><body>");
MyConnection c=new MyConnection();
Connection con;
try
{
con = c.connect();
Statement st = null;
String insertQuery = "SELECT distinct b.BookId, b.BookName,b.AuthorName,r.description,u.name"
+ " FROM book b join user_review ur on b.BookId=ur.bookid"
+ " join review r on r.reviewid=ur.reviewid join user u on u.userid=ur.userid"
+ " where b.BookId="+n;
st=con.createStatement();
ResultSet rs= st.executeQuery(insertQuery);
out.println(" <form action=\"AddReviewServlet\" name=\"myForm\" method=\"get \" > ");
out.println("<table border=1 width=50% height=25%>");
String radio="";
out.println("<tr><th>Book Name</th><th>Author Name</th><th>Review</th><th>Reviewed By</th><tr>");
if(!rs.next())
{
response.sendRedirect("FirstReview.html");
}
else
{
while (rs.next()) {
String a = rs.getString("BookName");
String bn = rs.getString("AuthorName");
String review=rs.getString("description");
String user=rs.getString("name");
int id=rs.getInt("BookId");
radio=""+id;
//out.print("<tr><td><input type='radio' name='radio' value='"+radio+"' > </td></tr>");
out.println("<tr><td>"+" <input type='radio' name='radio' value='"+radio+"' required> "+ a + "</td><td>" + bn + "</td><td>" + review + "</td><td>" + user + "</td></tr>");
}
out.println("</table>");
out.println("<textarea rows=\" 5\" cols=\" 40 \" name='review' required=\"required\"> </textarea><br><br>");
out.println("<input type='submit' value='Add Review' >");
out.print("</form>");
out.println("</div>");
out.println("</html></body>");
con.close();
}
}
catch (Exception e) {
out.println(""+e);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
<file_sep>/Fianal Upadated project with CSS/cybage net/src/cybagenetpackage/DisplayBookDetails.java
package cybagenetpackage;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
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 DatabaseConnection.MyConnection;
@WebServlet("/DisplayBookDetails")
public class DisplayBookDetails extends HttpServlet {
private static final long serialVersionUID = 1L;
public DisplayBookDetails() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session=request.getSession();
int n=Integer.parseInt(request.getParameter("radio"));
session.setAttribute("bookid",n);
PrintWriter out = response.getWriter();
out.println("<div align=\"center\">");
out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"CSS/style.css\">");
response.setContentType("text/html");
String loginuser= session.getAttribute("loginuser").toString();
out.println("<html><body>"
+ "<div id ='header'>"
+ "<h1>Welcome To CybNet</h1>"
+ "</div><div id='center'>"
+ "<div id='center'>");
response.getWriter().append("<h2 align='left'>Hello "+loginuser+"</h2>");
MyConnection c=new MyConnection();
Connection con;
try
{
con = c.connect();
Statement st = null;
String insertQuery = "SELECT distinct b.BookId, b.BookName,b.AuthorName,r.description,u.name"
+ " FROM book b join user_review ur on b.BookId=ur.bookid"
+ " join review r on r.reviewid=ur.reviewid join user u on u.userid=ur.userid"
+ " where b.BookId="+n;
st=con.createStatement();
ResultSet rs= st.executeQuery(insertQuery);
out.println(" <form action=\"AddReviewServlet\" method=\"get \" > ");
out.println("<table align='center' border=1 width=50% height=25%>");
String radio="";
out.println("<tr><th>Book Name</th><th>Author Name</th><th>Review</th><th>Reviewed By</th><tr>");
if(!rs.next())
{
response.sendRedirect("FirstReview.html");
}
else
{
rs.previous();
while (rs.next()) {
String a = rs.getString("BookName");
String bn = rs.getString("AuthorName");
String review=rs.getString("description");
String user=rs.getString("name");
int id=rs.getInt("BookId");
radio=""+id;
//out.print("<tr><td><input type='radio' name='radio' value='"+radio+"' > </td></tr>");
out.println("<tr><td>"+" <input type='radio' name='radio' value='"+radio+"' > "+ a + "</td><td>" + bn + "</td><td>" + review + "</td><td>" + user + "</td></tr>");
}
out.println("</table><br><br><br>");
out.println("<textarea rows=\" 5\" cols=\" 40 \" name='review'> </textarea><br><br>");
out.println("<button class='button' value='Details'>Add Review</button>");
out.print("</form>");
out.println("</div></div><div id='footer'><h4>© CybageNet...</h4></div>");
out.println("</body></html>");
con.close();
}
}
catch (Exception e) {
out.println(""+e);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
<file_sep>/Group 2 JAVA FRTP2016/cybage net/src/DAO/ReviewDAO.java
package DAO;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import DatabaseConnection.MyConnection;
public class ReviewDAO {
//method to add review
public void addReview(String username,int bookid,String review)
{
MyConnection c=new MyConnection();
Connection con;
try
{
//this is to get user id and name of the user who is adding review
con = c.connect();
Statement st = null;
PreparedStatement ps=null;
String sql="SELECT name,user.userId FROM login join user on login.userId = user.loginId where login.userName= ?";
ps = con.prepareStatement(sql);
ps.setString(1 , username);
ResultSet rs=ps.executeQuery();
rs.next();
String name=rs.getString("name");
Integer userid =rs.getInt("userId");
PreparedStatement pst = null;
//this is to get latest reviewid from review table.
sql="select * from review";
st=con.createStatement();
rs=st.executeQuery(sql);
while(rs.next())
{
}
rs.previous();
Integer rid=rs.getInt("reviewId");
rid++;
//this is to insert record in review table .
String insertQuery = "INSERT INTO review" + "(reviewId,description) VALUES" + "(?,?)";
pst = con.prepareStatement(insertQuery);
pst.setInt(1, rid);
pst.setString( 2, review);
pst.executeUpdate();
//this is to get last primary id user_review table;
sql="select * from user_review";
st=con.createStatement();
rs=st.executeQuery(sql);
while(rs.next())
{
}
rs.previous();
Integer id=rs.getInt("id");
id++;
//this is to insert record in user_review table .
insertQuery = "INSERT INTO user_review" + "(id,bookid,reviewid,userid) VALUES" + "(?,?,?,?)";
pst = con.prepareStatement(insertQuery);
pst.setInt(1, id);
pst.setInt(2, bookid);
pst.setInt(3, rid);
pst.setInt(4, userid);
System.out.println(pst.executeUpdate());
System.out.println("review submited successfully.");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
<file_sep>/Fianal Upadated project with CSS/cybage net/src/POJO/Review.java
package POJO;
public class Review {
int reviewid;
String description;
public int getReviewid() {
return reviewid;
}
public void setReviewid(int reviewid) {
this.reviewid = reviewid;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
<file_sep>/Fianal Upadated project with CSS/cybagenetbackup.sql
-- MySQL Administrator dump 1.4
--
-- ------------------------------------------------------
-- Server version 5.6.20
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
--
-- Create schema cybagenet
--
CREATE DATABASE IF NOT EXISTS cybagenet;
USE cybagenet;
--
-- Definition of table `book`
--
DROP TABLE IF EXISTS `book`;
CREATE TABLE `book` (
`BookId` int(10) unsigned NOT NULL AUTO_INCREMENT,
`BookName` varchar(45) NOT NULL,
`AuthorName` varchar(45) NOT NULL,
PRIMARY KEY (`BookId`)
) ENGINE=InnoDB AUTO_INCREMENT=8989 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `book`
--
/*!40000 ALTER TABLE `book` DISABLE KEYS */;
INSERT INTO `book` (`BookId`,`BookName`,`AuthorName`) VALUES
(1,'Wings Of Fire','Dr. APJ <NAME>'),
(255,'Playing it my way','SRT'),
(555,'abcd','aaaaa'),
(866,'abcd','kkkk');
/*!40000 ALTER TABLE `book` ENABLE KEYS */;
--
-- Definition of table `login`
--
DROP TABLE IF EXISTS `login`;
CREATE TABLE `login` (
`userId` int(10) unsigned NOT NULL AUTO_INCREMENT,
`userName` varchar(45) NOT NULL,
`password` varchar(45) NOT NULL,
`type` varchar(45) NOT NULL,
PRIMARY KEY (`userId`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `login`
--
/*!40000 ALTER TABLE `login` DISABLE KEYS */;
INSERT INTO `login` (`userId`,`userName`,`password`,`type`) VALUES
(1,'user1','<PASSWORD>','normal'),
(2,'admin','admin','<PASSWORD>'),
(3,'user2','adp','normal');
/*!40000 ALTER TABLE `login` ENABLE KEYS */;
--
-- Definition of table `review`
--
DROP TABLE IF EXISTS `review`;
CREATE TABLE `review` (
`reviewId` int(10) unsigned NOT NULL AUTO_INCREMENT,
`description` varchar(45) NOT NULL,
PRIMARY KEY (`reviewId`)
) ENGINE=InnoDB AUTO_INCREMENT=119 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `review`
--
/*!40000 ALTER TABLE `review` DISABLE KEYS */;
INSERT INTO `review` (`reviewId`,`description`) VALUES
(101,'good'),
(102,'fine'),
(103,'nice'),
(104,' wowwww'),
(105,'Inspirational aaaaaaa'),
(106,' Awesome'),
(107,' aaaaa'),
(108,' oh my god !!!'),
(109,' nice'),
(110,' aaaaa'),
(111,' niceeeeeeeeeee'),
(112,' ek numer'),
(113,' Hello'),
(114,' Greatttt'),
(115,' '),
(116,' '),
(117,' '),
(118,' ');
/*!40000 ALTER TABLE `review` ENABLE KEYS */;
--
-- Definition of table `session`
--
DROP TABLE IF EXISTS `session`;
CREATE TABLE `session` (
`sessioncount` int(10) unsigned DEFAULT NULL,
`hitcount` int(10) unsigned DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `session`
--
/*!40000 ALTER TABLE `session` DISABLE KEYS */;
INSERT INTO `session` (`sessioncount`,`hitcount`) VALUES
(26,1),
(26,2),
(26,3),
(26,4),
(26,5),
(26,6),
(26,7),
(26,8),
(26,9),
(26,10),
(26,11),
(26,12),
(26,13),
(26,14),
(26,15),
(26,16),
(26,17),
(26,18),
(26,19),
(26,20),
(26,21),
(26,22),
(26,23),
(26,24),
(26,25),
(26,26),
(26,27),
(26,28),
(26,29),
(26,30),
(26,31),
(26,32),
(26,33),
(26,34),
(26,35),
(26,36),
(26,37),
(26,38),
(26,39),
(26,40),
(26,41),
(26,42),
(26,43),
(26,44),
(26,45),
(26,46),
(26,47),
(26,48),
(26,49),
(26,50),
(26,51),
(26,52),
(26,53),
(26,54),
(26,55),
(26,56),
(27,57),
(28,58),
(29,59),
(30,60),
(31,61),
(32,62),
(33,63),
(34,64),
(35,65),
(36,66),
(37,67);
/*!40000 ALTER TABLE `session` ENABLE KEYS */;
--
-- Definition of table `user`
--
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`userId` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
`mobileNo` varchar(45) NOT NULL,
`loginId` int(10) unsigned NOT NULL,
PRIMARY KEY (`userId`),
KEY `FK_user_1` (`loginId`),
CONSTRAINT `FK_user_1` FOREIGN KEY (`loginId`) REFERENCES `login` (`userId`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `user`
--
/*!40000 ALTER TABLE `user` DISABLE KEYS */;
INSERT INTO `user` (`userId`,`name`,`mobileNo`,`loginId`) VALUES
(1,'alpeshp','9898558899',1),
(2,'mucool','9898558899',2),
(3,'alpesh','9921887849',3);
/*!40000 ALTER TABLE `user` ENABLE KEYS */;
--
-- Definition of table `user_review`
--
DROP TABLE IF EXISTS `user_review`;
CREATE TABLE `user_review` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`bookid` int(10) unsigned NOT NULL,
`reviewid` int(10) unsigned NOT NULL,
`userid` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `FK_user_review_1` (`bookid`),
KEY `FK_user_review_2` (`reviewid`),
KEY `FK_user_review_3` (`userid`),
CONSTRAINT `FK_user_review_1` FOREIGN KEY (`bookid`) REFERENCES `book` (`BookId`),
CONSTRAINT `FK_user_review_2` FOREIGN KEY (`reviewid`) REFERENCES `review` (`reviewId`),
CONSTRAINT `FK_user_review_3` FOREIGN KEY (`userid`) REFERENCES `user` (`userId`)
) ENGINE=InnoDB AUTO_INCREMENT=128 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `user_review`
--
/*!40000 ALTER TABLE `user_review` DISABLE KEYS */;
INSERT INTO `user_review` (`id`,`bookid`,`reviewid`,`userid`) VALUES
(111,1,101,2),
(112,1,102,2),
(113,1,104,3),
(114,1,105,1),
(115,1,106,1),
(116,1,107,1),
(117,1,108,1),
(118,1,109,1),
(119,1,110,1),
(120,255,111,1),
(121,1,112,1),
(122,255,113,1),
(123,1,114,1),
(124,255,115,1),
(125,1,116,1),
(126,255,117,1),
(127,255,118,1);
/*!40000 ALTER TABLE `user_review` ENABLE KEYS */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
<file_sep>/Group 2 JAVA FRTP2016/cybage net/src/cybagenetpackage/AddNewBookServlet.java
package cybagenetpackage;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
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 DAO.BookDao;
import DatabaseConnection.MyConnection;
@WebServlet("/AddNewBookServlet")
public class AddNewBookServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public AddNewBookServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
MyConnection c=new MyConnection();
Connection con;
HttpSession session=request.getSession();
try
{
con = c.connect();
PreparedStatement pst = null;
Integer id = Integer.parseInt(request.getParameter("bid"));
String bookname = request.getParameter("bname");
String authorname = request.getParameter("author");
BookDao b=new BookDao();
//gives call to DAO Layer and addnew book method to add new book to database
b.addNewBook(id, bookname, authorname);
response.sendRedirect("Admin.html");
}
catch (Exception e)
{
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
| 2770ccdb8a5e952ed9231eddf22e68b4d6742caf | [
"Java",
"SQL"
] | 6 | Java | kdrnaik24/Kedar | 5bcf1eabedf1ce06905f1bd00560aa1901a45917 | 6a11dc587592a9b7f4f91189dca6c68a9547a5a8 |
refs/heads/master | <repo_name>ailuoy/audio-fingerprint<file_sep>/fingerprint/fingerprint.go
package fingerprint
import (
"errors"
"fmt"
"io/ioutil"
"os"
"os/exec"
"regexp"
"strconv"
"strings"
)
const (
sampleTime = 500
span = 150
step = 1
minOverlap = 20
threshold = 0.5
)
type Fingerprint struct {
Duration int
Fingerprint []int32
}
func GetFingerPrintInfo(fileName string) (fingerprint Fingerprint, err error) {
_, err = os.Stat(fileName)
if err != nil {
err = errors.New(fmt.Sprintf("File does not exist %s", fileName))
return
}
content, fileErr := readFileFPRaw(fileName)
if err != nil {
err = fileErr
return
}
duration, fileErr := getDuration(content)
if err != nil {
err = fileErr
return
}
fp, _ := getFingerprint(content)
fingerprint = Fingerprint{
Duration: duration,
Fingerprint: fp,
}
return
}
func readFileFPRaw(fileName string) (content []byte, err error) {
cmd := exec.Command("/bin/bash", "-c", `fpcalc -raw `+fileName)
stdout, fileErr := cmd.StdoutPipe()
if fileErr != nil {
err = errors.New(fmt.Sprintf("Error:can not obtain stdout pipe for command:%s\n", fileErr))
return
}
if fileErr := cmd.Start(); fileErr != nil {
err = errors.New(fmt.Sprintf("Error:The command is err,%s", fileErr.Error()))
return
}
bytes, FileErr := ioutil.ReadAll(stdout)
if err != nil {
err = errors.New(fmt.Sprintf("ReadAll Stdout:%s", FileErr.Error()))
return
}
if FileErr := cmd.Wait(); FileErr != nil {
err = errors.New(fmt.Sprintf("wait:%s", FileErr.Error()))
return
}
str := fmt.Sprintf("%s", bytes)
content = []byte(str)
return
}
func getDuration(contents []byte) (duration int, err error) {
strDurationRe := `DURATION=(\d+)\nFINGERPRINT`
reg := regexp.MustCompile(strDurationRe)
match := reg.FindSubmatch(contents)
duration, err = strconv.Atoi(string(match[1]))
return
}
func getFingerprint(contents []byte) (fingerprint []int32, err error) {
strDurationRe := `FINGERPRINT=(.*)`
reg := regexp.MustCompile(strDurationRe)
match := reg.FindSubmatch(contents)
splitStr := strings.Split(string(match[1]), ",")
for _, v := range splitStr {
temp, _ := strconv.Atoi(v)
fingerprint = append(fingerprint, int32(temp))
}
return
}
func Correlate(source []int32, target []int32) (maxCorrIndex float32, maxCorrOffset int, err error) {
corr, err := compare(source, target, span, step)
if err != nil {
return
}
maxCorrIndex, maxCorrOffset = getMaxCorr(corr)
return
}
func getMaxCorr(corr []float32) (float32, int) {
maxCorrIndex := maxIndex(corr)
maxCorrOffset := -span + maxCorrIndex*step
return corr[maxCorrIndex], maxCorrOffset
}
func maxIndex(corr []float32) (maxIndex int) {
maxValue := corr[0]
for i, value := range corr {
if value > maxValue {
maxValue = value
maxIndex = i
}
}
return
}
func compare(source []int32, target []int32, span int, step int) (corrXy []float32, err error) {
sourceLen := len(source)
targetLen := len(target)
if span > Min(sourceLen, targetLen) {
err = errors.New("span >= sample size: %i >= %i")
return
}
var box []int
for i := -span; i < span+1; i += step {
box = append(box, i)
}
for _, offset := range box {
rate, _ := crossCorrelation(source, target, offset)
corrXy = append(corrXy, rate)
}
return
}
func Min(x, y int) int {
if x < y {
return x
}
return y
}
func crossCorrelation(source []int32, target []int32, offset int) (number float32, err error) {
sourceLen := len(source)
targetLen := len(target)
if offset > 0 {
source = source[offset:]
if sourceLen > targetLen {
target = target[:targetLen]
} else {
target = target[:sourceLen]
}
} else if offset < 0 {
offset = -offset
if offset > targetLen {
target = []int32{}
} else {
target = target[offset:]
}
if targetLen < sourceLen {
source = source[:targetLen]
}
}
if Min(len(source), len(target)) < minOverlap {
return
}
number, err = correlation(source, target)
return
}
func correlation(source []int32, target []int32) (rate float32, err error) {
sourceLen := len(source)
targetLen := len(target)
if sourceLen == 0 || targetLen == 0 {
err = errors.New("souce pr target len 0")
return
}
if sourceLen > targetLen {
source = source[:targetLen]
} else if sourceLen < targetLen {
target = target[:sourceLen]
}
var covariance float32
covariance = 0
for i := 0; i < len(source); i++ {
binStr := bin(source[i] ^ target[i])
covariance += (32 - float32(strings.Count(binStr, "1")))
}
covariance = covariance / float32(sourceLen)
rate = covariance / 32
return
}
func bin(number int32) (binStr string) {
return "0b" + strconv.FormatInt(int64(number), 2)
}
<file_sep>/README.MD
# Audio-Fingerprint
This project is to analyze the similarity between two audios.
## Building the Application
>Depends on [fpcalc](https://github.com/acoustid/chromaprint) linux extension
### Install fpcalc
```
sudo wget https://github.com/acoustid/chromaprint/releases/download/v1.4.3/chromaprint-fpcalc-1.4.3-linux-x86_64.tar.gz
sudo tar -zxvf chromaprint-fpcalc-1.4.3-linux-x86_64.tar.gz
sudo mv /usr/local/chromaprint-fpcalc-1.4.3-linux-x86_64/fpcalc /usr/local/bin
```
```
fpcalc -version
fpcalc version 1.4.3
```
## Getting Started
```
first, _ := fingerprint.GetFingerPrintInfo("first.mp3")
second, _ := fingerprint.GetFingerPrintInfo("second.mp3")
similarity, _, _ := fingerprint.Correlate(first.Fingerprint, second.Fingerprint)
fmt.Println(similarity)
```
## Benchmark
```php
go test -test.bench="BenchmarkSongFpCompare" -benchmem -benchtime=30s -cpuprofile profile_cpu.out
go tool pprof -svg profile_cpu.out > profile_cpu.svg
```
## References
### [go-fingerprint/gochroma](https://github.com/go-fingerprint/gochroma)
>Gochroma can only match exactly
### [chromaprint](https://github.com/acoustid/chromaprint)
## Thanks
- [nay-kang](https://github.com/nay-kang) Provide python script
<file_sep>/main.go
package main
import (
"fmt"
"github.com/audio-fingerprint/fingerprint"
)
func main() {
first, _ := fingerprint.GetFingerPrintInfo("first.mp3")
second, _ := fingerprint.GetFingerPrintInfo("second.mp3")
similarity, _, _ := fingerprint.Correlate(first.Fingerprint, second.Fingerprint)
fmt.Println(similarity)
}
| e37ce3fdb7b864ffb5ee868a6249e7759db7296c | [
"Markdown",
"Go"
] | 3 | Go | ailuoy/audio-fingerprint | e3856520ba3d78b5211bac669ef45d3474405a7b | 7dda689d0ef18f457b40ba208b8f14fc3286324a |
refs/heads/master | <file_sep># About
A Python app to send a batch of emails to different addresses following a template
# Requirements
The only requirement is Python 3 which has the following libraries included:
- [configparser](https://docs.python.org/3/library/configparser.html)
- [email.mime](https://docs.python.org/3/library/email.mime.html)
- [json](https://docs.python.org/3/library/json.html)
- [jsonschema](https://pypi.org/project/jsonschema/)
- [re](https://docs.python.org/3/library/re.html)
- [smtplib](https://docs.python.org/3/library/smtplib.html)
# To Run
1. Get credentials at your provider for sending emails programatically with SMTP (for gmail you can generate a token [here](https://security.google.com/settings/security/apppasswords))
2. Create a batch job file according to the following json schema (a batch file example is included in this repository):
```
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"subject": {
"type": "string"
},
"body_template": {
"type": "string"
},
"recipients": {
"type": "array",
"items": {
"type": "object",
"properties": {
"address": {
"type": "string"
},
"template_params": {
"type": "array",
"items": {
"type": "string"
}
}
},
"required": [
"address",
"template_params"
],
"additionalProperties": False
}
}
},
"required": [
"subject",
"body_template",
"recipients"
],
"additionalProperties": False
}
```
3. Edit "settings.ini" file with your configuration. The following fields are required:
- `sender_email`: email address of the sender
- `sender_token`: password or token for the sender
- `sender_name`: name of the sender as it appears on the receiver's inbox
- `batch_file`: file containing the batch job
- `stop_batch_if_error`: If "True", it will stop sending emails if an error occurs in one item of the batch
- `smtp_server_url` = Url for the SMTP server
4. Run command `python3 batch_email_sender.py`<file_sep>import os
import re
import configparser
import smtplib
import json
import jsonschema
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
BATCH_JSON_SCHEMA = {
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"subject": {
"type": "string"
},
"body_template": {
"type": "string"
},
"recipients": {
"type": "array",
"items": {
"type": "object",
"properties": {
"address": {
"type": "string"
},
"template_params": {
"type": "array",
"items": {
"type": "string"
}
}
},
"required": [
"address",
"template_params"
],
"additionalProperties": False
}
}
},
"required": [
"subject",
"body_template",
"recipients"
],
"additionalProperties": False
}
def send_email(smtp_server, sender, recipient, subject, body):
msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = f"{sender[2]} <{sender[0]}>"
msg['To'] = recipient
mime_text = MIMEText(body, 'plain')
msg.attach(mime_text)
try:
smtp_server.sendmail(msg['From'], msg['To'], msg.as_string())
except Exception as e:
print(e)
return False
return True
def stop_program(item_count):
print(f"Program will stop due to error on batch item {item_count}")
exit()
if __name__ == '__main__':
# Load config file
settings_file = 'settings.ini'
try:
config = configparser.ConfigParser()
config.read(settings_file)
batch_file = config['CONFIGURATION']['batch_file']
smtp_server_url = config['CONFIGURATION']['smtp_server_url']
stop_batch_if_error = (config['CONFIGURATION']['stop_batch_if_error'] == "True")
sender_email = config['CONFIGURATION']['sender_email']
sender_token = config['CONFIGURATION']['sender_token']
sender_name = config['CONFIGURATION']['sender_name']
sender = (sender_email, sender_token, sender_name)
except Exception as e:
print(f"Error: '{settings_file}' not found or invalid. {e}")
exit()
# Load batch file
try:
with open(batch_file, 'r') as f:
batch = json.loads(f.read())
jsonschema.validate(instance=batch, schema=BATCH_JSON_SCHEMA)
except Exception as e:
print(f"Error: '{batch_file}' not found or invalid. {e}")
exit()
# Log into server
smtp_server = smtplib.SMTP(smtp_server_url)
smtp_server.starttls()
try:
smtp_server.login(sender[0], sender[1])
except smtplib.SMTPAuthenticationError as e:
print("SMTPAuthenticationError: check your credentials. Exiting program...")
smtp_server.quit()
exit()
# Send emails
item_count = 0
for item in batch["recipients"]:
# Print completion rate
item_count = item_count + 1
batch_completion = (item_count / len(batch["recipients"])) * 100.0
send_to = item["address"]
print(f"({batch_completion:.2f}%) Processing batch item {item_count} for address '{send_to}'")
# Check if email address is valid
if(not re.match(r"^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]*$", send_to)):
print(f"Batch item {item_count} has invalid email address '{send_to}'")
if(stop_batch_if_error):
stop_program(item_count)
else:
continue
# Create email body
email_body = batch["body_template"]
param_count = 0
for param in item["template_params"]:
email_body = email_body.replace(f"[{param_count}]", param)
param_count = param_count + 1
# Send email
if(not send_email(smtp_server, sender, send_to, batch["subject"], email_body)):
print(f"Error while sending email to '{send_to}'")
if(stop_batch_if_error):
stop_program(item_count)
smtp_server.quit()
print("Done")<file_sep>[CONFIGURATION]
sender_email = <EMAIL>
sender_token = <PASSWORD>
sender_name = <NAME>
batch_file = batch.json
stop_batch_if_error = True
smtp_server_url = smtp.gmail.com:587 | da84aeb71d060f9859c7d75ae7eea7ffbbb1407e | [
"Markdown",
"Python",
"INI"
] | 3 | Markdown | urbanoanderson/batch-email-sender | 9bb84e1a62e2ecefa559efbb38d5c778c7046ab3 | 7e898e47f02fda7ce184b2f1d29f82c1c1e5ffff |
refs/heads/master | <file_sep># .home
This is my home - there are many like it, but this one is mine.
<file_sep>ln -s /media/jangu/stud ~/stud
cp ./.vimrc ~/.vimrc
cp ./.nanorc ~/.nanorc
| 0c6b365e33954fcf5c9acf82a0bd60a3ae3c9b0f | [
"Markdown",
"Shell"
] | 2 | Markdown | Gullern/.home | 450ddcb3f574cf8bb03bbf6926d89c3c354463e5 | 299300e79449840e1cb247e069e327381817f0b0 |
refs/heads/master | <file_sep>const connection=require("../connect.js");
var sql_conditions="";
var START=0;
var WHERE_OR_AND=" and ";
function addSqlString(key,value)
{
if(START==0)
{
WHERE_OR_AND=" where ";
START=1;
}
sql_conditions = sql_conditions + WHERE_OR_AND + key + " = '"+value+"' ";
WHERE_OR_AND =" and ";
}
function consistSqlString(reqBody)
{
if(reqBody.StudentNumber!="")
{
addSqlString("stu_id",reqBody.StudentNumber);
}
if(reqBody.StudentName!="")
{
addSqlString("stu_name",reqBody.StudentName);
}
if(reqBody.Department!="")
{
addSqlString("department",reqBody.Department);
}
if(reqBody.Major!="")
{
addSqlString("major",reqBody.Major);
}
if(false)
{
addSqlString("status",reqBody.Status);
}
if(reqBody.Grade!="")
{
addSqlString("grade",reqBody.Grade);
}
if(false)
{
out.println("sex为空");
}
}
function queryStudentInfo(reqBody,callback)
{
sql_conditions="";
START=0;
WHERE_OR_AND=" and ";
consistSqlString(reqBody);
console.log(sql_conditions);
connection.query("SELECT * from user_info"+sql_conditions, function (error, results, fields) {
if (error) throw error;
callback(results);
});
}
module.exports=queryStudentInfo;<file_sep># 学校教务管理平台
## 版本信息
node: v12.14.1
mysql: 8.0.19
## 目录介绍
### db
./db/model 数据库每个表的处理,业务逻辑操作
```
eg./db/model/studentInfo.js作为一个模块封装了对user_info该表的业务逻辑操作
```
./db/connect.js 连接数据库
### node_modules
nodejs的模块目录,通过npm install *<模块名>* 安装的模块**自动**存储在这个文件夹下
```
eg npm install mysql //安装mysql模块
```
### router
各种路由信息,每一个文件负责处理来自前端一个页面的所有请求get,post等
```
eg ./router/studentInfoManager.js处理来自学生信息管理的请求
```
### staticResource
存放css,javascript,html,images资源,在html中需要引用相应资源时从该目录开始寻址
```
eg 在html/学生信息管理.html 中要调用javascript/学生信息管理.js文件,用如下声明<script src="/staticResource/javascript/学生信息管理.js"></script>
```
### pre-prepare
前期准备的资料,包括axure原型设计资料等,存放设计资料等杂项
### server.js
项目启动入口,node server.js即可启动项目
## mysql 信息
依照./pre-prepare/DB/sql.sql文件建表
host : '127.0.0.1'
user : 'program',
password : '<PASSWORD>',
database : 'webprogram'
## 客户端浏览器访问
127.0.0.1:8888
| b669bc5c23f94630f8c32691a4b88d83b59f41cf | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | stereofire/webProgram | 73ed7e40e308e96f07b1734e6ad60c24a1050127 | 2f0cae9e88505c52ac4e2227e0968ebb7df76de7 |
refs/heads/master | <repo_name>WhiteBytez/DumbWays-Test<file_sep>/1.js
const myBio = () => {
return {
"name": "<NAME>",
"age": 26,
"address": "Bandung, Jawa Barat",
"hobbies": ["Astronomy", "Watching Movies", "Gaming"],
"is_married": true,
"list_school": [
{
"name": "SD Sukasari 2",
"year_in": 1992,
"year_out": 2005
}, {
"name": "SMPN 1 Baleendah",
"year_in": 2005,
"year_out": 2008
},
{
"name": "PKBM <NAME>",
"year_in": 2008,
"year_out": 2011
}
],
"interest_in_coding " : true
};
};
console.log(myBio());<file_sep>/7/readme.md
# Quick Count Apps (Tugas 7)
<p align="center">
<img width="700" align="center" src="https://s3-id-jkt-1.kilatstorage.id/files.deogw.com/DumbWays.jpg" alt="demo"/>
</p>
## Installation
```bash
- Clone repo
- Run composer install
- Buat Database quick_count
- Buat file .env, sample nya ada di file .env.example
- Run php artisan migrate && php artisan db:seed
- Run php artisan serve
- Open via browser
```
<file_sep>/2.js
const userNameValidation = (username) => {
let result;
let regexRules = /^(?=^[a-zA-Z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{5,9}/;
return result = !!username.match(regexRules);
};
const passwordValidation = (password) => {
let result;
let regexRules = /(?=.*[A-Z])(?=.*\d)(?=.*@)(?=.*[@$!%*?&#])[A-Za-z\d@$!%*?&#]{8,}$/;
return result = !!password.match(regexRules);
};
console.log(userNameValidation('@Najibb')); // will return false
console.log(userNameValidation('Ayu99v')); // will return true
console.log(passwordValidation('<PASSWORD>#')); // will return true
console.log(passwordValidation('<PASSWORD>!#')); // will return false
<file_sep>/README.md
<p align="center">
<img width="300" align="center" src="https://cdn.techinasia.com/data/images/LzvV52o01nNnKw9jBzEU9yTsdLLLNINayjwdwxV3.png" alt="demo"/>
</p>
# DumbWays Assignment (Deo)
### Soal 1 ([File Jawaban](https://github.com/WhiteBytez/DumbWays-Test/blob/master/1.js))
Online demo : https://es6console.com/k0j9trua/
Javascript Object Notation atau disingkat JSON sering dipakai dalam REST API.
JSON memiliki karekter sintak yang sangat jelas dan ringan, maka dari itu format JSON sering dipakai untuk bertukar data antara
Server dan Client begitupun sebaliknya.
### Soal 2 ([File Jawaban](https://github.com/WhiteBytez/DumbWays-Test/blob/master/2.js))
Online demo : https://es6console.com/k0jdovm2/
### Soal 3 ([File Jawaban](https://github.com/WhiteBytez/DumbWays-Test/blob/master/3.js))
WIP
### Soal 4 (WIP)
WIP
### Soal 5 ([File Jawaban](https://github.com/WhiteBytez/DumbWays-Test/blob/master/4.js))
https://es6console.com/k0jh5km0/
### Soal 6 ([File Jawaban](https://github.com/WhiteBytez/DumbWays-Test/blob/master/5.js))
WIP
### Soal 7 ([Project folder](https://github.com/WhiteBytez/DumbWays-Test/tree/master/7))
Quick count apps.<file_sep>/5.js
const drawLine = (column) => {
let output = "";
for (let i = 0; i <= column ; i++) {
for (let x = 0; x <= column ; x++) {
output = i === x ? output.concat("*") : output = output.concat(" ");
}
output = output.concat("\n");
}
console.log(output);
};
drawLine(1);<file_sep>/7/database/seeds/CandidatesTableSeeder.php
<?php
use App\Candidate;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class CandidatesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$candidateData = [
[
'name' => '<NAME>',
'earned_vote' => 0
],
[
'name' => 'Umam',
'earned_vote' => 0
]
];
Candidate::insert($candidateData);
}
}
<file_sep>/4.js
const countPhrase = (phrase, findText) => {
let stringContainCount;
let pattern = `/${findText}/`;
// WIP
};
const reverseText = (text) => {
return text.split("").reverse().join("");
};
countPhrase("bandanadana", "dana" );<file_sep>/3.js
const drawImage = (number) => {
let charEqual = '=';
let charAt = '@';
let output = '';
if(isOdd(number)) {
let middleOfNumber = Math.round(number);
// WIP
}
};
const isOdd = (number) => { return number === parseFloat(number) && !!(number % 2)};<file_sep>/7/app/Http/Controllers/VotingController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Candidate;
class VotingController extends Controller
{
public function index()
{
$candidateList = Candidate::all();
return view('home', compact('candidateList'));
}
public function vote(Request $request)
{
$candidate = Candidate::where('id', $request->id);
$addVote = $candidate->increment('earned_vote');
$returnData = [
'success' => false
];
if ($addVote) {
$returnData['success'] = true;
$returnData['count'] = $candidate->get('earned_vote');
}
return response()->json($returnData);
}
}
| 615c2cd59527ecce075093cac47eb7a5b89c0b91 | [
"JavaScript",
"PHP",
"Markdown"
] | 9 | JavaScript | WhiteBytez/DumbWays-Test | 2bb899dfe44b7dd7fca2503dd605146e6df7c83c | fdda914532ade847e5a20ab84ce5dbff0af65fc9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.