hexsha
stringlengths 40
40
| size
int64 5
1.05M
| ext
stringclasses 98
values | lang
stringclasses 21
values | max_stars_repo_path
stringlengths 3
945
| max_stars_repo_name
stringlengths 4
118
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
listlengths 1
10
| max_stars_count
int64 1
368k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 3
945
| max_issues_repo_name
stringlengths 4
118
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
listlengths 1
10
| max_issues_count
int64 1
134k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 3
945
| max_forks_repo_name
stringlengths 4
135
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
listlengths 1
10
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 5
1.05M
| avg_line_length
float64 1
1.03M
| max_line_length
int64 2
1.03M
| alphanum_fraction
float64 0
1
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c37861f11b6415fc55b5c872ff1912fa4629e921
| 460
|
cs
|
C#
|
AR Memory/Assets/Scripts/CloudMotor.cs
|
paosalcedo/ARkit-Memory
|
f034ab3d58525e76a150c7b0b2af680ca1cd47fc
|
[
"Unlicense"
] | null | null | null |
AR Memory/Assets/Scripts/CloudMotor.cs
|
paosalcedo/ARkit-Memory
|
f034ab3d58525e76a150c7b0b2af680ca1cd47fc
|
[
"Unlicense"
] | null | null | null |
AR Memory/Assets/Scripts/CloudMotor.cs
|
paosalcedo/ARkit-Memory
|
f034ab3d58525e76a150c7b0b2af680ca1cd47fc
|
[
"Unlicense"
] | null | null | null |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CloudMotor : MonoBehaviour {
public float speed;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
MoveCloud();
//kill cloud here
if(transform.position.x <= -300f)
Destroy(gameObject);
}
public void MoveCloud(){
transform.Translate(Vector3.left * speed * Time.deltaTime, Space.World);
}
}
| 17.692308
| 74
| 0.706522
|
da20a811b92bab28a52c534387def8d3968c9fd9
| 318
|
php
|
PHP
|
resources/views/exo3.blade.php
|
Jstaveau/revision_laravel_1
|
a3e30e41b950791233839a666cc77e7ff82e9b2c
|
[
"MIT"
] | null | null | null |
resources/views/exo3.blade.php
|
Jstaveau/revision_laravel_1
|
a3e30e41b950791233839a666cc77e7ff82e9b2c
|
[
"MIT"
] | null | null | null |
resources/views/exo3.blade.php
|
Jstaveau/revision_laravel_1
|
a3e30e41b950791233839a666cc77e7ff82e9b2c
|
[
"MIT"
] | null | null | null |
@extends('layout.app')
@section('content')
<h1>exo3</h1>
@if ($var1 != null && $var2 != null)
<p>{{ $var1 . ' + ' . $var2 . ' = ' . $var1 + $var2 }}</p>
<p>{{ $var1 . ' - ' . $var2 . ' = ' . $var1 - $var2 }}</p>
@else
<p>Vous devez entrer deux nombres...</p>
@endif
@endsection
| 28.909091
| 66
| 0.437107
|
c677ae2944406e6d7453607562134cb200e9743e
| 16,522
|
py
|
Python
|
main_cifar.py
|
isabella232/ml-data-parameters
|
c2931c12d2c6100105c4dcc14df2797e39772098
|
[
"AML"
] | 73
|
2019-11-18T15:56:04.000Z
|
2022-01-13T02:36:01.000Z
|
main_cifar.py
|
isabella232/ml-data-parameters
|
c2931c12d2c6100105c4dcc14df2797e39772098
|
[
"AML"
] | null | null | null |
main_cifar.py
|
isabella232/ml-data-parameters
|
c2931c12d2c6100105c4dcc14df2797e39772098
|
[
"AML"
] | 22
|
2019-11-04T20:23:23.000Z
|
2022-03-26T11:50:46.000Z
|
#
# For licensing see accompanying LICENSE file.
# Copyright (C) 2019 Apple Inc. All Rights Reserved.
#
import time
import argparse
import numpy as np
import torch
import torch.optim
import torch.nn as nn
import torch.utils.data
import torch.nn.parallel
import torch.utils.data.distributed
import torchvision.transforms as transforms
from tensorboard_logger import log_value
import utils
from dataset.cifar_dataset import CIFAR100WithIdx
from models.wide_resnet import WideResNet28_10
parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')
parser.add_argument('-j', '--workers', default=32, type=int, metavar='N',
help='number of data loading workers (default: 4)')
parser.add_argument('--epochs', default=120, type=int, metavar='N',
help='number of total epochs to run')
parser.add_argument('--start-epoch', default=0, type=int, metavar='N',
help='manual epoch number (useful on restarts)')
parser.add_argument('--restart', default=False, const=True, action='store_const',
help='Erase log and saved checkpoints and restart training')
parser.add_argument('-b', '--batch-size', default=128, type=int,
metavar='N', help='mini-batch size (default: 128)')
parser.add_argument('--lr', '--learning-rate', default=0.1, type=float,
metavar='LR', help='initial learning rate for model parameters', dest='lr')
parser.add_argument('--momentum', default=0.9, type=float, metavar='M', help='momentum')
parser.add_argument('--wd', '--weight-decay', default=5e-4, type=float,
metavar='W', help='weight decay (default: 5e-4)',
dest='weight_decay')
parser.add_argument('--rand_fraction', default=0.0, type=float, help='Fraction of data we will corrupt')
parser.add_argument('-p', '--print-freq', default=10, type=int,
metavar='N', help='print frequency')
parser.add_argument('--seed', default=1, type=int,
help='seed for initializing training. ')
parser.add_argument('--learn_class_parameters', default=False, const=True, action='store_const',
help='Learn temperature per class')
parser.add_argument('--learn_inst_parameters', default=False, const=True, action='store_const',
help='Learn temperature per instance')
parser.add_argument('--skip_clamp_data_param', default=False, const=True, action='store_const',
help='Do not clamp data parameters during optimization')
parser.add_argument('--lr_class_param', default=0.1, type=float, help='Learning rate for class parameters')
parser.add_argument('--lr_inst_param', default=0.1, type=float, help='Learning rate for instance parameters')
parser.add_argument('--wd_class_param', default=0.0, type=float, help='Weight decay for class parameters')
parser.add_argument('--wd_inst_param', default=0.0, type=float, help='Weight decay for instance parameters')
parser.add_argument('--init_class_param', default=1.0, type=float, help='Initial value for class parameters')
parser.add_argument('--init_inst_param', default=1.0, type=float, help='Initial value for instance parameters')
def adjust_learning_rate(model_initial_lr, optimizer, gamma, step):
"""Sets the learning rate to the initial learning rate decayed by 10 every few epochs.
Args:
model_initial_lr (int) : initial learning rate for model parameters
optimizer (class derived under torch.optim): torch optimizer.
gamma (float): fraction by which we are going to decay the learning rate of model parameters
step (int) : number of steps in staircase learning rate decay schedule
"""
lr = model_initial_lr * (gamma ** step)
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def get_train_and_val_loader(args):
""""Constructs data loaders for train and val on CIFAR100
Args:
args (argparse.Namespace):
Returns:
train_loader (torch.utils.data.DataLoader): data loader for CIFAR100 train data.
val_loader (torch.utils.data.DataLoader): data loader for CIFAR100 val data.
"""
print('==> Preparing data for CIFAR100..')
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
transform_val = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
trainset = CIFAR100WithIdx(root='/tmp/data',
train=True,
download=True,
transform=transform_train,
rand_fraction=args.rand_fraction)
valset = CIFAR100WithIdx(root='/tmp/data',
train=False,
download=True,
transform=transform_val)
train_loader = torch.utils.data.DataLoader(trainset,
batch_size=args.batch_size,
shuffle=True,
num_workers=args.workers)
val_loader = torch.utils.data.DataLoader(valset,
batch_size=100,
shuffle=False,
num_workers=args.workers)
return train_loader, val_loader
def get_model_and_loss_criterion(args):
"""Initializes DNN model and loss function.
Args:
args (argparse.Namespace):
Returns:
model (torch.nn.Module): DNN model.
criterion (torch.nn.modules.loss): cross entropy loss
"""
print('Building WideResNet28_10')
args.arch = 'WideResNet28_10'
model = WideResNet28_10(num_classes=args.nr_classes)
if args.device == 'cuda':
model = model.cuda()
criterion = nn.CrossEntropyLoss().cuda()
else:
criterion = nn.CrossEntropyLoss()
return model, criterion
def validate(args, val_loader, model, criterion, epoch):
"""Evaluates model on validation set and logs score on tensorboard.
Args:
args (argparse.Namespace):
val_loader (torch.utils.data.dataloader): dataloader for validation set.
model (torch.nn.Module): DNN model.
criterion (torch.nn.modules.loss): cross entropy loss
epoch (int): current epoch
"""
losses = utils.AverageMeter('Loss', ':.4e')
top1 = utils.AverageMeter('Acc@1', ':6.2f')
# switch to evaluate mode
model.eval()
with torch.no_grad():
for i, (inputs, target, _) in enumerate(val_loader):
if args.device == 'cuda':
inputs = inputs.cuda()
target = target.cuda()
# compute output
logits = model(inputs)
loss = criterion(logits, target)
# measure accuracy and record loss
acc1 = utils.compute_topk_accuracy(logits, target, topk=(1, ))
losses.update(loss.item(), inputs.size(0))
top1.update(acc1[0].item(), inputs.size(0))
print('Test-Epoch-{}: Acc:{}, Loss:{}'.format(epoch, top1.avg, losses.avg))
# Logging results on tensorboard
log_value('val/accuracy', top1.avg, step=epoch)
log_value('val/loss', losses.avg, step=epoch)
def train_for_one_epoch(args,
train_loader,
model,
criterion,
optimizer,
epoch,
global_iter,
optimizer_data_parameters,
data_parameters,
config):
"""Train model for one epoch on the train set.
Args:
args (argparse.Namespace):
train_loader (torch.utils.data.dataloader): dataloader for train set.
model (torch.nn.Module): DNN model.
criterion (torch.nn.modules.loss): cross entropy loss.
optimizer (torch.optim.SGD): optimizer for model parameters.
epoch (int): current epoch.
global_iter (int): current iteration count.
optimizer_data_parameters (tuple SparseSGD): SparseSGD optimizer for class and instance data parameters.
data_parameters (tuple of torch.Tensor): class and instance level data parameters.
config (dict): config file for the experiment.
Returns:
global iter (int): updated iteration count after 1 epoch.
"""
# Initialize counters
losses = utils.AverageMeter('Loss', ':.4e')
top1 = utils.AverageMeter('Acc@1', ':6.2f')
# Unpack data parameters
optimizer_class_param, optimizer_inst_param = optimizer_data_parameters
class_parameters, inst_parameters = data_parameters
# Switch to train mode
model.train()
start_epoch_time = time.time()
for i, (inputs, target, index_dataset) in enumerate(train_loader):
global_iter = global_iter + 1
inputs, target = inputs.to(args.device), target.to(args.device)
# Flush the gradient buffer for model and data-parameters
optimizer.zero_grad()
if args.learn_class_parameters:
optimizer_class_param.zero_grad()
if args.learn_inst_parameters:
optimizer_inst_param.zero_grad()
# Compute logits
logits = model(inputs)
if args.learn_class_parameters or args.learn_inst_parameters:
# Compute data parameters for instances in the minibatch
class_parameter_minibatch = class_parameters[target]
inst_parameter_minibatch = inst_parameters[index_dataset]
data_parameter_minibatch = utils.get_data_param_for_minibatch(
args,
class_param_minibatch=class_parameter_minibatch,
inst_param_minibatch=inst_parameter_minibatch)
# Compute logits scaled by data parameters
logits = logits / data_parameter_minibatch
loss = criterion(logits, target)
# Apply weight decay on data parameters
if args.learn_class_parameters or args.learn_inst_parameters:
loss = utils.apply_weight_decay_data_parameters(args, loss,
class_parameter_minibatch=class_parameter_minibatch,
inst_parameter_minibatch=inst_parameter_minibatch)
# Compute gradient and do SGD step
loss.backward()
optimizer.step()
if args.learn_class_parameters:
optimizer_class_param.step()
if args.learn_inst_parameters:
optimizer_inst_param.step()
# Clamp class and instance level parameters within certain bounds
if args.learn_class_parameters or args.learn_inst_parameters:
utils.clamp_data_parameters(args, class_parameters, config, inst_parameters)
# Measure accuracy and record loss
acc1 = utils.compute_topk_accuracy(logits, target, topk=(1, ))
losses.update(loss.item(), inputs.size(0))
top1.update(acc1[0].item(), inputs.size(0))
# Log stats for data parameters and loss every few iterations
if i % args.print_freq == 0:
utils.log_intermediate_iteration_stats(args, class_parameters, epoch,
global_iter, inst_parameters,
losses, top1)
# Print and log stats for the epoch
print('Time for epoch: {}'.format(time.time() - start_epoch_time))
print('Train-Epoch-{}: Acc:{}, Loss:{}'.format(epoch, top1.avg, losses.avg))
log_value('train/accuracy', top1.avg, step=epoch)
log_value('train/loss', losses.avg, step=epoch)
return global_iter
def main_worker(args, config):
"""Trains model on ImageNet using data parameters
Args:
args (argparse.Namespace):
config (dict): config file for the experiment.
"""
global_iter = 0
learning_rate_schedule = np.array([80, 100, 160])
# Create model
model, loss_criterion = get_model_and_loss_criterion(args)
# Define optimizer
optimizer = torch.optim.SGD(model.parameters(), args.lr,
momentum=args.momentum,
weight_decay=args.weight_decay)
# Get train and validation dataset loader
train_loader, val_loader = get_train_and_val_loader(args)
# Initialize class and instance based temperature
(class_parameters, inst_parameters,
optimizer_class_param, optimizer_inst_param) = utils.get_class_inst_data_params_n_optimizer(
args=args,
nr_classes=args.nr_classes,
nr_instances=len(train_loader.dataset),
device='cuda'
)
# Training loop
for epoch in range(args.start_epoch, args.epochs):
# Adjust learning rate for model parameters
if epoch in learning_rate_schedule:
adjust_learning_rate(model_initial_lr=args.lr,
optimizer=optimizer,
gamma=0.1,
step=np.sum(epoch >= learning_rate_schedule))
# Train for one epoch
global_iter = train_for_one_epoch(
args=args,
train_loader=train_loader,
model=model,
criterion=loss_criterion,
optimizer=optimizer,
epoch=epoch,
global_iter=global_iter,
optimizer_data_parameters=(optimizer_class_param, optimizer_inst_param),
data_parameters=(class_parameters, inst_parameters),
config=config)
# Evaluate on validation set
validate(args, val_loader, model, loss_criterion, epoch)
# Save artifacts
utils.save_artifacts(args, epoch, model, class_parameters, inst_parameters)
# Log temperature stats over epochs
if args.learn_class_parameters:
utils.log_stats(data=torch.exp(class_parameters),
name='epochs_stats_class_parameter',
step=epoch)
if args.learn_inst_parameters:
utils.log_stats(data=torch.exp(inst_parameters),
name='epoch_stats_inst_parameter',
step=epoch)
if args.rand_fraction > 0.0:
# We have corrupted labels in the train data; plot instance parameter stats for clean and corrupt data
nr_corrupt_instances = int(np.floor(len(train_loader.dataset) * args.rand_fraction))
# Corrupt data is in the top-fraction of dataset
utils.log_stats(data=torch.exp(inst_parameters[:nr_corrupt_instances]),
name='epoch_stats_corrupt_inst_parameter',
step=epoch)
utils.log_stats(data=torch.exp(inst_parameters[nr_corrupt_instances:]),
name='epoch_stats_clean_inst_parameter',
step=epoch)
def main():
args = parser.parse_args()
args.device = 'cuda' if torch.cuda.is_available() else 'cpu'
args.log_dir = './logs_CL_CIFAR'
args.save_dir = './weights_CL_CIFAR'
args.nr_classes = 100 # Number classes in CIFAR100
utils.generate_log_dir(args)
utils.generate_save_dir(args)
config = {}
config['clamp_inst_sigma'] = {}
config['clamp_inst_sigma']['min'] = np.log(1/20)
config['clamp_inst_sigma']['max'] = np.log(20)
config['clamp_cls_sigma'] = {}
config['clamp_cls_sigma']['min'] = np.log(1/20)
config['clamp_cls_sigma']['max'] = np.log(20)
utils.save_config(args.save_dir, config)
# Set seed for reproducibility
utils.set_seed(args)
# Simply call main_worker function
main_worker(args, config)
if __name__ == '__main__':
main()
| 42.473008
| 114
| 0.610882
|
388c5ffd49e068a6aabaab20132a64d6e9e20797
| 415
|
php
|
PHP
|
src/Framework/Traits/Hydrator.php
|
sldevand/petcare
|
45f55ed645e3d89335cacd10aedb04489cb7cdc7
|
[
"MIT"
] | null | null | null |
src/Framework/Traits/Hydrator.php
|
sldevand/petcare
|
45f55ed645e3d89335cacd10aedb04489cb7cdc7
|
[
"MIT"
] | null | null | null |
src/Framework/Traits/Hydrator.php
|
sldevand/petcare
|
45f55ed645e3d89335cacd10aedb04489cb7cdc7
|
[
"MIT"
] | null | null | null |
<?php
namespace Framework\Traits;
use Exception;
/**
* Trait Hydrator
* @package Framework\Traits
*/
trait Hydrator
{
/**
* @param array $properties
* @throws Exception
*/
public function hydrate(array $properties)
{
foreach ($properties as $property => $value) {
$setMethod = 'set' . ucfirst($property);
$this->$setMethod($value);
}
}
}
| 16.6
| 54
| 0.566265
|
8c5c4ca670c71e659cff3358c582a2affcfd8a05
| 4,413
|
lua
|
Lua
|
xsp/src/custom/position.lua
|
Kakamisan/xx_script
|
5c61f7dfe35d79ff93ef93466517cced264ccc22
|
[
"MIT"
] | 3
|
2019-06-12T07:53:04.000Z
|
2021-09-20T03:31:41.000Z
|
xsp/src/custom/position.lua
|
Kakamisan/xx_script
|
5c61f7dfe35d79ff93ef93466517cced264ccc22
|
[
"MIT"
] | 1
|
2019-06-12T07:53:29.000Z
|
2019-06-12T07:53:29.000Z
|
xsp/src/custom/position.lua
|
Kakamisan/xx_script
|
5c61f7dfe35d79ff93ef93466517cced264ccc22
|
[
"MIT"
] | 3
|
2019-06-12T07:54:29.000Z
|
2021-11-11T06:11:05.000Z
|
local pos = {}
pos.rotate = 1 --参考init的说明
pos.dw,pos.dh = 720,1280 --开发环境分辨率(需按自适应UI的基准比例开发)
pos.cw,pos.ch = getScreenSize() --当前设备分辨率
pos.dx,pos.dy = (function() --开发环境下横轴坐标最大值
if rotate == 0 then return pos.dw,pos.dh --竖屏下横坐标最大为w
else return pos.dh,pos.dw end --横屏下横坐标最大为h
end)()
pos.ds = {0,0,pos.dx,pos.dy} --开发环境下的屏幕区域
pos.cx,pos.cy = (function() --当前设备下横轴坐标最大值
if rotate == 0 then return pos.cw,pos.ch --竖屏下横坐标最大为sw
else return pos.ch,pos.cw end --横屏下横坐标最大为sh
end)()
pos.cs = {0,0,pos.cx,pos.cy} --当前设备下的屏幕区域
pos.xscl,pos.yscl = (function() --缩放比例(需要按原分辨率比例缩放)
local scale = math.min(pos.cx/pos.dx,pos.cy/pos.dy) --按小的那个来缩放
return scale,scale --(特殊情况下可特殊处理)
end)()
init("0",pos.rotate) --按rotate初始化脚本
----------------------------------坐标自适应函数----------------------------------------
function scale_init()
local list = {btn,item,sld,swc,text,view} --需要适配分辨率的物件种类列表
for i,v in ipairs(list) do
for k,E in pairs(v) do
E = do_scale(E) --对每个物件执行
v[k] = E
end
list[i] = v
end
btn = list[1]
item = list[2]
sld = list[3]
swc = list[4]
text = list[5]
view = list[6]
end
function do_scale(E)
-- E.anchor = (E.body or R.area) and (E.anchor or {0,0}) --有body或area时anchor默认居中
E.anchor = E.anchor or (E.body and {0,0})
E.anchor = E.anchor or (E.area and {0,0})
E.anchor = E.anchor or (E.from and {0,0})
E.anchor = E.anchor or (E.to and {0,0})
E.pivot = E.pivot or E.anchor --pivot默认与anchor相同
E.body = E.body and zoom_area(E.body,E.anchor,E.pivot)
E.area = E.area and zoom_area(E.area,E.anchor,E.pivot)
E.from = E.from and zoom_area(E.from,E.anchor,E.pivot)
E.to = E.to and zoom_area(E.to,E.anchor,E.pivot)
E.feature = E.feature and zoom_feature(E.feature)
E.disable = E.disable and zoom_feature(E.disable)
E.feature_off = E.feature_off and zoom_feature(E.feature_off)
E.items = E.items and (function()
for i,v in ipairs(E.items) do
v.area = zoom_area(v.area,v.anchor or {-1,-1},v.pivot or v.anchor or {-1,-1})
v.feature = zoom_feature(v.feature)
end
return E.items
end)()
return E
end
--根据anchor和pivot将area自适应
--外部参数为pos.ds pos.cs
function zoom_area(area,anchor,pivot)
local dev_anchor = {}
dev_anchor.x,dev_anchor.y = get_anchor_pos(pos.ds,anchor) --获取开发环境下anchor真实坐标
assert(dev_anchor.x and dev_anchor.y)
local cur_anchor = {}
cur_anchor.x,cur_anchor.y = get_anchor_pos(pos.cs,anchor) --获取当前设备下anchor真实坐标
assert(cur_anchor.x and cur_anchor.y)
local dev_pivot = {}
dev_pivot.x,dev_pivot.y = get_anchor_pos(area,pivot) --获取开发环境下pivot真实坐标
assert(dev_pivot.x and dev_pivot.y)
local relative_x,relative_y = dev_anchor.x-dev_pivot.x,dev_anchor.y-dev_pivot.y --计算相对位置的值
relative_x,relative_y = relative_x*pos.xscl,relative_y*pos.yscl --缩放相对位置的值
local cur_pivot = {}
cur_pivot.x,cur_pivot.y = cur_anchor.x-relative_x,cur_anchor.y-relative_y --缩放后的pivot值
return { --返回自适应后的area
math.ceil((area[1]-dev_pivot.x)*pos.xscl+cur_pivot.x),
math.ceil((area[2]-dev_pivot.y)*pos.yscl+cur_pivot.y),
math.ceil((area[3]-dev_pivot.x)*pos.xscl+cur_pivot.x),
math.ceil((area[4]-dev_pivot.y)*pos.yscl+cur_pivot.y)}
end
--变换feature
function zoom_feature(feature)
for i,v in ipairs(feature) do
if v.anchor then
v.x,v.y = zoom_pos(v.x,v.y,v.anchor)
else
v.x,v.y = math.ceil(v.x*pos.xscl),math.ceil(v.y*pos.yscl)
end
end
return feature
end
--变换position,由于单点的中心等于自身,所以无需pivot
--外部参数为pos.ds pos.cs
function zoom_pos(x,y,anchor)
local dev_anchor = {}
dev_anchor.x,dev_anchor.y = get_anchor_pos(pos.ds,anchor) --获取开发环境下anchor真实坐标
assert(dev_anchor.x and dev_anchor.y)
local cur_anchor = {}
cur_anchor.x,cur_anchor.y = get_anchor_pos(pos.cs,anchor) --获取当前设备下anchor真实坐标
assert(cur_anchor.x and cur_anchor.y)
local relative_x,relative_y = dev_anchor.x-x,dev_anchor.y-y --计算相对位置的值
relative_x,relative_y = relative_x*pos.xscl,relative_y*pos.yscl --缩放相对位置的值
return math.ceil(cur_anchor.x-relative_x),math.ceil(cur_anchor.y-relative_y)
end
--根据anchor类型在area中找到anchor真实坐标
function get_anchor_pos(area,anchor)
local xL,xR,xM = area[1],area[3],(area[1]+area[3])/2
local yT,yB,yM = area[2],area[4],(area[2]+area[4])/2
return
anchor[1]==-1 and xL or anchor[1]==0 and xM or anchor[1]==1 and xR,
anchor[2]==-1 and yT or anchor[2]==0 and yM or anchor[2]==1 and yB
end
return pos
| 31.978261
| 91
| 0.676184
|
b7a8f645c57e2970d5f4437928de8934fc50f6de
| 619
|
cpp
|
C++
|
test/ordinal/container/ordinal_range/ordinal_range_pass.cpp
|
jwakely/std-make
|
f09d052983ace70cf371bb8ddf78d4f00330bccd
|
[
"BSL-1.0"
] | 105
|
2015-01-24T13:26:41.000Z
|
2022-02-18T15:36:53.000Z
|
test/ordinal/container/ordinal_range/ordinal_range_pass.cpp
|
jwakely/std-make
|
f09d052983ace70cf371bb8ddf78d4f00330bccd
|
[
"BSL-1.0"
] | 37
|
2015-09-04T06:57:10.000Z
|
2021-09-09T18:01:44.000Z
|
test/ordinal/container/ordinal_range/ordinal_range_pass.cpp
|
jwakely/std-make
|
f09d052983ace70cf371bb8ddf78d4f00330bccd
|
[
"BSL-1.0"
] | 23
|
2015-01-27T11:09:18.000Z
|
2021-10-04T02:23:30.000Z
|
// Copyright (C) 2016 Vicente J. Botet Escriba
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// <experimental/ordinal_range.hpp>
#include <experimental/ordinal_range.hpp>
#include "../../Bool.hpp"
#include "../../Bounded.hpp"
#include <boost/detail/lightweight_test.hpp>
int main()
{
namespace stde = std::experimental;
using Indx = Bounded<1,4,unsigned char>;
{
stde::ordinal_range<Indx> rng;
auto b = rng.begin();
BOOST_TEST(b->value==1);
}
return ::boost::report_errors();
}
| 22.107143
| 80
| 0.688207
|
051813e46b7585f318de0a121ea8d6ecd323703b
| 1,735
|
gemspec
|
Ruby
|
cypress_rails.gemspec
|
Szeliga/cypress_rails
|
41ea764d92a4d5b145d2612e04a6ae961b1f8418
|
[
"MIT"
] | 2
|
2018-06-14T08:10:38.000Z
|
2018-06-14T08:28:18.000Z
|
cypress_rails.gemspec
|
Szeliga/cypress_rails
|
41ea764d92a4d5b145d2612e04a6ae961b1f8418
|
[
"MIT"
] | 3
|
2018-06-13T08:50:21.000Z
|
2018-06-29T14:28:33.000Z
|
cypress_rails.gemspec
|
Szeliga/cypress_rails
|
41ea764d92a4d5b145d2612e04a6ae961b1f8418
|
[
"MIT"
] | 1
|
2018-06-13T13:36:23.000Z
|
2018-06-13T13:36:23.000Z
|
# frozen_string_literal: true
lib = File.expand_path("lib", __dir__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "cypress_rails/version"
Gem::Specification.new do |gem|
gem.name = "cypress_rails"
gem.version = CypressRails::VERSION
gem.summary = "Integrate cypress.io with your rails app"
gem.description = "Easily run a test server for cypress to query against"
gem.license = "MIT"
gem.authors = ["Szymon Szeliga"]
gem.email = "szymon@szeliga.co"
gem.homepage = "https://rubygems.org/gems/cypress_rails"
gem.files = `git ls-files`.split($/)
`git submodule --quiet foreach --recursive pwd`.split($/).each do |submodule|
submodule.sub!("#{Dir.pwd}/", "")
Dir.chdir(submodule) do
`git ls-files`.split($/).map do |subpath|
gem.files << File.join(submodule, subpath)
end
end
end
gem.executables = gem.files.grep(%r{^bin/}).map { |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.require_paths = ["lib"]
gem.add_dependency "thor", "~> 0.20.0"
gem.add_dependency "railties", ">= 4.2.0"
gem.add_development_dependency "bundler", "~> 2.0"
gem.add_development_dependency "codeclimate-test-reporter", "~> 0.1"
gem.add_development_dependency "pry", "~> 0.11.3"
gem.add_development_dependency "rack", "~> 2.0"
gem.add_development_dependency "rake", "~> 10.0"
gem.add_development_dependency "rdoc", "~> 4.0"
gem.add_development_dependency "rspec", "~> 3.0"
gem.add_development_dependency "rubocop", "~> 0.55.0"
gem.add_development_dependency "rubygems-tasks", "~> 0.2"
gem.add_development_dependency "rspec_junit_formatter", "~> 0.3.0"
end
| 38.555556
| 79
| 0.666859
|
43beb67b7875cd8e68543a724b1273634ebdd0bd
| 5,251
|
ts
|
TypeScript
|
src/servers/hidkeyboardserver.ts
|
QPC-database/jacdac-ts
|
5636f5782806fb4e587bfd76e54029e6a3dc082a
|
[
"MIT"
] | 1
|
2021-07-04T03:40:13.000Z
|
2021-07-04T03:40:13.000Z
|
src/servers/hidkeyboardserver.ts
|
QPC-database/jacdac-ts
|
5636f5782806fb4e587bfd76e54029e6a3dc082a
|
[
"MIT"
] | null | null | null |
src/servers/hidkeyboardserver.ts
|
QPC-database/jacdac-ts
|
5636f5782806fb4e587bfd76e54029e6a3dc082a
|
[
"MIT"
] | null | null | null |
import {
CHANGE,
HidKeyboardAction,
HidKeyboardCmd,
HidKeyboardModifiers,
SRV_HID_KEYBOARD,
} from "../jdom/constants"
import Packet from "../jdom/packet"
import JDServiceServer, { ServerOptions } from "../jdom/serviceserver"
import { SMap } from "../jdom/utils"
export default class HIDKeyboardServer extends JDServiceServer {
private _lastKey: [number, HidKeyboardModifiers, HidKeyboardAction][]
constructor(options?: ServerOptions) {
super(SRV_HID_KEYBOARD, options)
this.addCommand(HidKeyboardCmd.Clear, this.handleClear.bind(this))
this.addCommand(HidKeyboardCmd.Key, this.handleKey.bind(this))
}
get lastKey() {
return this._lastKey
}
private handleKey(pkt: Packet) {
const [rest] =
pkt.jdunpack<[[number, HidKeyboardModifiers, HidKeyboardAction][]]>(
"r: u16 u8 u8"
)
this._lastKey = rest
this.emit(CHANGE)
}
private handleClear() {
if (this._lastKey) {
this._lastKey = undefined
this.emit(CHANGE)
}
}
}
export const selectors: SMap<number> = {
a: 0x04,
b: 0x05,
c: 0x06,
d: 0x07,
e: 0x08,
f: 0x09,
g: 0x0a,
h: 0x0b,
i: 0x0c,
j: 0x0d,
k: 0x0e,
l: 0x0f,
m: 0x10,
n: 0x11,
o: 0x12,
p: 0x13,
q: 0x14,
r: 0x15,
s: 0x16,
t: 0x17,
u: 0x18,
v: 0x19,
w: 0x1a,
x: 0x1b,
y: 0x1c,
z: 0x1d,
"1": 0x1e,
"2": 0x1f,
"3": 0x20,
"4": 0x21,
"5": 0x22,
"6": 0x23,
"7": 0x24,
"8": 0x25,
"9": 0x26,
"0": 0x27,
"!": 0x1e,
"@": 0x1f,
"#": 0x20,
$: 0x21,
"%": 0x22,
"^": 0x23,
"&": 0x24,
"*": 0x25,
"(": 0x26,
")": 0x27,
enter: 0x28,
escape: 0x29,
backspace: 0x2a,
tab: 0x2b,
" ": 0x2c,
"-": 0x2d,
_: 0x2d,
"=": 0x2e,
"+": 0x2e,
"[": 0x2f,
"{": 0x2f,
"]": 0x30,
"}": 0x30,
"\\": 0x31,
"|": 0x31,
// non-US #
"~": 0x32,
";": 0x33,
":": 0x33,
"'": 0x34,
'"': 0x34,
// grave accent tilde
",": 0x36,
"<": 0x37,
".": 0x37,
">": 0x37,
"/": 0x38,
"?": 0x38,
capslock: 0x39,
f1: 0x3a,
f2: 0x3b,
f3: 0x3c,
f4: 0x3d,
f5: 0x3e,
f6: 0x3f,
f7: 0x40,
f8: 0x41,
f9: 0x42,
f10: 0x43,
f11: 0x44,
f12: 0x45,
printscreen: 0x46,
scrolllock: 0x47,
pause: 0x48,
insert: 0x49,
home: 0x4a,
pageup: 0x4b,
delete: 0x4c,
end: 0x4d,
pagedown: 0x4e,
arrowright: 0x4f,
arrowleft: 0x50,
arrowdown: 0x51,
arrowup: 0x52,
numlock: 0x53,
numpaddivide: 0x54,
numpadmultiply: 0x55,
numpadsubstract: 0x56,
numpadadd: 0x57,
numpadenter: 0x58,
numpad1: 0x59,
numpad2: 0x5a,
numpad3: 0x5b,
numpad4: 0x5c,
numpad5: 0x5d,
numpad6: 0x5e,
numpad7: 0x5f,
numpad8: 0x60,
numpad9: 0x61,
numpad0: 0x62,
numpaddecimal: 0x63,
numpadequal: 0x67,
f13: 0x68,
f14: 0x69,
f15: 0x6a,
f16: 0x6b,
f17: 0x6c,
f18: 0x6d,
f19: 0x6e,
f20: 0x6f,
f21: 0x70,
f22: 0x71,
f23: 0x72,
f24: 0x73,
execute: 0x74,
help: 0x75,
contextmenu: 0x76,
select: 0x77,
stop: 0x78,
again: 0x79,
undo: 0x7a,
cut: 0x7b,
copy: 0x7c,
paste: 0x7d,
find: 0x7e,
mute: 0x7f,
volumeup: 0x80,
volumedown: 0x81,
numpadcomma: 0x85,
}
export const reverseSelectors: { [index: number]: string } = Object.keys(
selectors
).reduce((r, key) => {
if (!r[selectors[key]]) r[selectors[key]] = key
return r
}, {} as { [index: number]: string })
export const modifierCodes = {
controlleft: HidKeyboardModifiers.LeftControl,
altleft: HidKeyboardModifiers.LeftAlt,
shiftleft: HidKeyboardModifiers.LeftShift,
metaleft: HidKeyboardModifiers.LeftGUI,
controlright: HidKeyboardModifiers.RightControl,
altright: HidKeyboardModifiers.RightAlt,
shiftright: HidKeyboardModifiers.RightShift,
metaright: HidKeyboardModifiers.RightGUI,
}
export function renderKeyboardKey(
selector: number,
modifiers: HidKeyboardModifiers,
pretty: boolean
) {
const flags = pretty
? [
"Ctrl",
"Shift",
"Alt",
"Cmd",
"Ctrl Right",
"Shift Right",
"AltRight",
"Cmd Right",
]
: [
"{controlleft}",
"{shiftleft}",
"{altleft}",
"{metaleft}",
"{controlright}",
"{shiftright}",
"{altright}",
"{metaright}",
]
const sep = pretty ? " + " : " "
const values = []
flags.forEach((flag, i) => {
if (modifiers & (1 << i)) {
values.push(flag)
}
})
const sel = reverseSelectors[selector]
if (sel !== undefined)
values.push(
pretty
? sel.toUpperCase()
: !pretty && sel.length > 1
? `{${sel}}`
: sel
)
const value = values.filter(v => !!v).join(sep)
return value
}
| 20.352713
| 80
| 0.513997
|
bb30c753291ddfb579cd9cf3183a63c761c2b1f1
| 693
|
cs
|
C#
|
src/Marvin.JsonPatch/Helpers/JsonPatchProperty.cs
|
aaxelm/JsonPatch.NetStandard
|
1df0cddf140d66bfc5bb201850497b981e1b014c
|
[
"MIT"
] | 1
|
2020-01-04T11:45:07.000Z
|
2020-01-04T11:45:07.000Z
|
src/Marvin.JsonPatch/Helpers/JsonPatchProperty.cs
|
aaxelm/JsonPatch.NetStandard
|
1df0cddf140d66bfc5bb201850497b981e1b014c
|
[
"MIT"
] | null | null | null |
src/Marvin.JsonPatch/Helpers/JsonPatchProperty.cs
|
aaxelm/JsonPatch.NetStandard
|
1df0cddf140d66bfc5bb201850497b981e1b014c
|
[
"MIT"
] | null | null | null |
using Newtonsoft.Json.Serialization;
namespace Marvin.JsonPatch.Helpers
{
/// <summary>
/// Metadata for JsonProperty.
/// </summary>
public class JsonPatchProperty
{
/// <summary>
/// Initializes a new instance.
/// </summary>
public JsonPatchProperty(JsonProperty property, object parent)
{
Property = property;
Parent = parent;
}
/// <summary>
/// Gets or sets JsonProperty.
/// </summary>
public JsonProperty Property { get; set; }
/// <summary>
/// Gets or sets Parent.
/// </summary>
public object Parent { get; set; }
}
}
| 23.1
| 70
| 0.533911
|
02c917b230168e05d5c19fecf4033164e612a287
| 1,149
|
hpp
|
C++
|
src/utils/DisplayConfiguration.hpp
|
bonnefoa/flowstats
|
64f3e2d4466596788174b508bc62838379162224
|
[
"MIT"
] | 4
|
2020-07-21T12:34:26.000Z
|
2020-12-09T16:51:33.000Z
|
src/utils/DisplayConfiguration.hpp
|
bonnefoa/flowstats
|
64f3e2d4466596788174b508bc62838379162224
|
[
"MIT"
] | null | null | null |
src/utils/DisplayConfiguration.hpp
|
bonnefoa/flowstats
|
64f3e2d4466596788174b508bc62838379162224
|
[
"MIT"
] | 1
|
2020-07-21T12:34:31.000Z
|
2020-07-21T12:34:31.000Z
|
#pragma once
#include "Field.hpp"
#include "enum.h"
#include <string>
#include <vector>
namespace flowstats {
class DisplayConfiguration {
public:
DisplayConfiguration();
auto updateFieldSize(Field field, int delta) -> void;
auto emptyFilter() { filter = ""; };
auto addFilterChar(int c) { filter.push_back(c); };
auto removeFilterChar() { filter.pop_back(); };
auto toggleMergedDirection() { mergeDirection = !mergeDirection; };
auto setMaxResults(int newMaxResults) { maxResults = newMaxResults; };
auto nextRateMode() -> void;
auto previousRateMode() -> void;
[[nodiscard]] auto getFieldToSize() const& { return fieldToSize; };
[[nodiscard]] auto getFilter() const& { return filter; };
[[nodiscard]] auto getMaxResults() const { return maxResults; };
[[nodiscard]] auto getMergeDirection() const { return mergeDirection; };
[[nodiscard]] auto getRateMode() const { return rateMode; };
private:
std::vector<int> fieldToSize;
std::string filter;
bool mergeDirection = true;
int maxResults = 1000;
RateMode rateMode = +RateMode::AVG;
};
} // namespace flowstats
| 27.357143
| 76
| 0.678851
|
bdef64756a0f4fe59beb144cf0e837e4a6decaa4
| 617
|
rb
|
Ruby
|
db/migrate/20200904124305_create_comments.rb
|
alexisperrier/ragnar
|
8f3886dd7ab09719df7913f2aba55abb54e16433
|
[
"MIT"
] | null | null | null |
db/migrate/20200904124305_create_comments.rb
|
alexisperrier/ragnar
|
8f3886dd7ab09719df7913f2aba55abb54e16433
|
[
"MIT"
] | 7
|
2021-05-21T00:43:02.000Z
|
2022-03-31T01:50:54.000Z
|
db/migrate/20200904124305_create_comments.rb
|
alexisperrier/ragnar
|
8f3886dd7ab09719df7913f2aba55abb54e16433
|
[
"MIT"
] | null | null | null |
class CreateComments < ActiveRecord::Migration[5.2]
def change
create_table :comments do |t|
t.string :comment_id
t.string :video_id
t.string :discussion_id
t.string :parent_id
t.string :author_name
t.string :author_channel_id
t.string :text
t.integer :reply_count
t.integer :like_count
t.datetime :published_at
t.timestamps
end
add_index :comments, [:video_id], :unique => false
add_index :comments, [:discussion_id], :unique => false
end
end
| 29.380952
| 63
| 0.567261
|
726645296de1754f08f9c12d599d66e826afe70c
| 2,469
|
dart
|
Dart
|
lib/oboe.dart
|
ymzuiku/oboe
|
26951b5a78e2a3199c96930d81438ab0a610e361
|
[
"BSD-2-Clause"
] | 3
|
2021-06-21T17:43:22.000Z
|
2021-08-23T06:41:22.000Z
|
lib/oboe.dart
|
ymzuiku/oboe
|
26951b5a78e2a3199c96930d81438ab0a610e361
|
[
"BSD-2-Clause"
] | null | null | null |
lib/oboe.dart
|
ymzuiku/oboe
|
26951b5a78e2a3199c96930d81438ab0a610e361
|
[
"BSD-2-Clause"
] | null | null | null |
library oboe;
import 'dart:async';
import 'package:flutter/material.dart';
/// ## Oboe
///
/// > Oboe is like react.Consumer
///
/// Oboe is only one at project; it's single class.
/// Oboe have getState, and setState.
/// setState is trigger all stream listen, update state and call all Oboe widget update.
/// build is use _SubWidget create a StatefulWidget, and subscribe Oboe at _SubWidget.
class Oboe {
late StreamController _controller;
late Stream _stream;
Oboe() {
_controller = StreamController.broadcast();
_stream = _controller.stream;
}
Widget ob(Widget Function() builder, {List<dynamic> Function()? memo}) {
return _SubWidget(_stream, builder, memo);
}
next() {
_controller.add(true);
}
}
/// ## _SubWidget
///
/// > _SubWidget is like react.context.consumer style's state manage widget
///
/// builder[required]: use return widget
/// memo[options]: (state) => [], like react.useMemo, only array object is changed, widget can be update
/// _SubWidget listen Store.stream at initState, and cancel listen at widget dispose.
class _SubWidget extends StatefulWidget {
final Stream stream;
final List<dynamic> Function()? memo;
final Widget Function() builder;
_SubWidget(this.stream, this.builder, this.memo, {Key? key})
: super(key: key);
@override
_SubWidgetState createState() => _SubWidgetState(stream, memo, builder);
}
class _SubWidgetState extends State<_SubWidget> {
late StreamSubscription _sub;
late List<dynamic> _lastMemo;
final Stream _stream;
final List<dynamic> Function()? _memo;
final Widget Function() _builder;
_SubWidgetState(this._stream, this._memo, this._builder);
@override
void initState() {
super.initState();
_lastMemo = _memo == null ? [] : [..._memo!()];
_sub = _stream.listen((data) {
if (!mounted) {
return;
}
if (_memo == null) {
setState(() {});
} else if (_lastMemo.length > 0) {
bool isUpdate = false;
List nowMemo = [..._memo!()];
for (var i = 0; i < _lastMemo.length; i++) {
if (_lastMemo[i] != nowMemo[i]) {
isUpdate = true;
break;
}
}
if (isUpdate == true) {
_lastMemo = nowMemo;
setState(() {});
}
}
});
}
@override
void dispose() {
super.dispose();
_sub.cancel();
}
@override
Widget build(BuildContext context) {
return _builder();
}
}
| 24.69
| 104
| 0.631025
|
da4c9c34c8c444a72e905e4260df82d9d6ff0716
| 1,000
|
php
|
PHP
|
resources/views/layout/header_pembelian.blade.php
|
FahriKhalid/SUM
|
280bde9f7efecd72471944e0550555a977d31473
|
[
"MIT"
] | 1
|
2021-05-18T03:24:15.000Z
|
2021-05-18T03:24:15.000Z
|
resources/views/layout/header_pembelian.blade.php
|
FahriKhalid/SUM
|
280bde9f7efecd72471944e0550555a977d31473
|
[
"MIT"
] | null | null | null |
resources/views/layout/header_pembelian.blade.php
|
FahriKhalid/SUM
|
280bde9f7efecd72471944e0550555a977d31473
|
[
"MIT"
] | null | null | null |
<div class="height-100 bg-white shadow-sm">
<ul class="nav nav-tabs nav-justified" id="myTab" role="tablist">
<li class="nav-item">
<a class="nav-link text-muted {{ Request::segment(2) == 'pre_order' ? 'active' : ''}}" href="{{ url('pembelian/pre_order/show/'.$id) }}">Pre Order</a>
</li>
<li class="nav-item">
<a class="nav-link text-muted {{ Request::segment(2) == 'skpp' ? 'active' : ''}}" href="{{ url('pembelian/skpp/show/'.$id) }}">SKPP</a>
</li>
<li class="nav-item">
<a class="nav-link text-muted {{ Request::segment(2) == 'salesorder' ? 'active' : ''}}" href="{{ url('pembelian/salesorder/show/'.$id) }}">Sales Order</a>
</li>
<li class="nav-item">
<a class="nav-link text-muted {{ Request::segment(2) == 'invoice' ? 'active' : ''}}" href="{{ url('pembelian/invoice/index/'.$id) }}">Invoice</a>
</li>
<span class="nav-indicator"></span>
</ul>
</div>
| 58.823529
| 166
| 0.527
|
df8e7f6387ca34fe201f9db936f9810723da3dac
| 137
|
cs
|
C#
|
FinSharp/src/Entities/Commodity.cs
|
klinki/finsharp
|
b0d24442c132ab7882cb6b1bbf48062d3d789eaf
|
[
"MIT"
] | null | null | null |
FinSharp/src/Entities/Commodity.cs
|
klinki/finsharp
|
b0d24442c132ab7882cb6b1bbf48062d3d789eaf
|
[
"MIT"
] | null | null | null |
FinSharp/src/Entities/Commodity.cs
|
klinki/finsharp
|
b0d24442c132ab7882cb6b1bbf48062d3d789eaf
|
[
"MIT"
] | null | null | null |
using System;
using System.Collections.Generic;
using System.Text;
namespace FinSharp.Api.Entities
{
class Commodity
{
}
}
| 12.454545
| 33
| 0.708029
|
4be4e9d8e484496233a86d34b0a9ca874bd43888
| 742
|
h
|
C
|
Implementations/content/data-structures/1D Range Queries (9.2)/BITrange.h
|
pnchinmay/USACO
|
717696d69d0f260eb077a5d267de0f803d89e06e
|
[
"CC0-1.0"
] | null | null | null |
Implementations/content/data-structures/1D Range Queries (9.2)/BITrange.h
|
pnchinmay/USACO
|
717696d69d0f260eb077a5d267de0f803d89e06e
|
[
"CC0-1.0"
] | null | null | null |
Implementations/content/data-structures/1D Range Queries (9.2)/BITrange.h
|
pnchinmay/USACO
|
717696d69d0f260eb077a5d267de0f803d89e06e
|
[
"CC0-1.0"
] | 1
|
2021-06-12T05:27:34.000Z
|
2021-06-12T05:27:34.000Z
|
/**
* Description: 1D range increment and sum query.
* Possible for higher dimensions.
* Source: https://www.geeksforgeeks.org/binary-indexed-tree-range-update-range-queries/
* Verification: CSES
* Time: O(\log N)
*/
#include "BIT (9.2).h"
template<class T, int SZ> struct BITrange {
BIT<T,SZ> bit[2]; // piecewise linear functions
// let cum[x] = sum_{i=1}^{x}a[i]
void upd(int hi, T val) { // add val to a[1..hi]
// if x <= hi, cum[x] += val*x
bit[1].upd(1,val), bit[1].upd(hi+1,-val);
// if x > hi, cum[x] += val*hi
bit[0].upd(hi+1,hi*val);
}
void upd(int lo,int hi,T val){upd(lo-1,-val),upd(hi,val);}
T sum(int x) { return bit[1].sum(x)*x+bit[0].sum(x); }
T query(int x, int y) { return sum(y)-sum(x-1); }
};
| 30.916667
| 88
| 0.603774
|
e2d685b2b16223505f4de0741358a36023cbbc1e
| 537
|
py
|
Python
|
binary_search.py
|
matteoalberici4/algorithms
|
4ce633f324bb0c945661bd5fdfcf214470fa0562
|
[
"Apache-2.0"
] | null | null | null |
binary_search.py
|
matteoalberici4/algorithms
|
4ce633f324bb0c945661bd5fdfcf214470fa0562
|
[
"Apache-2.0"
] | null | null | null |
binary_search.py
|
matteoalberici4/algorithms
|
4ce633f324bb0c945661bd5fdfcf214470fa0562
|
[
"Apache-2.0"
] | null | null | null |
# Binary search
def binary_search(A: list, x: int):
i = 0
j = len(A)
while i < j:
m = (i + j) // 2
if A[m] == x:
return True
elif A[m] > x:
j = m
else:
i = m + 1
return False
def recursive_binary_search(A: list, x: int, start: int, end: int):
if end >= start:
m = start + (end - start) // 2
if A[m] == x:
return m
elif A[m] > m:
return recursive_binary_search(A, start, m - 1, x)
else:
return recursive_binary_search(A, m + 1, end, x)
else:
return -1
| 20.653846
| 67
| 0.519553
|
437b10142f32ddab9db8214b2b80151ef83cdab5
| 4,113
|
ts
|
TypeScript
|
EndGate/EndGate.Core.JS/Rendering/Renderer2d.ts
|
NTaylorMullen/EndGate
|
95a2d0cf82a84bb9994f00f2074e2ca5663c9bb9
|
[
"MIT"
] | 36
|
2015-02-03T21:16:37.000Z
|
2022-02-11T23:31:32.000Z
|
EndGate/EndGate.Core.JS/Rendering/Renderer2d.ts
|
paulvanbrenk/EndGate
|
99adab6039a2653d933a26026e6c16c894ace96b
|
[
"MIT"
] | 1
|
2016-08-01T10:46:42.000Z
|
2016-08-01T10:46:42.000Z
|
EndGate/EndGate.Core.JS/Rendering/Renderer2d.ts
|
paulvanbrenk/EndGate
|
99adab6039a2653d933a26026e6c16c894ace96b
|
[
"MIT"
] | 11
|
2015-06-26T13:31:23.000Z
|
2019-11-08T14:27:12.000Z
|
/// <reference path="IRenderer.ts" />
/// <reference path="IRenderable.ts" />
/// <reference path="../Interfaces/IDisposable.ts" />
/// <reference path="../Utilities/EventHandler1.ts" />
/// <reference path="../Assets/Sizes/Size2d.ts" />
module EndGate.Rendering {
/**
* Defines a 2d renderer that uses a double buffer to draw graphics.
*/
export class Renderer2d implements IDisposable, _.IRenderer {
public static _zindexSort: (a: IRenderable, b: IRenderable) => number = (a: IRenderable, b: IRenderable) => { return a.ZIndex - b.ZIndex; };
public _BufferCanvas: HTMLCanvasElement;
public _BufferContext: CanvasRenderingContext2D; // Protected
// These essentially are used to create a double buffer for rendering
private _visibleCanvas: HTMLCanvasElement;
private _visibleContext: CanvasRenderingContext2D;
private _disposed: boolean;
private _onRendererSizeChange: EventHandler1<Size2d>;
/**
* Creates a new instance of the Renderer2d object.
* @param renderOnto The canvas to render onto.
*/
constructor(renderOnto: HTMLCanvasElement) {
this._visibleCanvas = renderOnto;
this._visibleContext = renderOnto.getContext("2d");
// Create an equally sized canvas for a buffer
this._BufferCanvas = <HTMLCanvasElement>document.createElement("canvas");
this._BufferContext = this._BufferCanvas.getContext("2d");
this._onRendererSizeChange = new EventHandler1<Size2d>();
this.UpdateBufferSize();
this._disposed = false;
}
/**
* Gets an event that is triggered when the renderOnto canvas changes size. Functions can be bound or unbound to this event to be executed when the event triggers.
*/
public get OnRendererSizeChange(): EventHandler1<Size2d> {
return this._onRendererSizeChange;
}
/**
* Renders the provided renderables onto the renderOnto canvas. Returns the canvas that was rendered onto.
* @param renderables Array of items that are to be rendered, assumes Visible is set to true.
*/
public Render(renderables: IRenderable[]): CanvasRenderingContext2D {
// Check if our visible canvas has changed size
if (this._BufferCanvas.width !== this._visibleCanvas.width || this._BufferCanvas.height !== this._visibleCanvas.height) {
this.UpdateBufferSize();
}
// Push buffer to screen
this._visibleContext.clearRect(0, 0, this._visibleCanvas.width, this._visibleCanvas.height);
this._visibleContext.drawImage(this._BufferCanvas, 0, 0);
// Clear our buffer to prepare it for new drawings
this._ClearBuffer();
// Sort the renderables by the ZIndex so we draw in the correct order (for layering);
renderables.sort(Renderer2d._zindexSort);
// We do not save or restore the canvas state because we want to let the
// dev decide how they manipulate the canvas
for (var i = 0; i < renderables.length; i++) {
renderables[i].Draw(this._BufferContext);
}
return this._BufferContext;
}
/**
* Destroys the visible canvas.
*/
public Dispose(): void {
if (!this._disposed) {
this._disposed = true;
this._visibleCanvas.parentNode.removeChild(this._visibleCanvas);
this._onRendererSizeChange.Dispose();
}
}
public _ClearBuffer() {
this._BufferContext.clearRect(0, 0, this._BufferCanvas.width, this._BufferCanvas.height);
}
private UpdateBufferSize() {
this._BufferCanvas.width = this._visibleCanvas.width;
this._BufferCanvas.height = this._visibleCanvas.height;
this.OnRendererSizeChange.Trigger(new Size2d(this._visibleCanvas.width, this._visibleCanvas.height))
}
}
}
| 41.13
| 171
| 0.631413
|
2ccf57f2a1bd5bd7375b6faeb9760a2bb5378114
| 734
|
py
|
Python
|
intro_to_ml/data_exploration.py
|
Ragnarok540/kaggle_courses
|
1b52a9ae93493d36c792773f8ecc3b0d3751cda1
|
[
"MIT"
] | null | null | null |
intro_to_ml/data_exploration.py
|
Ragnarok540/kaggle_courses
|
1b52a9ae93493d36c792773f8ecc3b0d3751cda1
|
[
"MIT"
] | null | null | null |
intro_to_ml/data_exploration.py
|
Ragnarok540/kaggle_courses
|
1b52a9ae93493d36c792773f8ecc3b0d3751cda1
|
[
"MIT"
] | null | null | null |
import pandas as pd
# save filepath to variable for easier access
melbourne_file_path = '../data/melb_data.csv'
# read the data and store data in DataFrame titled melbourne_data
melbourne_data = pd.read_csv(melbourne_file_path)
# print a summary of the data in Melbourne data
desc = melbourne_data.describe()
print('Data description:')
print(desc)
# What is the average building area (rounded to nearest integer)?
avg_building_area = round(melbourne_data['BuildingArea'].mean())
print(f'Average building area: {avg_building_area}')
# As of today, how old is the newest home (current year - the date in which it was built)
newest_home_age = (2020 - melbourne_data['YearBuilt']).min()
print(f'Newest home age: {newest_home_age}')
| 34.952381
| 89
| 0.771117
|
83420c090ee35b30d039f2b90edf989e1686ad29
| 2,852
|
ts
|
TypeScript
|
src/app/services/eventlist.service.ts
|
alexeyvasilyev/tinycamcloud-client-web
|
09a7abcedda5d73e30c80302d2e3d938ef38e09c
|
[
"Apache-2.0"
] | 3
|
2020-08-25T02:21:37.000Z
|
2020-09-29T11:58:21.000Z
|
src/app/services/eventlist.service.ts
|
alexeyvasilyev/tinycamcloud-client-web
|
09a7abcedda5d73e30c80302d2e3d938ef38e09c
|
[
"Apache-2.0"
] | null | null | null |
src/app/services/eventlist.service.ts
|
alexeyvasilyev/tinycamcloud-client-web
|
09a7abcedda5d73e30c80302d2e3d938ef38e09c
|
[
"Apache-2.0"
] | 1
|
2021-06-03T21:31:56.000Z
|
2021-06-03T21:31:56.000Z
|
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Login, Server, EventRecord, ServerResponse } from '../models'
import 'rxjs/add/operator/toPromise';
@Injectable()
export class EventListService {
private MIN_DURATION_EVENT_MSEC = 3000;
constructor(private http: HttpClient) {
}
getEventListByDate(server: Server, login: Login, camId: number, date: Date, limit: number): Promise<EventRecord[]> {
return this.getEventList(server, login, camId, -1, date, limit, this.MIN_DURATION_EVENT_MSEC);
}
getEventListById(server: Server, login: Login, camId: number, eventId: number, limit: number): Promise<EventRecord[]> {
return this.getEventList(server, login, camId, eventId, null, limit, this.MIN_DURATION_EVENT_MSEC);
}
private getEventList(server: Server, login: Login, camId: number, eventId: number, date: Date, limit: number, minDuration: number): Promise<EventRecord[]> {
// console.log('getEventList(camId=' + camId + ', eventId=' + eventId + ', date=' + date + ', limit=' + limit + ')');
// {"login":"eu","pwd":"9fd858c200d2cad1d6b5e587e96e6dfb1e6a8bd9de359861608800f052327f57","event":{"event_id":0,"limit":25,"is_finished":1}}
let jsonLogin = login.toJSON();
var jsonEvent: any;
if (eventId < 0) {
jsonEvent = {
event: {
date: date.toISOString(),
limit: limit,
min_duration: minDuration
}
};
} else {
jsonEvent = {
event: {
event_id: eventId,
limit: limit,
min_duration: minDuration
}
};
}
var jsonCam = {};
if (camId != -1) {
jsonCam = {
cam: {
cam_id: camId
}
};
}
const jsonCombined = Object.assign(jsonLogin, jsonEvent, jsonCam);
const postData = JSON.stringify(jsonCombined);
const camListUrl = `https://${server.server_addr}/v1/event_list.php`;
return this.http
.post<ServerResponse>(camListUrl, postData)
.toPromise()
.then((res:ServerResponse) => res.data as EventRecord[])
.catch(this.handleError);
//[{"id":10,"cam_id":1444908568,"date":"2015-10-19 13:50:05","image":"2015-10-19_16:50:05_sen786945787.jpg",
// "video":"2015-10-19_16:50:05_rec.mp4","video_offset":17183,"duration":null,"has_audio":0,
// "has_video":1,"audio_level":0,"video_level":786945787}]
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}
| 38.540541
| 160
| 0.577489
|
23954b8c61f927ecb46188029ff8891e2ff25f56
| 406
|
js
|
JavaScript
|
server/methods.js
|
emminnn/donactions
|
0499a938263a8fe6e7f3bad99534767122fc63de
|
[
"CC0-1.0"
] | null | null | null |
server/methods.js
|
emminnn/donactions
|
0499a938263a8fe6e7f3bad99534767122fc63de
|
[
"CC0-1.0"
] | null | null | null |
server/methods.js
|
emminnn/donactions
|
0499a938263a8fe6e7f3bad99534767122fc63de
|
[
"CC0-1.0"
] | null | null | null |
Meteor.methods({
addAction: function(title, intro, category, brief) {
// Make sure the user is logged in before inserting a task
if (! Meteor.userId()) {
throw new Meteor.Error("not-authorized");
} else {
MyActions.insert({
'title': title,
'intro': intro,
'category': category,
'brief': brief,
'added_by': Meteor.userId()
});
}
}
});
| 25.375
| 62
| 0.564039
|
06ff41a7124cf90899f7413737f96e1f1bb07f6a
| 3,438
|
py
|
Python
|
hier_elbo.py
|
altosaar/hierarchical-variational-models-physics
|
611d91e0281664d7d5ba1679bec7adfb3aac41e2
|
[
"MIT"
] | 14
|
2020-05-10T20:44:49.000Z
|
2022-01-12T23:06:24.000Z
|
hier_elbo.py
|
altosaar/hierarchical-variational-models-physics
|
611d91e0281664d7d5ba1679bec7adfb3aac41e2
|
[
"MIT"
] | null | null | null |
hier_elbo.py
|
altosaar/hierarchical-variational-models-physics
|
611d91e0281664d7d5ba1679bec7adfb3aac41e2
|
[
"MIT"
] | null | null | null |
import numpy as np
import collections
import torch
from tqdm import tqdm
from .mean_field_elbo import MeanFieldELBO
class HierarchicalELBO(MeanFieldELBO):
def __init__(self,
config,
model,
variational_likelihood,
variational_prior,
variational_posterior,
proximity_loss=None
):
super().__init__(config, model, variational_likelihood)
self.config = config
self.p_z = model
self.q_z = variational_likelihood
self.q_nu = variational_prior
self.r_nu = variational_posterior
self.proximity_loss = None
def set_proximity_loss(self, proximity_loss):
self.proximity_loss = proximity_loss
@torch.no_grad()
def sample_objective(self, num_samples, batch_size=2**13):
cfg = self.config
res = []
assert num_samples >= batch_size
for _ in tqdm(range(num_samples // batch_size)):
hier_elbo = self.sample_objective_single_batch(batch_size)
res.extend(hier_elbo.tolist())
return res
@torch.no_grad()
def sample_objective_single_batch(self, batch_size, return_terms=False):
nu, log_q_nu = self.q_nu.sample_and_log_prob(num_samples=batch_size)
z = self.q_z.sample(logit=nu)
nu_0, log_r_i_nu, log_r_nu = self.r_nu.inverse_and_log_prob(nu, z)
if log_r_i_nu is not None:
dims = tuple(range(1, log_r_i_nu.ndim))
log_r_nu = log_r_i_nu.sum(dims) + log_r_nu
log_q_z = self.q_z.log_prob(logit=nu, value=z).sum((1, 2))
log_p_z = -self.config.beta * self.p_z.energy(z)
hier_elbo = (log_p_z - log_q_z + log_r_nu - log_q_nu).squeeze()
if return_terms:
res = {'log_p_z': log_p_z,
'log_q_z_entropy': -log_q_z,
'log_r_nu': log_r_nu,
'log_q_nu': log_q_nu,
'nu': nu,
'nu_0': nu_0}
return {k: v.cpu().numpy() for k, v in res.items()}
else:
return hier_elbo.cpu().detach().numpy()
def compute_grad(self, annealing_temp=1.0):
cfg = self.config
nu, log_q_nu = self.q_nu.sample_and_log_prob(cfg.num_samples_grad)
z = self.q_z.sample(logit=nu)
_, log_r_i_nu, log_r_nu = self.r_nu.inverse_and_log_prob(nu, z)
dims = tuple(range(1, log_r_nu.ndim))
if log_r_i_nu is not None:
log_r_nu = log_r_i_nu.sum(dims) + log_r_nu # (num_samples,)
log_r_i_nu = log_r_i_nu.detach() # (num_samples, L, L)
E_del_nu_z_i_terms = super().compute_grad_natural_parameters(
logit=nu,
z=z,
log_r_i_nu=log_r_i_nu,
annealing_temp=annealing_temp)
hier_elbo_pre_grad = (
# yields del_theta nu(eps; theta) del_nu L_{MF}
# both have 2 lattice dimensions; sum over these
(nu * E_del_nu_z_i_terms).sum(dims)
# yields E_q(z | nu) [del_theta nu(eps; theta) * del_nu log r(nu | z)]
+ log_r_nu / annealing_temp
# yields del_theta nu(eps; theta) del_nu log q(nu; theta)
- log_q_nu
) # do not take expectation over s(epsilon), only after adding proximity loss
# loss is negative elbo
loss = -hier_elbo_pre_grad
if self.proximity_loss is not None:
tensor_dict = {'log_q_nu': log_q_nu, 'log_r_nu': log_r_nu}
loss += self.proximity_loss.compute_total_constraint(tensor_dict)
self.proximity_loss.moving_average.update(tensor_dict)
# take expectation over s(epsilon) and compute gradients
loss.mean(0).backward()
| 37.369565
| 86
| 0.661431
|
7f2255474be2506b19bfe3bab150043d5bedbfbd
| 1,562
|
cs
|
C#
|
Eliza/Memory.cs
|
ishanshastri/Eliza_ChatBot
|
ce4e0a74dd59bc7561ad2b2ca0fb6634760dc265
|
[
"MIT"
] | null | null | null |
Eliza/Memory.cs
|
ishanshastri/Eliza_ChatBot
|
ce4e0a74dd59bc7561ad2b2ca0fb6634760dc265
|
[
"MIT"
] | null | null | null |
Eliza/Memory.cs
|
ishanshastri/Eliza_ChatBot
|
ce4e0a74dd59bc7561ad2b2ca0fb6634760dc265
|
[
"MIT"
] | null | null | null |
using System.Collections.Generic;
using System.Linq;
namespace Eliza
{
/// <summary>
/// Eliza's memory.
/// </summary>
public class Memory
{
#region Public methods
/// <summary>
/// Adds text to the memory, if not already present.
/// </summary>
/// <param name="text">The text to be added.</param>
public void AddText
(string text)
{
if (!this._memory.Contains(text)) {
this._memory.Add(text);
}
}
/// <summary>
/// Gets (and removes) the oldest text (if any) from the memory.
///
/// </summary>
/// <returns>The text.</returns>
public string GetOldestText()
{
string ret = null;
if (this._memory.Any()) {
ret = this._memory.First();
this._memory.Remove(ret);
}
return ret;
}
/// <summary>
/// Determines whether this instance is empty.
/// </summary>
/// <returns>
/// <langword cref="true"/> if the memory is empty, otherwise <langword cref="false"/>.
/// </returns>
public bool IsEmpty()
{
return !this._memory.Any();
}
#endregion
#region Fields
/// <summary>
/// Eliza's memory.
/// </summary>
private List<string> _memory = new List<string>();
#endregion
}
}
| 24.793651
| 96
| 0.455826
|
fac5cec61c7b83af53b80da59d59031b95a6a879
| 2,221
|
dart
|
Dart
|
packages/ranking_note_app/lib/commands/update_ranking_member_order.dart
|
John-Thailand/flutter_app_template
|
d2bcf99982667f68b07cbec5d6a0e7ff8d95be49
|
[
"MIT"
] | null | null | null |
packages/ranking_note_app/lib/commands/update_ranking_member_order.dart
|
John-Thailand/flutter_app_template
|
d2bcf99982667f68b07cbec5d6a0e7ff8d95be49
|
[
"MIT"
] | null | null | null |
packages/ranking_note_app/lib/commands/update_ranking_member_order.dart
|
John-Thailand/flutter_app_template
|
d2bcf99982667f68b07cbec5d6a0e7ff8d95be49
|
[
"MIT"
] | null | null | null |
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:sort_key_generator/sort_key_generator.dart';
import 'package:tuple/tuple.dart';
import '../domain/my_ranking/entities/ranking_member.dart';
import '../domain/my_ranking/references/my_ranking_member_reference.dart';
final updateRankingMemberOrder =
Provider((ref) => UpdateRankingMemberOrder(ref.read));
/// ランキングメンバーのランク(並び順序)を更新する
class UpdateRankingMemberOrder {
const UpdateRankingMemberOrder(this._read);
final Reader _read;
DocumentReference<RankingMember> _myRankingMemberDocRef({
required String rankingId,
required String memberId,
}) {
return _read(myRankingMemberDocRefProvider(
Tuple2(
rankingId,
memberId,
),
));
}
Future<void> call({
required String rankingId,
required String memberId,
required List<QueryDocumentSnapshot<RankingMember>> memberDocs,
required RankingMember oldMember,
required int newIndex,
}) async {
final previousIndex = newIndex - 1;
final previous = previousIndex.isNegative
? null
: memberDocs[previousIndex].data().order;
final nextIndex = newIndex + 1;
final next = nextIndex >= memberDocs.length
? null
: memberDocs[nextIndex].data().order;
final newOrder = generateSortKeyDouble(
previous: previous,
next: next,
);
if (newOrder == null) {
// 1075回を超えて並び替えされたため失敗。全ドキュメントにorderを振り直す必要あり。
final newDocs = <QueryDocumentSnapshot<RankingMember>>[];
for (var i = 0; i < memberDocs.length; i++) {
final memberDoc = memberDocs[i];
await memberDoc.reference.set(
memberDoc.data().copyWith(order: i.toDouble()),
);
newDocs.add(memberDoc);
}
// 再実行
return call(
rankingId: rankingId,
memberId: memberId,
memberDocs: newDocs,
oldMember: oldMember,
newIndex: newIndex,
);
}
final memberRef = _myRankingMemberDocRef(
rankingId: rankingId,
memberId: memberId,
);
final newMember = oldMember.copyWith(order: newOrder);
await memberRef.set(newMember);
}
}
| 29.613333
| 74
| 0.677623
|
f425f5843552a5db73dd9025976e8712938a43cd
| 1,733
|
cs
|
C#
|
VKLoader/VKPhotoResolution.cs
|
klujanrosas/VKLoader
|
aaa71cdc0d390df9db44bf4ca9a3a446dc63e857
|
[
"MIT"
] | null | null | null |
VKLoader/VKPhotoResolution.cs
|
klujanrosas/VKLoader
|
aaa71cdc0d390df9db44bf4ca9a3a446dc63e857
|
[
"MIT"
] | null | null | null |
VKLoader/VKPhotoResolution.cs
|
klujanrosas/VKLoader
|
aaa71cdc0d390df9db44bf4ca9a3a446dc63e857
|
[
"MIT"
] | null | null | null |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/*
Copyright (c) 2016 Kenneth Luján R.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
For further advice contact me at : klujanrosas@gmail.com
*/
namespace VKLoader
{
public class VKPhotoResolution
{
public int width { get; set; }
public int height { get; set; }
public string url { get; set; }
public VKPhotoResolution()
{
}
public VKPhotoResolution(int w, int h, string url)
{
width = w;
height = h;
this.url = url;
}
}
}
| 36.87234
| 163
| 0.684939
|
38612411ee75c8a5741184d341b156ce1081ff5d
| 892
|
php
|
PHP
|
src/SerializedRecordStorage.php
|
kapitancho/walnut-lib-recordstorage
|
f884ec94367240135e1260c580c2cde564a27965
|
[
"MIT"
] | null | null | null |
src/SerializedRecordStorage.php
|
kapitancho/walnut-lib-recordstorage
|
f884ec94367240135e1260c580c2cde564a27965
|
[
"MIT"
] | null | null | null |
src/SerializedRecordStorage.php
|
kapitancho/walnut-lib-recordstorage
|
f884ec94367240135e1260c580c2cde564a27965
|
[
"MIT"
] | null | null | null |
<?php
namespace Walnut\Lib\RecordStorage;
use Walnut\Lib\RecordStorage\ArrayDataSerializer\ArrayDataSerializer;
use Walnut\Lib\RecordStorage\KeyValueStorage\KeyValueStorage;
/**
* @package Walnut\Lib\RecordStorage
*/
final class SerializedRecordStorage implements RecordStorage {
public function __construct(
private readonly ArrayDataSerializer $dataSerializer,
private readonly KeyValueStorage $keyValueStorage
) { }
/**
* @param string $key
* @return array[]
*/
public function retrieveRecords(string $key): array {
/**
* @var array[]
*/
return $this->dataSerializer->unserialize(
$this->keyValueStorage->retrieve($key)
);
}
/**
* @param string $key
* @param array[] $records
*/
public function storeRecords(string $key, array $records): void {
$this->keyValueStorage->store($key,
$this->dataSerializer->serialize($records)
);
}
}
| 21.756098
| 69
| 0.716368
|
b550062d9a8c662d89510b698fb00f45f1735e59
| 2,651
|
rb
|
Ruby
|
recipes/dashboard.rb
|
openstack/cookbook-openstack-application-catalog
|
65b4895f9c9cf3ff4faf552ce017dd99d88677ca
|
[
"Apache-2.0"
] | 9
|
2016-09-30T15:46:10.000Z
|
2019-01-28T21:54:39.000Z
|
recipes/dashboard.rb
|
openstack/cookbook-openstack-application-catalog
|
65b4895f9c9cf3ff4faf552ce017dd99d88677ca
|
[
"Apache-2.0"
] | null | null | null |
recipes/dashboard.rb
|
openstack/cookbook-openstack-application-catalog
|
65b4895f9c9cf3ff4faf552ce017dd99d88677ca
|
[
"Apache-2.0"
] | null | null | null |
# Cookbook Name:: openstack-application-catalog
# Recipe:: dashboard
#
# Copyright (c) 2016 Mirantis Inc, All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'uri'
class ::Chef::Recipe
include ::Openstack
end
if node['openstack']['murano']['glare']
package 'murano-glance-artifacts-plugin' do
action :install
end
end
if node['openstack']['murano']['app_catalog_ui']
package 'python-app-catalog-ui' do
action :install
end
end
package 'python-murano-dashboard'
include_recipe 'apache2'
template node['openstack']['murano']['local_settings_path'] do
source 'local_settings.py.erb'
mode 00440
owner 'root'
group 'root'
variables(
api_url: node['openstack']['murano']['dashboard_api_url'],
repo_url: node['openstack']['murano']['dashboard_repo_url'],
max_file_size: node['openstack']['murano']['dashboard_max_file_size'],
metadata_dir: node['openstack']['murano']['dashboard_metadata_dir'],
dashboard_debug_level: node['openstack']['murano']['dashboard_debug_level'],
client_debug_level: node['openstack']['murano']['dashboard_client_debug_level'],
enable_glare: node['openstack']['murano']['glare'],
compress_offline: true
)
end
dashboard_user = node['openstack']['murano']['dashboard_apache_user']
dashboard_group = node['openstack']['murano']['dashboard_apache_group']
execute 'clean_horizon_config' do
command "sed -e '/^## MURANO_CONFIG_BEGIN/,/^## MURANO_CONFIG_END ##/ d' -i #{node['openstack']['murano']['local_settings_path']}"
only_if "grep '^## MURANO_CONFIG_BEGIN' #{node['openstack']['murano']['local_settings_path']}"
end
execute 'django_collectstatic' do
command "#{node['openstack']['murano']['dashboard_collect_static_script']} collectstatic --noinput"
environment ({
'APACHE_USER' => dashboard_user,
'APACHE_GROUP' => dashboard_group
})
end
execute 'django_compressstatic' do
command "#{node['openstack']['murano']['dashboard_collect_static_script']} compress --force"
environment ({
'APACHE_USER' => dashboard_user,
'APACHE_GROUP' => dashboard_group
})
notifies :reload, 'service[apache2]', :immediately
end
| 32.728395
| 132
| 0.728404
|
c96089376b0f6a57394c29c86107d5d5d59c40bd
| 209
|
ts
|
TypeScript
|
sample-mocha-chai-ts/test/dir/multiply.test.ts
|
matmanjs/test-automation-training
|
9a5fdad9cc351385480beaba5e838402d40fc6cb
|
[
"MIT"
] | 5
|
2020-07-20T08:25:48.000Z
|
2022-01-12T00:25:06.000Z
|
sample-mocha-chai/test/dir/multiply.test.js
|
fml077/test-automation-training
|
9a5fdad9cc351385480beaba5e838402d40fc6cb
|
[
"MIT"
] | 2
|
2020-09-04T02:24:15.000Z
|
2020-09-04T02:25:35.000Z
|
sample-mocha-chai/test/dir/multiply.test.js
|
fml077/test-automation-training
|
9a5fdad9cc351385480beaba5e838402d40fc6cb
|
[
"MIT"
] | 6
|
2020-07-20T08:25:50.000Z
|
2022-01-12T00:25:37.000Z
|
import { expect } from 'chai';
import multiply from '../../src/dir/multiply';
describe('乘法函数的测试', function () {
it('1 乘 1 应该等于 1', function () {
expect(multiply(1, 1)).to.be.equal(1);
});
});
| 23.222222
| 46
| 0.569378
|
a3e440a8ca5438c7969d9fa9b2ec0d9b0827cc60
| 2,312
|
java
|
Java
|
src/main/java/com/questhelper/requirements/ItemSlots.java
|
Zantier/quest-helper
|
72e875aae313c8749344eb17b429fb2d1229f5b0
|
[
"BSD-2-Clause"
] | null | null | null |
src/main/java/com/questhelper/requirements/ItemSlots.java
|
Zantier/quest-helper
|
72e875aae313c8749344eb17b429fb2d1229f5b0
|
[
"BSD-2-Clause"
] | null | null | null |
src/main/java/com/questhelper/requirements/ItemSlots.java
|
Zantier/quest-helper
|
72e875aae313c8749344eb17b429fb2d1229f5b0
|
[
"BSD-2-Clause"
] | null | null | null |
/*
* Copyright (c) 2020, Zoinkwiz <https://github.com/Zoinkwiz>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.questhelper.requirements;
public enum ItemSlots
{
ANY_EQUIPPED_AND_INVENTORY(-3, "equipped or your inventory slots"),
ANY_INVENTORY(-2, "inventory slots"),
ANY_EQUIPPED(-1, "equipped slots"),
HEAD(0, "head slot"),
CAPE(1, "cape slot"),
AMULET(2, "amulet slot"),
WEAPON(3, "weapon slot"),
BODY(4, "body slot"),
SHIELD(5, "shield slot"),
LEGS(7, "legs slot"),
GLOVES(9, "gloves slot"),
BOOTS(10, "boots slot"),
RING(12, "ring slot"),
AMMO(13, "ammo slot");
private final int slotIdx;
private final String name;
ItemSlots(int slotIdx, String name)
{
this.slotIdx = slotIdx;
this.name = name;
}
public int getSlotIdx()
{
return slotIdx;
}
public String getName()
{
return name;
}
public static String getById(int id) {
for(ItemSlots itemSlot : values()) {
if(itemSlot.slotIdx == id) return itemSlot.getName();
}
return ANY_EQUIPPED_AND_INVENTORY.getName();
}
}
| 33.507246
| 82
| 0.733564
|
da428333c06e99ea0323ac1e04388de3a1941f7c
| 1,436
|
php
|
PHP
|
tests/Mcfedr/QueueManagerBundle/Tests/Worker/DoctrineDelayWorkerTest.php
|
nonanerz/queue-manager-bundle
|
87eaeca5132061ed24b18efd28d20df39d2331d2
|
[
"MIT"
] | 9
|
2016-12-30T09:37:00.000Z
|
2021-11-29T12:33:16.000Z
|
tests/Mcfedr/QueueManagerBundle/Tests/Worker/DoctrineDelayWorkerTest.php
|
nonanerz/queue-manager-bundle
|
87eaeca5132061ed24b18efd28d20df39d2331d2
|
[
"MIT"
] | 16
|
2017-07-19T15:12:41.000Z
|
2022-02-21T09:24:24.000Z
|
tests/Mcfedr/QueueManagerBundle/Tests/Worker/DoctrineDelayWorkerTest.php
|
nonanerz/queue-manager-bundle
|
87eaeca5132061ed24b18efd28d20df39d2331d2
|
[
"MIT"
] | 18
|
2016-11-07T08:20:56.000Z
|
2022-02-04T15:45:41.000Z
|
<?php
declare(strict_types=1);
namespace Mcfedr\QueueManagerBundle\Tests\Worker;
use Carbon\Carbon;
use Mcfedr\QueueManagerBundle\Entity\DoctrineDelayJob;
use Mcfedr\QueueManagerBundle\Exception\UnrecoverableJobException;
use Mcfedr\QueueManagerBundle\Manager\QueueManagerRegistry;
use Mcfedr\QueueManagerBundle\Worker\DoctrineDelayWorker;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
/**
* @internal
*/
final class DoctrineDelayWorkerTest extends TestCase
{
/**
* @var MockObject|QueueManagerRegistry
*/
private $queueManagerRegistry;
/**
* @var DoctrineDelayWorker
*/
private $doctrineDelayWorker;
protected function setUp(): void
{
$this->queueManagerRegistry = $this->getMockBuilder(QueueManagerRegistry::class)->disableOriginalConstructor()->getMock();
$this->doctrineDelayWorker = new DoctrineDelayWorker($this->queueManagerRegistry);
}
public function testExecuteNoArgs(): void
{
$this->expectException(UnrecoverableJobException::class);
$this->doctrineDelayWorker->execute([]);
}
public function testExecute(): void
{
$this->queueManagerRegistry->expects(static::once())->method('put')->with('name', ['args'], ['options'], 'manager');
$this->doctrineDelayWorker->execute(['job' => new DoctrineDelayJob('name', ['args'], ['options'], 'manager', new Carbon())]);
}
}
| 29.306122
| 133
| 0.713788
|
a9eb4fb160cd91a4fa0b50b7ecee5950ffbc85c1
| 1,179
|
php
|
PHP
|
resources/views/backend/slider/create.blade.php
|
huungoc1994hd/hn.laravel-tuyendung
|
05c0facb34c82e364c0b95673ae297842b76b5a0
|
[
"MIT"
] | null | null | null |
resources/views/backend/slider/create.blade.php
|
huungoc1994hd/hn.laravel-tuyendung
|
05c0facb34c82e364c0b95673ae297842b76b5a0
|
[
"MIT"
] | null | null | null |
resources/views/backend/slider/create.blade.php
|
huungoc1994hd/hn.laravel-tuyendung
|
05c0facb34c82e364c0b95673ae297842b76b5a0
|
[
"MIT"
] | null | null | null |
@extends('backend.layouts.main')
@section('title', 'Thêm mới slide')
@section('body')
<section class="main--content">
<div class="panel">
<div class="records--body">
<div class="title">
<h6 class="h6">
<i class="fa fa-plus-circle"></i>
Thêm mới Slide
</h6>
{{
Html::linkRoute(
'admin.slider.index',
'<i class="fa fa-angle-double-left mr-2"></i>Quay lại danh sách',
[],
[
'class' => 'btn btn-sm btn-rounded btn-primary font-weight-bold'
]
)
}}
</div>
{!! Form::model($mediaModel, [
'data-validate' => 'true',
'route' => 'admin.slider.create'
]) !!}
@include('backend.slider._field')
{{ Form::close() }}
</div>
</div>
</section>
@endsection
| 31.864865
| 96
| 0.347752
|
a37e6be35436f6ecf415cf5178f45c1bc9bc48d4
| 8,480
|
java
|
Java
|
com.github.ipaas.ifw/com.github.ipaas.ifw.jdbc/src/test/java/com/github/ipaas/ifw/jdbc/impl/FwDbAccessResponseRowTest.java
|
darrellbear112/trytolearn
|
5b0eeb67d1cefd6329886bc03f7eb03d3544efe5
|
[
"Apache-2.0"
] | null | null | null |
com.github.ipaas.ifw/com.github.ipaas.ifw.jdbc/src/test/java/com/github/ipaas/ifw/jdbc/impl/FwDbAccessResponseRowTest.java
|
darrellbear112/trytolearn
|
5b0eeb67d1cefd6329886bc03f7eb03d3544efe5
|
[
"Apache-2.0"
] | null | null | null |
com.github.ipaas.ifw/com.github.ipaas.ifw.jdbc/src/test/java/com/github/ipaas/ifw/jdbc/impl/FwDbAccessResponseRowTest.java
|
darrellbear112/trytolearn
|
5b0eeb67d1cefd6329886bc03f7eb03d3544efe5
|
[
"Apache-2.0"
] | null | null | null |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.ipaas.ifw.jdbc.impl;
import static org.junit.Assert.assertEquals;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.github.ipaas.ifw.jdbc.impl.FwDbAccessResponseRow;
/**
* by whx
*
* @author harry
*
*/
public class FwDbAccessResponseRowTest {
@BeforeClass
public static void setUpOnce() {
}
@AfterClass
public static void tearDownOnce() {
}
@Test
public void testGetDateStringString() {
Map<Integer, String> meta = new HashMap<Integer, String>();
Map<String, Object> row = new HashMap<String, Object>();
FwDbAccessResponseRow rprow = new FwDbAccessResponseRow(row, meta);
meta.put(Integer.valueOf(1), "birth");
// test normal string convert
row.put("birth", "1981-05-07");
assertEquals(new Date(81, 4, 7), rprow.getDate("birth", "yyyy-MM-dd"));
// test normal date
row.put("birth", new Date(81, 4, 7));
assertEquals(new Date(81, 4, 7), rprow.getDate("birth", ""));
// test null
row.put("birth", null);
assertEquals(null, rprow.getDate("birth", "yyyy-MM-dd"));
}
@Test(expected = IllegalStateException.class)
public void testGetDateStringStringException() {
Map<Integer, String> meta = new HashMap<Integer, String>();
Map<String, Object> row = new HashMap<String, Object>();
FwDbAccessResponseRow rprow = new FwDbAccessResponseRow(row, meta);
// test no exist
rprow.getDate("notexist", "yyyy-MM-dd");
}
@Test
public void testGetDateIntString() {
Map<Integer, String> meta = new HashMap<Integer, String>();
meta.put(Integer.valueOf(1), "birth");
Map<String, Object> row = new HashMap<String, Object>();
row.put("birth", "1981-05-07");
FwDbAccessResponseRow rprow = new FwDbAccessResponseRow(row, meta);
assertEquals(new Date(81, 4, 7), rprow.getDate(1, "yyyy-MM-dd"));
row.put("birth", new Date(81, 4, 7));
assertEquals(new Date(81, 4, 7), rprow.getDate(1, ""));
row.put("birth", null);
assertEquals(null, rprow.getDate(1, "yyyy-MM-dd"));
}
@Test(expected = IllegalStateException.class)
public void testGetDateIntStringException() {
Map<Integer, String> meta = new HashMap<Integer, String>();
Map<String, Object> row = new HashMap<String, Object>();
FwDbAccessResponseRow rprow = new FwDbAccessResponseRow(row, meta);
meta.put(Integer.valueOf(1), "birth");
row.put("birth", "1981-05-07");
rprow.getDate(2, "yyyy-MM-dd");
}
@Test
public void testGetIntString() {
Map<Integer, String> meta = new HashMap<Integer, String>();
meta.put(Integer.valueOf(1), "age");
Map<String, Object> row = new HashMap<String, Object>();
FwDbAccessResponseRow rprow = new FwDbAccessResponseRow(row, meta);
// test normal
row.put("age", 30);
assertEquals(30, rprow.getInt("age"));
// test string convert
row.put("age", "30");
assertEquals(30, rprow.getInt("age"));
// test null
row.put("age", null);
assertEquals(0, rprow.getInt("age"));
}
@Test(expected = IllegalStateException.class)
public void testGetIntStringException() {
Map<Integer, String> meta = new HashMap<Integer, String>();
Map<String, Object> row = new HashMap<String, Object>();
FwDbAccessResponseRow rprow = new FwDbAccessResponseRow(row, meta);
meta.put(Integer.valueOf(1), "age");
row.put("age", 30);
// test no exist
rprow.getInt("notexist");
}
@Test
public void testGetIntInt() {
Map<Integer, String> meta = new HashMap<Integer, String>();
meta.put(Integer.valueOf(1), "age");
Map<String, Object> row = new HashMap<String, Object>();
FwDbAccessResponseRow rprow = new FwDbAccessResponseRow(row, meta);
// test normal
row.put("age", 30);
assertEquals(30, rprow.getInt(1));
// test string convert
row.put("age", "30");
assertEquals(30, rprow.getInt(1));
// test null
row.put("age", null);
assertEquals(0, rprow.getInt(1));
}
@Test(expected = IllegalStateException.class)
public void testGetIntIntException() {
Map<Integer, String> meta = new HashMap<Integer, String>();
Map<String, Object> row = new HashMap<String, Object>();
FwDbAccessResponseRow rprow = new FwDbAccessResponseRow(row, meta);
meta.put(Integer.valueOf(1), "age");
row.put("age", 30);
// test no exist
rprow.getInt(2);
}
@Test
public void testGetStringString() {
Map<Integer, String> meta = new HashMap<Integer, String>();
Map<String, Object> row = new HashMap<String, Object>();
FwDbAccessResponseRow rprow = new FwDbAccessResponseRow(row, meta);
meta.put(Integer.valueOf(1), "name");
// test normal
row.put("name", "harry");
assertEquals("harry", rprow.getString("name"));
}
@Test(expected = IllegalStateException.class)
public void testGetStringStringException() {
Map<Integer, String> meta = new HashMap<Integer, String>();
Map<String, Object> row = new HashMap<String, Object>();
FwDbAccessResponseRow rprow = new FwDbAccessResponseRow(row, meta);
meta.put(Integer.valueOf(1), "name");
// test normal
row.put("name", "harry");
rprow.getString("notexist");
}
@Test
public void testGetStringInt() {
Map<Integer, String> meta = new HashMap<Integer, String>();
Map<String, Object> row = new HashMap<String, Object>();
FwDbAccessResponseRow rprow = new FwDbAccessResponseRow(row, meta);
meta.put(Integer.valueOf(1), "name");
// test normal
row.put("name", "harry");
assertEquals("harry", rprow.getString(1));
}
@Test(expected = IllegalStateException.class)
public void testGetStringIntException() {
Map<Integer, String> meta = new HashMap<Integer, String>();
Map<String, Object> row = new HashMap<String, Object>();
FwDbAccessResponseRow rprow = new FwDbAccessResponseRow(row, meta);
meta.put(Integer.valueOf(1), "name");
// test normal
row.put("name", "harry");
rprow.getString(2);
}
@Test
public void testGetFloatString() {
Map<Integer, String> meta = new HashMap<Integer, String>();
Map<String, Object> row = new HashMap<String, Object>();
FwDbAccessResponseRow rprow = new FwDbAccessResponseRow(row, meta);
meta.put(Integer.valueOf(1), "cost");
// test normal
row.put("cost", 15.6f);
assertEquals(15.6f, rprow.getFloat("cost"), 0.1);
// test string convert
row.put("cost", "15.6");
assertEquals(15.6f, rprow.getFloat("cost"), 0.1);
// test null
row.put("cost", null);
assertEquals(0f, rprow.getFloat("cost"), 0.1);
}
@Test(expected = IllegalStateException.class)
public void testGetFloatStringException() {
Map<Integer, String> meta = new HashMap<Integer, String>();
meta.put(Integer.valueOf(1), "age");
Map<String, Object> row = new HashMap<String, Object>();
FwDbAccessResponseRow rprow = new FwDbAccessResponseRow(row, meta);
row.put("age", 30);
rprow.getFloat("notexist");
}
@Test
public void testGetFloatInt() {
Map<Integer, String> meta = new HashMap<Integer, String>();
Map<String, Object> row = new HashMap<String, Object>();
FwDbAccessResponseRow rprow = new FwDbAccessResponseRow(row, meta);
meta.put(Integer.valueOf(1), "cost");
// test normal
row.put("cost", 15.6f);
assertEquals(15.6f, rprow.getFloat(1), 0.1);
// test string convert
row.put("cost", "15.6");
assertEquals(15.6f, rprow.getFloat(1), 0.1);
// test null
row.put("cost", null);
assertEquals(0f, rprow.getFloat(1), 0.1);
}
@Test(expected = IllegalStateException.class)
public void testGetFloatIntException() {
Map<Integer, String> meta = new HashMap<Integer, String>();
meta.put(Integer.valueOf(1), "age");
Map<String, Object> row = new HashMap<String, Object>();
FwDbAccessResponseRow rprow = new FwDbAccessResponseRow(row, meta);
row.put("age", 30);
rprow.getFloat(2);
}
}
| 33.784861
| 76
| 0.67559
|
e09dea99618bd9cbe97eebc86638b80873102e3d
| 12,380
|
lua
|
Lua
|
_nrtr_my v41.lua
|
mzhumakhanov/qlua
|
a490d2aa5fa7d5e7328f5d482b1841e1687090b1
|
[
"MIT"
] | 56
|
2017-02-22T16:21:15.000Z
|
2022-02-23T09:41:37.000Z
|
_nrtr_my v41.lua
|
mzhumakhanov/qlua
|
a490d2aa5fa7d5e7328f5d482b1841e1687090b1
|
[
"MIT"
] | 3
|
2019-08-26T08:54:21.000Z
|
2021-08-05T20:12:25.000Z
|
_nrtr_my v41.lua
|
mzhumakhanov/qlua
|
a490d2aa5fa7d5e7328f5d482b1841e1687090b1
|
[
"MIT"
] | 46
|
2017-02-22T17:18:03.000Z
|
2022-01-31T20:50:56.000Z
|
--logfile=io.open("C:\\SBERBANK\\QUIK_SMS\\LuaIndicators\\qlua_log.txt", "w")
Settings=
{
Name = "*NRTR_EMA_Sar4.1",
period = 84,
value_type = "ATR",
multiple = 1.2,
use_awg = 1,
show_awg = 0,
awg_type = 2, -- 1 EMA, 2 THV
awg_period = 32,
koef_thv = 1,
vType_awg = "C",
showSar = 1,
SarPeriod = 64,
SarPeriod2 = 256,
SarDeviation = 2,
show_regime = 3, --0 all, 1 NRTR, 2 Sar, 3 only Sar
line =
{
{
Name = "NRTR_buy",
Color = RGB(40,240,250),
Type = TYPE_POINT,
Width = 4
},
{
Name = "NRTR_sell",
Color = RGB(255,0,255),
Type = TYPE_POINT,
Width = 4
},
{
Name = "SAR_buy",
Color = RGB(0,255,128),
Type = TYPE_TRIANGLE_UP,
Width = 3
},
{
Name = "SAR_sell",
Color = RGB(255,0,0),
Type = TYPE_TRIANGLE_DOWN,
Width = 3
},
{
Name = "Sar",
Color = RGB(0, 64, 0),
Type = TYPET_BAR,
Width = 1
},
{
Name = "EMA",
Color = RGB(255,128,10),
Type = TYPE_LINE,
Width = 1
}
}
}
function Init()
myNRTR = cached_NRTR()
return #Settings.line
end
function OnCalculate(index)
return myNRTR(index, Settings)
end
--------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------
function FindExistCandle(I)
local out = I
while not CandleExist(out) and out > 0 do
out = out -1
end
return out
end
function dValue(i,param)
local v = param or "C"
if not CandleExist(i) then
return nil
end
if v == "O" then
return O(i)
elseif v == "H" then
return H(i)
elseif v == "L" then
return L(i)
elseif v == "C" then
return C(i)
elseif v == "V" then
return V(i)
elseif v == "M" then
return (H(i) + L(i))/2
elseif v == "T" then
return (H(i) + L(i)+C(i))/3
elseif v == "W" then
return (H(i) + L(i)+2*C(i))/4
elseif v == "ATR" then
local previous = i-1
if not CandleExist(previous) then
previous = FindExistCandle(previous)
end
return math.max(math.abs(H(i) - L(i)), math.abs(H(i) - C(previous)), math.abs(C(previous) - L(i)))
else
return C(i)
end
end
function cached_NRTR()
local cache_NRTR={}
local cache_Value={}
local cache_HPrice={}
local cache_LPrice={}
local ATR_MA=fWMA()
local THV=fTHV()
local cache_ValueAwg={}
local cache_awgEMA={}
--Sar
local cache_SAR={}
local cache_ST={}
local EMA={}
local BB={}
--Sar
return function(ind, Fsettings)
local Fsettings=(Fsettings or {})
local p = 0
local ATR = 0
local index = ind
local period = Fsettings.period or 84
local multiple = Fsettings.multiple or 1.2
local v_type = Fsettings.value_type or "ATR"
local show_regime = Fsettings.show_regime or 1
local use_awg = Fsettings.use_awg or 0
local show_awg = Fsettings.show_awg or 0
local awg_period = Fsettings.awg_period or 24
local kawg = 2/(awg_period+1)
local awg_type = Fsettings.awg_type or 1
local koef_thv = Fsettings.koef_thv or 1
local vType_awg = Fsettings.vType_awg or "C"
--Sar
local SarPeriod = Fsettings.SarPeriod or 32
local SarPeriod2 = Fsettings.SarPeriod2 or 256
local SarDeviation = Fsettings.SarDeviation or 3
local showSar = Fsettings.showSar or 3
local sigma = 0
--Sar
local out1 = nil
local out2 = nil
local out3 = nil
local out4 = nil
local out5 = nil
local out6 = nil
if index == 1 then
cache_NRTR = {}
cache_Value = {}
cache_ValueAwg = {}
cache_awgEMA = {}
cache_HPrice = {}
cache_LPrice = {}
--Sar
if showSar == 1 then
cache_SAR={}
cache_ST={}
EMA={}
BB={}
end
--Sar
cache_Value[index] = 0
cache_ValueAwg[index] = 0
cache_NRTR[index] = 0
cache_LPrice[index] = C(index) or 0
cache_HPrice[index] = C(index) or 0
if awg_type == 1 then
cache_awgEMA[index] = 0
else
cache_awgEMA[index]= THV(index, awg_period, koef_thv, 0)
end
--Sar
if showSar == 1 then
if not CandleExist(index) then
BB[index]=0
cache_SAR[index]=0
EMA[index]=0
cache_ST[index]=1
else
BB[index]=0
cache_SAR[index]=L(index)-2*(H(index)-L(index))
EMA[index]=(C(index)+O(index))/2
cache_ST[index]=1
end
end
--Sar
return nil
end
cache_NRTR[index] = cache_NRTR[index-1]
cache_Value[index] = cache_Value[index-1]
cache_ValueAwg[index] = cache_ValueAwg[index-1]
cache_HPrice[index] = cache_HPrice[index-1]
cache_LPrice[index] = cache_LPrice[index-1]
cache_awgEMA[index] = cache_awgEMA[index-1]
--Sar
if showSar == 1 then
EMA[index]=EMA[index-1]
BB[index]=BB[index-1]
cache_SAR[index]=cache_SAR[index-1]
cache_ST[index]=cache_ST[index-1]
end
--Sar
--WriteLog ("index "..tostring(index))
--WriteLog ("CandleExist(index) "..tostring(CandleExist(index)))
--WriteLog ("cache_awgEMA[index] "..tostring(cache_awgEMA[index]))
if not CandleExist(index) then
if awg_type == 2 then
--WriteLog ("call")
call = THV(index, awg_period, koef_thv, 0)
end
return nil
end
--Average True Range
cache_Value[index] = dValue(index, v_type) or cache_Value[index-1]
cache_ValueAwg[index] = dValue(index, vType_awg) or cache_ValueAwg[index-1]
ATR = ATR_MA(index, period, cache_Value, nil)
--WriteLog ("cache_awgEMA[index-1] "..tostring(cache_awgEMA[index-1]))
if use_awg == 1 then
if awg_type == 1 then
cache_awgEMA[index]=kawg*C(index)+(1-kawg)*cache_awgEMA[index-1]
else
cache_awgEMA[index] = THV(index, awg_period, koef_thv, cache_ValueAwg)
end
end
if show_awg == 1 then
out6 = cache_awgEMA[index]
end
if index <= math.max(period, SarPeriod) then
return nil
end
if show_regime ~= 3 then
p = cache_NRTR[index-1] or C(index)
if C(index) <= p then
trend = 1
end
if C(index) >= p then
trend = -1
end
cache_HPrice[index] = highestHigh(index, period)
cache_LPrice[index] = lowestLow(index, period)
if trend >= 0 then
cache_HPrice[index] = math.max( C(index), cache_HPrice[index])
if use_awg == 1 and C(index)<= cache_awgEMA[index] then
trend = -1;
cache_LPrice[index] = C(index)
cache_NRTR[index] = C(index) + ATR*multiple
else
cache_NRTR[index] = cache_HPrice[index] - ATR*multiple
if C(index) <= cache_NRTR[index] then -- and
trend = -1;
cache_LPrice[index] = C(index)
cache_NRTR[index] = C(index) + ATR*multiple
end
end
end
if trend <= 0 then
cache_LPrice[index] = math.min( C(index), cache_LPrice[index] )
if use_awg == 1 and C(index)>= cache_awgEMA[index] then
trend = 1;
cache_HPrice[index] = C(index)
cache_NRTR[index] = C(index) - ATR*multiple
else
cache_NRTR[index] = cache_LPrice[index] + ATR*multiple
if C(index) >= cache_NRTR[index] then
trend = 1
cache_HPrice[index] = C(index)
cache_NRTR[index] = C(index) - ATR*multiple
end
end
end
local previous = math.max(index-1, 1)
if CandleExist(previous) and show_regime <= 1 then
previous = FindExistCandle(previous)
if (C(index) > cache_NRTR[index] and C(previous) < cache_NRTR[index-1]) then
out1 = cache_NRTR[index]
out2 = nil
end
if C(index) < cache_NRTR[index] and C(previous) > cache_NRTR[index-1] then
out1 = nil
out2 = cache_NRTR[index]
end
end
end
--Sar
if showSar == 1 then
EMA[index]=(2/(SarPeriod/2+1))*C(index)+(1-2/(SarPeriod/2+1))*EMA[index-1]
BB[index]=(2/(SarPeriod2/2+1))*(C(index)-EMA[index])^2+(1-2/(SarPeriod2/2+1))*BB[index-1]
sigma=BB[index]^(1/2)
if index ==2 then
return nil
end
------------------------------------------------------------------
if cache_ST[index]==1 then
cache_SAR[index]=math.max((EMA[index]-sigma*SarDeviation),cache_SAR[index-1])
if (cache_SAR[index] > C(index)) then
cache_ST[index] = 0
cache_SAR[index]=EMA[index]+sigma*SarDeviation
end
elseif cache_ST[index]==0 then
cache_SAR[index]=math.min((EMA[index]+sigma*SarDeviation),cache_SAR[index-1])
if (cache_SAR[index] < C(index)) then
cache_ST[index] = 1
cache_SAR[index]=EMA[index]-sigma*SarDeviation*1
end
end
previous = FindExistCandle(index-1)
if CandleExist(previous) and (show_regime == 0 or show_regime == 2) then
if (C(index) > cache_SAR[index] and C(previous) < cache_SAR[index-1]) then
out3 = cache_SAR[index-1]
out4 = nil
end
if C(index) < cache_SAR[index] and C(previous) > cache_SAR[index-1] then
out3 = nil
out4 = cache_SAR[index-1]
end
end
out5 = cache_SAR[index]
end
--Sar
return out1, out2, out3, out4, out5, out6
end
end
function WriteLog(text)
logfile:write(tostring(os.date("%c",os.time())).." "..text.."\n");
logfile:flush();
LASTLOGSTRING = text;
end;
function highestHigh(index, period)
if index == 1 then
return nil
else
local highestHigh = H(index)
for i = math.max(index - period, 2), index, 1 do
if CandleExist(i) then
if H(i) > highestHigh then
highestHigh = H(i)
end
end
end
return highestHigh
end
end
function lowestLow(index, period)
if index == 1 then
return nil
else
local lowestLow = L(index)
for i = math.max(index - period, 2), index, 1 do
if CandleExist(i) then
if L(i) < lowestLow then
lowestLow = L(i)
end
end
end
return lowestLow
end
end
------------------------------------------------------------------
--THV
------------------------------------------------------------------
function round(num, idp)
if idp and num then
local mult = 10^(idp or 0)
if num >= 0 then return math.floor(num * mult + 0.5) / mult
else return math.ceil(num * mult - 0.5) / mult end
else return num end
end
function fWMA()
return function (Index, Period, ds, idp)
local Out = nil
if Index >= Period then
local sum = 0
local step = Period
for i = Index-Period+1, Index do
if ds[i] == nil then
ds[i] = 0
end
sum = (step*ds[i]) + sum
step = step - 1
end
Out = (2*sum)/(Period*(Period-1))
end
return round(Out,idp)
end
end
function fTHV()
local g_ibuf_104={}
local gda_108={}
local gda_112={}
local gda_116={}
local gda_120={}
local gda_124={}
local gda_128={}
return function(ind, _p, _k, ds)
local period = _p
local index = ind
local koef = _k
local ild_0
local ld_8
local gd_188 = koef * koef
local gd_196 = 0
local gd_196 = gd_188 * koef
local gd_132 = -gd_196
local gd_140 = 3.0 * (gd_188 + gd_196)
local gd_148 = -3.0 * (2.0 * gd_188 + koef + gd_196)
local gd_156 = 3.0 * koef + 1.0 + gd_196 + 3.0 * gd_188
local gd_164 = period
if gd_164 < 1.0 then gd_164 = 1 end
gd_164 = (gd_164 - 1.0) / 2.0 + 1.0
local gd_172 = 2 / (gd_164 + 1.0)
local gd_180 = 1 - gd_172
if index == 1 then
g_ibuf_104={}
gda_108={}
gda_112={}
gda_116={}
gda_120={}
gda_124={}
gda_128={}
g_ibuf_104[index]=0
gda_108[index]=0
gda_112[index]=0
gda_116[index]=0
gda_120[index]=0
gda_124[index]=0
gda_128[index]=0
return 0
end
g_ibuf_104[index] = g_ibuf_104[index-1]
gda_108[index] = gda_108[index-1]
gda_112[index] = gda_112[index-1]
gda_116[index] = gda_116[index-1]
gda_120[index] = gda_120[index-1]
gda_124[index] = gda_124[index-1]
gda_128[index] = gda_128[index-1]
--WriteLog ("ds[index] "..tostring(ds[index]))
--WriteLog ("gda_108[index] "..tostring(gda_108[index]))
if not CandleExist(index) then
return 0
end
gda_108[index] = gd_172 * ds[index] + gd_180 * (gda_108[index - 1])
gda_112[index] = gd_172 * (gda_108[index]) + gd_180 * (gda_112[index - 1])
gda_116[index] = gd_172 * (gda_112[index]) + gd_180 * (gda_116[index - 1])
gda_120[index] = gd_172 * (gda_116[index]) + gd_180 * (gda_120[index - 1])
gda_124[index] = gd_172 * (gda_120[index]) + gd_180 * (gda_124[index - 1])
gda_128[index] = gd_172 * (gda_124[index]) + gd_180 * (gda_128[index - 1])
g_ibuf_104[index] = gd_132 * (gda_128[index]) + gd_140 * (gda_124[index]) + gd_148 * (gda_120[index]) + gd_156 * (gda_116[index])
local out = g_ibuf_104[index]
return out
end
end
| 22.146691
| 131
| 0.602746
|
14ef4e2702a6308acf1de9dfe45c1263d74c6891
| 1,201
|
ts
|
TypeScript
|
src/function.ts
|
ilsubyeega/gonghang-h-bot
|
2ca25325a51e72c78008d51c2524192c0daf8d30
|
[
"Apache-2.0",
"MIT"
] | 1
|
2021-10-30T14:30:58.000Z
|
2021-10-30T14:30:58.000Z
|
src/function.ts
|
ilsubyeega/gonghang-h-bot
|
2ca25325a51e72c78008d51c2524192c0daf8d30
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
src/function.ts
|
ilsubyeega/gonghang-h-bot
|
2ca25325a51e72c78008d51c2524192c0daf8d30
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
export async function getMeal(date: string): Promise<Meal> {
const req = await fetch(MEAL_API_URL+`MLSV_YMD=${date}`)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const res = await req.json() as any;
return res?.mealServiceDietInfo?.[1].row?.[0] as Meal;
}
export function dateToArray(date: string): number[] {
return [parseInt(date.substr(0, 4)), parseInt(date.substr(4, 2)), parseInt(date.substr(6, 2))];
}
export function pad(num: number): string {
return num < 10 ? `0${num}` : `${num}`;
}
const days = [
'일',
'월',
'화',
'수',
'목',
'금',
'토'
]
export function getDayFromText(input: string): string {
const datearr = dateToArray(input);
const date = new Date(datearr[0], datearr[1] - 1, datearr[2]);
console.log(date)
return days[date.getDay()];
}
interface Meal {
ATPT_OFCDC_SC_CODE: string;
ATPT_OFCDC_SC_NM: string;
SD_SCHUL_CODE: string;
SCHUL_NM: string;
MMEAL_SC_CODE: string;
MMEAL_SC_NM: string;
MLSV_YMD: string;
MLSV_FGR: string;
DDISH_NM: string;
ORPLC_INFO: string;
CAL_INFO: string;
NTR_INFO: string;
MLSV_FROM_YMD: string;
MLSV_TO_YMD: string;
}
| 27.930233
| 99
| 0.644463
|
f94e59bb8ebae3a16082016bc41da37a85ce5350
| 2,635
|
swift
|
Swift
|
ZDPicViewerDemo/ZDPictureViewerKit/ZDPictureViewCell.swift
|
seasonZhu/ZDPictureViewerKit
|
7a4b4dd1ab868dbad7e485de36fcf7a44fcceef2
|
[
"MIT"
] | 1
|
2018-09-10T03:44:54.000Z
|
2018-09-10T03:44:54.000Z
|
ZDPicViewerDemo/ZDPictureViewerKit/ZDPictureViewCell.swift
|
seasonZhu/ZDPictureViewerKit
|
7a4b4dd1ab868dbad7e485de36fcf7a44fcceef2
|
[
"MIT"
] | null | null | null |
ZDPicViewerDemo/ZDPictureViewerKit/ZDPictureViewCell.swift
|
seasonZhu/ZDPictureViewerKit
|
7a4b4dd1ab868dbad7e485de36fcf7a44fcceef2
|
[
"MIT"
] | null | null | null |
//
// ZDPictureViewCell.swift
// ZDPicViewerDemo
//
// Created by season on 2018/9/7.
// Copyright © 2018年 season. All rights reserved.
//
import UIKit
import Kingfisher
/// 这个类可用可不用,因为实际开发中你的cell的结构往往比这个更为复杂
public class ZDPictureViewCell: UICollectionViewCell {
//MARK:- 属性设置
// 图片
public lazy var imageView: AnimatedImageView = {
let imageView = AnimatedImageView()
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
return imageView
}()
//MARK:- 初始化
override init(frame: CGRect) {
super.init(frame: frame)
setUpUI()
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK:- 搭建界面
private func setUpUI() {
// 图片布局
contentView.addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
addConstraint(NSLayoutConstraint(item: imageView,
attribute: .leading,
relatedBy: .equal,
toItem: contentView,
attribute: .leading,
multiplier: 1,
constant: 0))
addConstraint(NSLayoutConstraint(item: imageView,
attribute: .top,
relatedBy: .equal,
toItem: contentView,
attribute: .top,
multiplier: 1,
constant: 0))
addConstraint(NSLayoutConstraint(item: imageView,
attribute: .trailing,
relatedBy: .equal,
toItem: contentView,
attribute: .trailing,
multiplier: 1,
constant: 0))
addConstraint(NSLayoutConstraint(item: imageView,
attribute: .bottom,
relatedBy: .equal,
toItem: contentView,
attribute: .bottom,
multiplier: 1,
constant: 0))
}
}
| 36.09589
| 67
| 0.420493
|
9030961c7df3f86373c89bccd0f958c3f1644dbf
| 286
|
dart
|
Dart
|
lib/src/novaluepresent.dart
|
JamesMcIntosh/optional.dart
|
50056db596ef9c33873ccc25c34ec526a2e86c87
|
[
"BSD-2-Clause"
] | 34
|
2015-01-25T16:00:59.000Z
|
2022-03-26T13:08:03.000Z
|
lib/src/novaluepresent.dart
|
JamesMcIntosh/optional.dart
|
50056db596ef9c33873ccc25c34ec526a2e86c87
|
[
"BSD-2-Clause"
] | 15
|
2015-12-15T17:28:58.000Z
|
2021-08-16T15:55:29.000Z
|
lib/src/novaluepresent.dart
|
JamesMcIntosh/optional.dart
|
50056db596ef9c33873ccc25c34ec526a2e86c87
|
[
"BSD-2-Clause"
] | 10
|
2018-06-06T15:18:14.000Z
|
2022-01-30T01:17:50.000Z
|
part of optional_internal;
/// Error thrown when attempting to operate on an empty Optional's value.
class NoValuePresentError extends StateError {
/// Creates a new NoValuePresentError with a message reading "no value present"
NoValuePresentError() : super('no value present');
}
| 35.75
| 81
| 0.776224
|
2357919824e8150f9eca546b131c996e19c7f3a6
| 247
|
dart
|
Dart
|
lib/design_patterns/proxy/customer/customer.dart
|
sinv207/flutter-design-patterns
|
b721cf0854d857cca07cf9fc763287a2a7aee8ab
|
[
"MIT"
] | null | null | null |
lib/design_patterns/proxy/customer/customer.dart
|
sinv207/flutter-design-patterns
|
b721cf0854d857cca07cf9fc763287a2a7aee8ab
|
[
"MIT"
] | null | null | null |
lib/design_patterns/proxy/customer/customer.dart
|
sinv207/flutter-design-patterns
|
b721cf0854d857cca07cf9fc763287a2a7aee8ab
|
[
"MIT"
] | 1
|
2021-07-02T02:30:48.000Z
|
2021-07-02T02:30:48.000Z
|
import 'package:faker/faker.dart';
import 'customer_details.dart';
class Customer {
late final String id;
late final String name;
CustomerDetails? details;
Customer() {
id = faker.guid.guid()!;
name = faker.person.name();
}
}
| 16.466667
| 34
| 0.672065
|
3ea58ab82c96ce8fdff16aae447c4aaf581f0eb7
| 459
|
sql
|
SQL
|
persistence/sql/migrations/20190100000003000000_client.up.sql
|
mig5/hydra
|
2d5449019cd7ae02745658a8c8ee16cf3c2ccc8f
|
[
"Apache-2.0"
] | 10,611
|
2017-02-08T01:43:36.000Z
|
2022-03-31T18:42:08.000Z
|
persistence/sql/migrations/20190100000003000000_client.up.sql
|
mig5/hydra
|
2d5449019cd7ae02745658a8c8ee16cf3c2ccc8f
|
[
"Apache-2.0"
] | 1,629
|
2017-02-09T12:39:37.000Z
|
2022-03-31T23:45:57.000Z
|
persistence/sql/migrations/20190100000003000000_client.up.sql
|
mig5/hydra
|
2d5449019cd7ae02745658a8c8ee16cf3c2ccc8f
|
[
"Apache-2.0"
] | 1,406
|
2017-02-11T19:34:40.000Z
|
2022-03-31T18:42:11.000Z
|
ALTER TABLE hydra_client ADD sector_identifier_uri TEXT;
ALTER TABLE hydra_client ADD jwks TEXT;
ALTER TABLE hydra_client ADD jwks_uri TEXT;
ALTER TABLE hydra_client ADD request_uris TEXT;
ALTER TABLE hydra_client ADD token_endpoint_auth_method VARCHAR(25) NOT NULL DEFAULT '';
ALTER TABLE hydra_client ADD request_object_signing_alg VARCHAR(10) NOT NULL DEFAULT '';
ALTER TABLE hydra_client ADD userinfo_signed_response_alg VARCHAR(10) NOT NULL DEFAULT '';
| 57.375
| 90
| 0.83878
|
2f6672ff8476712769d3a8dbc9381cac562b6d48
| 9,338
|
js
|
JavaScript
|
scripts/retention-metrics/base-cohort-analyser.js
|
madnight/gitter
|
599aa0d3fd638d43eef0f9c0d8758481f592e1f3
|
[
"MIT"
] | null | null | null |
scripts/retention-metrics/base-cohort-analyser.js
|
madnight/gitter
|
599aa0d3fd638d43eef0f9c0d8758481f592e1f3
|
[
"MIT"
] | null | null | null |
scripts/retention-metrics/base-cohort-analyser.js
|
madnight/gitter
|
599aa0d3fd638d43eef0f9c0d8758481f592e1f3
|
[
"MIT"
] | null | null | null |
'use strict';
var moment = require('moment');
var _ = require('lodash');
var assert = require('assert');
var cohortUtils = require('./cohort-utils');
function BaseRetentionAnalyser(db, options) {
this.db = db;
this.options = options || {};
this.debug = options.debug || function() {};
}
BaseRetentionAnalyser.prototype.getLoginDataPerDay = function (allCohortUsers, callback) {
var self = this;
var userLoginEvents = this.db.collection("gitter_user_login_events");
var orTerms = _(allCohortUsers)
.transform(function(result, userIds, timestamp) {
var ts = parseInt(timestamp, 10);
var start = new Date(ts);
var term = {
'd.userId': { $in: userIds },
t: { $gte: start }
};
var limit = self.options.limit;
if (limit) {
var limitOfUsage = moment(start).add(limit.amount, limit.unit).toDate();
term.t.$lt = limitOfUsage;
}
result.push(term);
}, [])
.value();
userLoginEvents.aggregate([
{
$match: {
$or: orTerms
},
},
{
$project: {
userId: '$d.userId',
period: { year: { $year: "$t" }, dayOfYear: { $dayOfYear: "$t" } }
}
},
{
$group:
{
_id: "$period",
userIds: { $addToSet: "$userId" }
}
}
],
function(err, periodData) {
if (err) return callback(err);
assert(periodData.length > 0, 'No activity found');
periodData.sort(function(a, b) {
var dA = cohortUtils.makeDate(a._id.year, a._id.dayOfYear).valueOf();
var dB = cohortUtils.makeDate(b._id.year, b._id.dayOfYear).valueOf();
if(dA < dB) return -1;
if(dA > dB) return +1;
return +0;
});
var r = periodData.reduce(function(memo, f) {
var ts = cohortUtils.makeDate(f._id.year, f._id.dayOfYear).valueOf();
memo[ts] = f.userIds;
return memo;
}, {});
callback(null, r);
});
};
BaseRetentionAnalyser.prototype.rollupUsageIntoWeeks = function(input) {
var uniqueUserCountBefore = _(input).values().uniq().size();
var weekly = _(input)
.transform(function(result, userIds, timestamp) {
var cohortDate = cohortUtils.getStartOfWeek(moment(parseInt(timestamp, 10)));
timestamp = cohortDate.valueOf();
if (result[timestamp]) {
result[timestamp] = result[timestamp].concat(userIds);
} else {
result[timestamp] = userIds;
}
})
.transform(function(result, userIds, timestamp) {
result[timestamp] = _.uniq(userIds);
})
.value();
var uniqueUserCountAfterwards = _(input).values().uniq().size();
/* Sanity check */
assert(uniqueUserCountBefore === uniqueUserCountAfterwards, 'Expected the number of users before and after the rollup to be the same (before: ' + uniqueUserCountBefore + ', after: ', uniqueUserCountAfterwards + ')');
return weekly;
};
BaseRetentionAnalyser.prototype.getUserInteractionsByDay = function (allCohortUsers, callback) {
var self = this;
this.getLoginDataPerDay(allCohortUsers, function(err, loginResults) {
if(err) return callback(err);
if (self.options.daily) {
return callback(null, loginResults);
}
// Roll into weeks
var weeklyUsage = self.rollupUsageIntoWeeks(loginResults);
return callback(null, weeklyUsage);
});
};
BaseRetentionAnalyser.prototype.getCohortUsersGrouped = function(start, end, callback) {
var self = this;
var newUserEvents = this.db.collection("gitter_new_user_events");
newUserEvents.aggregate([
{
$match: {
t: { $gte: start, $lt: end }
},
},
{
$project: {
userId: '$d.userId',
period: { year: { $year: "$t" }, dayOfYear: { $dayOfYear: "$t" } }
}
},
{
$group:
{
_id: "$period",
userIds: { $addToSet: "$userId" }
}
}
],
function(err, periodData) {
if (err) return callback(err);
var newUsersByDay = _(periodData)
.transform(function(result, dailyNewUsers) {
var cohortDate = moment(cohortUtils.makeDate(dailyNewUsers._id.year, dailyNewUsers._id.dayOfYear));
// Turn days into weeks...
if(!self.options.daily) {
cohortDate = cohortUtils.getStartOfWeek(cohortDate);
}
var ts = cohortDate.valueOf();
if(result[ts]) {
result[ts] = result[ts].concat(dailyNewUsers.userIds);
} else {
result[ts] = dailyNewUsers.userIds;
}
},{})
.transform(function(result, userIds, timestamp) {
result[timestamp] = _.uniq(userIds); // Probably not needed
})
.value();
callback(null, newUsersByDay);
});
};
BaseRetentionAnalyser.prototype.buildCohortRetention = function(cohortTimestamp, cohortUserIds, dailyInteractingUsers, categorisedUsers) {
var cohortUsersIndexed = _(cohortUserIds)
.transform(function(result, userId) {
result[userId] = true;
}, {})
.value();
var cohortDailyInteractingUsers = _(dailyInteractingUsers)
.transform(function(result, userIds, timestamp) {
var filteredUserIds = userIds.filter(function(userId) { return cohortUsersIndexed[userId]; });
if (filteredUserIds.length) {
var byCategory = _(filteredUserIds)
.transform(function(memo, userId) {
var category = categorisedUsers[userId];
if(memo[category]) {
memo[category]++;
} else {
memo[category] = 1;
}
}, {
total: filteredUserIds.length
})
.value();
result[timestamp] = byCategory;
}
})
.value();
// Count how many users are in each category
var categoryCounts = _(cohortUserIds)
.transform(function(result, userId) {
var category = categorisedUsers[userId];
if(result[category]) {
result[category]++;
} else {
result[category] = 1;
}
})
.value();
var allCategories = _(categoryCounts).keys().sort().value();
var subcohorts = _(allCategories)
.transform(function(result, category) {
result[category] = { total: categoryCounts[category] };
}, {})
.value();
var totals = _(cohortDailyInteractingUsers)
.keys()
.sort()
.transform(function(totals, time) {
var interactions = cohortDailyInteractingUsers[time];
var relativeDate = moment.duration(moment(parseInt(time, 10)).diff(parseInt(cohortTimestamp, 10))).asDays();
totals[relativeDate] = interactions.total;
allCategories.forEach(function(category) {
var subcohort = subcohorts[category];
var value = interactions[category] || 0;
subcohort[relativeDate] = value; // NB: side effect!
});
}, {
total: cohortUserIds.length
})
.value();
return {
cohortTimestamp: moment(parseInt(cohortTimestamp, 10)).toDate(),
cohortUsersCount: cohortUserIds.length,
totals: totals,
subcohorts: subcohorts
};
};
BaseRetentionAnalyser.prototype.buildRetention = function(start, end, callback) {
var self = this;
self.debug('Finding cohort users');
this.getCohortUsersGrouped(start, end, function(err, allCohortUsers) {
if (err) return callback(err);
/* Sanity check uniqueness of users */
var userIds = _(allCohortUsers).values().flatten();
assert(userIds.size() === userIds.uniq().size(), 'Duplicate users found in cohorts');
var allCohortUsersCount = userIds.size();
self.debug('Categorising cohort users');
self.categoriseUsers(allCohortUsers, function(err, categorisedUsers) {
if (err) return callback(err);
/* Sanity checks for the categorisations */
var categorisedUserCount = _(categorisedUsers).keys().size();
assert(categorisedUserCount === allCohortUsersCount, 'Categorised user count does not match all users');
self.debug('Getting user activity');
/* Proceed with the interactions */
self.getUserInteractionsByDay(allCohortUsers, function(err, dailyInteractingUsers) {
if (err) return callback(err);
self.debug('Crunching the numbers');
/* Some more sanity checks */
var limit = self.options.limit;
var limitOfUsage;
if (limit) {
limitOfUsage = moment(end).add(limit.amount, limit.unit).valueOf();
}
Object.keys(dailyInteractingUsers)
.forEach(function(timestamp) {
var ts = parseInt(timestamp, 10);
assert(ts >= start.valueOf(), 'Activity before start');
if (limitOfUsage) {
assert(ts < limitOfUsage, 'Activity after end');
}
});
/* Proceed with building the retention objects */
var result = _(allCohortUsers)
.keys()
.sort()
.map(function(cohortTimestamp) {
var cohortUserIds = allCohortUsers[cohortTimestamp];
return self.buildCohortRetention(cohortTimestamp, cohortUserIds, dailyInteractingUsers, categorisedUsers);
})
.value();
callback(null, result);
});
});
});
};
module.exports = BaseRetentionAnalyser;
| 28.644172
| 218
| 0.603662
|
6628a86502e4b471970a8631ac26d23a2eced8ee
| 838
|
py
|
Python
|
setup.py
|
msharp/epistle
|
5ca7e2cface6b66f9ee0e33bf4798ddb51ddd18d
|
[
"MIT"
] | null | null | null |
setup.py
|
msharp/epistle
|
5ca7e2cface6b66f9ee0e33bf4798ddb51ddd18d
|
[
"MIT"
] | null | null | null |
setup.py
|
msharp/epistle
|
5ca7e2cface6b66f9ee0e33bf4798ddb51ddd18d
|
[
"MIT"
] | 1
|
2018-09-07T02:43:59.000Z
|
2018-09-07T02:43:59.000Z
|
from setuptools import setup, find_packages
import epistle
setup(
name='epistle',
version=epistle.__version__,
license=epistle.__license__,
author=epistle.__author__,
description="Note taking with version control",
url='https://github.com/msharp/epistle',
author_email='maxsharples@gmail.com',
packages=find_packages(),
entry_points={
'console_scripts': [
'epistle = epistle.cli:epistle',
],
},
install_requires='click>=6.7',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming Language :: Python :: 3.6',
'Environment :: Console',
'License :: OSI Approved :: MIT License',
'Topic :: Terminals',
'Topic :: Text Processing',
'Topic :: Utilities'
],
)
| 27.933333
| 51
| 0.612172
|
8510134509d7a28e4801264efa50031144c979ce
| 1,288
|
cs
|
C#
|
src/Soil.Net/Channel/ChannelInactiveReason.cs
|
soilmeal/soil-csharp
|
3ce7f90c63f61b6af1b968d48c1b2657a72b5673
|
[
"MIT"
] | 6
|
2022-01-18T02:53:51.000Z
|
2022-02-17T17:12:58.000Z
|
src/Soil.Net/Channel/ChannelInactiveReason.cs
|
soilmeal/soil-csharp
|
3ce7f90c63f61b6af1b968d48c1b2657a72b5673
|
[
"MIT"
] | 5
|
2022-02-17T17:19:39.000Z
|
2022-03-30T13:42:07.000Z
|
src/Soil.Net/Channel/ChannelInactiveReason.cs
|
soilmeal/soil-csharp
|
3ce7f90c63f61b6af1b968d48c1b2657a72b5673
|
[
"MIT"
] | null | null | null |
using System;
namespace Soil.Net.Channel;
public enum ChannelInactiveReason
{
None = 0,
ByLocal = 1,
ByRemote = 2,
ByException = 3,
}
public static class ChannelInactiveReasonExtensions
{
public static string FastToString(this ChannelInactiveReason reason)
{
return reason switch
{
ChannelInactiveReason.None => nameof(ChannelInactiveReason.None),
ChannelInactiveReason.ByLocal => nameof(ChannelInactiveReason.ByLocal),
ChannelInactiveReason.ByRemote => nameof(ChannelInactiveReason.ByRemote),
ChannelInactiveReason.ByException => nameof(ChannelInactiveReason.ByException),
_ => throw new ArgumentOutOfRangeException(nameof(reason), reason, null),
};
}
public static ChannelReconnectReason ConvertToReconnectReason(this ChannelInactiveReason reason)
{
return reason switch
{
ChannelInactiveReason.ByLocal => ChannelReconnectReason.InactiveByLocal,
ChannelInactiveReason.ByRemote => ChannelReconnectReason.InactiveByRemote,
ChannelInactiveReason.ByException => ChannelReconnectReason.InactiveByException,
_ => ChannelReconnectReason.None,
};
}
}
| 31.414634
| 101
| 0.679348
|
cf17a3652c152b6334e850969e750229346bb59a
| 2,813
|
php
|
PHP
|
class/Renderer/HtmlFilter/SimpleButton.php
|
cascade-core/libduf
|
b66f80a228f574f472d7007a5cc40e9aa49ef6be
|
[
"Apache-2.0"
] | null | null | null |
class/Renderer/HtmlFilter/SimpleButton.php
|
cascade-core/libduf
|
b66f80a228f574f472d7007a5cc40e9aa49ef6be
|
[
"Apache-2.0"
] | null | null | null |
class/Renderer/HtmlFilter/SimpleButton.php
|
cascade-core/libduf
|
b66f80a228f574f472d7007a5cc40e9aa49ef6be
|
[
"Apache-2.0"
] | null | null | null |
<?php
/*
* Copyright (c) 2014, Josef Kufner <jk@frozen-doe.net>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
namespace Duf\Renderer\HtmlFilter;
/**
* Simple button to modify filters
*/
class SimpleButton implements \Duf\Renderer\IWidgetRenderer
{
use \Duf\Renderer\TagUtils;
/// @copydoc \Duf\Renderer\IWidgetRenderer::renderWidget
public static function renderWidget(\Duf\Form $form, $template_engine, $widget_conf)
{
// Get value early, so class can be set
$filters = $form->getViewData($widget_conf['group_id']);
echo "<a href=\"", htmlspecialchars(static::buildFilterLink($filters, $widget_conf['filters'])), "\"";
static::renderClassAttr($form, $template_engine,
isset($widget_conf['class']) ? $widget_conf['class'] : null,
'button filter',
static::isFilterActive($filters, $widget_conf['filters']) ? 'active' : null);
echo ">";
if (isset($widget_conf['widgets'])) {
$form->renderWidgets($template_engine, $widget_conf['widgets']);
} else if (isset($widget_conf['label'])) {
echo htmlspecialchars($widget_conf['label']);
}
echo "</a>\n";
}
/**
* Build link containing current filters overriden by $overrides. This
* function accepts more than one $overrides parameter.
*
* @param $filters Current filters.
* @param $overrides New filter setting. More than one argument may be specified.
* @return Query part of the URL, which should be just fine to use in
* `href` attribute. Filters are sorted to produce uniform links.
*/
protected static function buildFilterLink($filters, $overrides)
{
$f = array();
$link_filters = call_user_func_array('array_merge', array_filter(func_get_args(), function($x) { return $x !== null; }));
ksort($link_filters);
return '?'.http_build_query($link_filters);
}
protected static function isFilterActive($filters, $overrides)
{
if (empty($overrides)) {
return false;
}
$args = func_get_args();
$current_filters = array_shift($args);
$required_filters = call_user_func_array('array_merge', array_filter($args, function($x) { return $x !== null; }));
foreach ($required_filters as $k => $v) {
$cv = isset($current_filters[$k]) ? $current_filters[$k] : null;
if ($v === null ? $cv !== null : $v != $cv) {
return false;
}
}
return true;
}
}
| 31.965909
| 123
| 0.692144
|
c9cd72c2765136c455ba3d7fc484c96e48b56f3e
| 2,792
|
ts
|
TypeScript
|
apps/code-examples/src/app/code-examples/ag-grid/data-grid/basic/basic-data-grid-docs-demo.component.ts
|
Blackbaud-KevinEnns/skyux
|
dc8ed4162a2849ffe2de83454fa2d2faad92a152
|
[
"MIT"
] | null | null | null |
apps/code-examples/src/app/code-examples/ag-grid/data-grid/basic/basic-data-grid-docs-demo.component.ts
|
Blackbaud-KevinEnns/skyux
|
dc8ed4162a2849ffe2de83454fa2d2faad92a152
|
[
"MIT"
] | null | null | null |
apps/code-examples/src/app/code-examples/ag-grid/data-grid/basic/basic-data-grid-docs-demo.component.ts
|
Blackbaud-KevinEnns/skyux
|
dc8ed4162a2849ffe2de83454fa2d2faad92a152
|
[
"MIT"
] | null | null | null |
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
} from '@angular/core';
import { SkyAgGridService, SkyCellType } from '@skyux/ag-grid';
import {
GridApi,
GridOptions,
GridReadyEvent,
ValueFormatterParams,
} from 'ag-grid-community';
import { SKY_AG_GRID_DEMO_DATA } from './basic-data-grid-docs-demo-data';
@Component({
selector: 'app-basic-data-grid-docs-demo',
templateUrl: './basic-data-grid-docs-demo.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SkyBasicDataGridDemoComponent {
public columnDefs = [
{
field: 'selected',
type: SkyCellType.RowSelector,
},
{
field: 'name',
headerName: 'Name',
},
{
field: 'age',
headerName: 'Age',
type: SkyCellType.Number,
maxWidth: 60,
},
{
field: 'startDate',
headerName: 'Start date',
type: SkyCellType.Date,
sort: 'asc',
},
{
field: 'endDate',
headerName: 'End date',
type: SkyCellType.Date,
valueFormatter: this.endDateFormatter,
},
{
field: 'department',
headerName: 'Department',
type: SkyCellType.Autocomplete,
},
{
field: 'jobTitle',
headerName: 'Title',
type: SkyCellType.Autocomplete,
},
];
public gridApi: GridApi | undefined;
public gridData = SKY_AG_GRID_DEMO_DATA;
public gridOptions: GridOptions;
public searchText = '';
public noRowsTemplate: string;
constructor(
private agGridService: SkyAgGridService,
private changeDetector: ChangeDetectorRef
) {
this.noRowsTemplate = `<div class="sky-deemphasized">No results found.</div>`;
this.gridOptions = this.agGridService.getGridOptions({
gridOptions: {
columnDefs: this.columnDefs,
onGridReady: this.onGridReady.bind(this),
},
});
this.changeDetector.markForCheck();
}
public onGridReady(gridReadyEvent: GridReadyEvent): void {
this.gridApi = gridReadyEvent.api;
this.gridApi.sizeColumnsToFit();
this.changeDetector.markForCheck();
}
public searchApplied(searchText: string | void): void {
if (searchText) {
this.searchText = searchText;
} else {
this.searchText = '';
}
if (this.gridApi) {
this.gridApi.setQuickFilter(searchText);
const displayedRowCount = this.gridApi.getDisplayedRowCount();
if (displayedRowCount > 0) {
this.gridApi.hideOverlay();
} else {
this.gridApi.showNoRowsOverlay();
}
}
}
private endDateFormatter(params: ValueFormatterParams): string {
const dateConfig = { year: 'numeric', month: '2-digit', day: '2-digit' };
return params.value
? params.value.toLocaleDateString('en-us', dateConfig)
: 'N/A';
}
}
| 24.928571
| 82
| 0.644699
|
8e7e4e6aa3252cf6d685fb15ae6b26bad34edcbb
| 247
|
js
|
JavaScript
|
docs/reference/cmsis-plus/os_8h.js
|
micro-os-plus/web-preview
|
f22c44746b8f346e03363632d7d9c0c34d97b7d6
|
[
"MIT"
] | null | null | null |
docs/reference/cmsis-plus/os_8h.js
|
micro-os-plus/web-preview
|
f22c44746b8f346e03363632d7d9c0c34d97b7d6
|
[
"MIT"
] | 1
|
2016-03-04T10:49:16.000Z
|
2016-03-04T10:49:16.000Z
|
docs/reference/cmsis-plus/os_8h.js
|
micro-os-plus/web-preview
|
f22c44746b8f346e03363632d7d9c0c34d97b7d6
|
[
"MIT"
] | 2
|
2016-08-13T15:52:08.000Z
|
2018-07-30T16:56:39.000Z
|
var os_8h =
[
[ "children_threads", "os_8h.html#a7eb30a44d7db62a0ed7804451daaffc0", null ],
[ "make_shared", "os_8h.html#ga0449994d14fbd65e9db916aaf88da446", null ],
[ "stack", "os_8h.html#ga2060bb385320119880c8956fc8fb1c5b", null ]
];
| 41.166667
| 81
| 0.728745
|
40dc0eec81c812fcfe8591de80caf29801001cc4
| 560
|
ts
|
TypeScript
|
src/components/MemoryCardGame/constants.ts
|
shortgiraffe4/memory-card-game
|
5684815edb5e875d65caefa73abf0138e9fada45
|
[
"MIT"
] | 1
|
2018-08-11T19:45:31.000Z
|
2018-08-11T19:45:31.000Z
|
src/components/MemoryCardGame/constants.ts
|
shortgiraffe4/memory-card-game
|
5684815edb5e875d65caefa73abf0138e9fada45
|
[
"MIT"
] | null | null | null |
src/components/MemoryCardGame/constants.ts
|
shortgiraffe4/memory-card-game
|
5684815edb5e875d65caefa73abf0138e9fada45
|
[
"MIT"
] | 1
|
2019-04-13T04:02:24.000Z
|
2019-04-13T04:02:24.000Z
|
export const STAGES = {
MENU: 1,
HELP: 2,
HIGH_SCORES: 3,
PLAY: 4,
SCORE: 5
};
export const DIFFICULTIES: any = {
EASY: 'easy',
MEDIUM: 'medium',
HARD: 'hard',
VERY_HARD: 'extreme',
};
export const ICONS_PER_ROW: any = {
'easy': 4,
'medium': 6,
'hard': 8,
'extreme': 10,
}
export const PLAY_STATUS = {
PLAYING: 'PLAYING',
STOPPED: 'STOPPED',
PAUSED: 'PAUSED',
}
export const BOARD_SIZES = {
XL: 800,
LG: 700,
MD: 600,
SM: 500,
XS: 350
}
| 15.555556
| 36
| 0.503571
|
eef138d37aaae33fda53dd492e66235f9e625124
| 3,058
|
go
|
Go
|
popup.go
|
hfmrow/search-and-replace
|
c907ebb4507e1fef836a8204999334ea11e91792
|
[
"MIT"
] | 1
|
2020-02-09T14:18:36.000Z
|
2020-02-09T14:18:36.000Z
|
popup.go
|
hfmrow/search-and-replace
|
c907ebb4507e1fef836a8204999334ea11e91792
|
[
"MIT"
] | null | null | null |
popup.go
|
hfmrow/search-and-replace
|
c907ebb4507e1fef836a8204999334ea11e91792
|
[
"MIT"
] | null | null | null |
// popup.go
/*
Source file auto-generated on Sat, 24 Apr 2021 04:33:11 using Gotk3 Objects Handler v1.7.8
©2018-21 hfmrow https://hfmrow.github.io
This software use gotk3 that is licensed under the ISC License:
https://github.com/gotk3/gotk3/blob/master/LICENSE
Copyright ©2018-21 hfmrow - Search And Replace v1.10 github.com/hfmrow/search-and-replace
This program comes with absolutely no warranty. See the The MIT License (MIT) for details:
https://opensource.org/licenses/mit-license.php
*/
package main
import (
"fmt"
"log"
"path/filepath"
"github.com/gotk3/gotk3/glib"
"github.com/gotk3/gotk3/gtk"
"github.com/hfmrow/gotk3_gtksource/source"
)
/*
* Init Popup
*/
// initPopupTreeView:
func initTreeViewPopupMenu() {
popupMenu = PopupMenuIconStructNew()
popupMenu.AddItem("Open _directory", func() {
getTreeViewFilename()
openDir(currFilename)
}, popupMenu.OPT_ICON|popupMenu.OPT_NORMAL, folder48)
popupMenu.AddItem("Open _file", func() {
getTreeViewFilename()
openFile(currFilename)
}, popupMenu.OPT_ICON|popupMenu.OPT_NORMAL, mimetypeSourceIconGolang48)
popupMenu.MenuBuild()
}
// Retrieve filename from selected row to "currFilename"
func getTreeViewFilename() {
var (
err error
value *glib.Value
iters []*gtk.TreeIter
)
if iters = tvsList.GetSelectedIters(); len(iters) > 0 {
if value, err = tvsList.ListStore.GetValue(iters[0], 3); err == nil { // Field 3: get full path
currFilename, err = value.GetString() // Get selected file path
}
}
}
// openFile:
func openFile(filename string) {
// if _, err := os.Stat(filename); !os.IsNotExist(err) {
open(filename)
// }
}
// openDir:
func openDir(filename string) {
// if _, err := os.Stat(filename); !os.IsNotExist(err) {
open(filepath.Dir(filename))
// }
}
// open: show file or dir depending on "path".
func open(path string) {
var goFunc = func() {
if _, err := ExecCommand([]string{opt.AppLauncher, path}); err != nil {
// Error is handled by "xdg-open" command
fmt.Println(err)
}
}
glib.IdleAdd(func() { // IdleAdd to permit gtk3 working right during goroutine
// Using goroutine to permit the usage of another thread and freeing the current one.
go goFunc()
})
}
// popupTextViewPopulateMenu: Append some items to contextmenu of the popup textview
func popupTextViewPopulateMenu(srcView *source.SourceView, popup *gtk.Widget) {
if IWidget, err := popup.Cast(); err == nil {
pop := IWidget.(*gtk.Menu)
// create new menuitems
popMenuTextView = PopupMenuIconStructNew()
popMenuTextView.AddItem("", nil, popMenuTextView.OPT_SEPARATOR)
popMenuTextView.AddItem("Open _directory", func() { openDir(currFilename) },
popMenuTextView.OPT_ICON|popMenuTextView.OPT_NORMAL, folder48)
popMenuTextView.AddItem("Open _file", func() { openFile(currFilename) },
popMenuTextView.OPT_ICON|popMenuTextView.OPT_NORMAL, mimetypeSourceIconGolang48)
// Append them to the existing menu
popMenuTextView.AppendToExistingMenu(pop)
} else {
log.Printf("popupTextViewPopulateMenu: %v\n", err)
}
}
| 24.66129
| 97
| 0.722368
|
df0ca4455e21336b1dcd7df0393a8f609133aad7
| 577
|
cs
|
C#
|
src/Katalye.Host/SignalR/PostgreSqlDependencyInjectionExtensions.cs
|
Silvenga/Katalye
|
1ee39b0ced434f983ef0cb7ee28d6b4a1fffe31e
|
[
"MIT"
] | 1
|
2019-01-17T03:38:42.000Z
|
2019-01-17T03:38:42.000Z
|
src/Katalye.Host/SignalR/PostgreSqlDependencyInjectionExtensions.cs
|
Silvenga/Katalye
|
1ee39b0ced434f983ef0cb7ee28d6b4a1fffe31e
|
[
"MIT"
] | 3
|
2019-01-17T03:49:23.000Z
|
2019-02-01T21:18:22.000Z
|
src/Katalye.Host/SignalR/PostgreSqlDependencyInjectionExtensions.cs
|
Silvenga/Katalye
|
1ee39b0ced434f983ef0cb7ee28d6b4a1fffe31e
|
[
"MIT"
] | 3
|
2019-06-04T12:25:00.000Z
|
2021-10-10T20:32:40.000Z
|
using System;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.DependencyInjection;
namespace Katalye.Host.SignalR
{
public static class PostgreSqlDependencyInjectionExtensions
{
public static ISignalRServerBuilder AddPostgreSql(this ISignalRServerBuilder signalrBuilder, Action<PostgreSqlOptions> options)
{
signalrBuilder.Services.Configure(options);
signalrBuilder.Services.AddSingleton(typeof(HubLifetimeManager<>), typeof(PostgreSqlHubLifetimeManager<>));
return signalrBuilder;
}
}
}
| 36.0625
| 135
| 0.750433
|
189539fc028cf26b942ffc816dea3aeafe0f3d31
| 1,593
|
ts
|
TypeScript
|
src/@next/components/molecules/index.ts
|
marbin274/farmacia-retail-saleor-storefront
|
bdc5486a36261540b032cfc45356b6562ebfd23b
|
[
"BSD-3-Clause"
] | null | null | null |
src/@next/components/molecules/index.ts
|
marbin274/farmacia-retail-saleor-storefront
|
bdc5486a36261540b032cfc45356b6562ebfd23b
|
[
"BSD-3-Clause"
] | null | null | null |
src/@next/components/molecules/index.ts
|
marbin274/farmacia-retail-saleor-storefront
|
bdc5486a36261540b032cfc45356b6562ebfd23b
|
[
"BSD-3-Clause"
] | null | null | null |
export * from './AccountMenu';
export * from './AccountMenuMobile';
export * from './AccountTabTiles';
export * from './AddressAutocomplete';
export * from './AddressAutocompleteField';
export * from './AddressGeocalization';
export * from './AddressSummary';
export * from './AddressTile';
export * from './Alert';
export * from './AttributeValuesChecklist';
export * from './CachedImage';
export * from './CreditCardItem';
export * from './CardHeader';
export * from './CartResume';
export * from './CartSummaryRow';
export * from './CheckoutProgressBar';
export * from './Collapse';
export * from './CreditCardNumberWithIcon';
export * from './FormFooter';
export * from './InputSelect';
export * from './InputSelectField';
export * from './InputTextField';
export * from './Map';
export * from './MapField';
export { default as MenuDropdown } from './MenuDropdown';
export * from './OrderTabel';
export * from './OutOfTimeMessage';
export * from './OverlayItem';
export * from './PopAlert';
export * from './ProductDescription';
export * from './ProductImage';
export * from './ProductListHeader';
export * from './ProductListHeaderSearch';
export * from './ProductTile';
export * from './ProductTileAUNA';
export * from './ProductTileHorizontalAUNA';
export * from './ResetPasswordForm';
export * from './ShippingMethodItem';
export * from './SkeletonCarousel';
export * from './TextField';
export * from './Thumbnail';
export * from './TileRadio';
export * from './TileRadioGroup';
export * from './TileRadioGroupField';
export * from './EmptyProduct';
export * from './PaymentContent';
| 33.893617
| 57
| 0.708098
|
82a6f581469efc7de024bc73dca86096345ca928
| 9,054
|
dart
|
Dart
|
lib/Authentication/SignUp.dart
|
prajwal2146/Driver-Drowsiness-Detection
|
36c708b990af52506a12b995c98c76f7fe8eef7c
|
[
"MIT"
] | null | null | null |
lib/Authentication/SignUp.dart
|
prajwal2146/Driver-Drowsiness-Detection
|
36c708b990af52506a12b995c98c76f7fe8eef7c
|
[
"MIT"
] | null | null | null |
lib/Authentication/SignUp.dart
|
prajwal2146/Driver-Drowsiness-Detection
|
36c708b990af52506a12b995c98c76f7fe8eef7c
|
[
"MIT"
] | null | null | null |
import 'dart:ffi';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/services.dart';
import 'package:vivify/Authentication/LoginPage.dart';
class SignUp extends StatefulWidget {
@override
_SignUpState createState() => _SignUpState();
}
class _SignUpState extends State<SignUp> {
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
TextEditingController _emailController;
TextEditingController _passwordController;
String email;
String password;
String errorMsg;
bool _obscureText = true;
Future<void> _showDialog(BuildContext context) {
return showDialog<void>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Mail Is Sent To Your Email'),
content: const Text('Please Confirm Your EmailID'),
actions: <Widget>[
FlatButton(
child: Text('Ok'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => LoginPage(),
),
);
},
),
],
);
},
);
}
_showDialog1(BuildContext context) {
return showDialog<void>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Alert'),
content: const Text('User Registered'),
actions: <Widget>[
FlatButton(
child: Text('Ok'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SignUp(),
),
);
},
),
],
);
},
);
}
Future<Void> _showDialog2(BuildContext context) {
return showDialog<void>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Alert'),
content: const Text('Email or Password field is Empty'),
actions: <Widget>[
FlatButton(
child: Text('Ok'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SignUp(),
),
);
},
),
],
);
},
);
}
@override
void initState() {
super.initState();
_emailController = TextEditingController(text: "");
_passwordController = TextEditingController(text: "");
}
void _toggle() {
setState(() {
_obscureText = !_obscureText;
});
}
@override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitDown,
DeviceOrientation.portraitUp,
]);
return Scaffold(
body: SingleChildScrollView(
child: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: ExactAssetImage('Images/Cover3.jpg'),
fit: BoxFit.fill,
),
),
height: MediaQuery.of(context).size.height,
padding: EdgeInsets.all(16.0),
child: Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image(
image: AssetImage('Images/Vivify.png'),
),
SizedBox(height: 20),
TextField(
controller: _emailController,
style: TextStyle(fontSize: 18.0),
onChanged: (value) {
email = value;
},
keyboardType: TextInputType.emailAddress,
textAlign: TextAlign.center,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(20.0),
),
hintStyle: TextStyle(
fontSize: 17.0,
fontFamily: "Quando",
color: Colors.blueAccent),
hintText: 'Enter Email',
labelText: 'Email',
labelStyle: TextStyle(
fontSize: 17.0,
fontFamily: "Quando",
color: Colors.blueAccent),
icon: Icon(Icons.email),
),
),
SizedBox(
height: 20.0,
),
TextField(
controller: _passwordController,
style: TextStyle(fontSize: 18.0),
onChanged: (value) {
password = value;
},
keyboardType: TextInputType.text,
textAlign: TextAlign.center,
obscureText: _obscureText,
decoration: InputDecoration(
suffixIcon: IconButton(
icon: Icon(_obscureText ? Icons.lock_open :Icons.lock_outline),
onPressed: _toggle,),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(20.0),
),
hintStyle: TextStyle(
fontSize: 17.0,
fontFamily: "Quando",
color: Colors.blueAccent),
hintText: 'Enter Password',
labelText: 'Password',
labelStyle: TextStyle(
fontSize: 17.0,
fontFamily: "Quando",
color: Colors.blueAccent),
icon: Icon(Icons.lock),
),
),
SizedBox(
height: 40.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
splashColor: Colors.grey,
color: Color(0xFF64DD03),
onPressed: () async {
if (_emailController.text.isEmpty ||
_passwordController.text.isEmpty) {
_showDialog2(context);
}
FirebaseUser user ;
if (user == null) {
try {
user = (await _firebaseAuth.createUserWithEmailAndPassword(
email: email, password: password)) as FirebaseUser;
await user.sendEmailVerification();
_showDialog(context);
}
catch (e) {
_showDialog1(context);
}
}
},
elevation: 20.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0),
),
highlightElevation: 20.0,
highlightColor: Colors.white,
child: Text(
'Sign Up',
style: TextStyle(
fontFamily: "Quando",
fontSize: 20.0,
color: Colors.black),
),
),
SizedBox(
width: 25.0,
),
RaisedButton(
splashColor: Colors.grey,
color: Colors.lightBlueAccent[200],
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return LoginPage();
},
),
);
},
elevation: 20.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0),
),
highlightElevation: 20.0,
highlightColor: Colors.white,
child: Text(
'Back',
style: TextStyle(
fontFamily: "Quando",
fontSize: 20.0,
color: Colors.black),
),
),
],
),
],
),
),
),
);
}
}
| 33.783582
| 85
| 0.421803
|
b02a69da54ea1e93314c8d2e6acc18097b8961a6
| 1,646
|
py
|
Python
|
glanceR.py
|
koenry/glance_Server
|
0c1b80caf1d59b2c4625bfd4984248f58908aae5
|
[
"MIT"
] | null | null | null |
glanceR.py
|
koenry/glance_Server
|
0c1b80caf1d59b2c4625bfd4984248f58908aae5
|
[
"MIT"
] | null | null | null |
glanceR.py
|
koenry/glance_Server
|
0c1b80caf1d59b2c4625bfd4984248f58908aae5
|
[
"MIT"
] | null | null | null |
import pyautogui
import time
import subprocess
import cv2
import os
import datetime
from PIL import ImageGrab, Image
# we're using alt+prtscrn to take a ss of the current window and PIL to grab from clipboard and save it
def main():
time.sleep(1.5)
image = pyautogui.locateOnScreen("glance1.png") # waits for putty to fully load
while image == None:
image = pyautogui.locateOnScreen('glance1.png', confidence=.5)
time.sleep(1)
print("Still loading")
pyautogui.typewrite('glance') # GLANCE command
time.sleep(1)
pyautogui.press('enter')
image = pyautogui.locateOnScreen("glance2.png") # waits for glance to completely load
while image == None:
image = pyautogui.locateOnScreen('glance2.png', confidence=.5)
time.sleep(1)
print("Still loading")
pyautogui.press('q')
time.sleep(1)
def end():
time.sleep(0.5)
pyautogui.typewrite('exit') # double exit for CMD to putty on w7
time.sleep(1)
pyautogui.press('enter')
time.sleep(1.5)
pyautogui.typewrite('exit') # double exit for CMD to putty on w7
time.sleep(1)
pyautogui.press('enter')
time.sleep(3)
# Server1
time.sleep(1)
subprocess.Popen("putty.exe user@IP -pw PASSWORD")
time.sleep(1.5)
main()
pyautogui.hotkey('alt', 'PrtSc')
im = ImageGrab.grabclipboard()
if isinstance(im, Image.Image):
im.save('output/1.jpg')
end()
# vice-versa for all other servers left
print("************************************FINISHED***********************************\n")
raw_input("\nPress Enter to continue...")
| 27.898305
| 104
| 0.624544
|
38539bb9c57d5ac895bb6fdc2aea7618de1c591a
| 2,049
|
php
|
PHP
|
app/Views/bbs_show.php
|
kenjis/ci4-tettei-apps
|
4d64e2fe02da8280a7747441f28a328bde256eac
|
[
"BSD-3-Clause"
] | 2
|
2021-04-16T02:02:28.000Z
|
2022-02-13T19:18:24.000Z
|
app/Views/bbs_show.php
|
Zhang70742/ci3-to-ci4-apps
|
bbb94aca3253e98c1937e29a94b3367b1b5e0c78
|
[
"BSD-3-Clause"
] | null | null | null |
app/Views/bbs_show.php
|
Zhang70742/ci3-to-ci4-apps
|
bbb94aca3253e98c1937e29a94b3367b1b5e0c78
|
[
"BSD-3-Clause"
] | null | null | null |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="ja" xml:lang="ja">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="<?= base_url('css/bbs.css'); ?>" type="text/css" />
<script type="text/javascript" src="<?= base_url('js/bbs.js'); ?>"></script>
<title>掲示板</title>
</head>
<body onload="MM_preloadImages('<?= base_url('images/icons/bbs_new_on.jpg'); ?>')">
<!-- header -->
<?php $this->load->view('bbs_header'); ?>
<!-- main -->
<div id="main">
<div class="title_banner">
<img src="<?= base_url('images/icons/bbs_titile.jpg'); ?>" alt="掲示板" width="580" height="70" />
</div>
<div class="bbs_new_post_button">
<a href="<?= $this->config->site_url(); ?>bbs/post">
<img src="<?= base_url('images/icons/bbs_new_off.jpg'); ?>" alt="新規投稿" name="toukou" width="150" height="50" border="0" id="toukou" onmouseover="MM_swapImage('toukou','','<?= base_url('images/icons/bbs_new_on.jpg'); ?>',1)" onmouseout="MM_swapImgRestore()" />
</a>
</div>
<!-- ページネーションを表示します。 -->
<?= $pagination; ?>
<!-- ここから、php endforeachまで、記事を表示するループです。 -->
<?php foreach($query->result() as $row): ?>
<div class="article">
<h1 class="f_bbs_titile"><a id="id<?= html_escape($row->id); ?>" name="id<?= html_escape($row->id); ?>">[<?= html_escape($row->id); ?>]</a>
<?= html_escape($row->subject); ?></h1>
<div class="f_bbs_coment"><?= html_escape($row->name); ?>
<?= html_escape($row->datetime); ?> </div>
<div class="f_bbs_coment"><?= nl2br(html_escape($row->body)); ?></div>
<!-- 記事を削除するためのフォームを表示します。 -->
<div class="f_bbs_delete">
<?= form_open('bbs/delete/'. $row->id); ?>
削除パスワード: <input type="text" name="password" size="12" value="" />
<input type="submit" value="削除" />
<?= form_close() ;?>
</div><!-- end of f_bbs_delete -->
</div><!-- end of article -->
<?php endforeach; ?>
<?= $pagination; ?>
</div>
<!-- footer -->
<?php $this->load->view('ci_footer'); ?>
</body>
</html>
| 37.254545
| 259
| 0.622255
|
e75cdf3eff89b3d842b60ff6b38b852c130d7dc0
| 26,206
|
php
|
PHP
|
resources/views/final/indexOLD.blade.php
|
JuanBatkis/ProyectoFinalDH
|
e5f64d30cdbc002292058d993a834fa48e1ab640
|
[
"MIT"
] | null | null | null |
resources/views/final/indexOLD.blade.php
|
JuanBatkis/ProyectoFinalDH
|
e5f64d30cdbc002292058d993a834fa48e1ab640
|
[
"MIT"
] | null | null | null |
resources/views/final/indexOLD.blade.php
|
JuanBatkis/ProyectoFinalDH
|
e5f64d30cdbc002292058d993a834fa48e1ab640
|
[
"MIT"
] | null | null | null |
<?php
session_start();
//require_once("functions.php");
if (!isset($_POST["register"])) {
$_POST["register"] = "false";
}
if (!isset($_POST["logIn"])) {
$_POST["logIn"] = "false";
}
if ($_POST && $_POST["register"] == "true") {
//pueden hacer el if ternario mientras asignan la variable O directamente en el value de HTML
$email = $_POST["email"];
$user= $_POST["username"];
$errores=validarDatos($_POST);
$erroresExiste=yaExiste($_POST);
if(empty($errores) && empty($erroresExiste)){
$usuario= crearUsuario($_POST);
subirArchivo($_FILES);
guardarUsuario($usuario);
$logIn = loginUsuario($_POST);
}
}
if ($_POST && $_POST["logIn"] == "true") {
$user= $_POST["username"];
$erroresLogin = validarLogin($_POST);
if (empty($erroresLogin)) {
$logIn = loginUsuario($_POST);
if (isset($_POST["remember"])){
setcookie("user", $user, time() + 604800);
}
}
}
if (isset($logIn["error"])) {
if ($logIn["error"] == "no") {
$_SESSION["user"] = $user;
}
}
if (isset($_POST["logOut"])) {
if ($_POST["logOut"] == "true") {
session_destroy();
setcookie("user", $user, time() - 604800);
header('Location: '.$_SERVER['REQUEST_URI']);
}
}
/*echo "POST: "; var_dump($_POST);
echo "<br>";
echo "SESSION: "; var_dump($_SESSION);
echo "<br>";
echo "COOKIE: "; var_dump($_COOKIE);*/
?>
<!DOCTYPE html>
<html>
<head>
<link rel="icon" href="imagenes/icon_thicc.ico">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.9/css/all.css" integrity="sha384-5SOiIsAziJl6AWe0HWRKTXlfcSHKmYV4RBF18PPJ173Kzn7jzMyFuTtk8JA7QQG1" crossorigin="anonymous">
<link rel="stylesheet" href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Montserrat:100,300,400,500,700,800,900" rel="stylesheet">
<link rel="stylesheet" href="css\home.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<title>YPC</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript">
enable = "<?php echo (!empty($errores) || !empty($erroresExiste))?"not_black":"black" ?>";
function logInBlock() {
enable = "not_black";
$('.selling-text').removeClass('black');
document.getElementById("demo").style.display = "block";
document.getElementById("demo_back").style.display = "block";
document.getElementById("demo2").style.display = "none";
document.getElementById("all").style.position = "fixed";
document.getElementById("all").style.overflow = "hidden";
document.getElementsByClassName("black").style.opacity = "1";
}
function signUpBlock() {
enable = "not_black";
$('.selling-text').removeClass('black');
document.getElementById("demo2").style.display = "block";
document.getElementById("demo_back").style.display = "block";
document.getElementById("demo").style.display = "none";
document.getElementById("all").style.position = "fixed";
document.getElementById("all").style.overflow = "hidden";
document.getElementsByClassName("black").style.opacity = "1";
}
function unlockAll() {
enable = "black";
document.getElementById("demo").style.display = "none";
document.getElementById("demo2").style.display = "none";
document.getElementById("demo_back").style.display = "none";
document.getElementById("all").style.position = "unset";
document.getElementById("all").style.overflow = "auto";
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
$(window).on('scroll', function() {
if ($(window).scrollTop()) {
$('.selling-text').addClass(enable);
$('.main_page').addClass('main_page_scroll');
$('.gen-ref').addClass('gen-ref-scroll');
} else {
$('.selling-text').removeClass(enable);
$('.main_page').removeClass('main_page_scroll');
$('.gen-ref').removeClass('gen-ref-scroll');
}
})
</script>
</head>
<body id="body">
<div class="container_log_in" id="demo" style="display:<?php echo (!empty($erroresLogin) || (!empty($logIn) && $logIn["error"] !== "no"))?"block":"none" ?>;"><!--Log In!-->
<div class="title">
<h1 class="main-title"><p class="brand y">Y</p><p class="brand p">P</p><p class="brand c">C</p></h1>
<i class="exit fas fa-times" onclick="unlockAll()"></i>
</div>
<!--<div class="logo_form">
<img src="imagenes\JustLogo_400_transp.png" alt="logo">
</div>
<div class="logo_fake">
<img src="imagenes\JustLogo_400_transp.png" alt="logo">
</div>-->
<div class="form">
<form class="form_form" action="" method="post">
@csrf
<input type="hidden" name="logIn" value="true">
<div class="form_all">
<label for="username" >Username or E-mail:</label>
<input type="text" name="username" id="username" value='<?php echo !empty($user)? $user:"" ?>'>
<span id='logIn_username_errorloc' class='error'style="font-size: 14px;color: #c22424;font-weight: 500;">
@if (!empty($erroresLogin["username"]))
{{ $erroresLogin["username"] }}
@else
{{ "" }}
@endif
</span>
<label for="pass" >Password:</label>
<input type="password" name="password" id="pass" value="<?php echo isset($_POST["remember"])? $_POST["password"]:"" ?>">
<span id='logIn_username_errorloc' class='error'style="font-size: 14px;color: #c22424;font-weight: 500;">
@if (!empty($erroresLogin["password"]))
{{ $erroresLogin["password"] }}
@elseif (!empty($logIn["error"]) && $logIn["error"] !== "no")
{{ $logIn["error"] }}
@else
{{ "" }}
@endif
</span>
<div class="acepto_cont">
<label class="check_container">Remember me
<input type="checkbox" name="remember" value="true">
<span class="checkmark"></span>
</label>
</div>
<div class="forg"><a href="#" class="log-link">Forgot your password?</a></div>
</div>
<input type="submit" name="send" id="send_log" class="send" value="Log In!">
</form>
<p class="log-link" onclick="signUpBlock()">Don't have an account? Sign up!</p>
</div>
</div>
<div class="container_log_in" id="demo2" style="display:<?php echo (!empty($errores) || !empty($erroresExiste))?"block":"none" ?>;"><!--Sign Up!-->
<div class="title">
<h1 class="main-title"><p class="brand y">Y</p><p class="brand p">P</p><p class="brand c">C</p></h1>
<i class="exit fas fa-times" onclick="unlockAll()"></i>
</div>
<div class="form" id='fg_membersite'>
<form id='register' class="form_form" action="" method="post" enctype="multipart/form-data">
<input type="hidden" name="register" value="true">
<input type='hidden' name='submitted' id='submitted' value='1'/>
<div class="form_all">
<label for='username' >Username:</label>
<input type='text' name='username' id='username' value='<?php echo !empty($user)? $user:"" ?>' maxlength="50" />
<span id='register_username_errorloc' class='error'style="font-size: 14px;color: #c22424;font-weight: 500;">
@if (!empty($errores["user"]))
{{ $errores["user"] }}
@elseif (!empty($erroresExiste["username"]))
{{ $erroresExiste["username"] }}
@else
{{ "" }}
@endif
</span>
<label for='email' >E-mail:</label>
<input type='email' name='email' id='email' value='<?php echo !empty($email)? $email:"" ?>' maxlength="50" />
<span id='register_email_errorloc' class='error'style="font-size: 14px;color: #c22424;font-weight: 500;">
@if (!empty($errores["email"]))
{{ $errores["email"] }}
@elseif (!empty($erroresExiste["email"]))
{{ $erroresExiste["email"] }}
@else
{{ "" }}
@endif
</span>
<label for='password' >Password:</label>
<div class='pwdwidgetdiv' id='thepwddiv' ></div>
<input type='password' name='password' id='password' maxlength="50" />
<span id='register_password_errorloc' class='error' style='clear:both;font-size: 14px;color: #c22424;font-weight: 500;'>
@if (!empty($errores["password"]))
{{ $errores["password"] }}
@else
{{ "" }}
@endif
</span>
<label for='conpassword' >Confirm Password:</label>
<div class='pwdwidgetdiv' id='thepwddiv' ></div>
<input type='password' name='cpassword' id='password' maxlength="50" />
<span id='register_password_errorloc' class='error' style='clear:both;font-size: 14px;color: #c22424;font-weight: 500;'>
@if (!empty($errores["password"]))
{{ $errores["password"] }}
@elseif (!empty($errores["match"]))
{{ $errores["match"] }}
@else
{{ "" }}
@endif
</span>
<!--<label for='email' >Upload profile picture (optional):</label>
<div id="upload-file-container" >
<input type="file" name="archivo"/>
</div>-->
<div class="acepto_cont">
<label class="check_container" style="color:<?php echo (!empty($errores["acepto"]))?"#c22424":"" ?>;">I have read and accepted the <a href="#" class="log-link">Terms and Conditions</a>
<input type="checkbox" name="acepto" value="yes">
<span class="checkmark"></span>
</label>
</div>
</div>
<input type="submit" name="logIn" id="send" class="send" value="Sign Up!">
</form>
<p class="log-link" onclick="logInBlock()">Already have an account? Log in!</p>
</div>
</div>
<div id="all" style="position:<?php echo (!empty($errores) || !empty($erroresExiste) || !empty($erroresLogin) || (!empty($logIn) && $logIn["error"] !== "no"))?"fixed":"unset" ?>;overflow:<?php echo (!empty($errores) || !empty($erroresExiste) || !empty($erroresLogin) || (!empty($logIn) && $logIn["error"] !== "no"))?"hidden":"auto" ?>;">
<div class="top">
<nav>
<div class="name">
<a href="home" class="name-link"><img src="imagenes\NewLogo_long_thicc_400.png" alt="logo" class="main_logo" draggable="false"></a>
</div>
@if (isset($_SESSION["user"]) || isset($_COOKIE["user"]))
<div class="log-block">
<div class="user-name user-name-col"> <?php echo (isset($_SESSION["user"]))?$_SESSION["user"]:$_COOKIE["user"] ?> </div>
<div class="setting_cont">
<div class="setting_arrow user-name"><i class="fas fa-angle-left"></i><i class="fas fa-cog"></i></div>
<div class="setting_text"><a class="setting_text_link" href="settings">Settings</a></div>
</div>
<form action="" method="post">
<input type="hidden" name="logOut" value="true">
<input type="submit" name="logOut_bt" id="logOut" class="logOut" value="Log Out?">
</form>
</div>
@else
<div class="log">
<ul class="log-list">
<li class="log-block"><a href="#" class="log-link-main" onclick="logInBlock()">Log In</a></li>
<li class="log-line">|</li>
<li class="log-block"><a href="#" class="log-link-main" onclick="signUpBlock()">Sign Up</a></li>
</ul>
</div>
@endif
</nav>
</div>
<div class="main_nav">
<div class="nav_left_cont">
<ul class="nav_left_ul">
<li class="bar_li">
<div class="bar_a"><i class="big-icon fas fa-desktop"></i><i class="link-arrow fas fa-angle-right"></i><a href="#">Start a Build</a></div>
</li>
<li class="bar_li">
<div class="bar_a"><i class="big-icon fas fa-search"></i><i class="link-arrow fas fa-angle-right"></i><a href="search">Browse by Software</a></div>
</li>
<li class="bar_li">
<div class="bar_a"><i class="big-icon far fa-clock"></i><i class="link-arrow fas fa-angle-right"></i><a href="#new">Newest Builds</a></div>
</li>
<li class="bar_li">
<div class="bar_a"><i class="big-icon fas fa-trophy"></i><i class="link-arrow fas fa-angle-right"></i><a href="#top">Top Builds</a></div>
</li>
<li class="bar_li">
<div class="bar_a"><i class="big-icon fas fa-question"></i><i class="link-arrow fas fa-angle-right"></i><a href="#faq">FAQ</a></div>
</li>
</ul>
</div>
</div>
<div class="main_cont_back">
<div class="back_cont"></div>
</div>
<div class="floating_text_cont">
<div class="floating_text">
<p class="selling-text" id="selling-text">tell us what you do and we'll tell you what you need</p>
</div>
</div>
<div class="main_page">
<div class="bout_us">
<h2 class="bout_us_h2">About <span>US</span></h2>
<p class="bout_us_p">Lorem ipsum, dolor sit amet consectetur adipisicing elit. Saepe deleniti quibusdam non velit, tempore amet harum fugiat labore reprehenderit nisi minima. Magnam, quisquam sit mollitia ea cupiditate impedit ducimus odit?Lorem ipsum, dolor sit amet consectetur adipisicing elit. Saepe deleniti quibusdam non velit, tempore amet harum fugiat labore reprehenderit nisi minima. Magnam, quisquam sit mollitia ea cupiditate impedit ducimus odit?Lorem ipsum, dolor sit amet consectetur adipisicing elit. Saepe deleniti quibusdam non velit, tempore amet harum fugiat labore reprehenderit nisi minima. Magnam, quisquam sit mollitia ea cupiditate impedit ducimus odit?</p>
</div>
<div class="gen-ref" id="new"></div>
<div class="generic">
<h2 class="generic_h2">Newest Builds</h2>
<div class="comodin">
<span class="navigate">
<a id="scrollRight1" href="#"><i class="fas fa-angle-left"></i></a>
<a id="endRight1" href="#"><i class="fas fa-angle-double-left"></i></a>
</span>
<div class="generic_cont1">
@for ($i=0; $i < 10; $i++)
<div class="build_card" id="build_card">
<h3>Build Name</h3>
<p>Specifications:</p>
<ul>
<li>Cpu: <div>PlaceHolder</div></li>
<li>Gpu: <div>PlaceHolder</div></li>
<li>RAM: <div>PlaceHolder</div></li>
<li>Storage Capacity: <div>PlaceHolder</div></li>
</ul>
</div>
@endfor
</div>
<span class="navigate">
<a id="scrollLeft1" href="#"><i class="fas fa-angle-right"></i></a>
<a id="endLeft1" href="#"><i class="fas fa-angle-double-right"></i></a>
</span>
<script class="por_paso">
var step = ($("#build_card").outerWidth(true)+4);
var w = window.innerWidth;
if (w<542) {
var mult = 1;
} else {
if (w<768) {
var mult = 2;
} else {
if (w<842) {
var mult = 1;
} else {
var mult = 2;
}
}
}
var scrolling = false;
// Wire up events for the 'scrollUp' link:
$("#scrollRight1").bind("click", function(event) {
event.preventDefault();
// Animates the scrollTop property by the specified
// step.
$(".generic_cont1").animate({
scrollLeft: "-=" + step + "px"
});
}).bind("mouseover", function(event) {
scrolling = false;
// scrollContent("right");
}).bind("mouseout", function(event) {
scrolling = false;
});
$("#scrollLeft1").bind("click", function(event) {
event.preventDefault();
$(".generic_cont1").animate({
scrollLeft: "+=" + step + "px"
});
}).bind("mouseover", function(event) {
scrolling = false;
// scrollContent("down");
}).bind("mouseout", function(event) {
scrolling = false;
});
function scrollContent(direction) {
var amount = (direction === "right" ? "-=1px" : "+=1px");
$(".generic_cont1").animate({
scrollLeft: amount
}, 1, function() {
if (scrolling) {
scrollContent(direction);
}
});
}
</script>
<script class="final">
var end = 10000;
var scrolling = false;
// Wire up events for the 'scrollUp' link:
$("#endRight1").bind("click", function(event) {
event.preventDefault();
// Animates the scrollTop property by the specified
// step.
$(".generic_cont1").animate({
scrollLeft: "-=" + end + "px"
});
}).bind("mouseover", function(event) {
scrolling = false;
// scrollContent("right");
}).bind("mouseout", function(event) {
scrolling = false;
});
$("#endLeft1").bind("click", function(event) {
event.preventDefault();
$(".generic_cont1").animate({
scrollLeft: "+=" + end + "px"
});
}).bind("mouseover", function(event) {
scrolling = false;
// scrollContent("down");
}).bind("mouseout", function(event) {
scrolling = false;
});
function scrollContent(direction) {
var amount = (direction === "right" ? "-=1px" : "+=1px");
$(".generic_cont1").animate({
scrollLeft: amount
}, 1, function() {
if (scrolling) {
scrollContent(direction);
}
});
}
</script>
</div>
</div>
<div class="gen-ref" id="top"></div>
<div class="generic">
<h2 class="generic_h2">Top Builds</h2>
<div class="comodin">
<span class="navigate">
<a id="scrollRight2" href="#"><i class="fas fa-angle-left"></i></a>
<a id="endRight2" href="#"><i class="fas fa-angle-double-left"></i></a>
</span>
<div class="generic_cont2">
@for ($i=0; $i < 10; $i++)
<div class="build_card" id="build_card">
<h3>Build Name</h3>
<p>Specifications:</p>
<ul>
<li>Cpu: <div>PlaceHolder</div></li>
<li>Gpu: <div>PlaceHolder</div></li>
<li>RAM: <div>PlaceHolder</div></li>
<li>Storage Capacity: <div>PlaceHolder</div></li>
</ul>
</div>
@endfor
</div>
<span class="navigate">
<a id="scrollLeft2" href="#"><i class="fas fa-angle-right"></i></a>
<a id="endLeft2" href="#"><i class="fas fa-angle-double-right"></i></a>
</span>
<script class="por_paso">
var step = ($("#build_card").outerWidth(true)+4);
var w = window.innerWidth;
if (w<542) {
var mult = 1;
} else {
if (w<768) {
var mult = 2;
} else {
if (w<842) {
var mult = 1;
} else {
var mult = 2;
}
}
}
var scrolling = false;
// Wire up events for the 'scrollUp' link:
$("#scrollRight2").bind("click", function(event) {
event.preventDefault();
// Animates the scrollTop property by the specified
// step.
$(".generic_cont2").animate({
scrollLeft: "-=" + step + "px"
});
}).bind("mouseover", function(event) {
scrolling = false;
// scrollContent("right");
}).bind("mouseout", function(event) {
scrolling = false;
});
$("#scrollLeft2").bind("click", function(event) {
event.preventDefault();
$(".generic_cont2").animate({
scrollLeft: "+=" + step + "px"
});
}).bind("mouseover", function(event) {
scrolling = false;
// scrollContent("down");
}).bind("mouseout", function(event) {
scrolling = false;
});
function scrollContent(direction) {
var amount = (direction === "right" ? "-=1px" : "+=1px");
$(".generic_cont2").animate({
scrollLeft: amount
}, 1, function() {
if (scrolling) {
scrollContent(direction);
}
});
}
</script>
<script class="final">
var end = 10000;
var scrolling = false;
// Wire up events for the 'scrollUp' link:
$("#endRight2").bind("click", function(event) {
event.preventDefault();
// Animates the scrollTop property by the specified
// step.
$(".generic_cont2").animate({
scrollLeft: "-=" + end + "px"
});
}).bind("mouseover", function(event) {
scrolling = false;
// scrollContent("right");
}).bind("mouseout", function(event) {
scrolling = false;
});
$("#endLeft2").bind("click", function(event) {
event.preventDefault();
$(".generic_cont2").animate({
scrollLeft: "+=" + end + "px"
});
}).bind("mouseover", function(event) {
scrolling = false;
// scrollContent("down");
}).bind("mouseout", function(event) {
scrolling = false;
});
function scrollContent(direction) {
var amount = (direction === "right" ? "-=1px" : "+=1px");
$(".generic_cont2").animate({
scrollLeft: amount
}, 1, function() {
if (scrolling) {
scrollContent(direction);
}
});
}
</script>
</div>
</div>
<div class="gen-ref" id="faq"></div>
<div class="generic">
<h2 class="generic_h2">FAQ</h2>
<div class="generic_cont_q">
<div class="question">
<h3>Do I need to pay for this service? <i class="indic fas fa-angle-right"></i></h3>
<p class="answer">Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptas, dicta beatae quidem saepe corrupti molestias doloremque, ullam nam impedit, qui amet non. Voluptates, officiis adipisci. Dolor consequuntur odio quas ratione!Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptas, dicta beatae quidem saepe corrupti molestias doloremque, ullam nam impedit, qui amet non. Voluptates, officiis adipisci. Dolor consequuntur odio quas ratione!</p>
</div>
<div class="question">
<h3>How do I save my builds? <i class="indic fas fa-angle-right"></i></h3>
<p class="answer">Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptas, dicta beatae quidem saepe corrupti molestias doloremque, ullam nam impedit, qui amet non. Voluptates, officiis adipisci. Dolor consequuntur odio quas ratione!Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptas, dicta beatae quidem saepe corrupti molestias doloremque, ullam nam impedit, qui amet non. Voluptates, officiis adipisci. Dolor consequuntur odio quas ratione!</p>
</div>
<div class="question">
<h3>Can everyone see my builds? <i class="indic fas fa-angle-right"></i></h3>
<p class="answer">Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptas, dicta beatae quidem saepe corrupti molestias doloremque, ullam nam impedit, qui amet non. Voluptates, officiis adipisci. Dolor consequuntur odio quas ratione!Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptas, dicta beatae quidem saepe corrupti molestias doloremque, ullam nam impedit, qui amet non. Voluptates, officiis adipisci. Dolor consequuntur odio quas ratione!</p>
</div>
<div class="question">
<h3>Do I need to sign up to use this service? <i class="indic fas fa-angle-right"></i></h3>
<p class="answer">Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptas, dicta beatae quidem saepe corrupti molestias doloremque, ullam nam impedit, qui amet non. Voluptates, officiis adipisci. Dolor consequuntur odio quas ratione!Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptas, dicta beatae quidem saepe corrupti molestias doloremque, ullam nam impedit, qui amet non. Voluptates, officiis adipisci. Dolor consequuntur odio quas ratione!</p>
</div>
<div class="question">
<h3>The software I use is not listed. What do I do? <i class="indic fas fa-angle-right"></i></h3>
<p class="answer">Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptas, dicta beatae quidem saepe corrupti molestias doloremque, ullam nam impedit, qui amet non. Voluptates, officiis adipisci. Dolor consequuntur odio quas ratione!Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptas, dicta beatae quidem saepe corrupti molestias doloremque, ullam nam impedit, qui amet non. Voluptates, officiis adipisci. Dolor consequuntur odio quas ratione!</p>
</div>
<div class="question">
<h3>How are the top builds chosen? <i class="indic fas fa-angle-right"></i></h3>
<p class="answer">Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptas, dicta beatae quidem saepe corrupti molestias doloremque, ullam nam impedit, qui amet non. Voluptates, officiis adipisci. Dolor consequuntur odio quas ratione!Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptas, dicta beatae quidem saepe corrupti molestias doloremque, ullam nam impedit, qui amet non. Voluptates, officiis adipisci. Dolor consequuntur odio quas ratione!</p>
</div>
<div class="question">
<h3>For how long will I have my builds stored? <i class="indic fas fa-angle-right"></i></h3>
<p class="answer">Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptas, dicta beatae quidem saepe corrupti molestias doloremque, ullam nam impedit, qui amet non. Voluptates, officiis adipisci. Dolor consequuntur odio quas ratione!Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptas, dicta beatae quidem saepe corrupti molestias doloremque, ullam nam impedit, qui amet non. Voluptates, officiis adipisci. Dolor consequuntur odio quas ratione!</p>
</div>
<div class="question">
<h3>What can I do to support this page? <i class="indic fas fa-angle-right"></i></h3>
<p class="answer">Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptas, dicta beatae quidem saepe corrupti molestias doloremque, ullam nam impedit, qui amet non. Voluptates, officiis adipisci. Dolor consequuntur odio quas ratione!Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptas, dicta beatae quidem saepe corrupti molestias doloremque, ullam nam impedit, qui amet non. Voluptates, officiis adipisci. Dolor consequuntur odio quas ratione!</p>
</div>
</div>
</div>
</div>
</div>
</body>
<div class="back" id="demo_back" style="display:<?php echo (!empty($errores) || !empty($erroresExiste) || !empty($erroresLogin) || (!empty($logIn) && $logIn["error"] !== "no"))?"block":"none" ?>;" onclick="unlockAll()">
</div>
<div id="invento">
</div>
</html>
| 42.131833
| 686
| 0.611654
|
b0b25f97bf2dc90e0b287c037d895b17fad2e660
| 1,192
|
py
|
Python
|
yatube/posts/migrations/0011_auto_20220127_2115.py
|
Andr3w-k/yatube_final
|
940266c92eae10edf94692263ab1552afe5f6363
|
[
"MIT"
] | null | null | null |
yatube/posts/migrations/0011_auto_20220127_2115.py
|
Andr3w-k/yatube_final
|
940266c92eae10edf94692263ab1552afe5f6363
|
[
"MIT"
] | null | null | null |
yatube/posts/migrations/0011_auto_20220127_2115.py
|
Andr3w-k/yatube_final
|
940266c92eae10edf94692263ab1552afe5f6363
|
[
"MIT"
] | null | null | null |
# Generated by Django 2.2.16 on 2022-01-27 21:15
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('posts', '0010_follow'),
]
operations = [
migrations.AlterModelOptions(
name='comment',
options={'ordering': ('-created',), 'verbose_name': 'Комментарий', 'verbose_name_plural': 'Комментарии'},
),
migrations.AlterModelOptions(
name='follow',
options={'verbose_name': 'Подписка', 'verbose_name_plural': 'Подписки'},
),
migrations.AlterModelOptions(
name='group',
options={'verbose_name': 'Группа', 'verbose_name_plural': 'Группы'},
),
migrations.AlterField(
model_name='comment',
name='post',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='posts.Post', verbose_name='Пост'),
),
migrations.AddConstraint(
model_name='follow',
constraint=models.UniqueConstraint(fields=('user', 'author'), name='unique subscription'),
),
]
| 33.111111
| 144
| 0.602349
|
2fc751a07689597eb520fe0eb4337776e6ff00df
| 16
|
py
|
Python
|
python/coursera_python/MICHIGAN/DataStructures/test/range.py
|
SayanGhoshBDA/code-backup
|
8b6135facc0e598e9686b2e8eb2d69dd68198b80
|
[
"MIT"
] | 16
|
2018-11-26T08:39:42.000Z
|
2019-05-08T10:09:52.000Z
|
python/coursera_python/MICHIGAN/DataStructures/test/range.py
|
SayanGhoshBDA/code-backup
|
8b6135facc0e598e9686b2e8eb2d69dd68198b80
|
[
"MIT"
] | 8
|
2020-05-04T06:29:26.000Z
|
2022-02-12T05:33:16.000Z
|
python/coursera_python/MICHIGAN/DataStructures/test/range.py
|
SayanGhoshBDA/code-backup
|
8b6135facc0e598e9686b2e8eb2d69dd68198b80
|
[
"MIT"
] | 5
|
2020-02-11T16:02:21.000Z
|
2021-02-05T07:48:30.000Z
|
print(range(4))
| 8
| 15
| 0.6875
|
46eab922cc718d255274322d4507831c28b1e5c4
| 5,734
|
py
|
Python
|
SVM.py
|
AIKICo/Steganalysis-By-Frame
|
c2e1a20664056eb723c694949119a26f7fb6cfbc
|
[
"Apache-2.0"
] | 1
|
2019-03-25T07:20:05.000Z
|
2019-03-25T07:20:05.000Z
|
SVM.py
|
MohMehrnia/Steganalysis-By-Frame
|
c2e1a20664056eb723c694949119a26f7fb6cfbc
|
[
"Apache-2.0"
] | 1
|
2020-01-29T07:12:02.000Z
|
2020-01-29T07:12:02.000Z
|
SVM.py
|
MohMehrnia/Steganalysis-By-Frame
|
c2e1a20664056eb723c694949119a26f7fb6cfbc
|
[
"Apache-2.0"
] | null | null | null |
import csv
import numpy as np
from sklearn import svm
from sklearn.metrics.classification import accuracy_score
from sklearn.metrics import classification_report
from sklearn.metrics import roc_auc_score
from sklearn.metrics import roc_curve
import matplotlib.pyplot as plt
from sklearn.neural_network import MLPClassifier
def loaddata(filename,instanceCol):
file_reader = csv.reader(open(filename,'r'),delimiter=',')
x = []
y = []
for row in file_reader:
x.append(row[0:instanceCol])
y.append(row[-1])
return np.array(x[1:]).astype((np.float32)), np.array(y[1:]).astype(np.int)
def fractal_modeldata(filename, inc, plotlabel, count, te, a=0):
scores = []
print(filename)
X, Y = loaddata(filename, inc)
np.random.seed(13)
indices = np.random.permutation(count)
test_size = int(te * len(indices))
X_train = X[indices[:-test_size]]
Y_train = Y[indices[:-test_size]]
X_test = X[indices[-test_size:]]
Y_test = Y[indices[-test_size:]]
classifier = svm.SVC(probability=True)
# classifier = MLPClassifier(probability=True)
classifier.fit(X_train, Y_train)
Y_pred = classifier.predict(X_test)
y_pred_prob = classifier.predict_proba(X_test)[::, 1]
fpr, tpr, thre = roc_curve(Y_test, y_pred_prob)
auc = roc_auc_score(Y_test, np.asarray(Y_pred), average='weighted')
# plt.plot(fpr, tpr, markerfacecolor='none', label=plotlabel + ' AUC=' + str(auc))
if (a!=0):
plt.plot(fpr, tpr, markerfacecolor='none', label=plotlabel + ' AUC='+ str(round(a * 100 ,2)))
else:
plt.plot(fpr, tpr, markerfacecolor='none', label=plotlabel + ' AUC='+ str(round(auc * 100 ,2)))
plt.legend()
# print(classification_report(Y_test, Y_pred))
if __name__ == '__main__':
plt.figure()
plt.plot([0, 1], [0, 1], 'k--', lw=1)
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
# fractal_modeldata('D:\\MySourceCodes\\Projects-Python\\Steganalysis-By-Frame\\SteganalysisDatasets\\Dataset\\Fractal\\Fractal-Features-hide4pgp-100.csv',33, 'Fractal AUC=80.86')
# fractal_modeldata('D:\\MySourceCodes\\Projects-Python\\Steganalysis-By-Frame\\SteganalysisDatasets\\Dataset\\DeltaMFCC\\deltaMFCC-Features-hide4pgp-100.csv', 26, 'MFCC AUC=76.01')
# fractal_modeldata('D:\\MySourceCodes\\Projects-Python\\Steganalysis-By-Frame\\SteganalysisDatasets\\Dataset\\LogFBank\\LogFBank-Features-hide4pgp-100.csv',33, 'MFB AUC=74.12')
# fractal_modeldata('D:\\MySourceCodes\\Projects-Python\\Steganalysis-By-Frame\\SteganalysisDatasets\\Dataset\\FBank\\FBank-Features-hide4pgp-100.csv',33, 'LPC AUC=72.34')
# fractal_modeldata('D:\\MySourceCodes\\Projects-Python\\Steganalysis-By-Frame\\SteganalysisDatasets\\Dataset\\MFCC\\MFCC-Features-hide4pgp-100.csv',33, 'Wavelet AUC=30.09')
# fractal_modeldata('D:\\MySourceCodes\\Projects-Python\\Steganalysis-By-Frame\\SteganalysisDatasets\\Dataset\\LPC\\lpc-Features-hide4pgp-100.csv',33, '△MFCC AUC=74.05')
# fractal_modeldata('D:\\MySourceCodes\\Projects-Python\\Steganalysis-By-Frame\\SteganalysisDatasets\\Dataset\\Fractal\\Fractal-Features-steghide-100.csv',33, 'Proposed', 2038, 0.1, 0.9136)
# fractal_modeldata('D:\\MySourceCodes\\Projects-Python\\Steganalysis-By-Frame\\SteganalysisDatasets\\Dataset\\LogFBank\\LogFBank-Features-steghide-100.csv',33, 'GB', 2038,0.1, 0.8711)
# fractal_modeldata('D:\\MySourceCodes\\Projects-Python\\Steganalysis-By-Frame\\SteganalysisDatasets\\Dataset\\LogFBank\\LogFBank-Features-steghide-100.csv',33, 'MLP', 2038,0.5, 0.8625)
# fractal_modeldata('D:\\MySourceCodes\\Projects-Python\\Steganalysis-By-Frame\\SteganalysisDatasets\\Dataset\\LogFBank\\LogFBank-Features-steghide-100.csv',33, 'RF', 2038, 0.9, 0.8832)
# fractal_modeldata('D:\\MySourceCodes\\Projects-Python\\Steganalysis-By-Frame\\SteganalysisDatasets\\Dataset\\LPC\\lpc-Features-steghide-100.csv',33, 'KNN', 2038, 0.1, 0.7912)
# fractal_modeldata('D:\\MySourceCodes\\Projects-Python\\Steganalysis-By-Frame\\SteganalysisDatasets\\Dataset\\MFCC\\mfcc-Features-steghide-100.csv',29, 'Adaboost', 2038, 0.1, 0.8036)
# fractal_modeldata('D:\\MySourceCodes\\Projects-Python\\Steganalysis-By-Frame\\SteganalysisDatasets\\Dataset\\LogFBank\\LogFBank-Features-steghide-100.csv',20, 'DT', 2038,0.1, 0.78)
fractal_modeldata('D:\\MySourceCodes\\Projects-Python\\Steganalysis-By-Frame\\SteganalysisDatasets\\Dataset\\DeltaMFCC\\deltaMFCC-Features-steghide-100.csv',33, 'Proposed', 2038, 0.1, 1)
fractal_modeldata('D:\\MySourceCodes\\Projects-Python\\Steganalysis-By-Frame\\SteganalysisDatasets\\Dataset\\LogFBank\\LogFBank-Features-steghide-100.csv',33, 'MLP', 2038,0.6, 0.9886)
fractal_modeldata('D:\\MySourceCodes\\Projects-Python\\Steganalysis-By-Frame\\SteganalysisDatasets\\Dataset\\LogFBank\\LogFBank-Features-steghide-100.csv',33, 'DT', 2038,0.7, 0.9811)
fractal_modeldata('D:\\MySourceCodes\\Projects-Python\\Steganalysis-By-Frame\\SteganalysisDatasets\\Dataset\\LogFBank\\LogFBank-Features-steghide-100.csv',33, 'GB', 2038, 0.8, 0.8825)
fractal_modeldata('D:\\MySourceCodes\\Projects-Python\\Steganalysis-By-Frame\\SteganalysisDatasets\\Dataset\\LPC\\lpc-Features-steghide-100.csv',33, 'RF', 2038, 0.1, 0.8617)
fractal_modeldata('D:\\MySourceCodes\\Projects-Python\\Steganalysis-By-Frame\\SteganalysisDatasets\\Dataset\\MFCC\\mfcc-Features-steghide-100.csv',29, 'KNN', 2038, 0.1, 0.8036)
fractal_modeldata('D:\\MySourceCodes\\Projects-Python\\Steganalysis-By-Frame\\SteganalysisDatasets\\Dataset\\LogFBank\\LogFBank-Features-steghide-100.csv',20, 'Adaboost', 2038,0.1, 0.78)
plt.legend(loc='lower right')
plt.show()
| 69.084337
| 193
| 0.728462
|
b315d5e7c5561b17e1ba8b2d426a6e4148b62f10
| 20,271
|
py
|
Python
|
bnbapp/protocols/utils.py
|
Bionetbook/bionetbook
|
c92d5bbdc5c121631c2230cf93aa63977d381f30
|
[
"MIT"
] | null | null | null |
bnbapp/protocols/utils.py
|
Bionetbook/bionetbook
|
c92d5bbdc5c121631c2230cf93aa63977d381f30
|
[
"MIT"
] | null | null | null |
bnbapp/protocols/utils.py
|
Bionetbook/bionetbook
|
c92d5bbdc5c121631c2230cf93aa63977d381f30
|
[
"MIT"
] | null | null | null |
from protocols.forms import verbs as verb_forms
from protocols.forms import forms
import time
import pprint
pp = pprint.PrettyPrinter(indent=4)
def get_verb_list():
verb_list = []
for attr_name in dir(verb_forms):
form_candidate = getattr(verb_forms, attr_name, None)
try:
if issubclass(form_candidate, forms.Form):
verb_list.append(form_candidate)
except TypeError:
continue
return verb_list
VERB_LIST = get_verb_list()
VERB_CHOICES = [(x.slug, x.name) for x in VERB_LIST]
VERB_FORM_DICT = {x.slug: x for x in VERB_LIST}
MACHINE_VERBS = [x.slug for x in VERB_LIST if x.has_machine]
COMPONENT_VERBS = [x.slug for x in VERB_LIST if x.has_component]
THERMOCYCLER_VERBS = [x.slug for x in VERB_LIST if x.has_thermocycler]
MANUAL_VERBS = [x.slug for x in VERB_LIST if x.has_manual]
MANUAL_LAYER = dict((x.slug, x.layers) for x in VERB_LIST if x.layers)
# MANUAL_LAYER={'mix':['technique_comment','duration','duration_units'],
# 'place':['item_to_place','target','conditional_statement','technique_comment','duration','duration_units'],
# 'discard':['item_to_discard','item_to_retain','conditional_statement','technique_comment','duration','duration_units'],
# 'let-sit-stand':'settify',
# 'store':'settify',
# 'transfer':['item_to_place','old_vessel','new_vessel','item_to_discard','technique_comment','min_vol','vol_units','duration','duration_units'],
# 'dry':['technique_comment'],
# }
def settify(settings_dict, shorthand = True, summary = False, action = False, comments = False):
settings = []
units = ''
output = {}
# Duration replaces min_time if None, or not present.
# if 'duration' in settings_dict:
# if 'min_time' not in settings_dict or not settings_dict['min_time']:
# settings_dict['min_time'] = settings_dict['duration']
# if 'duration_units' in settings_dict:
# if 'time_units' not in settings_dict or not settings_dict['time_units']:
# settings_dict['time_units'] = settings_dict['duration_units']
items = ['temp', 'time', 'speed', 'cycle', 'comment', 'conc', 'vol', 'mass', 'link', 'technique']
for item in items:
data = dict((k, v) for k, v in settings_dict.iteritems() if item in k and v != None)
if not data:
continue
if item == 'cycle':
units = None
numbers = None
out = None
plural = ' cycles'
if 'cycle_back_to' in data and 'cycles' in data:
if data['cycles'] == '1':
plural = ' cycle'
numbers = str(data['cycles'])
units = plural
cycle_to = data['cycle_back_to']
if 'cycles' in data and 'cycle_back_to' not in data:
if data['cycles'] == '1':
plural = ' cycle'
numbers = str(data['cycles'])
units = plural
if summary:
output['cycles'] = numbers
output['cycle_back_to'] = data.get('cycle_back_to', None)
else:
settings.append(out)
if item == 'link':
if summary:
output['link'] = data['protocol_link']
if item == 'technique':
if 'technique_comment' in settings_dict:
output['technique_comment'] = settings_dict['technique_comment']
else:
max_item = 'max_' + item
min_item = 'min_' + item
unit_item = item + '_units'
comment_item = item + '_comment'
units = None
numbers = None
out = None
if max_item in data and min_item in data:
if data[max_item] == data[min_item]:
# units_c = conc['max_conc']
numbers = str(data[max_item])
else:
# units_c = data[min_item] + '-' + data[max_item]
numbers = str(data[min_item]) + '-' + str(data[max_item])
else:
if max_item in data:
# units_c = conc[max_item]
numbers = str(data[max_item])
if min_item in data:
# units_c = conc[min_item]
numbers = str(data[min_item])
if numbers != None:
if unit_item in data:
units = str(data[unit_item])
else:
units = ''
# return 'no concentration units specified for %s' % units_dict['name']
out = str(numbers) + ' ' + units
if comment_item in data:
comment = str(data[comment_item])
else:
comment = None
if shorthand:
units = shorten(units)
if comment:
output[item] = [numbers, units, comment]
if summary:
output[item] = [numbers, units]
else:
settings.append(out)
if summary:
return output
else:
return settings
def shorten(units):
d ={'nanograms':'ng',
'micrograms':'ug',
'milligrams':'mg',
'grams':'g',
'kilograms':'kg',
'nanoLiter':'ng',
'microLiter':'ul',
'microliter':'ul',
'milliLiter':'ml',
'Liters':'L',
'nanoMolar':'nM',
'microMolar':'uM',
'milliMolar':'mM',
'Molar':'M',
'nanomole':'nm',
'micromole':'um',
'millimole':'mm',
'mole':'m',
'nanograms/microLiter': 'ng/ul',
'Units/microliter': 'U/ul',
'Units': 'U',
# 'X':'X',
'minutes':'min',
'minute':'min',
'mins':'min',
'minu':'min',
'seconds':'sec',
'second':'sec',
'sec':'sec',
'hour':'hr',
'hours':'hr',
'day':'d',
'days':'d',
'degrees Celsius':'C',
'celsius':'C',
'farenheit':'F',
'kelvin':'K',
}
try:
short_units = d[units]
except KeyError:
short_units = units
return short_units
def labeler(object_dict):
output = {}
if object_dict['verb'] in MANUAL_VERBS:
verb_attrib_order = list(MANUAL_LAYER[object_dict['verb']]) # if this is not deep copied, the pop(settify) messes it up
output['display_order'] = verb_attrib_order
for item in verb_attrib_order:
if 'name' in object_dict.keys():
output['name'] = object_dict['name']
if item in object_dict.keys():
output[item] = object_dict[item]
if 'duration' in object_dict.keys() and 'duration_units' in object_dict.keys():
output['time'] = [object_dict['duration'], object_dict['duration_units']]
if 'duration' in object_dict.keys() and 'duration_units' not in object_dict.keys():
output['time'] = [object_dict['duration'], 'sec']
if 'settify' in item:
output.update(settify(object_dict, summary=True))
#SPECIAL CASES:
if 'call-for-protocol' in object_dict['verb']:
output['protocol_link'] = object_dict['protocol_name']
if 'settify' in verb_attrib_order:
settify_order = ['temp', 'speed', 'conc', 'vol', 'mass', 'time', 'technique_comment', 'link']
[output['display_order'].append(r) for r in settify_order if r in output.keys()]
output['display_order'].pop(output['display_order'].index('settify'))
return output
def get_timeunit(time_var, desired_unit = 'sec'):
''' time_var = [value_str, 'units']
return (float(min_value), [,float(max_value)], 'units', 'original units')
'''
factor = {
'sec' : {'sec': 1, 'min': 60, 'hrs': 3600,'h': 3600, 'd' : 86400, 'yrs': 31536000},
'min' : {'sec': 1/60, 'min': 1, 'hrs': 60, 'h': 60,'d' : 1440, 'yrs': 525600},
'hrs' : {'sec': 1/3600, 'min': 1/60, 'hrs': 1, 'h': 1, 'd' : 24, 'yrs': 8760},
'h' : {'sec': 1/3600, 'min': 1/60, 'hrs': 1, 'h': 1, 'd' : 24, 'yrs': 8760},
'd' : {'sec': 1/86400, 'min': 1/3600, 'hrs': 1/60, 'h': 1/60, 'd' : 1, 'yrs': 365},
'yrs' : {'sec': 1/31536000, 'min': 1/525600, 'hrs': 1/8760, 'h': 1/8760, 'd' : 1/365, 'yrs': 1},
}
if isinstance(time_var[0], str) and '-' in time_var[0]:
min_time = str(time_var[0][:time_var[0].index('-')])
max_time = str(time_var[0][time_var[0].index('-')+1:])
return ((float(factor[desired_unit][time_var[1]]) * float(min_time)),
(float(factor[desired_unit][time_var[1]]) * float(max_time)),
desired_unit,
time_var[1])
else:
return ((float(factor[desired_unit][time_var[1]]) * float(time_var[0])),
desired_unit,
time_var[1])
def eval_time(node, value = 'min_time'):
'''
return a string in sec 'min_time - max_time'
'''
# action_min_time = 0
# action_max_time = 0
time_unit = 'sec'
factor = {
'sec' : {'sec': 1, 'min': 60, 'hrs': 3600,'h': 3600, 'd' : 86400, 'yrs': 31536000},
'min' : {'sec': 1/60, 'min': 1, 'hrs': 60, 'h': 60,'d' : 1440, 'yrs': 525600},
'hrs' : {'sec': 1/3600, 'min': 1/60, 'hrs': 1, 'h': 1, 'd' : 24, 'yrs': 8760},
'h' : {'sec': 1/3600, 'min': 1/60, 'hrs': 1, 'h': 1, 'd' : 24, 'yrs': 8760},
'd' : {'sec': 1/86400, 'min': 1/3600, 'hrs': 1/60, 'h': 1/60, 'd' : 1, 'yrs': 365},
'yrs' : {'sec': 1/31536000, 'min': 1/525600, 'hrs': 1/8760, 'h': 1/8760, 'd' : 1/365, 'yrs': 1},
}
if 'time_units' in node and node['time_units'] is not None:
time_unit = node['time_units']
if time_unit == "minutes": # TEMP FIX TO SEE IF THIS WORKS. SOME PROTOCOLS NEED TO BE CORRECTED.
time_unit = "min"
if value in node and node[value] is not None:
return float(factor['sec'][time_unit]) * float(node[value])
try:
return float(factor['sec'][time_unit]) * float(node['min_time'])
except:
return 0
class ProtocolChangeLog(object):
def __init__(self, old_state, new_state):
self.old_record = old_state
self.new_record = new_state
self.old = self.record_to_dict(self.old_record)
self.new = self.record_to_dict(self.new_record)
self.hdf = {}
if self.old:
self.diff_protocol_keys()
self.diff_nodes()
else:
self.log_item(self.new_record.pk, 'create', 'protocol', self.new)
def record_to_dict(self, record):
result = {}
if record:
tmp_dict = record.__dict__
for key in tmp_dict:
if key[0] != "_":
result[key] = tmp_dict[key]
return result
def log_item(self, objectid, event, otype, data, parent_id=None):
new = True
if not event in self.hdf:
self.hdf[event] = []
# CHECK TO SEE IF THIS ITEM IS ALREADY IN THE LOG OR NOT
for item in self.hdf[event]:
if item['id'] == objectid and item['type'] == otype: # THEY ARE THE SAME OBJECT
item['attrs'].update( data )
new = False
if new:
self.hdf[event].append( { 'id':objectid, 'type':otype, 'attrs':data, 'parent_id':parent_id } )
def diff_protocol_keys(self):
'''
Takes the two Protocol Model Objects and diff's their attributes except for the JSON (data) & date fields.
'''
d = DataDiffer(self.old, self.new)
changed = d.changed()
if 'name' in changed:
self.log_item(objectid = self.old['id'], event='update', otype="protocol", data = { "name": self.new['name']} )
if 'id' in changed and 'author_id' not in changed:
self.log_item(objectid = self.old['id'], event = 'clone', otype="protocol", data = { "pk": self.new['id']} )
self.log_item(objectid = self.new['id'], event = 'create', otype="protocol", data = { "pk": self.new['data']} )
if 'user' in changed:
self.log_item(objectid = self.new['id'], event = 'forked', otype="protocol", data = { "author": self.new['author'] })
# self.log_item(objectid = self.new['id'], event = 'update', data = { "author": self.new.author })
if "published" in changed and 'id' not in changed:
self.log_item(objectid = self.old['id'], event = 'update', otype="protocol", data = { "published": self.new['published'] })
if "public" in changed:
self.log_item(objectid = self.old['id'], event = 'update', otype="protocol", data = { "public": self.new['public'] })
if "description" in changed:
self.log_item(objectid = self.old['id'], event = 'update', otype="protocol", data = { "description": self.new['description'] })
# def diff_dict(self, objid=None):
# '''this method takes a dict and finds the differences in it catching the following diffs:
# key-value pairs:
# triggered by a unicode / int / float / str type.
# finds the added, removed, changed key value pairs and creates a log for each change
# list objects:
# triggered by list type. calls the diff_list method
# '''
# if not objid: # if dict is protocol.data:
# obj_old = self.old.data
# obj_new = self.new.data
# # print "diffing data_a and data_b"
# else: # all other dicts in protocol.nodes
# obj_old = self.old.nodes[objid]
# obj_new = self.new.nodes[objid]
# # print "diffing %s, %s "% (obj_old['name'], obj_new['name'])
# diff = DataDiffer(obj_old, obj_new) ## diff the step content
# # print "added: %s, \n deleted: %s, \n update: %s"% (diff.added(), diff.removed(), diff.changed())
# all_keys = set(obj_old.keys()).union(set(obj_new.keys()))
# for key in all_keys:
# if key in diff.changed():
# if isinstance(obj_old[key], list):
# self.diff_list(obj_old[key], obj_new[key])
# # print "unpacking lisf of %s and %s"% (type(obj_old), type(obj_new))
# if isinstance(obj_old[key], (int, float, unicode, str)):
# self.log_item(objectid = objid, event = "update", data = {key: obj_new[key]})
# # print "logged changed %s, %s "% (objid, obj_new[key])
# if key in diff.added():
# self.log_item(objectid = objid, event = "create", data = { key: obj_new[key]} )
# # print "logged add %s, %s "% (objid, obj_new[key])
# if key in diff.removed():
# self.log_item(objectid = objid, event = "delete", data = { key: obj_old[key]} )
# # print "logged remove%s, %s "% (objid, obj_new[key])
def diff_nodes(self):
'''
Diff's nodes that are attached to protocols.
'''
old_ids = self.old_record.nodes.keys()
new_ids = self.new_record.nodes.keys()
for key in old_ids: # UPDATED AN DELETED NODES
if key in new_ids: # CHECK FOR NODE EDIT
# print "\nNODE EDIT: %s" % key
new_node = self.new_record.nodes[key]
node_type = new_node.__class__.__name__.lower()
changes = self.node_changes(self.clean_node_data(self.old_record.nodes[key]), self.clean_node_data(new_node))
for edit_type in ['create', 'update', 'delete']:
if changes[edit_type]:
self.log_item(key, edit_type, node_type, changes[edit_type], parent_id=new_node.parent.id )
new_ids.remove(key)
else:
node = self.old_record.nodes[key]
self.log_item(key, "delete", node.__class__.__name__.lower(), self.clean_node_data(node), parent_id=node.parent.id )
for key in new_ids: # NEW NODES
node = self.new_record.nodes[key]
self.log_item(key, "create", node.__class__.__name__.lower(), self.clean_node_data(node), parent_id=node.parent.id )
def clean_node_data(self, node):
'''
Returns a Node in the cleaned up format for logging
'''
result = {}
for key, item in node.items():
if key not in ['steps', 'actions', 'machine', 'components', 'thermocycler']:
result[key] = node[key]
return result
def node_changes(self, old_node, new_node):
result = { 'create':{}, 'update':{}, 'delete':{} }
differ = DataDiffer(old_node, new_node)
for key in differ.changed():
result['update'][key] = new_node[key]
for key in differ.added():
result['update'][key] = new_node[key]
for key in differ.removed():
result['delete'][key] = new_node[key]
return result
# def diff_list(self, list_a, list_b):
# ''' this method takes a list of object ids and compares it between the old and the new list.
# it will catch a few events:
# 1. turns the list of objects into a dict of objectids for ease of compare
# 2. finds the added removed or edited objects in each list
# 3. for added or removed objects it triggers a log event
# 4. for changed objects it recurses to diff_dict'''
# print "DIFF LIST CALLED"
# old_list = dict((item['objectid'],item) for item in list_a)
# new_list = dict((item['objectid'],item) for item in list_b)
# # find changes between list objects (add, delete update)
# diff_list_items = DataDiffer(old_list, new_list)
# changed = diff_list_items.changed()
# added = diff_list_items.added()
# removed = diff_list_items.removed()
# # print "added: %s, \n deleted: %s, \n update: %s"% (diff_list_items.added(), diff_list_items.removed(), diff_list_items.changed())
# ### Place Holder for finding chaned Order in list ###
# all_objectids = set(old_list.keys()).union(set(new_list.keys()))
# for objid in all_objectids:
# if objid in added:
# self.log_item(objectid = objid, event = 'create', otype="step", data = self.new_record.nodes[objid])
# # print "logged add%s, %s "% (objid, self.new.nodes[objid])
# if objid in removed:
# self.log_item(objectid = objid, event = 'delete', otype="", data = self.old_record.nodes[objid])
# # print "logged remove%s, %s "% (objid, self.old.nodes[objid])
# if objid in changed:
# self.diff_dict(objid) # recursive call.
# # print 'recursing dict %s' %objid
class DataDiffer(object):
def __init__(self, old_data, new_data, **kwargs):
self.old_data, self.new_data = old_data, new_data
self.set_a, self.set_b = set(old_data.keys()), set(new_data.keys())
self.intersect = self.set_a.intersection(self.set_b)
def removed(self):
return list(self.set_a - self.intersect)
def added(self):
return list(self.set_b - self.intersect)
def changed(self, **kwargs):
delta = list(o for o in self.intersect if self.new_data[o] != self.old_data[o])
return delta
def unchanged(self):
return list(o for o in self.intersect if self.new_data[o] == self.old_data[o])
| 39.747059
| 161
| 0.533767
|
853a22ea27c0a541b0479d2fe78f0f5603d47b24
| 1,536
|
cs
|
C#
|
Fenris-Manor/Assets/Scripts/DoorTrigger.cs
|
derrick-j-tubbs/FenrisManor
|
cbb4fa077edfcb76ebff8315f26d6342f4b1b7c4
|
[
"BSD-3-Clause"
] | null | null | null |
Fenris-Manor/Assets/Scripts/DoorTrigger.cs
|
derrick-j-tubbs/FenrisManor
|
cbb4fa077edfcb76ebff8315f26d6342f4b1b7c4
|
[
"BSD-3-Clause"
] | null | null | null |
Fenris-Manor/Assets/Scripts/DoorTrigger.cs
|
derrick-j-tubbs/FenrisManor
|
cbb4fa077edfcb76ebff8315f26d6342f4b1b7c4
|
[
"BSD-3-Clause"
] | null | null | null |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
public class DoorTrigger : MonoBehaviour {
public CinemachineVirtualCamera initialCamera;
public CinemachineVirtualCamera finalCamera;
public GameObject roomSpawnPoint;
protected PlayerController playerController;
protected PlayerPlatformerController platformerController;
public void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag != "Player")
return;
initialCamera.Priority = 0;
finalCamera.Priority = 1;
StartCoroutine(DisableControls());
collision.gameObject.transform.position = roomSpawnPoint.transform.position;
}
IEnumerator DisableControls() {
GameObject player = GameObject.Find("Player");
if ((platformerController = player.GetComponent<PlayerPlatformerController>()) &&
(playerController = player.GetComponent<PlayerController>())) {
Debug.Log("Controls Off");
ToggleControls(false);
playerController.PlayerAnimator.Play("PlayerIdle");
yield return new WaitForSeconds(1);
platformerController.SetPlayerVelocity(new Vector2(platformerController.GetPlayerVelocity().x, 0));
Debug.Log("Controls On");
ToggleControls(true);
}
}
void ToggleControls(bool state) {
platformerController.enabled = state;
playerController.setIsClimbing(!state);
}
}
| 32.680851
| 111
| 0.684245
|
1bda362d67e0b2a7783a14abe0b7f90cba630b38
| 7,756
|
swift
|
Swift
|
RiotSwiftUI/Modules/Onboarding/SplashScreen/View/OnboardingSplashScreen.swift
|
RamyRizkalla/element-ios
|
1122095229b11b89e10c6bff5aaa66ed274b6197
|
[
"Apache-2.0"
] | null | null | null |
RiotSwiftUI/Modules/Onboarding/SplashScreen/View/OnboardingSplashScreen.swift
|
RamyRizkalla/element-ios
|
1122095229b11b89e10c6bff5aaa66ed274b6197
|
[
"Apache-2.0"
] | null | null | null |
RiotSwiftUI/Modules/Onboarding/SplashScreen/View/OnboardingSplashScreen.swift
|
RamyRizkalla/element-ios
|
1122095229b11b89e10c6bff5aaa66ed274b6197
|
[
"Apache-2.0"
] | null | null | null |
//
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import SwiftUI
@available(iOS 14.0, *)
/// The splash screen shown at the beginning of the onboarding flow.
struct OnboardingSplashScreen: View {
// MARK: - Properties
// MARK: Private
@Environment(\.theme) private var theme
@Environment(\.layoutDirection) private var layoutDirection
private var isLeftToRight: Bool { layoutDirection == .leftToRight }
private var pageCount: Int { viewModel.viewState.content.count }
/// The dimensions of the stack with the action buttons and page indicator.
@State private var overlayFrame: CGRect = .zero
/// A timer to automatically animate the pages.
@State private var pageTimer: Timer?
/// The amount of offset to apply when a drag gesture is in progress.
@State private var dragOffset: CGFloat = .zero
// MARK: Public
@ObservedObject var viewModel: OnboardingSplashScreenViewModel.Context
/// The main action buttons.
var buttons: some View {
VStack(spacing: 12) {
Button { viewModel.send(viewAction: .register) } label: {
Text(VectorL10n.onboardingSplashRegisterButtonTitle)
}
.buttonStyle(PrimaryActionButtonStyle())
Button { viewModel.send(viewAction: .login) } label: {
Text(VectorL10n.onboardingSplashLoginButtonTitle)
.font(theme.fonts.body)
.padding(12)
}
}
}
/// The only part of the UI that isn't inside of the carousel.
var overlay: some View {
VStack(spacing: 50) {
Color.clear
Color.clear
VStack {
OnboardingSplashScreenPageIndicator(pageCount: pageCount,
pageIndex: viewModel.pageIndex)
Spacer()
buttons
.padding(.horizontal, 16)
.frame(maxWidth: OnboardingConstants.maxContentWidth)
Spacer()
}
.background(ViewFrameReader(frame: $overlayFrame))
}
}
var body: some View {
GeometryReader { geometry in
ZStack(alignment: .leading) {
// The main content of the carousel
HStack(spacing: 0) {
// Add a hidden page at the start of the carousel duplicating the content of the last page
OnboardingSplashScreenPage(content: viewModel.viewState.content[pageCount - 1],
overlayHeight: overlayFrame.height + geometry.safeAreaInsets.bottom)
.frame(width: geometry.size.width)
.tag(-1)
ForEach(0..<pageCount) { index in
OnboardingSplashScreenPage(content: viewModel.viewState.content[index],
overlayHeight: overlayFrame.height + geometry.safeAreaInsets.bottom)
.frame(width: geometry.size.width)
.tag(index)
}
}
.offset(x: (CGFloat(viewModel.pageIndex + 1) * -geometry.size.width) + dragOffset)
.gesture(
DragGesture()
.onChanged(handleDragGestureChange)
.onEnded { handleDragGestureEnded($0, viewSize: geometry.size) }
)
overlay
.frame(width: geometry.size.width)
}
}
.background(theme.colors.background.ignoresSafeArea())
.accentColor(theme.colors.accent)
.navigationBarHidden(true)
.onAppear {
startTimer()
}
.onDisappear { stopTimer() }
.track(screen: .welcome)
}
// MARK: - Animation
/// Starts the animation timer for an automatic carousel effect.
private func startTimer() {
guard pageTimer == nil else { return }
pageTimer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { timer in
if viewModel.pageIndex == pageCount - 1 {
viewModel.send(viewAction: .hiddenPage)
withAnimation(.easeInOut(duration: 0.7)) {
viewModel.send(viewAction: .nextPage)
}
} else {
withAnimation(.easeInOut(duration: 0.7)) {
viewModel.send(viewAction: .nextPage)
}
}
}
}
/// Stops the animation timer for manual interaction.
private func stopTimer() {
guard let pageTimer = pageTimer else { return }
self.pageTimer = nil
pageTimer.invalidate()
}
// MARK: - Gestures
/// Whether or not a drag gesture is valid or not.
/// - Parameter width: The gesture's translation width.
/// - Returns: `true` if there is another page to drag to.
private func shouldSwipeForTranslation(_ width: CGFloat) -> Bool {
if viewModel.pageIndex == 0 {
return isLeftToRight ? width < 0 : width > 0
} else if viewModel.pageIndex == pageCount - 1 {
return isLeftToRight ? width > 0 : width < 0
}
return true
}
/// Updates the `dragOffset` based on the gesture's value.
/// - Parameter drag: The drag gesture value to handle.
private func handleDragGestureChange(_ drag: DragGesture.Value) {
guard shouldSwipeForTranslation(drag.translation.width) else { return }
stopTimer()
// Animate the change over a few frames to smooth out any stuttering.
withAnimation(.linear(duration: 0.05)) {
dragOffset = isLeftToRight ? drag.translation.width : -drag.translation.width
}
}
/// Clears the drag offset and informs the view model to switch to another page if necessary.
/// - Parameter viewSize: The size of the view in which the gesture took place.
private func handleDragGestureEnded(_ drag: DragGesture.Value, viewSize: CGSize) {
guard shouldSwipeForTranslation(drag.predictedEndTranslation.width) else {
// Reset the offset just in case.
withAnimation { dragOffset = 0 }
return
}
withAnimation(.easeInOut(duration: 0.2)) {
if drag.predictedEndTranslation.width < -viewSize.width / 2 {
viewModel.send(viewAction: .nextPage)
} else if drag.predictedEndTranslation.width > viewSize.width / 2 {
viewModel.send(viewAction: .previousPage)
}
dragOffset = 0
}
}
}
// MARK: - Previews
@available(iOS 14.0, *)
struct OnboardingSplashScreen_Previews: PreviewProvider {
static let stateRenderer = MockOnboardingSplashScreenScreenState.stateRenderer
static var previews: some View {
stateRenderer.screenGroup()
}
}
| 37.110048
| 119
| 0.572718
|
c69d290d1913e97e1f3e487cae515d8c35221dcc
| 12,586
|
rs
|
Rust
|
helix-view/src/handlers/dap.rs
|
typerslow/helix
|
8eb15f52835c3669a5d5f0539a13f415a8a71856
|
[
"MIT"
] | null | null | null |
helix-view/src/handlers/dap.rs
|
typerslow/helix
|
8eb15f52835c3669a5d5f0539a13f415a8a71856
|
[
"MIT"
] | null | null | null |
helix-view/src/handlers/dap.rs
|
typerslow/helix
|
8eb15f52835c3669a5d5f0539a13f415a8a71856
|
[
"MIT"
] | null | null | null |
use crate::editor::{Action, Breakpoint};
use crate::{align_view, Align, Editor};
use helix_core::Selection;
use helix_dap::{self as dap, Client, Payload, Request, ThreadId};
use helix_lsp::block_on;
use log::warn;
use std::path::PathBuf;
#[macro_export]
macro_rules! debugger {
($editor:expr) => {{
match &mut $editor.debugger {
Some(debugger) => debugger,
None => return,
}
}};
}
// general utils:
pub fn dap_pos_to_pos(doc: &helix_core::Rope, line: usize, column: usize) -> Option<usize> {
// 1-indexing to 0 indexing
let line = doc.try_line_to_char(line - 1).ok()?;
let pos = line + column.saturating_sub(1);
// TODO: this is probably utf-16 offsets
Some(pos)
}
pub async fn select_thread_id(editor: &mut Editor, thread_id: ThreadId, force: bool) {
let debugger = debugger!(editor);
if !force && debugger.thread_id.is_some() {
return;
}
debugger.thread_id = Some(thread_id);
fetch_stack_trace(debugger, thread_id).await;
let frame = debugger.stack_frames[&thread_id].get(0).cloned();
if let Some(frame) = &frame {
jump_to_stack_frame(editor, frame);
}
}
pub async fn fetch_stack_trace(debugger: &mut Client, thread_id: ThreadId) {
let (frames, _) = match debugger.stack_trace(thread_id).await {
Ok(frames) => frames,
Err(_) => return,
};
debugger.stack_frames.insert(thread_id, frames);
debugger.active_frame = Some(0);
}
pub fn jump_to_stack_frame(editor: &mut Editor, frame: &helix_dap::StackFrame) {
let path = if let Some(helix_dap::Source {
path: Some(ref path),
..
}) = frame.source
{
path.clone()
} else {
return;
};
if let Err(e) = editor.open(path, Action::Replace) {
editor.set_error(format!("Unable to jump to stack frame: {}", e));
return;
}
let (view, doc) = current!(editor);
let text_end = doc.text().len_chars().saturating_sub(1);
let start = dap_pos_to_pos(doc.text(), frame.line, frame.column).unwrap_or(0);
let end = frame
.end_line
.and_then(|end_line| dap_pos_to_pos(doc.text(), end_line, frame.end_column.unwrap_or(0)))
.unwrap_or(start);
let selection = Selection::single(start.min(text_end), end.min(text_end));
doc.set_selection(view.id, selection);
align_view(doc, view, Align::Center);
}
pub fn breakpoints_changed(
debugger: &mut dap::Client,
path: PathBuf,
breakpoints: &mut [Breakpoint],
) -> Result<(), anyhow::Error> {
// TODO: handle capabilities correctly again, by filterin breakpoints when emitting
// if breakpoint.condition.is_some()
// && !debugger
// .caps
// .as_ref()
// .unwrap()
// .supports_conditional_breakpoints
// .unwrap_or_default()
// {
// bail!(
// "Can't edit breakpoint: debugger does not support conditional breakpoints"
// )
// }
// if breakpoint.log_message.is_some()
// && !debugger
// .caps
// .as_ref()
// .unwrap()
// .supports_log_points
// .unwrap_or_default()
// {
// bail!("Can't edit breakpoint: debugger does not support logpoints")
// }
let source_breakpoints = breakpoints
.iter()
.map(|breakpoint| helix_dap::SourceBreakpoint {
line: breakpoint.line + 1, // convert from 0-indexing to 1-indexing (TODO: could set debugger to 0-indexing on init)
..Default::default()
})
.collect::<Vec<_>>();
let request = debugger.set_breakpoints(path, source_breakpoints);
match block_on(request) {
Ok(Some(dap_breakpoints)) => {
for (breakpoint, dap_breakpoint) in breakpoints.iter_mut().zip(dap_breakpoints) {
breakpoint.id = dap_breakpoint.id;
breakpoint.verified = dap_breakpoint.verified;
breakpoint.message = dap_breakpoint.message;
// TODO: handle breakpoint.message
// TODO: verify source matches
breakpoint.line = dap_breakpoint.line.unwrap_or(0).saturating_sub(1); // convert to 0-indexing
// TODO: no unwrap
breakpoint.column = dap_breakpoint.column;
// TODO: verify end_linef/col instruction reference, offset
}
}
Err(e) => anyhow::bail!("Failed to set breakpoints: {}", e),
_ => {}
};
Ok(())
}
impl Editor {
pub async fn handle_debugger_message(&mut self, payload: helix_dap::Payload) -> bool {
use dap::requests::RunInTerminal;
use helix_dap::{events, Event};
let debugger = match self.debugger.as_mut() {
Some(debugger) => debugger,
None => return false,
};
match payload {
Payload::Event(ev) => match *ev {
Event::Stopped(events::Stopped {
thread_id,
description,
text,
reason,
all_threads_stopped,
..
}) => {
let all_threads_stopped = all_threads_stopped.unwrap_or_default();
if all_threads_stopped {
if let Ok(response) = debugger.request::<dap::requests::Threads>(()).await {
for thread in response.threads {
fetch_stack_trace(debugger, thread.id).await;
}
select_thread_id(self, thread_id.unwrap_or_default(), false).await;
}
} else if let Some(thread_id) = thread_id {
debugger.thread_states.insert(thread_id, reason.clone()); // TODO: dap uses "type" || "reason" here
// whichever thread stops is made "current" (if no previously selected thread).
select_thread_id(self, thread_id, false).await;
}
let scope = match thread_id {
Some(id) => format!("Thread {}", id),
None => "Target".to_owned(),
};
let mut status = format!("{} stopped because of {}", scope, reason);
if let Some(desc) = description {
status.push_str(&format!(" {}", desc));
}
if let Some(text) = text {
status.push_str(&format!(" {}", text));
}
if all_threads_stopped {
status.push_str(" (all threads stopped)");
}
self.set_status(status);
}
Event::Continued(events::Continued { thread_id, .. }) => {
debugger
.thread_states
.insert(thread_id, "running".to_owned());
if debugger.thread_id == Some(thread_id) {
debugger.resume_application();
}
}
Event::Thread(_) => {
// TODO: update thread_states, make threads request
}
Event::Breakpoint(events::Breakpoint { reason, breakpoint }) => {
match &reason[..] {
"new" => {
if let Some(source) = breakpoint.source {
self.breakpoints
.entry(source.path.unwrap()) // TODO: no unwraps
.or_default()
.push(Breakpoint {
id: breakpoint.id,
verified: breakpoint.verified,
message: breakpoint.message,
line: breakpoint.line.unwrap().saturating_sub(1), // TODO: no unwrap
column: breakpoint.column,
..Default::default()
});
}
}
"changed" => {
for breakpoints in self.breakpoints.values_mut() {
if let Some(i) =
breakpoints.iter().position(|b| b.id == breakpoint.id)
{
breakpoints[i].verified = breakpoint.verified;
breakpoints[i].message = breakpoint.message.clone();
breakpoints[i].line =
breakpoint.line.unwrap().saturating_sub(1); // TODO: no unwrap
breakpoints[i].column = breakpoint.column;
}
}
}
"removed" => {
for breakpoints in self.breakpoints.values_mut() {
if let Some(i) =
breakpoints.iter().position(|b| b.id == breakpoint.id)
{
breakpoints.remove(i);
}
}
}
reason => {
warn!("Unknown breakpoint event: {}", reason);
}
}
}
Event::Output(events::Output {
category, output, ..
}) => {
let prefix = match category {
Some(category) => {
if &category == "telemetry" {
return false;
}
format!("Debug ({}):", category)
}
None => "Debug:".to_owned(),
};
log::info!("{}", output);
self.set_status(format!("{} {}", prefix, output));
}
Event::Initialized => {
// send existing breakpoints
for (path, breakpoints) in &mut self.breakpoints {
// TODO: call futures in parallel, await all
let _ = breakpoints_changed(debugger, path.clone(), breakpoints);
}
// TODO: fetch breakpoints (in case we're attaching)
if debugger.configuration_done().await.is_ok() {
self.set_status("Debugged application started");
}; // TODO: do we need to handle error?
}
ev => {
log::warn!("Unhandled event {:?}", ev);
return false; // return early to skip render
}
},
Payload::Response(_) => unreachable!(),
Payload::Request(request) => match request.command.as_str() {
RunInTerminal::COMMAND => {
let arguments: dap::requests::RunInTerminalArguments =
serde_json::from_value(request.arguments.unwrap_or_default()).unwrap();
// TODO: no unwrap
let process = std::process::Command::new("tmux")
.arg("split-window")
.arg(arguments.args.join(" "))
.spawn()
.unwrap();
let _ = debugger
.reply(
request.seq,
dap::requests::RunInTerminal::COMMAND,
serde_json::to_value(dap::requests::RunInTerminalResponse {
process_id: Some(process.id()),
shell_process_id: None,
})
.map_err(|e| e.into()),
)
.await;
}
_ => log::error!("DAP reverse request not implemented: {:?}", request),
},
}
true
}
}
| 40.339744
| 128
| 0.456142
|
1a86d7e913c7bb033724341bcf41b0452442d37f
| 172
|
py
|
Python
|
baekjoon/4153/right_triangle.py
|
ucyang/AlgoEx
|
465c88f04b9449c06ee5c9a684ded5aba8ccf399
|
[
"MIT"
] | null | null | null |
baekjoon/4153/right_triangle.py
|
ucyang/AlgoEx
|
465c88f04b9449c06ee5c9a684ded5aba8ccf399
|
[
"MIT"
] | null | null | null |
baekjoon/4153/right_triangle.py
|
ucyang/AlgoEx
|
465c88f04b9449c06ee5c9a684ded5aba8ccf399
|
[
"MIT"
] | null | null | null |
while True:
a, b, c = sorted(map(int, input().split()))
if a == 0 and b == 0 and c == 0:
break
print("right" if a ** 2 + b ** 2 == c ** 2 else "wrong")
| 28.666667
| 60
| 0.465116
|
dae009a693954cd42f94f1228e6ad5e0a7bddbad
| 2,576
|
dart
|
Dart
|
lib/SettingsPage.dart
|
Dooomino/UOIT_GO
|
ad3f49a38537dd901329eaecd685d2bf3402c807
|
[
"Apache-2.0"
] | null | null | null |
lib/SettingsPage.dart
|
Dooomino/UOIT_GO
|
ad3f49a38537dd901329eaecd685d2bf3402c807
|
[
"Apache-2.0"
] | null | null | null |
lib/SettingsPage.dart
|
Dooomino/UOIT_GO
|
ad3f49a38537dd901329eaecd685d2bf3402c807
|
[
"Apache-2.0"
] | null | null | null |
import 'package:flutter/material.dart';
import 'package:flutter_i18n/flutter_i18n.dart';
import 'package:shared_preferences/shared_preferences.dart';
class SettingsPage extends StatefulWidget{
final String title;
BuildContext context;
SettingsPage({Key key,this.title,this.context}) : super(key:key);
@override
SettingsPageState createState() => SettingsPageState(context);
}
class SettingsPageState extends State<SettingsPage>{
@override
BuildContext context;
int lanValue = 0;
Locale newLocale;
SettingsPageState(BuildContext context){
this.context=context;
if(!mounted){
SharedPreferences.setMockInitialValues({"languageNum":0});
}else{
_setInt("languageNum", 0);
}
}
Future<int> _getInt(String key) async{
final SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getInt(key);
}
_setInt(String key,int n) async{
final SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setInt(key, n);
}
@override
Widget build(BuildContext context) {
_getInt("languageNum").then((val){
lanValue = val;
});
return Scaffold(
body: ListView(
children: <Widget>[
Card(
child: Row(
children: <Widget>[
Text("Language"),
Padding(padding: EdgeInsets.symmetric(horizontal: 10.0)),
DropdownButton(
value: lanValue,
onChanged: (value){
if(value == 1)
newLocale = Locale('zh');
else
newLocale = Locale('en');
setState(() {
_setInt("languageNum", value);
_getInt("languageNum").then((val){
lanValue = val;
});
_getInt("languageNum").then((val){
print(val);
});
FlutterI18n.refresh(context, newLocale);
});
},
items: <DropdownMenuItem>[
DropdownMenuItem(
child: Text("English"),
value: 0,
),
DropdownMenuItem(
child: Text("Chinese"),
value: 1,
)
],
)
],
)
)
],
),
);
}
}
| 28.622222
| 74
| 0.492624
|
43a4c3cbf2dffc211f1f8f2717fba5b77fc51ddf
| 1,344
|
tsx
|
TypeScript
|
components/layout.tsx
|
Garee/thedeetees.co.uk
|
093e1fb232fed0c5562627a23604564682d37f5e
|
[
"MIT"
] | null | null | null |
components/layout.tsx
|
Garee/thedeetees.co.uk
|
093e1fb232fed0c5562627a23604564682d37f5e
|
[
"MIT"
] | 5
|
2021-08-13T03:31:11.000Z
|
2022-02-17T22:05:51.000Z
|
components/layout.tsx
|
Garee/thedeetees.co.uk
|
093e1fb232fed0c5562627a23604564682d37f5e
|
[
"MIT"
] | null | null | null |
import Head from "next/head";
import Nav from "./nav";
import Footer from "./footer";
import {
appAuthor,
appDescription,
appName,
appSite,
appIcon,
} from "../lib/config";
import styles from "./layout.module.scss";
interface LayoutProps {
children: JSX.Element[] | JSX.Element;
}
export default function Layout({ children }: LayoutProps) {
return (
<div className={styles.container}>
<Head>
<title>{appName}</title>
<meta name="description" content={appDescription} />
<meta property="og:image" content={appIcon} />
<meta name="og:title" content={appName} />
<meta property="og:description" content={appDescription} />
<meta name="twitter:card" content="summary" />
<meta name="twitter:site" content={appSite} />
<meta name="twitter:creator" content={appAuthor} />
<meta name="twitter:title" content={appName} />
<meta name="twitter:description" content={appDescription} />
<meta name="twitter:image" content={appIcon} />
<meta name="theme-color" content="#ec1b24" />
<link rel="manifest" href="/site.webmanifest" />
<link rel="icon" href="/favicon.ico" />
<link rel="apple-touch-icon" href={appIcon} />
</Head>
<Nav />
<main>{children}</main>
<Footer />
</div>
);
}
| 31.255814
| 68
| 0.613095
|
6d12f0974ea660f6f225a010341cf02698054bdf
| 1,445
|
tsx
|
TypeScript
|
studio/components/interfaces/Authentication/Users/UsersPagination.tsx
|
ProPiloty/supabase
|
93d0dbf2c55596ef388cc2452da74b7a67ca811b
|
[
"Apache-2.0"
] | 2
|
2021-08-02T14:43:52.000Z
|
2021-10-17T04:17:25.000Z
|
studio/components/interfaces/Authentication/Users/UsersPagination.tsx
|
ProPiloty/supabase
|
93d0dbf2c55596ef388cc2452da74b7a67ca811b
|
[
"Apache-2.0"
] | 8
|
2022-02-28T03:37:34.000Z
|
2022-02-28T03:38:19.000Z
|
studio/components/interfaces/Authentication/Users/UsersPagination.tsx
|
ProPiloty/supabase
|
93d0dbf2c55596ef388cc2452da74b7a67ca811b
|
[
"Apache-2.0"
] | 1
|
2022-01-20T16:17:00.000Z
|
2022-01-20T16:17:00.000Z
|
import { useContext } from 'react'
import { observer } from 'mobx-react-lite'
import { Button } from '@supabase/ui'
import { PageContext } from 'pages/project/[ref]/auth/users'
const UsersPagination = () => {
const PageState: any = useContext(PageContext)
function onNext() {
PageState.fetchData(PageState.page + 1)
}
function onPrevious() {
PageState.fetchData(PageState.page - 1)
}
return (
<nav className="flex items-center justify-between overflow-hidden" aria-label="Pagination">
<div className="hidden sm:block">
<p className="text-xs text-gray-400">
Showing
<span className="px-1 font-medium text-gray-400">{PageState.fromRow}</span>
to
<span className="px-1 font-medium text-gray-400">{PageState.toRow}</span>
of
<span className="px-1 font-medium text-gray-400">{PageState.totalUsers}</span>
results
</p>
</div>
<div className="flex-1 flex justify-between sm:justify-end">
{PageState.hasPrevious && (
<Button type="secondary" disabled={!PageState.hasPrevious} onClick={onPrevious}>
Previous
</Button>
)}
{PageState.hasNext && (
<Button type="secondary" disabled={!PageState.hasNext} className="ml-3" onClick={onNext}>
Next
</Button>
)}
</div>
</nav>
)
}
export default observer(UsersPagination)
| 30.104167
| 99
| 0.614533
|
f43922180ea1eef1b047f1702dec97e8674906e5
| 420
|
css
|
CSS
|
src/main/resources/static/css/register.css
|
oracle-quickstart/oci-caas-pci-ecommerce
|
831337bb5307302190a0423a692604c72ea2e449
|
[
"UPL-1.0"
] | null | null | null |
src/main/resources/static/css/register.css
|
oracle-quickstart/oci-caas-pci-ecommerce
|
831337bb5307302190a0423a692604c72ea2e449
|
[
"UPL-1.0"
] | null | null | null |
src/main/resources/static/css/register.css
|
oracle-quickstart/oci-caas-pci-ecommerce
|
831337bb5307302190a0423a692604c72ea2e449
|
[
"UPL-1.0"
] | 2
|
2021-05-08T01:31:55.000Z
|
2021-06-13T06:26:58.000Z
|
body {
display: -ms-flexbox;
display: flex;
-ms-flex-align: center;
align-items: center;
padding-top: 40px;
padding-bottom: 40px;
background-color: #f5f5f5;
}
.signup-form{
width: 390px;
margin: 30px auto;
}
.signup-form form{
color: #999;
border-radius: 3px;
margin-bottom: 15px;
background: #fff;
box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
padding: 30px;
}
| 19.090909
| 47
| 0.604762
|
dd749a5f408ebdae83b74fe870b5624abce5b419
| 2,163
|
java
|
Java
|
financeBank/src/java/org/finance/bank/bean/TCargosAdmin.java
|
jfhflores11/FinanceBank
|
42dbee0490f88c4015f4deab269aa23d73c66df1
|
[
"Apache-2.0"
] | null | null | null |
financeBank/src/java/org/finance/bank/bean/TCargosAdmin.java
|
jfhflores11/FinanceBank
|
42dbee0490f88c4015f4deab269aa23d73c66df1
|
[
"Apache-2.0"
] | null | null | null |
financeBank/src/java/org/finance/bank/bean/TCargosAdmin.java
|
jfhflores11/FinanceBank
|
42dbee0490f88c4015f4deab269aa23d73c66df1
|
[
"Apache-2.0"
] | null | null | null |
package org.finance.bank.bean;
// Generated 07/01/2014 06:22:58 PM by Hibernate Tools 3.2.1.GA
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* TCargosAdmin generated by hbm2java
*/
@Entity
@Table(name="t_cargos_admin"
,schema="public"
)
public class TCargosAdmin implements java.io.Serializable {
private String idcargoadmin;
private String denominacion;
private String tipo;
private Set TCargosPrestamos = new HashSet(0);
public TCargosAdmin() {
}
public TCargosAdmin(String idcargoadmin, String denominacion) {
this.idcargoadmin = idcargoadmin;
this.denominacion = denominacion;
}
public TCargosAdmin(String idcargoadmin, String denominacion, String tipo, Set TCargosPrestamos) {
this.idcargoadmin = idcargoadmin;
this.denominacion = denominacion;
this.tipo = tipo;
this.TCargosPrestamos = TCargosPrestamos;
}
@Id
@Column(name="idcargoadmin", unique=true, nullable=false, length=41)
public String getIdcargoadmin() {
return this.idcargoadmin;
}
public void setIdcargoadmin(String idcargoadmin) {
this.idcargoadmin = idcargoadmin;
}
@Column(name="denominacion", nullable=false, length=200)
public String getDenominacion() {
return this.denominacion;
}
public void setDenominacion(String denominacion) {
this.denominacion = denominacion;
}
@Column(name="tipo", length=50)
public String getTipo() {
return this.tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="TCargosAdmin")
public Set getTCargosPrestamos() {
return this.TCargosPrestamos;
}
public void setTCargosPrestamos(Set TCargosPrestamos) {
this.TCargosPrestamos = TCargosPrestamos;
}
}
| 24.579545
| 102
| 0.689783
|
a38f9d415c3797e46290995baa982fc41107b810
| 1,907
|
java
|
Java
|
ada-vcs/src/main/java/ada/domain/dvc/protocol/serializers/RepositoryMessageSerializer.java
|
cokeSchlumpf/ada
|
a4f091cc00eab66211ee0830e4c2ae50574facca
|
[
"Apache-2.0"
] | 1
|
2019-06-17T09:01:11.000Z
|
2019-06-17T09:01:11.000Z
|
ada-vcs/src/main/java/ada/domain/dvc/protocol/serializers/RepositoryMessageSerializer.java
|
cokeSchlumpf/ada
|
a4f091cc00eab66211ee0830e4c2ae50574facca
|
[
"Apache-2.0"
] | null | null | null |
ada-vcs/src/main/java/ada/domain/dvc/protocol/serializers/RepositoryMessageSerializer.java
|
cokeSchlumpf/ada
|
a4f091cc00eab66211ee0830e4c2ae50574facca
|
[
"Apache-2.0"
] | null | null | null |
package ada.domain.dvc.protocol.serializers;
import ada.commons.databind.MessageSerializer;
import ada.domain.dvc.protocol.commands.*;
import ada.domain.dvc.protocol.events.*;
import ada.domain.dvc.protocol.queries.*;
import ada.domain.dvc.values.repository.RepositorySummary;
import akka.actor.ExtendedActorSystem;
import com.google.common.collect.Maps;
import java.util.Map;
public final class RepositoryMessageSerializer extends MessageSerializer {
public RepositoryMessageSerializer(ExtendedActorSystem actorSystem) {
super(actorSystem, 2403 + 1);
}
@Override
protected Map<String, Class<?>> getManifestToClass() {
Map<String, Class<?>> m = Maps.newHashMap();
m.put("requests/details/v1", RepositoryDetailsRequest.class);
m.put("responses/details/v1", RepositoryDetailsResponse.class);
m.put("requests/summary/v1", RepositorySummaryRequest.class);
m.put("responses/summary/v1", RepositorySummaryResponse.class);
m.put("commands/create/v1", CreateRepository.class);
m.put("commands/grant/v1", GrantAccessToRepository.class);
m.put("commands/pull/v1", Pull.class);
m.put("commands/push/v1", Push.class);
m.put("commands/remove/v1", RemoveRepository.class);
m.put("commands/summary/v1", RepositorySummary.class);
m.put("commands/revoke/v1", RevokedAccessFromRepository.class);
m.put("commands/submit/v1", SubmitPushInRepository.class);
m.put("events/created/v1", RepositoryCreated.class);
m.put("events/granted/v1", GrantedAccessToRepository.class);
m.put("events/removed/v1", RepositoryRemoved.class);
m.put("events/revoked/v1", RevokedAccessFromRepository.class);
m.put("events/upserted/v1", VersionUpsertedInRepository.class);
m.put("events/submitted/v1", SubmittedPushInRepository.class);
return m;
}
}
| 38.918367
| 74
| 0.714211
|
dbf0f33b6c1542632303a818420ad901ec20b1ce
| 7,587
|
php
|
PHP
|
arms/src/applications/registry/maintenance/controllers/nlaPullback.php
|
au-research/ANDS-Online-Services
|
e0812ca1e8d0cf54d5fe79ae4284b381ea02aba9
|
[
"Apache-2.0"
] | 1
|
2019-01-26T09:32:35.000Z
|
2019-01-26T09:32:35.000Z
|
arms/src/applications/registry/maintenance/controllers/nlaPullback.php
|
au-research/ANDS-Online-Services
|
e0812ca1e8d0cf54d5fe79ae4284b381ea02aba9
|
[
"Apache-2.0"
] | null | null | null |
arms/src/applications/registry/maintenance/controllers/nlaPullback.php
|
au-research/ANDS-Online-Services
|
e0812ca1e8d0cf54d5fe79ae4284b381ea02aba9
|
[
"Apache-2.0"
] | null | null | null |
<?php
class nlaPullback extends MX_Controller
{
private $input; // pointer to the shell input
private $start_time; // time script run (microtime float)
private $exec_time; // time execution started
private $_CI; // an internal reference to the CodeIgniter Engine
private $source;
private $nlaPartyPrefix; // all NLA party record identifiers start with this?
private $nlaPartyDataSourceKey; // what data source do we put them into?
private $nlaServiceURI;
private $dataSource = null; // pointer to target DS. leave as null
private $mode = '';
function index()
{
$pullback_queue = array();
/* Get a list of records which are related to NLA identifiers */
echo "Fetching all records which are related to NLA identifiers or have an NLA party identifier..." .NL;
$this->db->select("registry_object_id, related_object_key")->like("related_object_key", $this->nlaPartyPrefix, 'after')->from("registry_object_relationships");
$query = $this->db->get();
if (!$query->num_rows())
{
echo "Found no matching records...aborting." .NL;
return;
}
/* Check that they are parties and queue up the list of NLA identifiers */
foreach ($query->result_array() AS $result)
{
$this->load->model('registry_object/registry_objects', 'ro');
$ro = $this->ro->getByID($result['registry_object_id']);
if ($ro) // no class checking!
{
$pullback_queue[$result['related_object_key']] = $result['related_object_key'];
}
}
/* Get a list of records with NLA identifiers, excluding those already from our Party DS */
$this->load->library('solr');
$this->solr->setOpt('q', 'identifier_value:"'.$this->nlaPartyPrefix.'*" -data_source_id:'.$this->dataSource->id);
$this->solr->setOpt('fl','identifier_value');
$this->solr->setOpt('rows',1000);
$this->solr->executeSearch();
if ($this->solr->getNumFound() > 0)
{
$result = $this->solr->getResult();
foreach($result->docs AS $doc)
{
foreach($doc->identifier_value AS $identifier)
{
if (strpos($identifier, $this->nlaPartyPrefix) === 0)
{
$pullback_queue[$identifier] = $identifier;
}
}
}
}
echo "Queued " . count($pullback_queue) . " record(s) for pullback from NLA" . NL;
$xml_fragments = $this->extractRIFCSfromQueue($pullback_queue);
if ($xml_fragments)
{
echo "Retrieved " . count($xml_fragments) . " XML record fragment(s)..." . NL;
$this->importer->setXML($xml_fragments);
$this->importer->setDatasource($this->dataSource);
$this->importer->forcePublish();
$this->importer->commit();
if ($this->importer->getErrors())
{
echo $this->importer->getErrors();
}
echo $this->importer->getMessages();
}
else
{
echo "No Registry Object XML to import. Exiting..." . NL;
return;
}
}
function extractRIFCSfromQueue($pullback_queue)
{
$xml_fragments = array();
if (is_array($pullback_queue))
{
foreach ($pullback_queue AS $identifier)
{
$fragment = $this->pullbackRIFCSfromNLA(trim($identifier));
if ($fragment)
{
$xml_fragments[] = $this->pullbackRIFCSfromNLA(trim($identifier));
}
}
}
return $xml_fragments;
}
function pullbackRIFCSfromNLA($identifier)
{
$target_uri = $this->nlaServiceURI . "?query=rec.identifier=%22" . $identifier . "%22&version=1.1&operation=searchRetrieve&recordSchema=http%3A%2F%2Fands.org.au%2Fstandards%2Frif-cs%2FregistryObjects";
$response = curl_file_get_contents($target_uri);
if ($response)
{
try
{
$sxml = @simplexml_load_string($response);
if (!$sxml) { throw new Exception("No valid data! " . $target_uri); }
$sxml->registerXPathNamespace("srw", "http://www.loc.gov/zing/srw/");
$count = $sxml->xpath("//srw:searchRetrieveResponse/srw:numberOfRecords");
if (is_array($count))
{
// Get the matching element
$count = array_pop($count);
$count = (int) $count;
}
if ($count)
{
$data = $sxml->xpath("//srw:recordData");
if (is_array($data))
{
// Get the matching element
$data = array_pop($data);
if ($data->registryObjects)
{
return $data->registryObjects->asXML();
}
else
{
echo "No registryObjects elements discovered inside SRW response: " . $identifier . NL;
}
}
}
else
{
echo "No matches from NLA SRU service on retrieving records for: " . $identifier . NL;
}
}
catch (Exception $e)
{
echo "Unable to load XML from NLA endpoint for ".$identifier.". Response: " . $e->getMessage() . NL;
}
}
ob_flush();flush();
return;
}
function __construct()
{
parent::__construct();
ob_start();
$this->input = fopen ("php://stdin","r");
$this->start_time = microtime(true);
$this->_CI =& get_instance();
set_error_handler(array($this, 'cli_error_handler'));
set_exception_handler(array($this, 'cli_exception_handler'));
define('IS_CLI_SCRIPT', true);
/* Load config */
$this->load->config('nla_pullback');
parse_str(substr(strrchr($_SERVER['REQUEST_URI'], "?"), 1), $_GET);
if(isset($_GET['mode']))
{
$this->mode=$_GET['mode'];
}
$this->nlaPartyPrefix = $this->config->item('nlaPartyPrefix');
$this->nlaPartyDataSourceKey = $this->config->item('nlaPartyDataSourceKey'.$this->mode);
$this->nlaServiceURI = $this->config->item('nlaServiceURI'.$this->mode);
if (!$this->nlaPartyDataSourceKey)
{
echo "Not configured for NLA pullback - check your config options. Aborting..." .NL;
return;
}
/* Check the target datasource */
$this->_CI->load->model('data_source/data_sources', 'ds');
$this->dataSource = $this->_CI->ds->getByKey($this->nlaPartyDataSourceKey);
if (!$this->dataSource)
{
$this->dataSource = $this->ds->create($this->nlaPartyDataSourceKey, $this->config->item('nlaPartyDataSourceDefaultTitle'.$this->mode));
$this->dataSource->setAttribute('title', $this->config->item('nlaPartyDataSourceDefaultTitle'.$this->mode));
$this->dataSource->setAttribute('record_owner', 'SYSTEM');
$this->dataSource->save();
$this->dataSource->updateStats();
echo "ERROR: Unable to match key for target NLA Pullback data source. Creating a new one..." .NL;
}
}
function __destruct()
{
print NL . NL . "Execution finished! Took " . sprintf ("%.3f", (float) (microtime(true) - $this->start_time)) . "s" . NL;
$this->dataSource->append_log("Performing pullback of ".$this->mode." NLA records..." . NL . ob_get_contents());
ob_end_flush();
}
private function getInput()
{
if (is_resource(($this->input)))
{
return trim(fgets($this->input));
}
}
function cli_error_handler($number, $message, $file, $line, $vars)
{
if ($number == E_STRICT) { return true; }
echo NL.NL.str_repeat("=", 15);
echo NL .NL . "An error ($number) occurred on line $line in the file: $file:" . NL;
echo $message . NL;
echo str_repeat("=", 15) . NL;
//"<pre>" . print_r($vars, 1) . "</pre>";
// Make sure that you decide how to respond to errors (on the user's side)
// Either echo an error message, or kill the entire project. Up to you...
// The code below ensures that we only "die" if the error was more than
// just a NOTICE.
if ( ($number !== E_NOTICE) && ($number < 2048) ) {
// die("Exiting on error...");
}
}
function cli_exception_handler ($e)
{
echo "Uncaught exception: " , $e->getMessage(), "\n";
echo $e->getTraceAsString();
}
}
| 29.406977
| 203
| 0.634638
|
dd6ce158df07b0af8ae207370850d76bd1031bf7
| 4,900
|
java
|
Java
|
core/src/test/java/router/client/api2/OnChangeCallbackChainTest.java
|
realityforge-experiments/gwt-router
|
dce78043198bb367cb413f8153c8a5b8344078d3
|
[
"Apache-2.0"
] | null | null | null |
core/src/test/java/router/client/api2/OnChangeCallbackChainTest.java
|
realityforge-experiments/gwt-router
|
dce78043198bb367cb413f8153c8a5b8344078d3
|
[
"Apache-2.0"
] | null | null | null |
core/src/test/java/router/client/api2/OnChangeCallbackChainTest.java
|
realityforge-experiments/gwt-router
|
dce78043198bb367cb413f8153c8a5b8344078d3
|
[
"Apache-2.0"
] | null | null | null |
package router.client.api2;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import org.realityforge.guiceyloops.shared.ValueUtil;
import org.testng.annotations.Test;
import static org.mockito.Mockito.*;
import static org.testng.Assert.*;
@SuppressWarnings( "NonJREEmulationClassesInClientCode" )
public final class OnChangeCallbackChainTest
{
@Test
public void emptyChain_goesToNext()
{
final ArrayList<RouteEntry<OnChangeCallbackAsync>> elements = new ArrayList<>();
final OnChangeCallbackChain chain = new OnChangeCallbackChain( elements );
final TestContext context = new TestContext();
final Runnable abortAction = mock( Runnable.class );
final Runnable nextAction = mock( Runnable.class );
final String previousLocation = ValueUtil.randomString();
chain.onChange( context, previousLocation, abortAction, nextAction );
verify( abortAction, never() ).run();
verify( nextAction ).run();
}
@Test
public void basicChain()
{
final AtomicInteger count = new AtomicInteger();
final ArrayList<RouteEntry<OnChangeCallbackAsync>> elements = new ArrayList<>();
elements.add( FactoryUtil.createOnChangeCallbackAsync( count, ChainControl::proceed ) );
elements.add( FactoryUtil.createOnChangeCallbackAsync( count, ChainControl::proceed ) );
elements.add( FactoryUtil.createOnChangeCallbackAsync( count, ChainControl::proceed ) );
final OnChangeCallbackChain chain = new OnChangeCallbackChain( elements );
final TestContext context = new TestContext();
final Runnable abortAction = mock( Runnable.class );
final Runnable nextAction = mock( Runnable.class );
chain.onChange( context, ValueUtil.randomString(), abortAction, nextAction );
verify( abortAction, never() ).run();
verify( nextAction ).run();
assertEquals( count.intValue(), 3 );
}
@Test
public void basicChainWithHalt()
{
final AtomicInteger count = new AtomicInteger();
final ArrayList<RouteEntry<OnChangeCallbackAsync>> elements = new ArrayList<>();
elements.add( FactoryUtil.createOnChangeCallbackAsync( count, ChainControl::proceed ) );
elements.add( FactoryUtil.createOnChangeCallbackAsync( count, ChainControl::proceed ) );
elements.add( FactoryUtil.createOnChangeCallbackAsync( count, ChainControl::halt ) );
elements.add( FactoryUtil.createOnChangeCallbackAsync( count, ChainControl::proceed ) );
final OnChangeCallbackChain chain = new OnChangeCallbackChain( elements );
final TestContext context = new TestContext();
final Runnable abortAction = mock( Runnable.class );
final Runnable nextAction = mock( Runnable.class );
chain.onChange( context, ValueUtil.randomString(), abortAction, nextAction );
verify( abortAction, never() ).run();
verify( nextAction ).run();
assertEquals( count.intValue(), 3 );
}
@Test
public void basicChainWithAbort()
{
final AtomicInteger count = new AtomicInteger();
final ArrayList<RouteEntry<OnChangeCallbackAsync>> elements = new ArrayList<>();
elements.add( FactoryUtil.createOnChangeCallbackAsync( count, ChainControl::proceed ) );
elements.add( FactoryUtil.createOnChangeCallbackAsync( count, ChainControl::proceed ) );
elements.add( FactoryUtil.createOnChangeCallbackAsync( count, OnChangeControl::abort ) );
elements.add( FactoryUtil.createOnChangeCallbackAsync( count, ChainControl::proceed ) );
final OnChangeCallbackChain chain = new OnChangeCallbackChain( elements );
final TestContext context = new TestContext();
final Runnable abortAction = mock( Runnable.class );
final Runnable nextAction = mock( Runnable.class );
chain.onChange( context, ValueUtil.randomString(), abortAction, nextAction );
verify( abortAction ).run();
verify( nextAction, never() ).run();
assertEquals( count.intValue(), 3 );
}
@Test
public void basicChainAbortAfterHalt()
{
final AtomicInteger count = new AtomicInteger();
final ArrayList<RouteEntry<OnChangeCallbackAsync>> elements = new ArrayList<>();
elements.add( FactoryUtil.createOnChangeCallbackAsync( count, ChainControl::proceed ) );
elements.add( FactoryUtil.createOnChangeCallbackAsync( count, ChainControl::proceed ) );
elements.add( FactoryUtil.createOnChangeCallbackAsync( count, ChainControl::halt ) );
elements.add( FactoryUtil.createOnChangeCallbackAsync( count, OnChangeControl::abort ) );
final OnChangeCallbackChain chain = new OnChangeCallbackChain( elements );
final TestContext context = new TestContext();
final Runnable abortAction = mock( Runnable.class );
final Runnable nextAction = mock( Runnable.class );
chain.onChange( context, ValueUtil.randomString(), abortAction, nextAction );
verify( abortAction, never() ).run();
verify( nextAction ).run();
assertEquals( count.intValue(), 3 );
}
}
| 39.837398
| 93
| 0.740612
|
a44618a519587e337991a0492c8b32189a59ad87
| 773
|
php
|
PHP
|
database/migrations/2020_10_21_171818_fopfotospasos.php
|
gersongrowanalytics/leadcorporate-api
|
320f2e1f81f0438093f855eff8e7c899ec992951
|
[
"MIT"
] | null | null | null |
database/migrations/2020_10_21_171818_fopfotospasos.php
|
gersongrowanalytics/leadcorporate-api
|
320f2e1f81f0438093f855eff8e7c899ec992951
|
[
"MIT"
] | null | null | null |
database/migrations/2020_10_21_171818_fopfotospasos.php
|
gersongrowanalytics/leadcorporate-api
|
320f2e1f81f0438093f855eff8e7c899ec992951
|
[
"MIT"
] | null | null | null |
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class Fopfotospasos extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('fopfotospasos', function (Blueprint $table) {
$table->increments('fopid');
$table->unsignedInteger('dsuid');
$table->string('fopimagen');
$table->timestamps();
$table->foreign('dsuid')->references('dsuid')->on('dsudatossubpasos');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('fopfotospasos');
}
}
| 21.472222
| 82
| 0.574386
|
0d745e6018efc868ebda200bbcc57c89024184b3
| 9,789
|
cs
|
C#
|
EncoreTickets.SDK.Tests/IntegrationTests/PaymentServiceTests.cs
|
nickbenj/sdk-dotNet
|
f2c05316bae6d9c775d4ee2a423d8fba98336ecd
|
[
"MIT"
] | 1
|
2020-06-12T08:47:04.000Z
|
2020-06-12T08:47:04.000Z
|
EncoreTickets.SDK.Tests/IntegrationTests/PaymentServiceTests.cs
|
nickbenj/sdk-dotNet
|
f2c05316bae6d9c775d4ee2a423d8fba98336ecd
|
[
"MIT"
] | 8
|
2020-05-05T13:17:59.000Z
|
2020-08-26T15:57:04.000Z
|
EncoreTickets.SDK.Tests/IntegrationTests/PaymentServiceTests.cs
|
nickbenj/sdk-dotNet
|
f2c05316bae6d9c775d4ee2a423d8fba98336ecd
|
[
"MIT"
] | 3
|
2019-06-06T13:55:01.000Z
|
2019-10-25T14:07:32.000Z
|
using System;
using System.Collections.Generic;
using System.Net;
using EncoreTickets.SDK.Api.Models;
using EncoreTickets.SDK.Api.Results.Exceptions;
using EncoreTickets.SDK.Payment;
using EncoreTickets.SDK.Payment.Models;
using EncoreTickets.SDK.Payment.Models.RequestModels;
using EncoreTickets.SDK.Tests.Helpers;
using Microsoft.Extensions.Configuration;
using NUnit.Framework;
namespace EncoreTickets.SDK.Tests.IntegrationTests
{
internal class PaymentServiceTests
{
private IConfiguration configuration;
private Environments environment;
private ApiContext context;
private PaymentServiceApi service;
private string username;
private string password;
private string apiKey;
[SetUp]
public void SetupState()
{
configuration = ConfigurationHelper.GetConfiguration();
environment = Environments.Sandbox;
username = configuration["Payment:Username"];
password = configuration["Payment:Password"];
apiKey = configuration["Payment:ApiKey"];
context = new ApiContext(environment, apiKey)
{
Correlation = Guid.NewGuid().ToString(),
};
service = new PaymentServiceApi(context, true);
}
[Test]
public void Authentication_IfUsingUsernameAndPassword_Successful()
{
context = new ApiContext(environment, username, password);
service = new PaymentServiceApi(context, true);
service.AuthenticationService.Authenticate();
Assert.True(service.AuthenticationService.IsThereAuthentication());
}
[Test]
public void GetOrder_Successful()
{
var channelId = configuration["Payment:TestChannelId"];
var externalId = configuration["Payment:TestOrderExternalId"];
var order = service.GetOrder(channelId, externalId);
AssertThatOrderIsCorrect(order, channelId, externalId);
Assert.AreEqual(context.Correlation, context.ReceivedCorrelation);
}
[Test]
public void GetOrder_IfOrderWithChannelAndExternalIdDoesNotExist_Exception404()
{
var channelId = "not_channel";
var externalId = "not_id";
var exception = Assert.Catch<ApiException>(() =>
{
service.GetOrder(channelId, externalId);
});
Assert.AreEqual(HttpStatusCode.NotFound, exception.ResponseCode);
Assert.AreEqual(context.Correlation, context.ReceivedCorrelation);
}
[Test]
public void CreateOrder_Successful()
{
var channelId = configuration["Payment:TestChannelId"];
var externalId = Guid.NewGuid().ToString();
var amount = new Amount
{
Value = 8100,
Currency = "USD",
ExchangeRate = 1.2,
};
var orderRequest = new CreateOrderRequest
{
Description = "test description",
ChannelId = channelId,
ExternalId = externalId,
RedirectUrl = "https://payment-service.qatixuk.io/redirect",
Origin = "https://payment-service.qatixuk.io",
BillingAddress = new Address
{
Line1 = "115 Shaftesbury Avenue",
Line2 = null,
PostalCode = "WC2H 8AF",
City = "Cambridge Circus",
CountryCode = "UK",
LegacyCountryCode = null,
StateOrProvince = "London",
},
Shopper = new Shopper
{
Email = "test@test.com",
TelephoneNumber = "02072578183",
Title = "MS",
FirstName = "INNA",
LastName = "IVANOVA",
ExternalId = null,
},
Items = new List<OrderItem>
{
new OrderItem
{
Name = "WICKED",
Description = null,
Quantity = 1,
Amount = amount,
Tax = null,
ExternalId = "1587",
},
},
Amount = amount,
RiskData = new RiskData
{
DaysToEvent = 0,
DeliveryMethod = "collection",
OfficeId = 1,
},
};
var order = service.CreateOrder(orderRequest);
AssertThatOrderIsCorrect(order, channelId, externalId);
Assert.AreEqual(context.Correlation, context.ReceivedCorrelation);
}
[Test]
public void CreateOrder_IfOrderExists_Exception400()
{
var channelId = configuration["Payment:TestChannelId"];
var externalId = configuration["Payment:TestCreateOrderExternalId"];
var orderRequest = new CreateOrderRequest
{
Description = "test description",
ChannelId = channelId,
ExternalId = externalId,
RedirectUrl = "https://payment-service.qatixuk.io/redirect",
Origin = "https://payment-service.qatixuk.io",
Amount = new Amount
{
Value = 8100,
Currency = "USD",
ExchangeRate = 1.2,
},
};
var exception = Assert.Catch<ApiException>(() =>
{
service.CreateOrder(orderRequest);
});
Assert.AreEqual(HttpStatusCode.BadRequest, exception.ResponseCode);
Assert.AreEqual(context.Correlation, context.ReceivedCorrelation);
}
[Test]
public void UpdateOrder_Successful()
{
var channelId = configuration["Payment:TestChannelId"];
var externalId = configuration["Payment:TestOrderExternalId"];
var order = service.GetOrder(channelId, externalId);
var newGuid = Guid.NewGuid();
var updateOrderRequest = new UpdateOrderRequest
{
Shopper = order.Shopper,
BillingAddress = order.BillingAddress,
Items = order.Items,
RiskData = order.RiskData,
};
updateOrderRequest.Shopper.FirstName = $"Tom{newGuid}";
updateOrderRequest.BillingAddress.Line2 = $"Address{newGuid}";
updateOrderRequest.Items.ForEach(x => x.Name = $"Name{newGuid}");
updateOrderRequest.RiskData = new RiskData();
var updatedOrder = service.UpdateOrder(order.Id, updateOrderRequest);
AssertThatOrderIsCorrect(updatedOrder, channelId, externalId);
updatedOrder.ShouldBeEquivalentToObjectWithMoreProperties(order);
Assert.AreEqual(context.Correlation, context.ReceivedCorrelation);
}
[Test]
public void UpdateOrder_IfDeliveryMethodIsInvalid_Exception400()
{
var channelId = configuration["Payment:TestChannelId"];
var externalId = configuration["Payment:TestOrderExternalId"];
var order = service.GetOrder(channelId, externalId);
var updateOrderRequest = new UpdateOrderRequest
{
Shopper = order.Shopper,
BillingAddress = order.BillingAddress,
Items = order.Items,
RiskData = new RiskData
{
DaysToEvent = 2,
DeliveryMethod = "invalid",
OfficeId = 1,
},
};
var exception = Assert.Catch<ApiException>(() =>
{
service.UpdateOrder(order.Id, updateOrderRequest);
});
Assert.AreEqual(HttpStatusCode.BadRequest, exception.ResponseCode);
Assert.AreEqual(context.Correlation, context.ReceivedCorrelation);
}
[Test]
public void UpdateOrder_IfOrderWithIdDoesNotExist_Exception404()
{
var orderId = "not_id";
var updateOrderRequest = new UpdateOrderRequest();
var exception = Assert.Catch<ApiException>(() =>
{
service.UpdateOrder(orderId, updateOrderRequest);
});
Assert.AreEqual(HttpStatusCode.NotFound, exception.ResponseCode);
Assert.AreEqual(context.Correlation, context.ReceivedCorrelation);
}
[Test]
public void GetUsStates_Successful()
{
var states = service.GetUsStates();
Assert.NotNull(states);
states.ForEach(x =>
{
Assert.NotNull(x.Name);
Assert.NotNull(x.Abbreviation);
});
}
[Test]
public void GetCanadaProvinces_Successful()
{
var states = service.GetCanadaProvinces();
Assert.NotNull(states);
states.ForEach(x =>
{
Assert.NotNull(x.Name);
Assert.NotNull(x.Abbreviation);
});
Assert.AreEqual(context.Correlation, context.ReceivedCorrelation);
}
private void AssertThatOrderIsCorrect(Order order, string channelId, string externalId)
{
Assert.IsNotNull(order.Id);
Assert.AreEqual(channelId, order.ChannelId);
Assert.AreEqual(externalId, order.ExternalId);
}
}
}
| 35.596364
| 95
| 0.547758
|
dde5c56b42cb70d8a41726652b8d8ae68d9cf228
| 800
|
java
|
Java
|
data_parser/src/test/java/ru/jts/tests/parser/CursedWeaponDataParserTest.java
|
ChaosPaladin/jts
|
42d81605505f6db0aa62a6d839e747263e18244c
|
[
"Apache-2.0"
] | null | null | null |
data_parser/src/test/java/ru/jts/tests/parser/CursedWeaponDataParserTest.java
|
ChaosPaladin/jts
|
42d81605505f6db0aa62a6d839e747263e18244c
|
[
"Apache-2.0"
] | null | null | null |
data_parser/src/test/java/ru/jts/tests/parser/CursedWeaponDataParserTest.java
|
ChaosPaladin/jts
|
42d81605505f6db0aa62a6d839e747263e18244c
|
[
"Apache-2.0"
] | 1
|
2020-01-08T01:10:58.000Z
|
2020-01-08T01:10:58.000Z
|
package ru.jts.tests.parser;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import ru.jts.data.holder.CursedWeaponDataHolder;
import ru.jts.data.holder.cursedweapondata.CursedWeapon;
import ru.jts.data.parser.CursedWeaponDataParser;
/**
* @author : Camelion
* @date : 26.08.12 21:34
*/
public class CursedWeaponDataParserTest extends Assert {
@Before
public void setUp() throws Exception {
CursedWeaponDataParser.getInstance().load();
}
@Test
public void test() {
CursedWeaponDataHolder holder = CursedWeaponDataHolder.getInstance();
assertFalse(holder.getCursedWeapons().size() == 0);
for (CursedWeapon weapon : holder.getCursedWeapons()) {
assertFalse(weapon.item_name.isEmpty());
}
}
}
| 25.806452
| 77
| 0.7
|
3fe67a074c2ff8e275ac8f20d1e624eabce67401
| 209
|
rb
|
Ruby
|
app/models/application_record.rb
|
kjleitz/ode-to-16-color
|
131bc99315205098cce8a9b4d398559ed8d1b619
|
[
"MIT"
] | null | null | null |
app/models/application_record.rb
|
kjleitz/ode-to-16-color
|
131bc99315205098cce8a9b4d398559ed8d1b619
|
[
"MIT"
] | 1
|
2018-11-02T02:30:54.000Z
|
2018-11-02T02:30:54.000Z
|
app/models/application_record.rb
|
kjleitz/ode-to-16-color
|
131bc99315205098cce8a9b4d398559ed8d1b619
|
[
"MIT"
] | 1
|
2018-10-16T18:23:41.000Z
|
2018-10-16T18:23:41.000Z
|
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
default_scope { defined?(friendly) ? friendly : all }
# class << self
# def friendly
# defined()
# end
# end
end
| 17.416667
| 55
| 0.645933
|
ef66fde061c57a3fa0d8ace35bca4f09e0b92bcf
| 10,563
|
js
|
JavaScript
|
node_modules/@antv/x6/lib/model/store.js
|
leaderli/li-runner-flow
|
bb51a8a408c3f7b2754236c08aa35710e1252579
|
[
"MIT"
] | null | null | null |
node_modules/@antv/x6/lib/model/store.js
|
leaderli/li-runner-flow
|
bb51a8a408c3f7b2754236c08aa35710e1252579
|
[
"MIT"
] | null | null | null |
node_modules/@antv/x6/lib/model/store.js
|
leaderli/li-runner-flow
|
bb51a8a408c3f7b2754236c08aa35710e1252579
|
[
"MIT"
] | null | null | null |
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Store = void 0;
var common_1 = require("../common");
var util_1 = require("../util");
var Store = /** @class */ (function (_super) {
__extends(Store, _super);
function Store(data) {
if (data === void 0) { data = {}; }
var _this = _super.call(this) || this;
_this.pending = false;
_this.changing = false;
_this.data = {};
_this.mutate(util_1.ObjectExt.cloneDeep(data));
_this.changed = {};
return _this;
}
Store.prototype.mutate = function (data, options) {
var _this = this;
if (options === void 0) { options = {}; }
var unset = options.unset === true;
var silent = options.silent === true;
var changes = [];
var changing = this.changing;
this.changing = true;
if (!changing) {
this.previous = util_1.ObjectExt.cloneDeep(this.data);
this.changed = {};
}
var current = this.data;
var previous = this.previous;
var changed = this.changed;
Object.keys(data).forEach(function (k) {
var key = k;
var newValue = data[key];
if (!util_1.ObjectExt.isEqual(current[key], newValue)) {
changes.push(key);
}
if (!util_1.ObjectExt.isEqual(previous[key], newValue)) {
changed[key] = newValue;
}
else {
delete changed[key];
}
if (unset) {
delete current[key];
}
else {
current[key] = newValue;
}
});
if (!silent && changes.length > 0) {
this.pending = true;
this.pendingOptions = options;
changes.forEach(function (key) {
_this.emit('change:*', {
key: key,
options: options,
store: _this,
current: current[key],
previous: previous[key],
});
});
}
if (changing) {
return this;
}
if (!silent) {
// Changes can be recursively nested within `"change"` events.
while (this.pending) {
this.pending = false;
this.emit('changed', {
current: current,
previous: previous,
store: this,
options: this.pendingOptions,
});
}
}
this.pending = false;
this.changing = false;
this.pendingOptions = null;
return this;
};
Store.prototype.get = function (key, defaultValue) {
if (key == null) {
return this.data;
}
var ret = this.data[key];
return ret == null ? defaultValue : ret;
};
Store.prototype.getPrevious = function (key) {
if (this.previous) {
var ret = this.previous[key];
return ret == null ? undefined : ret;
}
return undefined;
};
Store.prototype.set = function (key, value, options) {
var _a;
if (key != null) {
if (typeof key === 'object') {
this.mutate(key, value);
}
else {
this.mutate((_a = {}, _a[key] = value, _a), options);
}
}
return this;
};
Store.prototype.remove = function (key, options) {
var empty = undefined;
var subset = {};
var opts;
if (typeof key === 'string') {
subset[key] = empty;
opts = options;
}
else if (Array.isArray(key)) {
key.forEach(function (k) { return (subset[k] = empty); });
opts = options;
}
else {
// eslint-disable-next-line
for (var key_1 in this.data) {
subset[key_1] = empty;
}
opts = key;
}
this.mutate(subset, __assign(__assign({}, opts), { unset: true }));
return this;
};
Store.prototype.getByPath = function (path) {
return util_1.ObjectExt.getByPath(this.data, path, '/');
};
Store.prototype.setByPath = function (path, value, options) {
if (options === void 0) { options = {}; }
var delim = '/';
var pathArray = Array.isArray(path) ? __spreadArray([], path, true) : path.split(delim);
var pathString = Array.isArray(path) ? path.join(delim) : path;
var property = pathArray[0];
var pathArrayLength = pathArray.length;
options.propertyPath = pathString;
options.propertyValue = value;
options.propertyPathArray = pathArray;
if (pathArrayLength === 1) {
this.set(property, value, options);
}
else {
var update = {};
var diver = update;
var nextKey = property;
// Initialize the nested object. Subobjects are either arrays or objects.
// An empty array is created if the sub-key is an integer. Otherwise, an
// empty object is created.
for (var i = 1; i < pathArrayLength; i += 1) {
var key = pathArray[i];
var isArrayIndex = Number.isFinite(Number(key));
diver = diver[nextKey] = isArrayIndex ? [] : {};
nextKey = key;
}
// Fills update with the `value` on `path`.
util_1.ObjectExt.setByPath(update, pathArray, value, delim);
var data = util_1.ObjectExt.cloneDeep(this.data);
// If rewrite mode enabled, we replace value referenced by path with the
// new one (we don't merge).
if (options.rewrite) {
util_1.ObjectExt.unsetByPath(data, path, delim);
}
var merged = util_1.ObjectExt.merge(data, update);
this.set(property, merged[property], options);
}
return this;
};
Store.prototype.removeByPath = function (path, options) {
var keys = Array.isArray(path) ? path : path.split('/');
var key = keys[0];
if (keys.length === 1) {
this.remove(key, options);
}
else {
var paths = keys.slice(1);
var prop = util_1.ObjectExt.cloneDeep(this.get(key));
if (prop) {
util_1.ObjectExt.unsetByPath(prop, paths);
}
this.set(key, prop, options);
}
return this;
};
Store.prototype.hasChanged = function (key) {
if (key == null) {
return Object.keys(this.changed).length > 0;
}
return key in this.changed;
};
/**
* Returns an object containing all the data that have changed,
* or `null` if there are no changes. Useful for determining what
* parts of a view need to be updated.
*/
Store.prototype.getChanges = function (diff) {
if (diff == null) {
return this.hasChanged() ? util_1.ObjectExt.cloneDeep(this.changed) : null;
}
var old = this.changing ? this.previous : this.data;
var changed = {};
var hasChanged;
// eslint-disable-next-line
for (var key in diff) {
var val = diff[key];
if (!util_1.ObjectExt.isEqual(old[key], val)) {
changed[key] = val;
hasChanged = true;
}
}
return hasChanged ? util_1.ObjectExt.cloneDeep(changed) : null;
};
/**
* Returns a copy of the store's `data` object.
*/
Store.prototype.toJSON = function () {
return util_1.ObjectExt.cloneDeep(this.data);
};
Store.prototype.clone = function () {
var constructor = this.constructor;
return new constructor(this.data);
};
Store.prototype.dispose = function () {
this.off();
this.data = {};
this.previous = {};
this.changed = {};
this.pending = false;
this.changing = false;
this.pendingOptions = null;
this.trigger('disposed', { store: this });
};
__decorate([
common_1.Basecoat.dispose()
], Store.prototype, "dispose", null);
return Store;
}(common_1.Basecoat));
exports.Store = Store;
//# sourceMappingURL=store.js.map
| 36.933566
| 150
| 0.515857
|
de371ac9a13e7b613c66a43ee1de6c1484a60e6a
| 719
|
sh
|
Shell
|
docs/examples/code/run_example.sh
|
gamazeps/wot
|
623bcdc78ad1fab43b3e05b467f961648741a7a0
|
[
"BSD-3-Clause"
] | null | null | null |
docs/examples/code/run_example.sh
|
gamazeps/wot
|
623bcdc78ad1fab43b3e05b467f961648741a7a0
|
[
"BSD-3-Clause"
] | null | null | null |
docs/examples/code/run_example.sh
|
gamazeps/wot
|
623bcdc78ad1fab43b3e05b467f961648741a7a0
|
[
"BSD-3-Clause"
] | null | null | null |
#!/usr/bin/env bash
# generate example data
python 00_generating_data.py
# generate cell sets
wot cells_by_gene_set --matrix matrix.txt --gene_sets gene_sets.gmt --out cell_sets.gmt --format gmt --quantile 0.99
# compute transport maps
wot optimal_transport --matrix matrix.txt --cell_days days.txt
# compute and plot trajectories
wot trajectory --tmap tmaps --cell_set cell_sets.gmt --day 7 --embedding embedding.csv --plot_divergence
# compute and plot trajectory trends
wot trajectory_trends --trajectory wot_trajectory.txt --cell_days days.txt --matrix matrix.txt --plot
# compute and plot validation summary
wot optimal_transport_validation --matrix matrix.txt --cell_days days.txt --covariate covariate.txt
| 35.95
| 116
| 0.792768
|
f160de6f53a3bd751b07bb01bc3f676303367fe0
| 1,615
|
sql
|
SQL
|
schema/initial.sql
|
illicitonion/edfringeplanner
|
ab6d4a3218ee211de5078b3205fd39da1fbdfb50
|
[
"BSD-3-Clause"
] | null | null | null |
schema/initial.sql
|
illicitonion/edfringeplanner
|
ab6d4a3218ee211de5078b3205fd39da1fbdfb50
|
[
"BSD-3-Clause"
] | null | null | null |
schema/initial.sql
|
illicitonion/edfringeplanner
|
ab6d4a3218ee211de5078b3205fd39da1fbdfb50
|
[
"BSD-3-Clause"
] | null | null | null |
CREATE TABLE IF NOT EXISTS venues (
id SERIAL PRIMARY KEY,
name VARCHAR UNIQUE,
edfringe_number INTEGER,
address VARCHAR,
latlong POINT
);
CREATE TABLE IF NOT EXISTS shows (
id SERIAL PRIMARY KEY,
edfringe_url VARCHAR UNIQUE,
title VARCHAR,
category VARCHAR,
venue_id INTEGER REFERENCES venues(id),
duration INTERVAL
);
CREATE TABLE IF NOT EXISTS performances (
id SERIAL PRIMARY KEY,
show_id INTEGER REFERENCES shows(id),
datetime_utc TIMESTAMP WITH TIME ZONE,
UNIQUE(show_id, datetime_utc)
);
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
email VARCHAR UNIQUE,
password_hash VARCHAR,
start_datetime_utc TIMESTAMP WITH TIME ZONE,
end_datetime_utc TIMESTAMP WITH TIME ZONE,
confirm_email_token VARCHAR,
import_token VARCHAR UNIQUE
);
CREATE TABLE IF NOT EXISTS interests (
id SERIAL PRIMARY KEY,
show_id INTEGER REFERENCES shows(id),
user_id INTEGER REFERENCES users(id),
interest VARCHAR, -- Booked, Must, Like
UNIQUE(show_id, user_id)
);
CREATE TABLE IF NOT EXISTS performance_interests (
id SERIAL PRIMARY KEY,
show_id INTEGER REFERENCES shows(id),
performance_id INTEGER REFERENCES performances(id),
user_id INTEGER REFERENCES users(id),
interest VARCHAR, -- Booked, Must
UNIQUE(performance_id, user_id)
);
CREATE TABLE IF NOT EXISTS shares (
id SERIAL PRIMARY KEY,
shared_by INTEGER REFERENCES users(id),
shared_with_email VARCHAR,
UNIQUE(shared_by, shared_with_email)
);
CREATE TABLE IF NOT EXISTS sold_out (
id SERIAL PRIMARY KEY,
performance_id INTEGER REFERENCES performances(id),
UNIQUE(performance_id)
);
| 25.234375
| 53
| 0.765325
|
ddb159f29165d84cb7cf1f610e668cd54d33f973
| 1,918
|
java
|
Java
|
src/main/java/org/apache/flume/interceptor/CacheableInterceptor.java
|
keedio/flume-cacheable-interceptor-skeleton
|
af771e530eb35edcc41d5739ac0b9013c3b2dae6
|
[
"Apache-2.0"
] | 1
|
2019-09-03T07:10:05.000Z
|
2019-09-03T07:10:05.000Z
|
src/main/java/org/apache/flume/interceptor/CacheableInterceptor.java
|
keedio/flume-cacheable-interceptor-skeleton
|
af771e530eb35edcc41d5739ac0b9013c3b2dae6
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/org/apache/flume/interceptor/CacheableInterceptor.java
|
keedio/flume-cacheable-interceptor-skeleton
|
af771e530eb35edcc41d5739ac0b9013c3b2dae6
|
[
"Apache-2.0"
] | null | null | null |
package org.apache.flume.interceptor;
import java.util.LinkedList;
import java.util.List;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.interceptor.service.FlumeCacheService;
import org.apache.flume.interceptor.service.ICacheService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Implements a cacheable interceptor
*
* @see <a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/html/cache.html">Spring Cache docs</a>
*/
public class CacheableInterceptor implements Interceptor {
private ApplicationContext context;
private ICacheService<Event> service;
public CacheableInterceptor() {
// Get Spring context
this.context = new ClassPathXmlApplicationContext("beans.xml");
}
@Override
public void initialize() {
// Get cache service instance
service = context.getBean(ICacheService.class);
}
@Override
public Event intercept(Event event) {
// Edit the FlumeCacheService.intercept method to implement
// the transformation you want to cache.
return service.intercept(event);
}
@Override
public List<Event> intercept(List<Event> events) {
List<Event> intercepted = new LinkedList<Event>();
for (Event e : events) {
intercepted.add(intercept(e));
}
return intercepted;
}
ApplicationContext getContext() {
return context;
}
ICacheService<Event> getService() {
return service;
}
@Override
public void close() {
}
public static class Builder implements Interceptor.Builder {
public Interceptor build() {
return new CacheableInterceptor();
}
@Override
public void configure(Context context) {
}
}
}
| 27.014085
| 124
| 0.683003
|
2a8ed7e21fa30a360c3c73a61de7d40df8d790cd
| 2,928
|
ps1
|
PowerShell
|
Tests/Install-Dirk.Tests.ps1
|
LockstepGroup/Dirk
|
7b4e406454058847b15d84e0e292f640b01cac9a
|
[
"MIT"
] | null | null | null |
Tests/Install-Dirk.Tests.ps1
|
LockstepGroup/Dirk
|
7b4e406454058847b15d84e0e292f640b01cac9a
|
[
"MIT"
] | null | null | null |
Tests/Install-Dirk.Tests.ps1
|
LockstepGroup/Dirk
|
7b4e406454058847b15d84e0e292f640b01cac9a
|
[
"MIT"
] | null | null | null |
<# if (-not $ENV:BHProjectPath) {
Set-BuildEnvironment -Path $PSScriptRoot\..
}
Remove-Module $ENV:BHProjectName -ErrorAction SilentlyContinue
Import-Module (Join-Path $ENV:BHProjectPath $ENV:BHProjectName) -Force
InModuleScope $ENV:BHProjectName {
# Setup creds to use for cmdlets
$TestAesKey = @(
226,
44,
221,
255,
218,
191,
19,
253,
10,
127,
225,
196,
43,
26,
228,
72,
101,
187,
186,
142,
250,
64,
230,
188,
190,
47,
64,
249,
195,
11,
230,
193
)
$TestUserName = "testuser"
$TestPassword = New-EncryptedString -PlainTextString 'testpassword' -AesKey $TestAesKey
$TestPassword = ConvertTo-SecureString $TestPassword -Key $TestAesKey
$TestCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $TestUserName, $TestPassword
$PSVersion = $PSVersionTable.PSVersion.Major
$ProjectRoot = $ENV:BHProjectPath
$Verbose = @{}
if ($ENV:BHBranchName -notlike "master" -or $env:BHCommitMessage -match "!verbose") {
$Verbose.add("Verbose", $True)
}
switch -Regex (Get-OsVersion) {
'MacOS' {
Mock sudo { return $true }
#############################################################
# Dummy fuctions for scheduled tasks, these have to be defined somewhere for Mock to work
function New-ScheduledTaskAction () {}
function New-ScheduledTaskTrigger () {}
function New-ScheduledTask () {}
function Register-ScheduledTask () {}
# Mocks for scheduled tasks that don't exist in MacOS
$TestPath = Join-Path $env:TMPDIR -ChildPath "Dirk"
}
'Windows' {
Mock Invoke-ElevatedProcess { return $true }
$TestPath = Join-Path $env:TEMP -ChildPath "Dirk"
}
}
#$TestPath = Join-Path $env:TMPDIR -ChildPath "Dirk"
Describe "Install-Dirk to Path: $TestPath" {
$env:DirkRoot = $null
$profile = @{AllUsersAllHosts = 'c:\Projects\dirk\profile.ps1'}
$ToddPath = Join-Path -Path $TestPath -ChildPath 'Todd'
if (Test-Path $ToddPath) {
Remove-Item -Path $ToddPath -Force
}
Mock Get-GithubRepo { New-Item -Path (Join-Path -Path $TestPath -ChildPath 'Todd') -ItemType Directory } -Verifiable
Mock Get-Content { return @('$env:DirkRoot = "c:\lockstep"') }
Mock Select-String { return @{Line = '$env:DirkRoot = "c:\lockstep"'} } -Verifiable
Install-Dirk -Path $TestPath -Force -GithubCredential $TestCredential
It "Should set env:DirkRoot" {
$env:DirkRoot | Should -Be $TestPath
}
Assert-VerifiableMock
}
} #>
| 30.5
| 127
| 0.5625
|
8956a7244dbaf73e2e7af277a90f9df97764da6d
| 834
|
dart
|
Dart
|
sosmap/lib/util/notiFCM.dart
|
hesheng1910/SOSMap
|
cd3e73750dc919825e26c52a13d4b931f7d45119
|
[
"MIT"
] | null | null | null |
sosmap/lib/util/notiFCM.dart
|
hesheng1910/SOSMap
|
cd3e73750dc919825e26c52a13d4b931f7d45119
|
[
"MIT"
] | null | null | null |
sosmap/lib/util/notiFCM.dart
|
hesheng1910/SOSMap
|
cd3e73750dc919825e26c52a13d4b931f7d45119
|
[
"MIT"
] | null | null | null |
import 'dart:convert';
import 'package:http/http.dart' as http;
class NotiFCM {
static String constructFCMPayload(
String token, String title, String message, String type) {
return jsonEncode({
'token': token,
'notification': {
'title': title,
'body': message,
},
'data': {'type': type},
});
}
static Future<void> sendPushMessage(
String token, String title, String message, String type) async {
try {
await http.post(
Uri.parse('https://sosmap.herokuapp.com/api/fcm/sosmap'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: constructFCMPayload(token, title, message, type),
);
print('FCM request for device sent!');
} catch (e) {
print(e);
}
}
}
| 25.272727
| 70
| 0.583933
|
da2a3f294afc59175de37bbf705df8a5cdbbdbfc
| 871
|
php
|
PHP
|
common/helpers/Helper.php
|
j3l11234/hdzx_v4
|
95e26cd4d391c83cffce2572d285ac1714f196a6
|
[
"BSD-3-Clause"
] | 4
|
2018-03-06T03:21:16.000Z
|
2020-03-20T06:30:08.000Z
|
common/helpers/Helper.php
|
j3l11234/hdzx_v4
|
95e26cd4d391c83cffce2572d285ac1714f196a6
|
[
"BSD-3-Clause"
] | null | null | null |
common/helpers/Helper.php
|
j3l11234/hdzx_v4
|
95e26cd4d391c83cffce2572d285ac1714f196a6
|
[
"BSD-3-Clause"
] | 1
|
2019-03-07T12:33:10.000Z
|
2019-03-07T12:33:10.000Z
|
<?php
/**
* @link http://www.j3l11234.com/
* @copyright Copyright (c) 2015 j3l11234
* @author j3l11234@j3l11234.com
*/
namespace common\helpers;
use Yii;
use yii\bootstrap\Alert;
/**
* 一些简易的操作类集合
*/
class Helper {
public static function renderFlash() {
if( Yii::$app->getSession()->hasFlash('success') ) {
return Alert::widget([
'options' => [
'class' => 'alert-success',
],
'body' => Yii::$app->getSession()->getFlash('success'),
]);
}
if( Yii::$app->getSession()->hasFlash('error') ) {
return Alert::widget([
'options' => [
'class' => 'alert-danger',
],
'body' => Yii::$app->getSession()->getFlash('error'),
]);
}
return '';
}
}
| 24.194444
| 71
| 0.459242
|
216100fdee24020e5412f4196fcd67d607492d98
| 254
|
ps1
|
PowerShell
|
Chapter19/1.4.11.CompositeValue_ShowIndividualFlags.ps1
|
wagnerhsu/packt-Mastering-Windows-PowerShell-Scripting-Fourth-Edition
|
be9f5cad2bf28de7c0a250590c65b72994800aeb
|
[
"MIT"
] | 27
|
2020-04-21T13:28:29.000Z
|
2022-03-09T12:19:24.000Z
|
Chapter19/1.4.11.CompositeValue_ShowIndividualFlags.ps1
|
wagnerhsu/packt-Mastering-Windows-PowerShell-Scripting-Fourth-Edition
|
be9f5cad2bf28de7c0a250590c65b72994800aeb
|
[
"MIT"
] | null | null | null |
Chapter19/1.4.11.CompositeValue_ShowIndividualFlags.ps1
|
wagnerhsu/packt-Mastering-Windows-PowerShell-Scripting-Fourth-Edition
|
be9f5cad2bf28de7c0a250590c65b72994800aeb
|
[
"MIT"
] | 15
|
2020-05-03T01:24:33.000Z
|
2022-01-26T04:57:23.000Z
|
# Requires 1.4.7 and 1.4.9
Get-FlagName -Value ([MyEnum]::FirstAndThird)
# Expects output:
#
# Name Integer Hexadecimal BitPosition
# ---- ------- ----------- -----------
# First 1 0x00000001 1
# Third 4 0x00000004 3
| 23.090909
| 45
| 0.519685
|
6d8caaf26e41ed83a65908114e69fd0045f6aecd
| 472
|
ts
|
TypeScript
|
wordpress/wp-content/plugins/woocommerce/packages/woocommerce-blocks/assets/js/data/cart/action-types.ts
|
kieuoanh231/CMS
|
777c43d1e8d42ad0f012adbcc254b563979fee8c
|
[
"Apache-2.0"
] | null | null | null |
wordpress/wp-content/plugins/woocommerce/packages/woocommerce-blocks/assets/js/data/cart/action-types.ts
|
kieuoanh231/CMS
|
777c43d1e8d42ad0f012adbcc254b563979fee8c
|
[
"Apache-2.0"
] | null | null | null |
wordpress/wp-content/plugins/woocommerce/packages/woocommerce-blocks/assets/js/data/cart/action-types.ts
|
kieuoanh231/CMS
|
777c43d1e8d42ad0f012adbcc254b563979fee8c
|
[
"Apache-2.0"
] | null | null | null |
export const ACTION_TYPES = {
RECEIVE_CART: 'RECEIVE_CART',
RECEIVE_ERROR: 'RECEIVE_ERROR',
REPLACE_ERRORS: 'REPLACE_ERRORS',
APPLYING_COUPON: 'APPLYING_COUPON',
REMOVING_COUPON: 'REMOVING_COUPON',
RECEIVE_CART_ITEM: 'RECEIVE_CART_ITEM',
ITEM_PENDING_QUANTITY: 'ITEM_PENDING_QUANTITY',
RECEIVE_REMOVED_ITEM: 'RECEIVE_REMOVED_ITEM',
UPDATING_CUSTOMER_DATA: 'UPDATING_CUSTOMER_DATA',
UPDATING_SELECTED_SHIPPING_RATE: 'UPDATING_SELECTED_SHIPPING_RATE',
} as const;
| 36.307692
| 68
| 0.826271
|
77845d0fd7f78e22ceb7c420027952b7cd618792
| 26,888
|
dart
|
Dart
|
now_partner_app/lib/ui/views/tab1.dart
|
duytungshrek/app
|
082f0938053090176ed9cdfeb5c8520806b734fe
|
[
"MIT"
] | null | null | null |
now_partner_app/lib/ui/views/tab1.dart
|
duytungshrek/app
|
082f0938053090176ed9cdfeb5c8520806b734fe
|
[
"MIT"
] | null | null | null |
now_partner_app/lib/ui/views/tab1.dart
|
duytungshrek/app
|
082f0938053090176ed9cdfeb5c8520806b734fe
|
[
"MIT"
] | null | null | null |
import 'package:date_format/date_format.dart';
import 'package:datetime_picker_formfield/datetime_picker_formfield.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:intl/intl.dart';
import 'package:now_partner/enums/view_state.dart';
import 'package:now_partner/scoped_models/home_view_model.dart';
import 'package:now_partner/ui/shared/flutter_screenutil.dart';
import 'package:now_partner/ui/shared/cus_dialog.dart' as customDialog;
import 'package:slider_button/slider_button.dart';
import 'tab3.dart';
import 'tab4.dart';
class Tab1 extends StatelessWidget {
final HomeViewModel model;
const Tab1(this.model);
@override
Widget build(BuildContext context) {
ScreenUtil.instance = ScreenUtil(width: 320, height: 568)..init(context);
void _showDialog() {
// flutter defined function
showDialog(
context: context,
builder: (BuildContext context) {
// return object of type Dialog
return customDialog.Dialog(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Container(
margin: EdgeInsets.fromLTRB(0, 20, 0, 0),
child: Text(
"Check - in hôm nay",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: ScreenUtil.getInstance().setSp(14),
),
),
alignment: AlignmentDirectional.center,
),
Container(
child: Text(
formatDate(DateTime.now(), [dd, '/', mm, '/', yyyy]),
style: TextStyle(
fontSize: ScreenUtil.getInstance().setSp(14),
),
),
alignment: AlignmentDirectional.center,
),
ListTile(
leading: Text(
"Đăng ký: ",
style: TextStyle(
fontSize: ScreenUtil.getInstance().setSp(14),
color: Colors.grey,
),
),
title: Text(
"Full time 0h00 - 23h59",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: ScreenUtil.getInstance().setSp(14),
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(
child: Text(
"Bắt đầu",
style: TextStyle(
fontSize: ScreenUtil.getInstance().setSp(14),
color: Colors.grey,
),
),
margin: EdgeInsets.fromLTRB(5, 5, 5, 0),
),
Container(
child: Text(
"Kết thúc",
style: TextStyle(
fontSize: ScreenUtil.getInstance().setSp(14),
color: Colors.grey),
),
margin: EdgeInsets.all(10),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
child: Text(
"Hiện tại",
style: TextStyle(
fontSize: ScreenUtil.getInstance().setSp(14),
fontWeight: FontWeight.bold,
color: Colors.green,
),
),
margin: EdgeInsets.all(5),
),
Container(
height: 1,
color: Colors.grey,
width: ScreenUtil.getInstance().setWidth(150),
),
Clock24Example(),
],
),
Container(
child: Text(
"Vị trí hiện tại của bạn: ",
style: TextStyle(
fontSize: ScreenUtil.getInstance().setSp(14),
color: Colors.grey),
),
margin: EdgeInsets.fromLTRB(0, 15, 0, 5),
alignment: AlignmentDirectional.center,
),
Container(
child: Text(
"500 Xã Đàn, Nam Đồng, Đống Đa, Hà Nội, Vietnam",
style: TextStyle(
fontSize: ScreenUtil.getInstance().setSp(14),
fontWeight: FontWeight.bold,
decoration: TextDecoration.underline,
),
textAlign: TextAlign.center,
maxLines: 2,
),
margin: EdgeInsets.fromLTRB(5, 10, 5, 5),
alignment: AlignmentDirectional.center,
),
Container(
child: Text(
"Lat: " +
model.location.lat.toString() +
"; Lon: " +
model.location.lon.toString(),
style: TextStyle(
fontSize: ScreenUtil.getInstance().setSp(12),
),
textAlign: TextAlign.center,
maxLines: 1,
),
margin: EdgeInsets.fromLTRB(5, 10, 5, 5),
alignment: AlignmentDirectional.center,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: RaisedButton(
color: Colors.grey,
onPressed: () {
Navigator.of(context).pop();
},
child: Text(
"Thoát",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: ScreenUtil.getInstance().setSp(14),
color: Colors.white),
),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: RaisedButton(
color: Colors.blue,
onPressed: () {},
child: Text(
"Check - in",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: ScreenUtil.getInstance().setSp(12),
color: Colors.white),
),
),
),
],
)
],
),
);
},
);
}
var tabController = new DefaultTabController(
length: 3,
child: new Scaffold(
appBar: new AppBar(
title: new TabBar(
labelPadding: EdgeInsets.all(2),
tabs: [
Tab(
text: "FREE-PICK",
),
Tab(
text: "ĐANG LÀM",
),
Tab(
text: "ĐÃ XONG",
),
],
labelStyle: TextStyle(fontWeight: FontWeight.bold),
),
actions: <Widget>[
FlatButton(
padding: EdgeInsets.all(0),
color: Colors.red,
onPressed: _showDialog,
child: Icon(
Icons.power_settings_new,
color: Colors.white,
)),
],
),
body: TabBarView(
children: [
model.state == ViewState.Busy
? Center(
child: CircularProgressIndicator(),
)
: TabFreePick(model),
Tab3(),
Tab4(),
],
physics: NeverScrollableScrollPhysics(),
),
));
return tabController;
}
}
class TabFreePick extends StatefulWidget {
final HomeViewModel model;
const TabFreePick(this.model);
@override
_TabFreePickState createState() => _TabFreePickState();
}
class _TabFreePickState extends State<TabFreePick> {
final Map<String, Marker> markers = <String, Marker>{};
Map<PolylineId, Polyline> _mapPolylines = <PolylineId, Polyline>{};
int _polylineIdCounter = 1;
GoogleMapController _mapController;
@override
void initState() {
super.initState();
_getLocation();
}
@override
Widget build(BuildContext context) {
return Container(
constraints: BoxConstraints.expand(),
child: Stack(
children: <Widget>[
GoogleMap(
onMapCreated: (GoogleMapController controller) {
_mapController = controller;
},
markers: Set<Marker>.of(markers.values),
polylines: Set<Polyline>.of(_mapPolylines.values),
mapType: MapType.normal,
initialCameraPosition: CameraPosition(
target: LatLng(21.0177511, 105.83147519999999),
zoom: 15,
)),
],
),
);
}
void _getLocation() {
setState(() {
markers.clear();
final marker = Marker(
markerId: MarkerId("curr_loc"),
position: LatLng(widget.model.location.lat, widget.model.location.lon),
infoWindow: InfoWindow(
title: 'Your Location ' +
"Lat: " +
widget.model.location.lat.toString() +
"; Lon: " +
widget.model.location.lon.toString()),
);
final marker2 = Marker(
onTap: showOrderAuto,
markerId: MarkerId("don_hang_1"),
position: LatLng(21.019358, 105.832817),
infoWindow: InfoWindow(title: 'Don hang 1'),
);
final marker3 = Marker(
onTap: showOrderSelect,
markerId: MarkerId("don_hang_2"),
position: LatLng(21.016364, 105.829983),
infoWindow: InfoWindow(title: 'Don hang tu chon 1'),
);
markers["Current Location"] = marker;
markers["Don hang tu dong"] = marker2;
markers["Don hang tu chon"] = marker3;
});
}
showOrderSelect(){
showGeneralDialog(
barrierLabel: "Label",
barrierDismissible: true,
barrierColor: Colors.black.withOpacity(0.5),
transitionDuration: Duration(milliseconds: 700),
context: context,
pageBuilder: (context, anim1, anim2) {
return Align(
alignment: Alignment.bottomCenter,
child: Container(
height: 300,
color: Colors.white,
margin: EdgeInsets.only(bottom: 50, left: 12, right: 12),
child: Column(
children: <Widget>[
Container(
child: Text("Delivery "),
alignment: AlignmentDirectional.topStart,
),
Row(
children: <Widget>[
],
),
],
),
),
);
},
transitionBuilder: (context, anim1, anim2, child) {
return SlideTransition(
position: Tween(begin: Offset(0, 1), end: Offset(0, 0)).animate(anim1),
child: child,
);
},
);
}
showOrderAuto() {
showDialog(
context: context,
builder: (BuildContext context) {
return customDialog.Dialog(
backgroundColor: Colors.transparent,
child: Column(
children: <Widget>[
Container(
alignment: AlignmentDirectional.bottomCenter,
height: ScreenUtil.getInstance().setHeight(100),
child: Text(
"Ship",
style: TextStyle(
fontSize: ScreenUtil.getInstance().setSp(18),
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
),
Container(
color: Colors.white,
margin: EdgeInsets.fromLTRB(0, 10, 0, 10),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Container(
child: Text(
"Gửi - Quán A Tũn",
style: TextStyle(
fontSize: ScreenUtil.getInstance().setSp(13),
color: Colors.grey),
),
margin: EdgeInsets.fromLTRB(20, 5, 5, 5),
alignment: AlignmentDirectional.topStart,
),
Container(
margin: EdgeInsets.fromLTRB(20, 5, 5, 5),
child: Text(
"Đối diện lô F1 khu đô thị, P. Nguyễn Cảnh Dị, Đại Từ, Hoàng Mai, Hà Nội, Vietnam",
style: TextStyle(
fontSize: ScreenUtil.getInstance().setSp(14),
color: Colors.black),
maxLines: 2,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.center,
),
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Container(
width: ScreenUtil.getInstance().setWidth(75),
height: ScreenUtil.getInstance().setHeight(30),
alignment: AlignmentDirectional.center,
margin: EdgeInsets.fromLTRB(25, 5, 5, 5),
decoration: BoxDecoration(
border: Border.all(
width: 1,
color: Colors.grey,
),
),
child: RichText(
text: TextSpan(
text: "Nhận: ",
style: TextStyle(
color: Colors.black,
fontSize:
ScreenUtil.getInstance().setSp(13)),
children: [
TextSpan(
text: "10:59",
style: TextStyle(
color: Colors.green,
fontWeight: FontWeight.bold,
fontSize: ScreenUtil.getInstance()
.setSp(13)))
]),
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Container(
width: ScreenUtil.getInstance().setWidth(125),
margin: EdgeInsets.fromLTRB(25, 5, 5, 5),
child: RichText(
text: TextSpan(
text: "Trả quán: ",
style: TextStyle(
color: Colors.black,
fontSize:
ScreenUtil.getInstance().setSp(13)),
children: [
TextSpan(
text: "10.000 đ",
style: TextStyle(
color: Colors.red,
fontWeight: FontWeight.bold,
fontSize: ScreenUtil.getInstance()
.setSp(13)))
]),
),
),
Container(
width: ScreenUtil.getInstance().setWidth(75),
height: ScreenUtil.getInstance().setHeight(30),
child: Image.asset(
"images/air-pay.png",
fit: BoxFit.contain,
),
),
],
),
Container(
child: Text(
"Nhận - A Tùng",
style: TextStyle(
fontSize: ScreenUtil.getInstance().setSp(13),
color: Colors.grey),
),
margin: EdgeInsets.fromLTRB(20, 5, 5, 5),
alignment: AlignmentDirectional.topStart,
),
Container(
margin: EdgeInsets.fromLTRB(20, 5, 5, 5),
child: Text(
"1277 Giải Phóng, Thịnh Liệt, Hoàng Mai, Hà Nội, Vietnam",
style: TextStyle(
fontSize: ScreenUtil.getInstance().setSp(14),
color: Colors.black),
maxLines: 2,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.center,
),
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Container(
width: ScreenUtil.getInstance().setWidth(150),
margin: EdgeInsets.fromLTRB(25, 5, 5, 5),
child: RichText(
text: TextSpan(
text: "Trả người nhận: ",
style: TextStyle(
color: Colors.black,
fontSize:
ScreenUtil.getInstance().setSp(13)),
children: [
TextSpan(
text: "30.000 đ",
style: TextStyle(
color: Colors.green,
fontWeight: FontWeight.bold,
fontSize: ScreenUtil.getInstance()
.setSp(13)))
]),
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Container(
color: Colors.grey[400],
width: ScreenUtil.getInstance().setWidth(110),
height: ScreenUtil.getInstance().setHeight(30),
margin: EdgeInsets.fromLTRB(25, 5, 5, 5),
alignment: AlignmentDirectional.center,
child: RichText(
text: TextSpan(
text: "4.5km - Phí: ",
style: TextStyle(
color: Colors.black,
fontSize:
ScreenUtil.getInstance().setSp(13)),
children: [
TextSpan(
text: "18k",
style: TextStyle(
color: Colors.green,
fontWeight: FontWeight.bold,
fontSize: ScreenUtil.getInstance()
.setSp(13)))
]),
),
),
Container(
width: ScreenUtil.getInstance().setWidth(75),
height: ScreenUtil.getInstance().setHeight(30),
margin: EdgeInsets.fromLTRB(25, 5, 5, 5),
alignment: AlignmentDirectional.center,
decoration: BoxDecoration(
border: Border.all(
width: 1,
color: Colors.grey,
),
),
child: RichText(
text: TextSpan(
text: "Nhận: ",
style: TextStyle(
color: Colors.black,
fontSize:
ScreenUtil.getInstance().setSp(13)),
children: [
TextSpan(
text: "10:59",
style: TextStyle(
color: Colors.green,
fontWeight: FontWeight.bold,
fontSize: ScreenUtil.getInstance()
.setSp(13)))
]),
),
),
Container(
color: Colors.red,
height: ScreenUtil.getInstance().setHeight(30),
width: ScreenUtil.getInstance().setWidth(50),
alignment: AlignmentDirectional.center,
margin: EdgeInsets.fromLTRB(25, 5, 5, 5),
child: Text(
"34'",
style: TextStyle(
fontSize: ScreenUtil.getInstance().setSp(16),
fontWeight: FontWeight.bold,
color: Colors.white),
),
),
],
),
],
),
),
Expanded(
child: Container(
),
),
Container(
child: SliderButton(
action: () {
///Do something here OnSlide
print("Nhan don");
Navigator.pop(context);
},
///Put label over here
label: Text(
"Nhận đơn",
style: TextStyle(
color: Color(0xff4a4a4a),
fontWeight: FontWeight.w500,
fontSize: ScreenUtil.getInstance().setSp(16)),
),
icon: Center(
child: Icon(
Icons.navigate_next,
color: Colors.black,
size: 40.0,
semanticLabel: 'Text to announce in accessibility modes',
)),
///Change All the color and size from here.
radius: 10,
buttonColor: Colors.white,
backgroundColor: Colors.blue[800],
highlightedColor: Colors.white,
baseColor: Colors.red,
width: 300,
),
)
],
),
);
});
}
}
class Clock24Example extends StatelessWidget {
final format = DateFormat("HH:mm");
@override
Widget build(BuildContext context) {
ScreenUtil.instance = ScreenUtil(width: 320, height: 568)..init(context);
return Column(children: <Widget>[
Container(
width: 95,
margin: EdgeInsets.fromLTRB(0, 0, 5, 0),
child: DateTimeField(
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: ScreenUtil.getInstance().setSp(14)),
textAlign: TextAlign.center,
decoration: InputDecoration(
contentPadding: EdgeInsets.all(0),
fillColor: Colors.red,
filled: true,
),
format: format,
resetIcon: null,
readOnly: true,
onShowPicker: (context, currentValue) async {
final time = await showTimePicker(
context: context,
initialTime:
TimeOfDay.fromDateTime(currentValue ?? DateTime.now()),
builder: (context, child) => MediaQuery(
data: MediaQuery.of(context)
.copyWith(alwaysUse24HourFormat: true),
child: child),
);
return DateTimeField.convert(time);
},
),
),
]);
}
}
| 39.367496
| 109
| 0.381992
|
2c726e26dbc634fe32ce8ee51e3229c60d158366
| 1,630
|
cpp
|
C++
|
src/lib/Micro-XRCE-DDS-Client/ucdr/test/FullBuffer.cpp
|
shaopengyuan/FMT-Firmware
|
bbdb3649ec4c1cad3d4a7fc3866091f99807fcfc
|
[
"Apache-2.0"
] | 72
|
2021-09-13T20:29:29.000Z
|
2022-03-30T01:42:09.000Z
|
src/lib/Micro-XRCE-DDS-Client/ucdr/test/FullBuffer.cpp
|
shaopengyuan/FMT-Firmware
|
bbdb3649ec4c1cad3d4a7fc3866091f99807fcfc
|
[
"Apache-2.0"
] | 33
|
2019-01-09T11:02:15.000Z
|
2022-03-31T11:47:54.000Z
|
src/lib/Micro-XRCE-DDS-Client/ucdr/test/FullBuffer.cpp
|
shaopengyuan/FMT-Firmware
|
bbdb3649ec4c1cad3d4a7fc3866091f99807fcfc
|
[
"Apache-2.0"
] | 35
|
2019-03-06T01:54:00.000Z
|
2022-02-03T07:06:37.000Z
|
// Copyright 2017 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "FullBuffer.hpp"
TEST_F(FullBuffer, Block_8)
{
fill_buffer_except(7);
try_block_8();
}
TEST_F(FullBuffer, Block_4)
{
fill_buffer_except(3);
try_block_4();
}
TEST_F(FullBuffer, Block_2)
{
fill_buffer_except(1);
try_block_2();
}
TEST_F(FullBuffer, Block_1)
{
fill_buffer_except(0);
try_block_1();
}
# define SUCCESSFUL_SERIALIZATION 3
# define ARRAY_SERIALIZATION (SUCCESSFUL_SERIALIZATION + 1)
TEST_F(FullBuffer, ArrayBlock_8)
{
fill_buffer_except(8 * SUCCESSFUL_SERIALIZATION + 7);
try_array_block_8(ARRAY_SERIALIZATION);
}
TEST_F(FullBuffer, ArrayBlock_4)
{
fill_buffer_except(4 * SUCCESSFUL_SERIALIZATION + 3);
try_array_block_4(ARRAY_SERIALIZATION);
}
TEST_F(FullBuffer, ArrayBlock_2)
{
fill_buffer_except(2 * SUCCESSFUL_SERIALIZATION + 1);
try_array_block_2(ARRAY_SERIALIZATION);
}
TEST_F(FullBuffer, ArrayBlock_1)
{
fill_buffer_except(SUCCESSFUL_SERIALIZATION);
try_array_block_1(ARRAY_SERIALIZATION);
}
| 24.328358
| 75
| 0.745399
|
6ca106d7d4f79fc8967bb4eda89b905d5df3652e
| 976
|
dart
|
Dart
|
do_quran/packages/do_core/lib/models/quran/surah.dart
|
ridlafadilah/do-quran
|
aabd70c794344aa1b0cea4898d22fca43dd8f285
|
[
"MIT"
] | 5
|
2021-04-11T18:58:42.000Z
|
2022-03-02T23:19:40.000Z
|
do_quran/packages/do_core/lib/models/quran/surah.dart
|
ridlafadilah/do-quran
|
aabd70c794344aa1b0cea4898d22fca43dd8f285
|
[
"MIT"
] | null | null | null |
do_quran/packages/do_core/lib/models/quran/surah.dart
|
ridlafadilah/do-quran
|
aabd70c794344aa1b0cea4898d22fca43dd8f285
|
[
"MIT"
] | 1
|
2021-04-19T02:49:03.000Z
|
2021-04-19T02:49:03.000Z
|
import 'package:do_core/models/quran/tafsir.dart';
import 'package:do_core/models/quran/translations.dart';
import 'package:json_annotation/json_annotation.dart';
part 'surah.g.dart';
@JsonSerializable()
class Surah {
Surah(
{this.number,
this.name,
this.nameLatin,
this.numberOfAyah,
this.text,
this.translations,
this.tafsir});
factory Surah.fromJson(Map<String, dynamic> json) => _$SurahFromJson(json);
Map<String, dynamic> toJson() => _$SurahToJson(this);
String number;
String name;
@JsonKey(name: 'name_latin')
String nameLatin;
@JsonKey(name: 'number_of_ayah')
String numberOfAyah;
Map<String, String> text;
Translations translations;
Tafsir tafsir;
@override
String toString() {
return '''
Surah : {${'number: $number, '}${'name: $name, '}${'nameLatin: $nameLatin, '}${'numberOfAyah: $numberOfAyah, '}${'text: $text, '}${'translations: $translations, '}${'tafsir: $tafsir, '}'}''';
}
}
| 25.684211
| 191
| 0.668033
|
3a77a5e891207bdf0eb98fdeb5c259ab9a8d2430
| 159
|
lua
|
Lua
|
Bindings.lua
|
Oppzippy/CopyAnything
|
218c9df754b05875f4285b69572d1186e940eb3e
|
[
"MIT"
] | null | null | null |
Bindings.lua
|
Oppzippy/CopyAnything
|
218c9df754b05875f4285b69572d1186e940eb3e
|
[
"MIT"
] | null | null | null |
Bindings.lua
|
Oppzippy/CopyAnything
|
218c9df754b05875f4285b69572d1186e940eb3e
|
[
"MIT"
] | null | null | null |
local L = LibStub("AceLocale-3.0"):GetLocale("CopyAnything")
_G["BINDING_HEADER_COPYANYTHING"] = L.copyAnything
_G["BINDING_NAME_COPYANYTHING_SHOW"] = L.show
| 31.8
| 60
| 0.779874
|
4557409d93487924a6ff35426f5092d794675038
| 3,659
|
py
|
Python
|
eval/run_hatespeech.py
|
jsandersen/MRTviaHIL
|
eaed679d014183b9b5bc4846db543c64e80592c8
|
[
"Apache-2.0"
] | null | null | null |
eval/run_hatespeech.py
|
jsandersen/MRTviaHIL
|
eaed679d014183b9b5bc4846db543c64e80592c8
|
[
"Apache-2.0"
] | null | null | null |
eval/run_hatespeech.py
|
jsandersen/MRTviaHIL
|
eaed679d014183b9b5bc4846db543c64e80592c8
|
[
"Apache-2.0"
] | null | null | null |
def main():
print('start ...')
print('hatespeech')
import logging
import os
import sys
import numpy as np
from tqdm import tqdm
import tensorflow.keras as tfk
cwd = os.getcwd()
sys.path.append(cwd + '/../.')
from src.util.data_loader import Dataset, load_data
from src.util.sbert_transformer import SbertSentenceMeanEncoder, SbertFullTextEncoder
from src.model.stats import predict, print_all_stats
from src.model.neural_networks import MLP
# load data
X, y = load_data(Dataset.HATE_SPEECH, './../labeled_data.csv')
X = None
# to binary
f = lambda x: 0 if x == 2 else x
y = list(map(f, y.tolist()))
y = np.array(y)
# load encoding
X_enc = np.load('./encodings/hatespeech_embeddings_full.npy')
X_enc = np.array(X_enc)
y = np.array(y)
print('Naive Bayes')
from sklearn.naive_bayes import GaussianNB
cls = GaussianNB
dfs = predict(cls, (X_enc), y, skl_model=True)
print_all_stats(dfs, 'hatespeech_gnb')
print('Logistic Regression')
from sklearn.linear_model import LogisticRegression
clf = LogisticRegression
model_args = {'random_state': 42, 'max_iter': 100}
dfs = predict(clf, X_enc, y, skl_model=True, **model_args)
print_all_stats(dfs, 'hatespeech_lr')
print('Random Forest Classifier')
from sklearn.ensemble import RandomForestClassifier
clf = RandomForestClassifier
model_args = {'n_estimators': 100, 'bootstrap': True, 'random_state': 42}
dfs = predict(clf, X_enc, y, skl_model=True, **model_args)
print_all_stats(dfs, 'hatespeech_rf')
from sklearn.neighbors import KNeighborsClassifier
print('K-Nearest Neighbors')
clf = KNeighborsClassifier
model_args = {'n_neighbors': 25}
dfs = predict(clf, X_enc, y, skl_model=True, **model_args)
print_all_stats(dfs, 'hatespeech_knn')
print('Suport Vector Machine')
from sklearn import svm
from src.model.wrapper import SklearnWrapper
clf = SklearnWrapper
model_args = {'Clf' : svm.SVC, 'kernel': 'linear', 'probability': True}
dfs = predict(clf, X_enc, y, skl_model=True, **model_args)
print_all_stats(dfs, 'hatespeech_svm')
print('Multi Layer Perceptron (TF)')
callback = tfk.callbacks.EarlyStopping(monitor='val_loss', patience=10, min_delta=0.0001)
model_args = {"input_shape": 768, "n_classes": 2, 'mcd':False, 'T':1, 'callbacks': [callback]}
dfs = predict(MLP, X_enc, y, batch_size=128, epochs=100, val=True, save='hatespeech', **model_args)
print_all_stats(dfs, 'hatespeech_mlp_tf')
print('Baysian Multi Layer Perceptron (TF)')
callback = tfk.callbacks.EarlyStopping(monitor='val_loss', patience=10, min_delta=0.0001)
model_args = {"input_shape": 768, "n_classes": 2, 'mcd':True, 'T':100, 'callbacks': [callback]}
dfs = predict(MLP, X_enc, y, batch_size=128, epochs=100, val=True, load='hatespeech', **model_args)
print_all_stats(dfs, 'hatespeech_bmlp_tf')
print('Multi Layer Perceptron (Sklearn)')
from sklearn.neural_network import MLPClassifier#
clf = MLPClassifier
model_args = {'random_state': 42, 'early_stopping': True, 'max_iter': 100, 'hidden_layer_sizes':(500, 500)}
dfs = predict(clf, X_enc, y, skl_model=True, **model_args)
print_all_stats(dfs, 'hatespeech_mlp')
print('Decision Tree Classifier')
from sklearn.tree import DecisionTreeClassifier
clf = DecisionTreeClassifier
model_args = {'random_state': 42}
dfs = predict(clf, X_enc, y, skl_model=True, **model_args)
print_all_stats(dfs, 'hatespeech_dt')
print('... end')
if __name__ == "__main__":
main()
| 36.227723
| 111
| 0.687346
|
4abcb944e9777004e52b4fe36355eb877afe219e
| 1,455
|
ps1
|
PowerShell
|
eng/publish/PublishNPMPackage.ps1
|
funkrider/interactive
|
17c8c613941f92915ef7eb3db734958fbc74db03
|
[
"MIT"
] | 1,712
|
2020-01-23T01:27:58.000Z
|
2022-03-31T22:07:10.000Z
|
eng/publish/PublishNPMPackage.ps1
|
funkrider/interactive
|
17c8c613941f92915ef7eb3db734958fbc74db03
|
[
"MIT"
] | 1,065
|
2020-01-22T23:20:05.000Z
|
2022-03-31T22:51:29.000Z
|
eng/publish/PublishNPMPackage.ps1
|
funkrider/interactive
|
17c8c613941f92915ef7eb3db734958fbc74db03
|
[
"MIT"
] | 267
|
2020-01-22T23:06:25.000Z
|
2022-03-25T07:42:09.000Z
|
[CmdletBinding(PositionalBinding = $false)]
param (
[string]$packageName,
[string]$registryUrl,
[string]$registryUser,
[string]$registryEmail,
[string]$currentBranch,
[string]$publishingBranch,
[string]$artifactDirectory,
[string]$registryPublishToken
)
Set-StrictMode -version 2.0
$ErrorActionPreference = "Stop"
try {
# create .npmrc with package feed
$registryPublishTokenBase64 = [Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($registryPublishToken))
$npmrcContents = "
; begin auth token
registry=https://$registryUrl
username=$registryUser
email=$registryEmail
_password=$registryPublishTokenBase64
_accessToken=$registryPublishToken
; end auth token"
$npmrcContents | Out-File "$artifactDirectory/.npmrc"
# publish to feed
if (($currentBranch -Eq $publishingBranch) -Or ($currentBranch -Eq "refs/heads/$publishingBranch")) {
$singlePackageName = Get-ChildItem "$artifactDirectory/$packageName" | Select-Object -First 1
Write-Host "Publishing $singlePackageName to $registryUrl"
npm publish "$singlePackageName" --access public
if ($LASTEXITCODE -ne 0) {
exit $LASTEXITCODE
}
}
else {
Write-Host "Branch '$currentBranch' does not match publishing branch '$publishingBranch', skipping publish."
}
}
catch {
Write-Host $_
Write-Host $_.Exception
Write-Host $_.ScriptStackTrace
exit 1
}
| 30.3125
| 122
| 0.704467
|
8ea66abd2e622879a2fe2df787dd49d548856693
| 511
|
js
|
JavaScript
|
tasks/grunt-csstree.js
|
gruntjs-updater/grunt-csstree
|
a1844eb22acc7359116ab1fa9bf1004a6512a2b2
|
[
"MIT"
] | null | null | null |
tasks/grunt-csstree.js
|
gruntjs-updater/grunt-csstree
|
a1844eb22acc7359116ab1fa9bf1004a6512a2b2
|
[
"MIT"
] | null | null | null |
tasks/grunt-csstree.js
|
gruntjs-updater/grunt-csstree
|
a1844eb22acc7359116ab1fa9bf1004a6512a2b2
|
[
"MIT"
] | null | null | null |
/*
* csstree
* https://github.com/apflieger/csstree
*
* Copyright (c) 2014 Arnaud Pflieger
* Licensed under the MIT license.
*/
'use strict';
var csstree = require('../lib/csstree')();
module.exports = function(grunt) {
grunt.registerMultiTask('csstree', 'Css files dependecies management.', function() {
var treeRoot = this.data.src;
grunt.log.write('Building tree ' + treeRoot + '...');
var tree = csstree.model(treeRoot);
csstree.generate(tree, this.options());
grunt.log.ok();
});
};
| 21.291667
| 85
| 0.667319
|
1a67eb1083fbcce160d6fb9b4f7083b0ef1d2e64
| 769
|
py
|
Python
|
users/users.py
|
TRUFA-rnaseq/trufa-users-ipa
|
1c0f050f05bdce9b6a2d480935dda5653b873ef5
|
[
"BSD-3-Clause"
] | null | null | null |
users/users.py
|
TRUFA-rnaseq/trufa-users-ipa
|
1c0f050f05bdce9b6a2d480935dda5653b873ef5
|
[
"BSD-3-Clause"
] | null | null | null |
users/users.py
|
TRUFA-rnaseq/trufa-users-ipa
|
1c0f050f05bdce9b6a2d480935dda5653b873ef5
|
[
"BSD-3-Clause"
] | null | null | null |
#-------------------------------------------------------------------------------
def checkUser( username, passwd ):
return False
#-------------------------------------------------------------------------------
def checkIfUserAvailable( username ):
return False
#-------------------------------------------------------------------------------
def getUserEmail( username ):
return None
#-------------------------------------------------------------------------------
def allowPasswordChange( username ):
return False
#-------------------------------------------------------------------------------
def changeUserPassword( username, oldpass, newpass ):
return False
#-------------------------------------------------------------------------------
| 34.954545
| 80
| 0.269181
|
811654a718e881e5ea4dedf21b86b7f1beb33bf3
| 191
|
asm
|
Assembly
|
core/words/qdup.asm
|
paulscottrobson/nextForth
|
3725af76cedd403e1e468fc8392e819fc0feb744
|
[
"MIT"
] | 2
|
2019-02-17T02:39:13.000Z
|
2020-06-10T09:57:22.000Z
|
core/words/qdup.asm
|
paulscottrobson/nextForth
|
3725af76cedd403e1e468fc8392e819fc0feb744
|
[
"MIT"
] | 1
|
2019-03-03T20:40:02.000Z
|
2020-07-02T09:39:48.000Z
|
core/words/qdup.asm
|
paulscottrobson/nextForth
|
3725af76cedd403e1e468fc8392e819fc0feb744
|
[
"MIT"
] | null | null | null |
;
; Word: ?dup
; Dictionary: (a - a) or (a - a b)
; Date: 1st February 2018
; Macro: Yes
; Notes:
;
pop ix
ld a,d
or e
jr z,__QDup
push de
__QDup:
jp (ix)
| 11.235294
| 36
| 0.486911
|
a36d7ec0d74dba4c1c8ba8f1e10a1707fc3fd337
| 1,942
|
java
|
Java
|
SXR/Extensions/3DCursor/IODevices/gearwear/PhoneSide/gearwearlibrary/src/main/java/com/samsungxr/io/gearwearlibrary/events/TouchMove.java
|
ejsamsung/sxrsdk
|
f8396eea87a1765bd7dfa6cc2184d5462ea723fe
|
[
"Apache-2.0"
] | 15
|
2018-10-24T19:46:44.000Z
|
2021-11-14T19:57:04.000Z
|
SXR/Extensions/3DCursor/IODevices/gearwear/PhoneSide/gearwearlibrary/src/main/java/com/samsungxr/io/gearwearlibrary/events/TouchMove.java
|
ejsamsung/sxrsdk
|
f8396eea87a1765bd7dfa6cc2184d5462ea723fe
|
[
"Apache-2.0"
] | 84
|
2018-10-25T15:55:49.000Z
|
2019-12-10T23:26:45.000Z
|
SXR/Extensions/3DCursor/IODevices/gearwear/PhoneSide/gearwearlibrary/src/main/java/com/samsungxr/io/gearwearlibrary/events/TouchMove.java
|
ejsamsung/sxrsdk
|
f8396eea87a1765bd7dfa6cc2184d5462ea723fe
|
[
"Apache-2.0"
] | 19
|
2018-10-26T20:44:33.000Z
|
2019-06-28T14:40:03.000Z
|
/*
* Copyright (c) 2016. Samsung Electronics Co., LTD
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.samsungxr.io.gearwearlibrary.events;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Occurs when user moves to a different touch area on the screen
*/
public class TouchMove implements Parcelable {
/**
* x-position
*/
public final int x;
/**
* y-position
*/
public final int y;
/**
* Create a touch move event
*
* @param x x-position
* @param y y-position
*/
public TouchMove(int x, int y) {
this.x = x;
this.y = y;
}
protected TouchMove(Parcel in) {
x = in.readInt();
y = in.readInt();
}
public static final Creator<TouchMove> CREATOR = new Creator<TouchMove>() {
@Override
public TouchMove createFromParcel(Parcel in) {
return new TouchMove(in);
}
@Override
public TouchMove[] newArray(int size) {
return new TouchMove[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(x);
dest.writeInt(y);
}
@Override
public String toString() {
return "TouchMove{" +
"x=" + x +
", y=" + y +
'}';
}
}
| 23.682927
| 79
| 0.597322
|
f48bbf91bb24341d791bf797c0cff3d3705dd770
| 213
|
ts
|
TypeScript
|
lib/client/with-screenshot.d.ts
|
kogai/zisui
|
265703bb7ce68fed8cc5d9b9ff02583392aa6cb2
|
[
"MIT"
] | null | null | null |
lib/client/with-screenshot.d.ts
|
kogai/zisui
|
265703bb7ce68fed8cc5d9b9ff02583392aa6cb2
|
[
"MIT"
] | null | null | null |
lib/client/with-screenshot.d.ts
|
kogai/zisui
|
265703bb7ce68fed8cc5d9b9ff02583392aa6cb2
|
[
"MIT"
] | null | null | null |
import { ScreenShotOptions } from "./types";
export interface WithScreenshot {
<T = Function>(options?: Partial<ScreenShotOptions>): T;
}
declare let withScreenshot: WithScreenshot;
export { withScreenshot };
| 30.428571
| 60
| 0.751174
|
3852887b5fc2768bc90394b531811210f02951e3
| 748
|
php
|
PHP
|
frontend-app-with-auth/src/Mod/Login/LoginView.php
|
infracamp/kickstart-skel
|
cb98bef721cc3b27cb65c6f97e0a3b620a689e96
|
[
"MIT"
] | null | null | null |
frontend-app-with-auth/src/Mod/Login/LoginView.php
|
infracamp/kickstart-skel
|
cb98bef721cc3b27cb65c6f97e0a3b620a689e96
|
[
"MIT"
] | null | null | null |
frontend-app-with-auth/src/Mod/Login/LoginView.php
|
infracamp/kickstart-skel
|
cb98bef721cc3b27cb65c6f97e0a3b620a689e96
|
[
"MIT"
] | 2
|
2018-10-01T10:52:20.000Z
|
2018-10-08T10:00:25.000Z
|
<?php
/**
* Created by PhpStorm.
* User: matthes
* Date: 09.07.18
* Time: 14:46
*/
namespace App\Mod\Login;
use HtmlTheme\Pack\CoreUI\CoreUi_Config_LoginPage;
use HtmlTheme\Pack\CoreUI\CoreUi_LoginPage;
use Phore\MicroApp\View\View;
class LoginView implements View
{
/**
* @var CoreUi_Config_LoginPage
*/
public $themeConfig;
public function __construct()
{
$c = $this->themeConfig = new CoreUi_Config_LoginPage();
$c->title = "Sign In";
$c->errorMsgHtml = null;
}
public function setErrorMsg($msg)
{
$this->themeConfig->errorMsgHtml = [$msg];
}
public function out()
{
app()->out((new CoreUi_LoginPage($this->themeConfig))->render());
}
}
| 17.809524
| 73
| 0.620321
|
b5713b7cdbb350075e21e896ef3f8c5bed5c91a9
| 468
|
rb
|
Ruby
|
c2s11/sportsball_version_gem/components/app_component/spec/models/app_component/game_spec.rb
|
yonyossef/cbra_book_code
|
8cfded8d7ebb69005928b7c45974a271c7f1393a
|
[
"MIT"
] | 24
|
2015-01-26T08:08:49.000Z
|
2021-08-22T04:36:07.000Z
|
c2s11/sportsball_version_gem/components/app_component/spec/models/app_component/game_spec.rb
|
yonyossef/cbra_book_code
|
8cfded8d7ebb69005928b7c45974a271c7f1393a
|
[
"MIT"
] | 1
|
2017-01-24T11:17:40.000Z
|
2019-01-28T17:07:24.000Z
|
c2s11/sportsball_version_gem/components/app_component/spec/models/app_component/game_spec.rb
|
yonyossef/cbra_book_code
|
8cfded8d7ebb69005928b7c45974a271c7f1393a
|
[
"MIT"
] | 3
|
2016-06-16T02:36:09.000Z
|
2021-08-23T20:01:48.000Z
|
RSpec.describe AppComponent::Game do
it { should validate_presence_of :date }
it { should validate_presence_of :location }
it { should validate_presence_of :first_team }
it { should validate_presence_of :second_team }
it { should validate_presence_of :winning_team }
it { should validate_presence_of :first_team_score }
it { should validate_presence_of :second_team_score }
it { should belong_to :first_team}
it { should belong_to :second_team}
end
| 36
| 55
| 0.775641
|
bb8e98479fe7a0a0e5d3be5d41b302d21337160b
| 13,528
|
cs
|
C#
|
Crash/Formats/Crash Formats/Zone/Entity.cs
|
Aedhen/CrashEdit
|
c9b35422aae40cbf7405efd06edffa1c289fd1ab
|
[
"MIT",
"BSD-3-Clause"
] | 60
|
2015-01-09T16:23:56.000Z
|
2018-06-21T20:45:53.000Z
|
Crash/Formats/Crash Formats/Zone/Entity.cs
|
Aedhen/CrashEdit
|
c9b35422aae40cbf7405efd06edffa1c289fd1ab
|
[
"MIT",
"BSD-3-Clause"
] | 122
|
2015-01-15T13:08:38.000Z
|
2018-05-31T18:49:40.000Z
|
Crash/Formats/Crash Formats/Zone/Entity.cs
|
Aedhen/CrashEdit
|
c9b35422aae40cbf7405efd06edffa1c289fd1ab
|
[
"MIT",
"BSD-3-Clause"
] | 14
|
2015-04-13T17:59:37.000Z
|
2018-05-28T07:30:58.000Z
|
using System;
using System.Reflection;
using System.Collections.Generic;
namespace Crash
{
public sealed class Entity
{
private static Dictionary<short,FieldInfo> propertyfields;
static Entity()
{
propertyfields = new Dictionary<short,FieldInfo>();
foreach (FieldInfo field in typeof(Entity).GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
{
foreach (EntityPropertyFieldAttribute attribute in field.GetCustomAttributes(typeof(EntityPropertyFieldAttribute),false))
{
propertyfields.Add(attribute.ID,field);
}
}
}
public static Entity Load(byte[] data)
{
if (data.Length < 16)
{
ErrorManager.SignalError("Entity: Data is too short");
}
int length = BitConv.FromInt32(data,0);
int propertycount = BitConv.FromInt32(data,12);
if (length != data.Length)
{
ErrorManager.SignalIgnorableError("Entity: Length field mismatch");
}
if (propertycount < 0 || propertycount > ushort.MaxValue)
{
ErrorManager.SignalError("Entity: Property count is invalid");
}
if (data.Length < 16 + propertycount * 8)
{
ErrorManager.SignalError("Entity: Data is too short");
}
Dictionary<short,EntityProperty> properties = new Dictionary<short,EntityProperty>();
for (int i = 0;i < propertycount;i++)
{
short id = BitConv.FromInt16(data,16 + i * 8);
int offset = (ushort)BitConv.FromInt16(data,18 + i * 8) + 12;
int nextoffset = (i == propertycount - 1) ? data.Length : ((ushort)BitConv.FromInt16(data,26 + i * 8) + 12);
byte type = data[20 + i * 8];
if (id == 0x103 && type == 0x13) type = 4; // force-fix a stupid bug
byte elementsize = data[21 + i * 8];
short unknown = BitConv.FromInt16(data,22 + i * 8);
if (offset > data.Length)
{
ErrorManager.SignalError("Entity: Property begins out of bounds");
}
if (nextoffset < offset)
{
ErrorManager.SignalError("Entity: Property ends before it begins");
}
if (nextoffset > data.Length)
{
ErrorManager.SignalError("Entity: Property ends out of bounds");
}
if (properties.ContainsKey(id))
{
ErrorManager.SignalIgnorableError("Entity: Duplicate property");
}
else
{
byte[] propertydata = new byte [nextoffset - offset];
Array.Copy(data,offset,propertydata,0,propertydata.Length);
EntityProperty property = EntityProperty.Load(type,elementsize,unknown,i == propertycount - 1,propertydata);
properties.Add(id,property);
}
}
return new Entity(properties);
}
//[EntityPropertyField(0x29)]
//private byte? mode;
//private int? mode;
[EntityPropertyField(0x2C)]
private string name;
[EntityPropertyField(0x32)]
private int? zmod;
[EntityPropertyField(0x4B)]
private List<EntityPosition> positions = null;
[EntityPropertyField(0x9F)]
private EntityID? id;
[EntityPropertyField(0xA4)]
private List<EntitySetting> settings = null;
[EntityPropertyField(0xA9)]
private int? type;
[EntityPropertyField(0xAA)]
private int? subtype;
[EntityPropertyField(0xC9)]
private EntitySetting? avgdist;
[EntityPropertyField(0x103)]
private EntityT4Property slst;
[EntityPropertyField(0x109)]
private EntityUInt32Property neighbors = null;
[EntityPropertyField(0x118)]
private int? othersettings = null;
[EntityPropertyField(0x130)]
private EntityVictimProperty fov = null;
[EntityPropertyField(0x13B)]
private EntityInt32Property drawlista = null;
[EntityPropertyField(0x13C)]
private EntityInt32Property drawlistb = null;
[EntityPropertyField(0x173)]
private int? cameraindex = null;
[EntityPropertyField(0x174)]
private int? camerasubindex = null;
[EntityPropertyField(0x208)]
private EntityT4Property loadlista = null;
[EntityPropertyField(0x209)]
private EntityT4Property loadlistb = null;
[EntityPropertyField(0x277)]
private int? ddasettings = null;
[EntityPropertyField(0x287)]
private List<EntityVictim> victims = null;
[EntityPropertyField(0x288)]
private int? ddasection = null;
[EntityPropertyField(0x28B)]
private EntitySetting? boxcount = null;
[EntityPropertyField(0x30E)]
private int? scaling = null;
[EntityPropertyField(0x336)]
private int? timetrialreward = null;
[EntityPropertyField(0x337)]
private EntitySetting? bonusboxcount = null;
private Dictionary<short,EntityProperty> extraproperties;
public Entity(IDictionary<short,EntityProperty> properties)
{
extraproperties = new Dictionary<short,EntityProperty>(properties);
foreach (KeyValuePair<short,FieldInfo> pair in propertyfields)
{
short id = pair.Key;
FieldInfo field = pair.Value;
if (field.FieldType.IsGenericType && field.FieldType.GetGenericTypeDefinition() == typeof(List<>))
{
field.SetValue(this,Activator.CreateInstance(field.FieldType));
}
else
{
field.SetValue(this,null);
}
if (extraproperties.ContainsKey(id))
{
EntityProperty property = extraproperties[id];
property.LoadToField(this,field);
extraproperties.Remove(id);
}
}
}
//public int? Mode
//{
// get => mode;
// set => mode = value;
//}
public string Name
{
get => name;
set => name = value;
}
public int? ZMod
{
get => zmod;
set => zmod = value;
}
public IList<EntityPosition> Positions => positions;
public int? ID
{
get => id.HasValue ? (int?)id.Value.ID : null;
set
{
if (value != null)
{
if (id.HasValue)
{
id = new EntityID(value.Value,id.Value.AlternateID);
}
else
{
id = new EntityID(value.Value);
}
}
else
{
if (id.HasValue && id.Value.AlternateID.HasValue)
{
throw new InvalidOperationException();
}
else
{
id = null;
}
}
}
}
public int? AlternateID
{
get => id.HasValue ? id.Value.AlternateID : null;
set
{
if (id != null)
{
id = new EntityID(id.Value.ID,value);
}
else
{
throw new InvalidOperationException();
}
}
}
public IList<EntitySetting> Settings => settings;
public int? Type
{
get => type;
set => type = value;
}
public int? Subtype
{
get => subtype;
set => subtype = value;
}
public EntitySetting? AverageDistance
{
get => avgdist;
set => avgdist = value;
}
public int? OtherSettings
{
get => othersettings;
set => othersettings = value;
}
public EntityVictimProperty FOV
{
get => fov;
set => fov = value;
}
public EntityInt32Property DrawListA
{
get => drawlista;
set => drawlista = value;
}
public EntityInt32Property DrawListB
{
get => drawlistb;
set => drawlistb = value;
}
public int? CameraIndex
{
get => cameraindex;
set => cameraindex = value;
}
public int? CameraSubIndex
{
get => camerasubindex;
set => camerasubindex = value;
}
public EntityT4Property SLST
{
get => slst;
set => slst = value;
}
public EntityUInt32Property Neighbors
{
get => neighbors;
set => neighbors = value;
}
public EntityT4Property LoadListA
{
get => loadlista;
set => loadlista = value;
}
public EntityT4Property LoadListB
{
get => loadlistb;
set => loadlistb = value;
}
public int? DDASettings
{
get => ddasettings;
set => ddasettings = value;
}
public List<EntityVictim> Victims => victims;
public int? DDASection
{
get => ddasection;
set => ddasection = value;
}
public EntitySetting? BoxCount
{
get => boxcount;
set => boxcount = value;
}
public int? Scaling
{
get => scaling;
set => scaling = value;
}
public int? TimeTrialReward
{
get => timetrialreward;
set => timetrialreward = value;
}
public EntitySetting? BonusBoxCount
{
get => bonusboxcount;
set => bonusboxcount = value;
}
public IDictionary<short,EntityProperty> ExtraProperties => extraproperties;
public byte[] Save()
{
if (LoadListA != null ^ LoadListB != null)
ErrorManager.SignalIgnorableError("Entity: Entity contains one load list but not the other");
if (DrawListA != null ^ DrawListB != null)
ErrorManager.SignalIgnorableError("Entity: Entity contains one draw list but not the other");
SortedDictionary<short,EntityProperty> properties = new SortedDictionary<short,EntityProperty>(extraproperties);
foreach (KeyValuePair<short,FieldInfo> pair in propertyfields)
{
short id = pair.Key;
FieldInfo field = pair.Value;
EntityProperty property = EntityProperty.LoadFromField(field.GetValue(this));
if (property != null)
{
properties.Add(id,property);
}
}
byte[] header = new byte [16 + 8 * properties.Count];
List<byte> result = new List<byte>();
int i = 0;
int offset = header.Length - 12;
foreach (KeyValuePair<short,EntityProperty> pair in properties)
{
EntityProperty property = pair.Value;
BitConv.ToInt16(header,16 + 8 * i + 0,pair.Key);
unchecked
{
BitConv.ToInt16(header,16 + 8 * i + 2,(short)offset);
}
header[16 + 8 * i + 4] = (byte)(property.Type | ((i == properties.Count - 1) ? 128 : 0) | (property.IsSparse ? 64 : 0) | (property.HasMetaValues ? 32 : 0));
header[16 + 8 * i + 5] = property.ElementSize;
BitConv.ToInt16(header,16 + 8 * i + 6,property.RowCount);
byte[] propertydata = property.Save();
i++;
offset += propertydata.Length;
result.AddRange(propertydata);
}
BitConv.ToInt32(header,0,offset + 12);
BitConv.ToInt32(header,4,0);
BitConv.ToInt32(header,8,0);
BitConv.ToInt32(header,12,properties.Count);
result.InsertRange(0,header);
return result.ToArray();
}
[AttributeUsage(AttributeTargets.Field)]
private class EntityPropertyFieldAttribute : Attribute
{
public EntityPropertyFieldAttribute(short id)
{
ID = id;
}
public short ID { get; }
}
}
}
| 33.568238
| 173
| 0.486473
|
699418e142e9673e1f353293c2797751a1ccec99
| 3,171
|
swift
|
Swift
|
QvikNetwork/Download.swift
|
qvik/qvik-network-ios
|
69bf2ee4bc61cdd1621dd0f99cbd6dd0a4726d1a
|
[
"MIT"
] | 1
|
2016-06-20T13:37:28.000Z
|
2016-06-20T13:37:28.000Z
|
QvikNetwork/Download.swift
|
qvik/qvik-network-ios
|
69bf2ee4bc61cdd1621dd0f99cbd6dd0a4726d1a
|
[
"MIT"
] | null | null | null |
QvikNetwork/Download.swift
|
qvik/qvik-network-ios
|
69bf2ee4bc61cdd1621dd0f99cbd6dd0a4726d1a
|
[
"MIT"
] | 5
|
2016-09-16T09:45:33.000Z
|
2019-05-03T10:27:54.000Z
|
// The MIT License (MIT)
//
// Copyright (c) 2015-2016 Qvik (www.qvik.fi)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
public func == (lhs: Download, rhs: Download) -> Bool {
return lhs === rhs
}
/**
A single download handle.
Do not create Download objects directly but instead through a DownloadManager/DownloadGroup instances.
All callbacks are called on the main (UI) thread (main queue).
All the methods in this class are thread safe.
*/
open class Download: Equatable {
public enum State {
case notInitialized
case starting
case inProgress
case failed
case completed
}
public enum Errors: Error {
case badResponse(statusCode: Int)
}
/// Download progress callback
open var progressCallback: DownloadProgressCallback?
/// Download completion callback
open var completionCallback: DownloadCompletionCallback?
/// Arbitrary user data for use by the caller
open var userData: AnyObject?
/// URL of this download
fileprivate(set) open var url: String
/// Download group of this download or nil if single download
internal(set) open var group: DownloadGroup?
/// State of this download
internal(set) open var state: State
/// Number of bytes downloaded
internal(set) open var bytesDownloaded: UInt64
/// Total size of the download
internal(set) open var totalSize: UInt64?
/// The Content-Type of this download. Set upon completion.
internal(set) open var contentType: String?
/// Error that occurred while downloading or nil if none
internal(set) open var error: Error?
init(url: String) {
self.url = url
self.state = .notInitialized
self.bytesDownloaded = 0
}
}
extension Download: CustomDebugStringConvertible {
public var debugDescription: String {
return "Download(url: \(self.url), state: \(state))"
}
}
extension Download: CustomStringConvertible {
public var description: String {
return "Download(url: \(self.url), state: \(state))"
}
}
| 32.030303
| 103
| 0.699149
|
4419d04b782dbce9b8ca67f5f5fcda1ac19db0b1
| 2,578
|
py
|
Python
|
src/test/testables/subsystems.py
|
Netortech/scrap-worker
|
eecd553b9726f5bc3329013823019b828640fd6f
|
[
"Apache-2.0"
] | null | null | null |
src/test/testables/subsystems.py
|
Netortech/scrap-worker
|
eecd553b9726f5bc3329013823019b828640fd6f
|
[
"Apache-2.0"
] | null | null | null |
src/test/testables/subsystems.py
|
Netortech/scrap-worker
|
eecd553b9726f5bc3329013823019b828640fd6f
|
[
"Apache-2.0"
] | null | null | null |
from __future__ import annotations
from ...scrap_worker.subsystems import (
HeartbeatSubsystem,
ElectionSubsystem,
QuellUprisingSubsystem,
UnionAttendanceSubsystem,
UnionLeadershipSubsystem,
UnionMembershipSubsystem,
WorkloadPreprocessorSubsystem,
)
from ..mocks.kafka import KafkaProducerBaseMock, KafkaConsumerBaseMock
class ElectionSubsystemTestable(ElectionSubsystem):
def _set_mock_producer(
self, producer: KafkaProducerBaseMock
) -> ElectionSubsystemTestable:
self.__TESTING_producer = producer
return self
def _configure_producer(self) -> KafkaProducerBaseMock:
return self.__TESTING_producer
def _set_mock_consumer(
self, consumer: KafkaConsumerBaseMock
) -> ElectionSubsystemTestable:
self.__TESTING_consumer = consumer
return self
def _configure_consumer(self) -> KafkaConsumerBaseMock:
return self.__TESTING_consumer
class HeartbeatSubsystemTestable(HeartbeatSubsystem):
def _set_mock_producer(
self, producer: KafkaProducerBaseMock
) -> HeartbeatSubsystemTestable:
self.__TESTING_producer = producer
def _configure_producer(self) -> KafkaProducerBaseMock:
return self.__TESTING_producer
class QuellUprisingSubsystemTestable(QuellUprisingSubsystem):
def _set_mock_producer(
self, producer: KafkaProducerBaseMock
) -> QuellUprisingSubsystemTestable:
self.__TESTING_producer = producer
return self
def _configure_producer(self) -> KafkaProducerBaseMock:
return self.__TESTING_producer
def _set_mock_consumer(
self, consumer: KafkaConsumerBaseMock
) -> QuellUprisingSubsystemTestable:
self.__TESTING_consumer = consumer
return self
def _configure_consumer(self) -> KafkaConsumerBaseMock:
return self.__TESTING_consumer
class UnionAttendanceSubsystemTestable(UnionAttendanceSubsystem):
def _set_mock_consumer(
self, consumer: KafkaConsumerBaseMock
) -> UnionAttendanceSubsystemTestable:
self.__TESTING_consumer = consumer
return self
def _configure_consumer(self) -> KafkaConsumerBaseMock:
return self.__TESTING_consumer
class UnionMembershipSubsystemTestable(UnionMembershipSubsystem):
def _set_mock_consumer(
self, consumer: KafkaConsumerBaseMock
) -> UnionMembershipSubsystemTestable:
self.__TESTING_consumer = consumer
return self
def _configure_consumer(self) -> KafkaConsumerBaseMock:
return self.__TESTING_consumer
| 30.329412
| 70
| 0.74903
|
390260402fabf499c2918da385e31f423df8eda6
| 1,259
|
py
|
Python
|
app.py
|
QuarKUS7/which-tram
|
768df4a8f9d6e20ec3787ca95e18da8d7b0b38fa
|
[
"Apache-2.0"
] | null | null | null |
app.py
|
QuarKUS7/which-tram
|
768df4a8f9d6e20ec3787ca95e18da8d7b0b38fa
|
[
"Apache-2.0"
] | null | null | null |
app.py
|
QuarKUS7/which-tram
|
768df4a8f9d6e20ec3787ca95e18da8d7b0b38fa
|
[
"Apache-2.0"
] | null | null | null |
from flask import Flask, render_template
from api import set_chromium, get_times, set_driver
import datetime
import os
app = Flask(__name__)
@app.route("/")
def hello():
message = find_direction()
return render_template('index.html', message=message)
def find_direction():
options = set_chromium()
now = datetime.datetime.now()
# give 9 minutes for walking to Masarykovo nard.
now_mas = now + datetime.timedelta(hours=2, minutes = 9)
now_mas = now_mas.strftime('%H:%M')
# give 7 minutes for walking to Masarykovo nard.
now_bil = now + datetime.timedelta(hours=2, minutes = 7)
now_bil = now_bil.strftime('%H:%M')
MASAR = 'Masarykovo nádraží'
BILA = 'Bílá labuť'
ARRIVAl = 'Letenské náměstí'
mas = get_times(now_mas, MASAR, ARRIVAl, options)
bil = get_times(now_bil, BILA, ARRIVAl, options)
if type(mas) == str:
return mas
if type(bil) == str:
return bil
if mas < bil:
return "Chod na Masaryckovo nadrazi: {:d}:{:02d}".format(mas.time().hour, mas.time().minute)
else:
return "Chod na Bielu labut: {:d}:{:02d}".format(bil.time().hour, bil.time().minute)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=os.environ.get('PORT', 5000))
| 29.27907
| 100
| 0.654488
|
14165414801a80d7cb10e098b38e1e2b62179268
| 1,285
|
tsx
|
TypeScript
|
src/DatePicker/__tests__/DatePicker.test.tsx
|
ericadamski/operational-ui
|
339802e36512617469126b43e202eb409fe41dcd
|
[
"MIT"
] | 1
|
2020-09-30T05:26:38.000Z
|
2020-09-30T05:26:38.000Z
|
src/DatePicker/__tests__/DatePicker.test.tsx
|
ericadamski/operational-ui
|
339802e36512617469126b43e202eb409fe41dcd
|
[
"MIT"
] | null | null | null |
src/DatePicker/__tests__/DatePicker.test.tsx
|
ericadamski/operational-ui
|
339802e36512617469126b43e202eb409fe41dcd
|
[
"MIT"
] | null | null | null |
import { render } from "enzyme"
import * as React from "react"
import { changeMonth, toYearMonthDay } from "../../DatePicker/DatePicker.utils"
import { DatePicker as ThemelessDatePicker } from "../../index"
import wrapDefaultTheme from "../../utils/wrap-default-theme"
const DatePicker = wrapDefaultTheme(ThemelessDatePicker)
describe("DatePicker Component", () => {
it("Should render", () => {
const renderedComponent = render(<DatePicker start="2018-01-02" end="2018-01-23" placeholder="Pick a date" />)
expect(renderedComponent).toMatchSnapshot()
})
it("Converts date string to a structured year-month-day object", () => {
expect(toYearMonthDay("2018-01-01").year).toEqual(2018)
expect(toYearMonthDay("2018-01-01").month).toEqual(0)
expect(toYearMonthDay("2018-01-01").day).toEqual(0)
})
it("Changes the current month", () => {
expect(changeMonth(2, { year: 2018, month: 2 })).toEqual({ year: 2018, month: 4 })
})
it("Changes the current month, going into the next year", () => {
expect(changeMonth(2, { year: 2018, month: 10 })).toEqual({ year: 2019, month: 0 })
})
it("Changes the current month, going into the previous year", () => {
expect(changeMonth(-1, { year: 2018, month: 0 })).toEqual({ year: 2017, month: 11 })
})
})
| 44.310345
| 114
| 0.668482
|
da724453ea8bae11e0352b21b255488dc3c3bb92
| 18,391
|
php
|
PHP
|
app/Plugin/Paszport/Vendor/oauth2-php/tests/OAuth2Test.php
|
epforgpl/_mojePanstwo-Portal
|
81746d61f19db3961f9eba505a557072266a78f3
|
[
"MIT"
] | 46
|
2015-01-05T13:27:02.000Z
|
2021-11-08T11:21:25.000Z
|
app/Plugin/Paszport/Vendor/oauth2-php/tests/OAuth2Test.php
|
epforgpl/_mojePanstwo-Portal
|
81746d61f19db3961f9eba505a557072266a78f3
|
[
"MIT"
] | 521
|
2015-01-02T18:03:00.000Z
|
2020-10-19T12:35:58.000Z
|
app/Plugin/Paszport/Vendor/oauth2-php/tests/OAuth2Test.php
|
epforgpl/_mojePanstwo-Portal
|
81746d61f19db3961f9eba505a557072266a78f3
|
[
"MIT"
] | 11
|
2015-01-09T22:30:55.000Z
|
2018-08-21T12:37:15.000Z
|
<?php
require __DIR__ . '/../lib/OAuth2.php';
require __DIR__ . '/../lib/IOAuth2Storage.php';
require __DIR__ . '/../lib/IOAuth2GrantCode.php';
/**
* OAuth2 test case.
*/
class OAuth2Test extends PHPUnit_Framework_TestCase
{
/**
* @var OAuth2
*/
private $fixture;
/**
* The actual token ID is irrelevant, so choose one:
* @var string
*/
private $tokenId = 'my_token';
/**
* Tests OAuth2->verifyAccessToken() with a missing token
*/
public function testVerifyAccessTokenWithNoParam()
{
$mockStorage = $this->getMock('IOAuth2Storage');
$this->fixture = new OAuth2($mockStorage);
$scope = null;
$this->setExpectedException('OAuth2AuthenticateException');
$this->fixture->verifyAccessToken('', $scope);
}
/**
* Tests OAuth2->verifyAccessToken() with a invalid token
*/
public function testVerifyAccessTokenInvalidToken()
{
// Set up the mock storage to say this token does not exist
$mockStorage = $this->getMock('IOAuth2Storage');
$mockStorage->expects($this->once())
->method('getAccessToken')
->will($this->returnValue(false));
$this->fixture = new OAuth2($mockStorage);
$scope = null;
$this->setExpectedException('OAuth2AuthenticateException');
$this->fixture->verifyAccessToken($this->tokenId, $scope);
}
/**
* Tests OAuth2->verifyAccessToken() with a malformed token
*
* @dataProvider generateMalformedTokens
*/
public function testVerifyAccessTokenMalformedToken($token)
{
// Set up the mock storage to say this token does not exist
$mockStorage = $this->getMock('IOAuth2Storage');
$mockStorage->expects($this->once())
->method('getAccessToken')
->will($this->returnValue($token));
$this->fixture = new OAuth2($mockStorage);
$scope = null;
$this->setExpectedException('OAuth2AuthenticateException');
$this->fixture->verifyAccessToken($this->tokenId, $scope);
}
/**
* Tests OAuth2->verifyAccessToken() with different expiry dates
*
* @dataProvider generateExpiryTokens
*/
public function testVerifyAccessTokenCheckExpiry($token, $expectedToPass)
{
// Set up the mock storage to say this token does not exist
$mockStorage = $this->getMock('IOAuth2Storage');
$mockStorage->expects($this->once())
->method('getAccessToken')
->will($this->returnValue($token));
$this->fixture = new OAuth2($mockStorage);
$scope = null;
// When valid, we just want any sort of token
if ($expectedToPass) {
$actual = $this->fixture->verifyAccessToken($this->tokenId, $scope);
$this->assertNotEmpty($actual, "verifyAccessToken() was expected to PASS, but it failed");
$this->assertInternalType('array', $actual);
} else {
$this->setExpectedException('OAuth2AuthenticateException');
$this->fixture->verifyAccessToken($this->tokenId, $scope);
}
}
/**
* Tests OAuth2->verifyAccessToken() with different scopes
*
* @dataProvider generateScopes
*/
public function testVerifyAccessTokenCheckScope($scopeRequired, $token, $expectedToPass)
{
// Set up the mock storage to say this token does not exist
$mockStorage = $this->getMock('IOAuth2Storage');
$mockStorage->expects($this->once())
->method('getAccessToken')
->will($this->returnValue($token));
$this->fixture = new OAuth2($mockStorage);
// When valid, we just want any sort of token
if ($expectedToPass) {
$actual = $this->fixture->verifyAccessToken($this->tokenId, $scopeRequired);
$this->assertNotEmpty($actual, "verifyAccessToken() was expected to PASS, but it failed");
$this->assertInternalType('array', $actual);
} else {
$this->setExpectedException('OAuth2AuthenticateException');
$this->fixture->verifyAccessToken($this->tokenId, $scopeRequired);
}
}
/**
* Tests OAuth2->grantAccessToken() for missing data
*
* @dataProvider generateEmptyDataForGrant
*/
public function testGrantAccessTokenMissingData($inputData, $authHeaders)
{
$mockStorage = $this->getMock('IOAuth2Storage');
$this->fixture = new OAuth2($mockStorage);
$this->setExpectedException('OAuth2ServerException');
$this->fixture->grantAccessToken($inputData, $authHeaders);
}
/**
* Tests OAuth2->grantAccessToken()
*
* Tests the different ways client credentials can be provided.
*/
public function testGrantAccessTokenCheckClientCredentials()
{
$mockStorage = $this->getMock('IOAuth2Storage');
$mockStorage->expects($this->any())
->method('checkClientCredentials')
->will($this->returnValue(true)); // Always return true for any combination of user/pass
$this->fixture = new OAuth2($mockStorage);
$inputData = array('grant_type' => OAuth2::GRANT_TYPE_AUTH_CODE);
$authHeaders = array();
// First, confirm that an non-client related error is thrown:
try {
$this->fixture->grantAccessToken($inputData, $authHeaders);
$this->fail('The expected exception OAuth2ServerException was not thrown');
} catch (OAuth2ServerException $e) {
$this->assertEquals(OAuth2::ERROR_INVALID_CLIENT, $e->getMessage());
}
// Confirm Auth header
$authHeaders = array('PHP_AUTH_USER' => 'dev-abc', 'PHP_AUTH_PW' => 'pass');
$inputData = array(
'grant_type' => OAuth2::GRANT_TYPE_AUTH_CODE,
'client_id' => 'dev-abc'
); // When using auth, client_id must match
try {
$this->fixture->grantAccessToken($inputData, $authHeaders);
$this->fail('The expected exception OAuth2ServerException was not thrown');
} catch (OAuth2ServerException $e) {
$this->assertNotEquals(OAuth2::ERROR_INVALID_CLIENT, $e->getMessage());
}
// Confirm GET/POST
$authHeaders = array();
$inputData = array(
'grant_type' => OAuth2::GRANT_TYPE_AUTH_CODE,
'client_id' => 'dev-abc',
'client_secret' => 'foo'
); // When using auth, client_id must match
try {
$this->fixture->grantAccessToken($inputData, $authHeaders);
$this->fail('The expected exception OAuth2ServerException was not thrown');
} catch (OAuth2ServerException $e) {
$this->assertNotEquals(OAuth2::ERROR_INVALID_CLIENT, $e->getMessage());
}
}
/**
* Tests OAuth2->grantAccessToken() with Auth code grant
*
*/
public function testGrantAccessTokenWithGrantAuthCodeMandatoryParams()
{
$mockStorage = $this->createBaseMock('IOAuth2GrantCode');
$inputData = array(
'grant_type' => OAuth2::GRANT_TYPE_AUTH_CODE,
'client_id' => 'a',
'client_secret' => 'b'
);
$fakeAuthCode = array(
'client_id' => $inputData['client_id'],
'redirect_uri' => '/foo',
'expires' => time() + 60
);
$fakeAccessToken = array('access_token' => 'abcde');
// Ensure redirect URI and auth-code is mandatory
try {
$this->fixture = new OAuth2($mockStorage);
$this->fixture->setVariable(OAuth2::CONFIG_ENFORCE_INPUT_REDIRECT, true); // Only required when this is set
$this->fixture->grantAccessToken($inputData + array('code' => 'foo'), array());
$this->fail('The expected exception OAuth2ServerException was not thrown');
} catch (OAuth2ServerException $e) {
$this->assertEquals(OAuth2::ERROR_INVALID_REQUEST, $e->getMessage());
}
try {
$this->fixture = new OAuth2($mockStorage);
$this->fixture->grantAccessToken($inputData + array('redirect_uri' => 'foo'), array());
$this->fail('The expected exception OAuth2ServerException was not thrown');
} catch (OAuth2ServerException $e) {
$this->assertEquals(OAuth2::ERROR_INVALID_REQUEST, $e->getMessage());
}
}
/**
*
* @param string $interfaceName
*/
protected function createBaseMock($interfaceName)
{
$mockStorage = $this->getMock($interfaceName);
$mockStorage->expects($this->any())
->method('checkClientCredentials')
->will($this->returnValue(true)); // Always return true for any combination of user/pass
$mockStorage->expects($this->any())
->method('checkRestrictedGrantType')
->will($this->returnValue(true)); // Always return true for any combination of user/pass
return $mockStorage;
}
/**
* Tests OAuth2->grantAccessToken() with Auth code grant
*
*/
public function testGrantAccessTokenWithGrantAuthCodeNoToken()
{
$mockStorage = $this->createBaseMock('IOAuth2GrantCode');
$inputData = array(
'grant_type' => OAuth2::GRANT_TYPE_AUTH_CODE,
'client_id' => 'a',
'client_secret' => 'b',
'redirect_uri' => 'foo',
'code' => 'foo'
);
// Ensure missing auth code raises an error
try {
$this->fixture = new OAuth2($mockStorage);
$this->fixture->grantAccessToken($inputData + array(), array());
$this->fail('The expected exception OAuth2ServerException was not thrown');
} catch (OAuth2ServerException $e) {
$this->assertEquals(OAuth2::ERROR_INVALID_GRANT, $e->getMessage());
}
}
/**
* Tests OAuth2->grantAccessToken() with checks the redirect URI
*
*/
public function testGrantAccessTokenWithGrantAuthCodeRedirectChecked()
{
$inputData = array(
'redirect_uri' => 'http://www.crossdomain.com/my/subdir',
'grant_type' => OAuth2::GRANT_TYPE_AUTH_CODE,
'client_id' => 'my_little_app',
'client_secret' => 'b',
'code' => 'foo'
);
$storedToken = array(
'redirect_uri' => 'http://www.example.com',
'client_id' => 'my_little_app',
'expires' => time() + 60
);
$mockStorage = $this->createBaseMock('IOAuth2GrantCode');
$mockStorage->expects($this->any())
->method('getAuthCode')
->will($this->returnValue($storedToken));
// Ensure that the redirect_uri is checked
try {
$this->fixture = new OAuth2($mockStorage);
$this->fixture->grantAccessToken($inputData, array());
$this->fail('The expected exception OAuth2ServerException was not thrown');
} catch (OAuth2ServerException $e) {
$this->assertEquals(OAuth2::ERROR_REDIRECT_URI_MISMATCH, $e->getMessage());
}
}
/**
* Tests OAuth2->grantAccessToken() with checks the client ID is matched
*
*/
public function testGrantAccessTokenWithGrantAuthCodeClientIdChecked()
{
$inputData = array(
'client_id' => 'another_app',
'grant_type' => OAuth2::GRANT_TYPE_AUTH_CODE,
'redirect_uri' => 'http://www.example.com/my/subdir',
'client_secret' => 'b',
'code' => 'foo'
);
$storedToken = array(
'client_id' => 'my_little_app',
'redirect_uri' => 'http://www.example.com',
'expires' => time() + 60
);
$mockStorage = $this->createBaseMock('IOAuth2GrantCode');
$mockStorage->expects($this->any())
->method('getAuthCode')
->will($this->returnValue($storedToken));
// Ensure the client ID is checked
try {
$this->fixture = new OAuth2($mockStorage);
$this->fixture->grantAccessToken($inputData, array());
$this->fail('The expected exception OAuth2ServerException was not thrown');
} catch (OAuth2ServerException $e) {
$this->assertEquals(OAuth2::ERROR_INVALID_GRANT, $e->getMessage());
}
}
/**
* Tests OAuth2->grantAccessToken() with implicit
*
*/
public function testGrantAccessTokenWithGrantImplicit()
{
$this->markTestIncomplete("grantAccessToken test not implemented");
$this->fixture->grantAccessToken( /* parameters */);
}
/**
* Tests OAuth2->grantAccessToken() with user credentials
*
*/
public function testGrantAccessTokenWithGrantUser()
{
$this->markTestIncomplete("grantAccessToken test not implemented");
$this->fixture->grantAccessToken( /* parameters */);
}
/**
* Tests OAuth2->grantAccessToken() with client credentials
*
*/
public function testGrantAccessTokenWithGrantClient()
{
$this->markTestIncomplete("grantAccessToken test not implemented");
$this->fixture->grantAccessToken( /* parameters */);
}
/**
* Tests OAuth2->grantAccessToken() with refresh token
*
*/
public function testGrantAccessTokenWithGrantRefresh()
{
$this->markTestIncomplete("grantAccessToken test not implemented");
$this->fixture->grantAccessToken( /* parameters */);
}
/**
* Tests OAuth2->grantAccessToken() with extension
*
*/
public function testGrantAccessTokenWithGrantExtension()
{
$this->markTestIncomplete("grantAccessToken test not implemented");
$this->fixture->grantAccessToken( /* parameters */);
}
/**
* Tests OAuth2->getAuthorizeParams()
*/
public function testGetAuthorizeParams()
{
// TODO Auto-generated OAuth2Test->testGetAuthorizeParams()
$this->markTestIncomplete("getAuthorizeParams test not implemented");
$this->fixture->getAuthorizeParams( /* parameters */);
}
// Utility methods
/**
* Tests OAuth2->finishClientAuthorization()
*/
public function testFinishClientAuthorization()
{
// TODO Auto-generated OAuth2Test->testFinishClientAuthorization()
$this->markTestIncomplete("finishClientAuthorization test not implemented");
$this->fixture->finishClientAuthorization( /* parameters */);
}
// Data Providers below:
/**
* Dataprovider for testVerifyAccessTokenMalformedToken().
*
* Produces malformed access tokens
*/
public function generateMalformedTokens()
{
return array(
array(array()), // an empty array as a token
array(array('expires' => 5)), // missing client_id
array(array('client_id' => 6)), // missing expires
array(array('something' => 6)), // missing both 'expires' and 'client_id'
);
}
/**
* Dataprovider for testVerifyAccessTokenCheckExpiry().
*
* Produces malformed access tokens
*/
public function generateExpiryTokens()
{
return array(
array(array('client_id' => 'blah', 'expires' => time() - 30), false),
// 30 seconds ago should fail
array(array('client_id' => 'blah', 'expires' => time() - 1), false),
// now-ish should fail
array(array('client_id' => 'blah', 'expires' => 0), false),
// 1970 should fail
array(array('client_id' => 'blah', 'expires' => time() + 30), true),
// 30 seconds in the future should be valid
array(array('client_id' => 'blah', 'expires' => time() + 86400), true),
// 1 day in the future should be valid
array(array('client_id' => 'blah', 'expires' => time() + (365 * 86400)), true),
// 1 year should be valid
array(array('client_id' => 'blah', 'expires' => time() + (10 * 365 * 86400)), true),
// 10 years should be valid
);
}
/**
* Dataprovider for testVerifyAccessTokenCheckExpiry().
*
* Produces malformed access tokens
*/
public function generateScopes()
{
$baseToken = array('client_id' => 'blah', 'expires' => time() + 60);
return array(
array(null, $baseToken + array(), true), // missing scope is valif
array(null, $baseToken + array('scope' => null), true), // null scope is valid
array('', $baseToken + array('scope' => ''), true), // empty scope is valid
array('read', $baseToken + array('scope' => 'read'), true), // exact same scope is valid
array('read', $baseToken + array('scope' => ' read '), true), // exact same scope is valid
array(' read ', $baseToken + array('scope' => 'read'), true), // exact same scope is valid
array('read', $baseToken + array('scope' => 'read write delete'), true), // contains scope
array('read', $baseToken + array('scope' => 'write read delete'), true), // contains scope
array('read', $baseToken + array('scope' => 'delete write read'), true), // contains scope
// Invalid combinations
array('read', $baseToken + array('scope' => 'write'), false),
array('read', $baseToken + array('scope' => 'apple banana'), false),
array('read', $baseToken + array('scope' => 'apple read-write'), false),
array('read', $baseToken + array('scope' => 'apple read,write'), false),
array('read', $baseToken + array('scope' => null), false),
array('read', $baseToken + array('scope' => ''), false),
);
}
/**
* Provider for OAuth2->grantAccessToken()
*/
public function generateEmptyDataForGrant()
{
return array(
array(
array(),
array()
),
array(
array(),
array('grant_type' => OAuth2::GRANT_TYPE_AUTH_CODE) // grant_type in auth headers should be ignored
),
array(
array('not_grant_type' => 5),
array()
),
);
}
}
| 35.164436
| 119
| 0.586319
|
92884218eeb62bf1788cbd272f3cbcdbab70bde0
| 143
|
rb
|
Ruby
|
db/migrate/20171114135347_add_project_id_to_specifications.rb
|
aizawa1126/USDM
|
11ef313d3e9c68946e9cfa69d3a21ab02d34e2af
|
[
"MIT"
] | 1
|
2018-02-27T02:53:31.000Z
|
2018-02-27T02:53:31.000Z
|
db/migrate/20171114135347_add_project_id_to_specifications.rb
|
aizawa1126/USDM
|
11ef313d3e9c68946e9cfa69d3a21ab02d34e2af
|
[
"MIT"
] | null | null | null |
db/migrate/20171114135347_add_project_id_to_specifications.rb
|
aizawa1126/USDM
|
11ef313d3e9c68946e9cfa69d3a21ab02d34e2af
|
[
"MIT"
] | null | null | null |
class AddProjectIdToSpecifications < ActiveRecord::Migration[5.1]
def change
add_column :specifications, :project_id, :integer
end
end
| 23.833333
| 65
| 0.783217
|