branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<file_sep>#include "mkfs_net.h"
#include <fcntl.h>
mkfs_net::mkfs_net()
{
conn_fd = sock_fd = 0;
}
mkfs_net::~mkfs_net()
{
if(conn_fd != 0) close(conn_fd);
if(sock_fd != 0) close(sock_fd);
}
void mkfs_net::clientConnect(string server, int port)
{
struct sockaddr_in clientaddr;
bzero(&clientaddr,sizeof(clientaddr));
clientaddr.sin_family=AF_INET;
clientaddr.sin_addr.s_addr=htons(INADDR_ANY);
clientaddr.sin_port=htons(0);
sock_fd=socket(AF_INET,SOCK_STREAM,0);
if(sock_fd<0)
{
perror("socket");
exit(1);
}
else
cout << "socket success"<<endl;
if(::bind(sock_fd,(struct sockaddr*)&clientaddr,sizeof(clientaddr))<0)
{
perror("bind");
exit(1);
}
else
cout << "bind success"<<endl;
struct sockaddr_in serv_addr;
bzero(&serv_addr,sizeof(serv_addr));
struct hostent *serv = gethostbyname(server.c_str());
if (serv == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)serv->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
serv->h_length);
serv_addr.sin_family=AF_INET;
serv_addr.sin_port=htons(port);
socklen_t svraddrlen=sizeof(serv_addr);
cout<<"connecting to server" <<endl;
if(connect(sock_fd,(struct sockaddr*)&serv_addr,svraddrlen)<0)
{
perror("connect");
exit(1);
}
cout<<"Client Connected to Server"<<endl;
}
void mkfs_net::clientSendCmdLine(string line)
{
// cout<<"Read to send "<<line<<endl;
int length=line.size();
int ret = send(sock_fd, &length, 4, 0);
// cout<<"send len " << ret << endl;
ret = send(sock_fd, line.c_str(),length,0);
// cout<<", send msg "<< ret<<endl;
}
void mkfs_net::clientWaitRespond()
{
char plen[4];
int size = 0;
size = ::recv(sock_fd, plen,4,0);
int len = *((int*)plen);
// cout<<"res len "<<len<<endl;
char buf[32];
string ret;
while(len > 0)
{
int cnt = recv(sock_fd, buf, sizeof(buf)-1,0);
string tmp(buf, cnt);
ret.append(tmp);
len -= cnt;
}
cout<<"remote : " <<ret<<endl;
}
void mkfs_net::serverStart(int port)
{
struct sockaddr_in addr_serv,addr_client;
sock_fd = socket(AF_INET,SOCK_STREAM,0);
if(sock_fd < 0){
perror("socket");
exit(1);
} else {
printf("sock sucessful\n");
}
memset(&addr_serv,0,sizeof(addr_serv));
addr_serv.sin_family = AF_INET;
addr_serv.sin_port = htons(port);
addr_serv.sin_addr.s_addr =INADDR_ANY;
memset(&addr_client,0,sizeof(addr_client));
socklen_t client_len = sizeof(addr_client);
int ret = ::bind(sock_fd,(struct sockaddr *)&addr_serv,sizeof(struct sockaddr_in));
if(ret < 0)
{
perror("bind");
exit(1);
} else {
printf("bind sucess\n");
}
if (listen(sock_fd,1) < 0){
perror("listen");
exit(1);
} else {
printf("listen sucessful\n");
}
printf("begin accept:\n");
conn_fd = ::accept(sock_fd,(struct sockaddr *)&addr_client,&client_len);
if(conn_fd < 0){
perror("accept");
exit(1);
}
printf("accept a new client,ip:%s\n",inet_ntoa(addr_client.sin_addr));
}
string mkfs_net::serverRead()
{
char plen[4];
int size = 0;
size = ::recv(conn_fd, plen,4,0);
int len = *((int*)plen);
char buf[32];
string ret;
while(len > 0)
{
int cnt = recv(conn_fd, buf, sizeof(buf)-1,0);
string tmp(buf, cnt);
ret.append(tmp);
len -= cnt;
}
cout<<"remote : "<<ret<<endl;
return ret;
}
void mkfs_net::serverGrabCout()
{
stdoutCopy = dup(1);
system("rm out.txt");
pipedOutFd = open("out.txt", O_WRONLY | O_CREAT, 0666);
if(dup2(pipedOutFd,1) == -1){
perror("dup2.1");
exit(-1);
}
}
void mkfs_net::serverReleaseCoutAndRespond()
{
close(pipedOutFd);
if(dup2(stdoutCopy,1) < 0){
perror("dup2.1 back");
exit(-1);
}
FILE *fd = fopen("out.txt","r");
string ret;
char buf[32];
fseek(fd,0,SEEK_END);
int len = ftell(fd);
fseek(fd,0,SEEK_SET);
// cout<<"file len = "<<len<<endl;
send(conn_fd,&len,4,0);
while(len > 0)
{
int size = fread(buf,1,32,fd);
len -= size;
ret += string(buf,size);
}
send(conn_fd,ret.c_str(),ret.size(),0);
fclose(fd);
}
<file_sep>#ifndef MKFS_NET_H
#define MKFS_NET_H
#include <string>
#include <iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<unistd.h>//close()
#include<netinet/in.h>//struct sockaddr_in
#include<arpa/inet.h>//inet_ntoa
#include <netdb.h>
using namespace std;
class mkfs_net
{
public:
mkfs_net();
~mkfs_net();
void clientConnect(string server, int port);
void clientSendCmdLine(string line);
void clientWaitRespond();
void serverStart(int port);
string serverRead();
void serverGrabCout();
void serverReleaseCoutAndRespond();
private:
string serverName;
int m_port;
int sock_fd;
int conn_fd;
int stdoutCopy;
int pipedOutFd;
};
#endif // MKFS_NET_H
<file_sep>pa1 : main.o zfs.o mkfs_net.o
g++ -o pa1 main.o zfs.o mkfs_net.o
main.o : main.cpp
g++ -c main.cpp
zfs.o : zfs.cpp zfs.h
g++ -c zfs.cpp
mkfs_net : mkfs_net.h
g++ -c mkfs.net.cpp
clean:
rm *.o
rm *.img
<file_sep>#ifndef ZFS_H
#define ZFS_H
#include <fstream>
#include <iostream>
#include <string>
#include <string.h>
#include <stdlib.h>
#include "mkfs_net.h"
using namespace std;
#define BLOCK_SIZE (4096)
#define TOTAL_SIZE (100*1024*1024)
#define BLOCK_NUM (TOTAL_SIZE/BLOCK_SIZE)
#define GET_BLOCK_INDEX(x) ((x)/BLOCK_SIZE)
#define SET_NAME(x,y) (strcpy(x,y))
#define BUF2FCB(x) ((FCB*)(blockBuf[x]))
#define MAX_NAME 256
#define MAX_BLOCK_POINTER ((BLOCK_SIZE - 272)/4)
#define MAX_DIRECT_DATA (MAX_BLOCK_POINTER * BLOCK_SIZE)
enum blockType{T_DIR,T_FILE,T_IGN};
struct FCB
{
blockType type;
int block;
int parent;
char name[MAX_NAME];
int size; // number of files of DIR, len of file for FILE
int direct_pointer[MAX_BLOCK_POINTER];
};
class ZFS
{
public:
ZFS();
~ZFS();
void startServer(int port);
void run();
void processCmd(string line);
void mkfs();
void pwd();
void open(string name, string flag);
string read(int fd, int size);
void write(int fd, string dat);
void seek(int fd, int offset);
void close(int fd);
void mkdir(string dir);
void rmdir(string dir);
void cd(string dir);
void ls();
void cat(string name);
void tree();
void import(string src, string dest);
void exprt(string src, string dest);
private:
FILE *fd;
FCB* findPath(string path); // return parent FCB contents path, support absolute path and relative path.
FCB* findFile(string path); // return file FCB support absolute path and relative path.
void writeFCB(int block, FCB* p);
void writeData(int block, void* p, int len, int blockOffset);
string readData(int block, int len, int offset);
void updatePageNum();
void lsOfBlockFcb(int block);
void insertFCBtoDirBlock(int block, FCB* p);
int currentDirBlock;
int nextNewInodeBlock;
int nextNewDataBlock;
FCB *currentWorkingVFile;
int VFilePage;
int VFilePageOffset;
int VFileOffset;
mkfs_net *net;
};
#endif // ZFS_H
<file_sep>remote:
Server ./pa1 -s port
Client ./pa1 -c servername port
servername could be IP or hostname.
Our code use out.txt as temporary stdout and output.img as VDisk File.
We cannot get tree command works
<file_sep>#include <iostream>
#include <sstream>
#include "zfs.h"
#include <stdlib.h>
#include <unistd.h>
#include "mkfs_net.h"
using namespace std;
int main(int argc, char *argv[])
{
if(argc == 4 && strcmp(argv[1],"-c") == 0)
{
mkfs_net net;
int port = atoi(argv[3]);
net.clientConnect(string(argv[2]),port);
string line;
while(getline(cin,line))
{
net.clientSendCmdLine(line);
net.clientWaitRespond();
}
}
else if(argc == 3 && strcmp(argv[1],"-s") == 0)
{
int port = atoi(argv[2]);
ZFS zfs;
zfs.startServer(port);
}
else
{
ZFS zfs;
zfs.run();
}
return 0;
}
|
073ce1e0b2569fcf3913550624f1fbe8da5a0fce
|
[
"Text",
"Makefile",
"C++"
] | 6 |
C++
|
zhoutl1106/PA1
|
715f513e1f954b510ba3f39b357a74baeeb669b6
|
8d8905a15effd30ba08dd5b200f47a4cd64a8ffa
|
refs/heads/master
|
<repo_name>mmmdamin/madad<file_sep>/account/admin.py
from django.contrib import admin
from account.models import Member
admin.site.register(Member)<file_sep>/account/models.py
from django.contrib.auth.models import AbstractUser
class Member(AbstractUser):
pass<file_sep>/base/views.py
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import redirect
def home(request):
if request.user.is_authenticated():
return HttpResponseRedirect(reverse('dashboard'))
return redirect('login')<file_sep>/requirements.txt
dj-database-url==0.3.0
dj-static==0.0.6
django-toolbelt==0.0.1
gunicorn==19.0.0
static3==0.5.1
wsgiref==0.1.2
Django==1.6.8
psycopg2
south
whitenoise
django-model-utils
django-password-reset
djrill
<file_sep>/account/views.py
from audioop import reverse
from django.contrib.auth import login as dj_login
from django.contrib.auth import logout as dj_logout
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect
from account.forms import SignInForm, PasswordForm
def login(request):
if request.user.is_authenticated():
return HttpResponseRedirect(reverse('dashboard'))
if request.method == 'POST':
form = SignInForm(request.POST)
if form.is_valid():
next_url = request.GET.get('next')
user = form.user
dj_login(request, user)
if not next_url:
next_url = reverse('dashboard')
return HttpResponseRedirect(next_url)
else:
form = SignInForm()
return render(request, 'account/login.html', {
'form': form,
})
def logout(request):
dj_logout(request)
return redirect('home')
@login_required
def password_reset_change(request):
if request.method == 'POST':
form = PasswordForm(user=request.user, data=request.POST)
form.is_valid()
sent = True
else:
form = PasswordForm(user=request.user)
sent = False
return render(request,
'password_reset/password_change.html',
{
'form': form,
'sent': sent,
})
def dashboard(request):
return<file_sep>/account/urls.py
from django.conf.urls import patterns, url, include
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('account.views',
url(r'^login/$', 'login', name='login'),
url(r'^logout/?$', 'logout', name='logout'),
url(r'^change-password/?$', 'password_reset_change', name='password_reset_change'),
url(r'^dashboard/$', 'dashboard', name='dashboard'),
url(r'^', include('password_reset.urls')),
)
|
0c0db15f9fe1ffec14269fa4bb361a5b0eb289c1
|
[
"Python",
"Text"
] | 6 |
Python
|
mmmdamin/madad
|
034bb9ddf5d0c9454525bbc5ac1ebbf029eedda0
|
66608e9941d343fa6ec8be8628cf6a486ec609b8
|
refs/heads/master
|
<repo_name>guihetz/ProjetoDsi<file_sep>/src/br/com/hotel/tabela/TableModelItensConsumo.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.hotel.tabela;
import br.com.hotel.dao.ConnectionFactory;
import br.com.hotel.dao.ItemConsumoDao;
import br.com.hotel.modelo.ItemConsumo;
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;
/**
*
* @author daylton
*/
public class TableModelItensConsumo extends AbstractTableModel{
private String[] nomesColunas = {"Descrição", "Categoria","Valor"};
private ArrayList<ItemConsumo> itensConsumo;
public TableModelItensConsumo(){
itensConsumo = new ArrayList<>();
}
public void preencherLista(ArrayList<ItemConsumo> listaItensConsumo){
itensConsumo.addAll(listaItensConsumo);
}
public ItemConsumo retornarObjetoSelecionado(int linha){
return itensConsumo.get(linha);
}
@Override
public int getRowCount() {
return itensConsumo.size();
}
@Override
public int getColumnCount() {
return nomesColunas.length;
}
@Override
public String getColumnName(int column) {
return nomesColunas[column];
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
ItemConsumoDao dao = new ItemConsumoDao(new ConnectionFactory().getConnection());
ItemConsumo ic = itensConsumo.get(rowIndex);
switch(columnIndex){
case 0:
return ic.getDescricao();
case 1:
return dao.getCategoria(ic.getCategoriaId());
case 2:
return ic.getValor();
default:
throw new UnsupportedOperationException("Operation not Suport!");
}
}
}
<file_sep>/src/br/com/hotel/painel/PainelGerenciarHotel.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.hotel.painel;
import br.com.hotel.apresentacao.TelaAdicionarAcomodacao;
import br.com.hotel.apresentacao.TelaEditarAcomodacao;
import br.com.hotel.apresentacao.TelaEditarItensConsumo;
import br.com.hotel.apresentacao.TelaEditarTipoAcomodacao;
import br.com.hotel.apresentacao.TelaAdicionarItensConsumo;
import br.com.hotel.apresentacao.TelaTipoAcomodacao;
import br.com.hotel.dao.AcomodacaoDao;
import br.com.hotel.dao.ConnectionFactory;
import br.com.hotel.dao.ItemConsumoDao;
import br.com.hotel.dao.TipoAcomodacaoDao;
import br.com.hotel.modelo.Acomodacao;
import br.com.hotel.modelo.ItemConsumo;
import br.com.hotel.modelo.TipoAcomodacao;
import br.com.hotel.tabela.TableModelAcomodacoes;
import br.com.hotel.tabela.TableModelItensConsumo;
import br.com.hotel.tabela.TableModelTipoAcomodacao;
import java.awt.Color;
import java.awt.Font;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import static javax.swing.SwingConstants.CENTER;
import javax.swing.table.DefaultTableCellRenderer;
/**
*
* @author daylton
*/
public class PainelGerenciarHotel extends javax.swing.JPanel {
/**
* Creates new form PainelGerenciarHotel
*/
private TableModelItensConsumo modeloItensConsumo;
private TableModelTipoAcomodacao modeloTipoAcomodacao;
private TableModelAcomodacoes modeloAcomodacao;
public PainelGerenciarHotel() {
initComponents();
preencherTabelaItensConsumo();
preencherTabelaTipoAcomodacao();
TipoAcomodacaoDao tad = new TipoAcomodacaoDao(new ConnectionFactory().getConnection());
if(tad.listarTipoAcomodacao().isEmpty()){
preecherTabelaAcomodacoes();
preencherMsg("Não existem acomodações cadastradas!", Color.red);
}else{
preecherTabelaAcomodacoes();
}
}
public void preencherMsg(String s, Color c){
lbMsg.setText(s);
lbMsg.setForeground(c);
lbMsg1.setText(s);
lbMsg1.setForeground(c);
lbMsg2.setText(s);
lbMsg2.setForeground(c);
}
public void preencherTabelaItensConsumo(){
ItemConsumoDao dao = new ItemConsumoDao(new ConnectionFactory().getConnection());
modeloItensConsumo = new TableModelItensConsumo();
modeloItensConsumo.preencherLista(dao.listarItensConsumo());
tbItensConsumo.setModel(modeloItensConsumo);
//
DefaultTableCellRenderer centerRender = new DefaultTableCellRenderer();
centerRender.setHorizontalAlignment(JLabel.CENTER);
tbItensConsumo.getColumnModel().getColumn(0).setCellRenderer(centerRender);
tbItensConsumo.getColumnModel().getColumn(1).setCellRenderer(centerRender);
tbItensConsumo.getColumnModel().getColumn(2).setCellRenderer(centerRender);
tbItensConsumo.getTableHeader().setFont(new Font("Hotel Oriental", 1, 18));
((DefaultTableCellRenderer) tbItensConsumo.getTableHeader().getDefaultRenderer()).setHorizontalAlignment(CENTER);
tbItensConsumo.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
public void preencherTabelaTipoAcomodacao(){
TipoAcomodacaoDao dao = new TipoAcomodacaoDao(new ConnectionFactory().getConnection());
modeloTipoAcomodacao = new TableModelTipoAcomodacao();
modeloTipoAcomodacao.preencherLista(dao.listarTipoAcomodacao());
tbTipoAcomodacoes.setModel(modeloTipoAcomodacao);
DefaultTableCellRenderer centerRender = new DefaultTableCellRenderer();
centerRender.setHorizontalAlignment(JLabel.CENTER);
tbTipoAcomodacoes.getColumnModel().getColumn(0).setCellRenderer(centerRender);
tbTipoAcomodacoes.getColumnModel().getColumn(1).setCellRenderer(centerRender);
tbTipoAcomodacoes.getColumnModel().getColumn(2).setCellRenderer(centerRender);
tbTipoAcomodacoes.getColumnModel().getColumn(3).setCellRenderer(centerRender);
tbTipoAcomodacoes.getColumnModel().getColumn(4).setCellRenderer(centerRender);
tbTipoAcomodacoes.getTableHeader().setFont(new Font("Hotel Oriental", 1, 18));
((DefaultTableCellRenderer) tbTipoAcomodacoes.getTableHeader().getDefaultRenderer()).setHorizontalAlignment(CENTER);
tbTipoAcomodacoes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
public void preecherTabelaAcomodacoes(){
AcomodacaoDao ad = new AcomodacaoDao(new ConnectionFactory().getConnection());
modeloAcomodacao = new TableModelAcomodacoes();
modeloAcomodacao.preencherLista(ad.listarAcomodacoes());
tbAcomodacoes.setModel(modeloAcomodacao);
tbAcomodacoes.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
tbAcomodacoes.getTableHeader().setFont(new Font("Hotel Oriental", 1, 18));
((DefaultTableCellRenderer) tbAcomodacoes.getTableHeader().getDefaultRenderer()).setHorizontalAlignment(CENTER);
tbAcomodacoes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel();
jPanel4 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
tbItensConsumo = new javax.swing.JTable();
btnAdicionarItem = new javax.swing.JButton();
btnEditarItem = new javax.swing.JButton();
btnExcluirItem = new javax.swing.JButton();
lbMsg = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
tbTipoAcomodacoes = new javax.swing.JTable();
btnAdicionarAcomodacao = new javax.swing.JButton();
btnEditarAcomodacao = new javax.swing.JButton();
btnExcluirAcomodacao = new javax.swing.JButton();
lbMsg1 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jPanel3 = new javax.swing.JPanel();
jPanel6 = new javax.swing.JPanel();
btnInserirAcomodacao = new javax.swing.JButton();
lbMsg2 = new javax.swing.JLabel();
jScrollPane3 = new javax.swing.JScrollPane();
tbAcomodacoes = new javax.swing.JTable();
btnApagarAcomodacao = new javax.swing.JButton();
btnAtualizarAcomodacao = new javax.swing.JButton();
jLabel8 = new javax.swing.JLabel();
jTabbedPane1.setFont(new java.awt.Font("Hotel Oriental", 0, 18)); // NOI18N
tbItensConsumo.setFont(new java.awt.Font("Hotel Oriental", 0, 18)); // NOI18N
tbItensConsumo.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null},
{null, null, null},
{null, null, null},
{null, null, null}
},
new String [] {
"Descrição", "Categoria", "Valor"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.Double.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
jScrollPane1.setViewportView(tbItensConsumo);
btnAdicionarItem.setFont(new java.awt.Font("Hotel Oriental", 0, 20)); // NOI18N
btnAdicionarItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/hotel/imagem/add.png"))); // NOI18N
btnAdicionarItem.setText("Adicionar Item de Consumo");
btnAdicionarItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAdicionarItemActionPerformed(evt);
}
});
btnEditarItem.setFont(new java.awt.Font("Hotel Oriental", 0, 20)); // NOI18N
btnEditarItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/hotel/imagem/edit.png"))); // NOI18N
btnEditarItem.setText("Editar Item de Consumo");
btnEditarItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnEditarItemActionPerformed(evt);
}
});
btnExcluirItem.setFont(new java.awt.Font("Hotel Oriental", 0, 20)); // NOI18N
btnExcluirItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/hotel/imagem/delete.png"))); // NOI18N
btnExcluirItem.setText("Excluir Item de Consumo");
btnExcluirItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnExcluirItemActionPerformed(evt);
}
});
lbMsg.setFont(new java.awt.Font("Hotel Oriental", 0, 18)); // NOI18N
lbMsg.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addComponent(lbMsg, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(btnAdicionarItem, javax.swing.GroupLayout.DEFAULT_SIZE, 320, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(btnEditarItem, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnExcluirItem, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 380, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnAdicionarItem)
.addComponent(btnEditarItem)
.addComponent(btnExcluirItem))
.addGap(18, 18, 18)
.addComponent(lbMsg, javax.swing.GroupLayout.DEFAULT_SIZE, 33, Short.MAX_VALUE)
.addContainerGap())
);
jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/hotel/imagem/city.png"))); // NOI18N
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jTabbedPane1.addTab("Gerenciar Itens de Consumo", jPanel1);
tbTipoAcomodacoes.setFont(new java.awt.Font("Hotel Oriental", 0, 18)); // NOI18N
tbTipoAcomodacoes.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane2.setViewportView(tbTipoAcomodacoes);
btnAdicionarAcomodacao.setFont(new java.awt.Font("Hotel Oriental", 0, 20)); // NOI18N
btnAdicionarAcomodacao.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/hotel/imagem/add.png"))); // NOI18N
btnAdicionarAcomodacao.setText("Adicionar Tipo de Acomodação");
btnAdicionarAcomodacao.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAdicionarAcomodacaoActionPerformed(evt);
}
});
btnEditarAcomodacao.setFont(new java.awt.Font("Hotel Oriental", 0, 20)); // NOI18N
btnEditarAcomodacao.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/hotel/imagem/edit.png"))); // NOI18N
btnEditarAcomodacao.setText("Editar Tipo de Acomodação");
btnEditarAcomodacao.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnEditarAcomodacaoActionPerformed(evt);
}
});
btnExcluirAcomodacao.setFont(new java.awt.Font("Hotel Oriental", 0, 20)); // NOI18N
btnExcluirAcomodacao.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/hotel/imagem/delete.png"))); // NOI18N
btnExcluirAcomodacao.setText("Excluir Tipo de Acomodação");
btnExcluirAcomodacao.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnExcluirAcomodacaoActionPerformed(evt);
}
});
lbMsg1.setFont(new java.awt.Font("Hotel Oriental", 0, 18)); // NOI18N
lbMsg1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(lbMsg1, javax.swing.GroupLayout.PREFERRED_SIZE, 1011, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel5Layout.createSequentialGroup()
.addComponent(btnAdicionarAcomodacao, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(btnEditarAcomodacao, javax.swing.GroupLayout.PREFERRED_SIZE, 330, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(303, 303, 303)))
.addGap(0, 45, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(btnExcluirAcomodacao, javax.swing.GroupLayout.PREFERRED_SIZE, 330, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 380, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnAdicionarAcomodacao)
.addComponent(btnExcluirAcomodacao)
.addComponent(btnEditarAcomodacao))
.addGap(18, 18, 18)
.addComponent(lbMsg1, javax.swing.GroupLayout.DEFAULT_SIZE, 33, Short.MAX_VALUE)
.addContainerGap())
);
jLabel7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/hotel/imagem/city.png"))); // NOI18N
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel7)
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel7)
.addContainerGap(15, Short.MAX_VALUE))
);
jTabbedPane1.addTab("Gerenciar Tipos de Acomodação", jPanel2);
btnInserirAcomodacao.setFont(new java.awt.Font("Hotel Oriental", 0, 20)); // NOI18N
btnInserirAcomodacao.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/hotel/imagem/add.png"))); // NOI18N
btnInserirAcomodacao.setText("Adicionar Acomodação");
btnInserirAcomodacao.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnInserirAcomodacaoActionPerformed(evt);
}
});
lbMsg2.setFont(new java.awt.Font("Hotel Oriental", 0, 18)); // NOI18N
lbMsg2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
tbAcomodacoes.setFont(new java.awt.Font("Hotel Oriental", 0, 18)); // NOI18N
tbAcomodacoes.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane3.setViewportView(tbAcomodacoes);
btnApagarAcomodacao.setFont(new java.awt.Font("Hotel Oriental", 0, 20)); // NOI18N
btnApagarAcomodacao.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/hotel/imagem/delete.png"))); // NOI18N
btnApagarAcomodacao.setText("Excluir Acomodação");
btnApagarAcomodacao.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnApagarAcomodacaoActionPerformed(evt);
}
});
btnAtualizarAcomodacao.setFont(new java.awt.Font("Hotel Oriental", 0, 20)); // NOI18N
btnAtualizarAcomodacao.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/hotel/imagem/edit.png"))); // NOI18N
btnAtualizarAcomodacao.setText("Editar Acomodação");
btnAtualizarAcomodacao.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAtualizarAcomodacaoActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbMsg2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 1056, Short.MAX_VALUE)
.addGroup(jPanel6Layout.createSequentialGroup()
.addComponent(btnInserirAcomodacao, javax.swing.GroupLayout.PREFERRED_SIZE, 326, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnAtualizarAcomodacao, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(btnApagarAcomodacao, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 380, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnApagarAcomodacao)
.addComponent(btnAtualizarAcomodacao)
.addComponent(btnInserirAcomodacao))
.addGap(18, 18, 18)
.addComponent(lbMsg2, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/hotel/imagem/city.png"))); // NOI18N
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel8))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel8)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jTabbedPane1.addTab("Gerenciar Acomodações", jPanel3);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(29, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void btnAdicionarItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAdicionarItemActionPerformed
TelaAdicionarItensConsumo t1 = new TelaAdicionarItensConsumo(this);
t1.setAlwaysOnTop(true);
t1.setVisible(true);
t1.setLocationRelativeTo(null);
}//GEN-LAST:event_btnAdicionarItemActionPerformed
private void btnEditarItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarItemActionPerformed
if(tbItensConsumo.getSelectedRow() >= 0){
ItemConsumo ic = modeloItensConsumo.retornarObjetoSelecionado(tbItensConsumo.getSelectedRow());
TelaEditarItensConsumo t2 = new TelaEditarItensConsumo(ic, this);
t2.setAlwaysOnTop(true);
t2.setVisible(true);
t2.setLocationRelativeTo(null);
}else{
preencherMsg("Nenhumo Item Selecionado", Color.RED);
}
}//GEN-LAST:event_btnEditarItemActionPerformed
private void btnExcluirItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirItemActionPerformed
if(tbItensConsumo.getSelectedRow() >= 0){
ItemConsumoDao dao = new ItemConsumoDao(new ConnectionFactory().getConnection());
ItemConsumo ic = modeloItensConsumo.retornarObjetoSelecionado(tbItensConsumo.getSelectedRow());
JLabel msg = new JLabel();
msg.setFont(new Font("Hotel Oriental", 1, 18));
msg.setForeground(Color.RED);
msg.setText("Voce tem certeza disso?");
int r = JOptionPane.showConfirmDialog(this, msg, "ATENÇÃO",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, new ImageIcon());
if(r == 0){
dao.excluirItemConsumo(ic.getCategoriaId());
preencherMsg("Item Excluido!", Color.red);
}
preencherTabelaItensConsumo();
}else{
preencherMsg("Nenhumo Item Selecionado", Color.RED);
}
}//GEN-LAST:event_btnExcluirItemActionPerformed
private void btnAdicionarAcomodacaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAdicionarAcomodacaoActionPerformed
TelaTipoAcomodacao t3 = new TelaTipoAcomodacao(this);
t3.setAlwaysOnTop(true);
t3.setVisible(true);
t3.setLocationRelativeTo(null);
}//GEN-LAST:event_btnAdicionarAcomodacaoActionPerformed
private void btnEditarAcomodacaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarAcomodacaoActionPerformed
if(tbTipoAcomodacoes.getSelectedRow() >= 0){
TipoAcomodacao tpa = modeloTipoAcomodacao.retornarObjetoSelecionado(tbTipoAcomodacoes.getSelectedRow());
TelaEditarTipoAcomodacao t4 = new TelaEditarTipoAcomodacao(tpa, this);
t4.setAlwaysOnTop(true);
t4.setVisible(true);
t4.setLocationRelativeTo(null);
}else{
preencherMsg("Nenhuma Acomodação Selecionada", Color.RED);
}
}//GEN-LAST:event_btnEditarAcomodacaoActionPerformed
private void btnExcluirAcomodacaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirAcomodacaoActionPerformed
if(tbTipoAcomodacoes.getSelectedRow() >= 0){
TipoAcomodacaoDao dao = new TipoAcomodacaoDao(new ConnectionFactory().getConnection());
TipoAcomodacao tpa = modeloTipoAcomodacao.retornarObjetoSelecionado(tbTipoAcomodacoes.getSelectedRow());
JLabel msg = new JLabel();
msg.setFont(new Font("Hotel Oriental", 1, 18));
msg.setForeground(Color.RED);
msg.setText("Voce tem certeza disso?? Acomodações deste tipo também serão excluidas!");
int r = JOptionPane.showConfirmDialog(this, msg, "ATENÇÃO",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, new ImageIcon());
if(r == 0){
dao.excluirTipoAcomodacao(tpa.getTipoAcomodacaoId());
preencherMsg("Tipo de Acomodação Excluido!", Color.red);
}
preencherTabelaTipoAcomodacao();
preecherTabelaAcomodacoes();
}else{
preencherMsg("Nenhuma Acomodação Selecionada", Color.RED);
}
}//GEN-LAST:event_btnExcluirAcomodacaoActionPerformed
private void btnInserirAcomodacaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInserirAcomodacaoActionPerformed
TelaAdicionarAcomodacao t5 = new TelaAdicionarAcomodacao(this);
t5.setAlwaysOnTop(true);
t5.setVisible(true);
t5.setLocationRelativeTo(null);
}//GEN-LAST:event_btnInserirAcomodacaoActionPerformed
private void btnApagarAcomodacaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnApagarAcomodacaoActionPerformed
if(tbAcomodacoes.getSelectedRow() >= 0){
AcomodacaoDao dao = new AcomodacaoDao(new ConnectionFactory().getConnection());
Acomodacao a = modeloAcomodacao.retornarObjetoSelecionado(tbAcomodacoes.getSelectedRow());
JLabel msg = new JLabel();
msg.setFont(new Font("Hotel Oriental", 1, 18));
msg.setForeground(Color.RED);
msg.setText("Voce tem certeza disso?");
int r = JOptionPane.showConfirmDialog(this, msg, "ATENÇÃO",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, new ImageIcon());
if(r == 0){
dao.excluirAcomodacao(a.getAcomodacaoId());
preencherMsg("Acomodação Excluida!", Color.red);
}
preecherTabelaAcomodacoes();
}else{
preencherMsg("Nenhuma Acomodação Selecionada", Color.RED);
}
}//GEN-LAST:event_btnApagarAcomodacaoActionPerformed
private void btnAtualizarAcomodacaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAtualizarAcomodacaoActionPerformed
if(tbAcomodacoes.getSelectedRow() >= 0){
Acomodacao ac = modeloAcomodacao.retornarObjetoSelecionado(tbTipoAcomodacoes.getSelectedRow());
TelaEditarAcomodacao t5 = new TelaEditarAcomodacao();
t5.setAlwaysOnTop(true);
t5.setVisible(true);
t5.setLocationRelativeTo(null);
}else{
preencherMsg("Nenhuma Acomodação Selecionada", Color.RED);
}
}//GEN-LAST:event_btnAtualizarAcomodacaoActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnAdicionarAcomodacao;
private javax.swing.JButton btnAdicionarItem;
private javax.swing.JButton btnApagarAcomodacao;
private javax.swing.JButton btnAtualizarAcomodacao;
private javax.swing.JButton btnEditarAcomodacao;
private javax.swing.JButton btnEditarItem;
private javax.swing.JButton btnExcluirAcomodacao;
private javax.swing.JButton btnExcluirItem;
private javax.swing.JButton btnInserirAcomodacao;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JTabbedPane jTabbedPane1;
private javax.swing.JLabel lbMsg;
private javax.swing.JLabel lbMsg1;
private javax.swing.JLabel lbMsg2;
private javax.swing.JTable tbAcomodacoes;
private javax.swing.JTable tbItensConsumo;
private javax.swing.JTable tbTipoAcomodacoes;
// End of variables declaration//GEN-END:variables
}
<file_sep>/src/br/com/hotel/tabela/TableModelReservas.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.hotel.tabela;
import br.com.hotel.dao.AcomodacaoDao;
import br.com.hotel.dao.ConnectionFactory;
import br.com.hotel.dao.HospedeDao;
import br.com.hotel.modelo.Acomodacao;
import br.com.hotel.modelo.Hospede;
import br.com.hotel.modelo.Reserva;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;
/**
*
* @author daylton
*/
public class TableModelReservas extends AbstractTableModel{
private String[] nomesColunas = {"Chegada", "Sáida", "Hospede", "Quarto", "Andar", "Diária", "Multa", "Desconto"};
private ArrayList<Reserva> listaReservas;
public TableModelReservas(){
listaReservas = new ArrayList<>();
}
public void preencherLista(ArrayList<Reserva> listaReservas){
this.listaReservas.addAll(listaReservas);
}
public Reserva retornarObjetoSelecionado(int linha){
return listaReservas.get(linha);
}
@Override
public int getRowCount() {
return listaReservas.size();
}
@Override
public int getColumnCount() {
return nomesColunas.length;
}
@Override
public String getColumnName(int column) {
return nomesColunas[column];
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Reserva r = listaReservas.get(rowIndex);
switch(columnIndex){
case 0:
return new SimpleDateFormat("dd/MM/yyyy").format(r.getDataChegada().getTime());
case 1:
return new SimpleDateFormat("dd/MM/yyyy").format(r.getDataSaida().getTime());
case 2:
HospedeDao hd = new HospedeDao(new ConnectionFactory().getConnection());
Hospede h = hd.buscarHospede(r.getHospedeId());
return h.getNome();
case 3:
AcomodacaoDao ad = new AcomodacaoDao(new ConnectionFactory().getConnection());
Acomodacao a = ad.buscarAcomodacao(r.getAcomodacaoId());
return a.getNumAcomodacao();
case 4:
AcomodacaoDao ad2 = new AcomodacaoDao(new ConnectionFactory().getConnection());
Acomodacao a2 = ad2.buscarAcomodacao(r.getAcomodacaoId());
return a2.getAndar();
case 5:
return r.getValorDiaria();
case 6:
return r.getTaxaMulta();
case 7:
return r.getDesconto();
default:
throw new UnsupportedOperationException("Operation not Suport!");
}
}
}
<file_sep>/script_projeto.sql
DROP DATABASE HOTEL;
CREATE DATABASE HOTEL;
USE HOTEL;
-- MySQL Workbench Forward Engineering
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Schema mydb
-- -----------------------------------------------------
-- -----------------------------------------------------
-- Table `hospedes`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `hospedes` ;
CREATE TABLE IF NOT EXISTS `hospedes` (
`hospede_id` INT NOT NULL AUTO_INCREMENT COMMENT '',
`cpf` VARCHAR(15) NOT NULL COMMENT '',
`nome` VARCHAR(45) NOT NULL COMMENT '',
`endereco` VARCHAR(100) NOT NULL COMMENT '',
`telefone` VARCHAR(20) NOT NULL COMMENT '',
`email` VARCHAR(45) NOT NULL COMMENT '',
`data_nascimento` DATE NOT NULL COMMENT '',
PRIMARY KEY (`hospede_id`) COMMENT '',
UNIQUE INDEX `email_UNIQUE` (`email` ASC) COMMENT '',
UNIQUE INDEX `cpf_UNIQUE` (`cpf` ASC) COMMENT '')
ENGINE = InnoDB
DEFAULT CHARACTER SET = cp850
COLLATE = cp850_general_ci;
-- -----------------------------------------------------
-- Table `categorias`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `categorias` ;
CREATE TABLE IF NOT EXISTS `categorias` (
`categoria_id` INT NOT NULL AUTO_INCREMENT COMMENT '',
`nome_categoria` VARCHAR(25) NOT NULL COMMENT '',
PRIMARY KEY (`categoria_id`) COMMENT '',
UNIQUE INDEX `nome_categoria_UNIQUE` (`nome_categoria` ASC) COMMENT '')
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `itens_consumo`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `itens_consumo` ;
CREATE TABLE IF NOT EXISTS `itens_consumo` (
`item_id` INT NOT NULL AUTO_INCREMENT COMMENT '',
`descricao` VARCHAR(45) NOT NULL COMMENT '',
`valor` DOUBLE NOT NULL COMMENT '',
`categoria_id` INT NULL COMMENT '',
PRIMARY KEY (`item_id`) COMMENT '',
UNIQUE INDEX `descricao_UNIQUE` (`descricao` ASC) COMMENT '',
CONSTRAINT `categoria_id`
FOREIGN KEY (`categoria_id`)
REFERENCES `categorias` (`categoria_id`)
ON DELETE CASCADE
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `tipo_acomodacao`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `tipo_acomodacao` ;
CREATE TABLE IF NOT EXISTS `tipo_acomodacao` (
`tipo_acomodacao_id` INT NOT NULL AUTO_INCREMENT COMMENT '',
`descricao` VARCHAR(45) NOT NULL COMMENT '',
`qtde_acomodacoes` INT NOT NULL COMMENT '',
`valor_diaria` DOUBLE NOT NULL COMMENT '',
`num_adultos` INT NOT NULL COMMENT '',
`num_criancas` INT NOT NULL COMMENT '',
PRIMARY KEY (`tipo_acomodacao_id`) COMMENT '',
UNIQUE INDEX `descricao_UNIQUE` (`descricao` ASC) COMMENT '')
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `acomodacoes`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `acomodacoes` ;
CREATE TABLE IF NOT EXISTS `acomodacoes` (
`acomodacao_id` INT NOT NULL AUTO_INCREMENT COMMENT '',
`num_acomodacao` INT NOT NULL COMMENT '',
`andar` INT NOT NULL COMMENT '',
`tipo_acomodacao_id` INT NOT NULL COMMENT '',
`reservado` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '',
PRIMARY KEY (`acomodacao_id`) COMMENT '',
UNIQUE INDEX `num_acomodacao_UNIQUE` (`num_acomodacao` ASC) COMMENT '',
CONSTRAINT `tipo_acomodacao_id`
FOREIGN KEY (`tipo_acomodacao_id`)
REFERENCES `tipo_acomodacao` (`tipo_acomodacao_id`)
ON DELETE CASCADE
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `cartoes`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `cartoes` ;
CREATE TABLE IF NOT EXISTS `cartoes` (
`cartao_id` INT NOT NULL AUTO_INCREMENT COMMENT '',
`numero_cartao` VARCHAR(45) NOT NULL COMMENT '',
`bandeira` VARCHAR(45) NOT NULL COMMENT '',
`hospede_id` INT NOT NULL COMMENT '',
PRIMARY KEY (`cartao_id`) COMMENT '',
UNIQUE INDEX `numero_cartao_UNIQUE` (`numero_cartao` ASC) COMMENT '',
CONSTRAINT `fk_cartoes_1`
FOREIGN KEY (`hospede_id`)
REFERENCES `hospedes` (`hospede_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `reservas`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `reservas` ;
CREATE TABLE IF NOT EXISTS `reservas` (
`reserva_id` INT NOT NULL AUTO_INCREMENT COMMENT '',
`data_chegada` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '',
`data_saida` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '',
`hospede_id` INT NOT NULL COMMENT '',
`acomodacao_id` INT NOT NULL COMMENT '',
`valor_diaria` DOUBLE NOT NULL COMMENT '',
`taxa_multa` DOUBLE NULL DEFAULT 0 COMMENT '',
`cartao_id` INT NULL COMMENT '',
`desconto` DOUBLE NULL DEFAULT 0 COMMENT '',
PRIMARY KEY (`reserva_id`) COMMENT '',
CONSTRAINT `cartao_id_fk`
FOREIGN KEY (`cartao_id`)
REFERENCES `cartoes` (`cartao_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `hospede_id_fk`
FOREIGN KEY (`hospede_id`)
REFERENCES `hospedes` (`hospede_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `tipo_acomodacao_id_fk`
FOREIGN KEY (`acomodacao_id`)
REFERENCES `acomodacoes` (`acomodacao_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `acompanhantes`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `acompanhantes` ;
CREATE TABLE IF NOT EXISTS `acompanhantes` (
`acompanhante_id` INT NOT NULL AUTO_INCREMENT COMMENT '',
`nome` VARCHAR(45) NOT NULL COMMENT '',
`idade` INT NOT NULL COMMENT '',
`reserva_id` INT NOT NULL COMMENT '',
PRIMARY KEY (`acompanhante_id`) COMMENT '',
UNIQUE INDEX `acompanhante_id_UNIQUE` (`acompanhante_id` ASC) COMMENT '',
CONSTRAINT `fk_acompanhantes_1`
FOREIGN KEY (`reserva_id`)
REFERENCES `reservas` (`reserva_id`)
ON DELETE CASCADE
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `entradas`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `entradas` ;
CREATE TABLE IF NOT EXISTS `entradas` (
`entrada_id` INT NOT NULL AUTO_INCREMENT COMMENT '',
`data_chegada` TIMESTAMP NULL COMMENT '',
`data_saida` TIMESTAMP NULL COMMENT '',
`reserva_id` INT NULL COMMENT '',
PRIMARY KEY (`entrada_id`) COMMENT '',
CONSTRAINT `reserva_id_fk`
FOREIGN KEY (`reserva_id`)
REFERENCES `reservas` (`reserva_id`)
ON DELETE CASCADE
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `consumos`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `consumos` ;
CREATE TABLE IF NOT EXISTS `consumos` (
`consumo_id` INT NOT NULL AUTO_INCREMENT COMMENT '',
`data_consumo` DATE NOT NULL COMMENT '',
`num_acomodacao` INT NOT NULL COMMENT '',
`item_id` INT NOT NULL COMMENT '',
`qtde_consumida` INT NOT NULL DEFAULT 0 COMMENT '',
PRIMARY KEY (`consumo_id`) COMMENT '',
CONSTRAINT `item_id`
FOREIGN KEY (`item_id`)
REFERENCES `itens_consumo` (`item_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `num_acomodacao`
FOREIGN KEY (`num_acomodacao`)
REFERENCES `acomodacoes` (`num_acomodacao`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `tipos_pagamento`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `tipos_pagamento` ;
CREATE TABLE IF NOT EXISTS `tipos_pagamento` (
`tipo_pagamento_id` INT NOT NULL AUTO_INCREMENT COMMENT '',
`tipo` VARCHAR(45) NOT NULL COMMENT '',
PRIMARY KEY (`tipo_pagamento_id`) COMMENT '',
UNIQUE INDEX `tipo_UNIQUE` (`tipo` ASC) COMMENT '')
ENGINE = InnoDB;
insert into tipos_pagamento(tipo) value('á vista');
insert into tipos_pagamento(tipo) value('cheque');
insert into tipos_pagamento(tipo) value('cartão');
-- -----------------------------------------------------
-- Table `saidas`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `saidas` ;
CREATE TABLE IF NOT EXISTS `saidas` (
`saida_id` INT NOT NULL AUTO_INCREMENT COMMENT '',
`num_acomodacao` INT NOT NULL COMMENT '',
`data_saida` TIMESTAMP NOT NULL COMMENT '',
`num_diarias` INT NOT NULL COMMENT '',
`valor_servicos` DOUBLE NOT NULL COMMENT '',
`desconto` DOUBLE NULL DEFAULT 0 COMMENT '',
`estadia_paga` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '',
`tipo_pagamento_id` INT NOT NULL COMMENT '',
`reserva_id` INT NULL COMMENT '',
PRIMARY KEY (`saida_id`) COMMENT '',
CONSTRAINT `tipo_pagamento_id`
FOREIGN KEY (`tipo_pagamento_id`)
REFERENCES `tipos_pagamento` (`tipo_pagamento_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `reservas_encerradas`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `reservas_encerradas` ;
CREATE TABLE IF NOT EXISTS `reservas_encerradas` (
`reserva_id` INT NOT NULL COMMENT '',
`data_chegada` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '',
`data_saida` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '',
`hospede_id` INT NOT NULL COMMENT '',
`acomodacao_id` INT NOT NULL COMMENT '',
`valor_diaria` DOUBLE NOT NULL COMMENT '',
`taxa_multa` DOUBLE NULL DEFAULT 0 COMMENT '',
`cartao_id` INT NULL COMMENT '',
`desconto` DOUBLE NULL DEFAULT 0 COMMENT '',
PRIMARY KEY (`reserva_id`) COMMENT '',
CONSTRAINT `cartao_id_fk2`
FOREIGN KEY (`cartao_id`)
REFERENCES `cartoes` (`cartao_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `hospede_id_fk2`
FOREIGN KEY (`hospede_id`)
REFERENCES `hospedes` (`hospede_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `tipo_acomodacao_id_fk2`
FOREIGN KEY (`acomodacao_id`)
REFERENCES `acomodacoes` (`acomodacao_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
DROP TRIGGER IF EXISTS `fechar_reservas`;
DELIMITER //
CREATE TRIGGER `fechar_reservas`
BEFORE DELETE
ON reservas FOR EACH ROW
BEGIN
-- Insert record into audit table
INSERT INTO reservas_encerradas
( reserva_id,
data_chegada,
data_saida,
hospede_id,
acomodacao_id,
valor_diaria,
taxa_multa,
cartao_id,
desconto)
VALUES
(OLD.reserva_id,
OLD.data_chegada,
OLD.data_saida,
OLD.hospede_id,
OLD.acomodacao_id,
OLD.valor_diaria,
OLD.taxa_multa,
OLD.cartao_id,
OLD.desconto);
END; //
DELIMITER ;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
<file_sep>/src/br/com/hotel/modelo/Acomodacao.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.hotel.modelo;
/**
*
* @author guilherme
*/
public class Acomodacao {
private int acomodacaoId;
private int numAcomodacao;
private int andar;
private int tipoAcomodacaoId;
private boolean reservado;
public int getAcomodacaoId() {
return acomodacaoId;
}
public void setAcomodacaoId(int acomodacaoId) {
this.acomodacaoId = acomodacaoId;
}
public int getNumAcomodacao() {
return numAcomodacao;
}
public void setNumAcomodacao(int numAcomodacao) {
this.numAcomodacao = numAcomodacao;
}
public int getAndar() {
return andar;
}
public void setAndar(int andar) {
this.andar = andar;
}
public int getTipoAcomodacaoId() {
return tipoAcomodacaoId;
}
public void setTipoAcomodacaoId(int tipoAcomodacaoId) {
this.tipoAcomodacaoId = tipoAcomodacaoId;
}
public boolean isReservado() {
return reservado;
}
public void setReservado(boolean reservado) {
this.reservado = reservado;
}
@Override
public String toString() {
return String.valueOf(this.numAcomodacao);
}
}
<file_sep>/src/br/com/hotel/apresentacao/TelaAdicionarCartao.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.hotel.apresentacao;
import br.com.hotel.modelo.Cartao;
import br.com.hotel.modelo.Hospede;
import javax.swing.JOptionPane;
/**
*
* @author guilherme
*/
public class TelaAdicionarCartao extends javax.swing.JFrame {
/**
* Creates new form TelaAdicionarCartao
*/
private Hospede h;
private Cartao c;
public TelaAdicionarCartao() {
initComponents();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public TelaAdicionarCartao(Hospede hospede, Cartao c){
this();
this.h = hospede;
this.c = c;
this.tfHospede.setText("Nome: " + h.getNome() + " CPF: " + h.getCpf());
this.tfNumeroCartao.setText(c.getNumeroCartao());
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
tfNumeroCartao = new javax.swing.JTextField();
cbBandeiras = new javax.swing.JComboBox<>();
jButton1 = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
tfHospede = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Cartões");
setResizable(false);
jLabel1.setText("Número do Cartão:");
jLabel2.setText("Bandeira:");
cbBandeiras.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "VISA", "MASTERCARD", "ELO" }));
jButton1.setText("Adicionar Cartão");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel3.setText("Hóspede:");
tfHospede.setEditable(false);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfNumeroCartao))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cbBandeiras, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jButton1))
.addGap(0, 144, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfHospede)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(tfHospede, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(31, 31, 31)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(cbBandeiras, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(tfNumeroCartao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
try{
c.setBandeira((String)cbBandeiras.getSelectedItem());
c.setHospedeId(h.getHospedeId());
c.setNumeroCartao(tfNumeroCartao.getText());
JOptionPane.showMessageDialog(null, "Cartão adicionado!");
this.dispose();
}catch(Exception erro){
JOptionPane.showMessageDialog(null, "Erro ao adicionar cartão");
}
}//GEN-LAST:event_jButton1ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(TelaAdicionarCartao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TelaAdicionarCartao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TelaAdicionarCartao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TelaAdicionarCartao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TelaAdicionarCartao().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JComboBox<String> cbBandeiras;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JTextField tfHospede;
private javax.swing.JTextField tfNumeroCartao;
// End of variables declaration//GEN-END:variables
}
<file_sep>/src/br/com/hotel/modelo/Consumo.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.hotel.modelo;
import java.util.Date;
/**
*
* @author guilherme
*/
public class Consumo {
private int consumoId;
private Date dataConsumo;
private int numAcomodacao;
private int itemId;
private int qtdeConsumida;
public int getConsumoId() {
return consumoId;
}
public void setConsumoId(int consumoId) {
this.consumoId = consumoId;
}
public Date getDataConsumo() {
return dataConsumo;
}
public void setDataConsumo(Date dataConsumo) {
this.dataConsumo = dataConsumo;
}
public int getNumAcomodacao() {
return numAcomodacao;
}
public void setNumAcomodacao(int numAcomodacao) {
this.numAcomodacao = numAcomodacao;
}
public int getItemId() {
return itemId;
}
public void setItemId(int itemId) {
this.itemId = itemId;
}
public int getQtdeConsumida() {
return qtdeConsumida;
}
public void setQtdeConsumida(int qtdeConsumida) {
this.qtdeConsumida = qtdeConsumida;
}
@Override
public String toString() {
return String.valueOf(this.itemId);
}
}
<file_sep>/src/br/com/hotel/dao/HospedeDao.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.hotel.dao;
import br.com.hotel.modelo.Hospede;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
/**
*
* @author <NAME> Guilherme
*/
public class HospedeDao {
private Connection conn;
public HospedeDao(Connection conn){
this.conn = conn;
}
public void liberarRecursos(Connection conn, PreparedStatement ps, ResultSet rs){
if(conn != null){
try {
conn.close();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
if(ps != null){
try {
ps.close();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
if(rs != null){
try {
rs.close();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
}
public boolean inserirHospede(Hospede h){
PreparedStatement ps = null;
String sql = "INSERT INTO hospedes(cpf, nome, endereco, telefone, email, data_nascimento) VALUES(?,?,?,?,?,?) ";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, h.getCpf());
ps.setString(2, h.getNome());
ps.setString(3, h.getEndereco());
ps.setString(4, h.getTelefone());
ps.setString(5, h.getEmail());
ps.setDate(6, new Date(h.getDataNascimento().getTime()));
ps.executeUpdate();
conn.commit();
return true;
} catch (SQLException ex) {
try {
conn.rollback();
} catch (SQLException ex1) {
throw new RuntimeException(ex1);
}
return false;
//throw new RuntimeException(ex);
}finally{
liberarRecursos(conn, ps, null);
}
}
public ArrayList<Hospede> listarHospedes(){
PreparedStatement ps = null;
ResultSet rs = null;
ArrayList<Hospede> hospedes = null;
String sql = "SELECT * FROM hospedes ";
try {
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
hospedes = new ArrayList<>();
while(rs.next()){
Hospede h = new Hospede();
h.setHospedeId(rs.getInt("hospede_id"));
h.setCpf(rs.getString("cpf"));
h.setNome(rs.getString("nome"));
h.setEndereco(rs.getString("endereco"));
h.setTelefone(rs.getString("telefone"));
h.setEmail(rs.getString("email"));
h.setDataNascimento(rs.getDate("data_nascimento"));
hospedes.add(h);
}
return hospedes;
} catch (SQLException ex) {
throw new RuntimeException(ex);
}finally{
liberarRecursos(conn, ps, rs);
}
}
public Hospede buscarHospede(int hospedeId){
PreparedStatement ps = null;
ResultSet rs = null;
String sql = "SELECT * FROM hospedes WHERE hospede_id = ? ";
try {
ps = conn.prepareStatement(sql);
ps.setInt(1, hospedeId);
rs = ps.executeQuery();
Hospede h = new Hospede();
while(rs.next()){
h.setHospedeId(rs.getInt("hospede_id"));
h.setCpf(rs.getString("cpf"));
h.setNome(rs.getString("nome"));
h.setEndereco(rs.getString("endereco"));
h.setTelefone(rs.getString("telefone"));
h.setEmail(rs.getString("email"));
h.setDataNascimento(rs.getDate("data_nascimento"));
}
return h;
} catch (SQLException ex) {
throw new RuntimeException(ex);
}finally{
liberarRecursos(conn, ps, rs);
}
}
public void excluirHospede(int hospedeId){
PreparedStatement ps = null;
String sql = "DELETE FROM hospedes WHERE hospede_id = ? ";
try {
ps = conn.prepareStatement(sql);
ps.setInt(1, hospedeId);
ps.executeUpdate();
conn.commit();
} catch (SQLException ex) {
try {
conn.rollback();
} catch (SQLException ex1) {
throw new RuntimeException(ex1);
}
throw new RuntimeException(ex);
}finally{
liberarRecursos(conn, ps, null);
}
}
public boolean atualizarHospede(Hospede h){
PreparedStatement ps = null;
String sql = "UPDATE hospedes SET cpf = ?, nome = ?, endereco = ?, telefone = ?, email = ?, data_nascimento = ? "
+ "WHERE hospede_id = ? ";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, h.getCpf());
ps.setString(2, h.getNome());
ps.setString(3, h.getEndereco());
ps.setString(4, h.getTelefone());
ps.setString(5, h.getEmail());
ps.setDate(6, new Date(h.getDataNascimento().getTime()));
ps.setInt(7, h.getHospedeId());
ps.executeUpdate();
conn.commit();
return true;
} catch (SQLException ex) {
try {
conn.rollback();
} catch (SQLException ex1) {
throw new RuntimeException(ex1);
}
return false;
//throw new RuntimeException(ex);
}finally{
liberarRecursos(conn, ps, null);
}
}
}
<file_sep>/src/br/com/hotel/dao/ItemConsumoDao.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.hotel.dao;
import br.com.hotel.modelo.ItemConsumo;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
/**
*
* @author Daylton e Guilherme
*/
public class ItemConsumoDao {
private Connection conn;
public ItemConsumoDao(Connection conn){
this.conn = conn;
}
public void liberarRecursos(Connection conn, PreparedStatement ps, ResultSet rs){
if(conn != null){
try {
conn.close();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
if(ps != null){
try {
ps.close();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
if( rs != null){
try {
rs.close();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
}
public boolean inserirItemConsumo(ItemConsumo ic){
PreparedStatement ps = null;
String sql = "INSERT INTO itens_consumo(descricao, valor, categoria_id) VALUES(?,?,?) ";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, ic.getDescricao());
ps.setDouble(2, ic.getValor());
ps.setInt(3, ic.getCategoriaId());
ps.executeUpdate();
conn.commit();
return true;
} catch (SQLException ex) {
try {
conn.rollback();
} catch (SQLException ex1) {
throw new RuntimeException(ex1);
}
return false;
//throw new RuntimeException(ex);
}finally{
liberarRecursos(conn, ps, null);
}
}
public ArrayList<ItemConsumo> listarItensConsumo(){
PreparedStatement ps = null;
ResultSet rs = null;
ArrayList<ItemConsumo> itens = null;
String sql = "SELECT * FROM itens_consumo ";
try {
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
itens = new ArrayList<>();
while(rs.next()){
ItemConsumo ic = new ItemConsumo();
ic.setCategoriaId(rs.getInt("categoria_id"));
ic.setItemId(rs.getInt("item_id"));
ic.setDescricao(rs.getString("descricao"));
ic.setValor(rs.getDouble("valor"));
itens.add(ic);
}
return itens;
} catch (SQLException ex) {
throw new RuntimeException(ex);
}finally{
liberarRecursos(conn, ps, rs);
}
}
public String getCategoria(int categoria_id){
PreparedStatement ps = null;
ResultSet rs = null;
String categoria = null;
String sql = "SELECT nome_categoria "
+ "FROM itens_consumo i JOIN categorias c "
+ "ON i.categoria_id = c.categoria_id "
+ "WHERE i.categoria_id = ? ";
try {
ps = conn.prepareStatement(sql);
ps.setInt(1, categoria_id);
rs = ps.executeQuery();
while(rs.next()){
categoria = rs.getString("nome_categoria");
}
return categoria;
} catch (SQLException ex) {
throw new RuntimeException(ex);
}finally{
liberarRecursos(conn, ps, rs);
}
}
public ItemConsumo buscarItemConsumo(int itemConsumoId){
PreparedStatement ps = null;
ResultSet rs = null;
String sql = " SELECT * FROM itens_consumo WHERE item_id = ? ";
try {
ps = conn.prepareStatement(sql);
ps.setInt(1, itemConsumoId);
rs = ps.executeQuery();
ItemConsumo ic = new ItemConsumo();
while(rs.next()){
ic.setItemId(rs.getInt("item_id"));
ic.setCategoriaId(rs.getInt("categoria_id"));
ic.setDescricao(rs.getString("descricao"));
ic.setValor(rs.getDouble("valor"));
}
return ic;
} catch (SQLException ex) {
throw new RuntimeException(ex);
}finally{
liberarRecursos(conn, ps, rs);
}
}
public boolean atualizarItemConsumo(ItemConsumo ic){
PreparedStatement ps = null;
String sql = "UPDATE itens_consumo SET descricao = ?, valor = ?, categoria_id = ? WHERE item_id = ? ";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, ic.getDescricao());
ps.setDouble(2, ic.getValor());
ps.setInt(3, ic.getCategoriaId());
ps.setInt(4, ic.getItemId());
ps.executeUpdate();
conn.commit();
return true;
} catch (SQLException ex) {
try {
conn.rollback();
} catch (SQLException ex1) {
throw new RuntimeException(ex1);
}
return false;
//throw new RuntimeException(ex);
}finally{
liberarRecursos(conn, ps, null);
}
}
public void excluirItemConsumo(int itemConsumoId){
PreparedStatement ps = null;
String sql = "DELETE FROM itens_consumo WHERE item_id = ? ";
try {
ps = conn.prepareStatement(sql);
ps.setInt(1, itemConsumoId);
ps.executeUpdate();
conn.commit();
} catch (SQLException ex) {
try {
conn.rollback();
} catch (SQLException ex1) {
throw new RuntimeException(ex1);
}
throw new RuntimeException(ex);
}finally{
liberarRecursos(conn, ps, null);
}
}
}
<file_sep>/src/br/com/hotel/apresentacao/TelaEditarItensConsumo.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.hotel.apresentacao;
import br.com.hotel.dao.CategoriaDao;
import br.com.hotel.dao.ConnectionFactory;
import br.com.hotel.dao.ItemConsumoDao;
import br.com.hotel.modelo.Categoria;
import br.com.hotel.modelo.ItemConsumo;
import br.com.hotel.painel.PainelGerenciarHotel;
import java.awt.Color;
/**
*
* @author daylton
*/
public final class TelaEditarItensConsumo extends javax.swing.JFrame {
private PainelGerenciarHotel pnGerenciarHotel;
/**
* Creates new form TelaEditarItensConsumo
*/
ItemConsumo ic;
public TelaEditarItensConsumo() {
initComponents();
}
public TelaEditarItensConsumo(ItemConsumo itemConsumo, javax.swing.JPanel panel){
this();
pnGerenciarHotel = (PainelGerenciarHotel) panel;
CategoriaDao dao = new CategoriaDao(new ConnectionFactory().getConnection());
ic = itemConsumo;
tfDescricao.setText(ic.getDescricao());
tfValor.setText("" + ic.getValor());
preencherComboCategorias();
}
public void preencherComboCategorias(){
cbCategoria.removeAllItems();
cbCategoria.addItem("-- Selecione --");
for(Categoria c: new CategoriaDao(new ConnectionFactory().getConnection()).listarCategorias()){
cbCategoria.addItem(c);
}
cbCategoria.setSelectedIndex(ic.getCategoriaId());
}
/**
* This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of this method is always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
tfDescricao = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
tfValor = new javax.swing.JTextField();
cbCategoria = new javax.swing.JComboBox();
btnInserir = new javax.swing.JButton();
lbMsg = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Itens de Consumo", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Hotel Oriental", 0, 20))); // NOI18N
jLabel1.setFont(new java.awt.Font("Hotel Oriental", 0, 18)); // NOI18N
jLabel1.setText("Descrição");
tfDescricao.setFont(new java.awt.Font("Hotel Oriental", 0, 18)); // NOI18N
jLabel2.setFont(new java.awt.Font("Hotel Oriental", 0, 18)); // NOI18N
jLabel2.setText("Valor");
jLabel3.setFont(new java.awt.Font("Hotel Oriental", 0, 18)); // NOI18N
jLabel3.setText("Categoria");
tfValor.setFont(new java.awt.Font("Hotel Oriental", 0, 18)); // NOI18N
cbCategoria.setFont(new java.awt.Font("Hotel Oriental", 0, 18)); // NOI18N
cbCategoria.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "--------------" }));
btnInserir.setFont(new java.awt.Font("Hotel Oriental", 0, 20)); // NOI18N
btnInserir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/hotel/imagem/edit.png"))); // NOI18N
btnInserir.setText("Editar Item");
btnInserir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnInserirActionPerformed(evt);
}
});
lbMsg.setFont(new java.awt.Font("Hotel Oriental", 0, 18)); // NOI18N
lbMsg.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(lbMsg, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(btnInserir))
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addComponent(tfValor, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel3)
.addGap(18, 18, 18)
.addComponent(cbCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(16, 16, 16)
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(tfDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, 400, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(tfDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(cbCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2)
.addComponent(tfValor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btnInserir, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lbMsg, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnInserirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInserirActionPerformed
try{
if(!"".equals(tfDescricao.getText())){
if(!"".equals(tfValor.getText()) && Double.valueOf(tfValor.getText()) > 0){
if(cbCategoria.getSelectedIndex() > 0){
Categoria c = (Categoria) cbCategoria.getSelectedItem();
ic.setDescricao(tfDescricao.getText());
ic.setValor(Double.valueOf(tfValor.getText()));
ic.setCategoriaId(c.getCategoriaId());
ItemConsumoDao dao = new ItemConsumoDao(new ConnectionFactory().getConnection());
dao.atualizarItemConsumo(ic);
this.dispose();
pnGerenciarHotel.preencherMsg("Item Atualizado", Color.green);
pnGerenciarHotel.preencherTabelaItensConsumo();
}else{
lbMsg.setText("Erro: Categoria Inválida!");
lbMsg.setForeground(Color.red);
}
}else{
lbMsg.setText("Erro: Valor Inválido!");
lbMsg.setForeground(Color.red);
}
}else{
lbMsg.setText("Erro: Descrição Inválida!");
lbMsg.setForeground(Color.red);
}
}catch(Exception e){
lbMsg.setText("Erro: " + e.getMessage());
lbMsg.setForeground(Color.red);
}
}//GEN-LAST:event_btnInserirActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(TelaEditarItensConsumo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TelaEditarItensConsumo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TelaEditarItensConsumo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TelaEditarItensConsumo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TelaEditarItensConsumo().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnInserir;
private javax.swing.JComboBox cbCategoria;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel lbMsg;
private javax.swing.JTextField tfDescricao;
private javax.swing.JTextField tfValor;
// End of variables declaration//GEN-END:variables
}
<file_sep>/src/br/com/hotel/dao/CartaoDao.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.hotel.dao;
import br.com.hotel.modelo.Cartao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
/**
*
* @author Daylton e Guilherme
*/
public class CartaoDao {
private Connection conn;
public CartaoDao(Connection conn){
this.conn = conn;
}
public void liberarRecursos(Connection conn, PreparedStatement ps, ResultSet rs){
if(conn != null){
try {
conn.close();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
if(ps != null){
try {
ps.close();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
if( rs != null){
try {
rs.close();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
}
public void inserirCartao(Cartao c){
PreparedStatement ps = null;
String sql = "INSERT INTO cartoes(numero_cartao, bandeira, hospede_id) VALUES(?,?,?) ";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, c.getNumeroCartao());
ps.setString(2, c.getBandeira());
ps.setInt(3, c.getHospedeId());
ps.executeUpdate();
conn.commit();
} catch (SQLException ex) {
try {
conn.rollback();
} catch (SQLException ex1) {
throw new RuntimeException(ex1);
}
throw new RuntimeException(ex);
}finally{
liberarRecursos(conn, ps, null);
}
}
public ArrayList<Cartao> listarCartoes(){
PreparedStatement ps = null;
ResultSet rs = null;
ArrayList<Cartao> cartoes = null;
String sql = "SELECT * FROM cartoes ";
try {
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
cartoes = new ArrayList<>();
while(rs.next()){
Cartao c = new Cartao();
c.setCartaoId(rs.getInt("cartao_id"));
c.setNumeroCartao(rs.getString("numero_cartao"));
c.setBandeira(rs.getString("bandeira"));
c.setHospedeId(rs.getInt("hospede_id"));
cartoes.add(c);
}
return cartoes;
} catch (SQLException ex) {
throw new RuntimeException(ex);
}finally{
liberarRecursos(conn, ps, rs);
}
}
public ArrayList<Cartao> listarCartoesPorHospede(int hospedeId){
PreparedStatement ps = null;
ResultSet rs = null;
ArrayList<Cartao> cartoes = null;
String sql = "SELECT * FROM cartoes WHERE hospede_id = ? ";
try {
ps = conn.prepareStatement(sql);
ps.setInt(1, hospedeId);
rs = ps.executeQuery();
cartoes = new ArrayList<>();
while(rs.next()){
Cartao c = new Cartao();
c.setCartaoId(rs.getInt("cartao_id"));
c.setNumeroCartao(rs.getString("numero_cartao"));
c.setBandeira(rs.getString("bandeira"));
c.setHospedeId(rs.getInt("hospede_id"));
cartoes.add(c);
}
return cartoes;
} catch (SQLException ex) {
throw new RuntimeException(ex);
}finally{
liberarRecursos(conn, ps, rs);
}
}
public Cartao buscarCartoesPorNumero(String numCartao){
PreparedStatement ps = null;
ResultSet rs = null;
String sql = "SELECT * FROM cartoes WHERE numero_cartao = ? ";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, numCartao);
rs = ps.executeQuery();
Cartao c = new Cartao();
while(rs.next()){
c.setCartaoId(rs.getInt("cartao_id"));
c.setNumeroCartao(rs.getString("numero_cartao"));
c.setBandeira(rs.getString("bandeira"));
c.setHospedeId(rs.getInt("hospede_id"));
}
return c;
} catch (SQLException ex) {
throw new RuntimeException(ex);
}finally{
liberarRecursos(conn, ps, rs);
}
}
public Cartao buscarCartao(int cartaoId){
PreparedStatement ps = null;
ResultSet rs = null;
Cartao c = null;
String sql = "SELECT * FROM cartoes WHERE cartao_id = ? ";
try {
ps = conn.prepareStatement(sql);
ps.setInt(1, cartaoId);
rs = ps.executeQuery();
c= new Cartao();
while(rs.next()){
c.setCartaoId(rs.getInt("cartao_id"));
c.setNumeroCartao(rs.getString("numero_cartao"));
c.setBandeira(rs.getString("bandeira"));
c.setHospedeId(rs.getInt("hospede_id"));
}
return c;
} catch (SQLException ex) {
throw new RuntimeException(ex);
}finally{
liberarRecursos(conn, ps, rs);
}
}
public void atualizarCartao(Cartao c){
PreparedStatement ps = null;
String sql = "UPDATE cartoes SET numero_cartao = ?, bandeira = ?, hospede_id = ? WHERE cartao_id = ? ";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, c.getNumeroCartao());
ps.setString(2, c.getBandeira());
ps.setInt(3, c.getHospedeId());
ps.setInt(4, c.getCartaoId());
ps.executeUpdate();
conn.commit();
} catch (SQLException ex) {
try {
conn.rollback();
} catch (SQLException ex1) {
throw new RuntimeException(ex1);
}
throw new RuntimeException(ex);
}finally{
liberarRecursos(conn, ps, null);
}
}
public void excluirCartao(int cartaoId){
PreparedStatement ps = null;
String sql = "DELETE FROM cartoes WHERE cartao_id = ? ";
try {
ps = conn.prepareStatement(sql);
ps.setInt(1, cartaoId);
ps.executeUpdate();
conn.commit();
} catch (SQLException ex) {
try {
conn.rollback();
} catch (SQLException ex1) {
throw new RuntimeException(ex1);
}
throw new RuntimeException(ex);
}finally{
liberarRecursos(conn, ps, null);
}
}
}
<file_sep>/src/br/com/hotel/dao/CategoriaDao.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.hotel.dao;
import br.com.hotel.modelo.Categoria;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
/**
*
* @author Daylton e Guilherme
*/
public class CategoriaDao {
private Connection conn;
public CategoriaDao(Connection conn){
this.conn = conn;
}
public void liberarRecursos(Connection conn, PreparedStatement ps, ResultSet rs){
if(conn != null){
try {
conn.close();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
if(ps != null){
try {
ps.close();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
if( rs != null){
try {
rs.close();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
}
public boolean inserirCategoria(Categoria c){
PreparedStatement ps = null;
String sql = "INSERT INTO categorias(nome_categoria) VALUES(?) ";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, c.getNomeCategoria());
ps.executeUpdate();
conn.commit();
return true;
} catch (SQLException ex) {
try {
conn.rollback();
} catch (SQLException ex1) {
throw new RuntimeException(ex1);
}
return false;
//throw new RuntimeException(ex);
}finally{
liberarRecursos(conn, ps, null);
}
}
public boolean alterarCategoria(Categoria c){
PreparedStatement ps = null;
String sql = "UPDATE categorias SET nome_categoria = ? WHERE categoria_id = ? ";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, c.getNomeCategoria());
ps.setInt(2, c.getCategoriaId());
ps.executeUpdate();
conn.commit();
return true;
} catch (SQLException ex) {
try {
conn.rollback();
} catch (SQLException ex1) {
throw new RuntimeException(ex1);
}
return false;
//throw new RuntimeException(ex);
}finally{
liberarRecursos(conn, ps, null);
}
}
public Categoria buscarCategoria(int categoriaId){
PreparedStatement ps = null;
ResultSet rs = null;
String sql = "SELECT * FROM categorias WHERE categoria_id = ? ";
try {
ps = conn.prepareStatement(sql);
ps.setInt(1, categoriaId);
rs = ps.executeQuery();
Categoria c = new Categoria();
while(rs.next()){
c.setCategoriaId(rs.getInt("categoria_id"));
c.setNomeCategoria("nome_categoria");
}
return c;
} catch (SQLException ex) {
throw new RuntimeException(ex);
}finally{
liberarRecursos(conn, ps, rs);
}
}
public ArrayList<Categoria> listarCategorias(){
PreparedStatement ps = null;
ResultSet rs = null;
ArrayList<Categoria> categorias = null;
String sql = "SELECT * FROM categorias ";
try {
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
categorias = new ArrayList<>();
while(rs.next()){
Categoria c = new Categoria();
c.setCategoriaId(rs.getInt("categoria_id"));
c.setNomeCategoria(rs.getString("nome_categoria"));
categorias.add(c);
}
return categorias;
} catch (SQLException ex) {
throw new RuntimeException(ex);
}finally{
liberarRecursos(conn, ps, rs);
}
}
public void excluirCategoria(int categoriaId){
PreparedStatement ps = null;
String sql = "DELETE FROM categorias WHERE categoria_id = ? ";
try {
ps = conn.prepareStatement(sql);
ps.setInt(1, categoriaId);
ps.executeUpdate();
conn.commit();
} catch (SQLException ex) {
try {
conn.rollback();
} catch (SQLException ex1) {
throw new RuntimeException(ex1);
}
throw new RuntimeException(ex);
}finally{
liberarRecursos(conn, ps, null);
}
}
}
<file_sep>/src/br/com/hotel/modelo/TipoAcomodacao.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.hotel.modelo;
/**
*
* @author guilherme
*/
public class TipoAcomodacao {
private int tipoAcomodacaoId;
private String descricao;
private int qtdeAcomodacoes;
private double valorDiaria;
private int numAdultos;
private int numCriancas;
public int getTipoAcomodacaoId() {
return tipoAcomodacaoId;
}
public void setTipoAcomodacaoId(int tipoAcomodacaoId) {
this.tipoAcomodacaoId = tipoAcomodacaoId;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public int getQtdeAcomodacoes() {
return qtdeAcomodacoes;
}
public void setQtdeAcomodacoes(int qtdeAcomodacoes) {
this.qtdeAcomodacoes = qtdeAcomodacoes;
}
public double getValorDiaria() {
return valorDiaria;
}
public void setValorDiaria(double valorDiaria) {
this.valorDiaria = valorDiaria;
}
public int getNumAdultos() {
return numAdultos;
}
public void setNumAdultos(int numAdultos) {
this.numAdultos = numAdultos;
}
public int getNumCriancas() {
return numCriancas;
}
public void setNumCriancas(int numCriancas) {
this.numCriancas = numCriancas;
}
@Override
public String toString() {
return this.descricao;
}
}
<file_sep>/src/br/com/hotel/dao/ConsumoDao.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.hotel.dao;
import br.com.hotel.modelo.Consumo;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author guilherme
*/
public class ConsumoDao {
private Connection conn;
public ConsumoDao(Connection conn){
this.conn = conn;
}
public void liberarRecursos(Connection conn, PreparedStatement ps, ResultSet rs){
if(conn != null){
try {
conn.close();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
if(ps != null){
try {
ps.close();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
if( rs != null){
try {
rs.close();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
}
public void inserirConsumo(Consumo c){
PreparedStatement ps = null;
String sql = "insert into consumos(data_consumo, num_acomodacao, item_id, qtde_consumida) values(?,?,?,?);";
try {
ps = conn.prepareStatement(sql);
ps.setDate(1, new Date(c.getDataConsumo().getTime()));
ps.setInt(2, c.getNumAcomodacao());
ps.setInt(3, c.getItemId());
ps.setInt(4, c.getQtdeConsumida());
ps.executeUpdate();
conn.commit();
} catch (SQLException ex) {
try {
conn.rollback();
} catch (SQLException ex1) {
throw new RuntimeException(ex1);
}
throw new RuntimeException(ex);
}finally{
liberarRecursos(conn, ps, null);
}
}
public ArrayList<Consumo> listarConsumos(){
PreparedStatement ps = null;
ResultSet rs = null;
ArrayList<Consumo> consumos;
String sql = "select * from consumos;";
try {
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
consumos = new ArrayList<>();
while(rs.next()){
Consumo c = new Consumo();
c.setConsumoId(rs.getInt("consumo_id"));
c.setDataConsumo(rs.getDate("data_consumo"));
c.setItemId(rs.getInt("item_id"));
c.setQtdeConsumida(rs.getInt("qtde_consumida"));
consumos.add(c);
}
return consumos;
} catch (SQLException ex) {
throw new RuntimeException(ex);
}finally{
liberarRecursos(conn, ps, rs);
}
}
public ArrayList<Consumo> listarConsumoPorAcomodacao(int numeroAcomodacao){
PreparedStatement ps = null;
ResultSet rs = null;
ArrayList<Consumo> consumos;
String sql = "select * from consumos where num_acomodacao = ?;";
try {
ps = conn.prepareStatement(sql);
ps.setInt(1, numeroAcomodacao);
rs = ps.executeQuery();
consumos = new ArrayList<>();
while(rs.next()){
Consumo c = new Consumo();
c.setConsumoId(rs.getInt("consumo_id"));
c.setDataConsumo(rs.getDate("data_consumo"));
c.setItemId(rs.getInt("item_id"));
c.setQtdeConsumida(rs.getInt("qtde_consumida"));
consumos.add(c);
}
return consumos;
} catch (SQLException ex) {
throw new RuntimeException(ex);
}finally{
liberarRecursos(conn, ps, rs);
}
}
public Consumo buscarConsumo(int consumoId){
PreparedStatement ps = null;
ResultSet rs = null;
Consumo c = null;
String sql = "select * from consumos where consumo_id = ?;";
try {
ps = conn.prepareStatement(sql);
ps.setInt(1, consumoId);
rs = ps.executeQuery();
c = new Consumo();
while(rs.next()){
c.setConsumoId(rs.getInt("consumo_id"));
c.setDataConsumo(rs.getDate("data_consumo"));
c.setItemId(rs.getInt("item_id"));
c.setQtdeConsumida(rs.getInt("qtde_consumida"));
}
return c;
} catch (SQLException ex) {
throw new RuntimeException(ex);
}finally{
liberarRecursos(conn, ps, rs);
}
}
public void atualizarConsumo(Consumo c){
PreparedStatement ps = null;
String sql = "update consumos set data_consumo = ?, num_acomodacao = ?, item_id = ?, qtde_consumida = ? where consumo_id = ?;";
try {
ps = conn.prepareStatement(sql);
ps.setDate(1, new Date(c.getDataConsumo().getTime()));
ps.setInt(2, c.getNumAcomodacao());
ps.setInt(3, c.getItemId());
ps.setInt(4, c.getQtdeConsumida());
ps.setInt(5, c.getConsumoId());
ps.executeUpdate();
conn.commit();
} catch (SQLException ex) {
try {
conn.rollback();
} catch (SQLException ex1) {
throw new RuntimeException(ex1);
}
throw new RuntimeException(ex);
}finally{
liberarRecursos(conn, ps, null);
}
}
public void excluirConsumo(int consumoId){
PreparedStatement ps = null;
String sql = "delete from consumos where consumo_id = ?;";
try {
ps = conn.prepareStatement(sql);
ps.setInt(1, consumoId);
ps.executeUpdate();
conn.commit();
} catch (SQLException ex) {
try {
conn.rollback();
} catch (SQLException ex1) {
throw new RuntimeException(ex1);
}
throw new RuntimeException(ex);
}finally{
liberarRecursos(conn, ps, null);
}
}
}
<file_sep>/src/br/com/hotel/tabela/TableModelAcompanhantes.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.hotel.tabela;
import br.com.hotel.modelo.Acompanhante;
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;
/**
*
* @author daylton
*/
public class TableModelAcompanhantes extends AbstractTableModel{
private String[] nomesColunas = {"Nome", "Idade"};
private ArrayList<Acompanhante> listaAcompanhantes;
public TableModelAcompanhantes(){
listaAcompanhantes = new ArrayList<>();
}
public void preencherLista(ArrayList<Acompanhante> listaAcompanhantes){
this.listaAcompanhantes.addAll(listaAcompanhantes);
}
public Acompanhante retornarObjetoSelecionado(int linha){
return listaAcompanhantes.get(linha);
}
@Override
public int getRowCount() {
return listaAcompanhantes.size();
}
@Override
public int getColumnCount() {
return nomesColunas.length;
}
@Override
public String getColumnName(int column) {
return nomesColunas[column];
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Acompanhante a = listaAcompanhantes.get(rowIndex);
switch(columnIndex){
case 0:
return a.getNome();
case 1:
return a.getIdade();
default:
throw new UnsupportedOperationException("Operation not Suport!");
}
}
}
|
4484c73fe162797b02604fddc13cc0da50879e18
|
[
"Java",
"SQL"
] | 15 |
Java
|
guihetz/ProjetoDsi
|
2eacc1f664f2000d94a348f3fa060d8d9acaa424
|
4d8b69ae5d3ef5a0541ee68e79ef517956cafc20
|
refs/heads/master
|
<repo_name>alchemz/ARcore_MultipleObjects_Interaction<file_sep>/ARcore_MultipleObjects_Interaction/Assets/ObjectToMove.cs
//reference: https://docs.unity3d.com/ScriptReference/Vector3.Lerp.html
//move from one endpoint to anther endpoint
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectToMove : MonoBehaviour {
public Transform startMarker;
public Vector3 endMarker;
public float speed = 0.1F;
private float startTime;
private float journeyLength;
// Use this for initialization
void Start () {
journeyLength =0;
}
void Update()
{
if (journeyLength > 0)
{
float distCovered = (Time.time - startTime) * speed;
float fracJourney = distCovered / journeyLength;
transform.position = Vector3.Lerp(startMarker.position, endMarker, fracJourney);
}
}
public void HitToMove(Vector3 endPos)
{
startMarker = this.transform;
endMarker = endPos;
startTime = Time.time;
journeyLength = Vector3.Distance(startMarker.position, endMarker);
}
}
|
57a4af4bab9a63e903691fdd098e8aaebadb98b6
|
[
"C#"
] | 1 |
C#
|
alchemz/ARcore_MultipleObjects_Interaction
|
32ef36f920e3b1f23a7ef9cd9d0234f29b077b35
|
db6babaa57bf4ebf58ce7dfdce509ba5f01f128f
|
refs/heads/main
|
<file_sep>var a = "a basic JS variable";
<file_sep>"""Development automation."""
from pathlib import Path
import tempfile
import nox
PACKAGE_NAME = "basic_ng_template"
nox.options.sessions = ["docs"]
@nox.session(name="docs-live", reuse_venv=True)
def docs_live(session):
_install_deps(session)
with tempfile.TemporaryDirectory() as destination:
session.run(
"sphinx-autobuild",
# for sphinx-autobuild
"--port=0",
"--watch=basic_ng_template",
"--watch=src",
"--open-browser",
"--pre-build=web-compile --exit-code 0",
# for sphinx
"-b=dirhtml",
"-a",
"docs",
destination,
env={"PYTHONPATH": "."},
)
@nox.session(reuse_venv=True)
def docs(session):
_install_deps(session)
session.run("web-compile", "--exit-code", "0")
session.run(
"sphinx-build",
"-b=dirhtml",
"-v",
"docs",
"docs/_build/example-docs",
env={"PYTHONPATH": "."},
)
def _install_deps(session):
if (Path(session.bin) / "sphinx-build").exists() and "reinstall" not in session.posargs:
return
session.install("-e", ".[docs]")
<file_sep># Section 2
```{toctree}
page-two-one
page-two-two
```
<file_sep># Sample Documentation
This is sample documentation, showing how `sphinx-basic-ng` can be used to
simplify the development of a Sphinx theme.
```{toctree}
top-level-one
section-one/index
section-two/index
top-level-two
```
## Header two
Lorem ipsum dolor sit amet consectetur adipisicing elit. Soluta quod
nulla officia! Ratione voluptate distinctio in architecto! Reprehenderit
neque dicta in eligendi similique obcaecati eos? Quibusdam assumenda
pariatur dolore voluptas?
```{toctree}
:caption: Caption!
:titlesonly:
top-level-three
```
## Header three
### Header four
Lorem ipsum dolor sit amet consectetur adipisicing elit. Soluta quod
nulla officia! Ratione voluptate distinctio in architecto! Reprehenderit
neque dicta in eligendi similique obcaecati eos? Quibusdam assumenda
pariatur dolore voluptas?
<file_sep># sphinx-basic-ng-template
This is a simple template repository to prototype what it looks like to sub-theme the [sphinx-basic-ng theme](https://sphinx-basic-ng.readthedocs.io/en/latest/).
## Goals of this template
- Utilize a python-only stack
- Show off some nice workflows for SCSS and JS compilation
- Only utilize the workflows that 80% of themes might be interested in
- Be copyable for other theme authors that want to use this as a starting point
## Notable aspects of this template
### SCSS and JS source files
Stored in `src/scss` and `src/js`, respectively.
These are compiled at build time with the [web-compile package](https://github.com/executablebooks/web-compile) to generate CSS and JS assets for our theme. They are then placed in `basic_ng_template/theme/basic_ng_template/static`.
The compiled CSS and JS assets are **not** included in the commit history of the package (they are listed in `.gitignore`). They will exist locally if you make a commit (via `pre-commit`) or run a build via `nox`, but they won't be included with your GitHub repository online.
This allows you to avoid creating clashes in PRs if multiple people modify an SCSS or JS file at the same time.
### Theme asset linking
Handled by the Python script at `basic_ng_template/__init__.py`.
This uses the `app.add_css_file` and `app.add_js_file` method to link the assets used by this theme.
We also generate a **hash** for each asset that we generate from its file contents.
The hash is used along with a `digest=` parameter, which will cause browsers to update to the latest versions of these assets when they are re-built.
### Theme configuration
Is located in `basic_ng_template/theme/basic_ng_template/theme.conf`.
This is left intentionally minimal - it simply declares the `basic-ng` theme as its parent.
### Theme HTML sections
This theme over-rides all of the sections defined by the `basic-ng` theme.
These are all located in `basic_ng_template/theme/basic_ng_template/sections/<section-name>.html`.
See the [sphinx-basic-ng documentation](https://sphinx-basic-ng.readthedocs.io/en/latest/) for more information about how these sections can be over-ridden.
### Theme HTML components
This theme also defines a custom component that is embedded in a section.
This component is located in `basic_ng_template/theme/basic_ng_template/components/mycustomcomponent.html`.
## Demo this theme
To demonstrate how this theme looks, first clone this repository:
```console
$ git clone https://github.com/choldgraf/sphinx-basic-ng-template
```
install `nox`:
```console
$ pip install nox
```
build the theme with `nox`:
```console
$ nox -s docs-live
```
This will install the necessary dependencies, build the sample documentation for this theme, and open a live server in your browser to preview the theme's built HTML.
<file_sep># Section 1
```{toctree}
page-one-one
page-one-two
```
<file_sep><!-- Intentionally blank --><file_sep># Page 3
Lorem ipsum dolor sit amet consectetur adipisicing elit. Soluta quod
nulla officia! Ratione voluptate distinctio in architecto! Reprehenderit
neque dicta in eligendi similique obcaecati eos? Quibusdam assumenda
pariatur dolore voluptas?
## Heading 1
Lorem ipsum dolor sit amet consectetur adipisicing elit. Soluta quod
nulla officia! Ratione voluptate distinctio in architecto! Reprehenderit
neque dicta in eligendi similique obcaecati eos? Quibusdam assumenda
pariatur dolore voluptas?
## Heading 2
Lorem ipsum dolor sit amet consectetur adipisicing elit. Soluta quod
nulla officia! Ratione voluptate distinctio in architecto! Reprehenderit
neque dicta in eligendi similique obcaecati eos? Quibusdam assumenda
pariatur dolore voluptas?
## Heading 3
Lorem ipsum dolor sit amet consectetur adipisicing elit. Soluta quod
nulla officia! Ratione voluptate distinctio in architecto! Reprehenderit
neque dicta in eligendi similique obcaecati eos? Quibusdam assumenda
pariatur dolore voluptas?
## Heading 4
Lorem ipsum dolor sit amet consectetur adipisicing elit. Soluta quod
nulla officia! Ratione voluptate distinctio in architecto! Reprehenderit
neque dicta in eligendi similique obcaecati eos? Quibusdam assumenda
pariatur dolore voluptas?
## Heading 5
Lorem ipsum dolor sit amet consectetur adipisicing elit. Soluta quod
nulla officia! Ratione voluptate distinctio in architecto! Reprehenderit
neque dicta in eligendi similique obcaecati eos? Quibusdam assumenda
pariatur dolore voluptas?
## Heading 6
Lorem ipsum dolor sit amet consectetur adipisicing elit. Soluta quod
nulla officia! Ratione voluptate distinctio in architecto! Reprehenderit
neque dicta in eligendi similique obcaecati eos? Quibusdam assumenda
pariatur dolore voluptas?
## Heading 7
Lorem ipsum dolor sit amet consectetur adipisicing elit. Soluta quod
nulla officia! Ratione voluptate distinctio in architecto! Reprehenderit
neque dicta in eligendi similique obcaecati eos? Quibusdam assumenda
pariatur dolore voluptas?
## Heading 8
Lorem ipsum dolor sit amet consectetur adipisicing elit. Soluta quod
nulla officia! Ratione voluptate distinctio in architecto! Reprehenderit
neque dicta in eligendi similique obcaecati eos? Quibusdam assumenda
pariatur dolore voluptas?
## Heading 9
Lorem ipsum dolor sit amet consectetur adipisicing elit. Soluta quod
nulla officia! Ratione voluptate distinctio in architecto! Reprehenderit
neque dicta in eligendi similique obcaecati eos? Quibusdam assumenda
pariatur dolore voluptas?
## Heading 10
Lorem ipsum dolor sit amet consectetur adipisicing elit. Soluta quod
nulla officia! Ratione voluptate distinctio in architecto! Reprehenderit
neque dicta in eligendi similique obcaecati eos? Quibusdam assumenda
pariatur dolore voluptas?
## Heading 11
Lorem ipsum dolor sit amet consectetur adipisicing elit. Soluta quod
nulla officia! Ratione voluptate distinctio in architecto! Reprehenderit
neque dicta in eligendi similique obcaecati eos? Quibusdam assumenda
pariatur dolore voluptas?
## Heading 12
Lorem ipsum dolor sit amet consectetur adipisicing elit. Soluta quod
nulla officia! Ratione voluptate distinctio in architecto! Reprehenderit
neque dicta in eligendi similique obcaecati eos? Quibusdam assumenda
pariatur dolore voluptas?
## Heading 13
Lorem ipsum dolor sit amet consectetur adipisicing elit. Soluta quod
nulla officia! Ratione voluptate distinctio in architecto! Reprehenderit
neque dicta in eligendi similique obcaecati eos? Quibusdam assumenda
pariatur dolore voluptas?
## Heading 14
Lorem ipsum dolor sit amet consectetur adipisicing elit. Soluta quod
nulla officia! Ratione voluptate distinctio in architecto! Reprehenderit
neque dicta in eligendi similique obcaecati eos? Quibusdam assumenda
pariatur dolore voluptas?
## Heading 15
Lorem ipsum dolor sit amet consectetur adipisicing elit. Soluta quod
nulla officia! Ratione voluptate distinctio in architecto! Reprehenderit
neque dicta in eligendi similique obcaecati eos? Quibusdam assumenda
pariatur dolore voluptas?
## Heading 16
Lorem ipsum dolor sit amet consectetur adipisicing elit. Soluta quod
nulla officia! Ratione voluptate distinctio in architecto! Reprehenderit
neque dicta in eligendi similique obcaecati eos? Quibusdam assumenda
pariatur dolore voluptas?
## Heading 17
Lorem ipsum dolor sit amet consectetur adipisicing elit. Soluta quod
nulla officia! Ratione voluptate distinctio in architecto! Reprehenderit
neque dicta in eligendi similique obcaecati eos? Quibusdam assumenda
pariatur dolore voluptas?
<file_sep>"""A modern skeleton for Sphinx themes."""
__version__ = "0.0.1"
from pathlib import Path
from typing import Any, Dict
from functools import lru_cache
import hashlib
import sphinx
_THEME_PATH = (Path(__file__).parent / "theme" / "basic_ng_template").resolve()
_STATIC_PATH = _THEME_PATH / "static"
def _html_page_context(
app: sphinx.application.Sphinx,
pagename: str,
templatename: str,
context: Dict[str, Any],
doctree: Any,
) -> None:
# Add a variable to the Sphinx context
context["myfootertext"] = "here's some demo footer text!"
def setup(app: sphinx.application.Sphinx) -> Dict[str, Any]:
"""Entry point for sphinx theming."""
app.require_sphinx("3.0")
# This activates the theme so users can use it in their docs
app.add_html_theme("basic-ng-template", str(_THEME_PATH))
# This adds a basic function that is called each time an HTML page is generated
app.connect("html-page-context", _html_page_context)
# Manually add CSS and JS files here so we can use *hashes*.
# This allows us to do cache-busting without hard-coding the hash in the filename.
path_css = _STATIC_PATH / "basic-ng-template.css"
digest_css = hashlib.sha1(path_css.read_bytes()).hexdigest()
app.add_css_file(f"{path_css.relative_to(_STATIC_PATH)}?digest={digest_css}")
path_js = _STATIC_PATH / "basic-ng-template.js"
digest_js = hashlib.sha1(path_js.read_bytes()).hexdigest()
app.add_js_file(f"{path_js.relative_to(_STATIC_PATH)}?digest={digest_js}")
return {
"parallel_read_safe": True,
"parallel_write_safe": True,
}
|
8887f7d13b8b432d17cb5ae402a87271263adb88
|
[
"JavaScript",
"Python",
"Markdown"
] | 9 |
JavaScript
|
choldgraf/sphinx-basic-ng-template
|
3ebd6401543a845160ff0191d6966df0e490156f
|
af3cd054f26a0bb27f5b7e0cf86cbc9765474302
|
refs/heads/master
|
<file_sep><?php
class Hotelslist extends CActiveRecord
{
public static function model($className = __CLASS__)
{
return parent::model($className);
}
public function relations()
{
return array(
'description'=>array(self::HAS_MANY,'Hotelsdescription','HotelCode'),
'amenities'=>array(self::HAS_MANY,'Hotelsamenities','HotelCode'),
'rusAmenities' => array(self::HAS_MANY, 'Hotelinforus', 'HotelCode')
);
}
public function tableName()
{
return 'hotelslist';
}
}<file_sep><ul id="menu">
<li><?php echo CHtml::link('На главную',array(Yii::app()->createUrl('site'))); ?></li>
<li><?php echo CHtml::link('О проетке',array('about')); ?></li>
<li><?php echo CHtml::link('Заказы',array('booking/bookingstatus')); ?></li>
</ul><file_sep><!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" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="language" content="en" />
<link href="<?=baseUrl().'/public/images/favicon.ico'?>" rel="shortcut icon" type="image/x-icon" />
<?php
registerCss("/public/css/style.css");
registerCss("/public/css/menu.css");
registerScript("/public/js/upButton.js");
?>
<title><?php echo CHtml::encode($this->pageTitle); ?></title>
</head>
<body>
<div id="total">
<div id="main">
<div id="header">
<div id="logo">
<a href="<?=Yii::app()->homeUrl?>">
<img src="<? echo baseUrl().'/public/images/my_Logo.png';?>" alt="logo"/>
</a>
</div>
<div id="menu">
<?php $this->widget('UserMenu'); ?>
</div>
</div>
<div id="content">
<?php echo $content; ?>
</div>
</div>
<div id="footer_space"></div>
</div>
<div id="footer">
© Copyright
</div>
</body>
</html>
<file_sep><table>
<tr>
<td>
<label>Код операции бронирования:</label>
</td>
<td>
<?=$cancelHotelBooking->trackingId?>
</td>
</tr>
<tr>
<td>
<label>Состояние заказа:</label>
</td>
<td>
<?=$cancelHotelBooking->bookingStatus;?>
</td>
</tr>
<tr>
<td>
<label>Комментарий:</label>
</td>
<td>
<?=$cancelHotelBooking->note;?>
</td>
</tr>
<tr>
<td>
<label>Номер агенства:</label>
</td>
<td>
<?=$cancelHotelBooking->agencyReferenceNumber;?>
</td>
</tr>
</table>
<file_sep><?php
/**
* This is the model class for table "hotelinforus".
*
* The followings are the available columns in table 'hotelinforus':
* @property string $hotelCode
* @property string $hotelName
* @property string $hotelAddress
* @property string $hotelDescription
* @property string $hotelAmenities
* @property string $roomAmenities
*/
class Hotelinforus extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* @param string $className active record class name.
* @return Hotelinforus the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'hotelinforus';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('hotelCode, hotelName, hotelAddress, hotelDescription, hotelAmenities, roomAmenities', 'required'),
array('hotelCode, hotelName, hotelAddress, hotelDescription, hotelAmenities, roomAmenities', 'length', 'max'=>255),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('hotelCode, hotelName, hotelAddress, hotelDescription, hotelAmenities, roomAmenities', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'list'=>array(self::BELONGS_TO,'Hotelslist','HotelCode'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'hotelCode' => 'Hotel Code',
'hotelName' => 'Hotel Name',
'hotelAddress' => 'Hotel Address',
'hotelDescription' => 'Hotel Description',
'hotelAmenities' => 'Hotel Amenities',
'roomAmenities' => 'Room Amenities',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('hotelCode',$this->hotelCode,true);
$criteria->compare('hotelName',$this->hotelName,true);
$criteria->compare('hotelAddress',$this->hotelAddress,true);
$criteria->compare('hotelDescription',$this->hotelDescription,true);
$criteria->compare('hotelAmenities',$this->hotelAmenities,true);
$criteria->compare('roomAmenities',$this->roomAmenities,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
}<file_sep><?php
class Controller extends CController
{
public $client;
public $dataDB;
public function init()
{
$this->client = new HotelsProAPI();
$this->dataDB = new DataReader();
}
}<file_sep><?php
require_once(dirname(__FILE__).'/protected/globals.php');
header('Content-Type: text/html; charset=UTF-8',true);
$yii=dirname(__FILE__).'/../framework/yii.php';
$config=dirname(__FILE__).'/protected/config/main.php';
defined('YII_DEBUG') or define('YII_DEBUG',true);
require_once($yii);
Yii::createWebApplication($config)->run();
<file_sep><script type="text/javascript"
src="http://maps.google.com/maps/api/js?v=3.9&sensor=false&&libraries=weather&language=ru&callback=initMap">
</script>
<script type="text/javascript">
var geocoder;
var icon = '/public/images/ih.png';
var center;
var map;
var currentPopup;
function addMarker(lat, lng, info) {
var point = new google.maps.LatLng(lat, lng);
var marker = new google.maps.Marker({
position: point,
icon: icon,
map: map
});
google.maps.event.addListener(marker, "click", function() {
popup = new google.maps.InfoWindow({
content: info,
maxWidth: 200
});
if (currentPopup != null) {
currentPopup.close();
currentPopup = null;
}
popup.open(map, marker);
currentPopup = popup;
});
}
function initMap() {
var destinations = <?=json_encode($coord)?>;
geocoder = new google.maps.Geocoder();
for(var i=0;i<destinations.length;i++){
if((destinations[i].Lat == "0.000000" || destinations[i].Lat == "") && (destinations[i].Long == "0.000000" || destinations[i].Long == "")){
}else{
var latlng = new google.maps.LatLng(destinations[i].Lat,destinations[i].Long);
}
}
map = new google.maps.Map(document.getElementById("map_canvas"), {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.BIG
}
});
var arr = new Array();
for(var i = 0; i<destinations.length; i++){
var city = destinations[i];
if((city.Lat == "0.000000" || city.Lat == "") && (city.Long == "0.000000" || city.Long == "")){
arr.push(city);
} else {
addMarker(city.Lat, city.Long, getInfo(city));
}
}
if(arr.length !=0){
for(var i=0;i<arr.length;++i){
(function(info){
geocoder.geocode( { 'address': arr[i].City + ',' + arr[i].HotelAddress + ',' + arr[i].Country},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
addMarker(results[0].geometry.location.lat(), results[0].geometry.location.lng(),info);
}
})
})(getInfo(arr[i]));
}
}
var weatherLayer = new google.maps.weather.WeatherLayer({
temperatureUnits: google.maps.weather.TemperatureUnit.Celsius
});
weatherLayer.setMap(map);
}
function getCoordinates(){
}
function getInfo(city){
return info = "<a href='<?=baseUrl().'/details/hotel/'?>"+city.HotelCode.toLowerCase()+
"/id/<?=strtolower(json_decode(Yii::app()->session['responseData'])->searchID)?>"+"'"+">"+
"<b>"+city.HotelName+"</b></a>"+
"<br><img src='"+city.Image+"' width=180 height=150 alt=image>"+
"<br><b><img src='<? echo baseUrl() . '/public/images/star_icon.png?>'?>'/>"+city.StarRating+"</b>"+
"<br>Полная стоимость: <b>$"+city.Price+"</b>";
}
</script>
<span id="title">
Найдено <? echo count($coord); ?> отелей.
</span>
<? if(count($coord) != 0): ?>
<div id="map_canvas" style="height:500px;margin-top: 20px">
</div>
<? endif; ?>
<file_sep><?php
class Hotelsdescription extends CActiveRecord
{
public static function model($className = __CLASS__)
{
return parent::model($className);
}
public function tableName()
{
return 'hotelsdescription';
}
public function relations()
{
return array(
'hotelCode' => array(self::BELONGS_TO, 'Hotelslist', 'HotelCode'),
);
}
}<file_sep><p>
Данный сервис поможет Вам забронировать номер в отеле в большинстве городов мира.
</p>
<file_sep><table>
<? if(isset($trackingID)): ?>
<tr>
<td>
<label>Код операции бронирования:</label>
</td>
<td>
<?=$trackingID?>
</td>
</tr>
<? endif; ?>
<? if(isset($getHotelBookingStatus->bookingStatus)):?>
<tr>
<td>
<label>Статус бронирования:</label>
</td>
<td>
<?
switch($getHotelBookingStatus->bookingStatus){
case 1: echo 'Заказ подтверждён'; break;
case 2: echo 'Заказ на рассмотрении'; break;
case 3: echo 'Заказ отклонён'; break;
case 4: echo 'Заказ отменён'; break;
case 5: echo 'Обработка платежа'; break;
}
?>
</td>
</tr>
<? endif; ?>
<? if(isset($getHotelBookingStatus->confirmationNumber)): ?>
<tr>
<td>
<label>Номер подтверждения:</label>
</td>
<td>
<?=$getHotelBookingStatus->confirmationNumber?>
</td>
</tr>
<? endif;
if(isset($getHotelBookingStatus->hotelCode)){
echo "<tr><td><label>Код отеля:</label></td><td><a href='".baseUrl().'/site/details?HotelCode='.$getHotelBookingStatus->hotelCode."'> $getHotelBookingStatus->hotelCode</a></td></tr>";
}
if(isset($getHotelBookingStatus->checkIn)){
echo "<tr><td><label>Дата прибытия:</label></td><td>$getHotelBookingStatus->checkIn</td></tr>";
}
if(isset($getHotelBookingStatus->checkOut)){
echo "<tr><td><label>Дата отъезда:</label></td><td>$getHotelBookingStatus->checkOut</td></tr>";
}
if(isset($getHotelBookingStatus->totalPrice)){
echo "<tr><td><label>Полная стоимость:</label></td><td>$getHotelBookingStatus->totalPrice</td></tr>";
}
if(isset($getHotelBookingStatus->totalSalePrice)){
echo "<tr><td><label>Скидка:</label></td><td>$getHotelBookingStatus->totalSalePrice</td></tr>";
}
if(isset($getHotelBookingStatus->currency)){
echo "<tr><td><label>Тип валюты:</label></td><td>$getHotelBookingStatus->currency</td></tr>";
}
if(isset($getHotelBookingStatus->boardType)){
echo "<tr><td><label>Тип комнаты:</label></td><td>$getHotelBookingStatus->boardType</td></tr>";
}
if(isset($getHotelBookingStatus->agencyReferenceNumber)){
echo "<tr><td><label>Номер агенства:</label></td><td>$getHotelBookingStatus->agencyReferenceNumber</td></tr>";
}
if(isset($getHotelBookingStatus->comments)){
echo "<tr><td><label>Комментарии:</label></td><td>$getHotelBookingStatus->comments</td></tr>";
}
?>
</table><file_sep><?php
class BookingController extends Controller {
public function actionIndex()
{
$searchData = unserialize(Yii::app()->cache['parameters']);
if(!isset($_POST['get_booking'])){
$response = $this->client->getHotelCancellationPolicy(Yii::app()->request->getParam('id'));
$policy = is_array($response->cancellationPolicy) ? $response->cancellationPolicy : array($response->cancellationPolicy);
$this->render('booking', array('data' => $searchData, 'policy' => $policy[0]));
}
else{
$info = $_POST['booking']['lead'];
$leadTraveller['paxInfo'] = array(
'paxType' => 'Adult',
'title' => $info['title'],
'firstName' => $info['1st_name'],
'lastName' => $info['2nd_name']
);
$leadTraveller['nationality'] = 'GB';
$otherTraveller = null;
if(isset($_POST['booking']['other'])){
$otherInfo = $_POST['booking']['other'];
for($i = 0; $i < count($otherInfo['title']); $i++){
$otherTraveller[] = array(
'title' => $otherInfo['title'][$i],
'firstName' => $otherInfo['1st_name'][$i],
'lastName' => $otherInfo['2nd_name'][$i]
);
}
}
$note = "";
if(isset($_POST['booking']['note'])){
$note = $_POST['booking']['note'];
}
$bookingResponse = $this->client->makeHotelBooking($leadTraveller, $otherTraveller, $_POST['processId'], "", $note);
$this->render('booking_status', array(
'getHotelBookingStatus' => $bookingResponse->hotelBookingInfo,
'trackingID' => $bookingResponse->trackingId
));
}
}
public function actionBookingStatus()
{
if(isset($_POST['getBookingStatus'])){
$trackingId = str_replace(' ', '',$_POST['status_trackingId']);
$getHotelBookingStatus = $this->client->getHotelBookingStatus($trackingId);
$this->render('booking_status', array(
'getHotelBookingStatus' => $getHotelBookingStatus->hotelBookingInfo,
'trackingID' => $getHotelBookingStatus->trackingId
)
);
}
elseif(isset($_POST['cancel'])){
$trackingId = str_replace(' ', '',$_POST['cancel_trackingId']);
$cancelHotelBooking = $this->client->cancelHotelBooking($trackingId);
$this->render('cancel_booking', array('cancelHotelBooking'=> $cancelHotelBooking));
}
else $this->render('get_booking_status');
}
}<file_sep><?php
class SiteController extends Controller
{
public function actions()
{
return array(
'page'=>array(
'class'=>'CViewAction',
),
);
}
public function actionIndex()
{
if(Yii::app()->cache->get('response')!==false){
Yii::app()->cache->delete('response');
}
$this->render('search');
}
public function actionAbout()
{
$this->render('about');
}
public function actionError()
{
if($error=Yii::app()->errorHandler->error)
{
if(Yii::app()->request->isAjaxRequest)
echo $error['message'];
else
$this->render('error', $error);
}
}
}
<file_sep><?php
class DetailsController extends Controller {
public function actionIndex()
{
$result = array();
$responseData = Yii::app()->request->getParam('id');
$hotelCode = Yii::app()->request->getParam('hotel');
$hotelsCode = $this->client->removeDuplicateHotels(unserialize(Yii::app()->cache->get('response')));
$hotel = join("','",$hotelsCode['hotelsCode']);
$data = Hotelslist::model()->findAll(array('condition'=>"HotelCode IN ('".$hotel."')"));
foreach($data as $key=>$val){
$result[] = $val->HotelCode;
}
$allocateHotelCode = $this->client->allocateHotelCode($hotelCode, $responseData);
$this->render('details',array(
'hotel'=>$this->dataDB->getHotelDescription($hotelCode),
'allocateResponse' => $allocateHotelCode,
'hotelsCode'=>$result,
));
}
}<file_sep> <?
registerCss('/public/css/jquery.qtip.min.css');
registerScript('/public/js/jquery.qtip.min.js');
registerScript('/public/js/messages_ru.js');
registerScript('/public/js/jquery.validate.min.js');
registerScript("/public/js/search_form.js");
Yii::app()->clientScript->registerScript('cities', "$(function(){
$('#param_city').chosen().change(function(){
var selected = $(this).find('option').eq(this.selectedIndex);
$('#city_id').attr('value', selected.attr('value'));
$('#search_city').attr('value', selected.text());
$('#param_city').trigger('liszt:updated');
});
$('#param_country').chosen().change(function(){
$('#param_city option').remove();
$('#param_city').append('<option>Выберите город...</option>');
$.post('". baseUrl()."/search/autocomplete','key='+$(this).val(), function(cities){
$.each(cities, function(){
$('#param_city').append($('<option value='+ this.id +'>' + this.city +'</option>'));
});
$('#param_city').trigger('liszt:updated');
}
);
});
});");
Yii::app()->clientScript->registerScript('datepickers',
'
$(function() {
$( "#coming_date" ).datepicker({
dateFormat: "yy-mm-dd",
changeMonth: true,
numberOfMonths: 1,
minDate: 1,
onSelect: function( selectedDate ) {
$( "#leaving_date" ).datepicker( "option", "minDate", selectedDate );
}
});
$( "#leaving_date" ).datepicker({
dateFormat: "yy-mm-dd",
changeMonth: true,
numberOfMonths: 1,
onClose: function( selectedDate ) {
$( "#coming_date" ).datepicker( "option", "maxDate", selectedDate );
}
});
});
$(function(){
if($("#is_child").is(":checked")){
$("#add_child").show();
$("#children_age").show()
}
})
')
?>
<form method="get" id=search_form class="adv_search" action="<?php echo baseUrl() ?>/search" style="padding-top: 10px; border-top: 1px solid rgba(173,170,140,0.63)">
<table>
<tr>
<td>
<label>Повторить поиск</label>
<input type="hidden" name="param[city_id]" id="city_id" value="<?=$parameters['city_id']?>"/>
<input type="hidden" name="param[search_city]" id="search_city" value="<?=$parameters['search_city']?>"/>
<?
$destinations = Hoteldestinations::model()->findAll(array(
'select' => 'Country',
'distinct' => true,
'order' => 'Country'));
$result = array();
foreach($destinations as $destination){
$result[$destination->Country] = $destination->Country;
}
echo CHtml::dropDownList('param[country]', '', $result, array(
'prompt'=> 'Выберите страну...',
'style' =>'width:180px',
'options' =>array(
$parameters['country'] => array(
'selected'=>'selected'
)
)
));
unset($result);
?>
</td>
</tr>
<tr>
<td >
<?
$cities = Hoteldestinations::model()->findAll('Country=:Country ORDER BY City', array(':Country'=>$parameters['country']));
$result = array();
foreach($cities as $destination){
$result[$destination->DestinationId] = $destination->City;
}
echo CHtml::dropDownList('param[city]', '', $result, array(
'empty'=> 'Выберите город...',
'style' =>'width:180px',
'options' =>array(
$parameters['city_id'] => array(
'selected'=>'selected'
)
)
));
unset($result);
?>
</td>
</tr>
<tr>
<td>
<input type="text" class="date_picker advanced" name="param[coming_date]" id="coming_date" autocomplete="off" style="width: 75px;" value="<? echo $parameters['coming_date']?>" placeholder="прибытие"/> -
<input type="text" class="date_picker advanced" name="param[leaving_date]" id="leaving_date" autocomplete="off" style="width: 75px;" value="<? echo $parameters['leaving_date']?>" placeholder="отъезд" />
</td>
<tr>
<td>
<label>Взрослых:<br></label>
<input type="text" name="param[adult_paxes]" id="adult" autocomplete="off" value="<? echo $parameters['adult_paxes']?>" placeholder="взрослых" style="width: 65px"/>
<input type="checkbox" name="param[is_child]" id="is_child" onchange="hide_block()" <?if(isset($parameters['is_child'])) echo "checked=true"?>/><label>  c детьми</label><br/>
</td>
</tr>
<tr id="add_child">
<td>
<label>Детей:</label><br/>
<input type="text" name="param[children_paxes]" id="children_paxes" autocomplete="off" style="width: 65px"
<?if(isset($parameters['is_child'])) echo "value=".$parameters['children_paxes']?>><br/>
</td>
</tr>
<tr id="children_age">
<td id="container">
<?if(isset($parameters['is_child']) && isset($parameters['child_age'])):?>
<?foreach($parameters['child_age'] as $key=>$value):?>
<label class="age_label">возраст детей<br/></label>
<input type="text" class="child_age" autocomplete="off" name="param[child_age][]" value="<?=$value?>" style="width:35px; margin-right:3px" />
<?endforeach?>
<?endif?>
</td>
</tr>
<tr>
<td>
<div id="button_wrap"><input type="submit" name="search_hotel" value="Повторить" /></div>
</td>
</tr>
</table>
</form><file_sep>$(function () {
var scroll_start = 200;
var top = 0;
$('body').append('<a href="#" id="gotop" title="Вверх"></a>');
var s = $('#gotop');
var margin_top = parseInt(s.css('top'));
function gotop_scroll() {
top = $(window).scrollTop();
if (top < scroll_start)s.fadeOut(400);
else s.css('opacity', 0.8).fadeIn(300)
}
$(window).scroll(gotop_scroll);
s.live(
{
mouseenter: function () {
if (top > scroll_start)$(this).fadeTo(200, 1.0)
}, mouseleave: function () {
if (top > scroll_start)$(this).fadeTo(400, 0.5)
}, click: function () {
$('html,body').animate({scrollTop: 0}, 'slow');
return false
}
}
)
}
);<file_sep>var geocoder;
var image = '/public/images/ih.png';
var map;
var markers = Array();
var infos = Array();
function addMarker(point)
{
var marker = new google.maps.Marker({
position: point,
icon: image,
map: map,
draggable:true
});
google.maps.event.addListener(marker, 'click', function(){
if (marker.getAnimation() != null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
});
}
function clearOverlays()
{
if (markers) {
for (i in markers) {
markers[i].setMap(null);
}
markers = [];
infos = [];
}
}
function clearInfo()
{
if (infos) {
for (i in infos) {
if (infos[i].getMap()) {
infos[i].close();
}
}
}
}
function initialize(address,lat,long,country,city)
{
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(lat,long);
var settings = {
zoom: 16,
center: latlng,
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),settings);
map.setMapTypeId(google.maps.MapTypeId.TERRAIN);
var transitLayer = new google.maps.TransitLayer();
transitLayer.setMap(map);
if((lat == "0.000000" || lat == "") && (long == "0.000000" || long == "")){
geocoder.geocode( { 'address': city+','+address+','+country}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
addMarker(results[0].geometry.location);
document.getElementById('lat').value = results[0].geometry.location.lat();
document.getElementById('lng').value = results[0].geometry.location.lng();
}
});
}else{
addMarker(latlng);
document.getElementById('lat').value = lat;
document.getElementById('lng').value = long;
}
}
function findPlaces()
{
var type = document.getElementById('gmap_type').value;
var radius = document.getElementById('gmap_radius').value;
var lat = document.getElementById('lat').value;
var lng = document.getElementById('lng').value;
var cur_location = new google.maps.LatLng(lat, lng);
var request = {
location: cur_location,
radius: radius,
types: [type]
};
service = new google.maps.places.PlacesService(map);
service.search(request, createMarkers);
}
function createMarkers(results, status)
{
if (status == google.maps.places.PlacesServiceStatus.OK) {
clearOverlays();
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
} else if (status == google.maps.places.PlacesServiceStatus.ZERO_RESULTS) {
alert('Извините, ничего не найдено');
}
}
function createMarker(obj)
{
var mark = new google.maps.Marker({
position: obj.geometry.location,
map: map,
title: obj.name
});
markers.push(mark);
var infowindow = new google.maps.InfoWindow({
content: '<img src="' + obj.icon + '" /><font style="color:#000;">' + obj.name +
'<br />Рейтинг: ' + obj.rating + '<br />Адрес: ' + obj.vicinity + '</font>'
});
google.maps.event.addListener(mark, 'click', function() {
clearInfo();
infowindow.open(map,mark);
});
infos.push(infowindow);
}<file_sep><?php
class SearchController extends Controller {
public function actionIndex()
{
Yii::app()->session['url'] = Yii::app()->request->getUrl();
Yii::app()->cache->set('parameters', serialize($_GET['param']));
$filter = null;
if(Yii::app()->request->cookies->contains('filter')){
$filter = unserialize(Yii::app()->request->cookies['filter']->value);
}
$this->render('hotels', array(
'hotels'=>$this->hotelsResponse(),
'filter' => $filter
), false);
}
public function actionAutocomplete()
{
if(isset($_POST['key'])){
$destinations = Hoteldestinations::model()->findAll('Country=:Country ORDER BY City', array(':Country'=>$_POST['key']));
$cities = array();
foreach($destinations as $city){
$cities[] = array('id' => $city->DestinationId, 'city' => $city->City);
}
header('Content-type: application/json');
echo json_encode($cities);
}
}
public function actionUpdate()
{
if(isset($_GET['search_hotel'])){
Yii::app()->cache->delete('response');
Yii::app()->cache->delete('parameters');
$this->setDataToCache();
}elseif(isset($_GET['search']) && Yii::app()->cache->get('response')===false){
$this->setDataToCache();
}
$hotelsCode = $this->client->removeDuplicateHotels(unserialize(Yii::app()->cache->get('response')));
$criteria = new CDbCriteria;
if(isset(Yii::app()->request->cookies['filter'])){
$filter = unserialize(Yii::app()->request->cookies['filter']->value);
$viewType = $filter['radio'];
}else{
$viewType = '_hotelview';
}
$params = array();
if(isset($_GET['adv_param'])) {
Yii::app()->request->cookies['filter'] = new CHttpCookie('filter',serialize($_GET['adv_param']));
foreach($_GET['adv_param'] as $key=>$value){
$params['adv_param'][$key] = $value;
}
$filterResult = $this->dataDB->filterSearchData($_GET['adv_param'], $hotelsCode);
$criteria = $filterResult['criteria'];
$viewType = $filterResult['viewType'];
$hotelsCode = $filterResult['hotelsCode'];
}
$criteria->addInCondition('HotelCode', $hotelsCode['hotelsCode'], 'AND');
if($viewType == '_mapview'){
$this->actionMap();
}else{
$dataProvider = new CActiveDataProvider(Hotelslist::model(), array(
'pagination' => array(
'pageSize' => 12,
'route' => 'search/update',
'params' => $params
),
'criteria' => $criteria,
'sort' => $this->Sort($_GET["adv_param"]),
));
$this->renderPartial('views/listview',array(
'dataProvider'=>$dataProvider,
'availableRooms' => $hotelsCode['availableRooms'],
'hotels'=>$this->hotelsResponse(),
'viewType' => $viewType,
'template' => Yii::app()->params[$viewType],
'priceRange' => $hotelsCode['priceRange']
), false, true);
}
}
private function hotelsResponse()
{
$response = unserialize(Yii::app()->cache->get('response'));
if(isset($response->availableHotels)){
if (is_object($response->availableHotels)) {
$hotels[] = $response->availableHotels;
} else {
$hotels = $response->availableHotels;
}
return $hotels;
}
}
private function setDataToCache()
{
$response = $this->client->getAvailableHotel($_GET['param']);
Yii::app()->cache->set('response', serialize($response));
Yii::app()->cache->set('parameters', serialize($_GET['param']));
Yii::app()->session['responseData'] = json_encode(array(
'responseID' => $response->responseId,
'searchID' => $response->searchId
));
}
private function Sort($paramsFromUrl)
{
$sort = new CSort();
$sort->sortVar = 'sort';
$sort->defaultOrder = 'HotelName ASC';
$sort->multiSort = true;
$sort->attributes = array(
'hotelName'=>array(
'label'=>'названию',
'asc'=>'HotelName ASC',
'desc'=>'HotelName DESC',
'default'=>'desc',
),
'starRating'=>array(
'asc'=>'StarRating ASC',
'desc'=>'StarRating DESC',
'default'=>'desc',
'label'=>'звёздам',
),
);
$sort->route = 'search/update';
$params = array();
foreach($paramsFromUrl as $key=>$value){
$params['adv_param'][$key] = $value;
}
$sort->params = $params;
return $sort;
}
public function actionMap()
{
$hotelsCode = $this->client->removeDuplicateHotels(unserialize(Yii::app()->cache->get('response')));
$filterResult = $this->dataDB->filterSearchData($_GET['adv_param'], $hotelsCode);
$criteria = $filterResult['criteria'];
$hotelsCode = $filterResult['hotelsCode'];
$criteria->addInCondition('HotelCode', $hotelsCode['hotelsCode'], 'AND');
$info = Hotelslist::model()->findAll($criteria);
$coord = array();
foreach ($info as $hotels) {
foreach($this->hotelsResponse() as $key=>$val){
if($val->hotelCode == $hotels->HotelCode){
$images = explode(';',$hotels->HotelImages);
$coord[] = array(
'Country' => $hotels->Country,
'City' => $hotels->Destination,
'HotelName' => $hotels->HotelName,
'HotelCode' => $hotels->HotelCode,
'Long' => $hotels->Longitude,
'HotelAddress' =>$hotels->HotelAddress,
'Lat' => $hotels->Latitude,
'StarRating' => $hotels->StarRating,
'Image' => $images[0],
'Price' => $val->totalPrice,
);
break;
}
}
}
$this->renderPartial('views/_mapview', array(
'coord' => $coord,
), false, true);
}
}<file_sep><?php
class DataReader
{
public function getHotelDescription($hotelCode)
{
$hotels = Hotelslist::model()->find('HotelCode=:HotelCode',array(':HotelCode'=>$hotelCode));
return $hotels;
}
public function filterSearchData($filter, $hotelsCode)
{
$criteria = new CDbCriteria;
$result = array();
$viewType = $filter['radio'];
$amenities = array_slice($filter,3);
$queryString = "";
if(count($amenities)){
foreach($amenities as $key=>$value){
$queryString .= " AND PAmenities LIKE '%$value%' ";
}
}
foreach($filter as $key=>$value){
if($key == 'price'){
$hotelsCode = HotelsProAPI::sortByPrice($value, unserialize(Yii::app()->cache->get('response')));
}elseif($key == 'StarRating'){
$criteria->addInCondition($key,$this->pullStarRange($value), 'AND');
}else{
$hotelCode = join("','",$hotelsCode['hotelsCode']);
$data = Hotelsamenities::model()->findAll(array('condition'=>"HotelCode IN ('".$hotelCode."') ".$queryString));
foreach($data as $key=>$val){
$result[] = $val->HotelCode;
}
$hotels = join("','",$result);
$criteria->addCondition("HotelCode IN ('".$hotels."')",'AND');
}
}
return array('criteria' => $criteria, 'viewType' => $viewType, 'hotelsCode' => $hotelsCode);
}
private function pullStarRange($inputRange){
$range = explode('-',$inputRange);
return range($range[0], $range[1]);
}
}<file_sep><?php
class HotelsProAPI
{
function __construct()
{
$this->client = new SoapClient(Yii::app()->params['HP_WSDL_PATH'], array('trace' => 1));
}
/**
* this function makes a request to the HotelPro service and return founded Hotels
* @param $param array that contains next data: CityCode, CheckIn date, CheckOut date, number of adult paxes, number of child paxes if they are defined
* @return mixed - response from service, object that contains info about founded hotels
*/
public function getAvailableHotel($param)
{
$room = array();
for($i = 0; $i< $param['adult_paxes']; $i++){
$room[] = array('paxType' => 'Adult');
}
if(isset($param['is_child'])){
foreach($param['child_age'] as $key=>$age){
$room[] = array('paxType' => 'Child', 'age' => $age );
}
}
$hotelRoom[] = $room;
/**
* @todo Продумать вопрос с размещением клиентов по комнатам .
*/
try{
$response = $this->client->getAvailableHotel(
Yii::app()->params['HP_API_KEY'],
$param['city_id'],
$this->convertDate($param['coming_date']),
$this->convertDate($param['leaving_date']),
"USD",
"GB",
"false",
$hotelRoom,
null
);
return $response;
}
catch(SoapFault $exception){
throw new CHttpException($exception->getCode(), $exception->getMessage());
}
}
public function allocateHotelCode($hotelCode, $searchId)
{
try{
$response = $this->client->allocateHotelCode(Yii::app()->params['HP_API_KEY'],
$searchId,
$hotelCode);
return $response;
}
catch(SoapFault $fault){
throw new CHttpException($fault->getCode(), $fault->getMessage());
}
}
private function convertDate($date)
{
$result = date("Y-m-d", strtotime($date));
return $result;
}
private static function responseToArray($response)
{
if(is_object($response->availableHotels)){
$hotels[] = $response->availableHotels;
}
else{
$hotels = $response->availableHotels;
}
return $hotels;
}
public function removeDuplicateHotels($response)
{
$hotels = $this->responseToArray($response);
$hotelsCode = array();
foreach((array)$hotels as $hotel){
$hotelsCode[] = $hotel->hotelCode;
}
$availableRooms =array_count_values($hotelsCode);
$hotelsCode = array_unique($hotelsCode);
return array(
'responseId' => $response->responseId,
'searchId' => $response->searchId,
'totalFound' =>count($hotelsCode),
'hotelsCode' => $hotelsCode,
'availableRooms' => $availableRooms
);
}
public static function sortByPrice($priceRange, $response)
{
$price = explode('-', $priceRange);
$price['from'] = intval(str_replace('$', '', $price[0]));
$price['to'] = intval(str_replace('$', '', $price[1]));
$hotels = HotelsProAPI::responseToArray($response);
$hotelsCode = array();
$priceRange = array();
foreach((array)$hotels as $hotel){
if($hotel->totalPrice >= $price['from'] && $hotel->totalPrice <= $price['to']){
$hotelsCode[] = $hotel->hotelCode;
$priceRange[$hotel->hotelCode] = $hotel->totalPrice;
}
}
$availableRooms =array_count_values($hotelsCode);
$hc = array_unique($hotelsCode);
return array(
'responseId' => $response->responseId,
'searchId' => $response->searchId,
'totalFound' =>count($hotelsCode),
'hotelsCode' => $hc,
'availableRooms' => $availableRooms,
'priceRange' => $priceRange
);
}
public function makeHotelBooking($lead, $other, $processId, $preferences, $notes)
{
try{
$response = $this->client->makeHotelBooking(
Yii::app()->params['HP_API_KEY'],
$processId,
"",
$lead,
$other,
$preferences,
$notes
);
return $response;
}
catch(SoapFault $exception){
throw new CHttpException($exception->getCode(), $exception->getMessage());
}
}
public function getHotelBookingStatus($trackingId)
{
try {
$getHotelBookingStatus = $this->client->getHotelBookingStatus(Yii::app()->params['HP_API_KEY'], $trackingId);
return $getHotelBookingStatus;
}
catch (SoapFault $exception) {
throw new CHttpException($exception->getCode(), $exception->getMessage());
}
}
public function cancelHotelBooking($trackingId)
{
try{
$response = $this->client->cancelHotelBooking(Yii::app()->params['HP_API_KEY'], $trackingId);
return $response;
}
catch(SoapFault $exception){
throw new CHttpException($exception->getCode(), $exception->getMessage());
}
}
public function getHotelCancellationPolicy($processId){
try{
$response = $this->client->getHotelCancellationPolicy(Yii::app()->params['HP_API_KEY'], $processId);
return $response;
}
catch(SoapFault $exception){
throw new CHttpException($exception->getCode(), $exception->getMessage());
}
}
}<file_sep><?$parameters = unserialize(Yii::app()->cache->get('parameters'));?>
<?php
$this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=> 'views/'.$viewType,
'sortableAttributes'=>array('starRating', 'hotelName'),
'sorterHeader'=>'Сортировать по:',
'viewData' => array('hotels' => $hotels, 'availableRooms' => $availableRooms, 'priceRange' => $priceRange ),
'template'=> $template,
'pager' => array(
'header' => '',
),
'itemsCssClass' => 'item-list',
'itemsTagName' => 'ul',
'id' => 'ajaxListView',
'ajaxUpdate' => true,
'ajaxUrl' => 'search/update',
'summaryText' =>
"<span id='title'>{start}-{end} отелей из {count}, найденных в <b>".
$parameters['search_city']."</b> для проживания с <b>".
$parameters['coming_date']."</b> по <b>".
$parameters['leaving_date']."</b>
</span>"
));
?><file_sep><?php
Yii::app()->getClientScript()->registerCoreScript( 'jquery.ui' );
registerCss('/public/css/jquery.qtip.min.css');
registerCss('/public/css/jquery.ui.min.css');
registerScript('/public/js/chosen.jquery.js');
registerScript("/public/js/search_form.js");
registerScript('/public/js/jquery.qtip.min.js');
registerScript('/public/js/jquery.validate.min.js');
registerScript('/public/js/messages_ru.js');
registerCss('/public/css/chosen.css');
unset(Yii::app()->session['adv_param']);
unset(Yii::app()->session['responseData']);
?>
<script type="text/javascript">
$(function(){
$('#param_city').chosen().change(function(){
var selected = $(this).find('option').eq(this.selectedIndex);
$('#city_id').attr('value', selected.attr('value'));
$('#search_city').attr('value', selected.text());
});
$("#param_country").chosen().change(function(){
$("#param_city option").remove();
$("#param_city").append("<option>Выберите город...</option>");
$.ajax({
url: '<?=Yii::app()->createUrl('search/autocomplete')?>',
type: 'post',
dataType: 'json',
data: 'key='+$(this).val(),
success: function(cities){
$.each(cities, function(){
$("#param_city").append($('<option value="'+ this.id +'">' + this.city +'</option>'));
});
$('#param_city').trigger("liszt:updated");
}
});
});
$('#preloader').ajaxStart(function(){
$(this).show();
}).ajaxStop(function(){
$(this).hide();
});
$(function() {
$( "#coming_date" ).datepicker({
dateFormat: "yy-mm-dd",
changeMonth: true,
numberOfMonths: 1,
minDate: 1,
onSelect: function( selectedDate ) {
$( "#leaving_date" ).datepicker( "option", "minDate", selectedDate );
}
});
$( "#leaving_date" ).datepicker({
dateFormat: "yy-mm-dd",
changeMonth: true,
numberOfMonths: 1,
onClose: function( selectedDate ) {
$( "#coming_date" ).datepicker( "option", "maxDate", selectedDate );
}
});
});
})
</script>
<div id="info">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus adipisci aspernatur autem eum facere illum in, iure mollitia nobis obcaecati, officiis pariatur perferendis placeat quis recusandae repellendus, reprehenderit sapiente sit ut voluptatum? Aspernatur, blanditiis culpa ea eos explicabo mollitia natus omnis quibusdam suscipit temporibus! Alias at autem beatae consequatur delectus distinctio illo labore libero, nemo non sint tempore vel, vero? Deleniti enim laboriosam perferendis quibusdam vero. Accusantium at dolorum laboriosam? Alias aspernatur aut beatae culpa cum cupiditate eligendi excepturi illum impedit ipsa ipsam itaque labore laborum, minus nam natus, quia quis, quod rerum sed sequi similique suscipit velit vero voluptate.
</div>
<form name=search_form class="search_form" id=search_form action='<?php echo baseUrl() ?>/search' method='get'>
<table>
<tr>
<td>
<input type="hidden" name="param[city_id]" id="city_id"/>
<input type="hidden" name="param[search_city]" id="search_city"/>
<?
$destinations = Hoteldestinations::model()->findAll(array(
'select' => 'Country',
'distinct' => true,
'order' => 'Country'));
$result = array();
foreach($destinations as $destination){
$result[$destination->Country] = $destination->Country;
}
echo CHtml::dropDownList('param[country]', '', $result, array('empty'=> 'Выберите страну...','style' =>'width:255px'));
?>
</td>
</tr>
<tr>
<td>
<?=CHtml::dropDownList('param[city]', '', array(), array('empty'=> 'Выберите город...', 'style' =>'width:255px'));?>
<div id="preloader"></div>
</td>
</tr>
<tr>
<td>
<input type="text" class="date_picker" style="width: 114px" name="param[coming_date]" id="coming_date" autocomplete="off"
value placeholder="прибытие"/> -
<input type="text" class="date_picker" style="width: 114px" name="param[leaving_date]" id="leaving_date" autocomplete="off"
value placeholder="отъезд"/>
</td>
</tr>
<tr>
<td>
<input type="text" name="param[adult_paxes]" id="adult" autocomplete="off" value placeholder="взрослых" style="width: 85px"/>
<input type="checkbox" name="param[is_child]" id="is_child" onchange="hide_block()"/><label>  c детьми</label><br/>
</td>
</tr>
<tr id="add_child">
<td>
<input type="text" name="param[children_paxes]" id="children_paxes" autocomplete="off" style="width: 85px" value
placeholder="детей"/><br/>
</td>
</tr>
<tr id="children_age">
<td id="container">
</td>
</tr>
<tr>
<td>
<div id="button_wrap">
<input type=submit name=search value="Поехали!"/>
</div>
</td>
</tr>
</table>
</form><file_sep><?
Yii::app()->getClientScript()->registerCoreScript('jquery');
registerCss('/public/css/style.css');
registerCss('/public/css/table.css');
registerScript('/public/js/arcticmodal.js');
registerCss('/public/css/arcticmodal.css');
?>
<div class="g-hidden">
<div class="box-modal" id='modal'>
<table class="info_table">
<tr>
<td style="width:100px">
Количество дней до заселения, когда возможно отменить бронирование:
</td>
<td>
<?if(isset($policy->cancellationDay)) echo $policy->cancellationDay ?>
</td>
</tr>
<tr>
<td>
Тип комиссии:
</td>
<td>
<?
if(isset($policy->feeType)){
switch($policy->feeType){
case 'Percent': echo 'процент';break;
case 'Night': echo 'За ночь';break;
case 'Amount': echo 'Общая стоимость';break;
}
}
?>
</td>
</tr>
<tr>
<td>
Размер комиссии:
</td>
<td><?if(isset($policy->feeAmount)) echo $policy->feeAmount ?></td>
</tr>
<tr>
<td>
Валюта:
</td>
<td><?if(isset($policy->currency)) echo $policy->currency ?></td>
</tr>
<tr>
<td>
Замечания:
</td>
<td><?if(isset($policy->remarks)) echo $policy->remarks ?></td>
</tr>
</table>
</div>
</div>
<form method="post" action="" style="margin: auto">
<table style="margin: auto">
<tr>
<td colspan="3">
<input type="hidden" name="processId" value="<?=Yii::app()->request->getParam('id')?>" >
<label style="font-size: 15px; font-style: italic; font-weight: bold">Ответственное лицо:</label><br>
</td>
</tr>
<tr>
<td>
<label for="lead_title">Привествие:</label><br>
</td>
<td>
<label for="lead_1st_name">Имя:</label><br>
</td>
<td>
<label for="lead_2nd_name">Фамилия:</label><br>
</td>
</tr>
<tr>
<td>
<select class="booking" style="width: 80px;" name="booking[lead][title]" id="lead_title">
<option>Mr</option>
<option>Ms</option>
</select>
</td>
<td>
<input class="booking" type="text" name="booking[lead][1st_name]" id="lead_1st_name"/>
</td>
<td>
<input class="booking" type="text" name="booking[lead][2nd_name]" id="lead_2nd_name"/>
</td>
</tr>
<tr>
<td colspan="2">
<?
if(isset($data['children_paxes'])){
$paxCount = $data['children_paxes'] + $data['adult_paxes'];
}else{
$paxCount = $data['adult_paxes'];
}
if($paxCount > 1):
?>
<label style="font-size: 15px; font-style: italic; font-weight: bold">Другие посетители:</label>
</td>
</tr>
<?php for($i = 0; $i < $paxCount - 1; $i++):?>
<tr>
<td>
<label>Привествие:</label>
</td>
<td>
<label>Имя:</label>
</td>
<td>
<label>Фамилия:</label>
</td>
</tr>
<tr>
<td>
<select class="booking" style="width: 80px;" name="booking[other][title][]">
<option>Mr</option>
<option>Ms</option>
</select>
</td>
<td>
<input class="booking" type="text" name="booking[other][1st_name][]"/>
</td>
<td>
<input class="booking" type="text" name="booking[other][2nd_name][]"/>
</td>
</tr>
<?endfor?>
<?endif?>
<tr>
<td colspan="3">
<label>Примечания:</label>
<textarea class="booking" name="booking[note]" style="width: 300px"></textarea>
</td>
</tr>
<tr>
<td colspan="3">
<div id="button_wrap">
<input type="submit" name="get_booking" value="Забронировать"/>
</div>
</td>
</tr>
</table>
</form>
<p style="text-align: center; font-weight: bold; font-style: italic">
<a id="get_policy" href="#" onclick="$('#modal').arcticmodal()">
Внимание!!! Перед бронирование настоятельно рекомендуем ознакомится с политикой отмены брони!
</a>
</p><file_sep>
function hide_block(){
if($("#is_child").is(":checked")){
$("#add_child").show(200);
}
else{
$("#add_child").hide(200);
$("#children_age").hide(200);
}
}
$(function(){
$("#add_child").hide();
$("#children_age").hide();
$("#load").hide();
$("#children_paxes").keyup(function(){
$("input.child_age").remove();
$(".age_label").remove()
$('<label>возраст детей</label><br/>').remove();
$("#children_age").show(200);
var children = $("#children_paxes").val();
if(children > 0 && children <=5){
$('<label class="age_label">возраст детей<br/></label>').fadeIn('slow').appendTo('#container');
for(var i = 0; i < children; i++ ){
$('<input type="text" class="child_age" autocomplete="off" name="param[child_age][]" style="width:35px; margin-right:3px" />').fadeIn('slow').appendTo('#container');
}
}
});
$("#search_form").validate({
rules: {
select:{
required: true
},
'param[coming_date]':{
required:true
},
'param[leaving_date]':{
required:true
},
'param[adult_paxes]':{
required: true,
max: 6
},
'param[children_paxes]':{
required: true,
max: 5
},
'param[child_age][]':{
required: true,
max:17
}
},
errorPlacement: function(error, element)
{
var elem = $(element);
var corners = ['right center', 'left center'];
if(!error.is(':empty')) {
elem.filter(':not(.valid)').qtip({
overwrite: true,
content: error,
position: {
my: corners[0],
at: corners[1]
},
show: {
event: false,
ready: true
},
hide: 'click',
style: {
classes: 'qtip-red'
}
})
.qtip('option', 'content.text', error);
}
else { elem.qtip('destroy'); }
},
success: $.noop,
onSelect: true
});
});
$(function(){
$("#radio").buttonset();
});
<file_sep><?
$images = explode(';',$data->HotelImages);
$price = 0;
?>
<tr style="height: 100px">
<td style="padding: 1px; width: 150px; overflow: visible">
<div style="height: 100px; overflow-y: hidden">
<a href="<?=getUrlDetails($data->HotelCode,json_decode(Yii::app()->session['responseData'])->searchID)?>">
<? if(($images[0]) == false): ?>
<img class="thumb" style="width: 150px;" src="<? echo baseUrl().'/public/images/no_photo.png'?>"/>
<? else: ?>
<img class="thumb" style="width: 150px;" src="<? echo $images[0]?>" alt="logo"/>
<? endif; ?>
</a>
</div>
</td>
<td style="vertical-align: top;width: 500px">
<a style="font-size: 22px; font-weight: 440" href="<?=getUrlDetails($data->HotelCode,json_decode(Yii::app()->session['responseData'])->searchID)?>"><?=$data->HotelName?></a><br/>
<label>Адрес: <?=$data->HotelAddress?></label><br/>
<?
foreach((array)$hotels as $key=>$hotel ){
if($hotel->hotelCode == $data->HotelCode){
if(isset($priceRange)){
$price = $priceRange[$hotel->hotelCode];
}
echo '<label>Тип номера: '.$hotel->boardType.'</label><br/>';
break;
}
}
?>
<?for($i=0;$i<$data->StarRating;$i++):?>
<img src="<? echo baseUrl().'/public/images/star_icon.png'?>" alt="star"/>
<?endfor?>
<br/>
</td>
<td>
<label>Полная стоимость: <b>$<? echo $price;?></b></label><br/>
<label>Доступных номеров:
<?
foreach($availableRooms as $key=>$value){
if($key == $data->HotelCode){
echo '<b>'.$value.'</b>';break;
}
}
?>
</label><br/>
<a class="button" href="<?=getUrlDetails($data->HotelCode,json_decode(Yii::app()->session['responseData'])->searchID)?>">подробнее</a>
</td>
</tr>
<file_sep><?
registerCss('/public/css/places.css');
Yii::app()->getClientScript()->registerCoreScript('jquery.ui');
registerCss('/public/css/jquery.ui.min.css')
?>
<script>
$(function () {
$("#tabs").tabs();
});
</script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=<?php echo Yii::app()->params['GOOGLE_MAPS_API_KEY']; ?>&sensor=true&language=ru&libraries=places">
</script>
<?php
$key = array_search($hotel->HotelCode,$hotelsCode);
registerScript("/public/js/slides.min.jquery.js");
registerScript("/public/js/maps.js");
registerScript("/public/js/details.js");
registerCss("/public/css/global.css");
registerCss("/public/css/table.css");
$images = explode(';',$hotel->HotelImages);
if(!isset($hotelsCode[$key-1])){
$hotelsCode[$key-1] = $hotelsCode[$key];
}elseif(!isset($hotelsCode[$key+1])){
$hotelsCode[$key+1] = $hotelsCode[$key];
}
?>
<a href="<?=getUrlDetails($hotelsCode[$key-1],json_decode(Yii::app()->session['responseData'])->searchID)?>">
<img src="<?echo baseUrl().'/public/images/back.png'?>" style="padding-right: 4px">
Предыдуший отель
</a>
<a href="<?=getUrlDetails($hotelsCode[$key+1],json_decode(Yii::app()->session['responseData'])->searchID)?>" style="float: right">
Следующий отель
<img src="<?echo baseUrl().'/public/images/forward.png'?>"style="padding-left: 4px">
</a>
<div id="tabs" style="min-height: 400px">
<ul>
<li><a href="#tabs-1">Общая нформация</a></li>
<li><a href="#tabs-2">Подробная информация</a></li>
<li><a href="#tabs-4">Забронировать</a></li>
<a href="<? echo baseUrl().Yii::app()->session['url'];?>" style="float: right;padding-top: 7px;padding-right: 5px">Возврат к списку отелей</a>
</ul>
<div id="tabs-1">
<? if(isset($images[1])): ?>
<div id="container">
<div id="example">
<div id="slides">
<div class="slides_container">
<?php
for ($i = 0; $i < count($images) - 1; $i++) {
echo '<div>
<img src=' . $images[$i] . ' width="370" height="260" alt="Logo">
</div>';
}
?>
</div>
<a href="#" class="prev"><img src=<?php echo baseUrl() . "/public/img/arrow-prev.png" ?> width="24"
height="43" alt="Arrow Prev"></a>
<a href="#" class="next"><img src=<?php echo baseUrl() . "/public/img/arrow-next.png" ?> width="24"
height="43" alt="Arrow Next"></a>
</div>
<img src=<?php echo baseUrl() . "/public/img/example-frame.png" ?> width="739" height="341" alt="Frame" id="frame">
</div>
</div>
<? endif; ?>
<p align="justify"><br>
<table class="specialty">
<tr>
<td>
<i>Страна: </i>
</td>
<td>
<b><?php echo $hotel->Country ?></b>
</td>
</tr>
<tr>
<td>
<i>Город: </i>
</td>
<td>
<b><?php echo $hotel->Destination ?></b>
</td>
</tr>
<tr>
<td>
<i>Название отеля: </i>
</td>
<td>
<b><?php echo $hotel->HotelName ?></b>
</td>
</tr>
<tr>
<td>
<i>Количество звезд: </i>
</td>
<td>
<b><?php for ($i = 0; $i < $hotel->StarRating; $i++) {
echo '<img src="' . baseUrl() . '/public/images/star_icon.png" alt="star"/>';
} ?></b>
</td>
</tr>
<tr>
<td>
<i>Адрес: </i>
</td>
<td>
<b><?php echo $hotel->HotelAddress ?></b>
</td>
</tr>
<tr>
<td>
<i>Местонахождение: </i>
</td>
<td>
<b><?php echo $hotel->description[0]->HotelLocation ?></b>
</td>
</tr>
<tr>
<td>
<i>Почтовый код: </i>
</td>
<td>
<b><?php echo $hotel->HotelPostalCode ?></b>
</td>
</tr>
<tr>
<td>
<i>Номер телефона: </i>
</td>
<td>
<b><?php echo $hotel->HotelPhoneNumber ?></b>
</td>
</tr>
</table>
</p>
<br>
<body onload="initialize(
<? echo "'".$hotel->HotelAddress."'";?>,
<? echo "'".$hotel->Latitude."'";?>,
<? echo "'".$hotel->Longitude."'";?>,
<? echo "'".$hotel->Country."'";?>,
<? echo "'".$hotel->Destination."'";?>)">
<div id="map_canvas" style="width:100%; height:500px">
</div>
</body>
<div class="actions">
<!-- <input hidden="" id="gmap_keyword" type="text" name="gmap_keyword" />-->
<div class="buttons">
<label for="gmap_type">Тип места:</label>
<select id="gmap_type">
<option value="airport">Аэропорт</option>
<option value="book_store">Книжные магазины</option>
<option value="church">Церкви,храмы</option>
<option value="liquor_store">Винные магазины</option>
<option value="clothing_store">Магазины одежды</option>
<option value="convenience_store">Продуктовые магазины</option>
<option value="hardware_store">Хозяйственные магазины</option>
<option value="doctor">Частные клиники</option>
<option value="library">Библиотеки</option>
<option value="movie_theater">Кинотеатры</option>
<option value="museum">Музеи</option>
<option value="night_club">Ночные клубы</option>
<option value="pharmacy">Аптеки</option>
<option value="post_office">Почтовое отделение</option>
<option value="shopping_mall">Торговый центр</option>
<option value="art_gallery">Галереи</option>
<option value="zoo">Зоопарки</option>
<option value="atm">Банкоматы</option>
<option value="bank">Банк</option>
<option value="park">Парки/места отдыха</option>
<option value="bar">Бар</option>
<option value="restaurant">Ресторан</option>
<option value="cafe">Кафе</option>
<option value="food">Закусочные</option>
<option value="hospital">Больница</option>
<option value="police">Полиция</option>
<option value="train_station">Вокзал ж/д</option>
<option value="bus_station">Автобусная остановка</option>
<option value="local_government_office">Правительственные учреждения</option>
<option value="establishment">Государственные заведения</option>
</select>
</div>
<div class="buttons">
<label for="gmap_radius">Радиус (м):</label>
<select id="gmap_radius">
<option value="500">500</option>
<option value="1000">1000</option>
<option value="1500">1500</option>
<option value="3000">3000</option>
<option value="5000">5000</option>
</select>
</div>
<input type="hidden" id="lat" name="lat" value="55.755786" />
<input type="hidden" id="lng" name="lng" value="37.617633" />
<div class="buttons" onclick="findPlaces(); return false;">Найти организации</div>
<div class="buttons" onclick="clearOverlays(); return false;">Очистить</div>
</div>
</div>
<div id="tabs-2">
<div class="info_table">
<?if (isset($hotel->rusAmenities[0])): ?>
<ul>
<li>
<table>
<?
$desc = preg_split("/(?<=[.])\s+(?=[А-Я])/", $hotel->rusAmenities[0]->HotelDescription);
foreach ($desc as $key => $value) :
$split = explode(':', $value);
?>
<tr>
<td>
<?php echo isset($split[0]) ? $split[0] : '' ?>:
</td>
<td>
<?php echo isset($split[1]) ? $split[1] : '' ?>
</td>
</tr>
<?endforeach?>
</table>
</li>
<li><hr/></li>
<li>
<table>
<tr>
<td><b>Особенности отеля</b></td>
<td><b>Особенности номеров</b></td>
</tr>
<tr>
<td>
<ul>
<?
$hamen = explode(',', $hotel->rusAmenities[0]->HotelAmenities);
if(count($hamen)== 0){
echo "<li>Нет данных</li>";
}
else{
foreach ($hamen as $amenities) {
echo "<li>$amenities</li>";
}
}
?>
</ul>
</td>
<td>
<ul>
<?
$ramen = explode(',', $hotel->rusAmenities[0]->RoomAmenities);
if(count($ramen)== 0){
echo "<li>Нет данных</li>";
}
else{
foreach ($ramen as $amenities) {
echo "<li>$amenities</li>";
}
}
?>
</ul>
</td>
</tr>
</table>
</li>
</ul>
<?else:?>
<ul>
<li>
<table>
<tr><td colspan="2"><b>Информация о данном отеле присутствует только на английском языке. Приносим свои извинения за предоставленные неудобства!</b></b></td> </tr>
<tr>
<td>Полное описание отеля</td>
<td><?=$hotel->description[0]->HotelInfo?></td>
</tr>
</table>
</li>
<li><hr/></li>
<li>
<table>
<tr>
<td><b>Особенности отеля</b></td>
<td><b>Особенности номеров</b></td>
</tr>
<tr>
<td>
<ul>
<?
$hamen = explode(';', $hotel->amenities[0]->PAmenities);
if(count($hamen)== 0){
echo "<li>Нет данных</li>";
}
else{
foreach ($hamen as $amenities) {
echo "<li>$amenities</li>";
}
}
?>
</ul>
</td>
<td>
<ul>
<?
$ramen = explode(';', $hotel->amenities[0]->RAmenities);
if(count($ramen)== 0){
echo "<li>Нет данных</li>";
}
else{
foreach ($ramen as $amenities) {
echo "<li>$amenities</li>";
}
}
?>
</ul>
</td>
</tr>
</table>
</li>
</ul>
<?endif?>
</div>
</div>
<div id="tabs-4">
<?
if (is_object($allocateResponse->availableHotels)) {
$hotels[] = $allocateResponse->availableHotels;
} else {
$hotels = $allocateResponse->availableHotels;
}
foreach ((array)$hotels as $num => $hotel):
if (is_object($hotel->rooms)) {
$rooms[] = $hotel->rooms;
} else {
$rooms = $hotel->rooms;
}
foreach ((array)$rooms as $rnum => $room) :
?>
<div class="info_table" style="border: #8d889e 1px solid; border-radius: 2px;padding: 10px;">
<a href="<?=Yii::app()->createUrl('booking',array('id' => strtolower($hotel->processId))) ?>" style="float: right">Забронировать</a><br/>
<table class="specialty">
<tr>
<td style="width: 300px">
<b>Комната <?php echo($rnum + 1);?> Категории: </b>
</td>
<td>
<?
echo $room->roomCategory;
?>
</td>
</tr>
<tr>
<td>
<b>Обшая стоимость за проживание: </b>
</td>
<td>
$<?php echo $room->totalRoomRate;?>
</td>
</tr>
<tr>
<td>
<b>Размещение + возраст:</b>
</td>
<td>
<?php
if (is_object($room->paxes)) {
$roomsInfo[] = $room->paxes;
} else {
$roomsInfo = $room->paxes;
}
if (is_object($room->ratesPerNight)) {
$ratesPerNight[] = $room->ratesPerNight;
} else {
$ratesPerNight = $room->ratesPerNight;
}
foreach ((array)$roomsInfo as $pnum => $pax) {
?>
<?php
$paxType = array('Adult'=>'Взрослый','Child'=>'Ребенок');
echo $paxType[$pax->paxType];
?> (<?php echo $pax->age; ?>) <br/>
<?php
}
?>
</td>
</tr>
<tr>
<td>
<b>Даты размешения + стоимость за ночь:</b>
</td>
<td>
<?php
foreach ((array)$ratesPerNight as $rpnum => $price) {
?>
<?php echo $price->date; ?> ($<?php echo $price->amount; ?>)<br/>
<?php
}
?>
</td>
</tr>
</table>
</div>
<br>
<? endforeach ?>
<? endforeach?>
</div>
</div><file_sep><?php
function baseUrl()
{
return Yii::app()->request->baseUrl;
}
function registerScript($dirName)
{
return Yii::app()->getClientScript()->registerScriptFile(Yii::app()->request->baseUrl.$dirName,CClientScript::POS_END);
}
function registerCss($dirName)
{
return Yii::app()->clientScript->registerCssFile(Yii::app()->request->baseUrl.$dirName,'screen');
}
function getUrlDetails($hotelCode,$searchId)
{
return Yii::app()->createUrl('details',array(
'hotel' => strtolower($hotelCode),
'id' => strtolower($searchId)));
}<file_sep><?php
Yii::app()->getClientScript()->registerCoreScript('jquery.ui');
registerCss('/public/css/jquery.ui.min.css');
registerScript('/public/js/chosen.jquery.js');
registerCss('/public/css/chosen.css');
registerScript('/public/js/filter_form.js');
registerCss('/public/css/table.css');
$parameters = unserialize(Yii::app()->cache->get('parameters'));
?>
<div id="advanced_search">
<?
Yii::app()->clientScript->registerScript('preload','
$(function (){
$("#search_result").css("background", "url(/public/images/301.gif) no-repeat center center");
var url = window.location.href;
var param = url.split("?");
var filter = $("#adv_search").serialize();
$("#adv_search :input").attr("disabled", true)
$("#price_range").slider({ disabled: true });
$("#star_range").slider({ disabled: true });
$( "#radio" ).buttonset({ disabled: true });
$.ajax({
type: "get",
url: "'.baseUrl().'/search/update",
data: filter+"&"+param[1],
success:function(response) {
$("#search_result").css("background","#fff").html(response);
$("#adv_search :input").attr("disabled", false);
$("#price_range").slider({ disabled: false });
$("#star_range").slider({ disabled: false });
$( "#radio" ).buttonset({ disabled: false });
},
error:function(){
$("#search_ewsult").html("<span>Что-то пошло не так! Попробуйте повторить поиск</span>").css("background","#fff");
}
})
});');
$this->renderPartial("columns/_filterform");
$this->renderPartial("columns/_searchform", array('parameters' => $parameters));
?>
</div>
<div id="search_result">
</div>
<script>
$(document).ready(function () {
filter = <?=json_encode($filter)?>;
var price, star;
if(filter){
price = filter.price.split("-");
price[0] = price[0].replace('$', '');price[1] = price[1].replace('$', '')
star = filter.StarRating.split('-');
for(var check in filter){
if(check != 'radio' && check!='price' && radio!='StarRating'){
$('#adv_search input:checkbox[name*='+check+']').attr('checked', 'checked');
}
}
$("[value='"+filter.radio+"']").attr('checked','checked');
}else{
price = new Array(2);price[0]=5;price[1]=2000;
star = new Array(2);star[0]=0;star[1]=5;
}
setRanges(price,star);
});
</script><file_sep><?
$images = explode(';',$data->HotelImages);
?>
<li>
<table style="width: 100%">
<tr>
<td>
<div style="overflow: hidden; height: 150px; text-align: center">
<a href="<?=getUrlDetails($data->HotelCode,json_decode(Yii::app()->session['responseData'])->searchID)?>">
<? if(($images[0]) == false): ?>
<img class="thumb" style="width: 200px;" src="<? echo baseUrl().'/public/images/no_photo.png'?>"/>
<? else: ?>
<img src="<? echo $images[0]?>" alt="logo" width="230"/>
<? endif; ?>
</a>
</div>
</td>
</tr>
<tr>
<td>
<a href="<?=getUrlDetails($data->HotelCode,json_decode(Yii::app()->session['responseData'])->searchID)?>"><? echo $data->HotelName?></a>
</td>
</tr>
<tr>
<td>
<?
foreach((array)$hotels as $key=>$hotel ){
if($hotel->hotelCode == $data->HotelCode){
echo '<label>Тип номера: '.$hotel->boardType.'</label><br/>';
echo '<label>Полная стоимость: <b>$'.$hotel->totalPrice.'</b></label><br/>';
break;
}
}
foreach($availableRooms as $key=>$value){
if($key == $data->HotelCode){
echo '<label>Доступных номеров:<b>'.$value.'</b></label><br/>';break;
}
}
?>
</td>
</tr>
<tr>
<td>
<?for($i=0;$i<$data->StarRating;$i++):?>
<img src="<? echo baseUrl().'/public/images/star_icon.png'?>" alt="star"/>
<?endfor?>
<a class="button" style="margin: 0;float: right" href="<?=getUrlDetails($data->HotelCode,json_decode(Yii::app()->session['responseData'])->searchID)?>">подробнее</a>
</td>
</tr>
</table>
</li>
|
42554f923ed03828ccddb79f5ae401b3a0ab8901
|
[
"JavaScript",
"PHP"
] | 29 |
PHP
|
shimovolos/Hotels
|
8622c2534f20dbc477ae545b1158f0b45d740ead
|
bb6c5e1e8044b3d091810fa7c452a63b4100bdd6
|
refs/heads/main
|
<file_sep>function menuClick() {
let items = document.querySelectorAll(".item")
items.forEach(item => {
item.classList.toggle("active");
});
}
|
2bd8d3b7953ccc598c5952b6cc1fb3fa31416df6
|
[
"JavaScript"
] | 1 |
JavaScript
|
AlejandroHM2/ARLO
|
6f3769ae15c13d0dc966cb2e3db039ff8cc55b45
|
cdce69c656276b176c0ad28e0bb90e4b36a46063
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 选课系统
{
class StuData
{
public static string StuID = "", StuName = "";//学生ID和姓名
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 选课系统
{
public partial class MyClass : Form
{
public MyClass()
{
InitializeComponent();
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void MyClass_Load(object sender, EventArgs e)
{
MyClassTable();
}
public void MyClassTable()
{
dataGridView1.Rows.Clear();//清空旧数据
pipe pip = new pipe();
string sql = $"select * from SelectClassTB WHERE StuID = '{StuData.StuID}'";
IDataReader dc = pip.read(sql);
string a0, a1;
while (dc.Read())
{
a0 = dc[1].ToString();//便于对数据进行处理
a1 = dc[2].ToString();
string[] table = { a0, a1};
dataGridView1.Rows.Add(table);
}
dc.Close();
pip.PipClose();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 选课系统
{
public partial class selectClass : Form
{
public selectClass()
{
InitializeComponent();
}
private void selectCalss_Load(object sender, EventArgs e)
{
ClassInfoTB();
SelectClassTB();
label9.Text = StuData.StuID;
label7.Text = StuData.StuName;
LeadinStuInfo();
}
private void label5_Click(object sender, EventArgs e)
{
}
private void label10_Click(object sender, EventArgs e)
{
}
public void ClassInfoTB()//从数据库读取数据显示在可选表格中
{
dataGridView2.Rows.Clear();//清空就数据
pipe pip = new pipe();
string sql = "select * from ClassInfoTB";
IDataReader dc = pip.read(sql);
string a0, a1, a2, a3;
while (dc.Read())
{
a0 = dc[0].ToString();//便于对数据进行处理
a1 = dc[2].ToString();
a2 = dc[1].ToString();
a3 = dc[3].ToString();
string[] table = { a0, a1, a2, a3 };
dataGridView2.Rows.Add(table);
}
dc.Close();
pip.PipClose();
}
public void SelectClassTB()
{
dataGridView1.Rows.Clear();//清空就数据
pipe pip = new pipe();
string sql = $"select * from TempSelectClassTB where StuID = '{StuData.StuID}'";
IDataReader dc = pip.read(sql);
string a0, a1;
int classnum = 0;
int credit = 0;
while (dc.Read())
{
a0 = dc[1].ToString();//便于对数据进行处理
a1 = dc[2].ToString();
string[] table = { a0, a1};
dataGridView1.Rows.Add(table);
classnum++;
credit += int.Parse(a1);
}
dc.Close();
pip.PipClose();
}
private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
label13.Text = dataGridView2.SelectedRows[0].Cells[0].Value.ToString();
label14.Text = dataGridView2.SelectedRows[0].Cells[1].Value.ToString();
}
private void AddClass_Click(object sender, EventArgs e)
{
try
{
string classname = dataGridView2.SelectedRows[0].Cells[0].Value.ToString();
string teacher = dataGridView2.SelectedRows[0].Cells[1].Value.ToString();
string credit = dataGridView2.SelectedRows[0].Cells[2].Value.ToString();
label13.Text = classname;
label14.Text = teacher;
DialogResult dr = MessageBox.Show("确认选这门课吗?","信息提示",MessageBoxButtons.OKCancel,MessageBoxIcon.Question);
if (dr == DialogResult.OK)
{
string sql = $"insert into TempSelectClassTB values ('{StuData.StuID}','{classname}',{credit})";
pipe pip = new pipe();
if (pip.Execute(sql) > 0)
{
MessageBox.Show("添加成功");
SelectClassTB();
}
else
{
MessageBox.Show("添加失败" + sql);
}
pip.PipClose();
}
}
catch
{
MessageBox.Show("请选择课程!","信息提示",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
public void LeadinStuInfo()
{
pipe pip = new pipe();
string sql = $"select * from StuInfoTB where StuID='{StuData.StuID}'";
IDataReader dc = pip.read(sql);
if (dc.Read())
{
string name = dc[1].ToString();
string classnum = dc[3].ToString();
string credit = dc[2].ToString();
label6.Text = classnum;
label5.Text = credit;
}
else
{
MessageBox.Show("读取学生信息失败");
}
}
private void flash_Click(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)//提交选课按钮
{
try
{
string classname = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
string credit = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
DialogResult dr = MessageBox.Show("确认提交这门课吗?", "信息提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (dr == DialogResult.OK)
{
if(JudgeClass(credit)==0)//符合规则
{
string sql1 = $"insert into SelectClassTB values ('{StuData.StuID}','{classname}',{credit})";
pipe pip = new pipe();
if (pip.Execute(sql1) > 0)
{
MessageBox.Show("添加成功");
SelectClassTB();
}
else
{
MessageBox.Show("添加失败" + sql1);
}
//插入学分到学生信息表
ClassData.credit = int.Parse(label5.Text) + int.Parse(credit);//已选学分
ClassData.classnum = int.Parse(label6.Text) + 1;
string sql2 = $"UPDATE StuInfoTB SET StuCredit = {ClassData.credit},ClassNum = {ClassData.classnum} WHERE StuID = '{StuData.StuID}'";
if (pip.Execute(sql2) > 0)
{
label6.Text = ClassData.classnum.ToString();
label5.Text = ClassData.credit.ToString();
MessageBox.Show("更改成功!");
}
else
{
MessageBox.Show("更改失败" + sql2);
}
pip.PipClose();
}
else//不符合规则
{
MessageBox.Show("不符合选课规则");
}
}
}
catch
{
MessageBox.Show("请选择课程!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void MyClass_Click(object sender, EventArgs e)
{
MyClass myclass = new MyClass();
myclass.ShowDialog();
}
public int JudgeClass(string c)
{
int tempclassnum = ClassData.classnum+1;
int tempcredit = int.Parse(label5.Text) + int.Parse(c);
if (tempclassnum >= 5 || tempcredit > 12)
{
return -1;
}
else return 0;
}
private void DeleteClass_Click(object sender, EventArgs e)
{
string classname = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
string credit = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
DialogResult dr = MessageBox.Show("确认删除这门课吗?", "信息提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (dr == DialogResult.OK)
{
string sql = $"delete from TempSelectClassTB where ClassName = '{classname}'";
pipe pip = new pipe();
if (pip.Execute(sql) > 0)
{
MessageBox.Show("删除成功");
SelectClassTB();
}
else
{
MessageBox.Show("删除失败" + sql);
}
pip.PipClose();
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 选课系统
{
class ClassData
{
public static int credit = 0;
public static int classnum = 0;
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 选课系统
{
public partial class quit : Form
{
public quit()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void choseClass_Click(object sender, EventArgs e)
{
if(tbStuID.Text!="")
{
StuData.StuID = tbStuID.Text;
StuData.StuName = label4.Text;
selectClass selectclass = new selectClass();
selectclass.ShowDialog();
}
else
{
MessageBox.Show("请输入学号!");
}
}
private void logout_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void tbStuID_TextChanged(object sender, EventArgs e)
{
if(tbStuID.Text.Length == 10)
{
//查询学号
pipe pip = new pipe();
string sql = $"select * from StuInfoTB where StuID='{tbStuID.Text}'";
IDataReader dc = pip.read(sql);
if (dc.Read())
{
string name = dc[1].ToString();
label4.Text = name;
StuData.StuName = name;
}
else
{
MessageBox.Show("查询失败");
}
pip.PipClose();
}
}
private void quit_Load(object sender, EventArgs e)
{
}
}
}
|
727ff050634e0312ec6e3de4e45063d8c258705b
|
[
"C#"
] | 5 |
C#
|
TommyGong08/SQLServerLearning
|
6e1efd3914748423b9343bba61cbbc108c8ade3a
|
3ce7ded62570c05ca5369b27caa09aca1a0b7036
|
refs/heads/main
|
<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace fremvisning_codereview
{
class CommandHandler
{
public Location[] SelectLocations;
public progressBar hackProgressBar;
public CommandHandler(params Location[] locations)
{
SelectLocations = locations;
}
public string HandleCommand(string command)
{
if (command == "start")
{
return "H4CKbot.exe loaded. \nType: targets";
}
if (command == "targets")
{
return "\n" + SelectLocations[0].Name + "\n" + SelectLocations[1].Name + "\n" + SelectLocations[2].Name + "\nChoose your company:";
}
if (command.Contains("NASA"))
{
return Nasa(command);
}
if (command.Contains("GOOGLE"))
{
return Google(command);
}
if (command.Contains("TWITCH"))
{
return Twitch(command);
}
return null;
}
private string Nasa(string command)
{
if (command == "NASA")
{
return "Type in commands.NASA to see your options";
}
if (command == "commands.NASA")
{
return "Hack, Locate, Trace" + "\nType: Trace.NASA";
}
if (command == "Trace.NASA")
{
return SelectLocations[0].IpAdress + "\nType: Locate.NASA";
}
if (command == "Locate.NASA")
{
return SelectLocations[0].Adress + "\nType: Hack.NASA";
}
if (command == "Hack.NASA")
{
SelectLocations[0].Hack();
}
return "";
}
private string Google(string command)
{
if (command == "GOOGLE")
{
return "Type in commands.GOOGLE to see your options";
}
if (command == "commands.GOOGLE")
{
return "Hack, Locate, Trace" + "\nType: Trace.GOOGLE";
}
if (command == "Trace.GOOGLE")
{
return SelectLocations[1].IpAdress + "\nType: Locate.GOOGLE";
}
if (command == "Locate.GOOGLE")
{
return SelectLocations[1].Adress + "\nType: Hack.GOOGLE";
}
if (command == "Hack.GOOGLE")
{
SelectLocations[1].Hack();
}
return "";
}
private string Twitch(string command)
{
if (command == "TWITCH")
{
return "Type in commands.TWITCH to see your options";
}
if (command == "commands.TWITCH")
{
return "Hack, Locate, Trace" + "\nType: Trace.TWITCH";
}
if (command == "Trace.TWITCH")
{
return SelectLocations[2].IpAdress + "\nType: Locate.TWITCH";
}
if (command == "Locate.TWITCH")
{
return SelectLocations[2].Adress + "\nType: Hack.TWITCH";
}
if (command == "Hack.TWITCH")
{
SelectLocations[2].Hack();
}
return "";
}
}
}
<file_sep>namespace fremvisning_codereview
{
public class Location
{
public string Name;
public string Adress;
public string IpAdress;
public progressBar HackProgress = new progressBar();
public Location(string name, string adress, string ipAdress)
{
Name = name;
Adress = adress;
IpAdress = ipAdress;
}
public void Hack()
{
HackProgress.ProgressBar();
}
}
}<file_sep>using System;
namespace fremvisning_codereview
{
class Program
{
static void Main(string[] args)
{
var hack = new progressBar();
var location1 = new Location("NASA", "NASA Headquarters\r\n300 E. Street SW, Suite 5R30\r\nWashington, DC 20546", "NASA: IPv4 Default Gateway 192.168.1.1");
var location2 = new Location("GOOGLE", "Mountain View, California, United States, 1600 Amphitheatre Parkway Mountain View, CA 94043", "192.168.0.1");
var location3 = new Location("TWITCH", "350 Bush St FL 2,, San Francisco, United States, CA, 94104 - 2879", "192.168.0.1");
var ch = new CommandHandler(location1, location2, location3);
while (true)
{
var myCommand = Console.ReadLine();
var text = ch.HandleCommand(myCommand);
Console.WriteLine(text);
}
}
}
}
|
485705b1ca73646648a0619e86099f0034a27d1b
|
[
"C#"
] | 3 |
C#
|
thuve92/fremvisning-codereview
|
1f0d5e608f3c6b24b7566b892d96e0e360586877
|
1df7518af54e373d43d9a4cd739d90e12a3c0df1
|
refs/heads/master
|
<repo_name>eonj/rim-rust<file_sep>/src/fs/blob.rs
use std::io::*;
use crypto::sha1::Sha1;
use crypto::digest::Digest;
use fs::tree::RimFile;
pub fn hash_file(filename: &String) -> Result<String> {
const BUFFER_SZ: usize = 0x10000usize;
let mut file = try!(RimFile::open(filename));
let mut buffer: [u8; BUFFER_SZ] = [0u8; BUFFER_SZ];
let mut sh = Sha1::new();
loop {
let count = try!(file.read(&mut buffer));
if count == 0 {
break;
}
sh.input(&buffer);
}
Ok(sh.result_str())
}<file_sep>/src/cl.rs
use std::env;
use fs::tree::*;
use fs::blob::*;
fn print_builtin_help() {
macro_rules! builtin_help_message {
() => ("Usage: rim <command>\n")
};
print!(builtin_help_message![]);
}
pub fn parse_args() -> Vec<String> {
let mut args = env::args();
args.next();
match args.next().as_ref().map(|s| &s[..]) {
None => {
print_builtin_help();
},
Some("status") => {
let wd_contents = scan_wd();
let wd_count = wd_contents.len();
for path in wd_contents {
println!("{}", path);
}
println!("{} files and folders found. done.", wd_count);
},
Some("hash") => {
for filename in args {
match hash_file(&filename) {
Ok(sha1_res) => println!("{} {}", sha1_res, filename),
Err(err) => println!("{}: {}", filename, err),
}
}
},
Some(s) => {
println!("{}: no such command, please check usage", s);
},
}
vec![]
}
<file_sep>/src/fs/tree.rs
use std::ffi::OsString;
use std::fs::*;
pub type RimFile = File;
pub fn scan_wd() -> Vec<String> {
let mut wd_all: Vec<String> = vec![".".to_owned()];
let ignore_starts: Vec<&'static str> = vec![".git", "target"];
let mut index = 0usize;
while index != wd_all.len() {
let meta = metadata(&wd_all[index]).unwrap();
if meta.is_dir() {
let subs = read_dir(&wd_all[index]).unwrap();
let mut append = 0usize;
for sub in subs {
let entry: OsString;
if index == 0usize {
entry = sub.unwrap().file_name();
} else {
entry = sub.unwrap().path().into_os_string();
}
let pathstr = entry.into_string().unwrap();
let mut ignore = false;
for i in 0..ignore_starts.len() {
if pathstr.starts_with(ignore_starts[i]) {
ignore = true;
}
}
if !ignore {
append += 1;
wd_all.insert(index + append, pathstr);
}
}
}
index += 1;
}
wd_all.remove(0);
wd_all
}
<file_sep>/README.md
Rim -- the conflictful CM for the real world
============================================
The name Rim promises.
<file_sep>/src/main.rs
extern crate crypto;
pub mod cl;
pub mod fs {
pub mod blob;
pub mod tree;
}
use cl::*;
fn main() {
parse_args();
}
<file_sep>/Cargo.toml
[package]
name = "rim"
version = "0.1.0"
authors = ["<NAME> <<EMAIL>>"]
description = "The conflictful configuration management system"
keywords = ["version control", "revision control", "source control", "configuration management", "software configuration management", "scm"]
readme = "README.md"
[dependencies]
rust-crypto = "*"
|
6da7d73365262c425ff2fb6f9f7190fe510a7e33
|
[
"Markdown",
"Rust",
"TOML"
] | 6 |
Rust
|
eonj/rim-rust
|
b9b312f0814d8970b42091760b15968e56b6a4c5
|
3205512cac74a5dd6b25c69df8c790aea302e652
|
refs/heads/master
|
<file_sep>/*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.http;
import io.netty.handler.codec.CharSequenceValueConverter;
import io.netty.handler.codec.DefaultHeaders;
import io.netty.handler.codec.Headers;
import io.netty.handler.codec.HeadersUtils;
import io.netty.handler.codec.ValueConverter;
import io.netty.util.AsciiString;
import io.netty.util.ByteProcessor;
import io.netty.util.internal.PlatformDependent;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import static io.netty.util.AsciiString.CASE_INSENSITIVE_HASHER;
import static io.netty.util.AsciiString.CASE_SENSITIVE_HASHER;
import static io.netty.util.internal.ObjectUtil.checkNotNull;
public class DefaultHttpHeaders extends DefaultHeaders<CharSequence> implements HttpHeaders {
private static final int HIGHEST_INVALID_VALUE_CHAR_MASK = ~15;
private static final ByteProcessor HEADER_NAME_VALIDATOR = new ByteProcessor() {
@Override
public boolean process(byte value) throws Exception {
validateChar((char) (value & 0xFF));
return true;
}
};
static final NameValidator<CharSequence> HttpNameValidator = new NameValidator<CharSequence>() {
@Override
public void validateName(CharSequence name) {
if (name instanceof AsciiString) {
try {
((AsciiString) name).forEachByte(HEADER_NAME_VALIDATOR);
} catch (Exception e) {
PlatformDependent.throwException(e);
}
} else {
checkNotNull(name, "name");
// Go through each character in the name
for (int index = 0; index < name.length(); ++index) {
validateChar(name.charAt(index));
}
}
}
};
public DefaultHttpHeaders() {
this(true);
}
@SuppressWarnings("unchecked")
public DefaultHttpHeaders(boolean validate) {
super(CASE_INSENSITIVE_HASHER, valueConverter(validate),
validate ? HttpNameValidator : NameValidator.NOT_NULL);
}
protected DefaultHttpHeaders(boolean validateValue, NameValidator<CharSequence> nameValidator) {
super(CASE_INSENSITIVE_HASHER, valueConverter(validateValue), nameValidator);
}
@Override
public HttpHeaders add(CharSequence name, CharSequence value) {
super.add(name, value);
return this;
}
@Override
public HttpHeaders add(CharSequence name, Iterable<? extends CharSequence> values) {
super.add(name, values);
return this;
}
@Override
public HttpHeaders add(CharSequence name, CharSequence... values) {
super.add(name, values);
return this;
}
@Override
public HttpHeaders addObject(CharSequence name, Object value) {
super.addObject(name, value);
return this;
}
@Override
public HttpHeaders addObject(CharSequence name, Iterable<?> values) {
super.addObject(name, values);
return this;
}
@Override
public HttpHeaders addObject(CharSequence name, Object... values) {
super.addObject(name, values);
return this;
}
@Override
public HttpHeaders addBoolean(CharSequence name, boolean value) {
super.addBoolean(name, value);
return this;
}
@Override
public HttpHeaders addChar(CharSequence name, char value) {
super.addChar(name, value);
return this;
}
@Override
public HttpHeaders addByte(CharSequence name, byte value) {
super.addByte(name, value);
return this;
}
@Override
public HttpHeaders addShort(CharSequence name, short value) {
super.addShort(name, value);
return this;
}
@Override
public HttpHeaders addInt(CharSequence name, int value) {
super.addInt(name, value);
return this;
}
@Override
public HttpHeaders addLong(CharSequence name, long value) {
super.addLong(name, value);
return this;
}
@Override
public HttpHeaders addFloat(CharSequence name, float value) {
super.addFloat(name, value);
return this;
}
@Override
public HttpHeaders addDouble(CharSequence name, double value) {
super.addDouble(name, value);
return this;
}
@Override
public HttpHeaders addTimeMillis(CharSequence name, long value) {
super.addTimeMillis(name, value);
return this;
}
@Override
public HttpHeaders add(Headers<? extends CharSequence> headers) {
super.add(headers);
return this;
}
@Override
public HttpHeaders set(CharSequence name, CharSequence value) {
super.set(name, value);
return this;
}
@Override
public HttpHeaders set(CharSequence name, Iterable<? extends CharSequence> values) {
super.set(name, values);
return this;
}
@Override
public HttpHeaders set(CharSequence name, CharSequence... values) {
super.set(name, values);
return this;
}
@Override
public HttpHeaders setObject(CharSequence name, Object value) {
super.setObject(name, value);
return this;
}
@Override
public HttpHeaders setObject(CharSequence name, Iterable<?> values) {
super.setObject(name, values);
return this;
}
@Override
public HttpHeaders setObject(CharSequence name, Object... values) {
super.setObject(name, values);
return this;
}
@Override
public HttpHeaders setBoolean(CharSequence name, boolean value) {
super.setBoolean(name, value);
return this;
}
@Override
public HttpHeaders setChar(CharSequence name, char value) {
super.setChar(name, value);
return this;
}
@Override
public HttpHeaders setByte(CharSequence name, byte value) {
super.setByte(name, value);
return this;
}
@Override
public HttpHeaders setShort(CharSequence name, short value) {
super.setShort(name, value);
return this;
}
@Override
public HttpHeaders setInt(CharSequence name, int value) {
super.setInt(name, value);
return this;
}
@Override
public HttpHeaders setLong(CharSequence name, long value) {
super.setLong(name, value);
return this;
}
@Override
public HttpHeaders setFloat(CharSequence name, float value) {
super.setFloat(name, value);
return this;
}
@Override
public HttpHeaders setDouble(CharSequence name, double value) {
super.setDouble(name, value);
return this;
}
@Override
public HttpHeaders setTimeMillis(CharSequence name, long value) {
super.setTimeMillis(name, value);
return this;
}
@Override
public HttpHeaders set(Headers<? extends CharSequence> headers) {
super.set(headers);
return this;
}
@Override
public HttpHeaders setAll(Headers<? extends CharSequence> headers) {
super.setAll(headers);
return this;
}
@Override
public HttpHeaders clear() {
super.clear();
return this;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof HttpHeaders)) {
return false;
}
return equals((HttpHeaders) o, CASE_SENSITIVE_HASHER);
}
@Override
public int hashCode() {
return hashCode(CASE_SENSITIVE_HASHER);
}
@Override
public String getAsString(CharSequence name) {
return HeadersUtils.getAsString(this, name);
}
@Override
public List<String> getAllAsString(CharSequence name) {
return HeadersUtils.getAllAsString(this, name);
}
@Override
public Iterator<Entry<String, String>> iteratorAsString() {
return HeadersUtils.iteratorAsString(this);
}
@Override
public boolean contains(CharSequence name, CharSequence value) {
return contains(name, value, false);
}
@Override
public boolean contains(CharSequence name, CharSequence value, boolean ignoreCase) {
return contains(name, value,
ignoreCase ? CASE_INSENSITIVE_HASHER : CASE_SENSITIVE_HASHER);
}
private static void validateChar(char character) {
switch (character) {
case '\t':
case '\n':
case 0x0b:
case '\f':
case '\r':
case ' ':
case ',':
case ':':
case ';':
case '=':
throw new IllegalArgumentException(
"a header name cannot contain the following prohibited characters: =,;: \\t\\r\\n\\v\\f: " +
character);
default:
// Check to see if the character is not an ASCII character, or invalid
if (character > 127) {
throw new IllegalArgumentException("a header name cannot contain non-ASCII character: " +
character);
}
}
}
private static ValueConverter<CharSequence> valueConverter(boolean validate) {
return validate ? HeaderValueConverterAndValidator.INSTANCE : HeaderValueConverter.INSTANCE;
}
private static class HeaderValueConverter extends CharSequenceValueConverter {
static final HeaderValueConverter INSTANCE = new HeaderValueConverter();
@Override
public CharSequence convertObject(Object value) {
checkNotNull(value, "value");
if (value instanceof CharSequence) {
return (CharSequence) value;
}
if (value instanceof Number) {
return value.toString();
}
if (value instanceof Date) {
return HttpHeaderDateFormat.get().format((Date) value);
}
if (value instanceof Calendar) {
return HttpHeaderDateFormat.get().format(((Calendar) value).getTime());
}
return value.toString();
}
}
private static final class HeaderValueConverterAndValidator extends HeaderValueConverter {
static final HeaderValueConverterAndValidator INSTANCE = new HeaderValueConverterAndValidator();
@Override
public CharSequence convertObject(Object value) {
CharSequence seq = super.convertObject(value);
int state = 0;
// Start looping through each of the character
for (int index = 0; index < seq.length(); index++) {
state = validateValueChar(seq, state, seq.charAt(index));
}
if (state != 0) {
throw new IllegalArgumentException("a header value must not end with '\\r' or '\\n':" + seq);
}
return seq;
}
private static int validateValueChar(CharSequence seq, int state, char character) {
/*
* State:
* 0: Previous character was neither CR nor LF
* 1: The previous character was CR
* 2: The previous character was LF
*/
if ((character & HIGHEST_INVALID_VALUE_CHAR_MASK) == 0) {
// Check the absolutely prohibited characters.
switch (character) {
case 0x0: // NULL
throw new IllegalArgumentException("a header value contains a prohibited character '\0': " + seq);
case 0x0b: // Vertical tab
throw new IllegalArgumentException("a header value contains a prohibited character '\\v': " + seq);
case '\f':
throw new IllegalArgumentException("a header value contains a prohibited character '\\f': " + seq);
}
}
// Check the CRLF (HT | SP) pattern
switch (state) {
case 0:
switch (character) {
case '\r':
return 1;
case '\n':
return 2;
}
break;
case 1:
switch (character) {
case '\n':
return 2;
default:
throw new IllegalArgumentException("only '\\n' is allowed after '\\r': " + seq);
}
case 2:
switch (character) {
case '\t':
case ' ':
return 0;
default:
throw new IllegalArgumentException("only ' ' and '\\t' are allowed after '\\n': " + seq);
}
}
return state;
}
}
}
<file_sep>/*
* Copyright 2015 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.http;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static io.netty.util.internal.StringUtil.COMMA;
import static io.netty.util.internal.StringUtil.DOUBLE_QUOTE;
class HttpHeadersTestUtils {
public enum HeaderValue {
UNKNOWN("unknown", 0),
ONE("one", 1),
TWO("two", 2),
THREE("three", 3),
FOUR("four", 4),
FIVE("five", 5),
SIX_QUOTED("six,", 6),
SEVEN_QUOTED("seven; , GMT", 7),
EIGHT("eight", 8);
private final int nr;
private final String value;
private CharSequence[] array;
HeaderValue(final String value, final int nr) {
this.nr = nr;
this.value = value;
}
@Override
public String toString() {
return value;
}
public CharSequence[] asArray() {
if (array == null) {
final String[] arr = new String[nr];
for (int i = 1, y = 0; i <= nr; i++, y++) {
arr[y] = of(i).toString();
}
array = arr;
}
return array;
}
public String[] subset(final int from) {
final int size = from - 1;
final String[] arr = new String[nr - size];
System.arraycopy(asArray(), size, arr, 0, arr.length);
return arr;
}
public String subsetAsCsvString(final int from) {
final String[] subset = subset(from);
return asCsv(subset);
}
public List<CharSequence> asList() {
return Arrays.<CharSequence>asList(asArray());
}
public String asCsv(final CharSequence[] arr) {
final StringBuilder sb = new StringBuilder();
int end = arr.length - 1;
for (int i = 0; i < end; i++) {
final CharSequence value = arr[i];
quoted(sb, value).append(COMMA);
}
quoted(sb, arr[end]);
return sb.toString();
}
public CharSequence asCsv() {
return asCsv(asArray());
}
private static StringBuilder quoted(final StringBuilder sb, final CharSequence value) {
if (contains(value, COMMA) && !contains(value, DOUBLE_QUOTE)) {
return sb.append(DOUBLE_QUOTE).append(value).append(DOUBLE_QUOTE);
}
return sb.append(value);
}
private static boolean contains(CharSequence value, char c) {
for (int i = 0; i < value.length(); ++i) {
if (value.charAt(i) == c) {
return true;
}
}
return false;
}
private static final Map<Integer, HeaderValue> MAP;
static {
final Map<Integer, HeaderValue> map = new HashMap<Integer, HeaderValue>();
for (HeaderValue v : values()) {
final int nr = v.nr;
map.put(Integer.valueOf(nr), v);
}
MAP = map;
}
public static HeaderValue of(final int nr) {
final HeaderValue v = MAP.get(Integer.valueOf(nr));
return v == null ? UNKNOWN : v;
}
}
}
<file_sep>/*
* Copyright 2015 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License, version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package io.netty.handler.codec.http2;
import static io.netty.util.internal.ObjectUtil.checkNotNull;
import static java.lang.Math.max;
import static java.lang.Math.min;
import java.util.Arrays;
/**
* A {@link StreamByteDistributor} that implements the HTTP/2 priority tree algorithm for allocating
* bytes for all streams in the connection.
*/
public final class PriorityStreamByteDistributor implements StreamByteDistributor {
private final Http2Connection connection;
private final Http2Connection.PropertyKey stateKey;
private final WriteVisitor writeVisitor = new WriteVisitor();
public PriorityStreamByteDistributor(Http2Connection connection) {
this.connection = checkNotNull(connection, "connection");
// Add a state for the connection.
stateKey = connection.newKey();
connection.connectionStream().setProperty(stateKey,
new PriorityState(connection.connectionStream()));
// Register for notification of new streams.
connection.addListener(new Http2ConnectionAdapter() {
@Override
public void onStreamAdded(Http2Stream stream) {
stream.setProperty(stateKey, new PriorityState(stream));
}
@Override
public void onStreamClosed(Http2Stream stream) {
state(stream).close();
}
@Override
public void onPriorityTreeParentChanged(Http2Stream stream, Http2Stream oldParent) {
Http2Stream parent = stream.parent();
if (parent != null) {
long delta = state(stream).unallocatedStreamableBytesForTree();
if (delta != 0) {
state(parent).unallocatedStreamableBytesForTreeChanged(delta);
}
}
}
@Override
public void onPriorityTreeParentChanging(Http2Stream stream, Http2Stream newParent) {
Http2Stream parent = stream.parent();
if (parent != null) {
long delta = state(stream).unallocatedStreamableBytesForTree();
if (delta != 0) {
state(parent).unallocatedStreamableBytesForTreeChanged(-delta);
}
}
}
});
}
@Override
public void updateStreamableBytes(StreamState streamState) {
state(streamState.stream()).updateStreamableBytes(streamState.streamableBytes(),
streamState.hasFrame());
}
@Override
public boolean distribute(int maxBytes, Writer writer) {
checkNotNull(writer, "writer");
if (maxBytes > 0) {
allocateBytesForTree(connection.connectionStream(), maxBytes);
}
// Need to write even if maxBytes == 0 in order to handle the case of empty frames.
writeVisitor.writeAllocatedBytes(writer);
return state(connection.connectionStream()).unallocatedStreamableBytesForTree() > 0;
}
/**
* For testing only.
*/
int unallocatedStreamableBytes(Http2Stream stream) {
return state(stream).unallocatedStreamableBytes();
}
/**
* For testing only.
*/
long unallocatedStreamableBytesForTree(Http2Stream stream) {
return state(stream).unallocatedStreamableBytesForTree();
}
/**
* This will allocate bytes by stream weight and priority for the entire tree rooted at {@code
* parent}, but does not write any bytes. The connection window is generally distributed amongst
* siblings according to their weight, however we need to ensure that the entire connection
* window is used (assuming streams have >= connection window bytes to send) and we may need
* some sort of rounding to accomplish this.
*
* @param parent The parent of the tree.
* @param connectionWindowSize The connection window this is available for use at this point in
* the tree.
* @return The number of bytes actually allocated.
*/
private int allocateBytesForTree(Http2Stream parent, int connectionWindowSize) {
PriorityState state = state(parent);
if (state.unallocatedStreamableBytesForTree() <= 0) {
return 0;
}
// If the number of streamable bytes for this tree will fit in the connection window
// then there is no need to prioritize the bytes...everyone sends what they have
if (state.unallocatedStreamableBytesForTree() <= connectionWindowSize) {
SimpleChildFeeder childFeeder = new SimpleChildFeeder(connectionWindowSize);
forEachChild(parent, childFeeder);
return childFeeder.bytesAllocated;
}
ChildFeeder childFeeder = new ChildFeeder(parent, connectionWindowSize);
// Iterate once over all children of this parent and try to feed all the children.
forEachChild(parent, childFeeder);
// Now feed any remaining children that are still hungry until the connection
// window collapses.
childFeeder.feedHungryChildren();
return childFeeder.bytesAllocated;
}
private void forEachChild(Http2Stream parent, Http2StreamVisitor childFeeder) {
try {
parent.forEachChild(childFeeder);
} catch (Http2Exception e) {
// Should never happen since the feeder doesn't throw.
throw new IllegalStateException(e);
}
}
private PriorityState state(Http2Stream stream) {
return checkNotNull(stream, "stream").getProperty(stateKey);
}
/**
* A {@link Http2StreamVisitor} that performs the HTTP/2 priority algorithm to distribute the
* available connection window appropriately to the children of a given stream.
*/
private final class ChildFeeder implements Http2StreamVisitor {
final int maxSize;
int totalWeight;
int connectionWindow;
int nextTotalWeight;
int nextConnectionWindow;
int bytesAllocated;
Http2Stream[] stillHungry;
int nextTail;
ChildFeeder(Http2Stream parent, int connectionWindow) {
maxSize = parent.numChildren();
totalWeight = parent.totalChildWeights();
this.connectionWindow = connectionWindow;
this.nextConnectionWindow = connectionWindow;
}
@Override
public boolean visit(Http2Stream child) {
// In order to make progress toward the connection window due to possible rounding errors, we make sure
// that each stream (with data to send) is given at least 1 byte toward the connection window.
int connectionWindowChunk =
max(1, (int) (connectionWindow * (child.weight() / (double) totalWeight)));
int bytesForTree = min(nextConnectionWindow, connectionWindowChunk);
PriorityState state = state(child);
int bytesForChild = min(state.unallocatedStreamableBytes(), bytesForTree);
// Allocate the bytes to this child.
if (bytesForChild > 0) {
state.allocate(bytesForChild);
bytesAllocated += bytesForChild;
nextConnectionWindow -= bytesForChild;
bytesForTree -= bytesForChild;
}
// Allocate any remaining bytes to the children of this stream.
if (bytesForTree > 0) {
int childBytesAllocated = allocateBytesForTree(child, bytesForTree);
bytesAllocated += childBytesAllocated;
nextConnectionWindow -= childBytesAllocated;
}
if (nextConnectionWindow > 0) {
// If this subtree still wants to send then it should be re-considered to take bytes that are unused by
// sibling nodes. This is needed because we don't yet know if all the peers will be able to use all of
// their "fair share" of the connection window, and if they don't use it then we should divide their
// unused shared up for the peers who still want to send.
if (state.unallocatedStreamableBytesForTree() > 0) {
stillHungry(child);
}
return true;
}
return false;
}
void feedHungryChildren() {
if (stillHungry == null) {
// There are no hungry children to feed.
return;
}
totalWeight = nextTotalWeight;
connectionWindow = nextConnectionWindow;
// Loop until there are not bytes left to stream or the connection window has collapsed.
for (int tail = nextTail; tail > 0 && connectionWindow > 0;) {
nextTotalWeight = 0;
nextTail = 0;
// Iterate over the children that are currently still hungry.
for (int head = 0; head < tail && nextConnectionWindow > 0; ++head) {
if (!visit(stillHungry[head])) {
// The connection window has collapsed, break out of the loop.
break;
}
}
connectionWindow = nextConnectionWindow;
totalWeight = nextTotalWeight;
tail = nextTail;
}
}
/**
* Indicates that the given child is still hungry (i.e. still has streamable bytes that can
* fit within the current connection window).
*/
void stillHungry(Http2Stream child) {
ensureSpaceIsAllocated(nextTail);
stillHungry[nextTail++] = child;
nextTotalWeight += child.weight();
}
/**
* Ensures that the {@link #stillHungry} array is properly sized to hold the given index.
*/
void ensureSpaceIsAllocated(int index) {
if (stillHungry == null) {
// Initial size is 1/4 the number of children. Clipping the minimum at 2, which will over allocate if
// maxSize == 1 but if this was true we shouldn't need to re-allocate because the 1 child should get
// all of the available connection window.
stillHungry = new Http2Stream[max(2, maxSize >>> 2)];
} else if (index == stillHungry.length) {
// Grow the array by a factor of 2.
stillHungry = Arrays.copyOf(stillHungry, min(maxSize, stillHungry.length << 1));
}
}
}
/**
* A simplified version of {@link ChildFeeder} that is only used when all streamable bytes fit
* within the available connection window.
*/
private final class SimpleChildFeeder implements Http2StreamVisitor {
int bytesAllocated;
int connectionWindow;
SimpleChildFeeder(int connectionWindow) {
this.connectionWindow = connectionWindow;
}
@Override
public boolean visit(Http2Stream child) {
PriorityState childState = state(child);
int bytesForChild = childState.unallocatedStreamableBytes();
if (bytesForChild > 0 || childState.hasFrame()) {
childState.allocate(bytesForChild);
bytesAllocated += bytesForChild;
connectionWindow -= bytesForChild;
}
int childBytesAllocated = allocateBytesForTree(child, connectionWindow);
bytesAllocated += childBytesAllocated;
connectionWindow -= childBytesAllocated;
return true;
}
}
/**
* The remote flow control state for a single stream.
*/
private final class PriorityState {
final Http2Stream stream;
boolean hasFrame;
int streamableBytes;
int allocated;
long unallocatedStreamableBytesForTree;
PriorityState(Http2Stream stream) {
this.stream = stream;
}
/**
* Recursively increments the {@link #unallocatedStreamableBytesForTree()} for this branch in
* the priority tree starting at the current node.
*/
void unallocatedStreamableBytesForTreeChanged(long delta) {
unallocatedStreamableBytesForTree += delta;
if (!stream.isRoot()) {
state(stream.parent()).unallocatedStreamableBytesForTreeChanged(delta);
}
}
void allocate(int bytes) {
allocated += bytes;
if (bytes != 0) {
// Also artificially reduce the streamable bytes for this tree to give the appearance
// that the data has been written. This will be restored before the allocated bytes are
// actually written.
unallocatedStreamableBytesForTreeChanged(-bytes);
}
}
/**
* Reset the number of bytes that have been allocated to this stream by the priority
* algorithm.
*/
void resetAllocated() {
allocate(-allocated);
}
void updateStreamableBytes(int newStreamableBytes, boolean hasFrame) {
this.hasFrame = hasFrame;
int delta = newStreamableBytes - streamableBytes;
if (delta != 0) {
streamableBytes = newStreamableBytes;
// Update this branch of the priority tree if the streamable bytes have changed for this node.
unallocatedStreamableBytesForTreeChanged(delta);
}
}
void close() {
// Unallocate all bytes.
resetAllocated();
// Clear the streamable bytes.
updateStreamableBytes(0, false);
}
boolean hasFrame() {
return hasFrame;
}
int unallocatedStreamableBytes() {
return streamableBytes - allocated;
}
long unallocatedStreamableBytesForTree() {
return unallocatedStreamableBytesForTree;
}
}
/**
* A connection stream visitor that delegates to the user provided visitor.
*/
private class WriteVisitor implements Http2StreamVisitor {
Writer writer;
RuntimeException error;
void writeAllocatedBytes(Writer writer) {
try {
this.writer = writer;
try {
connection.forEachActiveStream(this);
} catch (Http2Exception e) {
// Should never happen since the visitor doesn't throw.
throw new IllegalStateException(e);
}
// If an error was caught when calling back the visitor, throw it now.
if (error != null) {
throw error;
}
} finally {
error = null;
}
}
@Override
public boolean visit(Http2Stream stream) {
PriorityState state = state(stream);
try {
int allocated = state.allocated;
// Unallocate all bytes for this stream.
state.resetAllocated();
// Write the allocated bytes.
if (error == null) {
writer.write(stream, allocated);
}
} catch (RuntimeException e) {
// Stop calling the visitor, but continue in the loop to reset the allocated for
// all remaining states.
error = e;
}
// We have to iterate across all streams to ensure that we reset the allocated bytes.
return true;
}
}
}
<file_sep>/*
* Copyright 2014 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.stomp;
import io.netty.handler.codec.CharSequenceValueConverter;
import io.netty.handler.codec.DefaultHeaders;
import io.netty.handler.codec.Headers;
import io.netty.handler.codec.HeadersUtils;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import static io.netty.util.AsciiString.CASE_INSENSITIVE_HASHER;
import static io.netty.util.AsciiString.CASE_SENSITIVE_HASHER;
public class DefaultStompHeaders extends DefaultHeaders<CharSequence> implements StompHeaders {
public DefaultStompHeaders() {
super(CASE_SENSITIVE_HASHER, CharSequenceValueConverter.INSTANCE);
}
@Override
public StompHeaders add(CharSequence name, CharSequence value) {
super.add(name, value);
return this;
}
@Override
public StompHeaders add(CharSequence name, Iterable<? extends CharSequence> values) {
super.add(name, values);
return this;
}
@Override
public StompHeaders add(CharSequence name, CharSequence... values) {
super.add(name, values);
return this;
}
@Override
public StompHeaders addObject(CharSequence name, Object value) {
super.addObject(name, value);
return this;
}
@Override
public StompHeaders addObject(CharSequence name, Iterable<?> values) {
super.addObject(name, values);
return this;
}
@Override
public StompHeaders addObject(CharSequence name, Object... values) {
super.addObject(name, values);
return this;
}
@Override
public StompHeaders addBoolean(CharSequence name, boolean value) {
super.addBoolean(name, value);
return this;
}
@Override
public StompHeaders addChar(CharSequence name, char value) {
super.addChar(name, value);
return this;
}
@Override
public StompHeaders addByte(CharSequence name, byte value) {
super.addByte(name, value);
return this;
}
@Override
public StompHeaders addShort(CharSequence name, short value) {
super.addShort(name, value);
return this;
}
@Override
public StompHeaders addInt(CharSequence name, int value) {
super.addInt(name, value);
return this;
}
@Override
public StompHeaders addLong(CharSequence name, long value) {
super.addLong(name, value);
return this;
}
@Override
public StompHeaders addFloat(CharSequence name, float value) {
super.addFloat(name, value);
return this;
}
@Override
public StompHeaders addDouble(CharSequence name, double value) {
super.addDouble(name, value);
return this;
}
@Override
public StompHeaders addTimeMillis(CharSequence name, long value) {
super.addTimeMillis(name, value);
return this;
}
@Override
public StompHeaders add(Headers<? extends CharSequence> headers) {
super.add(headers);
return this;
}
@Override
public StompHeaders set(CharSequence name, CharSequence value) {
super.set(name, value);
return this;
}
@Override
public StompHeaders set(CharSequence name, Iterable<? extends CharSequence> values) {
super.set(name, values);
return this;
}
@Override
public StompHeaders set(CharSequence name, CharSequence... values) {
super.set(name, values);
return this;
}
@Override
public StompHeaders setObject(CharSequence name, Object value) {
super.setObject(name, value);
return this;
}
@Override
public StompHeaders setObject(CharSequence name, Iterable<?> values) {
super.setObject(name, values);
return this;
}
@Override
public StompHeaders setObject(CharSequence name, Object... values) {
super.setObject(name, values);
return this;
}
@Override
public StompHeaders setBoolean(CharSequence name, boolean value) {
super.setBoolean(name, value);
return this;
}
@Override
public StompHeaders setChar(CharSequence name, char value) {
super.setChar(name, value);
return this;
}
@Override
public StompHeaders setByte(CharSequence name, byte value) {
super.setByte(name, value);
return this;
}
@Override
public StompHeaders setShort(CharSequence name, short value) {
super.setShort(name, value);
return this;
}
@Override
public StompHeaders setInt(CharSequence name, int value) {
super.setInt(name, value);
return this;
}
@Override
public StompHeaders setLong(CharSequence name, long value) {
super.setLong(name, value);
return this;
}
@Override
public StompHeaders setFloat(CharSequence name, float value) {
super.setFloat(name, value);
return this;
}
@Override
public StompHeaders setDouble(CharSequence name, double value) {
super.setDouble(name, value);
return this;
}
@Override
public StompHeaders setTimeMillis(CharSequence name, long value) {
super.setTimeMillis(name, value);
return this;
}
@Override
public StompHeaders set(Headers<? extends CharSequence> headers) {
super.set(headers);
return this;
}
@Override
public StompHeaders setAll(Headers<? extends CharSequence> headers) {
super.setAll(headers);
return this;
}
@Override
public StompHeaders clear() {
super.clear();
return this;
}
@Override
public String getAsString(CharSequence name) {
return HeadersUtils.getAsString(this, name);
}
@Override
public List<String> getAllAsString(CharSequence name) {
return HeadersUtils.getAllAsString(this, name);
}
@Override
public Iterator<Entry<String, String>> iteratorAsString() {
return HeadersUtils.iteratorAsString(this);
}
@Override
public boolean contains(CharSequence name, CharSequence value) {
return contains(name, value, false);
}
@Override
public boolean contains(CharSequence name, CharSequence value, boolean ignoreCase) {
return contains(name, value,
ignoreCase ? CASE_INSENSITIVE_HASHER : CASE_SENSITIVE_HASHER);
}
}
<file_sep>/*
* Copyright 2013 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.spdy;
import io.netty.handler.codec.CharSequenceValueConverter;
import io.netty.handler.codec.DefaultHeaders;
import io.netty.handler.codec.Headers;
import io.netty.handler.codec.HeadersUtils;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import static io.netty.util.AsciiString.CASE_INSENSITIVE_HASHER;
import static io.netty.util.AsciiString.CASE_SENSITIVE_HASHER;
public class DefaultSpdyHeaders extends DefaultHeaders<CharSequence> implements SpdyHeaders {
private static final NameValidator<CharSequence> SpydNameValidator = new NameValidator<CharSequence>() {
@Override
public void validateName(CharSequence name) {
SpdyCodecUtil.validateHeaderName(name);
}
};
public DefaultSpdyHeaders() {
this(true);
}
@SuppressWarnings("unchecked")
public DefaultSpdyHeaders(boolean validate) {
super(CASE_INSENSITIVE_HASHER,
validate ? HeaderValueConverterAndValidator.INSTANCE : HeaderValueConverter.INSTANCE,
validate ? SpydNameValidator : NameValidator.NOT_NULL);
}
@Override
public SpdyHeaders add(CharSequence name, CharSequence value) {
super.add(name, value);
return this;
}
@Override
public SpdyHeaders add(CharSequence name, Iterable<? extends CharSequence> values) {
super.add(name, values);
return this;
}
@Override
public SpdyHeaders add(CharSequence name, CharSequence... values) {
super.add(name, values);
return this;
}
@Override
public SpdyHeaders addObject(CharSequence name, Object value) {
super.addObject(name, value);
return this;
}
@Override
public SpdyHeaders addObject(CharSequence name, Iterable<?> values) {
super.addObject(name, values);
return this;
}
@Override
public SpdyHeaders addObject(CharSequence name, Object... values) {
super.addObject(name, values);
return this;
}
@Override
public SpdyHeaders addBoolean(CharSequence name, boolean value) {
super.addBoolean(name, value);
return this;
}
@Override
public SpdyHeaders addChar(CharSequence name, char value) {
super.addChar(name, value);
return this;
}
@Override
public SpdyHeaders addByte(CharSequence name, byte value) {
super.addByte(name, value);
return this;
}
@Override
public SpdyHeaders addShort(CharSequence name, short value) {
super.addShort(name, value);
return this;
}
@Override
public SpdyHeaders addInt(CharSequence name, int value) {
super.addInt(name, value);
return this;
}
@Override
public SpdyHeaders addLong(CharSequence name, long value) {
super.addLong(name, value);
return this;
}
@Override
public SpdyHeaders addFloat(CharSequence name, float value) {
super.addFloat(name, value);
return this;
}
@Override
public SpdyHeaders addDouble(CharSequence name, double value) {
super.addDouble(name, value);
return this;
}
@Override
public SpdyHeaders addTimeMillis(CharSequence name, long value) {
super.addTimeMillis(name, value);
return this;
}
@Override
public SpdyHeaders add(Headers<? extends CharSequence> headers) {
super.add(headers);
return this;
}
@Override
public SpdyHeaders set(CharSequence name, CharSequence value) {
super.set(name, value);
return this;
}
@Override
public SpdyHeaders set(CharSequence name, Iterable<? extends CharSequence> values) {
super.set(name, values);
return this;
}
@Override
public SpdyHeaders set(CharSequence name, CharSequence... values) {
super.set(name, values);
return this;
}
@Override
public SpdyHeaders setObject(CharSequence name, Object value) {
super.setObject(name, value);
return this;
}
@Override
public SpdyHeaders setObject(CharSequence name, Iterable<?> values) {
super.setObject(name, values);
return this;
}
@Override
public SpdyHeaders setObject(CharSequence name, Object... values) {
super.setObject(name, values);
return this;
}
@Override
public SpdyHeaders setBoolean(CharSequence name, boolean value) {
super.setBoolean(name, value);
return this;
}
@Override
public SpdyHeaders setChar(CharSequence name, char value) {
super.setChar(name, value);
return this;
}
@Override
public SpdyHeaders setByte(CharSequence name, byte value) {
super.setByte(name, value);
return this;
}
@Override
public SpdyHeaders setShort(CharSequence name, short value) {
super.setShort(name, value);
return this;
}
@Override
public SpdyHeaders setInt(CharSequence name, int value) {
super.setInt(name, value);
return this;
}
@Override
public SpdyHeaders setLong(CharSequence name, long value) {
super.setLong(name, value);
return this;
}
@Override
public SpdyHeaders setFloat(CharSequence name, float value) {
super.setFloat(name, value);
return this;
}
@Override
public SpdyHeaders setDouble(CharSequence name, double value) {
super.setDouble(name, value);
return this;
}
@Override
public SpdyHeaders setTimeMillis(CharSequence name, long value) {
super.setTimeMillis(name, value);
return this;
}
@Override
public SpdyHeaders set(Headers<? extends CharSequence> headers) {
super.set(headers);
return this;
}
@Override
public SpdyHeaders setAll(Headers<? extends CharSequence> headers) {
super.setAll(headers);
return this;
}
@Override
public SpdyHeaders clear() {
super.clear();
return this;
}
@Override
public String getAsString(CharSequence name) {
return HeadersUtils.getAsString(this, name);
}
@Override
public List<String> getAllAsString(CharSequence name) {
return HeadersUtils.getAllAsString(this, name);
}
@Override
public Iterator<Entry<String, String>> iteratorAsString() {
return HeadersUtils.iteratorAsString(this);
}
@Override
public boolean contains(CharSequence name, CharSequence value) {
return contains(name, value, false);
}
@Override
public boolean contains(CharSequence name, CharSequence value, boolean ignoreCase) {
return contains(name, value,
ignoreCase ? CASE_INSENSITIVE_HASHER : CASE_SENSITIVE_HASHER);
}
private static class HeaderValueConverter extends CharSequenceValueConverter {
public static final HeaderValueConverter INSTANCE = new HeaderValueConverter();
@Override
public CharSequence convertObject(Object value) {
final CharSequence seq;
if (value instanceof CharSequence) {
seq = (CharSequence) value;
} else {
seq = value.toString();
}
return seq;
}
}
private static final class HeaderValueConverterAndValidator extends HeaderValueConverter {
public static final HeaderValueConverterAndValidator INSTANCE = new HeaderValueConverterAndValidator();
@Override
public CharSequence convertObject(Object value) {
final CharSequence seq = super.convertObject(value);
SpdyCodecUtil.validateHeaderValue(seq);
return seq;
}
}
}
<file_sep>/*
* Copyright 2015 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License, version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package io.netty.handler.codec;
import java.nio.charset.Charset;
import java.text.ParseException;
import io.netty.handler.codec.DefaultHeaders.HeaderDateFormat;
import io.netty.util.ByteString;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.PlatformDependent;
/**
* Converts to/from native types, general {@link Object}, and {@link ByteString}s.
*/
public final class ByteStringValueConverter implements ValueConverter<ByteString> {
public static final ByteStringValueConverter INSTANCE = new ByteStringValueConverter();
private static final Charset DEFAULT_CHARSET = CharsetUtil.UTF_8;
private ByteStringValueConverter() {
}
@Override
public ByteString convertObject(Object value) {
if (value instanceof ByteString) {
return (ByteString) value;
}
if (value instanceof CharSequence) {
return new ByteString((CharSequence) value, DEFAULT_CHARSET);
}
return new ByteString(value.toString(), DEFAULT_CHARSET);
}
@Override
public ByteString convertInt(int value) {
return new ByteString(String.valueOf(value), DEFAULT_CHARSET);
}
@Override
public ByteString convertLong(long value) {
return new ByteString(String.valueOf(value), DEFAULT_CHARSET);
}
@Override
public ByteString convertDouble(double value) {
return new ByteString(String.valueOf(value), DEFAULT_CHARSET);
}
@Override
public ByteString convertChar(char value) {
return new ByteString(String.valueOf(value), DEFAULT_CHARSET);
}
@Override
public ByteString convertBoolean(boolean value) {
return new ByteString(String.valueOf(value), DEFAULT_CHARSET);
}
@Override
public ByteString convertFloat(float value) {
return new ByteString(String.valueOf(value), DEFAULT_CHARSET);
}
@Override
public int convertToInt(ByteString value) {
return value.parseAsciiInt();
}
@Override
public long convertToLong(ByteString value) {
return value.parseAsciiLong();
}
@Override
public ByteString convertTimeMillis(long value) {
return new ByteString(String.valueOf(value), DEFAULT_CHARSET);
}
@Override
public long convertToTimeMillis(ByteString value) {
try {
return HeaderDateFormat.get().parse(value.toString());
} catch (ParseException e) {
PlatformDependent.throwException(e);
}
return 0;
}
@Override
public double convertToDouble(ByteString value) {
return value.parseAsciiDouble();
}
@Override
public char convertToChar(ByteString value) {
return value.parseChar();
}
@Override
public boolean convertToBoolean(ByteString value) {
return value.byteAt(0) != 0;
}
@Override
public float convertToFloat(ByteString value) {
return value.parseAsciiFloat();
}
@Override
public ByteString convertShort(short value) {
return new ByteString(String.valueOf(value), DEFAULT_CHARSET);
}
@Override
public short convertToShort(ByteString value) {
return value.parseAsciiShort();
}
@Override
public ByteString convertByte(byte value) {
return new ByteString(String.valueOf(value), DEFAULT_CHARSET);
}
@Override
public byte convertToByte(ByteString value) {
return value.byteAt(0);
}
}
<file_sep>/*
* Copyright 2015 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.microbench.headers;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http2.DefaultHttp2Headers;
import io.netty.microbench.util.AbstractMicrobenchmark;
import io.netty.util.AsciiString;
import io.netty.util.ByteString;
import io.netty.util.CharsetUtil;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
@Threads(1)
@State(Scope.Benchmark)
@Warmup(iterations = 5)
@Measurement(iterations = 5)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class HeadersBenchmark extends AbstractMicrobenchmark {
@Param
ExampleHeaders.HeaderExample exampleHeader;
AsciiString[] httpNames;
AsciiString[] httpValues;
ByteString[] http2Names;
ByteString[] http2Values;
DefaultHttpHeaders httpHeaders;
DefaultHttp2Headers http2Headers;
@Setup(Level.Trial)
public void setup() {
Map<String, String> headers = ExampleHeaders.EXAMPLES.get(exampleHeader);
httpNames = new AsciiString[headers.size()];
httpValues = new AsciiString[headers.size()];
http2Names = new ByteString[headers.size()];
http2Values = new ByteString[headers.size()];
httpHeaders = new DefaultHttpHeaders(false);
http2Headers = new DefaultHttp2Headers(false);
int idx = 0;
for (Map.Entry<String, String> header : headers.entrySet()) {
String name = header.getKey();
String value = header.getValue();
httpNames[idx] = new AsciiString(name);
httpValues[idx] = new AsciiString(value);
http2Names[idx] = new ByteString(name, CharsetUtil.US_ASCII);
http2Values[idx] = new ByteString(value, CharsetUtil.US_ASCII);
idx++;
httpHeaders.add(new AsciiString(name), new AsciiString(value));
http2Headers.add(new ByteString(name, CharsetUtil.US_ASCII), new ByteString(value, CharsetUtil.US_ASCII));
}
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public void httpRemove(Blackhole bh) {
for (AsciiString name : httpNames) {
bh.consume(httpHeaders.remove(name));
}
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public void httpGet(Blackhole bh) {
for (AsciiString name : httpNames) {
bh.consume(httpHeaders.get(name));
}
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public DefaultHttpHeaders httpPut() {
DefaultHttpHeaders headers = new DefaultHttpHeaders(false);
for (int i = 0; i < httpNames.length; i++) {
headers.add(httpNames[i], httpValues[i]);
}
return headers;
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public void httpIterate(Blackhole bh) {
for (Entry<CharSequence, CharSequence> entry : httpHeaders) {
bh.consume(entry);
}
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public void http2Remove(Blackhole bh) {
for (ByteString name : http2Names) {
bh.consume(http2Headers.remove(name));
}
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public void http2Get(Blackhole bh) {
for (ByteString name : http2Names) {
bh.consume(http2Headers.get(name));
}
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public DefaultHttp2Headers http2Put() {
DefaultHttp2Headers headers = new DefaultHttp2Headers(false);
for (int i = 0; i < httpNames.length; i++) {
headers.add(httpNames[i], httpValues[i]);
}
return headers;
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public void http2Iterate(Blackhole bh) {
for (Entry<ByteString, ByteString> entry : http2Headers) {
bh.consume(entry);
}
}
}
<file_sep>/*
* Copyright 2015 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License, version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package io.netty.handler.codec.http2;
import io.netty.util.collection.IntObjectHashMap;
import io.netty.util.collection.IntObjectMap;
import org.junit.Before;
import org.junit.Test;
import org.mockito.AdditionalMatchers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.mockito.verification.VerificationMode;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static io.netty.handler.codec.http2.Http2CodecUtil.DEFAULT_PRIORITY_WEIGHT;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.same;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link PriorityStreamByteDistributor}.
*/
public class PriorityStreamByteDistributorTest {
private static final int STREAM_A = 1;
private static final int STREAM_B = 3;
private static final int STREAM_C = 5;
private static final int STREAM_D = 7;
private static final int STREAM_E = 9;
private Http2Connection connection;
private PriorityStreamByteDistributor distributor;
@Mock
private StreamByteDistributor.Writer writer;
@Before
public void setup() throws Http2Exception {
MockitoAnnotations.initMocks(this);
connection = new DefaultHttp2Connection(false);
distributor = new PriorityStreamByteDistributor(connection);
// Assume we always write all the allocated bytes.
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock in) throws Throwable {
Http2Stream stream = (Http2Stream) in.getArguments()[0];
int numBytes = (Integer) in.getArguments()[1];
int streamableBytes = distributor.unallocatedStreamableBytes(stream) - numBytes;
updateStream(stream.id(), streamableBytes, streamableBytes > 0);
return null;
}
}).when(writer).write(any(Http2Stream.class), anyInt());
connection.local().createStream(STREAM_A, false);
connection.local().createStream(STREAM_B, false);
Http2Stream streamC = connection.local().createStream(STREAM_C, false);
Http2Stream streamD = connection.local().createStream(STREAM_D, false);
streamC.setPriority(STREAM_A, DEFAULT_PRIORITY_WEIGHT, false);
streamD.setPriority(STREAM_A, DEFAULT_PRIORITY_WEIGHT, false);
}
@Test
public void bytesUnassignedAfterProcessing() {
updateStream(STREAM_A, 1, true);
updateStream(STREAM_B, 2, true);
updateStream(STREAM_C, 3, true);
updateStream(STREAM_D, 4, true);
assertFalse(write(10));
verifyWrite(STREAM_A, 1);
verifyWrite(STREAM_B, 2);
verifyWrite(STREAM_C, 3);
verifyWrite(STREAM_D, 4);
assertFalse(write(10));
verifyWrite(STREAM_A, 0);
verifyWrite(STREAM_B, 0);
verifyWrite(STREAM_C, 0);
verifyWrite(STREAM_D, 0);
}
@Test
public void bytesUnassignedAfterProcessingWithException() {
updateStream(STREAM_A, 1, true);
updateStream(STREAM_B, 2, true);
updateStream(STREAM_C, 3, true);
updateStream(STREAM_D, 4, true);
Exception fakeException = new RuntimeException("Fake exception");
doThrow(fakeException).when(writer).write(same(stream(STREAM_C)), eq(3));
try {
write(10);
fail("Expected an exception");
} catch (RuntimeException e) {
assertSame(fakeException, e);
}
verifyWrite(atMost(1), STREAM_A, 1);
verifyWrite(atMost(1), STREAM_B, 2);
verifyWrite(STREAM_C, 3);
verifyWrite(atMost(1), STREAM_D, 4);
doNothing().when(writer).write(same(stream(STREAM_C)), eq(3));
write(10);
verifyWrite(atMost(1), STREAM_A, 1);
verifyWrite(atMost(1), STREAM_B, 2);
verifyWrite(times(2), STREAM_C, 3);
verifyWrite(atMost(1), STREAM_D, 4);
}
/**
* In this test, we block A which allows bytes to be written by C and D. Here's a view of the tree (stream A is
* blocked).
*
* <pre>
* 0
* / \
* [A] B
* / \
* C D
* </pre>
*/
@Test
public void blockedStreamShouldSpreadDataToChildren() throws Http2Exception {
// A cannot stream.
updateStream(STREAM_B, 10, true);
updateStream(STREAM_C, 10, true);
updateStream(STREAM_D, 10, true);
// Write up to 10 bytes.
assertTrue(write(10));
// A is not written
verifyWrite(STREAM_A, 0);
// B is partially written
verifyWrite(STREAM_B, 5);
// Verify that C and D each shared half of A's allowance. Since A's allowance (5) cannot
// be split evenly, one will get 3 and one will get 2.
verifyWrite(STREAM_C, 3);
verifyWrite(STREAM_D, 2);
}
/**
* In this test, we block B which allows all bytes to be written by A. A should not share the data with its children
* since it's not blocked.
*
* <pre>
* 0
* / \
* A [B]
* / \
* C D
* </pre>
*/
@Test
public void childrenShouldNotSendDataUntilParentBlocked() throws Http2Exception {
// B cannot stream.
updateStream(STREAM_A, 10, true);
updateStream(STREAM_C, 10, true);
updateStream(STREAM_D, 10, true);
// Write up to 10 bytes.
assertTrue(write(10));
// A is assigned all of the bytes.
verifyWrite(STREAM_A, 10);
verifyWrite(STREAM_B, 0);
verifyWrite(STREAM_C, 0);
verifyWrite(STREAM_D, 0);
}
/**
* In this test, we block B which allows all bytes to be written by A. Once A is complete, it will spill over the
* remaining of its portion to its children.
*
* <pre>
* 0
* / \
* A [B]
* / \
* C D
* </pre>
*/
@Test
public void parentShouldWaterFallDataToChildren() throws Http2Exception {
// B cannot stream.
updateStream(STREAM_A, 5, true);
updateStream(STREAM_C, 10, true);
updateStream(STREAM_D, 10, true);
// Write up to 10 bytes.
assertTrue(write(10));
verifyWrite(STREAM_A, 5);
verifyWrite(STREAM_B, 0);
verifyWrite(STREAM_C, 3);
verifyWrite(STREAM_D, 2);
}
/**
* In this test, we verify re-prioritizing a stream. We start out with B blocked:
*
* <pre>
* 0
* / \
* A [B]
* / \
* C D
* </pre>
*
* We then re-prioritize D so that it's directly off of the connection and verify that A and D split the written
* bytes between them.
*
* <pre>
* 0
* /|\
* / | \
* A [B] D
* /
* C
* </pre>
*/
@Test
public void reprioritizeShouldAdjustOutboundFlow() throws Http2Exception {
// B cannot stream.
updateStream(STREAM_A, 10, true);
updateStream(STREAM_C, 10, true);
updateStream(STREAM_D, 10, true);
// Re-prioritize D as a direct child of the connection.
setPriority(STREAM_D, 0, DEFAULT_PRIORITY_WEIGHT, false);
assertTrue(write(10));
verifyWrite(STREAM_A, 5);
verifyWrite(STREAM_B, 0);
verifyWrite(STREAM_C, 0);
verifyWrite(STREAM_D, 5);
}
/**
* Test that the maximum allowed amount the flow controller allows to be sent is always fully allocated if
* the streams have at least this much data to send. See https://github.com/netty/netty/issues/4266.
* <pre>
* 0
* / | \
* / | \
* A(0) B(0) C(0)
* /
* D(> allowed to send in 1 allocation attempt)
* </pre>
*/
@Test
public void unstreamableParentsShouldFeedHungryChildren() throws Http2Exception {
// Setup the priority tree.
setPriority(STREAM_A, 0, (short) 32, false);
setPriority(STREAM_B, 0, (short) 16, false);
setPriority(STREAM_C, 0, (short) 16, false);
setPriority(STREAM_D, STREAM_A, (short) 16, false);
final int writableBytes = 100;
// Send enough so it can not be completely written out
final int expectedUnsentAmount = 1;
updateStream(STREAM_D, writableBytes + expectedUnsentAmount, true);
assertTrue(write(writableBytes));
verifyWrite(STREAM_D, writableBytes);
assertEquals(expectedUnsentAmount, streamableBytesForTree(stream(STREAM_D)));
}
/**
* In this test, we root all streams at the connection, and then verify that data is split appropriately based on
* weight (all available data is the same).
*
* <pre>
* 0
* / / \ \
* A B C D
* </pre>
*/
@Test
public void writeShouldPreferHighestWeight() throws Http2Exception {
// Root the streams at the connection and assign weights.
setPriority(STREAM_A, 0, (short) 50, false);
setPriority(STREAM_B, 0, (short) 200, false);
setPriority(STREAM_C, 0, (short) 100, false);
setPriority(STREAM_D, 0, (short) 100, false);
updateStream(STREAM_A, 1000, true);
updateStream(STREAM_B, 1000, true);
updateStream(STREAM_C, 1000, true);
updateStream(STREAM_D, 1000, true);
assertTrue(write(1000));
// A is assigned all of the bytes.
int allowedError = 10;
verifyWriteWithDelta(STREAM_A, 109, allowedError);
verifyWriteWithDelta(STREAM_B, 445, allowedError);
verifyWriteWithDelta(STREAM_C, 223, allowedError);
verifyWriteWithDelta(STREAM_D, 223, allowedError);
}
/**
* In this test, we root all streams at the connection, and then verify that data is split equally among the stream,
* since they all have the same weight.
*
* <pre>
* 0
* / / \ \
* A B C D
* </pre>
*/
@Test
public void samePriorityShouldDistributeBasedOnData() throws Http2Exception {
// Root the streams at the connection with the same weights.
setPriority(STREAM_A, 0, DEFAULT_PRIORITY_WEIGHT, false);
setPriority(STREAM_B, 0, DEFAULT_PRIORITY_WEIGHT, false);
setPriority(STREAM_C, 0, DEFAULT_PRIORITY_WEIGHT, false);
setPriority(STREAM_D, 0, DEFAULT_PRIORITY_WEIGHT, false);
updateStream(STREAM_A, 400, true);
updateStream(STREAM_B, 500, true);
updateStream(STREAM_C, 0, true);
updateStream(STREAM_D, 700, true);
assertTrue(write(999));
verifyWrite(STREAM_A, 333);
verifyWrite(STREAM_B, 333);
verifyWrite(STREAM_C, 0);
verifyWrite(STREAM_D, 333);
}
/**
* In this test, we verify the priority bytes for each sub tree at each node are correct
*
* <pre>
* 0
* / \
* A B
* / \
* C D
* </pre>
*/
@Test
public void subTreeBytesShouldBeCorrect() throws Http2Exception {
Http2Stream stream0 = connection.connectionStream();
Http2Stream streamA = connection.stream(STREAM_A);
Http2Stream streamB = connection.stream(STREAM_B);
Http2Stream streamC = connection.stream(STREAM_C);
Http2Stream streamD = connection.stream(STREAM_D);
// Send a bunch of data on each stream.
final IntObjectMap<Integer> streamSizes = new IntObjectHashMap<Integer>(4);
streamSizes.put(STREAM_A, (Integer) 400);
streamSizes.put(STREAM_B, (Integer) 500);
streamSizes.put(STREAM_C, (Integer) 600);
streamSizes.put(STREAM_D, (Integer) 700);
updateStream(STREAM_A, streamSizes.get(STREAM_A), true);
updateStream(STREAM_B, streamSizes.get(STREAM_B), true);
updateStream(STREAM_C, streamSizes.get(STREAM_C), true);
updateStream(STREAM_D, streamSizes.get(STREAM_D), true);
assertEquals(calculateStreamSizeSum(streamSizes,
Arrays.asList(STREAM_A, STREAM_B, STREAM_C, STREAM_D)),
streamableBytesForTree(stream0));
assertEquals(
calculateStreamSizeSum(streamSizes, Arrays.asList(STREAM_A, STREAM_C, STREAM_D)),
streamableBytesForTree(streamA));
assertEquals(calculateStreamSizeSum(streamSizes, Collections.singletonList(STREAM_B)),
streamableBytesForTree(streamB));
assertEquals(calculateStreamSizeSum(streamSizes, Collections.singletonList(STREAM_C)),
streamableBytesForTree(streamC));
assertEquals(calculateStreamSizeSum(streamSizes, Collections.singletonList(STREAM_D)),
streamableBytesForTree(streamD));
}
/**
* In this test, we shift the priority tree and verify priority bytes for each subtree are correct
*
* <pre>
* 0
* / \
* A B
* / \
* C D
* </pre>
*
* After the tree shift:
*
* <pre>
* 0
* |
* A
* |
* B
* / \
* C D
* </pre>
*/
@Test
public void subTreeBytesShouldBeCorrectWithRestructure() throws Http2Exception {
Http2Stream stream0 = connection.connectionStream();
Http2Stream streamA = connection.stream(STREAM_A);
Http2Stream streamB = connection.stream(STREAM_B);
Http2Stream streamC = connection.stream(STREAM_C);
Http2Stream streamD = connection.stream(STREAM_D);
// Send a bunch of data on each stream.
final IntObjectMap<Integer> streamSizes = new IntObjectHashMap<Integer>(4);
streamSizes.put(STREAM_A, (Integer) 400);
streamSizes.put(STREAM_B, (Integer) 500);
streamSizes.put(STREAM_C, (Integer) 600);
streamSizes.put(STREAM_D, (Integer) 700);
updateStream(STREAM_A, streamSizes.get(STREAM_A), true);
updateStream(STREAM_B, streamSizes.get(STREAM_B), true);
updateStream(STREAM_C, streamSizes.get(STREAM_C), true);
updateStream(STREAM_D, streamSizes.get(STREAM_D), true);
streamB.setPriority(STREAM_A, DEFAULT_PRIORITY_WEIGHT, true);
assertEquals(calculateStreamSizeSum(streamSizes,
Arrays.asList(STREAM_A, STREAM_B, STREAM_C, STREAM_D)),
streamableBytesForTree(stream0));
assertEquals(calculateStreamSizeSum(streamSizes,
Arrays.asList(STREAM_A, STREAM_B, STREAM_C, STREAM_D)),
streamableBytesForTree(streamA));
assertEquals(calculateStreamSizeSum(streamSizes, Arrays.asList(STREAM_B, STREAM_C, STREAM_D)),
streamableBytesForTree(streamB));
assertEquals(calculateStreamSizeSum(streamSizes, Collections.singletonList(STREAM_C)),
streamableBytesForTree(streamC));
assertEquals(calculateStreamSizeSum(streamSizes, Collections.singletonList(STREAM_D)),
streamableBytesForTree(streamD));
}
/**
* In this test, we add a node to the priority tree and verify
*
* <pre>
* 0
* / \
* A B
* / \
* C D
* </pre>
*
* After the tree shift:
*
* <pre>
* 0
* / \
* A B
* |
* E
* / \
* C D
* </pre>
*/
@Test
public void subTreeBytesShouldBeCorrectWithAddition() throws Http2Exception {
Http2Stream stream0 = connection.connectionStream();
Http2Stream streamA = connection.stream(STREAM_A);
Http2Stream streamB = connection.stream(STREAM_B);
Http2Stream streamC = connection.stream(STREAM_C);
Http2Stream streamD = connection.stream(STREAM_D);
Http2Stream streamE = connection.local().createStream(STREAM_E, false);
streamE.setPriority(STREAM_A, DEFAULT_PRIORITY_WEIGHT, true);
// Send a bunch of data on each stream.
final IntObjectMap<Integer> streamSizes = new IntObjectHashMap<Integer>(4);
streamSizes.put(STREAM_A, (Integer) 400);
streamSizes.put(STREAM_B, (Integer) 500);
streamSizes.put(STREAM_C, (Integer) 600);
streamSizes.put(STREAM_D, (Integer) 700);
streamSizes.put(STREAM_E, (Integer) 900);
updateStream(STREAM_A, streamSizes.get(STREAM_A), true);
updateStream(STREAM_B, streamSizes.get(STREAM_B), true);
updateStream(STREAM_C, streamSizes.get(STREAM_C), true);
updateStream(STREAM_D, streamSizes.get(STREAM_D), true);
updateStream(STREAM_E, streamSizes.get(STREAM_E), true);
assertEquals(calculateStreamSizeSum(streamSizes,
Arrays.asList(STREAM_A, STREAM_B, STREAM_C, STREAM_D, STREAM_E)),
streamableBytesForTree(stream0));
assertEquals(calculateStreamSizeSum(streamSizes,
Arrays.asList(STREAM_A, STREAM_E, STREAM_C, STREAM_D)),
streamableBytesForTree(streamA));
assertEquals(calculateStreamSizeSum(streamSizes, Collections.singletonList(STREAM_B)),
streamableBytesForTree(streamB));
assertEquals(calculateStreamSizeSum(streamSizes, Collections.singletonList(STREAM_C)),
streamableBytesForTree(streamC));
assertEquals(calculateStreamSizeSum(streamSizes, Collections.singletonList(STREAM_D)),
streamableBytesForTree(streamD));
assertEquals(calculateStreamSizeSum(streamSizes, Arrays.asList(STREAM_E, STREAM_C, STREAM_D)),
streamableBytesForTree(streamE));
}
/**
* In this test, we close an internal stream in the priority tree but tree should not change
*
* <pre>
* 0
* / \
* A B
* / \
* C D
* </pre>
*/
@Test
public void subTreeBytesShouldBeCorrectWithInternalStreamClose() throws Http2Exception {
Http2Stream stream0 = connection.connectionStream();
Http2Stream streamA = connection.stream(STREAM_A);
Http2Stream streamB = connection.stream(STREAM_B);
Http2Stream streamC = connection.stream(STREAM_C);
Http2Stream streamD = connection.stream(STREAM_D);
// Send a bunch of data on each stream.
final IntObjectMap<Integer> streamSizes = new IntObjectHashMap<Integer>(4);
streamSizes.put(STREAM_A, (Integer) 400);
streamSizes.put(STREAM_B, (Integer) 500);
streamSizes.put(STREAM_C, (Integer) 600);
streamSizes.put(STREAM_D, (Integer) 700);
updateStream(STREAM_A, streamSizes.get(STREAM_A), true);
updateStream(STREAM_B, streamSizes.get(STREAM_B), true);
updateStream(STREAM_C, streamSizes.get(STREAM_C), true);
updateStream(STREAM_D, streamSizes.get(STREAM_D), true);
streamA.close();
assertEquals(calculateStreamSizeSum(streamSizes, Arrays.asList(STREAM_B, STREAM_C, STREAM_D)),
streamableBytesForTree(stream0));
assertEquals(calculateStreamSizeSum(streamSizes, Arrays.asList(STREAM_C, STREAM_D)),
streamableBytesForTree(streamA));
assertEquals(calculateStreamSizeSum(streamSizes, Collections.singletonList(STREAM_B)),
streamableBytesForTree(streamB));
assertEquals(calculateStreamSizeSum(streamSizes, Collections.singletonList(STREAM_C)),
streamableBytesForTree(streamC));
assertEquals(calculateStreamSizeSum(streamSizes, Collections.singletonList(STREAM_D)),
streamableBytesForTree(streamD));
}
/**
* In this test, we close a leaf stream in the priority tree and verify
*
* <pre>
* 0
* / \
* A B
* / \
* C D
* </pre>
*
* After the close:
* <pre>
* 0
* / \
* A B
* |
* D
* </pre>
*/
@Test
public void subTreeBytesShouldBeCorrectWithLeafStreamClose() throws Http2Exception {
Http2Stream stream0 = connection.connectionStream();
Http2Stream streamA = connection.stream(STREAM_A);
Http2Stream streamB = connection.stream(STREAM_B);
Http2Stream streamC = connection.stream(STREAM_C);
Http2Stream streamD = connection.stream(STREAM_D);
// Send a bunch of data on each stream.
final IntObjectMap<Integer> streamSizes = new IntObjectHashMap<Integer>(4);
streamSizes.put(STREAM_A, (Integer) 400);
streamSizes.put(STREAM_B, (Integer) 500);
streamSizes.put(STREAM_C, (Integer) 600);
streamSizes.put(STREAM_D, (Integer) 700);
updateStream(STREAM_A, streamSizes.get(STREAM_A), true);
updateStream(STREAM_B, streamSizes.get(STREAM_B), true);
updateStream(STREAM_C, streamSizes.get(STREAM_C), true);
updateStream(STREAM_D, streamSizes.get(STREAM_D), true);
streamC.close();
assertEquals(calculateStreamSizeSum(streamSizes, Arrays.asList(STREAM_A, STREAM_B, STREAM_D)),
streamableBytesForTree(stream0));
assertEquals(calculateStreamSizeSum(streamSizes, Arrays.asList(STREAM_A, STREAM_D)),
streamableBytesForTree(streamA));
assertEquals(calculateStreamSizeSum(streamSizes, Collections.singletonList(STREAM_B)),
streamableBytesForTree(streamB));
assertEquals(0, streamableBytesForTree(streamC));
assertEquals(calculateStreamSizeSum(streamSizes, Collections.singletonList(STREAM_D)),
streamableBytesForTree(streamD));
}
private Http2Stream stream(int streamId) {
return connection.stream(streamId);
}
private void updateStream(final int streamId, final int streamableBytes, final boolean hasFrame) {
final Http2Stream stream = stream(streamId);
distributor.updateStreamableBytes(new StreamByteDistributor.StreamState() {
@Override
public Http2Stream stream() {
return stream;
}
@Override
public int streamableBytes() {
return streamableBytes;
}
@Override
public boolean hasFrame() {
return hasFrame;
}
});
}
private void setPriority(int streamId, int parent, int weight, boolean exclusive) throws Http2Exception {
stream(streamId).setPriority(parent, (short) weight, exclusive);
}
private long streamableBytesForTree(Http2Stream stream) {
return distributor.unallocatedStreamableBytesForTree(stream);
}
private boolean write(int numBytes) {
return distributor.distribute(numBytes, writer);
}
private void verifyWrite(int streamId, int numBytes) {
verify(writer).write(same(stream(streamId)), eq(numBytes));
}
private void verifyWrite(VerificationMode mode, int streamId, int numBytes) {
verify(writer, mode).write(same(stream(streamId)), eq(numBytes));
}
private void verifyWriteWithDelta(int streamId, int numBytes, int delta) {
verify(writer).write(same(stream(streamId)), (int) AdditionalMatchers.eq(numBytes, delta));
}
private static long calculateStreamSizeSum(IntObjectMap<Integer> streamSizes, List<Integer> streamIds) {
long sum = 0;
for (Integer streamId : streamIds) {
Integer streamSize = streamSizes.get(streamId);
if (streamSize != null) {
sum += streamSize;
}
}
return sum;
}
}
|
a9a43a5a70a53d23702e1aad84eeb6477ada6049
|
[
"Java"
] | 8 |
Java
|
prange/netty
|
fdd15502196a97737ee505bbb40997f95a12ff9d
|
76d7d96ac55430270d26793ed75f3f2117269fb3
|
refs/heads/master
|
<repo_name>thewinterwind/symfony4-practice<file_sep>/src/Validators/DateValidator.php
<?php
namespace App\Validators;
use DateTime;
class DateValidator {
public function isValidDate(string $date)
{
$format = 'Y-m-d';
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) === $date;
}
}
<file_sep>/src/Entity/Player.php
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\PlayerRepository")
* @ORM\Table(name="player")
*/
class Player
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $first_name;
/**
* @ORM\Column(type="string", length=255)
*/
private $last_name;
/**
* @ORM\Column(type="date", nullable=true)
*/
private $dob;
/**
* @ORM\Column(type="datetime")
*/
private $created_at;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
private $updated_at;
public function getId(): ?int
{
return $this->id;
}
public function getFirstName(): ?string
{
return $this->first_name;
}
public function setFirstName(string $first_name): self
{
$this->first_name = $first_name;
return $this;
}
public function getLastName(): ?string
{
return $this->last_name;
}
public function setLastName(string $last_name): self
{
$this->last_name = $last_name;
return $this;
}
public function getDob(): ?string
{
return $this->dob->format('Y-m-d');
}
public function setDob(?\DateTimeInterface $dob): self
{
$this->dob = $dob;
return $this;
}
public function getCreatedAt(): ?string
{
return $this->created_at->format('Y-m-d H:i:s');
}
public function setCreatedAt(\DateTimeInterface $created_at): self
{
$this->created_at = $created_at;
return $this;
}
public function getUpdatedAt(): ?string
{
return $this->created_at->format('Y-m-d H:i:s');
}
public function setUpdatedAt(?\DateTimeInterface $updated_at): self
{
$this->updated_at = $updated_at;
return $this;
}
}
<file_sep>/src/Entity/User.php
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\UserRepository")
* @ORM\Table(name="users")
*/
class User
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="integer")
*/
private $order_limit;
/**
* @ORM\Column(type="integer")
*/
private $delivery_limit;
/**
* @ORM\Column(type="integer")
*/
private $invoice_limit;
/**
* @ORM\Column(type="datetime")
*/
private $created_at;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
private $updated_at;
public function getId(): ?int
{
return $this->id;
}
public function getOrderLimit(): ?string
{
return $this->order_limit;
}
public function getDeliveryLimit(): ?string
{
return $this->delivery_limit;
}
public function getInvoiceLimit(): ?string
{
return $this->invoice_limit;
}
public function getCreatedAt(): ?string
{
return $this->created_at->format('Y-m-d H:i:s');
}
public function setCreatedAt(\DateTimeInterface $created_at): self
{
$this->created_at = $created_at;
return $this;
}
}
<file_sep>/src/Entity/Order.php
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\OrderRepository")
* @ORM\Table(name="orders")
*/
class Order
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="integer")
*/
private $amount;
/**
* @ORM\Column(type="integer")
*/
private $product_id;
/**
* @ORM\Column(type="integer")
*/
private $user_id;
/**
* @ORM\Column(type="integer")
*/
private $order_limit;
/**
* @ORM\Column(type="datetime")
*/
private $created_at;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
private $updated_at;
public function getId(): ?int
{
return $this->id;
}
public function setUserId(int $userId): self
{
$this->user_id = $userId;
return $this;
}
public function setProductId(int $productId): self
{
$this->product_id = $productId;
return $this;
}
public function getAmount(): ?string
{
return $this->amount;
}
public function getOrderLimit(): ?string
{
return $this->order_limit;
}
public function setAmount(int $amount): self
{
$this->amount = $amount;
return $this;
}
public function getCreatedAt(): ?string
{
return $this->created_at->format('Y-m-d H:i:s');
}
public function setCreatedAt(\DateTimeInterface $created_at): self
{
$this->created_at = $created_at;
return $this;
}
}
<file_sep>/src/Controller/PlayerController.php
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Doctrine\ORM\Query;
use App\Entity\Player;
use App\Validators\DateValidator;
use DateTime;
class PlayerController extends AbstractController
{
/**
* @Route("/api/players", methods={"GET"})
*/
public function index()
{
$query = $this->getDoctrine()
->getRepository(Player::class)
->createQueryBuilder('c')
->getQuery();
$players = $query->getResult(Query::HYDRATE_ARRAY);
return $this->json([
'result' => 'success',
'data' => $players,
]);
}
/**
* @Route("/api/players/{id}", methods={"GET"})
*/
public function show(int $id)
{
if ($id < 1) {
return $this->json([
'result' => 'error',
'message' => 'id_must_be_positive',
], 400);
}
$player = $this->getDoctrine()
->getRepository(Player::class)
->find($id);
$orderLimit = $user->getOrderLimit();
dd($orderLimit);
if (!$player) {
return $this->json([
'result' => 'error',
'message' => 'entity_not_found',
], 404);
}
$player = [
'id' => $player->getId(),
'first_name' => $player->getFirstName(),
'last_name' => $player->getLastName(),
'dob' => $player->getDob(),
'created_at' => $player->getCreatedAt(),
'updated_at' => $player->getUpdatedAt(),
];
return $this->json([
'result' => 'success',
'data' => $player,
]);
}
/**
* @Route("/api/players", methods={"POST"})
*/
public function create(Request $request)
{
if (!$request->query->get('first_name') || !$request->query->get('last_name')) {
return $this->json([
'result' => 'error',
'message' => 'must_provide_first_name_and_last_name',
], 400);
}
$validator = new DateValidator;
if (!$validator->isValidDate($request->query->get('dob'))) {
return $this->json([
'result' => 'error',
'message' => 'dob_not_a_valid_date',
], 400);
}
$entityManager = $this->getDoctrine()->getManager();
$player = new Player;
$player->setFirstName(
$request->query->get('first_name')
);
$player->setLastName(
$request->query->get('last_name')
);
$dob = DateTime::createFromFormat('Y-m-d', $request->query->get('dob'));
$player->setDob($dob);
$player->setCreatedAt($datetime = new DateTime);
$player->setCreatedAt($datetime);
$entityManager->persist($player);
$entityManager->flush();
return $this->json([
'result' => 'success',
'data' => ['id' => $player->getId()],
]);
}
/**
* @Route("/api/players/{id}", methods={"PUT"})
*/
public function update($id, Request $request)
{
if ($id < 1) {
return $this->json([
'result' => 'error',
'message' => 'id_must_be_positive',
], 400);
}
$entityManager = $this->getDoctrine()->getManager();
$player = $entityManager->getRepository(Player::class)->find($id);
if (!$player) {
return $this->json([
'result' => 'error',
'message' => 'entity_not_found',
], 404);
}
$validator = new DateValidator;
if (!$validator->isValidDate($request->query->get('dob'))) {
return $this->json([
'result' => 'error',
'message' => 'dob_not_a_valid_date',
], 400);
}
$dob = DateTime::createFromFormat('Y-m-d', $request->query->get('dob'));
$player->setFirstName(
$request->query->get('first_name')
);
$player->setLastName(
$request->query->get('last_name')
);
$player->setDob($dob);
$entityManager->flush();
return $this->json([
'result' => 'success',
'data' => ['id' => $player->getId()],
]);
}
/**
* @Route("/api/players/{id}", methods={"DELETE"})
*/
public function delete($id)
{
if ($id < 1) {
return $this->json([
'result' => 'error',
'message' => 'id_must_be_positive',
], 400);
}
$entityManager = $this->getDoctrine()->getManager();
$player = $entityManager->getRepository(Player::class)->find($id);
if (!$player) {
return $this->json([
'result' => 'error',
'message' => 'entity_not_found',
], 404);
}
$playerId = $player->getId();
$entityManager->remove($player);
$entityManager->flush();
return $this->json([
'result' => 'success',
'data' => ['deleted_id' => $playerId],
]);
}
}
<file_sep>/src/Controller/OrderController.php
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Doctrine\ORM\Query;
use App\Entity\Order;
use App\Entity\User;
use DateTime;
class OrderController extends AbstractController
{
/**
* @Route("/", methods={"GET"})
*/
public function index()
{
return $this->render('orders/index.html.twig', ['error' => false]);
}
/**
* @Route("/", methods={"POST"})
*/
public function store(Request $request)
{
if (!$request->request->get('product_id')) {
return $this->json([
'result' => 'error',
'message' => 'product_id_not_provided',
], 400);
}
$feature = $request->request->get('feature');
$userId = $request->request->get('user_id');
$function = 'get' . $feature . 'Limit';
$date = new DateTime();
$date->modify('-24 hour');
$user = $this
->getDoctrine()
->getRepository(User::class)
->find($userId);
$orderLimit = (int) $user->$function();
$count = (int) $this->getDoctrine()
->getRepository(Order::class)
->createQueryBuilder('u')
->andWhere('u.user_id = :user_id')
->setParameter('user_id', $userId)
->andWhere('u.created_at > :date')
->setParameter(':date', $date)
->select('count(u.id)')
->getQuery()
->getSingleScalarResult();
if ($count >= $orderLimit) {
return $this->render('orders/index.html.twig', [
'error' => true,
'message' => 'This user has a ' . $feature . ' limit of ' . $orderLimit . ' in the last 24 hours',
]);
}
$entityManager = $this->getDoctrine()->getManager();
$order = new Order;
$order->setUserId($userId);
$order->setProductId(
$request->request->get('feature')
);
$order->setAmount(1);
$order->setCreatedAt(new DateTime);
$entityManager->persist($order);
$entityManager->flush();
return $this->render('orders/index.html.twig', [
'error' => false,
'message' => 'Order Created',
]);
}
}
<file_sep>/config/routes.php
<?php
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
use App\Controller\PlayerController;
$routes = new RouteCollection();
return $routes;
|
f124b01a36a56d38f7777507e9dc8ff29229dfa4
|
[
"PHP"
] | 7 |
PHP
|
thewinterwind/symfony4-practice
|
c560ee508c7e0e5e79791858fbdd95889b8bcae2
|
32e52459f22b557dcb893640895d23dd8d3d4d88
|
refs/heads/master
|
<file_sep>package zhangwei.zxingdemo;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.xys.libzxing.zxing.activity.CaptureActivity;
import com.xys.libzxing.zxing.encoding.EncodingUtils;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity {
@Bind(R.id.btn_qrcode)
Button mBtnQrcode;
@Bind(R.id.tv_result)
TextView mTvResult;
@Bind(R.id.et_content)
EditText mEtContent;
@Bind(R.id.btn_get_image)
Button mBtnGetImage;
@Bind(R.id.iv_image)
ImageView mIvImage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
@OnClick({R.id.btn_qrcode, R.id.btn_get_image})
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_qrcode://二维码扫描
Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
startActivityForResult(intent,0);
break;
case R.id.btn_get_image://获取图片
Bitmap bitmap = EncodingUtils.createQRCode(mEtContent.getText().toString(),500,500, BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher));
mIvImage.setImageBitmap(bitmap);
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK && requestCode == 0){
String result = data.getStringExtra("result");
Log.i("zhangwei", "result2223: " + result);
mTvResult.setText(result);
}
}
}
|
7525ee943b2c494e315603c040351c4afc3bc431
|
[
"Java"
] | 1 |
Java
|
vifreedom/testZxing
|
930c3dac74cd59fbcac692985633be2ac01bc099
|
1a939b48c4d1f7cfaea22e510c42eec8944ec0fc
|
refs/heads/master
|
<repo_name>crzhi/www<file_sep>/bing.php
<?php
$idx = $_POST['idx'];
if(!isset($idx)) {
header("Location: /");
}
$url = "https://cn.bing.com/HPImageArchive.aspx?format=js&idx=$idx&n=1&mkt=zh-CN";
$data = json_decode(file_get_contents($url), true);
$res = $data['images'][0];
$bing = [
'url' => 'https://cn.bing.com' . $res['url'],
'disc' => $res['copyright'],
'date' => substr($res['enddate'], 0, 4) . '-' . substr($res['enddate'], 4, 2) . '-' . substr($res['enddate'], 6, 2),
];
echo json_encode($bing);<file_sep>/static/js/app.js
//加载完成
window.onload = function() {
change(0)
}
//手机列表
document.getElementById('button').onclick = function(){
document.getElementById('menu').setAttribute('style', 'display: block')
document.getElementById('content').onclick = function(){
document.getElementById('menu').setAttribute('style', 'display: none')
}
}
//切换壁纸
var set = document.getElementsByClassName('set_list');
set[0].onclick = function() {
if(!this.classList.contains('disabled')) {
var idx = this.getAttribute('data-idx')
change(idx)
}
}
set[1].onclick = function() {
if(!this.classList.contains('disabled')) {
var idx = this.getAttribute('data-idx')
change(idx)
}
}
//切换
function change (idx) {
document.getElementsByClassName('loader')[0].setAttribute('style', 'display: block')
set[0].classList.remove('disabled')
set[1].classList.remove('disabled')
var url = '/bing.php'
var arr = {idx: idx}
Ajax('post', url, arr, function(data){
var data = JSON.parse(data)
document.getElementsByClassName('date')[0].innerHTML = data.date
document.getElementsByClassName('disc')[0].innerHTML = data.disc
document.getElementsByClassName('fixedbg')[0].setAttribute('style', 'background-image: url(' + data.url + ')')
document.getElementsByClassName('loader')[0].setAttribute('style', 'display: none')
});
if(idx >= 0 && idx <= 7) {
set[0].setAttribute('data-idx', Number(idx) + 1)
set[1].setAttribute('data-idx', Number(idx) - 1)
if(idx == 7) {
set[0].classList.add('disabled')
}
if(idx == 0) {
set[1].classList.add('disabled')
}
}
}
//ajax
function Ajax(type, url, data, success, error){
var xhr = null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject('Microsoft.XMLHTTP')
}
var type = type.toUpperCase();
var random = Math.random();
if(typeof data == 'object'){
var str = '';
for(var key in data){
str += key+'='+data[key]+'&';
}
data = str.replace(/&$/, '');
}
if(type == 'GET'){
if(data){
xhr.open('GET', url + '?' + data, true);
} else {
xhr.open('GET', url + '?t=' + random, true);
}
xhr.send();
} else if(type == 'POST'){
xhr.open('POST', url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(data);
}
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200){
success(xhr.responseText);
} else {
if(error){
error(xhr.status);
}
}
}
}
}<file_sep>/README.md
# www
网站首页 https://phpgeeker.com
|
4c888f9347cdb81705773314c80616df0cc33a65
|
[
"JavaScript",
"Markdown",
"PHP"
] | 3 |
PHP
|
crzhi/www
|
b9ed607f77aaa782a2e0f30fd3eb09dc55879b8e
|
7bcb0d3430ec3f3ccfafe0e98c7128a161159c20
|
refs/heads/master
|
<file_sep>#Read the data into R
data<-read.table("household_power_consumption.txt",sep=";",header=TRUE,colClasses=c(rep("character",2),rep("numeric",7)),na="?")
#Convierte Date en formato fecha
data$Date<-as.Date(data$Date,"%d/%m/%Y")
#Select only the dates that we're gonna plot
refineddata<-subset(data,Date=="2007-02-02"|Date=="2007-02-01")
#Creating the plot2.png file
png(file="plot2.png",width=480,height=480,units="px",bg="white")
with(refineddata,plot(Global_active_power,type="l",ylab="Global Active Power (kilowatts)",xaxt="n",xlab=""))
axis(1,at=c(0,1500,nrow(refineddata)),labels=c("Thu","Fri","Sat"))
#Closing the .png file
dev.off()
<file_sep>#Read the data into R
data<-read.table("household_power_consumption.txt",sep=";",header=TRUE,colClasses=c(rep("character",2),rep("numeric",7)),na="?")
#Convierte Date en formato fecha
data$Date<-as.Date(data$Date,"%d/%m/%Y")
#Select only the dates that we're gonna plot
refineddata<-subset(data,Date=="2007-02-02"|Date=="2007-02-01")
#Creating the plot3.png file
png(file="plot3.png",width=480,height=480,units="px",bg="white")
with(refineddata,plot(Sub_metering_1,type="l",ylab="Energy sub metering",xaxt="n",xlab=""))
lines(refineddata$Sub_metering_2,col="red")
lines(refineddata$Sub_metering_3,col="blue")
axis(1,at=c(0,1500,nrow(refineddata)),labels=c("Thu","Fri","Sat"))
legend("topright",lty=1,lwd=1,col=c("black","red","blue"),legend=c("Sub_metering_1","Sub_metering_2","Sub_metering_3"))
#closing the .png file
dev.off()
<file_sep>#Read the data into R
data<-read.table("household_power_consumption.txt",sep=";",header=TRUE,colClasses=c(rep("character",2),rep("numeric",7)),na="?")
#Convierte Date en formato fecha
data$Date<-as.Date(data$Date,"%d/%m/%Y")
#Select only the dates that we're gonna plot
refineddata<-subset(data,Date=="2007-02-02"|Date=="2007-02-01")
#Creating the plot1.png file
png(file="plot1.png",width=480, height=480,units="px",bg="white")
hist(refineddata$Global_active_power,col="red",xlab="Global Active Power (kilowatts)",main="Global Active Power")
#closing the .png file
dev.off()
<file_sep># ExData_PA1
Exploartory Data Plotting Assignment 1
<file_sep>#Read the data into R
data<-read.table("household_power_consumption.txt",sep=";",header=TRUE,colClasses=c(rep("character",2),rep("numeric",7)),na="?")
#Convierte Date en formato fecha
data$Date<-as.Date(data$Date,"%d/%m/%Y")
#Select only the dates that we're gonna plot
refineddata<-subset(data,Date=="2007-02-02"|Date=="2007-02-01")
#Creating the plot4.png file
##Creating the file and setting the format of the graph
png(file="plot4.png",width=480,height=480,units="px",bg="white")
par(mfrow=c(2,2),mar=c(5,4,2,1))
## Creating plot 4.1 (plot2 modifiying ylab)
plot(refineddata$Global_active_power,type="l",ylab="Global Active Power",xaxt="n",xlab="")
axis(1,at=c(0,1500,nrow(refineddata)),labels=c("Thu","Fri","Sat"))
## Creating plot 4.2
plot(refineddata$Voltage,type="l",ylab="Voltage",xlab="datetime",xaxt="n")
axis(1,at=c(0,1500,nrow(refineddata)),labels=c("Thu","Fri","Sat"))
## Creating plot 4.3 (plot3 modifiying bty="n")
plot(refineddata$Sub_metering_1,type="l",ylab="Energy sub metering",xaxt="n", xlab="")
lines(refineddata$Sub_metering_2,col="red")
lines(refineddata$Sub_metering_3,col="blue")
axis(1,at=c(0,1500,nrow(refineddata)),labels=c("Thu","Fri","Sat"))
legend("topright",bty="n",lty=1,lwd=1,col=c("black","red","blue"),legend=c("Sub_metering_1","Sub_metering_2","Sub_metering_3"))
##Creating plot 4.4
plot(refineddata$Global_reactive_power,ylab="Global_reactive_power",type="l",xlab="datetime",xaxt="n")
axis(1,at=c(0,1500,nrow(refineddata)),labels=c("Thu","Fri","Sat"))
##Closing the .png file
dev.off()
|
e5e7b46cb9bcf6954614d52bba8e1408b175c000
|
[
"Markdown",
"R"
] | 5 |
R
|
MariaMontesdeOca/ExData_PA1
|
1be0a18c662c6daa7aac88bba4d97ff45689bba6
|
596d6198ea59f984ff076fdb759617d080661f98
|
refs/heads/master
|
<file_sep>import { Validators } from '@angular/forms';
export const baseForm = {
code: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(25)]],
libelleCourt: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(50)]],
// libelleLong: ['', [Validators.max(250)]],
// description: [],
// mutualisable: [],
};
<file_sep>import { Component, Input, OnInit } from '@angular/core';
import { FormGroup, Validators } from '@angular/forms';
// fichier a part pour les regex
export const alphaNumeric = /^[a-zA-Z0-9\-]*$/;
@Component({
selector: 'app-input',
template:
`
<style>
input.auto-uppercase {
text-transform: uppercase;
}
</style>
<mat-form-field class="example-full-width" [formGroup]="parent">
<input
matInput
type="text"
[placeholder]="label"
[formControlName]="name"
[name]="name"
[class.auto-uppercase]="autoUppercase"
>
<!-- pour l'internationalisation passer les clés, voir pour le paramétrage, si c'est trop compliqué découpler les inputs par type -->
<mat-hint>Ceci est un indice pour le champ</mat-hint>
<mat-error *ngIf="parent.controls[name].errors && parent.controls[name].errors.required">Message required</mat-error>
<mat-error *ngIf="parent.controls[name].errors && parent.controls[name].errors.pattern">Error pattern</mat-error>
<mat-error *ngIf="parent.controls[name].errors &&
(parent.controls[name].errors.minlength
|| parent.controls[name].errors.maxlength)">
Error length
</mat-error>
</mat-form-field>
`,
})
export class CustomInputComponent {
@Input() parent: FormGroup;
@Input() name: string;
@Input() label: string;
@Input() autoUppercase = false;
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { alphaNumeric} from '../core/form/custom-input/custom-input.component';
import { baseForm } from '../core/form/form.model';
@Component({
selector: 'app-oo-form',
template: `
<form [formGroup]="form">
<app-input [parent]="form" name="code" label="Code" type="alphaNumeric" [autoUppercase]="true"></app-input>
<app-input [parent]="form" name="libelleCourt" label="Libellé Court"></app-input>
<button mat-flat-button [disabled]="!form.valid">Click me!</button>
</form>
<br>
`,
})
export class OoFormComponent implements OnInit {
// possibilite d'override le template de formulaire par défaut
form = this.fb.group({
...baseForm,
code: ['', [Validators.pattern(alphaNumeric), Validators.required]]
});
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.form.patchValue({
code: 'ue-anglais-110'
});
}
}
|
0fc6e771902506b7404881f46dc13338019ebb3f
|
[
"TypeScript"
] | 3 |
TypeScript
|
tollr/form-component
|
69c3cccdc9d2874931381db62a6ac961022687a5
|
b4fa180f14fda01fa660f533da68b06491b99616
|
refs/heads/main
|
<file_sep># Android
안드로이드 공부를 위한 repository. 각 기능들을 구현하기위해 개별로 프로젝트를 생성.
## Blutooth
블루투스 통신
- 검색
- 연결
- 데이터 수신
## Beacon
비콘 검색
- 주위의 비콘 검색
## Rotate_animation
이미지 회전 애니메이션
- 뷰 회전
<file_sep>package com.example.rotate_animation
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.view.animation.RotateAnimation
import android.widget.ImageView
//https://itpangpang.xyz/271
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val iv = findViewById<ImageView>(R.id.iv)
val animation: Animation = AnimationUtils.loadAnimation(this, R.anim.rotate)
// iv.animation = animation
animate(iv, 0.toFloat(), 230.toFloat())
animate(iv, 230.toFloat(), 100.toFloat())
}
private fun animate(view: View, fromDegree: Float, toDegree: Float) {
val animation: RotateAnimation = RotateAnimation(fromDegree, toDegree,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f)
animation.duration = 200
animation.fillAfter = true
view.startAnimation(animation);
}
}<file_sep>package com.example.beacon
import android.os.Bundle
import android.os.RemoteException
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.pedro.library.AutoPermissions.Companion.loadAllPermissions
import com.pedro.library.AutoPermissionsListener
import org.altbeacon.beacon.*
// https://github.com/int128/android-ble-button/blob/master/app/src/main/kotlin/org/hidetake/blebutton/ScanDevicesActivity.kt
// UUID 74278BDA-B644-4520-8F0C-720EAF059935
class MainActivity : AppCompatActivity(), BeaconConsumer, AutoPermissionsListener {
private var beaconManager: BeaconManager? = null
var beaconUUID = "AAC54CD6-EAAD-48D2-B060-AAAAAAAAE" // beacon -uuid
private val TAG = "####"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
loadAllPermissions(this, 101) // AutoPermissions
beaconManager = BeaconManager.getInstanceForApplication(this)
beaconManager!!.beaconParsers.add(BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"))
beaconManager!!.bind(this)
}
override fun onBeaconServiceConnect() {
beaconManager!!.removeAllMonitorNotifiers()
beaconManager!!.addRangeNotifier(RangeNotifier { beacons, region ->
if (beacons.isNotEmpty()) {
Log.i(TAG, "The first beacon I see is about ${(beacons.iterator().next() as Beacon).bluetoothAddress} ${(beacons.iterator().next() as Beacon).bluetoothName}" +
" ${(beacons.iterator().next() as Beacon).id1} ${(beacons.iterator().next() as Beacon).id2}" +
" ${(beacons.iterator().next() as Beacon).id3}" +
" ${(beacons.iterator().next() as Beacon).distance}" )
}
})
// beaconManager!!.addRangeNotifier(RangeNotifier{
// fun didRangeBeaconsInRegion(beacons: Collection<*>, region: Region?) {
//
// }
// })
beaconManager!!.addMonitorNotifier(object : MonitorNotifier {
override fun didEnterRegion(region: Region?) {
Log.i(TAG, "I just saw an beacon for the first time!")
Toast.makeText(this@MainActivity, "didEnterRegion - 비콘 연결됨", Toast.LENGTH_SHORT).show()
}
override fun didExitRegion(region: Region?) {
Log.i(TAG, "I no longer see an beacon")
Toast.makeText(this@MainActivity, "didExitRegion - 비콘 연결 끊김", Toast.LENGTH_SHORT).show()
}
override fun didDetermineStateForRegion(state: Int, region: Region?) {
Log.i(TAG, "I have just switched from seeing/not seeing beacons: $state")
}
})
try {
beaconManager!!.startMonitoringBeaconsInRegion(Region("beacon", null, null, null))
} catch (e: RemoteException) {
}
try {
beaconManager!!.startRangingBeaconsInRegion(Region("beacon", null, null, null))
} catch (e: RemoteException) {
}
} // onBeaconServiceConnect()..
override fun onDestroy() {
super.onDestroy()
beaconManager!!.unbind(this)
}
override fun onPointerCaptureChanged(hasCapture: Boolean) {}
override fun onDenied(requestCode: Int, permissions: Array<String>) {}
override fun onGranted(requestCode: Int, permissions: Array<String>) {}
}
<file_sep>package com.example.bluetooth
//import jdk.nashorn.internal.objects.ArrayBufferView.buffer
//import sun.security.krb5.Confounder.bytes
import android.app.Activity
import android.app.NotificationChannel
import android.app.NotificationManager
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothSocket
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.util.*
// http://jinyongjeong.github.io/2018/09/27/bluetoothpairing/
class MainActivity : AppCompatActivity() {
private val DEVICE_NAME = "HC-06"
private var DEVICE: BluetoothDevice? = null
private var status = 0
private var mBluetoothAdapter: BluetoothAdapter? = null
private val stateFilter = IntentFilter()
private var tv_status: TextView? = null
private var pairedDevices: Set<BluetoothDevice>? = null
private val REQUEST_ENABLE_BT = 1000
private val mBluetoothStateReceiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent) {
val action = intent.action //입력된 action
Log.d("#main_Bluetooth action", action!!)
val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
var name: String? = null
if (device != null) {
name = device.name //broadcast를 보낸 기기의 이름을 가져온다.
}
when (action) {
BluetoothAdapter.ACTION_STATE_CHANGED -> {
val state =
intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)
when (state) {
BluetoothAdapter.STATE_OFF -> {
}
BluetoothAdapter.STATE_TURNING_OFF -> {
}
BluetoothAdapter.STATE_ON -> {
}
BluetoothAdapter.STATE_TURNING_ON -> {
}
}
}
BluetoothDevice.ACTION_ACL_CONNECTED -> {
}
BluetoothDevice.ACTION_BOND_STATE_CHANGED -> {
}
BluetoothDevice.ACTION_ACL_DISCONNECTED -> {
}
BluetoothAdapter.ACTION_DISCOVERY_STARTED -> {
}
BluetoothDevice.ACTION_FOUND -> {
val device_name = device!!.name
val device_Address = device.address
if (device_name == DEVICE_NAME) {
DEVICE = device
}
Log.d("#main_device", "$device_name $device_Address")
}
BluetoothAdapter.ACTION_DISCOVERY_FINISHED -> {
if (DEVICE != null) {
DEVICE!!.createBond()
set_status(4)
}
Log.d("#main_Bluetooth", "Call Discovery finished")
}
BluetoothDevice.ACTION_PAIRING_REQUEST -> {
}
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.d("#main", "on create")
init()
registerReceiver(mBluetoothStateReceiver, stateFilter)
// mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter() //블루투스 adapter 획득
}
private fun init(){
// init filter
stateFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED) //BluetoothAdapter.ACTION_STATE_CHANGED : 블루투스 상태변화 액션
stateFilter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)
stateFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED) //연결 확인
stateFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED) //연결 끊김 확인
stateFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
stateFilter.addAction(BluetoothDevice.ACTION_FOUND) //기기 검색됨
stateFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED) //기기 검색 시작
stateFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED) //기기 검색 종료
stateFilter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST)
// init bt
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
// init tv, btn
tv_status = findViewById(R.id.tv_bt_status)
if (mBluetoothAdapter == null) set_status(0)
if (mBluetoothAdapter?.isEnabled == false) set_status(1)
else set_status(2)
pairedDevices = mBluetoothAdapter?.bondedDevices
pairedDevices?.forEach { device ->
val deviceName = device.name
val deviceHardwareAddress = device.address // MAC address
if (deviceName == DEVICE_NAME) {
set_status(4)
DEVICE = device
}
}
// val BluetoothDevice
// pairedDevices.contains()
findViewById<Button>(R.id.btn_on_off).setOnClickListener{
if (status == 1){
val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
}
}
findViewById<Button>(R.id.btn_bt_scan).setOnClickListener{
if (status == 2) {
mBluetoothAdapter!!.startDiscovery() //블루투스 기기 검색 시작
}
}
findViewById<Button>(R.id.btn_rcv).setOnClickListener{
// start_rcv()
val intent: Intent = Intent(this, ReceiveActivity::class.java)
intent.putExtra("device", DEVICE)
startActivity(intent)
}
createNotificationChannel()
}
// https://developer.android.com/guide/topics/connectivity/bluetooth?hl=ko#ConnectDevices
private var mBtSoket: BluetoothSocket? = null
private var mInput: InputStream? = null
private var mOutput: OutputStream? = null
private var mmBuffer: ByteArray = ByteArray(555)
private fun start_rcv(){
Log.d("#main_rcv", "start")
val uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb")
try{
mBtSoket = DEVICE!!.createRfcommSocketToServiceRecord(uuid)
mBtSoket!!.connect()
Log.d("#main_rcv", "socket connect")
mInput = mBtSoket!!.inputStream
mOutput = mBtSoket!!.outputStream
}catch (e: Exception){
e.printStackTrace()
}
Thread(Runnable {
var numBytes: Int
var str: String = ""
while (true) {
try {
numBytes = mInput!!.read(mmBuffer, 0, 512)
val readMessage: String = String(mmBuffer, 0, numBytes)
str += readMessage
if (str[str.lastIndex] == '^') {
str = str.substring(0, str.lastIndex)
Log.d("#main_rcv", str)
if (str.subSequence(0, 6).toString().trim().toInt() % 10 == 0) {
NotificationSomethings(str.substring(7,str.lastIndex))
}
str = ""
}
// Log.d("#main_rcv", "$numBytes $readMessage")
} catch (e: IOException) {
Log.d("#main_rcv", "Input stream was disconnected", e)
break
}
}
}).start()
}
// https://developer.android.com/training/notify-user/build-notification?hl=ko
private val CHANNEL_ID = "cho"
private fun NotificationSomethings(str: String) {
var builder = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_menu_search)
.setContentTitle("test")
.setContentText(str)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
with(NotificationManagerCompat.from(this)) {
// notificationId is a unique int for each notification that you must define
notify(10, builder.build())
}
}
private fun createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = getString(R.string.channel_name)
val descriptionText = getString(R.string.channel_description)
val importance = NotificationManager.IMPORTANCE_HIGH
val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
description = descriptionText
}
// Register the channel with the system
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}
override fun onDestroy() {
super.onDestroy()
unregisterReceiver(mBluetoothStateReceiver);
try{
mBtSoket!!.close()
}catch (e: Exception){
e.printStackTrace()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when(requestCode){
REQUEST_ENABLE_BT -> {
if (resultCode == Activity.RESULT_OK) set_status(2)
}
}
}
private fun set_status(stat: Int){
status = stat
when(stat){
0 -> tv_status!!.text = "이 기기는 블루투스를 지원하지 않습니다."
1 -> tv_status!!.text = "블루투스 OFF"
2 -> tv_status!!.text = "블루투스 ON"
3 -> tv_status!!.text = "페어링 필요"
4 -> tv_status!!.text = "페어링 완료"
}
}
}
<file_sep>package com.example.bluetooth
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothSocket
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.activity_receive_list.*
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList
class ReceiveActivity : AppCompatActivity() {
private var DEVICE: BluetoothDevice? = null
private lateinit var recyclerView: RecyclerView
private lateinit var viewAdapter: RecyclerView.Adapter<*>
private lateinit var viewManager: RecyclerView.LayoutManager
private var ItemList = arrayListOf<Item>(
// Item(0.0, 1.0, 2.0, 3.0, 4.0)
)
private var mAdapter: RvAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_receive_list)
mAdapter = RvAdapter(this, ItemList)
rcv_list.adapter = mAdapter
val lm = LinearLayoutManager(this)
rcv_list.layoutManager = lm
rcv_list.setHasFixedSize(true)
DEVICE = intent.extras!!.getParcelable<BluetoothDevice>("device")
start_rcv()
}
// https://developer.android.com/guide/topics/connectivity/bluetooth?hl=ko#ConnectDevices
private var mBtSoket: BluetoothSocket? = null
private var mInput: InputStream? = null
private var mOutput: OutputStream? = null
private var mmBuffer: ByteArray = ByteArray(555)
private fun start_rcv(){
Log.d("#main_rcv", "start")
val uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb")
try{
mBtSoket = DEVICE!!.createRfcommSocketToServiceRecord(uuid)
Log.d("#main_rcv", "123")
mBtSoket!!.connect()
Log.d("#main_rcv", "socket connect")
mInput = mBtSoket!!.inputStream
mOutput = mBtSoket!!.outputStream
}catch (e: Exception){
e.printStackTrace()
}
Thread(Runnable {
var numBytes: Int
var str: String = ""
while (true) {
try {
numBytes = mInput!!.read(mmBuffer, 0, 512)
val readMessage: String = String(mmBuffer, 0, numBytes)
str += readMessage
if (str[str.lastIndex] == '^') {
Log.d("#main_rcv", str)
str = str.substring(0, str.lastIndex)
// val time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
val items = str.split("$")[1].split(",")
// 현재시간을 msec 으로 구한다.
val now: Long = System.currentTimeMillis();
// 현재시간을 date 변수에 저장한다.
val date:Date = Date(now);
// 시간을 나타냇 포맷을 정한다 ( yyyy/MM/dd 같은 형태로 변형 가능 )
val sdfNow: SimpleDateFormat = SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
ItemList.add(Item(items[1].toDouble(), items[2].toDouble(), items[3].toDouble(), items[4].toDouble(), sdfNow.format(date)))
runOnUiThread{
mAdapter!!.notifyDataSetChanged()
rcv_list.scrollToPosition(ItemList.size - 1)
}
str = ""
}
} catch (e: IOException) {
Log.d("#main_rcv", "Input stream was disconnected", e)
break
}
}
}).start()
}
}
class Item(flow: Double, meter: Double, lat: Double, lon: Double, time: String){
var flow: Double = 0.0
var meter: Double = 0.0
var lat: Double = 0.0
var lon: Double = 0.0
var time: String = ""
init {
this.flow = flow
this.meter = meter
this.time = time
this.lat = lat
this.lon = lon
}
}
class RvAdapter(val context: Context, val itemList: ArrayList<Item>): RecyclerView.Adapter<RvAdapter.Holder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
val view = LayoutInflater.from(context).inflate(R.layout.rv_item, parent, false)
return Holder(view)
}
override fun getItemCount(): Int {
return itemList.size
}
override fun onBindViewHolder(holder: Holder, position: Int) {
holder?.bind(itemList[position], context)
}
inner class Holder(itemView: View?): RecyclerView.ViewHolder(itemView!!){
val time = itemView!!.findViewById<TextView>(R.id.time)
val flow = itemView!!.findViewById<TextView>(R.id.flow)
val meter = itemView!!.findViewById<TextView>(R.id.meter)
val lat = itemView!!.findViewById<TextView>(R.id.lat)
val lon = itemView!!.findViewById<TextView>(R.id.lon)
fun bind(item: Item, context: Context){
time.text = item.time
flow.text = "flow: ${item.flow.toString()}"
meter.text = "meter: ${item.meter.toString()}"
lat.text = "lat: ${item.lat.toString()}"
lon.text = "lon: ${item.lon.toString()}"
}
}
}
|
9e22fcbf2fab241a42388f89caebf5bed3d940bd
|
[
"Markdown",
"Kotlin"
] | 5 |
Markdown
|
choraeng/Android
|
5b11366ea2387d2c51d1ebb2b5863e8978251d4c
|
db9c9629c889eacaceb48568bdb6523c35773614
|
refs/heads/master
|
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.fatec.bean;
/**
*
* @author ProfAlexandre
*/
public class UsuarioPessoa {
private int idUsuPes;
private int idUsuario;
private int idPessoa;
private String Obs;
private Usuario usu;
private PessoaFisica pes;
public UsuarioPessoa(int idUsuPes, int idPessoa, int idUsuario, String Obs) {
this.idUsuPes = idUsuPes;
this.idUsuario = idUsuario;
this.idPessoa = idPessoa;
this.Obs = Obs;
}
public int getIdUsuPes() {
return idUsuPes;
}
public void setIdUsuPes(int idUsuPes) {
this.idUsuPes = idUsuPes;
}
public int getIdUsuario() {
return idUsuario;
}
public void setIdUsuario(int idUsuario) {
this.idUsuario = idUsuario;
}
public int getIdPessoa() {
return idPessoa;
}
public void setIdPessoa(int idPessoa) {
this.idPessoa = idPessoa;
}
public String getObs() {
return Obs;
}
public void setObs(String Obs) {
this.Obs = Obs;
}
public Usuario getUsu() {
return usu;
}
public void setUsu(Usuario usu) {
this.usu = usu;
}
public Pessoa getPes() {
return pes;
}
public void setPes(PessoaFisica pes) {
this.pes = pes;
}
}
<file_sep>deploy.ant.properties.file=C:\\Users\\maromba\\AppData\\Roaming\\NetBeans\\8.2\\config\\GlassFishEE6\\Properties\\gfv3719711796.properties
j2ee.platform.is.jsr109=true
j2ee.server.domain=C:/Users/maromba/GlassFish_Server/glassfish/domains/domain1
j2ee.server.home=C:/Users/maromba/GlassFish_Server/glassfish
j2ee.server.instance=[C:\\Users\\maromba\\GlassFish_Server\\glassfish;C:\\Users\\maromba\\GlassFish_Server\\glassfish\\domains\\domain1]deployer:gfv3ee6wc:localhost:4848
j2ee.server.middleware=C:/Users/maromba/GlassFish_Server
javac.debug=true
javadoc.preview=true
selected.browser=default
user.properties.file=C:\\Users\\maromba\\AppData\\Roaming\\NetBeans\\8.2\\build.properties
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.fatec.db;
import br.com.fatec.bean.PessoaFisica;
import br.com.fatec.util.ConexaoDB;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author ProfAlexandre
*/
public class PessoaDao {
private final Connection c;
public PessoaDao() throws SQLException, ClassNotFoundException{
this.c = new ConexaoDB().getConnection();
}
public List<PessoaFisica> listaTodos() throws SQLException{
// usus: array armazena a lista de registros
List<PessoaFisica> pess = new ArrayList<>();
String sql = "select * from pessoas";
PreparedStatement stmt = this.c.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
// criando o objeto Usuario
PessoaFisica pes = new PessoaFisica(
rs.getInt(1),
rs.getString(2),
rs.getString(3),
rs.getString(4),
rs.getString(5)
);
// adiciona o usu à lista de usus
pess.add(pes);
}
rs.close();
stmt.close();
return pess;
}
public PessoaFisica busca(PessoaFisica pes) throws SQLException{
String sql = "select * from pessoas WHERE id = ?";
PreparedStatement stmt = this.c.prepareStatement(sql);
// seta os valores
stmt.setInt(1,pes.getIdPessoa());
// executa
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
// criando o objeto Usuario
pes.setIdPessoa(rs.getInt(1));
pes.setNome(rs.getString(2));
pes.setCpf(rs.getString(3));
pes.setTipo(rs.getString(4));
pes.setEmail(rs.getString(5));
// adiciona o usu à lista de usus
}
return pes;
}
public PessoaFisica inserir(PessoaFisica pf) throws SQLException{
String sql = "insert into pessoas" + " (nome, cpf, tipo, email)" + " values (?,?,?,?)";
// prepared statement para inserção
PreparedStatement stmt = c.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
// seta os valores
stmt.setString(1,pf.getNome());
stmt.setString(2,pf.getCpf());
stmt.setString(3,pf.getTipo());
stmt.setString(4,pf.getEmail());
// executa
stmt.executeUpdate();
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()) {
int id = rs.getInt(1);
pf.setIdPessoa(id);
}
stmt.close();
return pf;
}
public PessoaFisica altera(PessoaFisica pf) throws SQLException{
String sql = "UPDATE pessoas SET nome = ?, cpf = ?, tipo = ?, email = ? WHERE id = ?";
// prepared statement para inserção
PreparedStatement stmt = c.prepareStatement(sql);
// seta os valores
stmt.setString(1,pf.getNome());
stmt.setString(2,pf.getCpf());
stmt.setString(3,pf.getTipo());
stmt.setString(4,pf.getEmail());
stmt.setInt(5,pf.getIdPessoa());
// executa
stmt.execute();
stmt.close();
return pf;
}
public PessoaFisica exclui(PessoaFisica pf) throws SQLException{
String sql = "delete from pessoas WHERE id = ?";
// prepared statement para inserção
PreparedStatement stmt = c.prepareStatement(sql);
// seta os valores
stmt.setInt(1,pf.getIdPessoa());
// executa
stmt.execute();
stmt.close();
c.close();
return pf;
}
}
<file_sep># ProjetoWeb4ADS
Projeto Web desenvolvido no 4ADS para manipulaçao de Usuario, Pessoas e Contatos
Com padrão MVC utilizando codigo JAVA e JSP com Banco de dados MYSQL
|
e43d906df4a23935f902bc3e4f4c61f8f7625074
|
[
"Markdown",
"Java",
"INI"
] | 4 |
Java
|
MILTONRUBRO/ProjetoWeb4ADS
|
d42b8a970b4d5f1c672d3f15ac34faddd903f19b
|
2c36a22005b0e6c438559c15b317d64ff5650a75
|
refs/heads/main
|
<repo_name>tmgorogers/Employee-Directory<file_sep>/employee-directory/src/components/Nav.js
import React from "react";
import SearchName from "./SearchName.js";
import "../styles/Nav.css";
const Nav = () => (
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<div id="navbarNav">
<div className="search-area" col-6>
<SearchName />
</div>
</div>
<button
className="navbar-toggler"
type="button"
data-bs-toggle="collapse"
data-bs-target="navbarSupportedContent"
aria-controls="navbarSupportedContent"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span class="navbar-toggler-icon"></span>
</button>
</nav>
);
export default Nav;
<file_sep>/README.md
# Employee-Directory
## Description
For this assignment, you'll create a employee directory with React. This assignment will require you to break up your application's UI into components, manage component state, and respond to user events.
## User Story
* As a user, I want to be able to view my entire employee directory at once so that I have quick access to their information.
## Business Context
An employee or manager would benefit greatly from being able to view non-sensitive data about other employees. It would be particularly helpful to be able to filter employees by name.
## Questions:
For any questions about my Employee Directory you can go to my Github page at the following link:
[Github Profile](https://github.com/tmgorogers/Employee-Directory)
[Github gh-pgs](https://tmgorogers.github.io/Employee-Directory/)
<file_sep>/employee-directory/src/components/Header.js
import React from "react";
import "../styles/Header.css";
const Header = () => (
<div className="header">
<h1>Employee Directory</h1>
<p>Filter or search by name to get a specfic results.</p>
</div>
)
export default Header;<file_sep>/employee-directory/src/components/Table.js
import React, {useContext} from "react";
import Body from "./Body";
import "../styles/Table.css";
import DataAreaContext from "../utils/DataAreaContext";
const Table = () => {
const context = useContext(DataAreaContext);
return (
<div className="datatable mt-5">
<table id="table" className="table table-striped table-hover table-condensed">
<thred>
<tr>
{context.developerState.headings.map(({ name, width })=>{
return(
<th className="col" key={name} style={{width}} onClick={() => context.handleSort(name)
}>
{name}
<span className="pointer"></span>
</th>
)
})}
</tr>
</thred>
<Body />
</table>
</div>
)
}
export default Table;
|
7a7d93c365b0b786602d473f96a920c25133a566
|
[
"JavaScript",
"Markdown"
] | 4 |
JavaScript
|
tmgorogers/Employee-Directory
|
661936f587db7ef6debd0ffe314723aed9cf509d
|
34d9f6a4a08c990b446bd609eb8f16e6c9733092
|
refs/heads/master
|
<file_sep>import threading
from robot.api.logger import BackgroundLogger
logger = BackgroundLogger()
def log_from_main(msg):
logger.info(msg)
def log_from_background(msg, thread=None):
t = threading.Thread(target=logger.info, args=(msg,))
if thread:
t.setName(thread)
t.start()
def log_background_messages(thread=None):
logger.log_background_messages(thread)
<file_sep># Copyright 2008-2014 Nokia Solutions and Networks
#
# 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.
"""Public logging API for test libraries.
This module provides a public API for writing messages to the log file
and the console. Test libraries can use this API like::
logger.info('My message')
instead of logging through the standard output like::
print '*INFO* My message'
In addition to a programmatic interface being cleaner to use, this API
has a benefit that the log messages have accurate timestamps.
If the logging methods are used when Robot Framework is not running,
the messages are redirected to the standard Python ``logging`` module
using logger named ``RobotFramework``. This feature was added in RF 2.8.7.
Log levels
----------
It is possible to log messages using levels ``TRACE``, ``DEBUG``, ``INFO``
and ``WARN`` either using the ``write`` method or, more commonly, with the
log level specific ``trace``, ``debug``, ``info`` and ``warn`` methods.
By default the trace and debug messages are not logged but that can be
changed with the ``--loglevel`` command line option. Warnings are
automatically written also to the `Test Execution Errors` section in
the log file and to the console.
Logging HTML
------------
All methods that are used for writing messages to the log file have an
optional ``html`` argument. If a message to be logged is supposed to be
shown as HTML, this argument should be set to ``True``.
Example
-------
::
from robot.api import logger
def my_keyword(arg):
logger.debug('Got argument %s.' % arg)
do_something()
logger.info('<i>This</i> is a boring example.', html=True)
Logging from background threads
-------------------------------
``BackgroundLogger`` is a custom logger that works mostly like the
standard ``robot.api.logger`` methods, but also stores messages logged by
background threads. It also provides a method the main thread can use to
forward the logged messages to Robot Framework's log. See below for more
information. ``BackgroundLogger`` is new in RF 2.8.7.
"""
from __future__ import with_statement
import logging
import threading
import time
try:
from collections import OrderedDict
except ImportError: # New in 2.7 but 2.4 compatible recipe would be available.
OrderedDict = dict
from robot.output import librarylogger
from robot.running.context import EXECUTION_CONTEXTS
def write(msg, level, html=False):
"""Writes the message to the log file using the given level.
Valid log levels are ``TRACE``, ``DEBUG``, ``INFO`` and ``WARN``.
Instead of using this method, it is generally better to use the level
specific methods such as ``info`` and ``debug``.
"""
if EXECUTION_CONTEXTS.current is not None:
librarylogger.write(msg, level, html)
else:
logger = logging.getLogger("RobotFramework")
level = {'TRACE': logging.DEBUG/2,
'DEBUG': logging.DEBUG,
'INFO': logging.INFO,
'WARN': logging.WARN}[level]
logger.log(level, msg)
def trace(msg, html=False):
"""Writes the message to the log file using the ``TRACE`` level."""
write(msg, 'TRACE', html)
def debug(msg, html=False):
"""Writes the message to the log file using the ``DEBUG`` level."""
write(msg, 'DEBUG', html)
def info(msg, html=False, also_console=False):
"""Writes the message to the log file using the ``INFO`` level.
If ``also_console`` argument is set to ``True``, the message is
written both to the log file and to the console.
"""
write(msg, 'INFO', html)
if also_console:
console(msg)
def warn(msg, html=False):
"""Writes the message to the log file using the ``WARN`` level."""
write(msg, 'WARN', html)
def console(msg, newline=True, stream='stdout'):
"""Writes the message to the console.
If the ``newline`` argument is ``True``, a newline character is
automatically added to the message.
By default the message is written to the standard output stream.
Using the standard error stream is possibly by giving the ``stream``
argument value ``'stderr'``. This is a new feature in RF 2.8.2.
"""
librarylogger.console(msg, newline, stream)
class BaseLogger(object):
"""Base class for custom loggers with same api as ``robot.api.logger``.
"""
def trace(self, msg, html=False):
self.write(msg, 'TRACE', html)
def debug(self, msg, html=False):
self.write(msg, 'DEBUG', html)
def info(self, msg, html=False, also_to_console=False):
self.write(msg, 'INFO', html)
if also_to_console:
self.console(msg)
def warn(self, msg, html=False):
self.write(msg, 'WARN', html)
def console(self, msg, newline=True, stream='stdout'):
console(msg, newline, stream)
def write(self, msg, level, html=False):
raise NotImplementedError
class BackgroundLogger(BaseLogger):
"""A logger which can be used from multiple threads. The messages from main
thread will go to robot logging api (or Python logging if Robot is not running).
Messages from other threads are saved to memory and can be later logged with
``log_background_messages()``. This will also remove the messages from memory.
Example::
from robotbackgroundlogger import BackgroundLogger
logger = BackgroundLogger()
After that logger can be used mostly like ``robot.api.logger`::
logger.debug('Hello, world!')
logger.info('<b>HTML</b> example', html=True)
"""
LOGGING_THREADS = librarylogger.LOGGING_THREADS
def __init__(self):
self.lock = threading.RLock()
self._messages = OrderedDict()
def write(self, msg, level, html=False):
with self.lock:
thread = threading.currentThread().getName()
if thread in self.LOGGING_THREADS:
write(msg, level, html)
else:
message = _BackgroundMessage(msg, level, html)
self._messages.setdefault(thread, []).append(message)
def log_background_messages(self, name=None):
"""Forwards messages logged on background to Robot Framework log.
By default forwards all messages logged by all threads, but can be
limited to a certain thread by passing thread's name as an argument.
This method must be called from the main thread.
Logged messages are removed from the message storage.
"""
thread = threading.currentThread().getName()
if thread not in self.LOGGING_THREADS:
raise RuntimeError("Logging background messages is only allowed from main thread. Current thread name: %s" % thread)
with self.lock:
if name:
self._log_messages_by_thread(name)
else:
self._log_all_messages()
def _log_messages_by_thread(self, name):
for message in self._messages.pop(name, []):
print message.format()
def _log_all_messages(self):
for thread in list(self._messages):
# Only way to get custom timestamps currently is with print
print "*HTML* <b>Messages by '%s'</b>" % thread
for message in self._messages.pop(thread):
print message.format()
def reset_background_messages(self, name=None):
with self.lock:
if name:
self._messages.pop(name)
else:
self._messages.clear()
class _BackgroundMessage(object):
def __init__(self, message, level='INFO', html=False):
self.message = message
self.level = level.upper()
self.html = html
self.timestamp = time.time() * 1000
def format(self):
# Can support HTML logging only with INFO level.
html = self.html and self.level == 'INFO'
level = self.level if not html else 'HTML'
return "*%s:%d* %s" % (level, round(self.timestamp), self.message)
|
3175188fbf23ebfd5358bd64dbffd3b92b4fd973
|
[
"Python"
] | 2 |
Python
|
dataxu/robotframework
|
71debe1d63534aafef89c82071d72196e0dc2c31
|
43cc7ca90e554371d61151a800f9831327e758b6
|
refs/heads/master
|
<file_sep><?php
namespace app\model;
use app\model\DB;
require 'DB.php';
class requestAuthentication {
//encryptUseRWorD
function encrypt_UseRWorD( $value ) {
$cryptKey = 'sqJuB0rGtlIn5UeB1xG03efyCpiman';
$qEncoded = base64_encode( mcrypt_encrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ), $value, MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ) );
return( $qEncoded );
}
//function to set user SESSION
public function setLogSESSION($Email,$psw){
session_start();
$_SESSION['userlog_<EMAIL>'] = $Email;
$_SESSION['<EMAIL>'] = $psw;
return "true";
}
//Function to check SQL injection
function check_injection($connect,$value) {
$value = trim($value);
$value = stripslashes($value);
$value = htmlspecialchars($value);
$value = mysqli_real_escape_string($connect,$value);
return $value;
}
//Function to register new user to the system
function registerUser($connect){
$F_name = $this ->check_injection($connect,htmlentities($_POST['Full_Name']));
$Email_address = $this ->check_injection($connect,htmlentities($_POST['emailreg']));
$psw = $this ->check_injection($connect,htmlentities($_POST['passwordreg']));
if(empty($F_name)){
echo "<label style='color:#F00;'>Full Name can not be empty.</label>";
}else if(empty($Email_address)){
echo "<label style='color:#F00;'>Email can not be empty</label>";
}else if(empty($psw)){
echo "<label style='color:#F00;'>Password can not be empty.</label>";
}else if(strlen($psw) < 7){
echo "<label style='color:#F00;'>Password Must be more than 6 characters!.</label>";
}else{
$userpsw = $this ->encrypt_UseRWorD($psw);
$queryeml = mysqli_query($connect,"SELECT * FROM users WHERE Email= '$Email_address' ");
$check_email = mysqli_num_rows($queryeml);
if($check_email > 0){
echo "<label style='color:#F00;'>".$Email_address." Is teken, select or use another email.</label>";
}else{
if(mysqli_query($connect,"INSERT INTO users VALUES ('','$F_name','$Email_address','$userpsw',Now())")){
$result = $this -> setLogSESSION($Email_address,$userpsw);
echo $result;
}else{
echo "not_true";
}
}
}
}
//Function to log in the user to the system
function loginUser($connect){
$Email_address = $this ->check_injection($connect,htmlentities($_POST['email_login']));
$password_one = $this ->check_injection($connect,htmlentities($_POST['passwordone_login']));
$userpsw = $this ->encrypt_UseRWorD($password_one);
$query = mysqli_query($connect,"SELECT * FROM users WHERE Email= '$Email_address' AND password='$<PASSWORD>'");
$check_user = mysqli_num_rows($query);
if($check_user > 0){
$result = $this ->setLogSESSION($Email_address,$userpsw);
echo $result;
}else{
echo "<label style='color:#F00;'>Invalid Email or Password!</label>";
}
}
}<file_sep><!DOCTYPE html>
<html lang="en">
<?php
include_once("head.php");
?>
<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<h1>Manage Product</h1>
<ol class="breadcrumb">
<li class="breadcrumb-item">
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModalnewProduct"><i class="icon-Product-1"></i> Add new Product</button>
<div class="modal fade" id="myModalnewProduct" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel"><i class="icon-Product-1"></i> Add new Product</h4>
</div>
<div class="modal-body">
<div id="Product_form">
<div class="">
<div id="TextBoxesGroup">
<div id="TextBoxDiv1">
<div class="form-group">
<img src="../../productImg/photo_default.png" id="Product_averta" style="margin-left: 0%; width: 60%;"><hr>
<label></label>
<label style="margin-top:0px; float: left; width:;"><a class="ajax-link" style="color:#2a9464;" ><i class="fa fa-camera"></i> Select Product Image</a></label>
<input type="file" name="imageProduct" id="imageProduct" style=" margin-top:-30px; height:37px; float: left; opacity:0; width:99%;"/>
</div>
<div class="form-group">
<label>Name</label>
<input class="form-control" placeholder="Product Name" id="pName">
</div>
<div class="form-group">
<label>Color</label>
<select class="form-control" id="pColor">
<option value="">Select Color</option>
<option value="Black">Black</option>
<option value="Yellow">Yellow</option>
<option value="Red">Red</option>
<option value="White">White</option>
</select>
</div>
<div class="form-group">
<label>Category</label>
<select class="form-control" id="pCategory">
<option value="">Select Category</option>
<option value="Casual Wear">Casual Wear</option>
<option value="Sports Wear">Sport Wear</option>
<option value="Office Wear">Office Wear</option>
</select>
</div>
<div class="form-group">
<label>Brand</label>
<select class="form-control" id="pBrand">
<option value="">Select Brand</option>
<option value="Adidas">Adidas</option>
<option value="Nike">Nike</option>
</select>
</div>
</div>
<div class="form-group">
<label>Price</label>
<input class="form-control" type="number" placeholder="Price" id="pPrice">
</div>
<div class="form-group">
<label>Quantity</label>
<input class="form-control" type="number" placeholder="Quantity" id="pQuantity">
</div>
</div>
<p id="removeMessage" style="color:#F00;"></p>
<button class="btn btn-success" id="saveProductproduct"><i class="fa fa-save"></i> Save Product</button>
<br><br>
<div id="savestatus1"></div><div id="savestatus2"></div><div id="savestatus3"></div>
<div id="savestatus4"></div><div id="savestatus5"></div><div id="savestatus6"></div>
<div id="savestatus7"></div>
<div id="savestatus"></div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
<!-- /.modal-content -->
</div>
</div>
</li>
</ol>
</div>
</div>
<script type="text/javascript">getProducts();</script>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
All Products
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<div class="dataTable_wrapper">
<div id="dataTables-example_wrapper" class="dataTables_wrapper form-inline dt-bootstrap no-footer">
<div class="row">
<h4 id="requestSearch_status"></h4>
<div class="col-sm-12">
<table width="100%" class="table table-striped table-bordered table-hover dataTable no-footer dtr-inline collapsed" id="dataTables-example" role="grid" aria-describedby="dataTables-example_info" style="width: 100%;">
<thead>
<tr role="row">
<th>Photo</th>
<th>Name</th>
<th>Price</th>
<th>Color</th>
<th>Category</th>
<th>Brand</th>
<th>Quantity</th>
<th>Action</th>
</tr>
</thead>
<tbody id="result_output">
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-12 -->
</div>
</div>
</div>
<script src="../../assets/scripts/jquery-2.2.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//change photo on select photo
$('#imageProduct').change(function(event) {
$("#Product_averta").fadeIn("fast").attr('src',URL.createObjectURL(event.target.files[0]));
});
//Process Avatar You
$("#saveProductproduct").click(function(){
var file = document.getElementById("imageProduct").files[0];
var pname = $("#pName").val();
var color = $("#pColor").val();
var category = $("#pCategory").val();
var brand = $("#pBrand").val();
var price = $("#pPrice").val();
var quantity = $("#pQuantity").val();
var formdata = new FormData();
formdata.append("ProductImage", file);
formdata.append("ProductName", pname);
formdata.append("ProductCategory", category);
formdata.append("Quantity", quantity);
formdata.append("Color", color);
formdata.append("Brand", brand);
formdata.append("Price", price);
var hr = new XMLHttpRequest();
var url = "../../app/controller/productController.php";
hr.open("POST", url, true);
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
if(return_data != "false"){
$('#result_output').prepend(''+return_data+'');
document.getElementById("Product_averta").src = '../../productimg/photo_default.png';
$('#savestatus1').html(''); $('#savestatus2').html(''); $('#savestatus3').html(''); $('#savestatus4').html(''); $('#savestatus5').html(''); $('#savestatus6').html(''); $('#savestatus7').html(''); //$('#savestatus').html('');
$('#savestatus').html("<i style='color:#5cb85c;'>Save Successful</i>");
$("#savestatus").fadeOut(9000);
clearFields();
}else{
$('#savestatus').html("<i style='color:#5cb85c;'><label style='color:#F00;'>ERROR: Please try again.</label></i>");
}
}else{
}
}
hr.send(formdata);
$("#savestatus").fadeIn();
$('#savestatus').html("<i style='color:#5cb85c;'>Saving Product Product...<i class='icon-spin6 animate-spin'></i></i></i>");
});
//*************Get all products***************
var hr = new XMLHttpRequest();
var url = "../../app/controller/productController.php";
var vars = "getAllProducts=true";
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
//var return_datad = JSON.parse(hr.responseText);
$('#result_output').html(return_data);
//console.log(return_datad.);
$('#requestSearch_status').html("");
}
}
hr.send(vars);
$('#requestSearch_status').html("<i style='color:green;'>Retrieving Products........</i>");
//End of Document.ready function
});
function clearFields() {
$('#Product_form').find('input:text').val('');
$('#pCategory option:first').prop('selected',true);
$("#pQuantity").val('');
$('#pBrand option:first').prop('selected',true);
$('#pColor option:first').prop('selected',true);
$("#pPrice").val('');
}
function getProducts(){
// var hr = new XMLHttpRequest();
// var url = "../../app/controller/productController.php";
// var vars = "getAllProducts=true";
// hr.open("POST", url, true);
// hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// hr.onreadystatechange = function() {
// if(hr.readyState == 4 && hr.status == 200) {
// var return_data = hr.responseText;
// $('#result_output').html(return_data);
// //$('#requestSearch_status').html("");
// }
// }
// hr.send(vars);
// $('#requestSearch_status').html("<i style='color:green;'>Retrieving Products........</i>");
}
//Change update photo onchnage
function chnageimgupdate(img){
var filesSelected = document.getElementById("imageProduct"+img).files;
var newimage = document.getElementById("Product_avertaupdate"+img);
if (filesSelected.length > 0)
{
var fileToLoad = filesSelected[0];
if (fileToLoad.type.match("image.*"))
{
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var imageLoaded = document.createElement("img");
newimage.src = fileLoadedEvent.target.result;
//document.getElementById("Product_averta"+img).src = imageLoaded;
//document.body.appendChild(imageLoaded);
};
fileReader.readAsDataURL(fileToLoad);
}
}
}
//Update Product image
function uploadProductFile(img,oldimg){
var file = document.getElementById("imageProduct"+img).files[0];
var formdata = new FormData();
formdata.append("ProductID", img);
formdata.append("ProductImage", file);
formdata.append("oldImageUpdate", oldimg);
var hr = new XMLHttpRequest();
var url = "../../app/controller/productController.php";
hr.open("POST", url, true);
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
console.log(return_data);
if(return_data != "false"){
document.getElementById("updateProductImg"+img).src = '../../productimg/'+return_data;
$('#statusimg'+img).html("<i style='color:#5cb85c;'>Update Successful</i>");
$("#statusimg"+img).fadeOut(9000);
}else{
$('#statusimg'+img).html("<i style='color:#F00;'>Error uploading, please try again.</i>");
}
}else{
// var return_data = JSON.parse(hr.responseText);
// console.log(return_data);
// $('#statusimg').html("<i style='color:#F00;'> Error</i>");
}
}
hr.send(formdata);
$("#statusimg"+img).fadeIn();
$('#statusimg'+img).html("<i style='color:#5cb85c;'>uploading...</i></i>");
}
//Update Product detailss
function updateProductproduct(Product){
var pname = $("#pName"+Product).val();
var color = $("#pColor"+Product).val();
var category = $("#pCategory"+Product).val();
var brand = $("#pBrand"+Product).val();
var price = $("#pPrice"+Product).val();
var quantity = $("#pQuantity"+Product).val();
var vars = "uProductID="+Product+"&uProductName="+pname+"&uProductCategory="+category+"&uQuantity="+quantity+"&uColor="+color+"&uBrand="+brand+"&uPrice="+price;
var hr = new XMLHttpRequest();
var url = "../../app/controller/productController.php";
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
if(return_data == "true"){
$('#upName'+Product).html(''+pname+'')
$('#updPrice'+Product).html('€ '+price+'')
$('#updColor'+Product).html(''+color+'')
$('#updCategory'+Product).html(''+category+'')
$('#updBrand'+Product).html(''+brand+'')
$('#updQuantity'+Product).html(''+quantity+'')
$('#savestatusupdate'+Product).html("<i style='color:#5cb85c;'>Save Successful</i>");
$("#savestatusupdate"+Product).fadeOut(9000);
}else{
$('#savestatusupdate'+Product).html(return_data);
}
}else{
// var return_data = JSON.parse(hr.responseText);
// console.log(return_data);
// $('#savestatus').html("<i style='color:#F00;'> Error</i>");
}
}
hr.send(vars);
$("#savestatusupdate"+Product).fadeIn();
$('#savestatusupdate'+Product).html("<i style='color:#5cb85c;'>Updating...<i class='icon-spin6 animate-spin'></i></i></i>");
}
//function to delete product
function deleteProduct(id,Product,img){
var con = confirm("Are you sure you want to delete"+Product+" ?");
if(con != true){
return false;
}else{
var vars = "ProductdeleterecordID="+id+"&oldImage="+img;
var hr = new XMLHttpRequest();
var url = "../../app/controller/productController.php";
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
$('#Productdeleterecord'+id).hide();
}
}
hr.send(vars);
$('#Productdeltemessage'+id).html("<i style='color:#FFF;'>dele...<i class='icon-spin6 animate-spin'></i></i>");
}
}
</script>
<!-- Bootstrap core JavaScript -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="../../assets/sbadmin/js/bootstrap.js"></script>
<!-- Page Specific Plugins -->
<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="http://cdn.oesmith.co.uk/morris-0.4.3.min.js"></script>
<?php
//include_once("footer.php");
?>
</body>
</html>
<file_sep><!DOCTYPE html>
<html>
<?php
include_once("head.php");
?>
<body class="">
<section>
<div class="container">
<div class="row">
<h4 id="requestCheckout_status"></h4>
<div class="col-lg-9">
<h2 class="page-header" style="text-align:center;">Check Out</h2>
<div class="panel panel-default">
<div class="panel-heading">
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<div class="table-responsive table-bordered">
<table class="table">
<thead>
<tr>
<th></th>
<th>Brand</th>
<th>category</th>
<th>Price</th>
</tr>
</thead>
<tbody id="checkOutresult_output">
</tbody>
</table>
</div>
<!-- /.table-responsive -->
</div>
<!-- /.panel-body -->
</div>
</div>
<div class="col-lg-3" style="border-left:3px #CCC solid;">
</div>
</div>
</div>
</section>
<script type="text/javascript">
function removeCart(ProductID,price){
var vars = "removetoCartID="+ProductID;
var hr = new XMLHttpRequest();
var url = "app/controller/productController.php";
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
var total = document.getElementById("totl_Amount").value;
total = total - price;
$('#totalText').html(number_format(total));
$('#totl_Amount').val(total);
var elem = document.getElementById("cart"+ProductID);
elem.parentElement.removeChild(elem);
$('#myCartotal').html(return_data);
//$("#cart"+ProductID).html("");
}
}
hr.send(vars);
$('#removeMeCart'+ProductID).html("<i style='color:green;'>removing..</i>");
}
function number_format(n) {
var parts=n.toString().split(".");
return parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");
}
</script>
<?php
include_once("footer.php");
?>
</body>
</html>
<file_sep><!DOCTYPE html>
<html lang="en">
<?php
include_once("headlinks.php");
?>
<body>
<div id="wrapper">
<!-- Include navigation links -->
<?php
include_once("navigation.php");
?>
<div id="page-wrapper">
<div class="row">
<h2 class="page-header" style="text-align:center;">Products</h2>
<h4 id="requestSearch_status"></h4>
<div class="col-lg-9" id="result_output">
</div>
<div class="col-lg-3" style="border-left:3px #CCC solid;">
<h3>Your Order</h3>
<!-- /row -->
<ul class="treatments clearfix">
<div id="total_cart">
<p id="requestCar_status"></p>
</div>
</ul>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
//*************Get all products ***************
var hr = new XMLHttpRequest();
var url = "app/controller/productController.php";
var vars = "LoadallProducts=true";
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
//var return_datad = JSON.parse(hr.responseText);
$('#result_output').html(return_data);
//console.log(return_datad.);
$('#requestSearch_status').html("");
}
}
hr.send(vars);
$('#requestSearch_status').html("<i style='color:green;'>Loading Products............</i>");
//*************Get all products users***************
var hrCart = new XMLHttpRequest();
var urlCart = "app/controller/productController.php";
var varsCart = "LoadallCartslogin=true";
hrCart.open("POST", urlCart, true);
hrCart.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hrCart.onreadystatechange = function() {
if(hrCart.readyState == 4 && hrCart.status == 200) {
var return_Cart = hrCart.responseText;
$('#total_cart').html(return_Cart);
//console.log(return_datad.);
$('#requestCar_status').html("");
}
}
hrCart.send(varsCart);
$('#requestCar_status').html("<i style='color:green;'>Loading cart............</i>");
});
function removeCart(ProductID,price){
var vars = "removetoCartID="+ProductID;
var hr = new XMLHttpRequest();
var url = "app/controller/productController.php";
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
var total = document.getElementById("totl_Amount").value;
total = total - price;
$('#totalText').html(number_format(total));
$('#totl_Amount').val(total);
var elem = document.getElementById("cart"+ProductID);
elem.parentElement.removeChild(elem);
$('#myCartotal').html(return_data);
//$("#cart"+ProductID).html("");
}
}
hr.send(vars);
$('#removeMeCart'+ProductID).html("<i style='color:green;'>removing..</i>");
}
function number_format(n) {
var parts=n.toString().split(".");
return parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");
}
function addTocart(ProductID,Product,price){
var vars = "addtoCartID="+ProductID;
var hr = new XMLHttpRequest();
var url = "app/controller/productController.php";
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
//if(return_data =="true"){
$('#Productdeltemessage'+ProductID).html("<i class='fa fa-shopping-cart'></i> Buy");
$('#total_cart').prepend('<li id="cart'+ProductID+'"><div class="checkbox"><input type="hidden" name="ProductAmount" value="'+price+'"><label for="visit4" class="css-label">'+Product+'<strong> € '+price+' <i class="fa fa-times-circle" style="color:#F00;" title="Remove" onclick="removeCart(\''+ProductID+'\',\''+price+'\');"></i></strong></label></div></li>');
var allPrice = document.getElementsByName("ProductAmount");
var grand_Total = 0;
for(var i = 0; i < allPrice.length; i++) {
grand_Total = parseFloat(grand_Total) + parseFloat(allPrice[i].value);
}
$('#totalText').html(number_format(grand_Total));
$('#totl_Amount').val(grand_Total);
$('#myCartotal').html(return_data);
//}
//$('#Productdeleterecord'+id).hide();
}
}
hr.send(vars);
$('#Productdeltemessage'+ProductID).html("<i style='color:#FFF;'>adding...</i>");
}
function number_format(n) {
var parts=n.toString().split(".");
return parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");
}
function removeCart(ProductID,price){
var vars = "removetoCartID="+ProductID;
var hr = new XMLHttpRequest();
var url = "app/controller/productController.php";
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
var total = document.getElementById("totl_Amount").value;
total = total - price;
$('#totalText').html(number_format(total));
$('#totl_Amount').val(total);
// var elem = document.getElementById("cart"+ProductID);
// elem.parentElement.removeChild(elem);
$('#myCartotal').html(return_data);
$("#cart"+ProductID).fadeOut(2000);
//$('#cart'+ProductID).html('');
}
}
hr.send(vars);
$('#removeMeCart'+ProductID).html("<i style='color:green;'>removing..</i>");
}
</script>
<?php
include_once("footer.php");
?>
</body>
</html>
<file_sep><!DOCTYPE html>
<html lang="en">
<?php
include_once("headlinks.php");
session_start();
$_SESSION['NameonCard'] = $_GET['NameonCard'];
$_SESSION['CardNumber'] = $_GET['CardNumber'];
$_SESSION['ExpirationDate'] = $_GET['ExpirationDate'];
$_SESSION['SecurityCode'] = $_GET['SecurityCode'];
$_SESSION['HomeAddress'] = $_GET['HomeAddress'];
?>
<body>
<div id="wrapper">
<!-- Include navigation links -->
<?php
include_once("navigation.php");
?>
<div id="page-wrapper">
<div class="row">
<div class="row">
<div class="col-lg-12">
<h1><small style="color:#FFF; background-color: #F00; border-radius: 90px; padding: 10px;">3</small> Transaction in Progress</h1>
</div>
<hr>
<div class="col-lg-11">
<h4>Please waite....this may take few seconds</h4>
<div id="progress" style=" width:100%;"></div>
<div id="information" style=" margin-left:20px;"></div>
<?php
$total = 10;
//'.$i.'%;
for($i=1; $i<=$total; $i++){
$percent = intval($i/$total * 100)."%";
echo '<script language="javascript">
document.getElementById("progress").innerHTML="<div style=\"width:'.$percent.';background-color:#009100;\"> </div>";
document.getElementById("information").innerHTML="Transaction in progress............................................... please wait!";
</script>';
echo str_repeat(' ',1024*64);
flush();
sleep(1);
if($i == 9){
echo '<script language="javascript">document.location = "?/&goto=confirm"; </script>';
}
}
?>
</div>
<div class="col-lg-3" style="border-left:3px #CCC solid;">
</div>
</div>
</div>
</div>
</div>
<?php
include_once("footer.php");
?>
</body>
</html>
<file_sep><?php
namespace app\model;
use app\model\DB;
require 'DB.php';
error_reporting(E_ALL);
error_reporting(E_ERROR);
ini_set('display_errors', '1');
class productModel {
//Method to insert new product
function saveProduct($connect){
if(empty($_FILES["ProductImage"]["name"])){
echo "<label style='color:#F00;'>Error: Please select a product picture...</label>";
}else if(empty($_POST['ProductName'])){
echo "<label style='color:#F00;'>Product Name can not be empty</label>";
}else if(empty($_POST['Color'])){
echo "<label style='color:#F00;'>Please select a product Color.</label>";
}else if(empty($_POST['ProductCategory'])){
echo "<label style='color:#F00;'>Product Category can not be empty.</label>";
}else if(empty($_POST['Brand'])){
echo "<label style='color:#F00;'>Please select the Brand of the product.</label>";
}else if(empty($_POST['Price'])){
echo "<label style='color:#F00;'>Price can not be empty</label>";
}else if(empty($_POST['Quantity'])){
echo "<label style='color:#F00;'>Quantity can not be empty.</label>";
}else{
$fileName = $_FILES["ProductImage"]["name"];
$fileTmpLoc = $_FILES["ProductImage"]["tmp_name"];
$fileType = $_FILES["ProductImage"]["type"];
$fileSize = $_FILES["ProductImage"]["size"];
$fileErrorMsg = $_FILES["ProductImage"]["error"];
if(move_uploaded_file($fileTmpLoc, "../../productImg/$fileName")){
mysqli_query($connect,"INSERT INTO products VALUES ('','".$_POST['ProductName']."','".$_POST['Price']."','$fileName','".$_POST['Color']."','".$_POST['Brand']."','".$_POST['ProductCategory']."','".$_POST['Quantity']."',Now())");
//echo "productImg/$fileName";
echo $this->getProductinserted($connect);;
} else {
echo "false";
}
}
}
//Method to update product Image
function updateProductImage($connect){
if(empty($_FILES["ProductImage"]["name"])){
echo "<label style='color:#F00;'>Error: Please select a product picture...</label>";
}else{
$fileName = $_FILES["ProductImage"]["name"];
$fileTmpLoc = $_FILES["ProductImage"]["tmp_name"];
$fileType = $_FILES["ProductImage"]["type"];
$fileSize = $_FILES["ProductImage"]["size"];
$fileErrorMsg = $_FILES["ProductImage"]["error"];
$oldPhoto =$_POST['oldImageUpdate'];
$productID = $_POST['ProductID'];
if(move_uploaded_file($fileTmpLoc, "../../productImg/$fileName")){
unlink("../../".$oldPhoto);
mysqli_query($connect,"UPDATE products SET image='$fileName' WHERE id='$productID' ");
echo $fileName;
} else {
echo "false";
}
}
}
//Function to Update Product Details
function updateProductDetails($connect){
if(empty($_POST['uProductName'])){
echo "<label style='color:#F00;'>Product Name can not be empty</label>";
}else if(empty($_POST['uColor'])){
echo "<label style='color:#F00;'>Please select a product Color.</label>";
}else if(empty($_POST['uProductCategory'])){
echo "<label style='color:#F00;'>Product Category can not be empty.</label>";
}else if(empty($_POST['uBrand'])){
echo "<label style='color:#F00;'>Please select the Brand of the product.</label>";
}else if(empty($_POST['uPrice'])){
echo "<label style='color:#F00;'>Price can not be empty</label>";
}else if(empty($_POST['uQuantity'])){
echo "<label style='color:#F00;'>Quantity can not be empty.</label>";
}else{
$proudctID =$_POST['uProductID'];
$getName = $_POST['uProductName'];
$getPrice = $_POST['uPrice'];
$getColor = $_POST['uColor'];
$getBrand = $_POST['uBrand'];
$getCategory = $_POST['uProductCategory'];
$getQuantity = $_POST['uQuantity'];
if(mysqli_query($connect,"UPDATE products SET
productName = '$getName',
price = '$getPrice',
color = '$getColor',
brand = '$getBrand',
category = '$getCategory',
quantity = '$getQuantity' WHERE id='$proudctID' ")){
echo "true";
} else {
echo "<label style='color:#F00;'>Error.... please try again</label>";
}
}
}
//Function to Delete Product
function deleteProduct($connect){
$proudctID =$_POST['ProductdeleterecordID'];
$oldPhoto = $_POST['oldImage'];
if(mysqli_query($connect,"DELETE FROM products WHERE id='$proudctID'")){
unlink("../../productimg/".$oldPhoto);
echo "";
}else{
echo "";
}
}
//Metho to get the last product inserted
function getProductinserted($connect){
$sql = mysqli_query($connect,"SELECT * FROM products ");
while($row = mysqli_fetch_array($sql)){
$ID = $row['id'];
$getName = $row['productName'];
$getPrice = $row['price'];
$getImage = $row['image'];
$getColor = $row['color'];
$getBrand = $row['brand'];
$getCategory = $row['category'];
$getQuantity = $row['quantity'];
}
return '<tr class="gradeA odd" role="row" id="Productdeleterecord'.$ID.'">
<td>
<img src="../../productImg/'.$getImage.'" id="updateProductImg'.$ID.'" style="height: 40px; width: 50px;">
</td>
<td id="upName'.$ID.'">'.$getName.'</td>
<td id="updPrice'.$ID.'">€ '.$getPrice.'</td>
<td id="updColor'.$ID.'">'.$getColor.'</td>
<td id="updCategory'.$ID.'">'.$getCategory.'</td>
<td id="updBrand'.$ID.'">'.$getBrand.'</td>
<td id="updQuantity'.$ID.'">'.$getQuantity.'</td>
<td class="center">
<a data-toggle="modal" data-target="#myModalnewProduct'.$ID.'" style="background-color: #449d44; color: #FFF; font-size: 11px; padding: 3px;" class="btn primary"><i class="fa fa-edit white"></i> Edit </a>
<a onClick="deleteProduct(\''.$ID.'\',\''.$getName.'\',\''.$getImage.'\')" id="Productdeltemessage'.$ID.'" style="background-color: #d9534f; color: #FFF; font-size: 11px; padding: 3px;" class="btn primary"><i class="fa fa-trash-o"></i> Delete </a>
<div class="modal fade" id="myModalnewProduct'.$ID.'" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel"><i class="icon-Product-1"></i> Update '.$getName.'</h4>
</div>
<div class="modal-body">
<div id="Product_form'.$ID.'">
<div class="">
<div id="TextBoxesGroup">
<div id="TextBoxDiv1">
<div class="form-group">
<img src="../../productImg/'.$getImage.'" id="Product_avertaupdate'.$ID.'" style="margin-left: 0%; width: 60%;"><hr>
<label></label>
<label style="margin-top:0px; float: left; width:;"><a class="ajax-link" style="color:#2a9464;" ><i class="fa fa-camera"></i> Select Product Image</a></label>
<input type="file" name="imageProduct'.$ID.'" id="imageProduct'.$ID.'" onchange="chnageimgupdate(\''.$ID.'\')" style=" margin-top:-30px; height:37px; float: left; opacity:0; width:99%;"/>
<br>
<button class="btn-primary" style="border-radius:3px; font-size: 13px; padding: 4px; color: #FFF;" onclick="uploadProductFile(\''.$ID.'\',\'productImg/'.$getImage.'\');"><i class="fa fa-upload"></i> Upload </button>
<code id="statusimg'.$ID.'" style="background-color:transparent;"></code>
</div>
<div class="form-group" style="width:100%;">
<label>Name</label>
<input class="form-control" value="'.$getName.'" placeholder="Product Name" id="pName'.$ID.'">
</div><br>
<div class="form-group" style="width:100%;">
<label>Color</label>
<select class="form-control" id="pColor'.$ID.'">
<option value="'.$getColor.'">'.$getColor.'</option>
<option value="Black">Black</option>
<option value="Yellow">Yellow</option>
<option value="Red">Red</option>
<option value="White">White</option>
</select>
</div><br>
<div class="form-group" style="width:100%;">
<label>Category</label>
<select class="form-control" id="pCategory'.$ID.'">
<option value="'.$getCategory.'">'.$getCategory.'</option>
<option value="Casual Wear">Casual Wear</option>
<option value="Sports Wear">Sport Wear</option>
<option value="Office Wear">Office Wear</option>
</select>
</div><br>
<div class="form-group" style="width:100%;">
<label>Brand</label>
<select class="form-control" id="pBrand'.$ID.'">
<option value="'.$getBrand.'">'.$getBrand.'</option>
<option value="Adidas">Adidas</option>
<option value="Nike">Nike</option>
</select>
</div><br>
</div>
<div class="form-group" style="width:100%;">
<label>Price</label>
<input class="form-control" type="number" placeholder="Price" value="'.$getPrice.'" id="pPrice'.$ID.'">
</div><br>
<div class="form-group" style="width:100%;">
<label>Quantity</label>
<input class="form-control" type="number" placeholder="Quantity" value="'.$getQuantity.'" id="pQuantity'.$ID.'">
</div><br>
</div>
<p id="removeMessage'.$ID.'" style="color:#F00;"></p>
<button class="btn btn-success" onclick="updateProductproduct(\''.$ID.'\');"><i class="fa fa-save"></i> Update Product</button>
<br><br>
<div id="savestatusupdate'.$ID.'"></div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
<!-- /.modal-content -->
</div>
</div>
</td>
</tr>
';
}
//Method to get all the product return the result to admin page
function getallProduct($connect){
$allProducts .= '';
$sql = mysqli_query($connect,"SELECT * FROM products ");
while($row = mysqli_fetch_array($sql)){
$ID = $row['id'];
$getName = $row['productName'];
$getPrice = $row['price'];
$getImage = $row['image'];
$getColor = $row['color'];
$getBrand = $row['brand'];
$getCategory = $row['category'];
$getQuantity = $row['quantity'];
$allProducts .= '
<tr role="row" id="Productdeleterecord'.$ID.'">
<td>
<img src="../../productImg/'.$getImage.'" id="updateProductImg'.$ID.'" style="height: 40px; width: 50px;">
</td>
<td id="upName'.$ID.'">'.$getName.'</td>
<td id="updPrice'.$ID.'">€ '.$getPrice.'</td>
<td id="updColor'.$ID.'">'.$getColor.'</td>
<td id="updCategory'.$ID.'">'.$getCategory.'</td>
<td id="updBrand'.$ID.'">'.$getBrand.'</td>
<td id="updQuantity'.$ID.'">'.$getQuantity.'</td>
<td class="center">
<a data-toggle="modal" data-target="#myModalnewProduct'.$ID.'" style="background-color: #449d44; color: #FFF; font-size: 11px; padding: 3px;" class="btn primary"><i class="fa fa-edit white"></i> Edit </a>
<a onClick="deleteProduct(\''.$ID.'\',\''.$getName.'\',\''.$getImage.'\')" id="Productdeltemessage'.$ID.'" style="background-color: #d9534f; color: #FFF; font-size: 11px; padding: 3px;" class="btn primary"><i class="fa fa-trash-o"></i> Delete </a>
<div class="modal fade" id="myModalnewProduct'.$ID.'" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel"><i class="icon-Product-1"></i> Update '.$getName.'</h4>
</div>
<div class="modal-body">
<div id="Product_form'.$ID.'">
<div class="">
<div id="TextBoxesGroup">
<div id="TextBoxDiv1">
<div class="form-group">
<img src="../../productImg/'.$getImage.'" id="Product_avertaupdate'.$ID.'" style="margin-left: 0%; width: 60%;"><hr>
<label></label>
<label style="margin-top:0px; float: left; width:;"><a class="ajax-link" style="color:#2a9464;" ><i class="fa fa-camera"></i> Select Product Image</a></label>
<input type="file" name="imageProduct'.$ID.'" id="imageProduct'.$ID.'" onchange="chnageimgupdate(\''.$ID.'\')" style=" margin-top:-30px; height:37px; float: left; opacity:0; width:99%;"/>
<br>
<button class="btn-primary" style="border-radius:3px; font-size: 13px; padding: 4px; color: #FFF;" onclick="uploadProductFile(\''.$ID.'\',\'productImg/'.$getImage.'\');"><i class="fa fa-upload"></i> Upload </button>
<code id="statusimg'.$ID.'" style="background-color:transparent;"></code>
</div>
<div class="form-group" style="width:100%;">
<label>Name</label>
<input class="form-control" value="'.$getName.'" placeholder="Product Name" id="pName'.$ID.'">
</div><br>
<div class="form-group" style="width:100%;">
<label>Color</label>
<select class="form-control" id="pColor'.$ID.'">
<option value="'.$getColor.'">'.$getColor.'</option>
<option value="Black">Black</option>
<option value="Yellow">Yellow</option>
<option value="Red">Red</option>
<option value="White">White</option>
</select>
</div><br>
<div class="form-group" style="width:100%;">
<label>Category</label>
<select class="form-control" id="pCategory'.$ID.'">
<option value="'.$getCategory.'">'.$getCategory.'</option>
<option value="Casual Wear">Casual Wear</option>
<option value="Sports Wear">Sport Wear</option>
<option value="Office Wear">Office Wear</option>
</select>
</div><br>
<div class="form-group" style="width:100%;">
<label>Brand</label>
<select class="form-control" id="pBrand'.$ID.'">
<option value="'.$getBrand.'">'.$getBrand.'</option>
<option value="Adidas">Adidas</option>
<option value="Nike">Nike</option>
</select>
</div><br>
</div>
<div class="form-group" style="width:100%;">
<label>Price</label>
<input class="form-control" type="number" placeholder="Price" value="'.$getPrice.'" id="pPrice'.$ID.'">
</div><br>
<div class="form-group" style="width:100%;">
<label>Quantity</label>
<input class="form-control" type="number" placeholder="Quantity" value="'.$getQuantity.'" id="pQuantity'.$ID.'">
</div><br>
</div>
<p id="removeMessage'.$ID.'" style="color:#F00;"></p>
<button class="btn btn-success" onclick="updateProductproduct(\''.$ID.'\');"><i class="fa fa-save"></i> Update Product</button>
<br><br>
<div id="savestatusupdate'.$ID.'"></div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
<!-- /.modal-content -->
</div>
</div>
</td>
</tr>
';
}
echo $allProducts;
}
//Method to get all the product return the result to User
function getallProductToUser($connect){
$allProducts .= '';
$sql = mysqli_query($connect,"SELECT * FROM products ORDER BY id DESC");
while($row = mysqli_fetch_array($sql)){
$ID = $row['id'];
$getName = $row['productName'];
$getPrice = $row['price'];
$getImage = $row['image'];
$getColor = $row['color'];
$getBrand = $row['brand'];
$getCategory = $row['category'];
$getQuantity = $row['quantity'];
$allProducts .='<div class="col-md-4 text-center">
<div class="thumbnail">
<img class="img-responsive" src="productImg/'.$getImage.'" style="width: 100%;
height: 330px;
" alt="name">
<div class="caption">
<h4 style="font-size:11px;">'.$getBrand.' '.$getName.' <br><label style="font-size:11px;">('.$getColor.')</label><br>
<small style="color: #F00;">€ '.$getPrice.'</small>
</h4>
<a onClick="addTocart(\''.$ID.'\',\''.$getName.'\',\''.$getPrice.'\')" id="Productdeltemessage'.$ID.'" class="btn btn-primary min"><i class="fa fa-shopping-cart"></i> Buy</a>
</div>
</div>
</div>';
}
echo $allProducts;
}
//function ot get all current carts to user
function getallCartsToUser($connect){
session_start();
$carts = implode(',', $_SESSION['shoppinCartProducts']);
$allCarts .= '';
$totalAmount = 0;
$sql = mysqli_query($connect,"SELECT * FROM products WHERE id IN ($carts) ");
while($row = mysqli_fetch_array($sql)){
$ID = $row['id'];
$getName = $row['productName'];
$getPrice = $row['price'];
$getImage = $row['image'];
$getColor = $row['color'];
$getBrand = $row['brand'];
$getCategory = $row['category'];
$getQuantity = $row['quantity'];
$totalAmount += $getPrice;
$allCarts .='<li id="cart'.$ID.'"><div class="checkbox"><input type="hidden" name="ProductAmount" value="'.$getPrice.'"><label for="visit4" class="css-label">'.$getName.'<strong> € '.$getPrice.' <label id="removeMeCart'.$ID.'" ><i class="fa fa-times-circle" style="color:#F00;" title="Remove" onclick="removeCart(\''.$ID.'\',\''.$getPrice.'\');"></i></label></strong></label></div></li>';
}
$allCarts .='<li>
<div class="checkbox">
<label for="visit4" class="css-label"><h4>
<input type="hidden" id="totl_Amount" value="'.$totalAmount.'">
Total <strong><label>€</label><label id="totalText">'.number_format($totalAmount).'</label></strong> </h4></label>
</div>
</li>
<a href="?/=checkOut" class="btn btn-success min"><i class="fa fa-shopping-cart"></i> Check Out</a>';
echo $allCarts;
}
//function ot get all current carts when user log in
function getallCartsToUserlogin($connect){
session_start();
$carts = implode(',', $_SESSION['shoppinCartProducts']);
$allCarts .= '';
$totalAmount = 0;
$sql = mysqli_query($connect,"SELECT * FROM products WHERE id IN ($carts) ");
while($row = mysqli_fetch_array($sql)){
$ID = $row['id'];
$getName = $row['productName'];
$getPrice = $row['price'];
$getImage = $row['image'];
$getColor = $row['color'];
$getBrand = $row['brand'];
$getCategory = $row['category'];
$getQuantity = $row['quantity'];
$totalAmount += $getPrice;
$allCarts .='<li id="cart'.$ID.'"><div class="checkbox"><input type="hidden" name="ProductAmount" value="'.$getPrice.'"><label for="visit4" class="css-label">'.$getName.'<strong> € '.$getPrice.' <label id="removeMeCart'.$ID.'" ><i class="fa fa-times-circle" style="color:#F00;" title="Remove" onclick="removeCart(\''.$ID.'\',\''.$getPrice.'\');"></i></label></strong></label></div></li>';
}
$allCarts .='<li>
<div class="checkbox">
<label for="visit4" class="css-label"><h4>
<input type="hidden" id="totl_Amount" value="'.$totalAmount.'">
Total <strong><label>€</label><label id="totalText">'.number_format($totalAmount).'</label></strong> </h4></label>
</div>
</li>
<a href="?/&goto=dashboard" class="btn btn-success min"><i class="fa fa-shopping-cart"></i> Check Out</a>';
echo $allCarts;
}
//function to get all check out
function getallCheckout($connect){
session_start();
$carts = implode(',', $_SESSION['shoppinCartProducts']);
$allCarts .= '';
$totalAmount = 0;
$sql = mysqli_query($connect,"SELECT * FROM products WHERE id IN ($carts) ");
while($row = mysqli_fetch_array($sql)){
$ID = $row['id'];
$getName = $row['productName'];
$getPrice = $row['price'];
$getImage = $row['image'];
$getColor = $row['color'];
$getBrand = $row['brand'];
$getCategory = $row['category'];
$getQuantity = $row['quantity'];
$totalAmount += $getPrice;
$allCarts .='
<tr id="cart'.$ID.'">
<td>
<div style="float:left;">
<img class="img-responsive" src="productImg/'.$getImage.'" style="height: 109px; width: 100px;" alt="'.$getName.'" title="'.$getName.'">
</div>
<div style="float:left; padding-left:9px;">
<h4>'.$getBrand.' '.$getName.' <br><label style="font-size:11px;">('.$getColor.')</label></h4>
<strong> <label id="removeMeCart'.$ID.'" ><i class="fa fa-times-circle" style="color:#F00; cursor:pointer;" title="Remove product" onclick="removeCart(\''.$ID.'\',\''.$getPrice.'\');">Remove product</i></label></strong>
</div>
</td>
<td>'.$getBrand.'</td>
<td>'.$getCategory.'</td>
<td>€ '.$getPrice.'</td>
</tr>';
}
$allCarts .='<tr><td></td>
<td></td>
<td></td>
<td>
<label for="visit4" class="css-label"><h4>
<input type="hidden" id="totl_Amount" value="'.$totalAmount.'">
<h3 style="color:#F00;">Total: <label>€ </label><label id="totalText"> '.number_format($totalAmount).'</label></h3> </h4></label><br>
<a href="?/=login" class="btn btn-success min"><i class="fa fa-shopping-cart"></i> Check Out to Pay</a>
</td>
</tr>';
echo $allCarts;
}
//function to get all check out befor paying
function getallCheckoutPay($connect){
session_start();
$carts = implode(',', $_SESSION['shoppinCartProducts']);
$allCarts .= '';
$totalAmount = 0;
$sql = mysqli_query($connect,"SELECT * FROM products WHERE id IN ($carts) ");
while($row = mysqli_fetch_array($sql)){
$ID = $row['id'];
$getName = $row['productName'];
$getPrice = $row['price'];
$getImage = $row['image'];
$getColor = $row['color'];
$getBrand = $row['brand'];
$getCategory = $row['category'];
$getQuantity = $row['quantity'];
$totalAmount += $getPrice;
$allCarts .='
<tr id="cart'.$ID.'">
<td>
<div style="float:left;">
<img class="img-responsive" src="productImg/'.$getImage.'" style="height: 109px; width: 100px;" alt="'.$getName.'" title="'.$getName.'">
</div>
<div style="float:left; padding-left:9px;">
<h4>'.$getBrand.' '.$getName.' <br><label style="font-size:11px;">('.$getColor.')</label></h4>
<strong> <label id="removeMeCart'.$ID.'" ><i class="fa fa-times-circle" style="color:#F00; cursor:pointer;" title="Remove product" onclick="removeCart(\''.$ID.'\',\''.$getPrice.'\');">Remove product</i></label></strong>
</div>
</td>
<td>'.$getBrand.'</td>
<td>'.$getCategory.'</td>
<td>€ '.$getPrice.'</td>
</tr>';
}
$allCarts .='<tr><td></td>
<td></td>
<td></td>
<td>
<label for="visit4" class="css-label"><h4>
<input type="hidden" id="totl_Amount" value="'.$totalAmount.'">
<h3 style="color:#F00;">Total: <label>€ </label><label id="totalText"> '.number_format($totalAmount).'</label></h3> </h4></label><br>
<a href="?/&goto=payment" class="btn btn-danger min"><i class="fa fa-shopping-cart"></i> Pay Now</a>
</td>
</tr>';
echo $allCarts;
}
//Mehod to add product to cart
function addProductToCart($connect, $product){
session_start();
//$_SESSION['shoppinCartProducts'] = null;
if(empty($_SESSION['shoppinCartProducts'])){
$_SESSION['shoppinCartProducts'] = array();
}
array_push($_SESSION['shoppinCartProducts'], $product);
// array_push($_SESSION['shoppinCartProducts'], $product);
// echo count($_SESSION['shoppinCartProducts']);
echo $this->totalCart();
//echo json_encode(array('foo' => 'bar'));
}
//function to get total cart
function totalCart(){
// foreach ($_SESSION['shoppinCartProducts'] as $key => $value) {
// if (empty($value)) {
// unset($_SESSION['shoppinCartProducts'][$key]);
// }
// }
// if (empty($_SESSION['shoppinCartProducts'])) {
// $_SESSION['shoppinCartProducts'] = null;
// }
return count($_SESSION['shoppinCartProducts']);
}
//function to remove product from array
function removeProductToCart($connect, $product){
session_start();
$key=array_search($product,$_SESSION['shoppinCartProducts']);
if($key!==false){
unset($_SESSION['shoppinCartProducts'][$key]);
}
//$_SESSION["shoppinCartProducts"] = array_values($_SESSION["shoppinCartProducts"]);
//reset($_SESSION["shoppinCartProducts"]);
//echo count($_SESSION['shoppinCartProducts']);
echo $this->totalCart();
}
}<file_sep><?php
namespace app\controller;
class pagesController {
public function __construct() {
//echo "Hello home page";
}
//Function to Navigate to Home page
public function HomePage(){
//include_once("view/home.php");
$this -> checkpageNotFound("view/home.php");
}
//Function to Navigate to user define page
public function set_New_pages($page){
if(empty($page)){
$this ->HomePage();
}else{
$page = strtok($page, '?');
$this -> checkpageNotFound("view/".$page.".php");
}
}
//function to handle all the navugation of user page
public function profileUserDashboard($dir, $userpage){
if($userpage == "dashboard"){
$this ->CheckpageNotFound("view/userpages/dashboard.php");
}else{
$userpage = strtok($userpage, '?');
$this ->CheckpageNotFound("view/userpages/".$userpage.".php");
}
}
//function to check if page exist
function checkpageNotFound($page){
$not_found = "404notfound";
if(!file_exists($page)){
return include_once("view/".$not_found.".php");
} else {
return include_once($page);
}
}
}
<file_sep><?php
error_reporting(E_ALL);
error_reporting(E_ERROR);
ini_set('display_errors', '1');
use app\controller\pagesController;
require 'app/controller/pagesController.php';
require './autoload.php';
//creating an object of pages Controller and Database Class
$set_Page = new pagesController();
//$connect = new DB();
//Get the new page to view and send it to set_New_pages method if the page exist else view the home page.
//$Newpage = $_GET['/'];
//$set_Page->set_New_pages($_GET['/']);
if(isset($_GET['/']) && isset($_GET['goto'])){
$Newpage = $_GET['/'];
$pagelocation = $_GET['goto'];
$set_Page->profileUserDashboard($Newpage,$pagelocation);
}else if(isset($_GET['goto'])){
$Newpage = '/';//$_GET['/'];
$pagelocation = $_GET['goto'];
$set_Page->profileUserDashboard($Newpage,$pagelocation);
}else if(isset($_GET['/'])){
$Newpage = $_GET['/'];
$set_Page->set_New_pages($Newpage);
}else{
$set_Page->HomePage();
}
<file_sep><?php
namespace app\model;
$connect = mysqli_connect('localhost','root','');
$mydatabase = mysqli_select_db($connect,'shop');
<file_sep><!DOCTYPE html>
<html lang="en">
<?php
include_once("headlinks.php");
?>
<body>
<div id="wrapper">
<!-- Include navigation links -->
<?php
include_once("navigation.php");
?>
<div id="page-wrapper">
<div class="row">
<h2 class="page-header" style="text-align:center;">My Order</h2>
<div class="col-lg-12" id="result_output">
<div class="panel panel-default">
<div class="panel-body">
<div class="row">
<div class="col-md-6 col-sm-6 text-left">
<?php
$UserID = $_SESSION['userIdentificationNavi'];
$uID = $_GET['cart'];
$querycheck= mysqli_query($connect,"SELECT * FROM ordercart WHERE id='$uID' AND UserID='$UserID' ");
while($revnt = mysqli_fetch_assoc($querycheck)){
$tranID = $revnt['id'];
$getUserID = $revnt['UserID'];
$getcarts = $revnt['chart'];
$getNameonCard = $revnt['NameonCard'];
$getCardNumber = $revnt['CardNumber'];
$getExpirationDate = $revnt['ExpirationDate'];
$getSecurityCode = $revnt['SecurityCode'];
$getHomeAddress = $revnt['HomeAddress'];
$getPaymenType = $revnt['PaymenType'];
$getcreated_at = $revnt['created_at'];
}
?>
<h4><strong>Order Date</strong> <?php echo $getcreated_at; ?></h4>
<ul class="list-unstyled">
<li><strong>Order Number:</strong> SORD<?php echo $tranID; ?>NG</li>
<li><strong>User Name:</strong> <?php echo $getNameonCard; ?></li>
<li><strong>Address:</strong> <?php echo $getHomeAddress; ?></li>
<li><strong>Mobile Number:</strong> <?php //echo $getcreated_at; ?></li>
</ul>
</div>
<div class="col-md-6 col-sm-6 text-right">
<h4><strong>Payment </strong> Source</h4>
<ul class="list-unstyled">
<li><strong>Paymen Type:</strong><label style="text-transform: uppercase;"> <?php echo $getPaymenType; ?></label></li>
</ul>
</div>
</div>
<div class="panel-body">
<div class="table-responsive table-bordered">
<table class="table">
<thead>
<tr>
<th></th>
<th>Brand</th>
<th>category</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php
$totalAmount = 0;
$sql = mysqli_query($connect,"SELECT * FROM products WHERE id IN ($getcarts) ");
while($row = mysqli_fetch_array($sql)){
$ID = $row['id'];
$getName = $row['productName'];
$getPrice = $row['price'];
$getImage = $row['image'];
$getColor = $row['color'];
$getBrand = $row['brand'];
$getCategory = $row['category'];
$getQuantity = $row['quantity'];
$totalAmount += $getPrice;
echo '<tr id="cart'.$ID.'">
<td>
<div style="float:left;">
<img class="img-responsive" src="productImg/'.$getImage.'" style="height: 109px; width: 100px;" alt="'.$getName.'" title="'.$getName.'">
</div>
<div style="float:left; padding-left:9px;">
<h4>'.$getBrand.' '.$getName.' <br><label style="font-size:11px;">('.$getColor.')</label></h4>
<strong></strong>
</div>
</td>
<td>'.$getBrand.'</td>
<td>'.$getCategory.'</td>
<td>€ '.$getPrice.'</td>
</tr>';
}
echo '<tr><td></td>
<td></td>
<td></td>
<td>
<label for="visit4" class="css-label"><h4>
<input type="hidden" id="totl_Amount" value="'.$totalAmount.'">
<h3 style="color:#F00;">Total: <label>€ </label><label id="totalText"> '.number_format($totalAmount).'</label></h3> </h4></label>
</td></tr>';
?>
</tbody>
</table>
</div>
<!-- /.table-responsive -->
</div>
<div>
</div>
</div>
<div class="panel panel-default text-right">
<div class="panel-body">
<a class="btn btn-success" href="page-invoice-print.html" target="_blank"><i class="fa fa-print"></i> PRINT </a>
</div>
</div>
</div>
</div>
<div class="col-lg-3" style="border-left:3px #CCC solid;">
</div>
</div>
</div>
</div>
<?php
include_once("footer.php");
?>
</body>
</html>
<file_sep><!DOCTYPE html>
<html lang="en">
<?php
include_once("headlinks.php");
$paymentMethod = $_GET['method'];
$_SESSION['PaymenType'] = $paymentMethod;
if($paymentMethod !="mastercard" && $paymentMethod != "bank"){
echo "<script type='text/javascript'>window.location.href = '?/&goto=payment';</script>";
exit();
}
?>
<body>
<div id="wrapper">
<!-- Include navigation links -->
<?php
include_once("navigation.php");
?>
<div id="page-wrapper">
<div class="row">
<div class="row">
<div class="col-lg-12">
<h1><small style="color:#FFF; background-color: #F00; border-radius: 90px; padding: 10px;">2</small> Transaction Details</h1>
</div>
<hr>
<div class="col-lg-5">
<h4>CARD DETAILS</h4>
<div style="padding: 10px;">
<div class="form-group">
<label>Name On Card</label>
<input class="form-control" placeholder="Name On Card" id="NameonCard" name="NameonCard">
</div>
<div class="form-group">
<label>Card Number</label>
<input class="form-control" placeholder="Card Number" id="CardNumber" name="CardNumber">
</div>
<div class="form-group">
<label>Expiration Date</label>
<input class="form-control" type="Date" placeholder="Expiration Date" id="ExpirationDate" name="ExpirationDate">
</div>
<div class="form-group">
<label>Security Code</label>
<input class="form-control" placeholder="Security Code" id="SecurityCode" name="SecurityCode">
</div>
<div class="form-group">
<label>Home Address</label>
<textarea class="form-control" placeholder="Home Address" id="HomeAddress" name="HomeAddress"></textarea>
</div>
<div class="form-group">
<a id="processOrder" class="btn btn-success min"><i class="fa fa-shopping-cart"></i> Pay Now</a>
<h4 id="paymentMessage"></h4>
</div>
</div>
</div>
<div class="col-lg-3" style="border-left:3px #CCC solid;">
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#processOrder").click(function(){
var NCard = $('#NameonCard').val();
var CNumber = $('#CardNumber').val();
var eDate = $('#ExpirationDate').val();
var Security = $('#SecurityCode').val();
var addr = $('#HomeAddress').val();
if(NCard == ""){
$('#paymentMessage').html("<i style='color:#F00;'>Name on Card can NOT be empty</i>");
}else if(isEmpty(CNumber)){
$('#paymentMessage').html("<i style='color:#F00;'>Card Number can NOT be empty</i>");
}else if(isEmpty(eDate)){
$('#paymentMessage').html("<i style='color:#F00;'>Please select Expiration Date</i>");
}else if(isEmpty(Security)){
$('#paymentMessage').html("<i style='color:#F00;'>Please type in your card Security Code</i>");
}else if(isEmpty(addr)){
$('#paymentMessage').html("<i style='color:#F00;'>HomeAddress can NOT be empty</i>");
}else{
window.location = "?/&goto=process_finalOrder&save_finalOrder=true&NameonCard="+NCard+"&CardNumber="+CNumber+"&ExpirationDate="+eDate+"&SecurityCode="+Security+"&HomeAddress="+addr;
}
});
function isEmpty(str){
return !str.replace(/^\s+/g, '').length;
}
});
</script>
<?php
include_once("footer.php");
?>
</body>
</html>
<file_sep><!DOCTYPE html>
<html lang="en">
<?php
include_once("head.php");
?>
<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<h1>Manage Order</h1>
</div>
</div>
<script type="text/javascript">getProducts();</script>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
All Products
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<div class="dataTable_wrapper">
<div id="dataTables-example_wrapper" class="dataTables_wrapper form-inline dt-bootstrap no-footer">
<div class="row">
<h4 id="requestSearch_status"></h4>
<div class="col-sm-12">
<table width="100%" class="table table-striped table-bordered table-hover dataTable no-footer dtr-inline collapsed" id="dataTables-example" role="grid" aria-describedby="dataTables-example_info" style="width: 100%;">
<thead>
<tr role="row">
<th class="sorting_asc" tabindex="0" aria-controls="dataTables-example" rowspan="1" colspan="1" aria-sort="ascending" aria-label="photo" style="width: 71px;">ID</th>
<th class="sorting" tabindex="0" aria-controls="dataTables-example" rowspan="1" colspan="1" aria-label="" style="width: 90px;">User ID</th>
<th class="sorting" tabindex="0" aria-controls="dataTables-example" rowspan="1" colspan="1" aria-label="" style="width: 81px;">Transaction name</th>
<th class="sorting" tabindex="0" aria-controls="dataTables-example" rowspan="1" colspan="1" aria-label="" style="width: 60px;">Paymen Type</th>
<th class="sorting" tabindex="0" aria-controls="dataTables-example" rowspan="1" colspan="1" aria-label="" style="width: 60px;">Address</th>
<th class="sorting" tabindex="0" aria-controls="dataTables-example" rowspan="1" colspan="1" aria-label="" style="width: 60px;">Products</th>
<th class="sorting" tabindex="0" aria-controls="dataTables-example" rowspan="1" colspan="1" aria-label="" style="width: 60px;">Order Date</th>
<th class="sorting" tabindex="0" aria-controls="dataTables-example" rowspan="1" colspan="1" aria-label="Action" style="width: 60px;">Action</th>
</tr>
</thead>
<tbody id="result_output">
<?php
$querycheck= mysqli_query($connect,"SELECT * FROM ordercart");
while($revnt = mysqli_fetch_assoc($querycheck)){
$tranID = $revnt['id'];
$getUserID = $revnt['UserID'];
$getcarts = $revnt['chart'];
$getNameonCard = $revnt['NameonCard'];
$getCardNumber = $revnt['CardNumber'];
$getExpirationDate = $revnt['ExpirationDate'];
$getSecurityCode = $revnt['SecurityCode'];
$getHomeAddress = $revnt['HomeAddress'];
$getPaymenType = $revnt['PaymenType'];
$getcreated_at = $revnt['created_at'];
echo '<tr>
<td>'.$tranID.'</td>
<td>'.$getUserID.'</td>
<td>'.$getNameonCard.'</td>
<td>'.$getPaymenType.'</td>
<td>'.$getHomeAddress.'</td>
<td>'.$getcarts.'</td>
<td>'.$getcreated_at.'</td>
<td><a href="orderdetails?cart='.$tranID.'" target="_blank">View Full Details</a></td>
</tr>';
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-12 -->
</div>
</div>
</div>
<!-- Bootstrap core JavaScript -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="../../assets/sbadmin/js/bootstrap.js"></script>
<!-- Page Specific Plugins -->
<?php
//include_once("footer.php");
?>
</body>
</html>
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.7.0
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Jun 22, 2018 at 06:11 AM
-- Server version: 10.1.22-MariaDB
-- PHP Version: 7.0.18
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `shop`
--
-- --------------------------------------------------------
--
-- Table structure for table `ordercart`
--
CREATE TABLE `ordercart` (
`id` int(11) NOT NULL,
`UserID` int(11) NOT NULL,
`chart` varchar(555) NOT NULL,
`NameonCard` varchar(255) NOT NULL,
`CardNumber` int(22) NOT NULL,
`ExpirationDate` varchar(70) NOT NULL,
`SecurityCode` int(11) NOT NULL,
`HomeAddress` varchar(255) NOT NULL,
`PaymenType` varchar(30) NOT NULL,
`created_at` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `ordercart`
--
INSERT INTO `ordercart` (`id`, `UserID`, `chart`, `NameonCard`, `CardNumber`, `ExpirationDate`, `SecurityCode`, `HomeAddress`, `PaymenType`, `created_at`) VALUES
(8, 2, '3,7,8', '<NAME>', 2147483647, '2018-06-13', 987, 'Port Harcourt Nigeria', 'MasterCard', '2018-06-21 18:32:15');
-- --------------------------------------------------------
--
-- Table structure for table `products`
--
CREATE TABLE `products` (
`id` int(11) NOT NULL,
`productName` varchar(100) NOT NULL,
`price` int(11) NOT NULL,
`image` varchar(255) NOT NULL,
`color` text NOT NULL,
`brand` varchar(100) NOT NULL,
`category` varchar(100) NOT NULL,
`quantity` int(11) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `products`
--
INSERT INTO `products` (`id`, `productName`, `price`, `image`, `color`, `brand`, `category`, `quantity`, `created_at`) VALUES
(3, 'Sandale', 89, 'adidas-originals-sandalen-schwarz-316836.jpg', 'Black', 'Adidas', 'Sports Wear', 93, '2018-06-20 13:35:35'),
(4, 'Polo shirt ', 79, 'adidas-originals-poloshirt-gruen-316854.jpg', 'Yellow', 'Nike', 'Casual Wear', 87, '2018-06-20 18:41:14'),
(5, 'Sneaker', 98, 'adidas-originals-sneaker-gruen-304205(1).jpg', 'Black', 'Adidas', 'Sports Wear', 89, '2018-06-20 18:44:46'),
(6, 'Uebergangs jacket', 67, 'adidas-originals-uebergangsjacke-grau-368730.jpg', 'White', 'Nike', 'Sports Wear', 45, '2018-06-20 18:48:37'),
(7, 'Sneaker', 77, 'adidas-originals-sneaker-schwarz-436928.jpg', 'Black', 'Adidas', 'Sports Wear', 79, '2018-06-20 18:50:45'),
(8, 'Tank Tops', 87, 'adidas-originals-tank-tops-weiss-304830.jpg', 'White', 'Nike', 'Casual Wear', 76, '2018-06-20 19:52:59');
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`Name` varchar(255) NOT NULL,
`Email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `Name`, `Email`, `password`, `created_at`) VALUES
(2, '<NAME>', '<EMAIL>', '<PASSWORD>=', '2018-06-19 13:19:45');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `ordercart`
--
ALTER TABLE `ordercart`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `products`
--
ALTER TABLE `products`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `ordercart`
--
ALTER TABLE `ordercart`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=34;
--
-- AUTO_INCREMENT for table `products`
--
ALTER TABLE `products`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>
<?php
include_once("head.php");
?>
<body class="">
<section>
<div class="container">
<h1>404 page not found</h1>
</div>
</section>
<?php
include_once("footer.php");
?>
</body>
</html>
<file_sep><?php
session_start();
include_once("app/model/check_authenticationlog.php");
?>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<title>Suleiman Shopping</title>
<!-- Bootstrap core CSS -->
<link href="assets/sbadmin/css/bootstrap.css" rel="stylesheet">
<!-- Add custom CSS here -->
<link href="assets/sbadmin/css/sb-admin.css" rel="stylesheet">
<link rel="stylesheet" href="assets/sbadmin/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="http://cdn.oesmith.co.uk/morris-0.4.3.min.css">
<script src="assets/scripts/jquery-2.2.4.min.js"></script>
</head>
<file_sep><h1>Shop</h1>
<h4>A web application with PHP which works like a small online shop.</h4>
<hr>
<h1>Installing / Deployment</h1>
<p>You need to have XAMPP with PHP 7.0 or Higher if you want to deploy it in your local host</p>
<li>Import the shop.sql Databese into your server</li>
<li>Create a foulder inside your local (xamp htdocs) directory and name it shop and extract the project inside.</li>
<p>NOTE:you can change the database name to what ever you want or you can just import all the table to your database from the shop.sql file.
</p>
<hr>
<h1>Configuration Details</h1>
<p>The Shop Applicatio was develop using a simple customize MVC framework developed with PHP.
Apart from the images, javascript and css folder, the MVC contains three
main folders (Controller, model and view) and a index.php file that send a
request to pagesController. The controller folder contain four files (pagesController.php,productController.php, userAuthentication.php and passwordEncryptController ).
<li>The pagesController handle the Navigation (raute)
between all the pages.</li>
<li>The productController handle all the requests between the user (Ajax function) and the model.<li>
<li>userAuthentication check if the user is valid or log out </li>
<li>The passwordEncryptController Encrypt the user passpord.</li>
</p>
<h1>Test</h1>
<p>
<a href="https://thelastcodebender.com/shop/" target="_blank">Click to see Life Demo or copy and paste the link in you url press enter https://thelastcodebender.com/shop/</a>
</p><file_sep><!DOCTYPE html>
<html lang="en">
<?php
include_once("headlinks.php");
?>
<body>
<div id="wrapper">
<!-- Include navigation links -->
<?php
include_once("navigation.php");
?>
<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<h1><small><?php echo $getFullName; ?></small> Check Out</h1>
</div>
<div class="row">
<h4 id="requestCheckout_status"></h4>
<div class="col-lg-9">
<div class="panel panel-default">
<div class="panel-heading">
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<div class="table-responsive table-bordered">
<table class="table">
<thead>
<tr>
<th></th>
<th>Brand</th>
<th>category</th>
<th>Price</th>
</tr>
</thead>
<tbody id="checkOutresult_output">
</tbody>
</table>
</div>
<!-- /.table-responsive -->
</div>
<!-- /.panel-body -->
</div>
</div>
<div class="col-lg-3" style="border-left:3px #CCC solid;">
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
//*************Get all check out pay***************
var hrCheckoutpay = new XMLHttpRequest();
var urlCartout = "app/controller/productController.php";
var varsCartoutpay = "LoadaCheckoutPay=true";
hrCheckoutpay.open("POST", urlCartout, true);
hrCheckoutpay.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hrCheckoutpay.onreadystatechange = function() {
if(hrCheckoutpay.readyState == 4 && hrCheckoutpay.status == 200) {
var return_Cart = hrCheckoutpay.responseText;
$('#checkOutresult_output').html(return_Cart);
$('#requestCheckout_status').html("");
}
}
hrCheckoutpay.send(varsCartoutpay);
$('#requestCheckout_status').html("<i style='color:green;'>Loading cart............</i>");
//End of Document.ready function
});
function removeCart(ProductID,price){
var vars = "removetoCartID="+ProductID;
var hr = new XMLHttpRequest();
var url = "app/controller/productController.php";
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
var total = document.getElementById("totl_Amount").value;
total = total - price;
$('#totalText').html(number_format(total));
$('#totl_Amount').val(total);
var elem = document.getElementById("cart"+ProductID);
elem.parentElement.removeChild(elem);
$('#myCartotal').html(return_data);
//$("#cart"+ProductID).html("");
}
}
hr.send(vars);
$('#removeMeCart'+ProductID).html("<i style='color:green;'>removing..</i>");
}
function number_format(n) {
var parts=n.toString().split(".");
return parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");
}
</script>
<?php
include_once("footer.php");
?>
</body>
</html>
<file_sep><?php
namespace app\model;
use app\model\DB;
require 'DB.php';
error_reporting(E_ALL);
error_reporting(E_ERROR);
ini_set('display_errors', '1');
session_start();
$Email_address = $_SESSION['userlog_EmailElement@<EMAIL>'];
$userpsw = $_SESSION['userlog@<EMAIL>'];
$querycheck= mysqli_query($connect,"SELECT * FROM users WHERE Email='$Email_address' AND password ='<PASSWORD>' ");
$checkAuth = mysqli_num_rows($querycheck);
while($revnt = mysqli_fetch_assoc($querycheck)){
$U_NavID = $revnt['id'];
$getFullName = $revnt['Name'];
}
//check if SESSION has expaired
if($checkAuth < 1){
echo "<script type='text/javascript'>window.location.href = 'http://localhost/suleiman/shop/';</script>";
exit();
}else{
$_SESSION['userIdentificationNavi'] = $U_NavID;
}
?><file_sep><?php
session_start();
//if(sizeof($_SESSION['shoppinCartProducts']) < 2){
//$_SESSION['shoppinCartProducts'] = null;
//}
?>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Suleiman Shopping</title>
<link href="assets/plugins/bootstrap/bootstrap.css" rel="stylesheet" />
<link href="assets/font-awesome/css/font-awesome.css" rel="stylesheet" />
<link rel="stylesheet" href="assets/sbadmin/font-awesome/css/font-awesome.min.css">
<link href="assets/plugins/pace/pace-theme-big-counter.css" rel="stylesheet" />
<link href="assets/css/style.css" rel="stylesheet" />
<link href="assets/css/main-style.css" rel="stylesheet" />
<link href="assets/css/mcustom.css" rel="stylesheet" />
<script src="assets/scripts/jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="assets/scripts/main_Authentication.js"></script>
</head>
<header id="home">
<div class="main-nav">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" style="border:3px #000 solid;" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="../shop">
<h4>Suleiman Shopping</h4>
</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="?/=checkOut"><i class="fa fa-shopping-cart"></i> <label id="myCartotal"><?php echo sizeof($_SESSION['shoppinCartProducts']);
?></label><br>shopping cart</a></li>
<li class="scroll"><a href="?/=login">Log in</a></li>
<li class="scroll"><a href="view/adminPage/" target="_blank">ADMIN PAGE</a></li>
</ul>
</div>
</div>
</div><!--/#main-nav-->
</header><!--/#home--><file_sep><!DOCTYPE html>
<html lang="en">
<?php
include_once("headlinks.php");
?>
<body>
<div id="wrapper">
<!-- Include navigation links -->
<?php
include_once("navigation.php");
?>
<div id="page-wrapper">
<div class="row">
<div class="row">
<div class="col-lg-12">
<h1><small style="color:#FFF; background-color: #F00; border-radius: 90px; padding: 10px;">1</small> Select Payment Method</h1>
</div>
<hr>
<div class="col-lg-10">
<div class="col-lg-5">
<img src="images/Mastercard-PNG-Picture-1000x600.png" style="width:100%; height:199px;" />
<h4 style="text-align: center;" title="pay with mastercard"><a href="?/&goto=paymentproceed&method=mastercard" class="btn btn-danger min"><i class="fa fa-shopping-cart"></i> Pay Now</a></h4>
</div>
<div class="col-lg-7">
<img src="images/bank_large.jpg" style="width:100%; height:199px;" />
<h4 style="text-align: center;" title="pay with bank transfer"><a href="?/&goto=paymentproceed&method=bank" class="btn btn-danger min"><i class="fa fa-shopping-cart"></i> Pay Now</a></h4>
</div>
</div>
<div class="col-lg-3" style="border-left:3px #CCC solid;">
</div>
</div>
</div>
</div>
</div>
<?php
include_once("footer.php");
?>
</body>
</html>
<file_sep><?php
//adding Users_Request class from model foulder
use app\model\requestAuthentication;
require '../model/requestAuthentication.php';
//creating an object of Users_Request class
$Request = new requestAuthentication();
//call Users_Request function depending on the request from Ajax function
if (isset($_POST['Full_Name']) && isset($_POST['emailreg']) && isset($_POST['passwordreg'])) {
$Request -> registerUser($connect);
}elseif (isset($_POST['email_login']) && isset($_POST['passwordone_login'])) {
$Request -> loginUser($connect);
}
<file_sep><?php
$navigate_to = '?/&goto';
?>
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="<?php echo $navigate_to; ?>=dashboard">Shop</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav side-nav">
<li class="active"><a href="<?php echo $navigate_to; ?>=dashboard"><i class="fa fa-dashboard"></i> Check Out</a></li>
<li><a href="<?php echo $navigate_to; ?>=product"><i class="fa fa-th-list"></i> Products</a></li>
<li><a href="<?php echo $navigate_to; ?>=order"><i class="fa fa-th-list"></i> My Order</a></li>
</ul>
<ul class="nav navbar-nav navbar-right navbar-user">
<li><a href="<?php echo $navigate_to; ?>=dashboard"><i class="fa fa-shopping-cart"></i> <label id="myCartotal"><?php echo sizeof($_SESSION['shoppinCartProducts']);
?></label></a></li>
<li class="dropdown user-dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-user"></i> <?php echo $getFullName; ?> <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="<?php echo $navigate_to; ?>=logout"><i class="fa fa-power-off"></i> Log Out</a></li>
</ul>
</li>
</ul>
</div>
</nav><file_sep><?php
session_start();
include_once("../../app/model/DB.php");
?>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<title>Suleiman Shopping</title>
<!-- Bootstrap core CSS -->
<link href="../../assets/sbadmin/css/bootstrap.css" rel="stylesheet">
<!-- Add custom CSS here -->
<link href="../../assets/sbadmin/css/sb-admin.css" rel="stylesheet">
<link rel="stylesheet" href="../../assets/sbadmin/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="http://cdn.oesmith.co.uk/morris-0.4.3.min.css">
<script type="text/javascript" src="../../assets/scripts/main_Authentication.js"></script>
</head>
<body>
<div id="wrapper">
<!-- Include navigation links -->
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="../adminPage">Suleiman Shopping</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav side-nav">
<li class="active"><a href="../adminPage"><i class="fa fa-dashboard"></i> Dashboard</a></li>
<li><a href="../adminPage"><i class="fa fa-edit"></i> Manage Product</a></li>
<li><a href="../adminPage/order"><i class="fa fa-table"></i> View Order </a></li>
</ul>
</div>
</nav><file_sep><?php
//adding Users_Request class from model foulder
use app\model\productModel;
require '../model/productModel.php';
//creating an object of Users_Request class
$Request = new productModel();
//call Users_Request function depending on the request from Ajax function
if(isset($_FILES["ProductImage"]["name"])
&& isset($_POST['ProductName'])
&& isset($_POST['ProductCategory'])
&& isset($_POST['Quantity'])
&& isset($_POST['Color'])
&& isset($_POST['Brand'])
&& isset($_POST['Price'])) {
$Request -> saveProduct($connect);
}elseif(isset($_POST['uProductID'])
&& isset($_POST['uProductName'])
&& isset($_POST['uProductCategory'])
&& isset($_POST['uQuantity'])
&& isset($_POST['uColor'])
&& isset($_POST['uBrand'])
&& isset($_POST['uPrice'])) {
$Request -> updateProductDetails($connect);
}elseif(isset($_POST['getAllProducts'])){
$Request -> getallProduct($connect);
}elseif(isset($_POST['LoadallProducts'])){
$Request -> getallProductToUser($connect);
}elseif(isset($_POST['LoadallCarts'])){
$Request -> getallCartsToUser($connect);
}elseif(isset($_POST['LoadallCartslogin'])){
$Request -> getallCartsToUserlogin($connect);
}elseif(isset($_POST['LoadaCheckout'])){
$Request -> getallCheckout($connect);
}elseif(isset($_POST['LoadaCheckoutPay'])){
$Request -> getallCheckoutPay($connect);
}elseif(isset($_FILES["ProductImage"]["name"]) && isset($_POST['ProductID']) && isset($_POST['oldImageUpdate']) ){
$Request -> updateProductImage($connect);
}elseif(isset($_POST['ProductdeleterecordID']) && isset($_POST['oldImage'])){
$Request -> deleteProduct($connect);
}elseif(isset($_POST['addtoCartID'])){
$Request -> addProductToCart($connect,$_POST['addtoCartID']);
}elseif(isset($_POST['removetoCartID'])){
$Request -> removeProductToCart($connect,$_POST['removetoCartID']);
}else{
echo "NOOOO";
//$Request -> loginUser($connect);
}
|
2dd9a340d14f48ba4ae43b04520b336cb0f3aa17
|
[
"Markdown",
"SQL",
"PHP"
] | 24 |
PHP
|
suleigolden/shop
|
43b5e2cb9e0fb11eefc254499b335732b4ac92e5
|
26b621510cd7d3ea0bbaa40b208b881b2b1b58ee
|
refs/heads/master
|
<file_sep># -*- coding: utf-8 -*-
'''Flask file for Raspberry Pi'''
import platform
import datetime
import os
import subprocess
import socket
from flask import render_template, redirect, request
from flask import Flask
from flask_bootstrap import Bootstrap
APP = Flask(__name__)
Bootstrap(APP)
@APP.route('/')
@APP.route('/main.html')
def mainhtml():
return render_template('main.html')
@APP.route('/stats.html')
def stats():
today = datetime.date.today()
system = platform.system()
node = platform.node()
arch = platform.machine()
user = os.getlogin()
space = os.statvfs('/home/'+user)
freespace = (space.f_frsize * space.f_bavail)/1024/1024
get_uptime = subprocess.Popen('uptime', stdout=subprocess.PIPE)
uptime = get_uptime.stdout.read()
return render_template('stats.html', today=today, system= \
system, node=node, arch=arch, user=user, \
freespace=freespace, uptime=uptime)
@APP.route('/dienste.html')
def vnc():
user = os.getlogin()
node = platform.node()
try:
myip = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
myip.connect(('8.8.8.8', 80))
getip = myip.getsockname()[0]
myip.close()
except StandardError:
getip = "IP nicht erkannt"
showbutton = True
if os.path.exists('/home/'+user+'/.vnc/'+node+':1.pid'):
showbutton = None
return render_template('dienste.html', showbutton=showbutton, getip=getip)
@APP.route('/<vncstatus>', methods=['POST'])
def vncsteer(vncstatus):
if vncstatus == "startserver":
try:
server_up = ["tightvncserver", ":1", "-geometry", \
"1024x768", "-depth", "24"]
subprocess.call(server_up)
except StandardError:
print "Server startet nicht oder läuft bereits."
if vncstatus == "stoppserver":
try:
server_down = ["tightvncserver", "-kill", ":1"]
subprocess.call(server_down)
except StandardError:
print "Server läuft nicht oder lässt sich nicht beenden."
return redirect('/dienste.html')
@APP.route('/reboot', methods=['POST'])
def reboot():
passwd = request.form['password']
rbt1 = subprocess.Popen(["echo", passwd], stdout=subprocess.PIPE)
rbt2 = subprocess.Popen(["sudo", "-S", "reboot"], stdin=rbt1.
stdout, stdout=subprocess.PIPE)
print rbt2.communicate()[0]
return redirect('/dienste.html')
if __name__ == "__main__":
APP.run(host='0.0.0.0', port=8080, debug=True)
<file_sep> from flask import Flask
from flask import render_template
from flask_bootstrap import Bootstrap
app = Flask(__name__)
Bootstrap(app)
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route('/hello.html')
def hello():
nachricht = "<NAME>!"
return render_template('hello.html', nachricht=nachricht)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8080, debug=True)
|
777ab4bf69f6a68f26b6d79fdc8ff79e1d26bfc0
|
[
"Python"
] | 2 |
Python
|
textvrbrln/flask_python
|
2852367291623f82cc65eddd07470c3e97a71351
|
83b706e54c6134a0d00509e1dd016af0cd625d2d
|
refs/heads/master
|
<repo_name>skylersidner/2015-02-09-html-form<file_sep>/main.rb
require "sinatra"
get "/welcome_page" do
"Welcome to the webpage."
end
get "/hooray" do
"HIP HIP HOORAY! I'M SO IMPRESSED, D00D!"
end
get "/test" do
@members = ["Gary", "Neal", "Virginia"]
puts @members
end
get "/test_page" do
@user_name = "Sky"
erb :welcome, :layout => :boilerplate # finds the file in views (welcome.erb) and returns it
end
get "/" do #homepage
# find file "welcome"; execute it within the layout "boilerplate"
erb :welcome, :layout => :boilerplate
end
# get "/greet" do
# #example of params:
# # {"my_name" => "Sky", "your_name" => "that_guy"}
#
# #person = "Sky"
# person = params["my_name"] #call for the value of this key
#
#
# "Hello, #{person}."
# end
get "/greet/:name" do #this passes a param key of {:name => "whatever_they_type_in_the_url"}
person = params["my_name"] #call for the value of this key
"Hello, #{person}. Your favorite name is #{params[:name]}."
end<file_sep>/index.html
<!DOCTYPE html>
<head>
<title>
Sky's HTML and CSS Wiki - HTML Form
</title>
<link rel="stylesheet" href="../2015-02-09-basic-html-css/index_style.css" type="text/css" media="screen" title="no title" charset="utf-8">
</head>
<body>
<h1>HTML</h1>
<h3>Lorem Ipsum!</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. <em>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</em> Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<div class="form">
<form>
<p>
<label for="first name">First name: </label>
<input type="text" name="firstname"><br>
<label for="last name">Last name: </label>
<input type="text" name="lastname"><br>
<label for="telephone">Telephone Number:</label>
<input type="text" name="telephone" maxlength="10" size="10"><br>
<label for="email">Email: </label>
<input type="text" name="email"><br>
<input type="radio" name="sex" value="Male">
<label for="Male">Male</label>
<input type="radio" name="sex" value="Female">
<label for="Female">Female</label><br>
<label for="favorites">Favorite Books:</label><br>
<textarea name="favorites" maxlength="1000" cols="25" rows="6"></textarea><br>
Genres of interest:<br>
<input type="checkbox" name="genre1" value="fantasy" />Fantasy<br>
<input type="checkbox" name="genre2" value="sci-fi" />Sci-Fi<br>
<input type="checkbox" name="genre3" value="historical fiction" />Historical Fiction<br>
<input type="checkbox" name="genre4" value="self-help" />Self-Help<br>
Select your closest branch:
<select name="branch">
<option value="Abrahams Branch">Abrahams Branch</option>
<option value="<NAME>">Clarke Swanson</option>
<option value="UNO Criss">UNO Criss</option>
<option value="Benson">Benson</option>
<option value="Sorenson">Sorenson</option>
<option value="C. <NAME>">C. B. Washington</option>
<option value="Owen">Owen</option>
<option value="<NAME>"><NAME></option>
</select>
<br><input type="submit" value="Send"> <input type="reset">
</p>
</form>
</div>
<div class="nav_menu">
<ul>
<li><a href="../2015-02-09-basic-html-css/index.html">Home</a></li>
<li><a href="../2015-02-09-basic-html-css/html/index.html">HTML</a></li>
<li><a href="../2015-02-09-basic-html-css/css/index.html">CSS</a></li>
<li><a href="../2015-02-09-basic-html-css/images/index.html">Images</a></li>
<li><a href="index.html">Form</a></li>
</ul>
</div>
<div>
<img class="cat_img"src="../2015-02-09-basic-html-css/images/cat_eyes.jpg" alt="cat with green eyes">
</div>
</body>
|
7a3090b484695706302f8ac66f472326452de6ac
|
[
"Ruby",
"HTML"
] | 2 |
Ruby
|
skylersidner/2015-02-09-html-form
|
3a9f8215f63e88cf3ed2a18b4697b61c0405990d
|
e6f9b5456da263cf80a43f4de5039e6f3363685c
|
refs/heads/main
|
<file_sep>import {red, green} from 'chalk';
export interface GithubCliExceptionParams {
message: string;
suggestion?: string;
file?: string;
line?: number;
}
export class GithubCliException {
private readonly message: string;
private readonly suggestion: string | undefined;
private file: string | undefined;
private line: string | undefined;
/**
* @constructor
*
* @param {GithubCliExceptionParams} params The params contaning, messages, suggestion
* line and files
*/
constructor(params: GithubCliExceptionParams) {
this.message = params.message;
this.suggestion = params.suggestion;
this.file = params.file == undefined ? '' : `in ${params.file}`;
this.line = params.line == undefined ? '' : `at line ${params.line}`;
}
/**
* @public
*
* Throw the exception
*
* @param {boolean} fatal Whether to exit from the program after the
* error or not
*/
public throwException(fatal: boolean) {
console.log(red(this.message));
if (this.file) {
console.log(red(`${this.file} ${this.line}`));
}
if (this.suggestion) {
console.log(green(this.suggestion));
}
if (fatal) {
process.exit();
}
}
}
<file_sep>import {Octokit} from '@octokit/core';
import axios, {AxiosResponse} from 'axios';
import boxen from 'boxen';
import {bold, cyan} from 'chalk';
import {GithubCliException} from '../../exception';
interface User {
// The login or the username
login: string;
// the id of the user
id: number;
// The url of the user avatar
avatar_url: string;
html_url: string;
// the name of the user
name: string | null;
// the user company
company: string | null;
// wensite url
blog: string | null;
// user location
location: string | null;
email: string | null;
hireable: boolean | null;
bio: string | null;
twitter_username: string | null;
public_repos: number;
public_gists: number;
followers: number;
following: number;
}
export class GithubUserData {
private username?: string;
private client: Octokit;
constructor(params: Map<string, string>, client: Octokit) {
this.username = params.get('user');
this.client = client;
this.createUserCards();
}
private createUserCards = async (): Promise<void> => {
const {data} = await this.client.request('/user');
const username = this.username || data.login;
axios
.get(`https://api.github.com/users/${username}`)
.then((response: AxiosResponse<any>) => {
const data = response.data as User;
const output: string = boxen(
[
`${cyan('User')} : ${bold(data.login)}`,
`${cyan('Name')} : ${bold(data.name || '[No Name]')}`,
`${cyan('Company')} : ${bold(data.company || 'None')}`,
`${cyan('Bio')} : ${bold(data.bio || '')}`,
`${cyan('Location')} : ${bold(data.location || '')}`,
`${cyan('Website')} : ${bold(data.blog)}`,
`${cyan('Email')} : ${bold(data.email || '[No email]')}`,
`${cyan('Twitter')} : ${bold(data.twitter_username || 'None')}`,
`${cyan('Hireable')} : ${bold(data.hireable || '[Not mentioned]')}`,
`${cyan('Repos')} : ${bold(data.public_repos)}`,
`${cyan('Gists')} : ${bold(data.public_gists)}`,
`${cyan('Followers')}: ${bold(data.followers)}`,
`${cyan('Following')}: ${bold(data.following)}`,
].join('\n'),
{
margin: 1,
float: 'center',
padding: 1,
borderStyle: 'single',
borderColor: 'cyan',
}
);
console.log(output);
})
.catch((exception: any) => {
const error = new GithubCliException({
message: exception.message || exception.info,
}).throwException(true);
});
};
}
<file_sep>import {Octokit} from '@octokit/core';
import {existsSync, readdirSync, readFileSync, statSync} from 'fs';
import inquirer from 'inquirer';
import {basename, join} from 'path';
import {GithubCliException} from '../../exception';
import open from 'open';
interface GistData {
files: Array<string>;
directory: Array<string>;
exclude: Array<string>;
}
export function checkFileExistence(path: string, file: boolean = true) {
try {
const exists = existsSync(path);
if (file) {
const isFile: boolean = statSync(path).isFile();
return exists && isFile;
}
return exists;
} catch (exception: any) {
return false;
}
}
function validateGistFiles(files: GistData): Array<Map<string, string>> {
const includes: Array<Map<string, string>> = new Array<Map<string, string>>();
for (let index = 0; index < files.files.length; index++) {
const filename = files.files[index];
if (checkFileExistence(filename, true)) {
includes.push(
new Map<string, string>([[filename, readFileSync(filename).toString()]])
);
} else {
const error = new GithubCliException({
message: `${filename} does not exist`,
}).throwException(true);
}
}
for (let idx = 0; idx < files.directory.length; idx++) {
const directory = files.directory[idx];
if (checkFileExistence(directory, false)) {
const directoryContent: Array<string> = readdirSync(directory);
console.log(directory, directoryContent);
for (
let contentIndex = 0;
contentIndex < directoryContent.length;
contentIndex++
) {
if (
statSync(join(directory, directoryContent[contentIndex])).isFile()
) {
console.log(directoryContent);
includes.push(
new Map<string, string>([
[
directoryContent[contentIndex],
readFileSync(directoryContent[contentIndex]).toString(),
],
])
);
}
}
} else {
const error = new GithubCliException({
message: `${directory} does not exist`,
}).throwException(true);
}
}
return includes;
}
function createMapObject(files: Array<Map<string, string>>): any {
const map: Map<string, any> = new Map<string, string>();
for (let fileIndex = 0; fileIndex < files.length; fileIndex++) {
const keys = Array.from(files[fileIndex].keys());
for (let idx = 0; idx < keys.length; idx++) {
map.set(basename(keys[idx]), {
content: files[fileIndex].get(keys[idx]),
});
}
}
return {files: Object.fromEntries(map)};
}
export class CreateGists {
private readonly options: Array<any> = [
{type: 'input', name: 'config', message: 'Config file path'},
];
private client: Octokit;
constructor(client: Octokit) {
this.client = client;
this.createQueryPrompt();
}
private createQueryPrompt = (): void => {
inquirer
.prompt(this.options)
.then((response: any) => {
const filename = response.config;
const exists = checkFileExistence(filename);
if (exists) {
const data = readFileSync(filename).toString();
try {
const json: GistData = JSON.parse(data) as GistData;
const validate: any = createMapObject(validateGistFiles(json));
this.client
.request('POST /gists', validate)
.then((response) => {
open(response.data.html_url || '');
})
.catch((error) => {
const exception = new GithubCliException({
message: error.message || error.info,
}).throwException(true);
});
} catch (exception) {
const error = new GithubCliException({
message: exception.info || exception.message,
}).throwException(true);
}
} else {
const error = new GithubCliException({
message: `${filename} does not exist`,
}).throwException(true);
}
})
.catch((error) => {
const exception = new GithubCliException({
message: error,
}).throwException(true);
});
};
}
<file_sep>import {Octokit} from '@octokit/core';
import {GithubCli} from './arguments/parser';
import {KeySetup} from './setup';
import {KeyStorage} from './store';
/**
* @exports
* @function
*
* Returns the api key and if the key doesn't
* exist, run the setup again
*
* @returns {string} The api key
*/
export function createApiKey() {
let key = new KeyStorage().retriveApiKey();
if (!key) {
const setup = new KeySetup(KeyStorage.directory);
key = new KeyStorage().retriveApiKey();
}
return key;
}
export const github = new Octokit({auth: createApiKey()});
const parser = new GithubCli(github);
<file_sep>import {Octokit} from '@octokit/core';
import axios from 'axios';
import {hex, italic, yellow, yellowBright} from 'chalk';
import {table} from 'table';
import {GithubCliException} from '../exception';
import {createLanguageColor} from './colors';
import {GithubRepo} from './interface';
export class GithubUserRepos {
private username: undefined | string;
private organization?: string;
private client: Octokit;
constructor(params: Map<string, string>, octokit: Octokit) {
this.username = params.get('user');
this.organization = params.get('org');
this.client = octokit;
if (this.username && this.organization) {
console.log(
yellowBright(
`Cannot search for user and organization at the same time.
Searching for organization repos`
)
);
}
this.assignUserParameter(this.username);
}
private assignUserParameter = async (
username: string | undefined
): Promise<null | void> => {
const {data} = await this.client.request('/user');
const name = this.organization || this.username || data.login;
const scope: string = this.organization ? 'orgs' : 'users';
const url = `https://api.github.com/${scope}/${name}/repos`;
axios
.get(url)
.then((data) => {
const output: Array<Array<string>> = [
['Name', 'private', 'Stars', 'Language', 'License'],
];
const repos: any = data.data;
for (let index = 0; index < repos.length; index++) {
const currentRepo = repos[index] as GithubRepo;
let language: string =
createLanguageColor(currentRepo.language) || '#FFFFF';
output.push([
italic(currentRepo.name),
currentRepo.private ? 'Yeah' : 'No',
currentRepo.stargazers_count,
hex(language).bold(currentRepo.language || 'Unknown'),
currentRepo.license ? currentRepo.license.name : 'None',
]);
}
console.log(table(output));
})
.catch((exception: any) => {
const error = new GithubCliException({
message: exception.message,
}).throwException(true);
});
};
}
<file_sep>import {Octokit} from '@octokit/core';
import {platform} from 'os';
import { GithubGists } from '../commands/gists/gist';
import {GithubUserRepos} from '../commands/repos';
import {GithubUserData} from '../commands/user/user';
// the list of all the cli commands
// along with the list of flags associated
// with the command
export const commands: Map<string, Array<string>> = new Map<
string,
Array<string>
>([
['repos', ['user', 'org']],
['user', ['user']],
["gists", []]
]);
/**
* @param command The command to execute
* @param params The params passed in
*/
export const performCommand = (
command: string,
params: Map<string, string>,
client: Octokit
) => {
if (command == 'repos') {
const repos = new GithubUserRepos(params, client);
} else if (command == 'user') {
const user = new GithubUserData(params, client);
} else if(command == "gists"){
const gists = new GithubGists(params, client)
}
};
<file_sep>import { basename, dirname, join, sep } from "path";
console.log(dirname(__filename).split(sep).pop())
console.log(join(basename("E:\dev-cli\test\path.ts"), "hehe"))<file_sep>// import { readFileSync } from "fs";
// import { join } from "path";
import {createLanguageColor} from '../commands/colors';
// const data = readFileSync(join(__dirname, "test.json"))
// console.log(JSON.parse(data.toString()))
const data = createLanguageColor('Pythjyjyjon');
console.log(data);
<file_sep>import {existsSync, mkdir, readFileSync, statSync, writeFileSync} from 'fs';
import {join} from 'path';
export class KeyStorage {
// the location of the secrets file containing
// the github user tokens
public static readonly directory: string = join(
__dirname,
'secrets',
'secrets.json'
);
/**
* @public
*
* Get the api key from teh json file fit exists
* else, return null
*
* @returns {string | null} Returns the key if it exists, else returns null
*/
public retriveApiKey = (): string | null => {
const exists = this.checkFileExistence(KeyStorage.directory);
if (!exists) {
mkdir(
join(__dirname, 'secrets'),
(error: NodeJS.ErrnoException | null) => {
if (error) {
throw error;
}
}
);
writeFileSync(KeyStorage.directory, JSON.stringify({}));
return null;
}
const data: Buffer = readFileSync(KeyStorage.directory);
try {
const json: any = JSON.parse(data.toString());
return json.key;
} catch (error: any) {
return null;
}
};
/**
* @private
*
* Checks if the path exists and if the path exists,
* Check if the path is a file based on the
* parameters and return teh results
*
* @param {string} path The path to check if exists or not
* @param {boolean} file Whether to check if the path is an actual file
* @returns {boolean}
*/
private checkFileExistence = (path: string, file: boolean = true) => {
try {
const exists = existsSync(path);
if (file) {
const isFile: boolean = statSync(path).isFile();
return exists && isFile;
}
return exists;
} catch (exception: any) {
return false;
}
};
}
<file_sep># Gist CLI
Create gists from the command line
## How to get started
```sh
# clone the github repository
git clone https://github.com/pranavbaburaj/gist-cli.git gist-cli
# get into the folder
cd gist-cli
npm install
npm install pkg typescript -g
tsc index.ts --outDir=dist
pkg node/index.js
```
## Commands
Run the `gist-cli` to run the setup. Create a new token from the developer settings and pass in as the key
```
gist-cli
```
```sh
# --user is optional. The user parameter
# is set to your current username by default
gist-cli repos --user=<username>
# or
gist-cli user --org=<orgname>
```
```sh
# for users
gist-cli user --user=<username(optional)>
```
### Create a new gist
Create a json file with all the information about the gist
```json
{
"files": [
],
"directory": [
]
}
```
```sh
gist-cli new
```
And pass in the json filename in the prompt
<file_sep>import {join} from 'path';
import {KeySetup} from '../setup';
const setup = new KeySetup(join(__dirname, 'lol.json'));
<file_sep>import {Octokit} from '@octokit/core';
import inquirer from 'inquirer';
import {GithubCliException} from '../../exception';
import {CreateGists} from './new';
const commands: Map<string, Function> = new Map<string, Function>([
[
'Create a new gist',
(client: Octokit) => {
const create = new CreateGists(client);
},
],
]);
function createGistPrompt(queries: any, client: Octokit) {
inquirer
.prompt(queries)
.then((solutions: any) => {
const func: Function | undefined = commands.get(solutions.create);
if (func) {
func(client);
}
})
.catch((error) => {
const exception = new GithubCliException({
message: error.message || error.info,
}).throwException(true);
});
}
export class GithubGists {
private client: Octokit;
private query: any = [
{
type: 'list',
name: 'create',
message: 'Select one',
choices: ['Create a new gist'],
},
];
constructor(params: Map<string, string>, client: Octokit) {
this.client = client;
createGistPrompt(this.query, this.client);
}
}
<file_sep># Clone the github repository and get into the
# directory to install dependencies and build
# the node js program into an executable
git clone https://github.com/pranavbaburaj/gist-cli.git gist-cli
cd gist-cli
# Install all the packages used in the project
npm install
# Install some packages
# pkg - For converting a node js application into an executable
# based on the operating system
# typescript-The typescript package consists of the tsc compiler
# used for compiling typescript into javascript
npm install pkg typescript -g
# Compile the source
tsc index.ts --outDir=dist
# Build the source
pkg node/index.js<file_sep>export interface GithubUser {
login: string;
id: number;
node_id: string;
type: string;
}
export interface GithubRepo {
id: number;
description: string;
node_id: string;
name: string;
private: boolean;
owner: GithubUser;
stargazers_count: number;
watchers_count: number;
language: string | null;
license: any;
}
<file_sep>import {Octokit} from '@octokit/core';
import {writeFileSync} from 'fs';
import {prompt, QuestionCollection} from 'inquirer';
interface InquirerQueryType {
type: string;
name: string;
defualt?: string;
message: string;
}
export class KeySetup {
private static readonly questions: QuestionCollection<any> = new Array({
type: 'password',
name: 'key',
message: 'Enter the api key',
});
private readonly filename: string;
constructor(readonly file: string) {
this.filename = file;
this.createQueryPrompt();
}
private createQueryPrompt = (): void => {
prompt(KeySetup.questions).then((solutions) => {
KeySetup.validateKey(solutions.key, (key: string) => {
writeFileSync(
this.filename,
JSON.stringify({
key: solutions.key,
})
);
});
});
};
public static validateKey = (key: string, callback: Function): any => {
const kit = new Octokit({auth: key});
const data = kit
.request('/user')
.then((data) => {
callback(key);
})
.catch((error: any) => {
console.log('NO');
process.exit();
});
};
}
<file_sep>import {readFileSync} from 'fs';
import {join} from 'path';
// Create the language color based on the language
// passed in as the parameter, data is retrieved from
// [__dirname]/json/data.json
export function createLanguageColor(
language: string | null
): string | undefined {
if (!language) {
return undefined;
}
const path: string = join(__dirname, 'json', 'colors.json');
const data: Buffer = readFileSync(path);
const json: any = JSON.parse(data.toString());
const map: Map<string, string> = new Map<string, string>();
for (const value in json) {
map.set(String(value), json[String(value)]);
}
return map.get(language);
}
|
5c47bdede6195db36f4d7590dec6db14d56b4c24
|
[
"Markdown",
"TypeScript",
"Shell"
] | 16 |
TypeScript
|
pranavbaburaj/gist-cli
|
c6d374bf382ef29d3ca034389b882e480a7e654e
|
c62ff9c1fdf20ad3be444537f85e3147eade23b9
|
refs/heads/master
|
<file_sep>##########################################################################################################
## Coursera Getting and Cleaning Data Course Project
## <NAME>
## 2015-09-27
# run_analysis.r File Description:
# This script will perform the following steps on the UCI HAR Dataset downloaded from
# https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip
# 1. Merge the training and the test sets to create one data set.
# 2. Extract only the measurements on the mean and standard deviation for each measurement.
# 3. Use descriptive activity names to name the activities in the data set
# 4. Appropriately label the data set with descriptive activity names.
# 5. Creates a second, independent tidy data set with the average of each variable for each activity and each subject.
##########################################################################################################
rm(list=ls())
## 1
# Read the files
activity_labels = read.table("./UCI HAR Dataset/activity_labels.txt",header=FALSE);
features = read.table("./UCI HAR Dataset/features.txt",header=FALSE);
testDat_x = read.table("./UCI HAR Dataset/test/X_test.txt",header=FALSE);
testDat_y = read.table("./UCI HAR Dataset/test/y_test.txt",header=FALSE);
subject_test = read.table("./UCI HAR Dataset/test/subject_test.txt",header=FALSE);
trainDat_x = read.table("./UCI HAR Dataset/train/X_train.txt",header=FALSE);
trainDat_y = read.table("./UCI HAR Dataset/train/y_train.txt",header=FALSE);
subject_train = read.table("./UCI HAR Dataset/train/subject_train.txt",header=FALSE);
#Assign column names
colnames(activity_labels) = c('activityId','activityType');
colnames(subject_train) = "subjectId";
colnames(trainDat_x) = features[,2];
colnames(trainDat_y) = "activityId";
colnames(subject_test) = "subjectId";
colnames(testDat_x) = features[,2];
colnames(testDat_y) = "activityId";
#Merge training data
trainDat = cbind(trainDat_y, subject_train, trainDat_x);
#Merge test data
testDat = cbind(testDat_y, subject_test, testDat_x);
#Combine all data sets into a single data set
dat = rbind(trainDat, testDat)
#Creates a vector of column names from dat to select mean and stddev columns
colNames = colnames(dat);
## 2
#Returns TRUE values for ID, mean and stddev columns and false for others
logicalVector = (grepl("activity..",colNames) | grepl("subject..",colNames) |
grepl("-mean..",colNames) & !grepl("-meanFreq..",colNames)
& !grepl("mean..-",colNames) | grepl("-std..",colNames)
& !grepl("-std()..-",colNames));
#Subset our dat for the columns we need
dat = dat[logicalVector==TRUE];
## 3
#Merge dat and activity_labels to include activity names
dat = merge(dat, activity_labels, by = 'activityId', all.x=TRUE);
#Refresh the col names after subset
colNames = colnames(dat);
## 4
# Clean var names
for (i in 1:length(colNames))
{
colNames[i] = gsub("\\()","",colNames[i])
colNames[i] = gsub("-std$","StdDev",colNames[i])
colNames[i] = gsub("-mean","Mean",colNames[i])
colNames[i] = gsub("^(t)","time",colNames[i])
colNames[i] = gsub("^(f)","freq",colNames[i])
colNames[i] = gsub("([Gg]ravity)","Gravity",colNames[i])
colNames[i] = gsub("([Bb]ody[Bb]ody|[Bb]ody)","Body",colNames[i])
colNames[i] = gsub("[Gg]yro","Gyro",colNames[i])
colNames[i] = gsub("AccMag","AccMagnitude",colNames[i])
colNames[i] = gsub("([Bb]odyaccjerkmag)","BodyAccJerkMagnitude",colNames[i])
colNames[i] = gsub("JerkMag","JerkMagnitude",colNames[i])
colNames[i] = gsub("GyroMag","GyroMagnitude",colNames[i])
};
colnames(dat) = colNames;
## 5
#New table, datNoActType without activityType column
datNoActType = dat[,names(dat) != 'activityType'];
#Summarize the datNoActType table to include mean of each var for each activity and each subject
cleandat = aggregate(datNoActType[,names(datNoActType) != c('activityId','subjectId')],
by=list(activityId=datNoActType$activityId,subjectId = datNoActType$subjectId),
mean);
#Merging the tidyData with activityType to include descriptive acitvity names
cleandat = merge(cleandat,activity_labels,by='activityId',all.x=TRUE);
# Export the cleandat set
write.table(cleandat, './tidyData.txt',row.names=TRUE,sep='\t');
|
aa43dfe98ccaeee6eee20de269447bb9ee567d7f
|
[
"R"
] | 1 |
R
|
talleyp/GettingAndCleaning
|
f6127b3a6423c468544413590abcfb0256fe91b4
|
3f4fcc0af7138f87ee61e373c7a56ee0499cf179
|
refs/heads/master
|
<repo_name>fossabot/lolibrary<file_sep>/Makefile
frontend:
docker build --target=build -f ./app/frontend/Dockerfile ./app
frontend-prod:
docker build --target=production -f ./app/frontend/Dockerfile ./app
frontend-test:
docker-compose \
-f docker-compose.test.yml \
-p testing \
up \
--build \
--renew-anon-volumes \
--exit-code-from test \
--abort-on-container-exit \
--remove-orphans
test: frontend-test
build: frontend
production: frontend-prod
.PHONY: build
<file_sep>/app/frontend/app/Console/Commands/RedisWaitCommand.php
<?php
namespace App\Console\Commands;
use Redis;
use App\Console\WaitCommand;
class RedisWaitCommand extends WaitCommand
{
/**
* The name for this command.
*
* @var string
*/
protected const TYPE = 'redis';
/**
* Try to connect to the redis database.
*
* @param string|null $connection
* @return bool
*/
protected function connect(?string $connection): bool
{
try {
Redis::connection($connection)->ping();
return true;
} catch (\Throwable $e) {
return false;
}
}
}
<file_sep>/app/frontend/app/Http/Controllers/Api/TagController.php
<?php
namespace App\Http\Controllers\Api;
use App\Models\Tag;
use Illuminate\Database\Eloquent\Builder;
use App\Http\Requests\Api\TagSearchRequest;
class TagController extends Controller
{
/**
* Get all tags, paginated.
*
* @return \App\Tag[]|\Illuminate\Pagination\LengthAwarePaginator
*/
public function index()
{
return Tag::orderBy('created_at')->paginate(100);
}
/**
* Get a specific category.
*
* @param \App\Tag $tag
* @return \App\Tag
*/
public function show(Tag $tag)
{
return $tag;
}
/**
* Search for a tag.
*
* @param \App\Http\Requests\Api\TagSearchRequest $request
* @return \App\Tag[]|\Illuminate\Pagination\LengthAwarePaginator
*/
public function search(TagSearchRequest $request)
{
return Tag::orderBy('created_at')->where(function (Builder $query) use ($request) {
$query->where('slug', 'ilike', "%{$request->search}%")
->orWhere('slug', 'ilike', "%{$request->search}%");
})->paginate(100);
}
}
<file_sep>/scripts/test.sh
docker-compose -f docker-compose.test.yml run test \
sh -c 'php artisan wait:db \
&& php artisan wait:redis \
&& php artisan migrate:fresh --seed --force --no-interaction \
&& vendor/bin/phpunit --coverage-clover=coverage.xml'
<file_sep>/app/frontend/routes/health.php
<?php
Route::get('/healthz', 'HealthCheckController@index')->name('healthz');
<file_sep>/app/frontend/app/Http/Controllers/HealthCheckController.php
<?php
namespace App\Http\Controllers;
class HealthCheckController extends Controller
{
/**
* Get the health check endpoint.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return response()->json(['alive' => true], 200);
}
}
<file_sep>/app/frontend/app/Console/Commands/DatabaseWaitCommand.php
<?php
namespace App\Console\Commands;
use DB;
use App\Console\WaitCommand;
class DatabaseWaitCommand extends WaitCommand
{
/**
* The name for this command.
*
* @var string
*/
protected const TYPE = 'db';
/**
* Try to connect to the database.
*
* @param string|null $connection
* @return bool
*/
protected function connect(?string $connection): bool
{
try {
$pdo = DB::connection($connection)->getPdo();
return $pdo !== null;
} catch (\Throwable $e) {
return false;
}
}
}
<file_sep>/app/frontend/routes/api.php
<?php
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
/** @var \Illuminate\Routing\Router $router */
$options = ['only' => ['index', 'show']];
$router->get('tags/search', 'TagController@search')->name('tags.search');
$router->resource('tags', 'TagController', $options);
$router->resource('colors', 'ColorController', $options);
$router->resource('brands', 'BrandController', $options);
$router->resource('categories', 'CategoryController', $options);
$router->resource('attributes', 'AttributeController', $options);
$router->resource('features', 'FeatureController', $options);
$router->resource('items', 'ItemController', $options);
$router->post('search', 'SearchController@search')->name('search');
<file_sep>/app/frontend/resources/assets/js/filter.js
import debounce from 'lodash/debounce';
export default class {
constructor(element) {
this.state = {
categories: [],
brands: [],
features: [],
years: [],
colors: [],
tags: [],
search: '',
};
this.element = element;
}
async update(bounce) {
const func = async () => {
await Promise.all([
async () => this.find('categories'),
async () => this.find('brands'),
async () => this.find('features'),
async () => this.find('years'),
async () => this.find('colors'),
async () => this.find('tags'),
async () => this.find('search'),
]);
let event = new CustomEvent('SearchStateUpdated', {
detail: this.state,
});
this.element.dispatchEvent(event);
};
if (bounce) {
debounce(func, 250);
} else {
await func();
}
}
find(id) {
let element = document.getElementById(id);
this.state[id] = $(element).val();
}
}
<file_sep>/app/frontend/app/Console/WaitCommand.php
<?php
namespace App\Console;
use Illuminate\Console\Command;
abstract class WaitCommand extends Command
{
/**
* This command's signature.
*
* @var string
*/
protected $signature = 'wait:#TYPE#
{--timeout=15 : Total seconds to wait until we exit early.}
{--sleep=200 : Milliseconds to usleep between attempts to connect.}
{--connection= : The connection to wait on.}';
/**
* This command's description.
*
* @var string
*/
protected $description = 'Wait for the given #TYPE# connection to become available.';
/**
* If we should terminate our while loop.
*
* @var bool
*/
protected $terminate = false;
/**
* The type to append for this command.
*
* @var string
*/
protected const TYPE = 'invalid';
/**
* Wait for the given service to become available.
*
* @return int The status code response of this command.
*/
public function handle()
{
$sleep = (int) $this->option('sleep');
$connection = $this->option('connection', null);
$this->signal();
while (true) {
if ($this->terminate) {
$this->error(
$this->replaceType('Timeout reached for #TYPE#, exiting.')
);
return 1;
}
if ($this->connect($connection)) {
$this->comment(
$this->replaceType('Connected to #TYPE#.')
);
return 0;
}
$this->comment(
$this->replaceType('Failed to connect to #TYPE#, trying again...')
);
usleep($sleep * 1000);
}
}
/**
* Install signal handlers for SIGALRM.
*
* @return void
*/
protected function signal()
{
$timeout = (int) $this->option('timeout');
pcntl_async_signals(true);
pcntl_signal(SIGALRM, function () {
$this->terminate = true;
});
pcntl_alarm($timeout);
}
/**
* Configure the console command using a fluent definition.
*
* @return void
*/
protected function configureUsingFluentDefinition()
{
$this->signature = $this->replaceType($this->signature);
parent::configureUsingFluentDefinition();
}
/**
* Set this command's description.
*
* @param string $description
* @return void
*/
public function setDescription($description)
{
parent::setDescription($this->replaceType($description));
}
/**
* Replace #TYPE# with static::TYPE in a string.
*
* @param string $str
* @return string
*/
protected function replaceType(string $str)
{
return str_replace('#TYPE#', static::TYPE, $str);
}
/**
* Try to connect to the given database.
*
* @param string|null $connection
* @return bool
*/
abstract protected function connect(?string $connection): bool;
}
<file_sep>/app/frontend/app/Http/Requests/Api/TagSearchRequest.php
<?php
namespace App\Http\Requests\Api;
use Illuminate\Foundation\Http\FormRequest;
/**
* Class TagSearchRequest.
*
* @property string $search
*/
class TagSearchRequest extends FormRequest
{
/**
* Authorize this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the rules for this request.
*
* @return array
*/
public function rules()
{
return [
'search' => 'required|string|min:1,max:30',
];
}
}
|
b51074003bf384682aa8c0748b6e9cf8c5dfb2a8
|
[
"JavaScript",
"Makefile",
"PHP",
"Shell"
] | 11 |
Makefile
|
fossabot/lolibrary
|
692878012a2cb826cbcbaff4f589445ad66ec4c9
|
815cc1941270573ac1bcb1aa10c3116d672dee8c
|
refs/heads/master
|
<repo_name>soraphis/HorrorOma<file_sep>/Assets/Scripts/ElectricalSparksController.cs
using UnityEngine;
using System.Collections;
public class ElectricalSparksController : MonoBehaviour {
const float StartTimer = 0.1f;
float timer = 0;
GameObject [] childs;
// Use this for initialization
void Start () {
var lightnings = GetComponentsInChildren<LightningBolt>();
childs = new GameObject[lightnings.Length];
for(int i = 0; i < lightnings.Length; ++i){
childs[i] = lightnings[i].gameObject;
}
}
// Update is called once per frame
void Update () {
timer -= Time.deltaTime;
if(timer > 0)return;
foreach(GameObject child in childs){
if(Random.value > 0.4f)
child.gameObject.SetActive(false);
else
child.gameObject.SetActive(true);
}
timer = StartTimer;
}
}
<file_sep>/Assets/Scripts/PlayerActionSensor.cs
using System.Collections;
using UnityEngine;
public class PlayerActionSensor : MonoBehaviour {
public float PlayerActionRange = 2.0f;
private int layermask = ~(Physics.IgnoreRaycastLayer | 1 << 4 | 1 << 9);
public GameObject Selected {
private set; get;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
////////////////////// build raycast
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay (new Vector3(Camera.main.pixelWidth / 2, Camera.main.pixelHeight / 2, 0));
GameObject newselect = null;
if (Physics.Raycast (ray, out hit, PlayerActionRange, layermask)) {
//if(hit.distance < PlayerActionRange){
//NotificationText.SimpleScreenText(hit.collider.name, 0.1f);
TriggerObject(hit.collider, out newselect);
//}
}
if (this.Selected != newselect) {
Highlighter h;
if(this.Selected != null){
h = this.Selected.GetComponent<Highlighter> ();
if(h != null) {
h.HighlightToggle(false);
GameObject.FindGameObjectWithTag("UICanvas").GetComponentInChildren<UISelector>().Visible = false;
}
}
if(newselect != null){
h = newselect.GetComponent<Highlighter> ();
if(h != null){
h.HighlightToggle(true);
GameObject.FindGameObjectWithTag("UICanvas").GetComponentInChildren<UISelector>().Visible = true;
}
}
}
this.Selected = newselect;
if (Input.GetButtonDown ("Fire1")) {
//Drop Kiste
if(Player.instance.inhand != null
&& Player.instance.inhand.worldObject != null
&& Player.instance.inhand.handsObject != null){
// Debug.Log (Player.instance.inhand);
if(Player.instance.inhand == Player.instance.BOX){
// drop that shit
Player.instance.inhand.PickDrop();
Player.instance.inhand = null;
return;
}else if(Player.instance.inhand == Player.instance.LAMP
&& (Selected == null || Selected.tag == "Kiste")){
Player.instance.inhand.PickDrop();
Player.instance.inhand = null;
return;
}
}
if (Selected == null)
return;
foreach (var c in Selected.GetComponents(typeof(IViewOver)))
{
((IViewOver)c).fireAction();
}
}
}
void TriggerObject(Collider other, out GameObject newselect){
newselect = null;
if (other.gameObject.layer == 8 // world
|| other.gameObject.layer == 9 // decals
// || other.gameObject.layer == 4 // water
// || other.gameObject.layer == 10 // doodads
)
return;
newselect = other.gameObject;
}
}
<file_sep>/Assets/Scripts/PauseMenu.cs
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class PauseMenu : MonoBehaviour {
[SerializeField] private bool justButtonFunctions = false;
private bool isPause = false;
private FPController fpsc;
// Use this for initialization
void Start () {
GameObject acteuer = GameObject.Find ("Akteuer");
if (acteuer == null) {
justButtonFunctions = true;
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
return;
}
fpsc = acteuer.GetComponent<FPController> ();
Process ();
}
// Update is called once per frame
void Update () {
if (justButtonFunctions)
return;
if (! Input.GetButtonDown ("Cancel"))
return;
Toggle ();
}
private void Process(){
transform.GetChild (0).gameObject.SetActive(isPause);
Time.timeScale = isPause ? 0 : 1;
fpsc.enabled = !isPause;
Cursor.lockState = isPause ? CursorLockMode.None : CursorLockMode.Locked;
Cursor.visible = isPause;
}
public void Toggle(){
isPause = !isPause;
Process ();
}
public void QuitGame(){
Application.Quit ();
}
public void Restart(){
// Application.LoadLevel (0);
SceneManager.LoadScene(0);
}
}
<file_sep>/Assets/Scripts/LampPickup.cs
using UnityEngine;
using System.Collections;
public class LampPickup : MonoBehaviour, IViewOver {
#region IViewOver implementation
public void fireSelect ()
{
}
public void fireAction ()
{
Player.instance.inhand = Player.instance.LAMP;
Player.instance.inhand.PickDrop ();
}
#endregion
}
<file_sep>/Assets/Scripts/WaterColliderHandler.cs
using Assets.Scripts;
using System.Collections;
using UnityEngine;
public class WaterColliderHandler : MonoBehaviour {
private Transform playerfeet;
// Use this for initialization
void Start () {
playerfeet = GameObject.FindWithTag("Player").transform.Find("feet");
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter(Collider other){
if(other.transform == playerfeet){ // player entered water
if(WaterSystem.instance.WaterElectrified)
other.GetComponent<GameOver>().Kill(GameOver.DeathType.ELECTRIFICATION);
else{
FPController fp = GameObject.FindWithTag("Player").GetComponent<FPController>();
fp.WaterSteps = true;
}
}
}
void OnTriggerExit(Collider other){
if(other.transform == playerfeet){ // player entered water
FPController fp = GameObject.FindWithTag("Player").GetComponent<FPController>();
fp.WaterSteps = false;
}
}
}
<file_sep>/Assets/AmbientSound.cs
using UnityEngine;
using System.Collections;
public class AmbientSound : MonoBehaviour {
//public AudioSource mainLoop;
[SerializeField] private AudioClip [] ambientSounds;
[SerializeField] private AudioSource ambientSource;
private const float time = 10f;
private float timer = time;
// Update is called once per frame
void Update () {
timer -= Time.deltaTime;
if(timer > 0) return;
timer = time;
if(ambientSource.isPlaying) return;
if(Random.value < 0.8) return;
ambientSource.clip = ambientSounds[(int)((Random.value * 100) % ambientSounds.Length)];
ambientSource.Play();
}
}
<file_sep>/Assets/Scripts/ViewSystem.cs
using System.Linq;
using UnityEngine;
namespace Assets.Scripts
{
/// <summary>
/// Raycast von der MainCamera nach vorne um alle Scripte die IViewOver implementieren auszuführen.
/// </summary>
class ViewSystem : MonoBehaviour
{
// private Transform _playerCameraTransform;
void Start()
{
// _playerCameraTransform = GameObject.FindGameObjectWithTag("MainCamera").transform;
}
void Update()
{
/*
RaycastHit hit;
Debug.DrawRay (_playerCameraTransform.position, _playerCameraTransform.forward * 3);
if (!Physics.Raycast(new Ray(_playerCameraTransform.position, _playerCameraTransform.forward), out hit)) return;
var scripts = hit.collider.gameObject.GetComponents<MonoBehaviour>();
foreach (var clickable in scripts.OfType<IViewOver>())
{
clickable.OnViewOver(hit.distance);
}
*/
}
}
}
<file_sep>/Assets/Scripts/LightFlicker.cs
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(AudioSource))]
public class LightFlicker : MonoBehaviour {
Light mylight;
float t;
public bool doesFlicker = false;
private bool forced = false;
private AudioSource audioSource;
// Use this for initialization
void Start () {
mylight = this.GetComponent<Light>();
audioSource = this.GetComponentInChildren<AudioSource>();
t = Random.value * 10;
}
// Update is called once per frame
void Update () {
Transform birne = this.transform.parent.FindChild("birne");
Renderer rend = birne.GetComponent<Renderer> ();
if(doesFlicker || forced){
t -= Time.deltaTime;
if(t < 0){
if(this.mylight.enabled){
audioSource.Play();
StartCoroutine(flickerOut());
t = Random.Range(1.3f, 2.8f);
//rend.material.SetColor("_EmissionColor", Color.white*0.8f);
}
else{
this.mylight.enabled = true;
forced = false;
t = Random.Range(4.3f, 6.8f);
//rend.material.SetColor("_EmissionColor", Color.white*0f);
}
}
}
if(this.mylight.enabled){
rend.material.SetColor("_EmissionColor", Color.white*0.8f);
}
else{
rend.material.SetColor("_EmissionColor", Color.white*0f);
}
}
public void ForceFlicker(){ this.ForceFlicker(1); }
// turns the light off
public void ForceFlicker(float seconds){
forced = true;
t = seconds;
audioSource.Play();
StartCoroutine(flickerOut());
}
private IEnumerator flickerOut(){
Transform birne = this.transform.parent.FindChild("birne");
Renderer rend = birne.GetComponent<Renderer> ();
this.mylight.enabled = true;
//rend.material.SetColor("_EmissionColor", Color.white*0f);
for(int i = 0; i < Random.Range(8, 12); ++i){
this.mylight.enabled = !this.mylight.enabled;
if(this.mylight.enabled){
rend.material.SetColor("_EmissionColor", Color.white*0.8f);
}else{
rend.material.SetColor("_EmissionColor", Color.white*0f);
}
yield return new WaitForSeconds(Random.Range(0.03f, 0.1f));
}
this.mylight.enabled = false;
rend.material.SetColor("_EmissionColor", Color.white*0f);
}
}
<file_sep>/Assets/Scripts/FrontDoorTrigger.cs
using System;
#if UNITY_EDITOR
using UnityEditorInternal;
#endif
using UnityEngine;
namespace Assets.Scripts
{
class FrontDoorTrigger : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
if (StateMachine.Instance.State == GameState.FindBox00)
{
if (!other.gameObject.tag.Equals("Kiste")) return;
StateMachine.Instance.State1_BoxAtFrontDoor = true;
}
}
private void OnTriggerExit(Collider other)
{
if (StateMachine.Instance.State == GameState.FindBox00)
{
if (!other.gameObject.tag.Equals("Kiste")) return;
StateMachine.Instance.State1_BoxAtFrontDoor = false;
}
}
}
}<file_sep>/Assets/Scripts/StateMachine.cs
using UnityEngine;
using System.Collections;
public enum GameState{
FindBox00,
FindBoxAgain01,
FindeWerkzeuge02,
WaterBoiler03,
WaterRises04,
SearchExit05
}
public class StateMachine {
private static StateMachine _instance;
private GameState _state;
public delegate void StateChangedHandler(GameState oldState, GameState newState);
public event StateChangedHandler OnStateChanged;
// true on first box pickup
public bool State1_BoxFound = false;
public bool State1_BoxAtFrontDoor = false;
// true on first box pickup after replacement
public bool State2_BoxFound = false;
public GameState State{
get{ return _state; }
set{
if (OnStateChanged != null) {
OnStateChanged(_state, value);
}
_state = value;
}
}
public static StateMachine Instance{
get{
if(_instance == null) {
StateMachine._instance = new StateMachine {State = GameState.FindBox00
};
}
return StateMachine._instance;
}
}
public static void Reset(){
StateMachine._instance = null;
}
protected StateMachine(){}
}
<file_sep>/Assets/SwingToyhorse.cs
using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
public class SwingToyhorse : MonoBehaviour {
private float swingTime = 2.0f; // 2 * pi * sqrt( 1m / 9.81m/s^2) = ~ 2s
private const float maximumDeflection = 30f;
private const float deflectionReduction = 3f;
private float currentDeflection = 0f;
private float timer = 0f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
currentDeflection = Mathf.Max(0, currentDeflection-deflectionReduction*Time.deltaTime);
if(currentDeflection <= 0f) return;
timer += Time.deltaTime;
Vector3 rot = transform.localEulerAngles;
rot.x = currentDeflection * Mathf.Cos(Mathf.PI * timer/swingTime);
transform.localEulerAngles = rot;
}
public void deflect(int amount){
float alpha = ((transform.localEulerAngles.x + 180) % 360) - 180;
currentDeflection = Mathf.Clamp (currentDeflection + amount, 0, maximumDeflection);
timer = Mathf.Acos (alpha / currentDeflection) * swingTime / Mathf.PI;
}
private IEnumerator smoothDeflect(int amount){
for(int i = 0; i < 30; ++i){
currentDeflection = Mathf.Clamp(currentDeflection + amount*1/30f, 0, maximumDeflection);
yield return new WaitForSeconds(1/30f);
}
}
}
<file_sep>/Assets/Scripts/MakePictureCreepy.cs
using UnityEngine;
using System.Collections;
public class MakePictureCreepy : MonoBehaviour {
[SerializeField] private bool creepy = false;
[SerializeField] private float time = 2f;
private Renderer myRenderer;
private bool pause = false;
// [ExecuteInEditMode]
// Use this for initialization
void Start () {
Transform creepyPic = transform.Find ("PictureCreepy");
this.myRenderer = creepyPic.GetComponent<Renderer> ();
}
// Update is called once per frame
void Update () {
float transparency = creepy ? 1 : 0;
Color c = myRenderer.material.color;
if (Mathf.Abs (c.a - transparency) > 0.01f) {
//NotificationText.SimpleScreenText(c.a.ToString(), 0.1f);
c.a += (transparency - (1 - transparency)) * Time.deltaTime / time;
c.a = Mathf.Clamp01 (c.a);
myRenderer.material.color = c;
} else {
pause = true;
}
}
private IEnumerator toggle(){
while (!pause) {
yield return new WaitForSeconds(0.2f);
}
creepy = !creepy;
pause = false;
}
public void ToggleCreepy(){
if (! this.gameObject.activeInHierarchy)
return;
StartCoroutine (toggle ());
}
}
<file_sep>/Assets/Scripts/WaterDrain.cs
using UnityEngine;
using System.Collections;
public class WaterDrain : MonoBehaviour {
void OnTriggerEnter(Collider other){
if(other.gameObject.layer == 4) // water
WaterSystem.instance.WaterOverDrain = true;
}
void OnTriggerExit(Collider other){
if(other.gameObject.layer == 4) // water
WaterSystem.instance.WaterOverDrain = false;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
<file_sep>/README.md
# HorrorOma
## Dependencies
Besuche alle links in `Assets\dependencies.txt`. In Unity öffnen. Herunterladen. Importieren.
Öffne den Asset store in unity (`ctrl + 9`)
<file_sep>/Assets/WrongBoxScript.cs
using UnityEngine;
using System.Collections;
public class WrongBoxScript : MonoBehaviour, IViewOver {
[SerializeField] private string errorMessage;
#region IViewOver implementation
public void fireSelect ()
{
}
public void fireAction ()
{
NotificationText.SimpleScreenText(errorMessage);
}
#endregion
public void ChangeMessage(string msg) {
errorMessage = msg;
}
void Start(){
if(GetComponent<Highlighter>() == null){
gameObject.AddComponent<Highlighter>();
}
}
}
<file_sep>/Assets/Scripts/ElectroColliderHandler.cs
using Assets.Scripts;
using System.Collections;
using UnityEngine;
public class ElectroColliderHandler : MonoBehaviour {
[SerializeField] Fuse WerkraumFuse;
bool deadly = true;
void Update() {
deadly = WerkraumFuse.PowerAble & WerkraumFuse.powered;
for(int i = 0; i < this.transform.childCount; ++i){
this.transform.GetChild(i).gameObject.SetActive(deadly);
}
}
void OnTriggerEnter(Collider other){
if(deadly == false) return;
if(other.CompareTag("Player")){ // player entered water
other.GetComponent<GameOver>().Kill(GameOver.DeathType.ELECTRIFICATION);
}
if(other.gameObject.layer == 4) // water
WaterSystem.instance.WaterElectrified = true;
}
void OnTriggerExit(Collider other){
if(other.gameObject.layer == 4) // water
WaterSystem.instance.WaterElectrified = false;
}
}
<file_sep>/Assets/Scripts/FrontDoor.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace Assets.Scripts
{
class FrontDoor : MonoBehaviour, IViewOver
{
private Vector3 boxStartPosition;
[SerializeField] private GameObject FrontDoorLight;
[SerializeField] private DoodadExchange doodadExchange = null;
public void fireAction()
{
if (StateMachine.Instance.State == GameState.FindBox00) {
if (!StateMachine.Instance.State1_BoxAtFrontDoor) return;
StartCoroutine(DisplayceBox());
StateMachine.Instance.State = GameState.FindBoxAgain01;
doodadExchange.Exchange(2);
doodadExchange.AddDecalLayer(2);
}
}
public void fireSelect()
{
}
IEnumerator DisplayceBox(){
var kiste = GameObject.FindWithTag("Kiste");
LightFlicker lf;
if( FrontDoorLight != null){
lf = FrontDoorLight.GetComponent<LightFlicker>();
lf.ForceFlicker(2);
}
yield return new WaitForSeconds(1.4f);
kiste.transform.localPosition = boxStartPosition;
}
void Start(){
var kiste = GameObject.FindWithTag("Kiste");
boxStartPosition = kiste.transform.localPosition;
}
}
}
<file_sep>/Assets/Scripts/Player.cs
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Player : MonoBehaviour {
public static Player instance {
get;
private set;
}
public delegate void LevelLoadComplete();
public event LevelLoadComplete onLevelLoad;
public GameObject LampLight;
[HideInInspector]
public GameObject Actor;
[HideInInspector]
public Pickable inhand = null;
public Pickable BOX;
public Pickable LAMP;
[SerializeField] private GameObject boxSpots;
private IEnumerator Load(){
// AsyncOperation levelLoader = Application.LoadLevelAdditiveAsync("UIScene");
AsyncOperation levelLoader = SceneManager.LoadSceneAsync("UIScene", LoadSceneMode.Additive);
yield return levelLoader;
if(onLevelLoad != null) onLevelLoad();
}
protected Player (){
}
void Awake(){
Player.instance = this;
StateMachine.Reset();
onLevelLoad += () => {
NotificationText.Initialize();
};
}
void Start(){
StartCoroutine(Load());
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
this.Actor = GameObject.FindGameObjectWithTag("Player");
if (BOX.worldObject.activeSelf) {
Transform t = boxSpots.transform.GetChild((int)((Random.value * 100)%boxSpots.transform.childCount));
BOX.worldObject.transform.position = t.position;
BOX.handsObject.SetActive(false);
}
if (LAMP.worldObject.activeSelf) {
LAMP.handsObject.SetActive(false);
}
Camera.main.clearStencilAfterLightingPass = true;
}
void Update(){
if (LAMP.worldObject.activeSelf) {
LampLight.SetActive (false);
} else {
LampLight.SetActive(true);
}
}
}
<file_sep>/Assets/Scripts/Highlighter.cs
using UnityEngine;
public class Highlighter : MonoBehaviour {
public GameObject Player;
public bool Highlighted { private set; get; }
private HighlightObjects highlightObjects;
// Use this for initialization
void Start () {
highlightObjects = Camera.main.GetComponent<HighlightObjects>();
}
// Update is called once per frame
void Update () {
}
public void HighlightToggle(bool b) {
Highlighted = b;
if(Highlighted) {
highlightObjects.addToHighlight(this.gameObject);
} else {
highlightObjects.removeToHighlight(this.gameObject);
}
}
public void HighlightToggle() {
HighlightToggle(!Highlighted);
}
}
<file_sep>/Assets/OutlineEffect/HighlightObjects.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Rendering;
using UnityStandardAssets.ImageEffects;
public class HighlightObjects : MonoBehaviour {
private RenderTexture hightlightRT;
private RenderTargetIdentifier rtID;
private CommandBuffer buffer;
public Material DrawMaterial;
public Material HighlightMaterial;
private List<GameObject> highlightList = new List<GameObject>();
private BlurOptimized blur;
private Antialiasing antialiasing;
private void CreateBuffers() {
hightlightRT = new RenderTexture(Screen.width, Screen.height, 0);
rtID = new RenderTargetIdentifier(hightlightRT);
buffer = new CommandBuffer();
blur = new BlurOptimized();
blur.blurShader = Shader.Find("Hidden/FastBlur");
blur.blurSize = 0.8f;
blur.blurIterations = 2;
blur.downsample = 2;
blur.blurType = BlurOptimized.BlurType.StandardGauss;
antialiasing = new Antialiasing();
antialiasing.shaderFXAAPreset2 = Shader.Find("Hidden/FXAA Preset 2");
antialiasing.shaderFXAAPreset3 = Shader.Find("Hidden/FXAA Preset 3");
antialiasing.shaderFXAAII = Shader.Find("Hidden/FXAA II");
antialiasing.shaderFXAAIII = Shader.Find("Hidden/FXAA III (Console)");
antialiasing.dlaaShader = Shader.Find("Hidden/DLAA");
antialiasing.ssaaShader = Shader.Find("Hidden/SSAA");
antialiasing.nfaaShader = Shader.Find("Hidden/NFAA");
antialiasing.mode = AAMode.FXAA1PresetA;
}
public void addToHighlight(GameObject obj) {
if(! highlightList.Contains(obj))
highlightList.Add(obj);
}
public void removeToHighlight(GameObject obj) { highlightList.Remove(obj); }
private void RenderHighlights() {
buffer.SetRenderTarget(rtID);
foreach(var o in highlightList) {
Renderer renderer = o.GetComponent<Renderer>();
buffer.DrawRenderer(renderer, DrawMaterial, 0);
}
RenderTexture.active = hightlightRT;
Graphics.ExecuteCommandBuffer(buffer);
RenderTexture.active = null;
}
// Use this for initialization
void Start () {
CreateBuffers();
}
void Update() {
/* highlightList.Clear();
RaycastHit hit;
if (Physics.SphereCast(transform.position, 0.1f, transform.forward, out hit, 3)) {
var ic = hit.collider.gameObject.GetComponent<Interactable>();
if (ic != null) addToHighlight(ic.gameObject);
}*/
}
private void ClearCommandBuffers() {
buffer.Clear();
RenderTexture.active = hightlightRT;
GL.Clear(true, true, Color.clear);
RenderTexture.active = null;
}
private void OnRenderImage(RenderTexture source, RenderTexture destination) {
ClearCommandBuffers();
RenderHighlights();
RenderTexture rt1 = RenderTexture.GetTemporary(Screen.width, Screen.height, 0);
blur.OnRenderImage(hightlightRT, rt1);
//antialiasing.OnRenderImage(rt1, rt1);
HighlightMaterial.SetTexture("_OccludeMap", hightlightRT);
Graphics.Blit(rt1, rt1, HighlightMaterial, 0);
HighlightMaterial.SetTexture("_OccludeMap", rt1);
Graphics.Blit(source, destination, HighlightMaterial, 1);
RenderTexture.ReleaseTemporary(rt1);
}
}
<file_sep>/Assets/Scripts/BoxPickup.cs
using UnityEngine;
using System.Collections;
public class BoxPickup : MonoBehaviour, IViewOver {
#region IViewOver implementation
public void fireSelect ()
{
}
public void fireAction ()
{
Player.instance.inhand = Player.instance.BOX;
Player.instance.inhand.PickDrop ();
}
#endregion
}
<file_sep>/Assets/Scripts/WaterSystem.cs
// using Mono.Xml.Xsl;
using System.Collections;
using UnityEngine;
public class WaterSystem : MonoBehaviour {
public static WaterSystem instance{
get;
private set;
}
protected WaterSystem(){
}
public bool WaterActivated = true; // so lange wahr, bis am rad abgedreht wurde
public bool WaterIncrease1 = false; // wird true, wenn Wasser im Werkraum einlaeuft
public float WaterIncrease1Amount = 2f; // Liter pro sekunde
public bool WaterIncrease2 = false; // wird true, wenn Wasser im Boilerraum einlaeuft
public float WaterIncrease2Amount = 6f; // Liter pro sekunde
public bool WaterDecrease = true; // TODO: false bis abfluss frei
public bool WaterOverDrain = false; // true wenn wasser oberhalb des abflusses ist
public float WaterDecreaseAmount = 4f; // Liter pro Sekunde
public float MaxLitre = 600;
public AnimationCurve AreaOverLitre = null;
public GameObject Water = null;
public float WaterAmount = 0f;
private float MaxHeight;
private float WaterBaseHeight;
public bool WaterElectrified = false;
void Awake(){
WaterSystem.instance = this;
}
// Use this for initialization
void Start () {
if(Water == null){
Debug.LogError("Water is not set to an instance of an object");
return;
}
GameObject player = GameObject.FindGameObjectWithTag("Player");
MaxHeight = (player.transform.position - Water.transform.position).y;
WaterBaseHeight = Water.transform.position.y;
}
// Update is called once per frame
void Update () {
if(Water == null) return; // do not spam errors
if(WaterActivated){
if(WaterIncrease1){
WaterAmount += WaterIncrease1Amount * Time.deltaTime;
}
if(WaterIncrease2){
WaterAmount += WaterIncrease2Amount * Time.deltaTime;
}
}
if(WaterDecrease && WaterOverDrain){
WaterAmount -= WaterDecreaseAmount * Time.deltaTime;
}
float percentual = WaterAmount / MaxLitre;
Vector3 w = Water.transform.position;
w.y = WaterBaseHeight + AreaOverLitre.Evaluate(percentual) * MaxHeight;
Water.transform.position = w;
}
}
<file_sep>/Assets/Scripts/IntroScript.cs
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class IntroScript : MonoBehaviour {
[SerializeField] private Image[] images;
[SerializeField] private float[] times;
private int current = 0;
void Update() {
if (current >= times.Length) {
LevelLoader.instance.ConditionToLoad = true;
this.enabled = false;
return;
}
times[current] -= Time.deltaTime;
if (times[current] < -1) {
current++;
return;
}
if (times[current] < 0) {
Color c = images[current].color;
c.a = -times[current];
images[current].color = c;
}
}
}
<file_sep>/Assets/Scripts/Pickable.cs
using UnityEngine;
using System.Collections;
using System;
[Serializable]
public class Pickable {
public GameObject handsObject;
public GameObject worldObject;
/*if (worldObject.activeSelf) {
handsObject.SetActive(false);
}*/
public Pickable(GameObject world, GameObject hand){
this.handsObject = hand;
this.worldObject = world;
Debug.Log ("new pickable created with: " + world + " " + hand);
}
// toggles current state
public void PickDrop(){
if (handsObject.activeSelf) {
Drop ();
Physics.IgnoreCollision(this.worldObject.GetComponent<Collider>(),
Player.instance.Actor.GetComponent<Collider>());
} else {
Pick ();
}
}
private void Pick(){
worldObject.SetActive (false);
handsObject.SetActive (true);
}
private void Drop(){
worldObject.SetActive (true);
handsObject.SetActive (false);
worldObject.transform.position = handsObject.transform.position;
worldObject.transform.rotation = handsObject.transform.rotation;
Rigidbody rb = worldObject.GetComponent<Rigidbody>();
if(rb != null){
Transform t = Camera.main.transform;
rb.AddForce(t.forward * 2.8f, ForceMode.Impulse);
}
}
}
<file_sep>/Assets/Scripts/LightKnockOut.cs
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
// Use this for initialization
class LightKnockOut : MonoBehaviour, IViewOver
{
#region IViewOver implementation
public void fireSelect ()
{
}
public void fireAction ()
{
foreach (Fuse fuse in fuses) {
fuse.PowerAble = !fuse.PowerAble;
fuse.RefreshItems();
}
// nicht gut!
if (StateMachine.Instance.State == GameState.WaterBoiler03){
GetComponent<AudioSource>().Play();
if(Boiler != null)
Boiler.GetComponent<BoilerExplode>().Sleep = false;
}
}
#endregion
public GameObject Boiler = null;
// contains all lamps which may have multiple lightobjects
public Fuse[] fuses = null;
}<file_sep>/Assets/Scripts/FrontDoorHandle.cs
using System.Collections;
using UnityEngine;
public class FrontDoorHandle : MonoBehaviour, IViewOver {
#region IViewOver implementation
public void fireSelect ()
{
}
public void fireAction ()
{
if(StateMachine.Instance.State == GameState.FindBox00 || !StateMachine.Instance.State2_BoxFound)
NotificationText.SimpleScreenText("(Ich sollte den Keller nicht ohne Kiste verlassen)");
else
NotificationText.SimpleScreenText("(Die Tür ist verschraubt, ich muss sie irgendwie öffnen)");
}
#endregion
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
<file_sep>/Assets/Scripts/GameOver.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityStandardAssets.Water;
namespace Assets.Scripts
{
class GameOver : MonoBehaviour
{
public Transform Water = null;
public Transform Boiler = null;
public Sprite TotBoxErtrunkenSprite = null;
public Sprite TotErtrunkenSprite = null;
public Sprite TotExplosionSprite = null;
public Sprite TotStromSprite = null;
private Transform player;
private Image gameOverImage;
public void KisteDestroyedUnderwater()
{
ShowDeathScreen(TotBoxErtrunkenSprite);
}
void Start()
{
player = GameObject.FindGameObjectWithTag("Player").transform;
Player.instance.onLevelLoad += UISceneLoaded;
StateMachine.Instance.OnStateChanged += ExplosionNow;
}
void Update()
{
}
private void ExplosionNow(GameState oldState, GameState newState)
{
if (newState != GameState.WaterRises04) return;
// Tod per Explosion
if (Vector3.Distance(player.position, Boiler.position) <= 10f)
{
Kill(DeathType.EXPLOSION);
}
}
void ShowDeathScreen(Sprite sprite)
{
player.gameObject.GetComponent<FPController>().enabled = false;
gameOverImage.sprite = sprite;
gameOverImage.color = Color.white;
Invoke("LoadAgain", 3);
}
void LoadAgain()
{
SceneManager.LoadScene(0);
}
void UISceneLoaded()
{
GameObject canvas = GameObject.FindGameObjectWithTag("UICanvas");
//foreach(Transform t in canvas.GetComponentsInChildren<Transform>()){
// Debug.Log(t.gameObject.name);
//}
gameOverImage = canvas.transform.Find("ImageForWinOrLose").GetComponent<Image>();
}
public enum DeathType{
EXPLOSION, HEARTHATTACK, DROWNING, ELECTRIFICATION
}
public void Kill(DeathType By) {
switch (By){
case(DeathType.ELECTRIFICATION):
ShowDeathScreen(TotStromSprite);
break;
case(DeathType.EXPLOSION):
ShowDeathScreen(TotExplosionSprite);
break;
// FIXME! - add more
default:
ShowDeathScreen(TotErtrunkenSprite);
break;
}
}
}
}
<file_sep>/Assets/Scripts/BoilerExplode.cs
using Assets.Scripts;
using System.Collections;
#if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEngine;
public class BoilerExplode : MonoBehaviour {
public bool Sleep = true;
private float countDown = 5;
[SerializeField] private GameObject SecretWall;
[SerializeField] private GameObject Stairs;
[SerializeField] private GameObject StairsBroken;
[SerializeField] private AudioClip ExplodeClip;
private AudioSource audioSource;
void Start(){
if(Stairs == null || StairsBroken == null){
Debug.Log("BoilerExplode.cs: Stairs is not Set");
}
audioSource = GetComponent<AudioSource>();
}
void Update(){
if (Sleep)
return;
if(StateMachine.Instance.State == GameState.WaterBoiler03){
countDown -= Time.deltaTime;
if (countDown <= 0) {
Explode();
}
}
}
public void IncreaseAudioPitch(float amount){
StartCoroutine(AudioPitchCoroutine(amount));
}
private IEnumerator AudioPitchCoroutine(float seconds){
float f = 0;
while (f < seconds){
f += Time.deltaTime;
audioSource.pitch *= 1.001f;
yield return null;
}
}
// public because there are multiple ways to let it explode
public void Explode(){
AudioSource.PlayClipAtPoint(ExplodeClip, transform.position);
GetComponentInChildren<AudioSource>().Play();
Stairs.SetActive(false);
StairsBroken.SetActive(true);
SecretWall.SetActive(false);
StateMachine.Instance.State = GameState.SearchExit05;
WaterSystem.instance.WaterIncrease2 = true;
Destroy(this.gameObject); // destroying this gameObject -> stopping all sounds from emiting and all scripts from executing
Sleep = true; // should not be necessary
}
#if UNITY_EDITOR
void OnDrawGizmos(){
Gizmos.DrawLine (this.transform.position, this.transform.position + Vector3.up * countDown / 10F);
}
#endif
}
<file_sep>/Assets/Scripts/DoorTrigger.cs
using UnityEngine;
/*
* Place this at the door handle
*/
public class DoorTrigger : MonoBehaviour, IViewOver {
#region IViewOver implementation
public void fireSelect ()
{
}
public void fireAction ()
{
this.Door.GetComponent<DoorOpen>().Trigger();
}
#endregion
public GameObject Door;
void Start(){
this.Door = this.transform.parent.Find("Tuer").gameObject;
}
}
<file_sep>/Assets/Scripts/Fuse.cs
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
using System.Collections;
public class Fuse : MonoBehaviour {
private Color offColor = new Color(200,0,0);
private Color onColor = new Color(0, 200, 0);
private bool _powered = false;
public bool PowerAble = true;
public bool IsOnAtStart;
public bool powered {
get {
return _powered;
}
set {
_powered = value;
RefreshItems();
}
}
private void UpdateLighswitchesLight()
{
foreach (Transform child in transform)
{
if(child == null) continue;
var lightTransform = child.Find("light");
if(lightTransform == null) continue;
if (lightTransform != null)
{
if (powered)
{
var mats = lightTransform.GetComponent<Renderer>().materials;
mats[0].SetColor("_Color", onColor);
mats[0].SetColor("_EmissionColor", onColor);
}
else
{
var mat = lightTransform.GetComponent<MeshRenderer>().material;
mat.SetColor("_Color", offColor);
mat.SetColor("_EmissionColor", offColor);
}
}
}
}
public GameObject[] Lights = null;
public void RefreshItems()
{
foreach (var myGameObject in Lights)
{
if(myGameObject == null) continue;
// each lightsorce (pointlight, spotlight, ...)
foreach (var myLight in myGameObject.GetComponentsInChildren<Light>(true))
{
myLight.enabled = _powered & PowerAble;
}
foreach(LightFlicker flicker in myGameObject.GetComponentsInChildren<LightFlicker>(true)){
flicker.enabled = _powered & PowerAble;
}
Transform birne = myGameObject.transform.FindChild("birne");
if(birne == null) continue;
Renderer rend = birne.GetComponent<Renderer>();
if(_powered & PowerAble){
//DynamicGI.SetEmissive(rend, Color.red * 0.8f);
rend.material.SetColor("_EmissionColor", Color.white*0.8f);
//
}else{
//DynamicGI.SetEmissive(rend, Color.green * 0f);
rend.material.SetColor("_EmissionColor", Color.white*0f);
}
DynamicGI.UpdateMaterials(rend);
}
UpdateLighswitchesLight();
}
void Start()
{
if (IsOnAtStart)
{
_powered = true;
UpdateLighswitchesLight();
}
else
{
RefreshItems();
}
}
#if UNITY_EDITOR
void OnDrawGizmosSelected(){
Gizmos.color = Color.cyan;
foreach (var l in Lights) {
if(l != null){
Gizmos.DrawLine (this.transform.position, l.transform.position);
}
}
}
#endif
}
<file_sep>/Assets/Scripts/UISelector.cs
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class UISelector : MonoBehaviour {
private void Fade(float f){
Color c = image.color;
Vector3 s = transform.localScale;
c.a = f;
s.x = 1+(1-f);
s.y = 1+(1-f);
image.color = c;
transform.localScale = s;
}
private IEnumerator FadeOut(){
for(float f = 1f; f >= 0.1f; f -= 0.1f){
Fade(f);
yield return null;
}
Fade(0.1f);
}
private IEnumerator FadeIn(){
for(float f = 0f; f <= 1; f += 0.1f){
Fade(f);
yield return null;
}
Fade(1f);
}
private bool visible = true;
public bool Visible{
get{ return visible; }
set{
if(value != visible){
if(value){StartCoroutine("FadeIn");}
else{ StartCoroutine("FadeOut"); }
}
visible = value;
}
}
Image image;
// Use this for initialization
void Start () {
image = GetComponent<Image>();
Visible = false; // Visible setter function!
}
// Update is called once per frame
void Update () {
}
}
<file_sep>/Assets/Scripts/FrontDoorScrewed.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace Assets.Scripts
{
internal class FrontDoorScrewed : MonoBehaviour
{
public Transform FrontDoor = null;
public AudioClip Audio = null;
public GameObject[] Holzbretter = null;
void OnTriggerEnter(Collider other)
{
if (StateMachine.Instance.State != GameState.FindBoxAgain01 || Player.instance.inhand != Player.instance.BOX)
return;
DoorOpen d = FrontDoor.GetComponentInChildren<DoorOpen>();
if(d.Open) d.Trigger();
d.locked = true;
AudioSource.PlayClipAtPoint(Audio, this.FrontDoor.position);
foreach (var holzbrett in Holzbretter)
{
holzbrett.SetActive(true);
}
StateMachine.Instance.State = GameState.FindeWerkzeuge02;
Destroy(gameObject);
}
}
}
<file_sep>/Assets/Scripts/DoodadExchange.cs
using UnityEngine;
using System.Collections;
public class DoodadExchange : MonoBehaviour {
[SerializeField] private GameObject GeruempelraumDoodadWrapper = null;
[SerializeField] private GameObject DecalWrapper = null;
// Use this for initialization
void Start () {
}
public void AddDecalLayer(int layer){
for(int i = 0; i < DecalWrapper.transform.childCount; ++i){
Transform room = DecalWrapper.transform.GetChild(i);
if(room == null) continue;
Transform layerObj = room.Find(layer.ToString());
if(layerObj != null) layerObj.gameObject.SetActive(true);
layerObj = room.Find(string.Format("{0} off", layer));
if(layerObj != null) layerObj.gameObject.SetActive(false);
}
}
public void Exchange(int newStateNumber){
GeruempelraumDoodadWrapper.transform.Find (((int)(newStateNumber - 1)).ToString()).gameObject.SetActive (false);
GeruempelraumDoodadWrapper.transform.Find (newStateNumber.ToString()).gameObject.SetActive (true);
}
}
<file_sep>/Assets/WaterPipeLeak.cs
using UnityEngine;
using System.Collections;
public class WaterPipeLeak : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
this.GetComponent<ParticleEmitter>().enabled = WaterSystem.instance.WaterActivated;
this.GetComponent<ParticleRenderer>().enabled = WaterSystem.instance.WaterActivated;
}
}
<file_sep>/Assets/Scripts/LightExplode.cs
using UnityEngine;
using System.Collections;
public class LightExplode : MonoBehaviour {
private Light myLight;
[SerializeField] private AudioClip breakbulb;
// Use this for initialization
void Start () {
myLight = transform.Find("Point light").GetComponent<Light>();
}
// Update is called once per frame
void Update () {
}
public void Explode(){
StartCoroutine(ExplodeRoutine());
}
private IEnumerator ExplodeRoutine(){
for(int i = 0; i < 10; ++i){
myLight.intensity += 1f;
yield return null;
}
yield return new WaitForSeconds(0.1f);
AudioSource.PlayClipAtPoint(breakbulb, transform.position);
Destroy(this.gameObject);
}
}
<file_sep>/Assets/Scripts/RenderedTrigger.cs
using UnityEngine;
using UnityEngine.UI;
public class RenderedTrigger : MonoBehaviour{
public delegate void looked();
public event looked OnWatchStart;
public event looked OnWatchStop;
private bool isRendered = false;
private bool isLookedAt = false;
private GameObject canvas;
private Color col;
public Renderer rend;
public bool checkLineOfSight = false;
public float maxRange = 15f;
void Start (){
rend = GetComponent<Renderer>();
col = Color.white;
}
void Update () {
if(isRendered) UpdateRendered();
}
void OnDrawGizmos(){
Vector3 center = rend.bounds.center;
float radius = rend.bounds.extents.magnitude;
Gizmos.color = col;
Gizmos.DrawWireSphere(center, radius);
}
void UpdateRendered(){
Vector3 center = rend.bounds.center;
float radius = rend.bounds.extents.magnitude;
Vector3 screenPosCenter = Camera.main.WorldToScreenPoint(center);
screenPosCenter.z = 0;
Vector3 screenPosEdge = Camera.main.WorldToScreenPoint(center + new Vector3(radius, 0 ,0));
float screenradius = Vector3.Distance(screenPosCenter, screenPosEdge);
if(screenradius*2 > 40 ){ // px
// large enough to be looked at
col = Color.blue;
screenPosCenter.x = (screenPosCenter.x - Camera.main.pixelWidth/2 );
screenPosCenter.y = (screenPosCenter.y - Camera.main.pixelHeight/2);
if (Mathf.Abs(screenPosCenter.x) < screenradius &&
Mathf.Abs(screenPosCenter.y) < screenradius ){
// centered enough
col = Color.red;
/// line of sight free?
bool b = false;
if(checkLineOfSight){
RaycastHit hit;
if(Physics.Raycast(Camera.main.transform.position,
this.transform.position - Camera.main.transform.position, out hit, maxRange)){
if(hit.transform == this.transform){
b = true;
}
}
}else{
b = true;
}
if(b && isLookedAt == false){
if(OnWatchStart != null) OnWatchStart();
isLookedAt = true;
}
}else if(isLookedAt == true){
if(OnWatchStop != null) OnWatchStop();
isLookedAt = false;
}
}else{
col = Color.white;
if(isLookedAt == true){
if(OnWatchStop != null) OnWatchStop();
isLookedAt = false;
}
}
}
void OnBecameVisible(){
isRendered = true;
}
void OnBecameInvisible() {
isRendered = false;
if(isLookedAt == true){
if(OnWatchStop != null) OnWatchStop();
isLookedAt = false;
}
}
}
<file_sep>/Assets/Scripts/FinalTriggerZone.cs
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class FinalTriggerZone : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter(Collider other) {
if (other.CompareTag ("Player")) {
if(StateMachine.Instance.State == GameState.SearchExit05){
// Application.LoadLevel("Credits");
SceneManager.LoadScene("Credits");
}else{
Debug.Log ("Cheater");
}
}
}
}
<file_sep>/Assets/BoxGameStateController.cs
using System.Collections;
using UnityEngine;
public class BoxGameStateController : MonoBehaviour , IViewOver
{
#region IViewOver implementation
public void fireSelect ()
{
}
public void fireAction ()
{
if (StateMachine.Instance.State == GameState.FindBox00){
StateMachine.Instance.State1_BoxFound = true;
}else if (StateMachine.Instance.State == GameState.FindBoxAgain01){
StateMachine.Instance.State2_BoxFound = true;
Destroy(this);
}
}
#endregion
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
<file_sep>/Assets/dummy.cs
using System.Collections;
using UnityEngine;
public class dummy : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.B)){
Rigidbody rb = this.GetComponent<Rigidbody>();
rb.AddExplosionForce(300*Random.value*4, new Vector3(0.85f + Random.value, 0f, -1.95f - Random.value*3), 20+Random.value*6);
}
}
}
<file_sep>/Assets/Scripts/LightSwitch.cs
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace Assets.Scripts
{
internal class LightSwitch : MonoBehaviour, IViewOver
{
#region IViewOver implementation
public void fireSelect ()
{
}
public void fireAction ()
{
foreach (Fuse fuse in fuses) {
fuse.powered = !fuse.powered;
}
GetComponent<AudioSource>().Play();
}
#endregion
// contains all lamps which may have multiple lightobjects
public Fuse[] fuses = null;
#if UNITY_EDITOR
void OnDrawGizmosSelected(){
Gizmos.color = Color.yellow;
foreach (var l in fuses)
//Handles.DrawLine (this.transform.position, l.transform.position);
Gizmos.DrawLine (this.transform.position, l.transform.position);
}
#endif
}
}<file_sep>/Assets/Scripts/DoorOpen.cs
using UnityEngine;
using System.Collections;
/*
* Place this at the door
*/
public class DoorOpen : MonoBehaviour{
private bool open = false;
private bool closed = true; // for simple sound controll
private float smooth = 1f;
private static float OPENTIME = 1.4f; // seconds
private float time = 0.0f;
public static float doorspeed = 0.1f;
public bool locked = false;
private AudioSource audioSource;
public AudioClip dooropen;
public AudioClip doorclose;
public AudioClip doorlocked;
private bool sleep = true;
private Quaternion startRotation;
private Quaternion closedRotation;
private Quaternion openedRotation;
private Transform parent;
public bool Open{
get{ return open; }
private set{ open = value; if(open) locked = false; }
}
public void Trigger(){
if (!open && locked) {
if(doorlocked != null && ! audioSource.isPlaying){
audioSource.PlayOneShot(doorlocked);
}
return;
}
sleep = false;
time = 0.0f;
open = !open;
startRotation = parent.transform.rotation;
}
// triggers if door is not @param open
public void ConditionalTrigger(bool open){
if(this.open != open) Trigger();
}
void Start () {
this.parent = this.transform.parent.parent;
startRotation = parent.transform.rotation * Quaternion.identity;
openedRotation = startRotation * Quaternion.Euler (0, 80, 0);
closedRotation = startRotation * Quaternion.identity;
audioSource = this.GetComponent<AudioSource> ();
}
/**
* Closes/Openes door without animation
*/
public void ForceSet(bool open){
Open = open;
Quaternion doorNew = this.open ? openedRotation
: closedRotation;
parent.transform.rotation = doorNew;
startRotation = parent.transform.rotation;
sleep = true;
time = 0.0f;
}
// helper function for unityevents
public void Lock(bool doorlocked){
this.locked = doorlocked;
}
void Update () {
if(sleep) return;
Quaternion doorNew = Open ? openedRotation
: closedRotation;
float angle = Quaternion.Angle (startRotation, doorNew);
if (Open && closed) {
if(dooropen != null && ! audioSource.isPlaying){
audioSource.PlayOneShot(dooropen);
}
closed = false;
}
time += Time.deltaTime * smooth;
float f = time/(OPENTIME - OPENTIME * (1.001f - angle/80f));
parent.transform.rotation = Quaternion.Slerp (startRotation, doorNew, f);
if(f >= 0.9){
if(!Open & !closed){
closed = true;
if(doorclose != null && ! audioSource.isPlaying){
audioSource.PlayOneShot(doorclose);
}
}
}
if(f >= 0.99){
//if (angle <= smooth) {
parent.transform.rotation = doorNew;
startRotation = parent.transform.rotation;
sleep = true;
time = 0.0f;
}
}
}
<file_sep>/Assets/Scripts/LevelLoader.cs
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.SceneManagement;
public class LevelLoader : MonoBehaviour {
public static LevelLoader instance;
private AsyncOperation async = null;
[SerializeField] GameObject ProgressCircle;
private Image image;
public bool ConditionToLoad = false;
public static void LoadLevel(int index){ instance.StartCoroutine(instance.Load (index)); }
public static void LoadLevel(string name){ instance.StartCoroutine(instance.Load (name)); }
private IEnumerator Load(int index){
yield return new WaitForSeconds(1);
async = SceneManager.LoadSceneAsync(index);
async.allowSceneActivation = false;
image.fillAmount = 0;
while (!async.isDone) {
image.fillAmount = async.progress / 0.91f;
if (Input.GetKeyDown(KeyCode.Escape) || ConditionToLoad){
ConditionToLoad = true;
async.allowSceneActivation = true;
}
yield return null;
}
image.fillAmount = 1;
Debug.Log("level loaded complete");
yield return new WaitForSeconds(0.8f);
}
private IEnumerator Load(string lvlname){ // todo: cleanup this copy&paste
yield return new WaitForSeconds(1);
async = SceneManager.LoadSceneAsync(lvlname);
async.allowSceneActivation = false;
async.priority = 10;
image.fillAmount = 0;
while (!async.isDone) {
image.fillAmount = async.progress / 0.9f;
Debug.Log(image.fillAmount);
yield return null;
}
image.fillAmount = 1;
Debug.Log("level loaded complete");
yield return null;
}
void Awake(){
if (LevelLoader.instance != null) {
Destroy (this);
return;
}
LevelLoader.instance = this;
}
// Use this for initialization
void Start () {
image = ProgressCircle.GetComponent<Image> ();
LevelLoader.LoadLevel (1);
}
// Update is called once per frame
void Update () {
}
}
<file_sep>/Assets/Editor/EditorTools.cs
using System;
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
public class EditorTools : Editor{
[MenuItem("Custom/Set Decal Layer")]
static void DecalFix(){
Decal [] all = (Decal[])FindObjectsOfType(typeof(Decal));
foreach (Decal d in all) {
d.affectedLayers = 1 << 5;
}
}
[MenuItem("Custom/RemoveHideFlags")]
static void RemoveHideFlags() {
Selection.activeObject.hideFlags = HideFlags.None;
}
[MenuItem("Custom/Orient On Ground")]
static void OrientOnGround(){
Transform t = Selection.activeGameObject.transform;
RaycastHit hit;
int layermask = (1 | 1 << 8 | 1 << 10);
if(Physics.Raycast(t.position, Vector3.down, out hit, 0.8f, layermask)){
RaycastHit hit2;
if(Physics.Raycast(hit.point, Vector3.up, out hit2, 0.8f, layermask)){
Vector3 pos = t.position;
pos.y -= hit2.distance;
t.position = pos;
}
}
}
[MenuItem("Custom/Load Scene Additive")]
static void Apply(){
String scenepath = AssetDatabase.GetAssetOrScenePath(Selection.activeObject);
if(scenepath == null || !scenepath.Contains(".unity")){
EditorUtility.DisplayDialog("Select Scene", "You Must Select a Scene!", "OK");
EditorApplication.Beep();
return;
}
Debug.Log("Opening " + scenepath + " additively");
//EditorApplication.OpenSceneAdditive(scenepath);
SceneManager.LoadScene(scenepath, LoadSceneMode.Additive);
}
[MenuItem("Custom/ProBuilder/Actions/Force Refresh Objects")]
public static void Inuit()
{
pb_Object[] all = (pb_Object[])FindObjectsOfType(typeof(pb_Object));
foreach(pb_Object pb in all)
pb.MakeUnique();
}
public override void OnInspectorGUI ()
{
// Draw the default inspector
DrawDefaultInspector();
TrigZone tg = (TrigZone)target;
tg.EnterObjectTag = EditorGUILayout.TagField("" , tg.EnterObjectTag);
// Save the changes back to the object
EditorUtility.SetDirty(target);
}
}
<file_sep>/Assets/Scripts/IViewOver.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/// <summary>
/// Wird von ViewSystem aufgrufen wenn die Camera auf das Objekt sieht.
/// </summary>
interface IViewOver
{
void fireSelect(); // fired when object is viewed
void fireAction(); // fired when object is clicked
}
<file_sep>/Assets/Scripts/WaterMainValve.cs
using System.Collections;
using UnityEngine;
public class WaterMainValve : MonoBehaviour, IViewOver {
#region IViewOver implementation
public void fireSelect ()
{
}
public void fireAction ()
{
if(! rotating){
WaterSystem.instance.WaterActivated = !WaterSystem.instance.WaterActivated;
this.GetComponent<AudioSource>().Play();
StartCoroutine(rotate());
}
}
#endregion
private IEnumerator rotate(){
int dir = WaterSystem.instance.WaterActivated ? 1 : -1;
this.rotating = true;
this.GetComponent<Highlighter>().enabled = false;
for(int i = 0; i < 100; ++i){
this.transform.Rotate(Vector3.forward, dir * 30 * Time.deltaTime);
yield return null;
}
this.GetComponent<Highlighter>().enabled = true;
this.rotating = false;
}
private bool rotating = false;
}
<file_sep>/Assets/boxOutOfRegal.cs
using UnityEngine;
using System.Collections;
public class boxOutOfRegal : MonoBehaviour {
private Transform actor;
private bool throwAble;
// Use this for initialization
void Start () {
actor = GameObject.Find("Akteuer").transform;
throwAble = true;
}
// Update is called once per frame
void Update () {
var dist = Vector3.Distance(actor.position, transform.position);
if (throwAble) {
if (dist < 10) {
Wurf ();
/*
Vector3 posAct = actor.position + new Vector3(1F,0F,0F);
transform.position = Vector3.MoveTowards (transform.position, posAct, 0.01F);
transform.LookAt(actor);
**/
}
}
}
void Wurf(){
Rigidbody myRigidbody = GetComponent<Rigidbody> ();
myRigidbody.AddForce(Vector3.forward * 2, ForceMode.Impulse);
throwAble = false;
}
}
<file_sep>/Assets/Scripts/WaterDamage.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace Assets.Scripts
{
class WaterDamage : MonoBehaviour
{
public GameObject Water = null;
internal class Variablen {
protected internal float DamagePerSecond = 0.2f;
protected internal float Health = 1.0f;
private static Variablen instance;
private Variablen() { }
public static Variablen Instance
{
get
{
if (instance == null)
{
instance = new Variablen();
}
return instance;
}
}
}
protected internal Variablen Vars = Variablen.Instance;
void OnTriggerEnter(Collider other)
{
if (other.gameObject.layer == LayerMask.NameToLayer("Water"))
{
TakeDamage();
}
}
void OnTriggerStay(Collider other)
{
if (other.gameObject.layer == LayerMask.NameToLayer("Water"))
{
TakeDamage();
}
}
void TakeDamage()
{
Vars.Health -= Time.deltaTime * Vars.DamagePerSecond;
if (Vars.Health <= 0)
{
GameObject.FindWithTag("Player").GetComponent<GameOver>().KisteDestroyedUnderwater();
}
}
}
}
<file_sep>/Assets/Scripts/MirrorCam.cs
using UnityEngine;
using System.Collections;
public class MirrorCam : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Vector3 v = Camera.main.transform.position - transform.parent.position;
Vector3 r = 2 * Vector3.Dot(v, transform.parent.up)*transform.parent.up - v;
this.transform.LookAt(transform.parent.position + r);
}
}
<file_sep>/Assets/Scripts/NotificationText.cs
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;
using UnityEngine.UI;
public class NotificationText{
private static GameObject TextPrefab;
private static GameObject Canvas;
private static List<GameObject> notes = new List<GameObject>();
public static void Initialize(){
TextPrefab = (GameObject)Resources.Load("Prefabs/Text");
Canvas = GameObject.FindGameObjectWithTag("UICanvas");
}
public static void SimpleScreenText(String text){
SimpleScreenText (text, 3.0f);
}
public static void SimpleScreenText(String text, float seconds){
GameObject str = UnityEngine.Object.Instantiate(TextPrefab);
str.transform.SetParent(Canvas.transform);
str.GetComponent<Text>().text = text;
str.GetComponent<EventHandler>().OnDestroyCallback += () => { notes.Remove(str); Rearrange(); };
notes.Add(str);
Rearrange();
UnityEngine.Object.Destroy(str, seconds);
}
private static void Rearrange(){
float y = -15;
foreach (var note in notes){
Vector3 v = ((RectTransform)note.transform).anchoredPosition;
v.y = y;
v.x = 100;
((RectTransform)note.transform).anchoredPosition = v;
y -= 30;
}
}
}
<file_sep>/Assets/Scripts/OutlineScript.cs
using UnityEngine;
using System.Collections;
/*
public class OutlineScript : MonoBehaviour {
public GameObject player;
public Shader shader1;
public Shader shader2;
public float outlineSize = 0.3f;
public float distanceToAct = 2;
public Color outlineColor = Color.red;
private bool alreadyNear = false;
// Use this for initialization
void Start () {
shader1 = Shader.Find("Standard");
shader2 = Shader.Find("Standard Outlined");
}
// Update is called once per frame
void Update () {
float distance = Vector3.Distance(gameObject.transform.position, player.transform.position);
if (distance <= distanceToAct) {
if (!alreadyNear) {
alreadyNear = true;
GetComponent<Renderer>().material.shader = shader2;
GetComponent<Renderer>().material.SetFloat("_Outline", outlineSize);
GetComponent<Renderer>().material.SetColor("_OutlineColor", outlineColor);
}
} else {
alreadyNear = false;
GetComponent<Renderer>().material.shader = shader1;
}
}
}
*/
<file_sep>/Assets/Scripts/TrigZone.cs
using System;
using UnityEngine;
using UnityEngine.Events;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditorInternal;
using com.spacepuppyeditor.Inspectors;
#endif
using UnityEngine.UI;
public class TrigZone : MonoBehaviour{
public enum ColliderFacingDirection{
DONTCARE, TARGETBEHIND, TARGETINFRONT, RAYCAST //, VISIBLERAYCAST
}
[Serializable]
public class TriggerZoneEvent : UnityEngine.Events.UnityEvent{
}
public int EnterUsages = 1; // -1 is unlimited
public int ExitUsages = 1; // -1 is unlimited
[Range(0.0f, 1.0f)]
public float Probability = 0.1f;
public bool UseOneProbability = false;
private float diceSave = 0;
public ColliderFacingDirection FacingDirection = ColliderFacingDirection.DONTCARE;
public int GameState = -1;
[SerializeField] private GameObject targetGameObject = null;
public TriggerZoneEvent EnterEvents;
#if UNITY_EDITOR
[TagSelectorAttribute]
#endif
public String EnterObjectTag = "Player";
public TriggerZoneEvent ExitEvents;
#if UNITY_EDITOR
[TagSelectorAttribute]
#endif
public String ExitObjectTag = "Player";
void OnTriggerEnter(Collider other) {
if(EnterUsages == 0) return;
if (! other.CompareTag(EnterObjectTag))return;
if (GameState != -1 && GameState != (int)StateMachine.Instance.State) return;
this.diceSave = UnityEngine.Random.value;
if(diceSave > Probability) return;
if(targetGameObject != null && ! checkFacing(other, FacingDirection, targetGameObject)) return;
EnterEvents.Invoke();
if((--EnterUsages) == 0){ // Usages = -1 should be (nearly) unlimited
EnterEvents.RemoveAllListeners();
//GameObject.Destroy(this.gameObject);
}
}
void OnTriggerExit(Collider other) {
if(ExitUsages == 0){
if(EnterUsages == 0)
GameObject.Destroy(this.gameObject);
return;
}
if (! other.CompareTag(ExitObjectTag))return;
if (GameState != -1 && GameState != (int)StateMachine.Instance.State) return;
float odds = UseOneProbability ? diceSave : UnityEngine.Random.value;
if(odds > Probability) return;
if(targetGameObject != null && ! checkFacing(other, FacingDirection, targetGameObject)) return;
ExitEvents.Invoke();
if((--ExitUsages) == 0){ // Usages = -1 should be (nearly) unlimited
ExitEvents.RemoveAllListeners();
}
}
protected bool checkFacing(Collider other, ColliderFacingDirection dir, GameObject target){
if(dir == ColliderFacingDirection.DONTCARE) return true;
Vector3 v = (other.transform.position - target.transform.position).normalized; // direction from player to door
float f = Vector3.Dot(v, Camera.main.transform.forward); // positive if looking in direction
switch (dir){
case(ColliderFacingDirection.TARGETBEHIND):
if(f < 0) return false; // the door could be seen!
break;
case(ColliderFacingDirection.TARGETINFRONT):
if(f >= 0) return false; // its next to or behind the player
break;
case(ColliderFacingDirection.RAYCAST):
if(f < 0){
RaycastHit hit;
int i = other.gameObject.layer;
other.gameObject.layer = 2; // ignore raycast - dont hit yourself
if(Physics.Raycast(other.transform.position, target.transform.position, out hit)){
if(hit.collider != target.transform){
other.gameObject.layer = i;
return false; // theres something between
}
}
other.gameObject.layer = i;
}
break;
}
return true;
}
#if UNITY_EDITOR
void OnDrawGizmosSelected(){
Gizmos.color = Color.yellow;
for(int i = 0; i < EnterEvents.GetPersistentEventCount(); ++i){
if(EnterEvents.GetPersistentTarget(i) == null || !(EnterEvents.GetPersistentTarget(i) is GameObject)) continue;
GameObject go = (GameObject) EnterEvents.GetPersistentTarget(i);
//Handles.DrawLine (this.transform.position, l.transform.position);
Gizmos.DrawLine (this.transform.position, go.transform.position);
}
Gizmos.color = Color.blue;
for(int i = 0; i < ExitEvents.GetPersistentEventCount(); ++i){
if(ExitEvents.GetPersistentTarget(i) == null || !(ExitEvents.GetPersistentTarget(i) is GameObject)) continue;
GameObject go = (GameObject) ExitEvents.GetPersistentTarget(i);
//Handles.DrawLine (this.transform.position, l.transform.position);
Gizmos.DrawLine (this.transform.position, go.transform.position);
}
}
#endif
}
<file_sep>/Assets/Scripts/WerkraumTrigger.cs
using System;
using System.Collections;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
using UnityStandardAssets.Water;
namespace Assets.Scripts
{
class WerkraumTrigger : MonoBehaviour
{
public GameObject[] ActivateGameObjects = null;
public GameObject[] DeactivateGameObjects = null;
private Image flashImage;
[SerializeField] private LightExplode explodingLight = null;
[SerializeField] private DoodadExchange doodadExchange = null;
private void OnTriggerEnter(Collider other)
{
if (StateMachine.Instance.State == GameState.FindeWerkzeuge02)
{
StateMachine.Instance.State = GameState.WaterBoiler03;
StartCoroutine(FlashScreen());
foreach (var gameObj in DeactivateGameObjects)
{
if(gameObj == null){
Debug.Log("GameObject reference is null");
continue;
}
gameObj.SetActive(false);
}
doodadExchange.Exchange(3);
doodadExchange.AddDecalLayer(3);
WaterSystem.instance.WaterIncrease1 = true;
}
}
private IEnumerator FlashScreen(){
explodingLight.Explode();
yield return new WaitForSeconds(0.2f);
GameObject.FindGameObjectWithTag ("Player").GetComponent<FPController> ().enabled = false;
flashImage.color = Color.white; // alpha should be 1
Color c = flashImage.color;
for(float f = 1f; f >= 0; f -= 0.3f * Time.deltaTime){
c.a = f;
flashImage.color = c;
yield return new WaitForSeconds(0.3f * Time.deltaTime);
}
c.a = 0;
flashImage.color = c;
yield return new WaitForSeconds(0.3f);
foreach (var gameObj in ActivateGameObjects)
{
if(gameObj == null){
Debug.Log("GameObject reference is null");
continue;
}
gameObj.SetActive(true);
}
GameObject.FindGameObjectWithTag ("Player").GetComponent<FPController> ().enabled = true;
GameObject.Destroy(this); // this should be the last things, this script does
}
void UISceneLoaded(){
GameObject canvas = GameObject.FindGameObjectWithTag("UICanvas");
flashImage = canvas.transform.Find("GamestateObjects/Flashback").GetComponent<Image>();
if(flashImage == null){
Debug.Log("image not found");
}
}
void Start(){
Player.instance.onLevelLoad += UISceneLoaded;
}
private void Update()
{
}
}
}
|
fca1291f7371fb3e1b590a4f2030f140ea644639
|
[
"Markdown",
"C#"
] | 52 |
C#
|
soraphis/HorrorOma
|
6b6341b37005c594946999adef9497325475283b
|
4ed0c27aed8d6c7e0035a5e589b5e75457681e12
|
refs/heads/master
|
<repo_name>khoalu/Procon<file_sep>/main.cpp
#include <bits/stdc++.h>
#include <nlohmann/json.hpp>
#define FOR(i,a,b) for(long long i = (a); i < (b); i++)
#define FORD(i,a,b) for(int i = (a); i >= (b); i--)
#define REP(i,a) for(int i = 0; i < (a); i++)
#define REPD(i,a) for(int i = (a)-1; i >= 0; i--)
#define sz(a) (int)a.size()
#define ALL(a) a.begin(),a.end()
#define ii pair<int,int>
#define fi first
#define se second
#define ll long long
#define N 1e5
using namespace std;
using json = nlohmann::json;
json j;
json out;
struct action
{
int id;
int dx;
int dy;
int turn;
int apply;
string type;
};
struct agent
{
int agentID;
int x, y;
int prevX,prevY;
string type;
};
struct team
{
int teamID;
vector<agent> ag;
int tilePoint;
int areaPoint;
};
struct match
{
int width;
int height;
vector<vector<int>>points;
int startedAtUnixTime;
int turn;
vector<vector<int>>tiled;
team tA, tB;
vector<action> act;
};
match now;
fstream ifs;
void readMap(int i)
{
ifs.open("fieldInfo_turn"+to_string(i)+".json",ios::in);
ifs>>j;
now.width=j["width"];
now.height=j["height"];
now.startedAtUnixTime=j["startedAtUnixTime"];
now.turn=j["turn"];
int ind=0;
string s=j["teams"].dump(2);
now.tA.teamID=j["teams"][0]["teamID"];
now.tA.tilePoint=j["teams"][0]["tilePoint"];
now.tA.areaPoint=j["teams"][0]["areaPoint"];
now.tB.teamID=j["teams"][1]["teamID"];
now.tB.tilePoint=j["teams"][1]["tilePoint"];
now.tB.areaPoint=j["teams"][1]["areaPoint"];
FOR (i,0,j["teams"][0]["agents"].size())
{
agent tmp;
tmp.agentID=j["teams"][0]["agents"][i]["agentID"];
tmp.x=j["teams"][0]["agents"][i]["x"];
tmp.y=j["teams"][0]["agents"][i]["y"];
now.tA.ag.push_back(tmp);
}
FOR (i,0,j["teams"][1]["agents"].size())
{
agent tmp;
tmp.agentID=j["teams"][1]["agents"][i]["agentID"];
tmp.x=j["teams"][1]["agents"][i]["x"];
tmp.y=j["teams"][1]["agents"][i]["y"];
now.tB.ag.push_back(tmp);
}
FOR(i,0,now.height)
{
vector<int>tmp;
j["points"][i].get_to(tmp);
now.points.push_back(tmp);
}
FOR(i,0,now.height)
{
vector<int>tmp;
j["tiled"][i].get_to(tmp);
now.tiled.push_back(tmp);
}
FOR(i,0,j["actions"].size())
{
action tmp;
tmp.id=j["actions"][i]["agentID"];
tmp.type=j["actions"][i]["type"];
tmp.dx=j["actions"][i]["dx"];
tmp.dy=j["actions"][i]["dy"];
tmp.turn=j["actions"][i]["turn"];
tmp.apply=j["actions"][i]["apply"];
now.act.push_back(tmp);
}
ifs.close();
}
void writeOutput(vector<action> decide)
{
out=
{
{"actions",{}},
};
FOR(i,0,decide.size())
{
/*auto text=R"(
{
"agentID" : 15,
"type": "move",
"dx": 15,
"dy": 15
}
)";*/
// out["actions"].push_back(json::get_to<string>("{ \"agentID\": 15, \"type\": 15,\"dx\": 15,\"dy\": 15 }"));
//out["actions"].push_back(json::parse(text));
/* out["actions"]="{ \"agentID\": 15, \"type\": 15,\"dx\": 15,\"dy\": 15 }"_json;
string s;
out["actions"].get_to(s);
cout<<s<<endl;*/
//out.push_back(json::object_t::value_type("agentID", 15));
//string s="{ \"agentID\": 15, \"type\": 15,\"dx\": 15,\"dy\": 15 }";
//out["actions"].get_to(s);
//
//out["actions"].push_back(json::object_t::value_type("xhree", 3));
//out["actions"][i] += json::object_t::value_type("four", 4);
out["actions"][i]["agentID"]=decide[i].id;
// out["actions"][i] += json::object_t::value_type("four", 4);
//out["actions"][i] += json::object_t::value_type("bour", 4);
out["actions"][i]["type"]=decide[i].type;
out["actions"][i]["dx"]=decide[i].dx;
out["actions"][i]["dy"]=decide[i].dy;
}
ifs.open("decide.json",ios::out);
cout<<std::setw(4)<<out;
ifs.close();
}
action decideEachAgent(int& staX,int& staY, agent &Ag,match Map,int teamID)
{
action decideOut;
int dx_des,dy_des;
if(staX<=2)dx_des=1;
else
{
if((staX-2)%4==1)dx_des=-1;
else dx_des=1;
}
if(staY%4==1)dy_des=-1;
else dy_des=1;
if(Ag.x+dx_des>Map.width || Ag.x+dx_des<1 )
{
return false;
}
else if( Ag.y+dy_des <1||Ag.y+dy_des>Map.height)
{
return false;
}
else if(Map.tiled[Ag.x+dx_des][Ag.y+dy_des]==0)
{
Ag.type="move";
Ag.x+=dx_des;
Ag.y+=dy_des;
Ag.prevX=Ag.x;
Ag.prevY=Ag.y;
decideOut.type="move";
decideOut.dx=dx_des;
decideOut.dy=dy_des;
decideOut.id=Ag.agentID;
staX++;
staY++;
}
else if(Map.tiled[Ag.x+dx_des][Ag.y+dy_des]==teamID)
{
bool trang=false;
FOR(i,-1,2)
{
FOR(j,-1,2)
{
if(i==0 && j==0)continue;
if(abs(i)==abs(j))continue;
if(Map.tiled[Ag.x+i][Ag.y+j]==0)
{
Ag.type="move";
Ag.x+=i;
Ag.y+=j;
Ag.prevX=Ag.x;
Ag.prevY=Ag.y;
decideOut.type="move";
decideOut.dx=i;
decideOut.dy=j;
decideOut.id=Ag.agentID;
trang=true;
break;
}
}
if(trang)break;
}
if(!trang)
{
FOR(i,-1,2)
{
FOR(j,-1,2)
{
if(i==0 && j==0)continue;
//if(abs(i)==abs(j))continue;
if(Map.tiled[Ag.x+i][Ag.y+j]==teamID)
{
Ag.type="move";
Ag.x+=i;
Ag.y+=j;
Ag.prevX=Ag.x;
Ag.prevY=Ag.y;
decideOut.type="move";
decideOut.dx=i;
decideOut.dy=j;
decideOut.id=Ag.agentID;
trang=true;
break;
}
}
if(trang)break;
}
}
if(!trang)
{
/*if(Ag.prevX==Ag.x && Ag.prevY==Ag.Y)
{
Ag.type="remove";
Ag.prevX=-1;
Ag.prevY=-1;
decideOut.type="remove" ;
decideOut.dx=-1;
decideOut.dy=-1;
decideOut.id=Ag.agentID;
}
else
{
FOR(i,-1,2)
{
FOR(j,-1,2)
{
if(j<=Ag.prevX && i<=Ag.prevY)continue;
Ag.type="remove";
Ag.prevX=j;
Ag.prevY=i;
decideOut.type="remove" ;
decideOut.dx=j;
decideOut.dy=i;
decideOut.id=Ag.agentID;
i=5;j=5;
}
}
}*/
vector<pair< >>>
for((prevX,prevY)==vector[i])prevx, prev=vector[i+1];
}
}
else
{
Ag.type="remove";
// Ag.x+=dx_des;
// Ag.y+=dy_des;
Ag.prevX=Ag.x;
Ag.prevY=Ag.y;
decideOut.type="remove";
decideOut.dx=dx_des;
decideOut.dy=dy_des;
decideOut.id=Ag.agentID;
}
return decideOut;
}
void strategy2(int teamID,int numOfTurns)
{
cout<<"Press enter to print output.json"<<endl;
while(true)
{
char x;
cin>>x;
if(x=='\n')break;
}
readMap(1);
int numOfAgent;
vector<action>decision;
static int staX[10];
static int staY[10];
FOR(i,0,10)staX[i]=1,staY[i]=1;
if(teamID==now.tA.teamID)
{
numOfAgent=now.tA.ag.size();
FOR(i,0,now.act.size())
{
if(now.act[i].apply==-1)
{
FOR()
}
}
}
FOR(i,0,numOfAgent)
{
decision.push_back(decideEachAgent2(staX[i],staY[i],now.tA.ag[i],now,teamID,numOfTurns));
}
}
else
{
numOfAgent=now.tB.ag.size();
FOR(i,0,numOfAgent)
{
decision.push_back(decideEachAgent2(staX[i],staY[i],now.tB.ag[i],now,teamID,numOfTurns));
}
}
writeOutput(decision);
strategy2(teamID);
}
void strategy1(int teamID)
{
cout<<"Press enter to print output.json"<<endl;
while(true)
{
char x;
cin>>x;
if(x=='\n')break;
}
int numOfAgent;
vector<action>decision;
static int staX[10];
static int staY[10];
FOR(i,0,10)staX[i]=1,staY[i]=1;
if(teamID==now.tA.teamID)
{
numOfAgent=now.tA.ag.size();
FOR(i,0,numOfAgent)
{
bool check=true;
action tmp=decideEachAgent(staX[i],staY[i],now.tA.ag[i],now,teamID,check);
if(check)decision.push_back(action);
else
{
}
}
}
else
{
numOfAgent=now.tB.ag.size();
FOR(i,0,numOfAgent)
{
decision.push_back(decideEachAgent(staX[i],staY[i],now.tB.ag[i],now,teamID));
}
}
writeOutput(decision);
strategy1(teamID);
}
int main()
{
readMap(0);
vector<action> decide;
action tmp;
tmp.apply=5;
tmp.dx=1;
tmp.dy=2;
tmp.id=3;
tmp.turn=4;
tmp.type="fdas";
decide.push_back(tmp);
decide.push_back(tmp);
//writeOutput(decide);
strategy1(5);
return 0;
}
|
a75ab9bd14f7be2730d0dfc819c23b5160c3aa5d
|
[
"C++"
] | 1 |
C++
|
khoalu/Procon
|
3ca114c4310b3db894eafd6555cc347b79e815dd
|
d5ef1a9679ad8522f747ce857010fab0a42a85b8
|
refs/heads/master
|
<repo_name>mafof/AutomationScriptsLinuxWebServer<file_sep>/README.md
# Скрипты для быстрого разворачивания веб сервера
Данные bash скрипты предназначены для ОС ubuntu/debian
1. initilizationWebServer.sh: Скрипт для быстрой установки необходимых пакетов(LAMP) и создания пользовательских директорий.
2. createSite.sh: Скрипт для создания/изменения доменного имени и других настроек сайта<file_sep>/createSite.sh
#!/bin/bash
RED='\033[0;31m'
GREEN='\033[0;32m'
NORMAL='\033[0m'
UNDERLINE='\033[4m'
F_NORMAL='\033[0m'
PATH_NGINX=("/etc/nginx/sites-available" "/etc/nginx/sites-enabled")
PATH_APACHE=("/etc/apache2/sites-available" "/etc/apache2/sites-enabled")
PATH_DIRECTORY="null" # Путь до директории где распологается сайт
SELECT_SITE="null" # Выбранный сайт в методе editSite
SELECT_SERVER="null"
SELECT_USER="null"
NAME_SITE="null"
tput sgr0
# Функция проверяющая существует ли пользователь(его домашняя папка)
function checkUser {
[ -d /home/$1 ]
}
# Метод создающий конфигурационный файл apache || nginx
function createConfig {
if [[ $SELECT_SERVER == "apache" ]]
then
export CONFIGAPACHE=$(cat <<END
<VirtualHost *:80>
ServerName $NAME_SITE
DocumentRoot $PATH_DIRECTORY
<Directory $PATH_DIRECTORY>
Options -Indexes +FollowSymLinks +MultiViews
AllowOverride All
Require all granted
</Directory>
ErrorLog /home/$SELECT_USER/logs/$NAME_SITE/error.log
CustomLog /home/$SELECT_USER/logs/$NAME_SITE/error.log combined
</VirtualHost>
END
);
echo "$CONFIGAPACHE" >> "${PATH_APACHE[0]}/$NAME_SITE.conf"
a2ensite "$NAME_SITE.conf"
elif [[ $SELECT_SERVER == "nginx" ]]
then
echo -en "${RED}Поддержка создания конфигурационного файла для nginx в разработке${NORMAL}"
# Добавить откат действий
exit
fi
}
function createSite {
echo -en "\n${UNDERLINE}Укажите название сайта:${F_NORMAL}"
read nameSites
NAME_SITE=$nameSites
# Подтверждение действия
echo -en "\n${UNDERLINE}Название сайта $NAME_SITE, подтвердить?(y|n)${F_NORMAL}"
read selectAccept
if [[ $selectAccept == "n" ]]
then
createSite
fi
echo -en "\n${UNDERLINE}Создание директории сайта...${F_NORMAL}"
PATH_DIRECTORY="/home/$SELECT_USER/sites/$NAME_SITE"
mkdir /home/$SELECT_USER/sites/$NAME_SITE
mkdir /home/$SELECT_USER/logs/$NAME_SITE
echo "<html><head><title>Test page</title></head><body>Page for check running site</body></html>" >> "/home/$SELECT_USER/sites/$NAME_SITE/index.html"
chmod -R 777 /home/$SELECT_USER/sites/$NAME_SITE
chmod -R 777 /home/$SELECT_USER/logs/$NAME_SITE
echo -en "${GREEN}[OK]${NORMAL}\n"
echo -en "${UNDERLINE}Создание конфигурационного файла...${F_NORMAL}"
createConfig
echo -en "${GREEN}[OK]${NORMAL}\n"
# Перезагрузка сервиса
if [[ $SELECT_SERVER == "apache" ]]
then
echo -en "${UNDERLINE}Перезагрузка сервиса...${F_NORMAL}"
service apache2 restart
echo -en "${GREEN}[OK]${NORMAL}\n"
elif [[ $SELECT_SERVER == "nginx" ]]
then
echo -en "${RED}Поддержка создания конфигурационного файла для nginx в разработке${NORMAL}"
# Добавить откат действий
exit
fi
echo -en "\n${UNDERLINE}Сайт успешно создан.\nДиректория сайта /home/$SELECT_USER/$NAME_SITE\nДиректория логов /home/$SELECT_USER/logs/$NAME_SITE\n ${F_NORMAL}"
}
# Удаление конфигураций
function removeConfiguration {
# Проверка существования конфигурации
if ! [ -f /etc/apache2/sites-available/$SELECT_SITE.conf ]
then
echo -en "\n${UNDERLINE}Файл конфигурации отсутствует...${F_NORMAL}"
else
a2dissite $SELECT_SITE.conf
rm /etc/apache2/sites-available/$SELECT_SITE.conf
fi
}
# Удаление директории
function removeDirectory {
rm -r /home/$SELECT_USER/sites/$SELECT_SITE
rm -r /home/$SELECT_USER/logs/$SELECT_SITE
}
function removeSite {
removeConfiguration # Удаляем конфигурации
removeDirectory # Удаляем директории
systemctl reload apache2
}
function editSite {
if [[ $SELECT_SERVER == "nginx" ]]
then
echo -en "\n${UNDERLINE}${RED}Подддержка nginx пока не доступна в изменение сайта${NORMAL}${F_NORMAL}"
exit
fi
echo -en "\n${UNDERLINE}Список ранее созданных сайтов:\n${F_NORMAL}"
TEMP_COUNTER=1
arrayfiles=()
# Выводим список сайтов (директорий)
for file in `find /home/$SELECT_USER/sites -maxdepth 1 | grep /home/$SELECT_USER/sites/[a-zA-Z0-9]`
do
echo -en "$TEMP_COUNTER. "
TEMP_TEXT=`echo $file | sed 's/\/home\/[a-z]*\/sites\///g'`
echo $TEMP_TEXT
TEMP_COUNTER=$[TEMP_COUNTER +1]
arrayfiles[${#arrayfiles[*]}]=$TEMP_TEXT
done
read selectCounter
selectCounter=$[selectCounter -1]
# Проверка существования директории
if ! [ -d /home/$SELECT_USER/sites/${arrayfiles[$selectCounter]} ];
then
echo -en "${RED}ВНИМАНИЕ ДАННОЙ ДИРЕКТОРИИ НЕ СУЩЕСТВУЕТ${NORMAL}"
editSite
fi
# Подтверждение выбора
echo -en "\n${UNDERLINE}Выбран ${arrayfiles[$selectCounter]}, подтвердить?(y|n)${F_NORMAL}"
read selectAccept
if [[ $selectAccept == "n" ]]
then
editSite;
fi
# Запись в глобальную переменную
SELECT_SITE=${arrayfiles[$selectCounter]}
# Выберем действие уже с ранее выбранным сайтом
echo -en "\n${UNDERLINE}Выберите действие:\n1.Удалить сайт и конфигурационный файл\n${F_NORMAL}"
read selectAction
case $selectAction in
1)
removeSite;;
esac
}
function requestSelectUser {
echo -en "${UNDERLINE}Введите имя пользователя:${F_NORMAL}"
read user
if checkUser $user;
then
SELECT_USER=$user
else
echo -en "${UNDERLINE}Данного пользователя не существует${F_NORMAL}\n"
requestSelectUser;
fi
}
# Метод выбирающий на каком пакете создать сайт (nginx || apache)
function requestSelectServer {
echo -en "\n${UNDERLINE}Выберите серверный пакет:\n1.nginx\n2.apache\n${F_NORMAL}"
read selectServer
SELECT_SERVER=selectServer
if [[ $selectServer == "1" ]]
then
SELECT_SERVER="nginx"
elif [[ $selectServer == "2" ]]
then
SELECT_SERVER="apache"
fi
echo -en "${UNDERLINE}Выбран $SELECT_SERVER, подтвердить?(y|n)${F_NORMAL}"
read selectAccept
if [[ $selectAccept == "n" || $selectAccept == "т" ]]
then
requestSelectServer
fi
}
function requestDoIt {
echo -en "\n${UNDERLINE}Выберите что нужно сделать:\n1.Создать сайт\n2.Изменить сайт${F_NORMAL}\n"
read doChoice
case $doChoice in
1)
createSite;;
2)
editSite;;
esac
}
function main {
requestSelectUser # Выбор пользователя
requestSelectServer # Выбор пакета сервера (nginx || apache)
requestDoIt # Выбор что нужно сделать (Создать сайт || Редактировать сайт)
}
main<file_sep>/initializationWebServer.sh
#!/bin/bash
RED='\033[0;31m'
GREEN='\033[0;32m'
NORMAL='\033[0m'
UNDERLINE='\033[4m'
F_NORMAL='\033[0m'
tput sgr0
arrayDontInstallPackage=()
selectedUser="0"
# Проверяет установлены ли необходимые пакеты (LAMP)
function checkInstallPackage {
package=`dpkg -s $1 . 2>/dev/null | grep "Status" `
if [ -n "$package" ]
then
echo -en "\n$1 ${GREEN}установлен${NORMAL}"
else
echo -en "\n$1 ${RED}не установлен${NORMAL}"
arrayDontInstallPackage[${#arrayDontInstallPackage[*]}]=$1
fi
}
# Метод устанавливающий пакеты из списка
function installPackageOutList {
_package=""
for item in ${arrayDontInstallPackage[*]}
do
#apt-get install $item
_package+=" $item"
done
apt-get install $_package
}
# Функция проверяющая существует ли пользователь(его домашняя папка)
function checkUser {
[ -d /home/$1 ]
}
# Запрос об обновление пакетов
function requestUpdatePackage {
echo -en "${UNDERLINE}Обновить пакеты (y|n)?${F_NORMAL}"
read accept
if [[ $accept == "y" || $accept == "н" ]]
then
echo -en "\n${UNDERLINE}Запускаю процес обновления пакетов:${F_NORMAL}"
apt-get update
apt-get upgrade
fi
}
function requestCreateDirectories {
echo -en "${UNDERLINE}Введите имя пользователя:${F_NORMAL}"
read user
if checkUser $user;
then
selectedUser=$user
echo -en "${UNDERLINE}Создание папок...${F_NORMAL}"
mkdir sites
mkdir mail
mkdir bashScripts;
mkdir logs;
else
echo -en "${UNDERLINE}Данного пользователя не существует${F_NORMAL}\n"
requestCreateDirectories;
fi
}
function requestInstallOS {
# Запрос об версии ОС
echo -en "\n${UNDERLINE}Укажите операционную систему:\n1.Debian 8\n2.Debian 9${F_NORMAL}"
read acceptOS
if [[ $acceptOS == "1" ]]
then
installPackageDebian8
elif [[ $acceptOS == "2" ]]
then
installPackageDebian9
fi
}
function installPackageDebian8 {
# Добавляем репозитории
echo "deb http://packages.dotdeb.org jessie all" >> /etc/apt/sources.list
echo "deb-src http://packages.dotdeb.org jessie all" >> /etc/apt/sources.list
# Скачиваем ключ расшифровки и применяем его
cd ~
wget https://www.dotdeb.org/dotdeb.gpg
apt-key add dotdeb.gpg
rm dotdeb.gpg
apt-get update
# Проверка
checkInstallPackage sudo
checkInstallPackage apache2
checkInstallPackage php7.0
checkInstallPackage php7.0-mysql
checkInstallPackage libapache2-mod-php7.0
checkInstallPackage php7.0-mbstring
checkInstallPackage php7.0-zip
checkInstallPackage php7.0-gd
checkInstallPackage mysql-server
checkInstallPackage mysql-client
checkInstallPackage mysql-common
checkInstallPackage unzip
# Проверка установлены ли все пакеты
if [[ ${#arrayDontInstallPackage[*]} != 0 ]]
then
echo -en "\n${UNDERLINE}Некоторые пакеты не установлены, установить их(y|n)?${F_NORMAL}"
read acceptInstall
if [[ $acceptInstall == "y" || $acceptInstall == "н" ]]
then
installPackageOutList
else
echo -en "${UNDERLINE}Отмена установки${F_NORMAL}\n"
exit
fi
fi
}
# Запрос об установки пакетов для Debian 9
function installPackageDebian9 {
# Проверка установки пакетов
echo -en "\n${UNDERLINE}Проверка установки пакетов:${F_NORMAL}"
checkInstallPackage sudo
checkInstallPackage apache2
checkInstallPackage php
checkInstallPackage php-mysql
checkInstallPackage libapache2-mod-php
checkInstallPackage php-mbstring
checkInstallPackage php-zip
checkInstallPackage php-gd
checkInstallPackage mysql-server
checkInstallPackage mysql-client
checkInstallPackage mysql-common
checkInstallPackage unzip
# Проверка установлены ли все пакеты
if [[ ${#arrayDontInstallPackage[*]} != 0 ]]
then
echo -en "\n${UNDERLINE}Некоторые пакеты не установлены, установить их(y|n)?${F_NORMAL}"
read acceptInstall
if [[ $acceptInstall == "y" || $acceptInstall == "н" ]]
then
installPackageOutList
else
echo -en "${UNDERLINE}Отмена установки${F_NORMAL}\n"
exit
fi
fi
}
function getScripts {
if [[ $selectedUser != "0" ]]
then
if [[ -d /home/$selectedUser/bashScripts ]]
then
echo -en "\n${UNDERLINE}Скачивание архива...${F_NORMAL}"
cd /home/$selectedUser/bashScripts
wget https://github.com/mafof/AutomationScriptsLinuxWebServer/archive/master.zip . 2>/dev/null
unzip -qq -u -j master.zip
rm README.md
rm master.zip
echo -en "${GREEN}[OK]${NORMAL}"
fi
else
echo -en "\n${UNDERLINE}Введите имя пользователя:${F_NORMAL}"
read user
if checkUser $user;
then
getScripts
else
echo -en "\n${RED}Неправильное имя пользователя${NORMAL}"
getScripts
fi
fi
}
# Главный метод
function main {
requestUpdatePackage # Обновление пакетов
requestCreateDirectories # Создавать ли окружение(папки)
requestInstallOS # Проверка Операционной системы
getScripts # Скачивание всех скриптов и перемещение их в папку bashScripts
echo -en "\n${UNDERLINE}Скрипт отработал успешно, для добавление сайтов воспользуйтесь файлом createSite.sh в директории /home/$selectedUser/bashScripts ${F_NORMAL}\n"
}
main
|
049e8bdb9a37e9ca1b1fd04f1ac26c97d86ec966
|
[
"Markdown",
"Shell"
] | 3 |
Markdown
|
mafof/AutomationScriptsLinuxWebServer
|
1db736433d8896f56702377438be870a4babc26c
|
5d5a84a875655882a8166da11908c47ca3c088a5
|
refs/heads/master
|
<file_sep>namespace Navigation
{
public interface INavigatingViewModel
{
IViewModelNavigation ViewModelNavigation { get; set; }
}
}
<file_sep>using System.Threading.Tasks;
namespace Navigation
{
public interface IViewModelNavigation
{
Task<object> PopAsync();
Task<object> PopModalAsync();
Task PopToRootAsync();
Task PushAsync(object viewModel);
Task PushModalAsync(object viewModel);
}
}
<file_sep>using System;
namespace Navigation
{
[AttributeUsage(AttributeTargets.Class)]
public class RegisterViewModelAttribute : Attribute
{
public Type ViewModelType { get; private set; }
public RegisterViewModelAttribute(Type viewModelType)
{
ViewModelType = viewModelType;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace Navigation
{
public class NavigationFrame : IViewModelNavigation
{
private static readonly Dictionary<Type,Type> ViewModelTypeToPageType;
private readonly NavigationPage _navigationPage;
static NavigationFrame()
{
ViewModelTypeToPageType = new Dictionary<Type, Type>();
// This is the hacky way we have to get the list of assemblies in a PCL for now.
// Hopefully Xamarin will expose Device.GetAssemblies() in a future version of Xamarin.Forms.
var currentDomain = typeof(string).GetTypeInfo().Assembly.GetType("System.AppDomain").GetRuntimeProperty("CurrentDomain").GetMethod.Invoke(null, new object[] {});
var getAssemblies = currentDomain.GetType().GetRuntimeMethod("GetAssemblies", new Type[]{ });
var assemblies = getAssemblies.Invoke (currentDomain, new object[]{ }) as Assembly[];
var allTypes = assemblies.SelectMany(a => a.DefinedTypes);
var typesWithRegisterAttributes = allTypes
.Select(t => new { TypeInfo = t, Attribute = t.GetCustomAttribute<RegisterViewModelAttribute>() })
.Where(p => p.Attribute != null);
foreach (var pair in typesWithRegisterAttributes)
{
if (!typeof(Page).GetTypeInfo().IsAssignableFrom(pair.TypeInfo))
{
var message = string.Format(
"RegisterViewModelAttribute applied to a class ({0}) that is not a Page",
pair.TypeInfo.FullName);
throw new InvalidOperationException(message);
}
if (ViewModelTypeToPageType.ContainsKey(pair.Attribute.ViewModelType))
{
var message = string.Format(
"Multiple Page types (new = {0}, previous = {1}) registered for the same view model type ({2})",
pair.TypeInfo.FullName,
ViewModelTypeToPageType[pair.Attribute.ViewModelType].FullName,
pair.Attribute.ViewModelType.FullName
);
throw new InvalidOperationException(message);
}
ViewModelTypeToPageType[pair.Attribute.ViewModelType] = pair.TypeInfo.AsType();
}
}
public NavigationFrame(object rootViewModel)
{
_navigationPage = new NavigationPage(CreatePageForViewModel(rootViewModel));
}
public Page Root { get { return _navigationPage; } }
public async Task<object> PopAsync()
{
var currentViewModel = CurrentViewModel;
await _navigationPage.PopAsync();;
return currentViewModel;
}
public async Task<object> PopModalAsync()
{
var poppedPage = await _navigationPage.Navigation.PopModalAsync();
return poppedPage.BindingContext;
}
public Task PopToRootAsync()
{
return _navigationPage.PopToRootAsync();
}
public Task PushAsync(object viewModel)
{
return _navigationPage.PushAsync(CreatePageForViewModel(viewModel));
}
public Task PushModalAsync(object viewModel)
{
return _navigationPage.Navigation.PushModalAsync(CreatePageForViewModel(viewModel));
}
public object CurrentViewModel
{
get
{
return _navigationPage.CurrentPage.BindingContext;
}
}
private Page CreatePageForViewModel(object viewModel)
{
Type newPageType = null;
if (!ViewModelTypeToPageType.TryGetValue(viewModel.GetType(), out newPageType))
{
throw new ArgumentException("Trying to create a Page for an unrecognized view model type. Did you forget to use the RegisterViewModel attribute?");
}
var newPage = (Page)Activator.CreateInstance(ViewModelTypeToPageType[viewModel.GetType()]);
newPage.BindingContext = viewModel;
SetFrameReference(viewModel, this);
return newPage;
}
private static void SetFrameReference(object viewModel, IViewModelNavigation frame)
{
if (viewModel == null)
{
return;
}
var navigatedPage = viewModel as INavigatingViewModel;
if (navigatedPage != null)
{
navigatedPage.ViewModelNavigation = frame;
}
}
}
}
|
678d3d4cedace1f2fb063bd18c69185fbf9cb0b3
|
[
"C#"
] | 4 |
C#
|
TheRealAdamKemp/Navigation
|
00e394f5d666d397fe37dd7c3ccffcf82bfca1b3
|
d8457da988cccc53ad66dbc9faf27b9cd38767c6
|
refs/heads/master
|
<file_sep>package main
import (
"fmt"
"log"
"math/rand"
"testing"
"time"
)
func TestMerge2Channels1(t *testing.T) {
f := func(n int) int {
sleep := rand.Int31n(100)
// log.Println("run =", n)
time.Sleep(time.Duration(sleep) * time.Millisecond)
//time.Sleep(2 * time.Second)
return (n * n)
}
rand.Seed(12000)
// repeats := rand.Intn(400)
repeats := 100
in1 := make(chan int, repeats)
in2 := make(chan int, repeats)
out := make(chan int, repeats)
// log.Println("Seed")
log.Println("Merge2Channels")
Merge2Channels(f, in1, in2, out, repeats/2)
Merge2Channels(f, in1, in2, out, repeats/2)
results := []int{}
go func() {
for i := 0; i < repeats; i++ {
i1 := rand.Intn(200)
i2 := rand.Intn(200)
in1 <- i1
in2 <- i2
results = append(results, (i1*i1)+(i2*i2))
}
}()
c := 0
log.Println("range out")
for i := range out {
if i != results[c] {
t.Errorf("%v != %v", i, results[c])
}
//log.Println("result =", results[c])
//log.Println("out =", i)
c++
if c == repeats {
close(out)
}
}
log.Println("REPEATS=", repeats)
// log.Println("results =", results)
}
func square(n int) int {
time.Sleep(time.Duration(rand.Int31n(10)) * time.Millisecond)
return n * n
}
func TestMerge2Channels2(t *testing.T) {
rand.Seed(time.Now().UnixNano())
repeats := 30
done := make(chan struct{}, 2)
runTimes := 2
for i := 0; i < runTimes; i++ {
go func() {
in1 := make(chan int, 100)
in2 := make(chan int, 100)
out := make(chan int, 100)
var expectedOut []int
for i := 1; i < 101; i++ {
in1 <- i
in2 <- i
expectedOut = append(expectedOut, square(i) * 2)
}
Merge2Channels(square, in1, in2, out, repeats)
go func(expectedResult []int, out<- chan int, done chan <- struct{}) {
for i := 0; i < repeats; i++ {
v := expectedOut[i]
r := <- out
if v != r {
t.Error("ОЖИДАЛ:", v, "ПОЛУЧИЛ:", r)
}
}
done <- struct{}{}
}(expectedOut, out, done)
}()
}
for i := 0; i < runTimes; i++ {
<- done
}
}
func fastSquare(a int) int {
return a * a
}
func slowSquare(a int) int {
time.Sleep(50 * time.Millisecond)
return a * a
}
func TestNonBlocking(t *testing.T) {
capacity := 100
ch1 := make(chan int, capacity)
a1 := make([]int, capacity)
ch2 := make(chan int, capacity)
a2 := make([]int, capacity)
chOut := make(chan int, capacity)
a3 := make([]int, capacity)
i := 0
for i < capacity {
a1[i] = i + 9
ch1 <- a1[i]
a2[i] = i*3 + 289
ch2 <- a2[i]
a3[i] = fastSquare(a1[i]) + fastSquare(a2[i])
i++
}
done := make(chan struct{})
portion := 30
go func() {
Merge2Channels(slowSquare, ch1, ch2, chOut, portion)
close(done)
}()
select {
case <-done:
case <-time.After(time.Millisecond * 100):
t.Fail()
panic("Function should be non-blocking")
}
}
func TestSlowSquare(t *testing.T) {
capacity := 100
ch1 := make(chan int, capacity)
a1 := make([]int, capacity)
ch2 := make(chan int, capacity)
a2 := make([]int, capacity)
chOut := make(chan int, capacity)
a3 := make([]int, capacity)
i := 0
for i < capacity {
a1[i] = i + 9
ch1 <- a1[i]
a2[i] = i*3 + 289
ch2 <- a2[i]
a3[i] = fastSquare(a1[i]) + fastSquare(a2[i])
i++
}
done := make(chan struct{})
portion := 30
go func() {
Merge2Channels(slowSquare, ch1, ch2, chOut, portion)
close(done)
}()
<-done
i = 0
for i < portion {
ans, ok := <-chOut
if !ok {
t.Fail()
panic("Output channel closed prematurely")
}
if ans != a3[i] {
t.Fail()
panic(fmt.Errorf("Got %d from output channel, should be %d", ans, a3[i]))
}
i++
}
if len(ch1) != capacity-portion {
t.Fail()
panic(fmt.Errorf("First channel has %d numbers in it, should have %d", len(ch1), capacity-portion))
}
if len(ch2) != capacity-portion {
t.Fail()
panic(fmt.Errorf("Second channel has %d numbers in it, should have %d", len(ch2), capacity-portion))
}
}
<file_sep>package main
func main() {
}
// Merge2Channels below
/*
func Merge2Channels(f func(int) int, in1 <-chan int, in2 <-chan int, out chan<- int, n int) {
}
*/
<file_sep>## Telegram группа
https://t.me/ozon_go_contest2020
## Этот репозиторий никак не связан с ozon
## Репо для проверки последнего задания
- `git clone <EMAIL>:Gasoid/last-task-go-contest-2020.git`
- добавляйте свою функцию в main.go
- запуск теста `go test . -v`
# Задание
Необходимо написать функцию func Merge2Channels(f func(int) int, in1 <-chan int, in2 <- chan int, out chan<- int, n int) в package main.
## Описание ее работы:
### n раз сделать следующее:
- прочитать по одному числу из каждого из двух каналов in1 и in2, назовем их x1 и x2.
- вычислить f(x1) + f(x2)
- записать полученное значение в out
Функция **Merge2Channels** должна быть неблокирующей, сразу возвращая управление.
Функция f может работать **долгое время**, ожидая чего-либо или производя вычисления.
## Формат ввода
Количество итераций передается через аргумент n.
Целые числа подаются через аргументы-каналы in1 и in2.
Функция для обработки чисел перед сложением передается через аргумент f.
## Формат вывода
Канал для вывода результатов передается через аргумент out.
## Примечания
Отправлять задачу необходимо под компилятором Make. Решения, выдающие неверный ответ, могут по техническим причинам получать вердикт Runtime Error. Медленные решения получают вердикт Idleness Limit, стоит рассматривать это как превышение времени исполнения.
|
f896a060a1b82d8a330e41f18c4df27c815ee32d
|
[
"Markdown",
"Go"
] | 3 |
Go
|
Gasoid/last-task-go-contest-2020
|
0a5afd4a062677536d377c1406c44affaa4219d0
|
ec9c9d7c9687c7717769c89e583ea7a1f86f7326
|
refs/heads/master
|
<repo_name>merlinmb/espTransitNeoPixel<file_sep>/StructDefs.h
#pragma once
#define DEBUG 1
#ifdef DEBUG
#define DEBUG_PRINT(x) Serial.print (x)
#define DEBUG_PRINTDEC(x,DEC) Serial.print (x, DEC)
#define DEBUG_PRINTLN(x) Serial.println (x)
#define DEBUG_PRINTLNDEC(x,DEC) Serial.println (x, DEC)
#else
#define DEBUG_PRINT(x)
#define DEBUG_PRINTDEC(x,DEC)
#define DEBUG_PRINTLN(x)
#define DEBUG_PRINTLNDEC(x,DEC)
#endif
#define NEOPIXELPIN D7 //neopixel gpio pin
#define NUMPIXELS 8 // number of pixels in ring
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, NEOPIXELPIN, NEO_GRB + NEO_KHZ800);
#define DEGREESPERSTEP 15;
struct Colour { int r;int g; int b; };
Colour _oldColour = { 255, 255, 255 };
Colour _currentColour = { 255, 255, 255 };
Colour colourRanges[] = {
{ 220, 220, 220 },
{ 0, 0, 255 },
{ 0, 255, 0 },
{ 215, 215, 0 },
{ 255, 0, 0 }
};
int _brightness = 100;
bool _isDisplayOn = true;
Colour findColourInRange(float PercentageVal) {
int __lb = 0;
int __ub = 0;
int __lbT = 0;
int __ubT = 0;
if (PercentageVal < 0) { PercentageVal = 0; }
if (PercentageVal > 40) { PercentageVal = 40;}
if (PercentageVal <= 0) { __lb = 0; __ub = 1; __lbT = 0; __ubT = 0; }
if (PercentageVal > 0 && PercentageVal < 25) { __lb = 1; __ub = 2; __lbT = 1; __ubT = 24; }
if (PercentageVal >= 25 && PercentageVal < 40){ __lb = 1; __ub = 2; __lbT = 25; __ubT = 39; }
if (PercentageVal >= 40) { __lb = 2; __ub = 3; __lbT = 40; __ubT = 40; }
DEBUG_PRINT("LowerBound: "); DEBUG_PRINTLN(__lb);
DEBUG_PRINT("UpperBound: "); DEBUG_PRINTLN(__ub);
float __step1 = (PercentageVal - __lbT);
Colour __newCol;
float __r = (colourRanges[__ub].r - colourRanges[__lb].r) / DEGREESPERSTEP;
float __g = (colourRanges[__ub].g - colourRanges[__lb].g) / DEGREESPERSTEP;
float __b = (colourRanges[__ub].b - colourRanges[__lb].b) / DEGREESPERSTEP;
__newCol.r = ( __r * __step1) + colourRanges[__lb].r;
__newCol.g = ( __g * __step1) + colourRanges[__lb].g;
__newCol.b = ( __b * __step1) + colourRanges[__lb].b;
return __newCol;
}
void fade(Colour fromColour, Colour toColour) {
int n = 200; //#steps
int Rnew = 0, Gnew = 0, Bnew = 0;
for (int i = 0; i <= n; i++)
{
Rnew = fromColour.r + (toColour.r - fromColour.r) * i / n;
Gnew = fromColour.g + (toColour.g - fromColour.g) * i / n;
Bnew = fromColour.b + (toColour.b - fromColour.b) * i / n;
Rnew = (Rnew*_brightness) / 100;
Gnew = (Gnew*_brightness) / 100;
Bnew = (Bnew*_brightness) / 100;
for (int j = 0; j < NUMPIXELS; j++) {
// Set pixel color here.
pixels.setPixelColor(j, pixels.Color(Rnew, Gnew, Bnew));
pixels.show();
}
delay(10);
}
}
void OutputColour(Colour _col) {
DEBUG_PRINT("R: "); DEBUG_PRINTLN(_col.r);
DEBUG_PRINT("G: "); DEBUG_PRINTLN(_col.g);
DEBUG_PRINT("B: "); DEBUG_PRINTLN(_col.b);
}
void clearpixels() {
for( int i = 0; i<NUMPIXELS; i++){
pixels.setPixelColor(i, 0x000000); pixels.show();
}
}
uint32_t dimColor(uint32_t color, uint8_t width) {
return (((color&0xFF0000)/width)&0xFF0000) + (((color&0x00FF00)/width)&0x00FF00) + (((color&0x0000FF)/width)&0x0000FF);
}
// Using a counter and for() loop, input a value 0 to 251 to get a color value.
// The colors transition like: red - org - ylw - grn - cyn - blue - vio - mag - back to red.
// Entering 255 will give you white, if you need it.
uint32_t colorWheel(byte WheelPos) {
byte state = WheelPos / 21;
switch(state) {
case 0: return pixels.Color(255, 0, 255 - ((((WheelPos % 21) + 1) * 6) + 127)); break;
case 1: return pixels.Color(255, ((WheelPos % 21) + 1) * 6, 0); break;
case 2: return pixels.Color(255, (((WheelPos % 21) + 1) * 6) + 127, 0); break;
case 3: return pixels.Color(255 - (((WheelPos % 21) + 1) * 6), 255, 0); break;
case 4: return pixels.Color(255 - (((WheelPos % 21) + 1) * 6) + 127, 255, 0); break;
case 5: return pixels.Color(0, 255, ((WheelPos % 21) + 1) * 6); break;
case 6: return pixels.Color(0, 255, (((WheelPos % 21) + 1) * 6) + 127); break;
case 7: return pixels.Color(0, 255 - (((WheelPos % 21) + 1) * 6), 255); break;
case 8: return pixels.Color(0, 255 - ((((WheelPos % 21) + 1) * 6) + 127), 255); break;
case 9: return pixels.Color(((WheelPos % 21) + 1) * 6, 0, 255); break;
case 10: return pixels.Color((((WheelPos % 21) + 1) * 6) + 127, 0, 255); break;
case 11: return pixels.Color(255, 0, 255 - (((WheelPos % 21) + 1) * 6)); break;
default: return pixels.Color(0, 0, 0); break;
}
}
// Cycles - one cycle is scanning through all pixels left then right (or right then left)
// Speed - how fast one cycle is (32 with 16 pixels is default KnightRider speed)
// Width - how wide the trail effect is on the fading out LEDs. The original display used
// light bulbs, so they have a persistance when turning off. This creates a trail.
// Effective range is 2 - 8, 4 is default for 16 pixels. Play with this.
// Color - 32-bit packed RGB color value. All pixels will be this color.
// knightRider(cycles, speed, width, color);
void knightRider(uint16_t cycles, uint16_t speed, uint8_t width, uint32_t color) {
uint32_t old_val[NUMPIXELS]; // up to 256 lights!
// Larson time baby!
for(int i = 0; i < cycles; i++){
for (int count = 1; count<NUMPIXELS; count++) {
pixels.setPixelColor(count, color);
old_val[count] = color;
for(int x = count; x>0; x--) {
old_val[x-1] = dimColor(old_val[x-1], width);
pixels.setPixelColor(x-1, old_val[x-1]);
}
pixels.show();
delay(speed);
}
for (int count = NUMPIXELS-1; count>=0; count--) {
pixels.setPixelColor(count, color);
old_val[count] = color;
for(int x = count; x<=NUMPIXELS ;x++) {
old_val[x-1] = dimColor(old_val[x-1], width);
pixels.setPixelColor(x+1, old_val[x+1]);
}
pixels.show();
delay(speed);
}
}
}
void pixelSetBrightness(int brightPercentage) {
//pixels.setBrightness(__brightness) is too lossy
float __newR, __newG, __newB;
__newR = _currentColour.r*brightPercentage / 100;
__newG = _currentColour.g*brightPercentage / 100;
__newB = _currentColour.b*brightPercentage / 100;
for (int i = 0; i < NUMPIXELS; i++) {
// pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
pixels.setPixelColor(i, pixels.Color((int)__newR, (int)__newG, (int)__newB)); // set rgb values
}
pixels.show();
}
///////////////////// loading neopixel //////////////////////////////////
uint32_t Wheel(byte WheelPos) {
if (WheelPos < 85) {
return (pixels.Color(WheelPos * 3, 255 - WheelPos * 3, 0) * 3);
}
else if (WheelPos < 170) {
WheelPos -= 85;
return (pixels.Color(255 - WheelPos * 3, 0, WheelPos * 3) * .3);
}
else {
WheelPos -= 170;
return (pixels.Color(0, WheelPos * 3, 255 - WheelPos * 3) * .3);
}
}
void loading_colors() {
DEBUG_PRINTLN("Loading Colours");
knightRider(3, 32, 2, 0xFFFFFF);
knightRider(3, 32, 2, 0xFFFFFF);
}
void loadingWheel(){
uint16_t i, j;
for (j = 0; j < 256; j++) {
for (i = 0; i < NUMPIXELS; i++) {
pixels.setPixelColor(i, Wheel((i + j) & 200));
}
pixels.setBrightness(_brightness);
pixels.show();
delay(10);
}
}
///////////////////// clear neopixel //////////////////////////////////
void clearcolors(bool _delay) {
DEBUG_PRINTLN("Clear Colours");
for (int i = 0; i < NUMPIXELS; i++) {
// pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
pixels.setPixelColor(i, pixels.Color(0, 0, 0)); // set rgb values
pixels.show(); // This sends the updated pixel color to the hardware.
if (_delay) delay(100);
}
}
// Pause = delay between transitions
// Steps = number of steps
// R, G, B = "Full-on" RGB values
void breathe2(int pause, int steps, byte R, byte G, byte B) {
int tmpR, tmpG, tmpB; // Temp values
// Fade down
for (int s = steps; s > 0; s--) {
tmpR = (R * s * _brightness) / steps / 100; // Multiply first to avoid truncation errors
tmpG = (G * s * _brightness) / steps / 100;
tmpB = (B * s * _brightness) / steps / 100;
for (int i = 0; i < NUMPIXELS; i++) {
pixels.setPixelColor(i, tmpR, tmpG, tmpB);
}
pixels.show();
delay(pause);
}
// Fade back up
for (int s = 1; s <= steps; s++) {
tmpR = (R * s * _brightness) / steps / 100; // Multiply first to avoid truncation errors
tmpG = (G * s * _brightness) / steps / 100;
tmpB = (B * s * _brightness) / steps / 100;
for (int i = 0; i < NUMPIXELS; i++) {
pixels.setPixelColor(i, tmpR, tmpG, tmpB);
}
pixels.show();
delay(pause);
}
}
<file_sep>/espTransitNeopix.ino
#include <FS.h> //this needs to be first, or it all crashes and burns...
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <ArduinoJson.h>
#include <Adafruit_NeoPixel.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPUpdateServer.h>
#include <ESP8266mDNS.h>
#include <ESP8266HTTPClient.h>
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
#include "StructDefs.h"
#define DEBUG 1
#ifdef DEBUG
#define DEBUG_PRINT(x) Serial.print (x)
#define DEBUG_PRINTDEC(x,DEC) Serial.print (x, DEC)
#define DEBUG_PRINTLN(x) Serial.println (x)
#define DEBUG_PRINTLNDEC(x,DEC) Serial.println (x, DEC)
#else
#define DEBUG_PRINT(x)
#define DEBUG_PRINTDEC(x,DEC)
#define DEBUG_PRINTLN(x)
#define DEBUG_PRINTLNDEC(x,DEC)
#endif
char mqtt_clientname[60] = "esptransit";
WiFiClient espClient;
String _lastMQTTMessage = "";
ESP8266HTTPUpdateServer _httpUpdater;
const char* _updateWebPath = "/firmware";
const char* _updateWebUsername = "admin";
const char* _updateWebPassword = "<PASSWORD>";
const char* _wifiAP = "********";
const char* _wifiAPPwd = "********";
ESP8266WebServer _httpServer(80);
String __webClientReturnString = "";
const char* host = "maps.googleapis.com";
const int httpsPort = 443;
float _normalDuration = 0;
float _transitDuration = 0;
float _tempVal = 0;
bool _displayTemp = false;
const long timebetweenruns = 5 * 60 * 1000; //300 000 = 5 min
const long timebetweenanimationruns = 60 * 1000; //every 60 seconds
const long timebetweentransitanimationruns = 15 * 1000; //every 15 seconds
unsigned long currentrun; //set variable to time store
unsigned long animationrun; //set variable to time store
unsigned long transitrun; //set variable to time store
unsigned long animationtransitrun; //set variable to time store
void SetIsDisplayOn(bool __isOn) {
if (__isOn==false)
clearcolors(true);
_isDisplayOn = __isOn;
}
String IpAddress2String(const IPAddress& ipAddress) {
return String(ipAddress[0]) + String(".") + \
String(ipAddress[1]) + String(".") + \
String(ipAddress[2]) + String(".") + \
String(ipAddress[3]);
}
void fetchTransit() {
DEBUG_PRINTLN("Fetching Transit Info");
// Use WiFiClientSecure class to create TLS connection
WiFiClientSecure client;
DEBUG_PRINT("connecting to ");
DEBUG_PRINTLN(host);
if (!client.connect(host, httpsPort)) {
DEBUG_PRINTLN("connection failed");
return;
}
String url = "/maps/api/distancematrix/json?units=metric&origins=1+Sandton+Drive&destinations=3+Melrose+Boulevard&Transit_model=best_guess&key=<KEY>&departure_time=now";
DEBUG_PRINT("requesting URL: ");
DEBUG_PRINTLN(url);
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"User-Agent: BuildFailureDetectorESP8266\r\n" +
"Connection: close\r\n\r\n");
DEBUG_PRINTLN("request sent");
while (client.connected()) {
String line = client.readStringUntil('\n');
if (line == "\r") {
DEBUG_PRINTLN("headers received");
break;
}
}
String line = "";
String json = "";
boolean httpBody = false;
while (client.available()) {
line = client.readStringUntil('\r');
json += line;
}
StaticJsonBuffer<1000> jsonBuffer;
DEBUG_PRINTLN("Got data:");
DEBUG_PRINTLN(json);
JsonObject& _jsonTransitObjRoot = jsonBuffer.parseObject(json);
_normalDuration = _jsonTransitObjRoot["rows"][0]["elements"][0]["duration"]["value"];
DEBUG_PRINT("Normal duration: ");
DEBUG_PRINTLN(_normalDuration);
_transitDuration = _jsonTransitObjRoot["rows"][0]["elements"][0]["duration_in_traffic"]["value"];
DEBUG_PRINT("Transit duration: ");
DEBUG_PRINTLN(_transitDuration);
DEBUG_PRINTLN("==========");
DEBUG_PRINTLN("closing connection");
// close any connection before send a new request.
// This will free the socket on the WiFi shield
client.stop();
}
///////////////////// Transit Mode //////////////////////////////////
void updateTransitColours() {
fetchTransit();
float __percentageDiff = 0;
//// set RGB colors for the quickest commute and before
if (_transitDuration < _normalDuration) {
_currentColour = {255, 255, 255};
}
else
{
__percentageDiff = (_transitDuration / _normalDuration) * 100;
_currentColour = findColourInRange(__percentageDiff);
fade(_oldColour, _currentColour);
_oldColour = _currentColour;
OutputColour(_currentColour);
}
}
void setupHTTPUpdateServer() {
_httpUpdater.setup(&_httpServer, _updateWebPath, _updateWebUsername, _updateWebPassword);
MDNS.addService("http", "tcp", 80);
DEBUG_PRINTLN("HTTPUpdateServer ready! Open http://" + String(mqtt_clientname) + String(_updateWebPath) + " in your browser and login with username " + String(_updateWebUsername) + " and password " + String(_updateWebPassword) + "\n");
}
void setupWebServer() {
DEBUG_PRINTLN("Handling Web Request...");
_httpServer.on("/", []() {
__webClientReturnString = "<HTML>";
__webClientReturnString += "<HEAD>";
__webClientReturnString += "<TITLE>MCMD Arduino</TITLE>";
__webClientReturnString += "</HEAD>";
__webClientReturnString += "<style>body {font: normal 12px Calibri, Arial;}</style>";
__webClientReturnString += "<BODY>";
__webClientReturnString += "<H1>" + String(mqtt_clientname) + " Control</H1>";
__webClientReturnString += "<hr><a href=\"/sendstat\">MQTT, re-read& send status</a><br>";
__webClientReturnString += "<hr><a href=\"/firmware\">Upgrade Firmware</a><br>";
__webClientReturnString += "<hr><a href=\"/displayon\">Display On</a><br>";
__webClientReturnString += "<a href=\"/displayoff\">Display Off</a><br>";
__webClientReturnString += "<hr><br>Transit without Traffic: " + String(_normalDuration / 60,2) + " minutes";
__webClientReturnString += "<br>Transit <b>with</b> Traffic: " + String(_transitDuration / 60,2) + " minutes";
float __percTransit = (_transitDuration / _normalDuration) * 100;
__webClientReturnString += "<br>Traffic / Transit: " + String(__percTransit,2) + " \%";
__webClientReturnString += "<br><a href=\"/UpdateTransit\">Update Transit</a><br>";
__webClientReturnString += "<hr><br>IP Address: " + IpAddress2String(WiFi.localIP());
__webClientReturnString += "<br>MAC Address: " + WiFi.macAddress();
__webClientReturnString += "<br>Last MQTT message recieved: " + _lastMQTTMessage;
__webClientReturnString += "</BODY>";
__webClientReturnString += "</HTML>";
_httpServer.send(200, "text/html", __webClientReturnString);
});
DEBUG_PRINTLN("Arg(0): " + _httpServer.argName(0));
_httpServer.on("/UpdateTransit", []() {
fetchTransit();
_httpServer.send(200, "text/plain", String("{\"state\": \"true\"}"));
});
_httpServer.on("/displayon", []() {
SetIsDisplayOn(true);
_httpServer.send(200, "text/plain", String("{\"state\": \"true\"}"));
});
_httpServer.on("/displayoff", []() {
SetIsDisplayOn(false);
_httpServer.send(200, "text/plain", String("{\"state\": \"false\"}"));
});
_httpServer.on("/reset", []() {
_httpServer.send(200, "text/plain", "Resetting");
ESP.reset();
});
DEBUG_PRINTLN("Web Request Completed...");
}
void setup() {
#ifdef DEBUG
Serial.begin(115200);
#endif // DEBUG
WiFi.begin(_wifiAP,_wifiAPPwd);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
DEBUG_PRINTLN(".");
}
DEBUG_PRINTLN("");
DEBUG_PRINTLN("WiFi connected");
// Print the IP address
DEBUG_PRINTLN(WiFi.localIP());
// Start the server
DEBUG_PRINTLN("Web Server config");
setupWebServer();
DEBUG_PRINTLN("Update Server config");
setupHTTPUpdateServer();
DEBUG_PRINTLN("Server starting");
_httpServer.begin();
MDNS.begin(mqtt_clientname);
pixels.begin();
currentrun = millis();
loading_colors(); // loading light sequence
updateTransitColours();
}
void loop() {
// Check if a client has connected
_httpServer.handleClient();
if (_isDisplayOn) {
currentrun = millis(); //sets the counter
//transit update
if (currentrun - transitrun >= timebetweenruns) {
DEBUG_PRINTLN("loading transit"); //for reference
transitrun = currentrun;
loading_colors(); // loading light sequence
updateTransitColours(); //update traffic info
}
//transit animation
if (currentrun - animationtransitrun >= timebetweentransitanimationruns) {
DEBUG_PRINTLN("transit animation"); //for reference
animationtransitrun = currentrun;
breathe2(50, 250, _currentColour.r, _currentColour.g, _currentColour.b);
}
}
}
|
d1d8a2643cde64f48a0a60c719878f8a78ae9933
|
[
"C",
"C++"
] | 2 |
C
|
merlinmb/espTransitNeoPixel
|
17b45f1b440184f713716d50b1976c7fc5a71f86
|
785d39b76cdfd9e54d00c60f7f2f6513f7c095b1
|
refs/heads/master
|
<repo_name>jevgen/Code-Snippets<file_sep>/Functions/Security/hide-wp-version.php
<?php
// Hide WordPress Version
function sl_remove_version() {
return '';
}
add_filter('the_generator', 'sl_remove_version');
// While this line removes the WordPress version from the head tags and the RSS Feeds, you will still need to remove the readme.html file from the root of your WordPress install
?><file_sep>/Functions/Admin-Dashboard/block-profile-and-redirect.php
<?php
// source: http://www.shinephp.com/how-to-block-wordpress-admin-menu-item/
// block profile menu for users with role subscriber
if ( is_user_logged_in() ) {
if (current_user_can('subscriber')) {
function remove_profile_submenu() {
global $submenu;
//remove Your profile submenu item
unset($submenu['profile.php'][5]);
}
add_action('admin_head', 'remove_profile_submenu');
function remove_profile_menu() {
global $menu;
// remove Profile top level menu
unset($menu[70]);
}
add_action('admin_head', 'remove_profile_menu');
function profile_redirect() {
$result = stripos($_SERVER['REQUEST_URI'], 'profile.php');
if ($result!==false) {
wp_redirect(get_option('siteurl') . '/wp-admin/index.php');
}
}
add_action('admin_menu', 'profile_redirect');
}
}
// end of block profile menu for users with role
<file_sep>/Functions/Admin-Dashboard/conditional-function-based-on-id-role-caps.php
<?php // conditional function based on ID / role / capabilities
function my_custom_dash() {
$user_id = get_current_user_id();
if ($user_id == 1) { // is one specific admin role
// Show This
} elseif (!current_user_can('administrator')) { // is not the administrator
// Show That
} elseif (!current_user_can('manage_options')) { // cannot manage options
} else {
//rest can see everything they can in that role
}
}
add_action('admin_head', 'my_custom_dash');
// needs to be used in combination with another function, for example: disable-sidebar-menus-4functions.php OR remove-dashboard-widgets.php
// REMOVE DASHBOARD MENUS FOR CERTAIN USERS - http://wordpress.stackexchange.com/questions/20942/allow-user-access-to-dashboard-only/20943#20943
// DOES NOT ENTIRELY WORK AND ONLY HIDES...
function hide_menu_items() {
global $submenu;
global $menu;
global $user_ID;
if( $user_ID ) :
/* Dashboard only acccess */
$user_id = get_current_user_id();
if ($user_id == 2) :
$restricted = array(
__('Links'),
__('Comments'),
__('Appearance'),
__('Plugins'),
__('Tools'),
__('Settings')
);
endif;
endif;
end ( $menu );
while ( prev( $menu ) ) :
$value = explode( ' ', $menu[key($menu)][0] );
if( in_array( $value[0] != NULL?$value[0]:"" , $restricted ) ) :
unset( $menu[key($menu)] );
endif;
endwhile;
}
add_action('admin_head', 'hide_menu_items');<file_sep>/WPML/simple-language-menu.php
<?php
// Add a simple EN / 中文 Language Switcher to a site that runs with the WPML plugin
// Add to functions.php or functionality plugin:
if (!function_exists('so_language_menu'))
{
function so_language_menu()
{
if (function_exists('icl_get_languages'))
{
$languages = icl_get_languages('orderby=name&order=ASC'); // you can change the parameters
$counter = 0;
if(!empty($languages))
{
echo '<ul class="lang-nav">';
foreach($languages as $l)
{
$counter += 1;
if ($l['active'])
continue;
echo '<li id="'.$l['language_code'].'">';
echo '<a href="'.$l['url'].'">';
if ($l['language_code'] == 'en') echo 'EN'; // Change this into any other language
elseif ($l['language_code'] == 'zh-hans') echo urldecode('%E4%B8%AD%E6%96%87'); // Change this into any other language
echo '</a>';
if ($counter < sizeof($languages)) echo ' | '; // optional line as a separator between languages
echo '</li>';
}
echo '</ul>';
}
}
}
}
?>
<?php
// Call in theme (header):
?>
<?php so_language_menu(); ?>
<file_sep>/Functions/Comments/remove-url-field.php
<?php //Remove URL field from comment form
function remove_comment_fields($fields) {
unset($fields['url']);
return $fields;
}
add_filter('comment_form_default_fields','remove_comment_fields');<file_sep>/Functions/Admin-Dashboard/disable-sidebar-menus-4functions.php
<?php
function remove_menus () {
global $menu;
$restricted = array(__('Links')); // OR $restricted = array(__('Links'), __('Media'));
end ($menu);
while (prev($menu)){
$value = explode(' ',$menu[key($menu)][0]);
if(in_array($value[0] != NULL?$value[0]:"" , $restricted)){unset($menu[key($menu)]);}
}
}
add_action('admin_menu', 'remove_menus');
// menu is made invisible, URL is still there!
function remove_top_level_menu() {
global $menu;
//remove post top level menu
unset($menu[5]);
}
add_action('admin_head', 'remove_top_level_menu');
// menu is made invisible, URL is still there!
function remove_sub_menu() {
global $submenu;
//remove Theme editor
unset($submenu['themes.php'][10]);
}
add_action('admin_head', 'remove_sub_menu');
// everything gone including URLs; menus of plugins need to be added separately
function remove_all_menus () {
global $menu, $submenu, $user_ID;
$the_user = new WP_User($user_ID);
$valid_page = "admin.php?page=contact-form-7/admin/admin.php"; // only contactform7 is allowed
$restricted = array('index.php','edit.php','categories.php','upload.php','link-manager.php','edit-pages.php','edit-comments.php', 'themes.php', 'plugins.php', 'users.php', 'profile.php', 'tools.php', 'options-general.php');
$restricted_str = 'widgets.php';
end ($menu);
while (prev($menu)){
$menu_item = $menu[key($menu)];
$restricted_str .= '|'.$menu_item[2];
if(in_array($menu_item[2] , $restricted)){
$submenu_item = $submenu[$menu_item[2]];
if($submenu_item != NULL){
$tmp = $submenu_item;
$max = array_pop(array_keys($tmp));
for($i = $max; $i > 0;$i-=5){
if($submenu_item[$i] != NULL){
$restricted_str .= '|'.$submenu[$menu_item[2]][$i][2];
unset($submenu[$menu_item[2]][$i]);
}
}
}
unset($menu[key($menu)]);
}
}
$result = preg_match('/(.*?)\/wp-admin\/?('.$restricted_str.')??(('.$restricted_str.'){1})(.*?)/',$_SERVER['REQUEST_URI']);
if ($result != 0 && $result != FALSE){
wp_redirect(get_option('siteurl') . '/wp-admin/' . $valid_page);
exit(0);
}
}
add_action('admin_menu', 'remove_all_menus');
<file_sep>/WPML/lang-select-flags-only.php
<?php
// Add to FUNCTIONS.PHP WPML Function to show flags in top navigation
function language_selector_flags(){
$languages = icl_get_languages('skip_missing=0&orderby=code');
if(!empty($languages)){
foreach($languages as $l){
if(!$l['active']) echo '<a href="'.$l['url'].'">';
echo '<img src="'.$l['country_flag_url'].'" height="12" alt="'.$l['language_code'].'" width="18" />';
if(!$l['active']) echo '</a>';
}
}
}
?>
<?php // Add to Navigation Menu (HEADER.PHP) or somewhere else to show on website ?>
<div id="flags_language_selector"><?php language_selector_flags(); ?></div><!-- added to show flags for selecting languages -->
</div><file_sep>/Functions/Admin-Dashboard/profile-custom-contact-fields.php
<?php
/** CUSTOM CONTACT FIELDS PROFILE - http://yoast.com/wordpress-rel-author-rel-me/ **/
function yoast_add_google_profile( $contactmethods ) {
// Add Social Media Profiles
$contactmethods['google_profile'] = 'Google Profile URL';
$contactmethods['linkedin_profile'] = 'LinkedIn Profile URL';
$contactmethods['twitter'] = 'Twitter URL';
$contactmethods['facebook'] = 'Facebook Page';
// Remove annoying and unwanted default fields
unset($contactmethods['aim']);
unset($contactmethods['jabber']);
unset($contactmethods['yim']);
return $contactmethods;
}
add_filter( 'user_contactmethods', 'yoast_add_google_profile', 10, 1);
/** END CUSTOM CONTACT FIELDS PROFILE **/
?><file_sep>/Functions/Admin-Dashboard/disable-password-field-non-admins.php
<?php
// disable password field on profile for non-administrators - http://wpengineer.com/2285/disable-password-fields-for-non-admins/
if ( is_admin() )
add_action( 'init', 'disable_password_fields', 10 );
function disable_password_fields() {
if ( ! current_user_can( 'administrator' ) )
$show_password_fields = add_filter( 'show_password_fields', '__return_false' );
}
?><file_sep>/Functions/Navigation/highlighting-wp_nav_menu-ancestor-children-custom-post-types.php
<?php // The code below then finds the menu item with this class CPT-menu-item and adds another “current_page_parent” class to it. Furthermore, it removes the “current_page_parent” from the blog menu item, if this is present. Via http://vayu.dk/highlighting-wp_nav_menu-ancestor-children-custom-post-types/
add_filter('nav_menu_css_class', 'current_type_nav_class', 10, 2);
function current_type_nav_class($classes, $item) {
// Get post_type for this post
$post_type = get_query_var('post_type');
// Removes current_page_parent class from blog menu item
if ( get_post_type() == $post_type )
$classes = array_filter($classes, "get_current_value" );
// Go to Menus and add a menu class named: {custom-post-type}-menu-item
// This adds a current_page_parent class to the parent menu item
if( in_array( $post_type.'-menu-item', $classes ) )
array_push($classes, 'current_page_parent');
return $classes;
}
function get_current_value( $element ) {
return ( $element != "current_page_parent" );
}<file_sep>/Functions/Admin-Dashboard/customize-dashboard-footer.php
<?php
// CUSTOMIZE DASHBOARD FOOTER
function remove_footer_admin ()
{
echo '<span id="footer-thankyou">';
echo '__("Custom Footer Text ", "text-domain")';
echo '<a href="#" target="_blank">';
echo '__("Link", "text-domain")';
echo '</a></span>';
}
add_filter('admin_footer_text', 'remove_footer_admin');
<file_sep>/Functions/Posts/add-post-content.php
<?php
// Insert custom content after each post http://digwp.com/2010/04/wordpress-custom-functions-php-template-part-2/
function add_post_content($content) {
if(!is_feed() && !is_home()) {
$content .= '<p>This article is copyright © '.date('Y').' '.bloginfo('name').'</p>';
}
return $content;
}
add_filter('the_content', 'add_post_content');<file_sep>/Functions/Admin-Dashboard/increase-height-excerpt-box.php
<?php // Increase Height Excerpt Box (source: 1st snippet on http://spyrestudios.com/17-time-saving-code-snippets-for-wordpress-developers/)
add_action('admin_head', 'excerpt_textarea_height');
function excerpt_textarea_height() {
echo'
<style type="text/css">
#excerpt{ height:500px; }
</style>
';
}<file_sep>/Functions/Pages/change-default-page-title-box-text.php
<?php //Change default Post title box text
function title_text_input( $title ){
return $title = __('Random text of your choosing', 'text-domain');
}
add_filter( 'enter_title_here', 'title_text_input' );<file_sep>/Functions/Security/protect-whole-site.php
<?php // Protect Whole Site snippet
function protect_whole_site() {
if ( !is_user_logged_in() ) {
auth_redirect();
}
}
add_action ('template_redirect', 'protect_whole_site');<file_sep>/Functions/SEO/meta-description-from-content.php
<?php
// Create Meta Description from Content
// source: http://www.paulund.co.uk/automatically-create-meta-description-from-content
function sl_create_meta_desc() {
global $post;
if (!is_single()) { return; }
$meta = strip_tags($post->post_content);
$meta = strip_shortcodes($post->post_content);
$meta = str_replace(array("\n", "\r", "\t"), ' ', $meta);
$meta = substr($meta, 0, 125); // number of characters it takes from the content and uses as meta description
echo "<meta name='description' content='$meta' />";
}
add_action('wp_head', 'sl_create_meta_desc');<file_sep>/Functions/Admin-Dashboard/edit-help-text.php
<?php
// Dashboard: Edit Help Dropdown Text in various places
// source: http://sixrevisions.com/wordpress/10-techniques-for-customizing-the-wordpress-admin-panel/ tip #7
// If you take a look at the top right of the WordPress Admin panels you’ll see a button that says "Help." When you click it, Help text slides down.
// This is a great place to add your own custom Help text for a client. You can even customize it for different Admin panels. For example, you can add a different Help text for the Add New Post panel and another one for the Comments panel.
// Here’s how you go about it:
add_action('load-page-new.php','custom_help_page');
add_action('load-page.php','custom_help_page');
function custom_help_page() {
add_filter('contextual_help','custom_page_help');
}
function custom_page_help($help) {
// echo $help; // Uncomment if you just want to append your custom Help text to the default Help text
echo "<h5>Custom Help text</h5>";
echo "<p> HTML goes here.</p>";
}
// To find what file you should add the action to, just check the address bar in your browser and add the load- prefix right before the file name. For example, if you wanted to add the custom Help text to the Add New Post panel, which has a file name of post-new.php, then you would use load-post-new.php as the parameter of the add_action function shown above.<file_sep>/Functions/Admin-Dashboard/customize-dashboard-header-logo.php
<?php
// CUSTOMIZE DASHBOARD HEADER LOGO
function custom_admin_logo() {
echo '<style type="text/css">#header-logo { background-image: url('.get_bloginfo('stylesheet_directory').'/images/logo_admin_dashboard.png) !important; }</style>';
}
add_action('admin_head', 'custom_admin_logo');<file_sep>/Functions/Posts/display-message-on-older-posts.php
<?php //display a message on older posts
function older_post_message () {
$posted = get_the_time('U');
$current = current_time('timestamp');
//Convert difference in seconds to days
$diffTime = ($current - $posted) / (60*60*24);
if($diffTime > 365){
echo '<div class=older-post-message>' . __('This post was written more than a year ago and <em>might</em> not be entirely accurate anymore.', 'wptips') . '</div><br />';
}
}
add_action('get_template_part_content','older_post_message');<file_sep>/Functions/Admin-Dashboard/customize-login-screen-3functions.php
<?php // CUSTOM ADMIN LOGIN HEADER LOGO
function my_custom_login_logo()
{
echo '<style type="text/css"> h1 a { background-image:url('.get_bloginfo('template_directory').'/images/logo_admin.png) !important; } </style>';
}
add_action('login_head', 'my_custom_login_logo');
// CUSTOM ADMIN LOGIN LOGO LINK
function change_wp_login_url()
{
echo bloginfo('url'); // OR ECHO YOUR OWN URL
}
add_filter('login_headerurl', 'change_wp_login_url');
// CUSTOM ADMIN LOGIN LOGO & ALT TEXT
function change_wp_login_title()
{
echo get_option('blogname'); // OR ECHO YOUR OWN ALT TEXT
}
add_filter('login_headertitle', 'change_wp_login_title');
<file_sep>/Functions/Admin-Dashboard/redirect-user-after-login.php
<?php
// redirect user after login not to go to profile, but elsewhere
// combination of http://www.shinephp.com/how-to-block-wordpress-admin-menu-item/ and
// http://www.strangework.com/2010/03/26/how-to-redirect-a-user-after-logging-into-wordpress/
if (current_user_can('subscriber')) {
function redirect_after_login() {
global $redirect_to;
if (!isset($_GET['redirect_to'])) {
$redirect_to = (get_option('siteurl') . '/wp-admin/rest-of-url');
}
}
add_action('login_form', 'redirect_after_login');
}
// end of redirect function
<file_sep>/Functions/Navigation/add-searchbox-navigation.php
<?php
// ADD SEARCH BOX TO NAVIGATION
function add_search_box($items, $args) {
ob_start();
get_search_form();
$searchform = ob_get_contents();
ob_end_clean();
$items .= '<li class="nav_search">' . $searchform . '</li>';
return $items;
}
add_filter('wp_nav_menu_items','add_search_box', 10, 2);
// END ADD SEARCH BOX
?><file_sep>/Functions/General/add-favicon-to-site.php
<?php
// add a favicon to your site I
function blog_favicon() {
echo '<link rel="Shortcut Icon" type="image/x-icon" href="'.get_bloginfo('wpurl').'/favicon.ico" />';
}
add_action('wp_head', 'blog_favicon');
// add favicon to your site II
function add_favicon() {
echo '<link rel="shortcut icon" href="<?php echo bloginfo("stylesheet_directory") ?>/images/favicon.ico"/>';
}
add_action('wp_head', 'add_favicon');
// add favicon to your site III: use Gravatar as favicon (source: http://wp-snippets.com/2129/gravatar-as-favicon/)
//STEP 1: add to functions.php
function GravatarAsFavicon() {
//We need to establish the hashed value of your email address
$GetTheHash = md5(strtolower(trim('<EMAIL>'))); // change to your own email address
echo 'http://www.gravatar.com/avatar/' . $GetTheHash . '?s=16';
}
//STEP 2: add to header.php, before </head> closing tag ?>
<link rel="shortcut icon" href="<?php GravatarAsFavicon(); ?>" />
<?php
// add favicon to your site IV
function my_favicon() { ?>
<link rel="shortcut icon" href="yourimagepathgoeshere" >
<?php }
add_action('wp_head', 'my_favicon');
|
a3e412a270958eb768f9a7d9f680ff4cb9390dc7
|
[
"PHP"
] | 23 |
PHP
|
jevgen/Code-Snippets
|
a747c4e4a82ccb4473ef0aaf4e4c83ba51dbd811
|
180c13e565a3338b199a9b00bdedea265b1abafa
|
refs/heads/master
|
<file_sep># -*- coding=utf-8 -*-
##########################################################
# Desc : Get PageRank of a Website, for Python2
# Author : iSayme
# E-Mail : <EMAIL>
# Website : http://www.isayme.org
# Date : 2012-09-18
##########################################################
import os
import time
import urllib
import platform
TOP_DIR = ""
COUNTRY = "en-US"
def get_platform():
return platform.system()
def get_bing_pic() :
# bing url
url = "http://www.bing.com/"
urllib.urlcleanup()
args = urllib.urlencode({"setmkt" : COUNTRY}, {"setlang" : "match"})
# open bing url
page = urllib.urlopen(url, args)
if None == page:
print('open %s error' % (url))
return -1
# get html souce code
data = page.read()
if not data:
print ('read %s content error' % url)
return -1
page.close()
# parse picture url
posleft = data.find(b'g_img={url:')
if -1 == posleft:
print ('jpg url not found')
return -1
posright = data.find(b'\'', posleft + 12)
if -1 == posright:
print ('jpg url not found')
return -1
jpgpath = data[posleft + 12 : posright].decode("ascii");
if 0 == cmp('/', jpgpath[0:1]):
jpgurl = url + jpgpath
else:
jpgurl = jpgpath
# make local file dir
if 0 == cmp('Windows', get_platform()):
localpath = TOP_DIR + time.strftime('bing\\%Y\\%m\\')
else:
localpath = TOP_DIR + time.strftime('bing/%Y/%m/')
if not os.path.exists(localpath):
os.makedirs(localpath)
# make local file path
localjpg = localpath + time.strftime('%d.jpg')
print ("remote file : %s" % jpgurl)
print ("local file : %s" % localjpg)
# download jpg file
urllib.urlretrieve(jpgurl, localjpg)
urllib.urlcleanup()
return 0
if __name__ == "__main__":
print ("start get bing day picture ...")
while 1:
if 0 == get_bing_pic():
print ("get picture ok")
break;
else:
print ("get picture error")
time.sleep(60)
|
c3adfd214c29d64e1e0db8d9c42111b2fd383292
|
[
"Python"
] | 1 |
Python
|
xyf514330947/get_bing_day_pic
|
65fbd0539c1da64c97876cace62b3bdbd00eb5f2
|
d4f034d0c30cf28017f4153d8bbdc26e244755a9
|
refs/heads/master
|
<file_sep>#!/usr/bin/env node
const process = require('process')
const yargs = require('yargs');
console.log('xxxx1',yargs.argv)
//dedent 可以百度一下
const dedent = require('dedent')
//用来解析参数的
const { hideBin } = require('yargs/helpers')
const arg = hideBin(process.argv); // qianmi-cli-dev --help 把脚手架命令后面的命令转成参数列表
console.log('参数',arg) //qianmi-cli-dev % qianmi-cli-dev hello --name 12 ---> [ 'hello', '--name', '12' ]
//参数列表传给yargs这个构造函数
/*
strict() 表示严格模式,当我们输入的参数和配置的参数不匹配,就会提示
usage()初始化一下信息
demandCommand(1,'xx') 至少输入一个命令,不输入就会提示xx
alias('h','help') 给help起个别名 h
wrap(100) 设置脚手架面板的宽度
wrap(cli.terminalWidth()) 设计脚手架面板的宽度填充终端
epilogue('Your own footer description') 在脚手架面板页脚自定义一段话
dedent(`xx`) 去除缩进,让文本顶行用的
options() 添加一组选项的,这个选项是对所有command都有效,对所有的command都能访问到
option()添加一个选项
group([],'') 对命令进行分组
*/
const cli = yargs(arg)
console.log('cli',cli.argv) // qianmi-cli-dev hello --name 12 ---> { _: [ 'hello' ], name: 12, '$0': 'qianmi-cli-dev' }
cli
.usage('qiammi-cli-dev [command] <options>')
.demandCommand(1,'A command is required. Pass --help to see all available commands and options.')
.strict()
.alias('h','help')
.alias('v','version')
.wrap(cli.terminalWidth())
.epilogue(dedent`
When a command fails, all logs are written to lerna-debug.log in the current working directory.
For more information, find our manual at https://github.com/lerna/lerna
`)
.options({
debug:{
type:'boolean',
describe:'Bootstrap debug mode',
alias:'d'
}
})
.option('registry',{
// type:'boolean',
// hidden:true //把这个命令隐藏了
type:'string',
describe:'Define global registry',
alias:'r'
})
.fail((err,msg)=>{
console.log('xxx',err,msg)
})
.recommendCommands()
.group(['debug'],'Dev Options')
.group(['registry'],'Extra Options')
.command('init [name]','Do init a project',(yargs)=>{
yargs
.option('name',{
type:'string',
describe:'Name of a project',
alias:'n'
})
},(yargs)=>{
console.log(yargs)
})
.command({
command:'list',
aliases:["ls", "la", "ll"],
describe: "List local packages",
builder:(yargs)=>{},
handler:(yargs)=>{
console.log(yargs)
}
})
.argv;
<file_sep>module.exports = {
sum(a,b){
return a+b
},
init({option,param}){
console.log('执行init流程',option,param)
}
}
|
0552a2b7e615067a021df032abf0b12c95f9ba0e
|
[
"JavaScript"
] | 2 |
JavaScript
|
521kwj/scaffolding
|
96809252b9605b8100b42cdf07d25f6011e01694
|
992ce3a0e23531134b0cf0540cd89fa93afd7278
|
refs/heads/master
|
<repo_name>Sedubald/prof-java-dev<file_sep>/src/test/java/de/fh/albsig/sauterse/tests/WeatherServletTests.java
package de.fh.albsig.sauterse.tests;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.junit.jupiter.api.Test;
import de.fh.albsig.sauterse.servlets.WeatherServlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class WeatherServletTests {
@Test
public void shouldReturnTextHtml() throws ServletException, IOException {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
when(request.getParameter("location")).thenReturn("Bitz");
when(request.getParameter("country")).thenReturn("de");
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
when(response.getWriter()).thenReturn(writer);
new WeatherServlet().doGet(request, response);
assertTrue(stringWriter != null);
assertFalse(stringWriter.toString().equals(""));
}
@Test
public void shouldReturnErrorCode() throws ServletException, IOException {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
when(request.getParameter("location")).thenReturn("Bitz");
when(response.getStatus()).thenReturn(400);
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
when(response.getWriter()).thenReturn(writer);
new WeatherServlet().doGet(request, response);
assertEquals(400, response.getStatus());
}
}
<file_sep>/README.md
# prof-java-dev
Seminar paper for the college.
# Setup
The project was developed with Windows.
If you run the application under Linux you have to adjust some paths.
## pom.xml
The descriptor path of the maven-assembly-plugin has to be changed to src/assembly/dep.xml
## dep.xml
The output directory nodes have to be changed to /
The directory under fileSet has to be ${project.build.directory}/site
# Code checks
You can run the following commands to check the code:
mvn checkstyle:check
mvn pmd:check
mvn findbugs:check
#Running the application
Start the Jetty server with the command mvn jetty:run.
Navigate to http://localhost:8080/prof-java-dev.
You will get an user interface which provides the possibility of a location and country input.
Or you are able to navigate directly on the servlet by http://localhost:8080/prof-java-dev/WeatherServlet?location=albstadt&country=de
Of course you can pass other URL parameters.
<file_sep>/src/main/java/de/fh/albsig/sauterse/data/ExceptionData.java
package de.fh.albsig.sauterse.data;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author <NAME>.
*
*/
@XmlRootElement
public class ExceptionData {
/**
* The exception name.
*/
private String name;
/**
* The exception message.
*/
private String message;
/**
* Default constructor.
*/
public ExceptionData() {
super();
}
/**
*
* @param pName the exception name.
* @param pMessage the exception message.
*/
public ExceptionData(final String pName, final String pMessage) {
this.name = pName;
this.message = pMessage;
}
/**
*
* @return name.
*/
public final String getName() {
return name;
}
/**
*
* @param pName set name.
*/
@XmlElement
public final void setName(final String pName) {
this.name = pName;
}
/**
*
* @return message.
*/
public final String getMessage() {
return message;
}
/**
*
* @param pMessage set message.
*/
@XmlElement
public final void setMessage(final String pMessage) {
this.message = pMessage;
}
}
|
adc5bb8095bc5850f1533b119c69c5d33075e195
|
[
"Markdown",
"Java"
] | 3 |
Java
|
Sedubald/prof-java-dev
|
6e53ae44b593869f31680a70622e6a00354fe219
|
d413959b4c03a6154721f7fe6f7089a9dc4d05c2
|
refs/heads/main
|
<file_sep><?php
class OperationsFills
{
private $con;
function __construct()
{
require_once dirname(__FILE__) . '/db_connect.php';
$db = new DatabaseConnect();
$this->con = $db->connect();
}
function getFillInterval($startDate, $endDate, $id_equipo)
{
//intervalo de fechas temporales
$sqlFill = $this->con->prepare("
SELECT llenados.id, llenados.fecha, llenados.porcentaje, llenados.presion, llenados.temperatura, cilindros.tipo, equipos.nombre, operadores.nombre
FROM llenados, cilindros, equipos, operadores
WHERE llenados.cilindro=cilindros.id
AND llenados.equipo=equipos.id
AND llenados.operador=operadores.id
AND llenados.fecha
BETWEEN '".$startDate." 00:00:01' AND '". $endDate." 23:59:59' AND equipos.id =".$id_equipo);
$sqlFill->execute();
$sqlFill->bind_result($id, $fecha, $porcentaje, $presion, $temperatura, $cilindroTipo, $equipoNombre, $operadorNombre);
$fill_json = array();
while($sqlFill->fetch())
{
$fill_array = array();
$fill_array['id'] = $id;
$fill_array['fecha'] = $fecha;
$fill_array['porcentaje'] = $porcentaje;
$fill_array['presion'] = $presion;
$fill_array['temperatura'] = $temperatura;
$fill_array['cilindroTipo'] = $cilindroTipo;
$fill_array['equipoNombre'] = $equipoNombre;
$fill_array['operadorNombre'] = $operadorNombre;
array_push($fill_json, $fill_array);
}
return $fill_json;
}
function getCurrentFill($id_equipo)
{
$sqlCurrentFill = $this->con->prepare("SELECT llenados.temperatura, llenados.presion, llenados.porcentaje
FROM llenados, equipos
WHERE llenados.equipo=equipos.id
AND llenados.id= (SELECT MAX(id) FROM (SELECT * FROM llenados WHERE equipo = ".$id_equipo.") llenados)");
$sqlCurrentFill->execute();
$sqlCurrentFill->bind_result($temperature, $presion, $percentage);
$current_fill_json = array();
while($sqlCurrentFill->fetch())
{
$current_fill = array();
$current_fill['temperatura'] = $temperature;
$current_fill['presion'] = $presion;
$current_fill['porcentaje'] = $percentage;
array_push($current_fill_json, $current_fill);
}
return $current_fill_json;
}
function getDataNotifications()
{
$sqlNotifications = $this->con->prepare("
SELECT alarmas.id, alarmas.fecha, equipos.nombre, alarma_tipo.nombre
FROM alarmas, equipos, alarma_tipo
WHERE alarmas.equipo = equipos.id
AND alarmas.alarma_tipos = alarma_tipo.id
AND alarmas.`status` = 1");
$sqlNotifications->execute();
$sqlNotifications->bind_result($id, $fecha, $nombreEquipo, $alarmaTipo);
$notifications_json = array();
while($sqlNotifications->fetch())
{
$notifications_array = array();
$notifications_array['id'] = $id;
$notifications_array['fecha'] = $fecha;
$notifications_array['nombreEquipo'] = $nombreEquipo;
$notifications_array['alarmaTipo'] = $alarmaTipo;
array_push($notifications_json, $notifications_array);
}
return $notifications_json;
}
}<file_sep># InfraIIOT
Proyecto IIoT para Infra
<file_sep><?php
require_once 'db_operations_fills.php';
function isTheseParametersAvailable($params) {
$available = true;
$missingparams = "";
foreach ($params as $param) {
if (!isset($_POST[$param]) || strlen($_POST[$param]) <= 0) {
$available = false;
$missingparams = $missingparams . ", " . $param;
}
}
if (!$available) {
$response = array();
$response['error'] = true;
$response['message'] = 'Parameters ' . substr($missingparams, 1, strlen($missingparams)) . ' missing';
echo json_encode($response);
die();
}
}
$response = array();
#Si contienen la clave api_fills
if (isset($_GET['api_fills']))
{
#Dependiendo del valor de la clave se llamará una operación de BD
switch ($_GET['api_fills'])
{
#Obtiene los parametros de llanado para dasboards
case 'get_fill_interval':
$db = new OperationsFills();
$response['error'] = false;
$response['message'] = 'Solicitud completada exitosamente';
$response['fillsInterval'] = $db->getFillInterval($_GET['startDate'], $_GET['endDate'], $_GET['idEquipo']);
break;
#Obtiene la temperatura, presion y llenado en tiempo real
case 'get_current_fill':
$db = new OperationsFills();
$response['error'] = false;
$response['message'] = 'Solicitud completada exitosamente';
$response['currentFill'] = $db->getCurrentFill($_GET['idEquipo']);
break;
/*
#Obtiene la lista de alarmas disparadas
case 'get_alarm_list':
$db = new OperationsFills();
$response['error'] = false;
$response['message'] = 'Solicitud completada exitosamente';
$response['alarmList'] = $db->getAlarmList($_GET['startDate'], $_GET['endDate']);
break;
#Obtiene la lista de alarmas por grupo
case 'get_alarm_groups':
$db = new OperationsFills();
$response['error'] = false;
$response['message'] = 'Solicitud completada exitosamente';
$response['alarmGroups'] = $db->getAlarmGroups($_GET['startDate'], $_GET['endDate']);
break;
*/
case 'get_alarm_notification':
$db = new OperationsFills();
$response['error'] = false;
$response['message'] = 'Solicitud completada exitosamente';
$response['notification'] = $db->getDataNotifications();
break;
}
}
else
{
$response['error'] = true;
$response['message'] = 'Clave invalida al llamar al API';
}
echo json_encode($response);
<file_sep>const logout = document.querySelector('#logout');
logout.addEventListener('click', e => {
e.preventDefault();
auth.signOut().then(() => {
//console.log('sign out OK')
})
})
function initApp() {
// Listening for auth state changes.
firebase.auth().onAuthStateChanged(
function (user) {
if (!user) {
location.href = 'index.html';
//localStorage.setItem("User", "");
sessionStorage.setItem("User", "");
return;
}
});
//document.getElementById("userName").innerText = localStorage.getItem("User");
document.getElementById("userName").innerText = sessionStorage.getItem('User');
//setInterval(function(){
//}, 1000);
}
window.onload = function () {
initApp();
};<file_sep>var tempTemperature = 0;
var tempPressure = 0;
var tempPercentage = 0;
function getFillsGauges(idEquipo) {
jQuery.ajax({
type: "GET",
url: 'api_fills.php',
dataType: 'json',
data: {api_fills: 'get_current_fill', idEquipo: idEquipo},
success: function (obj)
{
document.getElementById("message").innerHTML = " ";
if (!obj.error && !jQuery.isEmptyObject(obj.currentFill))
{
if (tempTemperature !== obj.currentFill[0].temperatura ||
tempPressure !== obj.currentFill[0].presion ||
tempPercentage !== obj.currentFill[0].porcentaje) {
tempTemperature = obj.currentFill[0].temperatura;
tempPressure = obj.currentFill[0].presion;
tempPercentage = obj.currentFill[0].porcentaje;
buildGauges(
obj.currentFill[0].temperatura,
obj.currentFill[0].presion,
obj.currentFill[0].porcentaje);
}
} else
{
if (jQuery.isEmptyObject(obj.currentFill))
{
document.getElementById("message").innerHTML = "Sin datos del equipo";
}
}
}
});
}
function buildGauges(temperature, pressure, percentage)
{
//54°C temperatura maxima
//3200 PSI presion maxima
var tempVal = Math.round(((temperature * 100) / 54) * 10) / 10;
var presVal = Math.round(((pressure * 100) / 3200) * 10) / 10;
/*********Gauge temperatura**************/
var chart = am4core.create("gauge_temperature", am4charts.PieChart);
// Add data
chart.data = [{
"country": "Temperatura",
"value": tempVal
}, {
"country": "Restante",
"value": 100 - tempVal
}];
// Add and configure Series
var pieSeries = chart.series.push(new am4charts.PieSeries());
pieSeries.dataFields.value = "value";
pieSeries.dataFields.category = "country";
pieSeries.labels.template.disabled = true;
pieSeries.ticks.template.disabled = true;
//chart.legend = new am4charts.Legend();
//chart.legend.position = "right";
chart.innerRadius = am4core.percent(70);
var label = pieSeries.createChild(am4core.Label);
label.text = temperature.toString() + " °C";
label.fill = "#7d7d7d";
label.horizontalCenter = "middle";
label.verticalCenter = "middle";
label.fontSize = 20;
/*********Gauge presión**************/
var chart = am4core.create("gauge_presion", am4charts.PieChart);
// Add data
chart.data = [{
"country": "Presión",
"value": presVal
}, {
"country": "Restante",
"value": 100 - presVal
}];
// Add and configure Series
var pieSeries = chart.series.push(new am4charts.PieSeries());
pieSeries.dataFields.value = "value";
pieSeries.dataFields.category = "country";
pieSeries.labels.template.disabled = true;
pieSeries.ticks.template.disabled = true;
//chart.legend = new am4charts.Legend();
//chart.legend.position = "right";
chart.innerRadius = am4core.percent(70);
var label = pieSeries.createChild(am4core.Label);
label.text = pressure.toString() + " PSI";
label.fill = "#7d7d7d";
label.horizontalCenter = "middle";
label.verticalCenter = "middle";
label.fontSize = 20;
/*********Gauge porcentaje**************/
var chart = am4core.create("gauge_percentage", am4charts.PieChart);
// Add data
chart.data = [{
"country": "Porcentaje",
"value": percentage
}, {
"country": "Restante",
"value": 100 - percentage
}];
// Add and configure Series
var pieSeries = chart.series.push(new am4charts.PieSeries());
pieSeries.dataFields.value = "value";
pieSeries.dataFields.category = "country";
pieSeries.labels.template.disabled = true;
pieSeries.ticks.template.disabled = true;
//chart.legend = new am4charts.Legend();
//chart.legend.position = "right";
chart.innerRadius = am4core.percent(70);
var label = pieSeries.createChild(am4core.Label);
label.text = percentage.toString() + " %";
label.fill = "#7d7d7d";
label.horizontalCenter = "middle";
label.verticalCenter = "middle";
label.fontSize = 20;
}
$(document).ready(function () {
buildGauges(0, 0, 0);
getFillsGauges();
});
setInterval(
function ()
{
getFillsGauges(idEquipSelected);
}, 5000);
<file_sep>COLOR BARRA DE NAVEGACION (SIDEBAR)
-> Linea 17347
-> Path "assets/css/black-dashboard"
CARDS-CHART
- #272A3D
<file_sep><?php
class OperationsAlarms
{
private $con;
function __construct()
{
require_once dirname(__FILE__) . '/db_connect.php';
$db = new DatabaseConnect();
$this->con = $db->connect();
}
function getAlarmList($startDate, $endDate, $idEquipo)
{
$AlarmsSQL = $this->con->prepare("
SELECT alarmas.fecha, equipos.nombre, alarma_tipo.nombre
FROM alarmas, equipos, alarma_tipo
WHERE alarmas.equipo = equipos.id
AND alarmas.alarma_tipos = alarma_tipo.id
AND alarmas.fecha BETWEEN '".$startDate." 00:00:01' AND '". $endDate." 23:59:59'
AND equipos.id = ".$idEquipo.
" ORDER BY alarmas.fecha");
$AlarmsSQL->execute();
$AlarmsSQL->bind_result($fecha, $equiposNombre, $alarmasNombre);
$AlarmsJSON = array();
while($AlarmsSQL->fetch())
{
$AlarmsArray = array();
$AlarmsArray['fecha'] = $fecha;
$AlarmsArray['equiposNombre'] = $equiposNombre;
$AlarmsArray['alarmasNombre'] = $alarmasNombre;
array_push($AlarmsJSON, $AlarmsArray);
}
return $AlarmsJSON;
}
function getAlarmGroups($startDate, $endDate, $idEquipo)
{
$AlarmsSQL = $this->con->prepare("
SELECT alarma_tipo.nombre, count(alarma_tipo.nombre) total
FROM alarmas, equipos, alarma_tipo
WHERE alarmas.equipo = equipos.id
AND alarmas.alarma_tipos = alarma_tipo.id
AND alarmas.fecha BETWEEN '".$startDate." 00:00:01' AND '". $endDate." 23:59:59'
AND equipos.id = ".$idEquipo.
" GROUP BY alarma_tipo.nombre
");
$AlarmsSQL->execute();
$AlarmsSQL->bind_result($nombre, $total);
$AlarmsJSON = array();
while($AlarmsSQL->fetch())
{
$AlarmsArray = array();
$AlarmsArray['nombre'] = $nombre;
$AlarmsArray['total'] = $total;
array_push($AlarmsJSON, $AlarmsArray);
}
return $AlarmsJSON;
}
}<file_sep>const months = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Deciembre"];
var idEquipSelected = 1;
$(document).ready(function () {
var dt = new Date();
var firstDataDB = dt.getFullYear() + '-' + String(dt.getMonth() + 1).padStart(2, '0') + '-' + '01';
var today = dt.getFullYear() + '-' + String(dt.getMonth() + 1).padStart(2, '0') + '-' + String(dt.getUTCDate()).padStart(2, '0');;
function getNameURLWeb(){
var sPath = window.location.pathname;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
return sPage;
}
//Para obtener los datos de la página actual solamente
if (getNameURLWeb() === "incidents_view.php")
{
//Obtenemos una referencia a los campos de fecha
const startDateInput = document.getElementById('startDateValue');
const endDateInput = document.getElementById('endDateValue');
//Bloquea pegado en inputs
startDateInput.onpaste = e => e.preventDefault();
endDateInput.onpaste = e => e.preventDefault();
//Ponemos las fechas en los campos de busqueda
document.getElementById("startDateValue").value = firstDataDB;
document.getElementById("endDateValue").value = today;
ajaxIncidentOperation(firstDataDB, today, idEquipSelected);
}
if (getNameURLWeb() === "product_view.php")
{
const startDateInput = document.getElementById('startDateValue');
const endDateInput = document.getElementById('endDateValue');
//Bloquea pegado en inputs
startDateInput.onpaste = e => e.preventDefault();
endDateInput.onpaste = e => e.preventDefault();
document.getElementById("startDateValue").value = firstDataDB;
document.getElementById("endDateValue").value = today;
document.getElementById("dayValue").value = today;
DayParse(today);
IntervalDatesParse(firstDataDB, today);
ajaxFillOperation(firstDataDB, today, idEquipSelected);
fillsDay(today, idEquipSelected);
}
});
//Funcion para verificar notofocaciones
$(document).ready(function () {
GetNotifications();
setInterval(function(){
GetNotifications();
},5000);
});
//Seleccionar equipo para desplegar datos
$("#eq01").click(function() {
idEquipSelected = 1;
alert("Se mostrarán solo datos del EQUIPO " + idEquipSelected);
ChangeEquipment(1);
});
$("#eq02").click(function() {
idEquipSelected = 2;
alert("Se mostrarán solo datos del EQUIPO " + idEquipSelected);
ChangeEquipment(2);
});
$("#eq03").click(function() {
idEquipSelected = 3;
alert("Se mostrarán solo datos del EQUIPO " + idEquipSelected);
ChangeEquipment(3);
});
$("#eq04").click(function() {
idEquipSelected = 4;
alert("Se mostrarán solo datos del EQUIPO " + idEquipSelected);
ChangeEquipment(4);
});
$("#eq05").click(function() {
idEquipSelected = 5;
alert("Se mostrarán solo datos del EQUIPO " + idEquipSelected);
ChangeEquipment(5);
});
function ChangeEquipment(idSelected)
{
document.getElementById("equipNameGauge").innerHTML = "Equipo " + idSelected;
//para charts por dia
document.getElementById("equipNameTemp").innerHTML = " ► Equipo " + idSelected;
document.getElementById("equipNamePres").innerHTML = " ► Equipo " + idSelected;
document.getElementById("equipNamePerc").innerHTML = " ► Equipo " + idSelected;
//para chart con promedio
document.getElementById("equipNameAver").innerHTML = "Equipo " + idSelected;
//document.getElementById("equipNameInc").innerHTML = "Equipo " + idSelected;
//document.getElementById("idEquipDonut").innerHTML = " ►  Equipo " + idSelected;
//document.getElementById("idEquipTab").innerHTML = " ► Equipo " + idSelected;
}
/*Obtiene el intervalo de meses consultados*/
function DayParse(day)
{
var options = {timeZone: 'UTC', year: 'numeric', month: 'long', day: 'numeric' };
document.getElementById("daySelectedTemp").innerHTML = new Date(day).toLocaleDateString("es-ES", options);
document.getElementById("daySelectedPres").innerHTML = new Date(day).toLocaleDateString("es-ES", options);
document.getElementById("daySelectedPerc").innerHTML = new Date(day).toLocaleDateString("es-ES", options);
}
function IntervalDatesParse(start, end)
{
var options = {timeZone: 'UTC', year: 'numeric', month: 'long', day: 'numeric' };
document.getElementById("daySelectedAverage").innerHTML = new Date(start).toLocaleDateString("es-ES", options) + " a " +
new Date(end).toLocaleDateString("es-ES", options);
}
/* Valida que solo se escriban numeros y "-" en los campos de fecha*/
function validateKeypress() {
/*
var alpha = /[ A-Za-z]/;
var numeric = /[0-9]/;
var alphanumeric = /[ A-Za-z0-9]/;
*/
var dateKey = /[0-9]/;
var keyChar = String.fromCharCode(event.which || event.keyCode);
return dateKey.test(keyChar) ? keyChar : false;
}
/* True -> Si la fecha tiene el formato adecuado yyyy-mm-dd || False -> Si la fecha esta escrita mal*/
function isValidDate(dateString)
{
var regEx = /^\d{4}-\d{2}-\d{2}$/;
if(!dateString.match(regEx))// Formato invalido
{
return false;
}
var d = new Date(dateString);
var dNum = d.getTime();
if(!dNum && dNum !== 0) // NaN value, Fecha invalida
{
return false;
}
return d.toISOString().slice(0,10) === dateString;
}
//Button - Función para filtrar llenados por fechas
$(document).ready(function ()
{
if(sessionStorage.getItem('User')===""){
location.href = 'index.html';
return;
}
$(".loader").fadeOut("slow");
$("#search_fills_button").click(function ()
{
var startDateValue = $("#startDateValue").val();
var endDateValue = $("#endDateValue").val();
if (isValidDate(startDateValue) && isValidDate(endDateValue))
{
var difference = (Date.parse(endDateValue) - Date.parse(startDateValue)) / (86400000 * 7);
if (difference < 0) {
alertify.error('La fecha de inicio debe ser anterior a la fecha de finalización.');
} else
{
ajaxFillOperation(startDateValue, endDateValue, idEquipSelected);
}
}
else
{
alertify.error("Formato de fecha incorrecto. Verifique yyyy-mm-dd")
}
});
$("#day_fills_button").click(function ()
{
var dayValue = $("#dayValue").val();
if (isValidDate(dayValue))
{
fillsDay(dayValue, idEquipSelected);
}
else
{
alertify.error("Formato de fecha incorrecto. Verifique yyyy-mm-dd")
}
});
});
//Button - Función para filtrar alarmas por fecha
$(document).ready(function ()
{
$("#search_alarms_button").click(function ()
{
var startDateValue = $("#startDateValue").val();
var endDateValue = $("#endDateValue").val();
if (isValidDate(startDateValue) && isValidDate(endDateValue))
{
var difference = (Date.parse(endDateValue) - Date.parse(startDateValue)) / (86400000 * 7);
if (difference < 0) {
alertify.error('La fecha de inicio debe ser anterior a la fecha de finalización.');
} else
{
ajaxIncidentOperation(startDateValue, endDateValue, idEquipSelected);
}
}
else
{
alertify.error("Formato de fecha incorrecto. Verifique yyyy-mm-dd")
}
});
});
//gradientDoughnut = {
// responsive: true,
// plugins: {
// legend: {
// position: 'top',
// },
// title: {
// display: false, //true,
// text: 'Chart.js Doughnut Chart'
// }
// }
//};
function ajaxFillOperation(startDay, endDay, idEquipo)
{
jQuery.ajax({
type: "GET",
url: 'api_fills.php',
dataType: 'json',
data: {api_fills: 'get_fill_interval', startDate: startDay, endDate: endDay, idEquipo: idEquipo},
success: function (obj)
{
if (!obj.error && jQuery.isEmptyObject(obj.fillsInterval))
{
alertify.error('Sin registros. Elija otras fechas');
} else
{
IntervalDatesParse(startDay, endDay);
var datesFills = [];
var temperatureFills = [];
var presionFills = [];
var percentageFills = [];
var temperatureMaxMin = [];
var presionMaxMin = [];
var percentageMaxMin = [];
var i;
var totalTemperature = 0;
var totalPressure = 0;
var totalPercentage = 0;
var countData = 0;
var tempDate = dateSplit(obj.fillsInterval[0].fecha);
for (i in obj.fillsInterval)
{
temperatureMaxMin.push(obj.fillsInterval[i].temperatura);
presionMaxMin.push(obj.fillsInterval[i].presion);
percentageMaxMin.push(obj.fillsInterval[i].porcentaje);
var rowDate = dateSplit(obj.fillsInterval[i].fecha);
if(rowDate === tempDate)
{
totalTemperature += obj.fillsInterval[i].temperatura;
totalPressure += obj.fillsInterval[i].presion;
totalPercentage += obj.fillsInterval[i].porcentaje;
countData += 1;
}
else
{
temperatureFills.push(Math.round(totalTemperature / countData));
presionFills.push(Math.round(totalPressure / countData));
percentageFills.push(Math.round(totalPercentage / countData));
datesFills.push(dateSplit(obj.fillsInterval[i-1].fecha));
totalTemperature = 0;
totalPressure = 0;
totalPercentage = 0;
totalTemperature += obj.fillsInterval[i].temperatura;
totalPressure += obj.fillsInterval[i].presion;
totalPercentage += obj.fillsInterval[i].porcentaje;
countData = 1;
tempDate = dateSplit(obj.fillsInterval[i].fecha);
}
}
if(countData !== 0)
{
temperatureFills.push(Math.round(totalTemperature / countData));
presionFills.push(Math.round(totalPressure / countData));
percentageFills.push(Math.round(totalPercentage / countData));
datesFills.push(dateSplit(obj.fillsInterval[obj.fillsInterval.length-1].fecha));
}
chartFusionBarInterval(datesFills, temperatureFills, presionFills, percentageFills, 'fusionchart-average');
}
}
});
}
function fillsDay(day, idEquipo)
{
jQuery.ajax({
type: "GET",
url: 'api_fills.php',
dataType: 'json',
data: {api_fills: 'get_fill_interval', startDate: day, endDate: day, idEquipo: idEquipo},
success: function (obj)
{
if (!obj.error && jQuery.isEmptyObject(obj.fillsInterval))
{
alertify.error('Sin registros en el día seleccionado. Elija otra fecha');
}
else
{
DayParse(day);
var datesFills = [];
var temperatureFills = [];
var presionFills = [];
var percentageFills = [];
var i;
for (i in obj.fillsInterval)
{
datesFills.push(obj.fillsInterval[i].fecha);
temperatureFills.push(obj.fillsInterval[i].temperatura);
presionFills.push(obj.fillsInterval[i].presion);
percentageFills.push(obj.fillsInterval[i].porcentaje);
}
document.getElementById("minTemperature").innerHTML = "Min. " + Math.min.apply(Math, temperatureFills);
document.getElementById("minPressure").innerHTML = "Min. " + Math.min.apply(Math, presionFills);
document.getElementById("minPercentage").innerHTML = "Min. " + Math.min.apply(Math, percentageFills);
document.getElementById("maxTemperature").innerHTML = "Máx. " + Math.max.apply(Math, temperatureFills);
document.getElementById("maxPressure").innerHTML = "Máx. " + Math.max.apply(Math, presionFills);
document.getElementById("maxPercentage").innerHTML = "Máx. " + Math.max.apply(Math, percentageFills);
chartFusionLineDay(datesFills, temperatureFills, 'fusionchart-temperature', '#09a6ee');
chartFusionLineDay(datesFills, presionFills, 'fusionchart-pressure', '#d346b1');
chartFusionLineDay(datesFills, percentageFills, 'fusionchart-percentage', '#1be3c1');
}
}
});
}
function chartFusionLineDay(labels, datafills, idHTML, linecolor)
{
var chart_labels = {category: []};
var chart_data = {data: [] };
for (var i = 0; i < datafills.length; i++)
{
chart_labels['category'].push({"label": labels[i].toString()});
chart_data['data'].push({"value": datafills[i].toString()});
}
var categories = [chart_labels];
var dataset = [chart_data];
var chartObj = new FusionCharts({
type: 'scrollline2d',
dataFormat: 'json',
renderAt: idHTML,
width: '100%',
height: '70%',
dataSource: {
chart: {
theme: "fusion",
bgColor: "#272A3D",
scrollColor : "#6b6b6c",
divLineColor: "#7d7d7d",
baseFontColor: "#7d7d7d",
//bgAlpha: "0,0",
showLabels: "0",
//caption: "Temperarura",
//subCaption: "2021-05-09",
//xAxisName: "Month",
//yAxisName: "Revenue",
//numberPrefix: "$",
lineThickness: "3",
lineColor: linecolor,
flatScrollBars: "1",
scrollheight: "10",
numVisiblePlot: "12",
showHoverEffect: "1"
},
categories: categories,
dataset: dataset
}
});
chartObj.render();
}
function chartFusionBarInterval(labels, temperature_data, pressure_data, percentage_data, idHTML)
{
var chart_labels = {category: []};
var chart_data_temp = {seriesname: "Temperatura", data: [] };
var chart_data_pres = {seriesname: "Presión", data: [] };
var chart_data_perc = {seriesname: "Porcentaje", data: [] };
for (var i = 0; i < labels.length; i++)
{
chart_labels['category'].push({"label": labels[i].toString()});
chart_data_temp['data'].push({"value": temperature_data[i].toString()});
chart_data_pres['data'].push({"value": pressure_data[i].toString()});
chart_data_perc['data'].push({"value": percentage_data[i].toString()});
}
var categories = [chart_labels];
var dataset = [chart_data_temp, chart_data_pres, chart_data_perc];
var chartObj = new FusionCharts({
type: 'mscolumn2d',
dataFormat: 'json',
renderAt: idHTML,
width: '100%',
height: '70%',
dataSource: {
chart: {
theme: "fusion",
bgColor: "#272A3D",
scrollColor : "#6b6b6c",
baseFontColor: "#7d7d7d",
formatnumberscale: "1",
drawcrossline: "1",
flatScrollBars: "1",
scrollheight: "10",
numVisiblePlot: "12",
showHoverEffect: "1",
scrollShowButtons: "0",
},
categories: categories,
dataset: dataset
}
});
chartObj.render();
}
function dateSplit(date)
{
var dateSplit = date.split(" ");
return dateSplit[0];
}
//var myChart;
function ajaxIncidentOperation(startDay, endDay, idEquipo) {
/* Llamada para obtener datos de alarmas por grupos (para grafica de dona) */
jQuery.ajax({
type: "GET",
url: 'api_alarms.php',
dataType: 'json',
data: {api_alarms: 'get_alarm_groups', startDate: startDay, endDate: endDay, idEquipo: idEquipo},
success: function (obj)
{
if (!obj.error && !jQuery.isEmptyObject(obj.alarmGroups))
{
var nombres = [];
var totales = [];
var i;
var totalAlarmas = 0;
for (i in obj.alarmGroups)
{
nombres.push(obj.alarmGroups[i].nombre);
totales.push(obj.alarmGroups[i].total);
totalAlarmas = totalAlarmas + obj.alarmGroups[i].total;
}
var options = {timeZone: 'UTC', year: 'numeric', month: 'long', day: 'numeric' };
document.getElementById("dateSelectedGroups").innerHTML = new Date(startDay).toLocaleDateString("es-ES", options) + " a " +
new Date(endDay).toLocaleDateString("es-ES", options);
document.getElementById("totalIncidents").innerHTML = " Total: " + totalAlarmas;;
chartFusionDonutIncidents(nombres, totales, 'chartdonut-indicidents');
/************************Doughnut Chart****************/
// var data = {
// labels: nombres /*['INC.', 'INC.2', 'INC.3', 'INC.4', 'INC.5']*/,
// datasets: [{
// label: "Incidencias",
// backgroundColor: [
// '#4dc9f6',
// '#f67019',
// '#f53794',
// '#537bc4',
// '#acc236',
// '#166a8f',
// '#00a950',
// '#58595b',
// '#8549ba',
// '#c0392b',
// '#9b59b6',
// '#2980b9',
// '#1abc9c',
// '#d35400',
// '#2e4053',
// '#6d1f35'
// ],
// data: totales /*[10, 20, 30, 15, 25]*/
// }]
// };
//
// //Para evitar el bug que mostraba la gráfica anterior bajo la nueva
// if (myChart != null)
// {
// myChart.destroy();
// }
//
// myChart = new Chart(ctxDoughnut, {
// type: 'pie',
// data: data,
// options: gradientDoughnut,
// responsive: true,
// });
/****************Final Doughnut Chart****************************/
}
else
{
//Si no se obtuvieron datos
if (jQuery.isEmptyObject(obj.alarmGroups))
{
//Ya se manda el mensaje en la función que llena la tabla
//alertify.error('Sin registros. Seleccione otra fecha');
// Se borra la gráfica
//myChart.destroy();
//Se limpia el mensaje de los meses
document.getElementById("totalIncidents").innerHTML = "";
}
}
}
});
/* Llamada para obtener datos de alarmas (para la lista) */
jQuery.ajax({
type: "GET",
url: 'api_alarms.php',
dataType: 'json',
data: {api_alarms: 'get_alarm_list', startDate: startDay, endDate: endDay, idEquipo: idEquipo},
success: function (obj)
{
var table = document.getElementById("content-incidents");
if (!obj.error && !jQuery.isEmptyObject(obj.alarmList))
{
$('#dataTables-incidents').DataTable().clear().destroy();
//Primero se tiene que limpiar la tabla para no añadirle las lineas
table.innerHTML = "";
//Se insertan las lineas generadas
var str = "";
var i;
for (i in obj.alarmList)
{
str = '<tr>' +
'<td>' + obj.alarmList[i].fecha + '</td>' +
'<td>' + obj.alarmList[i].alarmasNombre + '</td>' +
'<td>' + obj.alarmList[i].equiposNombre + '</td>' +
'</tr>';
table.insertRow(-1).innerHTML = str;
}
$('#dataTables-incidents').DataTable();
} else
{
//Si no obtuvimos resultados limpiamos la tabla
if (jQuery.isEmptyObject(obj.alarmList)) //Esto se puede meter en un variable bool y hacer solo una vez el llamado a la funcion
{
table.innerHTML = "";
alertify.error('Sin registros. Seleccione otra fecha');
}
}
}
});
}
function chartFusionDonutIncidents(labels, dataincidents, idHTML)
{
var dataset = {data: []};
for (var i = 0; i < dataincidents.length; i++)
{
dataset['data'].push({label: labels[i].toString(), value: dataincidents[i].toString()});
}
var chartObj = new FusionCharts({
type: 'doughnut2d',
dataFormat: 'json',
renderAt: idHTML,
width: '100%',
height: '85%',
dataSource: {
chart: {
theme: "fusion",
bgColor: "#272A3D",
baseFontColor: "#7d7d7d",
showLabels: "0",
showpercentvalues: "1",
//defaultcenterlabel: "Incidencias",
centerLabelColor: "#7d7d7d",
aligncaptionwithcanvas: "0",
captionpadding: "0",
decimals: "1",
baseFontColor: "#7d7d7d",
labelFontColor:"#7d7d7d"
},
data: dataset['data']
}
});
chartObj.render();
}
<file_sep><?php include 'header_page.php'; ?>
<!-- Conetenido Dashboards -->
<div class="content">
<div class="row">
<div class="col-12">
<div class="row">
<div class="col-sm-12">
<div class="btn-group btn-group-toggle float-right" data-toggle="buttons">
<label class="btn btn-sm btn-info btn-simple active">
<input type="radio" name="options" checked>
<span class="d-none d-sm-block d-md-block d-lg-block d-xl-block" id="eq01">O1</span>
</label>
<label class="btn btn-sm btn-info btn-simple">
<input type="radio" class="d-none d-sm-none" name="options">
<span class="d-none d-sm-block d-md-block d-lg-block d-xl-block" id="eq02">O2</span>
</label>
<label class="btn btn-sm btn-info btn-simple">
<input type="radio" class="d-none d-sm-none" name="options">
<span class="d-none d-sm-block d-md-block d-lg-block d-xl-block" id="eq03">O3</span>
</label>
<label class="btn btn-sm btn-info btn-simple">
<input type="radio" class="d-none d-sm-none" name="options">
<span class="d-none d-sm-block d-md-block d-lg-block d-xl-block" id="eq04">O4</span>
</label>
<label class="btn btn-sm btn-info btn-simple">
<input type="radio" class="d-none d-sm-none" name="options">
<span class="d-none d-sm-block d-md-block d-lg-block d-xl-block" id="eq05">O5</span>
</label>
</div>
</div>
</div>
<!-- Guages -->
<div class="card">
<div class="card card-chart">
<div class="card-header ">
<div class="row">
<div class="card-header">
<h3 class="card-title"><i class="tim-icons icon-chart-bar-32 text-primary"></i> Estado actual</h3>
</div>
<div class="dropdown">
<div class="card-category" id="equipNameGauge">Equipo 1</div>
<div class="card-category" id="message"></div>
</div>
</div>
</div>
<div class="card-body">
<div class="chart-area">
<div class="row">
<div class="col-lg-4">
<div class="card-header">
<h5 class="card-category">Temperatura</h5>
</div>
<div id="gauge_temperature"></div>
</div>
<div class="col-lg-4">
<div class="card-header">
<h5 class="card-category">Presión</h5>
</div>
<div id="gauge_presion"></div>
</div>
<div class="col-lg-4">
<div class="card-header">
<h5 class="card-category">Porcentaje</h5>
</div>
<div id="gauge_percentage"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Fin guajes -->
<!-- Formulario para dashboards por dia -->
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-body">
<div class="places-buttons">
<div class="row">
<div class="col-md-6 ml-auto mr-auto text-center">
<h4 class="card-title">
Seleccione una fecha
</h4>
</div>
</div>
<div class="row">
<div class="col-md-10 ml-auto mr-auto text-center">
<div class="card-body">
<form class="form-horizontal" name="formDay" role="form" enctype="multipar/form-data">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Fecha</label>
<input type="text" id="dayValue" placeholder="yyyy-mm-dd" class="form-control" onkeypress="validateKeypress();" required="required">
</div>
</div>
<div class="col-md-4">
<div class="form-group"><br>
<button type="button" id="day_fills_button" class="btn btn-fill btn-success">Buscar</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- TEMPERATURA - Fusion dash -->
<div class="row">
<div class="col-12">
<div class="card card-chart">
<div class="card-body">
<div class="card-header ">
<div class="row">
<div class="col-sm-6 text-left">
<h4 class="title d-inline">Temperatura</h4>
<p class="card-category d-inline" id="equipNameTemp">
► Equipo 1
</p>
<h5 class="card-category" id="daySelectedTemp"></h5>
</div>
<div class="dropdown">
<div class="card-category" id="minTemperature"></div>
<div class="card-category" id="maxTemperature"></div>
</div>
</div>
</div>
<div class="chart-area">
<div id="fusionchart-temperature">
No se encontraron registros de temperatura, seleccione otra fecha
</div>
</div>
</div>
</div>
</div>
</div>
<!-- PRESION - Fusion dash -->
<div class="row">
<div class="col-12">
<div class="card card-chart">
<div class="card-body">
<div class="card-header ">
<div class="row">
<div class="col-sm-6 text-left">
<h4 class="title d-inline">Presión</h4>
<p class="card-category d-inline" id="equipNamePres">
► Equipo 1
</p>
<h5 class="card-category" id="daySelectedPres"></h5>
</div>
<div class="dropdown">
<div class="card-category" id="minPressure"></div>
<div class="card-category" id="maxPressure"></div>
</div>
</div>
</div>
<div class="chart-area">
<div id="fusionchart-pressure">
No se encontraron registros de presión, seleccione otra fecha
</div>
</div>
</div>
</div>
</div>
</div>
<!-- PORCENTAJE - Fusion dash -->
<div class="row">
<div class="col-12">
<div class="card card-chart">
<div class="card-body">
<div class="card-header ">
<div class="row">
<div class="col-sm-6 text-left">
<h4 class="title d-inline">Porcentaje</h4>
<p class="card-category d-inline" id="equipNamePerc">
► Equipo 1
</p>
<h5 class="card-category" id="daySelectedPerc"></h5>
</div>
<div class="dropdown">
<div class="card-category" id="minPercentage"></div>
<div class="card-category" id="maxPercentage"></div>
</div>
</div>
</div>
<div class="chart-area">
<div id="fusionchart-percentage">
No se encontraron registros de porcentajes, seleccione otra fecha
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Formulario para promedio -->
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-body">
<div class="places-buttons">
<div class="row">
<div class="col-md-6 ml-auto mr-auto text-center">
<h4 class="card-title">
Seleccione intervalo de fechas para mostrar promedio
</h4>
</div>
</div>
<div class="row">
<div class="col-md-10 ml-auto mr-auto text-center">
<div class="card-body">
<form class="form-horizontal" name="formDates" role="form" enctype="multipar/form-data">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Fecha Inicial</label>
<input type="text" id="startDateValue" placeholder="yyyy-mm-dd" class="form-control" onkeypress="validateKeypress();" required="required">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="">Final Final</label>
<input type="text" id="endDateValue" placeholder="yyyy-mm-dd" class="form-control" onkeypress="validateKeypress();" required="required">
</div>
</div>
<div class="col-md-4">
<div class="form-group"><br>
<button type="button" id="search_fills_button" class="btn btn-fill btn-success">Buscar</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- PROMEDIO TEMPERATURA PRESION PORCENTAJE FUSION DASH -->
<div class="row">
<div class="col-12">
<div class="card card-chart">
<div class="card-body">
<div class="card-header ">
<div class="row">
<div class="col-sm-6 text-left">
<h4 class="title d-inline">Promedio en llenados</h4>
<h5 class="card-category" id="daySelectedAverage"></h5>
</div>
<div class="dropdown">
<div class="card-category" id="equipNameAver">Equipo 1</div>
</div>
</div>
</div>
<div class="chart-area">
<div id="fusionchart-average">
No se encontraron registros, seleccione otra fecha
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Fin Conetenido Dashboards -->
<?php include 'footer_page.php'; ?>
<file_sep><?php
// define('DB_HOST', 'remotemysql.com');
// define('DB_USER', 'VEEUbbBt3r');
// define('DB_PASS', '<PASSWORD>');
// define('DB_NAME', 'VEEUbbBt3r');
define('DB_HOST', 'localhost');
define('DB_USER', 'spaceuser');
define('DB_PASS', '<PASSWORD>');
define('DB_NAME', 'infra');
<file_sep><?php include 'header_page.php'; ?>
<!-- Conetenido Dashboards -->
<div class="content">
<div class="row">
<div class="col-12">
<!-- Botones para equipos -->
<div class="row">
<div class="col-sm-12">
<div class="btn-group btn-group-toggle float-right" data-toggle="buttons">
<label class="btn btn-sm btn-info btn-simple active">
<input type="radio" name="options" checked>
<span class="d-none d-sm-block d-md-block d-lg-block d-xl-block" id="eq01">O1</span>
</label>
<label class="btn btn-sm btn-info btn-simple">
<input type="radio" class="d-none d-sm-none" name="options">
<span class="d-none d-sm-block d-md-block d-lg-block d-xl-block" id="eq02">O2</span>
</label>
<label class="btn btn-sm btn-info btn-simple">
<input type="radio" class="d-none d-sm-none" name="options">
<span class="d-none d-sm-block d-md-block d-lg-block d-xl-block" id="eq03">O3</span>
</label>
<label class="btn btn-sm btn-info btn-simple">
<input type="radio" class="d-none d-sm-none" name="options">
<span class="d-none d-sm-block d-md-block d-lg-block d-xl-block" id="eq04">O4</span>
</label>
<label class="btn btn-sm btn-info btn-simple">
<input type="radio" class="d-none d-sm-none" name="options">
<span class="d-none d-sm-block d-md-block d-lg-block d-xl-block" id="eq05">O5</span>
</label>
</div>
</div>
</div>
<!-- Fin Botones para equipos -->
<!-- Barra de selección de fechas -->
<div class="row">
<div class="col-12">
<div class="card card-chart">
<div class="card-header">
<h4 class="card-title">Seleccione intervalo de fechas</h4>
<div class="dropdown">
<div class="card-category text-right" id=""></div>
</div>
</div>
<div class="card-body">
<form class="form-horizontal" name="formDates" role="form" enctype="multipar/form-data">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Fecha Inicial</label>
<input type="text" id="startDateValue" placeholder="yyyy-mm-dd" class="form-control" required="required">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="">Fecha Final</label>
<input type="text" id="endDateValue" placeholder="yyyy-mm-dd" class="form-control" required="required">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<br>
<button type="button" id="search_alarms_button" class="btn btn-fill btn-success">Buscar</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Fin de barra de selección de fechas -->
<div class="row">
<div class="col-lg-12 col-md-12">
<div class="card card-tasks">
<div class="card-header ">
<div class="row">
<div class="col-sm-11 text-left">
<h6 class="title d-inline">Registro de incidencias</h6>
<p class="card-category d-inline" id="">
</p>
<h5 class="card-category" id="dateSelectedGroups"></h5>
</div>
<div class="dropdown">
<div class="card-category" id="totalIncidents"></div>
</div>
</div>
</div>
<div class="card-body ">
<div id="chartdonut-indicidents"></div>
</div>
</div>
</div>
<div class="col-lg-12 col-md-12">
<div class="card ">
<div class="card-header ">
<div class="row">
<div class="col-sm-11 text-left">
<h6 class="title d-inline">Historial de incidencias</h6>
<p class="card-category d-inline" id="">
</p>
<h5 class="card-category" id="dateSelectedGroups"></h5>
</div>
<div class="dropdown">
<div class="card-category" id="totalIncidents"></div>
</div>
</div>
</div>
<div class="card-body">
<table class="display table table-dark" id="dataTables-incidents" style="width:100%" >
<thead class="">
<tr>
<th>
Fecha/Hora
</th>
<th>
Causa de la incidencia
</th>
<th>
Equipo
</th>
</tr>
</thead>
<tbody id="content-incidents">
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Fin Conetenido Dashboards -->
<?php include 'footer_page.php'; ?> <file_sep><?php
class OperationsNotificaciones
{
private $con;
function __construct()
{
require_once dirname(__FILE__) . '/db_connect.php';
$db = new DatabaseConnect();
$this->con = $db->connect();
}
function getNumberNotifications()
{
$sqlNotifications = $this->con->prepare("Select count(*) from alarmas where STATUS = 1");
$sqlNotifications->execute();
$sqlNotifications->bind_result($number);
$number_json = array();
while ($sqlNotifications->fetch()) {
$number_array = array();
$number_array['number'] = $number;
array_push($number_json, $number_array);
}
return $number_json;
}
function getDataNotifications()
{
$sqlNotifications = $this->con->prepare("
SELECT alarmas.id, alarmas.fecha, equipos.nombre, alarma_tipo.nombre
FROM alarmas, equipos, alarma_tipo
WHERE alarmas.equipo = equipos.id
AND alarmas.alarma_tipos = alarma_tipo.id
AND alarmas.`status` = 1");
$sqlNotifications->execute();
$sqlNotifications->bind_result($id, $fecha, $nombreEquipo, $alarmaTipo);
$notifications_json = array();
while ($sqlNotifications->fetch()) {
$notifications_array = array();
$notifications_array['id'] = $id;
$notifications_array['fecha'] = $fecha;
$notifications_array['nombreEquipo'] = $nombreEquipo;
$notifications_array['alarmaTipo'] = $alarmaTipo;
array_push($notifications_json, $notifications_array);
}
return $notifications_json;
}
function onViewNotification($id)
{
$fill_json_view = array();
$sqlViewNotification = $this->con->prepare("
UPDATE alarmas SET alarmas.status = 0 WHERE alarmas.id = " . $id);
$sqlViewNotification->execute();
$fill_array_view = array();
$fill_array_view['error'] = false;
$fill_array_view['mensaje'] = ' Actualización Realizada';
array_push($fill_json_view, $fill_array_view);
return $fill_json_view;
}
}
<file_sep><?php
require_once 'db_operations_notificaciones.php';
function isTheseParametersAvailable($params) {
$available = true;
$missingparams = "";
foreach ($params as $param) {
if (!isset($_POST[$param]) || strlen($_POST[$param]) <= 0) {
$available = false;
$missingparams = $missingparams . ", " . $param;
}
}
if (!$available) {
$response = array();
$response['error'] = true;
$response['message'] = 'Parameters ' . substr($missingparams, 1, strlen($missingparams)) . ' missing';
echo json_encode($response);
die();
}
}
$response = array();
if (isset($_GET['api_notificaciones']))
{
switch ($_GET['api_notificaciones'])
{/*
case 'get_notificaciones':
$db = new OperationsNotificaciones();
$response['error'] = false;
$response['message'] = 'Solicitud completada exitosamente';
$response['notificaciones'] = $db->getNotificaciones();
break;*/
case 'get_alarm_notification':
$db = new OperationsNotificaciones();
$response['error'] = false;
$response['message'] = 'Solicitud completada exitosamente';
$response['notification'] = $db->getDataNotifications();
break;
case 'get_alarms_number':
$db = new OperationsNotificaciones();
$response['error'] = false;
$response['message'] = 'Solicitud completada exitosamente';
$response['number'] = $db->getNumberNotifications();
break;
}
}
if(isset($_POST['notification_view'])){
switch($_POST['notification_view'])
{
case 'view':
$db = new OperationsNotificaciones();
$response['status'] = $db->onViewNotification($_POST['ID']);
break;
}
}
else
{
$response['error'] = true;
$response['message'] = 'Invalido al llamar API';
}
echo json_encode($response);
<file_sep>function ChangePage1() {
location.href = 'incidents_view.html';
}
const signinForm = document.querySelector('#signin-form');
signinForm.addEventListener('submit', (e) => {
e.preventDefault();
const email = document.querySelector('#email').value;
const password = document.querySelector('#password').value;
//.createUserWithEmailAndPassword(email, password)
auth
.signInWithEmailAndPassword(email, password)
.then((userCredential) => {
//clear form
document.getElementById("errorMessageSession").innerText = "";
//localStorage.setItem("User", email)
sessionStorage.setItem("User", email)
let data = sessionStorage.getItem('User');
signinForm.reset();
//console.log('sign in OK')
// ...
})
.catch((error) => {
var errorCode = error.code;
document.getElementById("errorMessageSession").innerText = "Usuario o contraseña incorrectos";
sessionStorage.clear();
/*var errorMessage = error.message;
console.log(errorMessage);
console.log(errorCode);
if (errorCode == 'auth/user-not-found') {
}*/
});
})
function sendPasswordReset() {
var email = document.getElementById('email').value;
firebase.auth().sendPasswordResetEmail(email).then(function () {
// Password Reset Email Sent!
//alert('Password Reset Email Sent!');
document.getElementById("errorMessageSession").innerText = "Se ha enviado un correo de recuperación";
}).catch(function (error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode == 'auth/invalid-email') {
//alert(errorMessage);
document.getElementById("errorMessageSession").innerText = "Formato de correo inválido";
} else if (errorCode == 'auth/user-not-found') {
//alert(errorMessage);
document.getElementById("errorMessageSession").innerText = "Correo electrónico no encontrado";
}
//console.log(error);
});
}
function initApp() {
// Listening for auth state changes.
firebase.auth().onAuthStateChanged(
function (user) {
if (user) {
location.href = 'product_view.php';
$(".loader").fadeOut("slow");
} else {
//console.log("log out");
$(".loader").fadeOut("slow");
}
});
document.getElementById('forgotPass').addEventListener('click', sendPasswordReset, false);
}
window.onload = function () {
initApp();
};<file_sep><?php
require_once 'db_operations_alarms.php';
function isTheseParametersAvailable($params) {
$available = true;
$missingparams = "";
foreach ($params as $param) {
if (!isset($_POST[$param]) || strlen($_POST[$param]) <= 0) {
$available = false;
$missingparams = $missingparams . ", " . $param;
}
}
if (!$available) {
$response = array();
$response['error'] = true;
$response['message'] = 'Parameters ' . substr($missingparams, 1, strlen($missingparams)) . ' missing';
echo json_encode($response);
die();
}
}
function areTheseParametersGETAvailable($params) {
$available = true;
$missingparams = "";
foreach ($params as $param) {
if (!isset($_GET[$param]) || strlen($_GET[$param]) <= 0) {
$available = false;
$missingparams = $missingparams . ", " . $param;
}
}
if (!$available) {
$response = array();
$response['error'] = true;
$response['message'] = 'Parameters ' . substr($missingparams, 1, strlen($missingparams)) . ' missing';
echo json_encode($response);
die();
}
}
$response = array();
#Si se llama a la api_alarms
if (isset($_GET['api_alarms']))
{
#Dependiendo del valor de la clave se llamará una operación de BD
switch ($_GET['api_alarms'])
{
#Obtiene la lista de alarmas disparadas
case 'get_alarm_list':
//first check the parameters required for this request are available or not
areTheseParametersGETAvailable(array('startDate','endDate','idEquipo'));
$db = new OperationsAlarms();
$response['error'] = false;
$response['message'] = 'Solicitud completada exitosamente';
$response['alarmList'] = $db->getAlarmList($_GET['startDate'], $_GET['endDate'], $_GET['idEquipo']);
break;
#Obtiene la lista de alarmas por grupo
case 'get_alarm_groups':
//first check the parameters required for this request are available or not
areTheseParametersGETAvailable(array('startDate','endDate','idEquipo'));
$db = new OperationsAlarms();
$response['error'] = false;
$response['message'] = 'Solicitud completada exitosamente';
$response['alarmGroups'] = $db->getAlarmGroups($_GET['startDate'], $_GET['endDate'], $_GET['idEquipo']);
break;
}
}
else
{
$response['error'] = true;
$response['message'] = 'Clave invalida al llamar al API';
}
echo json_encode($response);
|
418e280f0851c1de79fa9a33ed99757806b7b4d0
|
[
"Markdown",
"Text",
"JavaScript",
"PHP"
] | 15 |
PHP
|
FeSanz/InfraIIOT
|
37865db508ab806f3b9589a9ec4b8d073fc1a05e
|
0e552b2b1972f069658f8c3bd2f982e1f09f4d2b
|
refs/heads/master
|
<file_sep>using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Reflection;
using Gma.UserActivityMonitor;
using System.Diagnostics;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
#region Declarations
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
public const int MOUSEEVENTF_LEFTDOWN = 0x02;
public const int MOUSEEVENTF_LEFTUP = 0x04;
public const int MOUSEEVENTF_RIGHTDOWN = 0x08;
public const int MOUSEEVENTF_RIGHTUP = 0x10;
int timeInterval = 30;
int tickNumber = 0;
int speed = 1;
int timer2Tick;
int lineCounter;
int getTick = 0;
bool getLMouseDown;
bool getRMouseDown;
bool mouseLDown = false;
bool mouseRDown = false;
bool mouseLAlreadyDown = false;
bool mouseLAlreadyUp = true;
bool mouseRAlreadyDown = false;
bool mouseRAlreadyUp = true;
bool f7Pressed = false;
bool f8Pressed = false;
bool f9Pressed = false;
string elapsedTime;
string txtForUSe;
string[] allLines;
string[] txtfiles;
string[] lastLineSplit;
string[] splitLine = new string[4]; // this array holds the varriables of each line (the tick number, left mouse button down, right mouse button down, X, Y)
TimeSpan ts1 = new TimeSpan();
TimeSpan ts2 = new TimeSpan();
Point getMousePoint = new Point();
Point mouseMoveLocation = new Point();
Point mouseDownLocation = new Point();
Point mouseUpLocation = new Point();
Stopwatch timeCounter = new Stopwatch();
#endregion
public Form1()
{
InitializeComponent();
this.MaximizeBox = false;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
button3.Visible = false;
button2.Visible = true;
timer1.Interval = timeInterval;
timer2.Interval = timeInterval;
timer3.Interval = 500; //no need to be smaller
}
private void Form1_Load(object sender, EventArgs e)
{
string[] args = Environment.GetCommandLineArgs();
timer3.Start();
radioButton1.Checked = true;
//Loading hooks, they are not all needed though
HookManager.MouseMove += HookManager_MouseMove;
HookManager.MouseClick += HookManager_MouseClick;
HookManager.MouseDown += HookManager_MouseDown;
HookManager.MouseUp += HookManager_MouseUp;
HookManager.KeyPress += HookManager_KeyPress;
HookManager.KeyDown += HookManager_KeyDown;
HookManager.KeyUp += HookManager_KeyUp;
//Loading the saved txt files or not, into comboBox1 items list
txtfiles = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.txt");
foreach (string a in txtfiles)
{
string[] splitBuffer = a.Split('\\');
comboBox1.Items.Add(splitBuffer.Last().Replace(".txt", ""));
}
if (args.Length == 2)
{
txtForUSe = args[1];
txtForUSe = txtForUSe.Replace("\\", "/");
txtForUSe = txtForUSe.Replace(@"\", "/");
txtForUSe = txtForUSe.Split('/').Last();
txtForUSe = txtForUSe.Replace(".txt", "");
foreach (var s in comboBox1.Items)
{
if (s.ToString() == txtForUSe)
{
comboBox1.SelectedItem = s;
break;
}
else
return;
}
button1_Click(sender, e);
}
}
void HookManager_KeyUp(object sender, KeyEventArgs e) // on KeyUp, pressed keys goes to false again
{
f7Pressed = false;
f8Pressed = false;
f9Pressed = false;
}
void HookManager_KeyDown(object sender, KeyEventArgs e) // some key handling for using shurtcuts
{
if (e.KeyData == Keys.Escape) // This is the only way to interrupt the playback
{
if (timer2.Enabled)
{
timer2.Stop();
mouse_event(MOUSEEVENTF_LEFTUP, Cursor.Position.X, Cursor.Position.Y, 0, 0); // call this in case the mouse was left pushed in the end
}
if (timeCounter.IsRunning) // action proccess time elapsed counter
timeCounter.Stop();
e.Handled = true; // Let the key not being handled by others
}
if (e.KeyData == Keys.F7 && !f7Pressed)
{
f7Pressed =true;
button2_Click(sender, e);
e.Handled = true;
}
if (e.KeyData == Keys.F8 && !f8Pressed)
{
f8Pressed=true;
button3_Click(sender, e);
e.Handled = true;
}
if (e.KeyData == Keys.F9 && !f9Pressed)
{
f9Pressed = true;
button1_Click(sender, e);
e.Handled = true;
}
}
void HookManager_KeyPress(object sender, KeyPressEventArgs e) { }
void HookManager_MouseDown(object sender, MouseEventArgs e) // we have to know when the mouse is down or up with booleans
{
mouseDownLocation = e.Location;
if (e.Button == System.Windows.Forms.MouseButtons.Left)
mouseLDown = true;
if (e.Button == System.Windows.Forms.MouseButtons.Right)
mouseRDown = true; ;
}
void HookManager_MouseUp(object sender, MouseEventArgs e) // on MouseUp we have to set the MouseDown values to false
{
mouseUpLocation = e.Location;
if (e.Button == System.Windows.Forms.MouseButtons.Left)
mouseLDown = false;
if (e.Button == System.Windows.Forms.MouseButtons.Right)
mouseRDown = false;
}
void HookManager_MouseClick(object sender, MouseEventArgs e) { }
void HookManager_MouseMove(object sender, MouseEventArgs e) // displaying the location of the mouse
{
mouseMoveLocation = e.Location;
label1.Text = mouseMoveLocation.X.ToString();
label2.Text = mouseMoveLocation.Y.ToString();
}
private void button1_Click(object sender, EventArgs e) // this is the reproduction button
{
if (comboBox1.Text == "") // if there is no text in combobox stop button1_Click
{
MessageBox.Show("Choose a file or type a new");
return;
}
if (File.Exists(txtForUSe + ".txt")) // if there is text in combobox1 and it exists in our files
{
lastLineSplit = File.ReadLines(txtForUSe + ".txt").Last().Split(); // read the last line and split the line into an array of strings, i ll get the number of ticks occured from this
allLines = File.ReadAllLines(txtForUSe + ".txt"); // read all file and save each line in an array of strings
lineCounter = 0; // this is used to point the values in allLines[]
timer2Tick = int.Parse(lastLineSplit[0]); // we get the number of ticks occured
timer2.Interval = timeInterval / speed; // setting the speed of reproduction, timeInterval is how much time the timer uses for next tick
timer2.Start(); // we set the timer on
button1.Enabled = false; // avoid using the buttons and other when program runs the reproduction
button2.Enabled = false;
comboBox1.Enabled = false;
groupBox1.Enabled = false;
timeCounter.Reset(); // this is just a clock for displaying the time on screen
timeCounter.Start();
}
else // if file doesnt exist (ps. this is only for the reproduction fuction)
MessageBox.Show(this, "No data in file!", "No Data", MessageBoxButtons.OK);
}
private void button2_Click(object sender, EventArgs e) // this is the record button
{
if (comboBox1.Text == "") // if there is no text in combobox stop button2_Click
{
MessageBox.Show("Type or choose a file name");
return;
}
if (!File.Exists(txtForUSe + ".txt")) // if there is text in combobox1 and it is not exists in our files
{
if (DialogResult.OK == MessageBox.Show(this, "Recording will start in " + txtForUSe + ".txt", "Recording", MessageBoxButtons.OKCancel))
{
File.Create(txtForUSe + ".txt").Close(); // create the file
timer1.Start(); // start the record, timer1 is used here to save vars in this file in a sequence
button1.Enabled = false;
button2.Enabled = false;
button3.Enabled = true;
button3.Visible = true;
groupBox1.Enabled = false;
timeCounter.Reset();
timeCounter.Start();
comboBox1.Items.Add(txtForUSe + ".txt"); // add the name of the file to combobox1 items
}
}
else if (File.Exists(txtForUSe + ".txt")) // if there is text in combobox1 and it exists in our files make sure it is not a misstype mistake
{
if (DialogResult.Yes == MessageBox.Show(this, txtForUSe +".txt has data already! Erase and rewrite?", "Attention!", MessageBoxButtons.YesNo))
{
File.WriteAllText(txtForUSe + ".txt", String.Empty); // empty the file the user wants to rewrite
timer1.Start();
button1.Enabled = false;
button2.Enabled = false;
button3.Enabled = true;
button3.Visible = true;
groupBox1.Enabled = false;
timeCounter.Reset();
timeCounter.Start();
}
}
}
private void button3_Click(object sender, EventArgs e) // this button stops the timer1 which is the recorder
{
timer1.Stop();
tickNumber = 0; // set the tickNumber but to 0 for later uses again
button1.Enabled = true; // enable the buttons again
button2.Enabled = true;
button3.Enabled = false;
button3.Visible = false;
groupBox1.Enabled = true; ;
}
private void timer1_Tick(object sender, EventArgs e) // the recorder-timer
{
TextWriter writer = new StreamWriter(txtForUSe + ".txt", true); // open the file, the "true" value is to append the file because we use it multiple times
tickNumber++; // this is the number of tick occured, i use this to know when things are happening
if (mouseRDown && mouseLDown) // this checks if in this particular time clicks are up or down, then save them in file
writer.WriteLine(tickNumber + " " + true + " " + true + " " + mouseMoveLocation.X + " " + mouseMoveLocation.Y);
else if (mouseLDown && !mouseRDown)
writer.WriteLine(tickNumber + " " + true + " " + false + " " + mouseMoveLocation.X + " " + mouseMoveLocation.Y);
else if (!mouseLDown && mouseRDown)
writer.WriteLine(tickNumber + " " + false + " " + true + " " + mouseMoveLocation.X + " " + mouseMoveLocation.Y);
else
writer.WriteLine(tickNumber + " " + false + " " + false + " " + mouseMoveLocation.X + " " + mouseMoveLocation.Y);
writer.Close();
ts1 = timeCounter.Elapsed; // the display-timer format and diplay
elapsedTime = String.Format("{0:00}:{1:00}.{2:0}", ts1.TotalMinutes, ts1.Seconds, ts1.Milliseconds/10);
label3.Text = elapsedTime.ToString();
}
private void timer2_Tick(object sender, EventArgs e) // the playback-timer
{
if (timer2Tick > 0)
{
splitLine = allLines[lineCounter].Split();
getTick = int.Parse(splitLine[0]);
getLMouseDown = bool.Parse(splitLine[1]);
getRMouseDown = bool.Parse(splitLine[2]);
getMousePoint.X = int.Parse(splitLine[3]);
getMousePoint.Y = int.Parse(splitLine[4]);
Cursor.Position = getMousePoint;
if (getLMouseDown)
{
if (!mouseLAlreadyDown)
{
mouse_event(MOUSEEVENTF_LEFTDOWN, Cursor.Position.X, Cursor.Position.Y, 0, 0);
mouseLAlreadyDown = true;
mouseLAlreadyUp = false;
}
}
else
{
if (!mouseLAlreadyUp)
{
mouse_event(MOUSEEVENTF_LEFTUP, Cursor.Position.X, Cursor.Position.Y, 0, 0);
mouseLAlreadyDown = false;
mouseLAlreadyUp = true;
}
}
if (getRMouseDown)
{
if (!mouseRAlreadyDown)
{
mouse_event(MOUSEEVENTF_RIGHTDOWN, Cursor.Position.X, Cursor.Position.Y, 0, 0);
mouseRAlreadyDown = true;
mouseRAlreadyUp = false;
}
}
else
{
if (!mouseRAlreadyUp)
{
mouse_event(MOUSEEVENTF_RIGHTUP, Cursor.Position.X, Cursor.Position.Y, 0, 0);
mouseRAlreadyDown = false;
mouseRAlreadyUp = true;
}
}
lineCounter++;
}
else
{
mouse_event(MOUSEEVENTF_LEFTUP, Cursor.Position.X, Cursor.Position.Y, 0, 0);
timer2.Stop();
timeCounter.Stop();
}
timer2Tick--;
ts2 = timeCounter.Elapsed;
elapsedTime = String.Format("{0:00}:{1:00}.{2:00}", ts2.TotalMinutes, ts2.Seconds, ts2.Milliseconds/10);
label3.Text = elapsedTime.ToString();
}
private void timer3_Tick(object sender, EventArgs e) // a timer with 500ms interval used for some needs
{
if (!timer2.Enabled && !timer1.Enabled)
{
button1.Enabled = true;
button2.Enabled = true;
groupBox1.Enabled = true;
comboBox1.Enabled = true;
}
}
private void radioButton1_CheckedChanged(object sender, EventArgs e) // reproduction speed multiplier
{
if (radioButton1.Checked)
speed = 1;
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
if (radioButton2.Checked)
speed = 10;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) // get the name of the file when it is chosen
{
txtForUSe = comboBox1.Text;
}
private void ComboBox1_TextChanged(object sender, EventArgs e) // a way to take the name of the file when someone type it
{
txtForUSe = comboBox1.Text;
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e) // unhook
{
HookManager.MouseMove -= HookManager_MouseMove;
HookManager.MouseClick -= HookManager_MouseClick;
HookManager.MouseDown -= HookManager_MouseDown;
HookManager.MouseUp -= HookManager_MouseUp;
HookManager.KeyPress -= HookManager_KeyPress;
HookManager.KeyDown -= HookManager_KeyDown;
HookManager.KeyUp -= HookManager_KeyUp;
}
#region No Need To Be Shown
private void label2_Click(object sender, EventArgs e) { }
private void label1_Click(object sender, EventArgs e) { }
private void label2_Click_1(object sender, EventArgs e) { }
private void label3_Click(object sender, EventArgs e) { }
private void groupBox1_Enter(object sender, EventArgs e) { }
#endregion
}
}
<file_sep># Mouse-Recorder
Mouse recorder is a VS project
Debugged at the debug folder
to the App when you click and choose to run a saved file erese the ".txt" from the end that is automatically filled
|
07f88d8fcc63244d794fc8d8cd450ab532a95b1b
|
[
"Markdown",
"C#"
] | 2 |
C#
|
christoskaramou/Mouse-Recorder
|
ebb51f6df8d2f8689e2d40766304ee5834df548e
|
83285a73dd7b4417e53841c2eaf83973d2a24f08
|
refs/heads/master
|
<file_sep>#ifndef BASE_H
#define BASE_H
#include <SFML/Graphics.hpp>
class Base
{
/*
protected:
sf::Texture tx_fondo1;
sf::RenderWindow ventana;
sf::Font fuente;
sf::Sprite fondo1;
virtual bool inicializar();
virtual void dibujarSprites();
public:
Base(){}
*/
};
#endif // BASE_H
<file_sep>#ifndef PELOTA_HPP_INCLUDED
#define PELOTA_HPP_INCLUDED
#include "Bse.h"
#include <SFML/Graphics.hpp>
class Pelota:public Bse
{
/*
sf::Sprite m_sprite;
sf::Vector2f m_direccion;
int m_ancho_nivel;
int m_alto_nivel;
*/
int salto;
float velocidad;
public:
Pelota();
void inicializar(sf::Texture& tex, int ventana_w, int ventana_h);
const sf::Sprite& obtenerSprite();
//float obtenerX();
//float obtenerY();
void actualizar();
void reiniciar();
};
#endif // PELOTA_HPP_INCLUDED
<file_sep>#include <windows.h>
#include <iostream>
#include <stdlib.h>
#include <conio.h>
#include <stdio.h>
#define ARRIBA 72
#define IZQUIERDA 75
#define DERECHA 77
#define ABAJO 80
#define ESC 27
char tecla;
int velocidad = 10;
void gotoxy(int x, int y)
{
HANDLE hCon;
COORD dwPos;
dwPos.X = x;
dwPos.Y = y;
hCon = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(hCon,dwPos);
}
class Cjuego
{
private:
int velocidad;
public:
Cjuego(int);
void mostrarPared(void);
};
Cjuego::Cjuego(int _velocidad)
{
velocidad=_velocidad;
}
void Cjuego::mostrarPared(void)
{
int tam=28;
for(int i=0; i < tam; i++)
{
gotoxy (i, 0); printf ("%c", 205);
gotoxy(i, tam); printf ("%c", 205);
}
for(int v=0; v < tam; v++)
{
gotoxy (0,v); printf ("%c", 186);
gotoxy(tam,v); printf ("%c", 186);
}
}
class Cmovil
{
private:
int x,y;
public:
Cmovil(int,int);
void mostrar(void);
void mover(char);
};
Cmovil::Cmovil(int _x, int _y)
{
x=_x;
y=_y;
}
void Cmovil::mostrar(void)
{
int i,j;
for(i=1;i<= 3; i++)
{
for(j=1;j<=4; j++)
{
if(i==2 or j==2 or (i==1 and j==4) or (i==3 and j==4))
{
gotoxy (x+i, y+j); printf ("%s", "*");
}
else
{
gotoxy (x+i, y+j); printf ("%s", " ");
}
}
}
}
void Cmovil::mover(char tecla)
{
int i,j;
for(i=1;i<= 3; i++)
{
for(j=1;j<=4; j++)
{
gotoxy (x+i, y+j); printf ("%s", " ");
}
}
switch(tecla)
{
case ARRIBA : y--;break;
case ABAJO : y++;break;
case DERECHA : x++;break;
case IZQUIERDA : x--;break;
}
mostrar();
}
int main()
{
Cmovil *movil;
Cjuego *juego;
movil=new Cmovil(6,6);
movil->mostrar();
juego=new Cjuego(30);
juego->mostrarPared();
while(tecla != ESC )
{
if(kbhit())
{
tecla = getch();
movil->mover(tecla);
Sleep(velocidad);
}
}
return 0;
}
<file_sep>#ifndef BSE_H
#define BSE_H
#include <SFML/Graphics.hpp>
class Bse
{
protected:
sf::Sprite m_sprite;
sf::Vector2f m_direccion;
int m_ancho_nivel;
int m_alto_nivel;
public:
Bse(){}
float obtenerX();
float obtenerY();
};
#endif // BSE_H
<file_sep>#ifndef CJUGADOR_H
#define CJUGADOR_H
#include "premios.h"
#include "SFML/Graphics.hpp"
using namespace std;
using namespace sf;
class Cjugador
{
int x,y;
RectangleShape jugador;
public:
Cjugador(Vector2f size );
void move(Vector2f d);
int posx( );
void setPosition(int x,int y);
int posy();
void salta(int speed);
void dibujar(RenderWindow &ventana);
bool colision(int x,int y,int w,int H ,int m1,int m2,int W1,int H1);
};
#endif // CJUGADOR_H
<file_sep>#include "JUEGO.h"
#include "score.h"
#include "SFML/Graphics.hpp"
using namespace sf;
void gamemostrar();
JUEGO::JUEGO(int ancho,int alto,std::string letra){//creamos ventana
ventana = new RenderWindow(sf::VideoMode(ancho,alto),letra);
ventana->setFramerateLimit(60);
gamemostrar();
}
void JUEGO::gamemostrar(){
while(ventana->isOpen())
{
// Procesamos la pila de eventos
while (ventana->pollEvent(event))
{
// Si el evento es de tipo Closed cerramos la ventana
if (event.type == sf::Event::Closed)
ventana->close();
}
dibujar();
}
}
void JUEGO::dibujar()
{
ventana->clear();
//score.show(sf::RenderWindow *ventana);
ventana->display();
}
<file_sep>/*#include "manejar.h"
#include <assert.h>
//inicializo mi instancia a 0 o nulo
manejar *manejar::sIntancia = nullptr;
//definicion del constructor
manejar::manejar()
{
//Solo permite un Manejador de Assets si no manda una excepcion
//macro assert que verifica si la expresion es correcta
assert(sIntancia == nullptr);
sIntancia = this;
}
//definicion de obtenerTextura
sf::Texture &manejar::obtenerTextura(std::string const &nombreArchivo)
{
auto &mapTextura = sIntancia->m_Texturas;
//observamos si la textura esta lista para cargarlas
auto pairFound = mapTextura.find(nombreArchivo);
//Si esta lista regresamos la textura
if (pairFound != mapTextura.end())
{
return pairFound->second;
}
//si no carga la textura y la regresamos
else
{
//Creamos el elemento del map de la textura
auto &textura = mapTextura[nombreArchivo];
textura.loadFromFile(nombreArchivo);
return textura;
}
}
manejar::manejar()
{
//ctor
}
manejar::~manejar()
{
//dtor
}
*/
<file_sep>#include "score.h"
#include<sstream>
#include <cstring>
#include "mostrarPantalla.h"
#include "SFML/Graphics.hpp"
#include "JUEGO.h"
using namespace sf;
score::score()
{
puntoPlayer=0;
pointIA=0;
fuente1=new Font();
fuente1->loadFromFile("Antonine Personal Use.ttf");//cargamos fuente
textPlayer=new Text();
textPlayer->setFont(*fuente1);//cargando texto
textPlayer->setString("hola");
textPlayer->setCharacterSize(100);
textPlayer->setColor(sf::Color::Yellow);
}
void score::addPointPlayer(){
puntoPlayer++;}
void score::addPointIa(){
pointIA++;}
void score::show(sf::RenderWindow &ventana){
std::stringstream ia;
ia<<puntoPlayer;
//std::string st;
//st.push_back('0'+puntoPlayer);
//textPlayer->setString(st);
//textPlayer->setCharacterSize(100);
//textPlayer->setColor(sf::Color::Yellow);
//textPlayer->setPosition(ancho+textPlayer->getLocalBounds().ancho,20);
textPlayer->setPosition(0,-100);
ventana.draw(*textPlayer);
}
<file_sep>#include "jugador.h"
jugador::jugador()
{
//ctor
}
jugador::~jugador()
{
//dtor
}
<file_sep>
#include <iostream>
#include <sstream>
#include "Juego.h"
#define ANCHO 1200
#define ALTO 630
#define TITULO "JUEGO"
Juego::Juego()
{
iniciado = inicializar();
}
bool Juego::inicializar()
{
// Se cargan los archivos necesarios.
if (!fuente.loadFromFile("Fuentes/fuente.ttf"))
{
return false;
}
if (!tx_pelota.loadFromFile("imagenes/pelota.png"))
{
return false;
}
if (!tx_fondo.loadFromFile("imagenes/a.png"))
{
return false;
}
// Crear la ventana
ventana.create(sf::VideoMode(ANCHO, ALTO), TITULO);
// Limitar los FPS
ventana.setFramerateLimit(50);
// Fijar fuente para los textos
texto_score.setFont(fuente);
texto_score.setCharacterSize(40);
texto_tiempo.setFont(fuente);
texto_tiempo.setCharacterSize(40);
texto_fin.setFont(fuente);
texto_fin.setCharacterSize(40);
// Inicializar el score
texto_score.setString("Score");
texto_score.setPosition(50, 50);
score = 0;
// Inicializar el tiempo
texto_tiempo.setPosition(500, 20);
tiempo = 30.0;
actualizarTiempo();
// Textura del fondo
fondo.setTexture(tx_fondo);
// Inicializar los dos sprites
pelota1.inicializar(tx_pelota, ANCHO, ALTO);
pelota2.inicializar(tx_pelota, ANCHO, ALTO);
pelota3.inicializar(tx_pelota, ANCHO, ALTO);
return true;
}
void Juego::aumentarScore()
{
score += 1;
// Actualizar "texto_score" con el nuevo score.
std::stringstream s_score;
s_score << "Score" << std::endl << score;
texto_score.setString(s_score.str());
if (tiempo < 10)
{
tiempo += 1.0;
}
}
void Juego::actualizarTiempo()
{
std::stringstream s_tiempo;
s_tiempo << "Tiempo" << std::endl << tiempo;
texto_tiempo.setString(s_tiempo.str());
}
void Juego::actualizar()
{
pelota1.actualizar();
pelota2.actualizar();
pelota3.actualizar();
}
void Juego::dibujarSprites()
{
ventana.draw(fondo);
ventana.draw(pelota1.obtenerSprite());
ventana.draw(pelota2.obtenerSprite());
ventana.draw(pelota3.obtenerSprite());
ventana.draw(texto_score);
ventana.draw(texto_tiempo);
}
void Juego::dibujarFinal()
{
ventana.draw(texto_fin);
}
void Juego::correr()
{
if (!iniciado)
{
std::cout << "Falló al iniciar el juego..." << std::endl;
return;
}
sf::Clock reloj;
bool finalizado = false;
// Empieza el "loop" del juego
while (ventana.isOpen())
{
// Procesar los eventos de SFML
sf::Event event;
while (ventana.pollEvent(event))
{
// Evento: El usuario hace clic en el botón de cerrar [X]
if (event.type == sf::Event::Closed)
{
ventana.close();
}
// Evento: El usuario hace clic en la pantalla del juego
if (event.type == sf::Event::MouseButtonPressed
&& sf::Mouse::isButtonPressed(sf::Mouse::Left))
{
// Obtener las coordenadas del mouse
int mouseX = sf::Mouse::getPosition(ventana).x;
int mouseY = sf::Mouse::getPosition(ventana).y;
// Obtener las coordenadas de la primera pelota
float pelotaX = pelota1.obtenerX();
float pelotaY = pelota1.obtenerY();
// ¿El mouse tocó la pelota1?
if (mouseX > pelotaX - 40 && mouseX < pelotaX + 40
&& mouseY > pelotaY - 40 && mouseY < pelotaY + 40)
{
aumentarScore();
actualizarTiempo();
pelota1.reiniciar();
}
pelotaX = pelota2.obtenerX();
pelotaY = pelota2.obtenerY();
if (mouseX > pelotaX - 40 && mouseX < pelotaX + 40
&& mouseY > pelotaY - 40 && mouseY < pelotaY + 40)
{
aumentarScore();
actualizarTiempo();
pelota2.reiniciar();
}
pelotaX = pelota3.obtenerX();
pelotaY = pelota3.obtenerY();
if (mouseX > pelotaX - 40 && mouseX < pelotaX + 40
&& mouseY > pelotaY - 40 && mouseY < pelotaY + 40)
{
aumentarScore();
actualizarTiempo();
pelota3.reiniciar();
}
}
// Evento: Hubo una tecla presionada
if (event.type == sf::Event::KeyPressed && finalizado)
{
// Cerrar el juego en la escena final
ventana.close();
return;
}
}
if (reloj.getElapsedTime().asSeconds() >= 1.0)
{
if (tiempo == 0 && !finalizado)
{
// Poner el texto de fin y finalizar.
std::stringstream str;
str << " Tiempo!";
str << "\n";
str << "\n";
str << "Tu puntuacion final es: " << score;
texto_fin.setString(str.str());
texto_fin.setPosition(500, 250);
finalizado = true;
}
// El tiempo decrece cada segundo
--tiempo;
actualizarTiempo();
reloj.restart();
}
// Dibujar todo a la pantalla
if (!finalizado)
{
actualizar();
ventana.clear();
dibujarSprites();
}
else
{
ventana.clear(sf::Color(128, 128, 255));
dibujarFinal();
}
// Mostrar todo
ventana.display();
}
}
<file_sep>#include "Cjugador.h"
#include "SFML/Graphics.hpp"
#include<iostream>
using namespace std;
int Cjugador::posx(){
return jugador.getPosition().x;}
int Cjugador::posy(){
return jugador.getPosition().y;}
void Cjugador::setPosition(int x,int y){
jugador.setPosition(x,y);
}
void Cjugador::salta(int speed){
jugador.move(speed,0);
}
Cjugador::Cjugador(Vector2f size ){
jugador.setSize(size);
jugador.setFillColor(Color::Red);
}
void Cjugador::move(Vector2f d){
jugador.move(d);
}
void Cjugador::dibujar(RenderWindow &ventana){
ventana.draw(jugador);
}
bool Cjugador::colision(int jugador.posx(),int jugador.posy(),int w,int H ,int m1,int m2,int W1,int H1){
if(x+w <m1 || x > m1 +W1)
return false;
if(y+H < m2 || y > m2+H1){
jugador.move()
return false;}
return true;
}
<file_sep>#include "Pieza.h"
Pieza::Pieza()
{
//ctor
}
Pieza::~Pieza()
{
//dtor
}
<file_sep>#ifndef JUEGO_H
#define JUEGO_H
#include "SFML/Graphics.hpp"
#include <iostream>
#include<math.h>
using namespace sf;
class JUEGO
{
Sprite sprite,sprite1,sprite2;
public:
JUEGO(int ancho,int alto,std::string letra);
void gamemostrar();
void dibujar();
void mover();
private:
RenderWindow *ventana;
Event event;
};
#endif
<file_sep>#ifndef PREMIOS_H
#define PREMIOS_H
#include "SFML/Graphics.hpp"
using namespace std;
using namespace sf;
class premios
{
public:
RectangleShape *frutas,*monedas;
RenderWindow *mi_ventana;
vector<IntRect>framer;
float speed;
int x,y;
Sprite sprite;
void pospremios(int a,int b);
premios();
setVentana(RenderWindow *v);
void dibujar();
~premios();
};
#endif // PREMIOS_H
<file_sep>
#ifndef MENU_H
#define MENU_H
#include <SFML/Graphics.hpp>
#define MAX_NUMBER_OF_ITEMS 5
#include "Juego.h"
class Menu
{
public:
sf::RenderWindow ventana1;
sf::IntRect rectangulo;
bool inicio;
bool inicializa();
Juego juego;
sf::Texture tx_fondo1;
sf::Texture tx_fondo2;
sf::Sprite fondo1;
sf::Sprite fondo2;
void dibujarSprites();
void MoveUp();
void MoveDown();
int GetPressedItem() { return selectedItemIndex; }
Menu();
void accion();
private:
int selectedItemIndex;
sf::Text opcion[MAX_NUMBER_OF_ITEMS];
sf::Font fuente1;
sf::Font fuente2;
};
#endif // MENU_H
<file_sep>#include"mostrarPantalla.h"
#include"Cjugador.h"
#include "SFML/Graphics.hpp"
#include"JUEGO.h"
#include"score.h"
#include "premios.h"
using namespace std;
using namespace sf;
struct pelota{
RenderWindow* mi_ventana;
CircleShape* mi_at;
pelota(){
mi_at=new CircleShape(20);
}
setVentana(RenderWindow* v){
mi_ventana=v;
}
dibujar(){
mi_ventana->draw(*mi_at);
}
};
int main()
{
//Creando ventana
int ancho=800;
int altura=800;
RenderWindow ventana(VideoMode(ancho , altura), "mi videojuego");
ventana.setKeyRepeatEnabled(true);
//creando personaje
pelota P;
P.setVentana(&ventana);
P.mi_at->setFillColor(Color(0,255,0));
P.mi_at->setPosition(ancho/2,altura/2);
Cjugador persona(Vector2f(50,50));
persona.dibujar(ventana);
premios moneda;
moneda.pospremios(300,500);
moneda.setVentana(&ventana);
//SHAPE.setPosition(ancho/2,altura/2);
score s;
int dx=0;
int dy=0;
//pantalla es decir fondo
Texture fon;
fon.loadFromFile("");
Sprite imagen;
imagen.setTexture(fon);
Texture personaje;
personaje.loadFromFile("map1.png");
Sprite image1;
image1.setTexture(personaje);
imagen.setPosition(200,200);
image1.setPosition(ancho/2,altura/2);
//Creando camara
View vista(FloatRect(260 , 395 , 600 , 500));
vista.setSize( 1120 , 1280 );
vista.zoom(1);
vista.setCenter(200.f, 400.f);
int desplaza=100;
persona.colision()
//Cjugador jugador(Vector2f(32,32));
while (ventana.isOpen()) {
Event Event;
// screen scrolling
ventana.setView(vista);
//vista.move(desplaza,50);
while (ventana.pollEvent(Event)) {
switch (Event.type) {
case Event::Closed:
ventana.close();
}
//int moveSpeed = 100;
// isFiring = true;
if (Keyboard::isKeyPressed(Keyboard::Up)) {
//jugador.move(Vector2f(0, moveSpeed));
dy-=10;
} else if (Keyboard::isKeyPressed(Keyboard::Down)) {
dy+=10;
//jugador.move(Vector2f(0, -moveSpeed));
} else if (Keyboard::isKeyPressed(Keyboard::Left)) {
dx-=10;
//jugador.move(Vector2f(-moveSpeed, 0));
} else if (Keyboard::isKeyPressed(Keyboard::Right)) {
dx+=10;
//jugador.move(sf::Vector2f(moveSpeed, 0));
//desplaza = desplaza + 4;
}
}
ventana.clear();
s.show(ventana);
persona.setPosition(ancho/2+dx,altura/2+dy);
persona.posx();
persona.posy();
persona.dibujar(ventana);
moneda.dibujar();
// ventana.draw(imagen);
ventana.draw(image1);
ventana.display();
}
return 0;
}
<file_sep>
#ifndef JUEGO_HPP_INCLUDED
#define JUEGO_HPP_INCLUDED
#include <vector>
#include <SFML/Graphics.hpp>
#include "Pelota.h"
class Juego
{
//---------------------
// Variables privadas
//-------------------------
bool iniciado;
sf::RenderWindow ventana;
sf::Font fuente;
sf::Text texto_score;
sf::Text texto_tiempo;
sf::Text texto_fin;
int score;
int tiempo;
sf::Texture tx_fondo;
sf::Texture tx_pelota;
sf::Sprite fondo;
Pelota pelota1;
Pelota pelota2;
Pelota pelota3;
//--------------------
//Funciones privadas
//--------------------
bool inicializar();
void aumentarScore();
void actualizarTiempo();
void actualizar();
void dibujarSprites();
void dibujarFinal();
public:
Juego();
void correr();
};
#endif // JUEGO_HPP_INCLUDED
<file_sep>
#include "Juego.h"
#include "Menu.h"
#include <SFML/Graphics.hpp>
#include <iostream>
#include <sstream>
#define ANCHO 1200
#define ALTO 630
#define TITULO "Hit the Ball"
Menu::Menu()
{
inicio = inicializa();
}
bool Menu::inicializa()
{
// Se cargan los archivos necesarios.
if (!fuente1.loadFromFile("Fuentes/Abtecia.ttf"))
{
return false;
}
if (!fuente2.loadFromFile("Fuentes/ACafe.ttf"))
{
return false;
}
if (!tx_fondo1.loadFromFile("imagenes/opciones.jpg"))
{
return false;
}
// Crear la ventana
ventana1.create(sf::VideoMode(ANCHO, ALTO), TITULO);
// Limitar los FPS
ventana1.setFramerateLimit(50);
// Textura del fondo
fondo1.setTexture(tx_fondo1);
// Fijar fuente para los textos
opcion[0].setFont(fuente1);
opcion[1].setFont(fuente1);
opcion[2].setFont(fuente1);
opcion[3].setFont(fuente2);
opcion[4].setFont(fuente2);
// Inicializar el opcion
opcion[0].setString("PLAY");
opcion[0].setCharacterSize(40);
opcion[0].setPosition(520, 190);
opcion[0].setColor(sf::Color(255, 180, 255));
opcion[1].setString("ESCORES");
opcion[1].setCharacterSize(40);
opcion[1].setPosition(463, 305);
opcion[1].setColor(sf::Color(100, 0, 50));
opcion[2].setString("MINIJUEGO");
opcion[2].setCharacterSize(40);
opcion[2].setPosition(450, 423);
opcion[2].setColor(sf::Color(100, 0, 50));
opcion[3].setString("CREDITOS");
opcion[3].setCharacterSize(60);
opcion[3].setPosition(70, 500);
opcion[3].setColor(sf::Color(100, 0, 50));
opcion[4].setString("SALIR");
opcion[4].setCharacterSize(60);
opcion[4].setPosition(950, 500);
opcion[4].setColor(sf::Color(100, 0, 50));
selectedItemIndex = 0;
return true;
}
void Menu::dibujarSprites()
{
ventana1.draw(fondo1);
for(int i=0; i< MAX_NUMBER_OF_ITEMS ;i++){
ventana1.draw(opcion[i]);
}
}
void Menu::MoveUp()
{
if (selectedItemIndex - 1 >= 0)
{
opcion[selectedItemIndex].setColor(sf::Color(100, 0, 50));
selectedItemIndex--;
opcion[selectedItemIndex].setColor(sf::Color(255, 180, 255));
}
}
void Menu::MoveDown()
{
if (selectedItemIndex + 1 < MAX_NUMBER_OF_ITEMS)
{
opcion[selectedItemIndex].setColor(sf::Color(100, 0, 50));
selectedItemIndex++;
opcion[selectedItemIndex].setColor(sf::Color(255, 180, 255));
}
}
void Menu::accion()
{
if (!inicio)
{
std::cout << "Falló al iniciar el juego..." << std::endl;
return;
}
// Empieza el "loop" del juego
while (ventana1.isOpen())
{
// Procesar los eventos de SFML
sf::Event event;
while (ventana1.pollEvent(event))
{
switch (event.type)
{
case sf::Event::KeyReleased:
switch (event.key.code)
{
case sf::Keyboard::Up:
MoveUp();
break;
case sf::Keyboard::Down:
MoveDown();
break;
case sf::Keyboard::Return:
switch (GetPressedItem())
{
case 0:
std::cout << "Play apretaste el boton" << std::endl;
ventana1.close();
juego.correr();
break;
case 1:
std::cout << "Scores apretaste el boton" << std::endl;
break;
case 2:
std::cout << "Minijuego apretaste el boton" << std::endl;
break;
case 3:
std::cout << "Creditos apretaste el boton" << std::endl;
break;
case 4:
ventana1.close();
break;
}
break;
}
break;
case sf::Event::Closed:
ventana1.close();
break;
}
}
ventana1.clear();
// Mostrar todo
dibujarSprites();
ventana1.display();
}
}
<file_sep>
#include <cmath>
#include <cstdlib>
#include "Pelota.h"
Pelota::Pelota()
{
}
void Pelota::inicializar(sf::Texture& tex, int max_ancho, int max_alto)
{
m_sprite.setTexture(tex);
m_sprite.setOrigin(tex.getSize().x / 2, tex.getSize().y / 2);
m_ancho_nivel = max_ancho;
m_alto_nivel = max_alto;
salto=max_alto;
// Velocidad inicial
velocidad = 4.0;
reiniciar();
}
const sf::Sprite& Pelota::obtenerSprite()
{
return m_sprite;
}
/*
float Pelota::obtenerX()
{
return m_sprite.getPosition().x;
}
float Pelota::obtenerY()
{
return m_sprite.getPosition().y;
}
*/
void Pelota::actualizar()
{
m_sprite.move(m_direccion);
float posX = m_sprite.getPosition().x;
float posY = m_sprite.getPosition().y;
// Rebotar si las coordenadas sobrepasan el tamaño del nivel
if (posX < 0 || posX > m_ancho_nivel)
{
m_direccion.x *= -1;
}
if (posY < 0 || posY > salto)
{
m_direccion.y *= -1;
}
}
void Pelota::reiniciar()
{
m_sprite.setPosition(rand() % m_ancho_nivel, rand() %m_alto_nivel);
int dir = rand() % 180;
m_direccion.x = cos(dir * 3.1416 / 180) * velocidad;
m_direccion.y = sin(dir * 3.1416 / 180) * velocidad;
// La velocidad será un poco más rápida al próximo reinicio
velocidad += 0.1;
}
<file_sep>#ifndef JUGADOR_H
#define JUGADOR_H
class jugador
{
public:
jugador();
virtual ~jugador();
protected:
private:
};
#endif // JUGADOR_H
<file_sep>#define MOSTRARPANTALLA_H
static unsigned int ancho=1300;
static unsigned int alto=900;
<file_sep>
#include <cstdlib>
#include <ctime>
#include "Juego.h"
#include "Menu.h"
#include <iostream>
using namespace std;
int main()
{
srand(time(0));
//Juego juego;
//juego.correr();
Menu menu;
menu.accion();
//Juego juego;
//juego.correr();
return 0;
}
<file_sep>#include "Bse.h"
float Bse::obtenerX()
{
return m_sprite.getPosition().x;
}
float Bse::obtenerY()
{
return m_sprite.getPosition().y;
}
<file_sep>#ifndef PIEZA_H
#define PIEZA_H
class Pieza
{
public:
Pieza();
virtual ~Pieza();
protected:
private:
};
#endif // PIEZA_H
<file_sep>#include "premios.h"
#include "SFML/Graphics.hpp"
using namespace sf;
void premios::pospremios(int a,int b)
{
x=a;
y=b;
frutas->setPosition(Vector2f(x,y));
}
premios::premios(){
frutas=new RectangleShape(Vector2f(60,60));
}
premios::setVentana(RenderWindow *v){
mi_ventana=v;
}
void premios::dibujar(){
frutas->setFillColor(Color(100,0,100));
mi_ventana->draw(*frutas);
}
premios::~premios(){
delete frutas;
}
<file_sep>/*#ifndef MANEJAR_H
#define MANEJAR_H
#include <SFML\Graphics.hpp>
#include <map>
#include <string>
class manejar
{
public:
//constructor
manejar();
//funcion estatica para obtener las texturas
static sf::Texture &obtenerTextura(std::string const &nombreArchivo);
private:
//mapa que me servira manejar las texturas por medio de identificadores de cadenas
std::map<std::string, sf::Texture> m_Texturas;
//El manejador de assets es un singleton, esto solo es una instancia que puede
//existir al mantener un puntero estatico en una simple instancia del manejador
static manejar *sIntancia;
};
#endif// MANEJAR_H*/
|
0d0af8a5121a893459bbee88c857859d8635a1ab
|
[
"C",
"C++"
] | 26 |
C++
|
iriscuro/Proyecto_final
|
770ecf5a997b6f940fd6eaa99570b2944b592804
|
2f53ccdfc828de2d561a9262c676f12b2d4b1990
|
refs/heads/master
|
<file_sep>class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_filter :authenticate
skip_before_action :verify_authenticity_token
protected
def authenticate
authenticate_or_request_with_http_basic do |username, password|
puts 'get_authentication_username'
puts get_authentication_username
puts decode username
decode(username) == get_authentication_username && decode(password) == get_authentication_password
end
end
ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
ENCODING = "MOhqm0PnycUZeLdK8YvDCgNfb7FJtiHT52BrxoAkas9RWlXpEujSGI64VzQ31w"
def encode(text)
return text.tr(ALPHABET, ENCODING)
end
def decode(text)
return text.tr(ENCODING, ALPHABET)
end
def get_authentication_username
BasicAuthenticationInfo.last['username']
end
def get_authentication_password
<PASSWORD>['<PASSWORD>']
end
def nadastore_url
username = encode get_authentication_username
password = encode get_authentication_password
"http://#{username}:#{password}@localhost:3000/"
end
def cart_url
username = encode get_authentication_username
password = encode get_authentication_password
"http://#{username}:#{password}@localhost:3040/"
end
def store_url
username = encode get_authentication_username
password = encode get_authentication_password
"http://#{username}:#{password}@localhost:3050/"
end
def review_url
username = encode get_authentication_username
password = encode get_authentication_password
"http://#{username}:#{password}@localhost:3060/"
end
def order_url
username = encode get_authentication_username
password = encode get_authentication_password
"http://#{username}:#{password}@localhost:3070/"
end
end
<file_sep>class User < ActiveRecord::Base
after_save :clear_password
def clear_password
self.password = nil
end
validates :username, :presence => true, :uniqueness => true, :length => { :in => 3..50 }
validates :password, :presence => true, :length => { :in => 3..500 }
validates_format_of :email, with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
validates_format_of :firstname, with: /\A([a-z]{2,})\Z/i, :on => :create
validates_format_of :lastname, with: /\A([a-z]{2,})\Z/i, :on => :create
# EMAIL_REGEX = '/\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i'
end
<file_sep>class CheckoutController < ApplicationController
skip_before_action :verify_authenticity_token
#POST /user_id/charge
def charge
balance = Balance.where({:user_id => params[:user_id] })
balance.credit = params[:money]
end
# POST /checkout
def checkout
#get json containing items in card in items
#returned JSON:
# [{"id":null,"title":"Makwa","price":30.0,"quantity":70,
# "created_at":"2016-07-18T16:13:18.404Z",
# "updated_at":"2016-07-18T16:13:18.404Z","item_id":"1","user_quantity":70}]
str = cart_url + params[:user_id]
res_json = RestClient.get str, :content_type => 'application/json'
puts res_json
items = JSON.parse (res_json)
flag = true
invoice = 0
puts "items", items
items.each do |item|
puts "item", item
if item['user_quantity'].to_i > item['quantity'].to_i
flag = false
end
invoice += item['user_quantity'].to_f * item['price'].to_f
end
puts 'invoice', invoice
balance = 0
balance_record = Balance.where({:user_id => params[:user_id] })
puts "@", balance_record.empty?
if !balance_record.empty?
balance = balance_record.first[:credit]
end
if balance < invoice
flag = false
puts "ad" , balance
end
#Balance model attributes : user_id, credit
response = {}
if !flag
response[:error] = 'invalid transaction'
else
response[:response] = 'Success'
# request empty cart from CART
str = cart_url + params[:user_id]
RestClient.delete str, :content_type => 'application/json'
#buy items from STORE
items.each do |item|
str = store_url + item['item_id'].to_s + '/' + item['user_quantity'].to_s
RestClient.put str, :content_type => 'application/json'
end
#update balance
balance = Balance.where({:user_id => params[:user_id] }).first
balance.credit -= invoice
balance.save!
end
render :json => response.to_json
end
end
<file_sep>class BasicAuthenticationInfo < ActiveRecord::Base
end
<file_sep>class CartController < ApplicationController
def add
payload = params['item_tosend']
if payload['quantity'].to_i > 0
# puts "payload" , payload , "."
payload_json = payload.to_json
puts "payload", payload["id"]
str = cart_url + session[:user_id].to_s + '/' + payload[:id].to_s + '/' + payload[:quantity].to_s + '/'
res_json = RestClient.put str, :content_type => 'application/json'
ret = "success"
else
ret = "error"
end
redirect_to welcome_index_path(ret)
end
def remove
item_id = params['format']
str = cart_url + session[:user_id].to_s + '/' + item_id.to_s + '/'
res_json = RestClient.delete str, :content_type => 'application/json'
redirect_to cart_index_path
end
def update
######
end
def index
str = cart_url + session[:user_id].to_s
puts 'str' , str
res_json = RestClient.get str, :content_type => 'application/json'
puts res_json
@items = JSON.parse (res_json)
end
end
<file_sep>class UserController < ApplicationController
def create
payload = {:username => params[:user][:username].to_s, :password => encrypt_password( params[:user][:password].to_s),
:firstname => params[:user][:firstname].to_s, :email => params[:user][:email].to_s,
:lastname => params[:user][:lastname].to_s,
}
payload_json = payload.to_json
res_json = RestClient.post authentication_url + 'users', payload_json, :content_type => 'application/json'
res = JSON.parse(res_json)
puts "res", res
if res.has_key?("id")
session[:user_id] = res["id"]
session[:user_name] = res["name"]
@response = "User has been created successfully!!"
@user_id = res["id"]
####for the store
payload = {:credit => params[:user][:balance], :user_id => session[:user_id]}
payload_json = payload.to_json
str = order_url + 'balances/' # +params[:user][:balance].to_s + '/' + session[:user_id].to_s + '/'
puts "strrr" , str
res_json = RestClient.post str, payload_json, :content_type => 'application/json'
res = JSON.parse(res_json)
puts "res", res
redirect_to welcome_index_path
else
notice ="Unfortunately, there is something wrong"
redirect_to welcome_signup_path(notice)
end
end
def encrypt_password ( passo )
hashed_pass = <PASSWORD>.hexdigest (passo)
return hashed_pass
end
def login
@tempo = encrypt_password ( params[:user][:password].to_s )
payload = {:username => params[:user][:username].to_s, :password => <PASSWORD>.to_s}
payload_json = payload.to_json
res_json = RestClient.post authentication_url + 'users/login', payload_json, :content_type => 'application/json'
puts "res_json", res_json
res = JSON.parse(res_json)
puts res.has_key?("id").to_s
if res.has_key?("id") #YESS
session[:user_id] = res["id"]
session[:user_name] = res["name"]
@response = "You are logged in successfully!!"
redirect_to welcome_index_path
else
@response ="Unfortunately, there is something wrong"
end
end
def logout
session[:user_id] = nil
session[:user_name] = nil
redirect_to welcome_index_path
end
end
# 1.6.1 # RestClient.post 'http://example.com/resource', 'the post body', :content_type => 'text/plain'
<file_sep>class ApiController < ApplicationController
skip_before_action :verify_authenticity_token
def remove_item
response = {}
UserItem.where({:user_id => params[:user_id], :item_id => params[:item_id]}).destroy_all
response[:response] = 'Success'
render :json => response.to_json
end
def update_item
response = {}
user_item = UserItem.find_or_create_by!({:user_id => params[:user_id], :item_id => params[:item_id]})
user_item.quantity = params[:quantity].to_i
user_item.save!
response[:response] = 'Success'
render :json => response.to_json
end
def get_cart
response = []
puts params
user_items = UserItem.select('item_id, quantity as user_quantity').where({:user_id => params[:user_id]}).all
puts user_items
user_items.each do |item|
res_json = RestClient.get store_url + 'items/' + item['item_id'].to_s , :content_type => 'application/json'
puts res_json
item_from_store = JSON.parse(res_json)
puts item_from_store
response.push(item_from_store.merge(item.as_json))
end
render :json => response.to_json
end
def empty_cart
response = {}
UserItem.where(:user_id => params[:user_id]).destroy_all
response[:response] = 'Success'
render :json => response.to_json
end
before_filter :authenticate
protected
def authenticate
authenticate_or_request_with_http_basic do |username, password|
puts 'get_authentication_username'
puts get_authentication_username
puts decode username
decode(username) == get_authentication_username && decode(password) == get_authentication_password
end
end
end
<file_sep>require 'test_helper'
class CartOperationsControllerTest < ActionController::TestCase
test "should get add_tem" do
get :add_tem
assert_response :success
end
test "should get remove_item" do
get :remove_item
assert_response :success
end
test "should get update_item" do
get :update_item
assert_response :success
end
test "should get get_cart" do
get :get_cart
assert_response :success
end
end
<file_sep>json.extract! @balance, :id, :user_id, :credit, :created_at, :updated_at
<file_sep>class OrderController < ApplicationController
def add
# payload = @order
# puts payload
puts "********" , session[:user_id].to_s
# payload_json = payload.to_json
res_json = RestClient.post order_url + session[:user_id].to_s, :content_type => 'application/json'
puts "res_json", res_json
@res = JSON.parse(res_json)
end
end
<file_sep>class ItemController < ApplicationController
def index
@is_user_signed = session['user_id'].present?
res_json = RestClient.get store_url + 'items/' + params["item_id"] , :content_type => 'application/json'
@item = JSON.parse(res_json)
res_json = RestClient.get review_url + params["item_id"] , :content_type => 'application/json'
@reviews = JSON.parse(res_json)
end
def submit_review
@is_user_signed = session['user_id'].present?
if @is_user_signed
request_uri = review_url + params['item_id'] + '/' + session['user_id'].to_s + '/' \
+ params['review']['rating'] + '/' + params['review']['body']
RestClient.post URI.escape(request_uri) , :content_type => 'application/json'
end
redirect_to item_index_path(params['item_id'])
end
def add
filldb = Array[{'title' => "Makwa", 'price' => 30 , 'quantity' => 70},{'title' => "Fera5", 'price' => 20 , 'quantity'=> 9},
{'title' => "Cream", 'price' => 6 , 'quantity' => 100},{'title' => "batee5", 'price' => 55 , 'quantity'=> 2},
{'title' => "Shagara", 'price' => 4 , 'quantity' => 88},{'title' => "Wezza", 'price' => 35 , 'quantity'=> 4}]
# @items = Array[{'id'=> 1, 'title' => "Makwa", 'price' => 30 , 'quantity' => 70},{'id' => 2,'title' => "Fera5", 'price' => 20 , 'quantity'=> 9}]
filldb.each do |item|
payload_json = item.to_json
puts payload_json
res_json = RestClient.post 'http://localhost:3050/items', payload_json, :content_type => 'application/json'
res = JSON.parse(res_json)
puts "res", res
end
redirect_to welcome_index_path
end
end
<file_sep>class AddIndexToTableName < ActiveRecord::Migration
def change
add_index "user_items", ["user_id", "item_id"], :unique => true
end
end
<file_sep>class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
protected
ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
ENCODING = "MOhqm0PnycUZeLdK8YvDCgNfb7FJtiHT52BrxoAkas9RWlXpEujSGI64VzQ31w"
def encode(text)
return text.tr(ALPHABET, ENCODING)
end
def decode(text)
return text.tr(ENCODING, ALPHABET)
end
def get_authentication_username
BasicAuthenticationInfo.last['username']
end
def get_authentication_password
Basic<PASSWORD>.last['password']
end
def authentication_url
username = encode get_authentication_username
password = encode get_authentication_password
"http://#{username}:#{password}@localhost:3030/"
end
def nadastore_url
username = encode get_authentication_username
password = encode get_authentication_password
"http://#{username}:#{password}@localhost:3000/"
end
def cart_url
username = encode get_authentication_username
password = encode get_authentication_password
"http://#{username}:#{password}@localhost:3040/"
end
def store_url
username = encode get_authentication_username
password = encode get_authentication_password
"http://#{username}:#{password}@localhost:3050/"
end
def review_url
username = encode get_authentication_username
password = encode get_authentication_password
"http://#{username}:#{password}@localhost:3060/"
end
def order_url
username = encode get_authentication_username
password = encode get_authentication_password
"http://#{username}:#{password}@localhost:3070/"
end
end
<file_sep>class ApiController < ApplicationController
skip_before_action :verify_authenticity_token
def add_review
response = {}
user_item = Review.find_or_create_by!({:user_id => params[:user_id], :item_id => params[:item_id]})
user_item.rating = params[:rating].to_i
user_item.body = params[:body]
user_item.save!
response[:response] = 'Success'
render :json => response.to_json
end
def get_reviews
response = {}
reviews = Review.where({:item_id => params[:item_id]}).all
response = reviews
render :json => response.to_json(only: [:item_id, :user_id, :rating, :body, :error])
end
end
<file_sep>class WelcomeController < ApplicationController
def index
filldb = Array[{'title' => "Makwa", 'price' => 30 , 'quantity' => 70},{'title' => "Fera5", 'price' => 20 , 'quantity'=> 9}]
# @items = Array[{'id'=> 1, 'title' => "Makwa", 'price' => 30 , 'quantity' => 70},{'id' => 2,'title' => "Fera5", 'price' => 20 , 'quantity'=> 9}]
# filldb.each do |item|
# payload_json = item.to_json
# puts payload_json
# res_json = RestClient.post 'http://localhost:3050/items', payload_json, :content_type => 'application/json'
# res = JSON.parse(res_json)
# puts "res", res
# end
puts "a888888888", store_url + 'items'
items_json = RestClient.get store_url + 'items' , :content_type => 'application/json'
@items = JSON.parse(items_json)
puts "items", @items
puts "session", session['user_id']
end
def signup
end
def login
end
end
|
bee81c5cac6062bd958a1c27f48482bca4b8fbac
|
[
"Ruby"
] | 15 |
Ruby
|
armansabaa/projectX
|
ce90cca5b7ce68bbde18c299664e826a6c3aebcb
|
f998fe34608dc49bc2ba7ae9afed73dbde80a7b1
|
refs/heads/master
|
<repo_name>germandelvalle/tucelu2<file_sep>/src/store/index.js
import { createStore } from 'vuex'
export default createStore({
state: {
articulos: [
{
id: 0,
nombre: 'Iphone 8 ',
imagen: 'https://store.storeimages.cdn-apple.com/4668/as-images.apple.com/is/refurb-iphone8plus-spacegray?wid=1144&hei=1144&fmt=jpeg&qlt=95&op_usm=0.5,0.5&.v=1564083513793',
imagen2: 'https://c0.wallpaperflare.com/preview/699/948/962/space-gray-iphone-8-plus-on-brown-case.jpg',
descripcion: {
fecha: 'Lanzamiento: Septiembre 2017',
peso: 'PESO:202g',
espesor: 'ESPESOR:7.5mm',
memoria: 'MEMORIA:64GB',
pantalla: 'PANTALLA:5.5″1080×1920 pixels',
camara: '1CAMARA:12MP 2160p',
RAM: 'MEMORIA RAM:3GB',
procesador:'PROCESADOR:Apple A11 Bionic',
bateria: 'BATERIA:2691mAhLi-Ion'
},
precio: 80000
},
{
id: 1,
nombre: 'iPhone X',
imagen: 'https://store.storeimages.cdn-apple.com/4982/as-images.apple.com/is/iphone-xr-black-select-201809?wid=940&hei=1112&fmt=png-alpha&qlt=80&.v=1551226038992',
imagen2: 'https://www.dhresource.com/0x0s/f2-albu-g4-M01-5D-2B-rBVaEFmg8wCAQv5oAAB0IeTfpFc659.jpg/full-protective-case-for-iphone-x-tpu-acrylic.jpg',
descripcion: {
fecha: 'Lanzamiento Noviembre 2017',
peso: 'Peso 174 gramos',
espesor: 'Espesor 7.7mm ',
memoria: 'Memoria interna 64/256GB No Expandible',
pantalla: 'Pantalla de 5.8″',
camara: 'Camara Principal 12MP',
RAM: 'Memoria Ram 3GB',
procesador:'procesador Apple A11 (6 núcleos)',
bateria: 'Bateria 2716mAh Li-Ion'
},
precio: 140000
},
{
id: 2,
nombre: 'iPhone 11',
imagen: 'https://store.storeimages.cdn-apple.com/4982/as-images.apple.com/is/iphone11-black-select-2019?wid=470&hei=556&fmt=png-alpha&.v=1566956144418',
imagen2: 'https://cdn.shopify.com/s/files/1/0289/7061/4843/products/XR9DHD.jpg?v=1596039826',
descripcion: {
fecha: 'Lanzamiento septiembre 2019',
peso: 'Peso 194 g',
espesor: 'Espesor 8,3 mm ',
memoria: 'Memoria interna 128 GB',
pantalla: 'Pantalla de 6,1"',
camara: 'Camara Principal 12MP',
RAM: 'Memoria Ram 4 GB',
procesador:'procesador Chip A13 Bionic',
bateria: 'Carga rápida 18W (cargador no incluido)'
},
precio: 190000
}
]
},
mutations: {
aumentar(state,index){
state.frutas[index].cantidad ++
},
reiniciar(state){
state.frutas.forEach((elemento)=>{
elemento.cantidad=0
})
}
},
actions: {
},
modules: {
}
})
<file_sep>/README.md
# tucelu2
tucelu2 es una SPA (single page application) en desarrollo para proyecto final del programa "codo a codo".
Por el momento posee las siguientes tecnologias:
-HTML
-CSS
-BOOTSTRAP
-JAVASCRIPT ( VUE.JS)
Mirala en [tucelu2](https://tucelu2.netlify.app/#/).
## Project setup
```
npm install
```
### Compiles and hot-reloads for development
```
npm run serve
```
### Compiles and minifies for production
```
npm run build
```
### Lints and fixes files
```
npm run lint
```
### Customize configuration
See [Configuration Reference](https://cli.vuejs.org/config/).
|
4389a95209f741f54175c487df7ed564b3e4f84d
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
germandelvalle/tucelu2
|
fe583f21259c09429e5e39416384b1587bec74db
|
e4f5da5b53f8dc03bce5e19d2f48eebb584fd80b
|
refs/heads/master
|
<repo_name>VAMK-embedded-project-2019A/Bluetooth-Server<file_sep>/include/vamk_rsa.h
#ifndef VAMK_RSA
#define VAMK_RSA
#include <memory>
#include <vector>
namespace vamk {
class Rsa {
public:
Rsa();
Rsa(const Rsa &) = delete;
Rsa operator=(const Rsa &) = delete;
~Rsa();
void generateKeyPair();
std::vector<char> getPublicKey();
std::vector<char> decrypt(std::vector<char>);
private:
// pImpl technique
struct RsaImpl;
std::unique_ptr<RsaImpl> _pimpl;
};
}
#endif<file_sep>/include/vamk_random.h
#ifndef VAMK_RANDOM
#define VAMK_RANDOM
#include <vector>
namespace vamk {
void seedRandom();
std::vector<char> getRandom(int);
}
#endif<file_sep>/makefile
CC = gcc
CXX = g++
BIN = bt
SRC_DIR = src
INC_DIR = include
OBJ_DIR = obj
OBJS := $(patsubst $(SRC_DIR)/%.cpp, %, $(wildcard $(SRC_DIR)/*.cpp))
DEPS_OBJS = $(filter-out main, $(OBJS))
INCLUDE_FILES = $(foreach OBJ, $(DEPS_OBJS), $(INC_DIR)/$(OBJ).h)
OBJ_FILES = $(foreach OBJ, $(OBJS), $(OBJ_DIR)/$(OBJ).o)
INCLUDE_OPTS = -iquote include
LIB_OPTS = -lbluetooth -lcrypto
TOOL_OPTS = -std=c++11 -g
OPTS_OBJ = $(INCLUDE_OPTS) $(TOOL_OPTS)
OPTS_BIN = $(INCLUDE_OPTS) $(TOOL_OPTS) $(LIB_OPTS)
first: $(BIN)
$(BIN): $(OBJ_FILES)
$(CXX) -o $(BIN) $(OBJ_FILES) $(OPTS_BIN)
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp $(INCLUDE_DEPS)
$(CXX) $< -c -o $@ $(OPTS_OBJ)
clean:
rm -f $(OBJ_DIR)/*.o
<file_sep>/include/vamk_rfcomm.h
#ifndef VAMK_RFCOMM
#define VAMK_RFCOMM
#include <memory>
#include <vector>
namespace vamk {
class Socket;
class RfcommClientSocket;
class RfcommServerSocket : public Socket {
public:
// allocate the socket
RfcommServerSocket();
// delete implicit constructor
RfcommServerSocket(const RfcommServerSocket &) = delete;
RfcommServerSocket operator=(const RfcommServerSocket &) = delete;
// bind, start listening
void listen(int channel);
// accept a client
std::unique_ptr<RfcommClientSocket> accept();
};
class RfcommClientSocket : public Socket {
public:
// delete implicit constructor
RfcommClientSocket() = delete;
RfcommClientSocket(const RfcommClientSocket &) = delete;
RfcommServerSocket operator=(const RfcommClientSocket &) = delete;
// read from stream
int read(std::vector<char> &);
// write to stream
int write(const std::vector<char> &);
private:
// allocate the socket
RfcommClientSocket(int socket);
// only server can construct client
friend RfcommServerSocket;
};
}
#endif
<file_sep>/src/espp_bt_server.cpp
#include <stdio.h>
#include "vamk_socket.h"
#include "vamk_aes.h"
#include "vamk_rfcomm.h"
#include "vamk_rsa.h"
#include "vamk_sdp.h"
#include "espp_bt_client.h"
#include "espp_bt_server.h"
using std::unique_ptr;
using vamk::Sdp;
using vamk::Rsa;
using vamk::RfcommServerSocket;
using vamk::RfcommClientSocket;
namespace espp {
BtServer::BtServer() { _init(); }
BtServer::~BtServer() { stop(); }
void BtServer::start() {
_init();
uint8_t uuid[16] = {0x1e, 0x0c, 0xa4, 0xea, 0x29, 0x9d, 0x43, 0x35,
0x93, 0xeb, 0x27, 0xfc, 0xfe, 0x7f, 0xa8, 0x48};
vamk::SdpServiceInfo info = {};
info.name = "ESPP Music Player";
info.desc = "Service for music player based on weather from VAMK";
info.prov = "VAMK";
printf("Generating RSA key... ");
fflush(stdout);
_rsa->generateKeyPair();
printf("OK.\n");
printf("Start listening on channel %d. ", CHANNEL);
_server_socket->listen(CHANNEL);
printf("Started advertising SDP service.\n\n");
_sdp->startAdvertise(uuid, CHANNEL, &info);
}
void BtServer::stop() {
printf("\n");
if (_sdp) {
printf("Stopped advertising SDP service. ");
_sdp->endAdvertise();
}
if (_server_socket) {
printf("Closing server socket.");
_server_socket->close();
}
printf("\n");
_deinit();
}
std::unique_ptr<BtClient> BtServer::accept() {
printf("Waiting for client... ");
fflush(stdout);
auto client_socket = _server_socket->accept();
printf("OK.\n");
return unique_ptr<BtClient>(new BtClient(_rsa, client_socket));
}
// init the member pointer
void BtServer::_init() {
if (!_sdp)
_sdp = unique_ptr<Sdp>(new Sdp);
if (!_rsa)
_rsa = unique_ptr<Rsa>(new Rsa);
if (!_server_socket)
_server_socket = unique_ptr<RfcommServerSocket>(new RfcommServerSocket);
}
// free the member pointer
void BtServer::_deinit() {
if (_sdp)
_sdp.reset();
if (_rsa)
_rsa.reset();
if (_server_socket)
_server_socket.reset();
}
}
<file_sep>/src/main.cpp
#include "espp_bt_client.h"
#include "espp_bt_server.h"
#include <stdio.h>
using std::vector;
using espp::BtServer;
using espp::BtClient;
int main() {
BtServer server;
server.start();
auto client = server.accept();
printf("Exchanging key... ");
fflush(stdout);
if (client->exchangeKey())
printf("OK.\n");
else
printf("failed.\n");
server.stop();
return 0;
}
<file_sep>/src/espp_bt_client.cpp
#include <stdio.h>
#include "vamk_socket.h"
#include "vamk_aes.h"
#include "vamk_random.h"
#include "vamk_rfcomm.h"
#include "vamk_rsa.h"
#include "espp_bt_client.h"
using std::unique_ptr;
using std::vector;
using vamk::Aes;
using vamk::Rsa;
using vamk::RfcommClientSocket;
namespace espp {
BtClient::BtClient(std::shared_ptr<vamk::Rsa> rsa,
std::unique_ptr<vamk::RfcommClientSocket> &socket)
: _rsa(rsa) {
using std::swap;
swap(_socket, socket);
}
BtClient::~BtClient() {
if (_aes)
_aes.reset();
}
bool BtClient::exchangeKey() {
static const vector<char> init_message{'E', 'S', 'P', 'P'};
static const vector<char> ack_message{'O', 'K'};
static const vector<char> ready_message{'R', 'E', 'A', 'D', 'Y'};
vector<char> buf;
int size;
// receive init message
size = read(buf);
if (size < 0)
return false;
if (buf != init_message)
return false;
// send public key
auto rsa_key = _rsa->getPublicKey();
size = write(rsa_key);
if (size < 0)
return false;
// receive rsa key
size = read(buf);
if (size < 0)
return false;
// setup aes
_aes = unique_ptr<Aes>(new Aes);
auto aes_key = _rsa->decrypt(buf);
_aes->setKey(aes_key);
// verify aes key
size = write(ack_message);
if (size < 0)
return false;
size = read(buf);
if (size < 0)
return false;
if (buf != ack_message)
return false;
// send ready message
size = write(ready_message);
if (size < 0)
return false;
return true;
}
int BtClient::read(std::vector<char> &data) {
if (_aes) {
// read from socket
vector<char> buf;
int size = _socket->read(buf);
if (size < 16)
return -1;
// split iv and cipher text, then decrypt
vector<char> iv(buf.begin(), buf.begin() + 16);
vector<char> ctext(buf.begin() + 16, buf.end());
vector<char> ptext = _aes->decrypt(ctext, iv);
// return values
data = ptext;
return ptext.size();
} else
return _socket->read(data);
}
int BtClient::write(const std::vector<char> &data) {
if (_aes) {
vector<char> buf = vamk::getRandom(16); // iv
vector<char> ctext = _aes->encrypt(data, buf); // use buf as iv
// append cipher text to iv and send
buf.insert(buf.end(), ctext.begin(), ctext.end());
return _socket->write(buf);
} else
return _socket->write(data);
}
}
<file_sep>/include/espp_bt_client.h
#ifndef ESPP_BT_SOCKET
#define ESPP_BT_SOCKET
#include <memory>
#include <vector>
namespace vamk {
class Rsa;
class Aes;
class RfcommClientSocket;
}
namespace espp {
class BtServer;
class BtClient {
public:
BtClient() = delete;
BtClient(const BtClient &) = delete;
BtClient operator=(const BtClient &) = delete;
~BtClient();
bool exchangeKey();
int read(std::vector<char> &);
int write(const std::vector<char> &);
private:
BtClient(std::shared_ptr<vamk::Rsa> , std::unique_ptr<vamk::RfcommClientSocket> &);
std::shared_ptr<vamk::Rsa> _rsa;
std::unique_ptr<vamk::RfcommClientSocket> _socket;
std::unique_ptr<vamk::Aes> _aes;
friend BtServer;
};
}
#endif<file_sep>/src/vamk_rsa.cpp
#include <mutex>
#include <openssl/bn.h>
#include <openssl/rsa.h>
#include "vamk_random.h"
#include "vamk_rsa.h"
#define RSA_KEY_SIZE 2048
using std::unique_ptr;
using std::vector;
using std::mutex;
using std::lock_guard;
using BN_ptr = unique_ptr<BIGNUM, decltype(&::BN_free)>;
using RSA_ptr = unique_ptr<RSA, decltype(&::RSA_free)>;
namespace vamk {
struct Rsa::RsaImpl {
RsaImpl();
void generateKeyPair();
vector<char> getPublicKey();
vector<char> decrypt(vector<char>);
mutex rsa_mutex;
RSA_ptr rsa;
BN_ptr bn;
};
// Rsa implementation
Rsa::RsaImpl::RsaImpl() : rsa(RSA_new(), ::RSA_free), bn(BN_new(), ::BN_free) {}
void Rsa::RsaImpl::generateKeyPair() {
// seed the random number generator
vamk::seedRandom();
// set modulus
BN_set_word(bn.get(), RSA_F4);
// generate key
int err = RSA_generate_key_ex(rsa.get(), RSA_KEY_SIZE, bn.get(), NULL);
}
vector<char> Rsa::RsaImpl::getPublicKey() {
const lock_guard<mutex> lock(rsa_mutex);
// get public exponent
#if (OPENSSL_VERSION_NUMBER < 0x010100000)
BIGNUM *n = rsa->n;
#else
BIGNUM *n;
RSA_get0_key(rsa.get(), (const BIGNUM **)&n, NULL, NULL);
#endif
// copy public exponent into vector<byte>
vector<char> key(BN_num_bytes(n));
BN_bn2bin(n, (unsigned char *)&key[0]);
return key;
}
vector<char> Rsa::RsaImpl::decrypt(vector<char> data) {
const lock_guard<mutex> lock(rsa_mutex);
// allocate buffer
vector<char> text(RSA_size(rsa.get()));
// decrypt
ssize_t size = RSA_private_decrypt(
data.size(), (const unsigned char *)&data[0], (unsigned char *)&text[0],
rsa.get(), RSA_PKCS1_OAEP_PADDING);
// resize buffer to correct size
text.resize(size);
return text;
}
// Rsa forward
Rsa::Rsa() : _pimpl(new RsaImpl) {}
Rsa::~Rsa() {}
void Rsa::generateKeyPair() { _pimpl->generateKeyPair(); }
vector<char> Rsa::getPublicKey() { return _pimpl->getPublicKey(); }
vector<char> Rsa::decrypt(vector<char> data) { return _pimpl->decrypt(data); }
}
<file_sep>/include/vamk_aes.h
#ifndef VAMK_AES
#define VAMK_AES
#include <memory>
#include <vector>
namespace vamk {
class Aes {
public:
Aes();
Aes(const Aes &) = delete;
Aes operator=(const Aes &) = delete;
~Aes();
std::vector<char> decrypt(std::vector<char> data, std::vector<char> iv);
std::vector<char> encrypt(std::vector<char> data, std::vector<char> iv);
void setKey(std::vector<char> key);
private:
// pImpl technique
struct AesImpl;
std::unique_ptr<AesImpl> _pimpl;
};
}
#endif<file_sep>/src/vamk_socket.cpp
#include <unistd.h>
#include "vamk_socket.h"
namespace vamk {
Socket::Socket(int socket) : _socket(socket) {}
void Socket::close() {
using ::close;
close(_socket);
}
}<file_sep>/include/vamk_sdp.h
#ifndef VAMK_SDP
#define VAMK_SDP
#include <memory>
namespace vamk {
struct SdpServiceInfo {
const char *name;
const char *desc;
const char *prov;
};
class Sdp {
public:
Sdp();
Sdp(const Sdp &);
Sdp operator=(const Sdp &) = delete;
~Sdp();
void startAdvertise(void *uuid, char channel, SdpServiceInfo *info);
void endAdvertise();
private:
// pImpl technique
struct SdpImpl;
std::unique_ptr<SdpImpl> _pimpl;
};
}
#endif<file_sep>/src/vamk_random.cpp
#include <fcntl.h>
#include <openssl/rand.h>
#include <unistd.h>
#include "vamk_random.h"
namespace vamk {
void seedRandom() {
char buf[10];
int fd = open("/dev/random", O_RDONLY);
int n = read(fd, buf, sizeof buf);
close(fd);
RAND_add(buf, sizeof buf, n);
}
std::vector<char> getRandom(int size) {
std::vector<char> result(size);
RAND_bytes((unsigned char *)&result[0], size);
return result;
}
}
<file_sep>/src/vamk_sdp.cpp
#include <bluetooth/bluetooth.h>
#include <bluetooth/sdp.h>
#include <bluetooth/sdp_lib.h>
#include "vamk_sdp.h"
namespace vamk {
struct Sdp::SdpImpl {
sdp_session_t *session = nullptr;
};
Sdp::Sdp() : _pimpl(new SdpImpl) {}
Sdp::Sdp(const Sdp &) {}
Sdp::~Sdp() {}
void Sdp::startAdvertise(void *uuid, char channel_number,
SdpServiceInfo *info) {
uint8_t rfcomm_channel = channel_number;
uuid_t root_uuid, l2cap_uuid, rfcomm_uuid, svc_uuid;
sdp_list_t *l2cap_list = 0, *rfcomm_list = 0, *root_list = 0, *proto_list = 0,
*access_proto_list = 0;
sdp_data_t *channel = 0, *psm = 0;
sdp_record_t *record = sdp_record_alloc();
// set the general service ID
sdp_uuid128_create(&svc_uuid, uuid);
sdp_set_service_id(record, svc_uuid);
// make the service record publicly browsable
sdp_uuid16_create(&root_uuid, PUBLIC_BROWSE_GROUP);
root_list = sdp_list_append(0, &root_uuid);
sdp_set_browse_groups(record, root_list);
// set l2cap information
sdp_uuid16_create(&l2cap_uuid, L2CAP_UUID);
l2cap_list = sdp_list_append(0, &l2cap_uuid);
proto_list = sdp_list_append(0, l2cap_list);
// set rfcomm information
sdp_uuid16_create(&rfcomm_uuid, RFCOMM_UUID);
channel = sdp_data_alloc(SDP_UINT8, &rfcomm_channel);
rfcomm_list = sdp_list_append(0, &rfcomm_uuid);
sdp_list_append(rfcomm_list, channel);
sdp_list_append(proto_list, rfcomm_list);
// attach protocol information to service record
access_proto_list = sdp_list_append(0, proto_list);
sdp_set_access_protos(record, access_proto_list);
// set the name, provider, and description
sdp_set_info_attr(record, info->name, info->prov, info->desc);
int err = 0;
// connect to the local Sdp server, register the service record, and
// disconnect
bdaddr_t any = {0, 0, 0, 0, 0, 0};
bdaddr_t local = {0, 0, 0, 0xff, 0xff, 0xff};
_pimpl->session = sdp_connect(&any, &local, SDP_RETRY_IF_BUSY);
err = sdp_record_register(_pimpl->session, record, 0);
// cleanup
sdp_data_free(channel);
sdp_list_free(l2cap_list, 0);
sdp_list_free(rfcomm_list, 0);
sdp_list_free(root_list, 0);
sdp_list_free(access_proto_list, 0);
}
void Sdp::endAdvertise() {
if (_pimpl->session)
sdp_close(_pimpl->session);
_pimpl->session = nullptr;
}
}
<file_sep>/include/vamk_socket.h
#ifndef VAMK_SOCKET
#define VAMK_SOCKET
namespace vamk {
class Socket {
public:
void close();
protected:
Socket(int socket);
int _socket;
};
}
#endif<file_sep>/src/vamk_rfcomm.cpp
extern "C" {
#include <bluetooth/bluetooth.h>
#include <bluetooth/rfcomm.h>
}
#include <iostream>
#include <sys/socket.h>
#include <unistd.h>
#include "vamk_socket.h"
#include "vamk_rfcomm.h"
#define SZ_SIZE 2
using std::cout;
using std::endl;
namespace vamk {
// server socket
RfcommServerSocket::RfcommServerSocket()
: Socket(socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM)) {}
void RfcommServerSocket::listen(int channel) {
// server address struct
struct sockaddr_rc addr;
// bind socket to local bluetooth adapter
bdaddr_t any = {0, 0, 0, 0, 0, 0};
addr.rc_family = AF_BLUETOOTH;
addr.rc_bdaddr = any;
addr.rc_channel = (uint8_t)channel;
bind(_socket, (struct sockaddr *)&addr, sizeof(addr));
// put socket into listening mode
using ::listen;
listen(_socket, 1);
}
// accept one connection
std::unique_ptr<RfcommClientSocket> RfcommServerSocket::accept() {
// server address struct
struct sockaddr_rc addr;
socklen_t opt = sizeof(addr);
// accept one client
using ::accept;
int client = accept(_socket, (struct sockaddr *)&addr, &opt);
return std::unique_ptr<RfcommClientSocket>(new RfcommClientSocket(client));
}
// client socket
RfcommClientSocket::RfcommClientSocket(int socket) : Socket(socket) {}
int RfcommClientSocket::read(std::vector<char> &buffer) {
using ::read;
unsigned char sz_buf[SZ_SIZE];
ssize_t expt_sz; // expected size
ssize_t recv_sz; // received size
// read package size
recv_sz = read(_socket, sz_buf, SZ_SIZE);
if (recv_sz != SZ_SIZE)
return -1;
expt_sz = sz_buf[0] * 256 + sz_buf[1];
// read data into buffer
buffer.resize(expt_sz);
recv_sz = read(_socket, &buffer[0], expt_sz);
if (recv_sz != expt_sz)
return -1;
return expt_sz;
}
int RfcommClientSocket::write(const std::vector<char> &buffer) {
using ::write;
// write package size
size_t size = buffer.size();
unsigned char sz_buf[SZ_SIZE];
sz_buf[0] = (size / 256) % 256;
sz_buf[1] = size % 256;
// write to socket
write(this->_socket, sz_buf, 2);
return write(this->_socket, &buffer[0], size);
}
}
<file_sep>/include/espp_bt_server.h
#ifndef ESPP_BT_SERVER
#define ESPP_BT_SERVER
#include <memory>
#define CHANNEL 10
namespace vamk {
class RfcommServerSocket;
class Sdp;
}
namespace espp {
class BtClient;
class BtServer {
public:
BtServer();
BtServer(const BtServer &) = delete;
BtServer operator=(const BtServer &) = delete;
~BtServer();
void start();
void stop();
std::unique_ptr<BtClient> accept();
private:
void _init();
void _deinit();
std::unique_ptr<vamk::Sdp> _sdp;
std::shared_ptr<vamk::Rsa> _rsa;
std::unique_ptr<vamk::RfcommServerSocket> _server_socket;
};
}
#endif<file_sep>/src/vamk_aes.cpp
#include <openssl/evp.h>
#include <stdio.h>
#include "vamk_aes.h"
using std::unique_ptr;
using std::vector;
using EVP_ptr = unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>;
namespace vamk {
struct Aes::AesImpl {
AesImpl();
vector<char> decrypt(vector<char> data, vector<char> iv);
vector<char> encrypt(vector<char> data, vector<char> iv);
vector<char> key;
};
Aes::AesImpl::AesImpl() {}
vector<char> Aes::AesImpl::encrypt(vector<char> data, vector<char> iv) {
auto evp = EVP_ptr(EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
int len, err;
int ciphertext_len;
auto result = vector<char>(data.size() + 16);
err = EVP_EncryptInit_ex(evp.get(), EVP_aes_128_cbc(), NULL,
(const unsigned char *)&key[0],
(const unsigned char *)&iv[0]);
err = EVP_EncryptUpdate(evp.get(), (unsigned char *)&result[0], &len,
(const unsigned char *)&data[0], data.size());
ciphertext_len = len;
err = EVP_EncryptFinal_ex(evp.get(), (unsigned char *)&result[0] + len, &len);
ciphertext_len += len;
result.resize(ciphertext_len);
return result;
}
vector<char> Aes::AesImpl::decrypt(vector<char> data, vector<char> iv) {
auto evp = EVP_ptr(EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
int len, err;
int ciphertext_len;
auto result = vector<char>(data.size());
err = EVP_DecryptInit_ex(evp.get(), EVP_aes_128_cbc(), NULL,
(const unsigned char *)&key[0],
(const unsigned char *)&iv[0]);
err = EVP_DecryptUpdate(evp.get(), (unsigned char *)&result[0], &len,
(const unsigned char *)&data[0], data.size());
ciphertext_len = len;
err = EVP_DecryptFinal_ex(evp.get(), (unsigned char *)&result[0] + len, &len);
ciphertext_len += len;
result.resize(ciphertext_len);
return result;
}
// Aes forward
Aes::Aes() : _pimpl(new AesImpl) {}
Aes::~Aes() {}
vector<char> Aes::decrypt(vector<char> data, vector<char> iv) {
return _pimpl->decrypt(data, iv);
}
vector<char> Aes::encrypt(vector<char> data, vector<char> iv) {
return _pimpl->encrypt(data, iv);
}
void Aes::setKey(vector<char> key) { _pimpl->key = key; }
}
|
82eb908b49c92fde2cff85b68c0a9b3844453471
|
[
"Makefile",
"C++"
] | 18 |
C++
|
VAMK-embedded-project-2019A/Bluetooth-Server
|
874bdf50cff8a405839193679b3e64d0803b9b8f
|
071d223a968937cf31b0641502795bba989c65a9
|
refs/heads/master
|
<file_sep>require "minitest/autorun"
require_relative "bowling_class.rb"
class BowlingTest < Minitest::Test
def test_spo
scores = [["8", "2"], ["3", "0"], ["10"], ["10"], ["0", "0"], ["9", "1"], ["5", "5"], ["10"], ["10"], ["10", "10", "10"]]
test_final_score = 171
sl = scores.length
i = 0
final_total = 0
while i <= sl - 1
if scores[i].length == 2 && scores[i][0].to_i + scores[i][1].to_i == 10
final_total = 10 + scores[i+1][0].to_i + final_total
elsif scores[i].length == 3
final_total = scores[i][0].to_i + scores[i][1].to_i + scores[i][2].to_i + final_total
elsif scores[i][0].to_i == 10 && scores[i+1].length == 2
final_total = 10 + scores[i+1][0].to_i + scores[i+1][1].to_i + final_total
elsif scores[i][0].to_i == 10 && scores[i+1].length == 1 && scores[i+2].length != 1
final_total = 20 + scores[i+2][0].to_i + final_total
elsif scores[i][0].to_i == 10 && scores[i+1][0].to_i == 10 && scores[i+2] != nil
final_total = 30 + final_total
elsif scores[i][0].to_i == 10 && scores[i+1][0].to_i == 10 && scores[i+2] == nil
final_total = 10 + scores[i+1][0].to_i + scores[i+1][1].to_i + final_total
else
final_total = scores[i][0].to_i + scores[i][1].to_i + final_total
end
i += 1
end
assert_equal(final_total), test_final_score
end
<file_sep>class Bowling
attr_accessor :name, :scores
## name = array
## scores = array
def initialize(name, scores)
@name = name
@scores = scores
end
## Method Strike sPare Open
## name = array
def spo(name, scores)
name = name
sl = scores.length
i = 0
final_total = 0
## Looping through the score array adding up for the final total
while i <= sl - 1
## If the frame is a spare
if scores[i].length == 2 && scores[i][0].to_i + scores[i][1].to_i == 10
final_total = 10 + scores[i+1][0].to_i + final_total
## if the frame is the 10th frame
elsif scores[i].length == 3
final_total = scores[i][0].to_i + scores[i][1].to_i + scores[i][2].to_i + final_total
## if the frame is a strike and the next frame is either a spare or open
elsif scores[i][0].to_i == 10 && scores[i+1].length == 2
final_total = 10 + scores[i+1][0].to_i + scores[i+1][1].to_i + final_total
## if the next 2 frames are strikes and the next throw is not
elsif scores[i][0].to_i == 10 && scores[i+1].length == 1 && scores[i+2].length != 1
final_total = 20 + scores[i+2][0].to_i + final_total
## if the next 3 frames are strikes
elsif scores[i][0].to_i == 10 && scores[i+1][0].to_i == 10 && scores[i+2] != nil
final_total = 10 + scores[i+1][0].to_i + scores[i+2][0].to_i + final_total
## for the 9th frame if you strike and have a spare or open on the 10th frame
elsif scores[i][0].to_i == 10 && scores[i+1][0].to_i == 10 && scores[i+2] == nil
final_total = 10 + scores[i+1][0].to_i + scores[i+1][1].to_i + final_total
else
## for a open frame
final_total = scores[i][0].to_i + scores[i][1].to_i + final_total
end
i += 1
end
## final name and total score for the bowling game
final = name, final_total
end
end<file_sep>
# root = TkRoot.new
# root.title = "Highest Score to Lowest on a lane"
#
# filepath = Tk.getOpenFile
game = []
f = File.open("/Users/lorelei/Code/kristin-challenge/lane info/lane19.txt", "r")
f.each_line do |line|
game.push(line)
end
bowl = Bowling.new
binding.pry
puts game
#
# button_click = Proc.new {
# filepath = Tk.getOpenFile
#
#
# }
#
# button = TkButton.new(root) do
# text "Select lane's .txt file"
# pack("side" => "left", "padx"=> "100", "pady"=> "100")
# end
#
# button.comman = button_click
#
# Tk.mainloop<file_sep>require "pry"
require "tk"
require_relative "models/bowling_class"
## TkRoot creates a dialogue box for the user to select the text file
root = TkRoot.new
root.title = "Highest Score to Lowest on a lane"
filepath = Tk.getOpenFile
## game is created to hold the text file information
game = Hash.new{|hsh,key| hsh[key] = [] }
## f opnes the file and reads it only. Pulling the alpha characters and the digitial character for the bowlers name and scores. Pushing them into the empty hash with the names being the key and the scores being the value.
f = File.open(filepath, "r")
f.each_line do |line|
names = line.scan(/[[:alpha:]]+/)
scores = line.scan(/[[:digit:]]+/)
## game = {["names"] => [["scores"]]}
game[names].push(scores)
end
## Here we get the size of the group from length of keys we have in the game hash
## We set up early for sorting the data with the hightolow array outside the loop
## Finally we have the player_round to keep track how many players we loop through
size = game.length
player_round = 0
hightolow = []
## Creating a while loop we used a class for keep track of the score and adding it up for the final score
## Then pushing it into hightolow array to sort when players score the highest to lowest
while player_round <= size - 1
## name = array
## scores = array
## final = array
## bowl = class object
name = game.keys[player_round]
scores = game[name]
bowl = Bowling.new(name, scores)
final = bowl.spo(name, scores)
hightolow.push(final)
player_round += 1
end
## Outputs the score into the terminal
puts hightolow.sort_by{|k, v| [-v, k]}
<file_sep># kristin-challenge
Bowling
---------------
Build a program that will accept a text file that contains all of the bowling throws for complete games that involves
multiple players. The program should process the input file, calculate the scores for each player, and output a summary
with the score of each player sorted by highest score.
Requirements
- Input will be space delimited.
- Each line consists of a frame.
- The order of the lines is the order of the frames.
Input assumptions
- Player names will always be a string of only alpha characters
- All input is space delimited and valid
- Scores are always numeric.
Example input:
John 8 2
Lucy 0 0
John 3 0
Lucy 10
John 10
Lucy 0 10
John 10
Lucy 4 6
John 0 0
Lucy 10
John 9 1
Lucy 10
John 5 5
Lucy 5 5
John 10
Lucy 10
John 10
Lucy 10
John 10 10 10
Lucy 10 2 8
Example output:
Lucy 191
John 171
|
01fbbe00718b02ddbeb16c4b30ba5dc5a3806dd9
|
[
"Markdown",
"Ruby"
] | 5 |
Ruby
|
Zerasolar/bowling_challenge
|
18a79cb1a63268570683f9ac7c5092729d761e5f
|
1dd3752ef8b67b9d2968275da9f0e6c09b9a86c2
|
refs/heads/master
|
<file_sep>import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { DiscountService } from './discount.service';
import { IDiscount } from './IDiscount';
@Component({
selector: 'app-discount',
templateUrl: './discount.component.html',
styleUrls: ['./discount.component.css']
})
export class DiscountComponent implements OnInit {
private discounts = [];
private _selectedDiscount: IDiscount;
@Output() discontRate = new EventEmitter<IDiscount>();
constructor(private _discountService : DiscountService) { }
ngOnInit() {
this._discountService.getDiscounts().subscribe(data => this.discounts=data);
}
onChange(discount:any, isChecked: boolean) { // Use appropriate model type instead of any
this._selectedDiscount = discount;
// console.log(this._selectedDiscount);
this.discontRate.emit(this._selectedDiscount);
}
}
<file_sep>import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ProductService } from '../product.service';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { IProduct } from './IProduct';
@Component({
selector: 'app-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
customerId = "";
private products = [];
// orderForm: FormGroup;;
@Output() messageEvent = new EventEmitter<IProduct[]>();
constructor(private route: ActivatedRoute, private _productService : ProductService) {
this.route.params.subscribe(res => this.customerId = res.userId);
// console.log('i am inside product ', this.customerId);
// this.orderForm = new FormGroup({
// productId: new FormControl('', {
// validators: Validators.required,
// updateOn: 'change'
// })
// });
}
ngOnInit() {
this._productService.getProducts().subscribe(data => this.products = data);
this.products.forEach(element => {
console.log(element);
});
}
selectedProducts: any = { "products": [] };
onChange(product:any, isChecked: boolean) { // Use appropriate model type instead of any
if(isChecked) {
this.selectedProducts.products.push(product);
}else {
let index = this.selectedProducts.products.indexOf(product);
this.selectedProducts.products.splice(index,1);
}
// console.log(this.selectedProducts.products);
this.messageEvent.emit(this.selectedProducts.products);
// console.log('emit a event');
}
}
<file_sep>import { FormControl } from '@angular/forms';
import { Validators } from '@angular/forms';
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup } from '@angular/forms';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
customerid = '';
// customerForm: FormGroup;
customer = new Customer();
constructor(private router: Router) { }
ngOnInit() {
}
showProduct() {
// console.log('i am inside showProduct',this.customer.id);
if(this.customer.id != undefined){
this.router.navigate(['order', this.customer.id]);
}
}
}
export class Customer{
id: String;
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { IDiscount } from '../discount/IDiscount';
@Component({
selector: 'app-order',
templateUrl: './order.component.html',
styleUrls: ['./order.component.css']
})
export class OrderComponent implements OnInit {
customerId = "";
private selectedProducts = [];
private selectedDiscount: IDiscount;
private totalAmount: number;
private totalDiscount: number;
private subTotal: number;
constructor(private route: ActivatedRoute) {
this.route.params.subscribe(res => this.customerId = res.userId);
}
ngOnInit() {
}
receiveSelectedProducts($event) {
// console.log('i am inside receiveSelectedProducts()');
this.selectedProducts = $event;
// this.selectedProducts.forEach(i => console.log(i));reduce(((a,b) > a+b,0));
this.totalAmount = this.selectedProducts.map(((product) => product.price)).reduce((a,b)=>a+b,0);
this.calculateSubTotal();
}
receiveSelectedDiscount($event) {
this.selectedDiscount = $event;
this.calculateSubTotal();
}
calculateSubTotal(){
if(this.selectedDiscount != undefined){
if(this.selectedDiscount.type === "flat"){
this.totalDiscount = this.selectedDiscount.discount;
}else{
this.totalDiscount = (this.totalAmount * this.selectedDiscount.discount) / 100;
}
this.subTotal = this.totalAmount - this.totalDiscount;
}else{
this.totalDiscount = 0;
}
}
}
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule, Component } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { RouterModule, Routes } from '@angular/router';
import { ProductComponent } from './product/product.component';
import { FormsModule } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';
import { OrderComponent } from './order/order.component';
import { HttpClientModule } from '@angular/common/http';
import { ProductService } from './product.service';
import { DiscountService } from './discount/discount.service';
import { DiscountComponent } from './discount/discount.component';
const routes: Routes = [
{
path: 'product',
component: ProductComponent,
data: { title: 'Products List' }
},
{
path: 'order/:userId',
component: OrderComponent,
data: { title: 'Products List' }
},
{
path: '',
pathMatch: 'full',
component: HomeComponent
}
];
@NgModule({
declarations: [
AppComponent,
HomeComponent,
ProductComponent,
OrderComponent,
DiscountComponent
],
imports: [
BrowserModule,
AppRoutingModule,
RouterModule.forRoot(routes),
FormsModule,
ReactiveFormsModule,
HttpClientModule
],
providers: [ProductService, DiscountService],
bootstrap: [AppComponent]
})
export class AppModule { }
|
89d103aedc897aa484aa94e837df711a730eb230
|
[
"TypeScript"
] | 5 |
TypeScript
|
chiragdesai2005/ngfruitshop
|
0167eb6b89646f8202b740ed17a7d0d524087081
|
42c9f74889243a30cbd12b78b67256a958494709
|
refs/heads/master
|
<repo_name>qingfengforum/WindowsCmdTools<file_sep>/mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QProcess>
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::init_copyFW_components()
{
}
void MainWindow::on_pushBtn_Copy_clicked()
{
QProcess p(0);
p.start("C:/Users/qingfeng/Desktop/copy_bin.bat");
p.waitForStarted();
p.waitForFinished();
QString strTemp=QString::fromLocal8Bit(p.readAllStandardOutput());
QMessageBox testMassage;
testMassage.setText(strTemp);
testMassage.exec();
}
|
795a61c92cbe63269fcad0555e2752dc2a75e838
|
[
"C++"
] | 1 |
C++
|
qingfengforum/WindowsCmdTools
|
62dcbc33f467f9b331b3cff41536537f1f4b6446
|
57b28cde6bcc5671e8f89932d57a5e4b57459ac3
|
refs/heads/master
|
<repo_name>Naehyung/ReactJS-Portfolio<file_sep>/src/pages/Portfolio.js
import './Portfolio.css';
import Menu from './Menu';
import Project from './components/Project'
import Madtongsan from './components/images/Madtongsan.png'
import LOGINImage from './components/images/LOGIN.png'
import TextyAnim from 'rc-texty';
import ABOUTImage from './components/images/ABOUT.png'
import MENUImage from './components/images/MENU.png'
import CONTACTImage from './components/images/CONTACT.png'
import MainPage from './components/images/MainPage.png'
import MainPage2 from './components/images/MainPage2.png'
import Chatting from './components/images/Chatting.png'
import Footer from './components/Footer';
import HARMS1 from './components/images/HARMS1.png'
import HARMS2 from './components/images/HARMS2.png'
import HARMS3 from './components/images/HARMS3.png'
import Portfolio1 from './components/images/Portfolio1.png'
import Portfolio2 from './components/images/Portfolio2.png'
import Portfolio3 from './components/images/Portfolio3.png'
import Portfolio4 from './components/images/Portfolio4.png'
function Portfolio() {
return(
<div className = "portfolio">
<Menu/>
<div className = "portfolioText">
<TextyAnim type="swing" onEnd={(type) => {console.log(type);}}>
PORTFOLIO
</TextyAnim>
</div>
<div className = "project">
<Project
image={Madtongsan}
slideImage1={ABOUTImage}
slideImage2={MENUImage}
slideImage3={CONTACTImage}
MainText="MADTONGSAN WEBSITE"
Explanation="Simple Website using HTML, CSS, JavaScript"
githubPage="https://github.com/Naehyung/Madtongsan-Website1"/>
<Project image={LOGINImage}
slideImage1={MainPage}
slideImage2={MainPage2}
slideImage3={Chatting}
MainText="CHATTING APPLICATION"
Explanation="Simple Chatting Application using Java, AndroidStudio, SpringBoot, WebSocket, Restful API and STOMP"
githubPage="https://github.com/Naehyung/Simple-Chatting-Application"/>
<Project image={HARMS1}
slideImage1={HARMS1}
slideImage2={HARMS2}
slideImage3={HARMS3}
MainText="GUI FOR HARMS"
Explanation="Graphical User Interface for Hierarchical Attack Representation Model using Java, Python and SocketIO"
githubPage="https://github.com/Naehyung/HARMs"/>
<Project image={Portfolio1}
slideImage1={Portfolio2}
slideImage2={Portfolio3}
slideImage3={Portfolio4}
MainText="Portfolio Website"
Explanation="Portfolio Website using HTML, CSS, JavaScript, ReactJS"
githubPage="https://github.com/Naehyung/ReactJS-Portfolio"/>
</div>
<Footer/>
</div>
)
}
export default Portfolio;
<file_sep>/portfolio/src/pages/Contact.js
import Reacts from 'react';
import Menu from './Menu';
import TextyAnim from 'rc-texty';
import './Contact.css';
import { Button, Form } from 'react-bootstrap';
import Footer from './components/Footer';
function Contact() {
return(
<div className="contact">
<Menu/>
<div className = "contactText">
<TextyAnim type="swing" onEnd={(type) => {console.log(type);}}>
CONTACT
</TextyAnim>
</div>
<div className = "contactBody">
<div className = "contactBodyContent">
<Form>
<Form.Group controlId="formBasicEmail">
<Form.Label>Name</Form.Label>
<Form.Control type="email" placeholder="Enter Your Name" />
</Form.Group>
<Form.Group controlId="formBasicEmail">
<Form.Label>Email address</Form.Label>
<Form.Control type="email" placeholder="Enter email" />
<Form.Text className="text-muted">
We'll never share your email with anyone else.
</Form.Text>
</Form.Group>
<Form.Group controlId="exampleForm.ControlTextarea1">
<Form.Label>Your Message</Form.Label>
<Form.Control as="textarea" rows={7} />
</Form.Group>
<Button variant="primary" type="submit">
Submit
</Button>
</Form>
</div>
</div>
<Footer/>
</div>
)
}
export default Contact;
<file_sep>/src/pages/components/FlipImage.js
import './FlipImage.css'
import { useSpring, animated} from 'react-spring';
import ProgressBar from './ProgressBar';
function FlipImage(props) {
const props3 = useSpring({
from: {transform: "perspective(500px) rotateY(180deg)",opacity:0},
to: async (next, cancel) => {
await next({
transform: "perspective(1000px) rotateY(0)",opacity:1})},
delay: props.delay,
config: { tension: 20,friction: 5 }
})
return (
<div classNmae ="flipImageBody">
<div className = "flipImageMain">
<animated.div className = "flipImage" style={props3}>
<img src={props.image} alt="flipImage"/>
</animated.div>
<ProgressBar delayBar={props.delayBar}/>
</div>
<div className = "flipImageText">
<p>{props.text}</p>
</div>
</div>
)
}
export default FlipImage;
<file_sep>/src/pages/Main.js
import './Main.css';
import mainVideo from './components/video/main.mp4'
import { Link } from "react-router-dom";
import Typical from 'react-typical'
import { useSpring, animated } from "react-spring";
function Main() {
const [{ x, color}, set] = useSpring(() => ({ x:100, color:"#fff"}));
return (
<div className = "main">
<video autoPlay loop muted id="video">
<source src={mainVideo} type="video/mp4"/>
</video>
<div className = "text">
<Typical
steps={["Hello, I'm <NAME>.", 2000, "I'm a Software Engineer.", 2000]}
loop={Infinity}
wrapper="h1"/>
</div>
<div className = "button">
<button
onMouseEnter={() => set({ x: 0, color: "#000" })}
onMouseLeave={() => set({ x: 100, color: "#fff" })}>
<Link to = "/About" style={{ textDecoration: 'none' }}>
<animated.span style={{ color }}>
CHECK OUT MY WORK
</animated.span>
</Link>
<animated.div
style={{ transform: x.interpolate((v) => `translateX(${-v}%`) }}
className="glance"
/>
</button>
</div>
</div>
);
}
export default Main;
<file_sep>/src/pages/components/BarChart.js
import './BarChart.css'
import {useSpring, animated} from 'react-spring'
function BarChart(props) {
const props2 = useSpring({
from: {width: `${props.width}%`, transform: "translateX(-100%)",background:"red"},
to: async (next, cancel) => {
await next({transform:"translateX(0%)",background:"black"})
}, delay: props.delay, config: { tension: 60 }
})
return (
<div>
<div className = "bar">
<div className = "language">
{props.name}
</div>
<div className = "percentage">
<animated.div className="glance2" style={props2}/>
</div>
<div className = "percentageText">
{props.percentage}
</div>
</div>
</div>
)
}
export default BarChart;
<file_sep>/portfolio/src/pages/components/Project.js
import './Project.css';
import React, { useState } from 'react';
import { useSpring, animated } from "react-spring";
import NewWindow from 'react-new-window'
import ProjectModal from './ProjectModal'
import ABOUTImage from './images/ABOUT.png'
import MENUImage from './images/MENU.png'
import CONTACTImage from './images/CONTACT.png'
function Project(props) {
const [{yText, yButton, opacity, opacityText, color}, set] = useSpring(() => ({
yText: -200,
yButton: 300,
color: "white",
opacity: 1,
opacityText : 0,
config: { friction: 25 }}))
const [opacityTest, setOpacity] = useSpring(() => ({
opacity:0
}))
const [show, setShow] = useState(false);
function handleShow() {
setShow(true);
}
function handleClose() {
setShow(false);
}
const slideImages = [
ABOUTImage,
MENUImage,
CONTACTImage
];
return (
<div
className="projectImage"
onMouseMove={() => set({ yText: -100, yButton: 150,opacity: 0, opacityText: 1})}
onMouseLeave={() => set({ yText: -200, yButton: 300,opacity: 1, opacityText: 0})}
>
<animated.img style={{opacity}} src={props.image} />
<animated.div
style={Object.assign({},
{opacity: opacityText.interpolate((o) => `${o}`)},
{transform: yText.interpolate((v) => `translateY(${v}%`)})}
className="projectText">
{props.MainText}
</animated.div>
<animated.button
onMouseDown={handleShow}
style={Object.assign({},
{opacity: opacityText.interpolate((o) => `${o}`)},
{transform: yButton.interpolate((v) => `translateY(${v}%`)})}
className="projectButton">
LEARN MORE
</animated.button>
<ProjectModal
show={show}
handleClose={handleClose}
slideImage1={props.slideImage1}
slideImage2={props.slideImage2}
slideImage3={props.slideImage3}
MainText={props.MainText}
Explaination={props.Explanation}
githubPage = {props.githubPage}/>
</div>
)
}
export default Project;
<file_sep>/src/pages/components/Footer.js
import './Footer.css'
import SocialIconComp from './SocialIconComp'
function Footer() {
return (
<div className ="footer">
<div className ="footerBody">
<SocialIconComp url = "https://www.linkedin.com/in/naehyung-kim-15a1921b4/"/>
<SocialIconComp url = "https://www.facebook.com/skyfishknh"/>
<SocialIconComp url = "https://github.com/Naehyung"/>
<SocialIconComp url = "https://www.instagram.com/naehyung91/"/>
</div>
<div className ="footerText">
<p><NAME> © 2021</p>
</div>
</div>
)
}
export default Footer;
<file_sep>/portfolio/src/pages/Menu.js
import React, { useState } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Navbar, Nav, NavDropdown, Form, FormControl, Button } from 'react-bootstrap';
import './Menu.css';
function Menu() {
return (
<div>
<Navbar collapseOnSelect expand="lg" bg="dark" variant="dark">
<Navbar.Brand href="/">NAEHYUNG KIM</Navbar.Brand>
<Navbar.Toggle aria-controls="responsive-navbar-nav" />
<Navbar.Collapse id="responsive-navbar-nav">
<Nav className="mr-auto">
<Nav.Link href="/About">About</Nav.Link>
<Nav.Link href="/Portfolio">Portfolio</Nav.Link>
<Nav.Link href="/Contact">Contact</Nav.Link>
</Nav>
</Navbar.Collapse>
</Navbar>
</div>
);
}
export default Menu;
<file_sep>/README.md
## Portfolio
- Live Demo https://reactjs-portfolio-zeta.vercel.app/
## Description
- This is a ReactJS based personal resume website template by <NAME>
<file_sep>/portfolio/src/pages/About.js
import Reacts from 'react';
import './About.css';
import Menu from './Menu';
import TextyAnim from 'rc-texty';
import myImage from './components/images/about1.jpg'
import BarChart from './components/BarChart';
import FlipImage from './components/FlipImage'
import Creative from './components/images/creative.png';
import Dynamic from './components/images/dynamic.png';
import Responsive from './components/images/responsive.png'
import Fast from './components/images/fast.png'
import Footer from './components/Footer';
import { useSpring, animated } from "react-spring";
const text = 'ABOUT ME';
function About() {
const props3 = useSpring({
from: {transform: "perspective(500px) rotateY(180deg)",opacity:0},
to: async (next, cancel) => {
await next({
transform: "perspective(1000px) rotateY(0)",opacity:1})},
config: { tension: 40,friction: 10 }
})
return (
<div className ="about">
<Menu/>
<div className = "aboutText">
<TextyAnim type="swing" onEnd={(type) => {console.log(type);}}>
{text}
</TextyAnim>
</div>
<div className ="aboutHeader">
<div className ="headerItem">
<FlipImage delay="100" delayBar="100" image={Creative} text="Creative"/>
</div>
<div className ="headerItem">
<FlipImage delay="200" delayBar="200" image={Dynamic} text="Dynamic"/>
</div>
<div className ="headerItem">
<FlipImage delay="300" delayBar="300" image={Responsive} text="Responsive"/>
</div>
<div className ="headerItem">
<FlipImage delay="400" delayBar="400" image={Fast} text="Fast"/>
</div>
</div>
<div className = "aboutBody">
<div className = "bodyLeft">
<div className = "bodyLeftText">
<TextyAnim type="swing" onEnd={(type) => {console.log(type);}}>
WHO AM I?
</TextyAnim>
</div>
<animated.div className = "bodyLeftImage" style={props3}>
<img src = {myImage}/>
</animated.div>
<div className = "bodyLeftContent">
<p>I graudated from the University of Queensland<br/>with bachelor degree in Software Enginnering.</p>
</div>
</div>
<div className = "bodyRight">
<div className = "bodyRightText">
<TextyAnim type="swing" onEnd={(type) => {console.log(type);}}>
SKILLS
</TextyAnim>
</div>
<div className = "barChart">
<BarChart width = "100" delay ="100" name = "HTML" percentage = "90%"/>
<BarChart width = "90" delay = "120" name = "CSS" percentage = "80%"/>
<BarChart width = "80" delay = "140" name = "JavaScript" percentage = "70%"/>
<BarChart width = "100" delay = "160" name = "Java" percentage = "90%"/>
<BarChart width = "60" delay = "180" name = "SpringBoot" percentage = "50%"/>
<BarChart width = "80" delay = "200" name = "Android" percentage = "70%"/>
<BarChart width = "60" delay = "220" name = "PhotoShop" percentage = "50%"/>
</div>
</div>
</div>
<Footer/>
</div>
);
}
export default About;
<file_sep>/portfolio/src/pages/components/SocialIconComp.js
import './SocialIconComp.css';
import { SocialIcon } from 'react-social-icons';
import React, { useState } from 'react';
import { useSpring, animated } from "react-spring";
function SocialIconComp (props) {
const[color,setColor] = useState("rgba(52,58,64,1)");
return (
<div
className ="socialIconComp"
style={{backgroundColor:color}}
onMouseMove={()=>setColor("rgba(246, 36, 89, 1)")}
onMouseLeave={()=>setColor("rgba(52,58,64,1)")}>
<SocialIcon
url={props.url}
bgColor="transparent"
fgColor ="white"/>
</div>
)
}
export default SocialIconComp;
<file_sep>/src/pages/components/ProjectModal.js
import React from 'react';
import './ProjectModal.css';
import { Slide } from 'react-slideshow-image';
import 'react-slideshow-image/dist/styles.css'
import { Button, Modal } from 'react-bootstrap';
function ProjectModal(props) {
const properties = {
duration: 3000,
transitionDuration: 500,
};
return (
<>
<Modal
show={props.show}
onHide={props.handleClose}
dialogClassName="modal-90w"
centered>
<div className="slide-container">
<Slide {...properties}>
<div className="each-slide">
<div style={{'backgroundImage': `url(${props.slideImage1})`}}>
</div>
</div>
<div className="each-slide">
<div style={{'backgroundImage': `url(${props.slideImage2})`}}>
</div>
</div>
<div className="each-slide">
<div style={{'backgroundImage': `url(${props.slideImage3})`}}>
</div>
</div>
</Slide>
</div>
<Modal.Header>
<Modal.Title>{props.MainText}</Modal.Title>
</Modal.Header>
<Modal.Body>{props.Explaination}</Modal.Body>
<Modal.Footer>
<Button variant="outline-info" onClick={()=>window.open(props.githubPage, "_blank")}>
Check GitHub Page
</Button>
<Button variant="outline-secondary" onClick={props.handleClose}>
Close
</Button>
</Modal.Footer>
</Modal>
</>
)
}
export default ProjectModal;
|
d31b59b0e88d845ef577d5996f624fb5b14e6187
|
[
"JavaScript",
"Markdown"
] | 12 |
JavaScript
|
Naehyung/ReactJS-Portfolio
|
fc55394c05a4ad538304f70b4a164ac8f36c1e3f
|
0140097ca39dda069500b82a0e6492467a2e9664
|
refs/heads/master
|
<file_sep>{{if page.side:}}
{{right_sidebar_enabled=True}}
{{pass}}
{{extend 'layout.html'}}
<div id="content_main">
<div class='content_text'>
<h1>{{=page.title}}</h1>
<hr/>
{{=XML(page.body, sanitize=False)}}
</div>
{{block right_sidebar}}
<div id="content_main">
{{=XML(page.side, sanitize=False)}}
</div>
{{end}}
</div><file_sep># -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations
# -------------------------------------------------------------------------
# This is a sample controller
# - index is the default action of any application
# - user is required for authentication and authorization
# - download is for downloading files uploaded in the db (does streaming)
# -------------------------------------------------------------------------
def index():
""" Display the index page """
index = db(db.cms_page.page_index==0).select(db.cms_page.ALL).first().as_dict()
return locals()
def page():
"""" Show a page """
if not request.args(0):
redirect(URL('index'))
try:
page = db(db.cms_page.id == int(request.args(0))).select().first().as_dict()
except ValueError:
try:
page = db(db.cms_page.title=='%s' % request.args(0).title()).select().first().as_dict() or redirect(URL('default', 'index'))
except:
raise HTTP(404)
if page['members_only'] and not auth.user:
redirect(URL('index'))
elif page['members_only'] and not auth.has_membership('member', auth.user.id):
redirect(URL('index'))
else:
return locals()
def user():
"""
exposes:
http://..../[app]/default/user/login
http://..../[app]/default/user/logout
http://..../[app]/default/user/register
http://..../[app]/default/user/profile
http://..../[app]/default/user/retrieve_password
http://..../[app]/default/user/change_password
http://..../[app]/default/user/bulk_register
use @auth.requires_login()
@auth.requires_membership('group name')
@auth.requires_permission('read','table name',record_id)
to decorate functions that need access control
also notice there is http://..../[app]/appadmin/manage/auth to allow administrator to manage users
"""
return dict(form=auth())
@cache.action()
def download():
""" allow user to download files by name """
import contenttype as c
if not request.args:
raise HTTP(404)
elif 'cms_file.cms_file' in request.args[-1]:
return response.download(request, db)
else:
file_id = request.args[-1]
for row in db(db.cms_file.id>0).select():
# search for the original filename
if file_id in db.cms_file.cms_file.retrieve(row.cms_file):
try:
filename, file = db.cms_file.cms_file.retrieve(row.cms_file)
except IOError:
raise HTTP(404)
response.headers["Content-Type"] = c.contenttype(file_id)
response.headers["Content-Disposition"] = "attachment; filename=%s" % file_id
stream = response.stream(file, chunk_size=64*1024, request=request)
raise HTTP(200, stream, **response.headers)
def call():
"""
exposes services. for example:
http://..../[app]/default/call/jsonrpc
decorate with @services.jsonrpc the functions to expose
supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv
"""
return service()
def sitemap():
sitemap=TAG.urlset(_xmlns="http://www.sitemaps.org/schemas/sitemap/0.9") # & (db.cms_page.published==True)
sitemap.append(TAG.url(TAG.loc('http://%s' % request.env.http_host),TAG.priority(1.0)))
posts = db((db.cms_page.page_index >= 0) & (db.cms_page.main_menu == True) & (db.cms_page.published == True) & (db.cms_page.members_only == False)).select(db.cms_page.ALL, orderby=[db.cms_page.page_index])
for item in posts:
if item.published and item.page_index != 0:
sitemap.append(TAG.url(TAG.loc('http://%s/page/%s/%s' %(request.env.http_host, item.id, item.title))))
sitemap.append(TAG.url(TAG.loc('http://%s/sitemap.xml' % request.env.http_host)))
return '<?xml version="1.0" encoding="UTF-8"?>\n%s' %sitemap.xml()
<file_sep># -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations
# ----------------------------------------------------------------------------------------------------------------------
# Customize your APP title, subtitle and menus here
# ----------------------------------------------------------------------------------------------------------------------
response.logo = A(B('web', SPAN(2), 'py'), XML('™ '),
_class="navbar-brand", _href="http://www.web2py.com/",
_id="web2py-logo")
response.title = request.application.replace('_', ' ').title()
response.subtitle = ''
# ----------------------------------------------------------------------------------------------------------------------
# read more at http://dev.w3.org/html5/markup/meta.name.html
# ----------------------------------------------------------------------------------------------------------------------
response.meta.author = myconf.get('app.author')
response.meta.description = myconf.get('app.description')
response.meta.keywords = myconf.get('app.keywords')
response.meta.generator = myconf.get('app.generator')
# ----------------------------------------------------------------------------------------------------------------------
# your http://google.com/analytics id
# ----------------------------------------------------------------------------------------------------------------------
response.google_analytics_id = None
# ----------------------------------------------------------------------------------------------------------------------
# ADMIN MENU
# ----------------------------------------------------------------------------------------------------------------------
active_path = request.controller
response.admin_menu = [ (T('Site'), False, URL('default','index'), []),
#(T('Dash'), True if active_path == 'index' else False, URL('admin','index'), []),
(T('Pages'), True if active_path == 'cms_page' else False, URL('admin','index'), []),
(T('Files'), True if active_path == 'file' else False, URL('admin','file'), []),
]
response.admin_menu += [
(T('Users'), True if active_path == 'users' else False, URL('admin','list_users'), []),
(T('CSS'), True if active_path == 'css' else False, URL('admin','style_sheet'), []),
]
response.admin_menu += [
(T('Help'), True if active_path == 'help' else False, URL('admin','help'), []),]
# ----------------------------------------------------------------------------------------------------------------------
# MAIN MENU
# ----------------------------------------------------------------------------------------------------------------------
response.menu = [
(T('Home'), False, URL('default', 'index'), [])
]
# shortcuts
app = request.application
ctr = request.controller
cms_pages = None
if not auth.user:
cms_pages = db((db.cms_page.page_index >= 0) & (db.cms_page.main_menu == True) & (db.cms_page.published == True) & (db.cms_page.members_only == False)).select(db.cms_page.ALL, orderby=[db.cms_page.page_index])
elif auth.has_membership('user', auth.user.id):
cms_pages = db((db.cms_page.page_index >= 0) & (db.cms_page.main_menu == True) & (db.cms_page.published == True)).select(db.cms_page.ALL, orderby=[db.cms_page.page_index])
else:
cms_pages = db((db.cms_page.page_index >= 0) & (db.cms_page.main_menu == True) & (db.cms_page.published == True) & (db.cms_page.members_only == False)).select(db.cms_page.ALL, orderby=[db.cms_page.page_index])
for cms_page in cms_pages:
try:
if cms_page.title == 'Register' and auth.has_membership('user', auth.user.id):
continue
except AttributeError:
pass
if cms_page.page_index == 0:
response.title = cms_page.title
else:
if cms_page.published and not cms_page.parent_menu and not cms_page.url:
sub_items = []
for i in db(db.cms_page.parent_menu == cms_page.id).select(db.cms_page.id, db.cms_page.title, db.cms_page.parent_menu, db.cms_page.page_index, orderby=[db.cms_page.page_index]):
sub_items += (T(i.title), False, URL('default','page/%s/%s' % (i.id, i.title.lower())), [])
if sub_items:
response.menu+=[ (T(cms_page.title), False, URL('default','page/%s/%s' % (cms_page.id, cms_page.title.lower())), [sub_items])]
else:
response.menu+=[ (T(cms_page.title), False, URL('default','page/%s/%s' % (cms_page.id, cms_page.title.lower())))]
elif cms_page.url:
response.menu+=[ (T(cms_page.title), False, cms_page.url, []) ]
if "auth" in locals():
auth.wikimenu()
<file_sep>#
# CKEditor widget function
def advanced_editor(field, value):
return TEXTAREA(_id = str(field).replace('.','_'), _name=field.name, _class='text ckeditor', value=value, _cols=80, _rows=10)
#
# cms_page - cms_pages of the website
#
#db.define_table('cms_page',
# Field('main_menu', 'boolean'))
db.define_table('cms_page',
Field('title'),
Field('url', default=None, comment='Redirect to external page'),
Field('main_menu', 'boolean', default=True, comment='add to the main menu'),
Field('parent_menu', default=None),
Field('body', 'text', default=''),
Field('created_on', 'datetime', default=request.now),
Field('created_by', db.auth_user, default=auth.user_id),
Field('page_index', 'integer', comment='position page will appear on the main menu, blank if n/a' ),
Field('published', 'boolean', default=True, comment='make the page public'),
Field('members_only', 'boolean', default=False, comment='only members can view this page'),
format='%(title)s')
#,redefine=True)
db.cms_page.body.widget = advanced_editor
db.cms_page.created_by.readable = db.cms_page.created_by.writable = False
db.cms_page.created_on.readable = db.cms_page.created_on.writable = False
db.cms_page.main_menu.writable = True
db.cms_page.page_index.required = False
# Restrict the parent menu to only existing pages in the main menu - 2 tier menu system.
db.cms_page.parent_menu.requires = IS_EMPTY_OR(IS_IN_DB(
db((db.cms_page.main_menu == True)), db.cms_page.id, 'cms_page.title'))
# Create a default page index, total + 1 of pages in the main menu
db.cms_page.page_index.default = len(db((db.cms_page.id>0) & (db.cms_page.main_menu == True)).select(db.cms_page.ALL))
#
# cms_file - cms_files for the website
#
db.define_table('cms_file',
Field('cms_file', 'upload', required=True),
Field('created_on', 'datetime', default=request.now),
Field('created_by', 'reference auth_user', default=auth.user_id),
format='%(name)s')
db.cms_file.created_on.writable = False
db.cms_file.created_by.writable = False
db.cms_file.id.readable = False
#
# CUSTOMISE - customisable cms_files that allow the user to change html/css etc.
#
db.define_table('customise',
Field('name', unique=True),
Field('cms_file'),
Field('body', 'text'),
format='%(name)s'
)
db.customise.id.readable = db.customise.id.writable = False
db.customise.cms_file.readable = db.customise.cms_file.writable = False
#db.cms_page.insert(title = 'test123', subtitle = 'test123', body = 'test', parent_menu = None, main_menu = True, page_index = 79)
#db.customise.drop()
def check_initialize():
if not db().select(db.cms_page.ALL).first():
db.cms_page.insert(
title = 'Index',
body = '<p>Welcome Home</p>',
parent_menu = None,
main_menu = True,
published = True,
page_index = 0
)
if not db().select(db.customise.ALL).first():
db.customise.insert(
name='css_general',
body=None
)
db.customise.insert(
name='css_desktop',
body=None
)
db.customise.insert(
name='css_mobile',
body=None
)
cache.ram('db_initialized', check_initialize(), time_expire=None)
<file_sep>## Readme
web2py-liscio is a content management system (CMS) built on the web2py framework
Learn more about web2py at http://web2py.com
Licensed under the MIT License (MIT)
## Features
* Dynamic Page/Menu System
* File Manager
* Custom CSS
* Generated Sitemap
* User Manager
## Install
1. Simply install web2py from here http://www.web2py.com/init/default/download
2. Run your installation and access the admin panel (default location with rocket server: http://127.0.0.1:8000/admin/default/site)
3. In the right-hand pane, under Upload and install packed application
1. Enter the name of the application you wish to use (use "init" to automatically setup routing)
2. Enter web2py liscio github clone url in the "Or get from URL" field: https://github.com/peregrinius/web2py-liscio.git
## Setup
### Initialise Super Admin (yourself)
..liscio../models/\_db.py
At the end of the db.py file add your desired login details
user1 = db.auth_user.insert(
password = db.auth_user.password.validate('<PASSWORD>')[0],
email = '<EMAIL>',
first_name = 'Jack',
last_name = 'Frost',
)
## Admin
The admin section of the page is accessable through /[app_name]/admin
From here your users can manage the content of their website.
<file_sep># -*- coding: utf-8 -*-
@auth.requires_membership("admin")
def clear_cache():
cache.ram.clear()
redirect(URL('admin', 'index'))
def clear_cache_btn(fields, url):
return A(SPAN(T('Clear Cache'), _class='buttontext button'), _href=URL('clear_cache'), _class='w2p_trap button btn')
@auth.requires_membership("admin")
def index():
## Customise page model default
db.cms_page.id.readable = False
db.cms_page.url.readable = False
deletable = True
# If editing the index page
if 'edit' in request.args:
deletable = False
if db.cms_page(request.args(2)).page_index == 0:
#db.cms_page.title.writable = db.cms_page.title.readable = False
db.cms_page.url.writable = db.cms_page.url.readable = False
db.cms_page.main_menu.writable = db.cms_page.main_menu.readable = False
db.cms_page.page_index.writable = db.cms_page.page_index.readable = False
db.cms_page.published.writable = db.cms_page.published.readable = False
db.cms_page.members_only.writable = db.cms_page.members_only.readable = False
if 'delete' in request.args and db.cms_page(request.args(2)).page_index == 0:
session.flash = "Cannot delete this page"
redirect(URL('admin'))
## SQLFORM parameters
links = [dict(header='URL', body=lambda row: URL('default', 'page', args=[row.title]) if row.page_index != 0 else '/'), lambda row: A(SPAN(_class='icon magnifier icon-zoom-in'),SPAN(_class='buttontext button', _title='View'), 'Preview', _class='w2p_trap button btn', _href=URL("admin", "page_preview",args=[row.id]))]
query = db.cms_page.id>0
fields = [db.cms_page.id, db.cms_page.title, db.cms_page.main_menu, db.cms_page.published, db.cms_page.parent_menu, db.cms_page.members_only, db.cms_page.page_index]
orderby = [db.cms_page.page_index]
form = SQLFORM.grid(query=query, links=links, fields=fields, orderby=orderby, deletable=deletable, searchable=True, details=False, csv=False, search_widget=clear_cache_btn)
return dict(form=form)
@auth.requires_membership("admin")
def page_preview():
try:
page = db.cms_page(int(request.args(0)))
except:
raise HTTP(404)
return dict(page=page)
@auth.requires_membership("admin")
def style_sheet():
""" Create form for updating customised style sheets """
form = SQLFORM.grid(db.customise,
create=False,
details=False,
deletable=False,
orderby=~db.customise.id,
csv=False,
searchable=False)
return dict(form=form)
@auth.requires_membership("admin")
def file():
""" Manage files """
if 'new' in request.args:
db.cms_file.created_on.readable = False
db.cms_file.created_by.readable = False
#links = [dict(header='Name', body=lambda row: db.file.file.retrieve(row.file)[0]), dict(header='URL', body=lambda row: '/init/default/download/%s' %(db.file.file.retrieve(row.file)[0]))]
links = [dict(header='URL', body=lambda row: '/init/default/download/%s' %(db.cms_file.cms_file.retrieve(row.cms_file)[0]))]
fields =[db.cms_file.cms_file]
form = SQLFORM.grid(db.cms_file, links=links, searchable=False, csv=False, orderby=~db.cms_file.created_on)
return dict(form=form)
@auth.requires_membership("super_admin")
def manage_membership():
user_id = request.args(0)
db.auth_membership.user_id.default = int(user_id)
db.auth_membership.user_id.writable = False
form = SQLFORM.grid(db.auth_membership.user_id == user_id,
args=[user_id],
searchable=False,
details=False,
selectable=False,
csv=False)
return form
@auth.requires_membership("super_admin")
def manage_user():
user_id = request.args(0) or redirect(URL('list_users'))
form = SQLFORM(db.auth_user, user_id)
membership_panel = LOAD(request.controller,
'manage_membership.html',
args=[user_id],
ajax=True)
return dict(form=form, membership_panel=membership_panel)
@auth.requires_membership("super_admin")
def list_users():
links = [lambda row: A(SPAN(_class='icon pen icon-pencil'),SPAN(_class='buttontext button', _title='Edit'), 'Edit', _class='w2p_trap button btn', _href=URL('manage_user', args=row.id))]
users = SQLFORM.grid(db.auth_user,
links=links,
editable=False,
details=False,
csv=False)
return dict(users=users)
@auth.requires_membership("admin")
def help():
return locals()
<file_sep>{{extend 'admin/layout.html'}}
<h1>Help</h1>
<hr/>
<h2>Contents</h2>
<ol>
<li><a href="#Basic Table Usage">Basic Table Usage</a></li>
<li><a href="#Pages">Pages</a></li>
<ol>
<li><a href="#Index Page">Index Page</a></li>
<li><a href="#Content Pages">Content Pages</a></li>
<li><a href="#Orphan Pages">Orphan Pages</a></li>
</ol>
<ol>
<li><a href="#Searching">Searching</a></li>
<li><a href="#Exporting">Exporting</a></li>
<li><a href="#Deleting">Deleting</a></li>
</ol>
<li><a href="#Files">Files</a></li>
<li><a href="#Users">Users - Super Admin Only</a></li>
<ol>
<li><a href="#Groups">Groups</a></li>
</ol>
<li><a href="#CSS">CSS - Super Admin Only</a></li>
</ol>
<hr/>
<h2><a name="Basic Table Usage">Basic Table Usage</a></h2>
<p>
The Admin sections Pages, Files and Users all have the same tabular format, although some functions may be disabled on tables.
</p>
<hr/>
<h2><a name="Pages">Pages</a></h2>
<p>
The Pages section allows admins to manage the content on the site.
</p>
<h3><a name="Index Page">Index Page</a></h3>
<p>
The index page has a sequence of 0, and should be the only page with a sequence of 0. It is generally the first page users will visit when coming to the site. Although other pages may be deleted the index page should not be so this feature has been disabled.
</p>
<p>
The title for the index page can be edited to change the title of the site, which appears when users save the page and is the heading for the tab the site is in.
</p>
<h3><a name="Content Pages">Content Pages</a></h3>
<p>
Additional pages can be added to your website.
</p>
<ul>
<li>Title - the title will appear at the top of the page, it is also used in the main menu and the URL used to request the page.</li>
<li>Url - if you wish to add a link in the main menu to an external site, then adding the url to that site in url will redirect the user to that site.</li>
<li>Main Menu - when ticked will show the pages title in the main menu.</li>
<li>Body - the content displayed on the page. The body text area uses a rich text editor called CKEditor, please visit their <a href='http://docs.cksource.com/CKEditor_3.x/Users_Guide'>website</a> for further information on how to use the editor.</li>
<li>Sequence - what position the page will appear in the main menu</li>
<li>Published - when ticked will allow visitors to view the page, otherwise the page will only be viewable by people with admin access.</li>
<li>Members Only - when ticked the page will only be available to visitors with members access (anyone who registers on web2py-cms).</li>
</ul>
<h3><a name="Orphan Pages">Orphan Pages</a></h3>
<p>
Orphan pages is the term used for pages that are not attached to the main menu. To create an Orphan page, simply create a new page in the Pages section and untick the main menu box. The sequence should be left blank also.
</p>
<p>
Once the page has been created you may link to this page from within another pages content.
</p>
<hr/>
<h2><a name="Files">Files</a></h2>
<p>
The Files section stores all files required for the site, admins can upload images or documents and paste links to them in content pages.
</p>
<hr/>
<h2><a name="Users">Users - Super Admins Only</a></h2>
<p>
The Users section is used to manage user access, by adding or removing users from groups you can change the areas of access the user will have.
</p>
<h3><a name="Groups">Groups</a></h3>
<p>
When adding or editing a user, you can also edit the user groups that they belong too. The following user groups are available:
<ul>
<li>Member - Restricted access to only the main site and members content.</li>
<li>Admin - Access to the admin section of the website, can add/edit/delete pages and files.</li>
<li>Super Admin - Admin access plus can manage users and edit CSS.</li>
</ul>
Note: Users in the Super Admin group still require Admin and Member group access.
</p>
<hr/>
<h2><a name="CSS">CSS - Super Admins Only</a></h2>
<p>
If the admin wishes to customise the look of the content site then they may add their on custom CSS to this file.
</p>
<ul>
<li>CSS General - Any CSS updates you want to make to the site regardless of the device the visitor is using. Warning these changes should be mobile friendly.</li>
<li>CSS Mobile - Any CSS updates you want to make to the site that will only affect Mobile visitors.</li>
<li>CSS Desktop - Any CSS updates you want to make to the site that will only affect Desktop or non-mobile visitors.</li>
</ul>
|
a5ebd5277d0e3353a103be80b444055e335b982e
|
[
"Markdown",
"Python",
"HTML"
] | 7 |
HTML
|
peregrinius/web2py-liscio
|
2212027867d4533546dd140d23e167de7eaea4c6
|
a1c47f6db5ce947d152916b1beb61c508b99221e
|
refs/heads/master
|
<repo_name>naharmohsina/TourMate<file_sep>/app/src/main/java/com/example/android/tourmatefinalproject/CurrentWeatherFragment.java
package com.example.android.tourmatefinalproject;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.android.tourmatefinalproject.weather.WeatherResponse;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* A simple {@link Fragment} subclass.
*/
@SuppressLint("ValidFragment")
public class CurrentWeatherFragment extends Fragment {
private double latt,lonn;
double la=23.750883;
double lo=90.393404;
private TextView temp,humidity,place;
private Api_service service;
private String unit = "metric";
@SuppressLint("ValidFragment")
public CurrentWeatherFragment(double lat, double lon) {
// Required empty public constructor
latt=lat;
lonn=lon;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_current_weather, container, false);
temp=view.findViewById(R.id.temp);
humidity=view.findViewById(R.id.hum);
place=view.findViewById(R.id.place);
String url = String.format("weather?lat=%f&lon=%f&units=%s&appid=%s",latt,lonn,unit,getResources().getString(R.string.weather_key));
service = Api_response.getUser().create(Api_service.class);
Call<WeatherResponse> weatherResponseCall = service.getAllUser(url);
weatherResponseCall.enqueue(new Callback<WeatherResponse>() {
@Override
public void onResponse(Call <WeatherResponse> call, Response<WeatherResponse> response) {
if (response.code() == 200) {
WeatherResponse weatherResponse = response.body();
temp.setText("Temp "+weatherResponse.getMain().getTempMin().toString()+ " C");
humidity.setText("Humidity "+weatherResponse.getMain().getHumidity().toString()+" %");
place.setText(weatherResponse.getName());
}
}
@Override
public void onFailure(Call <WeatherResponse> call, Throwable t) {
}
});
return view;
}
}
<file_sep>/app/src/main/java/com/example/android/tourmatefinalproject/ApiService.java
package com.example.android.tourmatefinalproject;
import com.example.android.tourmatefinalproject.Nearby.NearbyResponse;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Url;
public interface ApiService {
@GET()
Call<NearbyResponse> getNearby(@Url String url);
@GET
Call<NearbyResponse> getNextPageToken(@Url String url);
}
<file_sep>/app/src/main/java/com/example/android/tourmatefinalproject/Api_service.java
package com.example.android.tourmatefinalproject;
import com.example.android.tourmatefinalproject.weather.WeatherResponse;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Url;
public interface Api_service {
@GET()
Call<WeatherResponse> getAllUser(@Url String url);
}
<file_sep>/app/src/main/java/com/example/android/tourmatefinalproject/DashboardEvent.java
package com.example.android.tourmatefinalproject;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Collections;
public class DashboardEvent extends AppCompatActivity {
String eventIdT;
String estimatedBudget;
int amount,amountCheck;
Boolean isFirst=false;
EditText expamount,exapD;
//Button addExp;
FirebaseAuth mAuth;
private String userId;
int estimatedBudgetInteger;
Button budget;
private ListView listViewExpense;
ArrayList<ExpensePojo> expenses;
// private BottomSheetBehavior sheetBehavior;
DatabaseReference databaseReference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard_event);
budget=(Button)findViewById(R.id.budget);
listViewExpense=(ListView)findViewById(R.id.listviewExpense);
userId= FirebaseAuth.getInstance().getUid();
expenses=new ArrayList<ExpensePojo>();
Intent intent=getIntent();
eventIdT = intent.getStringExtra("eventId");
estimatedBudget = intent.getStringExtra("budget");
expamount=(EditText)findViewById(R.id.expenseAmount);
exapD=(EditText)findViewById(R.id.expenseDetails);
//addExp=(Button)findViewById(R.id.addExpenseBtn);
estimatedBudgetInteger = Integer.parseInt(estimatedBudget);
//DatabaseReference databaseReference= FirebaseDatabase.getInstance().getReference().child("Users").child(FirebaseAuth.getInstance().getUid()).child("Event").child(eventIdT).child("Expense");
budget.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Intent intent=new Intent(DashboardEvent.this,AddExpense.class);
// intent.putExtra("eventIdd",eventIdT);
// intent.putExtra("budgett",estimatedBudget);
// startActivity(intent);
saveExpense();
}
});
// setUpReferences();
// sheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
// @Override
// public void onStateChanged(@NonNull View bottomSheet, int newState) {
// switch (newState) {
// case BottomSheetBehavior.STATE_HIDDEN:
// break;
//
// case BottomSheetBehavior.STATE_DRAGGING:
// sheetBehavior.setHideable(false);
// break;
// case BottomSheetBehavior.STATE_SETTLING:
// sheetBehavior.setHideable(false);
// break;
// }
// }
//
// @Override
// public void onSlide(@NonNull View bottomSheet, float slideOffset) {
//
// }
// });
// budgetList.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// Intent intent=new Intent(DashboardEvent.this,AddExpense.class);
// intent.putExtra("eventIdd",eventIdT);
// }
// });
databaseReference= FirebaseDatabase.getInstance().getReference().child("Users").child(userId).child("Event").child(eventIdT).child("Expense");
// databaseReference.addValueEventListener(new ValueEventListener() {
// @Override
// public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
// expenses.clear();
// for(DataSnapshot child: dataSnapshot.getChildren()) {
// ExpensePojo expenseClass = child.getValue(ExpensePojo.class);
//
// expenses.add(expenseClass);
// //finalEventListAdapter.notifyDataSetChanged();
//
// }
// Collections.reverse(expenses);
// ExpenseAdapter expenseAdapter=new ExpenseAdapter(DashboardEvent.this, expenses);
// listViewExpense.setAdapter(expenseAdapter);
//
//
// }
//
// @Override
// public void onCancelled(@NonNull DatabaseError databaseError) {
//
// }
// });
//
// addExp.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// String expenseDet=exapD.getText().toString();
// String expenseAm=expamount.getText().toString();
// if (TextUtils.isEmpty(expenseDet)) {
// exapD.setError("Enter your travel destination");
// exapD.requestFocus();
// return;
//
// } else if (TextUtils.isEmpty(expenseAm)) {
// expamount.setError("Enter your estimated budget");
// expamount.requestFocus();
// return;
//
// }
// else {
// final ProgressDialog progressDialog = new ProgressDialog(DashboardEvent.this);
// progressDialog.setMessage("Please waiting...");
// progressDialog.show();
// DatabaseReference databaseReference= FirebaseDatabase.getInstance().getReference().child("Users").child(userId).child("Event").child(eventIdT).child("Expense");
// String expenId=databaseReference.push().getKey();
// ExpensePojo eventPojo = new ExpensePojo(expenseDet, expenseAm,expenId);
// databaseReference.child(expenId).setValue(eventPojo).addOnCompleteListener(new OnCompleteListener<Void>() {
// @Override
// public void onComplete(@NonNull Task<Void> task) {
//
// if (task.isSuccessful()) {
// progressDialog.dismiss();
// Toast.makeText(DashboardEvent.this, "Thank you", Toast.LENGTH_SHORT).show();
//
// } else {
// Toast.makeText(DashboardEvent.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
// }
//
// }
// });
// exapD.setText("");
// expamount.setText("");
//
//
//
//
// Intent intent=new Intent(DashboardEvent.this,DashboardEvent.class);
// //intent.putExtra("eventIddd",eventIdT);
// //intent.putExtra("budgettt",estimatedBudget);
// startActivity(intent);
// // startActivity(new Intent(AddExpense.this,ShowExpense.class));
//
//
//
// }
// }
// });
}
private void saveExpense() {
String expenseDet=exapD.getText().toString();
String expenseAm=expamount.getText().toString();
if (TextUtils.isEmpty(expenseDet)) {
exapD.setError("Enter your expense details destination");
exapD.requestFocus();
return;
} else if (TextUtils.isEmpty(expenseAm)) {
expamount.setError("Enter your expense amount budget");
expamount.requestFocus();
return;
}
else
{
if (amountCheck>0) {
int totalExpenseWithCurrent = amountCheck + Integer.valueOf(expenseAm);
if (totalExpenseWithCurrent<=estimatedBudgetInteger){
final ProgressDialog progressDialog = new ProgressDialog(DashboardEvent.this);
progressDialog.setMessage("Please waiting...");
progressDialog.show();
DatabaseReference databaseReference= FirebaseDatabase.getInstance().getReference().child("Users").child(userId).child("Event").child(eventIdT).child("Expense");
String expenId=databaseReference.push().getKey();
ExpensePojo expensePojo = new ExpensePojo(expenseDet, expenseAm,expenId);
databaseReference.child(expenId).setValue(expensePojo).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
progressDialog.dismiss();
Toast.makeText(DashboardEvent.this, "Thank you", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(DashboardEvent.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
exapD.setText("");
expamount.setText("");
}
else {
Toast.makeText(DashboardEvent.this, "Budget Exceded!!", Toast.LENGTH_SHORT).show();
}
}
else if(isFirst)
{
int totalExpenseWithCurrent = amountCheck + Integer.valueOf(expenseAm);
if (totalExpenseWithCurrent<=estimatedBudgetInteger){
final ProgressDialog progressDialog = new ProgressDialog(DashboardEvent.this);
progressDialog.setMessage("Please waiting...");
progressDialog.show();
DatabaseReference databaseReference= FirebaseDatabase.getInstance().getReference().child("Users").child(userId).child("Event").child(eventIdT).child("Expense");
String expenId=databaseReference.push().getKey();
ExpensePojo expensePojo = new ExpensePojo(expenseDet, expenseAm,expenId);
databaseReference.child(expenId).setValue(expensePojo).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
progressDialog.dismiss();
Toast.makeText(DashboardEvent.this, "Thank you", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(DashboardEvent.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
exapD.setText("");
expamount.setText("");
}
else {
Toast.makeText(DashboardEvent.this, "Budget Exceded!!", Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(DashboardEvent.this, "Slow network connection! Try again", Toast.LENGTH_SHORT).show();
}
}
}
@Override
protected void onStart() {
super.onStart();
amount =0;
amountCheck = 0;
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
expenses.clear();
if (dataSnapshot.exists()) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
ExpensePojo expenseClass = child.getValue(ExpensePojo.class);
amount = amount+ Integer.parseInt(expenseClass.getExpenseAmount());
expenses.add(expenseClass);
//finalEventListAdapter.notifyDataSetChanged();
}
amountCheck = amount;
}
else {
isFirst = true;
//Toast.makeText(getActivity().this, "first", Toast.LENGTH_SHORT).show();
Toast.makeText(DashboardEvent.this, "first entry", Toast.LENGTH_SHORT).show();
}
Collections.reverse(expenses);
ExpenseAdapter expenseAdapter=new ExpenseAdapter(DashboardEvent.this, expenses);
listViewExpense.setAdapter(expenseAdapter);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
// private void setUpReferences() {
// LinearLayout layoutBottomSheet = findViewById(R.id.expense_bottom_sheet);
// //btnBottomSheet = findViewById(R.id.btn_bottom_sheet);
// sheetBehavior = BottomSheetBehavior.from(layoutBottomSheet);
// }
//
//
}
<file_sep>/app/src/main/java/com/example/android/tourmatefinalproject/TourActivity.java
package com.example.android.tourmatefinalproject;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Collections;
public class TourActivity extends AppCompatActivity {
private Button addButton;
private ListView listViewTour;
ArrayList<EventPojo>events;
String userId;
DatabaseReference databaseReference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tour);
addButton=(Button)findViewById(R.id.addeventButton);
listViewTour=(ListView)findViewById(R.id.listViewTourEvent);
userId= FirebaseAuth.getInstance().getUid();
events=new ArrayList<EventPojo>();
databaseReference= FirebaseDatabase.getInstance().getReference().child("Users").child(userId).child("Event");
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(TourActivity.this,CreateEvent.class));
}
});
listViewTour.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
EventPojo artist=events.get(i);
Intent intent=new Intent(TourActivity.this,DashboardEvent.class);
String getId = artist.getId();
String getBudget = artist.getTravelEstimatedBudget();
intent.putExtra("eventId",getId);
intent.putExtra("budget",getBudget);
startActivity(intent);
}
});
}
@Override
protected void onStart() {
super.onStart();
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
events.clear();
for(DataSnapshot child: dataSnapshot.getChildren()) {
EventPojo eventClass = child.getValue(EventPojo.class);
events.add(eventClass);
//finalEventListAdapter.notifyDataSetChanged();
}
Collections.reverse(events);
TourAdapter tourAdapter=new TourAdapter(TourActivity.this, events);
listViewTour.setAdapter(tourAdapter);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
// private boolean updateEvent(String travelDestination, String travelEndingDate,String travelStartingDate,String travelEstimatedBudget,String id) {
// //getting the specified artist reference
// DatabaseReference dR = databaseReference;
// //String travelDestination, String travelEstimatedBudget, String travelStartingDate, String travelEndingDate, String id) {
// //
//
// //updating artist
// EventPojo eventPojo = new EventPojo(travelDestination, travelEstimatedBudget, travelStartingDate,travelEndingDate,id);
// dR.setValue(eventPojo);
// Toast.makeText(getApplicationContext(), "Event Updated", Toast.LENGTH_LONG).show();
// return true;
// }
}
<file_sep>/app/src/main/java/com/example/android/tourmatefinalproject/WeatherForecast.java
package com.example.android.tourmatefinalproject;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
public class WeatherForecast extends AppCompatActivity {
private double latn,lonn;
String address;
private TabLayout tabLayout;
private ViewPager viewPager;
private ViewPagerAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weather_forecast);
tabLayout = findViewById(R.id.tabLayoutId);
viewPager = findViewById(R.id.viewPagerId);
adapter = new ViewPagerAdapter(getSupportFragmentManager());
Intent intent = getIntent();
latn = intent.getDoubleExtra("latitude",0);
lonn = intent.getDoubleExtra("longitude",0);
address = intent.getStringExtra("Address");
CurrentWeatherFragment currentWeatherFragment = new CurrentWeatherFragment(latn,lonn);
ForecastWeatherFragment forecastWeatherFragment = new ForecastWeatherFragment(latn,lonn);
adapter.addFragment(currentWeatherFragment,"Current Weather");
adapter.addFragment(forecastWeatherFragment,"Forecast Weather");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
}
}
|
94412209984be297ee05b04d04bbef0e98e274f1
|
[
"Java"
] | 6 |
Java
|
naharmohsina/TourMate
|
1b6f7e7749e9d4a6bbdcb7a37076f7c16cf12283
|
9f6dcc33ffd191ee5b83bc485648a529562ee62e
|
refs/heads/master
|
<repo_name>Mukit09/CertificateBasedAuth<file_sep>/src/main/java/Signer.java
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import java.security.PrivateKey;
import java.security.Signature;
@Slf4j
@Getter
@Setter
public class Signer {
private final static String SIGNATURE_ALGORITHM = "SHA256withECDSA";
private final static String SIGNATURE_PROVIDER = "SunEC";
private PrivateKey privateKey;
private byte[] byteDataArray;
private byte[] byteSignatureArray;
public void signData() {
try {
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM, SIGNATURE_PROVIDER);
signature.initSign(this.privateKey);
signature.update(this.byteDataArray);
this.byteSignatureArray = signature.sign();
} catch (Exception e) {
log.error("Exception: ", e);
}
}
public void loadData() {
String data = "My name is Mukit";
this.byteDataArray = data.getBytes();
}
}
<file_sep>/README.md
# CertificateBasedAuth
Using certificate to sign and verify data
At first need to create the key store file. For that, you need to go to the JAVA_HOME/bin.
Then run this command(for windows):
keytool -genkey -alias aliasName -keyalg EC -keystore {Directory}\keystore.jks -keysize 256
It will create a keystore.jks file in the given "Directory".
<file_sep>/src/main/java/CertificateGenerator.java
import lombok.Data;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.*;
import java.security.cert.Certificate;
import java.util.Enumeration;
@Slf4j
@Getter
@Data
public class CertificateGenerator {
private KeyStore keyStore;
private final static String KEY_STORE_PASSWORD = "<PASSWORD>";
private final static String PRIVATE_KEY_PASSWORD = "<PASSWORD>";
private final static String KEY_STORE_FILE_NAME = "keystore.jks";
public final static String CERTIFICATE_FILE_NAME = "certificate.crt";
CertificateGenerator() {
try {
this.keyStore = KeyStore.getInstance("JKS");
} catch (Exception e) {
log.error("Exception: ", e);
}
}
public void loadKeyStore() {
char passwordCharArray[] = KEY_STORE_PASSWORD.toCharArray();
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(KEY_STORE_FILE_NAME);
this.keyStore.load(inputStream, passwordCharArray);
} catch (Exception e) {
log.error("Exception: ", e);
} finally {
CloserUtility.getInstance().closeFileInputStream(inputStream);
}
}
public void logAllAliasesName() {
try {
log.debug("Size found: " + keyStore.size());
Enumeration<String> enumeration = keyStore.aliases();
while(enumeration.hasMoreElements()) {
log.debug(enumeration.nextElement());
}
} catch (Exception e) {
log.error("Exception: ", e);
}
}
public PrivateKey getPrivateKey() {
char[] passwordCharArray = PRIVATE_KEY_PASSWORD.toCharArray();
PrivateKey privateKey;
try {
privateKey = (PrivateKey) keyStore.getKey("aliasmukit", passwordCharArray);
log.debug(new String(privateKey.getEncoded()));
return privateKey;
} catch (Exception e) {
log.error("Exception: ", e);
}
return null;
}
public void generateCertificateAndWriteInFile() {
Certificate certificate;
FileOutputStream outputStream = null;
try {
certificate = keyStore.getCertificate("aliasmukit");
byte[] encodedCertificate = certificate.getEncoded();
outputStream = new FileOutputStream(CERTIFICATE_FILE_NAME);
outputStream.write(encodedCertificate);
} catch (Exception e) {
log.error("Exception: ", e);
} finally {
CloserUtility.getInstance().closeFileOutputStream(outputStream);
}
}
}
<file_sep>/src/main/java/CloserUtility.java
import lombok.extern.slf4j.Slf4j;
import java.io.FileInputStream;
import java.io.FileOutputStream;
@Slf4j
public class CloserUtility {
private static volatile CloserUtility closerUtility;
private CloserUtility() {}
public static CloserUtility getInstance() {
if(closerUtility == null) {
synchronized (CloserUtility.class) {
if(closerUtility == null) {
closerUtility = new CloserUtility();
}
}
}
return closerUtility;
}
public void closeFileInputStream(FileInputStream inputStream) {
try {
if(inputStream != null) inputStream.close();
} catch (Exception ex) {
log.error("Exception: ", ex);
}
}
public void closeFileOutputStream(FileOutputStream outputStream) {
try {
if(outputStream != null) outputStream.close();
} catch (Exception ex) {
log.error("Exception: ", ex);
}
}
}
|
c90f1759aeaba0c472987534d5b9db87999555b6
|
[
"Markdown",
"Java"
] | 4 |
Java
|
Mukit09/CertificateBasedAuth
|
3e3b5e64638315e54a8cb5ddb783fff01509ed1a
|
8f6d1e92b7b301359e162ae2dfb33e6e8fe9140b
|
refs/heads/master
|
<repo_name>apg/paycheck<file_sep>/setup.py
from distutils.cmd import Command
class test(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import tests
tests.run_tests()
from distutils.core import setup
setup(name = 'paycheck',
version ='0.4.3',
description ='A Python QuickCheck implementation',
author ='<NAME>',
author_email ='<EMAIL>',
url='http://github.com/markchadwick/paycheck/tree/master',
packages = ['paycheck'],
cmdclass = {"test" : test}
)
|
c5e9432de97aa2d98bb9ae323c3c12817caa4176
|
[
"Python"
] | 1 |
Python
|
apg/paycheck
|
4c646143a9edc1f825cba156c0f3b812e346497f
|
4adf9dbb840f6e9d5a27fae3ef8ef1f88452d4ba
|
refs/heads/master
|
<repo_name>mnishida/PyOptMat<file_sep>/README.md
# PyOptMat
[![PyPI version][pypi-image]][pypi-link]
[![Anaconda Version][anaconda-v-image]][anaconda-v-link]
[pypi-image]: https://badge.fury.io/py/pyoptmat.svg
[pypi-link]: https://pypi.org/project/pyoptmat
[anaconda-v-image]: https://anaconda.org/mnishida/pyoptmat/badges/version.svg
[anaconda-v-link]: https://anaconda.org/mnishida/pyoptmat
PyOptMat is a python package providing dielectric constants of optical materials
using data from the
[refractiveindex.info database](http://refractiveindex.info/)
developed by [<NAME>](https://github.com/polyanskiy).
## Features
The parameters of dielectric functions for noble metals are derived by fitting
the data shown in [1] or [2], refering to the parameters used in [3] and [4].
[1] <NAME> and <NAME>, Phys. Rev. B 6, 4370 (1972).
[2] Handbook of Optical Constants of Solids, ed Palik ED (Academic, Orlando)
(1985).
[3] <NAME>, <NAME>, <NAME>, <NAME>, <NAME>,
<NAME>, <NAME>, and <NAME>,
Proc. Nat. Acad. Sci. (USA) 103, 17143 (2006).
[4] <NAME>, <NAME>, J. Phys. D: Appl. Phys. 40 7152 (2007).
The parameters of the dielectric function for Aluminium are derived by fitting
the data shown in [5], [6] and [7], refering to the parameters used in [8].
[5] <NAME>ć, <NAME>šic, <NAME>, and <NAME>,
Appl. Opt. 37, 5271-5283 (1998).
[6] <NAME>, <NAME>, <NAME>, <NAME>, <NAME>,
<NAME>, and <NAME>,
ACS Photonics 2, 326-333 (2015).
[7] <NAME>, http://refractiveindex.info/
Refractive index database (2017).
[8] <NAME>, <NAME>, and <NAME>,
Phys. Rev. B 77, 075401 (2008).
## Install
#### Install and update using pip
```
$ pip install -U pyoptmat
```
#### Install using conda
```
$ conda install -c mnishida pyoptmat
```
## Usage
### Permittivity of Dielectric
#### Specify Reflactive Index
```
>>> import numpy as np
>>> from pyoptmat import Material
>>> wavelength = 0.5 # [um]
>>> w = np.pi / wavelength
>>> water = Material({'RI': 1.333})
>>> water.params
{'RI': 1.333, 'e': 1.776889}
>>> water(w) # independent of w
1.776889
```
#### Use RefractiveIndex.Info database
```
>>> import riip
>>> ri = riip.RiiDataFrame()
>>> ri.search("H2O")
shelf book page formula tabulated wl_min wl_max
id
426 main H2O (Liquid water, H2O) Hale 0 nk 0.200000 2.000000e+02
427 main H2O (Liquid water, H2O) Wang 0 k 1.200000 1.900000e+00
428 main H2O (Liquid water, H2O) Kedenburg 2 k 0.500000 1.600000e+00
429 main H2O (Liquid water, H2O) Daimon-19.0C 2 f 0.182000 1.129000e+00
430 main H2O (Liquid water, H2O) Daimon-20.0C 2 f 0.182000 1.129000e+00
431 main H2O (Liquid water, H2O) Daimon-21.5C 2 f 0.182000 1.129000e+00
432 main H2O (Liquid water, H2O) Daimon-24.0C 2 f 0.182000 1.129000e+00
433 main H2O (Liquid water, H2O) Segelstein 0 nk 0.033963 1.000000e+07
434 main H2O (Liquid water, H2O) Asfar-H2O 0 nk 22.220000 1.733000e+03
435 main H2O (Water ice) Warren-2008 0 nk 0.044300 2.000000e+06
436 main H2O (Water ice) Warren-1984 0 nk 0.044300 1.670000e+02
437 main H2O (Water ice) Kofman-10K 1 f 0.210000 7.570000e-01
438 main H2O (Water ice) Kofman-30K 1 f 0.210000 7.570000e-01
439 main H2O (Water ice) Kofman-50K 1 f 0.210000 7.570000e-01
440 main H2O (Water ice) Kofman-70K 1 f 0.210000 7.570000e-01
441 main H2O (Water ice) Kofman-90K 1 f 0.210000 7.570000e-01
442 main H2O (Water ice) Kofman-110K 1 f 0.210000 7.570000e-01
443 main H2O (Water ice) Kofman-130K 1 f 0.210000 7.570000e-01
444 main H2O (Water ice) Kofman-150K 1 f 0.210000 7.570000e-01
445 main H2O (Supercooled liquid water) Rowe-240K 0 nk 0.666684 1.039594e+04
446 main H2O (Supercooled liquid water) Rowe-253K 0 nk 0.666684 1.039594e+04
447 main H2O (Supercooled liquid water) Rowe-263K 0 nk 0.666684 1.039594e+04
448 main H2O (Supercooled liquid water) Rowe-273K 0 nk 0.666684 1.039594e+04
449 main H2O (Heavy water, D2O) Kedenburg-D2O 2 k 0.500000 1.600000e+00
450 main H2O (Heavy water, D2O) Wang-D2O 0 k 1.200000 2.600000e+00
451 main H2O (Heavy water, D2O) Asfar-D2O 0 nk 250.000000 2.000000e+03
>>> water2 = Material({"model": "rii", "shelf": "main", "book": "H2O (Liquid water, H2O)", "page": "Hale"})
>>> water2(w)
(1.7609289999916478+7.67006e-06j)
```
### Dielectric Function of Metal
```
>>> gold_dl = Material({"model": "gold_dl"})
>>> gold_dl(w)
(-46.55300320486374+3.326656611859579j)
>>> gold = Material({"model": "rii", "shelf": "DL", "book": "Au", "page": "Stewart"})
>>> gold(w)
(-46.55300320486374+3.326656611859579j)
```
## Uninstall
```
$ pip uninstall pyoptmat
```
or
```
$ conda uninstall pyoptmat
```
## Dependencies
- python 3
- numpy
- scipy
- riip
## Version
0.1.0
<file_sep>/setup.py
from setuptools import find_packages, setup
def get_install_requires():
with open("requirements.txt", "r") as f:
return [line.strip() for line in f.readlines() if not line.startswith("-")]
setup(
name="pyoptmat",
version="0.1.0",
author="<NAME>",
author_email="<EMAIL>",
url="https://github.com/mnishida/PyOptMat",
license="MIT",
description="Definitions of dielectric constants of optical materials.",
long_description=open("README.md").read(),
long_description_content_type="text/markdown",
packages=find_packages(),
include_package_data=True,
install_requires=get_install_requires(),
python_requires=">=3.7",
classifiers=[
"Development Status :: 2 - Pre-Alpha",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Topic :: Scientific/Engineering",
],
keywords="dielectric constant, optical material",
)
<file_sep>/requirements_dev.txt
pytest
pytest-regressions
pre-commit
flake8
black
tox
pydocstyle
<file_sep>/Makefile
install:
python -m pip install --upgrade pip
pip install -r requirements.txt --upgrade
pip install -r requirements_dev.txt --upgrade
pip install -e .
pre-commit install
test:
pytest
cov:
pytest --cov= riip
mypy:
mypy . --ignore-missing-imports
lint:
flake8
pylint:
pylint riip
lintd2:
flake8 --select RST
lintd:
pydocstyle riip
<file_sep>/tests/test_material.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
from numpy.testing import assert_allclose
result_gold_d = -42.438315881875219 + 3.1544052539392413j
result_gold_dl = -46.553004128210638 + 3.3266566828613278j
result_silver_dl = -48.058582927757783 + 2.9917315082144231j
result_aluminium_dl = -83.979985579914157 + 27.440127505777991j
result_GaN = 5.4598374108551901
result_W = -2.8490661174276219 + 21.023779631594959j
def test_material():
from pyoptmat import Material
air = Material({"model": "dielectric", "RI": 1.0})
water = Material({"model": "dielectric", "RI": 1.333})
gold_d = Material({"model": "gold_d"})
gold_dl = Material({"model": "gold_dl"})
silver_dl = Material({"model": "silver_dl"})
aluminium_dl = Material({"model": "aluminium_dl"})
aluminium_dl_low_loss = Material({"model": "aluminium_dl", "im_factor": 0.1})
GaN = Material(
{
"model": "rii",
"shelf": "main",
"book": "GaN (Experimental data)",
"page": "Barker-o",
}
)
W = Material({"model": "rii", "shelf": "DL", "book": "W", "page": "Rakic"})
w = 2.0 * np.pi
assert_allclose(air(w), 1.0)
assert_allclose(water(w), 1.333 ** 2)
assert_allclose(gold_d(w), result_gold_d)
assert_allclose(gold_dl(w), result_gold_dl)
assert_allclose(silver_dl(w), result_silver_dl)
assert_allclose(aluminium_dl(w), result_aluminium_dl)
assert_allclose(
aluminium_dl_low_loss(w),
result_aluminium_dl.real + 0.1j * result_aluminium_dl.imag,
)
assert_allclose(GaN(w), result_GaN)
assert_allclose(W(w), result_W)
<file_sep>/pyoptmat/__init__.py
# -*- coding: utf-8 -*-
"""PyOptMat is a python package defining dielectric constants of optical
materials.
"""
from pyoptmat.material import Material
__author__ = "<NAME>"
__version__ = "0.1.0"
__license__ = "MIT"
<file_sep>/tox.ini
[tox]
envlist = py38, py39
[testenv]
commands = pytest
deps=
pytest
-rrequirements.txt
-rrequirements_dev.txt
# Linters
[testenv:flake8]
basepython = python3
skip_install = true
deps =
flake8
flake8-bugbear
flake8-docstrings>=1.3.1
flake8-import-order>=0.9
flake8-typing-imports>=1.1
pep8-naming
commands =
flake8 pp
# Flake8 Configuration
[flake8]
ignore = E203, E266, E501, W503, F403, F401
exclude =
.tox,
.git,
__pycache__,
docs/source/conf.py,
build,
dist,
tests/fixtures/*,
*.pyc,
*.egg-info,
.cache,
.eggs
max-line-length = 88
max-complexity = 18
import-order-style = google
application-import-names = flake8
<file_sep>/pyoptmat/material.py
# -*- coding: utf-8 -*-
import numpy as np
import riip
class Material(object):
"""A class defining the dielectric function for a material.
Attributes:
model: A string indicating the model of dielectric function.
"""
def __init__(self, params):
"""Init Material class.
Args:
params: A dict whose keys are as follows.
'model': A string indicating the model of dielectric function,
that must be 'dielectric', 'pec', 'rii',
'gold_d', 'gold_dl', 'gold_rakic', 'silver_dl',
'aluminium_dl' (default 'dielectric')
'e' or 'RI': For 'dielectric'
'shelf', 'book', 'page': For 'rii',
Use data from <NAME>,
"Refractive index database," https://refractiveindex.info.
'im_factor': A float indicating the reduction factor for the
imaginary part of the dielectric constant
'bound_check': True if bound check should be done.
"""
self.__w = None
self.__eps = None
self.params = params
model = self.params.get("model", "dielectric")
self.model = model
self.__im_factor = self.params.get("im_factor", 1.0)
self.material = None
self.bound_chek = self.params.get("bound_check", True)
if model == "pec":
self.params["e"] = -1e8
elif model == "gold_dl":
ri = riip.RiiDataFrame()
idx = ri.catalog[
(ri.catalog["shelf"] == "DL")
& (ri.catalog["book"] == "Au")
& (ri.catalog["page"] == "Stewart")
].index[0]
self.material = ri.material(idx, self.bound_chek)
elif model == "gold_rakic":
ri = riip.RiiDataFrame()
idx = ri.catalog[
(ri.catalog["shelf"] == "DL")
& (ri.catalog["book"] == "Au")
& (ri.catalog["page"] == "Rakic")
].index[0]
self.material = ri.material(idx, self.bound_chek)
elif model == "silver_dl":
ri = riip.RiiDataFrame()
idx = ri.catalog[
(ri.catalog["shelf"] == "DL")
& (ri.catalog["book"] == "Ag")
& (ri.catalog["page"] == "Vial")
].index[0]
self.material = ri.material(idx, self.bound_chek)
elif model == "aluminium_dl":
ri = riip.RiiDataFrame()
idx = ri.catalog[
(ri.catalog["shelf"] == "DL")
& (ri.catalog["book"] == "Al")
& (ri.catalog["page"] == "Rakic")
].index[0]
self.material = ri.material(idx, self.bound_chek)
elif model == "gold_d":
ri = riip.RiiDataFrame()
idx = ri.catalog[
(ri.catalog["shelf"] == "Drude")
& (ri.catalog["book"] == "Au")
& (ri.catalog["page"] == "Vial")
].index[0]
self.material = ri.material(idx, self.bound_chek)
elif model == "rii":
ri = riip.RiiDataFrame()
idx = ri.catalog[
(ri.catalog["shelf"] == self.params["shelf"])
& (ri.catalog["book"] == self.params["book"])
& (ri.catalog["page"] == self.params["page"])
].index[0]
self.material = ri.material(idx, self.bound_chek)
elif model == "dielectric":
if "RI" in self.params:
if "e" in self.params:
if self.params["e"] != self.params["RI"] ** 2:
raise ValueError("e must be RI ** 2.")
else:
self.params["e"] = self.params["RI"] ** 2
else:
if "e" not in self.params:
raise ValueError("'RI' or 'e' must be specified.")
else:
raise ValueError("The model {} is not implemented.".format(model))
@property
def im_factor(self):
return self.__im_factor
@im_factor.setter
def im_factor(self, factor):
self.__w = None
self.__im_factor = factor
def __call__(self, w):
"""Return a float indicating the permittivity.
Args:
w: A float indicating the angular frequency.
Raises:
ValueError: The model is not defined.
"""
if self.__w is None or w != self.__w:
self.__w = w
model = self.model
p = self.params
if model in ["dielectric", "pec"]:
self.__eps = p["e"]
elif model in [
"gold_d",
"gold_dl",
"gold_rakic",
"silver_dl",
"aluminium_dl",
]:
eps = self.material.eps(2 * np.pi / w)
self.__eps = eps.real + 1j * self.im_factor * eps.imag
if self.__eps.imag < 1.0e-12:
self.__eps = self.__eps.real + 1.0e-12j
elif model == "rii":
if (
self.material.catalog["tabulated"] == "f"
and int(self.material.catalog["formula"]) <= 20
):
self.__eps = self.material.n(2 * np.pi / w) ** 2
else:
eps = self.material.eps(2 * np.pi / w)
self.__eps = eps.real + 1j * self.im_factor * eps.imag
if self.__eps.imag < 1.0e-12:
self.__eps = self.__eps.real + 1.0e-12j
else:
raise ValueError("The model is not defined.")
return self.__eps
|
cac800987d4b7c563e5f802bc264099bcc864fb0
|
[
"Markdown",
"Makefile",
"INI",
"Python",
"Text"
] | 8 |
Markdown
|
mnishida/PyOptMat
|
8ba44ed3941dbb92df7843ccb236909189dd8ab7
|
47f01e8815d218c40393ab7bf394cd772ec8180e
|
refs/heads/master
|
<repo_name>priteshkapuriya/task-management-angular<file_sep>/README.md
## Task Management App
## Start
Run `npm start` to start, Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.
## Demo
<file_sep>/src/app/app.component.spec.ts
import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { DataService } from "./data.service";
import { FormsModule } from '@angular/forms';
import { ListComponent } from './list/list.component';
import { TaskItemComponent } from './task-item/task-item.component';
import { SortablejsModule } from "angular-sortablejs";
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [FormsModule, SortablejsModule.forRoot({ animation: 150 })],
declarations: [
AppComponent,
ListComponent,
TaskItemComponent
],
providers:[DataService]
}).compileComponents();
}));
it('should create the app', async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
});
<file_sep>/src/app/task.interface.ts
export interface Task {
listId: string,
taskId: string,
text: string
}<file_sep>/src/app/list/list.component.ts
import { Component, OnInit, Input } from "@angular/core";
import { DataService } from "../data.service";
import { List } from "../list.interface";
import { SortablejsOptions } from "angular-sortablejs";
@Component({
selector: "list",
templateUrl: "./list.component.html",
styleUrls: ["./list.component.css"],
})
export class ListComponent implements OnInit {
@Input() data: List;
private editing: boolean = false;
private newTaskName: string;
private dataService: DataService;
private sortableOptions: SortablejsOptions = {
group: "shared",
handle: ".handle",
animation: 150,
onEnd: (event: any) => {
let taskId = event.item.id;
let toListId = event.to.id;
this.dataService.changeListId(taskId, toListId);
},
};
handleSortable(item) {
console.log(item);
return item;
}
constructor(dataServ: DataService) {
this.dataService = dataServ;
}
ngOnInit() {}
onSaveNewTask() {
let duplicate = false;
this.data.tasks.forEach((task) => {
if (
task.text.replace(/\s+/g, "").toLowerCase() ===
this.newTaskName.replace(/\s+/g, "").toLocaleLowerCase()
) {
duplicate = true;
alert("Task With Same Name Already Exists, Please Try Another Name");
}
});
if (this.newTaskName.trim() !== "" && !duplicate) {
this.dataService.saveNewTask(this.newTaskName.trim(), this.data);
this.newTaskName = "";
}
}
onRemoveList(name) {
if (confirm("Are you sure to delete list: " + name)) {
this.dataService.removeList(this.data.listId);
}
}
startEdit(input) {
this.editing = true;
setTimeout(() => {
input.focus();
}, 0);
}
finishEdit() {
setTimeout(() => {
this.editing = false;
this.dataService.save();
}, 300);
}
}
<file_sep>/src/app/app.component.ts
import { Component, NgZone } from "@angular/core";
import { DataService } from "./data.service";
import { List } from "./list.interface";
import { SortablejsOptions } from "angular-sortablejs";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"],
})
export class AppComponent {
private lists: Array<List>;
private addListText: String;
private dataService: DataService;
private sortableOptions: SortablejsOptions = {
group: "listSortable",
animation: 150,
handle: ".handle",
onUpdate: (event: any) => {
this.dataService.save();
},
};
constructor(dataServ: DataService, zone: NgZone) {
dataServ.subscribeToLists((data) => {
this.lists = data;
zone.run(() => {
console.log("Update");
});
});
this.dataService = dataServ;
}
onSaveNewList() {
let duplicate = false;
this.lists.forEach((list) => {
if (
this.addListText.replace(/\s+/g, "").toLowerCase() ===
list.name.replace(/\s+/g, "").toLowerCase()
) {
duplicate = true;
alert("List With Same Name Already Exists, Please Try Another Name");
}
});
if (this.addListText.trim() !== "" && !duplicate) {
this.dataService.saveNewList(this.addListText.trim());
this.addListText = "";
}
}
}
<file_sep>/src/app/task-item/task-item.component.ts
import { Component, OnChanges, Input } from "@angular/core";
import { Task } from "../task.interface";
import { DataService } from "../data.service";
@Component({
selector: "task-item",
templateUrl: "./task-item.component.html",
styleUrls: ["./task-item.component.css"],
})
export class TaskItemComponent implements OnChanges {
@Input() data: Task;
private dataService;
private editing: boolean = false;
constructor(dataServ: DataService) {
this.dataService = dataServ;
}
ngOnChanges(changes) {
// console.log(changes)
}
onRemoveTask(taskName, taskId) {
let cdata;
this.dataService.lists.forEach((item) => {
if (item.tasks.length > 0) {
item.tasks.forEach((elem) => {
if (elem.text === taskName && elem.taskId === taskId) {
debugger;
cdata = elem;
}
});
}
});
if (confirm("Are you sure to delete task: " + taskName)) {
this.dataService.removeTask(cdata);
}
}
onCompleted() {
this.dataService.save();
}
startEdit(input) {
this.editing = true;
setTimeout(() => {
input.focus();
}, 0);
}
finishEdit() {
setTimeout(() => {
this.editing = false;
this.dataService.save();
}, 300);
}
}
|
41d4c924a85f5c6d84640ea6c1e27d27d3495895
|
[
"Markdown",
"TypeScript"
] | 6 |
Markdown
|
priteshkapuriya/task-management-angular
|
8b6a3235edf58ee7ae1785ae0addc79d36fa40dc
|
89f9c4c0a76b7424e069e8c5ec555ea78a641fba
|
refs/heads/master
|
<file_sep>## BoilerPlate Webpack - backbone - lodash - jquery
how does it work:
Install all the dependencies, with ```npm install```
- prod: ```npm run build```
this create a ```dist``` file with ```webpack.prod``` config
- dev : ```npm run dev```
launch a Webpack dev server with hot reaload
<file_sep>var View = require( 'std/View' );
var Template = require( 'templates/layouts/page.html' );
module.exports = View.extend( {
constructor: function () {
View.prototype.constructor.apply( this, arguments );
},
initialize: function () {
View.prototype.initialize.apply( this, arguments );
this.render();
},
template: function () {
return _.template( Template( {
title: 'Home'
} ) );
},
render: function () {
this.$el.html( this.template() );
return this;
}
} );
|
96fd9a001df8db6426645962a90073b8c98df4a0
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
jdbonicel/boilerPlate-Backbone-lodash-jquery-webpack
|
9164b7f9f9a1d7d1020c4a4dfd8a8b6bbbb98da9
|
712d10e11bab03ee92ab03287ac7e31f04bb160f
|
refs/heads/master
|
<file_sep>/*
used for zlib support ...
*/
#include <assert.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
//#include <zlib.h>
#include <console/console.h>
#include <elf/elf.h>
#include <network/network.h>
#include <ppc/timebase.h>
#include <sys/iosupport.h>
#include <usb/usbmain.h>
#include <xb360/xb360.h>
#include <xenon_nand/xenon_sfcx.h>
#include <xetypes.h>
#include "../lv1/puff/puff.h"
#include "config.h"
#include "file.h"
#include "kboot/kbootconf.h"
#include "tftp/tftp.h"
#define CHUNK 16384
// int i;
extern char dt_blob_start[];
extern char dt_blob_end[];
const unsigned char elfhdr[] = {0x7f, 'E', 'L', 'F'};
const unsigned char cpiohdr[] = {0x30, 0x37, 0x30, 0x37};
const unsigned char kboothdr[] = "#KBOOTCONFIG";
struct filenames filelist[] = {{"kboot.conf", TYPE_KBOOT},
{"xenon.elf", TYPE_ELF},
{"xenon.z", TYPE_ELF},
{"vmlinux", TYPE_ELF},
{"updxell.bin",TYPE_UPDXELL},
{"updflash.bin",TYPE_NANDIMAGE},
{NULL, TYPE_INVALID}};
// Decompress a gzip file ...
//int inflate_read(char *source,int len,char **dest,int * destsize, int gzip) {
// int ret;
// unsigned have;
// z_stream strm;
// unsigned char out[CHUNK];
// int totalsize = 0;
//
// /* allocate inflate state */
// strm.zalloc = Z_NULL;
// strm.zfree = Z_NULL;
// strm.opaque = Z_NULL;
// strm.avail_in = 0;
// strm.next_in = Z_NULL;
//
// if(gzip)
// ret = inflateInit2(&strm, 16+MAX_WBITS);
// else
// ret = inflateInit(&strm);
//
// if (ret != Z_OK)
// return ret;
//
// strm.avail_in = len;
// strm.next_in = (Bytef*)source;
//
// /* run inflate() on input until output buffer not full */
// do {
// strm.avail_out = CHUNK;
// strm.next_out = (Bytef*)out;
// ret = inflate(&strm, Z_NO_FLUSH);
// assert(ret != Z_STREAM_ERROR); /* state not clobbered */
// switch (ret) {
// case Z_NEED_DICT:
// ret = Z_DATA_ERROR; /* and fall through */
// case Z_DATA_ERROR:
// case Z_MEM_ERROR:
// inflateEnd(&strm);
// return ret;
// }
// have = CHUNK - strm.avail_out;
// totalsize += have;
// if (totalsize > ELF_MAXSIZE)
// return Z_BUF_ERROR;
// //*dest = (char*)realloc(*dest,totalsize);
// memcpy(*dest + totalsize - have,out,have);
// *destsize = totalsize;
// } while (strm.avail_out == 0);
//
// /* clean up and return */
// (void)inflateEnd(&strm);
// return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
//}
void wait_and_cleanup_line() {
uint64_t t = mftb();
while (tb_diff_msec(mftb(), t) < 200) { // yield to network
network_poll();
}
console_clrline();
}
int launch_file(void *addr, unsigned len, int filetype) {
int ret = 0;
unsigned char *gzip_file;
switch (filetype) {
case TYPE_ELF:
// check if addr point to a gzip file
gzip_file = (unsigned char *)addr;
if ((gzip_file[0] == 0x1F) && (gzip_file[1] == 0x8B)) {
// found a gzip file
printf(" * Found a gzip file...\n");
char *dest = malloc(ELF_MAXSIZE);
long unsigned int destsize = 0;
// if(inflate_read((char*)addr, len, &dest, &destsize, 1) == 0){
if (puff((unsigned char *)dest, &destsize, addr,
(long unsigned int *)&len) == 0) {
// relocate elf ...
memcpy(addr, dest, destsize);
printf(" * Successfully unpacked...\n");
free(dest);
len = destsize;
} else {
printf(" * Unpacking failed...\n");
free(dest);
return -1;
}
}
if (memcmp(addr, elfhdr, 4))
return -1;
printf(" * Launching ELF...\n");
ret = elf_runWithDeviceTree(addr, len, dt_blob_start,
dt_blob_end - dt_blob_start);
break;
case TYPE_INITRD:
printf(" * Loading initrd into memory ...\n");
ret = kernel_prepare_initrd(addr, len);
break;
case TYPE_KBOOT:
printf(" * Loading kboot.conf ...\n");
ret = try_kbootconf(addr, len);
break;
// This shit is broken!
// case TYPE_UPDXELL:
//if (memcmp(addr + XELL_FOOTER_OFFSET, XELL_FOOTER, XELL_FOOTER_LENGTH) ||
// len != XELL_SIZE) return -1;
// printf(" * Loading UpdXeLL binary...\n");
// ret = updateXeLL(addr,len);
// break;
default:
printf("! Unsupported filetype supplied!\n");
}
return ret;
}
int try_load_file(char *filename, int filetype) {
int ret;
if (filetype == TYPE_NANDIMAGE) {
try_rawflash(filename);
return -1;
}
if (filetype == TYPE_UPDXELL) {
updateXeLL(filename);
return -1;
}
wait_and_cleanup_line();
printf("Trying %s...\r", filename);
struct stat s;
stat(filename, &s);
long size = s.st_size;
if (size <= 0)
return -1; // Size is invalid
int f = open(filename, O_RDONLY);
if (f < 0)
return f; // File wasn't opened...
void *buf = malloc(size);
printf("\n * '%s' found, loading %ld...\n", filename, size);
int r = read(f, buf, size);
if (r < 0) {
close(f);
free(buf);
return r;
}
if (filetype == TYPE_ELF) {
char *argv[] = {
filename,
};
int argc = sizeof(argv) / sizeof(char *);
elf_setArgcArgv(argc, argv);
}
ret = launch_file(buf, r, filetype);
free(buf);
return ret;
}
void fileloop() {
char filepath[255];
int i, j = 0;
for (i = 3; i < 16; i++) {
if (devoptab_list[i]->structSize) {
do {
usb_do_poll();
if (!devoptab_list[i]->structSize)
break;
sprintf(filepath, "%s:/%s", devoptab_list[i]->name,
filelist[j].filename);
if ((filelist[j].filetype == TYPE_UPDXELL ||
filelist[j].filetype == TYPE_NANDIMAGE) &&
(xenon_get_console_type() == REV_CORONA_PHISON)) {
wait_and_cleanup_line();
printf("MMC Console Detected! Skipping %s...\r", filepath);
j++;
} else {
try_load_file(filepath, filelist[j].filetype);
j++;
}
} while (filelist[j].filename != NULL);
j = 0;
}
}
}
void tftp_loop(ip_addr_t server) {
int i = 0;
do {
if ((filelist[i].filetype == TYPE_UPDXELL ||
filelist[i].filetype == TYPE_NANDIMAGE) &&
(xenon_get_console_type() == REV_CORONA_PHISON)) {
wait_and_cleanup_line();
printf("Skipping TFTP %s:%s... MMC Detected!\r", ipaddr_ntoa(&server),
filelist[i].filename);
i++;
} else {
wait_and_cleanup_line();
printf("Trying TFTP %s:%s... \r", ipaddr_ntoa(&server),
filelist[i].filename);
boot_tftp(server, filelist[i].filename, filelist[i].filetype);
i++;
}
network_poll();
} while (filelist[i].filename != NULL);
wait_and_cleanup_line();
printf("Trying TFTP %s:%s...\r", ipaddr_ntoa(&server), boot_file_name());
/* Assume that bootfile delivered via DHCP is an ELF */
boot_tftp(server, boot_file_name(), TYPE_ELF);
}
<file_sep>#!/bin/bash
GITREV=$(git describe --tags $(git rev-list --tags --max-count=1))
make clean
make
mkdir -p release/_DEBUG
cp *.bin release/
gunzip *.gz
cp stage2.elf32 release/
cp stage2.elf release/_DEBUG/
cp AUTHORS release/
cp CHANGELOG release/
cp README release/
cd release
tar czvf XeLL_Reloaded-2stages-${GITREV}.tar.gz *
mv *.tar.gz ..
cd ..
rm -rf release
make clean
|
6d255aff8ef510df7095fdc0f08d4ca58b2e8122
|
[
"C",
"Shell"
] | 2 |
C
|
xenia-project/xell-reloaded
|
06a241528e9a70137317fb08f1f4d7cb58b0412f
|
fd02d76200ebb143efaf1c7eea65d4e14f4d9078
|
refs/heads/master
|
<repo_name>ashrafghanem/HammingCode<file_sep>/HammingCode/src/Main.java
import java.util.Scanner;
public class Main {
public static boolean checkBinary(String input) {
for (int i = 0; i < input.length(); i++) {
if (!Character.isDigit(input.charAt(i)) || (input.charAt(i) != '0' && input.charAt(i) != '1')) {
return false;
}
}
return true;
}
public static void findParityTerm(String input, int step, String[] code) {
String P = "";
int count = 0;
for (int i = step - 1; i < input.length();) {
if ((i + step) > input.length())
P += input.substring(i, input.length());
else
P += input.substring(i, i + step);
if (step == 1 || step == 2)
i += Math.pow(2, step);
else if (step == 4 || step == 8)
i += Math.pow(2, step - 1);
}
for (int j = 0; j < P.length(); j++) {
if (P.charAt(j) == '1')
count++;
}
if (count % 2 == 0) {
if (step == 1)
code[0] = "0";
else if (step == 2)
code[1] = "0";
else if (step == 4)
code[2] = "0";
else if (step == 8)
code[3] = "0";
} else {
if (step == 1)
code[0] = "1";
else if (step == 2)
code[1] = "1";
else if (step == 4)
code[2] = "1";
else if (step == 8)
code[3] = "1";
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the binary input sent data [8 bits]: ");
String input;
input = in.nextLine();
while (true) {
try {
if (input.length() != 8 || !checkBinary(input))
throw new Exception();
else
break;
} catch (Exception ex) {
System.out.println("Wrong Input Data");
input = in.nextLine();
}
}
input = "XX" + input.charAt(0) + "X" + input.substring(1, 4) + "X" + input.substring(4, 8);
String encodedData = "";
String code[] = new String[4];
findParityTerm(input, 1, code);
findParityTerm(input, 2, code);
findParityTerm(input, 4, code);
findParityTerm(input, 8, code);
System.out.print("Code is: ");
for (int i = 0; i < code.length; i++) {
System.out.print(code[i]);
}
int k = 0;
for (int j = 0; j < input.length(); j++) {
if (input.charAt(j) == 'X') {
encodedData += code[k++];
} else {
encodedData += input.charAt(j);
}
}
System.out.println("\nEncoded Data is: " + encodedData);
System.out.println("Enter the received data, bit by bit:");
String receivedData = "";
while (true) {
for (int i = 0; i < 12; i++) {
receivedData += in.next();
}
if (!checkBinary(receivedData)) {
System.out.println("Wrong Data inserted!\nTry again");
} else
break;
}
String checkCode[] = new String[4];
findParityTerm(receivedData, 1, checkCode);
findParityTerm(receivedData, 2, checkCode);
findParityTerm(receivedData, 4, checkCode);
findParityTerm(receivedData, 8, checkCode);
int countErrorPosition = 0;
for (int i = 0; i < 4; i++) {
if (checkCode[i] == "1") {
countErrorPosition += Math.pow(2, i);
}
}
int c = 0;
for (int i = 0; i < encodedData.length(); i++) {
if (encodedData.charAt(i) != receivedData.charAt(i)) {
c++;
}
}
if (c > 1) {
System.out.println("More than one error occured! \nCannot correct them!");
} else if (countErrorPosition == 0) {
System.out.println("No Error");
} else {
System.out.println("The Error occured at bit: " + countErrorPosition);
}
in.close();
}
}
|
080e2fcd18ff066660153d994bbb150253676184
|
[
"Java"
] | 1 |
Java
|
ashrafghanem/HammingCode
|
cc53fe0e71d910e4511a0708607fba30799213c7
|
6063dbbaf206ccf74f8a031fd2c9d01cbf9f0a7b
|
refs/heads/main
|
<repo_name>m5atib/Algoritgms<file_sep>/Josephus.cpp
#include <iostream>
using namespace std;
int josepgusProblem (int n);
int main(int argc, char *argv[])
{
cout<<josepgusProblem(40)<<endl;
return 0;
}
int josepgusProblem (int n){
if (n<=1) return 1;
if (n%2) return 2*josepgusProblem((n/2))+1;
else return 2*josepgusProblem(n/2)-1;
}<file_sep>/Selection.cpp
#include <iostream>
using namespace std;
bool selectionSort (int arr[] , int s);
bool swapp(int &a , int &b );
int Mini(int a, int b);
void printArr(int arr[] , int s);
int main(int argc, char *argv[])
{
int sizo = 8;
int arr[8]={50,2,5,4,10,9,9,7}; //is not Stable Sort
cout<<"be4 sort : ";
printArr(arr , sizo);
selectionSort(arr ,sizo);
cout<<"after sort : ";
printArr(arr , sizo);
return 0;
}
void printArr(int arr[] , int s){
for (int i=0; i<s ; i++){
cout<<' '<<arr[i];
}
cout<<endl;
}
bool swapp(int &a , int &b ){
int temp = a;
a=b;
b=temp;
return 1;
}
bool selectionSort (int arr[] , int s){
int min;
for (int i=0; i<s-1 ; i++){
min=i;
for (int j=i+1 ; j<s ; j++){
if (arr[j]<arr[min]){
min=j;
}
}
swapp(arr[i],arr[min]);
printArr(arr , s);
}
return 1;
}<file_sep>/interPS.cpp
#include <iostream>
using namespace std;
int interpolationSearch(int arr[], int n, int x)
{
int lo = 0, hi = (n - 1);
while (lo <= hi && x >= arr[lo] && x <= arr[hi])
{
if (lo == hi)
{
if (arr[lo] == x) return lo;
return -1;
}
int pos = lo + (((double)(hi - lo) /(arr[hi] - arr[lo])) * (x - arr[lo]));
cout<<"the lo ex = "<<lo<<" | the pos ex = "<<pos <<" | the hi ex = "<<hi<<endl;
if (arr[pos] == x)
return pos;
if (arr[pos] < x)
lo = pos + 1;
else
hi = pos - 1;
}
return -1;
}
int main()
{
int arr[] = {10, 12, 13, 16, 18, 19, 20,24 ,25,30, 35, 40};
int n = sizeof(arr)/sizeof(arr[0]);
int x = 30;
int index = interpolationSearch(arr, n, x);
if (index != -1)
cout << "Element found at index " << index<<endl;
else
cout << "Element not found.\n";
return 0;
}<file_sep>/combination.cpp
#include <iostream>
using namespace std;
void Combination (int a [], int reqLen, int start, int currLen, bool check [], int len)
{
if (currLen> reqLen) return;
else if (currLen == reqLen)
{
cout << "\t";
for (int i = 0; i <len; i ++)
{
if (check [i] == true)
cout << a [i] << "" ;
}
cout << "\n";
return;
}
if (start == len) return;
check [start] = true;
Combination (a, reqLen, start + 1, currLen + 1, check, len);
check [start] = false;
Combination (a, reqLen, start + 1, currLen, check, len);
}
int main ()
{
int i;
const int n = 4;
bool check [n];
int arr [n];
for (i = 0;i <n; i++)
{
arr [i] = i + 1;
check [i] = 0;
}
for(i = 1; i <= n; i++)
{
cout << "\nThe combination of length\t" << i << "\tfor the given array set: \n";
Combination (arr, i, 0, 0, check, n);
}
return 0;}<file_sep>/RussianMul.cpp
#include <iostream>
using namespace std;
int russianPeasant( int n, int m) ;
int RP (int x , int y);
int main() {
cout << RP(10, 20) << endl;
cout << russianPeasant(7, 6) << endl;
return 0;
}
int russianPeasant( int n, int m) {
int result = 0;
while (m > 0) {
if (m & 1)
result = result + n;
n = n << 1;
m = m >> 1;
}
return result;
}
int RP (int n , int m){
int res = 0 ;
while (n>0){
if (n%2)
res+=m;
n/=2;
m*=2;
}
return res;
}<file_sep>/GCD p3.cpp
#include <iostream>
#include <math.h>
#include <list>
using namespace std;
int GCD_me (int m , int n);
int min_me(int x, int y);
int *prime_facto(int arr[], int n , int Out[], int &si);
void fill_meArr (int a[] ,int p);
void print_arr (int *a , int n);
int main(int argc, char *argv[])
{
cout<<"Hello, Wolrd!"<<endl;
int Int_array[26] ;
fill_meArr(Int_array,25);
print_arr(Int_array , 25);
int *ar = prime_facto(Int_array ,25);
print_arr(ar , 9);
return 0;
}
void print_arr (int *a , int n){
cout<<"Array = [ " ;
for (int i=0; i<=n ; i++){
cout<<*a<<' ';
a++;
}
cout<<" ] "<<endl;
}
void fill_meArr (int a[] ,int p){
for (int i=0; i<=p ;i++){
a[i] = i;
}
a[1]=0;
}
int *prime_facto(int arr[], int n , int Out[], int &si){
for (int i=2 ; i<=sqrt(n) ; i++){
int k = i*i;
while (k<=n){
arr[k] = 0;
k+=i;
}
}
int countOfl = 0;
for (int i=2 ; i<n ; i++){
if (arr[i]!=0){
countOfl++;
}
}
cout<<countOfl<<"this is number of l"<<endl;
int L[countOfl];
int c=0;
for (int i=0 ; i<=n ; i++)
{
if (arr[i]!=0){
L[c] = arr[i];
c++;
}
}
return ;
}
int GCD_me (int m , int n){
}
int min_me(int x, int y){
if (x<y)return x;
else return y;
}<file_sep>/GenrationSubsets.cpp
// C++ program to find all subsets of given set. Any
// repeated subset is considered only once in the output
#include<math.h>
#include <iostream>
using namespace std;
void allPossibleSubset(int arr[], int n)
{
int count = pow(2, n);
for (int i = 0; i < count; i++) {
cout<<"{";
for (int j = 0; j < n; j++) {
if ((i & (1 << j)) != 0)
cout << arr[j] << " ";
}
cout << " }\n";
}
}
int main()
{
int n;
cout << "Enter size of the set\n";
cin >> n;
int arr[n];
cout << "Enter Elements of the set\n";
for (int i = 0; i < n; i++)
cin >> arr[i];
allPossibleSubset(arr, n);
return 0;
}<file_sep>/searchOfptern.cpp
#include <iostream>
using namespace std;
void naiveSeacrh(char str[] , int m , char ptn[] , int n);
int main(int argc, char *argv[])
{
char str [24] = {'A','G','C','G','G','A','T','C','A','G','C','G','G','A','G','T','A','A','A','A','A','A','A','A'};
char ptr [5] = {'A','G','C','G','G'};
naiveSeacrh(str,24,ptr,5);
return 0;
}
void naiveSeacrh(char str[] , int m , char ptn[] , int n){
int k;
for (int i=0; i<=m-n ; i++){
k=0;
while (k<n && str[i+k] == ptn[k])
k++;
if (k==n)
cout<<"excit at postion "<< i <<endl;
}
}<file_sep>/Sum and Exp d&c.cpp
#include <iostream>
using namespace std;
int sum(int A[],int L, int R)
{
if(L==R) return A[L];
if(L<R)
{int mid=(L+R)/2;
int Lsum=sum(A,L,mid);
int Rsum=sum(A,mid+1,R);
return Lsum+Rsum;
}
}
int exp(int a,int l, int r)
{
if(r==0)return 1;
if(r==1)return a;
if(l==r)return a;
if(l<r)
{
int mid=(l+r)/2;
int pl=exp(a,l,mid);
int pr=exp(a,mid+1,r);
return pl*pr;
}
}
int main(int argc, char *argv[])
{
int A [8] = {1,6,3,8,5,2,5,9};
cout<<sum(A , 0 , 7)<<endl;
return 0;
}<file_sep>/stringMatching.cpp
#include <iostream>
using namespace std;
bool StringMatch(char Str[] , int sStr , char Ptn[] , int sPtn);
void printArr(char arr[] , int s){
for (int i=0; i<s ; i++){
cout<<' '<<arr[i];
}
cout<<endl;
}
int main(int argc, char *argv[])
{
char strM[12] = {'T','A','B','C','D','F','G','A','B','C','D','E'};
char ptnM[4] = {'A','B','C','D'};
cout<<*ptnM<<endl;
cout<<StringMatch(strM,12,ptnM,4)<<endl;
return 0;
}
bool StringMatch(char Str[] , int sStr , char Ptn[] , int sPtn){
bool f = 0;
cout<<sStr-sPtn<<endl;
for (int i=0; i<sStr-sPtn ; i++){
for (int j=0 ; j<sPtn ; j++){
if (Str[i+j] != Ptn[j])
{
f=0;
break;
}
else
{
f=1;
}
}
cout<<endl;
if (f==1) cout<<"Match At i = "<<i<<endl;;
}
return f;
}<file_sep>/Euclid's GCD.cpp
#include <iostream>
using namespace std;
int EGCDR(int m , int n);
int EGCD(int m, int n);
int main(int argc, char *argv[])
{
int m , n ;
m=60; n=24;
int re = EGCDR(60,24);
cout<<"EGCD( "<<m<<" , "<<n<<" ) = "<<re<<endl;
return 0;
}
int EGCD(int m, int n){
if (m<=0) return -1;
if (n<=0) return m;
int rem;
while (n>0){
rem=m%n;
m=n;
n = rem;
}
return m;
}
int EGCDR(int m , int n) {
if (m<=0) return -1;
if (n<=0) return m;
return (EGCD (n,m%n));
}<file_sep>/searchOfK.cpp
#include <iostream>
using namespace std;
bool Ksearch (int arr[] , int Left ,int Right , int k);
int main(int argc, char *argv[])
{
return 0;
}
int Ksearch (int arr[] , int Len, int Left ,int Right , int k){
if (Left < 0) return -1;
if (Right => Len) return -1;
if (arr[Left] == k) return Left;
else
return Ksearch (arr , Len, 0 , (Len-1)/2 , k );
if (arr[Right] == k) return Right;
else
return Ksearch (arr , Len , Len/2 , Len ,k );
}<file_sep>/BubbleSort.cpp
#include <iostream>
using namespace std;
bool Bubble(int A[],int n);
void printArr(int arr[] , int s){
for (int i=0; i<s ; i++){
cout<<' '<<arr[i];
}
cout<<endl;
}
bool swapp(int &a , int &b ){
int temp = a;
a=b;
b=temp;
return 1;
}
int main(int argc, char *argv[])
{
int sizo = 8;
int A[8]={50,2,5,4,10,9,9,7};
cout<<"be4 sort :\t";
printArr(A , sizo);
Bubble(A , 8);
cout<<"after sort :\t";
printArr(A , sizo);
return 0;
}
bool Bubble(int A[],int n) {
for(int i=0;i<n-1;i++)
{
for(int j=0;j<n-1-i;j++)
if(A[j+1]<A[j])
swapp(A[j+1],A[j]) ;
printArr(A , n);
}
return 1;
}<file_sep>/GCD p2.cpp
#include <iostream>
using namespace std;
int GCDCIC(int m,int n);
int minim (int x , int y);
int main(int argc, char *argv[])
{
cout<<"hello"<<endl;
cout<<GCDCIC(60,24)<<endl;
return 0;
}
int GCDCIC(int m,int n){
if ((m<=0)||(n<=0)) return -1;
int t=minim(m,n);
while (!((n%t==0)&&(m%t==0)))
t-=1;
return t;
}
int minim (int x , int y){
if (x<=y){
return x;
}
else {
return y;
}
}<file_sep>/comLPS.cpp
#include <iostream>
#include <string.h>
using namespace std;
void clps (char ptn[] , int n , int LPS[]);
void kmpSearch (char ptn[] , char txt[] ,int n , int m);
void printArr(int arr[] , int s){
for (int i=0; i<s ; i++){
cout<<' '<<arr[i];
}
cout<<endl;
}
int main(int argc, char *argv[])
{
char ptn [8]={'A','A','B','A','A','A','B','A'};
//AABAAABA
char txt[17] ={'A','B','A','B','A','B','C','A','B','A','B','A','B','A','C','B','C'};
kmpSearch (ptn , txt , 17,8);
return 0;
}
void clps (char ptn[] , int n , int LPS[]){
int i=1 , j=0;
LPS[0]=0;
while(i<n){
if (ptn[i] == ptn[j]){
j++;
LPS[i] = j;
i++;
}
else{
if (j!=0){
j = LPS[j-1];
}
else{
LPS[i] = 0;
i++;
}
}
}
}
void kmpSearch (char ptn[] , char txt[] , int n , int m){
int lps[m];
clps (ptn , m , lps);
cout<<"LPS = "; printArr(lps , m);
int i=0 , j=0;
while (i<n){
//cout<<"i = "<<i << " , j= "<<j <<endl;
if (ptn[i] == txt[j]){
j++;
i++;
}
if (j==m){
cout<<"founded at pos = "<<i-j<<endl;
j=lps[j-1];
}
else if ((i<n) && (ptn[i]!=txt[j])){
if (j!=0){
j = lps[j-1];
}
else{
i++;
}
}
}
}<file_sep>/allsubs.cpp
#include <iostream>
using namespace std;
void printArr(int arr[] , int s){
for (int i=0; i<s ; i++){
cout<<' '<<arr[i];
}
cout<<endl;
}
void allsubs(int *A, int len, int *B, int len2, int index)
{
if (index >= len)
{ for (int i = 0; i < len2; ++i)
{ cout<< B[i]; }
cout<<"\n"; return;
}
allsubs(A, len, B, len2, index+1);
B[len2] = A[index];
allsubs(A, len, B, len2+1, index+1);
}
int main(int argc, char *argv[])
{
int b[4] = {
1,2,3,4
};
int a[4]={
1,2,3,4
};
allsubs(a,4,b,4,0);
//printArr(b,16);
return 0;
}<file_sep>/Insertion.cpp
#include <iostream>
using namespace std;
bool insertionSort (int arr[] , int s);
bool swapp(int &a , int &b );
int Mini(int a, int b);
void printArr(int arr[] , int s);
bool InsSort (int arr[] , int s);
int main(int argc, char *argv[])
{
int sizo = 8;
int arr[8]={50,3,5,4,10,9,9,7};
printArr(arr , sizo);
cout<<"--------------------"<<endl;
InsSort(arr ,sizo);
return 0;
}
void printArr(int arr[] , int s){
for (int i=0; i<s ; i++){
cout<<' '<<arr[i];
}
cout<<endl;
}
bool swapp(int &a , int &b ){
int temp = a;
a=b;
b=temp;
return 1;
}
int Mini(int a, int b){
if (a<b){
return a;
}
else if (b<a) return b;
}
bool InsSort (int arr[] , int s){
for (int i=1; i<s ; i++){
for (int j=i ; j>0 ; j--){
if (arr[j-1]>arr[j])
swapp(arr[j-1],arr[j]);
else
break;
}
printArr(arr , s);
}
return 1;
}
bool insertionSort (int arr[] , int s){
int posR,BaseItemPos;
for (int i=0; i<s-1 ; i++){
if (arr[i+1]<arr[i]){
swapp(arr[i],arr[i+1]);
posR = i-1;
BaseItemPos=i;
while (posR>0){
if (arr[BaseItemPos]<arr[posR]){
swapp(arr[BaseItemPos],arr[posR]);
BaseItemPos = posR ;
}
posR--;
}
}
printArr(arr , 8);
}
return 1;
}
<file_sep>/MergeSor D&C.cpp
#include <iostream>
using namespace std;
void printArray (int arr[] , int n);
void mergeSort (int arr [], int l, int r);
void merge (int arr [], int l, int m, int r);
int main(int argc, char *argv[])
{
int arr[9] = { 7, 2, 9, 3, 1, 63, 7, 8, 4 };
cout<<"My Array : \n";
printArray(arr , 9);
mergeSort(arr , 0 , 8);
// printArray(arr , 9);
return 0;
}
void mergeSort (int arr [], int l, int r)
{
if (l >= r) return;
int m = (l + r-1) / 2;
mergeSort (arr, l, m);
mergeSort (arr, m + 1, r);
merge (arr, l, m, r);
}
void merge (int arr [], int l, int m, int r)
{
int n1 = m - l + 1;
int n2 = r - m;
int L [n1], R [n2];
for (int i = 0; i <n1; i ++)
L [i] = arr [l + i];
for (int j = 0; j <n2; j ++)
R [j] = arr [m + 1 + j];
int i = 0, j = 0;
int k = l;
while (i <n1 && j <n2) {
if (L [i] <= R [j]) {
arr [k] = L [i];
i ++;
}
else {
arr [k] = R [j];
j ++;
}
k ++;
}
while (i <n1) {
arr [k] = L [i];
i ++;
k ++;
}
while (j <n2) {
arr [k] = R [j];
j ++;
k ++;
}
printArray(arr , 9);
}
void printArray (int arr[] , int n)
{
for (int i = 0 ; i < n ; i++)
cout<<" "<<arr[i];
cout<<endl;
}<file_sep>/BFmode.cpp
#include <iostream>
using namespace std;
int BFmode (int arr[] , int n){
int x[n] ;
for (int i=0 ; i<n ; i++)
x[i ] = 0;
for (int i=0; i<n ; i++){
x[i]+=1;
for (int j=i+0; j<n ; j++){
if (arr[i]==arr[j]){
x[i]+=1;
}
}
}
int m=x[0] , pos = 0;
for (int i=1 ; i<n ; i++){
if (x[i]>m){
m=x[i];
pos = i;
}
}
return arr[pos];
}
int main(int argc, char *argv[])
{
int a[10] = {
4,8,7,6,4,2,4,4,1,2
};
cout<<BFmode(a , 10)<<endl;
return 0;
}<file_sep>/QuckSortPartiition.cpp
// A full c++ quicksort algorithm no bs
// quicksort in code
#include <iostream>
using namespace std;
void quicksort(int number[],int first,int last);
void QuickSort(int arr[], int start, int end);
int Partition(int arr[], int start, int end);
void SwapArrMem(int arr[], int a, int b);
void printArr(int arr[], int n);
int main()
{
int arr[8] = {15,13,10,19,18,3,14,16};
//int arr [9]= { 6,1,10, 9, 7, 4, 8, 2, 15 };
cout << endl << "The sorted numbers are:" << endl << endl;
quicksort(arr, 0, 7);
}
void QuickSort(int arr[], int start, int end)
{
if (start >= end) return;
int index = Partition(arr, start, end);
QuickSort(arr, start, index - 1);
QuickSort(arr, index + 1, end);
}
int Partition(int arr[], int start, int end)
{
int pivotindex = start;
int pivotvalue = arr[end];
for (int i = start; i < end; i++)
{
if (arr[i] < pivotvalue)
{
SwapArrMem(arr, i, pivotindex);
pivotindex++;
}
}
SwapArrMem(arr, pivotindex, end);
cout<<" j = "<<pivotindex <<" | ";
printArr(arr , 8);
return pivotindex;
}
void SwapArrMem(int arr[], int a, int b)
{
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
void printArr(int arr[], int n){
for (int i = 0; i < n; i++)
{
cout << arr[i] <<" ";
}
cout<<endl;
}
void quicksort(int number[],int first,int last){
int i, j, pivot, temp;
if(first<last){
pivot=first;
cout<<"pivot = "<<pivot<<endl;
i=first;
j=last;
while(i<j){
while(number[i]<=number[pivot]&&i<last)
i++;
while(number[j]>number[pivot])
j--;
if(i<j){
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
temp=number[pivot];
number[pivot]=number[j];
number[j]=temp;
cout<<"j = "<<j<<" , i = "<<i<<" |";
printArr(number , 8);
quicksort(number,first,j-1);
quicksort(number,j+1,last);
}
} <file_sep>/PresortMode.cpp
#include <iostream>
using namespace std;
int presortMode (int a[] , int n){
int i=0;
int modeFreq = 0 , runlen = 0 , runval=0 , modeval = -1;
while (i<n-1){
runlen=1; runval = a[i];
while (((i+runlen)<(n-1)) && (a[i+runlen]==runval)){
runlen+=1;
}
if (runlen > modeFreq){
modeFreq = runlen ; modeval=runval;
}
i+=runlen;
}
return modeval;
}
int main(int argc, char *argv[])
{
int arr[10]={1,2,2,4,4,4,4,6,7,8};
cout<<presortMode(arr , 10)<<endl;
return 0;
}
|
1037a39f6ba11c8394780391c7bdfdecee73574d
|
[
"C++"
] | 21 |
C++
|
m5atib/Algoritgms
|
9f955c3486403b07229cbd0a1db3030e6ed0b0f1
|
83a4dc9e011e145a20c7d54c056f2dd4450a50db
|
refs/heads/master
|
<file_sep>from django.http import HttpResponse
from django.shortcuts import render
from django.views import View
from upload.models import Shop
class UploadView(View):
def get(self,request):
return render(request,'upload.html')
def post(self,request):
# 获取文字字符串部分信息
desc = request.POST.get('desc')
name = request.POST.get('name')
# 获取文件部分信息
img = request.FILES.get('img')
# request.FILES.getlist('img')
shop = Shop(desc=desc,name=name,img=img)
shop.save()
return HttpResponse(f"<img src='http://127.0.0.1:8000/media/{shop.img}'width='500'>")
<file_sep>import os
from random import random
from django.db import models
from django.core.files.storage import FileSystemStorage
from datetime import datetime
# 图片名字+图片格式
class ImageFileStorage(FileSystemStorage):
# /upload_to/img/图片的名字
def _save(self, name, content):
old_name = name.split('/')[-1]
# 图片后缀名
suffix_name = old_name.split('.')[-1]
# IMG_201811201414
prefix_name = f"IMG_{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}{str(random.randint(100000,999999))}"
image_path = os.path.dirname(name)
name = os.path.join(image_path,f'{prefix_name}.{suffix_name}')
return super()._save(name,content)
class Shop(models.Model):
name = models.CharField(max_length=64)
desc = models.CharField(max_length=100)
# 框架自动配置了media
# img = models.ImageField(upload_to='shop/img/',storage=ImageFileStorage)
# img = models.ImageField(upload_to='shop/%Y/%m/%d/')
class Meta:
db_table = 'shop'
class Img(models.Model):
img = models.ImageField(upload_to='shop/img/', storage=ImageFileStorage)
# 1 表示商品图片
# 2 表示用户图片
type = models.SmallIntegerField()
name = models.ForeignKey(Shop,on_delete=models.CASCADE)
name = models.ForeignKey(Shop,on_delete=models.CASCADE)<file_sep>from django.conf.urls import url
from django.contrib import admin
from upload import views
urlpatterns = [
url('admin/', admin.site.urls),
url('upload/',views.UploadView.as_view()),
# 配置测试环境下上传文件路径
]
|
c888c2ac804d006282abc67520a09403e3ba2143
|
[
"Python"
] | 3 |
Python
|
zhujixiang1997/django_file_cache
|
c381e8bd1ed676380ea57c2d3b3a6fac343044e8
|
d66cc8d03fa27097192a92f30d3575cc768b16c7
|
refs/heads/master
|
<repo_name>iricigor/CS.Hello<file_sep>/README.md
# CS.Hello
CSharp Hello World
<file_sep>/Program.cs
using System;
using static Logger;
namespace CS.Hello
{
class Program {
static void Main(string[] args) {
// prepare loggers
var log1 = new Logger();
log1.AddScreen();
log1.AddFile("C:\\temp\\CSharp1.log");
log1.SetAutoRotate(500);
var log2 = new Logger("C:\\temp\\CSharp2.log",200);
var log3 = new Logger();
log3.AddScreen();
// main code
// Console.WriteLine("Hello World!");
log1.WriteLine("Hello world from logger!");
log2.WriteLine("This goes to file only");
log3.WriteLine("This goes to screen only");
log3.WriteLine("This has extended timestamp","G");
// finish
log1.Rotate(200);
}
}
}
<file_sep>/Logger.cs
using System;
using System.IO;
class Logger {
//
// properties
//
private string FileName;
private bool Screen = false;
private int AutoRotateSize = 0;
//
// Constructors
//
public Logger () {}
public Logger (string FileName, int AutoRotateSize = 0) {
this.FileName = FileName;
this.AutoRotateSize = AutoRotateSize;
}
//
// configuration methods
//
public void AddFile(string FileName) {
this.FileName = FileName;
// TODO: test if file exists, if not create it with some default text?
}
public void AddScreen() {
this.Screen = true;
}
public void SetAutoRotate(int MaxSize = 1000000) {
this.AutoRotateSize = MaxSize;
}
//
// main write method
//
public void WriteLine(string Message, string TimeStampFormat = "T") {
if (this.AutoRotateSize > 0)
this.Rotate(AutoRotateSize);
string ExtendedMessage = DateTime.Now.ToString(TimeStampFormat) + " " + Message;
if (this.Screen) {
Console.WriteLine(ExtendedMessage);
}
if (this.FileName != null) {
var logWriter = new StreamWriter(this.FileName, append: true);
logWriter.WriteLine(ExtendedMessage);
logWriter.Dispose();
}
}
//
// log rotation
//
public void Rotate(int MaxSize = 1000000) {
if (this.FileName == null)
return;
if (!File.Exists(this.FileName))
return;
var fileInfo = new FileInfo(this.FileName);
if (fileInfo.Length < MaxSize)
return;
var rotatedPath = this.FileName + DateTime.Now.ToString(".yyyy-MM-dd-hhmmss");;
File.Move(this.FileName, rotatedPath);
File.Create(this.FileName);
// TODO: implement zipping, retention
}
}
|
97586938720f73add539bd2df0105a3af19ef751
|
[
"Markdown",
"C#"
] | 3 |
Markdown
|
iricigor/CS.Hello
|
19ce8737dd67000fdae8b2b60420b7dd2a9fae00
|
d3d99a0156e7b9275e6d466e08c51a64818cb59b
|
refs/heads/master
|
<file_sep>import java.util.*;
import java.util.Scanner;
public class NeedlmanWunsch {
private static final int d = -8;
private static Blosum50 blosumMatrix;
public static void main(String[] args) {
blosumMatrix = new Blosum50("src/blosum50.txt");
Scanner sc = new Scanner(System.in);
String S1, S2;
S1 = sc.nextLine();
S2 = sc.nextLine();
String[] S1_arr = new String[S1.length()];
for (int i = 0; i < S1.length(); ++i)
S1_arr[i] = S1.substring(i, i+1);
String[] S2_arr = new String[S2.length()];
for (int j = 0; j < S2.length(); ++j)
S2_arr[j] = S2.substring(j, j+1);
int[][] matrix = new int[S2.length() + 1][S1.length() + 1];
for (int i = 0; i < S2.length() + 1; ++i)
matrix[i][0] = i*d;
for (int j = 0; j < S1.length() + 1; ++j)
matrix[0][j] = j*d;
for (int i = 1; i < S2.length() + 1; ++i) {
for (int j = 1; j < S1.length() + 1; ++j) {
int diagSum = matrix[i - 1][j - 1] + blosumMatrix.getValue(S1_arr[j - 1], S2_arr[i - 1]);
int rightSide = Math.max(matrix[i - 1][j] + d, matrix[i][j - 1] + d);
matrix[i][j] = Math.max(diagSum, rightSide);
}
}
System.out.println("Output the matrix of coefficients");
for (int[] row : matrix)
System.out.println(Arrays.toString(row));
StringBuilder AlignmentA = new StringBuilder();
StringBuilder AlignmentB = new StringBuilder();
int first_sequence_length = S2.length();
int second_sequence_length = S1.length();
while ( (first_sequence_length > 0) && (second_sequence_length > 0) ) {
int score = matrix[first_sequence_length][second_sequence_length];
int scoreDiag = matrix[first_sequence_length - 1][second_sequence_length - 1];
int scoreUp = matrix[first_sequence_length][second_sequence_length - 1];
int scoreLeft = matrix[first_sequence_length - 1][second_sequence_length];
if (score == (scoreDiag + blosumMatrix.getValue(S2_arr[first_sequence_length - 1],
S1_arr[second_sequence_length - 1]))) {
AlignmentA.append(S2_arr[first_sequence_length - 1]);
AlignmentB.append(S1_arr[second_sequence_length - 1]);
first_sequence_length--;
second_sequence_length--;
} else if (score == scoreLeft + d) {
AlignmentA.append(S2_arr[first_sequence_length - 1]);
AlignmentB.append("-");
first_sequence_length--;
} else if (score == scoreUp + d) {
AlignmentA.append("-");
AlignmentB.append(S1_arr[second_sequence_length - 1]);
second_sequence_length--;
}
}
while (first_sequence_length > 0) {
AlignmentA.append(S2_arr[first_sequence_length - 1]);
AlignmentB.append("-");
first_sequence_length--;
}
while (second_sequence_length > 0) {
AlignmentA.append("-");
AlignmentB.append(S1_arr[second_sequence_length - 1]);
second_sequence_length--;
}
System.out.println("\nGlobal aligned sequences");
System.out.println(AlignmentB.reverse().toString());
System.out.println(AlignmentA.reverse().toString());
}
}
<file_sep># bioinformatics-labs
University assignments for Bioinformatics course: algorithms
|
ffe42ce7810ded21f61490f6e487376807653bba
|
[
"Markdown",
"Java"
] | 2 |
Java
|
hamsternik/bioinformatic-course-labs
|
1b031bdf8539f664159ac31dba504fcb11beaf01
|
f9b0cfb567eb745ddcaa63a03c996d729f57c7f9
|
refs/heads/master
|
<file_sep># Python
Simple encryption programs with Python
Author: <NAME>
This repository includes:
-> Calculating Frequency Domain
-> Shift cipher, Vigenere cipher, LFSR cipher
-> Simple Data Encryption Standart algorithm [SDES]
-> Block cipher mode algorithm [CBC]
<file_sep># Created by <NAME> 19040186
import inspect
import matplotlib.pyplot as plt
# ------------ Functions -------------
def char_freq(string):
chars = {}
for s in string:
if s in chars.keys():
chars[s] += 1
else:
chars[s] = 1
return chars
def char_freq_file(file):
fd = open(file, 'r') # opens a file for reading
data = fd.read() # reads data
# print("\nData from file: ", data)
freq = char_freq(data)
return freq
def histogram(dict_freq):
plt.bar(list(dict_freq.keys()), dict_freq.values(), 0.05, color='g')
plt.grid(True)
plt.show()
return
# ----------- Main code ----------------
str_freq = char_freq('aaabbbccc')
file_freq = char_freq_file('data.txt')
print(str_freq)
print(file_freq)
histogram(file_freq)
<file_sep>import random
from string import ascii_uppercase as letters
# ---------- Functions ---------
# function that cretes 26x26 table (matrix)
def create_table():
tbl = [] # empty list created
for i in range(26): # appends emty list in each list item (26)
tbl.append([]) # 26x26 matrix is created
for row in range(26):
for col in range(26):
if(row + 65) + col > 90: # if number exceeds 90 [char(90) - Z], we will write from A again
tbl[row].append(chr((row + 65) + col - 26)) # chr(65) - A chr(90) - Z
else:
tbl[row].append(chr(row + 65 + col))
#for row in tbl:
# for col in row:
# print(col, end=' ')
# print(end='\n')
return tbl
# function that generates the key
def vigenere_genkey(n):
return ''.join(random.choice(letters) for i in range(n))
# function that maps the key with the message (makes the same lenght)
def map_the_key(key, msg):
key_map = '' # mapped key to the message
counter = 0 # counter
for i in range(len(msg)): # mapping the key
if ord(msg[i]) == 32: # if message contains space, add space to key_map
key_map += ' '
else:
if counter < len(key): # for e.g.: message is 'hello world' key is 'KEY', than
key_map += key[counter] # key_map will be 'KEYKE YKEYK'
counter += 1
else:
counter = 0
key_map += key[counter]
counter +=1
return key_map
# encryption function
def vigenere_encrypt(key, msg):
temp = msg.upper() # make every letter uppercase
ctx = '' # variable for encoded message
mapped_key = map_the_key(key, temp) # get mapped key
for i in range(len(temp)):
if ord(temp[i]) == 32: # if it's a space in the message
ctx += ' '
elif ord(temp[i]) < 65 | ord(temp[i]) > 90: # if it's a special character ',./*-+\..'
ctx += temp[i]
else:
row = ord(mapped_key[i]) - 65
col = ord(temp[i]) - 65
ctx += table[row][col]
return ctx
# decryption function
def vigenere_decrypt(key, ctx):
pp = '' # variable for encoded message
mapped_key = map_the_key(key, ctx) # get mapped key
for i in range(len(ctx)):
if ord(ctx[i]) == 32: # if it's a space in the message
pp += ' '
elif ord(ctx[i]) < 65 | ord(ctx[i]) > 90:
pp += ctx[i]
else:
idx = ord(ctx[i]) - ord(mapped_key[i])
if idx < 0:
idx += 26
pp += table[0][idx]
return pp
# --------- Main -------------
table = create_table()
key_lenght = 4
msg = '/-hello.world**'
key = vigenere_genkey(key_lenght)
C = vigenere_encrypt(key, msg)
P = vigenere_decrypt(key, C)
print('Key: ' + key + '\nOriginal message: ' + msg + '\nEncrypted message: |' + C + '|\nDecrypted message: |' + P + '|')<file_sep>from string import ascii_lowercase as lower
#from string import ascii_uppercase as upper
# -------- Functions ------------
# function that encrypts the given message
def shift_encrypt(key, msg):
temp = msg.lower()
ctx_indexes = [] # empty list for mod26 indexes
ctx = '' # emty string for ciphertext
for s in temp:
if s in table:
idx = get_mod26(key, table[s], 'e') # get mo26 values
ctx_indexes.append(idx) # add mod23 values to the list
else:
ctx_indexes.append(s)
# encrypt the message
for i in ctx_indexes:
if i in table.values():
ctx += list(table.keys())[list(table.values()).index(i)] # get key from dict by it's value and add it to the string
else:
ctx += i
return ctx
# function that decrypts the encrypted message
def shift_decrypt(key, ctx):
temp = ctx
pp_indexes = [] # empty list for mod26 indexes
pp = '' # emty string for decrypted message
for s in temp:
if s in table:
idx = get_mod26(key, table[s], 'd') # get mo26 values
pp_indexes.append(idx) # add mod23 values to the list
else:
pp_indexes.append(s)
# decrypt the ciphertext
for i in pp_indexes:
if i in table.values():
pp += list(table.keys())[list(table.values()).index(i)] # get key from dict by it's value and add it to the string
else:
pp += i
return pp
# funtion that creates a dictionary
def create_dictionary():
temp = {}
for i in lower:
temp[i] = len(temp)
return temp
# function that returns mod26 number
def get_mod26(key, number, method):
temp = 0
if method == 'e':
temp = (number + key) % 26
if method == 'd':
temp = number - key
if temp < 0:
temp += 26
return temp
# --------- Main code ----------
table = create_dictionary()
key = 3
msg = "a.b,c**"
C = shift_encrypt(key, msg)
P = shift_decrypt(key, C)
print('Key: ' + str(key) + '\nOriginal message: ' + msg + '\nEncrypted message: ' + C + '\nDecrypted message: ' + P)<file_sep>import random
# --------- Functions -----------
# key generation function (9bit)
def cbc_genkey():
key = ''
for i in range(9):
key += str(random.randint(0,1))
return key
# function for making 8bit from 9bit key
def key_8bit(key, n):
new_key = ''
idx = n
for i in range(8):
if idx == len(key)+1:
idx = 1
new_key += key[idx-1]
idx += 1
return new_key
# simple DES encryption function
def sdes_encrypt(key, pblock):
ctx = pblock
for i in range(3):
# copy L and R sides (both 6bits)
L = ctx[:6]
R = ctx[6:]
# regenerate key (8 bit)
k2 = key_8bit(key, i+2) # i+2 = 2, 3, 4 (key row number)
# go to function and expand R 6bit side to 8bit lenght message
Rf = R[:2] + R[3] + R[2] + R[3] + R[2] + R[4:]
# temp - for storing R(8 bit) side xor key(idx)
temp = ''
for i in range(len(Rf)):
temp += str(int(Rf[i]) ^ int(k2[i])) # xor operation
# spliting answer into 2x4bits
L_4bit = temp[:4] # used for 4bit left side in function
R_4bit = temp[4:] # used for 4bit right side in function
# taking values from SBoxes and joining them into 1 6bit string
fresult = get_sbox_value(L_4bit, 1)
fresult += get_sbox_value(R_4bit, 2)
# function output xor L side
tt = ''
for i in range(len(fresult)):
tt += str(int(L[i]) ^ int(fresult[i]))
# final ciphertext of the round
# in this case R is new L and tt is new R
ctx = R + tt
return ctx
# simple DES decryption function
def sdes_decrypt(key, cblock):
pp = cblock
for i in range(3):
# we know that Ln = Rn-1 (present L block is past R block)
Rpast = pp[:6]
# we need to make 8bit key again
k2 = key_8bit(key, 4-i)
# the steps are the same like in encryption, we need to get the function value
# we need to make R side 8bit
Rf = Rpast[:2] + Rpast[3] + Rpast[2] + Rpast[3] + Rpast[2] + Rpast[4:]
# now we have to use xor for k2 and Rf
temp = ''
for i in range(len(Rf)):
temp += str(int(Rf[i]) ^ int(k2[i]))
# spliting answer into 2x4bits
L_4bit = temp[:4] # used for 4bit left side in function
R_4bit = temp[4:] # used for 4bit right side in function
# now we need to take values from SBoxes and merge them into 6bit message
fresult = get_sbox_value(L_4bit, 1)
fresult += get_sbox_value(R_4bit, 2)
# now we need to take present R block
Rpresent = pp[6:]
# let's find the past L block by using xor (present R block xor function result)
Lpast = ''
for i in range(len(Rpresent)):
Lpast += str(int(Rpresent[i]) ^ int(fresult[i]))
pp = Lpast + Rpast
return pp
# function for getting SBoxes values
def get_sbox_value(value, box_idx):
result = '' # empty string for 3bit result
s1 = [['101', '010', '001', '110', '011', '100', '111', '000'],
['001', '100', '110', '010', '000', '111', '101', '011']]
s2 = [['100', '000', '110', '101', '111', '001', '011', '010'],
['101', '011', '000', '111', '110', '010', '001', '100']]
if box_idx == 1:
sbox = s1
else:
sbox = s2
# Sbox1
if value[0] == '0':
#take 1st row
if value[1:] == '000': # col: 0
result += sbox[0][0]
elif value[1:] == '001': # col: 1
result += sbox[0][1]
elif value[1:] == '010': # col: 2
result += sbox[0][2]
elif value[1:] == '011': # col: 3
result += sbox[0][3]
elif value[1:] == '100': # col: 4
result += sbox[0][4]
elif value[1:] == '101': # col: 5
result += sbox[0][5]
elif value[1:] == '110': # col: 6
result += sbox[0][6]
elif value[1:] == '111': # col: 7
result += sbox[0][7]
else:
#take 2nd row
if value[1:] == '000': # col: 0
result += sbox[1][0]
elif value[1:] == '001': # col: 1
result += sbox[1][1]
elif value[1:] == '010': # col: 2
result += sbox[1][2]
elif value[1:] == '011': # col: 3
result += sbox[1][3]
elif value[1:] == '100': # col: 4
result += sbox[1][4]
elif value[1:] == '101': # col: 5
result += sbox[1][5]
elif value[1:] == '110': # col: 6
result += sbox[1][6]
elif value[1:] == '111': # col: 7
result += sbox[1][7]
return result
# Cipher Block Chaining option encryption
def cbc_encrypt(keybits, ivbits, plainbits):
cblock = []
ctx = ''
times = int(len(plainbits) / 12) # number of 12bits plaintext blocks
for i in range(times): # encryption looop
temp = '' # variable for storing ciphertext temporary
pblock = plainbits[12*i:12*i+12] # take needed plaintext block
if(i == 0): # if it's the first cycle, we need ivbits xor plaintext block
for j in range(12):
temp += str(int(pblock[j]) ^ int(ivbits[j])) # xor operation
cblock.append(sdes_encrypt(keybits, temp))
else:
for j in range(12):
temp += str(int(pblock[j]) ^ int(cblock[i-1][j]))
cblock.append(sdes_encrypt(keybits, temp))
ctx += cblock[i]
return ctx
# Cipher Block Chaining option decryption
def cbc_decrypt(keybits, ivbits, cipherbits):
cblock = [] # for storing ciphertext blocks
pblock = [] # for storing plaintext blocks
ptx = ''
times = int(len(cipherbits) / 12) # number of 12bits ciphertext blocks
for i in range(times): # put ciphertext into blocks of 12
cblock.append(cipherbits[12*i:12*i+12])
for i in range(times): # encryption looop
temp = '' # variable for storing ciphertext temporary
if(i == 0): # if it's the first cycle, we need ivbits xor ciphertext block
dec = sdes_decrypt(keybits, cblock[i]) # decrypt sdes
for j in range(12):
temp += str(int(dec[j]) ^ int(ivbits[j])) # xor operation
pblock.append(temp)
else:
dec = sdes_decrypt(keybits, cblock[i]) # decrypt sdes
for j in range(12):
temp += str(int(dec[j]) ^ int(cblock[i-1][j])) # decrypted sdes xor ciphertext[i-1]
pblock.append(temp)
ptx += pblock[i]
return ptx
#--------- Main code -----------
msg = '111111000000111111000000000000000000' # 2x12 = 24bits; output -> 2x cipherblocks
ivbits = '000000000000' # iv 12xbits doesn't need to be something secret
key = cbc_genkey() # key of 9 random bits
cipherText = cbc_encrypt(key, ivbits, msg)
plainText = cbc_decrypt(key, ivbits, cipherText)
print('Key: ' + key + '\nOriginal message: ' + msg + '\nEncrypted message: ' + cipherText + '\nDecrypted message: ' + plainText )<file_sep>from string import ascii_uppercase as upper
# ---------- Functions ---------
# function that generated the key by the message lenght
def lfsr_genkey(n):
# I'm using x^4 key. xn=(xn-1 + xn-3 + xn-4)mod26
key = [1, 0, 15, 20] # B, A, P, U - primary key (seed) You can always change it. range[0-25]
if len(key) >= n: # if key is longer or the same lenght as a message, return key
return key
else:
for i in range(n-len(key)): # loop for key generation
xn = (key[len(key)-1] + key[len(key)-3] + key[len(key)-4]) % 26 # formula: xn=(xn-1 + xn-3 + xn-4)mod26
key.append(xn)
return key
# encryption function
def lfsr_encrypt(key, msg):
temp = msg.upper()
ctx = '' # emty string for ciphertext
for i in range(len(temp)):
if ord(temp[i]) == 32: # ignore space ' '
ctx += ' '
elif ord(temp[i]) < 65 | ord(temp[i]) > 90: # ignore special characters
ctx += temp[i]
else:
new_idx = ((ord(temp[i]) - 65) + key[i]) % 26 # add indexes of key and original msg and make new idx with mod26
ctx += chr(new_idx+65)
return ctx
# decryption function
def lfsr_decrypt(key, ctx):
pp = '' # empty string for decrypted message
for i in range(len(ctx)):
if ord(ctx[i]) == 32: # ignore space
pp += ' '
elif ord(ctx[i]) < 65 | ord(ctx[i]) > 90: #ignore special characters
pp += ctx[i]
else:
new_idx = (ord(ctx[i])-65) - key[i] # find original index of the letter
if new_idx < 0:
new_idx += 26
pp += chr(new_idx + 65)
return pp
# --------- Main -------------
msg = 'he-llo wor*ld' # message
key = lfsr_genkey(len(msg)) # key
C = lfsr_encrypt(key, msg)
P = lfsr_decrypt(key, C)
print('Key: ' + ''.join(chr(x+65) for x in key) + '\nOriginal message: |' + msg + '|\nEncrypted message: |' + C + '|\nDecrypted message: |' + P + '|')
|
bde86811991fbb781189990c0fc09d9a7439fda6
|
[
"Markdown",
"Python"
] | 6 |
Markdown
|
EdvinasDul/Python
|
b21e6fb3875c3d1fd69039cd7f23ea42174fd8b2
|
ae27a81e3c7cd18863d604e424b7e463376fe20b
|
refs/heads/master
|
<file_sep>import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
weather_data: any;
date: any;
dates: any=[];
days: any=[];
temp: any=[];
averages_temp: any=[];
averages_feels: any=[];
pressure: any=[];
humidity: any=[];
wind: any=[];
constructor(public navCtrl: NavController, private http: Http) {
this.date = new Date()
this.http.get("https://api.openweathermap.org/data/2.5/forecast?id=2964574&APPID=be7ca5c2465ad321a21d1c3249e73ad4").map(res=> res.json())
.subscribe(data => {
console.log(data);
this.weather_data = data;
for(var i = 0; i<=5; i++){
this.days.push(this.datefilter(this.weather_data.list,i));
}
console.log(this.days)
console.log(this.dates)
console.log(this.averages_temp)
console.log(this.averages_feels)
})
}
datefilter(items, day){
let newdate = new Date();
newdate.setDate( this.date.getDate() + day);
this.dates.push(newdate.toUTCString().substring(0,16))
let datestring = newdate.toISOString().substring(0,10);
var temp: any=[];
for(let item of items){
if(datestring == (item.dt_txt.substring(0,10))){
item.main.temp = (item.main.temp-273.15).toFixed(0)
item.main.feels_like = (item.main.feels_like - 273.15).toFixed(0)
item.main.temp_min = (item.main.temp_min - 273.15).toFixed(0)
item.main.temp_max = (item.main.temp_max - 273.15).toFixed(0)
temp.push(item)
}
}
let temp2_temp = 0;
let temp2_feels = 0;
let temp2_pre = 0;
let temp2_hum = 0;
let temp2_win = 0;
for(let item of temp){
temp2_temp = temp2_temp + parseInt(item.main.temp)
temp2_feels = temp2_feels + parseInt(item.main.feels_like)
temp2_pre = temp2_pre + item.main.pressure;
temp2_hum = temp2_hum + item.main.humidity;
temp2_win = temp2_win + item.wind.speed;
}
temp2_temp = Math.round(temp2_temp / temp.length)
temp2_feels = Math.round(temp2_feels / temp.length)
temp2_pre = Math.round(temp2_pre / temp.length)
temp2_hum = Math.round(temp2_hum / temp.length)
temp2_win = Math.round(temp2_win / temp.length)
this.pressure.push(temp2_pre)
this.humidity.push(temp2_hum)
this.wind.push(temp2_win)
this.averages_temp.push(temp2_temp)
this.averages_feels.push(temp2_feels)
return temp;
}
}
<file_sep># Wapp
Simple Weather App using OpenWeatherMap API
To run the app:
Clone the repo & extract the contents to a new folder
Open CMD/Terminal and install Ionic using "npm install -g ionic@latest"
Navigate to the new folder and run "npm install"
Finally type in "ionic serve"
To be implemented:
User input for city selection
Weather Animation
Responsive template implementation
Hosted at : https://wapp-darshmurarka.web.app/
|
28d6d1d5ca5d9d86a3e3fbe253fc76ed3dd4bb46
|
[
"Markdown",
"TypeScript"
] | 2 |
TypeScript
|
darshmurarka/Wapp
|
57d7ce1e6421bec0ef158c5a36e56a2bade22eda
|
d3d10225a05f1cc70c34690e2dafc71b78ccf096
|
refs/heads/master
|
<file_sep>export default function() {
return[
{title: 'Javascrpt: the good part',pages: 101},
{title: 'Harry potter', pages:200},
{title: 'The Dark Tower', pages:300},
{title: 'The Three Body Problem', pages:400}
];
}
|
6be153fa7456577f2df6b4c9fbe3eecdf87c055e
|
[
"JavaScript"
] | 1 |
JavaScript
|
iwenyou/Simple-BookList
|
8ee3d98cb6e6da35ed23ce79fe0f5dac1d22c453
|
f49315cbf2d48bd3445362a4949eed68e2dc2f74
|
refs/heads/master
|
<repo_name>filipstojakovic/Anova-PerformanseLab<file_sep>/src/main/java/analysis/AnalysisController.java
package analysis;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import main.Main;
import java.io.IOException;
import java.util.*;
public class AnalysisController
{
public static final double TEXT_FIELD_WIDTH = 100.0;
@FXML
private TextField probabilityTF;
@FXML
private Label overallMeanLbl;
@FXML
private Label ssaLbl;
@FXML
private Label sseLbl;
@FXML
private Label sstLbl;
@FXML
private Label varianceALbl;
@FXML
private Label varianceELbl;
@FXML
private Label FcalLbl;
@FXML
private Label FtabLbl;
@FXML
private Label resultLbl;
@FXML
private TextArea contrastTF;
@FXML
private GridPane gridPane;
private int numOFAlternatives;
private int numOfMeasurements;
private int numOfColumns;
private int numOfRows;
private Map<Integer, List<Double>> columnHashMap; // <Column number, values from column>
private double probability;
//get inputs from input window
public void setInputValues(int numOFAlternatives, int numOfMeasurements)
{
this.numOFAlternatives = numOFAlternatives;
this.numOfColumns = numOFAlternatives + 1;
this.numOfMeasurements = numOfMeasurements;
this.numOfRows = numOfMeasurements + 2;
createTable();
}
private void createTable()
{
gridPane.setAlignment(Pos.CENTER);
for (int col = 0; col < numOfColumns; col++)
{
for (int row = 0; row < numOfRows; row++)
{
TextField textField = new TextField();
textField.setPrefWidth(TEXT_FIELD_WIDTH);
textField.setAlignment(Pos.CENTER);
if (col == 0 || row == 0 || row == numOfRows - 1)
{
String text = "";
if (row == 0 && col == 0)
text = "br. mjer/alt";
else if (col == 0 && row == numOfRows - 1)
text = "sr. vrijednost";
else if (col == 0)
text = row + ".";
else if (row == 0)
text = col + ". alternativa";
textField.setText(text);
textField.setEditable(false);
textField.setStyle("-fx-background-color: #2ecc71");
}
StackPane pane = new StackPane(textField);
StackPane.setAlignment(textField, Pos.CENTER);
gridPane.add(pane, col, row);
}
}
}
//get all values from
public List<Double> getColumnValues(int col) throws NumberFormatException
{
List<Double> values = new ArrayList<>();
for (int row = 1; row < numOfRows - 1; row++)
{
Double value = getValueFromGridPane(row, col);
values.add(getValueFromGridPane(row, col));
}
return values;
}
//get value from position
private Double getValueFromGridPane(int row, int col) throws NumberFormatException
{
for (Node node : gridPane.getChildren())
{
if (node instanceof StackPane && GridPane.getColumnIndex(node) == col && GridPane.getRowIndex(node) == row)
{
StackPane pane = (StackPane) node;
TextField textField = (TextField) pane.getChildren().get(0);
return Double.parseDouble(textField.getText());
}
}
return null;
}
@FXML
void goBack(ActionEvent event)
{
try
{
FXMLLoader inputFXML = new FXMLLoader(getClass().getResource("../inputview.fxml"));
Parent inputViewParent = (Parent) inputFXML.load();
Stage stage = Main.getStage();
Scene scene = new Scene(inputViewParent);
stage.setScene(scene);
stage.centerOnScreen();
stage.show();
} catch (IOException ex)
{
ex.printStackTrace();
}
}
/**
* check if all fields are valid and saved them to hashmap
*
* @return true - all good, false - something is not good
*/
public boolean checkColumnsAndSave()
{
columnHashMap = new HashMap<>();
try
{
probability = Double.parseDouble(probabilityTF.getText());
if (!(0.0 < probability || probability > 1.0))
throw new NumberFormatException();
for (int i = 1; i < numOfColumns; i++)
{
List<Double> columnValues = getColumnValues(i);
columnHashMap.put(i - 1, columnValues); // i-1 da krece od 0, bice lakse kasnije
}
} catch (NumberFormatException ex)
{
ErrorUtil.show();
return false;
}
return true;
}
//Pritisnuto dugme Analiziraj (start analysis)
@FXML
void startAnalysis(ActionEvent event)
{
if (!checkColumnsAndSave())
return;
new Thread(() ->
{
AnalysisModel analysisModel = new AnalysisModel(numOfMeasurements, numOFAlternatives, probability, columnHashMap);
analysisModel.startAnalysis();
Platform.runLater(() ->
{
fillTableWithResults(analysisModel);
});
}).start();
}
// popuni view sa dobijenim rezultatima
private void fillTableWithResults(AnalysisModel analysisModel)
{
List<Double> alterMeans = analysisModel.alterMeans;
for (int i = 0; i < alterMeans.size(); i++)
setValueToGridPane(numOfRows - 1, i + 1, alterMeans.get(i));
overallMeanLbl.setText(String.format("%.3f", analysisModel.overAllMean));
ssaLbl.setText(String.format("%.3f", analysisModel.SSA));
sseLbl.setText(String.format("%.3f", analysisModel.SSE));
sstLbl.setText(String.format("%.3f", analysisModel.SST));
varianceALbl.setText(String.format("%.3f", analysisModel.varianceA));
varianceELbl.setText(String.format("%.3f", analysisModel.varianceE));
FcalLbl.setText(String.format("%.3f", analysisModel.Fcal));
FtabLbl.setText(String.format("%.3f", analysisModel.Ftab));
resultLbl.setText(analysisModel.getAnovaResult());
List<String> contrastResult = analysisModel.contrastResult;
contrastTF.clear();
for (String text : contrastResult)
contrastTF.appendText(text);
}
//sluzi za postavljanje srednjih vrijednosti
private void setValueToGridPane(int row, int col, double value)
{
for (Node node : gridPane.getChildren())
{
if (node instanceof StackPane && GridPane.getColumnIndex(node) == col && GridPane.getRowIndex(node) == row)
{
StackPane pane = (StackPane) node;
TextField textField = (TextField) pane.getChildren().get(0);
textField.setText(String.format("%.3f", value));
}
}
}
}
<file_sep>/src/main/java/main/Main.java
package main;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
/**
* @author <NAME>
*/
public class Main extends Application
{
public static final String APP_NAME = "ANOVA & kontrasti";
private static Stage stage;
public static void main(String[] args)
{
//lunch app
// GUI je odvratan! You've been warned!
try
{
launch(args);
}catch(Exception ex)
{
ex.printStackTrace();
}
}
@Override
public void start(Stage primaryStage) throws Exception
{
stage = primaryStage;
stage.setResizable(false); // za dobrobit naroda
Parent root = FXMLLoader.load(getClass().getResource("./../inputview.fxml"));
primaryStage.setTitle(APP_NAME);
primaryStage.setScene(new Scene(root));
primaryStage.centerOnScreen();
primaryStage.show();
}
public static Stage getStage()
{
return stage;
}
}
<file_sep>/src/main/java/analysis/ErrorUtil.java
package analysis;
import javafx.scene.control.Alert;
import javafx.scene.control.TextField;
public class ErrorUtil
{
//show error message
public static void show()
{
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Greška");
alert.setHeaderText("Nisu dobro unešeni podaci.");
alert.showAndWait();
}
//show error message
public static void show(String errorMsg)
{
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Greška");
alert.setHeaderText(errorMsg);
alert.showAndWait();
}
}
<file_sep>/src/main/java/analysis/AnalysisModel.java
package analysis;
import net.sourceforge.jdistlib.F;
import net.sourceforge.jdistlib.T;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class AnalysisModel
{
private int numOfMeasurements;
private int numOFAlternatives;
private Map<Integer, List<Double>> columnHashMap;
double probability;
//calculated values
double overAllMean; //ukupna prosjecna vrijednost
List<Double> alterMeans; //prosjecna vrijednost po kolonama
double SSA = 0.0; // varijacija usljed efekta alternativa(SSA)
double dfSSA; //stepen slobode ssa
double SSE = 0.0; // varijacija usljed gresaka u mjerenju (SSE)
double dfSSE; // stepen slobode sse
double SST = 0.0; // SST = SSA + SSE
double varianceA; //varijansa alternativa
double varianceE; //varijansa gresaka
double Fcal; // Fizr
double Ftab; // F tabelarno
double alpha; // 1 - probability
List<String> contrastResult;
public AnalysisModel(int numOfMeasurements, int numOFAlternatives, double probability, Map<Integer, List<Double>> columnHashMap)
{
this.numOfMeasurements = numOfMeasurements;
this.numOFAlternatives = numOFAlternatives;
this.columnHashMap = columnHashMap;
this.probability = probability;
alterMeans = new ArrayList<>(numOFAlternatives);
}
public String getAnovaResult()
{
return "Sistemi se " + (Fcal > Ftab ? "" : "ne ") + "razlikuju!";
}
public void startAnalysis()
{
calculateColumnsAndTotalMean();
calculateSSA();
calculateSSE();
calculateSST();
calculateVarianceA();
calcualteVarianceE();
calculateFcal();
calculateFtab();
calculateContrast();
}
private void calculateColumnsAndTotalMean()
{
double overAllSum = 0.0;
for (List<Double> columnValue : columnHashMap.values())
{
double columnSum = columnValue.stream().reduce(0.0, Double::sum);
overAllSum += columnSum;
double columnMean = columnSum / numOfMeasurements;
alterMeans.add(columnMean);
}
overAllMean = overAllSum / (numOfMeasurements * numOFAlternatives);
}
private void calculateSSE()
{
SSE = 0.0;
for (int i = 0; i < numOFAlternatives; i++)
{
List<Double> columnValues = columnHashMap.get(i);
double columnMean = alterMeans.get(i);
SSE += columnValues.stream().mapToDouble(y_ij -> (y_ij - columnMean) * (y_ij - columnMean)).sum();
}
dfSSE = numOFAlternatives * (numOfMeasurements - 1);
}
private void calculateSSA()
{
SSA = alterMeans.stream().mapToDouble(yj -> (yj - overAllMean) * (yj - overAllMean)).sum();// * numOfMeasurements;
SSA *= numOfMeasurements;
dfSSA = numOFAlternatives - 1;
}
private void calculateSST()
{
SST = SSA + SSE;
}
private void calculateVarianceA()
{
varianceA = SSA / dfSSA;
}
private void calcualteVarianceE()
{
varianceE = SSE / dfSSE;
}
private void calculateFcal()
{
Fcal = varianceA / varianceE;
}
private void calculateFtab()
{
alpha = 1 - probability;
Ftab = F.quantile(alpha, dfSSA, dfSSE, false, false);
}
// izracunaj interval povjerenja
private void calculateContrast()
{
double Sc = Math.sqrt(varianceE * 2.0 / (numOfMeasurements * numOFAlternatives));
double[] alphaEffects = alterMeans.stream().mapToDouble(alpha -> alpha - overAllMean).toArray();
double Tdistribution = T.quantile(alpha / 2.0, dfSSE, false, false);
//Tdist= 1.78228755564932 za 0.9, 5 mjerenja, 3 alternative
contrastResult = new ArrayList<>();
for (int i = 0; i < numOFAlternatives - 1; i++)
for (int j = i + 1; j < numOFAlternatives; j++)
{
double c = alphaEffects[i] - alphaEffects[j];
double c1 = c - Tdistribution * Sc;
double c2 = c + Tdistribution * Sc;
//ako obuhvata nulu => nema razlike
boolean zeroIncluded = true;
if ((c1 < 0.0 && c2 < 0.0) || (c1 > 0.0 && c2 > 0.0))
zeroIncluded = false;
String text = "Alternative " + (i + 1) + " i " + (j + 1) + " se" + (zeroIncluded ? " ne" : "") + " razlikuju ";
String interval = String.format("(%.3f, %.3f)", c1, c2);
contrastResult.add(text + interval + "\n");
}
}
}
<file_sep>/src/main/java/main/InputViewController.java
package main;
import analysis.AnalysisController;
import analysis.ErrorUtil;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import java.io.IOException;
public class InputViewController
{
@FXML
private TextField numOFAlternatives;
@FXML
private TextField numOfMeasurements;
@FXML
private Label errorMsg;
/**
* Check fields and start analysisview if all good
*/
@FXML
void submitClicked(ActionEvent event)
{
try
{
int alt = Integer.parseInt(numOFAlternatives.getText());
int measur = Integer.parseInt(numOfMeasurements.getText());
if(alt<1 || measur<1)
throw new NumberFormatException();
FXMLLoader analysisFXML = new FXMLLoader(getClass().getResource("../analysisview.fxml"));
Parent analysisViewParent = (Parent) analysisFXML.load();
//sending input values to the view
AnalysisController analysisController = analysisFXML.getController();
analysisController.setInputValues(alt, measur);
Stage stage = Main.getStage();
Scene scene = new Scene(analysisViewParent);
stage.setScene(scene);
stage.centerOnScreen();
stage.show();
} catch (NumberFormatException ex)
{
ErrorUtil.show();
errorMsg.setVisible(true);
} catch (IOException ex)
{
ex.printStackTrace();
}
}
}
|
5f321925699f24068b0a2d55c46837fda7457749
|
[
"Java"
] | 5 |
Java
|
filipstojakovic/Anova-PerformanseLab
|
7e03400d9ba287571acea0c5f764e03f2f90d377
|
dcacffda5ca2aebba04ba781c983151cfc558ac1
|
refs/heads/master
|
<repo_name>ManchuChris/KrisAlgorithm<file_sep>/bubbleSort.java
import java.io.*;
class bubbleSort {
public static void main(String args[]){
int ArrayList[] = {4,3,7,2,9,11,1,8};
printList(ArrayList);
SortBubble(ArrayList);
System.out.print("1\n");
printList(ArrayList);
}
public static void SortBubble (int[] list){
int length = list.length;
for (int i=0; i < length -1; i++){
boolean swapFlag = false;
for (int j=0; j< length-i-1; j++){
if (list[j] > list[j+1]){
int Temp = list[j];
list[j] = list[j+1];
list[j+1] = Temp;
System.out.println("Two numbers" + list[j] +"and" + list[j+1] + "swap.\n");
swapFlag = true;
}
}
printList(list);
if (swapFlag == false)
break;
}
}//SortBubble end
public static void printList (int[] list){
int len = list.length;
for (int i=0; i<=len-1; i++){
System.out.print(list[i] + " ");
}
System.out.print("\n");
}
}
|
99708f1b4b7e069b43d0bfa81c6e762bb1f55923
|
[
"Java"
] | 1 |
Java
|
ManchuChris/KrisAlgorithm
|
9a5c037076b0583d027b5c75b8f6419711ff8d9b
|
43dd4e2e60e2689d5b225632e0d094666e5cef30
|
refs/heads/master
|
<repo_name>AmanMinhas/lazy-app<file_sep>/src/App.js
import React, { Suspense, lazy } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
const HomePage = lazy(() => import('./Pages/Home'));
const AboutPage = lazy(() => import('./Pages/About'));
const ContactPage = lazy(() => import('./Pages/Contact'));
const App = () => {
return (
<div>
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route exact path='/' component={HomePage} />
<Route path='/about' component={AboutPage} />
<Route path='/contact' component={ContactPage} />
</Switch>
</Suspense>
</Router>
</div>
);
}
export default App;
<file_sep>/README.md
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Read on Medium
[React Suspense and lazy explained with example - Part 1](https://medium.com/@amandeepsinghminhas/react-suspense-and-lazy-explained-with-example-part-1-948fccd83c61)
[React Suspense and lazy explained with example - Part 2](https://medium.com/@amandeepsinghminhas/react-suspense-and-lazy-explained-with-example-part-2-d83b3baac47a)
|
38a6ef04e83bc3cb4c166f6f4b6c883c53a66b4d
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
AmanMinhas/lazy-app
|
db2a4e41031dca60df04413ce98379f217e08673
|
2016ef1fa14f8945b6a2a2da2feabef86e5ed5e0
|
refs/heads/master
|
<file_sep>package pt.c01interfaces.s01knowledge.s02app.actors;
import pt.c01interfaces.s01knowledge.s01base.impl.BaseConhecimento;
import pt.c01interfaces.s01knowledge.s01base.inter.IBaseConhecimento;
import pt.c01interfaces.s01knowledge.s01base.inter.IDeclaracao;
import pt.c01interfaces.s01knowledge.s01base.inter.IEnquirer;
import pt.c01interfaces.s01knowledge.s01base.inter.IObjetoConhecimento;
import pt.c01interfaces.s01knowledge.s01base.inter.IResponder;
/*importando biblioteca para uso do hashmap*/
import java.util.*;
public class Enquirer implements IEnquirer
{
IObjetoConhecimento obj;
String pergunta;
String respostaEsperada;
String resposta;
int i;
String animal;
public Enquirer()
{
}
@Override
public void connect(IResponder responder)
{
IBaseConhecimento bc = new BaseConhecimento();
HashMap<String,String> map=new HashMap<String,String>();
/*lista o nome de todos animais do banco de dados*/
String animais[] = bc.listaNomes();
boolean encontrou = true;
for (i = 0; i < animais.length && encontrou; i++) {
animal = animais[i];
obj = bc.recuperaObjeto(animal);
IDeclaracao decl = obj.primeira();
boolean esperado = true;
while (decl != null && esperado) {
pergunta = decl.getPropriedade();
respostaEsperada = decl.getValor();
if(!map.containsKey(pergunta)){
resposta = responder.ask(pergunta);
map.put(pergunta, resposta);
}
else
//ja fez a pergunta
resposta = map.get(pergunta);
if (resposta.equalsIgnoreCase(respostaEsperada)) {
decl = obj.proxima();
}
else {
esperado = false;
}
}
if (esperado) {
encontrou = false;
}
}
boolean acertei = responder.finalAnswer(animal);
if (acertei) {
System.out.println("Oba! Acertei!");
}
else
System.out.println("fuem! fuem! fuem");
}
}
<file_sep>package pt.c02classes.s01knowledge.s02app.app;
import pt.c02classes.s01knowledge.s01base.impl.BaseConhecimento;
import pt.c02classes.s01knowledge.s01base.impl.Statistics;
import pt.c02classes.s01knowledge.s01base.inter.IBaseConhecimento;
import pt.c02classes.s01knowledge.s01base.inter.IEnquirer;
import pt.c02classes.s01knowledge.s01base.inter.IResponder;
import pt.c02classes.s01knowledge.s01base.inter.IStatistics;
import pt.c02classes.s01knowledge.s02app.actors.EnquirerAnimals;
import pt.c02classes.s01knowledge.s02app.actors.EnquirerMaze;
import pt.c02classes.s01knowledge.s02app.actors.ResponderAnimals;
import pt.c02classes.s01knowledge.s02app.actors.ResponderMaze;
/*biblioteca com scanner*/
import java.util.Scanner;
public class OrchestratorInit {
public static void main(String args[])
{
IEnquirer enq;
IResponder resp;
IStatistics stat;
IBaseConhecimento base = new BaseConhecimento();
Scanner scanner = new Scanner(System.in);
System.out.println("Qual o jogo? [A]nimals ou [M]aze");
String tipo = scanner.nextLine();
if (tipo.equalsIgnoreCase("A")) {
base.setScenario("animals");
System.out.println("Qual o animal?");
String animal = scanner.nextLine();
stat = new Statistics();
resp = new ResponderAnimals(stat, animal);
enq = new EnquirerAnimals();
enq.connect(resp);
enq.discover();
}
else if (tipo.equalsIgnoreCase("M")) {
System.out.println("Qual o labirinto?");
String labirinto = scanner.nextLine();
stat = new Statistics();
resp = new ResponderMaze(stat, labirinto);
enq = new EnquirerMaze();
enq.connect(resp);
enq.discover();
}
scanner.close();
}
}
|
48beea2ef037dea8754287b3b4238b05c2c33330
|
[
"Java"
] | 2 |
Java
|
Guilhermeslucas/fluid2learn
|
e354006c6887a974a4b94ec7e9fc829214b28ec0
|
853c38de7027eed36952af71d76f3ef2c0d1eccf
|
refs/heads/main
|
<repo_name>aquasecurity/go-dep-parser<file_sep>/pkg/hex/mix/parse_test.go
package mix
import (
"os"
"sort"
"strings"
"testing"
"github.com/aquasecurity/go-dep-parser/pkg/types"
"github.com/stretchr/testify/assert"
)
func TestParser_Parse(t *testing.T) {
tests := []struct {
name string
inputFile string
want []types.Library
}{
{
name: "happy path",
inputFile: "testdata/happy.mix.lock",
want: []types.Library{
{
ID: "[email protected]",
Name: "bunt",
Version: "0.2.0",
Locations: []types.Location{{StartLine: 2, EndLine: 2}},
},
{
ID: "[email protected]",
Name: "credo",
Version: "1.6.6",
Locations: []types.Location{{StartLine: 3, EndLine: 3}},
},
{
ID: "[email protected]",
Name: "file_system",
Version: "0.2.10",
Locations: []types.Location{{StartLine: 4, EndLine: 4}},
},
{
ID: "[email protected]",
Name: "jason",
Version: "1.3.0",
Locations: []types.Location{{StartLine: 5, EndLine: 5}},
},
},
},
{
name: "empty",
inputFile: "testdata/empty.mix.lock",
want: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
parser := NewParser()
f, err := os.Open(tt.inputFile)
assert.NoError(t, err)
libs, _, _ := parser.Parse(f)
sortLibs(libs)
assert.Equal(t, tt.want, libs)
})
}
}
func sortLibs(libs []types.Library) {
sort.Slice(libs, func(i, j int) bool {
ret := strings.Compare(libs[i].Name, libs[j].Name)
if ret == 0 {
return libs[i].Version < libs[j].Version
}
return ret < 0
})
}
<file_sep>/pkg/python/pip/testdata/requirements_flask.txt
click==8.0.0
Flask==2.0.0
itsdangerous==2.0.0
Jinja2==3.0.0
MarkupSafe==2.0.0
Werkzeug==2.0.0
<file_sep>/pkg/gradle/lockfile/parse.go
package lockfile
import (
"bufio"
"strings"
dio "github.com/aquasecurity/go-dep-parser/pkg/io"
"github.com/aquasecurity/go-dep-parser/pkg/types"
"github.com/aquasecurity/go-dep-parser/pkg/utils"
)
type Parser struct{}
func NewParser() types.Parser {
return &Parser{}
}
func (Parser) Parse(r dio.ReadSeekerAt) ([]types.Library, []types.Dependency, error) {
var libs []types.Library
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if strings.HasPrefix(line, "#") { // skip comments
continue
}
// dependency format: group:artifact:version=classPaths
dep := strings.Split(line, ":")
if len(dep) != 3 { // skip the last line with lists of empty configurations
continue
}
libs = append(libs, types.Library{
Name: strings.Join(dep[:2], ":"),
Version: strings.Split(dep[2], "=")[0], // remove classPaths
})
}
return utils.UniqueLibraries(libs), nil, nil
}
<file_sep>/pkg/python/pip/testdata/requirements_operator.txt
keyring >= 4.1.1 # Minimum version 4.1.1
coverage != 3.5 # Version Exclusion. Anything except version 3.5
Mopidy-Dirble ~= 1.1 # Compatible release. Same as >= 1.1, == 1.*
Django == 2.3.4
SomeProject ==5.4 ; python_version < '3.8'
numpyNew; sys_platform == 'win32'
numpy >= 3.4.1; sys_platform == 'win32'<file_sep>/pkg/python/pipenv/parse_testcase.go
package pipenv
import "github.com/aquasecurity/go-dep-parser/pkg/types"
var (
// docker run --name pipenv --rm -it python:3.9-alpine sh
// apk add jq
// mkdir app && cd /app
// pip install pipenv
// pipenv install requests pyyaml
// pipenv graph --json | jq -rc '.[] | "{\"\(.package.package_name | ascii_downcase)\", \"\(.package.installed_version)\", \"\"},"'
// graph doesn't contain information about location of dependency in lock file.
// add locations manually
pipenvNormal = []types.Library{
{Name: "urllib3", Version: "1.24.2", Locations: []types.Location{{StartLine: 65, EndLine: 71}}},
{Name: "requests", Version: "2.21.0", Locations: []types.Location{{StartLine: 57, EndLine: 64}}},
{Name: "pyyaml", Version: "5.1", Locations: []types.Location{{StartLine: 40, EndLine: 56}}},
{Name: "idna", Version: "2.8", Locations: []types.Location{{StartLine: 33, EndLine: 39}}},
{Name: "chardet", Version: "3.0.4", Locations: []types.Location{{StartLine: 26, EndLine: 32}}},
{Name: "certifi", Version: "2019.3.9", Locations: []types.Location{{StartLine: 19, EndLine: 25}}},
}
// docker run --name pipenv --rm -it python:3.9-alpine bash
// apk add jq
// mkdir app && cd /app
// pip install pipenv
// pipenv install requests pyyaml django djangorestframework
// pipenv graph --json | jq -rc '.[] | "{\"\(.package.package_name | ascii_downcase)\", \"\(.package.installed_version)\", \"\"},"'
// graph doesn't contain information about location of dependency in lock file.
// add locations manually
pipenvDjango = []types.Library{
{Name: "urllib3", Version: "1.24.2", Locations: []types.Location{{StartLine: 95, EndLine: 101}}},
{Name: "sqlparse", Version: "0.3.0", Locations: []types.Location{{StartLine: 88, EndLine: 94}}},
{Name: "requests", Version: "2.21.0", Locations: []types.Location{{StartLine: 80, EndLine: 87}}},
{Name: "pyyaml", Version: "5.1", Locations: []types.Location{{StartLine: 63, EndLine: 79}}},
{Name: "pytz", Version: "2019.1", Locations: []types.Location{{StartLine: 56, EndLine: 62}}},
{Name: "idna", Version: "2.8", Locations: []types.Location{{StartLine: 49, EndLine: 55}}},
{Name: "djangorestframework", Version: "3.9.3", Locations: []types.Location{{StartLine: 41, EndLine: 48}}},
{Name: "django", Version: "2.2", Locations: []types.Location{{StartLine: 33, EndLine: 40}}},
{Name: "chardet", Version: "3.0.4", Locations: []types.Location{{StartLine: 26, EndLine: 32}}},
{Name: "certifi", Version: "2019.3.9", Locations: []types.Location{{StartLine: 19, EndLine: 25}}},
}
// docker run --name pipenv --rm -it python:3.9-alpine bash
// apk add jq
// mkdir app && cd /app
// pip install pipenv
// pipenv install requests pyyaml django djangorestframework six botocore python-dateutil simplejson setuptools pyasn1 awscli jinja2
// pipenv graph --json | jq -rc '.[] | "{\"\(.package.package_name | ascii_downcase)\", \"\(.package.installed_version)\", \"\"},"'
// graph doesn't contain information about location of dependency in lock file.
// add locations manually
pipenvMany = []types.Library{
{Name: "urllib3", Version: "1.24.2", Locations: []types.Location{{StartLine: 237, EndLine: 244}}},
{Name: "sqlparse", Version: "0.3.0", Locations: []types.Location{{StartLine: 230, EndLine: 236}}},
{Name: "six", Version: "1.12.0", Locations: []types.Location{{StartLine: 222, EndLine: 229}}},
{Name: "simplejson", Version: "3.16.0", Locations: []types.Location{{StartLine: 204, EndLine: 221}}},
{Name: "s3transfer", Version: "0.2.0", Locations: []types.Location{{StartLine: 197, EndLine: 203}}},
{Name: "rsa", Version: "3.4.2", Locations: []types.Location{{StartLine: 190, EndLine: 196}}},
{Name: "requests", Version: "2.21.0", Locations: []types.Location{{StartLine: 182, EndLine: 189}}},
{Name: "pyyaml", Version: "3.13", Locations: []types.Location{{StartLine: 165, EndLine: 181}}},
{Name: "pytz", Version: "2019.1", Locations: []types.Location{{StartLine: 158, EndLine: 164}}},
{Name: "python-dateutil", Version: "2.8.0", Locations: []types.Location{{StartLine: 150, EndLine: 157}}},
{Name: "pyasn1", Version: "0.4.5", Locations: []types.Location{{StartLine: 142, EndLine: 149}}},
{Name: "markupsafe", Version: "1.1.1", Locations: []types.Location{{StartLine: 109, EndLine: 141}}},
{Name: "jmespath", Version: "0.9.4", Locations: []types.Location{{StartLine: 102, EndLine: 108}}},
{Name: "jinja2", Version: "2.10.1", Locations: []types.Location{{StartLine: 94, EndLine: 101}}},
{Name: "idna", Version: "2.8", Locations: []types.Location{{StartLine: 87, EndLine: 93}}},
{Name: "framework", Version: "0.1.0", Locations: []types.Location{{StartLine: 80, EndLine: 86}}},
{Name: "docutils", Version: "0.14", Locations: []types.Location{{StartLine: 72, EndLine: 79}}},
{Name: "djangorestframework", Version: "3.9.3", Locations: []types.Location{{StartLine: 64, EndLine: 71}}},
{Name: "django", Version: "2.2", Locations: []types.Location{{StartLine: 56, EndLine: 63}}},
{Name: "colorama", Version: "0.3.9", Locations: []types.Location{{StartLine: 49, EndLine: 55}}},
{Name: "chardet", Version: "3.0.4", Locations: []types.Location{{StartLine: 42, EndLine: 48}}},
{Name: "certifi", Version: "2019.3.9", Locations: []types.Location{{StartLine: 35, EndLine: 41}}},
{Name: "botocore", Version: "1.12.137", Locations: []types.Location{{StartLine: 27, EndLine: 34}}},
{Name: "awscli", Version: "1.16.147", Locations: []types.Location{{StartLine: 19, EndLine: 26}}},
}
)
<file_sep>/pkg/java/pom/parse.go
package pom
import (
"encoding/xml"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"sort"
"strings"
dio "github.com/aquasecurity/go-dep-parser/pkg/io"
multierror "github.com/hashicorp/go-multierror"
"github.com/samber/lo"
"golang.org/x/net/html/charset"
"golang.org/x/xerrors"
"github.com/aquasecurity/go-dep-parser/pkg/log"
"github.com/aquasecurity/go-dep-parser/pkg/types"
"github.com/aquasecurity/go-dep-parser/pkg/utils"
)
const (
centralURL = "https://repo.maven.apache.org/maven2/"
)
type options struct {
offline bool
remoteRepos []string
}
type option func(*options)
func WithOffline(offline bool) option {
return func(opts *options) {
opts.offline = offline
}
}
func WithRemoteRepos(repos []string) option {
return func(opts *options) {
opts.remoteRepos = repos
}
}
type parser struct {
rootPath string
cache pomCache
localRepository string
remoteRepositories []string
offline bool
}
func NewParser(filePath string, opts ...option) types.Parser {
o := &options{
offline: false,
remoteRepos: []string{centralURL},
}
for _, opt := range opts {
opt(o)
}
s := readSettings()
localRepository := s.LocalRepository
if localRepository == "" {
homeDir, _ := os.UserHomeDir()
localRepository = filepath.Join(homeDir, ".m2", "repository")
}
return &parser{
rootPath: filepath.Clean(filePath),
cache: newPOMCache(),
localRepository: localRepository,
remoteRepositories: o.remoteRepos,
offline: o.offline,
}
}
func (p *parser) Parse(r dio.ReadSeekerAt) ([]types.Library, []types.Dependency, error) {
content, err := parsePom(r)
if err != nil {
return nil, nil, xerrors.Errorf("failed to parse POM: %w", err)
}
root := &pom{
filePath: p.rootPath,
content: content,
}
// Analyze root POM
result, err := p.analyze(root, analysisOptions{})
if err != nil {
return nil, nil, xerrors.Errorf("analyze error (%s): %w", p.rootPath, err)
}
// Cache root POM
p.cache.put(result.artifact, result)
return p.parseRoot(root.artifact())
}
func (p *parser) parseRoot(root artifact) ([]types.Library, []types.Dependency, error) {
// Prepare a queue for dependencies
queue := newArtifactQueue()
// Enqueue root POM
root.Root = true
root.Module = false
queue.enqueue(root)
var (
libs []types.Library
deps []types.Dependency
rootDepManagement []pomDependency
uniqArtifacts = map[string]artifact{}
uniqDeps = map[string][]string{}
)
// Iterate direct and transitive dependencies
for !queue.IsEmpty() {
art := queue.dequeue()
// Modules should be handled separately so that they can have independent dependencies.
// It means multi-module allows for duplicate dependencies.
if art.Module {
moduleLibs, moduleDeps, err := p.parseRoot(art)
if err != nil {
return nil, nil, err
}
libs = append(libs, moduleLibs...)
if moduleDeps != nil {
deps = append(deps, moduleDeps...)
}
continue
}
// For soft requirements, skip dependency resolution that has already been resolved.
if uniqueArt, ok := uniqArtifacts[art.Name()]; ok {
if !uniqueArt.Version.shouldOverride(art.Version) {
continue
}
// mark artifact as Direct, if saved artifact is Direct
// take a look `hard requirement for the specified version` test
if uniqueArt.Direct {
art.Direct = true
}
}
result, err := p.resolve(art, rootDepManagement)
if err != nil {
return nil, nil, xerrors.Errorf("resolve error (%s): %w", art, err)
}
if art.Root {
// Managed dependencies in the root POM affect transitive dependencies
rootDepManagement = p.resolveDepManagement(result.properties, result.dependencyManagement)
// mark root artifact and its dependencies as Direct
art.Direct = true
result.dependencies = lo.Map(result.dependencies, func(dep artifact, _ int) artifact {
dep.Direct = true
return dep
})
}
// Parse, cache, and enqueue modules.
for _, relativePath := range result.modules {
moduleArtifact, err := p.parseModule(result.filePath, relativePath)
if err != nil {
log.Logger.Debugf("Unable to parse %q module: %s", result.filePath, err)
continue
}
queue.enqueue(moduleArtifact)
}
// Resolve transitive dependencies later
queue.enqueue(result.dependencies...)
// Offline mode may be missing some fields.
if !art.IsEmpty() {
// Override the version
uniqArtifacts[art.Name()] = artifact{
Version: art.Version,
Licenses: result.artifact.Licenses,
Direct: art.Direct,
}
// save only dependency names
// version will be determined later
dependsOn := lo.Map(result.dependencies, func(a artifact, _ int) string {
return a.Name()
})
uniqDeps[packageID(art.Name(), art.Version.String())] = dependsOn
}
}
// Convert to []types.Library and []types.Dependency
for name, art := range uniqArtifacts {
lib := types.Library{
ID: packageID(name, art.Version.String()),
Name: name,
Version: art.Version.String(),
License: art.JoinLicenses(),
Indirect: !art.Direct,
}
libs = append(libs, lib)
// Convert dependency names into dependency IDs
dependsOn := lo.FilterMap(uniqDeps[lib.ID], func(dependOnName string, _ int) (string, bool) {
ver := depVersion(dependOnName, uniqArtifacts)
return packageID(dependOnName, ver), ver != ""
})
sort.Strings(dependsOn)
if len(dependsOn) > 0 {
deps = append(deps, types.Dependency{
ID: lib.ID,
DependsOn: dependsOn,
})
}
}
sort.Sort(types.Libraries(libs))
sort.Sort(types.Dependencies(deps))
return libs, deps, nil
}
// depVersion finds dependency in uniqArtifacts and return its version
func depVersion(depName string, uniqArtifacts map[string]artifact) string {
if art, ok := uniqArtifacts[depName]; ok {
return art.Version.String()
}
return ""
}
func (p *parser) parseModule(currentPath, relativePath string) (artifact, error) {
// modulePath: "root/" + "module/" => "root/module"
module, err := p.openRelativePom(currentPath, relativePath)
if err != nil {
return artifact{}, xerrors.Errorf("unable to open the relative path: %w", err)
}
result, err := p.analyze(module, analysisOptions{})
if err != nil {
return artifact{}, xerrors.Errorf("analyze error: %w", err)
}
moduleArtifact := module.artifact()
moduleArtifact.Module = true
p.cache.put(moduleArtifact, result)
return moduleArtifact, nil
}
func (p *parser) resolve(art artifact, rootDepManagement []pomDependency) (analysisResult, error) {
// If the artifact is found in cache, it is returned.
if result := p.cache.get(art); result != nil {
return *result, nil
}
log.Logger.Debugf("Resolving %s:%s:%s...", art.GroupID, art.ArtifactID, art.Version)
pomContent, err := p.tryRepository(art.GroupID, art.ArtifactID, art.Version.String())
if err != nil {
log.Logger.Debug(err)
}
result, err := p.analyze(pomContent, analysisOptions{
exclusions: art.Exclusions,
depManagement: rootDepManagement,
})
if err != nil {
return analysisResult{}, xerrors.Errorf("analyze error: %w", err)
}
p.cache.put(art, result)
return result, nil
}
type analysisResult struct {
filePath string
artifact artifact
dependencies []artifact
dependencyManagement []pomDependency // Keep the order of dependencies in 'dependencyManagement'
properties map[string]string
modules []string
}
type analysisOptions struct {
exclusions map[string]struct{}
depManagement []pomDependency // from the root POM
}
func (p *parser) analyze(pom *pom, opts analysisOptions) (analysisResult, error) {
if pom == nil || pom.content == nil {
return analysisResult{}, nil
}
// Update remoteRepositories
p.remoteRepositories = utils.UniqueStrings(append(p.remoteRepositories, pom.repositories()...))
// Parent
parent, err := p.parseParent(pom.filePath, pom.content.Parent)
if err != nil {
return analysisResult{}, xerrors.Errorf("parent error: %w", err)
}
// Inherit values/properties from parent
pom.inherit(parent)
// Generate properties
props := pom.properties()
// dependencyManagements have the next priority:
// 1. Managed dependencies from this POM
// 2. Managed dependencies from parent of this POM
depManagement := p.mergeDependencyManagements(pom.content.DependencyManagement.Dependencies.Dependency,
parent.dependencyManagement)
// Merge dependencies. Child dependencies must be preferred than parent dependencies.
// Parents don't have to resolve dependencies.
deps := p.parseDependencies(pom.content.Dependencies.Dependency, props, depManagement, opts.depManagement, opts.exclusions)
deps = p.mergeDependencies(parent.dependencies, deps, opts.exclusions)
return analysisResult{
filePath: pom.filePath,
artifact: pom.artifact(),
dependencies: deps,
dependencyManagement: depManagement,
properties: props,
modules: pom.content.Modules.Module,
}, nil
}
func (p *parser) mergeDependencyManagements(depManagements ...[]pomDependency) []pomDependency {
uniq := map[string]struct{}{}
var depManagement []pomDependency
// The preceding argument takes precedence.
for _, dm := range depManagements {
for _, dep := range dm {
if _, ok := uniq[dep.Name()]; ok {
continue
}
depManagement = append(depManagement, dep)
uniq[dep.Name()] = struct{}{}
}
}
return depManagement
}
func (p *parser) parseDependencies(deps []pomDependency, props map[string]string, depManagement, rootDepManagement []pomDependency,
exclusions map[string]struct{}) []artifact {
// Imported POMs often have no dependencies, so dependencyManagement resolution can be skipped.
if len(deps) == 0 {
return nil
}
// Resolve dependencyManagement
depManagement = p.resolveDepManagement(props, depManagement)
var dependencies []artifact
for _, d := range deps {
// Resolve dependencies
d = d.Resolve(props, depManagement, rootDepManagement)
if (d.Scope != "" && d.Scope != "compile") || d.Optional {
continue
}
dependencies = append(dependencies, d.ToArtifact(exclusions))
}
return dependencies
}
func (p *parser) resolveDepManagement(props map[string]string, depManagement []pomDependency) []pomDependency {
var newDepManagement, imports []pomDependency
for _, dep := range depManagement {
// cf. https://howtodoinjava.com/maven/maven-dependency-scopes/#import
if dep.Scope == "import" {
imports = append(imports, dep)
} else {
// Evaluate variables
newDepManagement = append(newDepManagement, dep.Resolve(props, nil, nil))
}
}
// Managed dependencies with a scope of "import" should be processed after other managed dependencies.
// cf. https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#importing-dependencies
for _, imp := range imports {
art := newArtifact(imp.GroupID, imp.ArtifactID, imp.Version, nil, props)
result, err := p.resolve(art, nil)
if err != nil {
continue
}
for k, dd := range result.dependencyManagement {
// Evaluate variables and overwrite dependencyManagement
result.dependencyManagement[k] = dd.Resolve(result.properties, nil, nil)
}
newDepManagement = p.mergeDependencyManagements(newDepManagement, result.dependencyManagement)
}
return newDepManagement
}
func (p *parser) mergeDependencies(parent, child []artifact, exclusions map[string]struct{}) []artifact {
var deps []artifact
unique := map[string]struct{}{}
for _, d := range append(parent, child...) {
if excludeDep(exclusions, d) {
continue
}
if _, ok := unique[d.Name()]; ok {
continue
}
unique[d.Name()] = struct{}{}
deps = append(deps, d)
}
return deps
}
func excludeDep(exclusions map[string]struct{}, art artifact) bool {
if _, ok := exclusions[art.Name()]; ok {
return true
}
// Maven can use "*" in GroupID and ArtifactID fields to exclude dependencies
// https://maven.apache.org/pom.html#exclusions
for exlusion := range exclusions {
// exclusion format - "<groupID>:<artifactID>"
e := strings.Split(exlusion, ":")
if (e[0] == art.GroupID || e[0] == "*") && (e[1] == art.ArtifactID || e[1] == "*") {
return true
}
}
return false
}
func (p *parser) parseParent(currentPath string, parent pomParent) (analysisResult, error) {
// Pass nil properties so that variables in <parent> are not evaluated.
target := newArtifact(parent.GroupId, parent.ArtifactId, parent.Version, nil, nil)
// if version is property (e.g. ${revision}) - we still need to parse this pom
if target.IsEmpty() && !isProperty(parent.Version) {
return analysisResult{}, nil
}
log.Logger.Debugf("Start parent: %s", target.String())
defer func() {
log.Logger.Debugf("Exit parent: %s", target.String())
}()
// If the artifact is found in cache, it is returned.
if result := p.cache.get(target); result != nil {
return *result, nil
}
parentPOM, err := p.retrieveParent(currentPath, parent.RelativePath, target)
if err != nil {
log.Logger.Debugf("parent POM not found: %s", err)
}
result, err := p.analyze(parentPOM, analysisOptions{})
if err != nil {
return analysisResult{}, xerrors.Errorf("analyze error: %w", err)
}
p.cache.put(target, result)
return result, nil
}
func (p *parser) retrieveParent(currentPath, relativePath string, target artifact) (*pom, error) {
var errs error
// Try relativePath
if relativePath != "" {
pom, err := p.tryRelativePath(target, currentPath, relativePath)
if err != nil {
errs = multierror.Append(errs, err)
} else {
return pom, nil
}
}
// If not found, search the parent director
pom, err := p.tryRelativePath(target, currentPath, "../pom.xml")
if err != nil {
errs = multierror.Append(errs, err)
} else {
return pom, nil
}
// If not found, search local/remote remoteRepositories
pom, err = p.tryRepository(target.GroupID, target.ArtifactID, target.Version.String())
if err != nil {
errs = multierror.Append(errs, err)
} else {
return pom, nil
}
// Reaching here means the POM wasn't found
return nil, errs
}
func (p *parser) tryRelativePath(parentArtifact artifact, currentPath, relativePath string) (*pom, error) {
pom, err := p.openRelativePom(currentPath, relativePath)
if err != nil {
return nil, err
}
result, err := p.analyze(pom, analysisOptions{})
if err != nil {
return nil, xerrors.Errorf("analyze error: %w", err)
}
if !parentArtifact.Equal(result.artifact) {
return nil, xerrors.New("'parent.relativePath' points at wrong local POM")
}
return pom, nil
}
func (p *parser) openRelativePom(currentPath, relativePath string) (*pom, error) {
// e.g. child/pom.xml => child/
dir := filepath.Dir(currentPath)
// e.g. child + ../parent => parent/
filePath := filepath.Join(dir, relativePath)
isDir, err := isDirectory(filePath)
if err != nil {
return nil, err
} else if isDir {
// e.g. parent/ => parent/pom.xml
filePath = filepath.Join(filePath, "pom.xml")
}
pom, err := p.openPom(filePath)
if err != nil {
return nil, xerrors.Errorf("failed to open %s: %w", filePath, err)
}
return pom, nil
}
func (p *parser) openPom(filePath string) (*pom, error) {
f, err := os.Open(filePath)
if err != nil {
return nil, xerrors.Errorf("file open error (%s): %w", filePath, err)
}
content, err := parsePom(f)
if err != nil {
return nil, xerrors.Errorf("failed to parse the local POM: %w", err)
}
return &pom{
filePath: filePath,
content: content,
}, nil
}
func (p *parser) tryRepository(groupID, artifactID, version string) (*pom, error) {
// Generate a proper path to the pom.xml
// e.g. com.fasterxml.jackson.core, jackson-annotations, 2.10.0
// => com/fasterxml/jackson/core/jackson-annotations/2.10.0/jackson-annotations-2.10.0.pom
paths := strings.Split(groupID, ".")
paths = append(paths, artifactID, version)
paths = append(paths, fmt.Sprintf("%s-%s.pom", artifactID, version))
// Search local remoteRepositories
loaded, err := p.loadPOMFromLocalRepository(paths)
if err == nil {
return loaded, nil
}
// Search remote remoteRepositories
loaded, err = p.fetchPOMFromRemoteRepository(paths)
if err == nil {
return loaded, nil
}
return nil, xerrors.Errorf("%s:%s:%s was not found in local/remote repositories", groupID, artifactID, version)
}
func (p *parser) loadPOMFromLocalRepository(paths []string) (*pom, error) {
paths = append([]string{p.localRepository}, paths...)
localPath := filepath.Join(paths...)
return p.openPom(localPath)
}
func (p *parser) fetchPOMFromRemoteRepository(paths []string) (*pom, error) {
// Do not try fetching pom.xml from remote repositories in offline mode
if p.offline {
log.Logger.Debug("Fetching the remote pom.xml is skipped")
return nil, xerrors.New("offline mode")
}
// try all remoteRepositories
for _, repo := range p.remoteRepositories {
repoURL, err := url.Parse(repo)
if err != nil {
continue
}
paths = append([]string{repoURL.Path}, paths...)
repoURL.Path = path.Join(paths...)
resp, err := http.Get(repoURL.String())
if err != nil || resp.StatusCode != http.StatusOK {
continue
}
content, err := parsePom(resp.Body)
if err != nil {
return nil, xerrors.Errorf("failed to parse the remote POM: %w", err)
}
return &pom{
filePath: "", // from remote repositories
content: content,
}, nil
}
return nil, xerrors.Errorf("the POM was not found in remote remoteRepositories")
}
func parsePom(r io.Reader) (*pomXML, error) {
parsed := &pomXML{}
decoder := xml.NewDecoder(r)
decoder.CharsetReader = charset.NewReaderLabel
if err := decoder.Decode(parsed); err != nil {
return nil, xerrors.Errorf("xml decode error: %w", err)
}
return parsed, nil
}
<file_sep>/pkg/python/pip/parse_testcase.go
package pip
import "github.com/aquasecurity/go-dep-parser/pkg/types"
var (
requirementsFlask = []types.Library{
{Name: "click", Version: "8.0.0"},
{Name: "Flask", Version: "2.0.0"},
{Name: "itsdangerous", Version: "2.0.0"},
{Name: "Jinja2", Version: "3.0.0"},
{Name: "MarkupSafe", Version: "2.0.0"},
{Name: "Werkzeug", Version: "2.0.0"},
}
requirementsComments = []types.Library{
{Name: "click", Version: "8.0.0"},
{Name: "Flask", Version: "2.0.0"},
{Name: "Jinja2", Version: "3.0.0"},
{Name: "MarkupSafe", Version: "2.0.0"},
}
requirementsSpaces = []types.Library{
{Name: "click", Version: "8.0.0"},
{Name: "Flask", Version: "2.0.0"},
{Name: "itsdangerous", Version: "2.0.0"},
{Name: "Jinja2", Version: "3.0.0"},
}
requirementsNoVersion = []types.Library{
{Name: "Flask", Version: "2.0.0"},
}
requirementsOperator = []types.Library{
{Name: "Django", Version: "2.3.4"},
{Name: "SomeProject", Version: "5.4"},
}
requirementsHash = []types.Library{
{Name: "FooProject", Version: "1.2"},
{Name: "Jinja2", Version: "3.0.0"},
}
requirementsHyphens = []types.Library{
{Name: "oauth2-client", Version: "4.0.0"},
{Name: "python-gitlab", Version: "2.0.0"},
}
requirementsExtras = []types.Library{
{Name: "pyjwt", Version: "2.1.0"},
{Name: "celery", Version: "4.4.7"},
}
)
<file_sep>/pkg/nuget/config/parse.go
package config
import (
"encoding/xml"
"golang.org/x/xerrors"
dio "github.com/aquasecurity/go-dep-parser/pkg/io"
"github.com/aquasecurity/go-dep-parser/pkg/types"
"github.com/aquasecurity/go-dep-parser/pkg/utils"
)
type cfgPackageReference struct {
XMLName xml.Name `xml:"package"`
TargetFramework string `xml:"targetFramework,attr"`
Version string `xml:"version,attr"`
DevDependency bool `xml:"developmentDependency,attr"`
ID string `xml:"id,attr"`
}
type config struct {
XMLName xml.Name `xml:"packages"`
Packages []cfgPackageReference `xml:"package"`
}
type Parser struct{}
func NewParser() types.Parser {
return &Parser{}
}
func (p *Parser) Parse(r dio.ReadSeekerAt) ([]types.Library, []types.Dependency, error) {
var cfgData config
if err := xml.NewDecoder(r).Decode(&cfgData); err != nil {
return nil, nil, xerrors.Errorf("failed to decode .config file: %w", err)
}
libs := make([]types.Library, 0)
for _, pkg := range cfgData.Packages {
if pkg.ID == "" || pkg.DevDependency {
continue
}
lib := types.Library{
Name: pkg.ID,
Version: pkg.Version,
}
libs = append(libs, lib)
}
return utils.UniqueLibraries(libs), nil, nil
}
<file_sep>/pkg/ruby/bundler/parse.go
package bundler
import (
"bufio"
"sort"
"strings"
"golang.org/x/exp/maps"
"golang.org/x/xerrors"
dio "github.com/aquasecurity/go-dep-parser/pkg/io"
"github.com/aquasecurity/go-dep-parser/pkg/types"
"github.com/aquasecurity/go-dep-parser/pkg/utils"
)
type Parser struct{}
func NewParser() types.Parser {
return &Parser{}
}
func (p *Parser) Parse(r dio.ReadSeekerAt) ([]types.Library, []types.Dependency, error) {
libs := map[string]types.Library{}
var dependsOn, directDeps []string
var deps []types.Dependency
var pkgID string
lineNum := 1
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := scanner.Text()
// Parse dependencies
if countLeadingSpace(line) == 4 {
if len(dependsOn) > 0 {
deps = append(deps, types.Dependency{
ID: pkgID,
DependsOn: dependsOn,
})
}
dependsOn = make([]string, 0) //re-initialize
line = strings.TrimSpace(line)
s := strings.Fields(line)
if len(s) != 2 {
continue
}
version := strings.Trim(s[1], "()") // drop parentheses
version = strings.SplitN(version, "-", 2)[0] // drop platform (e.g. 1.13.6-x86_64-linux => 1.13.6)
name := s[0]
pkgID = utils.PackageID(name, version)
libs[name] = types.Library{
ID: pkgID,
Name: name,
Version: version,
Indirect: true,
Locations: []types.Location{{StartLine: lineNum, EndLine: lineNum}},
}
}
// Parse dependency graph
if countLeadingSpace(line) == 6 {
line = strings.TrimSpace(line)
s := strings.Fields(line)
dependsOn = append(dependsOn, s[0]) //store name only for now
}
lineNum++
// Parse direct dependencies
if line == "DEPENDENCIES" {
directDeps = parseDirectDeps(scanner)
}
}
// append last dependency (if any)
if len(dependsOn) > 0 {
deps = append(deps, types.Dependency{
ID: pkgID,
DependsOn: dependsOn,
})
}
// Identify which are direct dependencies
for _, d := range directDeps {
if l, ok := libs[d]; ok {
l.Indirect = false
libs[d] = l
}
}
for i, dep := range deps {
dependsOn = make([]string, 0)
for _, pkgName := range dep.DependsOn {
if lib, ok := libs[pkgName]; ok {
dependsOn = append(dependsOn, utils.PackageID(pkgName, lib.Version))
}
}
deps[i].DependsOn = dependsOn
}
if err := scanner.Err(); err != nil {
return nil, nil, xerrors.Errorf("scan error: %w", err)
}
libSlice := maps.Values(libs)
sort.Slice(libSlice, func(i, j int) bool {
return libSlice[i].Name < libSlice[j].Name
})
return libSlice, deps, nil
}
func countLeadingSpace(line string) int {
i := 0
for _, runeValue := range line {
if runeValue == ' ' {
i++
} else {
break
}
}
return i
}
// Parse "DEPENDENCIES"
func parseDirectDeps(scanner *bufio.Scanner) []string {
var deps []string
for scanner.Scan() {
line := scanner.Text()
if countLeadingSpace(line) != 2 {
// Reach another section
break
}
ss := strings.Fields(line)
if len(ss) == 0 {
continue
}
deps = append(deps, ss[0])
}
return deps
}
<file_sep>/pkg/nodejs/yarn/parse.go
package yarn
import (
"bufio"
"bytes"
"github.com/aquasecurity/go-dep-parser/pkg/log"
"io"
"regexp"
"strings"
dio "github.com/aquasecurity/go-dep-parser/pkg/io"
"github.com/aquasecurity/go-dep-parser/pkg/types"
"github.com/aquasecurity/go-dep-parser/pkg/utils"
"github.com/samber/lo"
"golang.org/x/xerrors"
)
var (
yarnPatternRegexp = regexp.MustCompile(`^\s?\\?"?(?P<package>\S+?)@(?:(?P<protocol>\S+?):)?(?P<version>.+?)\\?"?:?$`)
yarnVersionRegexp = regexp.MustCompile(`^"?version:?"?\s+"?(?P<version>[^"]+)"?`)
yarnDependencyRegexp = regexp.MustCompile(`\s{4,}"?(?P<package>.+?)"?:?\s"?(?P<version>[^"]+)"?`)
)
type LockFile struct {
Dependencies map[string]Dependency
}
type Library struct {
Patterns []string
Name string
Version string
Location types.Location
}
type Dependency struct {
Pattern string
Name string
}
type LineScanner struct {
*bufio.Scanner
lineCount int
}
func NewLineScanner(r io.Reader) *LineScanner {
return &LineScanner{
Scanner: bufio.NewScanner(r),
}
}
func (s *LineScanner) Scan() bool {
scan := s.Scanner.Scan()
if scan {
s.lineCount++
}
return scan
}
func (s *LineScanner) LineNum(prevNum int) int {
return prevNum + s.lineCount - 1
}
func parsePattern(target string) (packagename, protocol, version string, err error) {
capture := yarnPatternRegexp.FindStringSubmatch(target)
if len(capture) < 3 {
return "", "", "", xerrors.New("not package format")
}
for i, group := range yarnPatternRegexp.SubexpNames() {
switch group {
case "package":
packagename = capture[i]
case "protocol":
protocol = capture[i]
case "version":
version = capture[i]
}
}
return
}
func parsePackagePatterns(target string) (packagename, protocol string, patterns []string, err error) {
patternsSplit := strings.Split(target, ", ")
packagename, protocol, _, err = parsePattern(patternsSplit[0])
if err != nil {
return "", "", nil, err
}
patterns = lo.Map(patternsSplit, func(pattern string, _ int) string {
_, _, version, _ := parsePattern(pattern)
return utils.PackageID(packagename, version)
})
return
}
func getVersion(target string) (version string, err error) {
capture := yarnVersionRegexp.FindStringSubmatch(target)
if len(capture) < 2 {
return "", xerrors.Errorf("failed to parse version: '%s", target)
}
return capture[len(capture)-1], nil
}
func getDependency(target string) (name, version string, err error) {
capture := yarnDependencyRegexp.FindStringSubmatch(target)
if len(capture) < 3 {
return "", "", xerrors.New("not dependency")
}
return capture[1], capture[2], nil
}
func validProtocol(protocol string) bool {
switch protocol {
// only scan npm packages
case "npm", "":
return true
}
return false
}
func ignoreProtocol(protocol string) bool {
switch protocol {
case "workspace", "patch", "file", "link", "portal", "github", "git", "git+ssh", "git+http", "git+https", "git+file":
return true
}
return false
}
func parseResults(patternIDs map[string]string, dependsOn map[string][]string) (deps []types.Dependency) {
// find dependencies by patterns
for libID, depPatterns := range dependsOn {
depIDs := lo.Map(depPatterns, func(pattern string, index int) string {
return patternIDs[pattern]
})
deps = append(deps, types.Dependency{
ID: libID,
DependsOn: depIDs,
})
}
return deps
}
type Parser struct{}
func NewParser() types.Parser {
return &Parser{}
}
func scanBlocks(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
if i := bytes.Index(data, []byte("\n\n")); i >= 0 {
// We have a full newline-terminated line.
return i + 2, data[0:i], nil
} else if i := bytes.Index(data, []byte("\r\n\r\n")); i >= 0 {
return i + 4, data[0:i], nil
}
// If we're at EOF, we have a final, non-terminated line. Return it.
if atEOF {
return len(data), data, nil
}
// Request more data.
return 0, nil, nil
}
func parseBlock(block []byte, lineNum int) (lib Library, deps []string, newLine int, err error) {
var (
emptyLines int // lib can start with empty lines first
skipBlock bool
)
scanner := NewLineScanner(bytes.NewReader(block))
for scanner.Scan() {
line := scanner.Text()
if len(line) == 0 {
emptyLines++
continue
}
if line[0] == '#' || skipBlock {
continue
}
// Skip this block
if strings.HasPrefix(line, "__metadata") {
skipBlock = true
continue
}
line = strings.TrimPrefix(strings.TrimSpace(line), "\"")
switch {
case strings.HasPrefix(line, "version"):
if lib.Version, err = getVersion(line); err != nil {
skipBlock = true
}
continue
case strings.HasPrefix(line, "dependencies:"):
// start dependencies block
deps = parseDependencies(scanner)
continue
}
// try parse package patterns
if name, protocol, patterns, patternErr := parsePackagePatterns(line); patternErr == nil {
if patterns == nil || !validProtocol(protocol) {
skipBlock = true
if !ignoreProtocol(protocol) {
// we need to calculate the last line of the block in order to correctly determine the line numbers of the next blocks
// store the error. we will handle it later
err = xerrors.Errorf("unknown protocol: '%s', line: %s", protocol, line)
continue
}
continue
} else {
lib.Patterns = patterns
lib.Name = name
continue
}
}
}
// in case an unsupported protocol is detected
// show warning and continue parsing
if err != nil {
log.Logger.Warnf("Yarn protocol error: %s", err)
return Library{}, nil, scanner.LineNum(lineNum), nil
}
lib.Location = types.Location{
StartLine: lineNum + emptyLines,
EndLine: scanner.LineNum(lineNum),
}
if scanErr := scanner.Err(); scanErr != nil {
err = scanErr
}
return lib, deps, scanner.LineNum(lineNum), err
}
func parseDependencies(scanner *LineScanner) (deps []string) {
for scanner.Scan() {
line := scanner.Text()
if dep, err := parseDependency(line); err != nil {
// finished dependencies block
return deps
} else {
deps = append(deps, dep)
}
}
return
}
func parseDependency(line string) (string, error) {
if name, version, err := getDependency(line); err != nil {
return "", err
} else {
return utils.PackageID(name, version), nil
}
}
func (p *Parser) Parse(r dio.ReadSeekerAt) ([]types.Library, []types.Dependency, error) {
lineNumber := 1
var libs []types.Library
// patternIDs holds mapping between patterns and library IDs
// e.g. ajv@^6.5.5 => [email protected]
patternIDs := map[string]string{}
scanner := bufio.NewScanner(r)
scanner.Split(scanBlocks)
dependsOn := map[string][]string{}
for scanner.Scan() {
block := scanner.Bytes()
lib, deps, newLine, err := parseBlock(block, lineNumber)
lineNumber = newLine + 2
if err != nil {
return nil, nil, err
} else if lib.Name == "" {
continue
}
libID := utils.PackageID(lib.Name, lib.Version)
libs = append(libs, types.Library{
ID: libID,
Name: lib.Name,
Version: lib.Version,
Locations: []types.Location{lib.Location},
})
for _, pattern := range lib.Patterns {
// e.g.
// combined-stream@^1.0.6 => [email protected]
// combined-stream@~1.0.6 => [email protected]
patternIDs[pattern] = libID
if len(deps) > 0 {
dependsOn[libID] = deps
}
}
}
if err := scanner.Err(); err != nil {
return nil, nil, xerrors.Errorf("failed to scan yarn.lock, got scanner error: %s", err.Error())
}
// Replace dependency patterns with library IDs
// e.g. ajv@^6.5.5 => [email protected]
deps := parseResults(patternIDs, dependsOn)
return libs, deps, nil
}
<file_sep>/pkg/ruby/gemspec/testdata/license.gemspec
# -*- encoding: utf-8 -*-
# ... REDACTED ...
Gem::Specification.new do |spec|
spec.name = "async".freeze
spec.version = "1.25.0"
spec.license = "MIT"
# ... REDACTED ...
end
<file_sep>/pkg/php/composer/parse.go
package composer
import (
"io"
"sort"
"strings"
"github.com/liamg/jfather"
"golang.org/x/exp/maps"
"golang.org/x/xerrors"
dio "github.com/aquasecurity/go-dep-parser/pkg/io"
"github.com/aquasecurity/go-dep-parser/pkg/log"
"github.com/aquasecurity/go-dep-parser/pkg/types"
"github.com/aquasecurity/go-dep-parser/pkg/utils"
)
type lockFile struct {
Packages []packageInfo `json:"packages"`
}
type packageInfo struct {
Name string `json:"name"`
Version string `json:"version"`
Require map[string]string `json:"require"`
License []string `json:"license"`
StartLine int
EndLine int
}
type Parser struct{}
func NewParser() types.Parser {
return &Parser{}
}
func (p *Parser) Parse(r dio.ReadSeekerAt) ([]types.Library, []types.Dependency, error) {
var lockFile lockFile
input, err := io.ReadAll(r)
if err != nil {
return nil, nil, xerrors.Errorf("read error: %w", err)
}
if err = jfather.Unmarshal(input, &lockFile); err != nil {
return nil, nil, xerrors.Errorf("decode error: %w", err)
}
libs := map[string]types.Library{}
foundDeps := map[string][]string{}
for _, pkg := range lockFile.Packages {
lib := types.Library{
ID: utils.PackageID(pkg.Name, pkg.Version),
Name: pkg.Name,
Version: pkg.Version,
Indirect: false, // composer.lock file doesn't have info about Direct/Indirect deps. Will think that all dependencies are Direct
License: strings.Join(pkg.License, ", "),
Locations: []types.Location{
{
StartLine: pkg.StartLine,
EndLine: pkg.EndLine,
},
},
}
libs[lib.Name] = lib
var dependsOn []string
for depName := range pkg.Require {
// Require field includes required php version, skip this
// Also skip PHP extensions
if depName == "php" || strings.HasPrefix(depName, "ext") {
continue
}
dependsOn = append(dependsOn, depName) // field uses range of versions, so later we will fill in the versions from the libraries
}
if len(dependsOn) > 0 {
foundDeps[lib.ID] = dependsOn
}
}
// fill deps versions
var deps []types.Dependency
for libID, depsOn := range foundDeps {
var dependsOn []string
for _, depName := range depsOn {
if lib, ok := libs[depName]; ok {
dependsOn = append(dependsOn, lib.ID)
continue
}
log.Logger.Debugf("unable to find version of %s", depName)
}
sort.Strings(dependsOn)
deps = append(deps, types.Dependency{
ID: libID,
DependsOn: dependsOn,
})
}
libSlice := maps.Values(libs)
sort.Sort(types.Libraries(libSlice))
sort.Sort(types.Dependencies(deps))
return libSlice, deps, nil
}
// UnmarshalJSONWithMetadata needed to detect start and end lines of deps
func (t *packageInfo) UnmarshalJSONWithMetadata(node jfather.Node) error {
if err := node.Decode(&t); err != nil {
return err
}
// Decode func will overwrite line numbers if we save them first
t.StartLine = node.Range().Start.Line
t.EndLine = node.Range().End.Line
return nil
}
<file_sep>/pkg/nodejs/yarn/testcase_deps_generator/index.js
const fs = require('fs')
const yarnpkg = require('@yarnpkg/lockfile')
const YAML = require('yaml')
const formatYarnV2 = (yaml) => {
delete yaml.__metadata
delete yaml["code@workspace:."]
result = {}
for (const [key, value] of Object.entries(yaml)) {
for (const splitKey of key.split(', ')) {
result[splitKey] = value
}
}
for (const [key, value] of Object.entries(result)) {
if (key.includes('@npm:')) {
result[key.replace('@npm:', '@')] = value
delete result[key]
}
}
return result
}
const formatYarnV1 = (obj) => obj.object
const readLockFile = (filepath) => {
const file = fs.readFileSync(filepath, 'utf8')
try {
return formatYarnV1(yarnpkg.parse(file))
} catch (e) {
return formatYarnV2(YAML.parse(file))
}
}
const createResultObj = (yarnObj) => {
result = {}
for (const [key, value] of Object.entries(yarnObj)) {
if (value.dependencies) {
libId = key.split('@')[0] + '@' + value.version
for (const [depName, depVersion] of Object.entries(value.dependencies)) {
if (!result[libId]) {
result[libId] = {dependsOn: []}
}
depLocator = depName + '@' + depVersion
depObj = yarnObj[depLocator]
if (!depObj) {
a = 1
}
depId = depName + '@' + depObj.version
if (!result[libId].dependsOn.includes(depId)) {
result[libId].dependsOn.push(depId)
}
}
}
}
return result
}
const createResultString = (result) => {
res = "[]types.Dependency{\n"
for (const [key, value] of Object.entries(result)) {
res += '{\nID:"' + key + '",\n'
res += 'DependsOn: []string{\n"' + value.dependsOn.join('",\n"') + '",\n},\n},\n'
}
res += '}'
return res
}
var args = process.argv.slice(2);
filePath = args[0]
lockfile = readLockFile(filePath)
resultObj = createResultObj(lockfile)
resultString = createResultString(resultObj)
console.log(resultString)
<file_sep>/pkg/ruby/gemspec/testdata/malformed01.gemspec
# -*- encoding: utf-8 -*-
# ... REDACTED ...
# Missing version attribute.
Gem::Specification.new do |s|
s.name = "async".freeze
# ... REDACTED ...
end
<file_sep>/pkg/dotnet/core_deps/parse.go
package core_deps
import (
"github.com/liamg/jfather"
"io"
"strings"
"golang.org/x/xerrors"
dio "github.com/aquasecurity/go-dep-parser/pkg/io"
"github.com/aquasecurity/go-dep-parser/pkg/types"
"github.com/aquasecurity/go-dep-parser/pkg/log"
)
type Parser struct{}
func NewParser() types.Parser {
return &Parser{}
}
func (p *Parser) Parse(r dio.ReadSeekerAt) ([]types.Library, []types.Dependency, error) {
var depsFile dotNetDependencies
input, err := io.ReadAll(r)
if err != nil {
return nil, nil, xerrors.Errorf("read error: %w", err)
}
if err := jfather.Unmarshal(input, &depsFile); err != nil {
return nil, nil, xerrors.Errorf("failed to decode .deps.json file: %w", err)
}
var libraries []types.Library
for nameVer, lib := range depsFile.Libraries {
if !strings.EqualFold(lib.Type, "package") {
continue
}
split := strings.Split(nameVer, "/")
if len(split) != 2 {
// Invalid name
log.Logger.Warnf("Cannot parse .NET library version from: %s", nameVer)
continue
}
libraries = append(libraries, types.Library{
Name: split[0],
Version: split[1],
Locations: []types.Location{{StartLine: lib.StartLine, EndLine: lib.EndLine}},
})
}
return libraries, nil, nil
}
type dotNetDependencies struct {
Libraries map[string]dotNetLibrary `json:"libraries"`
}
type dotNetLibrary struct {
Type string `json:"type"`
StartLine int
EndLine int
}
// UnmarshalJSONWithMetadata needed to detect start and end lines of deps
func (t *dotNetLibrary) UnmarshalJSONWithMetadata(node jfather.Node) error {
if err := node.Decode(&t); err != nil {
return err
}
// Decode func will overwrite line numbers if we save them first
t.StartLine = node.Range().Start.Line
t.EndLine = node.Range().End.Line
return nil
}
<file_sep>/pkg/python/pip/parse_test.go
package pip
import (
"os"
"path"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
func TestParse(t *testing.T) {
vectors := []struct {
file string
want []types.Library
}{
{
file: "testdata/requirements_flask.txt",
want: requirementsFlask,
},
{
file: "testdata/requirements_comments.txt",
want: requirementsComments,
},
{
file: "testdata/requirements_spaces.txt",
want: requirementsSpaces,
},
{
file: "testdata/requirements_no_version.txt",
want: requirementsNoVersion,
},
{
file: "testdata/requirements_operator.txt",
want: requirementsOperator,
},
{
file: "testdata/requirements_hash.txt",
want: requirementsHash,
},
{
file: "testdata/requirements_hyphens.txt",
want: requirementsHyphens,
},
{
file: "testdata/requirement_exstras.txt",
want: requirementsExtras,
},
}
for _, v := range vectors {
t.Run(path.Base(v.file), func(t *testing.T) {
f, err := os.Open(v.file)
require.NoError(t, err)
got, _, err := NewParser().Parse(f)
require.NoError(t, err)
assert.Equal(t, v.want, got)
})
}
}
<file_sep>/pkg/golang/mod/testdata/normal/go.mod
module github.com/org/repo
go 1.17
require github.com/aquasecurity/go-dep-parser v0.0.0-20211224170007-df43bca6b6ff
require (
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
)
<file_sep>/pkg/python/packaging/parse_test.go
package packaging_test
import (
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/aquasecurity/go-dep-parser/pkg/python/packaging"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
func TestParse(t *testing.T) {
tests := []struct {
name string
input string
want []types.Library
wantErr bool
}{
// listing dependencies based on METADATA/PKG-INFO files
// docker run --name pipenv --rm -it python:3.7-alpine /bin/sh
// pip install pipenv
// find / -wholename "*(dist-info/METADATA|.egg-info/PKG-INFO)" | xargs -I {} sh -c 'cat {} | grep -e "^Name:" -e "^Version:" -e "^License:"' | tee METADATAS
// cat METADATAS | cut -d" " -f2- | tr "\n" "\t" | awk -F "\t" '{for(i=1;i<=NF;i=i+3){printf "\{\""$i"\", \""$(i+1)"\", \""$(i+2)"\"\}\n"}}'
{
name: "egg PKG-INFO",
input: "testdata/setuptools-51.3.3-py3.8.egg-info.PKG-INFO",
// docker run --name python --rm -it python:3.9-alpine sh
// apk add py3-setuptools
// cd /usr/lib/python3.9/site-packages/setuptools-52.0.0-py3.9.egg-info/
// cat PKG-INFO | grep -e "^Name:" -e "^Version:" -e "^License:" | cut -d" " -f2- | \
// tr "\n" "\t" | awk -F "\t" '{printf("\{\""$1"\", \""$2"\", \""$3"\"\}\n")}'
want: []types.Library{{Name: "setuptools", Version: "51.3.3", License: "UNKNOWN"}},
},
{
name: "egg-info",
input: "testdata/distlib-0.3.1-py3.9.egg-info",
// docker run --name python --rm -it python:3.9-alpine sh
// apk add py3-distlib
// cd /usr/lib/python3.9/site-packages/
// cat distlib-0.3.1-py3.9.egg-info | grep -e "^Name:" -e "^Version:" -e "^License:" | cut -d" " -f2- | \
// tr "\n" "\t" | awk -F "\t" '{printf("\{\""$1"\", \""$2"\", \""$3"\"\}\n")}'
want: []types.Library{{Name: "distlib", Version: "0.3.1", License: "Python license"}},
},
{
name: "wheel METADATA",
input: "testdata/simple-0.1.0.METADATA",
// finding relevant metadata files for tests
// mkdir dist-infos
// find / -wholename "*dist-info/METADATA" | rev | cut -d '/' -f2- | rev | xargs -I % cp -r % dist-infos/
// find dist-infos/ | grep -v METADATA | xargs rm -R
// for single METADATA file with known name
// cat "{{ libname }}.METADATA | grep -e "^Name:" -e "^Version:" -e "^License:" | cut -d" " -f2- | tr "\n" "\t" | awk -F "\t" '{printf("\{\""$1"\", \""$2"\", \""$3"\"\}\n")}'
want: []types.Library{{Name: "simple", Version: "0.1.0", License: ""}},
},
{
name: "wheel METADATA",
// for single METADATA file with known name
// cat "{{ libname }}.METADATA | grep -e "^Name:" -e "^Version:" -e "^License:" | cut -d" " -f2- | tr "\n" "\t" | awk -F "\t" '{printf("\{\""$1"\", \""$2"\", \""$3"\"\}\n")}'
input: "testdata/distlib-0.3.1.METADATA",
want: []types.Library{{Name: "distlib", Version: "0.3.1", License: "Python license"}},
},
{
name: "invalid",
input: "testdata/invalid.json",
wantErr: true,
},
{
name: "with License-Expression field",
input: "testdata/iniconfig-2.0.0.METADATA",
want: []types.Library{
{
Name: "iniconfig",
Version: "2.0.0",
License: "MIT",
},
},
},
{
name: "with an empty license field but with license in Classifier",
input: "testdata/zipp-3.12.1.METADATA",
want: []types.Library{
{
Name: "zipp",
Version: "3.12.1",
License: "MIT License",
},
},
},
{
name: "without licenses, but with a license file (a license in Classifier was removed)",
input: "testdata/networkx-3.0.METADATA",
want: []types.Library{
{
Name: "networkx",
Version: "3.0",
License: "file://LICENSE.txt",
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f, err := os.Open(tt.input)
require.NoError(t, err)
got, _, err := packaging.NewParser().Parse(f)
require.Equal(t, tt.wantErr, err != nil)
assert.Equal(t, tt.want, got)
})
}
}
<file_sep>/pkg/python/pyproject/pyproject.go
package pyproject
import (
"io"
"github.com/BurntSushi/toml"
"golang.org/x/xerrors"
)
type PyProject struct {
Tool Tool `toml:"tool"`
}
type Tool struct {
Poetry Poetry `toml:"poetry"`
}
type Poetry struct {
Dependencies map[string]interface{} `toml:"dependencies"`
}
// Parser parses pyproject.toml defined in PEP518.
// https://peps.python.org/pep-0518/
type Parser struct {
}
func NewParser() *Parser {
return &Parser{}
}
func (p *Parser) Parse(r io.Reader) (map[string]interface{}, error) {
var conf PyProject
if _, err := toml.NewDecoder(r).Decode(&conf); err != nil {
return nil, xerrors.Errorf("toml decode error: %w", err)
}
return conf.Tool.Poetry.Dependencies, nil
}
<file_sep>/pkg/swift/cocoapods/parse_test.go
package cocoapods_test
import (
"os"
"testing"
"github.com/aquasecurity/go-dep-parser/pkg/swift/cocoapods"
"github.com/aquasecurity/go-dep-parser/pkg/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestParse(t *testing.T) {
tests := []struct {
name string
inputFile string // Test input file
wantLibs []types.Library
wantDeps []types.Dependency
}{
{
name: "happy path",
inputFile: "testdata/happy.lock",
wantLibs: []types.Library{
{
ID: "AppCenter/[email protected]",
Name: "AppCenter/Analytics",
Version: "4.2.0",
},
{
ID: "AppCenter/[email protected]",
Name: "AppCenter/Core",
Version: "4.2.0",
},
{
ID: "AppCenter/[email protected]",
Name: "AppCenter/Crashes",
Version: "4.2.0",
},
{
ID: "[email protected]",
Name: "AppCenter",
Version: "4.2.0",
},
{
ID: "[email protected]",
Name: "KeychainAccess",
Version: "4.2.1",
},
},
wantDeps: []types.Dependency{
{
ID: "AppCenter/[email protected]",
DependsOn: []string{
"AppCenter/[email protected]",
},
},
{
ID: "AppCenter/[email protected]",
DependsOn: []string{
"AppCenter/[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"AppCenter/[email protected]",
"AppCenter/[email protected]",
},
},
},
},
{
name: "happy path. lock file without dependencies",
inputFile: "testdata/empty.lock",
},
{
name: "sad path. wrong dep format",
inputFile: "testdata/sad.lock",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f, err := os.Open(tt.inputFile)
require.NoError(t, err)
defer f.Close()
gotLibs, gotDeps, err := cocoapods.NewParser().Parse(f)
require.NoError(t, err)
assert.Equal(t, tt.wantLibs, gotLibs)
assert.Equal(t, tt.wantDeps, gotDeps)
})
}
}
<file_sep>/pkg/java/pom/artifact.go
package pom
import (
"fmt"
"os"
"regexp"
"strings"
"github.com/aquasecurity/go-dep-parser/pkg/log"
"github.com/samber/lo"
"golang.org/x/exp/slices"
)
var (
varRegexp = regexp.MustCompile(`\${(\S+?)}`)
)
type artifact struct {
GroupID string
ArtifactID string
Version version
Licenses []string
Exclusions map[string]struct{}
Module bool
Root bool
Direct bool
}
func newArtifact(groupID, artifactID, version string, licenses []string, props map[string]string) artifact {
return artifact{
GroupID: evaluateVariable(groupID, props, nil),
ArtifactID: evaluateVariable(artifactID, props, nil),
Version: newVersion(evaluateVariable(version, props, nil)),
Licenses: licenses,
}
}
func (a artifact) IsEmpty() bool {
return a.GroupID == "" || a.ArtifactID == "" || a.Version.String() == ""
}
func (a artifact) Equal(o artifact) bool {
return a.GroupID == o.GroupID || a.ArtifactID == o.ArtifactID || a.Version.String() == o.Version.String()
}
func (a artifact) JoinLicenses() string {
return strings.Join(a.Licenses, ", ")
}
func (a artifact) ToPOMLicenses() pomLicenses {
return pomLicenses{License: lo.Map(a.Licenses, func(lic string, _ int) pomLicense {
return pomLicense{Name: lic}
})}
}
func (a artifact) Inherit(parent artifact) artifact {
// inherited from a parent
if a.GroupID == "" {
a.GroupID = parent.GroupID
}
if len(a.Licenses) == 0 {
a.Licenses = parent.Licenses
}
if a.Version.String() == "" {
a.Version = parent.Version
}
return a
}
func (a artifact) Name() string {
return fmt.Sprintf("%s:%s", a.GroupID, a.ArtifactID)
}
func (a artifact) String() string {
return fmt.Sprintf("%s:%s", a.Name(), a.Version)
}
type version struct {
ver string
hard bool
}
// Only soft and hard requirements for the specified version are supported at the moment.
func newVersion(s string) version {
var hard bool
if strings.HasPrefix(s, "[") && strings.HasSuffix(s, "]") {
s = strings.Trim(s, "[]")
hard = true
}
// TODO: Other requirements are not supported
if strings.ContainsAny(s, ",()[]") {
s = ""
}
return version{
ver: s,
hard: hard,
}
}
func (v1 version) shouldOverride(v2 version) bool {
if !v1.hard && v2.hard {
return true
}
return false
}
func (v1 version) String() string {
return v1.ver
}
func evaluateVariable(s string, props map[string]string, seenProps []string) string {
if props == nil {
props = map[string]string{}
}
for _, m := range varRegexp.FindAllStringSubmatch(s, -1) {
var newValue string
// env.X: https://maven.apache.org/pom.html#Properties
// e.g. env.PATH
if strings.HasPrefix(m[1], "env.") {
newValue = os.Getenv(strings.TrimPrefix(m[1], "env."))
} else {
// <properties> might include another property.
// e.g. <animal.sniffer.skip>${skipTests}</animal.sniffer.skip>
ss, ok := props[m[1]]
if ok {
// search for looped properties
if slices.Contains(seenProps, ss) {
printLoopedPropertiesStack(m[0], seenProps)
return ""
}
seenProps = append(seenProps, ss) // save evaluated props to check if we get this prop again
newValue = evaluateVariable(ss, props, seenProps)
seenProps = []string{} // clear props if we returned from recursive. Required for correct work with 2 same props like ${foo}-${foo}
}
}
s = strings.ReplaceAll(s, m[0], newValue)
}
return s
}
func printLoopedPropertiesStack(env string, usedProps []string) {
var s string
for _, prop := range usedProps {
s += fmt.Sprintf("%s -> ", prop)
}
log.Logger.Warnf("Lopped properties were detected: %s%s", s, env)
}
<file_sep>/pkg/dart/pub/parse_test.go
package pub_test
import (
"fmt"
"os"
"sort"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/aquasecurity/go-dep-parser/pkg/dart/pub"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
func TestParser_Parse(t *testing.T) {
tests := []struct {
name string
inputFile string
want []types.Library
wantErr assert.ErrorAssertionFunc
}{
{
name: "happy path",
inputFile: "testdata/happy.lock",
want: []types.Library{
{
ID: "[email protected]",
Name: "crypto",
Version: "3.0.2",
},
{
ID: "[email protected]",
Name: "flutter_test",
Version: "0.0.0",
},
{
ID: "[email protected]",
Name: "uuid",
Version: "3.0.6",
Indirect: true,
},
},
wantErr: assert.NoError,
},
{
name: "empty path",
inputFile: "testdata/empty.lock",
wantErr: assert.NoError,
},
{
name: "broken yaml",
inputFile: "testdata/broken.lock",
wantErr: assert.Error,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f, err := os.Open(tt.inputFile)
require.NoError(t, err)
defer f.Close()
gotLibs, _, err := pub.NewParser().Parse(f)
if !tt.wantErr(t, err, fmt.Sprintf("Parse(%v)", tt.inputFile)) {
return
}
sort.Slice(gotLibs, func(i, j int) bool {
return gotLibs[i].ID < gotLibs[j].ID
})
assert.Equal(t, tt.want, gotLibs)
})
}
}
<file_sep>/pkg/python/pip/parse.go
package pip
import (
"bufio"
"strings"
"unicode"
dio "github.com/aquasecurity/go-dep-parser/pkg/io"
"github.com/aquasecurity/go-dep-parser/pkg/types"
"golang.org/x/xerrors"
)
const (
commentMarker string = "#"
endColon string = ";"
hashMarker string = "--"
startExtras string = "["
endExtras string = "]"
)
type Parser struct{}
func NewParser() types.Parser {
return &Parser{}
}
func (p *Parser) Parse(r dio.ReadSeekerAt) ([]types.Library, []types.Dependency, error) {
scanner := bufio.NewScanner(r)
var libs []types.Library
for scanner.Scan() {
line := scanner.Text()
line = strings.ReplaceAll(line, " ", "")
line = strings.ReplaceAll(line, `\`, "")
line = removeExtras(line)
line = rStripByKey(line, commentMarker)
line = rStripByKey(line, endColon)
line = rStripByKey(line, hashMarker)
s := strings.Split(line, "==")
if len(s) != 2 {
continue
}
libs = append(libs, types.Library{
Name: s[0],
Version: s[1],
})
}
if err := scanner.Err(); err != nil {
return nil, nil, xerrors.Errorf("scan error: %w", err)
}
return libs, nil, nil
}
func rStripByKey(line string, key string) string {
if pos := strings.Index(line, key); pos >= 0 {
line = strings.TrimRightFunc((line)[:pos], unicode.IsSpace)
}
return line
}
func removeExtras(line string) string {
startIndex := strings.Index(line, startExtras)
endIndex := strings.Index(line, endExtras) + 1
if startIndex != -1 && endIndex != -1 {
line = line[:startIndex] + line[endIndex:]
}
return line
}
<file_sep>/pkg/golang/mod/testdata/no-go-version/go.mod
module github.com/org/repo
require github.com/aquasecurity/go-dep-parser v0.0.0-20211224170007-df43bca6b6ff<file_sep>/pkg/nuget/lock/parse.go
package lock
import (
"io"
"github.com/liamg/jfather"
"golang.org/x/xerrors"
dio "github.com/aquasecurity/go-dep-parser/pkg/io"
"github.com/aquasecurity/go-dep-parser/pkg/types"
"github.com/aquasecurity/go-dep-parser/pkg/utils"
)
type LockFile struct {
Version int `json:"version"`
Targets map[string]Dependencies `json:"dependencies"`
}
type Dependencies map[string]Dependency
type Dependency struct {
Type string `json:"type"`
Resolved string `json:"resolved"`
StartLine int
EndLine int
Dependencies map[string]string `json:"dependencies,omitempty"`
}
type Parser struct{}
func NewParser() types.Parser {
return &Parser{}
}
func (p *Parser) Parse(r dio.ReadSeekerAt) ([]types.Library, []types.Dependency, error) {
var lockFile LockFile
input, err := io.ReadAll(r)
if err != nil {
return nil, nil, xerrors.Errorf("failed to read packages.lock.json: %w", err)
}
if err := jfather.Unmarshal(input, &lockFile); err != nil {
return nil, nil, xerrors.Errorf("failed to decode packages.lock.json: %w", err)
}
libs := make([]types.Library, 0)
depsMap := make(map[string][]string)
for _, targetContent := range lockFile.Targets {
for packageName, packageContent := range targetContent {
// If package type is "project", it is the actual project, and we skip it.
if packageContent.Type == "Project" {
continue
}
depId := utils.PackageID(packageName, packageContent.Resolved)
lib := types.Library{
ID: depId,
Name: packageName,
Version: packageContent.Resolved,
Indirect: packageContent.Type != "Direct",
Locations: []types.Location{
{
StartLine: packageContent.StartLine,
EndLine: packageContent.EndLine,
},
},
}
libs = append(libs, lib)
var dependsOn []string
for depName := range packageContent.Dependencies {
dependsOn = append(dependsOn, utils.PackageID(depName, targetContent[depName].Resolved))
}
if savedDependsOn, ok := depsMap[depId]; ok {
dependsOn = utils.UniqueStrings(append(dependsOn, savedDependsOn...))
}
if len(dependsOn) > 0 {
depsMap[depId] = dependsOn
}
}
}
deps := make([]types.Dependency, 0)
for depId, dependsOn := range depsMap {
dep := types.Dependency{
ID: depId,
DependsOn: dependsOn,
}
deps = append(deps, dep)
}
return utils.UniqueLibraries(libs), deps, nil
}
// UnmarshalJSONWithMetadata needed to detect start and end lines of deps
func (t *Dependency) UnmarshalJSONWithMetadata(node jfather.Node) error {
if err := node.Decode(&t); err != nil {
return err
}
// Decode func will overwrite line numbers if we save them first
t.StartLine = node.Range().Start.Line
t.EndLine = node.Range().End.Line
return nil
}
<file_sep>/pkg/java/jar/testdata/testimage/gradle/build.gradle
plugins {
id 'application'
id 'war'
}
repositories {
// Use JCenter for resolving dependencies.
jcenter()
}
dependencies {
// Use JUnit test framework.
testImplementation 'junit:junit:4.13'
implementation 'commons-dbcp:commons-dbcp:1.4'
implementation 'commons-pool:commons-pool:1.6'
implementation 'log4j:log4j:1.2.17'
implementation 'org.apache.commons:commons-compress:1.19'
}
application {
// Define the main class for the application.
mainClass = 'gradle.App'
}
<file_sep>/pkg/golang/mod/parse_testcase.go
package mod
import "github.com/aquasecurity/go-dep-parser/pkg/types"
var (
// execute go mod tidy in normal folder
GoModNormal = []types.Library{
{
ID: "github.com/aquasecurity/[email protected]",
Name: "github.com/aquasecurity/go-dep-parser",
Version: "0.0.0-20211224170007-df43bca6b6ff",
Indirect: false,
ExternalReferences: []types.ExternalRef{
{
Type: types.RefVCS,
URL: "https://github.com/aquasecurity/go-dep-parser",
},
},
},
{
ID: "golang.org/x/[email protected]",
Name: "golang.org/x/xerrors",
Version: "0.0.0-20200804184101-5ec99f83aff1",
Indirect: true,
},
{
ID: "gopkg.in/[email protected]",
Name: "gopkg.in/yaml.v3",
Version: "3.0.0-20210107192922-496545a6307b",
Indirect: true,
ExternalReferences: []types.ExternalRef{
{
Type: types.RefVCS,
URL: "https://github.com/go-yaml/yaml",
},
},
},
}
// execute go mod tidy in replaced folder
GoModReplaced = []types.Library{
{
ID: "github.com/aquasecurity/[email protected]",
Name: "github.com/aquasecurity/go-dep-parser",
Version: "0.0.0-20220406074731-71021a481237",
Indirect: false,
ExternalReferences: []types.ExternalRef{
{
Type: types.RefVCS,
URL: "https://github.com/aquasecurity/go-dep-parser",
},
},
},
{
ID: "golang.org/x/[email protected]",
Name: "golang.org/x/xerrors",
Version: "0.0.0-20200804184101-5ec99f83aff1",
Indirect: true,
},
}
// execute go mod tidy in replaced folder
GoModUnreplaced = []types.Library{
{
ID: "github.com/aquasecurity/[email protected]",
Name: "github.com/aquasecurity/go-dep-parser",
Version: "0.0.0-20211110174639-8257534ffed3",
Indirect: false,
ExternalReferences: []types.ExternalRef{
{
Type: types.RefVCS,
URL: "https://github.com/aquasecurity/go-dep-parser",
},
},
},
{
ID: "golang.org/x/[email protected]",
Name: "golang.org/x/xerrors",
Version: "0.0.0-20200804184101-5ec99f83aff1",
Indirect: true,
},
}
// execute go mod tidy in replaced-with-version folder
GoModReplacedWithVersion = []types.Library{
{
ID: "github.com/aquasecurity/[email protected]",
Name: "github.com/aquasecurity/go-dep-parser",
Version: "0.0.0-20220406074731-71021a481237",
Indirect: false,
ExternalReferences: []types.ExternalRef{
{
Type: types.RefVCS,
URL: "https://github.com/aquasecurity/go-dep-parser",
},
},
},
{
ID: "golang.org/x/[email protected]",
Name: "golang.org/x/xerrors",
Version: "0.0.0-20200804184101-5ec99f83aff1",
Indirect: true,
},
}
// execute go mod tidy in replaced-with-version-mismatch folder
GoModReplacedWithVersionMismatch = []types.Library{
{
ID: "github.com/aquasecurity/[email protected]",
Name: "github.com/aquasecurity/go-dep-parser",
Version: "0.0.0-20211224170007-df43bca6b6ff",
Indirect: false,
ExternalReferences: []types.ExternalRef{
{
Type: types.RefVCS,
URL: "https://github.com/aquasecurity/go-dep-parser",
},
},
},
{
ID: "golang.org/x/[email protected]",
Name: "golang.org/x/xerrors",
Version: "0.0.0-20200804184101-5ec99f83aff1",
Indirect: true,
},
{
ID: "gopkg.in/[email protected]",
Name: "gopkg.in/yaml.v3",
Version: "3.0.0-20210107192922-496545a6307b",
Indirect: true,
ExternalReferences: []types.ExternalRef{
{
Type: types.RefVCS,
URL: "https://github.com/go-yaml/yaml",
},
},
},
}
// execute go mod tidy in replaced-with-local-path folder
GoModReplacedWithLocalPath = []types.Library{
{
ID: "github.com/aquasecurity/[email protected]",
Name: "github.com/aquasecurity/go-dep-parser",
Version: "0.0.0-20211224170007-df43bca6b6ff",
Indirect: false,
ExternalReferences: []types.ExternalRef{
{
Type: types.RefVCS,
URL: "https://github.com/aquasecurity/go-dep-parser",
},
},
},
{
ID: "gopkg.in/[email protected]",
Name: "gopkg.in/yaml.v3",
Version: "3.0.0-20210107192922-496545a6307b",
Indirect: true,
ExternalReferences: []types.ExternalRef{
{
Type: types.RefVCS,
URL: "https://github.com/go-yaml/yaml",
},
},
},
}
// execute go mod tidy in replaced-with-local-path-and-version folder
GoModReplacedWithLocalPathAndVersion = []types.Library{
{
ID: "github.com/aquasecurity/[email protected]",
Name: "github.com/aquasecurity/go-dep-parser",
Version: "0.0.0-20211224170007-df43bca6b6ff",
Indirect: false,
ExternalReferences: []types.ExternalRef{
{
Type: types.RefVCS,
URL: "https://github.com/aquasecurity/go-dep-parser",
},
},
},
{
ID: "gopkg.in/[email protected]",
Name: "gopkg.in/yaml.v3",
Version: "3.0.0-20210107192922-496545a6307b",
Indirect: true,
ExternalReferences: []types.ExternalRef{
{
Type: types.RefVCS,
URL: "https://github.com/go-yaml/yaml",
},
},
},
}
// execute go mod tidy in replaced-with-local-path-and-version-mismatch folder
GoModReplacedWithLocalPathAndVersionMismatch = []types.Library{
{
ID: "github.com/aquasecurity/[email protected]",
Name: "github.com/aquasecurity/go-dep-parser",
Version: "0.0.0-20211224170007-df43bca6b6ff",
Indirect: false,
ExternalReferences: []types.ExternalRef{
{
Type: types.RefVCS,
URL: "https://github.com/aquasecurity/go-dep-parser",
},
},
},
{
ID: "golang.org/x/[email protected]",
Name: "golang.org/x/xerrors",
Version: "0.0.0-20200804184101-5ec99f83aff1",
Indirect: true,
},
{
ID: "gopkg.in/[email protected]",
Name: "gopkg.in/yaml.v3",
Version: "3.0.0-20210107192922-496545a6307b",
Indirect: true,
ExternalReferences: []types.ExternalRef{
{
Type: types.RefVCS,
URL: "https://github.com/go-yaml/yaml",
},
},
},
}
// execute go mod tidy in go116 folder
GoMod116 = []types.Library{
{
ID: "github.com/aquasecurity/[email protected]",
Name: "github.com/aquasecurity/go-dep-parser",
Version: "0.0.0-20211224170007-df43bca6b6ff",
Indirect: false,
ExternalReferences: []types.ExternalRef{
{
Type: types.RefVCS,
URL: "https://github.com/aquasecurity/go-dep-parser",
},
},
},
}
// execute go mod tidy in no-go-version folder
GoModNoGoVersion = []types.Library{
{
ID: "github.com/aquasecurity/[email protected]",
Name: "github.com/aquasecurity/go-dep-parser",
Version: "0.0.0-20211224170007-df43bca6b6ff",
Indirect: false,
ExternalReferences: []types.ExternalRef{
{
Type: types.RefVCS,
URL: "https://github.com/aquasecurity/go-dep-parser",
},
},
},
}
)
<file_sep>/pkg/frameworks/wordpress/parse_test.go
package wordpress
import (
"os"
"path"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
func TestParseWordPress(t *testing.T) {
tests := []struct {
file string // Test input file
want types.Library
wantErr string
}{
{
file: "testdata/version.php",
want: types.Library{
Name: "wordpress",
Version: "4.9.4-alpha",
},
},
{
file: "testdata/versionFail.php",
wantErr: "version.php could not be parsed",
},
}
for _, tt := range tests {
t.Run(path.Base(tt.file), func(t *testing.T) {
f, err := os.Open(tt.file)
require.NoError(t, err)
got, err := Parse(f)
if tt.wantErr != "" {
require.Error(t, err)
assert.Contains(t, err.Error(), tt.wantErr)
return
}
require.NoError(t, err)
assert.Equal(t, tt.want, got)
})
}
}
<file_sep>/pkg/python/pip/testdata/requirements_spaces.txt
click == 8.0.0
Flask ==2.0.0
itsdangerous== 2.0.0
Jinja2 == 3.0.0 # comment
<file_sep>/pkg/swift/swift/types.go
package swift
type LockFile struct {
Object Object `json:"object"`
Pins []Pin `json:"pins"`
Version int `json:"version"`
}
type Object struct {
Pins []Pin `json:"pins"`
}
type Pin struct {
Package string `json:"package"`
RepositoryURL string `json:"repositoryURL"` // Package.revision v1
Location string `json:"location"` // Package.revision v2
State State `json:"state"`
StartLine int
EndLine int
}
type State struct {
Branch any `json:"branch"`
Revision string `json:"revision"`
Version string `json:"version"`
}
<file_sep>/pkg/rust/cargo/parse.go
package cargo
import (
"io"
"sort"
"strings"
"github.com/BurntSushi/toml"
dio "github.com/aquasecurity/go-dep-parser/pkg/io"
"github.com/aquasecurity/go-dep-parser/pkg/log"
"github.com/aquasecurity/go-dep-parser/pkg/types"
"github.com/aquasecurity/go-dep-parser/pkg/utils"
"github.com/samber/lo"
"golang.org/x/xerrors"
)
type cargoPkg struct {
Name string `toml:"name"`
Version string `toml:"version"`
Source string `toml:"source,omitempty"`
Dependencies []string `toml:"dependencies,omitempty"`
}
type Lockfile struct {
Packages []cargoPkg `toml:"package"`
}
type Parser struct{}
func NewParser() types.Parser {
return &Parser{}
}
func (p *Parser) Parse(r dio.ReadSeekerAt) ([]types.Library, []types.Dependency, error) {
var lockfile Lockfile
decoder := toml.NewDecoder(r)
if _, err := decoder.Decode(&lockfile); err != nil {
return nil, nil, xerrors.Errorf("decode error: %w", err)
}
if _, err := r.Seek(0, io.SeekStart); err != nil {
return nil, nil, xerrors.Errorf("seek error: %w", err)
}
// naive parser to get line numbers by package from lock file
pkgParser := naivePkgParser{r: r}
lineNumIdx := pkgParser.parse()
// We need to get version for unique dependencies for lockfile v3 from lockfile.Packages
pkgs := lo.SliceToMap(lockfile.Packages, func(pkg cargoPkg) (string, cargoPkg) {
return pkg.Name, pkg
})
var libs []types.Library
var deps []types.Dependency
for _, pkg := range lockfile.Packages {
pkgID := utils.PackageID(pkg.Name, pkg.Version)
lib := types.Library{
ID: pkgID,
Name: pkg.Name,
Version: pkg.Version,
}
if pos, ok := lineNumIdx[pkgID]; ok {
lib.Locations = []types.Location{{StartLine: pos.start, EndLine: pos.end}}
}
libs = append(libs, lib)
dep := parseDependencies(pkgID, pkg, pkgs)
if dep != nil {
deps = append(deps, *dep)
}
}
sort.Sort(types.Libraries(libs))
sort.Sort(types.Dependencies(deps))
return libs, deps, nil
}
func parseDependencies(pkgId string, pkg cargoPkg, pkgs map[string]cargoPkg) *types.Dependency {
var dependOn []string
for _, pkgDep := range pkg.Dependencies {
/*
Dependency entries look like:
old Cargo.lock - https://github.com/rust-lang/cargo/blob/46bac2dc448ab12fe0f182bee8d35cc804d9a6af/tests/testsuite/lockfile_compat.rs#L48-L50
"unsafe-any 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)"
new Cargo.lock -https://github.com/rust-lang/cargo/blob/46bac2dc448ab12fe0f182bee8d35cc804d9a6af/tests/testsuite/lockfile_compat.rs#L39-L41
"unsafe-any" - if lock file contains only 1 version of dependency
"unsafe-any 0.4.2" if lock file contains more than 1 version of dependency
*/
fields := strings.Fields(pkgDep)
switch len(fields) {
// unique dependency in new lock file
case 1:
name := fields[0]
version, ok := pkgs[name]
if !ok {
log.Logger.Debugf("can't find version for %s", name)
continue
}
dependOn = append(dependOn, utils.PackageID(name, version.Version))
// 2: non-unique dependency in new lock file
// 3: old lock file
case 2, 3:
dependOn = append(dependOn, utils.PackageID(fields[0], fields[1]))
default:
log.Logger.Debugf("wrong dependency format for %s", pkgDep)
continue
}
}
if len(dependOn) > 0 {
sort.Strings(dependOn)
return &types.Dependency{
ID: pkgId,
DependsOn: dependOn,
}
} else {
return nil
}
}
<file_sep>/pkg/java/jar/parse_test.go
package jar_test
import (
"encoding/json"
"github.com/aquasecurity/go-dep-parser/pkg/java/jar/sonatype"
"net/http"
"net/http/httptest"
"os"
"sort"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/aquasecurity/go-dep-parser/pkg/java/jar"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
var (
// cd testdata/testimage/maven && docker build -t test .
// docker run --rm --name test -it test bash
// mvn dependency:list
// mvn dependency:tree -Dscope=compile -Dscope=runtime | awk '/:tree/,/BUILD SUCCESS/' | awk 'NR > 1 { print }' | head -n -2 | awk '{print $NF}' | awk -F":" '{printf("{\""$1":"$2"\", \""$4 "\", \"\"},\n")}'
// paths filled in manually
wantMaven = []types.Library{
{
Name: "com.example:web-app",
Version: "1.0-SNAPSHOT",
FilePath: "testdata/maven.war",
},
{
Name: "com.fasterxml.jackson.core:jackson-databind",
Version: "2.9.10.6",
FilePath: "testdata/maven.war/WEB-INF/lib/jackson-databind-2.9.10.6.jar",
},
{
Name: "com.fasterxml.jackson.core:jackson-annotations",
Version: "2.9.10",
FilePath: "testdata/maven.war/WEB-INF/lib/jackson-annotations-2.9.10.jar",
},
{
Name: "com.fasterxml.jackson.core:jackson-core",
Version: "2.9.10",
FilePath: "testdata/maven.war/WEB-INF/lib/jackson-core-2.9.10.jar",
},
{
Name: "com.cronutils:cron-utils",
Version: "9.1.2",
FilePath: "testdata/maven.war/WEB-INF/lib/cron-utils-9.1.2.jar",
},
{
Name: "org.slf4j:slf4j-api",
Version: "1.7.30",
FilePath: "testdata/maven.war/WEB-INF/lib/slf4j-api-1.7.30.jar",
},
{
Name: "org.glassfish:javax.el",
Version: "3.0.0",
FilePath: "testdata/maven.war/WEB-INF/lib/javax.el-3.0.0.jar",
},
{
Name: "org.apache.commons:commons-lang3",
Version: "3.11",
FilePath: "testdata/maven.war/WEB-INF/lib/commons-lang3-3.11.jar",
},
}
// cd testdata/testimage/gradle && docker build -t test .
// docker run --rm --name test -it test bash
// gradle app:dependencies --configuration implementation | grep "[+\]---" | cut -d" " -f2 | awk -F":" '{printf("{\""$1":"$2"\", \""$3"\", \"\"},\n")}'
// paths filled in manually
wantGradle = []types.Library{
{
Name: "commons-dbcp:commons-dbcp",
Version: "1.4",
FilePath: "testdata/gradle.war/WEB-INF/lib/commons-dbcp-1.4.jar",
},
{
Name: "commons-pool:commons-pool",
Version: "1.6",
FilePath: "testdata/gradle.war/WEB-INF/lib/commons-pool-1.6.jar",
},
{
Name: "log4j:log4j",
Version: "1.2.17",
FilePath: "testdata/gradle.war/WEB-INF/lib/log4j-1.2.17.jar",
},
{
Name: "org.apache.commons:commons-compress",
Version: "1.19",
FilePath: "testdata/gradle.war/WEB-INF/lib/commons-compress-1.19.jar",
},
}
// manually created
wantSHA1 = []types.Library{
{
Name: "org.springframework:spring-core",
Version: "5.3.3",
FilePath: "testdata/test.jar",
},
}
// offline
wantOffline = []types.Library{
{
Name: "org.springframework:Spring Framework",
Version: "2.5.6.SEC03",
FilePath: "testdata/test.jar",
},
}
// manually created
wantHeuristic = []types.Library{
{
Name: "com.example:heuristic",
Version: "1.0.0-SNAPSHOT",
FilePath: "testdata/heuristic-1.0.0-SNAPSHOT.jar",
},
}
// manually created
wantFatjar = []types.Library{
{
Name: "com.google.guava:failureaccess",
Version: "1.0.1",
FilePath: "testdata/hadoop-shaded-guava-1.1.0-SNAPSHOT.jar",
},
{
Name: "com.google.guava:guava",
Version: "29.0-jre",
FilePath: "testdata/hadoop-shaded-guava-1.1.0-SNAPSHOT.jar",
},
{
Name: "com.google.guava:listenablefuture",
Version: "9999.0-empty-to-avoid-conflict-with-guava",
FilePath: "testdata/hadoop-shaded-guava-1.1.0-SNAPSHOT.jar",
},
{
Name: "com.google.j2objc:j2objc-annotations",
Version: "1.3",
FilePath: "testdata/hadoop-shaded-guava-1.1.0-SNAPSHOT.jar",
},
{
Name: "org.apache.hadoop.thirdparty:hadoop-shaded-guava",
Version: "1.1.0-SNAPSHOT",
FilePath: "testdata/hadoop-shaded-guava-1.1.0-SNAPSHOT.jar",
},
}
// manually created
wantNestedJar = []types.Library{
{
Name: "test:nested",
Version: "0.0.1",
FilePath: "testdata/nested.jar",
},
{
Name: "test:nested2",
Version: "0.0.2",
FilePath: "testdata/nested.jar/META-INF/jars/nested2.jar",
},
{
Name: "test:nested3",
Version: "0.0.3",
FilePath: "testdata/nested.jar/META-INF/jars/nested2.jar/META-INF/jars/nested3.jar",
},
}
// manually created
wantDuplicatesJar = []types.Library{
{
Name: "io.quarkus.gizmo:gizmo",
Version: "1.1.1.Final",
FilePath: "testdata/io.quarkus.gizmo.gizmo-1.1.1.Final.jar",
},
{
Name: "log4j:log4j",
Version: "1.2.16",
FilePath: "testdata/io.quarkus.gizmo.gizmo-1.1.1.Final.jar/jars/log4j-1.2.16.jar",
},
{
Name: "log4j:log4j",
Version: "1.2.17",
FilePath: "testdata/io.quarkus.gizmo.gizmo-1.1.1.Final.jar/jars/log4j-1.2.17.jar",
},
}
)
type apiResponse struct {
Response response `json:"response"`
}
type response struct {
NumFound int `json:"numFound"`
Docs []doc `json:"docs"`
}
type doc struct {
ID string `json:"id"`
GroupID string `json:"g"`
ArtifactID string `json:"a"`
Version string `json:"v"`
P string `json:"p"`
VersionCount int `json:versionCount`
}
func TestParse(t *testing.T) {
vectors := []struct {
name string
file string // Test input file
offline bool
want []types.Library
}{
{
name: "maven",
file: "testdata/maven.war",
want: wantMaven,
},
{
name: "gradle",
file: "testdata/gradle.war",
want: wantGradle,
},
{
name: "nested jars",
file: "testdata/nested.jar",
want: wantNestedJar,
},
{
name: "sha1 search",
file: "testdata/test.jar",
want: wantSHA1,
},
{
name: "offline",
file: "testdata/test.jar",
offline: true,
want: wantOffline,
},
{
name: "artifactId search",
file: "testdata/heuristic-1.0.0-SNAPSHOT.jar",
want: wantHeuristic,
},
{
name: "fat jar",
file: "testdata/hadoop-shaded-guava-1.1.0-SNAPSHOT.jar",
want: wantFatjar,
},
{
name: "duplicate libraries",
file: "testdata/io.quarkus.gizmo.gizmo-1.1.1.Final.jar",
want: wantDuplicatesJar,
},
}
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
res := apiResponse{
Response: response{
NumFound: 1,
},
}
switch {
case strings.Contains(r.URL.Query().Get("q"), "springframework"):
res.Response.NumFound = 0
case strings.Contains(r.URL.Query().Get("q"), "c666f5bc47eb64ed3bbd13505a26f58be71f33f0"):
res.Response.Docs = []doc{
{
ID: "org.springframework.spring-core",
GroupID: "org.springframework",
ArtifactID: "spring-core",
Version: "5.3.3",
},
}
case strings.Contains(r.URL.Query().Get("q"), "Gizmo"):
res.Response.NumFound = 0
case strings.Contains(r.URL.Query().Get("q"), "85d30c06026afd9f5be26da3194d4698c447a904"):
res.Response.Docs = []doc{
{
ID: "io.quarkus.gizmo.gizmo",
GroupID: "io.quarkus.gizmo",
ArtifactID: "gizmo",
Version: "1.1.1.Final",
},
}
case strings.Contains(r.URL.Query().Get("q"), "heuristic"):
res.Response.Docs = []doc{
{
ID: "org.springframework.heuristic",
GroupID: "org.springframework",
ArtifactID: "heuristic",
VersionCount: 10,
},
{
ID: "com.example.heuristic",
GroupID: "com.example",
ArtifactID: "heuristic",
VersionCount: 100,
},
}
}
_ = json.NewEncoder(w).Encode(res)
}))
for _, v := range vectors {
t.Run(v.name, func(t *testing.T) {
f, err := os.Open(v.file)
require.NoError(t, err)
stat, err := f.Stat()
require.NoError(t, err)
c := sonatype.New(sonatype.WithURL(ts.URL), sonatype.WithHTTPClient(ts.Client()))
p := jar.NewParser(c, jar.WithFilePath(v.file), jar.WithOffline(v.offline), jar.WithSize(stat.Size()))
got, _, err := p.Parse(f)
require.NoError(t, err)
sort.Slice(got, func(i, j int) bool {
return got[i].Name < got[j].Name
})
sort.Slice(v.want, func(i, j int) bool {
return v.want[i].Name < v.want[j].Name
})
assert.Equal(t, v.want, got)
})
}
}
<file_sep>/pkg/java/jar/types.go
package jar
import (
"fmt"
"github.com/aquasecurity/go-dep-parser/pkg/types"
"golang.org/x/xerrors"
)
var ArtifactNotFoundErr = xerrors.New("no artifact found")
type Properties struct {
GroupID string
ArtifactID string
Version string
FilePath string // path to file containing these props
}
func (p Properties) Library() types.Library {
return types.Library{
Name: fmt.Sprintf("%s:%s", p.GroupID, p.ArtifactID),
Version: p.Version,
FilePath: p.FilePath,
}
}
func (p Properties) Valid() bool {
return p.GroupID != "" && p.ArtifactID != "" && p.Version != ""
}
func (p Properties) String() string {
return fmt.Sprintf("%s:%s:%s", p.GroupID, p.ArtifactID, p.Version)
}
<file_sep>/pkg/conda/meta/testdata/README.md
To recreate the test files:
- Start a miniconda container:
```bash
docker run --name miniconda --rm -it continuumio/miniconda3@sha256:58b1c7df8d69655ffec017ede784a075e3c2e9feff0fc50ef65300fc75aa45ae bash
```
- In the container, initialize a conda environment:
```bash
conda create --yes -n test-dep-parser python=3.9.12
```
- Export conda package definitions out of the container:
```bash
docker cp miniconda:/opt/conda/envs/test-dep-parser/conda-meta/_libgcc_mutex-0.1-main.json .
docker cp miniconda:/opt/conda/envs/test-dep-parser/conda-meta/libgomp-11.2.0-h1234567_1.json .
```
<file_sep>/pkg/golang/mod/testdata/replaced-with-local-path-and-version/xerrors/xerrors.go
package xerrors
func Errorf(format string, a ...interface{}) error {
return nil
}
<file_sep>/pkg/java/pom/testdata/inherit-props/base/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.example</groupId>
<artifactId>parent</artifactId>
<version>1.0.0</version>
</parent>
<groupId>com.example</groupId>
<artifactId>test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<description>Spring Boot project</description>
<properties>
<bom.version>2.0.0</bom.version>
</properties>
<dependencies>
<dependency>
<groupId>org.example</groupId>
<artifactId>example-api</artifactId>
</dependency>
</dependencies>
</project><file_sep>/pkg/ruby/gemspec/parse_test.go
package gemspec_test
import (
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/aquasecurity/go-dep-parser/pkg/ruby/gemspec"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
func TestParse(t *testing.T) {
tests := []struct {
name string
inputFile string
want []types.Library
wantErr string
}{
{
name: "happy",
inputFile: "testdata/normal00.gemspec",
want: []types.Library{{
Name: "rake",
Version: "13.0.3",
License: "MIT",
}},
},
{
name: "another variable name",
inputFile: "testdata/normal01.gemspec",
want: []types.Library{{
Name: "async",
Version: "1.25.0",
}},
},
{
name: "license",
inputFile: "testdata/license.gemspec",
want: []types.Library{{
Name: "async",
Version: "1.25.0",
License: "MIT",
}},
},
{
name: "multiple licenses",
inputFile: "testdata/multiple_licenses.gemspec",
want: []types.Library{{
Name: "test-unit",
Version: "3.3.7",
License: "Ruby, BSDL, PSFL",
}},
},
{
name: "malformed variable name",
inputFile: "testdata/malformed00.gemspec",
wantErr: "failed to parse gemspec",
},
{
name: "missing version",
inputFile: "testdata/malformed01.gemspec",
wantErr: "failed to parse gemspec",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f, err := os.Open(tt.inputFile)
require.NoError(t, err)
got, _, err := gemspec.NewParser().Parse(f)
if tt.wantErr != "" {
require.NotNil(t, err)
assert.Contains(t, err.Error(), tt.wantErr)
return
}
assert.Equal(t, tt.want, got)
})
}
}
<file_sep>/pkg/golang/mod/testdata/normal/main.go
package main
import (
"log"
"github.com/aquasecurity/go-dep-parser/pkg/golang/mod"
)
func main() {
if _, err := mod.Parse(nil); err != nil {
log.Fatal(err)
}
}
<file_sep>/pkg/java/jar/sonatype/sonatype.go
package sonatype
import (
"encoding/json"
"fmt"
"net/http"
"os"
"sort"
"time"
"github.com/hashicorp/go-retryablehttp"
"golang.org/x/xerrors"
"github.com/aquasecurity/go-dep-parser/pkg/java/jar"
)
const (
baseURL = "https://search.maven.org/solrsearch/select"
idQuery = `g:"%s" AND a:"%s"`
artifactIdQuery = `a:"%s" AND p:"jar"`
sha1Query = `1:"%s"`
)
type apiResponse struct {
Response struct {
NumFound int `json:"numFound"`
Docs []struct {
ID string `json:"id"`
GroupID string `json:"g"`
ArtifactID string `json:"a"`
Version string `json:"v"`
P string `json:"p"`
VersionCount int `json:"versionCount"`
} `json:"docs"`
} `json:"response"`
}
type Sonatype struct {
baseURL string
httpClient *http.Client
}
type Option func(*Sonatype)
func WithURL(url string) Option {
return func(p *Sonatype) {
p.baseURL = url
}
}
func WithHTTPClient(client *http.Client) Option {
return func(p *Sonatype) {
p.httpClient = client
}
}
func New(opts ...Option) Sonatype {
// for HTTP retry
retryClient := retryablehttp.NewClient()
retryClient.Logger = logger{}
retryClient.RetryWaitMin = 20 * time.Second
retryClient.RetryWaitMax = 5 * time.Minute
retryClient.RetryMax = 5
client := retryClient.StandardClient()
// attempt to read the maven central api url from os environment, if it's
// not set use the default
mavenURL, ok := os.LookupEnv("MAVEN_CENTRAL_URL")
if !ok {
mavenURL = baseURL
}
s := Sonatype{
baseURL: mavenURL,
httpClient: client,
}
for _, opt := range opts {
opt(&s)
}
return s
}
func (s Sonatype) Exists(groupID, artifactID string) (bool, error) {
req, err := http.NewRequest(http.MethodGet, s.baseURL, nil)
if err != nil {
return false, xerrors.Errorf("unable to initialize HTTP client: %w", err)
}
q := req.URL.Query()
q.Set("q", fmt.Sprintf(idQuery, groupID, artifactID))
q.Set("rows", "1")
req.URL.RawQuery = q.Encode()
resp, err := s.httpClient.Do(req)
if err != nil {
return false, xerrors.Errorf("http error: %w", err)
}
defer resp.Body.Close()
var res apiResponse
if err = json.NewDecoder(resp.Body).Decode(&res); err != nil {
return false, xerrors.Errorf("json decode error: %w", err)
}
return res.Response.NumFound > 0, nil
}
func (s Sonatype) SearchBySHA1(sha1 string) (jar.Properties, error) {
req, err := http.NewRequest(http.MethodGet, s.baseURL, nil)
if err != nil {
return jar.Properties{}, xerrors.Errorf("unable to initialize HTTP client: %w", err)
}
q := req.URL.Query()
q.Set("q", fmt.Sprintf(sha1Query, sha1))
q.Set("rows", "1")
q.Set("wt", "json")
req.URL.RawQuery = q.Encode()
resp, err := s.httpClient.Do(req)
if err != nil {
return jar.Properties{}, xerrors.Errorf("sha1 search error: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return jar.Properties{}, xerrors.Errorf("status %s from %s", resp.Status, req.URL.String())
}
var res apiResponse
if err = json.NewDecoder(resp.Body).Decode(&res); err != nil {
return jar.Properties{}, xerrors.Errorf("json decode error: %w", err)
}
if len(res.Response.Docs) == 0 {
return jar.Properties{}, xerrors.Errorf("digest %s: %w", sha1, jar.ArtifactNotFoundErr)
}
// Some artifacts might have the same SHA-1 digests.
// e.g. "javax.servlet:jstl" and "jstl:jstl"
docs := res.Response.Docs
sort.Slice(docs, func(i, j int) bool {
return docs[i].ID < docs[j].ID
})
d := docs[0]
return jar.Properties{
GroupID: d.GroupID,
ArtifactID: d.ArtifactID,
Version: d.Version,
}, nil
}
func (s Sonatype) SearchByArtifactID(artifactID string) (string, error) {
req, err := http.NewRequest(http.MethodGet, s.baseURL, nil)
if err != nil {
return "", xerrors.Errorf("unable to initialize HTTP client: %w", err)
}
q := req.URL.Query()
q.Set("q", fmt.Sprintf(artifactIdQuery, artifactID))
q.Set("rows", "20")
q.Set("wt", "json")
req.URL.RawQuery = q.Encode()
resp, err := s.httpClient.Do(req)
if err != nil {
return "", xerrors.Errorf("artifactID search error: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", xerrors.Errorf("status %s from %s", resp.Status, req.URL.String())
}
var res apiResponse
if err = json.NewDecoder(resp.Body).Decode(&res); err != nil {
return "", xerrors.Errorf("json decode error: %w", err)
}
if len(res.Response.Docs) == 0 {
return "", xerrors.Errorf("artifactID %s: %w", artifactID, jar.ArtifactNotFoundErr)
}
// Some artifacts might have the same artifactId.
// e.g. "javax.servlet:jstl" and "jstl:jstl"
docs := res.Response.Docs
sort.Slice(docs, func(i, j int) bool {
return docs[i].VersionCount > docs[j].VersionCount
})
d := docs[0]
return d.GroupID, nil
}
<file_sep>/pkg/python/pyproject/pyproject_test.go
package pyproject_test
import (
"fmt"
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/aquasecurity/go-dep-parser/pkg/python/pyproject"
)
func TestParser_Parse(t *testing.T) {
tests := []struct {
name string
file string
want map[string]interface{}
wantErr assert.ErrorAssertionFunc
}{
{
name: "happy path",
file: "testdata/happy.toml",
want: map[string]interface{}{
"flask": "^1.0",
"python": "^3.9",
"requests": map[string]interface{}{
"version": "2.28.1",
"optional": true,
},
"virtualenv": []interface{}{
map[string]interface{}{
"version": "^20.4.3,!=20.4.5,!=20.4.6",
},
map[string]interface{}{
"version": "<20.16.6",
"markers": "sys_platform == 'win32' and python_version == '3.9'",
},
},
},
wantErr: assert.NoError,
},
{
name: "sad path",
file: "testdata/sad.toml",
wantErr: assert.Error,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f, err := os.Open(tt.file)
require.NoError(t, err)
defer f.Close()
p := &pyproject.Parser{}
got, err := p.Parse(f)
if !tt.wantErr(t, err, fmt.Sprintf("Parse(%v)", tt.file)) {
return
}
assert.Equalf(t, tt.want, got, "Parse(%v)", tt.file)
})
}
}
<file_sep>/pkg/c/conan/parse.go
package conan
import (
"fmt"
"github.com/liamg/jfather"
"io"
"strings"
"golang.org/x/exp/slices"
"golang.org/x/xerrors"
dio "github.com/aquasecurity/go-dep-parser/pkg/io"
"github.com/aquasecurity/go-dep-parser/pkg/log"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
type LockFile struct {
GraphLock GraphLock `json:"graph_lock"`
}
type GraphLock struct {
Nodes map[string]Node `json:"nodes"`
}
type Node struct {
Ref string `json:"ref"`
Requires []string `json:"requires"`
StartLine int
EndLine int
}
type Parser struct{}
func NewParser() types.Parser {
return &Parser{}
}
func (p *Parser) Parse(r dio.ReadSeekerAt) ([]types.Library, []types.Dependency, error) {
var lock LockFile
input, err := io.ReadAll(r)
if err != nil {
return nil, nil, xerrors.Errorf("failed to read canon lock file: %w", err)
}
if err := jfather.Unmarshal(input, &lock); err != nil {
return nil, nil, xerrors.Errorf("failed to decode canon lock file: %w", err)
}
// Get a list of direct dependencies
var directDeps []string
if root, ok := lock.GraphLock.Nodes["0"]; ok {
directDeps = root.Requires
}
// Parse packages
parsed := map[string]types.Library{}
for i, node := range lock.GraphLock.Nodes {
if node.Ref == "" {
continue
}
lib, err := parseRef(node)
if err != nil {
log.Logger.Debug(err)
continue
}
// Determine if the package is a direct dependency or not
direct := slices.Contains(directDeps, i)
lib.Indirect = !direct
parsed[i] = lib
}
// Parse dependency graph
var libs []types.Library
var deps []types.Dependency
for i, node := range lock.GraphLock.Nodes {
lib, ok := parsed[i]
if !ok {
continue
}
var childDeps []string
for _, req := range node.Requires {
if child, ok := parsed[req]; ok {
childDeps = append(childDeps, child.ID)
}
}
if len(childDeps) != 0 {
deps = append(deps, types.Dependency{
ID: lib.ID,
DependsOn: childDeps,
})
}
libs = append(libs, lib)
}
return libs, deps, nil
}
func parseRef(node Node) (types.Library, error) {
// full ref format: package/version@user/channel#rrev:package_id#prev
// various examples:
// 'pkga/0.1@user/testing'
// 'pkgb/0.1.0'
// 'pkgc/system'
// 'pkgd/0.1.0#7dcb50c43a5a50d984c2e8fa5898bf18'
ss := strings.Split(strings.Split(strings.Split(node.Ref, "@")[0], "#")[0], "/")
if len(ss) != 2 {
return types.Library{}, xerrors.Errorf("Unable to determine conan dependency: %q", node.Ref)
}
return types.Library{
ID: fmt.Sprintf("%s/%s", ss[0], ss[1]),
Name: ss[0],
Version: ss[1],
Locations: []types.Location{
{
StartLine: node.StartLine,
EndLine: node.EndLine,
},
},
}, nil
}
// UnmarshalJSONWithMetadata needed to detect start and end lines of deps
func (n *Node) UnmarshalJSONWithMetadata(node jfather.Node) error {
if err := node.Decode(&n); err != nil {
return err
}
// Decode func will overwrite line numbers if we save them first
n.StartLine = node.Range().Start.Line
n.EndLine = node.Range().End.Line
return nil
}
<file_sep>/pkg/rust/binary/parse_test.go
package binary_test
import (
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/aquasecurity/go-dep-parser/pkg/rust/binary"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
// Test binaries generated from cargo-auditable test fixture
// https://github.com/rust-secure-code/cargo-auditable/tree/6b77151/cargo-auditable/tests/fixtures/workspace
var (
libs = []types.Library{
{
ID: "[email protected]",
Name: "crate_with_features",
Version: "0.1.0",
Indirect: false,
},
{
ID: "[email protected]",
Name: "library_crate",
Version: "0.1.0",
Indirect: true,
},
}
deps = []types.Dependency{
{
ID: "[email protected]",
DependsOn: []string{"[email protected]"},
},
}
)
func TestParse(t *testing.T) {
tests := []struct {
name string
inputFile string
want []types.Library
wantDeps []types.Dependency
wantErr string
}{
{
name: "ELF",
inputFile: "testdata/test.elf",
want: libs,
wantDeps: deps,
},
{
name: "PE",
inputFile: "testdata/test.exe",
want: libs,
wantDeps: deps,
},
{
name: "Mach-O",
inputFile: "testdata/test.macho",
want: libs,
wantDeps: deps,
},
{
name: "sad path",
inputFile: "testdata/dummy",
wantErr: "unrecognized executable format",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f, err := os.Open(tt.inputFile)
require.NoError(t, err)
defer f.Close()
got, gotDeps, err := binary.NewParser().Parse(f)
if tt.wantErr != "" {
require.NotNil(t, err)
assert.Contains(t, err.Error(), tt.wantErr)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.want, got)
assert.Equal(t, tt.wantDeps, gotDeps)
})
}
}
<file_sep>/pkg/java/pom/testdata/multi-module/module/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>module</artifactId>
<version>1.1.1</version>
<name>module</name>
<description>Module</description>
<licenses>
<license>
<name>Apache 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.html</url>
<distribution>repo</distribution>
</license>
</licenses>
<dependencies>
<dependency>
<groupId>org.example</groupId>
<artifactId>example-dependency</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
</project>
<file_sep>/pkg/java/pom/queue.go
package pom
import "sync"
// artifactQueue the queue of Items
type artifactQueue struct {
items []artifact
lock sync.RWMutex
}
func newArtifactQueue() *artifactQueue {
return &artifactQueue{}
}
func (s *artifactQueue) enqueue(items ...artifact) {
s.lock.Lock()
s.items = append(s.items, items...)
s.lock.Unlock()
}
func (s *artifactQueue) dequeue() artifact {
s.lock.Lock()
item := s.items[0]
s.items = s.items[1:]
s.lock.Unlock()
return item
}
// IsEmpty returns true if the queue is empty
func (s *artifactQueue) IsEmpty() bool {
return len(s.items) == 0
}
<file_sep>/pkg/java/pom/pom.go
package pom
import (
"encoding/xml"
"fmt"
"io"
"reflect"
"strings"
"github.com/samber/lo"
"github.com/aquasecurity/go-dep-parser/pkg/utils"
)
type pom struct {
filePath string
content *pomXML
}
func (p *pom) inherit(result analysisResult) {
// Merge properties
p.content.Properties = utils.MergeMaps(result.properties, p.content.Properties)
art := p.artifact().Inherit(result.artifact)
p.content.GroupId = art.GroupID
p.content.ArtifactId = art.ArtifactID
p.content.Licenses = art.ToPOMLicenses()
if isProperty(art.Version.String()) {
p.content.Version = evaluateVariable(art.Version.String(), p.content.Properties, nil)
} else {
p.content.Version = art.Version.String()
}
}
func (p pom) properties() properties {
props := p.content.Properties
return utils.MergeMaps(props, p.projectProperties())
}
func (p pom) projectProperties() map[string]string {
val := reflect.ValueOf(p.content).Elem()
props := p.listProperties(val)
// "version" and "groupId" elements could be inherited from parent.
// https://maven.apache.org/pom.html#inheritance
props["groupId"] = p.content.GroupId
props["version"] = p.content.Version
// https://maven.apache.org/pom.html#properties
projectProperties := map[string]string{}
for k, v := range props {
if strings.HasPrefix(k, "project.") {
continue
}
// e.g. ${project.groupId}
key := fmt.Sprintf("project.%s", k)
projectProperties[key] = v
// It is deprecated, but still available.
// e.g. ${groupId}
projectProperties[k] = v
}
return projectProperties
}
func (p pom) listProperties(val reflect.Value) map[string]string {
props := map[string]string{}
for i := 0; i < val.NumField(); i++ {
f := val.Type().Field(i)
tag, ok := f.Tag.Lookup("xml")
if !ok || strings.Contains(tag, ",") {
// e.g. ",chardata"
continue
}
switch f.Type.Kind() {
case reflect.Slice:
continue
case reflect.Map:
m := val.Field(i)
for _, e := range m.MapKeys() {
v := m.MapIndex(e)
props[e.String()] = v.String()
}
case reflect.Struct:
nestedProps := p.listProperties(val.Field(i))
for k, v := range nestedProps {
key := fmt.Sprintf("%s.%s", tag, k)
props[key] = v
}
default:
props[tag] = val.Field(i).String()
}
}
return props
}
func (p pom) artifact() artifact {
return newArtifact(p.content.GroupId, p.content.ArtifactId, p.content.Version, p.licenses(), p.content.Properties)
}
func (p pom) licenses() []string {
return lo.FilterMap(p.content.Licenses.License, func(lic pomLicense, _ int) (string, bool) {
return lic.Name, lic.Name != ""
})
}
func (p pom) repositories() []string {
var urls []string
for _, rep := range p.content.Repositories.Repository {
if rep.Releases.Enabled != "false" {
urls = append(urls, rep.URL)
}
}
return urls
}
type pomXML struct {
Parent pomParent `xml:"parent"`
GroupId string `xml:"groupId"`
ArtifactId string `xml:"artifactId"`
Version string `xml:"version"`
Licenses pomLicenses `xml:"licenses"`
Modules struct {
Text string `xml:",chardata"`
Module []string `xml:"module"`
} `xml:"modules"`
Properties properties `xml:"properties"`
DependencyManagement struct {
Text string `xml:",chardata"`
Dependencies pomDependencies `xml:"dependencies"`
} `xml:"dependencyManagement"`
Dependencies pomDependencies `xml:"dependencies"`
Repositories struct {
Text string `xml:",chardata"`
Repository []struct {
Text string `xml:",chardata"`
ID string `xml:"id"`
Name string `xml:"name"`
URL string `xml:"url"`
Releases struct {
Text string `xml:",chardata"`
Enabled string `xml:"enabled"`
} `xml:"releases"`
Snapshots struct {
Text string `xml:",chardata"`
Enabled string `xml:"enabled"`
} `xml:"snapshots"`
} `xml:"repository"`
} `xml:"repositories"`
}
type pomParent struct {
GroupId string `xml:"groupId"`
ArtifactId string `xml:"artifactId"`
Version string `xml:"version"`
RelativePath string `xml:"relativePath"`
}
type pomLicenses struct {
Text string `xml:",chardata"`
License []pomLicense `xml:"license"`
}
type pomLicense struct {
Name string `xml:"name"`
}
type pomDependencies struct {
Text string `xml:",chardata"`
Dependency []pomDependency `xml:"dependency"`
}
type pomDependency struct {
Text string `xml:",chardata"`
GroupID string `xml:"groupId"`
ArtifactID string `xml:"artifactId"`
Version string `xml:"version"`
Scope string `xml:"scope"`
Optional bool `xml:"optional"`
Exclusions pomExclusions `xml:"exclusions"`
}
type pomExclusions struct {
Text string `xml:",chardata"`
Exclusion []pomExclusion `xml:"exclusion"`
}
// ref. https://maven.apache.org/guides/introduction/introduction-to-optional-and-excludes-dependencies.html
type pomExclusion struct {
GroupID string `xml:"groupId"`
ArtifactID string `xml:"artifactId"`
}
func (d pomDependency) Name() string {
return fmt.Sprintf("%s:%s", d.GroupID, d.ArtifactID)
}
// Resolve evaluates variables in the dependency and inherit some fields from dependencyManagement to the dependency.
func (d pomDependency) Resolve(props map[string]string, depManagement, rootDepManagement []pomDependency) pomDependency {
// Evaluate variables
dep := pomDependency{
Text: d.Text,
GroupID: evaluateVariable(d.GroupID, props, nil),
ArtifactID: evaluateVariable(d.ArtifactID, props, nil),
Version: evaluateVariable(d.Version, props, nil),
Scope: evaluateVariable(d.Scope, props, nil),
Optional: d.Optional,
Exclusions: d.Exclusions,
}
// If this dependency is managed in the root POM,
// we need to overwrite fields according to the managed dependency.
if managed, found := findDep(d.Name(), rootDepManagement); found { // dependencyManagement from the root POM
if managed.Version != "" {
dep.Version = evaluateVariable(managed.Version, props, nil)
}
if managed.Scope != "" {
dep.Scope = evaluateVariable(managed.Scope, props, nil)
}
if managed.Optional {
dep.Optional = managed.Optional
}
if len(managed.Exclusions.Exclusion) != 0 {
dep.Exclusions = managed.Exclusions
}
return dep
}
// Inherit version, scope and optional from dependencyManagement if empty
if managed, found := findDep(d.Name(), depManagement); found { // dependencyManagement from parent
if dep.Version == "" {
dep.Version = evaluateVariable(managed.Version, props, nil)
}
if dep.Scope == "" {
dep.Scope = evaluateVariable(managed.Scope, props, nil)
}
// TODO: need to check the behavior
if !dep.Optional {
dep.Optional = managed.Optional
}
if len(dep.Exclusions.Exclusion) == 0 {
dep.Exclusions = managed.Exclusions
}
}
return dep
}
// ToArtifact converts dependency to artifact.
// It should be called after calling Resolve() so that variables can be evaluated.
func (d pomDependency) ToArtifact(exclusions map[string]struct{}) artifact {
if exclusions == nil {
exclusions = map[string]struct{}{}
}
for _, e := range d.Exclusions.Exclusion {
exclusions[fmt.Sprintf("%s:%s", e.GroupID, e.ArtifactID)] = struct{}{}
}
return artifact{
GroupID: d.GroupID,
ArtifactID: d.ArtifactID,
Version: newVersion(d.Version),
Exclusions: exclusions,
}
}
type properties map[string]string
type property struct {
XMLName xml.Name
Value string `xml:",chardata"`
}
func (props *properties) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
*props = properties{}
for {
var p property
err := d.Decode(&p)
if err == io.EOF {
break
} else if err != nil {
return err
}
(*props)[p.XMLName.Local] = p.Value
}
return nil
}
func findDep(name string, depManagement []pomDependency) (pomDependency, bool) {
return lo.Find(depManagement, func(item pomDependency) bool {
return item.Name() == name
})
}
<file_sep>/pkg/nodejs/packagejson/parse_test.go
package packagejson_test
import (
"os"
"path"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/aquasecurity/go-dep-parser/pkg/nodejs/packagejson"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
func TestParse(t *testing.T) {
vectors := []struct {
name string
inputFile string
want packagejson.Package
wantErr string
}{
{
name: "happy path",
inputFile: "testdata/package.json",
// docker run --name composer --rm -it node:12-alpine sh
// npm init --force
// npm install --save promise jquery
// npm ls | grep -E -o "\S+@\S+" | awk -F@ 'NR>0 {printf("{\""$1"\", \""$2"\"},\n")}'
want: packagejson.Package{
Library: types.Library{
ID: "[email protected]",
Name: "bootstrap",
Version: "5.0.2",
License: "MIT",
},
Dependencies: map[string]string{
"js-tokens": "^4.0.0",
},
OptionalDependencies: map[string]string{
"colors": "^1.4.0",
},
DevDependencies: map[string]string{
"@babel/cli": "^7.14.5",
"@babel/core": "^7.14.6",
},
Workspaces: []string{
"packages/*",
"backend",
},
},
},
{
name: "happy path - legacy license",
inputFile: "testdata/legacy_package.json",
want: packagejson.Package{
Library: types.Library{
ID: "[email protected]",
Name: "angular",
Version: "4.1.2",
License: "ISC",
},
Dependencies: map[string]string{},
DevDependencies: map[string]string{
"@babel/cli": "^7.14.5",
"@babel/core": "^7.14.6",
},
},
},
{
name: "happy path - version doesn't exist",
inputFile: "testdata/without_version_package.json",
want: packagejson.Package{
Library: types.Library{
ID: "",
Name: "angular",
},
},
},
{
name: "sad path",
inputFile: "testdata/invalid_package.json",
// docker run --name composer --rm -it node:12-alpine sh
// npm init --force
// npm install --save promise jquery
// npm ls | grep -E -o "\S+@\S+" | awk -F@ 'NR>0 {printf("{\""$1"\", \""$2"\"},\n")}'
wantErr: "JSON decode error",
},
{
name: "without name and version",
inputFile: "testdata/without_name_and_version_package.json",
want: packagejson.Package{
Library: types.Library{
License: "MIT",
},
},
},
}
for _, v := range vectors {
t.Run(path.Base(v.name), func(t *testing.T) {
f, err := os.Open(v.inputFile)
require.NoError(t, err)
defer f.Close()
got, err := packagejson.NewParser().Parse(f)
if v.wantErr != "" {
assert.ErrorContains(t, err, v.wantErr)
return
}
require.NoError(t, err)
assert.Equal(t, v.want, got)
})
}
}
<file_sep>/pkg/python/packaging/parse.go
package packaging
import (
"bufio"
"io"
"net/textproto"
"strings"
"golang.org/x/xerrors"
dio "github.com/aquasecurity/go-dep-parser/pkg/io"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
type Parser struct{}
func NewParser() types.Parser {
return &Parser{}
}
// Parse parses egg and wheel metadata.
// e.g. .egg-info/PKG-INFO and dist-info/METADATA
func (*Parser) Parse(r dio.ReadSeekerAt) ([]types.Library, []types.Dependency, error) {
rd := textproto.NewReader(bufio.NewReader(r))
h, err := rd.ReadMIMEHeader()
if err != nil && err != io.EOF {
return nil, nil, xerrors.Errorf("read MIME error: %w", err)
}
// "License-Expression" takes precedence as "License" is deprecated.
// cf. https://peps.python.org/pep-0639/#deprecate-license-field
var license string
if l := h.Get("License-Expression"); l != "" {
license = l
} else if l := h.Get("License"); l != "" {
license = l
} else {
for _, classifier := range h.Values("Classifier") {
if strings.HasPrefix(classifier, "License :: ") {
values := strings.Split(classifier, " :: ")
license = values[len(values)-1]
break
}
}
}
if license == "" && h.Get("License-File") != "" {
license = "file://" + h.Get("License-File")
}
return []types.Library{
{
Name: h.Get("Name"),
Version: h.Get("Version"),
License: license,
},
}, nil, nil
}
<file_sep>/pkg/python/pip/testdata/requirements_comments.txt
# foo==8.0.0
#bar==8.0.0
#comment
click==8.0.0
Flask==2.0.0 #comment
Jinja2==3.0.0#comment
MarkupSafe==2.0.0 # comment
<file_sep>/pkg/log/log.go
package log
import (
"go.uber.org/zap"
)
var Logger *zap.SugaredLogger
func init() {
config := zap.Config{
Level: zap.NewAtomicLevelAt(zap.InfoLevel),
Development: false,
Encoding: "console",
EncoderConfig: zap.NewDevelopmentEncoderConfig(),
OutputPaths: []string{"stderr"},
ErrorOutputPaths: []string{"stderr"},
}
logger, _ := config.Build()
Logger = logger.Sugar()
}
func SetLogger(l *zap.SugaredLogger) {
Logger = l
}
<file_sep>/pkg/conda/meta/parse_test.go
package meta_test
import (
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/aquasecurity/go-dep-parser/pkg/conda/meta"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
func TestParse(t *testing.T) {
tests := []struct {
name string
input string
want []types.Library
wantErr string
}{
{
name: "_libgcc_mutex",
input: "testdata/_libgcc_mutex-0.1-main.json",
want: []types.Library{{Name: "_libgcc_mutex", Version: "0.1"}},
},
{
name: "libgomp",
input: "testdata/libgomp-11.2.0-h1234567_1.json",
want: []types.Library{{Name: "libgomp", Version: "11.2.0", License: "GPL-3.0-only WITH GCC-exception-3.1"}},
},
{
name: "invalid_json",
input: "testdata/invalid_json.json",
wantErr: "JSON decode error: invalid character",
},
{
name: "invalid_package",
input: "testdata/invalid_package.json",
wantErr: "unable to parse conda package",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f, err := os.Open(tt.input)
require.NoError(t, err)
defer f.Close()
got, _, err := meta.NewParser().Parse(f)
if tt.wantErr != "" {
assert.ErrorContains(t, err, tt.wantErr)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.want, got)
})
}
}
<file_sep>/pkg/types/types.go
package types
import (
dio "github.com/aquasecurity/go-dep-parser/pkg/io"
)
type Library struct {
ID string `json:",omitempty"`
Name string
Version string
Dev bool
Indirect bool `json:",omitempty"`
License string `json:",omitempty"`
ExternalReferences []ExternalRef `json:",omitempty"`
Locations Locations `json:",omitempty"`
FilePath string `json:",omitempty"` // Required to show nested jars
}
type Libraries []Library
func (libs Libraries) Len() int { return len(libs) }
func (libs Libraries) Less(i, j int) bool {
if libs[i].ID != libs[j].ID { // ID could be empty
return libs[i].ID < libs[j].ID
} else if libs[i].Name != libs[j].Name { // Name could be the same
return libs[i].Name < libs[j].Name
}
return libs[i].Version < libs[j].Version
}
func (libs Libraries) Swap(i, j int) { libs[i], libs[j] = libs[j], libs[i] }
// Location in lock file
type Location struct {
StartLine int `json:",omitempty"`
EndLine int `json:",omitempty"`
}
type Locations []Location
func (locs Locations) Len() int { return len(locs) }
func (locs Locations) Less(i, j int) bool {
return locs[i].StartLine < locs[j].StartLine
}
func (locs Locations) Swap(i, j int) { locs[i], locs[j] = locs[j], locs[i] }
type ExternalRef struct {
Type RefType
URL string
}
type Dependency struct {
ID string
DependsOn []string
}
type Dependencies []Dependency
func (deps Dependencies) Len() int { return len(deps) }
func (deps Dependencies) Less(i, j int) bool {
return deps[i].ID < deps[j].ID
}
func (deps Dependencies) Swap(i, j int) { deps[i], deps[j] = deps[j], deps[i] }
type Parser interface {
// Parse parses the dependency file
Parse(r dio.ReadSeekerAt) ([]Library, []Dependency, error)
}
type RefType string
const (
RefWebsite RefType = "website"
RefLicense RefType = "license"
RefVCS RefType = "vcs"
RefIssueTracker RefType = "issue-tracker"
RefOther RefType = "other"
)
<file_sep>/pkg/java/pom/parse_test.go
package pom_test
import (
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/aquasecurity/go-dep-parser/pkg/java/pom"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
func TestPom_Parse(t *testing.T) {
tests := []struct {
name string
inputFile string
local bool
offline bool
want []types.Library
wantDeps []types.Dependency
wantErr string
}{
{
name: "local repository",
inputFile: filepath.Join("testdata", "happy", "pom.xml"),
local: true,
want: []types.Library{
{
ID: "com.example:happy:1.0.0",
Name: "com.example:happy",
Version: "1.0.0",
License: "BSD-3-Clause",
},
{
ID: "org.example:example-api:1.7.30",
Name: "org.example:example-api",
Version: "1.7.30",
License: "The Apache Software License, Version 2.0",
},
},
wantDeps: []types.Dependency{
{
ID: "com.example:happy:1.0.0",
DependsOn: []string{
"org.example:example-api:1.7.30",
},
},
},
},
{
name: "remote repository",
inputFile: filepath.Join("testdata", "happy", "pom.xml"),
local: false,
want: []types.Library{
{
ID: "com.example:happy:1.0.0",
Name: "com.example:happy",
Version: "1.0.0",
License: "BSD-3-Clause",
},
{
ID: "org.example:example-api:1.7.30",
Name: "org.example:example-api",
Version: "1.7.30",
License: "The Apache Software License, Version 2.0",
},
},
wantDeps: []types.Dependency{
{
ID: "com.example:happy:1.0.0",
DependsOn: []string{
"org.example:example-api:1.7.30",
},
},
},
},
{
name: "offline mode",
inputFile: filepath.Join("testdata", "offline", "pom.xml"),
local: false,
offline: true,
want: []types.Library{
{
ID: "org.example:example-offline:2.3.4",
Name: "org.example:example-offline",
Version: "2.3.4",
},
},
},
{
name: "inherit parent properties",
inputFile: filepath.Join("testdata", "parent-properties", "child", "pom.xml"),
local: true,
want: []types.Library{
{
ID: "com.example:child:1.0.0",
Name: "com.example:child",
Version: "1.0.0",
License: "Apache 2.0",
},
{
ID: "org.example:example-api:1.7.30",
Name: "org.example:example-api",
Version: "1.7.30",
License: "The Apache Software License, Version 2.0",
},
},
wantDeps: []types.Dependency{
{
ID: "com.example:child:1.0.0",
DependsOn: []string{
"org.example:example-api:1.7.30",
},
},
},
},
{
name: "inherit project properties from parent",
inputFile: filepath.Join("testdata", "project-version-from-parent", "child", "pom.xml"),
local: true,
want: []types.Library{
{
ID: "com.example:child:2.0.0",
Name: "com.example:child",
Version: "2.0.0",
},
{
ID: "org.example:example-api:2.0.0",
Name: "org.example:example-api",
Version: "2.0.0",
License: "The Apache Software License, Version 2.0",
},
},
wantDeps: []types.Dependency{
{
ID: "com.example:child:2.0.0",
DependsOn: []string{
"org.example:example-api:2.0.0",
},
},
},
},
{
name: "inherit properties in parent depManagement with import scope",
inputFile: filepath.Join("testdata", "inherit-props", "base", "pom.xml"),
local: true,
want: []types.Library{
{
ID: "com.example:test:0.0.1-SNAPSHOT",
Name: "com.example:test",
Version: "0.0.1-SNAPSHOT",
},
{
ID: "org.example:example-api:2.0.0",
Name: "org.example:example-api",
Version: "2.0.0",
License: "The Apache Software License, Version 2.0",
},
},
wantDeps: []types.Dependency{
{
ID: "com.example:test:0.0.1-SNAPSHOT",
DependsOn: []string{
"org.example:example-api:2.0.0",
},
},
},
},
{
name: "dependencyManagement prefers child properties",
inputFile: filepath.Join("testdata", "parent-child-properties", "child", "pom.xml"),
local: true,
want: []types.Library{
{
ID: "com.example:child:1.0.0",
Name: "com.example:child",
Version: "1.0.0",
},
{
ID: "org.example:example-api:4.0.0",
Name: "org.example:example-api",
Version: "4.0.0",
Indirect: true,
},
{
ID: "org.example:example-dependency:1.2.3",
Name: "org.example:example-dependency",
Version: "1.2.3",
},
},
wantDeps: []types.Dependency{
{
ID: "com.example:child:1.0.0",
DependsOn: []string{
"org.example:example-dependency:1.2.3",
},
},
{
ID: "org.example:example-dependency:1.2.3",
DependsOn: []string{
"org.example:example-api:4.0.0",
},
},
},
},
{
name: "inherit parent dependencies",
inputFile: filepath.Join("testdata", "parent-dependencies", "child", "pom.xml"),
local: false,
want: []types.Library{
{
ID: "com.example:child:1.0.0-SNAPSHOT",
Name: "com.example:child",
Version: "1.0.0-SNAPSHOT",
License: "Apache 2.0",
},
{
ID: "org.example:example-api:1.7.30",
Name: "org.example:example-api",
Version: "1.7.30",
License: "The Apache Software License, Version 2.0",
},
},
wantDeps: []types.Dependency{
{
ID: "com.example:child:1.0.0-SNAPSHOT",
DependsOn: []string{
"org.example:example-api:1.7.30",
},
},
},
},
{
name: "inherit parent dependencyManagement",
inputFile: filepath.Join("testdata", "parent-dependency-management", "child", "pom.xml"),
local: true,
want: []types.Library{
{
ID: "com.example:child:3.0.0",
Name: "com.example:child",
Version: "3.0.0",
License: "Apache 2.0",
},
{
ID: "org.example:example-api:1.7.30",
Name: "org.example:example-api",
Version: "1.7.30",
License: "The Apache Software License, Version 2.0",
},
},
wantDeps: []types.Dependency{
{
ID: "com.example:child:3.0.0",
DependsOn: []string{
"org.example:example-api:1.7.30",
},
},
},
},
{
name: "transitive parents",
inputFile: filepath.Join("testdata", "transitive-parents", "base", "pom.xml"),
local: true,
want: []types.Library{
{
ID: "com.example:base:4.0.0",
Name: "com.example:base",
Version: "4.0.0",
License: "Apache 2.0",
},
{
ID: "org.example:example-api:1.7.30",
Name: "org.example:example-api",
Version: "1.7.30",
License: "The Apache Software License, Version 2.0",
Indirect: true,
},
{
ID: "org.example:example-child:2.0.0",
Name: "org.example:example-child",
Version: "2.0.0",
License: "Apache 2.0",
},
},
wantDeps: []types.Dependency{
{
ID: "com.example:base:4.0.0",
DependsOn: []string{
"org.example:example-child:2.0.0",
},
},
{
ID: "org.example:example-child:2.0.0",
DependsOn: []string{
"org.example:example-api:1.7.30",
},
},
},
},
{
name: "parent relativePath",
inputFile: filepath.Join("testdata", "parent-relative-path", "pom.xml"),
local: true,
want: []types.Library{
{
ID: "com.example:child:1.0.0",
Name: "com.example:child",
Version: "1.0.0",
License: "Apache 2.0",
},
{
ID: "org.example:example-api:1.7.30",
Name: "org.example:example-api",
Version: "1.7.30",
License: "The Apache Software License, Version 2.0",
},
},
wantDeps: []types.Dependency{
{
ID: "com.example:child:1.0.0",
DependsOn: []string{
"org.example:example-api:1.7.30",
},
},
},
},
{
name: "parent version in property",
inputFile: filepath.Join("testdata", "parent-version-is-property", "child", "pom.xml"),
local: false,
want: []types.Library{
{
ID: "com.example:child:1.0.0-SNAPSHOT",
Name: "com.example:child",
Version: "1.0.0-SNAPSHOT",
},
{
ID: "org.example:example-api:1.1.1",
Name: "org.example:example-api",
Version: "1.1.1",
},
},
wantDeps: []types.Dependency{
{
ID: "com.example:child:1.0.0-SNAPSHOT",
DependsOn: []string{
"org.example:example-api:1.1.1",
},
},
},
},
{
name: "parent in a remote repository",
inputFile: filepath.Join("testdata", "parent-remote-repository", "pom.xml"),
local: true,
want: []types.Library{
{
ID: "org.example:child:1.0.0",
Name: "org.example:child",
Version: "1.0.0",
License: "Apache 2.0",
},
{
ID: "org.example:example-api:1.7.30",
Name: "org.example:example-api",
Version: "1.7.30",
License: "The Apache Software License, Version 2.0",
},
},
wantDeps: []types.Dependency{
{
ID: "org.example:child:1.0.0",
DependsOn: []string{
"org.example:example-api:1.7.30",
},
},
},
},
{
// mvn dependency:tree
// [INFO] com.example:soft:jar:1.0.0
// [INFO] +- org.example:example-api:jar:1.7.30:compile
// [INFO] \- org.example:example-dependency:jar:1.2.3:compile
// Save DependsOn for each library - https://github.com/aquasecurity/go-dep-parser/pull/243#discussion_r1303904548
name: "soft requirement",
inputFile: filepath.Join("testdata", "soft-requirement", "pom.xml"),
local: true,
want: []types.Library{
{
ID: "com.example:soft:1.0.0",
Name: "com.example:soft",
Version: "1.0.0",
License: "Apache 2.0",
},
{
ID: "org.example:example-api:1.7.30",
Name: "org.example:example-api",
Version: "1.7.30",
License: "The Apache Software License, Version 2.0",
},
{
ID: "org.example:example-dependency:1.2.3",
Name: "org.example:example-dependency",
Version: "1.2.3",
},
},
wantDeps: []types.Dependency{
{
ID: "com.example:soft:1.0.0",
DependsOn: []string{
"org.example:example-api:1.7.30",
"org.example:example-dependency:1.2.3",
},
},
{
ID: "org.example:example-dependency:1.2.3",
DependsOn: []string{
"org.example:example-api:1.7.30",
},
},
},
},
{
// mvn dependency:tree
// [INFO] com.example:soft-transitive:jar:1.0.0
// [INFO] +- org.example:example-dependency:jar:1.2.3:compile
// [INFO] | \- org.example:example-api:jar:2.0.0:compile
// [INFO] \- org.example:example-dependency2:jar:2.3.4:compile
// Save DependsOn for each library - https://github.com/aquasecurity/go-dep-parser/pull/243#discussion_r1303904548
name: "soft requirement with transitive dependencies",
inputFile: filepath.Join("testdata", "soft-requirement-with-transitive-dependencies", "pom.xml"),
local: true,
want: []types.Library{
{
ID: "com.example:soft-transitive:1.0.0",
Name: "com.example:soft-transitive",
Version: "1.0.0",
},
{
ID: "org.example:example-api:2.0.0",
Name: "org.example:example-api",
Version: "2.0.0",
License: "The Apache Software License, Version 2.0",
Indirect: true,
},
{
ID: "org.example:example-dependency2:2.3.4",
Name: "org.example:example-dependency2",
Version: "2.3.4",
},
{
ID: "org.example:example-dependency:1.2.3",
Name: "org.example:example-dependency",
Version: "1.2.3",
},
},
wantDeps: []types.Dependency{
{
ID: "com.example:soft-transitive:1.0.0",
DependsOn: []string{
"org.example:example-dependency2:2.3.4",
"org.example:example-dependency:1.2.3",
},
},
{
ID: "org.example:example-dependency2:2.3.4",
DependsOn: []string{
"org.example:example-api:2.0.0",
},
},
{
ID: "org.example:example-dependency:1.2.3",
DependsOn: []string{
"org.example:example-api:2.0.0",
},
},
},
},
{
// mvn dependency:tree
//[INFO] com.example:hard:jar:1.0.0
//[INFO] +- org.example:example-nested:jar:3.3.4:compile
//[INFO] \- org.example:example-dependency:jar:1.2.3:compile
//[INFO] \- org.example:example-api:jar:2.0.0:compile
// Save DependsOn for each library - https://github.com/aquasecurity/go-dep-parser/pull/243#discussion_r1303904548
name: "hard requirement for the specified version",
inputFile: filepath.Join("testdata", "hard-requirement", "pom.xml"),
local: true,
want: []types.Library{
{
ID: "com.example:hard:1.0.0",
Name: "com.example:hard",
Version: "1.0.0",
License: "Apache 2.0",
},
{
ID: "org.example:example-api:2.0.0",
Name: "org.example:example-api",
Version: "2.0.0",
License: "The Apache Software License, Version 2.0",
Indirect: true,
},
{
ID: "org.example:example-dependency:1.2.3",
Name: "org.example:example-dependency",
Version: "1.2.3",
},
{
ID: "org.example:example-nested:3.3.4",
Name: "org.example:example-nested",
Version: "3.3.4",
},
},
wantDeps: []types.Dependency{
{
ID: "com.example:hard:1.0.0",
DependsOn: []string{
"org.example:example-dependency:1.2.3",
"org.example:example-nested:3.3.4",
},
},
{
ID: "org.example:example-dependency:1.2.3",
DependsOn: []string{
"org.example:example-api:2.0.0",
},
},
{
ID: "org.example:example-nested:3.3.4",
DependsOn: []string{
"org.example:example-dependency:1.2.3",
},
},
},
},
{
name: "version requirement",
inputFile: filepath.Join("testdata", "version-requirement", "pom.xml"),
local: true,
want: []types.Library{
{
ID: "com.example:hard:1.0.0",
Name: "com.example:hard",
Version: "1.0.0",
License: "Apache 2.0",
},
},
},
{
name: "import dependencyManagement",
inputFile: filepath.Join("testdata", "import-dependency-management", "pom.xml"),
local: true,
want: []types.Library{
{
ID: "com.example:import:2.0.0",
Name: "com.example:import",
Version: "2.0.0",
License: "Apache 2.0",
},
{
ID: "org.example:example-api:1.7.30",
Name: "org.example:example-api",
Version: "1.7.30",
License: "The Apache Software License, Version 2.0",
},
},
wantDeps: []types.Dependency{
{
ID: "com.example:import:2.0.0",
DependsOn: []string{
"org.example:example-api:1.7.30",
},
},
},
},
{
name: "import multiple dependencyManagement",
inputFile: filepath.Join("testdata", "import-dependency-management-multiple", "pom.xml"),
local: true,
want: []types.Library{
{
ID: "com.example:import:2.0.0",
Name: "com.example:import",
Version: "2.0.0",
License: "Apache 2.0",
},
{
ID: "org.example:example-api:1.7.30",
Name: "org.example:example-api",
Version: "1.7.30",
License: "The Apache Software License, Version 2.0",
},
},
wantDeps: []types.Dependency{
{
ID: "com.example:import:2.0.0",
DependsOn: []string{
"org.example:example-api:1.7.30",
},
},
},
},
{
name: "exclusions",
inputFile: filepath.Join("testdata", "exclusions", "pom.xml"),
local: true,
want: []types.Library{
{
ID: "com.example:exclusions:3.0.0",
Name: "com.example:exclusions",
Version: "3.0.0",
},
{
ID: "org.example:example-dependency:1.2.3",
Name: "org.example:example-dependency",
Version: "1.2.3",
Indirect: true,
},
{
ID: "org.example:example-nested:3.3.3",
Name: "org.example:example-nested",
Version: "3.3.3",
},
},
wantDeps: []types.Dependency{
{
ID: "com.example:exclusions:3.0.0",
DependsOn: []string{
"org.example:example-nested:3.3.3",
},
},
{
ID: "org.example:example-nested:3.3.3",
DependsOn: []string{
"org.example:example-dependency:1.2.3",
},
},
},
},
{
name: "exclusions with wildcards",
inputFile: filepath.Join("testdata", "wildcard-exclusions", "pom.xml"),
local: true,
want: []types.Library{
{
ID: "com.example:wildcard-exclusions:4.0.0",
Name: "com.example:wildcard-exclusions",
Version: "4.0.0",
},
{
ID: "org.example:example-dependency2:2.3.4",
Name: "org.example:example-dependency2",
Version: "2.3.4",
},
{
ID: "org.example:example-dependency:1.2.3",
Name: "org.example:example-dependency",
Version: "1.2.3",
},
{
ID: "org.example:example-nested:3.3.3",
Name: "org.example:example-nested",
Version: "3.3.3",
},
},
wantDeps: []types.Dependency{
{
ID: "com.example:wildcard-exclusions:4.0.0",
DependsOn: []string{
"org.example:example-dependency2:2.3.4",
"org.example:example-dependency:1.2.3",
"org.example:example-nested:3.3.3",
},
},
},
},
{
name: "multi module",
inputFile: filepath.Join("testdata", "multi-module", "pom.xml"),
local: true,
want: []types.Library{
{
ID: "com.example:aggregation:1.0.0",
Name: "com.example:aggregation",
Version: "1.0.0",
License: "Apache 2.0",
},
{
ID: "com.example:module:1.1.1",
Name: "com.example:module",
Version: "1.1.1",
License: "Apache 2.0",
},
{
ID: "org.example:example-api:2.0.0",
Name: "org.example:example-api",
Version: "2.0.0",
License: "The Apache Software License, Version 2.0",
Indirect: true,
},
{
ID: "org.example:example-dependency:1.2.3",
Name: "org.example:example-dependency",
Version: "1.2.3",
},
},
// maven doesn't include modules in dep tree of root pom
// for modules uses separate graph:
// ➜ mvn dependency:tree
// [INFO] --------------------------------[ jar ]---------------------------------
// [INFO]
// [INFO] --- dependency:3.6.0:tree (default-cli) @ module ---
// [INFO] com.example:module:jar:1.1.1
// [INFO] \- org.example:example-dependency:jar:1.2.3:compile
// [INFO] \- org.example:example-api:jar:2.0.0:compile
// [INFO]
// [INFO] ----------------------< com.example:aggregation >-----------------------
// [INFO] Building aggregation 1.0.0 [2/2]
// [INFO] from pom.xml
// [INFO] --------------------------------[ pom ]---------------------------------
// [INFO]
// [INFO] --- dependency:3.6.0:tree (default-cli) @ aggregation ---
// [INFO] com.example:aggregation:pom:1.0.0
wantDeps: []types.Dependency{
{
ID: "com.example:module:1.1.1",
DependsOn: []string{
"org.example:example-dependency:1.2.3",
},
},
{
ID: "org.example:example-dependency:1.2.3",
DependsOn: []string{
"org.example:example-api:2.0.0",
},
},
},
},
{
name: "multi module soft requirement",
inputFile: filepath.Join("testdata", "multi-module-soft-requirement", "pom.xml"),
local: true,
want: []types.Library{
{
ID: "com.example:aggregation:1.0.0",
Name: "com.example:aggregation",
Version: "1.0.0",
},
{
ID: "com.example:module1:1.1.1",
Name: "com.example:module1",
Version: "1.1.1",
},
{
ID: "com.example:module2:1.1.1",
Name: "com.example:module2",
Version: "1.1.1",
},
{
ID: "org.example:example-api:1.7.30",
Name: "org.example:example-api",
Version: "1.7.30",
License: "The Apache Software License, Version 2.0",
},
{
ID: "org.example:example-api:2.0.0",
Name: "org.example:example-api",
Version: "2.0.0",
License: "The Apache Software License, Version 2.0",
},
},
wantDeps: []types.Dependency{
{
ID: "com.example:module1:1.1.1",
DependsOn: []string{
"org.example:example-api:1.7.30",
},
},
{
ID: "com.example:module2:1.1.1",
DependsOn: []string{
"org.example:example-api:2.0.0",
},
},
},
},
{
name: "overwrite artifact version from dependencyManagement in the root POM",
inputFile: filepath.Join("testdata", "root-pom-dep-management", "pom.xml"),
local: true,
want: []types.Library{
{
ID: "com.example:root-pom-dep-management:1.0.0",
Name: "com.example:root-pom-dep-management",
Version: "1.0.0",
},
{
ID: "org.example:example-api:2.0.0",
Name: "org.example:example-api",
Version: "2.0.0",
License: "The Apache Software License, Version 2.0",
Indirect: true,
},
// dependency version is taken from `com.example:root-pom-dep-management` from dependencyManagement
// not from `com.example:example-nested` from `com.example:example-nested`
{
ID: "org.example:example-dependency:1.2.4",
Name: "org.example:example-dependency",
Version: "1.2.4",
Indirect: true,
},
{
ID: "org.example:example-nested:3.3.3",
Name: "org.example:example-nested",
Version: "3.3.3",
},
},
wantDeps: []types.Dependency{
{
ID: "com.example:root-pom-dep-management:1.0.0",
DependsOn: []string{
"org.example:example-nested:3.3.3",
},
},
{
ID: "org.example:example-dependency:1.2.4",
DependsOn: []string{
"org.example:example-api:2.0.0",
},
},
{
ID: "org.example:example-nested:3.3.3",
DependsOn: []string{
"org.example:example-dependency:1.2.4",
},
},
},
},
{
name: "transitive dependencyManagement should not be inherited",
inputFile: "testdata/transitive-dependency-management/pom.xml",
local: true,
want: []types.Library{
// Managed dependencies (org.example:example-api:1.7.30) in org.example:example-dependency-management3
// should not affect dependencies of example-dependency (org.example:example-api:2.0.0)
{
ID: "org.example:example-api:2.0.0",
Name: "org.example:example-api",
Version: "2.0.0",
License: "The Apache Software License, Version 2.0",
Indirect: true,
},
{
ID: "org.example:example-dependency-management3:1.1.1",
Name: "org.example:example-dependency-management3",
Version: "1.1.1",
},
{
ID: "org.example:example-dependency:1.2.3",
Name: "org.example:example-dependency",
Version: "1.2.3",
Indirect: true,
},
{
ID: "org.example:transitive-dependency-management:2.0.0",
Name: "org.example:transitive-dependency-management",
Version: "2.0.0",
},
},
wantDeps: []types.Dependency{
{
ID: "org.example:example-dependency-management3:1.1.1",
DependsOn: []string{
"org.example:example-dependency:1.2.3",
},
},
{
ID: "org.example:example-dependency:1.2.3",
DependsOn: []string{
"org.example:example-api:2.0.0",
},
},
{
ID: "org.example:transitive-dependency-management:2.0.0",
DependsOn: []string{
"org.example:example-dependency-management3:1.1.1",
},
},
},
},
{
name: "parent not found",
inputFile: filepath.Join("testdata", "not-found-parent", "pom.xml"),
local: true,
want: []types.Library{
{
ID: "com.example:no-parent:1.0-SNAPSHOT",
Name: "com.example:no-parent",
Version: "1.0-SNAPSHOT",
License: "Apache 2.0",
},
{
ID: "org.example:example-api:1.7.30",
Name: "org.example:example-api",
Version: "1.7.30",
License: "The Apache Software License, Version 2.0",
},
},
wantDeps: []types.Dependency{
{
ID: "com.example:no-parent:1.0-SNAPSHOT",
DependsOn: []string{
"org.example:example-api:1.7.30",
},
},
},
},
{
name: "dependency not found",
inputFile: filepath.Join("testdata", "not-found-dependency", "pom.xml"),
local: true,
want: []types.Library{
{
ID: "com.example:not-found-dependency:1.0.0",
Name: "com.example:not-found-dependency",
Version: "1.0.0",
License: "Apache 2.0",
},
{
ID: "org.example:example-not-found:999",
Name: "org.example:example-not-found",
Version: "999",
},
},
wantDeps: []types.Dependency{
{
ID: "com.example:not-found-dependency:1.0.0",
DependsOn: []string{
"org.example:example-not-found:999",
},
},
},
},
{
name: "module not found - unable to parse module",
inputFile: filepath.Join("testdata", "not-found-module", "pom.xml"),
local: true,
want: []types.Library{
{
ID: "com.example:aggregation:1.0.0",
Name: "com.example:aggregation",
Version: "1.0.0",
License: "Apache 2.0",
},
},
},
{
name: "multiply licenses",
inputFile: filepath.Join("testdata", "multiply-licenses", "pom.xml"),
local: true,
want: []types.Library{
{
ID: "com.example:multiply-licenses:1.0.0",
Name: "com.example:multiply-licenses",
Version: "1.0.0",
License: "MIT, Apache 2.0",
},
},
},
{
name: "inherit parent license",
inputFile: filepath.Join("testdata", "inherit-license", "module", "submodule", "pom.xml"),
local: true,
want: []types.Library{
{
ID: "com.example.app:submodule:1.0.0",
Name: "com.example.app:submodule",
Version: "1.0.0",
License: "Apache-2.0",
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f, err := os.Open(tt.inputFile)
require.NoError(t, err)
defer f.Close()
var remoteRepos []string
if tt.local {
// for local repository
t.Setenv("MAVEN_HOME", "testdata")
} else {
// for remote repository
h := http.FileServer(http.Dir(filepath.Join("testdata", "repository")))
ts := httptest.NewServer(h)
remoteRepos = []string{ts.URL}
}
p := pom.NewParser(tt.inputFile, pom.WithRemoteRepos(remoteRepos), pom.WithOffline(tt.offline))
gotLibs, gotDeps, err := p.Parse(f)
if tt.wantErr != "" {
require.NotNil(t, err)
assert.Contains(t, err.Error(), tt.wantErr)
return
}
require.NoError(t, err)
assert.Equal(t, tt.want, gotLibs)
assert.Equal(t, tt.wantDeps, gotDeps)
})
}
}
<file_sep>/pkg/python/pip/testdata/requirements_no_version.txt
Flask==2.0.0
pandas
<file_sep>/pkg/java/jar/testdata/testimage/gradle/Dockerfile
FROM gradle:6.8.1-jdk
RUN gradle init --type java-application
COPY build.gradle app/
RUN gradle war
<file_sep>/pkg/ruby/bundler/parse_test.go
package bundler_test
import (
"fmt"
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/aquasecurity/go-dep-parser/pkg/ruby/bundler"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
var (
NormalLibs = []types.Library{
{
ID: "[email protected]",
Name: "coderay",
Version: "1.1.2",
Indirect: true,
Locations: []types.Location{{StartLine: 4, EndLine: 4}},
},
{
ID: "[email protected]",
Name: "concurrent-ruby",
Version: "1.1.5",
Indirect: true,
Locations: []types.Location{{StartLine: 5, EndLine: 5}},
},
{
ID: "[email protected]",
Name: "dotenv",
Version: "2.7.2",
Locations: []types.Location{{StartLine: 6, EndLine: 6}},
},
{
ID: "[email protected]",
Name: "faker",
Version: "1.9.3",
Locations: []types.Location{{StartLine: 7, EndLine: 7}},
},
{
ID: "[email protected]",
Name: "i18n",
Version: "1.6.0",
Indirect: true,
Locations: []types.Location{{StartLine: 9, EndLine: 9}},
},
{
ID: "[email protected]",
Name: "method_source",
Version: "0.9.2",
Indirect: true,
Locations: []types.Location{{StartLine: 11, EndLine: 11}},
},
{
ID: "[email protected]",
Name: "pry",
Version: "0.12.2",
Locations: []types.Location{{StartLine: 12, EndLine: 12}},
},
}
NormalDeps = []types.Dependency{
{
ID: "[email protected]",
DependsOn: []string{"[email protected]"},
},
{
ID: "[email protected]",
DependsOn: []string{"[email protected]"},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
}
Bundler2Libs = []types.Library{
{
ID: "[email protected]",
Name: "coderay",
Version: "1.1.3",
Indirect: true,
Locations: []types.Location{{StartLine: 4, EndLine: 4}},
},
{
ID: "[email protected]",
Name: "concurrent-ruby",
Version: "1.1.10",
Indirect: true,
Locations: []types.Location{{StartLine: 5, EndLine: 5}},
},
{
ID: "[email protected]",
Name: "dotenv",
Version: "2.7.6",
Locations: []types.Location{{StartLine: 6, EndLine: 6}},
},
{
ID: "[email protected]",
Name: "faker",
Version: "2.21.0",
Locations: []types.Location{{StartLine: 7, EndLine: 7}},
},
{
ID: "[email protected]",
Name: "i18n",
Version: "1.10.0",
Indirect: true,
Locations: []types.Location{{StartLine: 9, EndLine: 9}},
},
{
ID: "[email protected]",
Name: "json",
Version: "2.6.2",
Locations: []types.Location{{StartLine: 11, EndLine: 11}},
},
{
ID: "[email protected]",
Name: "method_source",
Version: "1.0.0",
Indirect: true,
Locations: []types.Location{{StartLine: 12, EndLine: 12}},
},
{
ID: "[email protected]",
Name: "pry",
Version: "0.14.1",
Locations: []types.Location{{StartLine: 13, EndLine: 13}},
},
}
Bundler2Deps = []types.Dependency{
{
ID: "[email protected]",
DependsOn: []string{"[email protected]"},
},
{
ID: "[email protected]",
DependsOn: []string{"[email protected]"},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
}
)
func TestParser_Parse(t *testing.T) {
tests := []struct {
name string
file string
wantLibs []types.Library
wantDeps []types.Dependency
wantErr assert.ErrorAssertionFunc
}{
{
name: "normal",
file: "testdata/Gemfile_normal.lock",
wantLibs: NormalLibs,
wantDeps: NormalDeps,
wantErr: assert.NoError,
},
{
name: "bundler2",
file: "testdata/Gemfile_bundler2.lock",
wantLibs: Bundler2Libs,
wantDeps: Bundler2Deps,
wantErr: assert.NoError,
},
{
name: "malformed",
file: "testdata/Gemfile_malformed.lock",
wantLibs: []types.Library{},
wantErr: assert.NoError,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f, err := os.Open(tt.file)
require.NoError(t, err)
defer f.Close()
p := &bundler.Parser{}
gotLibs, gotDeps, err := p.Parse(f)
if !tt.wantErr(t, err, fmt.Sprintf("Parse(%v)", tt.file)) {
return
}
assert.Equalf(t, tt.wantLibs, gotLibs, "Parse(%v)", tt.file)
assert.Equalf(t, tt.wantDeps, gotDeps, "Parse(%v)", tt.file)
})
}
}
<file_sep>/pkg/golang/sum/parse_testcase.go
package sum
import "github.com/aquasecurity/go-dep-parser/pkg/types"
var (
// docker run --name gomod --rm -it golang:1.15 bash
// export USER=gomod
// mkdir repo
// cd repo
// go mod init github.com/org/repo
// go get golang.org/x/xerrors
// go list -m all | awk 'NR>1 {sub(/^v/, "", $2); printf("{\""$1"\", \""$2"\", },\n")}'
GoModNormal = []types.Library{
{Name: "golang.org/x/xerrors", Version: "0.0.0-20200804184101-5ec99f83aff1"},
}
// https://github.com/uudashr/gopkgs/blob/616744904701ef01d868da4b66aad0e6856c361d/v2/go.sum
GoModEmptyLine = []types.Library{
{Name: "github.com/karrick/godirwalk", Version: "1.12.0"},
{Name: "github.com/pkg/errors", Version: "0.8.1"},
}
// docker run --name gomod --rm -it golang:1.15 bash
// export USER=gomod
// mkdir repo
// cd repo
// go mod init github.com/org/repo
// go get golang.org/x/xerrors
// go get github.com/urfave/cli
// go get github.com/stretchr/testify
// go get github.com/BurntSushi/toml
// go list -m all | awk 'NR>1 {sub(/^v/, "", $2); printf("{\""$1"\", \""$2"\", },\n")}'
GoModMany = []types.Library{
{Name: "github.com/BurntSushi/toml", Version: "0.3.1"},
{Name: "github.com/cpuguy83/go-md2man/v2", Version: "2.0.0-20190314233015-f79a8a8ca69d"},
{Name: "github.com/davecgh/go-spew", Version: "1.1.0"},
{Name: "github.com/pmezard/go-difflib", Version: "1.0.0"},
{Name: "github.com/russross/blackfriday/v2", Version: "2.0.1"},
{Name: "github.com/shurcooL/sanitized_anchor_name", Version: "1.0.0"},
{Name: "github.com/stretchr/objx", Version: "0.1.0"},
{Name: "github.com/stretchr/testify", Version: "1.7.0"},
{Name: "github.com/urfave/cli", Version: "1.22.5"},
{Name: "golang.org/x/xerrors", Version: "0.0.0-20200804184101-5ec99f83aff1"},
{Name: "gopkg.in/check.v1", Version: "0.0.0-20161208181325-20d25e280405"},
{Name: "gopkg.in/yaml.v2", Version: "2.2.2"},
{Name: "gopkg.in/yaml.v3", Version: "3.0.0-20200313102051-9f266ea9e77c"},
}
// docker run --name gomod --rm -it golang:1.15 bash
// export USER=gomod
// mkdir repo
// cd repo
// go mod init github.com/org/repo
// go get github.com/aquasecurity/trivy
// go list -m all | awk 'NR>1 {sub(/^v/, "", $2); printf("{\""$1"\", \""$2"\", },\n")}'
GoModTrivy = []types.Library{
{Name: "cloud.google.com/go", Version: "0.65.0"},
{Name: "cloud.google.com/go/bigquery", Version: "1.8.0"},
{Name: "cloud.google.com/go/datastore", Version: "1.1.0"},
{Name: "cloud.google.com/go/pubsub", Version: "1.3.1"},
{Name: "cloud.google.com/go/storage", Version: "1.10.0"},
{Name: "dmitri.shuralyov.com/gpu/mtl", Version: "0.0.0-20190408044501-666a987793e9"},
{Name: "github.com/Azure/azure-sdk-for-go", Version: "38.0.0+incompatible"},
{Name: "github.com/Azure/go-ansiterm", Version: "0.0.0-20170929234023-d6e3b3328b78"},
{Name: "github.com/Azure/go-autorest/autorest", Version: "0.9.3"},
{Name: "github.com/Azure/go-autorest/autorest/adal", Version: "0.8.1"},
{Name: "github.com/Azure/go-autorest/autorest/date", Version: "0.2.0"},
{Name: "github.com/Azure/go-autorest/autorest/mocks", Version: "0.3.0"},
{Name: "github.com/Azure/go-autorest/autorest/to", Version: "0.3.0"},
{Name: "github.com/Azure/go-autorest/autorest/validation", Version: "0.1.0"},
{Name: "github.com/Azure/go-autorest/logger", Version: "0.1.0"},
{Name: "github.com/Azure/go-autorest/tracing", Version: "0.5.0"},
{Name: "github.com/BurntSushi/toml", Version: "0.3.1"},
{Name: "github.com/BurntSushi/xgb", Version: "0.0.0-20160522181843-27f122750802"},
{Name: "github.com/GoogleCloudPlatform/docker-credential-gcr", Version: "1.5.0"},
{Name: "github.com/GoogleCloudPlatform/k8s-cloud-provider", Version: "0.0.0-20190822182118-27a4ced34534"},
{Name: "github.com/Microsoft/go-winio", Version: "0.4.15-0.20190919025122-fc70bd9a86b5"},
{Name: "github.com/Microsoft/hcsshim", Version: "0.8.6"},
{Name: "github.com/NYTimes/gziphandler", Version: "0.0.0-20170623195520-56545f4a5d46"},
{Name: "github.com/OneOfOne/xxhash", Version: "1.2.7"},
{Name: "github.com/PuerkitoBio/purell", Version: "1.1.1"},
{Name: "github.com/PuerkitoBio/urlesc", Version: "0.0.0-20170810143723-de5bf2ad4578"},
{Name: "github.com/VividCortex/ewma", Version: "1.1.1"},
{Name: "github.com/alcortesm/tgz", Version: "0.0.0-20161220082320-9c5fe88206d7"},
{Name: "github.com/alecthomas/template", Version: "0.0.0-20160405071501-a0175ee3bccc"},
{Name: "github.com/alecthomas/units", Version: "0.0.0-20151022065526-2efee857e7cf"},
{Name: "github.com/alicebob/gopher-json", Version: "0.0.0-20200520072559-a9ecdc9d1d3a"},
{Name: "github.com/alicebob/miniredis/v2", Version: "2.14.1"},
{Name: "github.com/anmitsu/go-shlex", Version: "0.0.0-20161002113705-648efa622239"},
{Name: "github.com/aquasecurity/bolt-fixtures", Version: "0.0.0-20200903104109-d34e7f983986"},
{Name: "github.com/aquasecurity/fanal", Version: "0.0.0-20210119051230-28c249da7cfd"},
{Name: "github.com/aquasecurity/go-dep-parser", Version: "0.0.0-20201028043324-889d4a92b8e0"},
{Name: "github.com/aquasecurity/go-gem-version", Version: "0.0.0-20201115065557-8eed6fe000ce"},
{Name: "github.com/aquasecurity/go-npm-version", Version: "0.0.0-20201110091526-0b796d180798"},
{Name: "github.com/aquasecurity/go-pep440-version", Version: "0.0.0-20210121094942-22b2f8951d46"},
{Name: "github.com/aquasecurity/go-version", Version: "0.0.0-20210121072130-637058cfe492"},
{Name: "github.com/aquasecurity/testdocker", Version: "0.0.0-20210106133225-0b17fe083674"},
{Name: "github.com/aquasecurity/trivy", Version: "0.16.0"},
{Name: "github.com/aquasecurity/trivy-db", Version: "0.0.0-20210105160501-c5bf4e153277"},
{Name: "github.com/aquasecurity/vuln-list-update", Version: "0.0.0-20191016075347-3d158c2bf9a2"},
{Name: "github.com/araddon/dateparse", Version: "0.0.0-20190426192744-0d74ffceef83"},
{Name: "github.com/armon/consul-api", Version: "0.0.0-20180202201655-eb2c6b5be1b6"},
{Name: "github.com/armon/go-socks5", Version: "0.0.0-20160902184237-e75332964ef5"},
{Name: "github.com/aws/aws-sdk-go", Version: "1.27.1"},
{Name: "github.com/beorn7/perks", Version: "1.0.0"},
{Name: "github.com/bgentry/speakeasy", Version: "0.1.0"},
{Name: "github.com/blang/semver", Version: "3.5.0+incompatible"},
{Name: "github.com/briandowns/spinner", Version: "1.12.0"},
{Name: "github.com/caarlos0/env/v6", Version: "6.0.0"},
{Name: "github.com/cenkalti/backoff", Version: "2.2.1+incompatible"},
{Name: "github.com/census-instrumentation/opencensus-proto", Version: "0.2.1"},
{Name: "github.com/cespare/xxhash/v2", Version: "2.1.1"},
{Name: "github.com/cheggaaa/pb/v3", Version: "3.0.3"},
{Name: "github.com/chzyer/logex", Version: "1.1.10"},
{Name: "github.com/chzyer/readline", Version: "0.0.0-20180603132655-2972be24d48e"},
{Name: "github.com/chzyer/test", Version: "0.0.0-20180213035817-a1ea475d72b1"},
{Name: "github.com/client9/misspell", Version: "0.3.4"},
{Name: "github.com/cncf/udpa/go", Version: "0.0.0-20191209042840-269d4d468f6f"},
{Name: "github.com/cockroachdb/datadriven", Version: "0.0.0-20190809214429-80d97fb3cbaa"},
{Name: "github.com/containerd/containerd", Version: "1.3.3"},
{Name: "github.com/containerd/continuity", Version: "0.0.0-20190426062206-aaeac12a7ffc"},
{Name: "github.com/coreos/etcd", Version: "3.3.10+incompatible"},
{Name: "github.com/coreos/go-etcd", Version: "2.0.0+incompatible"},
{Name: "github.com/coreos/go-oidc", Version: "2.1.0+incompatible"},
{Name: "github.com/coreos/go-semver", Version: "0.3.0"},
{Name: "github.com/coreos/go-systemd", Version: "0.0.0-20190321100706-95778dfbb74e"},
{Name: "github.com/coreos/pkg", Version: "0.0.0-20180108230652-97fdf19511ea"},
{Name: "github.com/cpuguy83/go-md2man", Version: "1.0.10"},
{Name: "github.com/cpuguy83/go-md2man/v2", Version: "2.0.0"},
{Name: "github.com/creack/pty", Version: "1.1.9"},
{Name: "github.com/davecgh/go-spew", Version: "1.1.1"},
{Name: "github.com/deckarep/golang-set", Version: "1.7.1"},
{Name: "github.com/dgrijalva/jwt-go", Version: "3.2.0+incompatible"},
{Name: "github.com/dgryski/go-rendezvous", Version: "0.0.0-20200823014737-9f7001d12a5f"},
{Name: "github.com/dnaeon/go-vcr", Version: "1.0.1"},
{Name: "github.com/docker/cli", Version: "0.0.0-20191017083524-a8ff7f821017"},
{Name: "github.com/docker/distribution", Version: "2.7.1+incompatible"},
{Name: "github.com/docker/docker", Version: "1.4.2-0.20190924003213-a8608b5b67c7"},
{Name: "github.com/docker/docker-credential-helpers", Version: "0.6.3"},
{Name: "github.com/docker/go-connections", Version: "0.4.0"},
{Name: "github.com/docker/go-units", Version: "0.4.0"},
{Name: "github.com/docker/spdystream", Version: "0.0.0-20160310174837-449fdfce4d96"},
{Name: "github.com/dustin/go-humanize", Version: "1.0.0"},
{Name: "github.com/elazarl/goproxy", Version: "0.0.0-20200809112317-0581fc3aee2d"},
{Name: "github.com/elazarl/goproxy/ext", Version: "0.0.0-20200809112317-0581fc3aee2d"},
{Name: "github.com/emicklei/go-restful", Version: "2.9.5+incompatible"},
{Name: "github.com/emirpasic/gods", Version: "1.12.0"},
{Name: "github.com/envoyproxy/go-control-plane", Version: "0.9.4"},
{Name: "github.com/envoyproxy/protoc-gen-validate", Version: "0.1.0"},
{Name: "github.com/evanphx/json-patch", Version: "4.2.0+incompatible"},
{Name: "github.com/fatih/color", Version: "1.10.0"},
{Name: "github.com/flynn/go-shlex", Version: "0.0.0-20150515145356-3f9db97f8568"},
{Name: "github.com/fsnotify/fsnotify", Version: "1.4.9"},
{Name: "github.com/ghodss/yaml", Version: "1.0.0"},
{Name: "github.com/gin-contrib/sse", Version: "0.1.0"},
{Name: "github.com/gin-gonic/gin", Version: "1.5.0"},
{Name: "github.com/gliderlabs/ssh", Version: "0.2.2"},
{Name: "github.com/go-git/gcfg", Version: "1.5.0"},
{Name: "github.com/go-git/go-billy/v5", Version: "5.0.0"},
{Name: "github.com/go-git/go-git-fixtures/v4", Version: "4.0.1"},
{Name: "github.com/go-git/go-git/v5", Version: "5.0.0"},
{Name: "github.com/go-gl/glfw", Version: "0.0.0-20190409004039-e6da0acd62b1"},
{Name: "github.com/go-gl/glfw/v3.3/glfw", Version: "0.0.0-20200222043503-6f7a984d4dc4"},
{Name: "github.com/go-kit/kit", Version: "0.8.0"},
{Name: "github.com/go-logfmt/logfmt", Version: "0.3.0"},
{Name: "github.com/go-logr/logr", Version: "0.1.0"},
{Name: "github.com/go-openapi/jsonpointer", Version: "0.19.3"},
{Name: "github.com/go-openapi/jsonreference", Version: "0.19.3"},
{Name: "github.com/go-openapi/spec", Version: "0.19.3"},
{Name: "github.com/go-openapi/swag", Version: "0.19.5"},
{Name: "github.com/go-playground/locales", Version: "0.13.0"},
{Name: "github.com/go-playground/universal-translator", Version: "0.17.0"},
{Name: "github.com/go-redis/redis", Version: "6.15.7+incompatible"},
{Name: "github.com/go-redis/redis/v8", Version: "8.4.0"},
{Name: "github.com/go-restruct/restruct", Version: "0.0.0-20191227155143-5734170a48a1"},
{Name: "github.com/go-sql-driver/mysql", Version: "1.5.0"},
{Name: "github.com/go-stack/stack", Version: "1.8.0"},
{Name: "github.com/gobwas/glob", Version: "0.2.3"},
{Name: "github.com/goccy/go-yaml", Version: "1.8.2"},
{Name: "github.com/gogo/protobuf", Version: "1.3.1"},
{Name: "github.com/golang/glog", Version: "0.0.0-20160126235308-23def4e6c14b"},
{Name: "github.com/golang/groupcache", Version: "0.0.0-20200121045136-8c9f03a8e57e"},
{Name: "github.com/golang/mock", Version: "1.4.4"},
{Name: "github.com/golang/protobuf", Version: "1.4.2"},
{Name: "github.com/google/btree", Version: "1.0.0"},
{Name: "github.com/google/go-cmp", Version: "0.5.3"},
{Name: "github.com/google/go-containerregistry", Version: "0.0.0-20200331213917-3d03ed9b1ca2"},
{Name: "github.com/google/go-github/v28", Version: "28.1.1"},
{Name: "github.com/google/go-querystring", Version: "1.0.0"},
{Name: "github.com/google/gofuzz", Version: "1.0.0"},
{Name: "github.com/google/martian", Version: "2.1.0+incompatible"},
{Name: "github.com/google/martian/v3", Version: "3.0.0"},
{Name: "github.com/google/pprof", Version: "0.0.0-20200708004538-1a94d8640e99"},
{Name: "github.com/google/renameio", Version: "0.1.0"},
{Name: "github.com/google/subcommands", Version: "1.0.1"},
{Name: "github.com/google/uuid", Version: "1.1.1"},
{Name: "github.com/google/wire", Version: "0.3.0"},
{Name: "github.com/googleapis/gax-go/v2", Version: "2.0.5"},
{Name: "github.com/googleapis/gnostic", Version: "0.2.2"},
{Name: "github.com/gophercloud/gophercloud", Version: "0.1.0"},
{Name: "github.com/gopherjs/gopherjs", Version: "0.0.0-20200217142428-fce0ec30dd00"},
{Name: "github.com/gorilla/context", Version: "1.1.1"},
{Name: "github.com/gorilla/mux", Version: "1.7.4"},
{Name: "github.com/gorilla/websocket", Version: "1.4.0"},
{Name: "github.com/gregjones/httpcache", Version: "0.0.0-20180305231024-9cad4c3443a7"},
{Name: "github.com/grpc-ecosystem/go-grpc-middleware", Version: "1.0.1-0.20190118093823-f849b5445de4"},
{Name: "github.com/grpc-ecosystem/go-grpc-prometheus", Version: "1.2.0"},
{Name: "github.com/grpc-ecosystem/grpc-gateway", Version: "1.9.5"},
{Name: "github.com/hashicorp/errwrap", Version: "1.0.0"},
{Name: "github.com/hashicorp/go-multierror", Version: "1.1.0"},
{Name: "github.com/hashicorp/go-version", Version: "1.2.1"},
{Name: "github.com/hashicorp/golang-lru", Version: "0.5.3"},
{Name: "github.com/hashicorp/hcl", Version: "1.0.0"},
{Name: "github.com/hpcloud/tail", Version: "1.0.0"},
{Name: "github.com/ianlancetaylor/demangle", Version: "0.0.0-20181102032728-5e5cf60278f6"},
{Name: "github.com/imdario/mergo", Version: "0.3.5"},
{Name: "github.com/inconshreveable/mousetrap", Version: "1.0.0"},
{Name: "github.com/jbenet/go-context", Version: "0.0.0-20150711004518-d14ea06fba99"},
{Name: "github.com/jessevdk/go-flags", Version: "1.4.0"},
{Name: "github.com/jmespath/go-jmespath", Version: "0.0.0-20180206201540-c2b33e8439af"},
{Name: "github.com/joefitzgerald/rainbow-reporter", Version: "0.1.0"},
{Name: "github.com/jonboulle/clockwork", Version: "0.1.0"},
{Name: "github.com/json-iterator/go", Version: "1.1.8"},
{Name: "github.com/jstemmer/go-junit-report", Version: "0.9.1"},
{Name: "github.com/jtolds/gls", Version: "4.20.0+incompatible"},
{Name: "github.com/julienschmidt/httprouter", Version: "1.2.0"},
{Name: "github.com/kevinburke/ssh_config", Version: "0.0.0-20190725054713-01f96b0aa0cd"},
{Name: "github.com/kisielk/errcheck", Version: "1.2.0"},
{Name: "github.com/kisielk/gotool", Version: "1.0.0"},
{Name: "github.com/knqyf263/go-apk-version", Version: "0.0.0-20200609155635-041fdbb8563f"},
{Name: "github.com/knqyf263/go-deb-version", Version: "0.0.0-20190517075300-09fca494f03d"},
{Name: "github.com/knqyf263/go-rpm-version", Version: "0.0.0-20170716094938-74609b86c936"},
{Name: "github.com/knqyf263/go-rpmdb", Version: "0.0.0-20201215100354-a9e3110d8ee1"},
{Name: "github.com/knqyf263/nested", Version: "0.0.1"},
{Name: "github.com/konsorten/go-windows-terminal-sequences", Version: "1.0.2"},
{Name: "github.com/kr/logfmt", Version: "0.0.0-20140226030751-b84e30acd515"},
{Name: "github.com/kr/pretty", Version: "0.1.0"},
{Name: "github.com/kr/pty", Version: "1.1.5"},
{Name: "github.com/kr/text", Version: "0.2.0"},
{Name: "github.com/kylelemons/godebug", Version: "1.1.0"},
{Name: "github.com/leodido/go-urn", Version: "1.2.0"},
{Name: "github.com/magiconair/properties", Version: "1.8.0"},
{Name: "github.com/mailru/easyjson", Version: "0.7.0"},
{Name: "github.com/mattn/go-colorable", Version: "0.1.8"},
{Name: "github.com/mattn/go-isatty", Version: "0.0.12"},
{Name: "github.com/mattn/go-jsonpointer", Version: "0.0.0-20180225143300-37667080efed"},
{Name: "github.com/mattn/go-runewidth", Version: "0.0.9"},
{Name: "github.com/matttproud/golang_protobuf_extensions", Version: "1.0.1"},
{Name: "github.com/maxbrunsfeld/counterfeiter/v6", Version: "6.2.2"},
{Name: "github.com/mitchellh/go-homedir", Version: "1.1.0"},
{Name: "github.com/mitchellh/mapstructure", Version: "1.1.2"},
{Name: "github.com/modern-go/concurrent", Version: "0.0.0-20180306012644-bacd9c7ef1dd"},
{Name: "github.com/modern-go/reflect2", Version: "1.0.1"},
{Name: "github.com/morikuni/aec", Version: "1.0.0"},
{Name: "github.com/munnerz/goautoneg", Version: "0.0.0-20191010083416-a7dc8b61c822"},
{Name: "github.com/mwitkow/go-conntrack", Version: "0.0.0-20161129095857-cc309e4a2223"},
{Name: "github.com/mxk/go-flowrate", Version: "0.0.0-20140419014527-cca7078d478f"},
{Name: "github.com/niemeyer/pretty", Version: "0.0.0-20200227124842-a10e7caefd8e"},
{Name: "github.com/nxadm/tail", Version: "1.4.4"},
{Name: "github.com/olekukonko/tablewriter", Version: "0.0.2-0.20190607075207-195002e6e56a"},
{Name: "github.com/onsi/ginkgo", Version: "1.14.2"},
{Name: "github.com/onsi/gomega", Version: "1.10.3"},
{Name: "github.com/open-policy-agent/opa", Version: "0.21.1"},
{Name: "github.com/opencontainers/go-digest", Version: "1.0.0-rc1"},
{Name: "github.com/opencontainers/image-spec", Version: "1.0.2-0.20190823105129-775207bd45b6"},
{Name: "github.com/opencontainers/runc", Version: "0.1.1"},
{Name: "github.com/parnurzeal/gorequest", Version: "0.2.16"},
{Name: "github.com/pelletier/go-toml", Version: "1.2.0"},
{Name: "github.com/peterbourgon/diskv", Version: "2.0.1+incompatible"},
{Name: "github.com/peterh/liner", Version: "0.0.0-20170211195444-bf27d3ba8e1d"},
{Name: "github.com/pkg/errors", Version: "0.9.1"},
{Name: "github.com/pmezard/go-difflib", Version: "1.0.0"},
{Name: "github.com/pquerna/cachecontrol", Version: "0.0.0-20171018203845-0dec1b30a021"},
{Name: "github.com/prometheus/client_golang", Version: "1.0.0"},
{Name: "github.com/prometheus/client_model", Version: "0.0.0-20190812154241-14fe0d1b01d4"},
{Name: "github.com/prometheus/common", Version: "0.4.1"},
{Name: "github.com/prometheus/procfs", Version: "0.0.2"},
{Name: "github.com/rcrowley/go-metrics", Version: "0.0.0-20181016184325-3113b8401b8a"},
{Name: "github.com/remyoudompheng/bigfft", Version: "0.0.0-20170806203942-52369c62f446"},
{Name: "github.com/rogpeppe/fastuuid", Version: "0.0.0-20150106093220-6724a57986af"},
{Name: "github.com/rogpeppe/go-charset", Version: "0.0.0-20180617210344-2471d30d28b4"},
{Name: "github.com/rogpeppe/go-internal", Version: "1.3.0"},
{Name: "github.com/rubiojr/go-vhd", Version: "0.0.0-20160810183302-0bfd3b39853c"},
{Name: "github.com/russross/blackfriday", Version: "1.5.2"},
{Name: "github.com/russross/blackfriday/v2", Version: "2.0.1"},
{Name: "github.com/saracen/walker", Version: "0.0.0-20191201085201-324a081bae7e"},
{Name: "github.com/satori/go.uuid", Version: "1.2.0"},
{Name: "github.com/sclevine/spec", Version: "1.2.0"},
{Name: "github.com/sergi/go-diff", Version: "1.1.0"},
{Name: "github.com/shurcooL/sanitized_anchor_name", Version: "1.0.0"},
{Name: "github.com/simplereach/timeutils", Version: "1.2.0"},
{Name: "github.com/sirupsen/logrus", Version: "1.5.0"},
{Name: "github.com/smartystreets/assertions", Version: "1.2.0"},
{Name: "github.com/smartystreets/goconvey", Version: "1.6.4"},
{Name: "github.com/soheilhy/cmux", Version: "0.1.4"},
{Name: "github.com/sosedoff/gitkit", Version: "0.2.0"},
{Name: "github.com/spf13/afero", Version: "1.2.2"},
{Name: "github.com/spf13/cast", Version: "1.3.0"},
{Name: "github.com/spf13/cobra", Version: "0.0.5"},
{Name: "github.com/spf13/jwalterweatherman", Version: "1.0.0"},
{Name: "github.com/spf13/pflag", Version: "1.0.5"},
{Name: "github.com/spf13/viper", Version: "1.3.2"},
{Name: "github.com/stretchr/objx", Version: "0.3.0"},
{Name: "github.com/stretchr/testify", Version: "1.6.1"},
{Name: "github.com/testcontainers/testcontainers-go", Version: "0.3.1"},
{Name: "github.com/tmc/grpc-websocket-proxy", Version: "0.0.0-20170815181823-89b8d40f7ca8"},
{Name: "github.com/twitchtv/twirp", Version: "5.10.1+incompatible"},
{Name: "github.com/ugorji/go", Version: "1.1.7"},
{Name: "github.com/ugorji/go/codec", Version: "1.1.7"},
{Name: "github.com/urfave/cli", Version: "1.22.5"},
{Name: "github.com/urfave/cli/v2", Version: "2.3.0"},
{Name: "github.com/vdemeester/k8s-pkg-credentialprovider", Version: "1.17.4"},
{Name: "github.com/vmware/govmomi", Version: "0.20.3"},
{Name: "github.com/xanzy/ssh-agent", Version: "0.2.1"},
{Name: "github.com/xiang90/probing", Version: "0.0.0-20190116061207-43a291ad63a2"},
{Name: "github.com/xordataexchange/crypt", Version: "0.0.3-0.20170626215501-b2862e3d0a77"},
{Name: "github.com/yashtewari/glob-intersection", Version: "0.0.0-20180916065949-5c77d914dd0b"},
{Name: "github.com/yuin/goldmark", Version: "1.1.32"},
{Name: "github.com/yuin/gopher-lua", Version: "0.0.0-20191220021717-ab39c6098bdb"},
{Name: "go.etcd.io/bbolt", Version: "1.3.5"},
{Name: "go.etcd.io/etcd", Version: "0.0.0-20191023171146-3cf2f69b5738"},
{Name: "go.opencensus.io", Version: "0.22.4"},
{Name: "go.opentelemetry.io/otel", Version: "0.14.0"},
{Name: "go.uber.org/atomic", Version: "1.5.1"},
{Name: "go.uber.org/multierr", Version: "1.4.0"},
{Name: "go.uber.org/tools", Version: "0.0.0-20190618225709-2cfd321de3ee"},
{Name: "go.uber.org/zap", Version: "1.13.0"},
{Name: "golang.org/x/crypto", Version: "0.0.0-20201002170205-7f63de1d35b0"},
{Name: "golang.org/x/exp", Version: "0.0.0-20200224162631-6cc2880d07d6"},
{Name: "golang.org/x/image", Version: "0.0.0-20190802002840-cff245a6509b"},
{Name: "golang.org/x/lint", Version: "0.0.0-20200302205851-738671d3881b"},
{Name: "golang.org/x/mobile", Version: "0.0.0-20190719004257-d2bd2a29d028"},
{Name: "golang.org/x/mod", Version: "0.3.0"},
{Name: "golang.org/x/net", Version: "0.0.0-20201006153459-a7d1128ccaa0"},
{Name: "golang.org/x/oauth2", Version: "0.0.0-20201208152858-08078c50e5b5"},
{Name: "golang.org/x/sync", Version: "0.0.0-20200625203802-6e8e738ad208"},
{Name: "golang.org/x/sys", Version: "0.0.0-20201006155630-ac719f4daadf"},
{Name: "golang.org/x/text", Version: "0.3.3"},
{Name: "golang.org/x/time", Version: "0.0.0-20191024005414-555d28b269f0"},
{Name: "golang.org/x/tools", Version: "0.0.0-20200825202427-b303f430e36d"},
{Name: "golang.org/x/xerrors", Version: "0.0.0-20200804184101-5ec99f83aff1"},
{Name: "gonum.org/v1/gonum", Version: "0.0.0-20190331200053-3d26580ed485"},
{Name: "gonum.org/v1/netlib", Version: "0.0.0-20190331212654-76723241ea4e"},
{Name: "google.golang.org/api", Version: "0.30.0"},
{Name: "google.golang.org/appengine", Version: "1.6.6"},
{Name: "google.golang.org/genproto", Version: "0.0.0-20200825200019-8632dd797987"},
{Name: "google.golang.org/grpc", Version: "1.31.0"},
{Name: "google.golang.org/protobuf", Version: "1.25.0"},
{Name: "gopkg.in/alecthomas/kingpin.v2", Version: "2.2.6"},
{Name: "gopkg.in/check.v1", Version: "1.0.0-20200902074654-038fdea0a05b"},
{Name: "gopkg.in/cheggaaa/pb.v1", Version: "1.0.28"},
{Name: "gopkg.in/errgo.v2", Version: "2.1.0"},
{Name: "gopkg.in/fsnotify.v1", Version: "1.4.7"},
{Name: "gopkg.in/gcfg.v1", Version: "1.2.0"},
{Name: "gopkg.in/go-playground/assert.v1", Version: "1.2.1"},
{Name: "gopkg.in/go-playground/validator.v9", Version: "9.31.0"},
{Name: "gopkg.in/inf.v0", Version: "0.9.1"},
{Name: "gopkg.in/mgo.v2", Version: "2.0.0-20180705113604-9856a29383ce"},
{Name: "gopkg.in/natefinch/lumberjack.v2", Version: "2.0.0"},
{Name: "gopkg.in/resty.v1", Version: "1.12.0"},
{Name: "gopkg.in/square/go-jose.v2", Version: "2.2.2"},
{Name: "gopkg.in/tomb.v1", Version: "1.0.0-20141024135613-dd632973f1e7"},
{Name: "gopkg.in/warnings.v0", Version: "0.1.2"},
{Name: "gopkg.in/yaml.v2", Version: "2.4.0"},
{Name: "gopkg.in/yaml.v3", Version: "3.0.0-20200615113413-eeeca48fe776"},
{Name: "gotest.tools", Version: "2.2.0+incompatible"},
{Name: "honnef.co/go/tools", Version: "0.0.1-2020.1.4"},
{Name: "k8s.io/api", Version: "0.17.4"},
{Name: "k8s.io/apimachinery", Version: "0.17.4"},
{Name: "k8s.io/apiserver", Version: "0.17.4"},
{Name: "k8s.io/client-go", Version: "0.17.4"},
{Name: "k8s.io/cloud-provider", Version: "0.17.4"},
{Name: "k8s.io/code-generator", Version: "0.17.2"},
{Name: "k8s.io/component-base", Version: "0.17.4"},
{Name: "k8s.io/csi-translation-lib", Version: "0.17.4"},
{Name: "k8s.io/gengo", Version: "0.0.0-20190822140433-26a664648505"},
{Name: "k8s.io/klog", Version: "1.0.0"},
{Name: "k8s.io/klog/v2", Version: "2.0.0"},
{Name: "k8s.io/kube-openapi", Version: "0.0.0-20191107075043-30be4d16710a"},
{Name: "k8s.io/legacy-cloud-providers", Version: "0.17.4"},
{Name: "k8s.io/utils", Version: "0.0.0-20201110183641-67b214c5f920"},
{Name: "modernc.org/cc", Version: "1.0.0"},
{Name: "modernc.org/golex", Version: "1.0.0"},
{Name: "modernc.org/mathutil", Version: "1.0.0"},
{Name: "modernc.org/strutil", Version: "1.0.0"},
{Name: "modernc.org/xc", Version: "1.0.0"},
{Name: "moul.io/http2curl", Version: "1.0.0"},
{Name: "rsc.io/binaryregexp", Version: "0.2.0"},
{Name: "rsc.io/quote/v3", Version: "3.1.0"},
{Name: "rsc.io/sampler", Version: "1.3.0"},
{Name: "sigs.k8s.io/structured-merge-diff", Version: "1.0.1-0.20191108220359-b1b620dd3f06"},
{Name: "sigs.k8s.io/yaml", Version: "1.1.0"},
}
)
<file_sep>/pkg/python/poetry/parse_testcase.go
package poetry
import "github.com/aquasecurity/go-dep-parser/pkg/types"
var (
// docker run --name pipenv --rm -it python@sha256:e1141f10176d74d1a0e87a7c0a0a5a98dd98ec5ac12ce867768f40c6feae2fd9 sh
// apk add curl
// curl -sSL https://install.python-poetry.org | python3 -
// export PATH=/root/.local/bin:$PATH
// poetry new normal && cd normal
// poetry add [email protected]
// poetry show -a | awk '{gsub(/\(!\)/, ""); printf("{ID: \""$1"@"$2"\", Name: \""$1"\", Version: \""$2"\"},\n") }'
poetryNormal = []types.Library{
{ID: "[email protected]", Name: "pypi", Version: "2.1"},
}
// docker run --name pipenv --rm -it python@sha256:e1141f10176d74d1a0e87a7c0a0a5a98dd98ec5ac12ce867768f40c6feae2fd9 sh
// apk add curl
// curl -sSL https://install.python-poetry.org | python3 -
// export PATH=/root/.local/bin:$PATH
// poetry new many && cd many
// curl -o poetry.lock https://raw.githubusercontent.com/python-poetry/poetry/c8945eb110aeda611cc6721565d7ad0c657d453a/poetry.lock
// curl -o pyproject.toml https://raw.githubusercontent.com/python-poetry/poetry/c8945eb110aeda611cc6721565d7ad0c657d453a/pyproject.toml
// poetry show -a | awk '{gsub(/\(!\)/, ""); printf("{ID: \""$1"@"$2"\", Name: \""$1"\", Version: \""$2"\"},\n") }'
// `--no-dev` flag uncorrected returns deps. Then need to remove `dev` deps manually
// list of dev deps - cat poetry.lock | grep 'category = "dev"' -B 3
poetryMany = []types.Library{
{ID: "[email protected]", Name: "attrs", Version: "22.2.0"},
{ID: "[email protected]", Name: "backports-cached-property", Version: "1.0.2"},
{ID: "[email protected]", Name: "build", Version: "0.10.0"},
{ID: "[email protected]", Name: "cachecontrol", Version: "0.12.11"},
{ID: "[email protected]", Name: "certifi", Version: "2022.12.7"},
{ID: "[email protected]", Name: "cffi", Version: "1.15.1"},
{ID: "[email protected]", Name: "charset-normalizer", Version: "3.0.1"},
{ID: "[email protected]", Name: "cleo", Version: "2.0.1"},
{ID: "[email protected]", Name: "colorama", Version: "0.4.6"},
{ID: "[email protected]", Name: "crashtest", Version: "0.4.1"},
{ID: "[email protected]", Name: "cryptography", Version: "39.0.0"},
{ID: "[email protected]", Name: "distlib", Version: "0.3.6"},
{ID: "[email protected]", Name: "dulwich", Version: "0.21.2"},
{ID: "[email protected]", Name: "filelock", Version: "3.9.0"},
{ID: "[email protected]", Name: "html5lib", Version: "1.1"},
{ID: "[email protected]", Name: "idna", Version: "3.4"},
{ID: "[email protected]", Name: "importlib-metadata", Version: "6.0.0"},
{ID: "[email protected]", Name: "importlib-resources", Version: "5.10.2"},
{ID: "[email protected]", Name: "installer", Version: "0.6.0"},
{ID: "[email protected]", Name: "jaraco-classes", Version: "3.2.3"},
{ID: "[email protected]", Name: "jeepney", Version: "0.8.0"},
{ID: "[email protected]", Name: "jsonschema", Version: "4.17.3"},
{ID: "[email protected]", Name: "keyring", Version: "23.13.1"},
{ID: "[email protected]", Name: "lockfile", Version: "0.12.2"},
{ID: "[email protected]", Name: "more-itertools", Version: "9.0.0"},
{ID: "[email protected]", Name: "msgpack", Version: "1.0.4"},
{ID: "[email protected]", Name: "packaging", Version: "23.0"},
{ID: "[email protected]", Name: "pexpect", Version: "4.8.0"},
{ID: "[email protected]", Name: "pkginfo", Version: "1.9.6"},
{ID: "[email protected]", Name: "pkgutil-resolve-name", Version: "1.3.10"},
{ID: "[email protected]", Name: "platformdirs", Version: "2.6.2"},
{ID: "[email protected]", Name: "poetry-core", Version: "1.5.0"},
{ID: "[email protected]", Name: "poetry-plugin-export", Version: "1.3.0"},
{ID: "[email protected]", Name: "ptyprocess", Version: "0.7.0"},
{ID: "[email protected]", Name: "pycparser", Version: "2.21"},
{ID: "[email protected]", Name: "pyproject-hooks", Version: "1.0.0"},
{ID: "[email protected]", Name: "pyrsistent", Version: "0.19.3"},
{ID: "[email protected]", Name: "pywin32-ctypes", Version: "0.2.0"},
{ID: "[email protected]", Name: "rapidfuzz", Version: "2.13.7"},
{ID: "[email protected]", Name: "requests", Version: "2.28.2"},
{ID: "[email protected]", Name: "requests-toolbelt", Version: "0.10.1"},
{ID: "[email protected]", Name: "secretstorage", Version: "3.3.3"},
{ID: "[email protected]", Name: "shellingham", Version: "1.5.0.post1"},
{ID: "[email protected]", Name: "six", Version: "1.16.0"},
{ID: "[email protected]", Name: "tomli", Version: "2.0.1"},
{ID: "[email protected]", Name: "tomlkit", Version: "0.11.6"},
{ID: "[email protected]", Name: "trove-classifiers", Version: "2023.1.20"},
{ID: "[email protected]", Name: "typing-extensions", Version: "4.4.0"},
{ID: "[email protected]", Name: "urllib3", Version: "1.26.14"},
{ID: "[email protected]", Name: "virtualenv", Version: "20.16.5"},
{ID: "[email protected]", Name: "virtualenv", Version: "20.17.1"},
{ID: "[email protected]", Name: "webencodings", Version: "0.5.1"},
{ID: "[email protected]", Name: "xattr", Version: "0.10.1"},
{ID: "[email protected]", Name: "zipp", Version: "3.12.0"},
}
// cat poetry.lock | grep "\[package.dependencies\]" -B 3 -A 8 - it might help to complete this slice
poetryManyDeps = []types.Dependency{
{ID: "[email protected]", DependsOn: []string{"[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]", "[email protected]", "[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]", "[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]", "[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]", "[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]", "[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]", "[email protected]", "[email protected]", "[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]", "[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]", "[email protected]", "[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]", "[email protected]", "[email protected]", "[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]"}},
}
// docker run --name pipenv --rm -it python@sha256:e1141f10176d74d1a0e87a7c0a0a5a98dd98ec5ac12ce867768f40c6feae2fd9 sh
// apk add curl
// curl -sSL https://install.python-poetry.org | python3 -
// export PATH=/root/.local/bin:$PATH
// poetry new web && cd web
// poetry add [email protected]
// poetry show -a | awk '{gsub(/\(!\)/, ""); printf("{ID: \""$1"@"$2"\", Name: \""$1"\", Version: \""$2"\"},\n") }'
poetryFlask = []types.Library{
{ID: "[email protected]", Name: "click", Version: "8.1.3"},
{ID: "[email protected]", Name: "colorama", Version: "0.4.6"},
{ID: "[email protected]", Name: "flask", Version: "1.0.3"},
{ID: "[email protected]", Name: "itsdangerous", Version: "2.1.2"},
{ID: "[email protected]", Name: "jinja2", Version: "3.1.2"},
{ID: "[email protected]", Name: "markupsafe", Version: "2.1.2"},
{ID: "[email protected]", Name: "werkzeug", Version: "2.2.3"},
}
// cat poetry.lock | grep "\[package.dependencies\]" -B 3 -A 8 - it might help to complete this slice
poetryFlaskDeps = []types.Dependency{
{ID: "[email protected]", DependsOn: []string{"[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]", "[email protected]", "[email protected]", "[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]"}},
}
)
<file_sep>/pkg/nodejs/yarn/parse_test.go
package yarn
import (
"os"
"sort"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
func TestParsePattern(t *testing.T) {
vectors := []struct {
name string
target string
expectName string
expectProtocol string
expactVersion string
occurErr bool
}{
{
name: "normal",
target: `asn1@~0.2.3:`,
expectName: "asn1",
expactVersion: "~0.2.3",
},
{
name: "normal with protocol",
target: `asn1@npm:~0.2.3:`,
expectName: "asn1",
expectProtocol: "npm",
expactVersion: "~0.2.3",
},
{
name: "scope",
target: `@babel/code-frame@^7.0.0:`,
expectName: "@babel/code-frame",
expactVersion: "^7.0.0",
},
{
name: "scope with protocol",
target: `@babel/code-frame@npm:^7.0.0:`,
expectName: "@babel/code-frame",
expectProtocol: "npm",
expactVersion: "^7.0.0",
},
{
name: "scope with protocol and quotes",
target: `"@babel/code-frame@npm:^7.0.0":`,
expectName: "@babel/code-frame",
expectProtocol: "npm",
expactVersion: "^7.0.0",
},
{
name: "unusual version",
target: `[email protected].*:`,
expectName: "grunt-contrib-cssmin",
expactVersion: "3.0.*",
},
{
name: "conditional version",
target: `"js-tokens@^3.0.0 || ^4.0.0":`,
expectName: "js-tokens",
expactVersion: "^3.0.0 || ^4.0.0",
},
{
target: "grunt-contrib-uglify-es@gruntjs/grunt-contrib-uglify#harmony:",
expectName: "grunt-contrib-uglify-es",
expactVersion: "gruntjs/grunt-contrib-uglify#harmony",
},
{
target: `"jquery@git+https://xxxx:[email protected]/tomoyamachi/jquery":`,
expectName: "jquery",
expectProtocol: "git+https",
expactVersion: "//xxxx:[email protected]/tomoyamachi/jquery",
},
{
target: `normal line`,
occurErr: true,
},
}
for _, v := range vectors {
gotName, gotProtocol, gotVersion, err := parsePattern(v.target)
if v.occurErr != (err != nil) {
t.Errorf("expect error %t but err is %s", v.occurErr, err)
continue
}
if gotName != v.expectName {
t.Errorf("name mismatch: got %s, want %s, target :%s", gotName, v.expectName, v.target)
}
if gotProtocol != v.expectProtocol {
t.Errorf("protocol mismatch: got %s, want %s, target :%s", gotProtocol, v.expectProtocol, v.target)
}
if gotVersion != v.expactVersion {
t.Errorf("version mismatch: got %s, want %s, target :%s", gotVersion, v.expactVersion, v.target)
}
}
}
func TestParsePackagePatterns(t *testing.T) {
vectors := []struct {
name string
target string
expectName string
expectProtocol string
expactPatterns []string
occurErr bool
}{
{
name: "normal",
target: `asn1@~0.2.3:`,
expectName: "asn1",
expactPatterns: []string{
"asn1@~0.2.3",
},
},
{
name: "normal with quotes",
target: `"asn1@~0.2.3":`,
expectName: "asn1",
expactPatterns: []string{
"asn1@~0.2.3",
},
},
{
name: "normal with protocol",
target: `asn1@npm:~0.2.3:`,
expectName: "asn1",
expectProtocol: "npm",
expactPatterns: []string{
"asn1@~0.2.3",
},
},
{
name: "multiple patterns",
target: `loose-envify@^1.1.0, loose-envify@^1.4.0:`,
expectName: "loose-envify",
expactPatterns: []string{
"loose-envify@^1.1.0",
"loose-envify@^1.4.0",
},
},
{
name: "multiple patterns v2",
target: `"loose-envify@npm:^1.1.0, loose-envify@npm:^1.4.0":`,
expectName: "loose-envify",
expectProtocol: "npm",
expactPatterns: []string{
"loose-envify@^1.1.0",
"loose-envify@^1.4.0",
},
},
{
target: `normal line`,
occurErr: true,
},
}
for _, v := range vectors {
gotName, gotProtocol, gotPatterns, err := parsePackagePatterns(v.target)
if v.occurErr != (err != nil) {
t.Errorf("expect error %t but err is %s", v.occurErr, err)
continue
}
if gotName != v.expectName {
t.Errorf("name mismatch: got %s, want %s, target: %s", gotName, v.expectName, v.target)
}
if gotProtocol != v.expectProtocol {
t.Errorf("protocol mismatch: got %s, want %s, target: %s", gotProtocol, v.expectProtocol, v.target)
}
sort.Strings(gotPatterns)
sort.Strings(v.expactPatterns)
assert.Equal(t, v.expactPatterns, gotPatterns)
}
}
func TestGetDependency(t *testing.T) {
vectors := []struct {
name string
target string
expectName string
expactVersion string
occurErr bool
}{
{
name: "normal",
target: ` chalk "^2.0.1"`,
expectName: "chalk",
expactVersion: "^2.0.1",
},
{
name: "range",
target: ` js-tokens "^3.0.0 || ^4.0.0"`,
expectName: "js-tokens",
expactVersion: "^3.0.0 || ^4.0.0",
},
{
name: "normal v2",
target: ` depd: ~1.1.2`,
expectName: "depd",
expactVersion: "~1.1.2",
},
{
name: "range version v2",
target: ` statuses: ">= 1.5.0 < 2"`,
expectName: "statuses",
expactVersion: ">= 1.5.0 < 2",
},
{
name: "name with scope",
target: ` "@types/color-name": ^1.1.1`,
expectName: "@types/color-name",
expactVersion: "^1.1.1",
},
}
for _, v := range vectors {
gotName, gotVersion, err := getDependency(v.target)
if v.occurErr != (err != nil) {
t.Errorf("expect error %t but err is %s", v.occurErr, err)
continue
}
if gotName != v.expectName {
t.Errorf("name mismatch: got %s, want %s, target: %s", gotName, v.expectName, v.target)
}
if gotVersion != v.expactVersion {
t.Errorf("version mismatch: got %s, want %s, target: %s", gotVersion, v.expactVersion, v.target)
}
}
}
func TestParse(t *testing.T) {
tests := []struct {
name string
file string // Test input file
want []types.Library
wantDeps []types.Dependency
}{
{
name: "normal",
file: "testdata/yarn_normal.lock",
want: yarnNormal,
wantDeps: yarnNormalDeps,
},
{
name: "react",
file: "testdata/yarn_react.lock",
want: yarnReact,
wantDeps: yarnReactDeps,
},
{
name: "yarn with dev",
file: "testdata/yarn_with_dev.lock",
want: yarnWithDev,
wantDeps: yarnWithDevDeps,
},
{
name: "yarn many",
file: "testdata/yarn_many.lock",
want: yarnMany,
wantDeps: yarnManyDeps,
},
{
name: "yarn real world",
file: "testdata/yarn_realworld.lock",
want: yarnRealWorld,
wantDeps: yarnRealWorldDeps,
},
{
file: "testdata/yarn_with_npm.lock",
want: yarnWithNpm,
},
{
name: "yarn v2 normal",
file: "testdata/yarn_v2_normal.lock",
want: yarnV2Normal,
wantDeps: yarnV2NormalDeps,
},
{
name: "yarn v2 react",
file: "testdata/yarn_v2_react.lock",
want: yarnV2React,
wantDeps: yarnV2ReactDeps,
},
{
name: "yarn v2 with dev",
file: "testdata/yarn_v2_with_dev.lock",
want: yarnV2WithDev,
wantDeps: yarnV2WithDevDeps,
},
{
name: "yarn v2 many",
file: "testdata/yarn_v2_many.lock",
want: yarnV2Many,
wantDeps: yarnV2ManyDeps,
},
{
name: "yarn with local dependency",
file: "testdata/yarn_with_local.lock",
want: yarnNormal,
wantDeps: yarnNormalDeps,
},
{
name: "yarn with git dependency",
file: "testdata/yarn_with_git.lock",
},
{
name: "yarn file with bad protocol",
file: "testdata/yarn_with_bad_protocol.lock",
want: yarnBadProtocol,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f, err := os.Open(tt.file)
require.NoError(t, err)
got, deps, err := NewParser().Parse(f)
require.NoError(t, err)
sortLibs(got)
sortLibs(tt.want)
assert.Equal(t, tt.want, got)
if tt.wantDeps != nil {
sortDeps(deps)
sortDeps(tt.wantDeps)
assert.Equal(t, tt.wantDeps, deps)
}
})
}
}
func sortDeps(deps []types.Dependency) {
sort.Slice(deps, func(i, j int) bool {
return strings.Compare(deps[i].ID, deps[j].ID) < 0
})
for i := range deps {
sort.Strings(deps[i].DependsOn)
}
}
func sortLibs(libs []types.Library) {
sort.Slice(libs, func(i, j int) bool {
ret := strings.Compare(libs[i].Name, libs[j].Name)
if ret == 0 {
return libs[i].Version < libs[j].Version
}
return ret < 0
})
for _, lib := range libs {
sortLocations(lib.Locations)
}
}
func sortLocations(locs []types.Location) {
sort.Slice(locs, func(i, j int) bool {
return locs[i].StartLine < locs[j].StartLine
})
}
<file_sep>/pkg/python/poetry/parse_test.go
package poetry
import (
"fmt"
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
func TestParser_Parse(t *testing.T) {
tests := []struct {
name string
file string
wantLibs []types.Library
wantDeps []types.Dependency
wantErr assert.ErrorAssertionFunc
}{
{
name: "normal",
file: "testdata/poetry_normal.lock",
wantLibs: poetryNormal,
wantErr: assert.NoError,
},
{
name: "many",
file: "testdata/poetry_many.lock",
wantLibs: poetryMany,
wantDeps: poetryManyDeps,
wantErr: assert.NoError,
},
{
name: "flask",
file: "testdata/poetry_flask.lock",
wantLibs: poetryFlask,
wantDeps: poetryFlaskDeps,
wantErr: assert.NoError,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f, err := os.Open(tt.file)
require.NoError(t, err)
defer f.Close()
p := &Parser{}
gotLibs, gotDeps, err := p.Parse(f)
if !tt.wantErr(t, err, fmt.Sprintf("Parse(%v)", tt.file)) {
return
}
assert.Equalf(t, tt.wantLibs, gotLibs, "Parse(%v)", tt.file)
assert.Equalf(t, tt.wantDeps, gotDeps, "Parse(%v)", tt.file)
})
}
}
func TestParseDependency(t *testing.T) {
tests := []struct {
name string
packageName string
versionRange interface{}
libsVersions map[string][]string
want string
wantErr string
}{
{
name: "handle package name",
packageName: "Test_project.Name",
versionRange: "*",
libsVersions: map[string][]string{
"test-project-name": {"1.0.0"},
},
want: "[email protected]",
},
{
name: "version range as string",
packageName: "test",
versionRange: ">=1.0.0",
libsVersions: map[string][]string{
"test": {"2.0.0"},
},
want: "[email protected]",
},
{
name: "version range == *",
packageName: "test",
versionRange: "*",
libsVersions: map[string][]string{
"test": {"3.0.0"},
},
want: "[email protected]",
},
{
name: "version range as json",
packageName: "test",
versionRange: map[string]interface{}{
"version": ">=4.8.3",
"markers": "python_version < \"3.8\"",
},
libsVersions: map[string][]string{
"test": {"5.0.0"},
},
want: "[email protected]",
},
{
name: "libsVersions doesn't contain required version",
packageName: "test",
versionRange: ">=1.0.0",
libsVersions: map[string][]string{},
wantErr: "no version found",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := parseDependency(tt.packageName, tt.versionRange, tt.libsVersions)
if tt.wantErr != "" {
assert.ErrorContains(t, err, tt.wantErr)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.want, got)
})
}
}
<file_sep>/pkg/dart/pub/parse.go
package pub
import (
"fmt"
"golang.org/x/xerrors"
"gopkg.in/yaml.v3"
dio "github.com/aquasecurity/go-dep-parser/pkg/io"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
const (
idFormat = "%s@%s"
transitiveDep = "transitive"
)
// Parser is a parser for pubspec.lock
type Parser struct{}
func NewParser() types.Parser {
return &Parser{}
}
type lock struct {
Packages map[string]Dep `yaml:"packages"`
}
type Dep struct {
Dependency string `yaml:"dependency"`
Version string `yaml:"version"`
}
func (Parser) Parse(r dio.ReadSeekerAt) ([]types.Library, []types.Dependency, error) {
l := &lock{}
if err := yaml.NewDecoder(r).Decode(&l); err != nil {
return nil, nil, xerrors.Errorf("failed to decode pubspec.lock: %w", err)
}
var libs []types.Library
for name, dep := range l.Packages {
// We would like to exclude dev dependencies, but we cannot identify
// which indirect dependencies were introduced by dev dependencies
// as there are 3 dependency types, "direct main", "direct dev" and "transitive".
// It will be confusing if we exclude direct dev dependencies and include transitive dev dependencies.
// We decided to keep all dev dependencies until Pub will add support for "transitive main" and "transitive dev".
lib := types.Library{
ID: pkgID(name, dep.Version),
Name: name,
Version: dep.Version,
Indirect: dep.Dependency == transitiveDep,
}
libs = append(libs, lib)
}
return libs, nil, nil
}
func pkgID(name, version string) string {
return fmt.Sprintf(idFormat, name, version)
}
<file_sep>/pkg/frameworks/wordpress/parse.go
package wordpress
import (
"bufio"
"io"
"strings"
"golang.org/x/xerrors"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
func Parse(r io.Reader) (lib types.Library, err error) {
// If wordpress file, open file and
// find line with content
// $wp_version = '<WORDPRESS_VERSION>';
var version string
isComment := false
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := scanner.Text()
// Remove comment
commentIndex := strings.Index(line, "//")
if commentIndex != -1 {
line = line[:commentIndex]
}
line = strings.TrimSpace(line)
// Handle comment
switch {
case strings.HasPrefix(line, "/*"):
isComment = true
continue
case isComment && strings.HasSuffix(line, "*/"):
isComment = false
continue
case isComment:
continue
}
// It might include $wp_version_something
if !strings.HasPrefix(line, "$wp_version") {
continue
}
ss := strings.Split(line, "=")
if len(ss) != 2 || strings.TrimSpace(ss[0]) != "$wp_version" {
continue
}
// Each variable must end with ";".
end := strings.Index(ss[1], ";")
if end == -1 {
continue
}
// Remove ";" and white space.
version = strings.TrimSpace(ss[1][:end])
// Remove single and double quotes.
version = strings.Trim(version, `'"`)
break
}
if err = scanner.Err(); err != nil || version == "" {
return types.Library{}, xerrors.New("version.php could not be parsed")
}
return types.Library{
Name: "wordpress",
Version: version,
}, nil
}
<file_sep>/pkg/nodejs/pnpm/parse_testcase.go
package pnpm
import "github.com/aquasecurity/go-dep-parser/pkg/types"
var (
// docker run --name node --rm -it node:16-alpine sh
// npm install -g pnpm
// pnpm add promise jquery
// pnpm list --prod --depth 10 | grep -E -o "\S+\s+[0-9]+(\.[0-9]+)+$" | awk '{printf("{ID: \""$1"@"$2"\", Name: \""$1"\", Version: \""$2"\", Indirect: true},\n")}' | sort -u
pnpmNormal = []types.Library{
{ID: "[email protected]", Name: "asap", Version: "2.0.6", Indirect: true},
{ID: "[email protected]", Name: "jquery", Version: "3.6.0", Indirect: false},
{ID: "[email protected]", Name: "promise", Version: "8.1.0", Indirect: false},
}
pnpmNormalDeps = []types.Dependency{
{
ID: "[email protected]",
DependsOn: []string{"[email protected]"},
},
}
// docker run --name node --rm -it node:16-alpine sh
// npm install -g pnpm
// pnpm add react redux
// pnpm add -D mocha
// pnpm list --prod --depth 10 | grep -E -o "\S+\s+[0-9]+(\.[0-9]+)+$" | awk '{printf("{ID: \""$1"@"$2"\", Name: \""$1"\", Version: \""$2"\", Indirect: true},\n")}' | sort -u
pnpmWithDev = []types.Library{
{ID: "@babel/[email protected]", Name: "@babel/runtime", Version: "7.18.3", Indirect: true},
{ID: "[email protected]", Name: "js-tokens", Version: "4.0.0", Indirect: true},
{ID: "[email protected]", Name: "loose-envify", Version: "1.4.0", Indirect: true},
{ID: "[email protected]", Name: "react", Version: "18.1.0", Indirect: false},
{ID: "[email protected]", Name: "redux", Version: "4.2.0", Indirect: false},
{ID: "[email protected]", Name: "regenerator-runtime", Version: "0.13.9", Indirect: true},
}
pnpmWithDevDeps = []types.Dependency{
{
ID: "@babel/[email protected]",
DependsOn: []string{"[email protected]"},
},
{
ID: "[email protected]",
DependsOn: []string{"[email protected]"},
},
{
ID: "[email protected]",
DependsOn: []string{"[email protected]"},
},
{
ID: "[email protected]",
DependsOn: []string{"@babel/[email protected]"},
},
}
// docker run --name node --rm -it node:16-alpine sh
// npm install -g pnpm
// pnpm add react redux lodash request chalk commander
// pnpm add -D mocha
// pnpm list --prod --depth 10 | grep -E -o "\S+\s+[0-9]+(\.[0-9]+)+$" | awk '{printf("{ID: \""$1"@"$2"\", Name: \""$1"\", Version: \""$2"\", Indirect: true},\n")}' | sort -u
pnpmMany = []types.Library{
{ID: "@babel/[email protected]", Name: "@babel/runtime", Version: "7.18.3", Indirect: true},
{ID: "[email protected]", Name: "ajv", Version: "6.12.6", Indirect: true},
{ID: "[email protected]", Name: "asn1", Version: "0.2.6", Indirect: true},
{ID: "[email protected]", Name: "assert-plus", Version: "1.0.0", Indirect: true},
{ID: "[email protected]", Name: "asynckit", Version: "0.4.0", Indirect: true},
{ID: "[email protected]", Name: "aws-sign2", Version: "0.7.0", Indirect: true},
{ID: "[email protected]", Name: "aws4", Version: "1.11.0", Indirect: true},
{ID: "[email protected]", Name: "bcrypt-pbkdf", Version: "1.0.2", Indirect: true},
{ID: "[email protected]", Name: "caseless", Version: "0.12.0", Indirect: true},
{ID: "[email protected]", Name: "chalk", Version: "5.0.1", Indirect: false},
{ID: "[email protected]", Name: "combined-stream", Version: "1.0.8", Indirect: true},
{ID: "[email protected]", Name: "commander", Version: "9.3.0", Indirect: false},
{ID: "[email protected]", Name: "core-util-is", Version: "1.0.2", Indirect: true},
{ID: "[email protected]", Name: "dashdash", Version: "1.14.1", Indirect: true},
{ID: "[email protected]", Name: "delayed-stream", Version: "1.0.0", Indirect: true},
{ID: "[email protected]", Name: "ecc-jsbn", Version: "0.1.2", Indirect: true},
{ID: "[email protected]", Name: "extend", Version: "3.0.2", Indirect: true},
{ID: "[email protected]", Name: "extsprintf", Version: "1.3.0", Indirect: true},
{ID: "[email protected]", Name: "fast-deep-equal", Version: "3.1.3", Indirect: true},
{ID: "[email protected]", Name: "fast-json-stable-stringify", Version: "2.1.0", Indirect: true},
{ID: "[email protected]", Name: "forever-agent", Version: "0.6.1", Indirect: true},
{ID: "[email protected]", Name: "form-data", Version: "2.3.3", Indirect: true},
{ID: "[email protected]", Name: "getpass", Version: "0.1.7", Indirect: true},
{ID: "[email protected]", Name: "har-schema", Version: "2.0.0", Indirect: true},
{ID: "[email protected]", Name: "har-validator", Version: "5.1.5", Indirect: true},
{ID: "[email protected]", Name: "http-signature", Version: "1.2.0", Indirect: true},
{ID: "[email protected]", Name: "is-typedarray", Version: "1.0.0", Indirect: true},
{ID: "[email protected]", Name: "isstream", Version: "0.1.2", Indirect: true},
{ID: "[email protected]", Name: "js-tokens", Version: "4.0.0", Indirect: true},
{ID: "[email protected]", Name: "jsbn", Version: "0.1.1", Indirect: true},
{ID: "[email protected]", Name: "json-schema-traverse", Version: "0.4.1", Indirect: true},
{ID: "[email protected]", Name: "json-schema", Version: "0.4.0", Indirect: true},
{ID: "[email protected]", Name: "json-stringify-safe", Version: "5.0.1", Indirect: true},
{ID: "[email protected]", Name: "jsprim", Version: "1.4.2", Indirect: true},
{ID: "[email protected]", Name: "lodash", Version: "4.17.21", Indirect: false},
{ID: "[email protected]", Name: "loose-envify", Version: "1.4.0", Indirect: true},
{ID: "[email protected]", Name: "mime-db", Version: "1.52.0", Indirect: true},
{ID: "[email protected]", Name: "mime-types", Version: "2.1.35", Indirect: true},
{ID: "[email protected]", Name: "oauth-sign", Version: "0.9.0", Indirect: true},
{ID: "[email protected]", Name: "performance-now", Version: "2.1.0", Indirect: true},
{ID: "[email protected]", Name: "psl", Version: "1.8.0", Indirect: true},
{ID: "[email protected]", Name: "punycode", Version: "2.1.1", Indirect: true},
{ID: "[email protected]", Name: "qs", Version: "6.5.3", Indirect: true},
{ID: "[email protected]", Name: "react", Version: "18.1.0", Indirect: false},
{ID: "[email protected]", Name: "redux", Version: "4.2.0", Indirect: false},
{ID: "[email protected]", Name: "regenerator-runtime", Version: "0.13.9", Indirect: true},
{ID: "[email protected]", Name: "request", Version: "2.88.2", Indirect: false},
{ID: "[email protected]", Name: "safe-buffer", Version: "5.2.1", Indirect: true},
{ID: "[email protected]", Name: "safer-buffer", Version: "2.1.2", Indirect: true},
{ID: "[email protected]", Name: "sshpk", Version: "1.17.0", Indirect: true},
{ID: "[email protected]", Name: "tough-cookie", Version: "2.5.0", Indirect: true},
{ID: "[email protected]", Name: "tunnel-agent", Version: "0.6.0", Indirect: true},
{ID: "[email protected]", Name: "tweetnacl", Version: "0.14.5", Indirect: true},
{ID: "[email protected]", Name: "uri-js", Version: "4.4.1", Indirect: true},
{ID: "[email protected]", Name: "uuid", Version: "3.4.0", Indirect: true},
{ID: "[email protected]", Name: "verror", Version: "1.10.0", Indirect: true},
}
pnpmManyDeps = []types.Dependency{
{ID: "@babel/[email protected]", DependsOn: []string{"[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]", "[email protected]", "[email protected]", "[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]", "[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]", "[email protected]", "[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]", "[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]", "[email protected]", "[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]", "[email protected]", "[email protected]", "[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"@babel/[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]", "[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]"}},
{ID: "[email protected]", DependsOn: []string{"[email protected]", "[email protected]", "[email protected]"}},
}
// docker run --name node --rm -it node@sha256:710a2c192ca426e03e4f3ec1869e5c29db855eb6969b74e6c50fd270ffccd3f1 sh
// npm install -g [email protected]
// mkdir /temp && cd /temp
// npm install [email protected]
// cd ./node_modules/lodash/
// npm pack
// mkdir -p /app/foo/bar && cd /app
// cp /temp/node_modules/lodash/lodash-4.17.21.tgz /app/foo/bar/lodash.tgz
// npm install ./foo/bar/lodash.tgz
// pnpm update
// pnpm add https://github.com/debug-js/debug/tarball/4.3.4
// pnpm add https://codeload.github.com/zkochan/is-negative/tar.gz/2fa0531ab04e300a24ef4fd7fb3a280eccb7ccc5
// pnpm list --prod --depth 10 | grep -E -o "\S+\s+[0-9]+(\.[0-9]+)+$" | awk '{printf("{ID: \""$1"@"$2"\", Name: \""$1"\", Version: \""$2"\", Indirect: false},\n")}' | sort -u
pnpmArchives = []types.Library{
{ID: "[email protected]", Name: "debug", Version: "4.3.4", Indirect: false},
{ID: "[email protected]", Name: "is-negative", Version: "2.0.1", Indirect: false},
{ID: "[email protected]", Name: "lodash", Version: "4.17.21", Indirect: false},
{ID: "[email protected]", Name: "ms", Version: "2.1.2", Indirect: true},
}
pnpmArchivesDeps = []types.Dependency{
{
ID: "[email protected]",
DependsOn: []string{"[email protected]"},
},
}
// docker run --name node --rm -it node@sha256:710a2c192ca426e03e4f3ec1869e5c29db855eb6969b74e6c50fd270ffccd3f1 sh
// npm install -g [email protected]
// pnpm add [email protected] [email protected]
// pnpm list --prod --depth 10 | grep -E -o "\S+\s+[0-9]+(\.[0-9]+)+$" | awk '{printf("{ID: \""$1"@"$2"\", Name: \""$1"\", Version: \""$2"\", Indirect: true},\n")}' | sort -u
pnpmV6 = pnpmNormal
pnpmV6Deps = pnpmNormalDeps
// docker run --name node --rm -it node@sha256:710a2c192ca426e03e4f3ec1869e5c29db855eb6969b74e6c50fd270ffccd3f1 sh
// npm install -g [email protected]
// pnpm add [email protected] [email protected]
// pnpm add -D [email protected]
// pnpm list --prod --depth 10 | grep -E -o "\S+\s+[0-9]+(\.[0-9]+)+$" | awk '{printf("{ID: \""$1"@"$2"\", Name: \""$1"\", Version: \""$2"\", Indirect: true},\n")}' | sort -u
pnpmV6WithDev = []types.Library{
{ID: "@babel/[email protected]", Name: "@babel/runtime", Version: "7.22.3", Indirect: true},
{ID: "[email protected]", Name: "js-tokens", Version: "4.0.0", Indirect: true},
{ID: "[email protected]", Name: "loose-envify", Version: "1.4.0", Indirect: true},
{ID: "[email protected]", Name: "react", Version: "18.1.0", Indirect: false},
{ID: "[email protected]", Name: "redux", Version: "4.2.0", Indirect: false},
{ID: "[email protected]", Name: "regenerator-runtime", Version: "0.13.11", Indirect: true},
}
pnpmV6WithDevDeps = []types.Dependency{
{
ID: "@babel/[email protected]",
DependsOn: []string{"[email protected]"},
},
{
ID: "[email protected]",
DependsOn: []string{"[email protected]"},
},
{
ID: "[email protected]",
DependsOn: []string{"[email protected]"},
},
{
ID: "[email protected]",
DependsOn: []string{"@babel/[email protected]"},
},
}
)
<file_sep>/pkg/java/jar/testdata/testimage/maven/Dockerfile
FROM maven:3.6.3-jdk-11
RUN mvn archetype:generate -DgroupId=com.example -DartifactId=web-app -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false
WORKDIR /web-app
COPY pom.xml .
RUN mvn clean install && mvn package
CMD ["mvn", "dependency:tree"]
<file_sep>/pkg/java/jar/sonatype/log.go
package sonatype
import "github.com/aquasecurity/go-dep-parser/pkg/log"
// logger implements LeveledLogger
// https://github.com/hashicorp/go-retryablehttp/blob/991b9d0a42d13014e3689dd49a94c02be01f4237/client.go#L285-L290
type logger struct{}
func (logger) Error(msg string, keysAndValues ...interface{}) {
// Use Debugw to suppress errors on failure
if msg == "request failed" {
log.Logger.Debugw(msg, keysAndValues...)
return
}
log.Logger.Errorw(msg, keysAndValues)
}
func (logger) Info(msg string, keysAndValues ...interface{}) {
log.Logger.Infow(msg, keysAndValues...)
}
func (logger) Debug(msg string, keysAndValues ...interface{}) {
// This message is displayed too much
if msg == "performing request" {
return
}
log.Logger.Debugw(msg, keysAndValues...)
}
func (logger) Warn(msg string, keysAndValues ...interface{}) {
log.Logger.Warnw(msg, keysAndValues...)
}
<file_sep>/pkg/swift/cocoapods/parse.go
package cocoapods
import (
"sort"
"strings"
"golang.org/x/exp/maps"
"golang.org/x/xerrors"
"gopkg.in/yaml.v3"
dio "github.com/aquasecurity/go-dep-parser/pkg/io"
"github.com/aquasecurity/go-dep-parser/pkg/log"
"github.com/aquasecurity/go-dep-parser/pkg/types"
"github.com/aquasecurity/go-dep-parser/pkg/utils"
)
type Parser struct{}
func NewParser() types.Parser {
return &Parser{}
}
type lockFile struct {
Pods []any `yaml:"PODS"` // pod can be string or map[string]interface{}
}
func (Parser) Parse(r dio.ReadSeekerAt) ([]types.Library, []types.Dependency, error) {
lock := &lockFile{}
decoder := yaml.NewDecoder(r)
if err := decoder.Decode(&lock); err != nil {
return nil, nil, xerrors.Errorf("failed to decode cocoapods lock file: %s", err.Error())
}
parsedDeps := map[string]types.Library{} // dependency name => Library
directDeps := map[string][]string{} // dependency name => slice of child dependency names
for _, pod := range lock.Pods {
switch p := pod.(type) {
case string: // dependency with version number
lib, err := parseDep(p)
if err != nil {
log.Logger.Debug(err)
continue
}
parsedDeps[lib.Name] = lib
case map[string]interface{}: // dependency with its child dependencies
for dep, childDeps := range p {
lib, err := parseDep(dep)
if err != nil {
log.Logger.Debug(err)
continue
}
parsedDeps[lib.Name] = lib
children, ok := childDeps.([]interface{})
if !ok {
return nil, nil, xerrors.Errorf("invalid value of cocoapods direct dependency: %q", childDeps)
}
for _, childDep := range children {
s, ok := childDep.(string)
if !ok {
return nil, nil, xerrors.Errorf("must be string: %q", childDep)
}
directDeps[lib.Name] = append(directDeps[lib.Name], strings.Fields(s)[0])
}
}
}
}
var deps []types.Dependency
for dep, childDeps := range directDeps {
var dependsOn []string
// find versions for child dependencies
for _, childDep := range childDeps {
dependsOn = append(dependsOn, utils.PackageID(childDep, parsedDeps[childDep].Version))
}
deps = append(deps, types.Dependency{
ID: parsedDeps[dep].ID,
DependsOn: dependsOn,
})
}
sort.Sort(types.Dependencies(deps))
return utils.UniqueLibraries(maps.Values(parsedDeps)), deps, nil
}
func parseDep(dep string) (types.Library, error) {
// dep example:
// 'AppCenter (4.2.0)'
// direct dep examples:
// 'AppCenter/Core'
// 'AppCenter/Analytics (= 4.2.0)'
// 'AppCenter/Analytics (-> 4.2.0)'
ss := strings.Split(dep, " (")
if len(ss) != 2 {
return types.Library{}, xerrors.Errorf("Unable to determine cocoapods dependency: %q", dep)
}
name := ss[0]
version := strings.Trim(strings.TrimSpace(ss[1]), "()")
lib := types.Library{
ID: utils.PackageID(name, version),
Name: name,
Version: version,
}
return lib, nil
}
<file_sep>/pkg/nodejs/yarn/testcase_deps_generator/Dockerfile
FROM node:14-alpine
COPY index.js /test_deps_generator/index.js
COPY yarn.lock /test_deps_generator/yarn.lock
COPY package.json /test_deps_generator/package.json<file_sep>/pkg/hex/mix/parse.go
package mix
import (
"bufio"
"fmt"
"strings"
"unicode"
dio "github.com/aquasecurity/go-dep-parser/pkg/io"
"github.com/aquasecurity/go-dep-parser/pkg/log"
"github.com/aquasecurity/go-dep-parser/pkg/types"
"github.com/aquasecurity/go-dep-parser/pkg/utils"
)
// Parser is a parser for mix.lock
type Parser struct{}
func NewParser() types.Parser {
return &Parser{}
}
func (Parser) Parse(r dio.ReadSeekerAt) ([]types.Library, []types.Dependency, error) {
var libs []types.Library
scanner := bufio.NewScanner(r)
var lineNumber int // It is used to save dependency location
for scanner.Scan() {
lineNumber++
line := strings.TrimSpace(scanner.Text())
name, body, ok := strings.Cut(line, ":")
if !ok {
// skip 1st and last lines
continue
}
name = strings.Trim(name, `"`)
// dependency format:
// "<depName>": {<:hex|:git>, :<depName>, "<depVersion>", "<checksum>", [:mix], [<required deps>], hexpm", "<checksum>"},
ss := strings.FieldsFunc(body, func(r rune) bool {
return unicode.IsSpace(r) || r == ','
})
if len(ss) < 8 { // In the case where <required deps> array is empty: s == 8, in other cases s > 8
// git repository doesn't have dependency version
// skip these dependencies
if !strings.Contains(ss[0], ":git") {
log.Logger.Warnf("Cannot parse dependency: %s", line)
} else {
log.Logger.Debugf("Skip git dependencies: %s", name)
}
continue
}
version := strings.Trim(ss[2], `"`)
libs = append(libs, types.Library{
ID: fmt.Sprintf("%s@%s", name, version),
Name: name,
Version: version,
Locations: []types.Location{{StartLine: lineNumber, EndLine: lineNumber}},
})
}
return utils.UniqueLibraries(libs), nil, nil
}
<file_sep>/pkg/golang/mod/parse.go
package mod
import (
"fmt"
"io"
"regexp"
"strconv"
"strings"
"golang.org/x/exp/maps"
"golang.org/x/mod/modfile"
"golang.org/x/xerrors"
dio "github.com/aquasecurity/go-dep-parser/pkg/io"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
var (
// By convention, modules with a major version equal to or above v2
// have it as suffix in their module path.
VCSUrlMajorVersionSuffixRegex = regexp.MustCompile(`(/v[\d]+)$`)
// gopkg.in/user/pkg.v -> github.com/user/pkg
VCSUrlGoPkgInRegexWithUser = regexp.MustCompile(`^gopkg\.in/([^/]+)/([^.]+)\..*$`)
// gopkg.in without user segment
// Example: gopkg.in/pkg.v3 -> github.com/go-pkg/pkg
VCSUrlGoPkgInRegexWithoutUser = regexp.MustCompile(`^gopkg\.in/([^.]+)\..*$`)
)
type Parser struct {
replace bool // 'replace' represents if the 'replace' directive should be taken into account.
}
func NewParser(replace bool) types.Parser {
return &Parser{
replace: replace,
}
}
func (p *Parser) GetExternalRefs(path string) []types.ExternalRef {
if url := resolveVCSUrl(path); url != "" {
return []types.ExternalRef{
{
Type: types.RefVCS,
URL: url,
},
}
}
return nil
}
func resolveVCSUrl(modulePath string) string {
switch {
case strings.HasPrefix(modulePath, "github.com/"):
return "https://" + VCSUrlMajorVersionSuffixRegex.ReplaceAllString(modulePath, "")
case VCSUrlGoPkgInRegexWithUser.MatchString(modulePath):
return "https://" + VCSUrlGoPkgInRegexWithUser.ReplaceAllString(modulePath, "github.com/$1/$2")
case VCSUrlGoPkgInRegexWithoutUser.MatchString(modulePath):
return "https://" + VCSUrlGoPkgInRegexWithoutUser.ReplaceAllString(modulePath, "github.com/go-$1/$1")
}
return ""
}
// Parse parses a go.mod file
func (p *Parser) Parse(r dio.ReadSeekerAt) ([]types.Library, []types.Dependency, error) {
libs := map[string]types.Library{}
goModData, err := io.ReadAll(r)
if err != nil {
return nil, nil, xerrors.Errorf("file read error: %w", err)
}
modFileParsed, err := modfile.Parse("go.mod", goModData, nil)
if err != nil {
return nil, nil, xerrors.Errorf("go.mod parse error: %w", err)
}
skipIndirect := true
if modFileParsed.Go != nil { // Old go.mod file may not include the go version. Go version for these files is less than 1.17
skipIndirect = lessThan117(modFileParsed.Go.Version)
}
for _, require := range modFileParsed.Require {
// Skip indirect dependencies less than Go 1.17
if skipIndirect && require.Indirect {
continue
}
libs[require.Mod.Path] = types.Library{
ID: ModuleID(require.Mod.Path, require.Mod.Version[1:]),
Name: require.Mod.Path,
Version: require.Mod.Version[1:],
Indirect: require.Indirect,
ExternalReferences: p.GetExternalRefs(require.Mod.Path),
}
}
// No need to evaluate the 'replace' directive for indirect dependencies
if p.replace {
for _, rep := range modFileParsed.Replace {
// Check if replaced path is actually in our libs.
old, ok := libs[rep.Old.Path]
if !ok {
continue
}
// If the replace directive has a version on the left side, make sure it matches the version that was imported.
if rep.Old.Version != "" && old.Version != rep.Old.Version[1:] {
continue
}
// Only support replace directive with version on the right side.
// Directive without version is a local path.
if rep.New.Version == "" {
// Delete old lib, since it's a local path now.
delete(libs, rep.Old.Path)
continue
}
// Delete old lib, in case the path has changed.
delete(libs, rep.Old.Path)
// Add replaced library to library register.
libs[rep.New.Path] = types.Library{
ID: ModuleID(rep.New.Path, rep.New.Version[1:]),
Name: rep.New.Path,
Version: rep.New.Version[1:],
Indirect: old.Indirect,
ExternalReferences: p.GetExternalRefs(rep.New.Path),
}
}
}
return maps.Values(libs), nil, nil
}
// Check if the Go version is less than 1.17
func lessThan117(ver string) bool {
ss := strings.Split(ver, ".")
if len(ss) != 2 {
return false
}
major, err := strconv.Atoi(ss[0])
if err != nil {
return false
}
minor, err := strconv.Atoi(ss[1])
if err != nil {
return false
}
return major <= 1 && minor < 17
}
// ModuleID returns a module ID according the Go way.
// Format: <module_name>@v<module_version>
// e.g. github.com/aquasecurity/[email protected]
func ModuleID(name, version string) string {
return fmt.Sprintf("%s@v%s", name, version)
}
<file_sep>/pkg/java/pom/cache.go
package pom
import "fmt"
type pomCache map[string]*analysisResult
func newPOMCache() pomCache {
return pomCache{}
}
func (c pomCache) put(art artifact, result analysisResult) {
c[c.key(art)] = &result
}
func (c pomCache) get(art artifact) *analysisResult {
return c[c.key(art)]
}
func (c pomCache) key(art artifact) string {
return fmt.Sprintf("%s:%s", art.Name(), art.Version)
}
<file_sep>/pkg/java/pom/testdata/inherit-props/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>parent</artifactId>
<version>1.0.0</version>
<packaging>pom</packaging>
<name>parent</name>
<description>Parent</description>
<properties>
<bom.version>1.0.0</bom.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.example</groupId>
<artifactId>example-bom</artifactId>
<version>${bom.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>
<file_sep>/pkg/nuget/config/parse_test.go
package config_test
import (
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/aquasecurity/go-dep-parser/pkg/nuget/config"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
func TestParse(t *testing.T) {
tests := []struct {
name string // Test input file
inputFile string
want []types.Library
wantErr string
}{
{
name: "Config",
inputFile: "testdata/packages.config",
want: []types.Library{
{Name: "Newtonsoft.Json", Version: "6.0.4"},
{Name: "Microsoft.AspNet.WebApi", Version: "5.2.2"},
},
},
{
name: "with development dependency",
inputFile: "testdata/dev_dependency.config",
want: []types.Library{
{Name: "Newtonsoft.Json", Version: "8.0.3"},
},
},
{
name: "sad path",
inputFile: "testdata/malformed_xml.config",
wantErr: "failed to decode .config file: XML syntax error on line 5: unexpected EOF",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f, err := os.Open(tt.inputFile)
require.NoError(t, err)
got, _, err := config.NewParser().Parse(f)
if tt.wantErr != "" {
require.NotNil(t, err)
assert.Contains(t, err.Error(), tt.wantErr)
return
}
assert.NoError(t, err)
assert.ElementsMatch(t, tt.want, got)
})
}
}
<file_sep>/pkg/swift/swift/parse_test.go
package swift
import (
"github.com/aquasecurity/go-dep-parser/pkg/types"
"github.com/stretchr/testify/assert"
"os"
"testing"
)
func TestParser_Parse(t *testing.T) {
tests := []struct {
name string
inputFile string
want []types.Library
}{
// docker run -it --rm swift@sha256:3c62ac97506ecf19ca15e4db57d7930e6a71559b23b19aa57e13d380133a54db
// mkdir app && cd app
// swift package init
// ## add new deps: ##
// sed -i 's/"1.0.0")/"1.0.0")\n.package(url: "https:\/\/github.com\/ReactiveCocoa\/ReactiveSwift", from: "7.0.0"),\n.package(url: "https:\/\/github.com\/Quick\/Nimble", .exact("9.2.1"))/' Package.swift
// swift package update
{
name: "happy path v1",
inputFile: "testdata/happy-v1-Package.resolved",
want: []types.Library{
{
ID: "github.com/Quick/[email protected]",
Name: "github.com/Quick/Nimble",
Version: "9.2.1",
Locations: []types.Location{{StartLine: 4, EndLine: 12}},
},
{
ID: "github.com/ReactiveCocoa/[email protected]",
Name: "github.com/ReactiveCocoa/ReactiveSwift",
Version: "7.1.1",
Locations: []types.Location{{StartLine: 13, EndLine: 21}},
},
},
},
// docker run -it --rm swift@sha256:45e5e44ed4873063795f150182437f4dbe7d5527ba5655979d7d11e0829179a7
// mkdir app && cd app
// swift package init
// ## add new deps: ##
// sed -i 's/],/],\ndependencies: [\n.package(url: "https:\/\/github.com\/ReactiveCocoa\/ReactiveSwift", from: "7.0.0"),\n.package(url: "https:\/\/github.com\/Quick\/Quick.git", from: "7.0.0"),\n.package(url: "https:\/\/github.com\/Quick\/Nimble.git", .exact("9.2.1")),\n],/' Package.swift
// swift package update
{
name: "happy path v2",
inputFile: "testdata/happy-v2-Package.resolved",
want: []types.Library{
{
ID: "github.com/Quick/[email protected]",
Name: "github.com/Quick/Nimble",
Version: "9.2.1",
Locations: []types.Location{{StartLine: 21, EndLine: 29}},
},
{
ID: "github.com/Quick/[email protected]",
Name: "github.com/Quick/Quick",
Version: "7.2.0",
Locations: []types.Location{{StartLine: 30, EndLine: 38}},
},
{
ID: "github.com/ReactiveCocoa/[email protected]",
Name: "github.com/ReactiveCocoa/ReactiveSwift",
Version: "7.1.1",
Locations: []types.Location{{StartLine: 39, EndLine: 47}},
},
{
ID: "github.com/mattgallagher/[email protected]",
Name: "github.com/mattgallagher/CwlCatchException",
Version: "2.1.2",
Locations: []types.Location{{StartLine: 3, EndLine: 11}},
},
{
ID: "github.com/mattgallagher/[email protected]",
Name: "github.com/mattgallagher/CwlPreconditionTesting",
Version: "2.1.2",
Locations: []types.Location{{StartLine: 12, EndLine: 20}},
},
},
},
{
name: "empty",
inputFile: "testdata/empty-Package.resolved",
want: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
parser := NewParser()
f, err := os.Open(tt.inputFile)
assert.NoError(t, err)
libs, _, err := parser.Parse(f)
assert.NoError(t, err)
assert.Equal(t, tt.want, libs)
})
}
}
<file_sep>/pkg/python/pyproject/testdata/happy.toml
[tool.poetry]
name = "example"
version = "0.1.0"
description = "My Hello World Example"
[tool.poetry.dependencies]
python = "^3.9"
flask = "^1.0"
requests = {version = "2.28.1", optional = true}
virtualenv = [
{ version = "^20.4.3,!=20.4.5,!=20.4.6" },
{ version = "<20.16.6", markers = "sys_platform == 'win32' and python_version == '3.9'" },
]
[tool.poetry.dev-dependencies]
[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
<file_sep>/pkg/php/composer/parse_test.go
package composer
import (
"github.com/aquasecurity/go-dep-parser/pkg/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"os"
"testing"
)
var (
// docker run --name composer --rm -it composer@sha256:082ed124b68e7e880721772a6bf22ad809e3bc87db8bbee9f0ec7127bb21ccad bash
// apk add jq
// composer require guzzlehttp/guzzle:6.5.8
// composer require pear/log:1.13.3 --dev
// composer show -i --no-dev -f json | jq --sort-keys -rc '.installed[] | "{ID: \"\(.name)@\(.version)\", Name: \"\(.name)\", Version: \"\(.version)\", License: \"MIT\", Locations: []types.Location{{StartLine: , EndLine: }}},"'
// locations are filled manually
composerLibs = []types.Library{
{
ID: "guzzlehttp/[email protected]",
Name: "guzzlehttp/guzzle",
Version: "6.5.8",
License: "MIT",
Locations: []types.Location{
{
StartLine: 9,
EndLine: 123,
},
},
},
{
ID: "guzzlehttp/[email protected]",
Name: "guzzlehttp/promises",
Version: "1.5.2",
License: "MIT",
Locations: []types.Location{
{
StartLine: 124,
EndLine: 207,
},
},
},
{
ID: "guzzlehttp/[email protected]",
Name: "guzzlehttp/psr7",
Version: "1.9.0",
License: "MIT",
Locations: []types.Location{
{
StartLine: 208,
EndLine: 317,
},
},
},
{
ID: "psr/[email protected]",
Name: "psr/http-message",
Version: "1.0.1",
License: "MIT",
Locations: []types.Location{
{
StartLine: 318,
EndLine: 370,
},
},
},
{
ID: "ralouphie/[email protected]",
Name: "ralouphie/getallheaders",
Version: "3.0.3",
License: "MIT",
Locations: []types.Location{
{
StartLine: 371,
EndLine: 414,
},
},
},
{
ID: "symfony/[email protected]",
Name: "symfony/polyfill-intl-idn",
Version: "v1.27.0",
License: "MIT",
Locations: []types.Location{
{
StartLine: 415,
EndLine: 501,
},
},
},
{
ID: "symfony/[email protected]",
Name: "symfony/polyfill-intl-normalizer",
Version: "v1.27.0",
License: "MIT",
Locations: []types.Location{
{
StartLine: 502,
EndLine: 585,
},
},
},
{
ID: "symfony/[email protected]",
Name: "symfony/polyfill-php72",
Version: "v1.27.0",
License: "MIT",
Locations: []types.Location{
{
StartLine: 586,
EndLine: 661,
},
},
},
}
// dependencies are filled manually
composerDeps = []types.Dependency{
{
ID: "guzzlehttp/[email protected]",
DependsOn: []string{
"guzzlehttp/[email protected]",
"guzzlehttp/[email protected]",
"symfony/[email protected]",
},
},
{
ID: "guzzlehttp/[email protected]",
DependsOn: []string{
"psr/[email protected]",
"ralouphie/[email protected]",
},
},
{
ID: "symfony/[email protected]",
DependsOn: []string{
"symfony/[email protected]",
"symfony/[email protected]",
},
},
}
)
func TestParse(t *testing.T) {
tests := []struct {
name string
file string
wantLibs []types.Library
wantDeps []types.Dependency
}{
{
name: "happy path",
file: "testdata/composer_happy.lock",
wantLibs: composerLibs,
wantDeps: composerDeps,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f, err := os.Open(tt.file)
require.NoError(t, err)
defer f.Close()
gotLibs, gotDeps, err := NewParser().Parse(f)
require.NoError(t, err)
assert.Equal(t, tt.wantLibs, gotLibs)
assert.Equal(t, tt.wantDeps, gotDeps)
})
}
}
<file_sep>/pkg/python/pipenv/parse_test.go
package pipenv
import (
"os"
"path"
"sort"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
func TestParse(t *testing.T) {
vectors := []struct {
file string // Test input file
want []types.Library
}{
{
file: "testdata/Pipfile_normal.lock",
want: pipenvNormal,
},
{
file: "testdata/Pipfile_django.lock",
want: pipenvDjango,
},
{
file: "testdata/Pipfile_many.lock",
want: pipenvMany,
},
}
for _, v := range vectors {
t.Run(path.Base(v.file), func(t *testing.T) {
f, err := os.Open(v.file)
require.NoError(t, err)
got, _, err := NewParser().Parse(f)
require.NoError(t, err)
sort.Slice(got, func(i, j int) bool {
ret := strings.Compare(got[i].Name, got[j].Name)
if ret == 0 {
return got[i].Version < got[j].Version
}
return ret < 0
})
sort.Slice(v.want, func(i, j int) bool {
ret := strings.Compare(v.want[i].Name, v.want[j].Name)
if ret == 0 {
return v.want[i].Version < v.want[j].Version
}
return ret < 0
})
assert.Equal(t, v.want, got)
})
}
}
<file_sep>/pkg/ruby/gemspec/testdata/normal01.gemspec
# -*- encoding: utf-8 -*-
# ... REDACTED ...
Gem::Specification.new do |spec|
spec.name = "async".freeze # comment
spec.version = "1.25.0"
spec.licenses = "MIT" # invalid
# ... REDACTED ...
end
<file_sep>/pkg/nuget/lock/parse_test.go
package lock
import (
"os"
"path"
"sort"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
func TestParse(t *testing.T) {
vectors := []struct {
file string // Test input file
want []types.Library
wantDeps []types.Dependency
}{
{
file: "testdata/packages_lock_simple.json",
want: nuGetSimple,
wantDeps: nuGetSimpleDeps,
},
{
file: "testdata/packages_lock_subdependencies.json",
want: nuGetSubDependencies,
wantDeps: nuGetSubDependenciesDeps,
},
{
file: "testdata/packages_lock_multi.json",
want: nuGetMultiTarget,
wantDeps: nuGetMultiTargetDeps,
},
{
file: "testdata/packages_lock_legacy.json",
want: nuGetLegacy,
wantDeps: nuGetLegacyDeps,
},
}
for _, v := range vectors {
t.Run(path.Base(v.file), func(t *testing.T) {
f, err := os.Open(v.file)
require.NoError(t, err)
got, deps, err := NewParser().Parse(f)
require.NoError(t, err)
sort.Slice(got, func(i, j int) bool {
ret := strings.Compare(got[i].Name, got[j].Name)
if ret == 0 {
return got[i].Version < got[j].Version
}
return ret < 0
})
sort.Slice(v.want, func(i, j int) bool {
ret := strings.Compare(v.want[i].Name, v.want[j].Name)
if ret == 0 {
return v.want[i].Version < v.want[j].Version
}
return ret < 0
})
assert.Equal(t, v.want, got)
if v.wantDeps != nil {
sortDeps(deps)
sortDeps(v.wantDeps)
assert.Equal(t, v.wantDeps, deps)
}
})
}
}
func sortDeps(deps []types.Dependency) {
sort.Slice(deps, func(i, j int) bool {
return strings.Compare(deps[i].ID, deps[j].ID) < 0
})
for i := range deps {
sort.Strings(deps[i].DependsOn)
}
}
<file_sep>/pkg/nodejs/npm/parse.go
package npm
import (
"fmt"
"github.com/samber/lo"
"io"
"path"
"sort"
"strings"
"github.com/liamg/jfather"
"golang.org/x/exp/maps"
"golang.org/x/xerrors"
dio "github.com/aquasecurity/go-dep-parser/pkg/io"
"github.com/aquasecurity/go-dep-parser/pkg/log"
"github.com/aquasecurity/go-dep-parser/pkg/types"
"github.com/aquasecurity/go-dep-parser/pkg/utils"
)
const nodeModulesDir = "node_modules"
type LockFile struct {
Dependencies map[string]Dependency `json:"dependencies"`
Packages map[string]Package `json:"packages"`
LockfileVersion int `json:"lockfileVersion"`
}
type Dependency struct {
Version string `json:"version"`
Dev bool `json:"dev"`
Dependencies map[string]Dependency `json:"dependencies"`
Requires map[string]string `json:"requires"`
Resolved string `json:"resolved"`
StartLine int
EndLine int
}
type Package struct {
Name string `json:"name"`
Version string `json:"version"`
Dependencies map[string]string `json:"dependencies"`
OptionalDependencies map[string]string `json:"optionalDependencies"`
DevDependencies map[string]string `json:"devDependencies"`
Resolved string `json:"resolved"`
Dev bool `json:"dev"`
Link bool `json:"link"`
Workspaces []string `json:"workspaces"`
StartLine int
EndLine int
}
type Parser struct{}
func NewParser() types.Parser {
return &Parser{}
}
func (p *Parser) Parse(r dio.ReadSeekerAt) ([]types.Library, []types.Dependency, error) {
var lockFile LockFile
input, err := io.ReadAll(r)
if err != nil {
return nil, nil, xerrors.Errorf("read error: %w", err)
}
if err := jfather.Unmarshal(input, &lockFile); err != nil {
return nil, nil, xerrors.Errorf("decode error: %w", err)
}
var libs []types.Library
var deps []types.Dependency
if lockFile.LockfileVersion == 1 {
libs, deps = p.parseV1(lockFile.Dependencies, map[string]string{})
} else {
libs, deps = p.parseV2(lockFile.Packages)
}
return utils.UniqueLibraries(libs), uniqueDeps(deps), nil
}
func (p *Parser) parseV2(packages map[string]Package) ([]types.Library, []types.Dependency) {
libs := make(map[string]types.Library, len(packages)-1)
var deps []types.Dependency
// Resolve links first
// https://docs.npmjs.com/cli/v9/configuring-npm/package-lock-json#packages
resolveLinks(packages)
directDeps := map[string]struct{}{}
for name, version := range lo.Assign(packages[""].Dependencies, packages[""].OptionalDependencies, packages[""].DevDependencies) {
pkgPath := joinPaths(nodeModulesDir, name)
if _, ok := packages[pkgPath]; !ok {
log.Logger.Debugf("Unable to find the direct dependency: '%s@%s'", name, version)
continue
}
// Store the package paths of direct dependencies
// e.g. node_modules/body-parser
directDeps[pkgPath] = struct{}{}
}
for pkgPath, pkg := range packages {
if !strings.HasPrefix(pkgPath, "node_modules") {
continue
}
// pkg.Name exists when package name != folder name
pkgName := pkg.Name
if pkgName == "" {
pkgName = pkgNameFromPath(pkgPath)
}
pkgID := utils.PackageID(pkgName, pkg.Version)
location := types.Location{
StartLine: pkg.StartLine,
EndLine: pkg.EndLine,
}
// There are cases when similar libraries use same dependencies
// we need to add location for each these dependencies
if savedLib, ok := libs[pkgID]; ok {
savedLib.Locations = append(savedLib.Locations, location)
sort.Sort(savedLib.Locations)
libs[pkgID] = savedLib
continue
}
lib := types.Library{
ID: pkgID,
Name: pkgName,
Version: pkg.Version,
Indirect: isIndirectLib(pkgPath, directDeps),
Dev: pkg.Dev,
ExternalReferences: []types.ExternalRef{
{
Type: types.RefOther,
URL: pkg.Resolved,
},
},
Locations: []types.Location{location},
}
libs[pkgID] = lib
// npm builds graph using optional deps. e.g.:
// └─┬ [email protected]
// ├─┬ [email protected] - optional dependency
// │ └── [email protected].
dependencies := lo.Assign(pkg.Dependencies, pkg.OptionalDependencies)
dependsOn := make([]string, 0, len(dependencies))
for depName, depVersion := range dependencies {
depID, err := findDependsOn(pkgPath, depName, packages)
if err != nil {
log.Logger.Warnf("Cannot resolve the version: '%s@%s'", depName, depVersion)
continue
}
dependsOn = append(dependsOn, depID)
}
if len(dependsOn) > 0 {
deps = append(deps, types.Dependency{
ID: lib.ID,
DependsOn: dependsOn,
})
}
}
return maps.Values(libs), deps
}
// for local package npm uses links. e.g.:
// function/func1 -> target of package
// node_modules/func1 -> link to target
// see `package-lock_v3_with_workspace.json` to better understanding
func resolveLinks(packages map[string]Package) {
links := lo.PickBy(packages, func(_ string, pkg Package) bool {
return pkg.Link
})
// Early return
if len(links) == 0 {
return
}
rootPkg := packages[""]
if rootPkg.Dependencies == nil {
rootPkg.Dependencies = make(map[string]string)
}
workspaces := rootPkg.Workspaces
for pkgPath, pkg := range packages {
for linkPath, link := range links {
if !strings.HasPrefix(pkgPath, link.Resolved) {
continue
}
// The target doesn't have the "resolved" field, so we need to copy it from the link.
if pkg.Resolved == "" {
pkg.Resolved = link.Resolved
}
// Resolve the link package so all packages are located under "node_modules".
resolvedPath := strings.ReplaceAll(pkgPath, link.Resolved, linkPath)
packages[resolvedPath] = pkg
// Delete the target package
delete(packages, pkgPath)
if isWorkspace(pkgPath, workspaces) {
rootPkg.Dependencies[pkgNameFromPath(linkPath)] = pkg.Version
}
break
}
}
packages[""] = rootPkg
}
func isWorkspace(pkgPath string, workspaces []string) bool {
for _, workspace := range workspaces {
if match, err := path.Match(workspace, pkgPath); err != nil {
log.Logger.Debugf("unable to parse workspace %q for %s", workspace, pkgPath)
} else if match {
return true
}
}
return false
}
func findDependsOn(pkgPath, depName string, packages map[string]Package) (string, error) {
depPath := joinPaths(pkgPath, nodeModulesDir)
paths := strings.Split(depPath, "/")
// Try to resolve the version with the nearest directory
// e.g. for pkgPath == `node_modules/body-parser/node_modules/debug`, depName == `ms`:
// - "node_modules/body-parser/node_modules/debug/node_modules/ms"
// - "node_modules/body-parser/node_modules/ms"
// - "node_modules/ms"
for i := len(paths) - 1; i >= 0; i-- {
if paths[i] != nodeModulesDir {
continue
}
path := joinPaths(paths[:i+1]...)
path = joinPaths(path, depName)
if dep, ok := packages[path]; ok {
return utils.PackageID(depName, dep.Version), nil
}
}
// It should not reach here.
return "", xerrors.Errorf("can't find dependsOn for %s", depName)
}
func (p *Parser) parseV1(dependencies map[string]Dependency, versions map[string]string) ([]types.Library, []types.Dependency) {
// Update package name and version mapping.
for pkgName, dep := range dependencies {
// Overwrite the existing package version so that the nested version can take precedence.
versions[pkgName] = dep.Version
}
var libs []types.Library
var deps []types.Dependency
for pkgName, dependency := range dependencies {
lib := types.Library{
ID: utils.PackageID(pkgName, dependency.Version),
Name: pkgName,
Version: dependency.Version,
Dev: dependency.Dev,
Indirect: true, // lockfile v1 schema doesn't have information about Direct dependencies
ExternalReferences: []types.ExternalRef{
{
Type: types.RefOther,
URL: dependency.Resolved,
},
},
Locations: []types.Location{
{
StartLine: dependency.StartLine,
EndLine: dependency.EndLine,
},
},
}
libs = append(libs, lib)
dependsOn := make([]string, 0, len(dependency.Requires))
for libName, requiredVer := range dependency.Requires {
// Try to resolve the version with nested dependencies first
if resolvedDep, ok := dependency.Dependencies[libName]; ok {
libID := utils.PackageID(libName, resolvedDep.Version)
dependsOn = append(dependsOn, libID)
continue
}
// Try to resolve the version with the higher level dependencies
if ver, ok := versions[libName]; ok {
dependsOn = append(dependsOn, utils.PackageID(libName, ver))
continue
}
// It should not reach here.
log.Logger.Warnf("Cannot resolve the version: %s@%s", libName, requiredVer)
}
if len(dependsOn) > 0 {
deps = append(deps, types.Dependency{
ID: utils.PackageID(lib.Name, lib.Version),
DependsOn: dependsOn,
})
}
if dependency.Dependencies != nil {
// Recursion
childLibs, childDeps := p.parseV1(dependency.Dependencies, maps.Clone(versions))
libs = append(libs, childLibs...)
deps = append(deps, childDeps...)
}
}
return libs, deps
}
func uniqueDeps(deps []types.Dependency) []types.Dependency {
var uniqDeps []types.Dependency
unique := make(map[string]struct{})
for _, dep := range deps {
sort.Strings(dep.DependsOn)
depKey := fmt.Sprintf("%s:%s", dep.ID, strings.Join(dep.DependsOn, ","))
if _, ok := unique[depKey]; !ok {
unique[depKey] = struct{}{}
uniqDeps = append(uniqDeps, dep)
}
}
sort.Sort(types.Dependencies(uniqDeps))
return uniqDeps
}
func isIndirectLib(pkgPath string, directDeps map[string]struct{}) bool {
// A project can contain 2 different versions of the same dependency.
// e.g. `node_modules/string-width/node_modules/strip-ansi` and `node_modules/string-ansi`
// direct dependencies always have root path (`node_modules/<lib_name>`)
if _, ok := directDeps[pkgPath]; ok {
return false
}
return true
}
func pkgNameFromPath(path string) string {
// lock file contains path to dependency in `node_modules`. e.g.:
// node_modules/string-width
// node_modules/string-width/node_modules/strip-ansi
// we renamed to `node_modules` directory prefixes `workspace` when resolving Links
// node_modules/function1
// node_modules/nested_func/node_modules/debug
if index := strings.LastIndex(path, nodeModulesDir); index != -1 {
return path[index+len(nodeModulesDir)+1:]
}
log.Logger.Warnf("npm %q package path doesn't have `node_modules` prefix", path)
return path
}
func joinPaths(paths ...string) string {
return strings.Join(paths, "/")
}
// UnmarshalJSONWithMetadata needed to detect start and end lines of deps for v1
func (t *Dependency) UnmarshalJSONWithMetadata(node jfather.Node) error {
if err := node.Decode(&t); err != nil {
return err
}
// Decode func will overwrite line numbers if we save them first
t.StartLine = node.Range().Start.Line
t.EndLine = node.Range().End.Line
return nil
}
// UnmarshalJSONWithMetadata needed to detect start and end lines of deps for v2 or newer
func (t *Package) UnmarshalJSONWithMetadata(node jfather.Node) error {
if err := node.Decode(&t); err != nil {
return err
}
// Decode func will overwrite line numbers if we save them first
t.StartLine = node.Range().Start.Line
t.EndLine = node.Range().End.Line
return nil
}
<file_sep>/pkg/golang/mod/testdata/replaced-with-version/go.mod
module github.com/org/repo
go 1.17
require github.com/aquasecurity/go-dep-parser v0.0.0-20211110174639-8257534ffed3
require golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
replace github.com/aquasecurity/go-dep-parser v0.0.0-20211110174639-8257534ffed3 => github.com/aquasecurity/go-dep-parser v0.0.0-20220406074731-71021a481237
<file_sep>/pkg/rust/binary/parse.go
// Detects dependencies from Rust binaries built with https://github.com/rust-secure-code/cargo-auditable
package binary
import (
"golang.org/x/xerrors"
dio "github.com/aquasecurity/go-dep-parser/pkg/io"
"github.com/aquasecurity/go-dep-parser/pkg/types"
"github.com/aquasecurity/go-dep-parser/pkg/utils"
rustaudit "github.com/microsoft/go-rustaudit"
)
var (
ErrUnrecognizedExe = xerrors.New("unrecognized executable format")
ErrNonRustBinary = xerrors.New("non Rust auditable binary")
)
// convertError detects rustaudit.ErrUnknownFileFormat and convert to
// ErrUnrecognizedExe and convert rustaudit.ErrNoRustDepInfo to ErrNonRustBinary
func convertError(err error) error {
if err == rustaudit.ErrUnknownFileFormat {
return ErrUnrecognizedExe
}
if err == rustaudit.ErrNoRustDepInfo {
return ErrNonRustBinary
}
return err
}
type Parser struct{}
func NewParser() types.Parser {
return &Parser{}
}
// Parse scans files to try to report Rust crates and version injected into Rust binaries
// via https://github.com/rust-secure-code/cargo-auditable
func (p *Parser) Parse(r dio.ReadSeekerAt) ([]types.Library, []types.Dependency, error) {
info, err := rustaudit.GetDependencyInfo(r)
if err != nil {
return nil, nil, convertError(err)
}
var libs []types.Library
var deps []types.Dependency
for _, pkg := range info.Packages {
if pkg.Kind == rustaudit.Runtime {
pkgID := utils.PackageID(pkg.Name, pkg.Version)
libs = append(libs, types.Library{
ID: pkgID,
Name: pkg.Name,
Version: pkg.Version,
Indirect: !pkg.Root,
})
var childDeps []string
for _, dep_idx := range pkg.Dependencies {
dep := info.Packages[dep_idx]
if dep.Kind == rustaudit.Runtime {
childDeps = append(childDeps, utils.PackageID(dep.Name, dep.Version))
}
}
if len(childDeps) > 0 {
deps = append(deps, types.Dependency{ID: pkgID, DependsOn: childDeps})
}
}
}
return libs, deps, nil
}
<file_sep>/pkg/golang/mod/testdata/replaced-with-local-path-and-version/xerrors/go.mod
module golang.org/x/xerrors
go 1.12
<file_sep>/pkg/python/pipenv/parse.go
package pipenv
import (
"github.com/liamg/jfather"
"io"
"strings"
dio "github.com/aquasecurity/go-dep-parser/pkg/io"
"github.com/aquasecurity/go-dep-parser/pkg/types"
"golang.org/x/xerrors"
)
type lockFile struct {
Default map[string]dependency `json:"default"`
}
type dependency struct {
Version string `json:"version"`
StartLine int
EndLine int
}
type Parser struct{}
func NewParser() types.Parser {
return &Parser{}
}
func (p *Parser) Parse(r dio.ReadSeekerAt) ([]types.Library, []types.Dependency, error) {
var lockFile lockFile
input, err := io.ReadAll(r)
if err != nil {
return nil, nil, xerrors.Errorf("failed to read packages.lock.json: %w", err)
}
if err := jfather.Unmarshal(input, &lockFile); err != nil {
return nil, nil, xerrors.Errorf("failed to decode Pipenv.lock: %w", err)
}
var libs []types.Library
for pkgName, dependency := range lockFile.Default {
libs = append(libs, types.Library{
Name: pkgName,
Version: strings.TrimLeft(dependency.Version, "="),
Locations: []types.Location{{StartLine: dependency.StartLine, EndLine: dependency.EndLine}},
})
}
return libs, nil, nil
}
// UnmarshalJSONWithMetadata needed to detect start and end lines of deps
func (t *dependency) UnmarshalJSONWithMetadata(node jfather.Node) error {
if err := node.Decode(&t); err != nil {
return err
}
// Decode func will overwrite line numbers if we save them first
t.StartLine = node.Range().Start.Line
t.EndLine = node.Range().End.Line
return nil
}
<file_sep>/pkg/nodejs/pnpm/parse.go
package pnpm
import (
"fmt"
"strconv"
"strings"
"golang.org/x/xerrors"
"gopkg.in/yaml.v3"
dio "github.com/aquasecurity/go-dep-parser/pkg/io"
"github.com/aquasecurity/go-dep-parser/pkg/log"
"github.com/aquasecurity/go-dep-parser/pkg/types"
"github.com/aquasecurity/go-version/pkg/semver"
)
type PackageResolution struct {
Tarball string `yaml:"tarball,omitempty"`
}
type PackageInfo struct {
Resolution PackageResolution `yaml:"resolution"`
Dependencies map[string]string `yaml:"dependencies,omitempty"`
DevDependencies map[string]string `yaml:"devDependencies,omitempty"`
IsDev bool `yaml:"dev,omitempty"`
Name string `yaml:"name,omitempty"`
Version string `yaml:"version,omitempty"`
}
type LockFile struct {
LockfileVersion any `yaml:"lockfileVersion"`
Dependencies map[string]any `yaml:"dependencies,omitempty"`
DevDependencies map[string]any `yaml:"devDependencies,omitempty"`
Packages map[string]PackageInfo `yaml:"packages,omitempty"`
}
type Parser struct{}
func NewParser() types.Parser {
return &Parser{}
}
func (p *Parser) ID(name, version string) string {
return fmt.Sprintf("%s@%s", name, version)
}
func (p *Parser) Parse(r dio.ReadSeekerAt) ([]types.Library, []types.Dependency, error) {
var lockFile LockFile
if err := yaml.NewDecoder(r).Decode(&lockFile); err != nil {
return nil, nil, xerrors.Errorf("decode error: %w", err)
}
lockVer := parseLockfileVersion(lockFile)
if lockVer < 0 {
return nil, nil, nil
}
libs, deps := p.parse(lockVer, lockFile)
return libs, deps, nil
}
func (p *Parser) parse(lockVer float64, lockFile LockFile) ([]types.Library, []types.Dependency) {
var libs []types.Library
var deps []types.Dependency
// Dependency path is a path to a dependency with a specific set of resolved subdependencies.
// cf. https://github.com/pnpm/spec/blob/ad27a225f81d9215becadfa540ef05fa4ad6dd60/dependency-path.md
for depPath, info := range lockFile.Packages {
if info.IsDev {
continue
}
// Packages from tarball have `name` and `version` fields.
// cf. https://github.com/pnpm/spec/blob/ad27a225f81d9215becadfa540ef05fa4ad6dd60/lockfile/5.2.md#packagesdependencypathname
name := info.Name
version := info.Version
// Other packages don't have these fields.
// Parse `dependencyPath` to determine name and version.
if info.Resolution.Tarball == "" {
name, version = parsePackage(depPath, lockVer)
}
pkgID := p.ID(name, version)
dependencies := make([]string, 0, len(info.Dependencies))
for depName, depVer := range info.Dependencies {
dependencies = append(dependencies, p.ID(depName, depVer))
}
libs = append(libs, types.Library{
ID: pkgID,
Name: name,
Version: version,
Indirect: isIndirectLib(name, lockFile.Dependencies),
})
if len(dependencies) > 0 {
deps = append(deps, types.Dependency{
ID: pkgID,
DependsOn: dependencies,
})
}
}
return libs, deps
}
func parseLockfileVersion(lockFile LockFile) float64 {
switch v := lockFile.LockfileVersion.(type) {
// v5
case float64:
return v
// v6+
case string:
if lockVer, err := strconv.ParseFloat(v, 64); err != nil {
log.Logger.Debugf("Unable to convert the lock file version to float: %s", err)
return -1
} else {
return lockVer
}
default:
log.Logger.Debugf("Unknown type for the lock file version: %s", lockFile.LockfileVersion)
return -1
}
}
func isIndirectLib(name string, directDeps map[string]interface{}) bool {
_, ok := directDeps[name]
return !ok
}
// cf. https://github.com/pnpm/pnpm/blob/ce61f8d3c29eee46cee38d56ced45aea8a439a53/packages/dependency-path/src/index.ts#L112-L163
func parsePackage(depPath string, lockFileVersion float64) (string, string) {
// The version separator is different between v5 and v6+.
versionSep := "@"
if lockFileVersion < 6 {
versionSep = "/"
}
return parseDepPath(depPath, versionSep)
}
func parseDepPath(depPath, versionSep string) (string, string) {
// Skip registry
// e.g.
// - "registry.npmjs.org/lodash/4.17.10" => "lodash/4.17.10"
// - "registry.npmjs.org/@babel/generator/7.21.9" => "@babel/generator/7.21.9"
// - "/lodash/4.17.10" => "lodash/4.17.10"
_, depPath, _ = strings.Cut(depPath, "/")
// Parse scope
// e.g.
// - v5: "@babel/generator/7.21.9" => {"babel", "generator/7.21.9"}
// - v6+: "@babel/[email protected]" => "{"babel", "[email protected]"}
var scope string
if strings.HasPrefix(depPath, "@") {
scope, depPath, _ = strings.Cut(depPath, "/")
}
// Parse package name
// e.g.
// - v5: "generator/7.21.9" => {"generator", "7.21.9"}
// - v6+: "[email protected]" => {"helper-annotate-as-pure", "7.18.6"}
var name, version string
name, version, _ = strings.Cut(depPath, versionSep)
if scope != "" {
name = fmt.Sprintf("%s/%s", scope, name)
}
// Trim peer deps
// e.g.
// - v5: "7.21.5_@[email protected]" => "7.21.5"
// - v6+: "7.21.5(@babel/[email protected])" => "7.21.5"
if idx := strings.IndexAny(version, "_("); idx != -1 {
version = version[:idx]
}
if _, err := semver.Parse(version); err != nil {
log.Logger.Debugf("Skip %q package. %q doesn't match semver: %s", depPath, version, err)
return "", ""
}
return name, version
}
<file_sep>/pkg/java/jar/parse.go
package jar
import (
"archive/zip"
"bufio"
"crypto/sha1"
"encoding/hex"
"fmt"
dio "github.com/aquasecurity/go-dep-parser/pkg/io"
"github.com/aquasecurity/go-dep-parser/pkg/log"
"github.com/aquasecurity/go-dep-parser/pkg/types"
"github.com/samber/lo"
"go.uber.org/zap"
"golang.org/x/xerrors"
"io"
"os"
"path"
"path/filepath"
"regexp"
"strings"
)
var (
jarFileRegEx = regexp.MustCompile(`^([a-zA-Z0-9\._-]*[^-*])-(\d\S*(?:-SNAPSHOT)?).jar$`)
)
type Client interface {
Exists(groupID, artifactID string) (bool, error)
SearchBySHA1(sha1 string) (Properties, error)
SearchByArtifactID(artifactID string) (string, error)
}
type Parser struct {
rootFilePath string
offline bool
size int64
client Client
}
type Option func(*Parser)
func WithFilePath(filePath string) Option {
return func(p *Parser) {
p.rootFilePath = filePath
}
}
func WithOffline(offline bool) Option {
return func(p *Parser) {
p.offline = offline
}
}
func WithSize(size int64) Option {
return func(p *Parser) {
p.size = size
}
}
func NewParser(c Client, opts ...Option) types.Parser {
p := &Parser{
client: c,
}
for _, opt := range opts {
opt(p)
}
return p
}
func (p *Parser) Parse(r dio.ReadSeekerAt) ([]types.Library, []types.Dependency, error) {
libs, deps, err := p.parseArtifact(p.rootFilePath, p.size, r)
if err != nil {
return nil, nil, xerrors.Errorf("unable to parse %s: %w", p.rootFilePath, err)
}
return removeLibraryDuplicates(libs), deps, nil
}
func (p *Parser) parseArtifact(filePath string, size int64, r dio.ReadSeekerAt) ([]types.Library, []types.Dependency, error) {
log.Logger.Debugw("Parsing Java artifacts...", zap.String("file", filePath))
zr, err := zip.NewReader(r, size)
if err != nil {
return nil, nil, xerrors.Errorf("zip error: %w", err)
}
// Try to extract artifactId and version from the file name
// e.g. spring-core-5.3.4-SNAPSHOT.jar => sprint-core, 5.3.4-SNAPSHOT
fileName := filepath.Base(filePath)
fileProps := parseFileName(filePath)
var libs []types.Library
var m manifest
var foundPomProps bool
for _, fileInJar := range zr.File {
switch {
case filepath.Base(fileInJar.Name) == "pom.properties":
props, err := parsePomProperties(fileInJar, filePath)
if err != nil {
return nil, nil, xerrors.Errorf("failed to parse %s: %w", fileInJar.Name, err)
}
libs = append(libs, props.Library())
// Check if the pom.properties is for the original JAR/WAR/EAR
if fileProps.ArtifactID == props.ArtifactID && fileProps.Version == props.Version {
foundPomProps = true
}
case filepath.Base(fileInJar.Name) == "MANIFEST.MF":
m, err = parseManifest(fileInJar)
if err != nil {
return nil, nil, xerrors.Errorf("failed to parse MANIFEST.MF: %w", err)
}
case isArtifact(fileInJar.Name):
innerLibs, _, err := p.parseInnerJar(fileInJar, filePath) //TODO process inner deps
if err != nil {
log.Logger.Debugf("Failed to parse %s: %s", fileInJar.Name, err)
continue
}
libs = append(libs, innerLibs...)
}
}
// If pom.properties is found, it should be preferred than MANIFEST.MF.
if foundPomProps {
return libs, nil, nil
}
manifestProps := m.properties(filePath)
if p.offline {
// In offline mode, we will not check if the artifact information is correct.
if !manifestProps.Valid() {
log.Logger.Debugw("Unable to identify POM in offline mode", zap.String("file", fileName))
return libs, nil, nil
}
return append(libs, manifestProps.Library()), nil, nil
}
if manifestProps.Valid() {
// Even if MANIFEST.MF is found, the groupId and artifactId might not be valid.
// We have to make sure that the artifact exists actually.
if ok, _ := p.client.Exists(manifestProps.GroupID, manifestProps.ArtifactID); ok {
// If groupId and artifactId are valid, they will be returned.
return append(libs, manifestProps.Library()), nil, nil
}
}
// If groupId and artifactId are not found, call Maven Central's search API with SHA-1 digest.
props, err := p.searchBySHA1(r, filePath)
if err == nil {
return append(libs, props.Library()), nil, nil
} else if !xerrors.Is(err, ArtifactNotFoundErr) {
return nil, nil, xerrors.Errorf("failed to search by SHA1: %w", err)
}
log.Logger.Debugw("No such POM in the central repositories", zap.String("file", fileName))
// Return when artifactId or version from the file name are empty
if fileProps.ArtifactID == "" || fileProps.Version == "" {
return libs, nil, nil
}
// Try to search groupId by artifactId via sonatype API
// When some artifacts have the same groupIds, it might result in false detection.
fileProps.GroupID, err = p.client.SearchByArtifactID(fileProps.ArtifactID)
if err == nil {
log.Logger.Debugw("POM was determined in a heuristic way", zap.String("file", fileName),
zap.String("artifact", fileProps.String()))
libs = append(libs, fileProps.Library())
} else if !xerrors.Is(err, ArtifactNotFoundErr) {
return nil, nil, xerrors.Errorf("failed to search by artifact id: %w", err)
}
return libs, nil, nil
}
func (p *Parser) parseInnerJar(zf *zip.File, rootPath string) ([]types.Library, []types.Dependency, error) {
fr, err := zf.Open()
if err != nil {
return nil, nil, xerrors.Errorf("unable to open %s: %w", zf.Name, err)
}
f, err := os.CreateTemp("", "inner")
if err != nil {
return nil, nil, xerrors.Errorf("unable to create a temp file: %w", err)
}
defer func() {
f.Close()
os.Remove(f.Name())
}()
// Copy the file content to the temp file
if _, err = io.Copy(f, fr); err != nil {
return nil, nil, xerrors.Errorf("file copy error: %w", err)
}
// build full path to inner jar
fullPath := path.Join(rootPath, zf.Name)
// Parse jar/war/ear recursively
innerLibs, innerDeps, err := p.parseArtifact(fullPath, int64(zf.UncompressedSize64), f)
if err != nil {
return nil, nil, xerrors.Errorf("failed to parse %s: %w", zf.Name, err)
}
return innerLibs, innerDeps, nil
}
func (p *Parser) searchBySHA1(r io.ReadSeeker, filePath string) (Properties, error) {
if _, err := r.Seek(0, io.SeekStart); err != nil {
return Properties{}, xerrors.Errorf("file seek error: %w", err)
}
h := sha1.New()
if _, err := io.Copy(h, r); err != nil {
return Properties{}, xerrors.Errorf("unable to calculate SHA-1: %w", err)
}
s := hex.EncodeToString(h.Sum(nil))
prop, err := p.client.SearchBySHA1(s)
if err != nil {
return Properties{}, err
}
prop.FilePath = filePath
return prop, nil
}
func isArtifact(name string) bool {
ext := filepath.Ext(name)
if ext == ".jar" || ext == ".ear" || ext == ".war" {
return true
}
return false
}
func parseFileName(filePath string) Properties {
fileName := filepath.Base(filePath)
packageVersion := jarFileRegEx.FindStringSubmatch(fileName)
if len(packageVersion) != 3 {
return Properties{}
}
return Properties{
ArtifactID: packageVersion[1],
Version: packageVersion[2],
FilePath: filePath,
}
}
func parsePomProperties(f *zip.File, filePath string) (Properties, error) {
file, err := f.Open()
if err != nil {
return Properties{}, xerrors.Errorf("unable to open pom.properties: %w", err)
}
defer file.Close()
p := Properties{
FilePath: filePath,
}
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
switch {
case strings.HasPrefix(line, "groupId="):
p.GroupID = strings.TrimPrefix(line, "groupId=")
case strings.HasPrefix(line, "artifactId="):
p.ArtifactID = strings.TrimPrefix(line, "artifactId=")
case strings.HasPrefix(line, "version="):
p.Version = strings.TrimPrefix(line, "version=")
}
}
if err = scanner.Err(); err != nil {
return Properties{}, xerrors.Errorf("scan error: %w", err)
}
return p, nil
}
type manifest struct {
implementationVersion string
implementationTitle string
implementationVendor string
implementationVendorId string
specificationTitle string
specificationVersion string
specificationVendor string
bundleName string
bundleVersion string
bundleSymbolicName string
}
func parseManifest(f *zip.File) (manifest, error) {
file, err := f.Open()
if err != nil {
return manifest{}, xerrors.Errorf("unable to open MANIFEST.MF: %w", err)
}
defer file.Close()
var m manifest
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
// Skip variables. e.g. Bundle-Name: %bundleName
ss := strings.Fields(line)
if len(ss) <= 1 || (len(ss) > 1 && strings.HasPrefix(ss[1], "%")) {
continue
}
// It is not determined which fields are present in each application.
// In some cases, none of them are included, in which case they cannot be detected.
switch {
case strings.HasPrefix(line, "Implementation-Version:"):
m.implementationVersion = strings.TrimPrefix(line, "Implementation-Version:")
case strings.HasPrefix(line, "Implementation-Title:"):
m.implementationTitle = strings.TrimPrefix(line, "Implementation-Title:")
case strings.HasPrefix(line, "Implementation-Vendor:"):
m.implementationVendor = strings.TrimPrefix(line, "Implementation-Vendor:")
case strings.HasPrefix(line, "Implementation-Vendor-Id:"):
m.implementationVendorId = strings.TrimPrefix(line, "Implementation-Vendor-Id:")
case strings.HasPrefix(line, "Specification-Version:"):
m.specificationVersion = strings.TrimPrefix(line, "Specification-Version:")
case strings.HasPrefix(line, "Specification-Title:"):
m.specificationTitle = strings.TrimPrefix(line, "Specification-Title:")
case strings.HasPrefix(line, "Specification-Vendor:"):
m.specificationVendor = strings.TrimPrefix(line, "Specification-Vendor:")
case strings.HasPrefix(line, "Bundle-Version:"):
m.bundleVersion = strings.TrimPrefix(line, "Bundle-Version:")
case strings.HasPrefix(line, "Bundle-Name:"):
m.bundleName = strings.TrimPrefix(line, "Bundle-Name:")
case strings.HasPrefix(line, "Bundle-SymbolicName:"):
m.bundleSymbolicName = strings.TrimPrefix(line, "Bundle-SymbolicName:")
}
}
if err = scanner.Err(); err != nil {
return manifest{}, xerrors.Errorf("scan error: %w", err)
}
return m, nil
}
func (m manifest) properties(filePath string) Properties {
groupID, err := m.determineGroupID()
if err != nil {
return Properties{}
}
artifactID, err := m.determineArtifactID()
if err != nil {
return Properties{}
}
version, err := m.determineVersion()
if err != nil {
return Properties{}
}
return Properties{
GroupID: groupID,
ArtifactID: artifactID,
Version: version,
FilePath: filePath,
}
}
func (m manifest) determineGroupID() (string, error) {
var groupID string
switch {
case m.implementationVendorId != "":
groupID = m.implementationVendorId
case m.bundleSymbolicName != "":
groupID = m.bundleSymbolicName
// e.g. "com.fasterxml.jackson.core.jackson-databind" => "com.fasterxml.jackson.core"
idx := strings.LastIndex(m.bundleSymbolicName, ".")
if idx > 0 {
groupID = m.bundleSymbolicName[:idx]
}
case m.implementationVendor != "":
groupID = m.implementationVendor
case m.specificationVendor != "":
groupID = m.specificationVendor
default:
return "", xerrors.New("no groupID found")
}
return strings.TrimSpace(groupID), nil
}
func (m manifest) determineArtifactID() (string, error) {
var artifactID string
switch {
case m.implementationTitle != "":
artifactID = m.implementationTitle
case m.specificationTitle != "":
artifactID = m.specificationTitle
case m.bundleName != "":
artifactID = m.bundleName
default:
return "", xerrors.New("no artifactID found")
}
return strings.TrimSpace(artifactID), nil
}
func (m manifest) determineVersion() (string, error) {
var version string
switch {
case m.implementationVersion != "":
version = m.implementationVersion
case m.specificationVersion != "":
version = m.specificationVersion
case m.bundleVersion != "":
version = m.bundleVersion
default:
return "", xerrors.New("no version found")
}
return strings.TrimSpace(version), nil
}
func removeLibraryDuplicates(libs []types.Library) []types.Library {
return lo.UniqBy(libs, func(lib types.Library) string {
return fmt.Sprintf("%s::%s::%s", lib.Name, lib.Version, lib.FilePath)
})
}
<file_sep>/pkg/nodejs/yarn/parse_testcase.go
package yarn
import "github.com/aquasecurity/go-dep-parser/pkg/types"
var (
// cd ./pkg/nodejs/yarn
// docker build -t yarn-test testcase_deps_generator
// docker run --name node --rm -it yarn-test sh
// yarn init -y
// yarn add promise jquery
// yarn list | grep -E -o "\S+@[^\^~]\S+" | awk -F@ 'NR>0 {printf("{\""$1"\", \""$2"\", \"\"},\n")}'
// to get deps with locations from lock file use following commands:
// cat yarn.lock | awk '/^\S+@[~^*]?(>= )?[0-9.]*/,/^$/{if($0=="") {print "--"prev} else { if(substr($0,1,2)!=" ") {print NR":"$0} else {print $0}} prev=NR}; END{print "--"prev}' | awk 'BEGIN {s=""}; {(substr($0,1,2)=="--") ? (s=s$0"\n") : (s=s$0)}; END { print s}' | sed -E 's/@([0-9~><*\^]|npm).*version:? "?/:/' | sed 's/ /:/' | sed 's/"//g'| awk 'match($0, /[[:digit:]]+$/) {print substr($0, RSTART, RLENGTH)":"$0 }' | awk -F":" '{print "{ID: \""$3"@"$4"\", Name: \""$3"\", Version: \""$4"\", Locations: []types.Location{{StartLine: "$2", EndLine: "$1"}}},"}'
yarnNormal = []types.Library{
{ID: "[email protected]", Name: "asap", Version: "2.0.6", Locations: []types.Location{{StartLine: 5, EndLine: 8}}},
{ID: "[email protected]", Name: "jquery", Version: "3.4.1", Locations: []types.Location{{StartLine: 10, EndLine: 13}}},
{ID: "[email protected]", Name: "promise", Version: "8.0.3", Locations: []types.Location{{StartLine: 15, EndLine: 20}}},
}
// ... and
// yarn --cwd test_deps_generator install
// node test_deps_generator/index.js yarn.lock
yarnNormalDeps = []types.Dependency{
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
}
// ... and
// yarn add react redux
// yarn list | grep -E -o "\S+@[^\^~]\S+" | awk -F@ 'NR>0 {printf("{\""$1"\", \""$2"\", \"\"},\n")}'
// to get deps with locations from lock file use following commands:
// awk '/^\S+@[~^*]?(>= )?[0-9.]*/,/^$/{if($0=="") {print "--"prev} else { if(substr($0,1,2)!=" ") {print NR":"$0} else {print $0}} prev=NR}; END{print "--"prev}' | awk 'BEGIN {s=""}; {(substr($0,1,2)=="--") ? (s=s$0"\n") : (s=s$0)}; END { print s}' | sed -E 's/@([0-9~><*\^]|npm).*version:? "?/:/' | sed 's/ /:/' | sed 's/"//g'| awk 'match($0, /[[:digit:]]+$/) {print substr($0, RSTART, RLENGTH)":"$0 }' | awk -F":" '{print "{ID: \""$3"@"$4"\", Name: \""$3"\", Version: \""$4"\", Locations: []types.Location{{StartLine: "$2", EndLine: "$1"}}},"}'
yarnReact = []types.Library{
{ID: "[email protected]", Name: "asap", Version: "2.0.6", Locations: []types.Location{{StartLine: 5, EndLine: 8}}},
{ID: "[email protected]", Name: "jquery", Version: "3.4.1", Locations: []types.Location{{StartLine: 10, EndLine: 13}}},
{ID: "[email protected]", Name: "js-tokens", Version: "4.0.0", Locations: []types.Location{{StartLine: 15, EndLine: 18}}},
{ID: "[email protected]", Name: "loose-envify", Version: "1.4.0", Locations: []types.Location{{StartLine: 20, EndLine: 25}}},
{ID: "[email protected]", Name: "object-assign", Version: "4.1.1", Locations: []types.Location{{StartLine: 27, EndLine: 30}}},
{ID: "[email protected]", Name: "promise", Version: "8.0.3", Locations: []types.Location{{StartLine: 32, EndLine: 37}}},
{ID: "[email protected]", Name: "prop-types", Version: "15.7.2", Locations: []types.Location{{StartLine: 39, EndLine: 46}}},
{ID: "[email protected]", Name: "react-is", Version: "16.8.6", Locations: []types.Location{{StartLine: 48, EndLine: 51}}},
{ID: "[email protected]", Name: "react", Version: "16.8.6", Locations: []types.Location{{StartLine: 53, EndLine: 61}}},
{ID: "[email protected]", Name: "redux", Version: "4.0.1", Locations: []types.Location{{StartLine: 63, EndLine: 69}}},
{ID: "[email protected]", Name: "scheduler", Version: "0.13.6", Locations: []types.Location{{StartLine: 71, EndLine: 77}}},
{ID: "[email protected]", Name: "symbol-observable", Version: "1.2.0", Locations: []types.Location{{StartLine: 79, EndLine: 82}}},
}
// ... and
// node test_deps_generator/index.js yarn.lock
yarnReactDeps = []types.Dependency{
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
}
// ... and
// yarn add -D mocha
// yarn list | grep -E -o "\S+@[^\^~]\S+" | awk -F@ 'NR>0 {printf("{\""$1"\", \""$2"\", \"\"},\n")}' | sort | uniq
// to get deps with locations from lock file use following commands:
// awk '/^\S+@[~^*]?(>= )?[0-9.]*/,/^$/{if($0=="") {print "--"prev} else { if(substr($0,1,2)!=" ") {print NR":"$0} else {print $0}} prev=NR}; END{print "--"prev}' | awk 'BEGIN {s=""}; {(substr($0,1,2)=="--") ? (s=s$0"\n") : (s=s$0)}; END { print s}' | sed -E 's/@([0-9~><*\^]|npm).*version:? "?/:/' | sed 's/ /:/' | sed 's/"//g'| awk 'match($0, /[[:digit:]]+$/) {print substr($0, RSTART, RLENGTH)":"$0 }' | awk -F":" '{print "{ID: \""$3"@"$4"\", Name: \""$3"\", Version: \""$4"\", Locations: []types.Location{{StartLine: "$2", EndLine: "$1"}}},"}'
yarnWithDev = []types.Library{
{ID: "[email protected]", Name: "ansi-colors", Version: "3.2.3", Locations: []types.Location{{StartLine: 5, EndLine: 8}}},
{ID: "[email protected]", Name: "ansi-regex", Version: "2.1.1", Locations: []types.Location{{StartLine: 10, EndLine: 13}}},
{ID: "[email protected]", Name: "ansi-regex", Version: "3.0.0", Locations: []types.Location{{StartLine: 15, EndLine: 18}}},
{ID: "[email protected]", Name: "ansi-regex", Version: "4.1.0", Locations: []types.Location{{StartLine: 20, EndLine: 23}}},
{ID: "[email protected]", Name: "ansi-styles", Version: "3.2.1", Locations: []types.Location{{StartLine: 25, EndLine: 30}}},
{ID: "[email protected]", Name: "argparse", Version: "1.0.10", Locations: []types.Location{{StartLine: 32, EndLine: 37}}},
{ID: "[email protected]", Name: "asap", Version: "2.0.6", Locations: []types.Location{{StartLine: 39, EndLine: 42}}},
{ID: "[email protected]", Name: "balanced-match", Version: "1.0.0", Locations: []types.Location{{StartLine: 44, EndLine: 47}}},
{ID: "[email protected]", Name: "brace-expansion", Version: "1.1.11", Locations: []types.Location{{StartLine: 49, EndLine: 55}}},
{ID: "[email protected]", Name: "browser-stdout", Version: "1.3.1", Locations: []types.Location{{StartLine: 57, EndLine: 60}}},
{ID: "[email protected]", Name: "camelcase", Version: "5.3.1", Locations: []types.Location{{StartLine: 62, EndLine: 65}}},
{ID: "[email protected]", Name: "chalk", Version: "2.4.2", Locations: []types.Location{{StartLine: 67, EndLine: 74}}},
{ID: "[email protected]", Name: "cliui", Version: "4.1.0", Locations: []types.Location{{StartLine: 76, EndLine: 83}}},
{ID: "[email protected]", Name: "code-point-at", Version: "1.1.0", Locations: []types.Location{{StartLine: 85, EndLine: 88}}},
{ID: "[email protected]", Name: "color-convert", Version: "1.9.3", Locations: []types.Location{{StartLine: 90, EndLine: 95}}},
{ID: "[email protected]", Name: "color-name", Version: "1.1.3", Locations: []types.Location{{StartLine: 97, EndLine: 100}}},
{ID: "[email protected]", Name: "concat-map", Version: "0.0.1", Locations: []types.Location{{StartLine: 102, EndLine: 105}}},
{ID: "[email protected]", Name: "cross-spawn", Version: "6.0.5", Locations: []types.Location{{StartLine: 107, EndLine: 116}}},
{ID: "[email protected]", Name: "debug", Version: "3.2.6", Locations: []types.Location{{StartLine: 118, EndLine: 123}}},
{ID: "[email protected]", Name: "decamelize", Version: "1.2.0", Locations: []types.Location{{StartLine: 125, EndLine: 128}}},
{ID: "[email protected]", Name: "define-properties", Version: "1.1.3", Locations: []types.Location{{StartLine: 130, EndLine: 135}}},
{ID: "[email protected]", Name: "diff", Version: "3.5.0", Locations: []types.Location{{StartLine: 137, EndLine: 140}}},
{ID: "[email protected]", Name: "emoji-regex", Version: "7.0.3", Locations: []types.Location{{StartLine: 142, EndLine: 145}}},
{ID: "[email protected]", Name: "end-of-stream", Version: "1.4.1", Locations: []types.Location{{StartLine: 147, EndLine: 152}}},
{ID: "[email protected]", Name: "es-abstract", Version: "1.13.0", Locations: []types.Location{{StartLine: 154, EndLine: 164}}},
{ID: "[email protected]", Name: "es-to-primitive", Version: "1.2.0", Locations: []types.Location{{StartLine: 166, EndLine: 173}}},
{ID: "[email protected]", Name: "escape-string-regexp", Version: "1.0.5", Locations: []types.Location{{StartLine: 175, EndLine: 178}}},
{ID: "[email protected]", Name: "esprima", Version: "4.0.1", Locations: []types.Location{{StartLine: 180, EndLine: 183}}},
{ID: "[email protected]", Name: "execa", Version: "1.0.0", Locations: []types.Location{{StartLine: 185, EndLine: 196}}},
{ID: "[email protected]", Name: "find-up", Version: "3.0.0", Locations: []types.Location{{StartLine: 198, EndLine: 203}}},
{ID: "[email protected]", Name: "flat", Version: "4.1.0", Locations: []types.Location{{StartLine: 205, EndLine: 210}}},
{ID: "[email protected]", Name: "fs.realpath", Version: "1.0.0", Locations: []types.Location{{StartLine: 212, EndLine: 215}}},
{ID: "[email protected]", Name: "function-bind", Version: "1.1.1", Locations: []types.Location{{StartLine: 217, EndLine: 220}}},
{ID: "[email protected]", Name: "get-caller-file", Version: "1.0.3", Locations: []types.Location{{StartLine: 222, EndLine: 225}}},
{ID: "[email protected]", Name: "get-caller-file", Version: "2.0.5", Locations: []types.Location{{StartLine: 227, EndLine: 230}}},
{ID: "[email protected]", Name: "get-stream", Version: "4.1.0", Locations: []types.Location{{StartLine: 232, EndLine: 237}}},
{ID: "[email protected]", Name: "glob", Version: "7.1.3", Locations: []types.Location{{StartLine: 239, EndLine: 249}}},
{ID: "[email protected]", Name: "growl", Version: "1.10.5", Locations: []types.Location{{StartLine: 251, EndLine: 254}}},
{ID: "[email protected]", Name: "has-flag", Version: "3.0.0", Locations: []types.Location{{StartLine: 256, EndLine: 259}}},
{ID: "[email protected]", Name: "has-symbols", Version: "1.0.0", Locations: []types.Location{{StartLine: 261, EndLine: 264}}},
{ID: "[email protected]", Name: "has", Version: "1.0.3", Locations: []types.Location{{StartLine: 266, EndLine: 271}}},
{ID: "[email protected]", Name: "he", Version: "1.2.0", Locations: []types.Location{{StartLine: 273, EndLine: 276}}},
{ID: "[email protected]", Name: "inflight", Version: "1.0.6", Locations: []types.Location{{StartLine: 278, EndLine: 284}}},
{ID: "[email protected]", Name: "inherits", Version: "2.0.3", Locations: []types.Location{{StartLine: 286, EndLine: 289}}},
{ID: "[email protected]", Name: "invert-kv", Version: "2.0.0", Locations: []types.Location{{StartLine: 291, EndLine: 294}}},
{ID: "[email protected]", Name: "is-buffer", Version: "2.0.3", Locations: []types.Location{{StartLine: 296, EndLine: 299}}},
{ID: "[email protected]", Name: "is-callable", Version: "1.1.4", Locations: []types.Location{{StartLine: 301, EndLine: 304}}},
{ID: "[email protected]", Name: "is-date-object", Version: "1.0.1", Locations: []types.Location{{StartLine: 306, EndLine: 309}}},
{ID: "[email protected]", Name: "is-fullwidth-code-point", Version: "1.0.0", Locations: []types.Location{{StartLine: 311, EndLine: 316}}},
{ID: "[email protected]", Name: "is-fullwidth-code-point", Version: "2.0.0", Locations: []types.Location{{StartLine: 318, EndLine: 321}}},
{ID: "[email protected]", Name: "is-regex", Version: "1.0.4", Locations: []types.Location{{StartLine: 323, EndLine: 328}}},
{ID: "[email protected]", Name: "is-stream", Version: "1.1.0", Locations: []types.Location{{StartLine: 330, EndLine: 333}}},
{ID: "[email protected]", Name: "is-symbol", Version: "1.0.2", Locations: []types.Location{{StartLine: 335, EndLine: 340}}},
{ID: "[email protected]", Name: "isexe", Version: "2.0.0", Locations: []types.Location{{StartLine: 342, EndLine: 345}}},
{ID: "[email protected]", Name: "jquery", Version: "3.4.1", Locations: []types.Location{{StartLine: 347, EndLine: 350}}},
{ID: "[email protected]", Name: "js-tokens", Version: "4.0.0", Locations: []types.Location{{StartLine: 352, EndLine: 355}}},
{ID: "[email protected]", Name: "js-yaml", Version: "3.13.1", Locations: []types.Location{{StartLine: 357, EndLine: 363}}},
{ID: "[email protected]", Name: "lcid", Version: "2.0.0", Locations: []types.Location{{StartLine: 365, EndLine: 370}}},
{ID: "[email protected]", Name: "locate-path", Version: "3.0.0", Locations: []types.Location{{StartLine: 372, EndLine: 378}}},
{ID: "[email protected]", Name: "lodash", Version: "4.17.11", Locations: []types.Location{{StartLine: 380, EndLine: 383}}},
{ID: "[email protected]", Name: "log-symbols", Version: "2.2.0", Locations: []types.Location{{StartLine: 385, EndLine: 390}}},
{ID: "[email protected]", Name: "loose-envify", Version: "1.4.0", Locations: []types.Location{{StartLine: 392, EndLine: 397}}},
{ID: "[email protected]", Name: "map-age-cleaner", Version: "0.1.3", Locations: []types.Location{{StartLine: 399, EndLine: 404}}},
{ID: "[email protected]", Name: "mem", Version: "4.3.0", Locations: []types.Location{{StartLine: 406, EndLine: 413}}},
{ID: "[email protected]", Name: "mimic-fn", Version: "2.1.0", Locations: []types.Location{{StartLine: 415, EndLine: 418}}},
{ID: "[email protected]", Name: "minimatch", Version: "3.0.4", Locations: []types.Location{{StartLine: 420, EndLine: 425}}},
{ID: "[email protected]", Name: "minimist", Version: "0.0.8", Locations: []types.Location{{StartLine: 427, EndLine: 430}}},
{ID: "[email protected]", Name: "mkdirp", Version: "0.5.1", Locations: []types.Location{{StartLine: 432, EndLine: 437}}},
{ID: "[email protected]", Name: "mocha", Version: "6.1.4", Locations: []types.Location{{StartLine: 439, EndLine: 466}}},
{ID: "[email protected]", Name: "ms", Version: "2.1.1", Locations: []types.Location{{StartLine: 468, EndLine: 471}}},
{ID: "[email protected]", Name: "nice-try", Version: "1.0.5", Locations: []types.Location{{StartLine: 473, EndLine: 476}}},
{ID: "[email protected]", Name: "node-environment-flags", Version: "1.0.5", Locations: []types.Location{{StartLine: 478, EndLine: 484}}},
{ID: "[email protected]", Name: "npm-run-path", Version: "2.0.2", Locations: []types.Location{{StartLine: 486, EndLine: 491}}},
{ID: "[email protected]", Name: "number-is-nan", Version: "1.0.1", Locations: []types.Location{{StartLine: 493, EndLine: 496}}},
{ID: "[email protected]", Name: "object-assign", Version: "4.1.1", Locations: []types.Location{{StartLine: 498, EndLine: 501}}},
{ID: "[email protected]", Name: "object-keys", Version: "1.1.1", Locations: []types.Location{{StartLine: 503, EndLine: 506}}},
{ID: "[email protected]", Name: "object.assign", Version: "4.1.0", Locations: []types.Location{{StartLine: 508, EndLine: 516}}},
{ID: "[email protected]", Name: "object.getownpropertydescriptors", Version: "2.0.3", Locations: []types.Location{{StartLine: 518, EndLine: 524}}},
{ID: "[email protected]", Name: "once", Version: "1.4.0", Locations: []types.Location{{StartLine: 526, EndLine: 531}}},
{ID: "[email protected]", Name: "os-locale", Version: "3.1.0", Locations: []types.Location{{StartLine: 533, EndLine: 540}}},
{ID: "[email protected]", Name: "p-defer", Version: "1.0.0", Locations: []types.Location{{StartLine: 542, EndLine: 545}}},
{ID: "[email protected]", Name: "p-finally", Version: "1.0.0", Locations: []types.Location{{StartLine: 547, EndLine: 550}}},
{ID: "[email protected]", Name: "p-is-promise", Version: "2.1.0", Locations: []types.Location{{StartLine: 552, EndLine: 555}}},
{ID: "[email protected]", Name: "p-limit", Version: "2.2.0", Locations: []types.Location{{StartLine: 557, EndLine: 562}}},
{ID: "[email protected]", Name: "p-locate", Version: "3.0.0", Locations: []types.Location{{StartLine: 564, EndLine: 569}}},
{ID: "[email protected]", Name: "p-try", Version: "2.2.0", Locations: []types.Location{{StartLine: 571, EndLine: 574}}},
{ID: "[email protected]", Name: "path-exists", Version: "3.0.0", Locations: []types.Location{{StartLine: 576, EndLine: 579}}},
{ID: "[email protected]", Name: "path-is-absolute", Version: "1.0.1", Locations: []types.Location{{StartLine: 581, EndLine: 584}}},
{ID: "[email protected]", Name: "path-key", Version: "2.0.1", Locations: []types.Location{{StartLine: 586, EndLine: 589}}},
{ID: "[email protected]", Name: "promise", Version: "8.0.3", Locations: []types.Location{{StartLine: 591, EndLine: 596}}},
{ID: "[email protected]", Name: "prop-types", Version: "15.7.2", Locations: []types.Location{{StartLine: 598, EndLine: 605}}},
{ID: "[email protected]", Name: "pump", Version: "3.0.0", Locations: []types.Location{{StartLine: 607, EndLine: 613}}},
{ID: "[email protected]", Name: "react-is", Version: "16.8.6", Locations: []types.Location{{StartLine: 615, EndLine: 618}}},
{ID: "[email protected]", Name: "react", Version: "16.8.6", Locations: []types.Location{{StartLine: 620, EndLine: 628}}},
{ID: "[email protected]", Name: "redux", Version: "4.0.1", Locations: []types.Location{{StartLine: 630, EndLine: 636}}},
{ID: "[email protected]", Name: "require-directory", Version: "2.1.1", Locations: []types.Location{{StartLine: 638, EndLine: 641}}},
{ID: "[email protected]", Name: "require-main-filename", Version: "1.0.1", Locations: []types.Location{{StartLine: 643, EndLine: 646}}},
{ID: "[email protected]", Name: "require-main-filename", Version: "2.0.0", Locations: []types.Location{{StartLine: 648, EndLine: 651}}},
{ID: "[email protected]", Name: "scheduler", Version: "0.13.6", Locations: []types.Location{{StartLine: 653, EndLine: 659}}},
{ID: "[email protected]", Name: "semver", Version: "5.7.0", Locations: []types.Location{{StartLine: 661, EndLine: 664}}},
{ID: "[email protected]", Name: "set-blocking", Version: "2.0.0", Locations: []types.Location{{StartLine: 666, EndLine: 669}}},
{ID: "[email protected]", Name: "shebang-command", Version: "1.2.0", Locations: []types.Location{{StartLine: 671, EndLine: 676}}},
{ID: "[email protected]", Name: "shebang-regex", Version: "1.0.0", Locations: []types.Location{{StartLine: 678, EndLine: 681}}},
{ID: "[email protected]", Name: "signal-exit", Version: "3.0.2", Locations: []types.Location{{StartLine: 683, EndLine: 686}}},
{ID: "[email protected]", Name: "sprintf-js", Version: "1.0.3", Locations: []types.Location{{StartLine: 688, EndLine: 691}}},
{ID: "[email protected]", Name: "string-width", Version: "1.0.2", Locations: []types.Location{{StartLine: 693, EndLine: 700}}},
{ID: "[email protected]", Name: "string-width", Version: "2.1.1", Locations: []types.Location{{StartLine: 702, EndLine: 708}}},
{ID: "[email protected]", Name: "string-width", Version: "3.1.0", Locations: []types.Location{{StartLine: 710, EndLine: 717}}},
{ID: "[email protected]", Name: "strip-ansi", Version: "3.0.1", Locations: []types.Location{{StartLine: 719, EndLine: 724}}},
{ID: "[email protected]", Name: "strip-ansi", Version: "4.0.0", Locations: []types.Location{{StartLine: 726, EndLine: 731}}},
{ID: "[email protected]", Name: "strip-ansi", Version: "5.2.0", Locations: []types.Location{{StartLine: 733, EndLine: 738}}},
{ID: "[email protected]", Name: "strip-eof", Version: "1.0.0", Locations: []types.Location{{StartLine: 740, EndLine: 743}}},
{ID: "[email protected]", Name: "strip-json-comments", Version: "2.0.1", Locations: []types.Location{{StartLine: 745, EndLine: 748}}},
{ID: "[email protected]", Name: "supports-color", Version: "6.0.0", Locations: []types.Location{{StartLine: 750, EndLine: 755}}},
{ID: "[email protected]", Name: "supports-color", Version: "5.5.0", Locations: []types.Location{{StartLine: 757, EndLine: 762}}},
{ID: "[email protected]", Name: "symbol-observable", Version: "1.2.0", Locations: []types.Location{{StartLine: 764, EndLine: 767}}},
{ID: "[email protected]", Name: "which-module", Version: "2.0.0", Locations: []types.Location{{StartLine: 769, EndLine: 772}}},
{ID: "[email protected]", Name: "which", Version: "1.3.1", Locations: []types.Location{{StartLine: 774, EndLine: 779}}},
{ID: "[email protected]", Name: "wide-align", Version: "1.1.3", Locations: []types.Location{{StartLine: 781, EndLine: 786}}},
{ID: "[email protected]", Name: "wrap-ansi", Version: "2.1.0", Locations: []types.Location{{StartLine: 788, EndLine: 794}}},
{ID: "[email protected]", Name: "wrappy", Version: "1.0.2", Locations: []types.Location{{StartLine: 796, EndLine: 799}}},
{ID: "[email protected]", Name: "y18n", Version: "4.0.0", Locations: []types.Location{{StartLine: 801, EndLine: 804}}},
{ID: "[email protected]", Name: "yargs-parser", Version: "13.0.0", Locations: []types.Location{{StartLine: 806, EndLine: 812}}},
{ID: "[email protected]", Name: "yargs-parser", Version: "11.1.1", Locations: []types.Location{{StartLine: 814, EndLine: 820}}},
{ID: "[email protected]", Name: "yargs-parser", Version: "13.1.0", Locations: []types.Location{{StartLine: 822, EndLine: 828}}},
{ID: "[email protected]", Name: "yargs-unparser", Version: "1.5.0", Locations: []types.Location{{StartLine: 830, EndLine: 837}}},
{ID: "[email protected]", Name: "yargs", Version: "13.2.2", Locations: []types.Location{{StartLine: 839, EndLine: 854}}},
{ID: "[email protected]", Name: "yargs", Version: "12.0.5", Locations: []types.Location{{StartLine: 856, EndLine: 872}}},
}
// ... and
// node test_deps_generator/index.js yarn.lock
yarnWithDevDeps = []types.Dependency{
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
}
// ... and
// yarn add lodash request chalk commander express async axios vue
// yarn list | grep -E -o "\S+@[^\^~]\S+" | awk -F@ 'NR>0 {printf("{\""$1"\", \""$2"\", \"\"},\n")}' | sort | uniq
// to get deps with locations from lock file use following commands:
// awk '/^\S+@[~^*]?(>= )?[0-9.]*/,/^$/{if($0=="") {print "--"prev} else { if(substr($0,1,2)!=" ") {print NR":"$0} else {print $0}} prev=NR}; END{print "--"prev}' | awk 'BEGIN {s=""}; {(substr($0,1,2)=="--") ? (s=s$0"\n") : (s=s$0)}; END { print s}' | sed -E 's/@([0-9~><*\^]|npm).*version:? "?/:/' | sed 's/ /:/' | sed 's/"//g'| awk 'match($0, /[[:digit:]]+$/) {print substr($0, RSTART, RLENGTH)":"$0 }' | awk -F":" '{print "{ID: \""$3"@"$4"\", Name: \""$3"\", Version: \""$4"\", Locations: []types.Location{{StartLine: "$2", EndLine: "$1"}}},"}'
yarnMany = []types.Library{
{ID: "[email protected]", Name: "accepts", Version: "1.3.7", Locations: []types.Location{{StartLine: 5, EndLine: 11}}},
{ID: "[email protected]", Name: "ajv", Version: "6.10.0", Locations: []types.Location{{StartLine: 13, EndLine: 21}}},
{ID: "[email protected]", Name: "ansi-colors", Version: "3.2.3", Locations: []types.Location{{StartLine: 23, EndLine: 26}}},
{ID: "[email protected]", Name: "ansi-regex", Version: "2.1.1", Locations: []types.Location{{StartLine: 28, EndLine: 31}}},
{ID: "[email protected]", Name: "ansi-regex", Version: "3.0.0", Locations: []types.Location{{StartLine: 33, EndLine: 36}}},
{ID: "[email protected]", Name: "ansi-regex", Version: "4.1.0", Locations: []types.Location{{StartLine: 38, EndLine: 41}}},
{ID: "[email protected]", Name: "ansi-styles", Version: "3.2.1", Locations: []types.Location{{StartLine: 43, EndLine: 48}}},
{ID: "[email protected]", Name: "argparse", Version: "1.0.10", Locations: []types.Location{{StartLine: 50, EndLine: 55}}},
{ID: "[email protected]", Name: "array-flatten", Version: "1.1.1", Locations: []types.Location{{StartLine: 57, EndLine: 60}}},
{ID: "[email protected]", Name: "asap", Version: "2.0.6", Locations: []types.Location{{StartLine: 62, EndLine: 65}}},
{ID: "[email protected]", Name: "asn1", Version: "0.2.4", Locations: []types.Location{{StartLine: 67, EndLine: 72}}},
{ID: "[email protected]", Name: "assert-plus", Version: "1.0.0", Locations: []types.Location{{StartLine: 74, EndLine: 77}}},
{ID: "[email protected]", Name: "async", Version: "2.6.2", Locations: []types.Location{{StartLine: 79, EndLine: 84}}},
{ID: "[email protected]", Name: "asynckit", Version: "0.4.0", Locations: []types.Location{{StartLine: 86, EndLine: 89}}},
{ID: "[email protected]", Name: "aws-sign2", Version: "0.7.0", Locations: []types.Location{{StartLine: 91, EndLine: 94}}},
{ID: "[email protected]", Name: "aws4", Version: "1.8.0", Locations: []types.Location{{StartLine: 96, EndLine: 99}}},
{ID: "[email protected]", Name: "axios", Version: "0.18.0", Locations: []types.Location{{StartLine: 101, EndLine: 107}}},
{ID: "[email protected]", Name: "balanced-match", Version: "1.0.0", Locations: []types.Location{{StartLine: 109, EndLine: 112}}},
{ID: "[email protected]", Name: "bcrypt-pbkdf", Version: "1.0.2", Locations: []types.Location{{StartLine: 114, EndLine: 119}}},
{ID: "[email protected]", Name: "body-parser", Version: "1.18.3", Locations: []types.Location{{StartLine: 121, EndLine: 135}}},
{ID: "[email protected]", Name: "brace-expansion", Version: "1.1.11", Locations: []types.Location{{StartLine: 137, EndLine: 143}}},
{ID: "[email protected]", Name: "browser-stdout", Version: "1.3.1", Locations: []types.Location{{StartLine: 145, EndLine: 148}}},
{ID: "[email protected]", Name: "bytes", Version: "3.0.0", Locations: []types.Location{{StartLine: 150, EndLine: 153}}},
{ID: "[email protected]", Name: "camelcase", Version: "5.3.1", Locations: []types.Location{{StartLine: 155, EndLine: 158}}},
{ID: "[email protected]", Name: "caseless", Version: "0.12.0", Locations: []types.Location{{StartLine: 160, EndLine: 163}}},
{ID: "[email protected]", Name: "chalk", Version: "2.4.2", Locations: []types.Location{{StartLine: 165, EndLine: 172}}},
{ID: "[email protected]", Name: "cliui", Version: "4.1.0", Locations: []types.Location{{StartLine: 174, EndLine: 181}}},
{ID: "[email protected]", Name: "code-point-at", Version: "1.1.0", Locations: []types.Location{{StartLine: 183, EndLine: 186}}},
{ID: "[email protected]", Name: "color-convert", Version: "1.9.3", Locations: []types.Location{{StartLine: 188, EndLine: 193}}},
{ID: "[email protected]", Name: "color-name", Version: "1.1.3", Locations: []types.Location{{StartLine: 195, EndLine: 198}}},
{ID: "[email protected]", Name: "combined-stream", Version: "1.0.8", Locations: []types.Location{{StartLine: 200, EndLine: 205}}},
{ID: "[email protected]", Name: "commander", Version: "2.20.0", Locations: []types.Location{{StartLine: 207, EndLine: 210}}},
{ID: "[email protected]", Name: "concat-map", Version: "0.0.1", Locations: []types.Location{{StartLine: 212, EndLine: 215}}},
{ID: "[email protected]", Name: "content-disposition", Version: "0.5.2", Locations: []types.Location{{StartLine: 217, EndLine: 220}}},
{ID: "[email protected]", Name: "content-type", Version: "1.0.4", Locations: []types.Location{{StartLine: 222, EndLine: 225}}},
{ID: "[email protected]", Name: "cookie-signature", Version: "1.0.6", Locations: []types.Location{{StartLine: 227, EndLine: 230}}},
{ID: "[email protected]", Name: "cookie", Version: "0.3.1", Locations: []types.Location{{StartLine: 232, EndLine: 235}}},
{ID: "[email protected]", Name: "core-util-is", Version: "1.0.2", Locations: []types.Location{{StartLine: 237, EndLine: 240}}},
{ID: "[email protected]", Name: "cross-spawn", Version: "6.0.5", Locations: []types.Location{{StartLine: 242, EndLine: 251}}},
{ID: "[email protected]", Name: "dashdash", Version: "1.14.1", Locations: []types.Location{{StartLine: 253, EndLine: 258}}},
{ID: "[email protected]", Name: "debug", Version: "2.6.9", Locations: []types.Location{{StartLine: 260, EndLine: 265}}},
{ID: "[email protected]", Name: "debug", Version: "3.2.6", Locations: []types.Location{{StartLine: 267, EndLine: 272}}},
{ID: "[email protected]", Name: "decamelize", Version: "1.2.0", Locations: []types.Location{{StartLine: 274, EndLine: 277}}},
{ID: "[email protected]", Name: "define-properties", Version: "1.1.3", Locations: []types.Location{{StartLine: 279, EndLine: 284}}},
{ID: "[email protected]", Name: "delayed-stream", Version: "1.0.0", Locations: []types.Location{{StartLine: 286, EndLine: 289}}},
{ID: "[email protected]", Name: "depd", Version: "1.1.2", Locations: []types.Location{{StartLine: 291, EndLine: 294}}},
{ID: "[email protected]", Name: "destroy", Version: "1.0.4", Locations: []types.Location{{StartLine: 296, EndLine: 299}}},
{ID: "[email protected]", Name: "diff", Version: "3.5.0", Locations: []types.Location{{StartLine: 301, EndLine: 304}}},
{ID: "[email protected]", Name: "ecc-jsbn", Version: "0.1.2", Locations: []types.Location{{StartLine: 306, EndLine: 312}}},
{ID: "[email protected]", Name: "ee-first", Version: "1.1.1", Locations: []types.Location{{StartLine: 314, EndLine: 317}}},
{ID: "[email protected]", Name: "emoji-regex", Version: "7.0.3", Locations: []types.Location{{StartLine: 319, EndLine: 322}}},
{ID: "[email protected]", Name: "encodeurl", Version: "1.0.2", Locations: []types.Location{{StartLine: 324, EndLine: 327}}},
{ID: "[email protected]", Name: "end-of-stream", Version: "1.4.1", Locations: []types.Location{{StartLine: 329, EndLine: 334}}},
{ID: "[email protected]", Name: "es-abstract", Version: "1.13.0", Locations: []types.Location{{StartLine: 336, EndLine: 346}}},
{ID: "[email protected]", Name: "es-to-primitive", Version: "1.2.0", Locations: []types.Location{{StartLine: 348, EndLine: 355}}},
{ID: "[email protected]", Name: "escape-html", Version: "1.0.3", Locations: []types.Location{{StartLine: 357, EndLine: 360}}},
{ID: "[email protected]", Name: "escape-string-regexp", Version: "1.0.5", Locations: []types.Location{{StartLine: 362, EndLine: 365}}},
{ID: "[email protected]", Name: "esprima", Version: "4.0.1", Locations: []types.Location{{StartLine: 367, EndLine: 370}}},
{ID: "[email protected]", Name: "etag", Version: "1.8.1", Locations: []types.Location{{StartLine: 372, EndLine: 375}}},
{ID: "[email protected]", Name: "execa", Version: "1.0.0", Locations: []types.Location{{StartLine: 377, EndLine: 388}}},
{ID: "[email protected]", Name: "express", Version: "4.16.4", Locations: []types.Location{{StartLine: 390, EndLine: 424}}},
{ID: "[email protected]", Name: "extend", Version: "3.0.2", Locations: []types.Location{{StartLine: 426, EndLine: 429}}},
{ID: "[email protected]", Name: "extsprintf", Version: "1.3.0", Locations: []types.Location{{StartLine: 431, EndLine: 434}}},
{ID: "[email protected]", Name: "extsprintf", Version: "1.4.0", Locations: []types.Location{{StartLine: 436, EndLine: 439}}},
{ID: "[email protected]", Name: "fast-deep-equal", Version: "2.0.1", Locations: []types.Location{{StartLine: 441, EndLine: 444}}},
{ID: "[email protected]", Name: "fast-json-stable-stringify", Version: "2.0.0", Locations: []types.Location{{StartLine: 446, EndLine: 449}}},
{ID: "[email protected]", Name: "finalhandler", Version: "1.1.1", Locations: []types.Location{{StartLine: 451, EndLine: 462}}},
{ID: "[email protected]", Name: "find-up", Version: "3.0.0", Locations: []types.Location{{StartLine: 464, EndLine: 469}}},
{ID: "[email protected]", Name: "flat", Version: "4.1.0", Locations: []types.Location{{StartLine: 471, EndLine: 476}}},
{ID: "[email protected]", Name: "follow-redirects", Version: "1.7.0", Locations: []types.Location{{StartLine: 478, EndLine: 483}}},
{ID: "[email protected]", Name: "forever-agent", Version: "0.6.1", Locations: []types.Location{{StartLine: 485, EndLine: 488}}},
{ID: "[email protected]", Name: "form-data", Version: "2.3.3", Locations: []types.Location{{StartLine: 490, EndLine: 497}}},
{ID: "[email protected]", Name: "forwarded", Version: "0.1.2", Locations: []types.Location{{StartLine: 499, EndLine: 502}}},
{ID: "[email protected]", Name: "fresh", Version: "0.5.2", Locations: []types.Location{{StartLine: 504, EndLine: 507}}},
{ID: "[email protected]", Name: "fs.realpath", Version: "1.0.0", Locations: []types.Location{{StartLine: 509, EndLine: 512}}},
{ID: "[email protected]", Name: "function-bind", Version: "1.1.1", Locations: []types.Location{{StartLine: 514, EndLine: 517}}},
{ID: "[email protected]", Name: "get-caller-file", Version: "1.0.3", Locations: []types.Location{{StartLine: 519, EndLine: 522}}},
{ID: "[email protected]", Name: "get-caller-file", Version: "2.0.5", Locations: []types.Location{{StartLine: 524, EndLine: 527}}},
{ID: "[email protected]", Name: "get-stream", Version: "4.1.0", Locations: []types.Location{{StartLine: 529, EndLine: 534}}},
{ID: "[email protected]", Name: "getpass", Version: "0.1.7", Locations: []types.Location{{StartLine: 536, EndLine: 541}}},
{ID: "[email protected]", Name: "glob", Version: "7.1.3", Locations: []types.Location{{StartLine: 543, EndLine: 553}}},
{ID: "[email protected]", Name: "growl", Version: "1.10.5", Locations: []types.Location{{StartLine: 555, EndLine: 558}}},
{ID: "[email protected]", Name: "har-schema", Version: "2.0.0", Locations: []types.Location{{StartLine: 560, EndLine: 563}}},
{ID: "[email protected]", Name: "har-validator", Version: "5.1.3", Locations: []types.Location{{StartLine: 565, EndLine: 571}}},
{ID: "[email protected]", Name: "has-flag", Version: "3.0.0", Locations: []types.Location{{StartLine: 573, EndLine: 576}}},
{ID: "[email protected]", Name: "has-symbols", Version: "1.0.0", Locations: []types.Location{{StartLine: 578, EndLine: 581}}},
{ID: "[email protected]", Name: "has", Version: "1.0.3", Locations: []types.Location{{StartLine: 583, EndLine: 588}}},
{ID: "[email protected]", Name: "he", Version: "1.2.0", Locations: []types.Location{{StartLine: 590, EndLine: 593}}},
{ID: "[email protected]", Name: "http-errors", Version: "1.6.3", Locations: []types.Location{{StartLine: 595, EndLine: 603}}},
{ID: "[email protected]", Name: "http-signature", Version: "1.2.0", Locations: []types.Location{{StartLine: 605, EndLine: 612}}},
{ID: "[email protected]", Name: "iconv-lite", Version: "0.4.23", Locations: []types.Location{{StartLine: 614, EndLine: 619}}},
{ID: "[email protected]", Name: "inflight", Version: "1.0.6", Locations: []types.Location{{StartLine: 621, EndLine: 627}}},
{ID: "[email protected]", Name: "inherits", Version: "2.0.3", Locations: []types.Location{{StartLine: 629, EndLine: 632}}},
{ID: "[email protected]", Name: "invert-kv", Version: "2.0.0", Locations: []types.Location{{StartLine: 634, EndLine: 637}}},
{ID: "[email protected]", Name: "ipaddr.js", Version: "1.9.0", Locations: []types.Location{{StartLine: 639, EndLine: 642}}},
{ID: "[email protected]", Name: "is-buffer", Version: "1.1.6", Locations: []types.Location{{StartLine: 644, EndLine: 647}}},
{ID: "[email protected]", Name: "is-buffer", Version: "2.0.3", Locations: []types.Location{{StartLine: 649, EndLine: 652}}},
{ID: "[email protected]", Name: "is-callable", Version: "1.1.4", Locations: []types.Location{{StartLine: 654, EndLine: 657}}},
{ID: "[email protected]", Name: "is-date-object", Version: "1.0.1", Locations: []types.Location{{StartLine: 659, EndLine: 662}}},
{ID: "[email protected]", Name: "is-fullwidth-code-point", Version: "1.0.0", Locations: []types.Location{{StartLine: 664, EndLine: 669}}},
{ID: "[email protected]", Name: "is-fullwidth-code-point", Version: "2.0.0", Locations: []types.Location{{StartLine: 671, EndLine: 674}}},
{ID: "[email protected]", Name: "is-regex", Version: "1.0.4", Locations: []types.Location{{StartLine: 676, EndLine: 681}}},
{ID: "[email protected]", Name: "is-stream", Version: "1.1.0", Locations: []types.Location{{StartLine: 683, EndLine: 686}}},
{ID: "[email protected]", Name: "is-symbol", Version: "1.0.2", Locations: []types.Location{{StartLine: 688, EndLine: 693}}},
{ID: "[email protected]", Name: "is-typedarray", Version: "1.0.0", Locations: []types.Location{{StartLine: 695, EndLine: 698}}},
{ID: "[email protected]", Name: "isexe", Version: "2.0.0", Locations: []types.Location{{StartLine: 700, EndLine: 703}}},
{ID: "[email protected]", Name: "isstream", Version: "0.1.2", Locations: []types.Location{{StartLine: 705, EndLine: 708}}},
{ID: "[email protected]", Name: "jquery", Version: "3.4.1", Locations: []types.Location{{StartLine: 710, EndLine: 713}}},
{ID: "[email protected]", Name: "js-tokens", Version: "4.0.0", Locations: []types.Location{{StartLine: 715, EndLine: 718}}},
{ID: "[email protected]", Name: "js-yaml", Version: "3.13.1", Locations: []types.Location{{StartLine: 720, EndLine: 726}}},
{ID: "[email protected]", Name: "jsbn", Version: "0.1.1", Locations: []types.Location{{StartLine: 728, EndLine: 731}}},
{ID: "[email protected]", Name: "json-schema-traverse", Version: "0.4.1", Locations: []types.Location{{StartLine: 733, EndLine: 736}}},
{ID: "[email protected]", Name: "json-schema", Version: "0.2.3", Locations: []types.Location{{StartLine: 738, EndLine: 741}}},
{ID: "[email protected]", Name: "json-stringify-safe", Version: "5.0.1", Locations: []types.Location{{StartLine: 743, EndLine: 746}}},
{ID: "[email protected]", Name: "jsprim", Version: "1.4.1", Locations: []types.Location{{StartLine: 748, EndLine: 756}}},
{ID: "[email protected]", Name: "lcid", Version: "2.0.0", Locations: []types.Location{{StartLine: 758, EndLine: 763}}},
{ID: "[email protected]", Name: "locate-path", Version: "3.0.0", Locations: []types.Location{{StartLine: 765, EndLine: 771}}},
{ID: "[email protected]", Name: "lodash", Version: "4.17.11", Locations: []types.Location{{StartLine: 773, EndLine: 776}}},
{ID: "[email protected]", Name: "log-symbols", Version: "2.2.0", Locations: []types.Location{{StartLine: 778, EndLine: 783}}},
{ID: "[email protected]", Name: "loose-envify", Version: "1.4.0", Locations: []types.Location{{StartLine: 785, EndLine: 790}}},
{ID: "[email protected]", Name: "map-age-cleaner", Version: "0.1.3", Locations: []types.Location{{StartLine: 792, EndLine: 797}}},
{ID: "[email protected]", Name: "media-typer", Version: "0.3.0", Locations: []types.Location{{StartLine: 799, EndLine: 802}}},
{ID: "[email protected]", Name: "mem", Version: "4.3.0", Locations: []types.Location{{StartLine: 804, EndLine: 811}}},
{ID: "[email protected]", Name: "merge-descriptors", Version: "1.0.1", Locations: []types.Location{{StartLine: 813, EndLine: 816}}},
{ID: "[email protected]", Name: "methods", Version: "1.1.2", Locations: []types.Location{{StartLine: 818, EndLine: 821}}},
{ID: "[email protected]", Name: "mime-db", Version: "1.40.0", Locations: []types.Location{{StartLine: 823, EndLine: 826}}},
{ID: "[email protected]", Name: "mime-types", Version: "2.1.24", Locations: []types.Location{{StartLine: 828, EndLine: 833}}},
{ID: "[email protected]", Name: "mime", Version: "1.4.1", Locations: []types.Location{{StartLine: 835, EndLine: 838}}},
{ID: "[email protected]", Name: "mimic-fn", Version: "2.1.0", Locations: []types.Location{{StartLine: 840, EndLine: 843}}},
{ID: "[email protected]", Name: "minimatch", Version: "3.0.4", Locations: []types.Location{{StartLine: 845, EndLine: 850}}},
{ID: "[email protected]", Name: "minimist", Version: "0.0.8", Locations: []types.Location{{StartLine: 852, EndLine: 855}}},
{ID: "[email protected]", Name: "mkdirp", Version: "0.5.1", Locations: []types.Location{{StartLine: 857, EndLine: 862}}},
{ID: "[email protected]", Name: "mocha", Version: "6.1.4", Locations: []types.Location{{StartLine: 864, EndLine: 891}}},
{ID: "[email protected]", Name: "ms", Version: "2.0.0", Locations: []types.Location{{StartLine: 893, EndLine: 896}}},
{ID: "[email protected]", Name: "ms", Version: "2.1.1", Locations: []types.Location{{StartLine: 898, EndLine: 901}}},
{ID: "[email protected]", Name: "negotiator", Version: "0.6.2", Locations: []types.Location{{StartLine: 903, EndLine: 906}}},
{ID: "[email protected]", Name: "nice-try", Version: "1.0.5", Locations: []types.Location{{StartLine: 908, EndLine: 911}}},
{ID: "[email protected]", Name: "node-environment-flags", Version: "1.0.5", Locations: []types.Location{{StartLine: 913, EndLine: 919}}},
{ID: "[email protected]", Name: "npm-run-path", Version: "2.0.2", Locations: []types.Location{{StartLine: 921, EndLine: 926}}},
{ID: "[email protected]", Name: "number-is-nan", Version: "1.0.1", Locations: []types.Location{{StartLine: 928, EndLine: 931}}},
{ID: "[email protected]", Name: "oauth-sign", Version: "0.9.0", Locations: []types.Location{{StartLine: 933, EndLine: 936}}},
{ID: "[email protected]", Name: "object-assign", Version: "4.1.1", Locations: []types.Location{{StartLine: 938, EndLine: 941}}},
{ID: "[email protected]", Name: "object-keys", Version: "1.1.1", Locations: []types.Location{{StartLine: 943, EndLine: 946}}},
{ID: "[email protected]", Name: "object.assign", Version: "4.1.0", Locations: []types.Location{{StartLine: 948, EndLine: 956}}},
{ID: "[email protected]", Name: "object.getownpropertydescriptors", Version: "2.0.3", Locations: []types.Location{{StartLine: 958, EndLine: 964}}},
{ID: "[email protected]", Name: "on-finished", Version: "2.3.0", Locations: []types.Location{{StartLine: 966, EndLine: 971}}},
{ID: "[email protected]", Name: "once", Version: "1.4.0", Locations: []types.Location{{StartLine: 973, EndLine: 978}}},
{ID: "[email protected]", Name: "os-locale", Version: "3.1.0", Locations: []types.Location{{StartLine: 980, EndLine: 987}}},
{ID: "[email protected]", Name: "p-defer", Version: "1.0.0", Locations: []types.Location{{StartLine: 989, EndLine: 992}}},
{ID: "[email protected]", Name: "p-finally", Version: "1.0.0", Locations: []types.Location{{StartLine: 994, EndLine: 997}}},
{ID: "[email protected]", Name: "p-is-promise", Version: "2.1.0", Locations: []types.Location{{StartLine: 999, EndLine: 1002}}},
{ID: "[email protected]", Name: "p-limit", Version: "2.2.0", Locations: []types.Location{{StartLine: 1004, EndLine: 1009}}},
{ID: "[email protected]", Name: "p-locate", Version: "3.0.0", Locations: []types.Location{{StartLine: 1011, EndLine: 1016}}},
{ID: "[email protected]", Name: "p-try", Version: "2.2.0", Locations: []types.Location{{StartLine: 1018, EndLine: 1021}}},
{ID: "[email protected]", Name: "parseurl", Version: "1.3.3", Locations: []types.Location{{StartLine: 1023, EndLine: 1026}}},
{ID: "[email protected]", Name: "path-exists", Version: "3.0.0", Locations: []types.Location{{StartLine: 1028, EndLine: 1031}}},
{ID: "[email protected]", Name: "path-is-absolute", Version: "1.0.1", Locations: []types.Location{{StartLine: 1033, EndLine: 1036}}},
{ID: "[email protected]", Name: "path-key", Version: "2.0.1", Locations: []types.Location{{StartLine: 1038, EndLine: 1041}}},
{ID: "[email protected]", Name: "path-to-regexp", Version: "0.1.7", Locations: []types.Location{{StartLine: 1043, EndLine: 1046}}},
{ID: "[email protected]", Name: "performance-now", Version: "2.1.0", Locations: []types.Location{{StartLine: 1048, EndLine: 1051}}},
{ID: "[email protected]", Name: "promise", Version: "8.0.3", Locations: []types.Location{{StartLine: 1053, EndLine: 1058}}},
{ID: "[email protected]", Name: "prop-types", Version: "15.7.2", Locations: []types.Location{{StartLine: 1060, EndLine: 1067}}},
{ID: "[email protected]", Name: "proxy-addr", Version: "2.0.5", Locations: []types.Location{{StartLine: 1069, EndLine: 1075}}},
{ID: "[email protected]", Name: "psl", Version: "1.1.31", Locations: []types.Location{{StartLine: 1077, EndLine: 1080}}},
{ID: "[email protected]", Name: "pump", Version: "3.0.0", Locations: []types.Location{{StartLine: 1082, EndLine: 1088}}},
{ID: "[email protected]", Name: "punycode", Version: "1.4.1", Locations: []types.Location{{StartLine: 1090, EndLine: 1093}}},
{ID: "[email protected]", Name: "punycode", Version: "2.1.1", Locations: []types.Location{{StartLine: 1095, EndLine: 1098}}},
{ID: "[email protected]", Name: "qs", Version: "6.5.2", Locations: []types.Location{{StartLine: 1100, EndLine: 1103}}},
{ID: "[email protected]", Name: "range-parser", Version: "1.2.1", Locations: []types.Location{{StartLine: 1105, EndLine: 1108}}},
{ID: "[email protected]", Name: "raw-body", Version: "2.3.3", Locations: []types.Location{{StartLine: 1110, EndLine: 1118}}},
{ID: "[email protected]", Name: "react-is", Version: "16.8.6", Locations: []types.Location{{StartLine: 1120, EndLine: 1123}}},
{ID: "[email protected]", Name: "react", Version: "16.8.6", Locations: []types.Location{{StartLine: 1125, EndLine: 1133}}},
{ID: "[email protected]", Name: "redux", Version: "4.0.1", Locations: []types.Location{{StartLine: 1135, EndLine: 1141}}},
{ID: "[email protected]", Name: "request", Version: "2.88.0", Locations: []types.Location{{StartLine: 1143, EndLine: 1167}}},
{ID: "[email protected]", Name: "require-directory", Version: "2.1.1", Locations: []types.Location{{StartLine: 1169, EndLine: 1172}}},
{ID: "[email protected]", Name: "require-main-filename", Version: "1.0.1", Locations: []types.Location{{StartLine: 1174, EndLine: 1177}}},
{ID: "[email protected]", Name: "require-main-filename", Version: "2.0.0", Locations: []types.Location{{StartLine: 1179, EndLine: 1182}}},
{ID: "[email protected]", Name: "safe-buffer", Version: "5.1.2", Locations: []types.Location{{StartLine: 1184, EndLine: 1187}}},
{ID: "[email protected]", Name: "safer-buffer", Version: "2.1.2", Locations: []types.Location{{StartLine: 1189, EndLine: 1192}}},
{ID: "[email protected]", Name: "scheduler", Version: "0.13.6", Locations: []types.Location{{StartLine: 1194, EndLine: 1200}}},
{ID: "[email protected]", Name: "semver", Version: "5.7.0", Locations: []types.Location{{StartLine: 1202, EndLine: 1205}}},
{ID: "[email protected]", Name: "send", Version: "0.16.2", Locations: []types.Location{{StartLine: 1207, EndLine: 1224}}},
{ID: "[email protected]", Name: "serve-static", Version: "1.13.2", Locations: []types.Location{{StartLine: 1226, EndLine: 1234}}},
{ID: "[email protected]", Name: "set-blocking", Version: "2.0.0", Locations: []types.Location{{StartLine: 1236, EndLine: 1239}}},
{ID: "[email protected]", Name: "setprototypeof", Version: "1.1.0", Locations: []types.Location{{StartLine: 1241, EndLine: 1244}}},
{ID: "[email protected]", Name: "shebang-command", Version: "1.2.0", Locations: []types.Location{{StartLine: 1246, EndLine: 1251}}},
{ID: "[email protected]", Name: "shebang-regex", Version: "1.0.0", Locations: []types.Location{{StartLine: 1253, EndLine: 1256}}},
{ID: "[email protected]", Name: "signal-exit", Version: "3.0.2", Locations: []types.Location{{StartLine: 1258, EndLine: 1261}}},
{ID: "[email protected]", Name: "sprintf-js", Version: "1.0.3", Locations: []types.Location{{StartLine: 1263, EndLine: 1266}}},
{ID: "[email protected]", Name: "sshpk", Version: "1.16.1", Locations: []types.Location{{StartLine: 1268, EndLine: 1281}}},
{ID: "[email protected]", Name: "statuses", Version: "1.5.0", Locations: []types.Location{{StartLine: 1283, EndLine: 1286}}},
{ID: "[email protected]", Name: "statuses", Version: "1.4.0", Locations: []types.Location{{StartLine: 1288, EndLine: 1291}}},
{ID: "[email protected]", Name: "string-width", Version: "1.0.2", Locations: []types.Location{{StartLine: 1293, EndLine: 1300}}},
{ID: "[email protected]", Name: "string-width", Version: "2.1.1", Locations: []types.Location{{StartLine: 1302, EndLine: 1308}}},
{ID: "[email protected]", Name: "string-width", Version: "3.1.0", Locations: []types.Location{{StartLine: 1310, EndLine: 1317}}},
{ID: "[email protected]", Name: "strip-ansi", Version: "3.0.1", Locations: []types.Location{{StartLine: 1319, EndLine: 1324}}},
{ID: "[email protected]", Name: "strip-ansi", Version: "4.0.0", Locations: []types.Location{{StartLine: 1326, EndLine: 1331}}},
{ID: "[email protected]", Name: "strip-ansi", Version: "5.2.0", Locations: []types.Location{{StartLine: 1333, EndLine: 1338}}},
{ID: "[email protected]", Name: "strip-eof", Version: "1.0.0", Locations: []types.Location{{StartLine: 1340, EndLine: 1343}}},
{ID: "[email protected]", Name: "strip-json-comments", Version: "2.0.1", Locations: []types.Location{{StartLine: 1345, EndLine: 1348}}},
{ID: "[email protected]", Name: "supports-color", Version: "6.0.0", Locations: []types.Location{{StartLine: 1350, EndLine: 1355}}},
{ID: "[email protected]", Name: "supports-color", Version: "5.5.0", Locations: []types.Location{{StartLine: 1357, EndLine: 1362}}},
{ID: "[email protected]", Name: "symbol-observable", Version: "1.2.0", Locations: []types.Location{{StartLine: 1364, EndLine: 1367}}},
{ID: "[email protected]", Name: "tough-cookie", Version: "2.4.3", Locations: []types.Location{{StartLine: 1369, EndLine: 1375}}},
{ID: "[email protected]", Name: "tunnel-agent", Version: "0.6.0", Locations: []types.Location{{StartLine: 1377, EndLine: 1382}}},
{ID: "[email protected]", Name: "tweetnacl", Version: "0.14.5", Locations: []types.Location{{StartLine: 1384, EndLine: 1387}}},
{ID: "[email protected]", Name: "type-is", Version: "1.6.18", Locations: []types.Location{{StartLine: 1389, EndLine: 1395}}},
{ID: "[email protected]", Name: "unpipe", Version: "1.0.0", Locations: []types.Location{{StartLine: 1397, EndLine: 1400}}},
{ID: "[email protected]", Name: "uri-js", Version: "4.2.2", Locations: []types.Location{{StartLine: 1402, EndLine: 1407}}},
{ID: "[email protected]", Name: "utils-merge", Version: "1.0.1", Locations: []types.Location{{StartLine: 1409, EndLine: 1412}}},
{ID: "[email protected]", Name: "uuid", Version: "3.3.2", Locations: []types.Location{{StartLine: 1414, EndLine: 1417}}},
{ID: "[email protected]", Name: "vary", Version: "1.1.2", Locations: []types.Location{{StartLine: 1419, EndLine: 1422}}},
{ID: "[email protected]", Name: "verror", Version: "1.10.0", Locations: []types.Location{{StartLine: 1424, EndLine: 1431}}},
{ID: "[email protected]", Name: "vue", Version: "2.6.10", Locations: []types.Location{{StartLine: 1433, EndLine: 1436}}},
{ID: "[email protected]", Name: "which-module", Version: "2.0.0", Locations: []types.Location{{StartLine: 1438, EndLine: 1441}}},
{ID: "[email protected]", Name: "which", Version: "1.3.1", Locations: []types.Location{{StartLine: 1443, EndLine: 1448}}},
{ID: "[email protected]", Name: "wide-align", Version: "1.1.3", Locations: []types.Location{{StartLine: 1450, EndLine: 1455}}},
{ID: "[email protected]", Name: "wrap-ansi", Version: "2.1.0", Locations: []types.Location{{StartLine: 1457, EndLine: 1463}}},
{ID: "[email protected]", Name: "wrappy", Version: "1.0.2", Locations: []types.Location{{StartLine: 1465, EndLine: 1468}}},
{ID: "[email protected]", Name: "y18n", Version: "4.0.0", Locations: []types.Location{{StartLine: 1470, EndLine: 1473}}},
{ID: "[email protected]", Name: "yargs-parser", Version: "13.0.0", Locations: []types.Location{{StartLine: 1475, EndLine: 1481}}},
{ID: "[email protected]", Name: "yargs-parser", Version: "11.1.1", Locations: []types.Location{{StartLine: 1483, EndLine: 1489}}},
{ID: "[email protected]", Name: "yargs-parser", Version: "13.1.0", Locations: []types.Location{{StartLine: 1491, EndLine: 1497}}},
{ID: "[email protected]", Name: "yargs-unparser", Version: "1.5.0", Locations: []types.Location{{StartLine: 1499, EndLine: 1506}}},
{ID: "[email protected]", Name: "yargs", Version: "13.2.2", Locations: []types.Location{{StartLine: 1508, EndLine: 1523}}},
{ID: "[email protected]", Name: "yargs", Version: "12.0.5", Locations: []types.Location{{StartLine: 1525, EndLine: 1541}}},
}
// ... and
// node test_deps_generator/index.js yarn.lock
yarnManyDeps = []types.Dependency{
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
}
// yarn list | grep -E -o "\S+@[^\^~]\S+" | awk -F@ 'NR>0 {printf("{\""$1"\", \""$2"\", \"\"},\n")}' | sort | uniq
// to get deps with locations from lock file use following commands:
// awk '/^\S+@[~^*]?(>= )?[0-9.]*/,/^$/{if($0=="") {print "--"prev} else { if(substr($0,1,2)!=" ") {print NR":"$0} else {print $0}} prev=NR}; END{print "--"prev}' | awk 'BEGIN {s=""}; {(substr($0,1,2)=="--") ? (s=s$0"\n") : (s=s$0)}; END { print s}' | sed -E 's/@([0-9~><*\^]|npm).*version:? "?/:/' | sed 's/ /:/' | sed 's/"//g'| awk 'match($0, /[[:digit:]]+$/) {print substr($0, RSTART, RLENGTH)":"$0 }' | awk -F":" '{print "{ID: \""$3"@"$4"\", Name: \""$3"\", Version: \""$4"\", Locations: []types.Location{{StartLine: "$2", EndLine: "$1"}}},"}'
yarnRealWorld = []types.Library{
{ID: "@babel/[email protected]", Name: "@babel/code-frame", Version: "7.0.0", Locations: []types.Location{{StartLine: 5, EndLine: 10}}},
{ID: "@babel/[email protected]", Name: "@babel/code-frame", Version: "7.0.0-beta.44", Locations: []types.Location{{StartLine: 12, EndLine: 17}}},
{ID: "@babel/[email protected]", Name: "@babel/core", Version: "7.1.0", Locations: []types.Location{{StartLine: 19, EndLine: 37}}},
{ID: "@babel/[email protected]", Name: "@babel/core", Version: "7.4.4", Locations: []types.Location{{StartLine: 39, EndLine: 57}}},
{ID: "@babel/[email protected]", Name: "@babel/generator", Version: "7.0.0-beta.44", Locations: []types.Location{{StartLine: 59, EndLine: 68}}},
{ID: "@babel/[email protected]", Name: "@babel/generator", Version: "7.4.4", Locations: []types.Location{{StartLine: 70, EndLine: 79}}},
{ID: "@babel/[email protected]", Name: "@babel/helper-annotate-as-pure", Version: "7.0.0", Locations: []types.Location{{StartLine: 81, EndLine: 86}}},
{ID: "@babel/[email protected]", Name: "@babel/helper-builder-binary-assignment-operator-visitor", Version: "7.1.0", Locations: []types.Location{{StartLine: 88, EndLine: 94}}},
{ID: "@babel/[email protected]", Name: "@babel/helper-builder-react-jsx", Version: "7.3.0", Locations: []types.Location{{StartLine: 96, EndLine: 102}}},
{ID: "@babel/[email protected]", Name: "@babel/helper-call-delegate", Version: "7.4.4", Locations: []types.Location{{StartLine: 104, EndLine: 111}}},
{ID: "@babel/[email protected]", Name: "@babel/helper-create-class-features-plugin", Version: "7.4.4", Locations: []types.Location{{StartLine: 113, EndLine: 123}}},
{ID: "@babel/[email protected]", Name: "@babel/helper-define-map", Version: "7.4.4", Locations: []types.Location{{StartLine: 125, EndLine: 132}}},
{ID: "@babel/[email protected]", Name: "@babel/helper-explode-assignable-expression", Version: "7.1.0", Locations: []types.Location{{StartLine: 134, EndLine: 140}}},
{ID: "@babel/[email protected]", Name: "@babel/helper-function-name", Version: "7.0.0-beta.44", Locations: []types.Location{{StartLine: 142, EndLine: 149}}},
{ID: "@babel/[email protected]", Name: "@babel/helper-function-name", Version: "7.1.0", Locations: []types.Location{{StartLine: 151, EndLine: 158}}},
{ID: "@babel/[email protected]", Name: "@babel/helper-get-function-arity", Version: "7.0.0-beta.44", Locations: []types.Location{{StartLine: 160, EndLine: 165}}},
{ID: "@babel/[email protected]", Name: "@babel/helper-get-function-arity", Version: "7.0.0", Locations: []types.Location{{StartLine: 167, EndLine: 172}}},
{ID: "@babel/[email protected]", Name: "@babel/helper-hoist-variables", Version: "7.4.4", Locations: []types.Location{{StartLine: 174, EndLine: 179}}},
{ID: "@babel/[email protected]", Name: "@babel/helper-member-expression-to-functions", Version: "7.0.0", Locations: []types.Location{{StartLine: 181, EndLine: 186}}},
{ID: "@babel/[email protected]", Name: "@babel/helper-module-imports", Version: "7.0.0", Locations: []types.Location{{StartLine: 188, EndLine: 193}}},
{ID: "@babel/[email protected]", Name: "@babel/helper-module-transforms", Version: "7.4.4", Locations: []types.Location{{StartLine: 195, EndLine: 205}}},
{ID: "@babel/[email protected]", Name: "@babel/helper-optimise-call-expression", Version: "7.0.0", Locations: []types.Location{{StartLine: 207, EndLine: 212}}},
{ID: "@babel/[email protected]", Name: "@babel/helper-plugin-utils", Version: "7.0.0", Locations: []types.Location{{StartLine: 214, EndLine: 217}}},
{ID: "@babel/[email protected]", Name: "@babel/helper-regex", Version: "7.4.4", Locations: []types.Location{{StartLine: 219, EndLine: 224}}},
{ID: "@babel/[email protected]", Name: "@babel/helper-remap-async-to-generator", Version: "7.1.0", Locations: []types.Location{{StartLine: 226, EndLine: 235}}},
{ID: "@babel/[email protected]", Name: "@babel/helper-replace-supers", Version: "7.4.4", Locations: []types.Location{{StartLine: 237, EndLine: 245}}},
{ID: "@babel/[email protected]", Name: "@babel/helper-simple-access", Version: "7.1.0", Locations: []types.Location{{StartLine: 247, EndLine: 253}}},
{ID: "@babel/[email protected]", Name: "@babel/helper-split-export-declaration", Version: "7.0.0-beta.44", Locations: []types.Location{{StartLine: 255, EndLine: 260}}},
{ID: "@babel/[email protected]", Name: "@babel/helper-split-export-declaration", Version: "7.4.4", Locations: []types.Location{{StartLine: 262, EndLine: 267}}},
{ID: "@babel/[email protected]", Name: "@babel/helper-wrap-function", Version: "7.2.0", Locations: []types.Location{{StartLine: 269, EndLine: 277}}},
{ID: "@babel/[email protected]", Name: "@babel/helpers", Version: "7.4.4", Locations: []types.Location{{StartLine: 279, EndLine: 286}}},
{ID: "@babel/[email protected]", Name: "@babel/highlight", Version: "7.0.0-beta.44", Locations: []types.Location{{StartLine: 288, EndLine: 295}}},
{ID: "@babel/[email protected]", Name: "@babel/highlight", Version: "7.0.0", Locations: []types.Location{{StartLine: 297, EndLine: 304}}},
{ID: "@babel/[email protected]", Name: "@babel/parser", Version: "7.4.4", Locations: []types.Location{{StartLine: 306, EndLine: 309}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-proposal-async-generator-functions", Version: "7.2.0", Locations: []types.Location{{StartLine: 311, EndLine: 318}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-proposal-class-properties", Version: "7.1.0", Locations: []types.Location{{StartLine: 320, EndLine: 330}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-proposal-class-properties", Version: "7.4.4", Locations: []types.Location{{StartLine: 332, EndLine: 338}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-proposal-decorators", Version: "7.1.2", Locations: []types.Location{{StartLine: 340, EndLine: 348}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-proposal-json-strings", Version: "7.2.0", Locations: []types.Location{{StartLine: 350, EndLine: 356}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-proposal-object-rest-spread", Version: "7.0.0", Locations: []types.Location{{StartLine: 358, EndLine: 364}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-proposal-object-rest-spread", Version: "7.4.4", Locations: []types.Location{{StartLine: 366, EndLine: 372}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-proposal-optional-catch-binding", Version: "7.2.0", Locations: []types.Location{{StartLine: 374, EndLine: 380}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-proposal-unicode-property-regex", Version: "7.4.4", Locations: []types.Location{{StartLine: 382, EndLine: 389}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-syntax-async-generators", Version: "7.2.0", Locations: []types.Location{{StartLine: 391, EndLine: 396}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-syntax-class-properties", Version: "7.2.0", Locations: []types.Location{{StartLine: 398, EndLine: 403}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-syntax-decorators", Version: "7.2.0", Locations: []types.Location{{StartLine: 405, EndLine: 410}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-syntax-dynamic-import", Version: "7.0.0", Locations: []types.Location{{StartLine: 412, EndLine: 417}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-syntax-dynamic-import", Version: "7.2.0", Locations: []types.Location{{StartLine: 419, EndLine: 424}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-syntax-flow", Version: "7.2.0", Locations: []types.Location{{StartLine: 426, EndLine: 431}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-syntax-json-strings", Version: "7.2.0", Locations: []types.Location{{StartLine: 433, EndLine: 438}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-syntax-jsx", Version: "7.2.0", Locations: []types.Location{{StartLine: 440, EndLine: 445}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-syntax-object-rest-spread", Version: "7.2.0", Locations: []types.Location{{StartLine: 447, EndLine: 452}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-syntax-optional-catch-binding", Version: "7.2.0", Locations: []types.Location{{StartLine: 454, EndLine: 459}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-syntax-typescript", Version: "7.3.3", Locations: []types.Location{{StartLine: 461, EndLine: 466}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-arrow-functions", Version: "7.2.0", Locations: []types.Location{{StartLine: 468, EndLine: 473}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-async-to-generator", Version: "7.4.4", Locations: []types.Location{{StartLine: 475, EndLine: 482}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-block-scoped-functions", Version: "7.2.0", Locations: []types.Location{{StartLine: 484, EndLine: 489}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-block-scoping", Version: "7.4.4", Locations: []types.Location{{StartLine: 491, EndLine: 497}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-classes", Version: "7.1.0", Locations: []types.Location{{StartLine: 499, EndLine: 511}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-classes", Version: "7.4.4", Locations: []types.Location{{StartLine: 513, EndLine: 525}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-computed-properties", Version: "7.2.0", Locations: []types.Location{{StartLine: 527, EndLine: 532}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-destructuring", Version: "7.0.0", Locations: []types.Location{{StartLine: 534, EndLine: 539}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-destructuring", Version: "7.4.4", Locations: []types.Location{{StartLine: 541, EndLine: 546}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-dotall-regex", Version: "7.4.4", Locations: []types.Location{{StartLine: 548, EndLine: 555}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-duplicate-keys", Version: "7.2.0", Locations: []types.Location{{StartLine: 557, EndLine: 562}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-exponentiation-operator", Version: "7.2.0", Locations: []types.Location{{StartLine: 564, EndLine: 570}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-flow-strip-types", Version: "7.0.0", Locations: []types.Location{{StartLine: 572, EndLine: 578}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-flow-strip-types", Version: "7.4.4", Locations: []types.Location{{StartLine: 580, EndLine: 586}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-for-of", Version: "7.4.4", Locations: []types.Location{{StartLine: 588, EndLine: 593}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-function-name", Version: "7.4.4", Locations: []types.Location{{StartLine: 595, EndLine: 601}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-literals", Version: "7.2.0", Locations: []types.Location{{StartLine: 603, EndLine: 608}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-member-expression-literals", Version: "7.2.0", Locations: []types.Location{{StartLine: 610, EndLine: 615}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-modules-amd", Version: "7.2.0", Locations: []types.Location{{StartLine: 617, EndLine: 623}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-modules-commonjs", Version: "7.4.4", Locations: []types.Location{{StartLine: 625, EndLine: 632}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-modules-systemjs", Version: "7.4.4", Locations: []types.Location{{StartLine: 634, EndLine: 640}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-modules-umd", Version: "7.2.0", Locations: []types.Location{{StartLine: 642, EndLine: 648}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-named-capturing-groups-regex", Version: "7.4.4", Locations: []types.Location{{StartLine: 650, EndLine: 655}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-new-target", Version: "7.4.4", Locations: []types.Location{{StartLine: 657, EndLine: 662}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-object-super", Version: "7.2.0", Locations: []types.Location{{StartLine: 664, EndLine: 670}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-parameters", Version: "7.4.4", Locations: []types.Location{{StartLine: 672, EndLine: 679}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-property-literals", Version: "7.2.0", Locations: []types.Location{{StartLine: 681, EndLine: 686}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-react-constant-elements", Version: "7.0.0", Locations: []types.Location{{StartLine: 688, EndLine: 694}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-react-constant-elements", Version: "7.2.0", Locations: []types.Location{{StartLine: 696, EndLine: 702}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-react-display-name", Version: "7.0.0", Locations: []types.Location{{StartLine: 704, EndLine: 709}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-react-display-name", Version: "7.2.0", Locations: []types.Location{{StartLine: 711, EndLine: 716}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-react-jsx-self", Version: "7.2.0", Locations: []types.Location{{StartLine: 718, EndLine: 724}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-react-jsx-source", Version: "7.2.0", Locations: []types.Location{{StartLine: 726, EndLine: 732}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-react-jsx", Version: "7.3.0", Locations: []types.Location{{StartLine: 734, EndLine: 741}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-regenerator", Version: "7.4.4", Locations: []types.Location{{StartLine: 743, EndLine: 748}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-reserved-words", Version: "7.2.0", Locations: []types.Location{{StartLine: 750, EndLine: 755}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-runtime", Version: "7.1.0", Locations: []types.Location{{StartLine: 757, EndLine: 765}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-shorthand-properties", Version: "7.2.0", Locations: []types.Location{{StartLine: 767, EndLine: 772}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-spread", Version: "7.2.2", Locations: []types.Location{{StartLine: 774, EndLine: 779}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-sticky-regex", Version: "7.2.0", Locations: []types.Location{{StartLine: 781, EndLine: 787}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-template-literals", Version: "7.4.4", Locations: []types.Location{{StartLine: 789, EndLine: 795}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-typeof-symbol", Version: "7.2.0", Locations: []types.Location{{StartLine: 797, EndLine: 802}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-typescript", Version: "7.4.4", Locations: []types.Location{{StartLine: 804, EndLine: 810}}},
{ID: "@babel/[email protected]", Name: "@babel/plugin-transform-unicode-regex", Version: "7.4.4", Locations: []types.Location{{StartLine: 812, EndLine: 819}}},
{ID: "@babel/[email protected]", Name: "@babel/preset-env", Version: "7.1.0", Locations: []types.Location{{StartLine: 821, EndLine: 866}}},
{ID: "@babel/[email protected]", Name: "@babel/preset-env", Version: "7.4.4", Locations: []types.Location{{StartLine: 868, EndLine: 920}}},
{ID: "@babel/[email protected]", Name: "@babel/preset-flow", Version: "7.0.0", Locations: []types.Location{{StartLine: 922, EndLine: 928}}},
{ID: "@babel/[email protected]", Name: "@babel/preset-react", Version: "7.0.0", Locations: []types.Location{{StartLine: 930, EndLine: 939}}},
{ID: "@babel/[email protected]", Name: "@babel/preset-typescript", Version: "7.1.0", Locations: []types.Location{{StartLine: 941, EndLine: 947}}},
{ID: "@babel/[email protected]", Name: "@babel/register", Version: "7.4.4", Locations: []types.Location{{StartLine: 949, EndLine: 959}}},
{ID: "@babel/[email protected]", Name: "@babel/runtime", Version: "7.0.0", Locations: []types.Location{{StartLine: 961, EndLine: 966}}},
{ID: "@babel/[email protected]", Name: "@babel/runtime", Version: "7.4.4", Locations: []types.Location{{StartLine: 968, EndLine: 973}}},
{ID: "@babel/[email protected]", Name: "@babel/template", Version: "7.0.0-beta.44", Locations: []types.Location{{StartLine: 975, EndLine: 983}}},
{ID: "@babel/[email protected]", Name: "@babel/template", Version: "7.4.4", Locations: []types.Location{{StartLine: 985, EndLine: 992}}},
{ID: "@babel/[email protected]", Name: "@babel/traverse", Version: "7.0.0-beta.44", Locations: []types.Location{{StartLine: 994, EndLine: 1008}}},
{ID: "@babel/[email protected]", Name: "@babel/traverse", Version: "7.4.4", Locations: []types.Location{{StartLine: 1010, EndLine: 1023}}},
{ID: "@babel/[email protected]", Name: "@babel/types", Version: "7.0.0-beta.44", Locations: []types.Location{{StartLine: 1025, EndLine: 1032}}},
{ID: "@babel/[email protected]", Name: "@babel/types", Version: "7.4.4", Locations: []types.Location{{StartLine: 1034, EndLine: 1041}}},
{ID: "@emotion/[email protected]", Name: "@emotion/cache", Version: "0.8.8", Locations: []types.Location{{StartLine: 1043, EndLine: 1050}}},
{ID: "@emotion/[email protected]", Name: "@emotion/core", Version: "0.13.1", Locations: []types.Location{{StartLine: 1052, EndLine: 1061}}},
{ID: "@emotion/[email protected]", Name: "@emotion/css", Version: "0.9.8", Locations: []types.Location{{StartLine: 1063, EndLine: 1069}}},
{ID: "@emotion/[email protected]", Name: "@emotion/hash", Version: "0.6.6", Locations: []types.Location{{StartLine: 1071, EndLine: 1074}}},
{ID: "@emotion/[email protected]", Name: "@emotion/is-prop-valid", Version: "0.6.8", Locations: []types.Location{{StartLine: 1076, EndLine: 1081}}},
{ID: "@emotion/[email protected]", Name: "@emotion/is-prop-valid", Version: "0.7.3", Locations: []types.Location{{StartLine: 1083, EndLine: 1088}}},
{ID: "@emotion/[email protected]", Name: "@emotion/memoize", Version: "0.7.1", Locations: []types.Location{{StartLine: 1090, EndLine: 1093}}},
{ID: "@emotion/[email protected]", Name: "@emotion/memoize", Version: "0.6.6", Locations: []types.Location{{StartLine: 1095, EndLine: 1098}}},
{ID: "@emotion/[email protected]", Name: "@emotion/provider", Version: "0.11.2", Locations: []types.Location{{StartLine: 1100, EndLine: 1106}}},
{ID: "@emotion/[email protected]", Name: "@emotion/serialize", Version: "0.9.1", Locations: []types.Location{{StartLine: 1108, EndLine: 1116}}},
{ID: "@emotion/[email protected]", Name: "@emotion/sheet", Version: "0.8.1", Locations: []types.Location{{StartLine: 1118, EndLine: 1121}}},
{ID: "@emotion/[email protected]", Name: "@emotion/styled-base", Version: "0.10.6", Locations: []types.Location{{StartLine: 1123, EndLine: 1130}}},
{ID: "@emotion/[email protected]", Name: "@emotion/styled", Version: "0.10.6", Locations: []types.Location{{StartLine: 1132, EndLine: 1137}}},
{ID: "@emotion/[email protected]", Name: "@emotion/stylis", Version: "0.7.1", Locations: []types.Location{{StartLine: 1139, EndLine: 1142}}},
{ID: "@emotion/[email protected]", Name: "@emotion/unitless", Version: "0.6.7", Locations: []types.Location{{StartLine: 1144, EndLine: 1147}}},
{ID: "@emotion/[email protected]", Name: "@emotion/unitless", Version: "0.7.3", Locations: []types.Location{{StartLine: 1149, EndLine: 1152}}},
{ID: "@emotion/[email protected]", Name: "@emotion/utils", Version: "0.8.2", Locations: []types.Location{{StartLine: 1154, EndLine: 1157}}},
{ID: "@emotion/[email protected]", Name: "@emotion/weak-memoize", Version: "0.1.3", Locations: []types.Location{{StartLine: 1159, EndLine: 1162}}},
{ID: "@icons/[email protected]", Name: "@icons/material", Version: "0.2.4", Locations: []types.Location{{StartLine: 1164, EndLine: 1167}}},
{ID: "@loadable/[email protected]", Name: "@loadable/component", Version: "5.10.1", Locations: []types.Location{{StartLine: 1169, EndLine: 1175}}},
{ID: "@material-ui/[email protected]", Name: "@material-ui/core", Version: "3.9.3", Locations: []types.Location{{StartLine: 1177, EndLine: 1208}}},
{ID: "@material-ui/[email protected]", Name: "@material-ui/icons", Version: "3.0.2", Locations: []types.Location{{StartLine: 1210, EndLine: 1216}}},
{ID: "@material-ui/[email protected]", Name: "@material-ui/system", Version: "3.0.0-alpha.2", Locations: []types.Location{{StartLine: 1218, EndLine: 1226}}},
{ID: "@material-ui/[email protected]", Name: "@material-ui/utils", Version: "3.0.0-alpha.3", Locations: []types.Location{{StartLine: 1228, EndLine: 1235}}},
{ID: "@mrmlnc/[email protected]", Name: "@mrmlnc/readdir-enhanced", Version: "2.2.1", Locations: []types.Location{{StartLine: 1237, EndLine: 1243}}},
{ID: "@nodelib/[email protected]", Name: "@nodelib/fs.stat", Version: "1.1.3", Locations: []types.Location{{StartLine: 1245, EndLine: 1248}}},
{ID: "@octokit/[email protected]", Name: "@octokit/rest", Version: "15.18.1", Locations: []types.Location{{StartLine: 1250, EndLine: 1263}}},
{ID: "@samverschueren/[email protected]", Name: "@samverschueren/stream-to-observable", Version: "0.3.0", Locations: []types.Location{{StartLine: 1265, EndLine: 1270}}},
{ID: "@storybook/[email protected]", Name: "@storybook/addon-actions", Version: "4.1.18", Locations: []types.Location{{StartLine: 1272, EndLine: 1290}}},
{ID: "@storybook/[email protected]", Name: "@storybook/addon-info", Version: "4.1.18", Locations: []types.Location{{StartLine: 1292, EndLine: 1307}}},
{ID: "@storybook/[email protected]", Name: "@storybook/addon-knobs", Version: "4.1.18", Locations: []types.Location{{StartLine: 1309, EndLine: 1327}}},
{ID: "@storybook/[email protected]", Name: "@storybook/addons", Version: "4.1.18", Locations: []types.Location{{StartLine: 1329, EndLine: 1337}}},
{ID: "@storybook/[email protected]", Name: "@storybook/channel-postmessage", Version: "4.1.18", Locations: []types.Location{{StartLine: 1339, EndLine: 1346}}},
{ID: "@storybook/[email protected]", Name: "@storybook/channels", Version: "4.1.18", Locations: []types.Location{{StartLine: 1348, EndLine: 1351}}},
{ID: "@storybook/[email protected]", Name: "@storybook/cli", Version: "4.1.18", Locations: []types.Location{{StartLine: 1353, EndLine: 1372}}},
{ID: "@storybook/[email protected]", Name: "@storybook/client-logger", Version: "4.1.18", Locations: []types.Location{{StartLine: 1374, EndLine: 1377}}},
{ID: "@storybook/[email protected]", Name: "@storybook/codemod", Version: "4.1.18", Locations: []types.Location{{StartLine: 1379, EndLine: 1386}}},
{ID: "@storybook/[email protected]", Name: "@storybook/components", Version: "4.1.18", Locations: []types.Location{{StartLine: 1388, EndLine: 1402}}},
{ID: "@storybook/[email protected]", Name: "@storybook/core-events", Version: "4.1.18", Locations: []types.Location{{StartLine: 1404, EndLine: 1407}}},
{ID: "@storybook/[email protected]", Name: "@storybook/core", Version: "4.1.18", Locations: []types.Location{{StartLine: 1409, EndLine: 1477}}},
{ID: "@storybook/[email protected]", Name: "@storybook/mantra-core", Version: "1.7.2", Locations: []types.Location{{StartLine: 1479, EndLine: 1486}}},
{ID: "@storybook/[email protected]", Name: "@storybook/node-logger", Version: "4.1.18", Locations: []types.Location{{StartLine: 1488, EndLine: 1497}}},
{ID: "@storybook/[email protected]", Name: "@storybook/podda", Version: "1.2.3", Locations: []types.Location{{StartLine: 1499, EndLine: 1505}}},
{ID: "@storybook/[email protected]", Name: "@storybook/react-komposer", Version: "2.0.5", Locations: []types.Location{{StartLine: 1507, EndLine: 1516}}},
{ID: "@storybook/[email protected]", Name: "@storybook/react-simple-di", Version: "1.3.0", Locations: []types.Location{{StartLine: 1518, EndLine: 1526}}},
{ID: "@storybook/[email protected]", Name: "@storybook/react-stubber", Version: "1.0.1", Locations: []types.Location{{StartLine: 1528, EndLine: 1533}}},
{ID: "@storybook/[email protected]", Name: "@storybook/react", Version: "4.1.18", Locations: []types.Location{{StartLine: 1535, EndLine: 1559}}},
{ID: "@storybook/[email protected]", Name: "@storybook/ui", Version: "4.1.18", Locations: []types.Location{{StartLine: 1561, EndLine: 1587}}},
{ID: "@svgr/[email protected]", Name: "@svgr/babel-plugin-add-jsx-attribute", Version: "4.2.0", Locations: []types.Location{{StartLine: 1589, EndLine: 1592}}},
{ID: "@svgr/[email protected]", Name: "@svgr/babel-plugin-remove-jsx-attribute", Version: "4.2.0", Locations: []types.Location{{StartLine: 1594, EndLine: 1597}}},
{ID: "@svgr/[email protected]", Name: "@svgr/babel-plugin-remove-jsx-empty-expression", Version: "4.2.0", Locations: []types.Location{{StartLine: 1599, EndLine: 1602}}},
{ID: "@svgr/[email protected]", Name: "@svgr/babel-plugin-replace-jsx-attribute-value", Version: "4.2.0", Locations: []types.Location{{StartLine: 1604, EndLine: 1607}}},
{ID: "@svgr/[email protected]", Name: "@svgr/babel-plugin-svg-dynamic-title", Version: "4.2.0", Locations: []types.Location{{StartLine: 1609, EndLine: 1612}}},
{ID: "@svgr/[email protected]", Name: "@svgr/babel-plugin-svg-em-dimensions", Version: "4.2.0", Locations: []types.Location{{StartLine: 1614, EndLine: 1617}}},
{ID: "@svgr/[email protected]", Name: "@svgr/babel-plugin-transform-react-native-svg", Version: "4.2.0", Locations: []types.Location{{StartLine: 1619, EndLine: 1622}}},
{ID: "@svgr/[email protected]", Name: "@svgr/babel-plugin-transform-svg-component", Version: "4.2.0", Locations: []types.Location{{StartLine: 1624, EndLine: 1627}}},
{ID: "@svgr/[email protected]", Name: "@svgr/babel-preset", Version: "4.2.0", Locations: []types.Location{{StartLine: 1629, EndLine: 1641}}},
{ID: "@svgr/[email protected]", Name: "@svgr/core", Version: "4.2.0", Locations: []types.Location{{StartLine: 1643, EndLine: 1650}}},
{ID: "@svgr/[email protected]", Name: "@svgr/hast-util-to-babel-ast", Version: "4.2.0", Locations: []types.Location{{StartLine: 1652, EndLine: 1657}}},
{ID: "@svgr/[email protected]", Name: "@svgr/plugin-jsx", Version: "4.2.0", Locations: []types.Location{{StartLine: 1659, EndLine: 1669}}},
{ID: "@svgr/[email protected]", Name: "@svgr/plugin-svgo", Version: "4.2.0", Locations: []types.Location{{StartLine: 1671, EndLine: 1678}}},
{ID: "@svgr/[email protected]", Name: "@svgr/webpack", Version: "4.2.0", Locations: []types.Location{{StartLine: 1680, EndLine: 1692}}},
{ID: "@types/[email protected]", Name: "@types/events", Version: "3.0.0", Locations: []types.Location{{StartLine: 1694, EndLine: 1697}}},
{ID: "@types/[email protected]", Name: "@types/glob", Version: "7.1.1", Locations: []types.Location{{StartLine: 1699, EndLine: 1706}}},
{ID: "@types/[email protected]", Name: "@types/jss", Version: "9.5.8", Locations: []types.Location{{StartLine: 1708, EndLine: 1714}}},
{ID: "@types/[email protected]", Name: "@types/minimatch", Version: "3.0.3", Locations: []types.Location{{StartLine: 1716, EndLine: 1719}}},
{ID: "@types/[email protected]", Name: "@types/node", Version: "12.0.2", Locations: []types.Location{{StartLine: 1721, EndLine: 1724}}},
{ID: "@types/[email protected]", Name: "@types/prop-types", Version: "15.7.1", Locations: []types.Location{{StartLine: 1726, EndLine: 1729}}},
{ID: "@types/[email protected]", Name: "@types/q", Version: "1.5.2", Locations: []types.Location{{StartLine: 1731, EndLine: 1734}}},
{ID: "@types/[email protected]", Name: "@types/react-transition-group", Version: "2.9.1", Locations: []types.Location{{StartLine: 1736, EndLine: 1741}}},
{ID: "@types/[email protected]", Name: "@types/react", Version: "16.8.17", Locations: []types.Location{{StartLine: 1743, EndLine: 1749}}},
{ID: "@types/[email protected]", Name: "@types/unist", Version: "2.0.3", Locations: []types.Location{{StartLine: 1751, EndLine: 1754}}},
{ID: "@types/[email protected]", Name: "@types/vfile-message", Version: "1.0.1", Locations: []types.Location{{StartLine: 1756, EndLine: 1762}}},
{ID: "@types/[email protected]", Name: "@types/vfile", Version: "3.0.2", Locations: []types.Location{{StartLine: 1764, EndLine: 1771}}},
{ID: "@webassemblyjs/[email protected]", Name: "@webassemblyjs/ast", Version: "1.8.5", Locations: []types.Location{{StartLine: 1773, EndLine: 1780}}},
{ID: "@webassemblyjs/[email protected]", Name: "@webassemblyjs/floating-point-hex-parser", Version: "1.8.5", Locations: []types.Location{{StartLine: 1782, EndLine: 1785}}},
{ID: "@webassemblyjs/[email protected]", Name: "@webassemblyjs/helper-api-error", Version: "1.8.5", Locations: []types.Location{{StartLine: 1787, EndLine: 1790}}},
{ID: "@webassemblyjs/[email protected]", Name: "@webassemblyjs/helper-buffer", Version: "1.8.5", Locations: []types.Location{{StartLine: 1792, EndLine: 1795}}},
{ID: "@webassemblyjs/[email protected]", Name: "@webassemblyjs/helper-code-frame", Version: "1.8.5", Locations: []types.Location{{StartLine: 1797, EndLine: 1802}}},
{ID: "@webassemblyjs/[email protected]", Name: "@webassemblyjs/helper-fsm", Version: "1.8.5", Locations: []types.Location{{StartLine: 1804, EndLine: 1807}}},
{ID: "@webassemblyjs/[email protected]", Name: "@webassemblyjs/helper-module-context", Version: "1.8.5", Locations: []types.Location{{StartLine: 1809, EndLine: 1815}}},
{ID: "@webassemblyjs/[email protected]", Name: "@webassemblyjs/helper-wasm-bytecode", Version: "1.8.5", Locations: []types.Location{{StartLine: 1817, EndLine: 1820}}},
{ID: "@webassemblyjs/[email protected]", Name: "@webassemblyjs/helper-wasm-section", Version: "1.8.5", Locations: []types.Location{{StartLine: 1822, EndLine: 1830}}},
{ID: "@webassemblyjs/[email protected]", Name: "@webassemblyjs/ieee754", Version: "1.8.5", Locations: []types.Location{{StartLine: 1832, EndLine: 1837}}},
{ID: "@webassemblyjs/[email protected]", Name: "@webassemblyjs/leb128", Version: "1.8.5", Locations: []types.Location{{StartLine: 1839, EndLine: 1844}}},
{ID: "@webassemblyjs/[email protected]", Name: "@webassemblyjs/utf8", Version: "1.8.5", Locations: []types.Location{{StartLine: 1846, EndLine: 1849}}},
{ID: "@webassemblyjs/[email protected]", Name: "@webassemblyjs/wasm-edit", Version: "1.8.5", Locations: []types.Location{{StartLine: 1851, EndLine: 1863}}},
{ID: "@webassemblyjs/[email protected]", Name: "@webassemblyjs/wasm-gen", Version: "1.8.5", Locations: []types.Location{{StartLine: 1865, EndLine: 1874}}},
{ID: "@webassemblyjs/[email protected]", Name: "@webassemblyjs/wasm-opt", Version: "1.8.5", Locations: []types.Location{{StartLine: 1876, EndLine: 1884}}},
{ID: "@webassemblyjs/[email protected]", Name: "@webassemblyjs/wasm-parser", Version: "1.8.5", Locations: []types.Location{{StartLine: 1886, EndLine: 1896}}},
{ID: "@webassemblyjs/[email protected]", Name: "@webassemblyjs/wast-parser", Version: "1.8.5", Locations: []types.Location{{StartLine: 1898, EndLine: 1908}}},
{ID: "@webassemblyjs/[email protected]", Name: "@webassemblyjs/wast-printer", Version: "1.8.5", Locations: []types.Location{{StartLine: 1910, EndLine: 1917}}},
{ID: "@xtuc/[email protected]", Name: "@xtuc/ieee754", Version: "1.2.0", Locations: []types.Location{{StartLine: 1919, EndLine: 1922}}},
{ID: "@xtuc/[email protected]", Name: "@xtuc/long", Version: "4.2.2", Locations: []types.Location{{StartLine: 1924, EndLine: 1927}}},
{ID: "[email protected]", Name: "JSONStream", Version: "1.3.5", Locations: []types.Location{{StartLine: 1929, EndLine: 1935}}},
{ID: "[email protected]", Name: "abab", Version: "2.0.0", Locations: []types.Location{{StartLine: 1937, EndLine: 1940}}},
{ID: "[email protected]", Name: "abbrev", Version: "1.1.1", Locations: []types.Location{{StartLine: 1942, EndLine: 1945}}},
{ID: "[email protected]", Name: "accepts", Version: "1.3.7", Locations: []types.Location{{StartLine: 1947, EndLine: 1953}}},
{ID: "[email protected]", Name: "acorn-dynamic-import", Version: "4.0.0", Locations: []types.Location{{StartLine: 1955, EndLine: 1958}}},
{ID: "[email protected]", Name: "acorn-globals", Version: "4.3.2", Locations: []types.Location{{StartLine: 1960, EndLine: 1966}}},
{ID: "[email protected]", Name: "acorn-jsx", Version: "5.0.1", Locations: []types.Location{{StartLine: 1968, EndLine: 1971}}},
{ID: "[email protected]", Name: "acorn-walk", Version: "6.1.1", Locations: []types.Location{{StartLine: 1973, EndLine: 1976}}},
{ID: "[email protected]", Name: "acorn", Version: "5.7.3", Locations: []types.Location{{StartLine: 1978, EndLine: 1981}}},
{ID: "[email protected]", Name: "acorn", Version: "6.1.1", Locations: []types.Location{{StartLine: 1983, EndLine: 1986}}},
{ID: "[email protected]", Name: "address", Version: "1.0.3", Locations: []types.Location{{StartLine: 1988, EndLine: 1991}}},
{ID: "[email protected]", Name: "address", Version: "1.1.0", Locations: []types.Location{{StartLine: 1993, EndLine: 1996}}},
{ID: "[email protected]", Name: "after", Version: "0.8.2", Locations: []types.Location{{StartLine: 1998, EndLine: 2001}}},
{ID: "[email protected]", Name: "agent-base", Version: "4.2.1", Locations: []types.Location{{StartLine: 2003, EndLine: 2008}}},
{ID: "[email protected]", Name: "agentkeepalive", Version: "3.5.2", Locations: []types.Location{{StartLine: 2010, EndLine: 2015}}},
{ID: "[email protected]", Name: "airbnb-js-shims", Version: "2.2.0", Locations: []types.Location{{StartLine: 2017, EndLine: 2038}}},
{ID: "[email protected]", Name: "airbnb-prop-types", Version: "2.13.2", Locations: []types.Location{{StartLine: 2040, EndLine: 2054}}},
{ID: "[email protected]", Name: "ajv-errors", Version: "1.0.1", Locations: []types.Location{{StartLine: 2056, EndLine: 2059}}},
{ID: "[email protected]", Name: "ajv-keywords", Version: "3.4.0", Locations: []types.Location{{StartLine: 2061, EndLine: 2064}}},
{ID: "[email protected]", Name: "ajv", Version: "6.10.0", Locations: []types.Location{{StartLine: 2066, EndLine: 2074}}},
{ID: "[email protected]", Name: "ansi-align", Version: "2.0.0", Locations: []types.Location{{StartLine: 2076, EndLine: 2081}}},
{ID: "[email protected]", Name: "ansi-align", Version: "3.0.0", Locations: []types.Location{{StartLine: 2083, EndLine: 2088}}},
{ID: "[email protected]", Name: "ansi-colors", Version: "3.2.4", Locations: []types.Location{{StartLine: 2090, EndLine: 2093}}},
{ID: "[email protected]", Name: "ansi-escapes", Version: "1.4.0", Locations: []types.Location{{StartLine: 2095, EndLine: 2098}}},
{ID: "[email protected]", Name: "ansi-escapes", Version: "3.2.0", Locations: []types.Location{{StartLine: 2100, EndLine: 2103}}},
{ID: "[email protected]", Name: "ansi-html", Version: "0.0.7", Locations: []types.Location{{StartLine: 2105, EndLine: 2108}}},
{ID: "[email protected]", Name: "ansi-regex", Version: "2.1.1", Locations: []types.Location{{StartLine: 2110, EndLine: 2113}}},
{ID: "[email protected]", Name: "ansi-regex", Version: "3.0.0", Locations: []types.Location{{StartLine: 2115, EndLine: 2118}}},
{ID: "[email protected]", Name: "ansi-regex", Version: "4.1.0", Locations: []types.Location{{StartLine: 2120, EndLine: 2123}}},
{ID: "[email protected]", Name: "ansi-styles", Version: "2.2.1", Locations: []types.Location{{StartLine: 2125, EndLine: 2128}}},
{ID: "[email protected]", Name: "ansi-styles", Version: "3.2.1", Locations: []types.Location{{StartLine: 2130, EndLine: 2135}}},
{ID: "[email protected]", Name: "ansi-styles", Version: "1.0.0", Locations: []types.Location{{StartLine: 2137, EndLine: 2140}}},
{ID: "[email protected]", Name: "ansicolors", Version: "0.3.2", Locations: []types.Location{{StartLine: 2142, EndLine: 2145}}},
{ID: "[email protected]", Name: "ansistyles", Version: "0.1.3", Locations: []types.Location{{StartLine: 2147, EndLine: 2150}}},
{ID: "[email protected]", Name: "any-observable", Version: "0.3.0", Locations: []types.Location{{StartLine: 2152, EndLine: 2155}}},
{ID: "[email protected]", Name: "anymatch", Version: "1.3.2", Locations: []types.Location{{StartLine: 2157, EndLine: 2163}}},
{ID: "[email protected]", Name: "anymatch", Version: "2.0.0", Locations: []types.Location{{StartLine: 2165, EndLine: 2171}}},
{ID: "[email protected]", Name: "app-root-dir", Version: "1.0.2", Locations: []types.Location{{StartLine: 2173, EndLine: 2176}}},
{ID: "[email protected]", Name: "append-transform", Version: "0.4.0", Locations: []types.Location{{StartLine: 2178, EndLine: 2183}}},
{ID: "[email protected]", Name: "aproba", Version: "1.2.0", Locations: []types.Location{{StartLine: 2185, EndLine: 2188}}},
{ID: "[email protected]", Name: "aproba", Version: "2.0.0", Locations: []types.Location{{StartLine: 2190, EndLine: 2193}}},
{ID: "[email protected]", Name: "archy", Version: "1.0.0", Locations: []types.Location{{StartLine: 2195, EndLine: 2198}}},
{ID: "[email protected]", Name: "are-we-there-yet", Version: "1.1.5", Locations: []types.Location{{StartLine: 2200, EndLine: 2206}}},
{ID: "[email protected]", Name: "argparse", Version: "1.0.10", Locations: []types.Location{{StartLine: 2208, EndLine: 2213}}},
{ID: "[email protected]", Name: "aria-query", Version: "3.0.0", Locations: []types.Location{{StartLine: 2215, EndLine: 2221}}},
{ID: "[email protected]", Name: "arr-diff", Version: "2.0.0", Locations: []types.Location{{StartLine: 2223, EndLine: 2228}}},
{ID: "[email protected]", Name: "arr-diff", Version: "4.0.0", Locations: []types.Location{{StartLine: 2230, EndLine: 2233}}},
{ID: "[email protected]", Name: "arr-flatten", Version: "1.1.0", Locations: []types.Location{{StartLine: 2235, EndLine: 2238}}},
{ID: "[email protected]", Name: "arr-union", Version: "3.1.0", Locations: []types.Location{{StartLine: 2240, EndLine: 2243}}},
{ID: "[email protected]", Name: "array-equal", Version: "1.0.0", Locations: []types.Location{{StartLine: 2245, EndLine: 2248}}},
{ID: "[email protected]", Name: "array-filter", Version: "1.0.0", Locations: []types.Location{{StartLine: 2250, EndLine: 2253}}},
{ID: "[email protected]", Name: "array-filter", Version: "0.0.1", Locations: []types.Location{{StartLine: 2255, EndLine: 2258}}},
{ID: "[email protected]", Name: "array-flatten", Version: "1.1.1", Locations: []types.Location{{StartLine: 2260, EndLine: 2263}}},
{ID: "[email protected]", Name: "array-flatten", Version: "2.1.2", Locations: []types.Location{{StartLine: 2265, EndLine: 2268}}},
{ID: "[email protected]", Name: "array-includes", Version: "3.0.3", Locations: []types.Location{{StartLine: 2270, EndLine: 2276}}},
{ID: "[email protected]", Name: "array-map", Version: "0.0.0", Locations: []types.Location{{StartLine: 2278, EndLine: 2281}}},
{ID: "[email protected]", Name: "array-reduce", Version: "0.0.0", Locations: []types.Location{{StartLine: 2283, EndLine: 2286}}},
{ID: "[email protected]", Name: "array-union", Version: "1.0.2", Locations: []types.Location{{StartLine: 2288, EndLine: 2293}}},
{ID: "[email protected]", Name: "array-uniq", Version: "1.0.3", Locations: []types.Location{{StartLine: 2295, EndLine: 2298}}},
{ID: "[email protected]", Name: "array-unique", Version: "0.2.1", Locations: []types.Location{{StartLine: 2300, EndLine: 2303}}},
{ID: "[email protected]", Name: "array-unique", Version: "0.3.2", Locations: []types.Location{{StartLine: 2305, EndLine: 2308}}},
{ID: "[email protected]", Name: "array.prototype.find", Version: "2.0.4", Locations: []types.Location{{StartLine: 2310, EndLine: 2316}}},
{ID: "[email protected]", Name: "array.prototype.flat", Version: "1.2.1", Locations: []types.Location{{StartLine: 2318, EndLine: 2325}}},
{ID: "[email protected]", Name: "array.prototype.flatmap", Version: "1.2.1", Locations: []types.Location{{StartLine: 2327, EndLine: 2334}}},
{ID: "[email protected]", Name: "arraybuffer.slice", Version: "0.0.7", Locations: []types.Location{{StartLine: 2336, EndLine: 2339}}},
{ID: "[email protected]", Name: "arrify", Version: "1.0.1", Locations: []types.Location{{StartLine: 2341, EndLine: 2344}}},
{ID: "[email protected]", Name: "asap", Version: "2.0.6", Locations: []types.Location{{StartLine: 2346, EndLine: 2349}}},
{ID: "[email protected]", Name: "asn1.js", Version: "4.10.1", Locations: []types.Location{{StartLine: 2351, EndLine: 2358}}},
{ID: "[email protected]", Name: "asn1", Version: "0.2.4", Locations: []types.Location{{StartLine: 2360, EndLine: 2365}}},
{ID: "[email protected]", Name: "assert-plus", Version: "1.0.0", Locations: []types.Location{{StartLine: 2367, EndLine: 2370}}},
{ID: "[email protected]", Name: "assert", Version: "1.5.0", Locations: []types.Location{{StartLine: 2372, EndLine: 2378}}},
{ID: "[email protected]", Name: "assign-symbols", Version: "1.0.0", Locations: []types.Location{{StartLine: 2380, EndLine: 2383}}},
{ID: "[email protected]", Name: "ast-types-flow", Version: "0.0.7", Locations: []types.Location{{StartLine: 2385, EndLine: 2388}}},
{ID: "[email protected]", Name: "ast-types", Version: "0.11.3", Locations: []types.Location{{StartLine: 2390, EndLine: 2393}}},
{ID: "[email protected]", Name: "ast-types", Version: "0.11.5", Locations: []types.Location{{StartLine: 2395, EndLine: 2398}}},
{ID: "[email protected]", Name: "ast-types", Version: "0.11.7", Locations: []types.Location{{StartLine: 2400, EndLine: 2403}}},
{ID: "[email protected]", Name: "astral-regex", Version: "1.0.0", Locations: []types.Location{{StartLine: 2405, EndLine: 2408}}},
{ID: "[email protected]", Name: "async-each", Version: "1.0.3", Locations: []types.Location{{StartLine: 2410, EndLine: 2413}}},
{ID: "[email protected]", Name: "async-limiter", Version: "1.0.0", Locations: []types.Location{{StartLine: 2415, EndLine: 2418}}},
{ID: "[email protected]", Name: "async", Version: "1.5.2", Locations: []types.Location{{StartLine: 2420, EndLine: 2423}}},
{ID: "[email protected]", Name: "async", Version: "2.6.2", Locations: []types.Location{{StartLine: 2425, EndLine: 2430}}},
{ID: "[email protected]", Name: "asynckit", Version: "0.4.0", Locations: []types.Location{{StartLine: 2432, EndLine: 2435}}},
{ID: "[email protected]", Name: "atob", Version: "2.1.2", Locations: []types.Location{{StartLine: 2437, EndLine: 2440}}},
{ID: "[email protected]", Name: "attr-accept", Version: "1.1.3", Locations: []types.Location{{StartLine: 2442, EndLine: 2447}}},
{ID: "[email protected]", Name: "autodll-webpack-plugin", Version: "0.4.2", Locations: []types.Location{{StartLine: 2449, EndLine: 2463}}},
{ID: "[email protected]", Name: "autoprefixer", Version: "8.6.5", Locations: []types.Location{{StartLine: 2465, EndLine: 2475}}},
{ID: "[email protected]", Name: "autoprefixer", Version: "9.5.1", Locations: []types.Location{{StartLine: 2477, EndLine: 2487}}},
{ID: "[email protected]", Name: "aws-sign2", Version: "0.7.0", Locations: []types.Location{{StartLine: 2489, EndLine: 2492}}},
{ID: "[email protected]", Name: "aws4", Version: "1.8.0", Locations: []types.Location{{StartLine: 2494, EndLine: 2497}}},
{ID: "[email protected]", Name: "axios", Version: "0.18.0", Locations: []types.Location{{StartLine: 2499, EndLine: 2505}}},
{ID: "[email protected]", Name: "axobject-query", Version: "2.0.2", Locations: []types.Location{{StartLine: 2507, EndLine: 2512}}},
{ID: "[email protected]", Name: "babel-cli", Version: "6.26.0", Locations: []types.Location{{StartLine: 2514, EndLine: 2534}}},
{ID: "[email protected]", Name: "babel-code-frame", Version: "6.26.0", Locations: []types.Location{{StartLine: 2536, EndLine: 2543}}},
{ID: "[email protected]", Name: "babel-core", Version: "6.26.3", Locations: []types.Location{{StartLine: 2545, EndLine: 2568}}},
{ID: "[email protected]", Name: "babel-eslint", Version: "8.2.6", Locations: []types.Location{{StartLine: 2570, EndLine: 2580}}},
{ID: "[email protected]", Name: "babel-generator", Version: "6.26.1", Locations: []types.Location{{StartLine: 2582, EndLine: 2594}}},
{ID: "[email protected]", Name: "babel-helper-bindify-decorators", Version: "6.24.1", Locations: []types.Location{{StartLine: 2596, EndLine: 2603}}},
{ID: "[email protected]", Name: "babel-helper-builder-binary-assignment-operator-visitor", Version: "6.24.1", Locations: []types.Location{{StartLine: 2605, EndLine: 2612}}},
{ID: "[email protected]", Name: "babel-helper-builder-react-jsx", Version: "6.26.0", Locations: []types.Location{{StartLine: 2614, EndLine: 2621}}},
{ID: "[email protected]", Name: "babel-helper-call-delegate", Version: "6.24.1", Locations: []types.Location{{StartLine: 2623, EndLine: 2631}}},
{ID: "[email protected]", Name: "babel-helper-define-map", Version: "6.26.0", Locations: []types.Location{{StartLine: 2633, EndLine: 2641}}},
{ID: "[email protected]", Name: "babel-helper-evaluate-path", Version: "0.5.0", Locations: []types.Location{{StartLine: 2643, EndLine: 2646}}},
{ID: "[email protected]", Name: "babel-helper-explode-assignable-expression", Version: "6.24.1", Locations: []types.Location{{StartLine: 2648, EndLine: 2655}}},
{ID: "[email protected]", Name: "babel-helper-explode-class", Version: "6.24.1", Locations: []types.Location{{StartLine: 2657, EndLine: 2665}}},
{ID: "[email protected]", Name: "babel-helper-flip-expressions", Version: "0.4.3", Locations: []types.Location{{StartLine: 2667, EndLine: 2670}}},
{ID: "[email protected]", Name: "babel-helper-function-name", Version: "6.24.1", Locations: []types.Location{{StartLine: 2672, EndLine: 2681}}},
{ID: "[email protected]", Name: "babel-helper-get-function-arity", Version: "6.24.1", Locations: []types.Location{{StartLine: 2683, EndLine: 2689}}},
{ID: "[email protected]", Name: "babel-helper-hoist-variables", Version: "6.24.1", Locations: []types.Location{{StartLine: 2691, EndLine: 2697}}},
{ID: "[email protected]", Name: "babel-helper-is-nodes-equiv", Version: "0.0.1", Locations: []types.Location{{StartLine: 2699, EndLine: 2702}}},
{ID: "[email protected]", Name: "babel-helper-is-void-0", Version: "0.4.3", Locations: []types.Location{{StartLine: 2704, EndLine: 2707}}},
{ID: "[email protected]", Name: "babel-helper-mark-eval-scopes", Version: "0.4.3", Locations: []types.Location{{StartLine: 2709, EndLine: 2712}}},
{ID: "[email protected]", Name: "babel-helper-optimise-call-expression", Version: "6.24.1", Locations: []types.Location{{StartLine: 2714, EndLine: 2720}}},
{ID: "[email protected]", Name: "babel-helper-regex", Version: "6.26.0", Locations: []types.Location{{StartLine: 2722, EndLine: 2729}}},
{ID: "[email protected]", Name: "babel-helper-remap-async-to-generator", Version: "6.24.1", Locations: []types.Location{{StartLine: 2731, EndLine: 2740}}},
{ID: "[email protected]", Name: "babel-helper-remove-or-void", Version: "0.4.3", Locations: []types.Location{{StartLine: 2742, EndLine: 2745}}},
{ID: "[email protected]", Name: "babel-helper-replace-supers", Version: "6.24.1", Locations: []types.Location{{StartLine: 2747, EndLine: 2757}}},
{ID: "[email protected]", Name: "babel-helper-to-multiple-sequence-expressions", Version: "0.5.0", Locations: []types.Location{{StartLine: 2759, EndLine: 2762}}},
{ID: "[email protected]", Name: "babel-helpers", Version: "6.24.1", Locations: []types.Location{{StartLine: 2764, EndLine: 2770}}},
{ID: "[email protected]", Name: "babel-jest", Version: "23.6.0", Locations: []types.Location{{StartLine: 2772, EndLine: 2778}}},
{ID: "[email protected]", Name: "babel-loader", Version: "8.0.4", Locations: []types.Location{{StartLine: 2780, EndLine: 2788}}},
{ID: "[email protected]", Name: "babel-loader", Version: "7.1.5", Locations: []types.Location{{StartLine: 2790, EndLine: 2797}}},
{ID: "[email protected]", Name: "babel-messages", Version: "6.23.0", Locations: []types.Location{{StartLine: 2799, EndLine: 2804}}},
{ID: "[email protected]", Name: "babel-plugin-check-es2015-constants", Version: "6.22.0", Locations: []types.Location{{StartLine: 2806, EndLine: 2811}}},
{ID: "[email protected]", Name: "babel-plugin-dynamic-import-node", Version: "2.2.0", Locations: []types.Location{{StartLine: 2813, EndLine: 2818}}},
{ID: "[email protected]", Name: "babel-plugin-istanbul", Version: "4.1.6", Locations: []types.Location{{StartLine: 2820, EndLine: 2828}}},
{ID: "[email protected]", Name: "babel-plugin-jest-hoist", Version: "23.2.0", Locations: []types.Location{{StartLine: 2830, EndLine: 2833}}},
{ID: "[email protected]", Name: "babel-plugin-macros", Version: "2.4.2", Locations: []types.Location{{StartLine: 2835, EndLine: 2841}}},
{ID: "[email protected]", Name: "babel-plugin-macros", Version: "2.5.1", Locations: []types.Location{{StartLine: 2843, EndLine: 2850}}},
{ID: "[email protected]", Name: "babel-plugin-minify-builtins", Version: "0.5.0", Locations: []types.Location{{StartLine: 2852, EndLine: 2855}}},
{ID: "[email protected]", Name: "babel-plugin-minify-constant-folding", Version: "0.5.0", Locations: []types.Location{{StartLine: 2857, EndLine: 2862}}},
{ID: "[email protected]", Name: "babel-plugin-minify-dead-code-elimination", Version: "0.5.0", Locations: []types.Location{{StartLine: 2864, EndLine: 2872}}},
{ID: "[email protected]", Name: "babel-plugin-minify-flip-comparisons", Version: "0.4.3", Locations: []types.Location{{StartLine: 2874, EndLine: 2879}}},
{ID: "[email protected]", Name: "babel-plugin-minify-guarded-expressions", Version: "0.4.3", Locations: []types.Location{{StartLine: 2881, EndLine: 2886}}},
{ID: "[email protected]", Name: "babel-plugin-minify-infinity", Version: "0.4.3", Locations: []types.Location{{StartLine: 2888, EndLine: 2891}}},
{ID: "[email protected]", Name: "babel-plugin-minify-mangle-names", Version: "0.5.0", Locations: []types.Location{{StartLine: 2893, EndLine: 2898}}},
{ID: "[email protected]", Name: "babel-plugin-minify-numeric-literals", Version: "0.4.3", Locations: []types.Location{{StartLine: 2900, EndLine: 2903}}},
{ID: "[email protected]", Name: "babel-plugin-minify-replace", Version: "0.5.0", Locations: []types.Location{{StartLine: 2905, EndLine: 2908}}},
{ID: "[email protected]", Name: "babel-plugin-minify-simplify", Version: "0.5.0", Locations: []types.Location{{StartLine: 2910, EndLine: 2917}}},
{ID: "[email protected]", Name: "babel-plugin-minify-type-constructors", Version: "0.4.3", Locations: []types.Location{{StartLine: 2919, EndLine: 2924}}},
{ID: "[email protected]", Name: "babel-plugin-named-asset-import", Version: "0.2.3", Locations: []types.Location{{StartLine: 2926, EndLine: 2929}}},
{ID: "[email protected]", Name: "babel-plugin-react-docgen", Version: "2.0.2", Locations: []types.Location{{StartLine: 2931, EndLine: 2938}}},
{ID: "[email protected]", Name: "babel-plugin-react-html-attrs", Version: "2.1.0", Locations: []types.Location{{StartLine: 2940, EndLine: 2943}}},
{ID: "[email protected]", Name: "babel-plugin-styled-components", Version: "1.10.0", Locations: []types.Location{{StartLine: 2945, EndLine: 2953}}},
{ID: "[email protected]", Name: "babel-plugin-syntax-async-functions", Version: "6.13.0", Locations: []types.Location{{StartLine: 2955, EndLine: 2958}}},
{ID: "[email protected]", Name: "babel-plugin-syntax-async-generators", Version: "6.13.0", Locations: []types.Location{{StartLine: 2960, EndLine: 2963}}},
{ID: "[email protected]", Name: "babel-plugin-syntax-class-constructor-call", Version: "6.18.0", Locations: []types.Location{{StartLine: 2965, EndLine: 2968}}},
{ID: "[email protected]", Name: "babel-plugin-syntax-class-properties", Version: "6.13.0", Locations: []types.Location{{StartLine: 2970, EndLine: 2973}}},
{ID: "[email protected]", Name: "babel-plugin-syntax-decorators", Version: "6.13.0", Locations: []types.Location{{StartLine: 2975, EndLine: 2978}}},
{ID: "[email protected]", Name: "babel-plugin-syntax-dynamic-import", Version: "6.18.0", Locations: []types.Location{{StartLine: 2980, EndLine: 2983}}},
{ID: "[email protected]", Name: "babel-plugin-syntax-exponentiation-operator", Version: "6.13.0", Locations: []types.Location{{StartLine: 2985, EndLine: 2988}}},
{ID: "[email protected]", Name: "babel-plugin-syntax-export-extensions", Version: "6.13.0", Locations: []types.Location{{StartLine: 2990, EndLine: 2993}}},
{ID: "[email protected]", Name: "babel-plugin-syntax-flow", Version: "6.18.0", Locations: []types.Location{{StartLine: 2995, EndLine: 2998}}},
{ID: "[email protected]", Name: "babel-plugin-syntax-jsx", Version: "6.18.0", Locations: []types.Location{{StartLine: 3000, EndLine: 3003}}},
{ID: "[email protected]", Name: "babel-plugin-syntax-object-rest-spread", Version: "6.13.0", Locations: []types.Location{{StartLine: 3005, EndLine: 3008}}},
{ID: "[email protected]", Name: "babel-plugin-syntax-trailing-function-commas", Version: "6.22.0", Locations: []types.Location{{StartLine: 3010, EndLine: 3013}}},
{ID: "[email protected]", Name: "babel-plugin-transform-async-generator-functions", Version: "6.24.1", Locations: []types.Location{{StartLine: 3015, EndLine: 3022}}},
{ID: "[email protected]", Name: "babel-plugin-transform-async-to-generator", Version: "6.24.1", Locations: []types.Location{{StartLine: 3024, EndLine: 3031}}},
{ID: "[email protected]", Name: "babel-plugin-transform-class-constructor-call", Version: "6.24.1", Locations: []types.Location{{StartLine: 3033, EndLine: 3040}}},
{ID: "[email protected]", Name: "babel-plugin-transform-class-properties", Version: "6.24.1", Locations: []types.Location{{StartLine: 3042, EndLine: 3050}}},
{ID: "[email protected]", Name: "babel-plugin-transform-decorators", Version: "6.24.1", Locations: []types.Location{{StartLine: 3052, EndLine: 3061}}},
{ID: "[email protected]", Name: "babel-plugin-transform-es2015-arrow-functions", Version: "6.22.0", Locations: []types.Location{{StartLine: 3063, EndLine: 3068}}},
{ID: "[email protected]", Name: "babel-plugin-transform-es2015-block-scoped-functions", Version: "6.22.0", Locations: []types.Location{{StartLine: 3070, EndLine: 3075}}},
{ID: "[email protected]", Name: "babel-plugin-transform-es2015-block-scoping", Version: "6.26.0", Locations: []types.Location{{StartLine: 3077, EndLine: 3086}}},
{ID: "[email protected]", Name: "babel-plugin-transform-es2015-classes", Version: "6.24.1", Locations: []types.Location{{StartLine: 3088, EndLine: 3101}}},
{ID: "[email protected]", Name: "babel-plugin-transform-es2015-computed-properties", Version: "6.24.1", Locations: []types.Location{{StartLine: 3103, EndLine: 3109}}},
{ID: "[email protected]", Name: "babel-plugin-transform-es2015-destructuring", Version: "6.23.0", Locations: []types.Location{{StartLine: 3111, EndLine: 3116}}},
{ID: "[email protected]", Name: "babel-plugin-transform-es2015-duplicate-keys", Version: "6.24.1", Locations: []types.Location{{StartLine: 3118, EndLine: 3124}}},
{ID: "[email protected]", Name: "babel-plugin-transform-es2015-for-of", Version: "6.23.0", Locations: []types.Location{{StartLine: 3126, EndLine: 3131}}},
{ID: "[email protected]", Name: "babel-plugin-transform-es2015-function-name", Version: "6.24.1", Locations: []types.Location{{StartLine: 3133, EndLine: 3140}}},
{ID: "[email protected]", Name: "babel-plugin-transform-es2015-literals", Version: "6.22.0", Locations: []types.Location{{StartLine: 3142, EndLine: 3147}}},
{ID: "[email protected]", Name: "babel-plugin-transform-es2015-modules-amd", Version: "6.24.1", Locations: []types.Location{{StartLine: 3149, EndLine: 3156}}},
{ID: "[email protected]", Name: "babel-plugin-transform-es2015-modules-commonjs", Version: "6.26.2", Locations: []types.Location{{StartLine: 3158, EndLine: 3166}}},
{ID: "[email protected]", Name: "babel-plugin-transform-es2015-modules-systemjs", Version: "6.24.1", Locations: []types.Location{{StartLine: 3168, EndLine: 3175}}},
{ID: "[email protected]", Name: "babel-plugin-transform-es2015-modules-umd", Version: "6.24.1", Locations: []types.Location{{StartLine: 3177, EndLine: 3184}}},
{ID: "[email protected]", Name: "babel-plugin-transform-es2015-object-super", Version: "6.24.1", Locations: []types.Location{{StartLine: 3186, EndLine: 3192}}},
{ID: "[email protected]", Name: "babel-plugin-transform-es2015-parameters", Version: "6.24.1", Locations: []types.Location{{StartLine: 3194, EndLine: 3204}}},
{ID: "[email protected]", Name: "babel-plugin-transform-es2015-shorthand-properties", Version: "6.24.1", Locations: []types.Location{{StartLine: 3206, EndLine: 3212}}},
{ID: "[email protected]", Name: "babel-plugin-transform-es2015-spread", Version: "6.22.0", Locations: []types.Location{{StartLine: 3214, EndLine: 3219}}},
{ID: "[email protected]", Name: "babel-plugin-transform-es2015-sticky-regex", Version: "6.24.1", Locations: []types.Location{{StartLine: 3221, EndLine: 3228}}},
{ID: "[email protected]", Name: "babel-plugin-transform-es2015-template-literals", Version: "6.22.0", Locations: []types.Location{{StartLine: 3230, EndLine: 3235}}},
{ID: "[email protected]", Name: "babel-plugin-transform-es2015-typeof-symbol", Version: "6.23.0", Locations: []types.Location{{StartLine: 3237, EndLine: 3242}}},
{ID: "[email protected]", Name: "babel-plugin-transform-es2015-unicode-regex", Version: "6.24.1", Locations: []types.Location{{StartLine: 3244, EndLine: 3251}}},
{ID: "[email protected]", Name: "babel-plugin-transform-exponentiation-operator", Version: "6.24.1", Locations: []types.Location{{StartLine: 3253, EndLine: 3260}}},
{ID: "[email protected]", Name: "babel-plugin-transform-export-extensions", Version: "6.22.0", Locations: []types.Location{{StartLine: 3262, EndLine: 3268}}},
{ID: "[email protected]", Name: "babel-plugin-transform-flow-strip-types", Version: "6.22.0", Locations: []types.Location{{StartLine: 3270, EndLine: 3276}}},
{ID: "[email protected]", Name: "babel-plugin-transform-inline-consecutive-adds", Version: "0.4.3", Locations: []types.Location{{StartLine: 3278, EndLine: 3281}}},
{ID: "[email protected]", Name: "babel-plugin-transform-member-expression-literals", Version: "6.9.4", Locations: []types.Location{{StartLine: 3283, EndLine: 3286}}},
{ID: "[email protected]", Name: "babel-plugin-transform-merge-sibling-variables", Version: "6.9.4", Locations: []types.Location{{StartLine: 3288, EndLine: 3291}}},
{ID: "[email protected]", Name: "babel-plugin-transform-minify-booleans", Version: "6.9.4", Locations: []types.Location{{StartLine: 3293, EndLine: 3296}}},
{ID: "[email protected]", Name: "babel-plugin-transform-object-rest-spread", Version: "6.26.0", Locations: []types.Location{{StartLine: 3298, EndLine: 3304}}},
{ID: "[email protected]", Name: "babel-plugin-transform-property-literals", Version: "6.9.4", Locations: []types.Location{{StartLine: 3306, EndLine: 3311}}},
{ID: "[email protected]", Name: "babel-plugin-transform-react-display-name", Version: "6.25.0", Locations: []types.Location{{StartLine: 3313, EndLine: 3318}}},
{ID: "[email protected]", Name: "babel-plugin-transform-react-jsx-self", Version: "6.22.0", Locations: []types.Location{{StartLine: 3320, EndLine: 3326}}},
{ID: "[email protected]", Name: "babel-plugin-transform-react-jsx-source", Version: "6.22.0", Locations: []types.Location{{StartLine: 3328, EndLine: 3334}}},
{ID: "[email protected]", Name: "babel-plugin-transform-react-jsx", Version: "6.24.1", Locations: []types.Location{{StartLine: 3336, EndLine: 3343}}},
{ID: "[email protected]", Name: "babel-plugin-transform-react-remove-prop-types", Version: "0.4.18", Locations: []types.Location{{StartLine: 3345, EndLine: 3348}}},
{ID: "[email protected]", Name: "babel-plugin-transform-regenerator", Version: "6.26.0", Locations: []types.Location{{StartLine: 3350, EndLine: 3355}}},
{ID: "[email protected]", Name: "babel-plugin-transform-regexp-constructors", Version: "0.4.3", Locations: []types.Location{{StartLine: 3357, EndLine: 3360}}},
{ID: "[email protected]", Name: "babel-plugin-transform-remove-console", Version: "6.9.4", Locations: []types.Location{{StartLine: 3362, EndLine: 3365}}},
{ID: "[email protected]", Name: "babel-plugin-transform-remove-debugger", Version: "6.9.4", Locations: []types.Location{{StartLine: 3367, EndLine: 3370}}},
{ID: "[email protected]", Name: "babel-plugin-transform-remove-undefined", Version: "0.5.0", Locations: []types.Location{{StartLine: 3372, EndLine: 3377}}},
{ID: "[email protected]", Name: "babel-plugin-transform-runtime", Version: "6.23.0", Locations: []types.Location{{StartLine: 3379, EndLine: 3384}}},
{ID: "[email protected]", Name: "babel-plugin-transform-simplify-comparison-operators", Version: "6.9.4", Locations: []types.Location{{StartLine: 3386, EndLine: 3389}}},
{ID: "[email protected]", Name: "babel-plugin-transform-strict-mode", Version: "6.24.1", Locations: []types.Location{{StartLine: 3391, EndLine: 3397}}},
{ID: "[email protected]", Name: "babel-plugin-transform-undefined-to-void", Version: "6.9.4", Locations: []types.Location{{StartLine: 3399, EndLine: 3402}}},
{ID: "[email protected]", Name: "babel-polyfill", Version: "6.26.0", Locations: []types.Location{{StartLine: 3404, EndLine: 3411}}},
{ID: "[email protected]", Name: "babel-preset-env", Version: "1.7.0", Locations: []types.Location{{StartLine: 3413, EndLine: 3447}}},
{ID: "[email protected]", Name: "babel-preset-es2015", Version: "6.24.1", Locations: []types.Location{{StartLine: 3449, EndLine: 3477}}},
{ID: "[email protected]", Name: "babel-preset-flow", Version: "6.23.0", Locations: []types.Location{{StartLine: 3479, EndLine: 3484}}},
{ID: "[email protected]", Name: "babel-preset-jest", Version: "23.2.0", Locations: []types.Location{{StartLine: 3486, EndLine: 3492}}},
{ID: "[email protected]", Name: "babel-preset-minify", Version: "0.5.0", Locations: []types.Location{{StartLine: 3494, EndLine: 3521}}},
{ID: "[email protected]", Name: "babel-preset-react-app", Version: "6.1.0", Locations: []types.Location{{StartLine: 3523, EndLine: 3546}}},
{ID: "[email protected]", Name: "babel-preset-react", Version: "6.24.1", Locations: []types.Location{{StartLine: 3548, EndLine: 3558}}},
{ID: "[email protected]", Name: "babel-preset-stage-1", Version: "6.24.1", Locations: []types.Location{{StartLine: 3560, EndLine: 3567}}},
{ID: "[email protected]", Name: "babel-preset-stage-2", Version: "6.24.1", Locations: []types.Location{{StartLine: 3569, EndLine: 3577}}},
{ID: "[email protected]", Name: "babel-preset-stage-3", Version: "6.24.1", Locations: []types.Location{{StartLine: 3579, EndLine: 3588}}},
{ID: "[email protected]", Name: "babel-register", Version: "6.26.0", Locations: []types.Location{{StartLine: 3590, EndLine: 3601}}},
{ID: "[email protected]", Name: "babel-runtime", Version: "6.26.0", Locations: []types.Location{{StartLine: 3603, EndLine: 3609}}},
{ID: "[email protected]", Name: "babel-standalone", Version: "6.26.0", Locations: []types.Location{{StartLine: 3611, EndLine: 3614}}},
{ID: "[email protected]", Name: "babel-template", Version: "6.26.0", Locations: []types.Location{{StartLine: 3616, EndLine: 3625}}},
{ID: "[email protected]", Name: "babel-traverse", Version: "6.26.0", Locations: []types.Location{{StartLine: 3627, EndLine: 3640}}},
{ID: "[email protected]", Name: "babel-types", Version: "6.26.0", Locations: []types.Location{{StartLine: 3642, EndLine: 3650}}},
{ID: "[email protected]", Name: "babylon", Version: "7.0.0-beta.44", Locations: []types.Location{{StartLine: 3652, EndLine: 3655}}},
{ID: "[email protected]", Name: "babylon", Version: "6.18.0", Locations: []types.Location{{StartLine: 3657, EndLine: 3660}}},
{ID: "[email protected]", Name: "babylon", Version: "7.0.0-beta.47", Locations: []types.Location{{StartLine: 3662, EndLine: 3665}}},
{ID: "[email protected]", Name: "backo2", Version: "1.0.2", Locations: []types.Location{{StartLine: 3667, EndLine: 3670}}},
{ID: "[email protected]", Name: "bail", Version: "1.0.4", Locations: []types.Location{{StartLine: 3672, EndLine: 3675}}},
{ID: "[email protected]", Name: "balanced-match", Version: "1.0.0", Locations: []types.Location{{StartLine: 3677, EndLine: 3680}}},
{ID: "[email protected]", Name: "base64-arraybuffer", Version: "0.1.5", Locations: []types.Location{{StartLine: 3682, EndLine: 3685}}},
{ID: "[email protected]", Name: "base64-js", Version: "1.3.0", Locations: []types.Location{{StartLine: 3687, EndLine: 3690}}},
{ID: "[email protected]", Name: "base64id", Version: "1.0.0", Locations: []types.Location{{StartLine: 3692, EndLine: 3695}}},
{ID: "[email protected]", Name: "base", Version: "0.11.2", Locations: []types.Location{{StartLine: 3697, EndLine: 3708}}},
{ID: "[email protected]", Name: "batch", Version: "0.6.1", Locations: []types.Location{{StartLine: 3710, EndLine: 3713}}},
{ID: "[email protected]", Name: "bcrypt-pbkdf", Version: "1.0.2", Locations: []types.Location{{StartLine: 3715, EndLine: 3720}}},
{ID: "[email protected]", Name: "before-after-hook", Version: "1.4.0", Locations: []types.Location{{StartLine: 3722, EndLine: 3725}}},
{ID: "[email protected]", Name: "better-assert", Version: "1.0.2", Locations: []types.Location{{StartLine: 3727, EndLine: 3732}}},
{ID: "[email protected]", Name: "bfj", Version: "6.1.1", Locations: []types.Location{{StartLine: 3734, EndLine: 3742}}},
{ID: "[email protected]", Name: "big-integer", Version: "1.6.43", Locations: []types.Location{{StartLine: 3744, EndLine: 3747}}},
{ID: "[email protected]", Name: "big.js", Version: "3.2.0", Locations: []types.Location{{StartLine: 3749, EndLine: 3752}}},
{ID: "[email protected]", Name: "big.js", Version: "5.2.2", Locations: []types.Location{{StartLine: 3754, EndLine: 3757}}},
{ID: "[email protected]", Name: "bin-links", Version: "1.1.2", Locations: []types.Location{{StartLine: 3759, EndLine: 3768}}},
{ID: "[email protected]", Name: "binary-extensions", Version: "1.13.1", Locations: []types.Location{{StartLine: 3770, EndLine: 3773}}},
{ID: "[email protected]", Name: "binary", Version: "0.3.0", Locations: []types.Location{{StartLine: 3775, EndLine: 3781}}},
{ID: "[email protected]", Name: "blob", Version: "0.0.5", Locations: []types.Location{{StartLine: 3783, EndLine: 3786}}},
{ID: "[email protected]", Name: "block-stream", Version: "0.0.9", Locations: []types.Location{{StartLine: 3788, EndLine: 3793}}},
{ID: "[email protected]", Name: "bluebird", Version: "3.5.4", Locations: []types.Location{{StartLine: 3795, EndLine: 3798}}},
{ID: "[email protected]", Name: "bluebird", Version: "3.4.7", Locations: []types.Location{{StartLine: 3800, EndLine: 3803}}},
{ID: "[email protected]", Name: "bn.js", Version: "4.11.8", Locations: []types.Location{{StartLine: 3805, EndLine: 3808}}},
{ID: "[email protected]", Name: "body-parser", Version: "1.18.3", Locations: []types.Location{{StartLine: 3810, EndLine: 3824}}},
{ID: "[email protected]", Name: "bonjour", Version: "3.5.0", Locations: []types.Location{{StartLine: 3826, EndLine: 3836}}},
{ID: "[email protected]", Name: "boolbase", Version: "1.0.0", Locations: []types.Location{{StartLine: 3838, EndLine: 3841}}},
{ID: "[email protected]", Name: "boxen", Version: "1.3.0", Locations: []types.Location{{StartLine: 3843, EndLine: 3854}}},
{ID: "[email protected]", Name: "boxen", Version: "2.1.0", Locations: []types.Location{{StartLine: 3856, EndLine: 3867}}},
{ID: "[email protected]", Name: "brace-expansion", Version: "1.1.11", Locations: []types.Location{{StartLine: 3869, EndLine: 3875}}},
{ID: "[email protected]", Name: "braces", Version: "1.8.5", Locations: []types.Location{{StartLine: 3877, EndLine: 3884}}},
{ID: "[email protected]", Name: "braces", Version: "2.3.2", Locations: []types.Location{{StartLine: 3886, EndLine: 3900}}},
{ID: "[email protected]", Name: "brcast", Version: "3.0.1", Locations: []types.Location{{StartLine: 3902, EndLine: 3905}}},
{ID: "[email protected]", Name: "brorand", Version: "1.1.0", Locations: []types.Location{{StartLine: 3907, EndLine: 3910}}},
{ID: "[email protected]", Name: "browser-process-hrtime", Version: "0.1.3", Locations: []types.Location{{StartLine: 3912, EndLine: 3915}}},
{ID: "[email protected]", Name: "browser-resolve", Version: "1.11.3", Locations: []types.Location{{StartLine: 3917, EndLine: 3922}}},
{ID: "[email protected]", Name: "browserify-aes", Version: "1.2.0", Locations: []types.Location{{StartLine: 3924, EndLine: 3934}}},
{ID: "[email protected]", Name: "browserify-cipher", Version: "1.0.1", Locations: []types.Location{{StartLine: 3936, EndLine: 3943}}},
{ID: "[email protected]", Name: "browserify-des", Version: "1.0.2", Locations: []types.Location{{StartLine: 3945, EndLine: 3953}}},
{ID: "[email protected]", Name: "browserify-rsa", Version: "4.0.1", Locations: []types.Location{{StartLine: 3955, EndLine: 3961}}},
{ID: "[email protected]", Name: "browserify-sign", Version: "4.0.4", Locations: []types.Location{{StartLine: 3963, EndLine: 3974}}},
{ID: "[email protected]", Name: "browserify-zlib", Version: "0.2.0", Locations: []types.Location{{StartLine: 3976, EndLine: 3981}}},
{ID: "[email protected]", Name: "browserslist", Version: "4.1.1", Locations: []types.Location{{StartLine: 3983, EndLine: 3990}}},
{ID: "[email protected]", Name: "browserslist", Version: "3.2.8", Locations: []types.Location{{StartLine: 3992, EndLine: 3998}}},
{ID: "[email protected]", Name: "browserslist", Version: "4.6.0", Locations: []types.Location{{StartLine: 4000, EndLine: 4007}}},
{ID: "[email protected]", Name: "bser", Version: "2.0.0", Locations: []types.Location{{StartLine: 4009, EndLine: 4014}}},
{ID: "[email protected]", Name: "btoa-lite", Version: "1.0.0", Locations: []types.Location{{StartLine: 4016, EndLine: 4019}}},
{ID: "[email protected]", Name: "buffer-from", Version: "1.1.1", Locations: []types.Location{{StartLine: 4021, EndLine: 4024}}},
{ID: "[email protected]", Name: "buffer-indexof-polyfill", Version: "1.0.1", Locations: []types.Location{{StartLine: 4026, EndLine: 4029}}},
{ID: "[email protected]", Name: "buffer-indexof", Version: "1.1.1", Locations: []types.Location{{StartLine: 4031, EndLine: 4034}}},
{ID: "[email protected]", Name: "buffer-shims", Version: "1.0.0", Locations: []types.Location{{StartLine: 4036, EndLine: 4039}}},
{ID: "[email protected]", Name: "buffer-xor", Version: "1.0.3", Locations: []types.Location{{StartLine: 4041, EndLine: 4044}}},
{ID: "[email protected]", Name: "buffer", Version: "4.9.1", Locations: []types.Location{{StartLine: 4046, EndLine: 4053}}},
{ID: "[email protected]", Name: "buffers", Version: "0.1.1", Locations: []types.Location{{StartLine: 4055, EndLine: 4058}}},
{ID: "[email protected]", Name: "builtin-status-codes", Version: "3.0.0", Locations: []types.Location{{StartLine: 4060, EndLine: 4063}}},
{ID: "[email protected]", Name: "builtins", Version: "1.0.3", Locations: []types.Location{{StartLine: 4065, EndLine: 4068}}},
{ID: "[email protected]", Name: "byline", Version: "5.0.0", Locations: []types.Location{{StartLine: 4070, EndLine: 4073}}},
{ID: "[email protected]", Name: "byte-size", Version: "5.0.1", Locations: []types.Location{{StartLine: 4075, EndLine: 4078}}},
{ID: "[email protected]", Name: "bytes", Version: "3.0.0", Locations: []types.Location{{StartLine: 4080, EndLine: 4083}}},
{ID: "[email protected]", Name: "cacache", Version: "10.0.4", Locations: []types.Location{{StartLine: 4085, EndLine: 4102}}},
{ID: "[email protected]", Name: "cacache", Version: "11.3.2", Locations: []types.Location{{StartLine: 4104, EndLine: 4122}}},
{ID: "[email protected]", Name: "cache-base", Version: "1.0.1", Locations: []types.Location{{StartLine: 4124, EndLine: 4137}}},
{ID: "[email protected]", Name: "cache-loader", Version: "1.2.5", Locations: []types.Location{{StartLine: 4139, EndLine: 4147}}},
{ID: "[email protected]", Name: "call-limit", Version: "1.1.0", Locations: []types.Location{{StartLine: 4149, EndLine: 4152}}},
{ID: "[email protected]", Name: "call-me-maybe", Version: "1.0.1", Locations: []types.Location{{StartLine: 4154, EndLine: 4157}}},
{ID: "[email protected]", Name: "caller-callsite", Version: "2.0.0", Locations: []types.Location{{StartLine: 4159, EndLine: 4164}}},
{ID: "[email protected]", Name: "caller-path", Version: "2.0.0", Locations: []types.Location{{StartLine: 4166, EndLine: 4171}}},
{ID: "[email protected]", Name: "callsite", Version: "1.0.0", Locations: []types.Location{{StartLine: 4173, EndLine: 4176}}},
{ID: "[email protected]", Name: "callsites", Version: "2.0.0", Locations: []types.Location{{StartLine: 4178, EndLine: 4181}}},
{ID: "[email protected]", Name: "callsites", Version: "3.1.0", Locations: []types.Location{{StartLine: 4183, EndLine: 4186}}},
{ID: "[email protected]", Name: "camel-case", Version: "3.0.0", Locations: []types.Location{{StartLine: 4188, EndLine: 4194}}},
{ID: "[email protected]", Name: "camelcase", Version: "3.0.0", Locations: []types.Location{{StartLine: 4196, EndLine: 4199}}},
{ID: "[email protected]", Name: "camelcase", Version: "4.1.0", Locations: []types.Location{{StartLine: 4201, EndLine: 4204}}},
{ID: "[email protected]", Name: "camelcase", Version: "5.3.1", Locations: []types.Location{{StartLine: 4206, EndLine: 4209}}},
{ID: "[email protected]", Name: "camelize", Version: "1.0.0", Locations: []types.Location{{StartLine: 4211, EndLine: 4214}}},
{ID: "[email protected]", Name: "caniuse-lite", Version: "1.0.30000967", Locations: []types.Location{{StartLine: 4216, EndLine: 4219}}},
{ID: "[email protected]", Name: "capture-exit", Version: "1.2.0", Locations: []types.Location{{StartLine: 4221, EndLine: 4226}}},
{ID: "[email protected]", Name: "capture-stack-trace", Version: "1.0.1", Locations: []types.Location{{StartLine: 4228, EndLine: 4231}}},
{ID: "[email protected]", Name: "case-sensitive-paths-webpack-plugin", Version: "2.2.0", Locations: []types.Location{{StartLine: 4233, EndLine: 4236}}},
{ID: "[email protected]", Name: "caseless", Version: "0.12.0", Locations: []types.Location{{StartLine: 4238, EndLine: 4241}}},
{ID: "[email protected]", Name: "ccount", Version: "1.0.4", Locations: []types.Location{{StartLine: 4243, EndLine: 4246}}},
{ID: "[email protected]", Name: "chainsaw", Version: "0.1.0", Locations: []types.Location{{StartLine: 4248, EndLine: 4253}}},
{ID: "[email protected]", Name: "chalk", Version: "2.4.1", Locations: []types.Location{{StartLine: 4255, EndLine: 4262}}},
{ID: "[email protected]", Name: "chalk", Version: "1.1.3", Locations: []types.Location{{StartLine: 4264, EndLine: 4273}}},
{ID: "[email protected]", Name: "chalk", Version: "2.4.2", Locations: []types.Location{{StartLine: 4275, EndLine: 4282}}},
{ID: "[email protected]", Name: "chalk", Version: "0.4.0", Locations: []types.Location{{StartLine: 4284, EndLine: 4291}}},
{ID: "[email protected]", Name: "change-emitter", Version: "0.1.6", Locations: []types.Location{{StartLine: 4293, EndLine: 4296}}},
{ID: "[email protected]", Name: "chardet", Version: "0.7.0", Locations: []types.Location{{StartLine: 4298, EndLine: 4301}}},
{ID: "[email protected]", Name: "charenc", Version: "0.0.2", Locations: []types.Location{{StartLine: 4303, EndLine: 4306}}},
{ID: "[email protected]", Name: "check-types", Version: "7.4.0", Locations: []types.Location{{StartLine: 4308, EndLine: 4311}}},
{ID: "[email protected]", Name: "cheerio", Version: "1.0.0-rc.3", Locations: []types.Location{{StartLine: 4313, EndLine: 4323}}},
{ID: "[email protected]", Name: "child-process-promise", Version: "2.2.1", Locations: []types.Location{{StartLine: 4325, EndLine: 4332}}},
{ID: "[email protected]", Name: "chokidar", Version: "1.7.0", Locations: []types.Location{{StartLine: 4334, EndLine: 4348}}},
{ID: "[email protected]", Name: "chokidar", Version: "2.1.5", Locations: []types.Location{{StartLine: 4350, EndLine: 4367}}},
{ID: "[email protected]", Name: "chownr", Version: "1.1.1", Locations: []types.Location{{StartLine: 4369, EndLine: 4372}}},
{ID: "[email protected]", Name: "chrome-trace-event", Version: "1.0.0", Locations: []types.Location{{StartLine: 4374, EndLine: 4379}}},
{ID: "[email protected]", Name: "ci-info", Version: "1.6.0", Locations: []types.Location{{StartLine: 4381, EndLine: 4384}}},
{ID: "[email protected]", Name: "ci-info", Version: "2.0.0", Locations: []types.Location{{StartLine: 4386, EndLine: 4389}}},
{ID: "[email protected]", Name: "cidr-regex", Version: "2.0.10", Locations: []types.Location{{StartLine: 4391, EndLine: 4396}}},
{ID: "[email protected]", Name: "cipher-base", Version: "1.0.4", Locations: []types.Location{{StartLine: 4398, EndLine: 4404}}},
{ID: "[email protected]", Name: "class-utils", Version: "0.3.6", Locations: []types.Location{{StartLine: 4406, EndLine: 4414}}},
{ID: "[email protected]", Name: "classnames", Version: "2.2.6", Locations: []types.Location{{StartLine: 4416, EndLine: 4419}}},
{ID: "[email protected]", Name: "clean-css", Version: "4.2.1", Locations: []types.Location{{StartLine: 4421, EndLine: 4426}}},
{ID: "[email protected]", Name: "clean-webpack-plugin", Version: "0.1.19", Locations: []types.Location{{StartLine: 4428, EndLine: 4433}}},
{ID: "[email protected]", Name: "cli-boxes", Version: "1.0.0", Locations: []types.Location{{StartLine: 4435, EndLine: 4438}}},
{ID: "[email protected]", Name: "cli-columns", Version: "3.1.2", Locations: []types.Location{{StartLine: 4440, EndLine: 4446}}},
{ID: "[email protected]", Name: "cli-cursor", Version: "1.0.2", Locations: []types.Location{{StartLine: 4448, EndLine: 4453}}},
{ID: "[email protected]", Name: "cli-cursor", Version: "2.1.0", Locations: []types.Location{{StartLine: 4455, EndLine: 4460}}},
{ID: "[email protected]", Name: "cli-table3", Version: "0.5.1", Locations: []types.Location{{StartLine: 4462, EndLine: 4470}}},
{ID: "[email protected]", Name: "cli-truncate", Version: "0.2.1", Locations: []types.Location{{StartLine: 4472, EndLine: 4478}}},
{ID: "[email protected]", Name: "cli-width", Version: "1.1.1", Locations: []types.Location{{StartLine: 4480, EndLine: 4483}}},
{ID: "[email protected]", Name: "cli-width", Version: "2.2.0", Locations: []types.Location{{StartLine: 4485, EndLine: 4488}}},
{ID: "[email protected]", Name: "cliui", Version: "3.2.0", Locations: []types.Location{{StartLine: 4490, EndLine: 4497}}},
{ID: "[email protected]", Name: "cliui", Version: "4.1.0", Locations: []types.Location{{StartLine: 4499, EndLine: 4506}}},
{ID: "[email protected]", Name: "clone-deep", Version: "0.2.4", Locations: []types.Location{{StartLine: 4508, EndLine: 4517}}},
{ID: "[email protected]", Name: "clone", Version: "1.0.4", Locations: []types.Location{{StartLine: 4519, EndLine: 4522}}},
{ID: "[email protected]", Name: "clsx", Version: "1.0.4", Locations: []types.Location{{StartLine: 4524, EndLine: 4527}}},
{ID: "[email protected]", Name: "cmd-shim", Version: "2.0.2", Locations: []types.Location{{StartLine: 4529, EndLine: 4535}}},
{ID: "[email protected]", Name: "co", Version: "4.6.0", Locations: []types.Location{{StartLine: 4537, EndLine: 4540}}},
{ID: "[email protected]", Name: "coa", Version: "2.0.2", Locations: []types.Location{{StartLine: 4542, EndLine: 4549}}},
{ID: "[email protected]", Name: "code-point-at", Version: "1.1.0", Locations: []types.Location{{StartLine: 4551, EndLine: 4554}}},
{ID: "[email protected]", Name: "collection-visit", Version: "1.0.0", Locations: []types.Location{{StartLine: 4556, EndLine: 4562}}},
{ID: "[email protected]", Name: "color-convert", Version: "1.9.3", Locations: []types.Location{{StartLine: 4564, EndLine: 4569}}},
{ID: "[email protected]", Name: "color-name", Version: "1.1.3", Locations: []types.Location{{StartLine: 4571, EndLine: 4574}}},
{ID: "[email protected]", Name: "colors", Version: "1.3.3", Locations: []types.Location{{StartLine: 4576, EndLine: 4579}}},
{ID: "[email protected]", Name: "columnify", Version: "1.5.4", Locations: []types.Location{{StartLine: 4581, EndLine: 4587}}},
{ID: "[email protected]", Name: "combined-stream", Version: "1.0.8", Locations: []types.Location{{StartLine: 4589, EndLine: 4594}}},
{ID: "[email protected]", Name: "comma-separated-tokens", Version: "1.0.7", Locations: []types.Location{{StartLine: 4596, EndLine: 4599}}},
{ID: "[email protected]", Name: "commander", Version: "2.17.1", Locations: []types.Location{{StartLine: 4601, EndLine: 4604}}},
{ID: "[email protected]", Name: "commander", Version: "2.20.0", Locations: []types.Location{{StartLine: 4606, EndLine: 4609}}},
{ID: "[email protected]", Name: "commander", Version: "2.19.0", Locations: []types.Location{{StartLine: 4611, EndLine: 4614}}},
{ID: "[email protected]", Name: "common-tags", Version: "1.8.0", Locations: []types.Location{{StartLine: 4616, EndLine: 4619}}},
{ID: "[email protected]", Name: "commondir", Version: "1.0.1", Locations: []types.Location{{StartLine: 4621, EndLine: 4624}}},
{ID: "[email protected]", Name: "component-bind", Version: "1.0.0", Locations: []types.Location{{StartLine: 4626, EndLine: 4629}}},
{ID: "[email protected]", Name: "component-emitter", Version: "1.2.1", Locations: []types.Location{{StartLine: 4631, EndLine: 4634}}},
{ID: "[email protected]", Name: "component-emitter", Version: "1.3.0", Locations: []types.Location{{StartLine: 4636, EndLine: 4639}}},
{ID: "[email protected]", Name: "component-inherit", Version: "0.0.3", Locations: []types.Location{{StartLine: 4641, EndLine: 4644}}},
{ID: "[email protected]", Name: "compressible", Version: "2.0.17", Locations: []types.Location{{StartLine: 4646, EndLine: 4651}}},
{ID: "[email protected]", Name: "compression", Version: "1.7.4", Locations: []types.Location{{StartLine: 4653, EndLine: 4664}}},
{ID: "[email protected]", Name: "concat-map", Version: "0.0.1", Locations: []types.Location{{StartLine: 4666, EndLine: 4669}}},
{ID: "[email protected]", Name: "concat-stream", Version: "1.6.2", Locations: []types.Location{{StartLine: 4671, EndLine: 4679}}},
{ID: "[email protected]", Name: "config-chain", Version: "1.1.12", Locations: []types.Location{{StartLine: 4681, EndLine: 4687}}},
{ID: "[email protected]", Name: "configstore", Version: "3.1.2", Locations: []types.Location{{StartLine: 4689, EndLine: 4699}}},
{ID: "[email protected]", Name: "connect-history-api-fallback", Version: "1.6.0", Locations: []types.Location{{StartLine: 4701, EndLine: 4704}}},
{ID: "[email protected]", Name: "console-browserify", Version: "1.1.0", Locations: []types.Location{{StartLine: 4706, EndLine: 4711}}},
{ID: "[email protected]", Name: "console-control-strings", Version: "1.1.0", Locations: []types.Location{{StartLine: 4713, EndLine: 4716}}},
{ID: "[email protected]", Name: "console-polyfill", Version: "0.3.0", Locations: []types.Location{{StartLine: 4718, EndLine: 4721}}},
{ID: "[email protected]", Name: "constants-browserify", Version: "1.0.0", Locations: []types.Location{{StartLine: 4723, EndLine: 4726}}},
{ID: "[email protected]", Name: "contains-path", Version: "0.1.0", Locations: []types.Location{{StartLine: 4728, EndLine: 4731}}},
{ID: "[email protected]", Name: "content-disposition", Version: "0.5.2", Locations: []types.Location{{StartLine: 4733, EndLine: 4736}}},
{ID: "[email protected]", Name: "content-type", Version: "1.0.4", Locations: []types.Location{{StartLine: 4738, EndLine: 4741}}},
{ID: "[email protected]", Name: "convert-source-map", Version: "1.6.0", Locations: []types.Location{{StartLine: 4743, EndLine: 4748}}},
{ID: "[email protected]", Name: "cookie-signature", Version: "1.0.6", Locations: []types.Location{{StartLine: 4750, EndLine: 4753}}},
{ID: "[email protected]", Name: "cookie", Version: "0.3.1", Locations: []types.Location{{StartLine: 4755, EndLine: 4758}}},
{ID: "[email protected]", Name: "copy-concurrently", Version: "1.0.5", Locations: []types.Location{{StartLine: 4760, EndLine: 4770}}},
{ID: "[email protected]", Name: "copy-descriptor", Version: "0.1.1", Locations: []types.Location{{StartLine: 4772, EndLine: 4775}}},
{ID: "[email protected]", Name: "copy-to-clipboard", Version: "3.2.0", Locations: []types.Location{{StartLine: 4777, EndLine: 4782}}},
{ID: "[email protected]", Name: "copy-webpack-plugin", Version: "4.6.0", Locations: []types.Location{{StartLine: 4784, EndLine: 4796}}},
{ID: "[email protected]", Name: "core-js-compat", Version: "3.0.1", Locations: []types.Location{{StartLine: 4798, EndLine: 4806}}},
{ID: "[email protected]", Name: "core-js-pure", Version: "3.0.1", Locations: []types.Location{{StartLine: 4808, EndLine: 4811}}},
{ID: "[email protected]", Name: "core-js", Version: "3.0.1", Locations: []types.Location{{StartLine: 4813, EndLine: 4816}}},
{ID: "[email protected]", Name: "core-js", Version: "1.2.7", Locations: []types.Location{{StartLine: 4818, EndLine: 4821}}},
{ID: "[email protected]", Name: "core-js", Version: "2.6.5", Locations: []types.Location{{StartLine: 4823, EndLine: 4826}}},
{ID: "[email protected]", Name: "core-util-is", Version: "1.0.2", Locations: []types.Location{{StartLine: 4828, EndLine: 4831}}},
{ID: "[email protected]", Name: "cosmiconfig", Version: "4.0.0", Locations: []types.Location{{StartLine: 4833, EndLine: 4841}}},
{ID: "[email protected]", Name: "cosmiconfig", Version: "5.2.1", Locations: []types.Location{{StartLine: 4843, EndLine: 4851}}},
{ID: "[email protected]", Name: "create-ecdh", Version: "4.0.3", Locations: []types.Location{{StartLine: 4853, EndLine: 4859}}},
{ID: "[email protected]", Name: "create-error-class", Version: "3.0.2", Locations: []types.Location{{StartLine: 4861, EndLine: 4866}}},
{ID: "[email protected]", Name: "create-hash", Version: "1.2.0", Locations: []types.Location{{StartLine: 4868, EndLine: 4877}}},
{ID: "[email protected]", Name: "create-hmac", Version: "1.1.7", Locations: []types.Location{{StartLine: 4879, EndLine: 4889}}},
{ID: "[email protected]", Name: "create-react-class", Version: "15.6.3", Locations: []types.Location{{StartLine: 4891, EndLine: 4898}}},
{ID: "[email protected]", Name: "create-react-context", Version: "0.2.2", Locations: []types.Location{{StartLine: 4900, EndLine: 4906}}},
{ID: "[email protected]", Name: "create-react-context", Version: "0.2.3", Locations: []types.Location{{StartLine: 4908, EndLine: 4914}}},
{ID: "[email protected]", Name: "cross-spawn", Version: "6.0.5", Locations: []types.Location{{StartLine: 4916, EndLine: 4925}}},
{ID: "[email protected]", Name: "cross-spawn", Version: "4.0.2", Locations: []types.Location{{StartLine: 4927, EndLine: 4933}}},
{ID: "[email protected]", Name: "cross-spawn", Version: "5.1.0", Locations: []types.Location{{StartLine: 4935, EndLine: 4942}}},
{ID: "[email protected]", Name: "crypt", Version: "0.0.2", Locations: []types.Location{{StartLine: 4944, EndLine: 4947}}},
{ID: "[email protected]", Name: "crypto-browserify", Version: "3.12.0", Locations: []types.Location{{StartLine: 4949, EndLine: 4964}}},
{ID: "[email protected]", Name: "crypto-random-string", Version: "1.0.0", Locations: []types.Location{{StartLine: 4966, EndLine: 4969}}},
{ID: "[email protected]", Name: "css-color-keywords", Version: "1.0.0", Locations: []types.Location{{StartLine: 4971, EndLine: 4974}}},
{ID: "[email protected]", Name: "css-loader", Version: "1.0.1", Locations: []types.Location{{StartLine: 4976, EndLine: 4992}}},
{ID: "[email protected]", Name: "css-select-base-adapter", Version: "0.1.1", Locations: []types.Location{{StartLine: 4994, EndLine: 4997}}},
{ID: "[email protected]", Name: "css-select", Version: "1.2.0", Locations: []types.Location{{StartLine: 4999, EndLine: 5007}}},
{ID: "[email protected]", Name: "css-select", Version: "2.0.2", Locations: []types.Location{{StartLine: 5009, EndLine: 5017}}},
{ID: "[email protected]", Name: "css-selector-tokenizer", Version: "0.7.1", Locations: []types.Location{{StartLine: 5019, EndLine: 5026}}},
{ID: "[email protected]", Name: "css-to-react-native", Version: "2.3.1", Locations: []types.Location{{StartLine: 5028, EndLine: 5035}}},
{ID: "[email protected]", Name: "css-tree", Version: "1.0.0-alpha.28", Locations: []types.Location{{StartLine: 5037, EndLine: 5043}}},
{ID: "[email protected]", Name: "css-tree", Version: "1.0.0-alpha.29", Locations: []types.Location{{StartLine: 5045, EndLine: 5051}}},
{ID: "[email protected]", Name: "css-url-regex", Version: "1.1.0", Locations: []types.Location{{StartLine: 5053, EndLine: 5056}}},
{ID: "[email protected]", Name: "css-vendor", Version: "0.3.8", Locations: []types.Location{{StartLine: 5058, EndLine: 5063}}},
{ID: "[email protected]", Name: "css-what", Version: "2.1.3", Locations: []types.Location{{StartLine: 5065, EndLine: 5068}}},
{ID: "[email protected]", Name: "cssesc", Version: "0.1.0", Locations: []types.Location{{StartLine: 5070, EndLine: 5073}}},
{ID: "[email protected]", Name: "csso", Version: "3.5.1", Locations: []types.Location{{StartLine: 5075, EndLine: 5080}}},
{ID: "[email protected]", Name: "cssom", Version: "0.3.6", Locations: []types.Location{{StartLine: 5082, EndLine: 5085}}},
{ID: "[email protected]", Name: "cssstyle", Version: "1.2.2", Locations: []types.Location{{StartLine: 5087, EndLine: 5092}}},
{ID: "[email protected]", Name: "csstype", Version: "2.6.4", Locations: []types.Location{{StartLine: 5094, EndLine: 5097}}},
{ID: "[email protected]", Name: "cyclist", Version: "0.2.2", Locations: []types.Location{{StartLine: 5099, EndLine: 5102}}},
{ID: "[email protected]", Name: "damerau-levenshtein", Version: "1.0.5", Locations: []types.Location{{StartLine: 5104, EndLine: 5107}}},
{ID: "[email protected]", Name: "dashdash", Version: "1.14.1", Locations: []types.Location{{StartLine: 5109, EndLine: 5114}}},
{ID: "[email protected]", Name: "data-urls", Version: "1.1.0", Locations: []types.Location{{StartLine: 5116, EndLine: 5123}}},
{ID: "[email protected]", Name: "date-fns", Version: "1.30.1", Locations: []types.Location{{StartLine: 5125, EndLine: 5128}}},
{ID: "[email protected]", Name: "date-fns", Version: "2.0.0-alpha.27", Locations: []types.Location{{StartLine: 5130, EndLine: 5133}}},
{ID: "[email protected]", Name: "date-now", Version: "0.1.4", Locations: []types.Location{{StartLine: 5135, EndLine: 5138}}},
{ID: "[email protected]", Name: "debounce", Version: "1.2.0", Locations: []types.Location{{StartLine: 5140, EndLine: 5143}}},
{ID: "[email protected]", Name: "debug", Version: "2.6.9", Locations: []types.Location{{StartLine: 5145, EndLine: 5150}}},
{ID: "[email protected]", Name: "debug", Version: "3.1.0", Locations: []types.Location{{StartLine: 5152, EndLine: 5157}}},
{ID: "[email protected]", Name: "debug", Version: "3.2.6", Locations: []types.Location{{StartLine: 5159, EndLine: 5164}}},
{ID: "[email protected]", Name: "debug", Version: "4.1.1", Locations: []types.Location{{StartLine: 5166, EndLine: 5171}}},
{ID: "[email protected]", Name: "debuglog", Version: "1.0.1", Locations: []types.Location{{StartLine: 5173, EndLine: 5176}}},
{ID: "[email protected]", Name: "decamelize", Version: "1.2.0", Locations: []types.Location{{StartLine: 5178, EndLine: 5181}}},
{ID: "[email protected]", Name: "decode-uri-component", Version: "0.2.0", Locations: []types.Location{{StartLine: 5183, EndLine: 5186}}},
{ID: "[email protected]", Name: "decompress-response", Version: "3.3.0", Locations: []types.Location{{StartLine: 5188, EndLine: 5193}}},
{ID: "[email protected]", Name: "dedent", Version: "0.7.0", Locations: []types.Location{{StartLine: 5195, EndLine: 5198}}},
{ID: "[email protected]", Name: "deep-equal", Version: "1.0.1", Locations: []types.Location{{StartLine: 5200, EndLine: 5203}}},
{ID: "[email protected]", Name: "deep-extend", Version: "0.6.0", Locations: []types.Location{{StartLine: 5205, EndLine: 5208}}},
{ID: "[email protected]", Name: "deep-is", Version: "0.1.3", Locations: []types.Location{{StartLine: 5210, EndLine: 5213}}},
{ID: "[email protected]", Name: "deepmerge", Version: "2.2.1", Locations: []types.Location{{StartLine: 5215, EndLine: 5218}}},
{ID: "[email protected]", Name: "deepmerge", Version: "3.2.0", Locations: []types.Location{{StartLine: 5220, EndLine: 5223}}},
{ID: "[email protected]", Name: "default-gateway", Version: "4.2.0", Locations: []types.Location{{StartLine: 5225, EndLine: 5231}}},
{ID: "[email protected]", Name: "default-require-extensions", Version: "1.0.0", Locations: []types.Location{{StartLine: 5233, EndLine: 5238}}},
{ID: "[email protected]", Name: "defaults", Version: "1.0.3", Locations: []types.Location{{StartLine: 5240, EndLine: 5245}}},
{ID: "[email protected]", Name: "define-properties", Version: "1.1.3", Locations: []types.Location{{StartLine: 5247, EndLine: 5252}}},
{ID: "[email protected]", Name: "define-property", Version: "0.2.5", Locations: []types.Location{{StartLine: 5254, EndLine: 5259}}},
{ID: "[email protected]", Name: "define-property", Version: "1.0.0", Locations: []types.Location{{StartLine: 5261, EndLine: 5266}}},
{ID: "[email protected]", Name: "define-property", Version: "2.0.2", Locations: []types.Location{{StartLine: 5268, EndLine: 5274}}},
{ID: "[email protected]", Name: "del", Version: "3.0.0", Locations: []types.Location{{StartLine: 5276, EndLine: 5286}}},
{ID: "[email protected]", Name: "del", Version: "4.1.1", Locations: []types.Location{{StartLine: 5288, EndLine: 5299}}},
{ID: "[email protected]", Name: "delayed-stream", Version: "1.0.0", Locations: []types.Location{{StartLine: 5301, EndLine: 5304}}},
{ID: "[email protected]", Name: "delegates", Version: "1.0.0", Locations: []types.Location{{StartLine: 5306, EndLine: 5309}}},
{ID: "[email protected]", Name: "depd", Version: "1.1.2", Locations: []types.Location{{StartLine: 5311, EndLine: 5314}}},
{ID: "[email protected]", Name: "des.js", Version: "1.0.0", Locations: []types.Location{{StartLine: 5316, EndLine: 5322}}},
{ID: "[email protected]", Name: "destroy", Version: "1.0.4", Locations: []types.Location{{StartLine: 5324, EndLine: 5327}}},
{ID: "[email protected]", Name: "detect-file", Version: "1.0.0", Locations: []types.Location{{StartLine: 5329, EndLine: 5332}}},
{ID: "[email protected]", Name: "detect-indent", Version: "4.0.0", Locations: []types.Location{{StartLine: 5334, EndLine: 5339}}},
{ID: "[email protected]", Name: "detect-indent", Version: "5.0.0", Locations: []types.Location{{StartLine: 5341, EndLine: 5344}}},
{ID: "[email protected]", Name: "detect-libc", Version: "1.0.3", Locations: []types.Location{{StartLine: 5346, EndLine: 5349}}},
{ID: "[email protected]", Name: "detect-newline", Version: "2.1.0", Locations: []types.Location{{StartLine: 5351, EndLine: 5354}}},
{ID: "[email protected]", Name: "detect-node", Version: "2.0.4", Locations: []types.Location{{StartLine: 5356, EndLine: 5359}}},
{ID: "[email protected]", Name: "detect-port-alt", Version: "1.1.6", Locations: []types.Location{{StartLine: 5361, EndLine: 5367}}},
{ID: "[email protected]", Name: "detect-port", Version: "1.3.0", Locations: []types.Location{{StartLine: 5369, EndLine: 5375}}},
{ID: "[email protected]", Name: "dezalgo", Version: "1.0.3", Locations: []types.Location{{StartLine: 5377, EndLine: 5383}}},
{ID: "[email protected]", Name: "diff", Version: "3.5.0", Locations: []types.Location{{StartLine: 5385, EndLine: 5388}}},
{ID: "[email protected]", Name: "diffie-hellman", Version: "5.0.3", Locations: []types.Location{{StartLine: 5390, EndLine: 5397}}},
{ID: "[email protected]", Name: "dir-glob", Version: "2.2.2", Locations: []types.Location{{StartLine: 5399, EndLine: 5404}}},
{ID: "[email protected]", Name: "discontinuous-range", Version: "1.0.0", Locations: []types.Location{{StartLine: 5406, EndLine: 5409}}},
{ID: "[email protected]", Name: "dns-equal", Version: "1.0.0", Locations: []types.Location{{StartLine: 5411, EndLine: 5414}}},
{ID: "[email protected]", Name: "dns-packet", Version: "1.3.1", Locations: []types.Location{{StartLine: 5416, EndLine: 5422}}},
{ID: "[email protected]", Name: "dns-txt", Version: "2.0.2", Locations: []types.Location{{StartLine: 5424, EndLine: 5429}}},
{ID: "[email protected]", Name: "doctrine", Version: "1.5.0", Locations: []types.Location{{StartLine: 5431, EndLine: 5437}}},
{ID: "[email protected]", Name: "doctrine", Version: "2.1.0", Locations: []types.Location{{StartLine: 5439, EndLine: 5444}}},
{ID: "[email protected]", Name: "doctrine", Version: "3.0.0", Locations: []types.Location{{StartLine: 5446, EndLine: 5451}}},
{ID: "[email protected]", Name: "dom-converter", Version: "0.2.0", Locations: []types.Location{{StartLine: 5453, EndLine: 5458}}},
{ID: "[email protected]", Name: "dom-helpers", Version: "3.4.0", Locations: []types.Location{{StartLine: 5460, EndLine: 5465}}},
{ID: "[email protected]", Name: "dom-serializer", Version: "0.1.1", Locations: []types.Location{{StartLine: 5467, EndLine: 5473}}},
{ID: "[email protected]", Name: "dom-walk", Version: "0.1.1", Locations: []types.Location{{StartLine: 5475, EndLine: 5478}}},
{ID: "[email protected]", Name: "domain-browser", Version: "1.2.0", Locations: []types.Location{{StartLine: 5480, EndLine: 5483}}},
{ID: "[email protected]", Name: "domelementtype", Version: "1.3.1", Locations: []types.Location{{StartLine: 5485, EndLine: 5488}}},
{ID: "[email protected]", Name: "domexception", Version: "1.0.1", Locations: []types.Location{{StartLine: 5490, EndLine: 5495}}},
{ID: "[email protected]", Name: "domhandler", Version: "2.4.2", Locations: []types.Location{{StartLine: 5497, EndLine: 5502}}},
{ID: "[email protected]", Name: "domutils", Version: "1.5.1", Locations: []types.Location{{StartLine: 5504, EndLine: 5510}}},
{ID: "[email protected]", Name: "domutils", Version: "1.7.0", Locations: []types.Location{{StartLine: 5512, EndLine: 5518}}},
{ID: "[email protected]", Name: "dot-prop", Version: "4.2.0", Locations: []types.Location{{StartLine: 5520, EndLine: 5525}}},
{ID: "[email protected]", Name: "dotenv-defaults", Version: "1.0.2", Locations: []types.Location{{StartLine: 5527, EndLine: 5532}}},
{ID: "[email protected]", Name: "dotenv-expand", Version: "4.2.0", Locations: []types.Location{{StartLine: 5534, EndLine: 5537}}},
{ID: "[email protected]", Name: "dotenv-webpack", Version: "1.7.0", Locations: []types.Location{{StartLine: 5539, EndLine: 5544}}},
{ID: "[email protected]", Name: "dotenv", Version: "5.0.1", Locations: []types.Location{{StartLine: 5546, EndLine: 5549}}},
{ID: "[email protected]", Name: "dotenv", Version: "6.2.0", Locations: []types.Location{{StartLine: 5551, EndLine: 5554}}},
{ID: "[email protected]", Name: "duplexer2", Version: "0.1.4", Locations: []types.Location{{StartLine: 5556, EndLine: 5561}}},
{ID: "[email protected]", Name: "duplexer3", Version: "0.1.4", Locations: []types.Location{{StartLine: 5563, EndLine: 5566}}},
{ID: "[email protected]", Name: "duplexer", Version: "0.1.1", Locations: []types.Location{{StartLine: 5568, EndLine: 5571}}},
{ID: "[email protected]", Name: "duplexify", Version: "3.7.1", Locations: []types.Location{{StartLine: 5573, EndLine: 5581}}},
{ID: "[email protected]", Name: "ecc-jsbn", Version: "0.1.2", Locations: []types.Location{{StartLine: 5583, EndLine: 5589}}},
{ID: "[email protected]", Name: "editor", Version: "1.0.0", Locations: []types.Location{{StartLine: 5591, EndLine: 5594}}},
{ID: "[email protected]", Name: "ee-first", Version: "1.1.1", Locations: []types.Location{{StartLine: 5596, EndLine: 5599}}},
{ID: "[email protected]", Name: "ejs", Version: "2.6.1", Locations: []types.Location{{StartLine: 5601, EndLine: 5604}}},
{ID: "[email protected]", Name: "electron-to-chromium", Version: "1.3.134", Locations: []types.Location{{StartLine: 5606, EndLine: 5609}}},
{ID: "[email protected]", Name: "elegant-spinner", Version: "1.0.1", Locations: []types.Location{{StartLine: 5611, EndLine: 5614}}},
{ID: "[email protected]", Name: "elliptic", Version: "6.4.1", Locations: []types.Location{{StartLine: 5616, EndLine: 5627}}},
{ID: "[email protected]", Name: "emoji-regex", Version: "7.0.3", Locations: []types.Location{{StartLine: 5629, EndLine: 5632}}},
{ID: "[email protected]", Name: "emojis-list", Version: "2.1.0", Locations: []types.Location{{StartLine: 5634, EndLine: 5637}}},
{ID: "[email protected]", Name: "encodeurl", Version: "1.0.2", Locations: []types.Location{{StartLine: 5639, EndLine: 5642}}},
{ID: "[email protected]", Name: "encoding", Version: "0.1.12", Locations: []types.Location{{StartLine: 5644, EndLine: 5649}}},
{ID: "[email protected]", Name: "end-of-stream", Version: "1.4.1", Locations: []types.Location{{StartLine: 5651, EndLine: 5656}}},
{ID: "[email protected]", Name: "engine.io-client", Version: "3.3.2", Locations: []types.Location{{StartLine: 5658, EndLine: 5673}}},
{ID: "[email protected]", Name: "engine.io-parser", Version: "2.1.3", Locations: []types.Location{{StartLine: 5675, EndLine: 5684}}},
{ID: "[email protected]", Name: "engine.io", Version: "3.3.2", Locations: []types.Location{{StartLine: 5686, EndLine: 5696}}},
{ID: "[email protected]", Name: "enhanced-resolve", Version: "4.1.0", Locations: []types.Location{{StartLine: 5698, EndLine: 5705}}},
{ID: "[email protected]", Name: "entities", Version: "1.1.2", Locations: []types.Location{{StartLine: 5707, EndLine: 5710}}},
{ID: "[email protected]", Name: "enzyme-adapter-react-16", Version: "1.13.0", Locations: []types.Location{{StartLine: 5712, EndLine: 5723}}},
{ID: "[email protected]", Name: "enzyme-adapter-utils", Version: "1.12.0", Locations: []types.Location{{StartLine: 5725, EndLine: 5735}}},
{ID: "[email protected]", Name: "enzyme", Version: "3.9.0", Locations: []types.Location{{StartLine: 5737, EndLine: 5762}}},
{ID: "[email protected]", Name: "err-code", Version: "1.1.2", Locations: []types.Location{{StartLine: 5764, EndLine: 5767}}},
{ID: "[email protected]", Name: "errno", Version: "0.1.7", Locations: []types.Location{{StartLine: 5769, EndLine: 5774}}},
{ID: "[email protected]", Name: "error-ex", Version: "1.3.2", Locations: []types.Location{{StartLine: 5776, EndLine: 5781}}},
{ID: "[email protected]", Name: "es-abstract", Version: "1.13.0", Locations: []types.Location{{StartLine: 5783, EndLine: 5793}}},
{ID: "[email protected]", Name: "es-to-primitive", Version: "1.2.0", Locations: []types.Location{{StartLine: 5795, EndLine: 5802}}},
{ID: "[email protected]", Name: "es5-shim", Version: "4.5.13", Locations: []types.Location{{StartLine: 5804, EndLine: 5807}}},
{ID: "[email protected]", Name: "es6-promise-promise", Version: "1.0.0", Locations: []types.Location{{StartLine: 5809, EndLine: 5814}}},
{ID: "[email protected]", Name: "es6-promise", Version: "3.3.1", Locations: []types.Location{{StartLine: 5816, EndLine: 5819}}},
{ID: "[email protected]", Name: "es6-promise", Version: "4.2.6", Locations: []types.Location{{StartLine: 5821, EndLine: 5824}}},
{ID: "[email protected]", Name: "es6-promisify", Version: "5.0.0", Locations: []types.Location{{StartLine: 5826, EndLine: 5831}}},
{ID: "[email protected]", Name: "es6-shim", Version: "0.35.5", Locations: []types.Location{{StartLine: 5833, EndLine: 5836}}},
{ID: "[email protected]", Name: "escape-html", Version: "1.0.3", Locations: []types.Location{{StartLine: 5838, EndLine: 5841}}},
{ID: "[email protected]", Name: "escape-string-regexp", Version: "1.0.5", Locations: []types.Location{{StartLine: 5843, EndLine: 5846}}},
{ID: "[email protected]", Name: "escodegen", Version: "1.11.1", Locations: []types.Location{{StartLine: 5848, EndLine: 5858}}},
{ID: "[email protected]", Name: "eslint-config-airbnb-base", Version: "13.1.0", Locations: []types.Location{{StartLine: 5860, EndLine: 5867}}},
{ID: "[email protected]", Name: "eslint-config-airbnb", Version: "17.1.0", Locations: []types.Location{{StartLine: 5869, EndLine: 5876}}},
{ID: "[email protected]", Name: "eslint-import-resolver-node", Version: "0.3.2", Locations: []types.Location{{StartLine: 5878, EndLine: 5884}}},
{ID: "[email protected]", Name: "eslint-loader", Version: "2.1.2", Locations: []types.Location{{StartLine: 5886, EndLine: 5895}}},
{ID: "[email protected]", Name: "eslint-module-utils", Version: "2.4.0", Locations: []types.Location{{StartLine: 5897, EndLine: 5903}}},
{ID: "[email protected]", Name: "eslint-plugin-import", Version: "2.17.2", Locations: []types.Location{{StartLine: 5905, EndLine: 5920}}},
{ID: "[email protected]", Name: "eslint-plugin-jsx-a11y", Version: "6.2.1", Locations: []types.Location{{StartLine: 5922, EndLine: 5934}}},
{ID: "[email protected]", Name: "eslint-plugin-react", Version: "7.13.0", Locations: []types.Location{{StartLine: 5936, EndLine: 5947}}},
{ID: "[email protected]", Name: "eslint-restricted-globals", Version: "0.1.1", Locations: []types.Location{{StartLine: 5949, EndLine: 5952}}},
{ID: "[email protected]", Name: "eslint-scope", Version: "3.7.1", Locations: []types.Location{{StartLine: 5954, EndLine: 5960}}},
{ID: "[email protected]", Name: "eslint-scope", Version: "4.0.3", Locations: []types.Location{{StartLine: 5962, EndLine: 5968}}},
{ID: "[email protected]", Name: "eslint-utils", Version: "1.3.1", Locations: []types.Location{{StartLine: 5970, EndLine: 5973}}},
{ID: "[email protected]", Name: "eslint-visitor-keys", Version: "1.0.0", Locations: []types.Location{{StartLine: 5975, EndLine: 5978}}},
{ID: "[email protected]", Name: "eslint", Version: "5.16.0", Locations: []types.Location{{StartLine: 5980, EndLine: 6020}}},
{ID: "[email protected]", Name: "espree", Version: "5.0.1", Locations: []types.Location{{StartLine: 6022, EndLine: 6029}}},
{ID: "[email protected]", Name: "esprima", Version: "3.1.3", Locations: []types.Location{{StartLine: 6031, EndLine: 6034}}},
{ID: "[email protected]", Name: "esprima", Version: "4.0.1", Locations: []types.Location{{StartLine: 6036, EndLine: 6039}}},
{ID: "[email protected]", Name: "esquery", Version: "1.0.1", Locations: []types.Location{{StartLine: 6041, EndLine: 6046}}},
{ID: "[email protected]", Name: "esrecurse", Version: "4.2.1", Locations: []types.Location{{StartLine: 6048, EndLine: 6053}}},
{ID: "[email protected]", Name: "estraverse", Version: "4.2.0", Locations: []types.Location{{StartLine: 6055, EndLine: 6058}}},
{ID: "[email protected]", Name: "esutils", Version: "2.0.2", Locations: []types.Location{{StartLine: 6060, EndLine: 6063}}},
{ID: "[email protected]", Name: "etag", Version: "1.8.1", Locations: []types.Location{{StartLine: 6065, EndLine: 6068}}},
{ID: "[email protected]", Name: "eventemitter3", Version: "3.1.2", Locations: []types.Location{{StartLine: 6070, EndLine: 6073}}},
{ID: "[email protected]", Name: "events", Version: "3.0.0", Locations: []types.Location{{StartLine: 6075, EndLine: 6078}}},
{ID: "[email protected]", Name: "eventsource", Version: "0.1.6", Locations: []types.Location{{StartLine: 6080, EndLine: 6085}}},
{ID: "[email protected]", Name: "eventsource", Version: "1.0.7", Locations: []types.Location{{StartLine: 6087, EndLine: 6092}}},
{ID: "[email protected]", Name: "evp_bytestokey", Version: "1.0.3", Locations: []types.Location{{StartLine: 6094, EndLine: 6100}}},
{ID: "[email protected]", Name: "exec-sh", Version: "0.2.2", Locations: []types.Location{{StartLine: 6102, EndLine: 6107}}},
{ID: "[email protected]", Name: "execa", Version: "0.7.0", Locations: []types.Location{{StartLine: 6109, EndLine: 6120}}},
{ID: "[email protected]", Name: "execa", Version: "0.9.0", Locations: []types.Location{{StartLine: 6122, EndLine: 6133}}},
{ID: "[email protected]", Name: "execa", Version: "1.0.0", Locations: []types.Location{{StartLine: 6135, EndLine: 6146}}},
{ID: "[email protected]", Name: "exenv", Version: "1.2.2", Locations: []types.Location{{StartLine: 6148, EndLine: 6151}}},
{ID: "[email protected]", Name: "exit-hook", Version: "1.1.1", Locations: []types.Location{{StartLine: 6153, EndLine: 6156}}},
{ID: "[email protected]", Name: "exit", Version: "0.1.2", Locations: []types.Location{{StartLine: 6158, EndLine: 6161}}},
{ID: "[email protected]", Name: "expand-brackets", Version: "0.1.5", Locations: []types.Location{{StartLine: 6163, EndLine: 6168}}},
{ID: "[email protected]", Name: "expand-brackets", Version: "2.1.4", Locations: []types.Location{{StartLine: 6170, EndLine: 6181}}},
{ID: "[email protected]", Name: "expand-range", Version: "1.8.2", Locations: []types.Location{{StartLine: 6183, EndLine: 6188}}},
{ID: "[email protected]", Name: "expand-tilde", Version: "2.0.2", Locations: []types.Location{{StartLine: 6190, EndLine: 6195}}},
{ID: "[email protected]", Name: "expect", Version: "23.6.0", Locations: []types.Location{{StartLine: 6197, EndLine: 6207}}},
{ID: "[email protected]", Name: "express", Version: "4.16.4", Locations: []types.Location{{StartLine: 6209, EndLine: 6243}}},
{ID: "[email protected]", Name: "extend-shallow", Version: "2.0.1", Locations: []types.Location{{StartLine: 6245, EndLine: 6250}}},
{ID: "[email protected]", Name: "extend-shallow", Version: "3.0.2", Locations: []types.Location{{StartLine: 6252, EndLine: 6258}}},
{ID: "[email protected]", Name: "extend", Version: "3.0.2", Locations: []types.Location{{StartLine: 6260, EndLine: 6263}}},
{ID: "[email protected]", Name: "external-editor", Version: "3.0.3", Locations: []types.Location{{StartLine: 6265, EndLine: 6272}}},
{ID: "[email protected]", Name: "extglob", Version: "0.3.2", Locations: []types.Location{{StartLine: 6274, EndLine: 6279}}},
{ID: "[email protected]", Name: "extglob", Version: "2.0.4", Locations: []types.Location{{StartLine: 6281, EndLine: 6293}}},
{ID: "[email protected]", Name: "extract-text-webpack-plugin", Version: "4.0.0-beta.0", Locations: []types.Location{{StartLine: 6295, EndLine: 6303}}},
{ID: "[email protected]", Name: "extsprintf", Version: "1.3.0", Locations: []types.Location{{StartLine: 6305, EndLine: 6308}}},
{ID: "[email protected]", Name: "extsprintf", Version: "1.4.0", Locations: []types.Location{{StartLine: 6310, EndLine: 6313}}},
{ID: "[email protected]", Name: "faker", Version: "4.1.0", Locations: []types.Location{{StartLine: 6315, EndLine: 6318}}},
{ID: "[email protected]", Name: "fast-deep-equal", Version: "2.0.1", Locations: []types.Location{{StartLine: 6320, EndLine: 6323}}},
{ID: "[email protected]", Name: "fast-glob", Version: "2.2.6", Locations: []types.Location{{StartLine: 6325, EndLine: 6335}}},
{ID: "[email protected]", Name: "fast-json-stable-stringify", Version: "2.0.0", Locations: []types.Location{{StartLine: 6337, EndLine: 6340}}},
{ID: "[email protected]", Name: "fast-levenshtein", Version: "2.0.6", Locations: []types.Location{{StartLine: 6342, EndLine: 6345}}},
{ID: "[email protected]", Name: "fastparse", Version: "1.1.2", Locations: []types.Location{{StartLine: 6347, EndLine: 6350}}},
{ID: "[email protected]", Name: "faye-websocket", Version: "0.10.0", Locations: []types.Location{{StartLine: 6352, EndLine: 6357}}},
{ID: "[email protected]", Name: "faye-websocket", Version: "0.11.1", Locations: []types.Location{{StartLine: 6359, EndLine: 6364}}},
{ID: "[email protected]", Name: "fb-watchman", Version: "2.0.0", Locations: []types.Location{{StartLine: 6366, EndLine: 6371}}},
{ID: "[email protected]", Name: "fbjs", Version: "0.8.17", Locations: []types.Location{{StartLine: 6373, EndLine: 6384}}},
{ID: "[email protected]", Name: "figgy-pudding", Version: "3.5.1", Locations: []types.Location{{StartLine: 6386, EndLine: 6389}}},
{ID: "[email protected]", Name: "figures", Version: "1.7.0", Locations: []types.Location{{StartLine: 6391, EndLine: 6397}}},
{ID: "[email protected]", Name: "figures", Version: "2.0.0", Locations: []types.Location{{StartLine: 6399, EndLine: 6404}}},
{ID: "[email protected]", Name: "file-entry-cache", Version: "5.0.1", Locations: []types.Location{{StartLine: 6406, EndLine: 6411}}},
{ID: "[email protected]", Name: "file-loader", Version: "1.1.11", Locations: []types.Location{{StartLine: 6413, EndLine: 6419}}},
{ID: "[email protected]", Name: "file-loader", Version: "2.0.0", Locations: []types.Location{{StartLine: 6421, EndLine: 6427}}},
{ID: "[email protected]", Name: "file-selector", Version: "0.1.11", Locations: []types.Location{{StartLine: 6429, EndLine: 6434}}},
{ID: "[email protected]", Name: "file-system-cache", Version: "1.0.5", Locations: []types.Location{{StartLine: 6436, EndLine: 6443}}},
{ID: "[email protected]", Name: "filename-regex", Version: "2.0.1", Locations: []types.Location{{StartLine: 6445, EndLine: 6448}}},
{ID: "[email protected]", Name: "fileset", Version: "2.0.3", Locations: []types.Location{{StartLine: 6450, EndLine: 6456}}},
{ID: "[email protected]", Name: "filesize", Version: "3.6.1", Locations: []types.Location{{StartLine: 6458, EndLine: 6461}}},
{ID: "[email protected]", Name: "fill-range", Version: "2.2.4", Locations: []types.Location{{StartLine: 6463, EndLine: 6472}}},
{ID: "[email protected]", Name: "fill-range", Version: "4.0.0", Locations: []types.Location{{StartLine: 6474, EndLine: 6482}}},
{ID: "[email protected]", Name: "finalhandler", Version: "1.1.1", Locations: []types.Location{{StartLine: 6484, EndLine: 6495}}},
{ID: "[email protected]", Name: "find-cache-dir", Version: "0.1.1", Locations: []types.Location{{StartLine: 6497, EndLine: 6504}}},
{ID: "[email protected]", Name: "find-cache-dir", Version: "1.0.0", Locations: []types.Location{{StartLine: 6506, EndLine: 6513}}},
{ID: "[email protected]", Name: "find-cache-dir", Version: "2.1.0", Locations: []types.Location{{StartLine: 6515, EndLine: 6522}}},
{ID: "[email protected]", Name: "find-npm-prefix", Version: "1.0.2", Locations: []types.Location{{StartLine: 6524, EndLine: 6527}}},
{ID: "[email protected]", Name: "find-parent-dir", Version: "0.3.0", Locations: []types.Location{{StartLine: 6529, EndLine: 6532}}},
{ID: "[email protected]", Name: "find-up", Version: "3.0.0", Locations: []types.Location{{StartLine: 6534, EndLine: 6539}}},
{ID: "[email protected]", Name: "find-up", Version: "1.1.2", Locations: []types.Location{{StartLine: 6541, EndLine: 6547}}},
{ID: "[email protected]", Name: "find-up", Version: "2.1.0", Locations: []types.Location{{StartLine: 6549, EndLine: 6554}}},
{ID: "[email protected]", Name: "findup-sync", Version: "2.0.0", Locations: []types.Location{{StartLine: 6556, EndLine: 6564}}},
{ID: "[email protected]", Name: "flat-cache", Version: "2.0.1", Locations: []types.Location{{StartLine: 6566, EndLine: 6573}}},
{ID: "[email protected]", Name: "flatted", Version: "2.0.0", Locations: []types.Location{{StartLine: 6575, EndLine: 6578}}},
{ID: "[email protected]", Name: "flow-bin", Version: "0.89.0", Locations: []types.Location{{StartLine: 6580, EndLine: 6583}}},
{ID: "[email protected]", Name: "flow-parser", Version: "0.98.1", Locations: []types.Location{{StartLine: 6585, EndLine: 6588}}},
{ID: "[email protected]", Name: "flow-typed", Version: "2.5.1", Locations: []types.Location{{StartLine: 6590, EndLine: 6609}}},
{ID: "[email protected]", Name: "flush-write-stream", Version: "1.1.1", Locations: []types.Location{{StartLine: 6611, EndLine: 6617}}},
{ID: "[email protected]", Name: "follow-redirects", Version: "1.7.0", Locations: []types.Location{{StartLine: 6619, EndLine: 6624}}},
{ID: "[email protected]", Name: "for-in", Version: "0.1.8", Locations: []types.Location{{StartLine: 6626, EndLine: 6629}}},
{ID: "[email protected]", Name: "for-in", Version: "1.0.2", Locations: []types.Location{{StartLine: 6631, EndLine: 6634}}},
{ID: "[email protected]", Name: "for-own", Version: "0.1.5", Locations: []types.Location{{StartLine: 6636, EndLine: 6641}}},
{ID: "[email protected]", Name: "forever-agent", Version: "0.6.1", Locations: []types.Location{{StartLine: 6643, EndLine: 6646}}},
{ID: "[email protected]", Name: "form-data", Version: "2.3.3", Locations: []types.Location{{StartLine: 6648, EndLine: 6655}}},
{ID: "[email protected]", Name: "formik", Version: "1.5.1", Locations: []types.Location{{StartLine: 6657, EndLine: 6670}}},
{ID: "[email protected]", Name: "forwarded", Version: "0.1.2", Locations: []types.Location{{StartLine: 6672, EndLine: 6675}}},
{ID: "[email protected]", Name: "fragment-cache", Version: "0.2.1", Locations: []types.Location{{StartLine: 6677, EndLine: 6682}}},
{ID: "[email protected]", Name: "fresh", Version: "0.5.2", Locations: []types.Location{{StartLine: 6684, EndLine: 6687}}},
{ID: "[email protected]", Name: "from2", Version: "1.3.0", Locations: []types.Location{{StartLine: 6689, EndLine: 6695}}},
{ID: "[email protected]", Name: "from2", Version: "2.3.0", Locations: []types.Location{{StartLine: 6697, EndLine: 6703}}},
{ID: "[email protected]", Name: "fs-extra", Version: "0.30.0", Locations: []types.Location{{StartLine: 6705, EndLine: 6714}}},
{ID: "[email protected]", Name: "fs-extra", Version: "5.0.0", Locations: []types.Location{{StartLine: 6716, EndLine: 6723}}},
{ID: "[email protected]", Name: "fs-extra", Version: "7.0.1", Locations: []types.Location{{StartLine: 6725, EndLine: 6732}}},
{ID: "[email protected]", Name: "fs-minipass", Version: "1.2.5", Locations: []types.Location{{StartLine: 6734, EndLine: 6739}}},
{ID: "[email protected]", Name: "fs-readdir-recursive", Version: "1.1.0", Locations: []types.Location{{StartLine: 6741, EndLine: 6744}}},
{ID: "[email protected]", Name: "fs-vacuum", Version: "1.2.10", Locations: []types.Location{{StartLine: 6746, EndLine: 6753}}},
{ID: "[email protected]", Name: "fs-write-stream-atomic", Version: "1.0.10", Locations: []types.Location{{StartLine: 6755, EndLine: 6763}}},
{ID: "[email protected]", Name: "fs.realpath", Version: "1.0.0", Locations: []types.Location{{StartLine: 6765, EndLine: 6768}}},
{ID: "[email protected]", Name: "fsevents", Version: "1.2.9", Locations: []types.Location{{StartLine: 6770, EndLine: 6776}}},
{ID: "[email protected]", Name: "fstream", Version: "1.0.12", Locations: []types.Location{{StartLine: 6778, EndLine: 6786}}},
{ID: "[email protected]", Name: "function-bind", Version: "1.1.1", Locations: []types.Location{{StartLine: 6788, EndLine: 6791}}},
{ID: "[email protected]", Name: "function.prototype.name", Version: "1.1.0", Locations: []types.Location{{StartLine: 6793, EndLine: 6800}}},
{ID: "[email protected]", Name: "functional-red-black-tree", Version: "1.0.1", Locations: []types.Location{{StartLine: 6802, EndLine: 6805}}},
{ID: "[email protected]", Name: "fuse.js", Version: "3.4.4", Locations: []types.Location{{StartLine: 6807, EndLine: 6810}}},
{ID: "[email protected]", Name: "gauge", Version: "2.7.4", Locations: []types.Location{{StartLine: 6812, EndLine: 6824}}},
{ID: "[email protected]", Name: "genfun", Version: "5.0.0", Locations: []types.Location{{StartLine: 6826, EndLine: 6829}}},
{ID: "[email protected]", Name: "gentle-fs", Version: "2.0.1", Locations: []types.Location{{StartLine: 6831, EndLine: 6843}}},
{ID: "[email protected]", Name: "get-caller-file", Version: "1.0.3", Locations: []types.Location{{StartLine: 6845, EndLine: 6848}}},
{ID: "[email protected]", Name: "get-own-enumerable-property-symbols", Version: "3.0.0", Locations: []types.Location{{StartLine: 6850, EndLine: 6853}}},
{ID: "[email protected]", Name: "get-stdin", Version: "6.0.0", Locations: []types.Location{{StartLine: 6855, EndLine: 6858}}},
{ID: "[email protected]", Name: "get-stream", Version: "3.0.0", Locations: []types.Location{{StartLine: 6860, EndLine: 6863}}},
{ID: "[email protected]", Name: "get-stream", Version: "4.1.0", Locations: []types.Location{{StartLine: 6865, EndLine: 6870}}},
{ID: "[email protected]", Name: "get-value", Version: "2.0.6", Locations: []types.Location{{StartLine: 6872, EndLine: 6875}}},
{ID: "[email protected]", Name: "getpass", Version: "0.1.7", Locations: []types.Location{{StartLine: 6877, EndLine: 6882}}},
{ID: "[email protected]", Name: "glob-base", Version: "0.3.0", Locations: []types.Location{{StartLine: 6884, EndLine: 6890}}},
{ID: "[email protected]", Name: "glob-parent", Version: "2.0.0", Locations: []types.Location{{StartLine: 6892, EndLine: 6897}}},
{ID: "[email protected]", Name: "glob-parent", Version: "3.1.0", Locations: []types.Location{{StartLine: 6899, EndLine: 6905}}},
{ID: "[email protected]", Name: "glob-to-regexp", Version: "0.3.0", Locations: []types.Location{{StartLine: 6907, EndLine: 6910}}},
{ID: "[email protected]", Name: "glob", Version: "7.1.4", Locations: []types.Location{{StartLine: 6912, EndLine: 6922}}},
{ID: "[email protected]", Name: "global-dirs", Version: "0.1.1", Locations: []types.Location{{StartLine: 6924, EndLine: 6929}}},
{ID: "[email protected]", Name: "global-modules", Version: "1.0.0", Locations: []types.Location{{StartLine: 6931, EndLine: 6938}}},
{ID: "[email protected]", Name: "global-prefix", Version: "1.0.2", Locations: []types.Location{{StartLine: 6940, EndLine: 6949}}},
{ID: "[email protected]", Name: "global", Version: "4.3.2", Locations: []types.Location{{StartLine: 6951, EndLine: 6957}}},
{ID: "[email protected]", Name: "globals", Version: "11.12.0", Locations: []types.Location{{StartLine: 6959, EndLine: 6962}}},
{ID: "[email protected]", Name: "globals", Version: "9.18.0", Locations: []types.Location{{StartLine: 6964, EndLine: 6967}}},
{ID: "[email protected]", Name: "globalthis", Version: "1.0.0", Locations: []types.Location{{StartLine: 6969, EndLine: 6976}}},
{ID: "[email protected]", Name: "globby", Version: "8.0.1", Locations: []types.Location{{StartLine: 6978, EndLine: 6989}}},
{ID: "[email protected]", Name: "globby", Version: "6.1.0", Locations: []types.Location{{StartLine: 6991, EndLine: 7000}}},
{ID: "[email protected]", Name: "globby", Version: "7.1.1", Locations: []types.Location{{StartLine: 7002, EndLine: 7012}}},
{ID: "[email protected]", Name: "got", Version: "6.7.1", Locations: []types.Location{{StartLine: 7014, EndLine: 7029}}},
{ID: "[email protected]", Name: "got", Version: "7.1.0", Locations: []types.Location{{StartLine: 7031, EndLine: 7049}}},
{ID: "[email protected]", Name: "graceful-fs", Version: "4.1.15", Locations: []types.Location{{StartLine: 7051, EndLine: 7054}}},
{ID: "[email protected]", Name: "growly", Version: "1.3.0", Locations: []types.Location{{StartLine: 7056, EndLine: 7059}}},
{ID: "[email protected]", Name: "gud", Version: "1.0.0", Locations: []types.Location{{StartLine: 7061, EndLine: 7064}}},
{ID: "[email protected]", Name: "gzip-size", Version: "5.0.0", Locations: []types.Location{{StartLine: 7066, EndLine: 7072}}},
{ID: "[email protected]", Name: "gzip-size", Version: "5.1.0", Locations: []types.Location{{StartLine: 7074, EndLine: 7080}}},
{ID: "[email protected]", Name: "handle-thing", Version: "2.0.0", Locations: []types.Location{{StartLine: 7082, EndLine: 7085}}},
{ID: "[email protected]", Name: "handlebars", Version: "4.1.2", Locations: []types.Location{{StartLine: 7087, EndLine: 7096}}},
{ID: "[email protected]", Name: "har-schema", Version: "2.0.0", Locations: []types.Location{{StartLine: 7098, EndLine: 7101}}},
{ID: "[email protected]", Name: "har-validator", Version: "5.1.3", Locations: []types.Location{{StartLine: 7103, EndLine: 7109}}},
{ID: "[email protected]", Name: "hard-source-webpack-plugin", Version: "0.13.1", Locations: []types.Location{{StartLine: 7111, EndLine: 7128}}},
{ID: "[email protected]", Name: "has-ansi", Version: "2.0.0", Locations: []types.Location{{StartLine: 7130, EndLine: 7135}}},
{ID: "[email protected]", Name: "has-binary2", Version: "1.0.3", Locations: []types.Location{{StartLine: 7137, EndLine: 7142}}},
{ID: "[email protected]", Name: "has-color", Version: "0.1.7", Locations: []types.Location{{StartLine: 7144, EndLine: 7147}}},
{ID: "[email protected]", Name: "has-cors", Version: "1.1.0", Locations: []types.Location{{StartLine: 7149, EndLine: 7152}}},
{ID: "[email protected]", Name: "has-flag", Version: "1.0.0", Locations: []types.Location{{StartLine: 7154, EndLine: 7157}}},
{ID: "[email protected]", Name: "has-flag", Version: "3.0.0", Locations: []types.Location{{StartLine: 7159, EndLine: 7162}}},
{ID: "[email protected]", Name: "has-symbol-support-x", Version: "1.4.2", Locations: []types.Location{{StartLine: 7164, EndLine: 7167}}},
{ID: "[email protected]", Name: "has-symbols", Version: "1.0.0", Locations: []types.Location{{StartLine: 7169, EndLine: 7172}}},
{ID: "[email protected]", Name: "has-to-string-tag-x", Version: "1.4.1", Locations: []types.Location{{StartLine: 7174, EndLine: 7179}}},
{ID: "[email protected]", Name: "has-unicode", Version: "2.0.1", Locations: []types.Location{{StartLine: 7181, EndLine: 7184}}},
{ID: "[email protected]", Name: "has-value", Version: "0.3.1", Locations: []types.Location{{StartLine: 7186, EndLine: 7193}}},
{ID: "[email protected]", Name: "has-value", Version: "1.0.0", Locations: []types.Location{{StartLine: 7195, EndLine: 7202}}},
{ID: "[email protected]", Name: "has-values", Version: "0.1.4", Locations: []types.Location{{StartLine: 7204, EndLine: 7207}}},
{ID: "[email protected]", Name: "has-values", Version: "1.0.0", Locations: []types.Location{{StartLine: 7209, EndLine: 7215}}},
{ID: "[email protected]", Name: "has", Version: "1.0.3", Locations: []types.Location{{StartLine: 7217, EndLine: 7222}}},
{ID: "[email protected]", Name: "hash-base", Version: "3.0.4", Locations: []types.Location{{StartLine: 7224, EndLine: 7230}}},
{ID: "[email protected]", Name: "hash.js", Version: "1.1.7", Locations: []types.Location{{StartLine: 7232, EndLine: 7238}}},
{ID: "[email protected]", Name: "hast-util-from-parse5", Version: "5.0.0", Locations: []types.Location{{StartLine: 7240, EndLine: 7249}}},
{ID: "[email protected]", Name: "hast-util-parse-selector", Version: "2.2.1", Locations: []types.Location{{StartLine: 7251, EndLine: 7254}}},
{ID: "[email protected]", Name: "hastscript", Version: "5.0.0", Locations: []types.Location{{StartLine: 7256, EndLine: 7264}}},
{ID: "[email protected]", Name: "he", Version: "1.2.0", Locations: []types.Location{{StartLine: 7266, EndLine: 7269}}},
{ID: "[email protected]", Name: "history", Version: "4.9.0", Locations: []types.Location{{StartLine: 7271, EndLine: 7281}}},
{ID: "[email protected]", Name: "hmac-drbg", Version: "1.0.1", Locations: []types.Location{{StartLine: 7283, EndLine: 7290}}},
{ID: "[email protected]", Name: "hoist-non-react-statics", Version: "1.2.0", Locations: []types.Location{{StartLine: 7292, EndLine: 7295}}},
{ID: "[email protected]", Name: "hoist-non-react-statics", Version: "2.5.5", Locations: []types.Location{{StartLine: 7297, EndLine: 7300}}},
{ID: "[email protected]", Name: "hoist-non-react-statics", Version: "3.3.0", Locations: []types.Location{{StartLine: 7302, EndLine: 7307}}},
{ID: "[email protected]", Name: "home-or-tmp", Version: "2.0.0", Locations: []types.Location{{StartLine: 7309, EndLine: 7315}}},
{ID: "[email protected]", Name: "homedir-polyfill", Version: "1.0.3", Locations: []types.Location{{StartLine: 7317, EndLine: 7322}}},
{ID: "[email protected]", Name: "hoopy", Version: "0.1.4", Locations: []types.Location{{StartLine: 7324, EndLine: 7327}}},
{ID: "[email protected]", Name: "hosted-git-info", Version: "2.7.1", Locations: []types.Location{{StartLine: 7329, EndLine: 7332}}},
{ID: "[email protected]", Name: "hpack.js", Version: "2.1.6", Locations: []types.Location{{StartLine: 7334, EndLine: 7342}}},
{ID: "[email protected]", Name: "html-element-map", Version: "1.0.1", Locations: []types.Location{{StartLine: 7344, EndLine: 7349}}},
{ID: "[email protected]", Name: "html-encoding-sniffer", Version: "1.0.2", Locations: []types.Location{{StartLine: 7351, EndLine: 7356}}},
{ID: "[email protected]", Name: "html-entities", Version: "1.2.1", Locations: []types.Location{{StartLine: 7358, EndLine: 7361}}},
{ID: "[email protected]", Name: "html-minifier", Version: "3.5.21", Locations: []types.Location{{StartLine: 7363, EndLine: 7374}}},
{ID: "[email protected]", Name: "html-webpack-harddisk-plugin", Version: "1.0.1", Locations: []types.Location{{StartLine: 7376, EndLine: 7381}}},
{ID: "[email protected]", Name: "html-webpack-plugin", Version: "3.2.0", Locations: []types.Location{{StartLine: 7383, EndLine: 7394}}},
{ID: "[email protected]", Name: "html-webpack-plugin", Version: "4.0.0-beta.5", Locations: []types.Location{{StartLine: 7396, EndLine: 7406}}},
{ID: "[email protected]", Name: "htmlparser2", Version: "3.10.1", Locations: []types.Location{{StartLine: 7408, EndLine: 7418}}},
{ID: "[email protected]", Name: "http-cache-semantics", Version: "3.8.1", Locations: []types.Location{{StartLine: 7420, EndLine: 7423}}},
{ID: "[email protected]", Name: "http-deceiver", Version: "1.2.7", Locations: []types.Location{{StartLine: 7425, EndLine: 7428}}},
{ID: "[email protected]", Name: "http-errors", Version: "1.6.3", Locations: []types.Location{{StartLine: 7430, EndLine: 7438}}},
{ID: "[email protected]", Name: "http-parser-js", Version: "0.5.0", Locations: []types.Location{{StartLine: 7440, EndLine: 7443}}},
{ID: "[email protected]", Name: "http-proxy-agent", Version: "2.1.0", Locations: []types.Location{{StartLine: 7445, EndLine: 7451}}},
{ID: "[email protected]", Name: "http-proxy-middleware", Version: "0.19.1", Locations: []types.Location{{StartLine: 7453, EndLine: 7461}}},
{ID: "[email protected]", Name: "http-proxy", Version: "1.17.0", Locations: []types.Location{{StartLine: 7463, EndLine: 7470}}},
{ID: "[email protected]", Name: "http-signature", Version: "1.2.0", Locations: []types.Location{{StartLine: 7472, EndLine: 7479}}},
{ID: "[email protected]", Name: "https-browserify", Version: "1.0.0", Locations: []types.Location{{StartLine: 7481, EndLine: 7484}}},
{ID: "[email protected]", Name: "https-proxy-agent", Version: "2.2.1", Locations: []types.Location{{StartLine: 7486, EndLine: 7492}}},
{ID: "[email protected]", Name: "humanize-ms", Version: "1.2.1", Locations: []types.Location{{StartLine: 7494, EndLine: 7499}}},
{ID: "[email protected]", Name: "husky", Version: "1.3.1", Locations: []types.Location{{StartLine: 7501, EndLine: 7515}}},
{ID: "[email protected]", Name: "hyphenate-style-name", Version: "1.0.3", Locations: []types.Location{{StartLine: 7517, EndLine: 7520}}},
{ID: "[email protected]", Name: "i", Version: "0.3.6", Locations: []types.Location{{StartLine: 7522, EndLine: 7525}}},
{ID: "[email protected]", Name: "iconv-lite", Version: "0.4.23", Locations: []types.Location{{StartLine: 7527, EndLine: 7532}}},
{ID: "[email protected]", Name: "iconv-lite", Version: "0.4.24", Locations: []types.Location{{StartLine: 7534, EndLine: 7539}}},
{ID: "[email protected]", Name: "icss-replace-symbols", Version: "1.1.0", Locations: []types.Location{{StartLine: 7541, EndLine: 7544}}},
{ID: "[email protected]", Name: "icss-utils", Version: "2.1.0", Locations: []types.Location{{StartLine: 7546, EndLine: 7551}}},
{ID: "[email protected]", Name: "ieee754", Version: "1.1.13", Locations: []types.Location{{StartLine: 7553, EndLine: 7556}}},
{ID: "[email protected]", Name: "iferr", Version: "0.1.5", Locations: []types.Location{{StartLine: 7558, EndLine: 7561}}},
{ID: "[email protected]", Name: "iferr", Version: "1.0.2", Locations: []types.Location{{StartLine: 7563, EndLine: 7566}}},
{ID: "[email protected]", Name: "ignore-walk", Version: "3.0.1", Locations: []types.Location{{StartLine: 7568, EndLine: 7573}}},
{ID: "[email protected]", Name: "ignore", Version: "3.3.10", Locations: []types.Location{{StartLine: 7575, EndLine: 7578}}},
{ID: "[email protected]", Name: "ignore", Version: "4.0.6", Locations: []types.Location{{StartLine: 7580, EndLine: 7583}}},
{ID: "[email protected]", Name: "immer", Version: "1.7.2", Locations: []types.Location{{StartLine: 7585, EndLine: 7588}}},
{ID: "[email protected]", Name: "immutable", Version: "3.8.2", Locations: []types.Location{{StartLine: 7590, EndLine: 7593}}},
{ID: "[email protected]", Name: "import-cwd", Version: "2.1.0", Locations: []types.Location{{StartLine: 7595, EndLine: 7600}}},
{ID: "[email protected]", Name: "import-fresh", Version: "2.0.0", Locations: []types.Location{{StartLine: 7602, EndLine: 7608}}},
{ID: "[email protected]", Name: "import-fresh", Version: "3.0.0", Locations: []types.Location{{StartLine: 7610, EndLine: 7616}}},
{ID: "[email protected]", Name: "import-from", Version: "2.1.0", Locations: []types.Location{{StartLine: 7618, EndLine: 7623}}},
{ID: "[email protected]", Name: "import-lazy", Version: "2.1.0", Locations: []types.Location{{StartLine: 7625, EndLine: 7628}}},
{ID: "[email protected]", Name: "import-local", Version: "1.0.0", Locations: []types.Location{{StartLine: 7630, EndLine: 7636}}},
{ID: "[email protected]", Name: "import-local", Version: "2.0.0", Locations: []types.Location{{StartLine: 7638, EndLine: 7644}}},
{ID: "[email protected]", Name: "imurmurhash", Version: "0.1.4", Locations: []types.Location{{StartLine: 7646, EndLine: 7649}}},
{ID: "[email protected]", Name: "indefinite-observable", Version: "1.0.2", Locations: []types.Location{{StartLine: 7651, EndLine: 7656}}},
{ID: "[email protected]", Name: "indent-string", Version: "3.2.0", Locations: []types.Location{{StartLine: 7658, EndLine: 7661}}},
{ID: "[email protected]", Name: "indexof", Version: "0.0.1", Locations: []types.Location{{StartLine: 7663, EndLine: 7666}}},
{ID: "[email protected]", Name: "inflight", Version: "1.0.6", Locations: []types.Location{{StartLine: 7668, EndLine: 7674}}},
{ID: "[email protected]", Name: "inherits", Version: "2.0.3", Locations: []types.Location{{StartLine: 7676, EndLine: 7679}}},
{ID: "[email protected]", Name: "inherits", Version: "2.0.1", Locations: []types.Location{{StartLine: 7681, EndLine: 7684}}},
{ID: "[email protected]", Name: "ini", Version: "1.3.5", Locations: []types.Location{{StartLine: 7686, EndLine: 7689}}},
{ID: "[email protected]", Name: "init-package-json", Version: "1.10.3", Locations: []types.Location{{StartLine: 7691, EndLine: 7703}}},
{ID: "[email protected]", Name: "inquirer", Version: "6.2.0", Locations: []types.Location{{StartLine: 7705, EndLine: 7722}}},
{ID: "[email protected]", Name: "inquirer", Version: "0.11.4", Locations: []types.Location{{StartLine: 7724, EndLine: 7741}}},
{ID: "[email protected]", Name: "inquirer", Version: "6.3.1", Locations: []types.Location{{StartLine: 7743, EndLine: 7760}}},
{ID: "[email protected]", Name: "internal-ip", Version: "4.3.0", Locations: []types.Location{{StartLine: 7762, EndLine: 7768}}},
{ID: "[email protected]", Name: "interpret", Version: "1.2.0", Locations: []types.Location{{StartLine: 7770, EndLine: 7773}}},
{ID: "[email protected]", Name: "intl-messageformat-parser", Version: "1.4.0", Locations: []types.Location{{StartLine: 7775, EndLine: 7778}}},
{ID: "[email protected]", Name: "intl-messageformat", Version: "2.2.0", Locations: []types.Location{{StartLine: 7780, EndLine: 7785}}},
{ID: "[email protected]", Name: "intl", Version: "1.2.5", Locations: []types.Location{{StartLine: 7787, EndLine: 7790}}},
{ID: "[email protected]", Name: "invariant", Version: "2.2.4", Locations: []types.Location{{StartLine: 7792, EndLine: 7797}}},
{ID: "[email protected]", Name: "invert-kv", Version: "1.0.0", Locations: []types.Location{{StartLine: 7799, EndLine: 7802}}},
{ID: "[email protected]", Name: "invert-kv", Version: "2.0.0", Locations: []types.Location{{StartLine: 7804, EndLine: 7807}}},
{ID: "[email protected]", Name: "ip-regex", Version: "2.1.0", Locations: []types.Location{{StartLine: 7809, EndLine: 7812}}},
{ID: "[email protected]", Name: "ip", Version: "1.1.5", Locations: []types.Location{{StartLine: 7814, EndLine: 7817}}},
{ID: "[email protected]", Name: "ipaddr.js", Version: "1.9.0", Locations: []types.Location{{StartLine: 7819, EndLine: 7822}}},
{ID: "[email protected]", Name: "is-accessor-descriptor", Version: "0.1.6", Locations: []types.Location{{StartLine: 7824, EndLine: 7829}}},
{ID: "[email protected]", Name: "is-accessor-descriptor", Version: "1.0.0", Locations: []types.Location{{StartLine: 7831, EndLine: 7836}}},
{ID: "[email protected]", Name: "is-arrayish", Version: "0.2.1", Locations: []types.Location{{StartLine: 7838, EndLine: 7841}}},
{ID: "[email protected]", Name: "is-binary-path", Version: "1.0.1", Locations: []types.Location{{StartLine: 7843, EndLine: 7848}}},
{ID: "[email protected]", Name: "is-boolean-object", Version: "1.0.0", Locations: []types.Location{{StartLine: 7850, EndLine: 7853}}},
{ID: "[email protected]", Name: "is-buffer", Version: "1.1.6", Locations: []types.Location{{StartLine: 7855, EndLine: 7858}}},
{ID: "[email protected]", Name: "is-buffer", Version: "2.0.3", Locations: []types.Location{{StartLine: 7860, EndLine: 7863}}},
{ID: "[email protected]", Name: "is-callable", Version: "1.1.4", Locations: []types.Location{{StartLine: 7865, EndLine: 7868}}},
{ID: "[email protected]", Name: "is-ci", Version: "1.2.1", Locations: []types.Location{{StartLine: 7870, EndLine: 7875}}},
{ID: "[email protected]", Name: "is-ci", Version: "2.0.0", Locations: []types.Location{{StartLine: 7877, EndLine: 7882}}},
{ID: "[email protected]", Name: "is-cidr", Version: "3.0.0", Locations: []types.Location{{StartLine: 7884, EndLine: 7889}}},
{ID: "[email protected]", Name: "is-data-descriptor", Version: "0.1.4", Locations: []types.Location{{StartLine: 7891, EndLine: 7896}}},
{ID: "[email protected]", Name: "is-data-descriptor", Version: "1.0.0", Locations: []types.Location{{StartLine: 7898, EndLine: 7903}}},
{ID: "[email protected]", Name: "is-date-object", Version: "1.0.1", Locations: []types.Location{{StartLine: 7905, EndLine: 7908}}},
{ID: "[email protected]", Name: "is-descriptor", Version: "0.1.6", Locations: []types.Location{{StartLine: 7910, EndLine: 7917}}},
{ID: "[email protected]", Name: "is-descriptor", Version: "1.0.2", Locations: []types.Location{{StartLine: 7919, EndLine: 7926}}},
{ID: "[email protected]", Name: "is-directory", Version: "0.3.1", Locations: []types.Location{{StartLine: 7928, EndLine: 7931}}},
{ID: "[email protected]", Name: "is-dom", Version: "1.0.9", Locations: []types.Location{{StartLine: 7933, EndLine: 7936}}},
{ID: "[email protected]", Name: "is-dotfile", Version: "1.0.3", Locations: []types.Location{{StartLine: 7938, EndLine: 7941}}},
{ID: "[email protected]", Name: "is-electron", Version: "2.2.0", Locations: []types.Location{{StartLine: 7943, EndLine: 7946}}},
{ID: "[email protected]", Name: "is-equal-shallow", Version: "0.1.3", Locations: []types.Location{{StartLine: 7948, EndLine: 7953}}},
{ID: "[email protected]", Name: "is-extendable", Version: "0.1.1", Locations: []types.Location{{StartLine: 7955, EndLine: 7958}}},
{ID: "[email protected]", Name: "is-extendable", Version: "1.0.1", Locations: []types.Location{{StartLine: 7960, EndLine: 7965}}},
{ID: "[email protected]", Name: "is-extglob", Version: "1.0.0", Locations: []types.Location{{StartLine: 7967, EndLine: 7970}}},
{ID: "[email protected]", Name: "is-extglob", Version: "2.1.1", Locations: []types.Location{{StartLine: 7972, EndLine: 7975}}},
{ID: "[email protected]", Name: "is-finite", Version: "1.0.2", Locations: []types.Location{{StartLine: 7977, EndLine: 7982}}},
{ID: "[email protected]", Name: "is-fullwidth-code-point", Version: "1.0.0", Locations: []types.Location{{StartLine: 7984, EndLine: 7989}}},
{ID: "[email protected]", Name: "is-fullwidth-code-point", Version: "2.0.0", Locations: []types.Location{{StartLine: 7991, EndLine: 7994}}},
{ID: "[email protected]", Name: "is-generator-fn", Version: "1.0.0", Locations: []types.Location{{StartLine: 7996, EndLine: 7999}}},
{ID: "[email protected]", Name: "is-glob", Version: "2.0.1", Locations: []types.Location{{StartLine: 8001, EndLine: 8006}}},
{ID: "[email protected]", Name: "is-glob", Version: "3.1.0", Locations: []types.Location{{StartLine: 8008, EndLine: 8013}}},
{ID: "[email protected]", Name: "is-glob", Version: "4.0.1", Locations: []types.Location{{StartLine: 8015, EndLine: 8020}}},
{ID: "[email protected]", Name: "is-in-browser", Version: "1.1.3", Locations: []types.Location{{StartLine: 8022, EndLine: 8025}}},
{ID: "[email protected]", Name: "is-installed-globally", Version: "0.1.0", Locations: []types.Location{{StartLine: 8027, EndLine: 8033}}},
{ID: "[email protected]", Name: "is-npm", Version: "1.0.0", Locations: []types.Location{{StartLine: 8035, EndLine: 8038}}},
{ID: "[email protected]", Name: "is-number-object", Version: "1.0.3", Locations: []types.Location{{StartLine: 8040, EndLine: 8043}}},
{ID: "[email protected]", Name: "is-number", Version: "2.1.0", Locations: []types.Location{{StartLine: 8045, EndLine: 8050}}},
{ID: "[email protected]", Name: "is-number", Version: "3.0.0", Locations: []types.Location{{StartLine: 8052, EndLine: 8057}}},
{ID: "[email protected]", Name: "is-number", Version: "4.0.0", Locations: []types.Location{{StartLine: 8059, EndLine: 8062}}},
{ID: "[email protected]", Name: "is-obj", Version: "1.0.1", Locations: []types.Location{{StartLine: 8064, EndLine: 8067}}},
{ID: "[email protected]", Name: "is-object", Version: "1.0.1", Locations: []types.Location{{StartLine: 8069, EndLine: 8072}}},
{ID: "[email protected]", Name: "is-observable", Version: "1.1.0", Locations: []types.Location{{StartLine: 8074, EndLine: 8079}}},
{ID: "[email protected]", Name: "is-path-cwd", Version: "1.0.0", Locations: []types.Location{{StartLine: 8081, EndLine: 8084}}},
{ID: "[email protected]", Name: "is-path-cwd", Version: "2.1.0", Locations: []types.Location{{StartLine: 8086, EndLine: 8089}}},
{ID: "[email protected]", Name: "is-path-in-cwd", Version: "1.0.1", Locations: []types.Location{{StartLine: 8091, EndLine: 8096}}},
{ID: "[email protected]", Name: "is-path-in-cwd", Version: "2.1.0", Locations: []types.Location{{StartLine: 8098, EndLine: 8103}}},
{ID: "[email protected]", Name: "is-path-inside", Version: "1.0.1", Locations: []types.Location{{StartLine: 8105, EndLine: 8110}}},
{ID: "[email protected]", Name: "is-path-inside", Version: "2.1.0", Locations: []types.Location{{StartLine: 8112, EndLine: 8117}}},
{ID: "[email protected]", Name: "is-plain-obj", Version: "1.1.0", Locations: []types.Location{{StartLine: 8119, EndLine: 8122}}},
{ID: "[email protected]", Name: "is-plain-object", Version: "2.0.4", Locations: []types.Location{{StartLine: 8124, EndLine: 8129}}},
{ID: "[email protected]", Name: "is-posix-bracket", Version: "0.1.1", Locations: []types.Location{{StartLine: 8131, EndLine: 8134}}},
{ID: "[email protected]", Name: "is-primitive", Version: "2.0.0", Locations: []types.Location{{StartLine: 8136, EndLine: 8139}}},
{ID: "[email protected]", Name: "is-promise", Version: "2.1.0", Locations: []types.Location{{StartLine: 8141, EndLine: 8144}}},
{ID: "[email protected]", Name: "is-redirect", Version: "1.0.0", Locations: []types.Location{{StartLine: 8146, EndLine: 8149}}},
{ID: "[email protected]", Name: "is-regex", Version: "1.0.4", Locations: []types.Location{{StartLine: 8151, EndLine: 8156}}},
{ID: "[email protected]", Name: "is-regexp", Version: "1.0.0", Locations: []types.Location{{StartLine: 8158, EndLine: 8161}}},
{ID: "[email protected]", Name: "is-retry-allowed", Version: "1.1.0", Locations: []types.Location{{StartLine: 8163, EndLine: 8166}}},
{ID: "[email protected]", Name: "is-root", Version: "2.0.0", Locations: []types.Location{{StartLine: 8168, EndLine: 8171}}},
{ID: "[email protected]", Name: "is-stream", Version: "1.1.0", Locations: []types.Location{{StartLine: 8173, EndLine: 8176}}},
{ID: "[email protected]", Name: "is-string", Version: "1.0.4", Locations: []types.Location{{StartLine: 8178, EndLine: 8181}}},
{ID: "[email protected]", Name: "is-subset", Version: "0.1.1", Locations: []types.Location{{StartLine: 8183, EndLine: 8186}}},
{ID: "[email protected]", Name: "is-symbol", Version: "1.0.2", Locations: []types.Location{{StartLine: 8188, EndLine: 8193}}},
{ID: "[email protected]", Name: "is-typedarray", Version: "1.0.0", Locations: []types.Location{{StartLine: 8195, EndLine: 8198}}},
{ID: "[email protected]", Name: "is-utf8", Version: "0.2.1", Locations: []types.Location{{StartLine: 8200, EndLine: 8203}}},
{ID: "[email protected]", Name: "is-windows", Version: "1.0.2", Locations: []types.Location{{StartLine: 8205, EndLine: 8208}}},
{ID: "[email protected]", Name: "is-wsl", Version: "1.1.0", Locations: []types.Location{{StartLine: 8210, EndLine: 8213}}},
{ID: "[email protected]", Name: "isarray", Version: "0.0.1", Locations: []types.Location{{StartLine: 8215, EndLine: 8218}}},
{ID: "[email protected]", Name: "isarray", Version: "1.0.0", Locations: []types.Location{{StartLine: 8220, EndLine: 8223}}},
{ID: "[email protected]", Name: "isarray", Version: "2.0.1", Locations: []types.Location{{StartLine: 8225, EndLine: 8228}}},
{ID: "[email protected]", Name: "isexe", Version: "2.0.0", Locations: []types.Location{{StartLine: 8230, EndLine: 8233}}},
{ID: "[email protected]", Name: "isobject", Version: "2.1.0", Locations: []types.Location{{StartLine: 8235, EndLine: 8240}}},
{ID: "[email protected]", Name: "isobject", Version: "3.0.1", Locations: []types.Location{{StartLine: 8242, EndLine: 8245}}},
{ID: "[email protected]", Name: "isomorphic-fetch", Version: "2.2.1", Locations: []types.Location{{StartLine: 8247, EndLine: 8253}}},
{ID: "[email protected]", Name: "isstream", Version: "0.1.2", Locations: []types.Location{{StartLine: 8255, EndLine: 8258}}},
{ID: "[email protected]", Name: "istanbul-api", Version: "1.3.7", Locations: []types.Location{{StartLine: 8260, EndLine: 8275}}},
{ID: "[email protected]", Name: "istanbul-lib-coverage", Version: "1.2.1", Locations: []types.Location{{StartLine: 8277, EndLine: 8280}}},
{ID: "[email protected]", Name: "istanbul-lib-hook", Version: "1.2.2", Locations: []types.Location{{StartLine: 8282, EndLine: 8287}}},
{ID: "[email protected]", Name: "istanbul-lib-instrument", Version: "1.10.2", Locations: []types.Location{{StartLine: 8289, EndLine: 8300}}},
{ID: "[email protected]", Name: "istanbul-lib-report", Version: "1.1.5", Locations: []types.Location{{StartLine: 8302, EndLine: 8310}}},
{ID: "[email protected]", Name: "istanbul-lib-source-maps", Version: "1.2.6", Locations: []types.Location{{StartLine: 8312, EndLine: 8321}}},
{ID: "[email protected]", Name: "istanbul-reports", Version: "1.5.1", Locations: []types.Location{{StartLine: 8323, EndLine: 8328}}},
{ID: "[email protected]", Name: "isurl", Version: "1.0.0", Locations: []types.Location{{StartLine: 8330, EndLine: 8336}}},
{ID: "[email protected]", Name: "jest-changed-files", Version: "23.4.2", Locations: []types.Location{{StartLine: 8338, EndLine: 8343}}},
{ID: "[email protected]", Name: "jest-cli", Version: "23.6.0", Locations: []types.Location{{StartLine: 8345, EndLine: 8385}}},
{ID: "[email protected]", Name: "jest-config", Version: "23.6.0", Locations: []types.Location{{StartLine: 8387, EndLine: 8405}}},
{ID: "[email protected]", Name: "jest-diff", Version: "23.6.0", Locations: []types.Location{{StartLine: 8407, EndLine: 8415}}},
{ID: "[email protected]", Name: "jest-docblock", Version: "23.2.0", Locations: []types.Location{{StartLine: 8417, EndLine: 8422}}},
{ID: "[email protected]", Name: "jest-each", Version: "23.6.0", Locations: []types.Location{{StartLine: 8424, EndLine: 8430}}},
{ID: "[email protected]", Name: "jest-environment-jsdom", Version: "23.4.0", Locations: []types.Location{{StartLine: 8432, EndLine: 8439}}},
{ID: "[email protected]", Name: "jest-environment-node", Version: "23.4.0", Locations: []types.Location{{StartLine: 8441, EndLine: 8447}}},
{ID: "[email protected]", Name: "jest-get-type", Version: "22.4.3", Locations: []types.Location{{StartLine: 8449, EndLine: 8452}}},
{ID: "[email protected]", Name: "jest-haste-map", Version: "23.6.0", Locations: []types.Location{{StartLine: 8454, EndLine: 8466}}},
{ID: "[email protected]", Name: "jest-jasmine2", Version: "23.6.0", Locations: []types.Location{{StartLine: 8468, EndLine: 8484}}},
{ID: "[email protected]", Name: "jest-leak-detector", Version: "23.6.0", Locations: []types.Location{{StartLine: 8486, EndLine: 8491}}},
{ID: "[email protected]", Name: "jest-matcher-utils", Version: "23.6.0", Locations: []types.Location{{StartLine: 8493, EndLine: 8500}}},
{ID: "[email protected]", Name: "jest-message-util", Version: "23.4.0", Locations: []types.Location{{StartLine: 8502, EndLine: 8511}}},
{ID: "[email protected]", Name: "jest-mock", Version: "23.2.0", Locations: []types.Location{{StartLine: 8513, EndLine: 8516}}},
{ID: "[email protected]", Name: "jest-regex-util", Version: "23.3.0", Locations: []types.Location{{StartLine: 8518, EndLine: 8521}}},
{ID: "[email protected]", Name: "jest-resolve-dependencies", Version: "23.6.0", Locations: []types.Location{{StartLine: 8523, EndLine: 8529}}},
{ID: "[email protected]", Name: "jest-resolve", Version: "23.6.0", Locations: []types.Location{{StartLine: 8531, EndLine: 8538}}},
{ID: "[email protected]", Name: "jest-runner", Version: "23.6.0", Locations: []types.Location{{StartLine: 8540, EndLine: 8557}}},
{ID: "[email protected]", Name: "jest-runtime", Version: "23.6.0", Locations: []types.Location{{StartLine: 8559, EndLine: 8584}}},
{ID: "[email protected]", Name: "jest-serializer", Version: "23.0.1", Locations: []types.Location{{StartLine: 8586, EndLine: 8589}}},
{ID: "[email protected]", Name: "jest-snapshot", Version: "23.6.0", Locations: []types.Location{{StartLine: 8591, EndLine: 8605}}},
{ID: "[email protected]", Name: "jest-util", Version: "23.4.0", Locations: []types.Location{{StartLine: 8607, EndLine: 8619}}},
{ID: "[email protected]", Name: "jest-validate", Version: "23.6.0", Locations: []types.Location{{StartLine: 8621, EndLine: 8629}}},
{ID: "[email protected]", Name: "jest-watcher", Version: "23.4.0", Locations: []types.Location{{StartLine: 8631, EndLine: 8638}}},
{ID: "[email protected]", Name: "jest-worker", Version: "23.2.0", Locations: []types.Location{{StartLine: 8640, EndLine: 8645}}},
{ID: "[email protected]", Name: "jest", Version: "23.6.0", Locations: []types.Location{{StartLine: 8647, EndLine: 8653}}},
{ID: "[email protected]", Name: "js-file-download", Version: "0.4.5", Locations: []types.Location{{StartLine: 8655, EndLine: 8658}}},
{ID: "[email protected]", Name: "js-levenshtein", Version: "1.1.6", Locations: []types.Location{{StartLine: 8660, EndLine: 8663}}},
{ID: "[email protected]", Name: "js-tokens", Version: "3.0.2", Locations: []types.Location{{StartLine: 8665, EndLine: 8668}}},
{ID: "[email protected]", Name: "js-tokens", Version: "4.0.0", Locations: []types.Location{{StartLine: 8670, EndLine: 8673}}},
{ID: "[email protected]", Name: "js-yaml", Version: "3.13.1", Locations: []types.Location{{StartLine: 8675, EndLine: 8681}}},
{ID: "[email protected]", Name: "jsbn", Version: "0.1.1", Locations: []types.Location{{StartLine: 8683, EndLine: 8686}}},
{ID: "[email protected]", Name: "jscodeshift", Version: "0.5.1", Locations: []types.Location{{StartLine: 8688, EndLine: 8707}}},
{ID: "[email protected]", Name: "jsdom", Version: "11.12.0", Locations: []types.Location{{StartLine: 8709, EndLine: 8739}}},
{ID: "[email protected]", Name: "jsesc", Version: "1.3.0", Locations: []types.Location{{StartLine: 8741, EndLine: 8744}}},
{ID: "[email protected]", Name: "jsesc", Version: "2.5.2", Locations: []types.Location{{StartLine: 8746, EndLine: 8749}}},
{ID: "[email protected]", Name: "jsesc", Version: "0.5.0", Locations: []types.Location{{StartLine: 8751, EndLine: 8754}}},
{ID: "[email protected]", Name: "json-parse-better-errors", Version: "1.0.2", Locations: []types.Location{{StartLine: 8756, EndLine: 8759}}},
{ID: "[email protected]", Name: "json-schema-traverse", Version: "0.4.1", Locations: []types.Location{{StartLine: 8761, EndLine: 8764}}},
{ID: "[email protected]", Name: "json-schema", Version: "0.2.3", Locations: []types.Location{{StartLine: 8766, EndLine: 8769}}},
{ID: "[email protected]", Name: "json-stable-stringify-without-jsonify", Version: "1.0.1", Locations: []types.Location{{StartLine: 8771, EndLine: 8774}}},
{ID: "[email protected]", Name: "json-stringify-safe", Version: "5.0.1", Locations: []types.Location{{StartLine: 8776, EndLine: 8779}}},
{ID: "[email protected]", Name: "json3", Version: "3.3.2", Locations: []types.Location{{StartLine: 8781, EndLine: 8784}}},
{ID: "[email protected]", Name: "json5", Version: "0.5.1", Locations: []types.Location{{StartLine: 8786, EndLine: 8789}}},
{ID: "[email protected]", Name: "json5", Version: "1.0.1", Locations: []types.Location{{StartLine: 8791, EndLine: 8796}}},
{ID: "[email protected]", Name: "json5", Version: "2.1.0", Locations: []types.Location{{StartLine: 8798, EndLine: 8803}}},
{ID: "[email protected]", Name: "jsonfile", Version: "2.4.0", Locations: []types.Location{{StartLine: 8805, EndLine: 8810}}},
{ID: "[email protected]", Name: "jsonfile", Version: "4.0.0", Locations: []types.Location{{StartLine: 8812, EndLine: 8817}}},
{ID: "[email protected]", Name: "jsonify", Version: "0.0.0", Locations: []types.Location{{StartLine: 8819, EndLine: 8822}}},
{ID: "[email protected]", Name: "jsonparse", Version: "1.3.1", Locations: []types.Location{{StartLine: 8824, EndLine: 8827}}},
{ID: "[email protected]", Name: "jsprim", Version: "1.4.1", Locations: []types.Location{{StartLine: 8829, EndLine: 8837}}},
{ID: "[email protected]", Name: "jss-camel-case", Version: "6.1.0", Locations: []types.Location{{StartLine: 8839, EndLine: 8844}}},
{ID: "[email protected]", Name: "jss-default-unit", Version: "8.0.2", Locations: []types.Location{{StartLine: 8846, EndLine: 8849}}},
{ID: "[email protected]", Name: "jss-global", Version: "3.0.0", Locations: []types.Location{{StartLine: 8851, EndLine: 8854}}},
{ID: "[email protected]", Name: "jss-nested", Version: "6.0.1", Locations: []types.Location{{StartLine: 8856, EndLine: 8861}}},
{ID: "[email protected]", Name: "jss-props-sort", Version: "6.0.0", Locations: []types.Location{{StartLine: 8863, EndLine: 8866}}},
{ID: "[email protected]", Name: "jss-vendor-prefixer", Version: "7.0.0", Locations: []types.Location{{StartLine: 8868, EndLine: 8873}}},
{ID: "[email protected]", Name: "jss", Version: "9.8.7", Locations: []types.Location{{StartLine: 8875, EndLine: 8882}}},
{ID: "[email protected]", Name: "jsx-ast-utils", Version: "2.1.0", Locations: []types.Location{{StartLine: 8884, EndLine: 8889}}},
{ID: "[email protected]", Name: "keycode", Version: "2.2.0", Locations: []types.Location{{StartLine: 8891, EndLine: 8894}}},
{ID: "[email protected]", Name: "killable", Version: "1.0.1", Locations: []types.Location{{StartLine: 8896, EndLine: 8899}}},
{ID: "[email protected]", Name: "kind-of", Version: "2.0.1", Locations: []types.Location{{StartLine: 8901, EndLine: 8906}}},
{ID: "[email protected]", Name: "kind-of", Version: "3.2.2", Locations: []types.Location{{StartLine: 8908, EndLine: 8913}}},
{ID: "[email protected]", Name: "kind-of", Version: "4.0.0", Locations: []types.Location{{StartLine: 8915, EndLine: 8920}}},
{ID: "[email protected]", Name: "kind-of", Version: "5.1.0", Locations: []types.Location{{StartLine: 8922, EndLine: 8925}}},
{ID: "[email protected]", Name: "kind-of", Version: "6.0.2", Locations: []types.Location{{StartLine: 8927, EndLine: 8930}}},
{ID: "[email protected]", Name: "klaw", Version: "1.3.1", Locations: []types.Location{{StartLine: 8932, EndLine: 8937}}},
{ID: "[email protected]", Name: "kleur", Version: "2.0.2", Locations: []types.Location{{StartLine: 8939, EndLine: 8942}}},
{ID: "[email protected]", Name: "latest-version", Version: "3.1.0", Locations: []types.Location{{StartLine: 8944, EndLine: 8949}}},
{ID: "[email protected]", Name: "lazy-cache", Version: "0.2.7", Locations: []types.Location{{StartLine: 8951, EndLine: 8954}}},
{ID: "[email protected]", Name: "lazy-cache", Version: "1.0.4", Locations: []types.Location{{StartLine: 8956, EndLine: 8959}}},
{ID: "[email protected]", Name: "lazy-property", Version: "1.0.0", Locations: []types.Location{{StartLine: 8961, EndLine: 8964}}},
{ID: "[email protected]", Name: "lazy-universal-dotenv", Version: "2.0.0", Locations: []types.Location{{StartLine: 8966, EndLine: 8975}}},
{ID: "[email protected]", Name: "lcid", Version: "1.0.0", Locations: []types.Location{{StartLine: 8977, EndLine: 8982}}},
{ID: "[email protected]", Name: "lcid", Version: "2.0.0", Locations: []types.Location{{StartLine: 8984, EndLine: 8989}}},
{ID: "[email protected]", Name: "left-pad", Version: "1.3.0", Locations: []types.Location{{StartLine: 8991, EndLine: 8994}}},
{ID: "[email protected]", Name: "leven", Version: "2.1.0", Locations: []types.Location{{StartLine: 8996, EndLine: 8999}}},
{ID: "[email protected]", Name: "levn", Version: "0.3.0", Locations: []types.Location{{StartLine: 9001, EndLine: 9007}}},
{ID: "[email protected]", Name: "libcipm", Version: "3.0.3", Locations: []types.Location{{StartLine: 9009, EndLine: 9028}}},
{ID: "[email protected]", Name: "libnpm", Version: "2.0.1", Locations: []types.Location{{StartLine: 9030, EndLine: 9054}}},
{ID: "[email protected]", Name: "libnpmaccess", Version: "3.0.1", Locations: []types.Location{{StartLine: 9056, EndLine: 9064}}},
{ID: "[email protected]", Name: "libnpmconfig", Version: "1.2.1", Locations: []types.Location{{StartLine: 9066, EndLine: 9073}}},
{ID: "[email protected]", Name: "libnpmhook", Version: "5.0.2", Locations: []types.Location{{StartLine: 9075, EndLine: 9083}}},
{ID: "[email protected]", Name: "libnpmorg", Version: "1.0.0", Locations: []types.Location{{StartLine: 9085, EndLine: 9093}}},
{ID: "[email protected]", Name: "libnpmpublish", Version: "1.1.1", Locations: []types.Location{{StartLine: 9095, EndLine: 9108}}},
{ID: "[email protected]", Name: "libnpmsearch", Version: "2.0.0", Locations: []types.Location{{StartLine: 9110, EndLine: 9117}}},
{ID: "[email protected]", Name: "libnpmteam", Version: "1.0.1", Locations: []types.Location{{StartLine: 9119, EndLine: 9127}}},
{ID: "[email protected]", Name: "libnpx", Version: "10.2.0", Locations: []types.Location{{StartLine: 9129, EndLine: 9141}}},
{ID: "[email protected]", Name: "linear-layout-vector", Version: "0.0.1", Locations: []types.Location{{StartLine: 9143, EndLine: 9146}}},
{ID: "[email protected]", Name: "lint-staged", Version: "7.3.0", Locations: []types.Location{{StartLine: 9148, EndLine: 9174}}},
{ID: "[email protected]", Name: "listenercount", Version: "1.0.1", Locations: []types.Location{{StartLine: 9176, EndLine: 9179}}},
{ID: "[email protected]", Name: "listr-silent-renderer", Version: "1.1.1", Locations: []types.Location{{StartLine: 9181, EndLine: 9184}}},
{ID: "[email protected]", Name: "listr-update-renderer", Version: "0.5.0", Locations: []types.Location{{StartLine: 9186, EndLine: 9198}}},
{ID: "[email protected]", Name: "listr-verbose-renderer", Version: "0.5.0", Locations: []types.Location{{StartLine: 9200, EndLine: 9208}}},
{ID: "[email protected]", Name: "listr", Version: "0.14.3", Locations: []types.Location{{StartLine: 9210, EndLine: 9223}}},
{ID: "[email protected]", Name: "load-json-file", Version: "1.1.0", Locations: []types.Location{{StartLine: 9225, EndLine: 9234}}},
{ID: "[email protected]", Name: "load-json-file", Version: "2.0.0", Locations: []types.Location{{StartLine: 9236, EndLine: 9244}}},
{ID: "[email protected]", Name: "load-json-file", Version: "4.0.0", Locations: []types.Location{{StartLine: 9246, EndLine: 9254}}},
{ID: "[email protected]", Name: "load-script", Version: "1.0.0", Locations: []types.Location{{StartLine: 9256, EndLine: 9259}}},
{ID: "[email protected]", Name: "loader-fs-cache", Version: "1.0.2", Locations: []types.Location{{StartLine: 9261, EndLine: 9267}}},
{ID: "[email protected]", Name: "loader-runner", Version: "2.4.0", Locations: []types.Location{{StartLine: 9269, EndLine: 9272}}},
{ID: "[email protected]", Name: "loader-utils", Version: "1.1.0", Locations: []types.Location{{StartLine: 9274, EndLine: 9281}}},
{ID: "[email protected]", Name: "loader-utils", Version: "0.2.17", Locations: []types.Location{{StartLine: 9283, EndLine: 9291}}},
{ID: "[email protected]", Name: "loader-utils", Version: "1.2.3", Locations: []types.Location{{StartLine: 9293, EndLine: 9300}}},
{ID: "[email protected]", Name: "locate-path", Version: "2.0.0", Locations: []types.Location{{StartLine: 9302, EndLine: 9308}}},
{ID: "[email protected]", Name: "locate-path", Version: "3.0.0", Locations: []types.Location{{StartLine: 9310, EndLine: 9316}}},
{ID: "[email protected]", Name: "lock-verify", Version: "2.1.0", Locations: []types.Location{{StartLine: 9318, EndLine: 9324}}},
{ID: "[email protected]", Name: "lockfile", Version: "1.0.4", Locations: []types.Location{{StartLine: 9326, EndLine: 9331}}},
{ID: "[email protected]", Name: "lodash-es", Version: "4.17.11", Locations: []types.Location{{StartLine: 9333, EndLine: 9336}}},
{ID: "[email protected]", Name: "lodash._baseuniq", Version: "4.6.0", Locations: []types.Location{{StartLine: 9338, EndLine: 9344}}},
{ID: "[email protected]", Name: "lodash._createset", Version: "4.0.3", Locations: []types.Location{{StartLine: 9346, EndLine: 9349}}},
{ID: "[email protected]", Name: "lodash._root", Version: "3.0.1", Locations: []types.Location{{StartLine: 9351, EndLine: 9354}}},
{ID: "[email protected]", Name: "lodash.assign", Version: "4.2.0", Locations: []types.Location{{StartLine: 9356, EndLine: 9359}}},
{ID: "[email protected]", Name: "lodash.clonedeep", Version: "4.5.0", Locations: []types.Location{{StartLine: 9361, EndLine: 9364}}},
{ID: "[email protected]", Name: "lodash.escape", Version: "4.0.1", Locations: []types.Location{{StartLine: 9366, EndLine: 9369}}},
{ID: "[email protected]", Name: "lodash.flattendeep", Version: "4.4.0", Locations: []types.Location{{StartLine: 9371, EndLine: 9374}}},
{ID: "[email protected]", Name: "lodash.isequal", Version: "4.5.0", Locations: []types.Location{{StartLine: 9376, EndLine: 9379}}},
{ID: "[email protected]", Name: "lodash.isplainobject", Version: "4.0.6", Locations: []types.Location{{StartLine: 9381, EndLine: 9384}}},
{ID: "[email protected]", Name: "lodash.merge", Version: "4.6.1", Locations: []types.Location{{StartLine: 9386, EndLine: 9389}}},
{ID: "[email protected]", Name: "lodash.some", Version: "4.6.0", Locations: []types.Location{{StartLine: 9391, EndLine: 9394}}},
{ID: "[email protected]", Name: "lodash.sortby", Version: "4.7.0", Locations: []types.Location{{StartLine: 9396, EndLine: 9399}}},
{ID: "[email protected]", Name: "lodash.union", Version: "4.6.0", Locations: []types.Location{{StartLine: 9401, EndLine: 9404}}},
{ID: "[email protected]", Name: "lodash.uniq", Version: "4.5.0", Locations: []types.Location{{StartLine: 9406, EndLine: 9409}}},
{ID: "[email protected]", Name: "lodash.without", Version: "4.4.0", Locations: []types.Location{{StartLine: 9411, EndLine: 9414}}},
{ID: "[email protected]", Name: "lodash", Version: "4.17.11", Locations: []types.Location{{StartLine: 9416, EndLine: 9419}}},
{ID: "[email protected]", Name: "lodash", Version: "3.10.1", Locations: []types.Location{{StartLine: 9421, EndLine: 9424}}},
{ID: "[email protected]", Name: "log-symbols", Version: "1.0.2", Locations: []types.Location{{StartLine: 9426, EndLine: 9431}}},
{ID: "[email protected]", Name: "log-symbols", Version: "2.2.0", Locations: []types.Location{{StartLine: 9433, EndLine: 9438}}},
{ID: "[email protected]", Name: "log-update", Version: "2.3.0", Locations: []types.Location{{StartLine: 9440, EndLine: 9447}}},
{ID: "[email protected]", Name: "loglevel", Version: "1.6.1", Locations: []types.Location{{StartLine: 9449, EndLine: 9452}}},
{ID: "[email protected]", Name: "loose-envify", Version: "1.4.0", Locations: []types.Location{{StartLine: 9454, EndLine: 9459}}},
{ID: "[email protected]", Name: "lower-case", Version: "1.1.4", Locations: []types.Location{{StartLine: 9461, EndLine: 9464}}},
{ID: "[email protected]", Name: "lowercase-keys", Version: "1.0.1", Locations: []types.Location{{StartLine: 9466, EndLine: 9469}}},
{ID: "[email protected]", Name: "lru-cache", Version: "4.1.5", Locations: []types.Location{{StartLine: 9471, EndLine: 9477}}},
{ID: "[email protected]", Name: "lru-cache", Version: "5.1.1", Locations: []types.Location{{StartLine: 9479, EndLine: 9484}}},
{ID: "[email protected]", Name: "macos-release", Version: "2.2.0", Locations: []types.Location{{StartLine: 9486, EndLine: 9489}}},
{ID: "[email protected]", Name: "make-dir", Version: "1.3.0", Locations: []types.Location{{StartLine: 9491, EndLine: 9496}}},
{ID: "[email protected]", Name: "make-dir", Version: "2.1.0", Locations: []types.Location{{StartLine: 9498, EndLine: 9504}}},
{ID: "[email protected]", Name: "make-error", Version: "1.3.5", Locations: []types.Location{{StartLine: 9506, EndLine: 9509}}},
{ID: "[email protected]", Name: "make-fetch-happen", Version: "4.0.1", Locations: []types.Location{{StartLine: 9511, EndLine: 9526}}},
{ID: "[email protected]", Name: "makeerror", Version: "1.0.11", Locations: []types.Location{{StartLine: 9528, EndLine: 9533}}},
{ID: "[email protected]", Name: "mamacro", Version: "0.0.3", Locations: []types.Location{{StartLine: 9535, EndLine: 9538}}},
{ID: "[email protected]", Name: "map-age-cleaner", Version: "0.1.3", Locations: []types.Location{{StartLine: 9540, EndLine: 9545}}},
{ID: "[email protected]", Name: "map-cache", Version: "0.2.2", Locations: []types.Location{{StartLine: 9547, EndLine: 9550}}},
{ID: "[email protected]", Name: "map-visit", Version: "1.0.0", Locations: []types.Location{{StartLine: 9552, EndLine: 9557}}},
{ID: "[email protected]", Name: "marked", Version: "0.3.19", Locations: []types.Location{{StartLine: 9559, EndLine: 9562}}},
{ID: "[email protected]", Name: "marksy", Version: "6.1.0", Locations: []types.Location{{StartLine: 9564, EndLine: 9571}}},
{ID: "[email protected]", Name: "material-colors", Version: "1.2.6", Locations: []types.Location{{StartLine: 9573, EndLine: 9576}}},
{ID: "[email protected]", Name: "math-random", Version: "1.0.4", Locations: []types.Location{{StartLine: 9578, EndLine: 9581}}},
{ID: "[email protected]", Name: "md5.js", Version: "1.3.5", Locations: []types.Location{{StartLine: 9583, EndLine: 9590}}},
{ID: "[email protected]", Name: "md5", Version: "2.2.1", Locations: []types.Location{{StartLine: 9592, EndLine: 9599}}},
{ID: "[email protected]", Name: "mdn-data", Version: "1.1.4", Locations: []types.Location{{StartLine: 9601, EndLine: 9604}}},
{ID: "[email protected]", Name: "meant", Version: "1.0.1", Locations: []types.Location{{StartLine: 9606, EndLine: 9609}}},
{ID: "[email protected]", Name: "media-typer", Version: "0.3.0", Locations: []types.Location{{StartLine: 9611, EndLine: 9614}}},
{ID: "[email protected]", Name: "mem", Version: "1.1.0", Locations: []types.Location{{StartLine: 9616, EndLine: 9621}}},
{ID: "[email protected]", Name: "mem", Version: "4.3.0", Locations: []types.Location{{StartLine: 9623, EndLine: 9630}}},
{ID: "[email protected]", Name: "memoize-one", Version: "4.1.0", Locations: []types.Location{{StartLine: 9632, EndLine: 9635}}},
{ID: "[email protected]", Name: "memory-fs", Version: "0.4.1", Locations: []types.Location{{StartLine: 9637, EndLine: 9643}}},
{ID: "[email protected]", Name: "memorystream", Version: "0.3.1", Locations: []types.Location{{StartLine: 9645, EndLine: 9648}}},
{ID: "[email protected]", Name: "merge-deep", Version: "3.0.2", Locations: []types.Location{{StartLine: 9650, EndLine: 9657}}},
{ID: "[email protected]", Name: "merge-descriptors", Version: "1.0.1", Locations: []types.Location{{StartLine: 9659, EndLine: 9662}}},
{ID: "[email protected]", Name: "merge-dirs", Version: "0.2.1", Locations: []types.Location{{StartLine: 9664, EndLine: 9672}}},
{ID: "[email protected]", Name: "merge-stream", Version: "1.0.1", Locations: []types.Location{{StartLine: 9674, EndLine: 9679}}},
{ID: "[email protected]", Name: "merge2", Version: "1.2.3", Locations: []types.Location{{StartLine: 9681, EndLine: 9684}}},
{ID: "[email protected]", Name: "merge", Version: "1.2.1", Locations: []types.Location{{StartLine: 9686, EndLine: 9689}}},
{ID: "[email protected]", Name: "methods", Version: "1.1.2", Locations: []types.Location{{StartLine: 9691, EndLine: 9694}}},
{ID: "[email protected]", Name: "micromatch", Version: "2.3.11", Locations: []types.Location{{StartLine: 9696, EndLine: 9713}}},
{ID: "[email protected]", Name: "micromatch", Version: "3.1.10", Locations: []types.Location{{StartLine: 9715, EndLine: 9732}}},
{ID: "[email protected]", Name: "miller-rabin", Version: "4.0.1", Locations: []types.Location{{StartLine: 9734, EndLine: 9740}}},
{ID: "[email protected]", Name: "mime-db", Version: "1.40.0", Locations: []types.Location{{StartLine: 9742, EndLine: 9745}}},
{ID: "[email protected]", Name: "mime-types", Version: "2.1.24", Locations: []types.Location{{StartLine: 9747, EndLine: 9752}}},
{ID: "[email protected]", Name: "mime", Version: "1.4.1", Locations: []types.Location{{StartLine: 9754, EndLine: 9757}}},
{ID: "[email protected]", Name: "mime", Version: "2.4.2", Locations: []types.Location{{StartLine: 9759, EndLine: 9762}}},
{ID: "[email protected]", Name: "mimic-fn", Version: "1.2.0", Locations: []types.Location{{StartLine: 9764, EndLine: 9767}}},
{ID: "[email protected]", Name: "mimic-fn", Version: "2.1.0", Locations: []types.Location{{StartLine: 9769, EndLine: 9772}}},
{ID: "[email protected]", Name: "mimic-response", Version: "1.0.1", Locations: []types.Location{{StartLine: 9774, EndLine: 9777}}},
{ID: "[email protected]", Name: "min-document", Version: "2.19.0", Locations: []types.Location{{StartLine: 9779, EndLine: 9784}}},
{ID: "[email protected]", Name: "mini-css-extract-plugin", Version: "0.4.5", Locations: []types.Location{{StartLine: 9786, EndLine: 9793}}},
{ID: "[email protected]", Name: "minimalistic-assert", Version: "1.0.1", Locations: []types.Location{{StartLine: 9795, EndLine: 9798}}},
{ID: "[email protected]", Name: "minimalistic-crypto-utils", Version: "1.0.1", Locations: []types.Location{{StartLine: 9800, EndLine: 9803}}},
{ID: "[email protected]", Name: "minimatch", Version: "3.0.4", Locations: []types.Location{{StartLine: 9805, EndLine: 9810}}},
{ID: "[email protected]", Name: "minimist", Version: "0.0.8", Locations: []types.Location{{StartLine: 9812, EndLine: 9815}}},
{ID: "[email protected]", Name: "minimist", Version: "1.2.0", Locations: []types.Location{{StartLine: 9817, EndLine: 9820}}},
{ID: "[email protected]", Name: "minimist", Version: "0.0.10", Locations: []types.Location{{StartLine: 9822, EndLine: 9825}}},
{ID: "[email protected]", Name: "minipass", Version: "2.3.5", Locations: []types.Location{{StartLine: 9827, EndLine: 9833}}},
{ID: "[email protected]", Name: "minizlib", Version: "1.2.1", Locations: []types.Location{{StartLine: 9835, EndLine: 9840}}},
{ID: "[email protected]", Name: "mississippi", Version: "2.0.0", Locations: []types.Location{{StartLine: 9842, EndLine: 9856}}},
{ID: "[email protected]", Name: "mississippi", Version: "3.0.0", Locations: []types.Location{{StartLine: 9858, EndLine: 9872}}},
{ID: "[email protected]", Name: "mixin-deep", Version: "1.3.1", Locations: []types.Location{{StartLine: 9874, EndLine: 9880}}},
{ID: "[email protected]", Name: "mixin-object", Version: "2.0.1", Locations: []types.Location{{StartLine: 9882, EndLine: 9888}}},
{ID: "[email protected]", Name: "mkdirp", Version: "0.5.1", Locations: []types.Location{{StartLine: 9890, EndLine: 9895}}},
{ID: "[email protected]", Name: "moment-timezone", Version: "0.5.23", Locations: []types.Location{{StartLine: 9897, EndLine: 9902}}},
{ID: "[email protected]", Name: "moment", Version: "2.23.0", Locations: []types.Location{{StartLine: 9904, EndLine: 9907}}},
{ID: "[email protected]", Name: "moment", Version: "2.24.0", Locations: []types.Location{{StartLine: 9909, EndLine: 9912}}},
{ID: "[email protected]", Name: "moo", Version: "0.4.3", Locations: []types.Location{{StartLine: 9914, EndLine: 9917}}},
{ID: "[email protected]", Name: "move-concurrently", Version: "1.0.1", Locations: []types.Location{{StartLine: 9919, EndLine: 9929}}},
{ID: "[email protected]", Name: "ms", Version: "2.0.0", Locations: []types.Location{{StartLine: 9931, EndLine: 9934}}},
{ID: "[email protected]", Name: "ms", Version: "2.1.1", Locations: []types.Location{{StartLine: 9936, EndLine: 9939}}},
{ID: "[email protected]", Name: "multicast-dns-service-types", Version: "1.1.0", Locations: []types.Location{{StartLine: 9941, EndLine: 9944}}},
{ID: "[email protected]", Name: "multicast-dns", Version: "6.2.3", Locations: []types.Location{{StartLine: 9946, EndLine: 9952}}},
{ID: "[email protected]", Name: "mute-stream", Version: "0.0.5", Locations: []types.Location{{StartLine: 9954, EndLine: 9957}}},
{ID: "[email protected]", Name: "mute-stream", Version: "0.0.7", Locations: []types.Location{{StartLine: 9959, EndLine: 9962}}},
{ID: "[email protected]", Name: "mute-stream", Version: "0.0.8", Locations: []types.Location{{StartLine: 9964, EndLine: 9967}}},
{ID: "[email protected]", Name: "nan", Version: "2.13.2", Locations: []types.Location{{StartLine: 9969, EndLine: 9972}}},
{ID: "[email protected]", Name: "nanomatch", Version: "1.2.13", Locations: []types.Location{{StartLine: 9974, EndLine: 9989}}},
{ID: "[email protected]", Name: "natural-compare", Version: "1.4.0", Locations: []types.Location{{StartLine: 9991, EndLine: 9994}}},
{ID: "[email protected]", Name: "nearley", Version: "2.16.0", Locations: []types.Location{{StartLine: 9996, EndLine: 10005}}},
{ID: "[email protected]", Name: "needle", Version: "2.4.0", Locations: []types.Location{{StartLine: 10007, EndLine: 10014}}},
{ID: "[email protected]", Name: "negotiator", Version: "0.6.2", Locations: []types.Location{{StartLine: 10016, EndLine: 10019}}},
{ID: "[email protected]", Name: "neo-async", Version: "2.6.1", Locations: []types.Location{{StartLine: 10021, EndLine: 10024}}},
{ID: "[email protected]", Name: "nested-object-assign", Version: "1.0.3", Locations: []types.Location{{StartLine: 10026, EndLine: 10029}}},
{ID: "[email protected]", Name: "nice-try", Version: "1.0.5", Locations: []types.Location{{StartLine: 10031, EndLine: 10034}}},
{ID: "[email protected]", Name: "no-case", Version: "2.3.2", Locations: []types.Location{{StartLine: 10036, EndLine: 10041}}},
{ID: "[email protected]", Name: "node-dir", Version: "0.1.8", Locations: []types.Location{{StartLine: 10043, EndLine: 10046}}},
{ID: "[email protected]", Name: "node-dir", Version: "0.1.17", Locations: []types.Location{{StartLine: 10048, EndLine: 10053}}},
{ID: "[email protected]", Name: "node-fetch-npm", Version: "2.0.2", Locations: []types.Location{{StartLine: 10055, EndLine: 10062}}},
{ID: "[email protected]", Name: "node-fetch", Version: "1.7.3", Locations: []types.Location{{StartLine: 10064, EndLine: 10070}}},
{ID: "[email protected]", Name: "node-fetch", Version: "2.5.0", Locations: []types.Location{{StartLine: 10072, EndLine: 10075}}},
{ID: "[email protected]", Name: "node-forge", Version: "0.7.5", Locations: []types.Location{{StartLine: 10077, EndLine: 10080}}},
{ID: "[email protected]", Name: "node-fs", Version: "0.1.7", Locations: []types.Location{{StartLine: 10082, EndLine: 10085}}},
{ID: "[email protected]", Name: "node-gyp", Version: "3.8.0", Locations: []types.Location{{StartLine: 10087, EndLine: 10103}}},
{ID: "[email protected]", Name: "node-gyp", Version: "4.0.0", Locations: []types.Location{{StartLine: 10105, EndLine: 10120}}},
{ID: "[email protected]", Name: "node-int64", Version: "0.4.0", Locations: []types.Location{{StartLine: 10122, EndLine: 10125}}},
{ID: "[email protected]", Name: "node-libs-browser", Version: "2.2.0", Locations: []types.Location{{StartLine: 10127, EndLine: 10154}}},
{ID: "[email protected]", Name: "node-modules-regexp", Version: "1.0.0", Locations: []types.Location{{StartLine: 10156, EndLine: 10159}}},
{ID: "[email protected]", Name: "node-notifier", Version: "5.4.0", Locations: []types.Location{{StartLine: 10161, EndLine: 10170}}},
{ID: "[email protected]", Name: "node-object-hash", Version: "1.4.2", Locations: []types.Location{{StartLine: 10172, EndLine: 10175}}},
{ID: "[email protected]", Name: "node-pre-gyp", Version: "0.12.0", Locations: []types.Location{{StartLine: 10177, EndLine: 10191}}},
{ID: "[email protected]", Name: "node-releases", Version: "1.1.19", Locations: []types.Location{{StartLine: 10193, EndLine: 10198}}},
{ID: "[email protected]", Name: "node-version", Version: "1.2.0", Locations: []types.Location{{StartLine: 10200, EndLine: 10203}}},
{ID: "[email protected]", Name: "nomnom", Version: "1.8.1", Locations: []types.Location{{StartLine: 10205, EndLine: 10211}}},
{ID: "[email protected]", Name: "nopt", Version: "3.0.6", Locations: []types.Location{{StartLine: 10213, EndLine: 10218}}},
{ID: "[email protected]", Name: "nopt", Version: "4.0.1", Locations: []types.Location{{StartLine: 10220, EndLine: 10226}}},
{ID: "[email protected]", Name: "normalize-package-data", Version: "2.5.0", Locations: []types.Location{{StartLine: 10228, EndLine: 10236}}},
{ID: "[email protected]", Name: "normalize-path", Version: "2.1.1", Locations: []types.Location{{StartLine: 10238, EndLine: 10243}}},
{ID: "[email protected]", Name: "normalize-path", Version: "3.0.0", Locations: []types.Location{{StartLine: 10245, EndLine: 10248}}},
{ID: "[email protected]", Name: "normalize-range", Version: "0.1.2", Locations: []types.Location{{StartLine: 10250, EndLine: 10253}}},
{ID: "[email protected]", Name: "normalize-scroll-left", Version: "0.1.2", Locations: []types.Location{{StartLine: 10255, EndLine: 10258}}},
{ID: "[email protected]", Name: "npm-audit-report", Version: "1.3.2", Locations: []types.Location{{StartLine: 10260, EndLine: 10266}}},
{ID: "[email protected]", Name: "npm-bundled", Version: "1.0.6", Locations: []types.Location{{StartLine: 10268, EndLine: 10271}}},
{ID: "[email protected]", Name: "npm-cache-filename", Version: "1.0.2", Locations: []types.Location{{StartLine: 10273, EndLine: 10276}}},
{ID: "[email protected]", Name: "npm-install-checks", Version: "3.0.0", Locations: []types.Location{{StartLine: 10278, EndLine: 10283}}},
{ID: "[email protected]", Name: "npm-lifecycle", Version: "2.1.1", Locations: []types.Location{{StartLine: 10285, EndLine: 10297}}},
{ID: "[email protected]", Name: "npm-logical-tree", Version: "1.2.1", Locations: []types.Location{{StartLine: 10299, EndLine: 10302}}},
{ID: "[email protected]", Name: "npm-package-arg", Version: "6.1.0", Locations: []types.Location{{StartLine: 10304, EndLine: 10312}}},
{ID: "[email protected]", Name: "npm-packlist", Version: "1.4.1", Locations: []types.Location{{StartLine: 10314, EndLine: 10320}}},
{ID: "[email protected]", Name: "npm-path", Version: "2.0.4", Locations: []types.Location{{StartLine: 10322, EndLine: 10327}}},
{ID: "[email protected]", Name: "npm-pick-manifest", Version: "2.2.3", Locations: []types.Location{{StartLine: 10329, EndLine: 10336}}},
{ID: "[email protected]", Name: "npm-profile", Version: "4.0.1", Locations: []types.Location{{StartLine: 10338, EndLine: 10345}}},
{ID: "[email protected]", Name: "npm-registry-fetch", Version: "3.9.0", Locations: []types.Location{{StartLine: 10347, EndLine: 10357}}},
{ID: "[email protected]", Name: "npm-run-all", Version: "4.1.5", Locations: []types.Location{{StartLine: 10359, EndLine: 10372}}},
{ID: "[email protected]", Name: "npm-run-path", Version: "2.0.2", Locations: []types.Location{{StartLine: 10374, EndLine: 10379}}},
{ID: "[email protected]", Name: "npm-user-validate", Version: "1.0.0", Locations: []types.Location{{StartLine: 10381, EndLine: 10384}}},
{ID: "[email protected]", Name: "npm-which", Version: "3.0.1", Locations: []types.Location{{StartLine: 10386, EndLine: 10393}}},
{ID: "[email protected]", Name: "npm", Version: "6.9.0", Locations: []types.Location{{StartLine: 10395, EndLine: 10507}}},
{ID: "[email protected]", Name: "npmlog", Version: "4.1.2", Locations: []types.Location{{StartLine: 10509, EndLine: 10517}}},
{ID: "[email protected]", Name: "nth-check", Version: "1.0.2", Locations: []types.Location{{StartLine: 10519, EndLine: 10524}}},
{ID: "[email protected]", Name: "num2fraction", Version: "1.2.2", Locations: []types.Location{{StartLine: 10526, EndLine: 10529}}},
{ID: "[email protected]", Name: "number-is-nan", Version: "1.0.1", Locations: []types.Location{{StartLine: 10531, EndLine: 10534}}},
{ID: "[email protected]", Name: "nwsapi", Version: "2.1.4", Locations: []types.Location{{StartLine: 10536, EndLine: 10539}}},
{ID: "[email protected]", Name: "oauth-sign", Version: "0.9.0", Locations: []types.Location{{StartLine: 10541, EndLine: 10544}}},
{ID: "[email protected]", Name: "object-assign", Version: "4.1.1", Locations: []types.Location{{StartLine: 10546, EndLine: 10549}}},
{ID: "[email protected]", Name: "object-component", Version: "0.0.3", Locations: []types.Location{{StartLine: 10551, EndLine: 10554}}},
{ID: "[email protected]", Name: "object-copy", Version: "0.1.0", Locations: []types.Location{{StartLine: 10556, EndLine: 10563}}},
{ID: "[email protected]", Name: "object-hash", Version: "1.3.1", Locations: []types.Location{{StartLine: 10565, EndLine: 10568}}},
{ID: "[email protected]", Name: "object-inspect", Version: "1.6.0", Locations: []types.Location{{StartLine: 10570, EndLine: 10573}}},
{ID: "[email protected]", Name: "object-is", Version: "1.0.1", Locations: []types.Location{{StartLine: 10575, EndLine: 10578}}},
{ID: "[email protected]", Name: "object-keys", Version: "1.1.1", Locations: []types.Location{{StartLine: 10580, EndLine: 10583}}},
{ID: "[email protected]", Name: "object-visit", Version: "1.0.1", Locations: []types.Location{{StartLine: 10585, EndLine: 10590}}},
{ID: "[email protected]", Name: "object.assign", Version: "4.1.0", Locations: []types.Location{{StartLine: 10592, EndLine: 10600}}},
{ID: "[email protected]", Name: "object.entries", Version: "1.1.0", Locations: []types.Location{{StartLine: 10602, EndLine: 10610}}},
{ID: "[email protected]", Name: "object.fromentries", Version: "2.0.0", Locations: []types.Location{{StartLine: 10612, EndLine: 10620}}},
{ID: "[email protected]", Name: "object.getownpropertydescriptors", Version: "2.0.3", Locations: []types.Location{{StartLine: 10622, EndLine: 10628}}},
{ID: "[email protected]", Name: "object.omit", Version: "2.0.1", Locations: []types.Location{{StartLine: 10630, EndLine: 10636}}},
{ID: "[email protected]", Name: "object.pick", Version: "1.3.0", Locations: []types.Location{{StartLine: 10638, EndLine: 10643}}},
{ID: "[email protected]", Name: "object.values", Version: "1.1.0", Locations: []types.Location{{StartLine: 10645, EndLine: 10653}}},
{ID: "[email protected]", Name: "obuf", Version: "1.1.2", Locations: []types.Location{{StartLine: 10655, EndLine: 10658}}},
{ID: "[email protected]", Name: "on-finished", Version: "2.3.0", Locations: []types.Location{{StartLine: 10660, EndLine: 10665}}},
{ID: "[email protected]", Name: "on-headers", Version: "1.0.2", Locations: []types.Location{{StartLine: 10667, EndLine: 10670}}},
{ID: "[email protected]", Name: "once", Version: "1.4.0", Locations: []types.Location{{StartLine: 10672, EndLine: 10677}}},
{ID: "[email protected]", Name: "onetime", Version: "1.1.0", Locations: []types.Location{{StartLine: 10679, EndLine: 10682}}},
{ID: "[email protected]", Name: "onetime", Version: "2.0.1", Locations: []types.Location{{StartLine: 10684, EndLine: 10689}}},
{ID: "[email protected]", Name: "opener", Version: "1.5.1", Locations: []types.Location{{StartLine: 10691, EndLine: 10694}}},
{ID: "[email protected]", Name: "opn", Version: "5.4.0", Locations: []types.Location{{StartLine: 10696, EndLine: 10701}}},
{ID: "[email protected]", Name: "opn", Version: "5.5.0", Locations: []types.Location{{StartLine: 10703, EndLine: 10708}}},
{ID: "[email protected]", Name: "optimist", Version: "0.6.1", Locations: []types.Location{{StartLine: 10710, EndLine: 10716}}},
{ID: "[email protected]", Name: "optionator", Version: "0.8.2", Locations: []types.Location{{StartLine: 10718, EndLine: 10728}}},
{ID: "[email protected]", Name: "original", Version: "1.0.2", Locations: []types.Location{{StartLine: 10730, EndLine: 10735}}},
{ID: "[email protected]", Name: "os-browserify", Version: "0.3.0", Locations: []types.Location{{StartLine: 10737, EndLine: 10740}}},
{ID: "[email protected]", Name: "os-homedir", Version: "1.0.2", Locations: []types.Location{{StartLine: 10742, EndLine: 10745}}},
{ID: "[email protected]", Name: "os-locale", Version: "1.4.0", Locations: []types.Location{{StartLine: 10747, EndLine: 10752}}},
{ID: "[email protected]", Name: "os-locale", Version: "2.1.0", Locations: []types.Location{{StartLine: 10754, EndLine: 10761}}},
{ID: "[email protected]", Name: "os-locale", Version: "3.1.0", Locations: []types.Location{{StartLine: 10763, EndLine: 10770}}},
{ID: "[email protected]", Name: "os-name", Version: "3.1.0", Locations: []types.Location{{StartLine: 10772, EndLine: 10778}}},
{ID: "[email protected]", Name: "os-tmpdir", Version: "1.0.2", Locations: []types.Location{{StartLine: 10780, EndLine: 10783}}},
{ID: "[email protected]", Name: "osenv", Version: "0.1.5", Locations: []types.Location{{StartLine: 10785, EndLine: 10791}}},
{ID: "[email protected]", Name: "output-file-sync", Version: "1.1.2", Locations: []types.Location{{StartLine: 10793, EndLine: 10800}}},
{ID: "[email protected]", Name: "p-cancelable", Version: "0.3.0", Locations: []types.Location{{StartLine: 10802, EndLine: 10805}}},
{ID: "[email protected]", Name: "p-defer", Version: "1.0.0", Locations: []types.Location{{StartLine: 10807, EndLine: 10810}}},
{ID: "[email protected]", Name: "p-finally", Version: "1.0.0", Locations: []types.Location{{StartLine: 10812, EndLine: 10815}}},
{ID: "[email protected]", Name: "p-is-promise", Version: "2.1.0", Locations: []types.Location{{StartLine: 10817, EndLine: 10820}}},
{ID: "[email protected]", Name: "p-limit", Version: "1.3.0", Locations: []types.Location{{StartLine: 10822, EndLine: 10827}}},
{ID: "[email protected]", Name: "p-limit", Version: "2.2.0", Locations: []types.Location{{StartLine: 10829, EndLine: 10834}}},
{ID: "[email protected]", Name: "p-locate", Version: "2.0.0", Locations: []types.Location{{StartLine: 10836, EndLine: 10841}}},
{ID: "[email protected]", Name: "p-locate", Version: "3.0.0", Locations: []types.Location{{StartLine: 10843, EndLine: 10848}}},
{ID: "[email protected]", Name: "p-map", Version: "1.2.0", Locations: []types.Location{{StartLine: 10850, EndLine: 10853}}},
{ID: "[email protected]", Name: "p-map", Version: "2.1.0", Locations: []types.Location{{StartLine: 10855, EndLine: 10858}}},
{ID: "[email protected]", Name: "p-timeout", Version: "1.2.1", Locations: []types.Location{{StartLine: 10860, EndLine: 10865}}},
{ID: "[email protected]", Name: "p-try", Version: "1.0.0", Locations: []types.Location{{StartLine: 10867, EndLine: 10870}}},
{ID: "[email protected]", Name: "p-try", Version: "2.2.0", Locations: []types.Location{{StartLine: 10872, EndLine: 10875}}},
{ID: "[email protected]", Name: "package-json", Version: "4.0.1", Locations: []types.Location{{StartLine: 10877, EndLine: 10885}}},
{ID: "[email protected]", Name: "pacote", Version: "9.5.0", Locations: []types.Location{{StartLine: 10887, EndLine: 10918}}},
{ID: "[email protected]", Name: "pako", Version: "1.0.10", Locations: []types.Location{{StartLine: 10920, EndLine: 10923}}},
{ID: "[email protected]", Name: "parallel-transform", Version: "1.1.0", Locations: []types.Location{{StartLine: 10925, EndLine: 10932}}},
{ID: "[email protected]", Name: "param-case", Version: "2.1.1", Locations: []types.Location{{StartLine: 10934, EndLine: 10939}}},
{ID: "[email protected]", Name: "parent-module", Version: "1.0.1", Locations: []types.Location{{StartLine: 10941, EndLine: 10946}}},
{ID: "[email protected]", Name: "parse-asn1", Version: "5.1.4", Locations: []types.Location{{StartLine: 10948, EndLine: 10958}}},
{ID: "[email protected]", Name: "parse-glob", Version: "3.0.4", Locations: []types.Location{{StartLine: 10960, EndLine: 10968}}},
{ID: "[email protected]", Name: "parse-json", Version: "2.2.0", Locations: []types.Location{{StartLine: 10970, EndLine: 10975}}},
{ID: "[email protected]", Name: "parse-json", Version: "4.0.0", Locations: []types.Location{{StartLine: 10977, EndLine: 10983}}},
{ID: "[email protected]", Name: "parse-passwd", Version: "1.0.0", Locations: []types.Location{{StartLine: 10985, EndLine: 10988}}},
{ID: "[email protected]", Name: "parse5", Version: "4.0.0", Locations: []types.Location{{StartLine: 10990, EndLine: 10993}}},
{ID: "[email protected]", Name: "parse5", Version: "3.0.3", Locations: []types.Location{{StartLine: 10995, EndLine: 11000}}},
{ID: "[email protected]", Name: "parse5", Version: "5.1.0", Locations: []types.Location{{StartLine: 11002, EndLine: 11005}}},
{ID: "[email protected]", Name: "parseqs", Version: "0.0.5", Locations: []types.Location{{StartLine: 11007, EndLine: 11012}}},
{ID: "[email protected]", Name: "parseuri", Version: "0.0.5", Locations: []types.Location{{StartLine: 11014, EndLine: 11019}}},
{ID: "[email protected]", Name: "parseurl", Version: "1.3.3", Locations: []types.Location{{StartLine: 11021, EndLine: 11024}}},
{ID: "[email protected]", Name: "pascalcase", Version: "0.1.1", Locations: []types.Location{{StartLine: 11026, EndLine: 11029}}},
{ID: "[email protected]", Name: "path-browserify", Version: "0.0.0", Locations: []types.Location{{StartLine: 11031, EndLine: 11034}}},
{ID: "[email protected]", Name: "path-dirname", Version: "1.0.2", Locations: []types.Location{{StartLine: 11036, EndLine: 11039}}},
{ID: "[email protected]", Name: "path-exists", Version: "2.1.0", Locations: []types.Location{{StartLine: 11041, EndLine: 11046}}},
{ID: "[email protected]", Name: "path-exists", Version: "3.0.0", Locations: []types.Location{{StartLine: 11048, EndLine: 11051}}},
{ID: "[email protected]", Name: "path-is-absolute", Version: "1.0.1", Locations: []types.Location{{StartLine: 11053, EndLine: 11056}}},
{ID: "[email protected]", Name: "path-is-inside", Version: "1.0.2", Locations: []types.Location{{StartLine: 11058, EndLine: 11061}}},
{ID: "[email protected]", Name: "path-key", Version: "2.0.1", Locations: []types.Location{{StartLine: 11063, EndLine: 11066}}},
{ID: "[email protected]", Name: "path-parse", Version: "1.0.6", Locations: []types.Location{{StartLine: 11068, EndLine: 11071}}},
{ID: "[email protected]", Name: "path-to-regexp", Version: "0.1.7", Locations: []types.Location{{StartLine: 11073, EndLine: 11076}}},
{ID: "[email protected]", Name: "path-to-regexp", Version: "1.7.0", Locations: []types.Location{{StartLine: 11078, EndLine: 11083}}},
{ID: "[email protected]", Name: "path-type", Version: "1.1.0", Locations: []types.Location{{StartLine: 11085, EndLine: 11092}}},
{ID: "[email protected]", Name: "path-type", Version: "2.0.0", Locations: []types.Location{{StartLine: 11094, EndLine: 11099}}},
{ID: "[email protected]", Name: "path-type", Version: "3.0.0", Locations: []types.Location{{StartLine: 11101, EndLine: 11106}}},
{ID: "[email protected]", Name: "path", Version: "0.12.7", Locations: []types.Location{{StartLine: 11108, EndLine: 11114}}},
{ID: "[email protected]", Name: "pbkdf2", Version: "3.0.17", Locations: []types.Location{{StartLine: 11116, EndLine: 11125}}},
{ID: "[email protected]", Name: "performance-now", Version: "2.1.0", Locations: []types.Location{{StartLine: 11127, EndLine: 11130}}},
{ID: "[email protected]", Name: "pidtree", Version: "0.3.0", Locations: []types.Location{{StartLine: 11132, EndLine: 11135}}},
{ID: "[email protected]", Name: "pify", Version: "2.3.0", Locations: []types.Location{{StartLine: 11137, EndLine: 11140}}},
{ID: "[email protected]", Name: "pify", Version: "3.0.0", Locations: []types.Location{{StartLine: 11142, EndLine: 11145}}},
{ID: "[email protected]", Name: "pify", Version: "4.0.1", Locations: []types.Location{{StartLine: 11147, EndLine: 11150}}},
{ID: "[email protected]", Name: "pinkie-promise", Version: "2.0.1", Locations: []types.Location{{StartLine: 11152, EndLine: 11157}}},
{ID: "[email protected]", Name: "pinkie", Version: "2.0.4", Locations: []types.Location{{StartLine: 11159, EndLine: 11162}}},
{ID: "[email protected]", Name: "pirates", Version: "4.0.1", Locations: []types.Location{{StartLine: 11164, EndLine: 11169}}},
{ID: "[email protected]", Name: "pkg-dir", Version: "1.0.0", Locations: []types.Location{{StartLine: 11171, EndLine: 11176}}},
{ID: "[email protected]", Name: "pkg-dir", Version: "2.0.0", Locations: []types.Location{{StartLine: 11178, EndLine: 11183}}},
{ID: "[email protected]", Name: "pkg-dir", Version: "3.0.0", Locations: []types.Location{{StartLine: 11185, EndLine: 11190}}},
{ID: "[email protected]", Name: "pkg-up", Version: "2.0.0", Locations: []types.Location{{StartLine: 11192, EndLine: 11197}}},
{ID: "[email protected]", Name: "please-upgrade-node", Version: "3.1.1", Locations: []types.Location{{StartLine: 11199, EndLine: 11204}}},
{ID: "[email protected]", Name: "pn", Version: "1.1.0", Locations: []types.Location{{StartLine: 11206, EndLine: 11209}}},
{ID: "[email protected]", Name: "popper.js", Version: "1.15.0", Locations: []types.Location{{StartLine: 11211, EndLine: 11214}}},
{ID: "[email protected]", Name: "portfinder", Version: "1.0.20", Locations: []types.Location{{StartLine: 11216, EndLine: 11223}}},
{ID: "[email protected]", Name: "posix-character-classes", Version: "0.1.1", Locations: []types.Location{{StartLine: 11225, EndLine: 11228}}},
{ID: "[email protected]", Name: "postcss-flexbugs-fixes", Version: "4.1.0", Locations: []types.Location{{StartLine: 11230, EndLine: 11235}}},
{ID: "[email protected]", Name: "postcss-load-config", Version: "2.0.0", Locations: []types.Location{{StartLine: 11237, EndLine: 11243}}},
{ID: "[email protected]", Name: "postcss-loader", Version: "3.0.0", Locations: []types.Location{{StartLine: 11245, EndLine: 11253}}},
{ID: "[email protected]", Name: "postcss-modules-extract-imports", Version: "1.2.1", Locations: []types.Location{{StartLine: 11255, EndLine: 11260}}},
{ID: "[email protected]", Name: "postcss-modules-local-by-default", Version: "1.2.0", Locations: []types.Location{{StartLine: 11262, EndLine: 11268}}},
{ID: "[email protected]", Name: "postcss-modules-scope", Version: "1.1.0", Locations: []types.Location{{StartLine: 11270, EndLine: 11276}}},
{ID: "[email protected]", Name: "postcss-modules-values", Version: "1.3.0", Locations: []types.Location{{StartLine: 11278, EndLine: 11284}}},
{ID: "[email protected]", Name: "postcss-value-parser", Version: "3.3.1", Locations: []types.Location{{StartLine: 11286, EndLine: 11289}}},
{ID: "[email protected]", Name: "postcss", Version: "6.0.23", Locations: []types.Location{{StartLine: 11291, EndLine: 11298}}},
{ID: "[email protected]", Name: "postcss", Version: "7.0.16", Locations: []types.Location{{StartLine: 11300, EndLine: 11307}}},
{ID: "[email protected]", Name: "prelude-ls", Version: "1.1.2", Locations: []types.Location{{StartLine: 11309, EndLine: 11312}}},
{ID: "[email protected]", Name: "prepend-http", Version: "1.0.4", Locations: []types.Location{{StartLine: 11314, EndLine: 11317}}},
{ID: "[email protected]", Name: "preserve", Version: "0.2.0", Locations: []types.Location{{StartLine: 11319, EndLine: 11322}}},
{ID: "[email protected]", Name: "pretty-error", Version: "2.1.1", Locations: []types.Location{{StartLine: 11324, EndLine: 11330}}},
{ID: "[email protected]", Name: "pretty-format", Version: "23.6.0", Locations: []types.Location{{StartLine: 11332, EndLine: 11338}}},
{ID: "[email protected]", Name: "pretty-hrtime", Version: "1.0.3", Locations: []types.Location{{StartLine: 11340, EndLine: 11343}}},
{ID: "[email protected]", Name: "private", Version: "0.1.8", Locations: []types.Location{{StartLine: 11345, EndLine: 11348}}},
{ID: "[email protected]", Name: "process-nextick-args", Version: "1.0.7", Locations: []types.Location{{StartLine: 11350, EndLine: 11353}}},
{ID: "[email protected]", Name: "process-nextick-args", Version: "2.0.0", Locations: []types.Location{{StartLine: 11355, EndLine: 11358}}},
{ID: "[email protected]", Name: "process", Version: "0.11.10", Locations: []types.Location{{StartLine: 11360, EndLine: 11363}}},
{ID: "[email protected]", Name: "process", Version: "0.5.2", Locations: []types.Location{{StartLine: 11365, EndLine: 11368}}},
{ID: "[email protected]", Name: "progress", Version: "2.0.3", Locations: []types.Location{{StartLine: 11370, EndLine: 11373}}},
{ID: "[email protected]", Name: "promise-inflight", Version: "1.0.1", Locations: []types.Location{{StartLine: 11375, EndLine: 11378}}},
{ID: "[email protected]", Name: "promise-polyfill", Version: "6.1.0", Locations: []types.Location{{StartLine: 11380, EndLine: 11383}}},
{ID: "[email protected]", Name: "promise-retry", Version: "1.1.1", Locations: []types.Location{{StartLine: 11385, EndLine: 11391}}},
{ID: "[email protected]", Name: "promise.allsettled", Version: "1.0.1", Locations: []types.Location{{StartLine: 11393, EndLine: 11400}}},
{ID: "[email protected]", Name: "promise.prototype.finally", Version: "3.1.0", Locations: []types.Location{{StartLine: 11402, EndLine: 11409}}},
{ID: "[email protected]", Name: "promise", Version: "7.3.1", Locations: []types.Location{{StartLine: 11411, EndLine: 11416}}},
{ID: "[email protected]", Name: "prompts", Version: "0.1.14", Locations: []types.Location{{StartLine: 11418, EndLine: 11424}}},
{ID: "[email protected]", Name: "promzard", Version: "0.3.0", Locations: []types.Location{{StartLine: 11426, EndLine: 11431}}},
{ID: "[email protected]", Name: "prop-types-exact", Version: "1.2.0", Locations: []types.Location{{StartLine: 11433, EndLine: 11440}}},
{ID: "[email protected]", Name: "prop-types", Version: "15.7.2", Locations: []types.Location{{StartLine: 11442, EndLine: 11449}}},
{ID: "[email protected]", Name: "property-information", Version: "5.1.0", Locations: []types.Location{{StartLine: 11451, EndLine: 11456}}},
{ID: "[email protected]", Name: "proto-list", Version: "1.2.4", Locations: []types.Location{{StartLine: 11458, EndLine: 11461}}},
{ID: "[email protected]", Name: "protoduck", Version: "5.0.1", Locations: []types.Location{{StartLine: 11463, EndLine: 11468}}},
{ID: "[email protected]", Name: "proxy-addr", Version: "2.0.5", Locations: []types.Location{{StartLine: 11470, EndLine: 11476}}},
{ID: "[email protected]", Name: "prr", Version: "1.0.1", Locations: []types.Location{{StartLine: 11478, EndLine: 11481}}},
{ID: "[email protected]", Name: "pseudomap", Version: "1.0.2", Locations: []types.Location{{StartLine: 11483, EndLine: 11486}}},
{ID: "[email protected]", Name: "psl", Version: "1.1.31", Locations: []types.Location{{StartLine: 11488, EndLine: 11491}}},
{ID: "[email protected]", Name: "public-encrypt", Version: "4.0.3", Locations: []types.Location{{StartLine: 11493, EndLine: 11503}}},
{ID: "[email protected]", Name: "pump", Version: "2.0.1", Locations: []types.Location{{StartLine: 11505, EndLine: 11511}}},
{ID: "[email protected]", Name: "pump", Version: "3.0.0", Locations: []types.Location{{StartLine: 11513, EndLine: 11519}}},
{ID: "[email protected]", Name: "pumpify", Version: "1.5.1", Locations: []types.Location{{StartLine: 11521, EndLine: 11528}}},
{ID: "[email protected]", Name: "punycode", Version: "1.3.2", Locations: []types.Location{{StartLine: 11530, EndLine: 11533}}},
{ID: "[email protected]", Name: "punycode", Version: "1.4.1", Locations: []types.Location{{StartLine: 11535, EndLine: 11538}}},
{ID: "[email protected]", Name: "punycode", Version: "2.1.1", Locations: []types.Location{{StartLine: 11540, EndLine: 11543}}},
{ID: "[email protected]", Name: "q", Version: "1.5.1", Locations: []types.Location{{StartLine: 11545, EndLine: 11548}}},
{ID: "[email protected]", Name: "qrcode-terminal", Version: "0.12.0", Locations: []types.Location{{StartLine: 11550, EndLine: 11553}}},
{ID: "[email protected]", Name: "qs", Version: "6.5.2", Locations: []types.Location{{StartLine: 11555, EndLine: 11558}}},
{ID: "[email protected]", Name: "qs", Version: "6.7.0", Locations: []types.Location{{StartLine: 11560, EndLine: 11563}}},
{ID: "[email protected]", Name: "query-string", Version: "6.5.0", Locations: []types.Location{{StartLine: 11565, EndLine: 11572}}},
{ID: "[email protected]", Name: "querystring-es3", Version: "0.2.1", Locations: []types.Location{{StartLine: 11574, EndLine: 11577}}},
{ID: "[email protected]", Name: "querystring", Version: "0.2.0", Locations: []types.Location{{StartLine: 11579, EndLine: 11582}}},
{ID: "[email protected]", Name: "querystringify", Version: "2.1.1", Locations: []types.Location{{StartLine: 11584, EndLine: 11587}}},
{ID: "[email protected]", Name: "qw", Version: "1.0.1", Locations: []types.Location{{StartLine: 11589, EndLine: 11592}}},
{ID: "[email protected]", Name: "raf", Version: "3.4.1", Locations: []types.Location{{StartLine: 11594, EndLine: 11599}}},
{ID: "[email protected]", Name: "railroad-diagrams", Version: "1.0.0", Locations: []types.Location{{StartLine: 11601, EndLine: 11604}}},
{ID: "[email protected]", Name: "ramda", Version: "0.21.0", Locations: []types.Location{{StartLine: 11606, EndLine: 11609}}},
{ID: "[email protected]", Name: "randexp", Version: "0.4.6", Locations: []types.Location{{StartLine: 11611, EndLine: 11617}}},
{ID: "[email protected]", Name: "randomatic", Version: "3.1.1", Locations: []types.Location{{StartLine: 11619, EndLine: 11626}}},
{ID: "[email protected]", Name: "randombytes", Version: "2.1.0", Locations: []types.Location{{StartLine: 11628, EndLine: 11633}}},
{ID: "[email protected]", Name: "randomfill", Version: "1.0.4", Locations: []types.Location{{StartLine: 11635, EndLine: 11641}}},
{ID: "[email protected]", Name: "range-parser", Version: "1.2.1", Locations: []types.Location{{StartLine: 11643, EndLine: 11646}}},
{ID: "[email protected]", Name: "raven-for-redux", Version: "1.4.0", Locations: []types.Location{{StartLine: 11648, EndLine: 11651}}},
{ID: "[email protected]", Name: "raven-js", Version: "3.27.0", Locations: []types.Location{{StartLine: 11653, EndLine: 11656}}},
{ID: "[email protected]", Name: "raw-body", Version: "2.3.3", Locations: []types.Location{{StartLine: 11658, EndLine: 11666}}},
{ID: "[email protected]", Name: "raw-loader", Version: "0.5.1", Locations: []types.Location{{StartLine: 11668, EndLine: 11671}}},
{ID: "[email protected]", Name: "rc", Version: "1.2.8", Locations: []types.Location{{StartLine: 11673, EndLine: 11681}}},
{ID: "[email protected]", Name: "react-addons-create-fragment", Version: "15.6.2", Locations: []types.Location{{StartLine: 11683, EndLine: 11690}}},
{ID: "[email protected]", Name: "react-color", Version: "2.17.3", Locations: []types.Location{{StartLine: 11692, EndLine: 11702}}},
{ID: "[email protected]", Name: "react-datepicker", Version: "2.5.0", Locations: []types.Location{{StartLine: 11704, EndLine: 11713}}},
{ID: "[email protected]", Name: "react-dev-utils", Version: "6.1.1", Locations: []types.Location{{StartLine: 11715, EndLine: 11743}}},
{ID: "[email protected]", Name: "react-docgen", Version: "3.0.0", Locations: []types.Location{{StartLine: 11745, EndLine: 11756}}},
{ID: "[email protected]", Name: "react-dom", Version: "16.8.3", Locations: []types.Location{{StartLine: 11758, EndLine: 11766}}},
{ID: "[email protected]", Name: "react-dom", Version: "16.8.6", Locations: []types.Location{{StartLine: 11768, EndLine: 11776}}},
{ID: "[email protected]", Name: "react-dropzone", Version: "10.1.4", Locations: []types.Location{{StartLine: 11778, EndLine: 11785}}},
{ID: "[email protected]", Name: "react-error-overlay", Version: "5.1.6", Locations: []types.Location{{StartLine: 11787, EndLine: 11790}}},
{ID: "[email protected]", Name: "react-event-listener", Version: "0.6.6", Locations: []types.Location{{StartLine: 11792, EndLine: 11799}}},
{ID: "[email protected]", Name: "react-fast-compare", Version: "2.0.4", Locations: []types.Location{{StartLine: 11801, EndLine: 11804}}},
{ID: "[email protected]", Name: "react-fuzzy", Version: "0.5.2", Locations: []types.Location{{StartLine: 11806, EndLine: 11814}}},
{ID: "[email protected]", Name: "react-ga", Version: "2.5.7", Locations: []types.Location{{StartLine: 11816, EndLine: 11819}}},
{ID: "[email protected]", Name: "react-gateway", Version: "3.0.0", Locations: []types.Location{{StartLine: 11821, EndLine: 11827}}},
{ID: "[email protected]", Name: "react-inspector", Version: "2.3.1", Locations: []types.Location{{StartLine: 11829, EndLine: 11836}}},
{ID: "[email protected]", Name: "react-intl-universal", Version: "1.16.2", Locations: []types.Location{{StartLine: 11838, EndLine: 11853}}},
{ID: "[email protected]", Name: "react-is", Version: "16.8.6", Locations: []types.Location{{StartLine: 11855, EndLine: 11858}}},
{ID: "[email protected]", Name: "react-lifecycles-compat", Version: "3.0.4", Locations: []types.Location{{StartLine: 11860, EndLine: 11863}}},
{ID: "[email protected]", Name: "react-modal", Version: "3.8.1", Locations: []types.Location{{StartLine: 11865, EndLine: 11873}}},
{ID: "[email protected]", Name: "react-onclickoutside", Version: "6.8.0", Locations: []types.Location{{StartLine: 11875, EndLine: 11878}}},
{ID: "[email protected]", Name: "react-popper", Version: "1.3.3", Locations: []types.Location{{StartLine: 11880, EndLine: 11890}}},
{ID: "[email protected]", Name: "react-prop-types", Version: "0.4.0", Locations: []types.Location{{StartLine: 11892, EndLine: 11897}}},
{ID: "[email protected]", Name: "react-redux", Version: "6.0.1", Locations: []types.Location{{StartLine: 11899, EndLine: 11909}}},
{ID: "[email protected]", Name: "react-router-dom", Version: "4.3.1", Locations: []types.Location{{StartLine: 11911, EndLine: 11921}}},
{ID: "[email protected]", Name: "react-router", Version: "4.3.1", Locations: []types.Location{{StartLine: 11923, EndLine: 11934}}},
{ID: "[email protected]", Name: "react-split-pane", Version: "0.1.87", Locations: []types.Location{{StartLine: 11936, EndLine: 11943}}},
{ID: "[email protected]", Name: "react-style-proptype", Version: "3.2.2", Locations: []types.Location{{StartLine: 11945, EndLine: 11950}}},
{ID: "[email protected]", Name: "react-test-renderer", Version: "16.8.6", Locations: []types.Location{{StartLine: 11952, EndLine: 11960}}},
{ID: "[email protected]", Name: "react-textarea-autosize", Version: "7.1.0", Locations: []types.Location{{StartLine: 11962, EndLine: 11968}}},
{ID: "[email protected]", Name: "react-transition-group", Version: "2.9.0", Locations: []types.Location{{StartLine: 11970, EndLine: 11978}}},
{ID: "[email protected]", Name: "react-treebeard", Version: "3.1.0", Locations: []types.Location{{StartLine: 11980, EndLine: 11991}}},
{ID: "[email protected]", Name: "react-virtualized", Version: "9.21.1", Locations: []types.Location{{StartLine: 11993, EndLine: 12004}}},
{ID: "[email protected]", Name: "react", Version: "16.8.3", Locations: []types.Location{{StartLine: 12006, EndLine: 12014}}},
{ID: "[email protected]", Name: "react", Version: "16.8.6", Locations: []types.Location{{StartLine: 12016, EndLine: 12024}}},
{ID: "[email protected]", Name: "reactcss", Version: "1.2.3", Locations: []types.Location{{StartLine: 12026, EndLine: 12031}}},
{ID: "[email protected]", Name: "read-cmd-shim", Version: "1.0.1", Locations: []types.Location{{StartLine: 12033, EndLine: 12038}}},
{ID: "[email protected]", Name: "read-installed", Version: "4.0.3", Locations: []types.Location{{StartLine: 12040, EndLine: 12052}}},
{ID: "[email protected]", Name: "read-package-json", Version: "2.0.13", Locations: []types.Location{{StartLine: 12054, EndLine: 12064}}},
{ID: "[email protected]", Name: "read-package-tree", Version: "5.2.2", Locations: []types.Location{{StartLine: 12066, EndLine: 12075}}},
{ID: "[email protected]", Name: "read-pkg-up", Version: "1.0.1", Locations: []types.Location{{StartLine: 12077, EndLine: 12083}}},
{ID: "[email protected]", Name: "read-pkg-up", Version: "2.0.0", Locations: []types.Location{{StartLine: 12085, EndLine: 12091}}},
{ID: "[email protected]", Name: "read-pkg", Version: "1.1.0", Locations: []types.Location{{StartLine: 12093, EndLine: 12100}}},
{ID: "[email protected]", Name: "read-pkg", Version: "2.0.0", Locations: []types.Location{{StartLine: 12102, EndLine: 12109}}},
{ID: "[email protected]", Name: "read-pkg", Version: "3.0.0", Locations: []types.Location{{StartLine: 12111, EndLine: 12118}}},
{ID: "[email protected]", Name: "read-pkg", Version: "4.0.1", Locations: []types.Location{{StartLine: 12120, EndLine: 12127}}},
{ID: "[email protected]", Name: "read", Version: "1.0.7", Locations: []types.Location{{StartLine: 12129, EndLine: 12134}}},
{ID: "[email protected]", Name: "readable-stream", Version: "2.3.6", Locations: []types.Location{{StartLine: 12136, EndLine: 12147}}},
{ID: "[email protected]", Name: "readable-stream", Version: "3.3.0", Locations: []types.Location{{StartLine: 12149, EndLine: 12156}}},
{ID: "[email protected]", Name: "readable-stream", Version: "1.1.14", Locations: []types.Location{{StartLine: 12158, EndLine: 12166}}},
{ID: "[email protected]", Name: "readable-stream", Version: "2.1.5", Locations: []types.Location{{StartLine: 12168, EndLine: 12179}}},
{ID: "[email protected]", Name: "readdir-scoped-modules", Version: "1.0.2", Locations: []types.Location{{StartLine: 12181, EndLine: 12189}}},
{ID: "[email protected]", Name: "readdirp", Version: "2.2.1", Locations: []types.Location{{StartLine: 12191, EndLine: 12198}}},
{ID: "[email protected]", Name: "readline2", Version: "1.0.1", Locations: []types.Location{{StartLine: 12200, EndLine: 12207}}},
{ID: "[email protected]", Name: "realpath-native", Version: "1.1.0", Locations: []types.Location{{StartLine: 12209, EndLine: 12214}}},
{ID: "[email protected]", Name: "recast", Version: "0.14.7", Locations: []types.Location{{StartLine: 12216, EndLine: 12224}}},
{ID: "[email protected]", Name: "recast", Version: "0.15.5", Locations: []types.Location{{StartLine: 12226, EndLine: 12234}}},
{ID: "[email protected]", Name: "recast", Version: "0.16.2", Locations: []types.Location{{StartLine: 12236, EndLine: 12244}}},
{ID: "[email protected]", Name: "rechoir", Version: "0.6.2", Locations: []types.Location{{StartLine: 12246, EndLine: 12251}}},
{ID: "[email protected]", Name: "recompose", Version: "0.30.0", Locations: []types.Location{{StartLine: 12253, EndLine: 12263}}},
{ID: "[email protected]", Name: "recursive-readdir", Version: "2.2.2", Locations: []types.Location{{StartLine: 12265, EndLine: 12270}}},
{ID: "[email protected]", Name: "redux-thunk", Version: "2.3.0", Locations: []types.Location{{StartLine: 12272, EndLine: 12275}}},
{ID: "[email protected]", Name: "redux", Version: "4.0.1", Locations: []types.Location{{StartLine: 12277, EndLine: 12283}}},
{ID: "[email protected]", Name: "reflect.ownkeys", Version: "0.2.0", Locations: []types.Location{{StartLine: 12285, EndLine: 12288}}},
{ID: "[email protected]", Name: "regenerate-unicode-properties", Version: "8.1.0", Locations: []types.Location{{StartLine: 12290, EndLine: 12295}}},
{ID: "[email protected]", Name: "regenerate", Version: "1.4.0", Locations: []types.Location{{StartLine: 12297, EndLine: 12300}}},
{ID: "[email protected]", Name: "regenerator-runtime", Version: "0.10.5", Locations: []types.Location{{StartLine: 12302, EndLine: 12305}}},
{ID: "[email protected]", Name: "regenerator-runtime", Version: "0.11.1", Locations: []types.Location{{StartLine: 12307, EndLine: 12310}}},
{ID: "[email protected]", Name: "regenerator-runtime", Version: "0.12.1", Locations: []types.Location{{StartLine: 12312, EndLine: 12315}}},
{ID: "[email protected]", Name: "regenerator-runtime", Version: "0.13.2", Locations: []types.Location{{StartLine: 12317, EndLine: 12320}}},
{ID: "[email protected]", Name: "regenerator-transform", Version: "0.10.1", Locations: []types.Location{{StartLine: 12322, EndLine: 12329}}},
{ID: "[email protected]", Name: "regenerator-transform", Version: "0.13.4", Locations: []types.Location{{StartLine: 12331, EndLine: 12336}}},
{ID: "[email protected]", Name: "regex-cache", Version: "0.4.4", Locations: []types.Location{{StartLine: 12338, EndLine: 12343}}},
{ID: "[email protected]", Name: "regex-not", Version: "1.0.2", Locations: []types.Location{{StartLine: 12345, EndLine: 12351}}},
{ID: "[email protected]", Name: "regexp-tree", Version: "0.1.6", Locations: []types.Location{{StartLine: 12353, EndLine: 12356}}},
{ID: "[email protected]", Name: "regexp.prototype.flags", Version: "1.2.0", Locations: []types.Location{{StartLine: 12358, EndLine: 12363}}},
{ID: "[email protected]", Name: "regexpp", Version: "2.0.1", Locations: []types.Location{{StartLine: 12365, EndLine: 12368}}},
{ID: "[email protected]", Name: "regexpu-core", Version: "1.0.0", Locations: []types.Location{{StartLine: 12370, EndLine: 12377}}},
{ID: "[email protected]", Name: "regexpu-core", Version: "2.0.0", Locations: []types.Location{{StartLine: 12379, EndLine: 12386}}},
{ID: "[email protected]", Name: "regexpu-core", Version: "4.5.4", Locations: []types.Location{{StartLine: 12388, EndLine: 12398}}},
{ID: "[email protected]", Name: "registry-auth-token", Version: "3.4.0", Locations: []types.Location{{StartLine: 12400, EndLine: 12406}}},
{ID: "[email protected]", Name: "registry-url", Version: "3.1.0", Locations: []types.Location{{StartLine: 12408, EndLine: 12413}}},
{ID: "[email protected]", Name: "regjsgen", Version: "0.2.0", Locations: []types.Location{{StartLine: 12415, EndLine: 12418}}},
{ID: "[email protected]", Name: "regjsgen", Version: "0.5.0", Locations: []types.Location{{StartLine: 12420, EndLine: 12423}}},
{ID: "[email protected]", Name: "regjsparser", Version: "0.1.5", Locations: []types.Location{{StartLine: 12425, EndLine: 12430}}},
{ID: "[email protected]", Name: "regjsparser", Version: "0.6.0", Locations: []types.Location{{StartLine: 12432, EndLine: 12437}}},
{ID: "[email protected]", Name: "rehype-parse", Version: "6.0.0", Locations: []types.Location{{StartLine: 12439, EndLine: 12446}}},
{ID: "[email protected]", Name: "relateurl", Version: "0.2.7", Locations: []types.Location{{StartLine: 12448, EndLine: 12451}}},
{ID: "[email protected]", Name: "remove-trailing-separator", Version: "1.1.0", Locations: []types.Location{{StartLine: 12453, EndLine: 12456}}},
{ID: "[email protected]", Name: "render-fragment", Version: "0.1.1", Locations: []types.Location{{StartLine: 12458, EndLine: 12461}}},
{ID: "[email protected]", Name: "renderkid", Version: "2.0.3", Locations: []types.Location{{StartLine: 12463, EndLine: 12472}}},
{ID: "[email protected]", Name: "repeat-element", Version: "1.1.3", Locations: []types.Location{{StartLine: 12474, EndLine: 12477}}},
{ID: "[email protected]", Name: "repeat-string", Version: "1.6.1", Locations: []types.Location{{StartLine: 12479, EndLine: 12482}}},
{ID: "[email protected]", Name: "repeating", Version: "2.0.1", Locations: []types.Location{{StartLine: 12484, EndLine: 12489}}},
{ID: "[email protected]", Name: "replace-ext", Version: "1.0.0", Locations: []types.Location{{StartLine: 12491, EndLine: 12494}}},
{ID: "[email protected]", Name: "request-promise-core", Version: "1.1.2", Locations: []types.Location{{StartLine: 12496, EndLine: 12501}}},
{ID: "[email protected]", Name: "request-promise-native", Version: "1.0.7", Locations: []types.Location{{StartLine: 12503, EndLine: 12510}}},
{ID: "[email protected]", Name: "request", Version: "2.88.0", Locations: []types.Location{{StartLine: 12512, EndLine: 12536}}},
{ID: "[email protected]", Name: "require-directory", Version: "2.1.1", Locations: []types.Location{{StartLine: 12538, EndLine: 12541}}},
{ID: "[email protected]", Name: "require-from-string", Version: "2.0.2", Locations: []types.Location{{StartLine: 12543, EndLine: 12546}}},
{ID: "[email protected]", Name: "require-main-filename", Version: "1.0.1", Locations: []types.Location{{StartLine: 12548, EndLine: 12551}}},
{ID: "[email protected]", Name: "requires-port", Version: "1.0.0", Locations: []types.Location{{StartLine: 12553, EndLine: 12556}}},
{ID: "[email protected]", Name: "resolve-cwd", Version: "2.0.0", Locations: []types.Location{{StartLine: 12558, EndLine: 12563}}},
{ID: "[email protected]", Name: "resolve-dir", Version: "1.0.1", Locations: []types.Location{{StartLine: 12565, EndLine: 12571}}},
{ID: "[email protected]", Name: "resolve-from", Version: "3.0.0", Locations: []types.Location{{StartLine: 12573, EndLine: 12576}}},
{ID: "[email protected]", Name: "resolve-from", Version: "4.0.0", Locations: []types.Location{{StartLine: 12578, EndLine: 12581}}},
{ID: "[email protected]", Name: "resolve-pathname", Version: "2.2.0", Locations: []types.Location{{StartLine: 12583, EndLine: 12586}}},
{ID: "[email protected]", Name: "resolve-url", Version: "0.2.1", Locations: []types.Location{{StartLine: 12588, EndLine: 12591}}},
{ID: "[email protected]", Name: "resolve", Version: "1.1.7", Locations: []types.Location{{StartLine: 12593, EndLine: 12596}}},
{ID: "[email protected]", Name: "resolve", Version: "1.10.1", Locations: []types.Location{{StartLine: 12598, EndLine: 12603}}},
{ID: "[email protected]", Name: "restore-cursor", Version: "1.0.1", Locations: []types.Location{{StartLine: 12605, EndLine: 12611}}},
{ID: "[email protected]", Name: "restore-cursor", Version: "2.0.0", Locations: []types.Location{{StartLine: 12613, EndLine: 12619}}},
{ID: "[email protected]", Name: "ret", Version: "0.1.15", Locations: []types.Location{{StartLine: 12621, EndLine: 12624}}},
{ID: "[email protected]", Name: "retry", Version: "0.10.1", Locations: []types.Location{{StartLine: 12626, EndLine: 12629}}},
{ID: "[email protected]", Name: "retry", Version: "0.12.0", Locations: []types.Location{{StartLine: 12631, EndLine: 12634}}},
{ID: "[email protected]", Name: "rimraf", Version: "2.6.3", Locations: []types.Location{{StartLine: 12636, EndLine: 12641}}},
{ID: "[email protected]", Name: "rimraf", Version: "2.2.8", Locations: []types.Location{{StartLine: 12643, EndLine: 12646}}},
{ID: "[email protected]", Name: "ripemd160", Version: "2.0.2", Locations: []types.Location{{StartLine: 12648, EndLine: 12654}}},
{ID: "[email protected]", Name: "rst-selector-parser", Version: "2.2.3", Locations: []types.Location{{StartLine: 12656, EndLine: 12662}}},
{ID: "[email protected]", Name: "rsvp", Version: "3.6.2", Locations: []types.Location{{StartLine: 12664, EndLine: 12667}}},
{ID: "[email protected]", Name: "run-async", Version: "0.1.0", Locations: []types.Location{{StartLine: 12669, EndLine: 12674}}},
{ID: "[email protected]", Name: "run-async", Version: "2.3.0", Locations: []types.Location{{StartLine: 12676, EndLine: 12681}}},
{ID: "[email protected]", Name: "run-node", Version: "1.0.0", Locations: []types.Location{{StartLine: 12683, EndLine: 12686}}},
{ID: "[email protected]", Name: "run-queue", Version: "1.0.3", Locations: []types.Location{{StartLine: 12688, EndLine: 12693}}},
{ID: "[email protected]", Name: "rx-lite", Version: "3.1.2", Locations: []types.Location{{StartLine: 12695, EndLine: 12698}}},
{ID: "[email protected]", Name: "rxjs", Version: "6.5.2", Locations: []types.Location{{StartLine: 12700, EndLine: 12705}}},
{ID: "[email protected]", Name: "safe-buffer", Version: "5.1.1", Locations: []types.Location{{StartLine: 12707, EndLine: 12710}}},
{ID: "[email protected]", Name: "safe-buffer", Version: "5.1.2", Locations: []types.Location{{StartLine: 12712, EndLine: 12715}}},
{ID: "[email protected]", Name: "safe-regex", Version: "1.1.0", Locations: []types.Location{{StartLine: 12717, EndLine: 12722}}},
{ID: "[email protected]", Name: "safer-buffer", Version: "2.1.2", Locations: []types.Location{{StartLine: 12724, EndLine: 12727}}},
{ID: "[email protected]", Name: "sane", Version: "2.5.2", Locations: []types.Location{{StartLine: 12729, EndLine: 12743}}},
{ID: "[email protected]", Name: "sax", Version: "1.2.4", Locations: []types.Location{{StartLine: 12745, EndLine: 12748}}},
{ID: "[email protected]", Name: "scheduler", Version: "0.13.6", Locations: []types.Location{{StartLine: 12750, EndLine: 12756}}},
{ID: "[email protected]", Name: "schema-utils", Version: "0.4.7", Locations: []types.Location{{StartLine: 12758, EndLine: 12764}}},
{ID: "[email protected]", Name: "schema-utils", Version: "1.0.0", Locations: []types.Location{{StartLine: 12766, EndLine: 12773}}},
{ID: "[email protected]", Name: "select-hose", Version: "2.0.0", Locations: []types.Location{{StartLine: 12775, EndLine: 12778}}},
{ID: "[email protected]", Name: "selfsigned", Version: "1.10.4", Locations: []types.Location{{StartLine: 12780, EndLine: 12785}}},
{ID: "[email protected]", Name: "semver-compare", Version: "1.0.0", Locations: []types.Location{{StartLine: 12787, EndLine: 12790}}},
{ID: "[email protected]", Name: "semver-diff", Version: "2.1.0", Locations: []types.Location{{StartLine: 12792, EndLine: 12797}}},
{ID: "[email protected]", Name: "semver", Version: "5.7.0", Locations: []types.Location{{StartLine: 12799, EndLine: 12802}}},
{ID: "[email protected]", Name: "semver", Version: "6.0.0", Locations: []types.Location{{StartLine: 12804, EndLine: 12807}}},
{ID: "[email protected]", Name: "semver", Version: "5.3.0", Locations: []types.Location{{StartLine: 12809, EndLine: 12812}}},
{ID: "[email protected]", Name: "send", Version: "0.16.2", Locations: []types.Location{{StartLine: 12814, EndLine: 12831}}},
{ID: "[email protected]", Name: "serialize-javascript", Version: "1.7.0", Locations: []types.Location{{StartLine: 12833, EndLine: 12836}}},
{ID: "[email protected]", Name: "serve-favicon", Version: "2.5.0", Locations: []types.Location{{StartLine: 12838, EndLine: 12847}}},
{ID: "[email protected]", Name: "serve-index", Version: "1.9.1", Locations: []types.Location{{StartLine: 12849, EndLine: 12860}}},
{ID: "[email protected]", Name: "serve-static", Version: "1.13.2", Locations: []types.Location{{StartLine: 12862, EndLine: 12870}}},
{ID: "[email protected]", Name: "set-blocking", Version: "2.0.0", Locations: []types.Location{{StartLine: 12872, EndLine: 12875}}},
{ID: "[email protected]", Name: "set-value", Version: "0.4.3", Locations: []types.Location{{StartLine: 12877, EndLine: 12885}}},
{ID: "[email protected]", Name: "set-value", Version: "2.0.0", Locations: []types.Location{{StartLine: 12887, EndLine: 12895}}},
{ID: "[email protected]", Name: "setimmediate", Version: "1.0.5", Locations: []types.Location{{StartLine: 12897, EndLine: 12900}}},
{ID: "[email protected]", Name: "setprototypeof", Version: "1.1.0", Locations: []types.Location{{StartLine: 12902, EndLine: 12905}}},
{ID: "[email protected]", Name: "sha.js", Version: "2.4.11", Locations: []types.Location{{StartLine: 12907, EndLine: 12913}}},
{ID: "[email protected]", Name: "sha", Version: "2.0.1", Locations: []types.Location{{StartLine: 12915, EndLine: 12921}}},
{ID: "[email protected]", Name: "shallow-clone", Version: "0.1.2", Locations: []types.Location{{StartLine: 12923, EndLine: 12931}}},
{ID: "[email protected]", Name: "shallowequal", Version: "1.1.0", Locations: []types.Location{{StartLine: 12933, EndLine: 12936}}},
{ID: "[email protected]", Name: "shebang-command", Version: "1.2.0", Locations: []types.Location{{StartLine: 12938, EndLine: 12943}}},
{ID: "[email protected]", Name: "shebang-regex", Version: "1.0.0", Locations: []types.Location{{StartLine: 12945, EndLine: 12948}}},
{ID: "[email protected]", Name: "shell-quote", Version: "1.6.1", Locations: []types.Location{{StartLine: 12950, EndLine: 12958}}},
{ID: "[email protected]", Name: "shelljs", Version: "0.8.3", Locations: []types.Location{{StartLine: 12960, EndLine: 12967}}},
{ID: "[email protected]", Name: "shellwords", Version: "0.1.1", Locations: []types.Location{{StartLine: 12969, EndLine: 12972}}},
{ID: "[email protected]", Name: "signal-exit", Version: "3.0.2", Locations: []types.Location{{StartLine: 12974, EndLine: 12977}}},
{ID: "[email protected]", Name: "sisteransi", Version: "0.1.1", Locations: []types.Location{{StartLine: 12979, EndLine: 12982}}},
{ID: "[email protected]", Name: "slash", Version: "1.0.0", Locations: []types.Location{{StartLine: 12984, EndLine: 12987}}},
{ID: "[email protected]", Name: "slash", Version: "2.0.0", Locations: []types.Location{{StartLine: 12989, EndLine: 12992}}},
{ID: "[email protected]", Name: "slice-ansi", Version: "0.0.4", Locations: []types.Location{{StartLine: 12994, EndLine: 12997}}},
{ID: "[email protected]", Name: "slice-ansi", Version: "1.0.0", Locations: []types.Location{{StartLine: 12999, EndLine: 13004}}},
{ID: "[email protected]", Name: "slice-ansi", Version: "2.1.0", Locations: []types.Location{{StartLine: 13006, EndLine: 13013}}},
{ID: "[email protected]", Name: "slide", Version: "1.1.6", Locations: []types.Location{{StartLine: 13015, EndLine: 13018}}},
{ID: "[email protected]", Name: "smart-buffer", Version: "4.0.2", Locations: []types.Location{{StartLine: 13020, EndLine: 13023}}},
{ID: "[email protected]", Name: "snapdragon-node", Version: "2.1.1", Locations: []types.Location{{StartLine: 13025, EndLine: 13032}}},
{ID: "[email protected]", Name: "snapdragon-util", Version: "3.0.1", Locations: []types.Location{{StartLine: 13034, EndLine: 13039}}},
{ID: "[email protected]", Name: "snapdragon", Version: "0.8.2", Locations: []types.Location{{StartLine: 13041, EndLine: 13053}}},
{ID: "[email protected]", Name: "socket.io-adapter", Version: "1.1.1", Locations: []types.Location{{StartLine: 13055, EndLine: 13058}}},
{ID: "[email protected]", Name: "socket.io-client", Version: "2.2.0", Locations: []types.Location{{StartLine: 13060, EndLine: 13078}}},
{ID: "[email protected]", Name: "socket.io-parser", Version: "3.3.0", Locations: []types.Location{{StartLine: 13080, EndLine: 13087}}},
{ID: "[email protected]", Name: "socket.io", Version: "2.2.0", Locations: []types.Location{{StartLine: 13089, EndLine: 13099}}},
{ID: "[email protected]", Name: "sockjs-client", Version: "1.1.5", Locations: []types.Location{{StartLine: 13101, EndLine: 13111}}},
{ID: "[email protected]", Name: "sockjs-client", Version: "1.3.0", Locations: []types.Location{{StartLine: 13113, EndLine: 13123}}},
{ID: "[email protected]", Name: "sockjs", Version: "0.3.19", Locations: []types.Location{{StartLine: 13125, EndLine: 13131}}},
{ID: "[email protected]", Name: "socks-proxy-agent", Version: "4.0.2", Locations: []types.Location{{StartLine: 13133, EndLine: 13139}}},
{ID: "[email protected]", Name: "socks", Version: "2.3.2", Locations: []types.Location{{StartLine: 13141, EndLine: 13147}}},
{ID: "[email protected]", Name: "sort-keys", Version: "2.0.0", Locations: []types.Location{{StartLine: 13149, EndLine: 13154}}},
{ID: "[email protected]", Name: "sorted-object", Version: "2.0.1", Locations: []types.Location{{StartLine: 13156, EndLine: 13159}}},
{ID: "[email protected]", Name: "sorted-union-stream", Version: "2.1.3", Locations: []types.Location{{StartLine: 13161, EndLine: 13167}}},
{ID: "[email protected]", Name: "source-list-map", Version: "2.0.1", Locations: []types.Location{{StartLine: 13169, EndLine: 13172}}},
{ID: "[email protected]", Name: "source-map-resolve", Version: "0.5.2", Locations: []types.Location{{StartLine: 13174, EndLine: 13183}}},
{ID: "[email protected]", Name: "source-map-support", Version: "0.4.18", Locations: []types.Location{{StartLine: 13185, EndLine: 13190}}},
{ID: "[email protected]", Name: "source-map-support", Version: "0.5.12", Locations: []types.Location{{StartLine: 13192, EndLine: 13198}}},
{ID: "[email protected]", Name: "source-map-url", Version: "0.4.0", Locations: []types.Location{{StartLine: 13200, EndLine: 13203}}},
{ID: "[email protected]", Name: "source-map", Version: "0.5.7", Locations: []types.Location{{StartLine: 13205, EndLine: 13208}}},
{ID: "[email protected]", Name: "source-map", Version: "0.6.1", Locations: []types.Location{{StartLine: 13210, EndLine: 13213}}},
{ID: "[email protected]", Name: "space-separated-tokens", Version: "1.1.4", Locations: []types.Location{{StartLine: 13215, EndLine: 13218}}},
{ID: "[email protected]", Name: "spawn-promise", Version: "0.1.8", Locations: []types.Location{{StartLine: 13220, EndLine: 13225}}},
{ID: "[email protected]", Name: "spdx-correct", Version: "3.1.0", Locations: []types.Location{{StartLine: 13227, EndLine: 13233}}},
{ID: "[email protected]", Name: "spdx-exceptions", Version: "2.2.0", Locations: []types.Location{{StartLine: 13235, EndLine: 13238}}},
{ID: "[email protected]", Name: "spdx-expression-parse", Version: "3.0.0", Locations: []types.Location{{StartLine: 13240, EndLine: 13246}}},
{ID: "[email protected]", Name: "spdx-license-ids", Version: "3.0.4", Locations: []types.Location{{StartLine: 13248, EndLine: 13251}}},
{ID: "[email protected]", Name: "spdy-transport", Version: "3.0.0", Locations: []types.Location{{StartLine: 13253, EndLine: 13263}}},
{ID: "[email protected]", Name: "spdy", Version: "4.0.0", Locations: []types.Location{{StartLine: 13265, EndLine: 13274}}},
{ID: "[email protected]", Name: "split-on-first", Version: "1.1.0", Locations: []types.Location{{StartLine: 13276, EndLine: 13279}}},
{ID: "[email protected]", Name: "split-string", Version: "3.1.0", Locations: []types.Location{{StartLine: 13281, EndLine: 13286}}},
{ID: "[email protected]", Name: "sprintf-js", Version: "1.0.3", Locations: []types.Location{{StartLine: 13288, EndLine: 13291}}},
{ID: "[email protected]", Name: "sshpk", Version: "1.16.1", Locations: []types.Location{{StartLine: 13293, EndLine: 13306}}},
{ID: "[email protected]", Name: "ssri", Version: "5.3.0", Locations: []types.Location{{StartLine: 13308, EndLine: 13313}}},
{ID: "[email protected]", Name: "ssri", Version: "6.0.1", Locations: []types.Location{{StartLine: 13315, EndLine: 13320}}},
{ID: "[email protected]", Name: "stable", Version: "0.1.8", Locations: []types.Location{{StartLine: 13322, EndLine: 13325}}},
{ID: "[email protected]", Name: "stack-utils", Version: "1.0.2", Locations: []types.Location{{StartLine: 13327, EndLine: 13330}}},
{ID: "[email protected]", Name: "staged-git-files", Version: "1.1.1", Locations: []types.Location{{StartLine: 13332, EndLine: 13335}}},
{ID: "[email protected]", Name: "static-extend", Version: "0.1.2", Locations: []types.Location{{StartLine: 13337, EndLine: 13343}}},
{ID: "[email protected]", Name: "statuses", Version: "1.5.0", Locations: []types.Location{{StartLine: 13345, EndLine: 13348}}},
{ID: "[email protected]", Name: "statuses", Version: "1.4.0", Locations: []types.Location{{StartLine: 13350, EndLine: 13353}}},
{ID: "[email protected]", Name: "stealthy-require", Version: "1.1.1", Locations: []types.Location{{StartLine: 13355, EndLine: 13358}}},
{ID: "[email protected]", Name: "stream-browserify", Version: "2.0.2", Locations: []types.Location{{StartLine: 13360, EndLine: 13366}}},
{ID: "[email protected]", Name: "stream-each", Version: "1.2.3", Locations: []types.Location{{StartLine: 13368, EndLine: 13374}}},
{ID: "[email protected]", Name: "stream-http", Version: "2.8.3", Locations: []types.Location{{StartLine: 13376, EndLine: 13385}}},
{ID: "[email protected]", Name: "stream-iterate", Version: "1.2.0", Locations: []types.Location{{StartLine: 13387, EndLine: 13393}}},
{ID: "[email protected]", Name: "stream-shift", Version: "1.0.0", Locations: []types.Location{{StartLine: 13395, EndLine: 13398}}},
{ID: "[email protected]", Name: "strict-uri-encode", Version: "2.0.0", Locations: []types.Location{{StartLine: 13400, EndLine: 13403}}},
{ID: "[email protected]", Name: "string-argv", Version: "0.0.2", Locations: []types.Location{{StartLine: 13405, EndLine: 13408}}},
{ID: "[email protected]", Name: "string-length", Version: "2.0.0", Locations: []types.Location{{StartLine: 13410, EndLine: 13416}}},
{ID: "[email protected]", Name: "string-width", Version: "1.0.2", Locations: []types.Location{{StartLine: 13418, EndLine: 13425}}},
{ID: "[email protected]", Name: "string-width", Version: "2.1.1", Locations: []types.Location{{StartLine: 13427, EndLine: 13433}}},
{ID: "[email protected]", Name: "string-width", Version: "3.1.0", Locations: []types.Location{{StartLine: 13435, EndLine: 13442}}},
{ID: "[email protected]", Name: "string.prototype.matchall", Version: "3.0.1", Locations: []types.Location{{StartLine: 13444, EndLine: 13453}}},
{ID: "[email protected]", Name: "string.prototype.padend", Version: "3.0.0", Locations: []types.Location{{StartLine: 13455, EndLine: 13462}}},
{ID: "[email protected]", Name: "string.prototype.padstart", Version: "3.0.0", Locations: []types.Location{{StartLine: 13464, EndLine: 13471}}},
{ID: "[email protected]", Name: "string.prototype.trim", Version: "1.1.2", Locations: []types.Location{{StartLine: 13473, EndLine: 13480}}},
{ID: "[email protected]", Name: "string_decoder", Version: "1.2.0", Locations: []types.Location{{StartLine: 13482, EndLine: 13487}}},
{ID: "[email protected]", Name: "string_decoder", Version: "0.10.31", Locations: []types.Location{{StartLine: 13489, EndLine: 13492}}},
{ID: "[email protected]", Name: "string_decoder", Version: "1.1.1", Locations: []types.Location{{StartLine: 13494, EndLine: 13499}}},
{ID: "[email protected]", Name: "stringify-object", Version: "3.3.0", Locations: []types.Location{{StartLine: 13501, EndLine: 13508}}},
{ID: "[email protected]", Name: "stringify-package", Version: "1.0.0", Locations: []types.Location{{StartLine: 13510, EndLine: 13513}}},
{ID: "[email protected]", Name: "strip-ansi", Version: "4.0.0", Locations: []types.Location{{StartLine: 13515, EndLine: 13520}}},
{ID: "[email protected]", Name: "strip-ansi", Version: "3.0.1", Locations: []types.Location{{StartLine: 13522, EndLine: 13527}}},
{ID: "[email protected]", Name: "strip-ansi", Version: "5.2.0", Locations: []types.Location{{StartLine: 13529, EndLine: 13534}}},
{ID: "[email protected]", Name: "strip-ansi", Version: "0.1.1", Locations: []types.Location{{StartLine: 13536, EndLine: 13539}}},
{ID: "[email protected]", Name: "strip-bom", Version: "3.0.0", Locations: []types.Location{{StartLine: 13541, EndLine: 13544}}},
{ID: "[email protected]", Name: "strip-bom", Version: "2.0.0", Locations: []types.Location{{StartLine: 13546, EndLine: 13551}}},
{ID: "[email protected]", Name: "strip-eof", Version: "1.0.0", Locations: []types.Location{{StartLine: 13553, EndLine: 13556}}},
{ID: "[email protected]", Name: "strip-json-comments", Version: "2.0.1", Locations: []types.Location{{StartLine: 13558, EndLine: 13561}}},
{ID: "[email protected]", Name: "style-loader", Version: "0.23.1", Locations: []types.Location{{StartLine: 13563, EndLine: 13569}}},
{ID: "[email protected]", Name: "styled-components", Version: "4.1.3", Locations: []types.Location{{StartLine: 13571, EndLine: 13586}}},
{ID: "[email protected]", Name: "stylis-rule-sheet", Version: "0.0.10", Locations: []types.Location{{StartLine: 13588, EndLine: 13591}}},
{ID: "[email protected]", Name: "stylis", Version: "3.5.4", Locations: []types.Location{{StartLine: 13593, EndLine: 13596}}},
{ID: "[email protected]", Name: "supports-color", Version: "2.0.0", Locations: []types.Location{{StartLine: 13598, EndLine: 13601}}},
{ID: "[email protected]", Name: "supports-color", Version: "3.2.3", Locations: []types.Location{{StartLine: 13603, EndLine: 13608}}},
{ID: "[email protected]", Name: "supports-color", Version: "5.5.0", Locations: []types.Location{{StartLine: 13610, EndLine: 13615}}},
{ID: "[email protected]", Name: "supports-color", Version: "6.1.0", Locations: []types.Location{{StartLine: 13617, EndLine: 13622}}},
{ID: "[email protected]", Name: "svg-url-loader", Version: "2.3.2", Locations: []types.Location{{StartLine: 13624, EndLine: 13630}}},
{ID: "[email protected]", Name: "svgo", Version: "1.2.2", Locations: []types.Location{{StartLine: 13632, EndLine: 13650}}},
{ID: "[email protected]", Name: "symbol-observable", Version: "1.2.0", Locations: []types.Location{{StartLine: 13652, EndLine: 13655}}},
{ID: "[email protected]", Name: "symbol-tree", Version: "3.2.2", Locations: []types.Location{{StartLine: 13657, EndLine: 13660}}},
{ID: "[email protected]", Name: "symbol.prototype.description", Version: "1.0.0", Locations: []types.Location{{StartLine: 13662, EndLine: 13667}}},
{ID: "[email protected]", Name: "table", Version: "4.0.3", Locations: []types.Location{{StartLine: 13669, EndLine: 13679}}},
{ID: "[email protected]", Name: "table", Version: "5.3.3", Locations: []types.Location{{StartLine: 13681, EndLine: 13689}}},
{ID: "[email protected]", Name: "tapable", Version: "1.1.3", Locations: []types.Location{{StartLine: 13691, EndLine: 13694}}},
{ID: "[email protected]", Name: "tar", Version: "2.2.2", Locations: []types.Location{{StartLine: 13696, EndLine: 13703}}},
{ID: "[email protected]", Name: "tar", Version: "4.4.8", Locations: []types.Location{{StartLine: 13705, EndLine: 13716}}},
{ID: "[email protected]", Name: "temp", Version: "0.8.3", Locations: []types.Location{{StartLine: 13718, EndLine: 13724}}},
{ID: "[email protected]", Name: "term-size", Version: "1.2.0", Locations: []types.Location{{StartLine: 13726, EndLine: 13731}}},
{ID: "[email protected]", Name: "terser-webpack-plugin", Version: "1.2.4", Locations: []types.Location{{StartLine: 13733, EndLine: 13746}}},
{ID: "[email protected]", Name: "terser", Version: "3.17.0", Locations: []types.Location{{StartLine: 13748, EndLine: 13755}}},
{ID: "[email protected]", Name: "test-exclude", Version: "4.2.3", Locations: []types.Location{{StartLine: 13757, EndLine: 13766}}},
{ID: "[email protected]", Name: "text-table", Version: "0.2.0", Locations: []types.Location{{StartLine: 13768, EndLine: 13771}}},
{ID: "[email protected]", Name: "throat", Version: "4.1.0", Locations: []types.Location{{StartLine: 13773, EndLine: 13776}}},
{ID: "[email protected]", Name: "through2", Version: "2.0.5", Locations: []types.Location{{StartLine: 13778, EndLine: 13784}}},
{ID: "[email protected]", Name: "through", Version: "2.3.8", Locations: []types.Location{{StartLine: 13786, EndLine: 13789}}},
{ID: "[email protected]", Name: "thunky", Version: "1.0.3", Locations: []types.Location{{StartLine: 13791, EndLine: 13794}}},
{ID: "[email protected]", Name: "timed-out", Version: "4.0.1", Locations: []types.Location{{StartLine: 13796, EndLine: 13799}}},
{ID: "[email protected]", Name: "timers-browserify", Version: "2.0.10", Locations: []types.Location{{StartLine: 13801, EndLine: 13806}}},
{ID: "[email protected]", Name: "tiny-invariant", Version: "1.0.4", Locations: []types.Location{{StartLine: 13808, EndLine: 13811}}},
{ID: "[email protected]", Name: "tiny-relative-date", Version: "1.3.0", Locations: []types.Location{{StartLine: 13813, EndLine: 13816}}},
{ID: "[email protected]", Name: "tiny-warning", Version: "1.0.2", Locations: []types.Location{{StartLine: 13818, EndLine: 13821}}},
{ID: "[email protected]", Name: "tinycolor2", Version: "1.4.1", Locations: []types.Location{{StartLine: 13823, EndLine: 13826}}},
{ID: "[email protected]", Name: "tmp", Version: "0.0.33", Locations: []types.Location{{StartLine: 13828, EndLine: 13833}}},
{ID: "[email protected]", Name: "tmpl", Version: "1.0.4", Locations: []types.Location{{StartLine: 13835, EndLine: 13838}}},
{ID: "[email protected]", Name: "to-array", Version: "0.1.4", Locations: []types.Location{{StartLine: 13840, EndLine: 13843}}},
{ID: "[email protected]", Name: "to-arraybuffer", Version: "1.0.1", Locations: []types.Location{{StartLine: 13845, EndLine: 13848}}},
{ID: "[email protected]", Name: "to-fast-properties", Version: "1.0.3", Locations: []types.Location{{StartLine: 13850, EndLine: 13853}}},
{ID: "[email protected]", Name: "to-fast-properties", Version: "2.0.0", Locations: []types.Location{{StartLine: 13855, EndLine: 13858}}},
{ID: "[email protected]", Name: "to-object-path", Version: "0.3.0", Locations: []types.Location{{StartLine: 13860, EndLine: 13865}}},
{ID: "[email protected]", Name: "to-regex-range", Version: "2.1.1", Locations: []types.Location{{StartLine: 13867, EndLine: 13873}}},
{ID: "[email protected]", Name: "to-regex", Version: "3.0.2", Locations: []types.Location{{StartLine: 13875, EndLine: 13883}}},
{ID: "[email protected]", Name: "toggle-selection", Version: "1.0.6", Locations: []types.Location{{StartLine: 13885, EndLine: 13888}}},
{ID: "[email protected]", Name: "toposort", Version: "1.0.7", Locations: []types.Location{{StartLine: 13890, EndLine: 13893}}},
{ID: "[email protected]", Name: "tough-cookie", Version: "2.5.0", Locations: []types.Location{{StartLine: 13895, EndLine: 13901}}},
{ID: "[email protected]", Name: "tough-cookie", Version: "2.4.3", Locations: []types.Location{{StartLine: 13903, EndLine: 13909}}},
{ID: "[email protected]", Name: "tr46", Version: "1.0.1", Locations: []types.Location{{StartLine: 13911, EndLine: 13916}}},
{ID: "[email protected]", Name: "traverse", Version: "0.3.9", Locations: []types.Location{{StartLine: 13918, EndLine: 13921}}},
{ID: "[email protected]", Name: "trim-right", Version: "1.0.1", Locations: []types.Location{{StartLine: 13923, EndLine: 13926}}},
{ID: "[email protected]", Name: "trough", Version: "1.0.4", Locations: []types.Location{{StartLine: 13928, EndLine: 13931}}},
{ID: "[email protected]", Name: "tryer", Version: "1.0.1", Locations: []types.Location{{StartLine: 13933, EndLine: 13936}}},
{ID: "[email protected]", Name: "tslib", Version: "1.9.3", Locations: []types.Location{{StartLine: 13938, EndLine: 13941}}},
{ID: "[email protected]", Name: "tty-browserify", Version: "0.0.0", Locations: []types.Location{{StartLine: 13943, EndLine: 13946}}},
{ID: "[email protected]", Name: "tunnel-agent", Version: "0.6.0", Locations: []types.Location{{StartLine: 13948, EndLine: 13953}}},
{ID: "[email protected]", Name: "tweetnacl", Version: "0.14.5", Locations: []types.Location{{StartLine: 13955, EndLine: 13958}}},
{ID: "[email protected]", Name: "type-check", Version: "0.3.2", Locations: []types.Location{{StartLine: 13960, EndLine: 13965}}},
{ID: "[email protected]", Name: "type-is", Version: "1.6.18", Locations: []types.Location{{StartLine: 13967, EndLine: 13973}}},
{ID: "[email protected]", Name: "typed-styles", Version: "0.0.7", Locations: []types.Location{{StartLine: 13975, EndLine: 13978}}},
{ID: "[email protected]", Name: "typedarray", Version: "0.0.6", Locations: []types.Location{{StartLine: 13980, EndLine: 13983}}},
{ID: "[email protected]", Name: "ua-parser-js", Version: "0.7.19", Locations: []types.Location{{StartLine: 13985, EndLine: 13988}}},
{ID: "[email protected]", Name: "uglify-js", Version: "3.4.10", Locations: []types.Location{{StartLine: 13990, EndLine: 13996}}},
{ID: "[email protected]", Name: "uglify-js", Version: "3.5.12", Locations: []types.Location{{StartLine: 13998, EndLine: 14004}}},
{ID: "[email protected]", Name: "uid-number", Version: "0.0.6", Locations: []types.Location{{StartLine: 14006, EndLine: 14009}}},
{ID: "[email protected]", Name: "umask", Version: "1.1.0", Locations: []types.Location{{StartLine: 14011, EndLine: 14014}}},
{ID: "[email protected]", Name: "underscore", Version: "1.6.0", Locations: []types.Location{{StartLine: 14016, EndLine: 14019}}},
{ID: "[email protected]", Name: "unicode-canonical-property-names-ecmascript", Version: "1.0.4", Locations: []types.Location{{StartLine: 14021, EndLine: 14024}}},
{ID: "[email protected]", Name: "unicode-match-property-ecmascript", Version: "1.0.4", Locations: []types.Location{{StartLine: 14026, EndLine: 14032}}},
{ID: "[email protected]", Name: "unicode-match-property-value-ecmascript", Version: "1.1.0", Locations: []types.Location{{StartLine: 14034, EndLine: 14037}}},
{ID: "[email protected]", Name: "unicode-property-aliases-ecmascript", Version: "1.0.5", Locations: []types.Location{{StartLine: 14039, EndLine: 14042}}},
{ID: "[email protected]", Name: "unified", Version: "7.1.0", Locations: []types.Location{{StartLine: 14044, EndLine: 14056}}},
{ID: "[email protected]", Name: "union-value", Version: "1.0.0", Locations: []types.Location{{StartLine: 14058, EndLine: 14066}}},
{ID: "[email protected]", Name: "unique-filename", Version: "1.1.1", Locations: []types.Location{{StartLine: 14068, EndLine: 14073}}},
{ID: "[email protected]", Name: "unique-slug", Version: "2.0.1", Locations: []types.Location{{StartLine: 14075, EndLine: 14080}}},
{ID: "[email protected]", Name: "unique-string", Version: "1.0.0", Locations: []types.Location{{StartLine: 14082, EndLine: 14087}}},
{ID: "[email protected]", Name: "unist-util-stringify-position", Version: "1.1.2", Locations: []types.Location{{StartLine: 14089, EndLine: 14092}}},
{ID: "[email protected]", Name: "unist-util-stringify-position", Version: "2.0.0", Locations: []types.Location{{StartLine: 14094, EndLine: 14099}}},
{ID: "[email protected]", Name: "universal-user-agent", Version: "2.1.0", Locations: []types.Location{{StartLine: 14101, EndLine: 14106}}},
{ID: "[email protected]", Name: "universalify", Version: "0.1.2", Locations: []types.Location{{StartLine: 14108, EndLine: 14111}}},
{ID: "[email protected]", Name: "unpipe", Version: "1.0.0", Locations: []types.Location{{StartLine: 14113, EndLine: 14116}}},
{ID: "[email protected]", Name: "unquote", Version: "1.1.1", Locations: []types.Location{{StartLine: 14118, EndLine: 14121}}},
{ID: "[email protected]", Name: "unset-value", Version: "1.0.0", Locations: []types.Location{{StartLine: 14123, EndLine: 14129}}},
{ID: "[email protected]", Name: "unzip-response", Version: "2.0.1", Locations: []types.Location{{StartLine: 14131, EndLine: 14134}}},
{ID: "[email protected]", Name: "unzipper", Version: "0.8.14", Locations: []types.Location{{StartLine: 14136, EndLine: 14149}}},
{ID: "[email protected]", Name: "upath", Version: "1.1.2", Locations: []types.Location{{StartLine: 14151, EndLine: 14154}}},
{ID: "[email protected]", Name: "update-notifier", Version: "2.5.0", Locations: []types.Location{{StartLine: 14156, EndLine: 14170}}},
{ID: "[email protected]", Name: "upper-case", Version: "1.1.3", Locations: []types.Location{{StartLine: 14172, EndLine: 14175}}},
{ID: "[email protected]", Name: "uri-js", Version: "4.2.2", Locations: []types.Location{{StartLine: 14177, EndLine: 14182}}},
{ID: "[email protected]", Name: "urix", Version: "0.1.0", Locations: []types.Location{{StartLine: 14184, EndLine: 14187}}},
{ID: "[email protected]", Name: "url-loader", Version: "1.1.2", Locations: []types.Location{{StartLine: 14189, EndLine: 14196}}},
{ID: "[email protected]", Name: "url-parse-lax", Version: "1.0.0", Locations: []types.Location{{StartLine: 14198, EndLine: 14203}}},
{ID: "[email protected]", Name: "url-parse", Version: "1.4.7", Locations: []types.Location{{StartLine: 14205, EndLine: 14211}}},
{ID: "[email protected]", Name: "url-template", Version: "2.0.8", Locations: []types.Location{{StartLine: 14213, EndLine: 14216}}},
{ID: "[email protected]", Name: "url-to-options", Version: "1.0.1", Locations: []types.Location{{StartLine: 14218, EndLine: 14221}}},
{ID: "[email protected]", Name: "url", Version: "0.11.0", Locations: []types.Location{{StartLine: 14223, EndLine: 14229}}},
{ID: "[email protected]", Name: "use", Version: "3.1.1", Locations: []types.Location{{StartLine: 14231, EndLine: 14234}}},
{ID: "[email protected]", Name: "user-home", Version: "1.1.1", Locations: []types.Location{{StartLine: 14236, EndLine: 14239}}},
{ID: "[email protected]", Name: "util-deprecate", Version: "1.0.2", Locations: []types.Location{{StartLine: 14241, EndLine: 14244}}},
{ID: "[email protected]", Name: "util-extend", Version: "1.0.3", Locations: []types.Location{{StartLine: 14246, EndLine: 14249}}},
{ID: "[email protected]", Name: "util.promisify", Version: "1.0.0", Locations: []types.Location{{StartLine: 14251, EndLine: 14257}}},
{ID: "[email protected]", Name: "util", Version: "0.10.3", Locations: []types.Location{{StartLine: 14259, EndLine: 14264}}},
{ID: "[email protected]", Name: "util", Version: "0.10.4", Locations: []types.Location{{StartLine: 14266, EndLine: 14271}}},
{ID: "[email protected]", Name: "util", Version: "0.11.1", Locations: []types.Location{{StartLine: 14273, EndLine: 14278}}},
{ID: "[email protected]", Name: "utila", Version: "0.4.0", Locations: []types.Location{{StartLine: 14280, EndLine: 14283}}},
{ID: "[email protected]", Name: "utils-merge", Version: "1.0.1", Locations: []types.Location{{StartLine: 14285, EndLine: 14288}}},
{ID: "[email protected]", Name: "uuid", Version: "3.3.2", Locations: []types.Location{{StartLine: 14290, EndLine: 14293}}},
{ID: "[email protected]", Name: "v8-compile-cache", Version: "2.0.3", Locations: []types.Location{{StartLine: 14295, EndLine: 14298}}},
{ID: "[email protected]", Name: "v8flags", Version: "2.1.1", Locations: []types.Location{{StartLine: 14300, EndLine: 14305}}},
{ID: "[email protected]", Name: "validate-npm-package-license", Version: "3.0.4", Locations: []types.Location{{StartLine: 14307, EndLine: 14313}}},
{ID: "[email protected]", Name: "validate-npm-package-name", Version: "3.0.0", Locations: []types.Location{{StartLine: 14315, EndLine: 14320}}},
{ID: "[email protected]", Name: "value-equal", Version: "0.4.0", Locations: []types.Location{{StartLine: 14322, EndLine: 14325}}},
{ID: "[email protected]", Name: "vary", Version: "1.1.2", Locations: []types.Location{{StartLine: 14327, EndLine: 14330}}},
{ID: "[email protected]", Name: "velocity-animate", Version: "1.5.2", Locations: []types.Location{{StartLine: 14332, EndLine: 14335}}},
{ID: "[email protected]", Name: "velocity-react", Version: "1.4.3", Locations: []types.Location{{StartLine: 14337, EndLine: 14345}}},
{ID: "[email protected]", Name: "verror", Version: "1.10.0", Locations: []types.Location{{StartLine: 14347, EndLine: 14354}}},
{ID: "[email protected]", Name: "vfile-message", Version: "1.1.1", Locations: []types.Location{{StartLine: 14356, EndLine: 14361}}},
{ID: "[email protected]", Name: "vfile-message", Version: "2.0.0", Locations: []types.Location{{StartLine: 14363, EndLine: 14369}}},
{ID: "[email protected]", Name: "vfile", Version: "3.0.1", Locations: []types.Location{{StartLine: 14371, EndLine: 14379}}},
{ID: "[email protected]", Name: "vfile", Version: "4.0.0", Locations: []types.Location{{StartLine: 14381, EndLine: 14390}}},
{ID: "[email protected]", Name: "vm-browserify", Version: "0.0.4", Locations: []types.Location{{StartLine: 14392, EndLine: 14397}}},
{ID: "[email protected]", Name: "w3c-hr-time", Version: "1.0.1", Locations: []types.Location{{StartLine: 14399, EndLine: 14404}}},
{ID: "[email protected]", Name: "walker", Version: "1.0.7", Locations: []types.Location{{StartLine: 14406, EndLine: 14411}}},
{ID: "[email protected]", Name: "warning", Version: "3.0.0", Locations: []types.Location{{StartLine: 14413, EndLine: 14418}}},
{ID: "[email protected]", Name: "warning", Version: "4.0.3", Locations: []types.Location{{StartLine: 14420, EndLine: 14425}}},
{ID: "[email protected]", Name: "watch", Version: "0.18.0", Locations: []types.Location{{StartLine: 14427, EndLine: 14433}}},
{ID: "[email protected]", Name: "watchpack", Version: "1.6.0", Locations: []types.Location{{StartLine: 14435, EndLine: 14442}}},
{ID: "[email protected]", Name: "wbuf", Version: "1.7.3", Locations: []types.Location{{StartLine: 14444, EndLine: 14449}}},
{ID: "[email protected]", Name: "wcwidth", Version: "1.0.1", Locations: []types.Location{{StartLine: 14451, EndLine: 14456}}},
{ID: "[email protected]", Name: "web-namespaces", Version: "1.1.3", Locations: []types.Location{{StartLine: 14458, EndLine: 14461}}},
{ID: "[email protected]", Name: "webidl-conversions", Version: "4.0.2", Locations: []types.Location{{StartLine: 14463, EndLine: 14466}}},
{ID: "[email protected]", Name: "webpack-bundle-analyzer", Version: "3.3.2", Locations: []types.Location{{StartLine: 14468, EndLine: 14485}}},
{ID: "[email protected]", Name: "webpack-cli", Version: "3.3.2", Locations: []types.Location{{StartLine: 14487, EndLine: 14502}}},
{ID: "[email protected]", Name: "webpack-dev-middleware", Version: "3.7.0", Locations: []types.Location{{StartLine: 14504, EndLine: 14512}}},
{ID: "[email protected]", Name: "webpack-dev-server", Version: "3.3.1", Locations: []types.Location{{StartLine: 14514, EndLine: 14548}}},
{ID: "[email protected]", Name: "webpack-hot-middleware", Version: "2.25.0", Locations: []types.Location{{StartLine: 14550, EndLine: 14558}}},
{ID: "[email protected]", Name: "webpack-log", Version: "2.0.0", Locations: []types.Location{{StartLine: 14560, EndLine: 14566}}},
{ID: "[email protected]", Name: "webpack-merge", Version: "4.2.1", Locations: []types.Location{{StartLine: 14568, EndLine: 14573}}},
{ID: "[email protected]", Name: "webpack-sources", Version: "1.3.0", Locations: []types.Location{{StartLine: 14575, EndLine: 14581}}},
{ID: "[email protected]", Name: "webpack", Version: "4.31.0", Locations: []types.Location{{StartLine: 14583, EndLine: 14611}}},
{ID: "[email protected]", Name: "websocket-driver", Version: "0.7.0", Locations: []types.Location{{StartLine: 14613, EndLine: 14619}}},
{ID: "[email protected]", Name: "websocket-extensions", Version: "0.1.3", Locations: []types.Location{{StartLine: 14621, EndLine: 14624}}},
{ID: "[email protected]", Name: "whatwg-encoding", Version: "1.0.5", Locations: []types.Location{{StartLine: 14626, EndLine: 14631}}},
{ID: "[email protected]", Name: "whatwg-fetch", Version: "3.0.0", Locations: []types.Location{{StartLine: 14633, EndLine: 14636}}},
{ID: "[email protected]", Name: "whatwg-mimetype", Version: "2.3.0", Locations: []types.Location{{StartLine: 14638, EndLine: 14641}}},
{ID: "[email protected]", Name: "whatwg-url", Version: "6.5.0", Locations: []types.Location{{StartLine: 14643, EndLine: 14650}}},
{ID: "[email protected]", Name: "whatwg-url", Version: "7.0.0", Locations: []types.Location{{StartLine: 14652, EndLine: 14659}}},
{ID: "[email protected]", Name: "which-module", Version: "1.0.0", Locations: []types.Location{{StartLine: 14661, EndLine: 14664}}},
{ID: "[email protected]", Name: "which-module", Version: "2.0.0", Locations: []types.Location{{StartLine: 14666, EndLine: 14669}}},
{ID: "[email protected]", Name: "which", Version: "1.3.1", Locations: []types.Location{{StartLine: 14671, EndLine: 14676}}},
{ID: "[email protected]", Name: "wide-align", Version: "1.1.3", Locations: []types.Location{{StartLine: 14678, EndLine: 14683}}},
{ID: "[email protected]", Name: "widest-line", Version: "2.0.1", Locations: []types.Location{{StartLine: 14685, EndLine: 14690}}},
{ID: "[email protected]", Name: "window-size", Version: "0.2.0", Locations: []types.Location{{StartLine: 14692, EndLine: 14695}}},
{ID: "[email protected]", Name: "windows-release", Version: "3.2.0", Locations: []types.Location{{StartLine: 14697, EndLine: 14702}}},
{ID: "[email protected]", Name: "wordwrap", Version: "0.0.3", Locations: []types.Location{{StartLine: 14704, EndLine: 14707}}},
{ID: "[email protected]", Name: "wordwrap", Version: "1.0.0", Locations: []types.Location{{StartLine: 14709, EndLine: 14712}}},
{ID: "[email protected]", Name: "worker-farm", Version: "1.7.0", Locations: []types.Location{{StartLine: 14714, EndLine: 14719}}},
{ID: "[email protected]", Name: "wrap-ansi", Version: "2.1.0", Locations: []types.Location{{StartLine: 14721, EndLine: 14727}}},
{ID: "[email protected]", Name: "wrap-ansi", Version: "3.0.1", Locations: []types.Location{{StartLine: 14729, EndLine: 14735}}},
{ID: "[email protected]", Name: "wrappy", Version: "1.0.2", Locations: []types.Location{{StartLine: 14737, EndLine: 14740}}},
{ID: "[email protected]", Name: "write-file-atomic", Version: "1.3.4", Locations: []types.Location{{StartLine: 14742, EndLine: 14749}}},
{ID: "[email protected]", Name: "write-file-atomic", Version: "2.4.2", Locations: []types.Location{{StartLine: 14751, EndLine: 14758}}},
{ID: "[email protected]", Name: "write-json-file", Version: "2.3.0", Locations: []types.Location{{StartLine: 14760, EndLine: 14770}}},
{ID: "[email protected]", Name: "write", Version: "1.0.3", Locations: []types.Location{{StartLine: 14772, EndLine: 14777}}},
{ID: "[email protected]", Name: "ws", Version: "5.2.2", Locations: []types.Location{{StartLine: 14779, EndLine: 14784}}},
{ID: "[email protected]", Name: "ws", Version: "6.2.1", Locations: []types.Location{{StartLine: 14786, EndLine: 14791}}},
{ID: "[email protected]", Name: "ws", Version: "6.1.4", Locations: []types.Location{{StartLine: 14793, EndLine: 14798}}},
{ID: "[email protected]", Name: "x-is-string", Version: "0.1.0", Locations: []types.Location{{StartLine: 14800, EndLine: 14803}}},
{ID: "[email protected]", Name: "xdg-basedir", Version: "3.0.0", Locations: []types.Location{{StartLine: 14805, EndLine: 14808}}},
{ID: "[email protected]", Name: "xml-name-validator", Version: "3.0.0", Locations: []types.Location{{StartLine: 14810, EndLine: 14813}}},
{ID: "[email protected]", Name: "xmlhttprequest-ssl", Version: "1.5.5", Locations: []types.Location{{StartLine: 14815, EndLine: 14818}}},
{ID: "[email protected]", Name: "xtend", Version: "4.0.1", Locations: []types.Location{{StartLine: 14820, EndLine: 14823}}},
{ID: "[email protected]", Name: "y18n", Version: "3.2.1", Locations: []types.Location{{StartLine: 14825, EndLine: 14828}}},
{ID: "[email protected]", Name: "y18n", Version: "4.0.0", Locations: []types.Location{{StartLine: 14830, EndLine: 14833}}},
{ID: "[email protected]", Name: "yallist", Version: "2.1.2", Locations: []types.Location{{StartLine: 14835, EndLine: 14838}}},
{ID: "[email protected]", Name: "yallist", Version: "3.0.3", Locations: []types.Location{{StartLine: 14840, EndLine: 14843}}},
{ID: "[email protected]", Name: "yargs-parser", Version: "11.1.1", Locations: []types.Location{{StartLine: 14845, EndLine: 14851}}},
{ID: "[email protected]", Name: "yargs-parser", Version: "2.4.1", Locations: []types.Location{{StartLine: 14853, EndLine: 14859}}},
{ID: "[email protected]", Name: "yargs-parser", Version: "9.0.2", Locations: []types.Location{{StartLine: 14861, EndLine: 14866}}},
{ID: "[email protected]", Name: "yargs", Version: "12.0.5", Locations: []types.Location{{StartLine: 14868, EndLine: 14884}}},
{ID: "[email protected]", Name: "yargs", Version: "11.1.0", Locations: []types.Location{{StartLine: 14886, EndLine: 14902}}},
{ID: "[email protected]", Name: "yargs", Version: "4.8.1", Locations: []types.Location{{StartLine: 14904, EndLine: 14922}}},
{ID: "[email protected]", Name: "yeast", Version: "0.1.2", Locations: []types.Location{{StartLine: 14924, EndLine: 14927}}},
}
// ... and
// node test_deps_generator/index.js yarn.lock
yarnRealWorldDeps = []types.Dependency{
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@babel/[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@emotion/[email protected]",
DependsOn: []string{
"@emotion/[email protected]",
"@emotion/[email protected]",
"@emotion/[email protected]",
},
},
{
ID: "@emotion/[email protected]",
DependsOn: []string{
"@emotion/[email protected]",
"@emotion/[email protected]",
"@emotion/[email protected]",
"@emotion/[email protected]",
"@emotion/[email protected]",
},
},
{
ID: "@emotion/[email protected]",
DependsOn: []string{
"@emotion/[email protected]",
"@emotion/[email protected]",
},
},
{
ID: "@emotion/[email protected]",
DependsOn: []string{
"@emotion/[email protected]",
},
},
{
ID: "@emotion/[email protected]",
DependsOn: []string{
"@emotion/[email protected]",
},
},
{
ID: "@emotion/[email protected]",
DependsOn: []string{
"@emotion/[email protected]",
"@emotion/[email protected]",
},
},
{
ID: "@emotion/[email protected]",
DependsOn: []string{
"@emotion/[email protected]",
"@emotion/[email protected]",
"@emotion/[email protected]",
"@emotion/[email protected]",
},
},
{
ID: "@emotion/[email protected]",
DependsOn: []string{
"@emotion/[email protected]",
"@emotion/[email protected]",
"@emotion/[email protected]",
},
},
{
ID: "@emotion/[email protected]",
DependsOn: []string{
"@emotion/[email protected]",
},
},
{
ID: "@loadable/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"[email protected]",
},
},
{
ID: "@material-ui/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@material-ui/[email protected]",
"@material-ui/[email protected]",
"@types/[email protected]",
"@types/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@material-ui/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"[email protected]",
},
},
{
ID: "@material-ui/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@material-ui/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@mrmlnc/[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "@octokit/[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@samverschueren/[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "@storybook/[email protected]",
DependsOn: []string{
"@emotion/[email protected]",
"@emotion/[email protected]",
"@emotion/[email protected]",
"@storybook/[email protected]",
"@storybook/[email protected]",
"@storybook/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@storybook/[email protected]",
DependsOn: []string{
"@storybook/[email protected]",
"@storybook/[email protected]",
"@storybook/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@storybook/[email protected]",
DependsOn: []string{
"@emotion/[email protected]",
"@storybook/[email protected]",
"@storybook/[email protected]",
"@storybook/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@storybook/[email protected]",
DependsOn: []string{
"@storybook/[email protected]",
"@storybook/[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@storybook/[email protected]",
DependsOn: []string{
"@storybook/[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@storybook/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@storybook/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@storybook/[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@storybook/[email protected]",
DependsOn: []string{
"@emotion/[email protected]",
"@emotion/[email protected]",
"@emotion/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@storybook/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"@emotion/[email protected]",
"@emotion/[email protected]",
"@emotion/[email protected]",
"@storybook/[email protected]",
"@storybook/[email protected]",
"@storybook/[email protected]",
"@storybook/[email protected]",
"@storybook/[email protected]",
"@storybook/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@storybook/[email protected]",
DependsOn: []string{
"@storybook/[email protected]",
"@storybook/[email protected]",
"[email protected]",
},
},
{
ID: "@storybook/[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@storybook/[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "@storybook/[email protected]",
DependsOn: []string{
"@storybook/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@storybook/[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@storybook/[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "@storybook/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@emotion/[email protected]",
"@storybook/[email protected]",
"@storybook/[email protected]",
"@svgr/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@storybook/[email protected]",
DependsOn: []string{
"@emotion/[email protected]",
"@emotion/[email protected]",
"@emotion/[email protected]",
"@storybook/[email protected]",
"@storybook/[email protected]",
"@storybook/[email protected]",
"@storybook/[email protected]",
"@storybook/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@svgr/[email protected]",
DependsOn: []string{
"@svgr/[email protected]",
"@svgr/[email protected]",
"@svgr/[email protected]",
"@svgr/[email protected]",
"@svgr/[email protected]",
"@svgr/[email protected]",
"@svgr/[email protected]",
"@svgr/[email protected]",
},
},
{
ID: "@svgr/[email protected]",
DependsOn: []string{
"@svgr/[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@svgr/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "@svgr/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@svgr/[email protected]",
"@svgr/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@svgr/[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "@svgr/[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@svgr/[email protected]",
"@svgr/[email protected]",
"@svgr/[email protected]",
"[email protected]",
},
},
{
ID: "@types/[email protected]",
DependsOn: []string{
"@types/[email protected]",
"@types/[email protected]",
"@types/[email protected]",
},
},
{
ID: "@types/[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "@types/[email protected]",
DependsOn: []string{
"@types/[email protected]",
},
},
{
ID: "@types/[email protected]",
DependsOn: []string{
"@types/[email protected]",
"[email protected]",
},
},
{
ID: "@types/[email protected]",
DependsOn: []string{
"@types/[email protected]",
"@types/[email protected]",
},
},
{
ID: "@types/[email protected]",
DependsOn: []string{
"@types/[email protected]",
"@types/[email protected]",
"@types/[email protected]",
},
},
{
ID: "@webassemblyjs/[email protected]",
DependsOn: []string{
"@webassemblyjs/[email protected]",
"@webassemblyjs/[email protected]",
"@webassemblyjs/[email protected]",
},
},
{
ID: "@webassemblyjs/[email protected]",
DependsOn: []string{
"@webassemblyjs/[email protected]",
},
},
{
ID: "@webassemblyjs/[email protected]",
DependsOn: []string{
"@webassemblyjs/[email protected]",
"[email protected]",
},
},
{
ID: "@webassemblyjs/[email protected]",
DependsOn: []string{
"@webassemblyjs/[email protected]",
"@webassemblyjs/[email protected]",
"@webassemblyjs/[email protected]",
"@webassemblyjs/[email protected]",
},
},
{
ID: "@webassemblyjs/[email protected]",
DependsOn: []string{
"@xtuc/[email protected]",
},
},
{
ID: "@webassemblyjs/[email protected]",
DependsOn: []string{
"@xtuc/[email protected]",
},
},
{
ID: "@webassemblyjs/[email protected]",
DependsOn: []string{
"@webassemblyjs/[email protected]",
"@webassemblyjs/[email protected]",
"@webassemblyjs/[email protected]",
"@webassemblyjs/[email protected]",
"@webassemblyjs/[email protected]",
"@webassemblyjs/[email protected]",
"@webassemblyjs/[email protected]",
"@webassemblyjs/[email protected]",
},
},
{
ID: "@webassemblyjs/[email protected]",
DependsOn: []string{
"@webassemblyjs/[email protected]",
"@webassemblyjs/[email protected]",
"@webassemblyjs/[email protected]",
"@webassemblyjs/[email protected]",
"@webassemblyjs/[email protected]",
},
},
{
ID: "@webassemblyjs/[email protected]",
DependsOn: []string{
"@webassemblyjs/[email protected]",
"@webassemblyjs/[email protected]",
"@webassemblyjs/[email protected]",
"@webassemblyjs/[email protected]",
},
},
{
ID: "@webassemblyjs/[email protected]",
DependsOn: []string{
"@webassemblyjs/[email protected]",
"@webassemblyjs/[email protected]",
"@webassemblyjs/[email protected]",
"@webassemblyjs/[email protected]",
"@webassemblyjs/[email protected]",
"@webassemblyjs/[email protected]",
},
},
{
ID: "@webassemblyjs/[email protected]",
DependsOn: []string{
"@webassemblyjs/[email protected]",
"@webassemblyjs/[email protected]",
"@webassemblyjs/[email protected]",
"@webassemblyjs/[email protected]",
"@webassemblyjs/[email protected]",
"@xtuc/[email protected]",
},
},
{
ID: "@webassemblyjs/[email protected]",
DependsOn: []string{
"@webassemblyjs/[email protected]",
"@webassemblyjs/[email protected]",
"@xtuc/[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"@babel/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"@types/[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"@types/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"@babel/[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"@mrmlnc/[email protected]",
"@nodelib/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"@octokit/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"@samverschueren/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"@types/[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"@icons/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@babel/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@emotion/[email protected]",
"@emotion/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"@babel/[email protected]",
"@emotion/[email protected]",
"@emotion/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"@types/[email protected]",
"@types/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"@types/[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"@types/[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"@types/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"@webassemblyjs/[email protected]",
"@webassemblyjs/[email protected]",
"@webassemblyjs/[email protected]",
"@webassemblyjs/[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
}
// docker run --name yarn2 --rm -it -w /code node:12-alpine sh
// yarn set version berry
// apk add git
// yarn init
// yarn add promise jquery
// yarn info --recursive --dependents --json | jq -r .value | grep -v workspace | awk -F'[@:]' '{printf("{\""$1"\", \""$3"\", \"\"},\n")}'
// to get deps with locations from lock file use following commands:
// awk '/^\S+@[~^*]?(>= )?[0-9.]*/,/^$/{if($0=="") {print "--"prev} else { if(substr($0,1,2)!=" ") {print NR":"$0} else {print $0}} prev=NR}; END{print "--"prev}' | awk 'BEGIN {s=""}; {(substr($0,1,2)=="--") ? (s=s$0"\n") : (s=s$0)}; END { print s}' | sed -E 's/@([0-9~><*\^]|npm).*version:? "?/:/' | sed 's/ /:/' | sed 's/"//g'| awk 'match($0, /[[:digit:]]+$/) {print substr($0, RSTART, RLENGTH)":"$0 }' | awk -F":" '{print "{ID: \""$3"@"$4"\", Name: \""$3"\", Version: \""$4"\", Locations: []types.Location{{StartLine: "$2", EndLine: "$1"}}},"}'
// and remove 'code@workspace' dependency
yarnV2Normal = []types.Library{
{ID: "[email protected]", Name: "asap", Version: "2.0.6", Locations: []types.Location{{StartLine: 8, EndLine: 13}}},
{ID: "[email protected]", Name: "jquery", Version: "3.5.1", Locations: []types.Location{{StartLine: 24, EndLine: 29}}},
{ID: "[email protected]", Name: "promise", Version: "8.1.0", Locations: []types.Location{{StartLine: 31, EndLine: 38}}},
}
// ... and
// node test_deps_generator/index.js yarn.lock
yarnV2NormalDeps = []types.Dependency{
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
}
// ... and
// yarn add react redux
// yarn info --recursive --dependents --json | jq -r .value | grep -v workspace | awk -F'[@:]' '{printf("{\""$1"\", \""$3"\", \"\"},\n")}'
// to get deps with locations from lock file use following commands:
// awk '/^\S+@[~^*]?(>= )?[0-9.]*/,/^$/{if($0=="") {print "--"prev} else { if(substr($0,1,2)!=" ") {print NR":"$0} else {print $0}} prev=NR}; END{print "--"prev}' | awk 'BEGIN {s=""}; {(substr($0,1,2)=="--") ? (s=s$0"\n") : (s=s$0)}; END { print s}' | sed -E 's/@([0-9~><*\^]|npm).*version:? "?/:/' | sed 's/ /:/' | sed 's/"//g'| awk 'match($0, /[[:digit:]]+$/) {print substr($0, RSTART, RLENGTH)":"$0 }' | awk -F":" '{print "{ID: \""$3"@"$4"\", Name: \""$3"\", Version: \""$4"\", Locations: []types.Location{{StartLine: "$2", EndLine: "$1"}}},"}'
// and remove 'code@workspace' and 'fsevents@patch' dependencies
yarnV2React = []types.Library{
{ID: "[email protected]", Name: "asap", Version: "2.0.6", Locations: []types.Location{{StartLine: 8, EndLine: 13}}},
{ID: "[email protected]", Name: "jquery", Version: "3.5.1", Locations: []types.Location{{StartLine: 26, EndLine: 31}}},
{ID: "[email protected]", Name: "js-tokens", Version: "4.0.0", Locations: []types.Location{{StartLine: 33, EndLine: 38}}},
{ID: "[email protected]", Name: "loose-envify", Version: "1.4.0", Locations: []types.Location{{StartLine: 40, EndLine: 49}}},
{ID: "[email protected]", Name: "object-assign", Version: "4.1.1", Locations: []types.Location{{StartLine: 51, EndLine: 56}}},
{ID: "[email protected]", Name: "promise", Version: "8.1.0", Locations: []types.Location{{StartLine: 58, EndLine: 65}}},
{ID: "[email protected]", Name: "prop-types", Version: "15.7.2", Locations: []types.Location{{StartLine: 67, EndLine: 76}}},
{ID: "[email protected]", Name: "react-is", Version: "16.13.1", Locations: []types.Location{{StartLine: 78, EndLine: 83}}},
{ID: "[email protected]", Name: "react", Version: "16.13.1", Locations: []types.Location{{StartLine: 85, EndLine: 94}}},
{ID: "[email protected]", Name: "redux", Version: "4.0.5", Locations: []types.Location{{StartLine: 96, EndLine: 104}}},
{ID: "[email protected]", Name: "symbol-observable", Version: "1.2.0", Locations: []types.Location{{StartLine: 106, EndLine: 111}}},
}
// ... and
// node test_deps_generator/index.js yarn.lock
yarnV2ReactDeps = []types.Dependency{
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
}
// ... and
// yarn add -D mocha
// yarn info --recursive --dependents --json | jq -r .value | grep -v workspace | awk -F'[@:]' '{printf("{\""$1"\", \""$3"\", \"\"},\n")}'
// to get deps with locations from lock file use following commands:
// awk '/^\S+@[~^*]?(>= )?[0-9.]*/,/^$/{if($0=="") {print "--"prev} else { if(substr($0,1,2)!=" ") {print NR":"$0} else {print $0}} prev=NR}; END{print "--"prev}' | awk 'BEGIN {s=""}; {(substr($0,1,2)=="--") ? (s=s$0"\n") : (s=s$0)}; END { print s}' | sed -E 's/@([0-9~><*\^]|npm).*version:? "?/:/' | sed 's/ /:/' | sed 's/"//g'| awk 'match($0, /[[:digit:]]+$/) {print substr($0, RSTART, RLENGTH)":"$0 }' | awk -F":" '{print "{ID: \""$3"@"$4"\", Name: \""$3"\", Version: \""$4"\", Locations: []types.Location{{StartLine: "$2", EndLine: "$1"}}},"}'
// and remove 'code@workspace' and 'fsevents@patch' dependencies
yarnV2WithDev = []types.Library{
{ID: "@types/[email protected]", Name: "@types/color-name", Version: "1.1.1", Locations: []types.Location{{StartLine: 8, EndLine: 13}}},
{ID: "[email protected]", Name: "abbrev", Version: "1.1.1", Locations: []types.Location{{StartLine: 15, EndLine: 20}}},
{ID: "[email protected]", Name: "ajv", Version: "6.12.4", Locations: []types.Location{{StartLine: 22, EndLine: 32}}},
{ID: "[email protected]", Name: "ansi-colors", Version: "4.1.1", Locations: []types.Location{{StartLine: 34, EndLine: 39}}},
{ID: "[email protected]", Name: "ansi-regex", Version: "2.1.1", Locations: []types.Location{{StartLine: 41, EndLine: 46}}},
{ID: "[email protected]", Name: "ansi-regex", Version: "3.0.0", Locations: []types.Location{{StartLine: 48, EndLine: 53}}},
{ID: "[email protected]", Name: "ansi-regex", Version: "4.1.0", Locations: []types.Location{{StartLine: 55, EndLine: 60}}},
{ID: "[email protected]", Name: "ansi-styles", Version: "3.2.1", Locations: []types.Location{{StartLine: 62, EndLine: 69}}},
{ID: "[email protected]", Name: "ansi-styles", Version: "4.2.1", Locations: []types.Location{{StartLine: 71, EndLine: 79}}},
{ID: "[email protected]", Name: "anymatch", Version: "3.1.1", Locations: []types.Location{{StartLine: 81, EndLine: 89}}},
{ID: "[email protected]", Name: "aproba", Version: "1.2.0", Locations: []types.Location{{StartLine: 91, EndLine: 96}}},
{ID: "[email protected]", Name: "are-we-there-yet", Version: "1.1.5", Locations: []types.Location{{StartLine: 98, EndLine: 106}}},
{ID: "[email protected]", Name: "argparse", Version: "1.0.10", Locations: []types.Location{{StartLine: 108, EndLine: 115}}},
{ID: "[email protected]", Name: "array.prototype.map", Version: "1.0.2", Locations: []types.Location{{StartLine: 117, EndLine: 127}}},
{ID: "[email protected]", Name: "asap", Version: "2.0.6", Locations: []types.Location{{StartLine: 129, EndLine: 134}}},
{ID: "[email protected]", Name: "asn1", Version: "0.2.4", Locations: []types.Location{{StartLine: 136, EndLine: 143}}},
{ID: "[email protected]", Name: "assert-plus", Version: "1.0.0", Locations: []types.Location{{StartLine: 145, EndLine: 150}}},
{ID: "[email protected]", Name: "asynckit", Version: "0.4.0", Locations: []types.Location{{StartLine: 152, EndLine: 157}}},
{ID: "[email protected]", Name: "aws-sign2", Version: "0.7.0", Locations: []types.Location{{StartLine: 159, EndLine: 164}}},
{ID: "[email protected]", Name: "aws4", Version: "1.10.1", Locations: []types.Location{{StartLine: 166, EndLine: 171}}},
{ID: "[email protected]", Name: "balanced-match", Version: "1.0.0", Locations: []types.Location{{StartLine: 173, EndLine: 178}}},
{ID: "[email protected]", Name: "bcrypt-pbkdf", Version: "1.0.2", Locations: []types.Location{{StartLine: 180, EndLine: 187}}},
{ID: "[email protected]", Name: "binary-extensions", Version: "2.1.0", Locations: []types.Location{{StartLine: 189, EndLine: 194}}},
{ID: "[email protected]", Name: "brace-expansion", Version: "1.1.11", Locations: []types.Location{{StartLine: 196, EndLine: 204}}},
{ID: "[email protected]", Name: "braces", Version: "3.0.2", Locations: []types.Location{{StartLine: 206, EndLine: 213}}},
{ID: "[email protected]", Name: "browser-stdout", Version: "1.3.1", Locations: []types.Location{{StartLine: 215, EndLine: 220}}},
{ID: "[email protected]", Name: "camelcase", Version: "5.3.1", Locations: []types.Location{{StartLine: 222, EndLine: 227}}},
{ID: "[email protected]", Name: "caseless", Version: "0.12.0", Locations: []types.Location{{StartLine: 229, EndLine: 234}}},
{ID: "[email protected]", Name: "chalk", Version: "4.1.0", Locations: []types.Location{{StartLine: 236, EndLine: 244}}},
{ID: "[email protected]", Name: "chokidar", Version: "3.4.2", Locations: []types.Location{{StartLine: 246, EndLine: 263}}},
{ID: "[email protected]", Name: "chownr", Version: "2.0.0", Locations: []types.Location{{StartLine: 265, EndLine: 270}}},
{ID: "[email protected]", Name: "cliui", Version: "5.0.0", Locations: []types.Location{{StartLine: 272, EndLine: 281}}},
{ID: "[email protected]", Name: "code-point-at", Version: "1.1.0", Locations: []types.Location{{StartLine: 283, EndLine: 288}}},
{ID: "[email protected]", Name: "color-convert", Version: "1.9.3", Locations: []types.Location{{StartLine: 302, EndLine: 309}}},
{ID: "[email protected]", Name: "color-convert", Version: "2.0.1", Locations: []types.Location{{StartLine: 311, EndLine: 318}}},
{ID: "[email protected]", Name: "color-name", Version: "1.1.3", Locations: []types.Location{{StartLine: 320, EndLine: 325}}},
{ID: "[email protected]", Name: "color-name", Version: "1.1.4", Locations: []types.Location{{StartLine: 327, EndLine: 332}}},
{ID: "[email protected]", Name: "combined-stream", Version: "1.0.8", Locations: []types.Location{{StartLine: 334, EndLine: 341}}},
{ID: "[email protected]", Name: "concat-map", Version: "0.0.1", Locations: []types.Location{{StartLine: 343, EndLine: 348}}},
{ID: "[email protected]", Name: "console-control-strings", Version: "1.1.0", Locations: []types.Location{{StartLine: 350, EndLine: 355}}},
{ID: "[email protected]", Name: "core-util-is", Version: "1.0.2", Locations: []types.Location{{StartLine: 357, EndLine: 362}}},
{ID: "[email protected]", Name: "dashdash", Version: "1.14.1", Locations: []types.Location{{StartLine: 364, EndLine: 371}}},
{ID: "[email protected]", Name: "debug", Version: "4.1.1", Locations: []types.Location{{StartLine: 373, EndLine: 380}}},
{ID: "[email protected]", Name: "decamelize", Version: "1.2.0", Locations: []types.Location{{StartLine: 382, EndLine: 387}}},
{ID: "[email protected]", Name: "define-properties", Version: "1.1.3", Locations: []types.Location{{StartLine: 389, EndLine: 396}}},
{ID: "[email protected]", Name: "delayed-stream", Version: "1.0.0", Locations: []types.Location{{StartLine: 398, EndLine: 403}}},
{ID: "[email protected]", Name: "delegates", Version: "1.0.0", Locations: []types.Location{{StartLine: 405, EndLine: 410}}},
{ID: "[email protected]", Name: "diff", Version: "4.0.2", Locations: []types.Location{{StartLine: 412, EndLine: 417}}},
{ID: "[email protected]", Name: "ecc-jsbn", Version: "0.1.2", Locations: []types.Location{{StartLine: 419, EndLine: 427}}},
{ID: "[email protected]", Name: "emoji-regex", Version: "7.0.3", Locations: []types.Location{{StartLine: 429, EndLine: 434}}},
{ID: "[email protected]", Name: "env-paths", Version: "2.2.0", Locations: []types.Location{{StartLine: 436, EndLine: 441}}},
{ID: "[email protected]", Name: "es-abstract", Version: "1.17.6", Locations: []types.Location{{StartLine: 443, EndLine: 460}}},
{ID: "[email protected]", Name: "es-array-method-boxes-properly", Version: "1.0.0", Locations: []types.Location{{StartLine: 462, EndLine: 467}}},
{ID: "[email protected]", Name: "es-get-iterator", Version: "1.1.0", Locations: []types.Location{{StartLine: 469, EndLine: 482}}},
{ID: "[email protected]", Name: "es-to-primitive", Version: "1.2.1", Locations: []types.Location{{StartLine: 484, EndLine: 493}}},
{ID: "[email protected]", Name: "escape-string-regexp", Version: "4.0.0", Locations: []types.Location{{StartLine: 495, EndLine: 500}}},
{ID: "[email protected]", Name: "esprima", Version: "4.0.1", Locations: []types.Location{{StartLine: 502, EndLine: 510}}},
{ID: "[email protected]", Name: "extend", Version: "3.0.2", Locations: []types.Location{{StartLine: 512, EndLine: 517}}},
{ID: "[email protected]", Name: "extsprintf", Version: "1.3.0", Locations: []types.Location{{StartLine: 519, EndLine: 524}}},
{ID: "[email protected]", Name: "fast-deep-equal", Version: "3.1.3", Locations: []types.Location{{StartLine: 526, EndLine: 531}}},
{ID: "[email protected]", Name: "fast-json-stable-stringify", Version: "2.1.0", Locations: []types.Location{{StartLine: 533, EndLine: 538}}},
{ID: "[email protected]", Name: "fill-range", Version: "7.0.1", Locations: []types.Location{{StartLine: 540, EndLine: 547}}},
{ID: "[email protected]", Name: "find-up", Version: "5.0.0", Locations: []types.Location{{StartLine: 549, EndLine: 557}}},
{ID: "[email protected]", Name: "find-up", Version: "3.0.0", Locations: []types.Location{{StartLine: 559, EndLine: 566}}},
{ID: "[email protected]", Name: "flat", Version: "4.1.0", Locations: []types.Location{{StartLine: 568, EndLine: 577}}},
{ID: "[email protected]", Name: "forever-agent", Version: "0.6.1", Locations: []types.Location{{StartLine: 579, EndLine: 584}}},
{ID: "[email protected]", Name: "form-data", Version: "2.3.3", Locations: []types.Location{{StartLine: 586, EndLine: 595}}},
{ID: "[email protected]", Name: "fs-minipass", Version: "2.1.0", Locations: []types.Location{{StartLine: 597, EndLine: 604}}},
{ID: "[email protected]", Name: "fs.realpath", Version: "1.0.0", Locations: []types.Location{{StartLine: 606, EndLine: 611}}},
{ID: "[email protected]", Name: "fsevents", Version: "2.1.3", Locations: []types.Location{{StartLine: 622, EndLine: 629}}},
{ID: "[email protected]", Name: "function-bind", Version: "1.1.1", Locations: []types.Location{{StartLine: 631, EndLine: 636}}},
{ID: "[email protected]", Name: "gauge", Version: "2.7.4", Locations: []types.Location{{StartLine: 638, EndLine: 652}}},
{ID: "[email protected]", Name: "get-caller-file", Version: "2.0.5", Locations: []types.Location{{StartLine: 654, EndLine: 659}}},
{ID: "[email protected]", Name: "getpass", Version: "0.1.7", Locations: []types.Location{{StartLine: 661, EndLine: 668}}},
{ID: "[email protected]", Name: "glob-parent", Version: "5.1.1", Locations: []types.Location{{StartLine: 670, EndLine: 677}}},
{ID: "[email protected]", Name: "glob", Version: "7.1.6", Locations: []types.Location{{StartLine: 679, EndLine: 691}}},
{ID: "[email protected]", Name: "graceful-fs", Version: "4.2.4", Locations: []types.Location{{StartLine: 693, EndLine: 698}}},
{ID: "[email protected]", Name: "growl", Version: "1.10.5", Locations: []types.Location{{StartLine: 700, EndLine: 705}}},
{ID: "[email protected]", Name: "har-schema", Version: "2.0.0", Locations: []types.Location{{StartLine: 707, EndLine: 712}}},
{ID: "[email protected]", Name: "har-validator", Version: "5.1.5", Locations: []types.Location{{StartLine: 714, EndLine: 722}}},
{ID: "[email protected]", Name: "has-flag", Version: "4.0.0", Locations: []types.Location{{StartLine: 724, EndLine: 729}}},
{ID: "[email protected]", Name: "has-symbols", Version: "1.0.1", Locations: []types.Location{{StartLine: 731, EndLine: 736}}},
{ID: "[email protected]", Name: "has-unicode", Version: "2.0.1", Locations: []types.Location{{StartLine: 738, EndLine: 743}}},
{ID: "[email protected]", Name: "has", Version: "1.0.3", Locations: []types.Location{{StartLine: 745, EndLine: 752}}},
{ID: "[email protected]", Name: "he", Version: "1.2.0", Locations: []types.Location{{StartLine: 754, EndLine: 761}}},
{ID: "[email protected]", Name: "http-signature", Version: "1.2.0", Locations: []types.Location{{StartLine: 763, EndLine: 772}}},
{ID: "[email protected]", Name: "inflight", Version: "1.0.6", Locations: []types.Location{{StartLine: 774, EndLine: 782}}},
{ID: "[email protected]", Name: "inherits", Version: "2.0.4", Locations: []types.Location{{StartLine: 784, EndLine: 789}}},
{ID: "[email protected]", Name: "is-arguments", Version: "1.0.4", Locations: []types.Location{{StartLine: 791, EndLine: 796}}},
{ID: "[email protected]", Name: "is-binary-path", Version: "2.1.0", Locations: []types.Location{{StartLine: 798, EndLine: 805}}},
{ID: "[email protected]", Name: "is-buffer", Version: "2.0.4", Locations: []types.Location{{StartLine: 807, EndLine: 812}}},
{ID: "[email protected]", Name: "is-callable", Version: "1.2.0", Locations: []types.Location{{StartLine: 814, EndLine: 819}}},
{ID: "[email protected]", Name: "is-date-object", Version: "1.0.2", Locations: []types.Location{{StartLine: 821, EndLine: 826}}},
{ID: "[email protected]", Name: "is-extglob", Version: "2.1.1", Locations: []types.Location{{StartLine: 828, EndLine: 833}}},
{ID: "[email protected]", Name: "is-fullwidth-code-point", Version: "1.0.0", Locations: []types.Location{{StartLine: 835, EndLine: 842}}},
{ID: "[email protected]", Name: "is-fullwidth-code-point", Version: "2.0.0", Locations: []types.Location{{StartLine: 844, EndLine: 849}}},
{ID: "[email protected]", Name: "is-glob", Version: "4.0.1", Locations: []types.Location{{StartLine: 851, EndLine: 858}}},
{ID: "[email protected]", Name: "is-map", Version: "2.0.1", Locations: []types.Location{{StartLine: 860, EndLine: 865}}},
{ID: "[email protected]", Name: "is-number", Version: "7.0.0", Locations: []types.Location{{StartLine: 867, EndLine: 872}}},
{ID: "[email protected]", Name: "is-plain-obj", Version: "1.1.0", Locations: []types.Location{{StartLine: 874, EndLine: 879}}},
{ID: "[email protected]", Name: "is-regex", Version: "1.1.1", Locations: []types.Location{{StartLine: 881, EndLine: 888}}},
{ID: "[email protected]", Name: "is-set", Version: "2.0.1", Locations: []types.Location{{StartLine: 890, EndLine: 895}}},
{ID: "[email protected]", Name: "is-string", Version: "1.0.5", Locations: []types.Location{{StartLine: 897, EndLine: 902}}},
{ID: "[email protected]", Name: "is-symbol", Version: "1.0.3", Locations: []types.Location{{StartLine: 904, EndLine: 911}}},
{ID: "[email protected]", Name: "is-typedarray", Version: "1.0.0", Locations: []types.Location{{StartLine: 913, EndLine: 918}}},
{ID: "[email protected]", Name: "isarray", Version: "2.0.5", Locations: []types.Location{{StartLine: 920, EndLine: 925}}},
{ID: "[email protected]", Name: "isarray", Version: "1.0.0", Locations: []types.Location{{StartLine: 927, EndLine: 932}}},
{ID: "[email protected]", Name: "isexe", Version: "2.0.0", Locations: []types.Location{{StartLine: 934, EndLine: 939}}},
{ID: "[email protected]", Name: "isstream", Version: "0.1.2", Locations: []types.Location{{StartLine: 941, EndLine: 946}}},
{ID: "[email protected]", Name: "iterate-iterator", Version: "1.0.1", Locations: []types.Location{{StartLine: 948, EndLine: 953}}},
{ID: "[email protected]", Name: "iterate-value", Version: "1.0.2", Locations: []types.Location{{StartLine: 955, EndLine: 963}}},
{ID: "[email protected]", Name: "jquery", Version: "3.5.1", Locations: []types.Location{{StartLine: 965, EndLine: 970}}},
{ID: "[email protected]", Name: "js-tokens", Version: "4.0.0", Locations: []types.Location{{StartLine: 972, EndLine: 977}}},
{ID: "[email protected]", Name: "js-yaml", Version: "3.14.0", Locations: []types.Location{{StartLine: 979, EndLine: 989}}},
{ID: "[email protected]", Name: "jsbn", Version: "0.1.1", Locations: []types.Location{{StartLine: 991, EndLine: 996}}},
{ID: "[email protected]", Name: "json-schema-traverse", Version: "0.4.1", Locations: []types.Location{{StartLine: 998, EndLine: 1003}}},
{ID: "[email protected]", Name: "json-schema", Version: "0.2.3", Locations: []types.Location{{StartLine: 1005, EndLine: 1010}}},
{ID: "[email protected]", Name: "json-stringify-safe", Version: "5.0.1", Locations: []types.Location{{StartLine: 1012, EndLine: 1017}}},
{ID: "[email protected]", Name: "jsprim", Version: "1.4.1", Locations: []types.Location{{StartLine: 1019, EndLine: 1029}}},
{ID: "[email protected]", Name: "locate-path", Version: "3.0.0", Locations: []types.Location{{StartLine: 1031, EndLine: 1039}}},
{ID: "[email protected]", Name: "locate-path", Version: "6.0.0", Locations: []types.Location{{StartLine: 1041, EndLine: 1048}}},
{ID: "[email protected]", Name: "log-symbols", Version: "4.0.0", Locations: []types.Location{{StartLine: 1050, EndLine: 1057}}},
{ID: "[email protected]", Name: "loose-envify", Version: "1.4.0", Locations: []types.Location{{StartLine: 1059, EndLine: 1068}}},
{ID: "[email protected]", Name: "mime-db", Version: "1.44.0", Locations: []types.Location{{StartLine: 1070, EndLine: 1075}}},
{ID: "[email protected]", Name: "mime-types", Version: "2.1.27", Locations: []types.Location{{StartLine: 1077, EndLine: 1084}}},
{ID: "[email protected]", Name: "minimatch", Version: "3.0.4", Locations: []types.Location{{StartLine: 1086, EndLine: 1093}}},
{ID: "[email protected]", Name: "minipass", Version: "3.1.3", Locations: []types.Location{{StartLine: 1095, EndLine: 1102}}},
{ID: "[email protected]", Name: "minizlib", Version: "2.1.2", Locations: []types.Location{{StartLine: 1104, EndLine: 1112}}},
{ID: "[email protected]", Name: "mkdirp", Version: "1.0.4", Locations: []types.Location{{StartLine: 1114, EndLine: 1121}}},
{ID: "[email protected]", Name: "mocha", Version: "8.1.3", Locations: []types.Location{{StartLine: 1123, EndLine: 1157}}},
{ID: "[email protected]", Name: "ms", Version: "2.1.2", Locations: []types.Location{{StartLine: 1159, EndLine: 1164}}},
{ID: "[email protected]", Name: "node-gyp", Version: "7.1.0", Locations: []types.Location{{StartLine: 1166, EndLine: 1184}}},
{ID: "[email protected]", Name: "nopt", Version: "4.0.3", Locations: []types.Location{{StartLine: 1186, EndLine: 1196}}},
{ID: "[email protected]", Name: "normalize-path", Version: "3.0.0", Locations: []types.Location{{StartLine: 1198, EndLine: 1203}}},
{ID: "[email protected]", Name: "npmlog", Version: "4.1.2", Locations: []types.Location{{StartLine: 1205, EndLine: 1215}}},
{ID: "[email protected]", Name: "number-is-nan", Version: "1.0.1", Locations: []types.Location{{StartLine: 1217, EndLine: 1222}}},
{ID: "[email protected]", Name: "oauth-sign", Version: "0.9.0", Locations: []types.Location{{StartLine: 1224, EndLine: 1229}}},
{ID: "[email protected]", Name: "object-assign", Version: "4.1.1", Locations: []types.Location{{StartLine: 1231, EndLine: 1236}}},
{ID: "[email protected]", Name: "object-inspect", Version: "1.8.0", Locations: []types.Location{{StartLine: 1238, EndLine: 1243}}},
{ID: "[email protected]", Name: "object-keys", Version: "1.1.1", Locations: []types.Location{{StartLine: 1245, EndLine: 1250}}},
{ID: "[email protected]", Name: "object.assign", Version: "4.1.0", Locations: []types.Location{{StartLine: 1252, EndLine: 1262}}},
{ID: "[email protected]", Name: "once", Version: "1.4.0", Locations: []types.Location{{StartLine: 1264, EndLine: 1271}}},
{ID: "[email protected]", Name: "os-homedir", Version: "1.0.2", Locations: []types.Location{{StartLine: 1273, EndLine: 1278}}},
{ID: "[email protected]", Name: "os-tmpdir", Version: "1.0.2", Locations: []types.Location{{StartLine: 1280, EndLine: 1285}}},
{ID: "[email protected]", Name: "osenv", Version: "0.1.5", Locations: []types.Location{{StartLine: 1287, EndLine: 1295}}},
{ID: "[email protected]", Name: "p-limit", Version: "2.3.0", Locations: []types.Location{{StartLine: 1297, EndLine: 1304}}},
{ID: "[email protected]", Name: "p-limit", Version: "3.0.2", Locations: []types.Location{{StartLine: 1306, EndLine: 1313}}},
{ID: "[email protected]", Name: "p-locate", Version: "3.0.0", Locations: []types.Location{{StartLine: 1315, EndLine: 1322}}},
{ID: "[email protected]", Name: "p-locate", Version: "5.0.0", Locations: []types.Location{{StartLine: 1324, EndLine: 1331}}},
{ID: "[email protected]", Name: "p-try", Version: "2.2.0", Locations: []types.Location{{StartLine: 1333, EndLine: 1338}}},
{ID: "[email protected]", Name: "path-exists", Version: "3.0.0", Locations: []types.Location{{StartLine: 1340, EndLine: 1345}}},
{ID: "[email protected]", Name: "path-exists", Version: "4.0.0", Locations: []types.Location{{StartLine: 1347, EndLine: 1352}}},
{ID: "[email protected]", Name: "path-is-absolute", Version: "1.0.1", Locations: []types.Location{{StartLine: 1354, EndLine: 1359}}},
{ID: "[email protected]", Name: "performance-now", Version: "2.1.0", Locations: []types.Location{{StartLine: 1361, EndLine: 1366}}},
{ID: "[email protected]", Name: "picomatch", Version: "2.2.2", Locations: []types.Location{{StartLine: 1368, EndLine: 1373}}},
{ID: "[email protected]", Name: "process-nextick-args", Version: "2.0.1", Locations: []types.Location{{StartLine: 1375, EndLine: 1380}}},
{ID: "[email protected]", Name: "promise.allsettled", Version: "1.0.2", Locations: []types.Location{{StartLine: 1382, EndLine: 1393}}},
{ID: "[email protected]", Name: "promise", Version: "8.1.0", Locations: []types.Location{{StartLine: 1395, EndLine: 1402}}},
{ID: "[email protected]", Name: "prop-types", Version: "15.7.2", Locations: []types.Location{{StartLine: 1404, EndLine: 1413}}},
{ID: "[email protected]", Name: "psl", Version: "1.8.0", Locations: []types.Location{{StartLine: 1415, EndLine: 1420}}},
{ID: "[email protected]", Name: "punycode", Version: "2.1.1", Locations: []types.Location{{StartLine: 1422, EndLine: 1427}}},
{ID: "[email protected]", Name: "qs", Version: "6.5.2", Locations: []types.Location{{StartLine: 1429, EndLine: 1434}}},
{ID: "[email protected]", Name: "randombytes", Version: "2.1.0", Locations: []types.Location{{StartLine: 1436, EndLine: 1443}}},
{ID: "[email protected]", Name: "react-is", Version: "16.13.1", Locations: []types.Location{{StartLine: 1445, EndLine: 1450}}},
{ID: "[email protected]", Name: "react", Version: "16.13.1", Locations: []types.Location{{StartLine: 1452, EndLine: 1461}}},
{ID: "[email protected]", Name: "readable-stream", Version: "2.3.7", Locations: []types.Location{{StartLine: 1463, EndLine: 1476}}},
{ID: "[email protected]", Name: "readdirp", Version: "3.4.0", Locations: []types.Location{{StartLine: 1478, EndLine: 1485}}},
{ID: "[email protected]", Name: "redux", Version: "4.0.5", Locations: []types.Location{{StartLine: 1487, EndLine: 1495}}},
{ID: "[email protected]", Name: "request", Version: "2.88.2", Locations: []types.Location{{StartLine: 1497, EndLine: 1523}}},
{ID: "[email protected]", Name: "require-directory", Version: "2.1.1", Locations: []types.Location{{StartLine: 1525, EndLine: 1530}}},
{ID: "[email protected]", Name: "require-main-filename", Version: "2.0.0", Locations: []types.Location{{StartLine: 1532, EndLine: 1537}}},
{ID: "[email protected]", Name: "rimraf", Version: "2.7.1", Locations: []types.Location{{StartLine: 1539, EndLine: 1548}}},
{ID: "[email protected]", Name: "safe-buffer", Version: "5.2.1", Locations: []types.Location{{StartLine: 1550, EndLine: 1555}}},
{ID: "[email protected]", Name: "safe-buffer", Version: "5.1.2", Locations: []types.Location{{StartLine: 1557, EndLine: 1562}}},
{ID: "[email protected]", Name: "safer-buffer", Version: "2.1.2", Locations: []types.Location{{StartLine: 1564, EndLine: 1569}}},
{ID: "[email protected]", Name: "semver", Version: "7.3.2", Locations: []types.Location{{StartLine: 1571, EndLine: 1578}}},
{ID: "[email protected]", Name: "serialize-javascript", Version: "4.0.0", Locations: []types.Location{{StartLine: 1580, EndLine: 1587}}},
{ID: "[email protected]", Name: "set-blocking", Version: "2.0.0", Locations: []types.Location{{StartLine: 1589, EndLine: 1594}}},
{ID: "[email protected]", Name: "signal-exit", Version: "3.0.3", Locations: []types.Location{{StartLine: 1596, EndLine: 1601}}},
{ID: "[email protected]", Name: "sprintf-js", Version: "1.0.3", Locations: []types.Location{{StartLine: 1603, EndLine: 1608}}},
{ID: "[email protected]", Name: "sshpk", Version: "1.16.1", Locations: []types.Location{{StartLine: 1610, EndLine: 1629}}},
{ID: "[email protected]", Name: "string-width", Version: "1.0.2", Locations: []types.Location{{StartLine: 1631, EndLine: 1640}}},
{ID: "[email protected]", Name: "string-width", Version: "2.1.1", Locations: []types.Location{{StartLine: 1642, EndLine: 1650}}},
{ID: "[email protected]", Name: "string-width", Version: "3.1.0", Locations: []types.Location{{StartLine: 1652, EndLine: 1661}}},
{ID: "[email protected]", Name: "string.prototype.trimend", Version: "1.0.1", Locations: []types.Location{{StartLine: 1663, EndLine: 1671}}},
{ID: "[email protected]", Name: "string.prototype.trimstart", Version: "1.0.1", Locations: []types.Location{{StartLine: 1673, EndLine: 1681}}},
{ID: "[email protected]", Name: "string_decoder", Version: "1.1.1", Locations: []types.Location{{StartLine: 1683, EndLine: 1690}}},
{ID: "[email protected]", Name: "strip-ansi", Version: "3.0.1", Locations: []types.Location{{StartLine: 1692, EndLine: 1699}}},
{ID: "[email protected]", Name: "strip-ansi", Version: "4.0.0", Locations: []types.Location{{StartLine: 1701, EndLine: 1708}}},
{ID: "[email protected]", Name: "strip-ansi", Version: "5.2.0", Locations: []types.Location{{StartLine: 1710, EndLine: 1717}}},
{ID: "[email protected]", Name: "strip-json-comments", Version: "3.0.1", Locations: []types.Location{{StartLine: 1719, EndLine: 1724}}},
{ID: "[email protected]", Name: "supports-color", Version: "7.1.0", Locations: []types.Location{{StartLine: 1726, EndLine: 1733}}},
{ID: "[email protected]", Name: "symbol-observable", Version: "1.2.0", Locations: []types.Location{{StartLine: 1735, EndLine: 1740}}},
{ID: "[email protected]", Name: "tar", Version: "6.0.5", Locations: []types.Location{{StartLine: 1742, EndLine: 1754}}},
{ID: "[email protected]", Name: "to-regex-range", Version: "5.0.1", Locations: []types.Location{{StartLine: 1756, EndLine: 1763}}},
{ID: "[email protected]", Name: "tough-cookie", Version: "2.5.0", Locations: []types.Location{{StartLine: 1765, EndLine: 1773}}},
{ID: "[email protected]", Name: "tunnel-agent", Version: "0.6.0", Locations: []types.Location{{StartLine: 1775, EndLine: 1782}}},
{ID: "[email protected]", Name: "tweetnacl", Version: "0.14.5", Locations: []types.Location{{StartLine: 1784, EndLine: 1789}}},
{ID: "[email protected]", Name: "uri-js", Version: "4.4.0", Locations: []types.Location{{StartLine: 1791, EndLine: 1798}}},
{ID: "[email protected]", Name: "util-deprecate", Version: "1.0.2", Locations: []types.Location{{StartLine: 1800, EndLine: 1805}}},
{ID: "[email protected]", Name: "uuid", Version: "3.4.0", Locations: []types.Location{{StartLine: 1807, EndLine: 1814}}},
{ID: "[email protected]", Name: "verror", Version: "1.10.0", Locations: []types.Location{{StartLine: 1816, EndLine: 1825}}},
{ID: "[email protected]", Name: "which-module", Version: "2.0.0", Locations: []types.Location{{StartLine: 1827, EndLine: 1832}}},
{ID: "[email protected]", Name: "which", Version: "2.0.2", Locations: []types.Location{{StartLine: 1834, EndLine: 1843}}},
{ID: "[email protected]", Name: "wide-align", Version: "1.1.3", Locations: []types.Location{{StartLine: 1845, EndLine: 1852}}},
{ID: "[email protected]", Name: "workerpool", Version: "6.0.0", Locations: []types.Location{{StartLine: 1854, EndLine: 1859}}},
{ID: "[email protected]", Name: "wrap-ansi", Version: "5.1.0", Locations: []types.Location{{StartLine: 1861, EndLine: 1870}}},
{ID: "[email protected]", Name: "wrappy", Version: "1.0.2", Locations: []types.Location{{StartLine: 1872, EndLine: 1877}}},
{ID: "[email protected]", Name: "y18n", Version: "4.0.0", Locations: []types.Location{{StartLine: 1879, EndLine: 1884}}},
{ID: "[email protected]", Name: "yallist", Version: "4.0.0", Locations: []types.Location{{StartLine: 1886, EndLine: 1891}}},
{ID: "[email protected]", Name: "yargs-parser", Version: "13.1.2", Locations: []types.Location{{StartLine: 1893, EndLine: 1901}}},
{ID: "[email protected]", Name: "yargs-parser", Version: "15.0.1", Locations: []types.Location{{StartLine: 1903, EndLine: 1911}}},
{ID: "[email protected]", Name: "yargs-unparser", Version: "1.6.1", Locations: []types.Location{{StartLine: 1913, EndLine: 1924}}},
{ID: "[email protected]", Name: "yargs", Version: "13.3.2", Locations: []types.Location{{StartLine: 1926, EndLine: 1942}}},
{ID: "[email protected]", Name: "yargs", Version: "14.2.3", Locations: []types.Location{{StartLine: 1944, EndLine: 1961}}},
}
// ... and
// node test_deps_generator/index.js yarn.lock
yarnV2WithDevDeps = []types.Dependency{
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"@types/[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
}
// ... and
// yarn add lodash request chalk commander express async axios vue
// yarn info --recursive --dependents --json | jq -r .value | grep -v workspace | awk -F'[@:]' '{printf("{\""$1"\", \""$3"\", \"\"},\n")}'
// to get deps with locations from lock file use following commands:
// awk '/^\S+@[~^*]?(>= )?[0-9.]*/,/^$/{if($0=="") {print "--"prev} else { if(substr($0,1,2)!=" ") {print NR":"$0} else {print $0}} prev=NR}; END{print "--"prev}' | awk 'BEGIN {s=""}; {(substr($0,1,2)=="--") ? (s=s$0"\n") : (s=s$0)}; END { print s}' | sed -E 's/@([0-9~><*\^]|npm).*version:? "?/:/' | sed 's/ /:/' | sed 's/"//g'| awk 'match($0, /[[:digit:]]+$/) {print substr($0, RSTART, RLENGTH)":"$0 }' | awk -F":" '{print "{ID: \""$3"@"$4"\", Name: \""$3"\", Version: \""$4"\", Locations: []types.Location{{StartLine: "$2", EndLine: "$1"}}},"}'
// and remove 'code@workspace' and 'fsevents@patch' dependencies
yarnV2Many = []types.Library{
{ID: "@types/[email protected]", Name: "@types/color-name", Version: "1.1.1", Locations: []types.Location{{StartLine: 8, EndLine: 13}}},
{ID: "[email protected]", Name: "abbrev", Version: "1.1.1", Locations: []types.Location{{StartLine: 15, EndLine: 20}}},
{ID: "[email protected]", Name: "accepts", Version: "1.3.7", Locations: []types.Location{{StartLine: 22, EndLine: 30}}},
{ID: "[email protected]", Name: "ajv", Version: "6.12.4", Locations: []types.Location{{StartLine: 32, EndLine: 42}}},
{ID: "[email protected]", Name: "ansi-colors", Version: "4.1.1", Locations: []types.Location{{StartLine: 44, EndLine: 49}}},
{ID: "[email protected]", Name: "ansi-regex", Version: "2.1.1", Locations: []types.Location{{StartLine: 51, EndLine: 56}}},
{ID: "[email protected]", Name: "ansi-regex", Version: "3.0.0", Locations: []types.Location{{StartLine: 58, EndLine: 63}}},
{ID: "[email protected]", Name: "ansi-regex", Version: "4.1.0", Locations: []types.Location{{StartLine: 65, EndLine: 70}}},
{ID: "[email protected]", Name: "ansi-styles", Version: "3.2.1", Locations: []types.Location{{StartLine: 72, EndLine: 79}}},
{ID: "[email protected]", Name: "ansi-styles", Version: "4.2.1", Locations: []types.Location{{StartLine: 81, EndLine: 89}}},
{ID: "[email protected]", Name: "anymatch", Version: "3.1.1", Locations: []types.Location{{StartLine: 91, EndLine: 99}}},
{ID: "[email protected]", Name: "aproba", Version: "1.2.0", Locations: []types.Location{{StartLine: 101, EndLine: 106}}},
{ID: "[email protected]", Name: "are-we-there-yet", Version: "1.1.5", Locations: []types.Location{{StartLine: 108, EndLine: 116}}},
{ID: "[email protected]", Name: "argparse", Version: "1.0.10", Locations: []types.Location{{StartLine: 118, EndLine: 125}}},
{ID: "[email protected]", Name: "array-flatten", Version: "1.1.1", Locations: []types.Location{{StartLine: 127, EndLine: 132}}},
{ID: "[email protected]", Name: "array.prototype.map", Version: "1.0.2", Locations: []types.Location{{StartLine: 134, EndLine: 144}}},
{ID: "[email protected]", Name: "asap", Version: "2.0.6", Locations: []types.Location{{StartLine: 146, EndLine: 151}}},
{ID: "[email protected]", Name: "asn1", Version: "0.2.4", Locations: []types.Location{{StartLine: 153, EndLine: 160}}},
{ID: "[email protected]", Name: "assert-plus", Version: "1.0.0", Locations: []types.Location{{StartLine: 162, EndLine: 167}}},
{ID: "[email protected]", Name: "async", Version: "3.2.0", Locations: []types.Location{{StartLine: 169, EndLine: 174}}},
{ID: "[email protected]", Name: "asynckit", Version: "0.4.0", Locations: []types.Location{{StartLine: 176, EndLine: 181}}},
{ID: "[email protected]", Name: "aws-sign2", Version: "0.7.0", Locations: []types.Location{{StartLine: 183, EndLine: 188}}},
{ID: "[email protected]", Name: "aws4", Version: "1.10.1", Locations: []types.Location{{StartLine: 190, EndLine: 195}}},
{ID: "[email protected]", Name: "axios", Version: "0.20.0", Locations: []types.Location{{StartLine: 197, EndLine: 204}}},
{ID: "[email protected]", Name: "balanced-match", Version: "1.0.0", Locations: []types.Location{{StartLine: 206, EndLine: 211}}},
{ID: "[email protected]", Name: "bcrypt-pbkdf", Version: "1.0.2", Locations: []types.Location{{StartLine: 213, EndLine: 220}}},
{ID: "[email protected]", Name: "binary-extensions", Version: "2.1.0", Locations: []types.Location{{StartLine: 222, EndLine: 227}}},
{ID: "[email protected]", Name: "body-parser", Version: "1.19.0", Locations: []types.Location{{StartLine: 229, EndLine: 245}}},
{ID: "[email protected]", Name: "brace-expansion", Version: "1.1.11", Locations: []types.Location{{StartLine: 247, EndLine: 255}}},
{ID: "[email protected]", Name: "braces", Version: "3.0.2", Locations: []types.Location{{StartLine: 257, EndLine: 264}}},
{ID: "[email protected]", Name: "browser-stdout", Version: "1.3.1", Locations: []types.Location{{StartLine: 266, EndLine: 271}}},
{ID: "[email protected]", Name: "bytes", Version: "3.1.0", Locations: []types.Location{{StartLine: 273, EndLine: 278}}},
{ID: "[email protected]", Name: "camelcase", Version: "5.3.1", Locations: []types.Location{{StartLine: 280, EndLine: 285}}},
{ID: "[email protected]", Name: "caseless", Version: "0.12.0", Locations: []types.Location{{StartLine: 287, EndLine: 292}}},
{ID: "[email protected]", Name: "chalk", Version: "4.1.0", Locations: []types.Location{{StartLine: 294, EndLine: 302}}},
{ID: "[email protected]", Name: "chokidar", Version: "3.4.2", Locations: []types.Location{{StartLine: 304, EndLine: 321}}},
{ID: "[email protected]", Name: "chownr", Version: "2.0.0", Locations: []types.Location{{StartLine: 323, EndLine: 328}}},
{ID: "[email protected]", Name: "cliui", Version: "5.0.0", Locations: []types.Location{{StartLine: 330, EndLine: 339}}},
{ID: "[email protected]", Name: "code-point-at", Version: "1.1.0", Locations: []types.Location{{StartLine: 341, EndLine: 346}}},
{ID: "[email protected]", Name: "color-convert", Version: "1.9.3", Locations: []types.Location{{StartLine: 368, EndLine: 375}}},
{ID: "[email protected]", Name: "color-convert", Version: "2.0.1", Locations: []types.Location{{StartLine: 377, EndLine: 384}}},
{ID: "[email protected]", Name: "color-name", Version: "1.1.3", Locations: []types.Location{{StartLine: 386, EndLine: 391}}},
{ID: "[email protected]", Name: "color-name", Version: "1.1.4", Locations: []types.Location{{StartLine: 393, EndLine: 398}}},
{ID: "[email protected]", Name: "combined-stream", Version: "1.0.8", Locations: []types.Location{{StartLine: 400, EndLine: 407}}},
{ID: "[email protected]", Name: "commander", Version: "6.1.0", Locations: []types.Location{{StartLine: 409, EndLine: 414}}},
{ID: "[email protected]", Name: "concat-map", Version: "0.0.1", Locations: []types.Location{{StartLine: 416, EndLine: 421}}},
{ID: "[email protected]", Name: "console-control-strings", Version: "1.1.0", Locations: []types.Location{{StartLine: 423, EndLine: 428}}},
{ID: "[email protected]", Name: "content-disposition", Version: "0.5.3", Locations: []types.Location{{StartLine: 430, EndLine: 437}}},
{ID: "[email protected]", Name: "content-type", Version: "1.0.4", Locations: []types.Location{{StartLine: 439, EndLine: 444}}},
{ID: "[email protected]", Name: "cookie-signature", Version: "1.0.6", Locations: []types.Location{{StartLine: 446, EndLine: 451}}},
{ID: "[email protected]", Name: "cookie", Version: "0.4.0", Locations: []types.Location{{StartLine: 453, EndLine: 458}}},
{ID: "[email protected]", Name: "core-util-is", Version: "1.0.2", Locations: []types.Location{{StartLine: 460, EndLine: 465}}},
{ID: "[email protected]", Name: "dashdash", Version: "1.14.1", Locations: []types.Location{{StartLine: 467, EndLine: 474}}},
{ID: "[email protected]", Name: "debug", Version: "2.6.9", Locations: []types.Location{{StartLine: 476, EndLine: 483}}},
{ID: "[email protected]", Name: "debug", Version: "4.1.1", Locations: []types.Location{{StartLine: 485, EndLine: 492}}},
{ID: "[email protected]", Name: "decamelize", Version: "1.2.0", Locations: []types.Location{{StartLine: 494, EndLine: 499}}},
{ID: "[email protected]", Name: "define-properties", Version: "1.1.3", Locations: []types.Location{{StartLine: 501, EndLine: 508}}},
{ID: "[email protected]", Name: "delayed-stream", Version: "1.0.0", Locations: []types.Location{{StartLine: 510, EndLine: 515}}},
{ID: "[email protected]", Name: "delegates", Version: "1.0.0", Locations: []types.Location{{StartLine: 517, EndLine: 522}}},
{ID: "[email protected]", Name: "depd", Version: "1.1.2", Locations: []types.Location{{StartLine: 524, EndLine: 529}}},
{ID: "[email protected]", Name: "destroy", Version: "1.0.4", Locations: []types.Location{{StartLine: 531, EndLine: 536}}},
{ID: "[email protected]", Name: "diff", Version: "4.0.2", Locations: []types.Location{{StartLine: 538, EndLine: 543}}},
{ID: "[email protected]", Name: "ecc-jsbn", Version: "0.1.2", Locations: []types.Location{{StartLine: 545, EndLine: 553}}},
{ID: "[email protected]", Name: "ee-first", Version: "1.1.1", Locations: []types.Location{{StartLine: 555, EndLine: 560}}},
{ID: "[email protected]", Name: "emoji-regex", Version: "7.0.3", Locations: []types.Location{{StartLine: 562, EndLine: 567}}},
{ID: "[email protected]", Name: "encodeurl", Version: "1.0.2", Locations: []types.Location{{StartLine: 569, EndLine: 574}}},
{ID: "[email protected]", Name: "env-paths", Version: "2.2.0", Locations: []types.Location{{StartLine: 576, EndLine: 581}}},
{ID: "[email protected]", Name: "es-abstract", Version: "1.17.6", Locations: []types.Location{{StartLine: 583, EndLine: 600}}},
{ID: "[email protected]", Name: "es-array-method-boxes-properly", Version: "1.0.0", Locations: []types.Location{{StartLine: 602, EndLine: 607}}},
{ID: "[email protected]", Name: "es-get-iterator", Version: "1.1.0", Locations: []types.Location{{StartLine: 609, EndLine: 622}}},
{ID: "[email protected]", Name: "es-to-primitive", Version: "1.2.1", Locations: []types.Location{{StartLine: 624, EndLine: 633}}},
{ID: "[email protected]", Name: "escape-html", Version: "1.0.3", Locations: []types.Location{{StartLine: 635, EndLine: 640}}},
{ID: "[email protected]", Name: "escape-string-regexp", Version: "4.0.0", Locations: []types.Location{{StartLine: 642, EndLine: 647}}},
{ID: "[email protected]", Name: "esprima", Version: "4.0.1", Locations: []types.Location{{StartLine: 649, EndLine: 657}}},
{ID: "[email protected]", Name: "etag", Version: "1.8.1", Locations: []types.Location{{StartLine: 659, EndLine: 664}}},
{ID: "[email protected]", Name: "express", Version: "4.17.1", Locations: []types.Location{{StartLine: 666, EndLine: 702}}},
{ID: "[email protected]", Name: "extend", Version: "3.0.2", Locations: []types.Location{{StartLine: 704, EndLine: 709}}},
{ID: "[email protected]", Name: "extsprintf", Version: "1.3.0", Locations: []types.Location{{StartLine: 711, EndLine: 716}}},
{ID: "[email protected]", Name: "fast-deep-equal", Version: "3.1.3", Locations: []types.Location{{StartLine: 718, EndLine: 723}}},
{ID: "[email protected]", Name: "fast-json-stable-stringify", Version: "2.1.0", Locations: []types.Location{{StartLine: 725, EndLine: 730}}},
{ID: "[email protected]", Name: "fill-range", Version: "7.0.1", Locations: []types.Location{{StartLine: 732, EndLine: 739}}},
{ID: "[email protected]", Name: "finalhandler", Version: "1.1.2", Locations: []types.Location{{StartLine: 741, EndLine: 754}}},
{ID: "[email protected]", Name: "find-up", Version: "5.0.0", Locations: []types.Location{{StartLine: 756, EndLine: 764}}},
{ID: "[email protected]", Name: "find-up", Version: "3.0.0", Locations: []types.Location{{StartLine: 766, EndLine: 773}}},
{ID: "[email protected]", Name: "flat", Version: "4.1.0", Locations: []types.Location{{StartLine: 775, EndLine: 784}}},
{ID: "[email protected]", Name: "follow-redirects", Version: "1.13.0", Locations: []types.Location{{StartLine: 786, EndLine: 791}}},
{ID: "[email protected]", Name: "forever-agent", Version: "0.6.1", Locations: []types.Location{{StartLine: 793, EndLine: 798}}},
{ID: "[email protected]", Name: "form-data", Version: "2.3.3", Locations: []types.Location{{StartLine: 800, EndLine: 809}}},
{ID: "[email protected]", Name: "forwarded", Version: "0.1.2", Locations: []types.Location{{StartLine: 811, EndLine: 816}}},
{ID: "[email protected]", Name: "fresh", Version: "0.5.2", Locations: []types.Location{{StartLine: 818, EndLine: 823}}},
{ID: "[email protected]", Name: "fs-minipass", Version: "2.1.0", Locations: []types.Location{{StartLine: 825, EndLine: 832}}},
{ID: "[email protected]", Name: "fs.realpath", Version: "1.0.0", Locations: []types.Location{{StartLine: 834, EndLine: 839}}},
{ID: "[email protected]", Name: "fsevents", Version: "2.1.3", Locations: []types.Location{{StartLine: 850, EndLine: 857}}},
{ID: "[email protected]", Name: "function-bind", Version: "1.1.1", Locations: []types.Location{{StartLine: 859, EndLine: 864}}},
{ID: "[email protected]", Name: "gauge", Version: "2.7.4", Locations: []types.Location{{StartLine: 866, EndLine: 880}}},
{ID: "[email protected]", Name: "get-caller-file", Version: "2.0.5", Locations: []types.Location{{StartLine: 882, EndLine: 887}}},
{ID: "[email protected]", Name: "getpass", Version: "0.1.7", Locations: []types.Location{{StartLine: 889, EndLine: 896}}},
{ID: "[email protected]", Name: "glob-parent", Version: "5.1.1", Locations: []types.Location{{StartLine: 898, EndLine: 905}}},
{ID: "[email protected]", Name: "glob", Version: "7.1.6", Locations: []types.Location{{StartLine: 907, EndLine: 919}}},
{ID: "[email protected]", Name: "graceful-fs", Version: "4.2.4", Locations: []types.Location{{StartLine: 921, EndLine: 926}}},
{ID: "[email protected]", Name: "growl", Version: "1.10.5", Locations: []types.Location{{StartLine: 928, EndLine: 933}}},
{ID: "[email protected]", Name: "har-schema", Version: "2.0.0", Locations: []types.Location{{StartLine: 935, EndLine: 940}}},
{ID: "[email protected]", Name: "har-validator", Version: "5.1.5", Locations: []types.Location{{StartLine: 942, EndLine: 950}}},
{ID: "[email protected]", Name: "has-flag", Version: "4.0.0", Locations: []types.Location{{StartLine: 952, EndLine: 957}}},
{ID: "[email protected]", Name: "has-symbols", Version: "1.0.1", Locations: []types.Location{{StartLine: 959, EndLine: 964}}},
{ID: "[email protected]", Name: "has-unicode", Version: "2.0.1", Locations: []types.Location{{StartLine: 966, EndLine: 971}}},
{ID: "[email protected]", Name: "has", Version: "1.0.3", Locations: []types.Location{{StartLine: 973, EndLine: 980}}},
{ID: "[email protected]", Name: "he", Version: "1.2.0", Locations: []types.Location{{StartLine: 982, EndLine: 989}}},
{ID: "[email protected]", Name: "http-errors", Version: "1.7.2", Locations: []types.Location{{StartLine: 991, EndLine: 1002}}},
{ID: "[email protected]", Name: "http-errors", Version: "1.7.3", Locations: []types.Location{{StartLine: 1004, EndLine: 1015}}},
{ID: "[email protected]", Name: "http-signature", Version: "1.2.0", Locations: []types.Location{{StartLine: 1017, EndLine: 1026}}},
{ID: "[email protected]", Name: "iconv-lite", Version: "0.4.24", Locations: []types.Location{{StartLine: 1028, EndLine: 1035}}},
{ID: "[email protected]", Name: "inflight", Version: "1.0.6", Locations: []types.Location{{StartLine: 1037, EndLine: 1045}}},
{ID: "[email protected]", Name: "inherits", Version: "2.0.4", Locations: []types.Location{{StartLine: 1047, EndLine: 1052}}},
{ID: "[email protected]", Name: "inherits", Version: "2.0.3", Locations: []types.Location{{StartLine: 1054, EndLine: 1059}}},
{ID: "[email protected]", Name: "ipaddr.js", Version: "1.9.1", Locations: []types.Location{{StartLine: 1061, EndLine: 1066}}},
{ID: "[email protected]", Name: "is-arguments", Version: "1.0.4", Locations: []types.Location{{StartLine: 1068, EndLine: 1073}}},
{ID: "[email protected]", Name: "is-binary-path", Version: "2.1.0", Locations: []types.Location{{StartLine: 1075, EndLine: 1082}}},
{ID: "[email protected]", Name: "is-buffer", Version: "2.0.4", Locations: []types.Location{{StartLine: 1084, EndLine: 1089}}},
{ID: "[email protected]", Name: "is-callable", Version: "1.2.0", Locations: []types.Location{{StartLine: 1091, EndLine: 1096}}},
{ID: "[email protected]", Name: "is-date-object", Version: "1.0.2", Locations: []types.Location{{StartLine: 1098, EndLine: 1103}}},
{ID: "[email protected]", Name: "is-extglob", Version: "2.1.1", Locations: []types.Location{{StartLine: 1105, EndLine: 1110}}},
{ID: "[email protected]", Name: "is-fullwidth-code-point", Version: "1.0.0", Locations: []types.Location{{StartLine: 1112, EndLine: 1119}}},
{ID: "[email protected]", Name: "is-fullwidth-code-point", Version: "2.0.0", Locations: []types.Location{{StartLine: 1121, EndLine: 1126}}},
{ID: "[email protected]", Name: "is-glob", Version: "4.0.1", Locations: []types.Location{{StartLine: 1128, EndLine: 1135}}},
{ID: "[email protected]", Name: "is-map", Version: "2.0.1", Locations: []types.Location{{StartLine: 1137, EndLine: 1142}}},
{ID: "[email protected]", Name: "is-number", Version: "7.0.0", Locations: []types.Location{{StartLine: 1144, EndLine: 1149}}},
{ID: "[email protected]", Name: "is-plain-obj", Version: "1.1.0", Locations: []types.Location{{StartLine: 1151, EndLine: 1156}}},
{ID: "[email protected]", Name: "is-regex", Version: "1.1.1", Locations: []types.Location{{StartLine: 1158, EndLine: 1165}}},
{ID: "[email protected]", Name: "is-set", Version: "2.0.1", Locations: []types.Location{{StartLine: 1167, EndLine: 1172}}},
{ID: "[email protected]", Name: "is-string", Version: "1.0.5", Locations: []types.Location{{StartLine: 1174, EndLine: 1179}}},
{ID: "[email protected]", Name: "is-symbol", Version: "1.0.3", Locations: []types.Location{{StartLine: 1181, EndLine: 1188}}},
{ID: "[email protected]", Name: "is-typedarray", Version: "1.0.0", Locations: []types.Location{{StartLine: 1190, EndLine: 1195}}},
{ID: "[email protected]", Name: "isarray", Version: "2.0.5", Locations: []types.Location{{StartLine: 1197, EndLine: 1202}}},
{ID: "[email protected]", Name: "isarray", Version: "1.0.0", Locations: []types.Location{{StartLine: 1204, EndLine: 1209}}},
{ID: "[email protected]", Name: "isexe", Version: "2.0.0", Locations: []types.Location{{StartLine: 1211, EndLine: 1216}}},
{ID: "[email protected]", Name: "isstream", Version: "0.1.2", Locations: []types.Location{{StartLine: 1218, EndLine: 1223}}},
{ID: "[email protected]", Name: "iterate-iterator", Version: "1.0.1", Locations: []types.Location{{StartLine: 1225, EndLine: 1230}}},
{ID: "[email protected]", Name: "iterate-value", Version: "1.0.2", Locations: []types.Location{{StartLine: 1232, EndLine: 1240}}},
{ID: "[email protected]", Name: "jquery", Version: "3.5.1", Locations: []types.Location{{StartLine: 1242, EndLine: 1247}}},
{ID: "[email protected]", Name: "js-tokens", Version: "4.0.0", Locations: []types.Location{{StartLine: 1249, EndLine: 1254}}},
{ID: "[email protected]", Name: "js-yaml", Version: "3.14.0", Locations: []types.Location{{StartLine: 1256, EndLine: 1266}}},
{ID: "[email protected]", Name: "jsbn", Version: "0.1.1", Locations: []types.Location{{StartLine: 1268, EndLine: 1273}}},
{ID: "[email protected]", Name: "json-schema-traverse", Version: "0.4.1", Locations: []types.Location{{StartLine: 1275, EndLine: 1280}}},
{ID: "[email protected]", Name: "json-schema", Version: "0.2.3", Locations: []types.Location{{StartLine: 1282, EndLine: 1287}}},
{ID: "[email protected]", Name: "json-stringify-safe", Version: "5.0.1", Locations: []types.Location{{StartLine: 1289, EndLine: 1294}}},
{ID: "[email protected]", Name: "jsprim", Version: "1.4.1", Locations: []types.Location{{StartLine: 1296, EndLine: 1306}}},
{ID: "[email protected]", Name: "locate-path", Version: "3.0.0", Locations: []types.Location{{StartLine: 1308, EndLine: 1316}}},
{ID: "[email protected]", Name: "locate-path", Version: "6.0.0", Locations: []types.Location{{StartLine: 1318, EndLine: 1325}}},
{ID: "[email protected]", Name: "lodash", Version: "4.17.20", Locations: []types.Location{{StartLine: 1327, EndLine: 1332}}},
{ID: "[email protected]", Name: "log-symbols", Version: "4.0.0", Locations: []types.Location{{StartLine: 1334, EndLine: 1341}}},
{ID: "[email protected]", Name: "loose-envify", Version: "1.4.0", Locations: []types.Location{{StartLine: 1343, EndLine: 1352}}},
{ID: "[email protected]", Name: "media-typer", Version: "0.3.0", Locations: []types.Location{{StartLine: 1354, EndLine: 1359}}},
{ID: "[email protected]", Name: "merge-descriptors", Version: "1.0.1", Locations: []types.Location{{StartLine: 1361, EndLine: 1366}}},
{ID: "[email protected]", Name: "methods", Version: "1.1.2", Locations: []types.Location{{StartLine: 1368, EndLine: 1373}}},
{ID: "[email protected]", Name: "mime-db", Version: "1.44.0", Locations: []types.Location{{StartLine: 1375, EndLine: 1380}}},
{ID: "[email protected]", Name: "mime-types", Version: "2.1.27", Locations: []types.Location{{StartLine: 1382, EndLine: 1389}}},
{ID: "[email protected]", Name: "mime", Version: "1.6.0", Locations: []types.Location{{StartLine: 1391, EndLine: 1398}}},
{ID: "[email protected]", Name: "minimatch", Version: "3.0.4", Locations: []types.Location{{StartLine: 1400, EndLine: 1407}}},
{ID: "[email protected]", Name: "minipass", Version: "3.1.3", Locations: []types.Location{{StartLine: 1409, EndLine: 1416}}},
{ID: "[email protected]", Name: "minizlib", Version: "2.1.2", Locations: []types.Location{{StartLine: 1418, EndLine: 1426}}},
{ID: "[email protected]", Name: "mkdirp", Version: "1.0.4", Locations: []types.Location{{StartLine: 1428, EndLine: 1435}}},
{ID: "[email protected]", Name: "mocha", Version: "8.1.3", Locations: []types.Location{{StartLine: 1437, EndLine: 1471}}},
{ID: "[email protected]", Name: "ms", Version: "2.0.0", Locations: []types.Location{{StartLine: 1473, EndLine: 1478}}},
{ID: "[email protected]", Name: "ms", Version: "2.1.1", Locations: []types.Location{{StartLine: 1480, EndLine: 1485}}},
{ID: "[email protected]", Name: "ms", Version: "2.1.2", Locations: []types.Location{{StartLine: 1487, EndLine: 1492}}},
{ID: "[email protected]", Name: "negotiator", Version: "0.6.2", Locations: []types.Location{{StartLine: 1494, EndLine: 1499}}},
{ID: "[email protected]", Name: "node-gyp", Version: "7.1.0", Locations: []types.Location{{StartLine: 1501, EndLine: 1519}}},
{ID: "[email protected]", Name: "nopt", Version: "4.0.3", Locations: []types.Location{{StartLine: 1521, EndLine: 1531}}},
{ID: "[email protected]", Name: "normalize-path", Version: "3.0.0", Locations: []types.Location{{StartLine: 1533, EndLine: 1538}}},
{ID: "[email protected]", Name: "npmlog", Version: "4.1.2", Locations: []types.Location{{StartLine: 1540, EndLine: 1550}}},
{ID: "[email protected]", Name: "number-is-nan", Version: "1.0.1", Locations: []types.Location{{StartLine: 1552, EndLine: 1557}}},
{ID: "[email protected]", Name: "oauth-sign", Version: "0.9.0", Locations: []types.Location{{StartLine: 1559, EndLine: 1564}}},
{ID: "[email protected]", Name: "object-assign", Version: "4.1.1", Locations: []types.Location{{StartLine: 1566, EndLine: 1571}}},
{ID: "[email protected]", Name: "object-inspect", Version: "1.8.0", Locations: []types.Location{{StartLine: 1573, EndLine: 1578}}},
{ID: "[email protected]", Name: "object-keys", Version: "1.1.1", Locations: []types.Location{{StartLine: 1580, EndLine: 1585}}},
{ID: "[email protected]", Name: "object.assign", Version: "4.1.0", Locations: []types.Location{{StartLine: 1587, EndLine: 1597}}},
{ID: "[email protected]", Name: "on-finished", Version: "2.3.0", Locations: []types.Location{{StartLine: 1599, EndLine: 1606}}},
{ID: "[email protected]", Name: "once", Version: "1.4.0", Locations: []types.Location{{StartLine: 1608, EndLine: 1615}}},
{ID: "[email protected]", Name: "os-homedir", Version: "1.0.2", Locations: []types.Location{{StartLine: 1617, EndLine: 1622}}},
{ID: "[email protected]", Name: "os-tmpdir", Version: "1.0.2", Locations: []types.Location{{StartLine: 1624, EndLine: 1629}}},
{ID: "[email protected]", Name: "osenv", Version: "0.1.5", Locations: []types.Location{{StartLine: 1631, EndLine: 1639}}},
{ID: "[email protected]", Name: "p-limit", Version: "2.3.0", Locations: []types.Location{{StartLine: 1641, EndLine: 1648}}},
{ID: "[email protected]", Name: "p-limit", Version: "3.0.2", Locations: []types.Location{{StartLine: 1650, EndLine: 1657}}},
{ID: "[email protected]", Name: "p-locate", Version: "3.0.0", Locations: []types.Location{{StartLine: 1659, EndLine: 1666}}},
{ID: "[email protected]", Name: "p-locate", Version: "5.0.0", Locations: []types.Location{{StartLine: 1668, EndLine: 1675}}},
{ID: "[email protected]", Name: "p-try", Version: "2.2.0", Locations: []types.Location{{StartLine: 1677, EndLine: 1682}}},
{ID: "[email protected]", Name: "parseurl", Version: "1.3.3", Locations: []types.Location{{StartLine: 1684, EndLine: 1689}}},
{ID: "[email protected]", Name: "path-exists", Version: "3.0.0", Locations: []types.Location{{StartLine: 1691, EndLine: 1696}}},
{ID: "[email protected]", Name: "path-exists", Version: "4.0.0", Locations: []types.Location{{StartLine: 1698, EndLine: 1703}}},
{ID: "[email protected]", Name: "path-is-absolute", Version: "1.0.1", Locations: []types.Location{{StartLine: 1705, EndLine: 1710}}},
{ID: "[email protected]", Name: "path-to-regexp", Version: "0.1.7", Locations: []types.Location{{StartLine: 1712, EndLine: 1717}}},
{ID: "[email protected]", Name: "performance-now", Version: "2.1.0", Locations: []types.Location{{StartLine: 1719, EndLine: 1724}}},
{ID: "[email protected]", Name: "picomatch", Version: "2.2.2", Locations: []types.Location{{StartLine: 1726, EndLine: 1731}}},
{ID: "[email protected]", Name: "process-nextick-args", Version: "2.0.1", Locations: []types.Location{{StartLine: 1733, EndLine: 1738}}},
{ID: "[email protected]", Name: "promise.allsettled", Version: "1.0.2", Locations: []types.Location{{StartLine: 1740, EndLine: 1751}}},
{ID: "[email protected]", Name: "promise", Version: "8.1.0", Locations: []types.Location{{StartLine: 1753, EndLine: 1760}}},
{ID: "[email protected]", Name: "prop-types", Version: "15.7.2", Locations: []types.Location{{StartLine: 1762, EndLine: 1771}}},
{ID: "[email protected]", Name: "proxy-addr", Version: "2.0.6", Locations: []types.Location{{StartLine: 1773, EndLine: 1781}}},
{ID: "[email protected]", Name: "psl", Version: "1.8.0", Locations: []types.Location{{StartLine: 1783, EndLine: 1788}}},
{ID: "[email protected]", Name: "punycode", Version: "2.1.1", Locations: []types.Location{{StartLine: 1790, EndLine: 1795}}},
{ID: "[email protected]", Name: "qs", Version: "6.7.0", Locations: []types.Location{{StartLine: 1797, EndLine: 1802}}},
{ID: "[email protected]", Name: "qs", Version: "6.5.2", Locations: []types.Location{{StartLine: 1804, EndLine: 1809}}},
{ID: "[email protected]", Name: "randombytes", Version: "2.1.0", Locations: []types.Location{{StartLine: 1811, EndLine: 1818}}},
{ID: "[email protected]", Name: "range-parser", Version: "1.2.1", Locations: []types.Location{{StartLine: 1820, EndLine: 1825}}},
{ID: "[email protected]", Name: "raw-body", Version: "2.4.0", Locations: []types.Location{{StartLine: 1827, EndLine: 1837}}},
{ID: "[email protected]", Name: "react-is", Version: "16.13.1", Locations: []types.Location{{StartLine: 1839, EndLine: 1844}}},
{ID: "[email protected]", Name: "react", Version: "16.13.1", Locations: []types.Location{{StartLine: 1846, EndLine: 1855}}},
{ID: "[email protected]", Name: "readable-stream", Version: "2.3.7", Locations: []types.Location{{StartLine: 1857, EndLine: 1870}}},
{ID: "[email protected]", Name: "readdirp", Version: "3.4.0", Locations: []types.Location{{StartLine: 1872, EndLine: 1879}}},
{ID: "[email protected]", Name: "redux", Version: "4.0.5", Locations: []types.Location{{StartLine: 1881, EndLine: 1889}}},
{ID: "[email protected]", Name: "request", Version: "2.88.2", Locations: []types.Location{{StartLine: 1891, EndLine: 1917}}},
{ID: "[email protected]", Name: "require-directory", Version: "2.1.1", Locations: []types.Location{{StartLine: 1919, EndLine: 1924}}},
{ID: "[email protected]", Name: "require-main-filename", Version: "2.0.0", Locations: []types.Location{{StartLine: 1926, EndLine: 1931}}},
{ID: "[email protected]", Name: "rimraf", Version: "2.7.1", Locations: []types.Location{{StartLine: 1933, EndLine: 1942}}},
{ID: "[email protected]", Name: "safe-buffer", Version: "5.1.2", Locations: []types.Location{{StartLine: 1944, EndLine: 1949}}},
{ID: "[email protected]", Name: "safe-buffer", Version: "5.2.1", Locations: []types.Location{{StartLine: 1951, EndLine: 1956}}},
{ID: "[email protected]", Name: "safer-buffer", Version: "2.1.2", Locations: []types.Location{{StartLine: 1958, EndLine: 1963}}},
{ID: "[email protected]", Name: "semver", Version: "7.3.2", Locations: []types.Location{{StartLine: 1965, EndLine: 1972}}},
{ID: "[email protected]", Name: "send", Version: "0.17.1", Locations: []types.Location{{StartLine: 1974, EndLine: 1993}}},
{ID: "[email protected]", Name: "serialize-javascript", Version: "4.0.0", Locations: []types.Location{{StartLine: 1995, EndLine: 2002}}},
{ID: "[email protected]", Name: "serve-static", Version: "1.14.1", Locations: []types.Location{{StartLine: 2004, EndLine: 2014}}},
{ID: "[email protected]", Name: "set-blocking", Version: "2.0.0", Locations: []types.Location{{StartLine: 2016, EndLine: 2021}}},
{ID: "[email protected]", Name: "setprototypeof", Version: "1.1.1", Locations: []types.Location{{StartLine: 2023, EndLine: 2028}}},
{ID: "[email protected]", Name: "signal-exit", Version: "3.0.3", Locations: []types.Location{{StartLine: 2030, EndLine: 2035}}},
{ID: "[email protected]", Name: "sprintf-js", Version: "1.0.3", Locations: []types.Location{{StartLine: 2037, EndLine: 2042}}},
{ID: "[email protected]", Name: "sshpk", Version: "1.16.1", Locations: []types.Location{{StartLine: 2044, EndLine: 2063}}},
{ID: "[email protected]", Name: "statuses", Version: "1.5.0", Locations: []types.Location{{StartLine: 2065, EndLine: 2070}}},
{ID: "[email protected]", Name: "string-width", Version: "1.0.2", Locations: []types.Location{{StartLine: 2072, EndLine: 2081}}},
{ID: "[email protected]", Name: "string-width", Version: "2.1.1", Locations: []types.Location{{StartLine: 2083, EndLine: 2091}}},
{ID: "[email protected]", Name: "string-width", Version: "3.1.0", Locations: []types.Location{{StartLine: 2093, EndLine: 2102}}},
{ID: "[email protected]", Name: "string.prototype.trimend", Version: "1.0.1", Locations: []types.Location{{StartLine: 2104, EndLine: 2112}}},
{ID: "[email protected]", Name: "string.prototype.trimstart", Version: "1.0.1", Locations: []types.Location{{StartLine: 2114, EndLine: 2122}}},
{ID: "[email protected]", Name: "string_decoder", Version: "1.1.1", Locations: []types.Location{{StartLine: 2124, EndLine: 2131}}},
{ID: "[email protected]", Name: "strip-ansi", Version: "3.0.1", Locations: []types.Location{{StartLine: 2133, EndLine: 2140}}},
{ID: "[email protected]", Name: "strip-ansi", Version: "4.0.0", Locations: []types.Location{{StartLine: 2142, EndLine: 2149}}},
{ID: "[email protected]", Name: "strip-ansi", Version: "5.2.0", Locations: []types.Location{{StartLine: 2151, EndLine: 2158}}},
{ID: "[email protected]", Name: "strip-json-comments", Version: "3.0.1", Locations: []types.Location{{StartLine: 2160, EndLine: 2165}}},
{ID: "[email protected]", Name: "supports-color", Version: "7.1.0", Locations: []types.Location{{StartLine: 2167, EndLine: 2174}}},
{ID: "[email protected]", Name: "symbol-observable", Version: "1.2.0", Locations: []types.Location{{StartLine: 2176, EndLine: 2181}}},
{ID: "[email protected]", Name: "tar", Version: "6.0.5", Locations: []types.Location{{StartLine: 2183, EndLine: 2195}}},
{ID: "[email protected]", Name: "to-regex-range", Version: "5.0.1", Locations: []types.Location{{StartLine: 2197, EndLine: 2204}}},
{ID: "[email protected]", Name: "toidentifier", Version: "1.0.0", Locations: []types.Location{{StartLine: 2206, EndLine: 2211}}},
{ID: "[email protected]", Name: "tough-cookie", Version: "2.5.0", Locations: []types.Location{{StartLine: 2213, EndLine: 2221}}},
{ID: "[email protected]", Name: "tunnel-agent", Version: "0.6.0", Locations: []types.Location{{StartLine: 2223, EndLine: 2230}}},
{ID: "[email protected]", Name: "tweetnacl", Version: "0.14.5", Locations: []types.Location{{StartLine: 2232, EndLine: 2237}}},
{ID: "[email protected]", Name: "type-is", Version: "1.6.18", Locations: []types.Location{{StartLine: 2239, EndLine: 2247}}},
{ID: "[email protected]", Name: "unpipe", Version: "1.0.0", Locations: []types.Location{{StartLine: 2249, EndLine: 2254}}},
{ID: "[email protected]", Name: "uri-js", Version: "4.4.0", Locations: []types.Location{{StartLine: 2256, EndLine: 2263}}},
{ID: "[email protected]", Name: "util-deprecate", Version: "1.0.2", Locations: []types.Location{{StartLine: 2265, EndLine: 2270}}},
{ID: "[email protected]", Name: "utils-merge", Version: "1.0.1", Locations: []types.Location{{StartLine: 2272, EndLine: 2277}}},
{ID: "[email protected]", Name: "uuid", Version: "3.4.0", Locations: []types.Location{{StartLine: 2279, EndLine: 2286}}},
{ID: "[email protected]", Name: "vary", Version: "1.1.2", Locations: []types.Location{{StartLine: 2288, EndLine: 2293}}},
{ID: "[email protected]", Name: "verror", Version: "1.10.0", Locations: []types.Location{{StartLine: 2295, EndLine: 2304}}},
{ID: "[email protected]", Name: "vue", Version: "2.6.12", Locations: []types.Location{{StartLine: 2306, EndLine: 2311}}},
{ID: "[email protected]", Name: "which-module", Version: "2.0.0", Locations: []types.Location{{StartLine: 2313, EndLine: 2318}}},
{ID: "[email protected]", Name: "which", Version: "2.0.2", Locations: []types.Location{{StartLine: 2320, EndLine: 2329}}},
{ID: "[email protected]", Name: "wide-align", Version: "1.1.3", Locations: []types.Location{{StartLine: 2331, EndLine: 2338}}},
{ID: "[email protected]", Name: "workerpool", Version: "6.0.0", Locations: []types.Location{{StartLine: 2340, EndLine: 2345}}},
{ID: "[email protected]", Name: "wrap-ansi", Version: "5.1.0", Locations: []types.Location{{StartLine: 2347, EndLine: 2356}}},
{ID: "[email protected]", Name: "wrappy", Version: "1.0.2", Locations: []types.Location{{StartLine: 2358, EndLine: 2363}}},
{ID: "[email protected]", Name: "y18n", Version: "4.0.0", Locations: []types.Location{{StartLine: 2365, EndLine: 2370}}},
{ID: "[email protected]", Name: "yallist", Version: "4.0.0", Locations: []types.Location{{StartLine: 2372, EndLine: 2377}}},
{ID: "[email protected]", Name: "yargs-parser", Version: "13.1.2", Locations: []types.Location{{StartLine: 2379, EndLine: 2387}}},
{ID: "[email protected]", Name: "yargs-parser", Version: "15.0.1", Locations: []types.Location{{StartLine: 2389, EndLine: 2397}}},
{ID: "[email protected]", Name: "yargs-unparser", Version: "1.6.1", Locations: []types.Location{{StartLine: 2399, EndLine: 2410}}},
{ID: "[email protected]", Name: "yargs", Version: "13.3.2", Locations: []types.Location{{StartLine: 2412, EndLine: 2428}}},
{ID: "[email protected]", Name: "yargs", Version: "14.2.3", Locations: []types.Location{{StartLine: 2430, EndLine: 2447}}},
}
// ... and
// node test_deps_generator/index.js yarn.lock
yarnV2ManyDeps = []types.Dependency{
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"@types/[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
{
ID: "[email protected]",
DependsOn: []string{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
},
},
}
// docker run --name node --rm -it node:16-alpine sh
// mkdir app && cd app
// yarn init -y
// yarn add jquery
// npm install
yarnWithNpm = []types.Library{
{ID: "[email protected]", Name: "jquery", Version: "3.6.0", Locations: []types.Location{{StartLine: 1, EndLine: 4}}},
}
yarnBadProtocol = []types.Library{
{ID: "[email protected]", Name: "jquery", Version: "3.4.1", Locations: []types.Location{{StartLine: 4, EndLine: 7}}},
}
)
<file_sep>/pkg/golang/mod/parse_test.go
package mod
import (
"os"
"sort"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
func TestParse(t *testing.T) {
tests := []struct {
name string
file string
replace bool
want []types.Library
}{
{
name: "normal",
file: "testdata/normal/go.mod",
replace: true,
want: GoModNormal,
},
{
name: "without go version",
file: "testdata/no-go-version/go.mod",
replace: true,
want: GoModNoGoVersion,
},
{
name: "replace",
file: "testdata/replaced/go.mod",
replace: true,
want: GoModReplaced,
},
{
name: "no replace",
file: "testdata/replaced/go.mod",
replace: false,
want: GoModUnreplaced,
},
{
name: "replace with version",
file: "testdata/replaced-with-version/go.mod",
replace: true,
want: GoModReplacedWithVersion,
},
{
name: "replaced with version mismatch",
file: "testdata/replaced-with-version-mismatch/go.mod",
replace: true,
want: GoModReplacedWithVersionMismatch,
},
{
name: "replaced with local path",
file: "testdata/replaced-with-local-path/go.mod",
replace: true,
want: GoModReplacedWithLocalPath,
},
{
name: "replaced with local path and version",
file: "testdata/replaced-with-local-path-and-version/go.mod",
replace: true,
want: GoModReplacedWithLocalPathAndVersion,
},
{
name: "replaced with local path and version, mismatch",
file: "testdata/replaced-with-local-path-and-version-mismatch/go.mod",
replace: true,
want: GoModReplacedWithLocalPathAndVersionMismatch,
},
{
name: "go 1.16",
file: "testdata/go116/go.mod",
replace: true,
want: GoMod116,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f, err := os.Open(tt.file)
require.NoError(t, err)
got, _, err := NewParser(tt.replace).Parse(f)
require.NoError(t, err)
sort.Slice(got, func(i, j int) bool {
return got[i].Name < got[j].Name
})
sort.Slice(tt.want, func(i, j int) bool {
return tt.want[i].Name < tt.want[j].Name
})
assert.Equal(t, tt.want, got)
})
}
}
func TestModuleID(t *testing.T) {
type args struct {
name string
version string
}
tests := []struct {
name string
args args
want string
}{
{
name: "normal",
args: args{
name: "github.com/aquasecurity/trivy",
version: "0.38.0",
},
want: "github.com/aquasecurity/[email protected]",
},
{
name: "pseudo version",
args: args{
name: "github.com/aquasecurity/go-dep-parser",
version: "0.0.0-20230130190635-5e31092b0621",
},
want: "github.com/aquasecurity/[email protected]",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equalf(t, tt.want, ModuleID(tt.args.name, tt.args.version), "ModuleID(%v, %v)", tt.args.name, tt.args.version)
})
}
}
<file_sep>/pkg/c/conan/parse_test.go
package conan_test
import (
"os"
"sort"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/aquasecurity/go-dep-parser/pkg/c/conan"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
func TestParse(t *testing.T) {
tests := []struct {
name string
inputFile string // Test input file
wantLibs []types.Library
wantDeps []types.Dependency
}{
{
name: "happy path",
inputFile: "testdata/happy.lock",
wantLibs: []types.Library{
{
ID: "pkga/0.0.1",
Name: "pkga",
Version: "0.0.1",
Locations: []types.Location{
{
StartLine: 13,
EndLine: 22,
},
},
},
{
ID: "pkgb/system",
Name: "pkgb",
Version: "system",
Indirect: true,
Locations: []types.Location{
{
StartLine: 23,
EndLine: 29,
},
},
},
{
ID: "pkgc/0.1.1",
Name: "pkgc",
Version: "0.1.1",
Locations: []types.Location{
{
StartLine: 30,
EndLine: 35,
},
},
},
},
wantDeps: []types.Dependency{
{
ID: "pkga/0.0.1",
DependsOn: []string{
"pkgb/system",
},
},
},
},
{
name: "happy path. lock file with revisions support",
inputFile: "testdata/happy2.lock",
wantLibs: []types.Library{
{
ID: "openssl/3.0.3",
Name: "openssl",
Version: "3.0.3",
Locations: []types.Location{
{
StartLine: 12,
EndLine: 22,
},
},
},
{
ID: "zlib/1.2.12",
Name: "zlib",
Version: "1.2.12",
Indirect: true,
Locations: []types.Location{
{
StartLine: 23,
EndLine: 30,
},
},
},
},
wantDeps: []types.Dependency{
{
ID: "openssl/3.0.3",
DependsOn: []string{
"zlib/1.2.12",
},
},
},
},
{
name: "happy path. lock file without dependencies",
inputFile: "testdata/empty.lock",
},
{
name: "sad path. wrong ref format",
inputFile: "testdata/sad.lock",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f, err := os.Open(tt.inputFile)
require.NoError(t, err)
defer f.Close()
gotLibs, gotDeps, err := conan.NewParser().Parse(f)
require.NoError(t, err)
sort.Slice(gotLibs, func(i, j int) bool {
ret := strings.Compare(gotLibs[i].Name, gotLibs[j].Name)
if ret != 0 {
return ret < 0
}
return gotLibs[i].Version < gotLibs[j].Version
})
assert.Equal(t, tt.wantLibs, gotLibs)
assert.Equal(t, tt.wantDeps, gotDeps)
})
}
}
<file_sep>/pkg/python/poetry/parse.go
package poetry
import (
"sort"
"strings"
"github.com/BurntSushi/toml"
"golang.org/x/xerrors"
dio "github.com/aquasecurity/go-dep-parser/pkg/io"
"github.com/aquasecurity/go-dep-parser/pkg/log"
"github.com/aquasecurity/go-dep-parser/pkg/types"
"github.com/aquasecurity/go-dep-parser/pkg/utils"
version "github.com/aquasecurity/go-pep440-version"
)
type Lockfile struct {
Packages []struct {
Category string `toml:"category"`
Description string `toml:"description"`
Marker string `toml:"marker,omitempty"`
Name string `toml:"name"`
Optional bool `toml:"optional"`
PythonVersions string `toml:"python-versions"`
Version string `toml:"version"`
Dependencies map[string]interface{} `toml:"dependencies"`
Metadata interface{}
} `toml:"package"`
}
type Parser struct{}
func NewParser() types.Parser {
return &Parser{}
}
func (p *Parser) Parse(r dio.ReadSeekerAt) ([]types.Library, []types.Dependency, error) {
var lockfile Lockfile
if _, err := toml.NewDecoder(r).Decode(&lockfile); err != nil {
return nil, nil, xerrors.Errorf("failed to decode poetry.lock: %w", err)
}
// Keep all installed versions
libVersions := parseVersions(lockfile)
var libs []types.Library
var deps []types.Dependency
for _, pkg := range lockfile.Packages {
if pkg.Category == "dev" {
continue
}
pkgID := utils.PackageID(pkg.Name, pkg.Version)
libs = append(libs, types.Library{
ID: pkgID,
Name: pkg.Name,
Version: pkg.Version,
})
dependsOn := parseDependencies(pkg.Dependencies, libVersions)
if len(dependsOn) != 0 {
deps = append(deps, types.Dependency{
ID: pkgID,
DependsOn: dependsOn,
})
}
}
return libs, deps, nil
}
// parseVersions stores all installed versions of libraries for use in dependsOn
// as the dependencies of libraries use version range.
func parseVersions(lockfile Lockfile) map[string][]string {
libVersions := map[string][]string{}
for _, pkg := range lockfile.Packages {
if pkg.Category == "dev" {
continue
}
if vers, ok := libVersions[pkg.Name]; ok {
libVersions[pkg.Name] = append(vers, pkg.Version)
} else {
libVersions[pkg.Name] = []string{pkg.Version}
}
}
return libVersions
}
func parseDependencies(deps map[string]any, libVersions map[string][]string) []string {
var dependsOn []string
for name, versRange := range deps {
if dep, err := parseDependency(name, versRange, libVersions); err != nil {
log.Logger.Debugf("failed to parse poetry dependency: %s", err)
} else if dep != "" {
dependsOn = append(dependsOn, dep)
}
}
sort.Slice(dependsOn, func(i, j int) bool {
return dependsOn[i] < dependsOn[j]
})
return dependsOn
}
func parseDependency(name string, versRange any, libVersions map[string][]string) (string, error) {
name = normalizePkgName(name)
vers, ok := libVersions[name]
if !ok {
return "", xerrors.Errorf("no version found for %q", name)
}
for _, ver := range vers {
var vRange string
switch r := versRange.(type) {
case string:
vRange = r
case map[string]interface{}:
for k, v := range r {
if k == "version" {
vRange = v.(string)
}
}
}
if matched, err := matchVersion(ver, vRange); err != nil {
return "", xerrors.Errorf("failed to match version for %s: %w", name, err)
} else if matched {
return utils.PackageID(name, ver), nil
}
}
return "", xerrors.Errorf("no matched version found for %q", name)
}
// matchVersion checks if the package version satisfies the given constraint.
func matchVersion(currentVersion, constraint string) (bool, error) {
v, err := version.Parse(currentVersion)
if err != nil {
return false, xerrors.Errorf("python version error (%s): %s", currentVersion, err)
}
c, err := version.NewSpecifiers(constraint, version.WithPreRelease(true))
if err != nil {
return false, xerrors.Errorf("python constraint error (%s): %s", constraint, err)
}
return c.Check(v), nil
}
func normalizePkgName(name string) string {
// The package names don't use `_`, `.` or upper case, but dependency names can contain them.
// We need to normalize those names.
name = strings.ToLower(name) // e.g. https://github.com/python-poetry/poetry/blob/c8945eb110aeda611cc6721565d7ad0c657d453a/poetry.lock#L819
name = strings.ReplaceAll(name, "_", "-") // e.g. https://github.com/python-poetry/poetry/blob/c8945eb110aeda611cc6721565d7ad0c657d453a/poetry.lock#L50
name = strings.ReplaceAll(name, ".", "-") // e.g. https://github.com/python-poetry/poetry/blob/c8945eb110aeda611cc6721565d7ad0c657d453a/poetry.lock#L816
return name
}
<file_sep>/pkg/golang/sum/parse.go
package sum
import (
"bufio"
"strings"
"golang.org/x/xerrors"
"github.com/aquasecurity/go-dep-parser/pkg/golang/mod"
dio "github.com/aquasecurity/go-dep-parser/pkg/io"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
type Parser struct{}
func NewParser() types.Parser {
return &Parser{}
}
// Parse parses a go.sum file
func (p *Parser) Parse(r dio.ReadSeekerAt) ([]types.Library, []types.Dependency, error) {
var libs []types.Library
uniqueLibs := make(map[string]string)
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
s := strings.Fields(line)
if len(s) < 2 {
continue
}
// go.sum records and sorts all non-major versions
// with the latest version as last entry
uniqueLibs[s[0]] = strings.TrimSuffix(strings.TrimPrefix(s[1], "v"), "/go.mod")
}
if err := scanner.Err(); err != nil {
return nil, nil, xerrors.Errorf("scan error: %w", err)
}
for k, v := range uniqueLibs {
libs = append(libs, types.Library{
ID: mod.ModuleID(k, v),
Name: k,
Version: v,
})
}
return libs, nil, nil
}
<file_sep>/pkg/golang/sum/parse_test.go
package sum
import (
"os"
"path"
"sort"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
func TestParse(t *testing.T) {
vectors := []struct {
file string
want []types.Library
}{
{
file: "testdata/gomod_normal.sum",
want: GoModNormal,
},
{
file: "testdata/gomod_emptyline.sum",
want: GoModEmptyLine,
},
{
file: "testdata/gomod_many.sum",
want: GoModMany,
},
{
file: "testdata/gomod_trivy.sum",
want: GoModTrivy,
},
}
for _, v := range vectors {
t.Run(path.Base(v.file), func(t *testing.T) {
f, err := os.Open(v.file)
require.NoError(t, err)
defer f.Close()
got, _, err := NewParser().Parse(f)
require.NoError(t, err)
for i := range got {
got[i].ID = "" // Not compare IDs, tested in mod.TestModuleID()
}
sort.Slice(got, func(i, j int) bool {
return got[i].Name < got[j].Name
})
sort.Slice(v.want, func(i, j int) bool {
return v.want[i].Name < v.want[j].Name
})
assert.Equal(t, v.want, got)
})
}
}
<file_sep>/pkg/gradle/lockfile/parse_test.go
package lockfile
import (
"os"
"sort"
"strings"
"testing"
"github.com/aquasecurity/go-dep-parser/pkg/types"
"github.com/stretchr/testify/assert"
)
func TestParser_Parse(t *testing.T) {
tests := []struct {
name string
inputFile string
want []types.Library
}{
{
name: "happy path",
inputFile: "testdata/happy.lockfile",
want: []types.Library{
{
Name: "cglib:cglib-nodep",
Version: "2.1.2",
},
{
Name: "org.springframework:spring-asm",
Version: "3.1.3.RELEASE",
},
{
Name: "org.springframework:spring-beans",
Version: "5.0.5.RELEASE",
},
},
},
{
name: "empty",
inputFile: "testdata/empty.lockfile",
want: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
parser := NewParser()
f, err := os.Open(tt.inputFile)
assert.NoError(t, err)
libs, _, _ := parser.Parse(f)
sortLibs(libs)
assert.Equal(t, tt.want, libs)
})
}
}
func sortLibs(libs []types.Library) {
sort.Slice(libs, func(i, j int) bool {
ret := strings.Compare(libs[i].Name, libs[j].Name)
if ret == 0 {
return libs[i].Version < libs[j].Version
}
return ret < 0
})
}
<file_sep>/pkg/java/pom/testdata/inherit-license/pom.xml
<project>
<modelVersion>4.0.0</modelVersion>
<packaging>pom</packaging>
<groupId>com.example.app</groupId>
<artifactId>my-app</artifactId>
<version>1.0.0</version>
<licenses>
<license>
<name>Apache-2.0</name>
<url>https://www.apache.org/licenses/LICENSE-2.0</url>
<distribution>repo</distribution>
</license>
</licenses>
</project><file_sep>/pkg/python/pip/testdata/requirement_exstras.txt
pyjwt[crypto]==2.1.0
celery[redis, pytest]==4.4.7<file_sep>/pkg/ruby/gemspec/testdata/malformed00.gemspec
# -*- encoding: utf-8 -*-
# ... REDACTED ...
# Wrong attribute value assignment.
Gem::Specification.new do |spec|
s.name = "async".freeze
s.version = "1.25.0"
# ... REDACTED ...
end
<file_sep>/pkg/golang/mod/testdata/go116/go.mod
module github.com/org/repo
go 1.16
require github.com/aquasecurity/go-dep-parser v0.0.0-20211224170007-df43bca6b6ff
require gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
<file_sep>/pkg/ruby/gemspec/parse.go
package gemspec
import (
"bufio"
"fmt"
"regexp"
"strings"
"golang.org/x/xerrors"
dio "github.com/aquasecurity/go-dep-parser/pkg/io"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
const specNewStr = "Gem::Specification.new"
var (
// Capture the variable name
// e.g. Gem::Specification.new do |s|
// => s
newVarRegexp = regexp.MustCompile(`\|(?P<var>.*)\|`)
// Capture the value of "name"
// e.g. s.name = "async".freeze
// => "async".freeze
nameRegexp = regexp.MustCompile(`\.name\s*=\s*(?P<name>\S+)`)
// Capture the value of "version"
// e.g. s.version = "1.2.3"
// => "1.2.3"
versionRegexp = regexp.MustCompile(`\.version\s*=\s*(?P<version>\S+)`)
// Capture the value of "license"
// e.g. s.license = "MIT"
// => "MIT"
licenseRegexp = regexp.MustCompile(`\.license\s*=\s*(?P<license>\S+)`)
// Capture the value of "licenses"
// e.g. s.license = ["MIT".freeze, "BSDL".freeze]
// => "MIT".freeze, "BSDL".freeze
licensesRegexp = regexp.MustCompile(`\.licenses\s*=\s*\[(?P<licenses>.+)\]`)
)
type Parser struct{}
func NewParser() types.Parser {
return &Parser{}
}
func (p *Parser) Parse(r dio.ReadSeekerAt) (libs []types.Library, deps []types.Dependency, err error) {
var newVar, name, version, license string
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if strings.Contains(line, specNewStr) {
newVar = findSubString(newVarRegexp, line, "var")
}
if newVar == "" {
continue
}
// Capture name, version, license, and licenses
switch {
case strings.HasPrefix(line, fmt.Sprintf("%s.name", newVar)):
// https://guides.rubygems.org/specification-reference/#name
name = findSubString(nameRegexp, line, "name")
name = trim(name)
case strings.HasPrefix(line, fmt.Sprintf("%s.version", newVar)):
// https://guides.rubygems.org/specification-reference/#version
version = findSubString(versionRegexp, line, "version")
version = trim(version)
case strings.HasPrefix(line, fmt.Sprintf("%s.licenses", newVar)):
// https://guides.rubygems.org/specification-reference/#licenses=
license = findSubString(licensesRegexp, line, "licenses")
license = parseLicenses(license)
case strings.HasPrefix(line, fmt.Sprintf("%s.license", newVar)):
// https://guides.rubygems.org/specification-reference/#license=
license = findSubString(licenseRegexp, line, "license")
license = trim(license)
}
// No need to iterate the loop anymore
if name != "" && version != "" && license != "" {
break
}
}
if err := scanner.Err(); err != nil {
return nil, nil, xerrors.Errorf("failed to parse gemspec: %w", err)
}
if name == "" || version == "" {
return nil, nil, xerrors.New("failed to parse gemspec")
}
return []types.Library{
{
Name: name,
Version: version,
License: license,
}}, nil, nil
}
func findSubString(re *regexp.Regexp, line, name string) string {
m := re.FindStringSubmatch(line)
if m == nil {
return ""
}
return m[re.SubexpIndex(name)]
}
// Trim single quotes, double quotes and ".freeze"
// e.g. "async".freeze => async
func trim(s string) string {
s = strings.TrimSpace(s)
s = strings.TrimSuffix(s, ".freeze")
return strings.Trim(s, `'"`)
}
func parseLicenses(s string) string {
// e.g. `"Ruby".freeze, "BSDL".freeze`
// => {"\"Ruby\".freeze", "\"BSDL\".freeze"}
ss := strings.Split(s, ",")
// e.g. {"\"Ruby\".freeze", "\"BSDL\".freeze"}
// => {"Ruby", "BSDL"}
var licenses []string
for _, l := range ss {
licenses = append(licenses, trim(l))
}
return strings.Join(licenses, ", ")
}
<file_sep>/pkg/java/pom/testdata/import-dependency-management/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>import</artifactId>
<version>2.0.0</version>
<packaging>pom</packaging>
<name>import</name>
<description>Import dependencyManagement</description>
<licenses>
<license>
<name>Apache 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.html</url>
<distribution>repo</distribution>
</license>
</licenses>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.example</groupId>
<artifactId>example-dependency-management</artifactId>
<version>2.2.2</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.example</groupId>
<artifactId>example-api</artifactId>
</dependency>
</dependencies>
</project>
<file_sep>/pkg/nodejs/pnpm/parse_test.go
package pnpm
import (
"os"
"sort"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
func TestParse(t *testing.T) {
tests := []struct {
name string
file string // Test input file
want []types.Library
wantDeps []types.Dependency
}{
{
name: "normal",
file: "testdata/pnpm-lock_normal.yaml",
want: pnpmNormal,
wantDeps: pnpmNormalDeps,
},
{
name: "with dev deps",
file: "testdata/pnpm-lock_with_dev.yaml",
want: pnpmWithDev,
wantDeps: pnpmWithDevDeps,
},
{
name: "many",
file: "testdata/pnpm-lock_many.yaml",
want: pnpmMany,
wantDeps: pnpmManyDeps,
},
{
name: "archives",
file: "testdata/pnpm-lock_archives.yaml",
want: pnpmArchives,
wantDeps: pnpmArchivesDeps,
},
{
name: "v6",
file: "testdata/pnpm-lock_v6.yaml",
want: pnpmV6,
wantDeps: pnpmV6Deps,
},
{
name: "v6 with dev deps",
file: "testdata/pnpm-lock_v6_with_dev.yaml",
want: pnpmV6WithDev,
wantDeps: pnpmV6WithDevDeps,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f, err := os.Open(tt.file)
require.NoError(t, err)
got, deps, err := NewParser().Parse(f)
require.NoError(t, err)
sortLibs(got)
sortLibs(tt.want)
assert.Equal(t, tt.want, got)
if tt.wantDeps != nil {
sortDeps(deps)
sortDeps(tt.wantDeps)
assert.Equal(t, tt.wantDeps, deps)
}
})
}
}
func sortDeps(deps []types.Dependency) {
sort.Slice(deps, func(i, j int) bool {
return strings.Compare(deps[i].ID, deps[j].ID) < 0
})
for i := range deps {
sort.Strings(deps[i].DependsOn)
}
}
func sortLibs(libs []types.Library) {
sort.Slice(libs, func(i, j int) bool {
ret := strings.Compare(libs[i].Name, libs[j].Name)
if ret == 0 {
return libs[i].Version < libs[j].Version
}
return ret < 0
})
}
func Test_parsePackage(t *testing.T) {
tests := []struct {
name string
lockFileVer float64
pkg string
wantName string
wantVersion string
}{
{
name: "v5 - relative path",
lockFileVer: 5.0,
pkg: "/lodash/4.17.10",
wantName: "lodash",
wantVersion: "4.17.10",
},
{
name: "v5 - registry",
lockFileVer: 5.0,
pkg: "registry.npmjs.org/lodash/4.17.10",
wantName: "lodash",
wantVersion: "4.17.10",
},
{
name: "v5 - relative path with slash",
lockFileVer: 5.0,
pkg: "/@babel/generator/7.21.9",
wantName: "@babel/generator",
wantVersion: "7.21.9",
},
{
name: "v5 - registry path with slash",
lockFileVer: 5.0,
pkg: "registry.npmjs.org/@babel/generator/7.21.9",
wantName: "@babel/generator",
wantVersion: "7.21.9",
},
{
name: "v5 - relative path with slash and peer deps",
lockFileVer: 5.0,
pkg: "/@babel/helper-compilation-targets/7.21.5_@[email protected]",
wantName: "@babel/helper-compilation-targets",
wantVersion: "7.21.5",
},
{
name: "v5 - relative path with underline and peer deps",
lockFileVer: 5.0,
pkg: "/lodash._baseclone/4.5.7_@[email protected]",
wantName: "lodash._baseclone",
wantVersion: "4.5.7",
},
{
name: "v5 - registry with slash and peer deps",
lockFileVer: 5.0,
pkg: "registry.npmjs.org/@babel/helper-compilation-targets/7.21.5_@[email protected]",
wantName: "@babel/helper-compilation-targets",
wantVersion: "7.21.5",
},
{
name: "v5 - relative path with wrong version",
lockFileVer: 5.0,
pkg: "/lodash/4-wrong",
wantName: "",
wantVersion: "",
},
{
name: "v6 - relative path",
lockFileVer: 6.0,
pkg: "/[email protected]",
wantName: "update-browserslist-db",
wantVersion: "1.0.11",
},
{
name: "v6 - registry",
lockFileVer: 6.0,
pkg: "registry.npmjs.org/[email protected]",
wantName: "lodash",
wantVersion: "4.17.10",
},
{
name: "v6 - relative path with slash",
lockFileVer: 6.0,
pkg: "/@babel/[email protected]",
wantName: "@babel/helper-annotate-as-pure",
wantVersion: "7.18.6",
},
{
name: "v6 - registry with slash",
lockFileVer: 6.0,
pkg: "registry.npmjs.org/@babel/[email protected]",
wantName: "@babel/helper-annotate-as-pure",
wantVersion: "7.18.6",
},
{
name: "v6 - relative path with slash and peer deps",
lockFileVer: 6.0,
pkg: "/@babel/[email protected](@babel/[email protected])",
wantName: "@babel/helper-compilation-targets",
wantVersion: "7.21.5",
},
{
name: "v6 - registry with slash and peer deps",
lockFileVer: 6.0,
pkg: "registry.npmjs.org/@babel/[email protected](@babel/[email protected])",
wantName: "@babel/helper-compilation-targets",
wantVersion: "7.21.5",
},
{
name: "v6 - relative path with wrong version",
lockFileVer: 6.0,
pkg: "/lodash@4-wrong",
wantName: "",
wantVersion: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotName, gotVersion := parsePackage(tt.pkg, tt.lockFileVer)
assert.Equal(t, tt.wantName, gotName)
assert.Equal(t, tt.wantVersion, gotVersion)
})
}
}
<file_sep>/pkg/golang/binary/parse.go
package binary
import (
"debug/buildinfo"
"strings"
"golang.org/x/xerrors"
dio "github.com/aquasecurity/go-dep-parser/pkg/io"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
var (
ErrUnrecognizedExe = xerrors.New("unrecognized executable format")
ErrNonGoBinary = xerrors.New("non go binary")
)
// convertError detects buildinfo.errUnrecognizedFormat and convert to
// ErrUnrecognizedExe and convert buildinfo.errNotGoExe to ErrNonGoBinary
func convertError(err error) error {
errText := err.Error()
if strings.HasSuffix(errText, "unrecognized file format") {
return ErrUnrecognizedExe
}
if strings.HasSuffix(errText, "not a Go executable") {
return ErrNonGoBinary
}
return err
}
type Parser struct{}
func NewParser() types.Parser {
return &Parser{}
}
// Parse scans file to try to report the Go and module versions.
func (p *Parser) Parse(r dio.ReadSeekerAt) ([]types.Library, []types.Dependency, error) {
info, err := buildinfo.Read(r)
if err != nil {
return nil, nil, convertError(err)
}
libs := make([]types.Library, 0, len(info.Deps))
for _, dep := range info.Deps {
// binaries with old go version may incorrectly add module in Deps
// In this case Path == "", Version == "Devel"
// we need to skip this
if dep.Path == "" {
continue
}
mod := dep
if dep.Replace != nil {
mod = dep.Replace
}
libs = append(libs, types.Library{
Name: mod.Path,
Version: mod.Version,
})
}
return libs, nil, nil
}
<file_sep>/pkg/dotnet/core_deps/parse_test.go
package core_deps
import (
"os"
"path"
"sort"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
func TestParse(t *testing.T) {
vectors := []struct {
file string // Test input file
want []types.Library
wantErr string
}{
{
file: "testdata/ExampleApp1.deps.json",
want: []types.Library{
{Name: "Newtonsoft.Json", Version: "13.0.1", Locations: []types.Location{{StartLine: 33, EndLine: 39}}},
},
},
{
file: "testdata/NoLibraries.deps.json",
want: nil,
},
{
file: "testdata/InvalidJson.deps.json",
wantErr: "failed to decode .deps.json file: EOF",
},
}
for _, tt := range vectors {
t.Run(path.Base(tt.file), func(t *testing.T) {
f, err := os.Open(tt.file)
require.NoError(t, err)
got, _, err := NewParser().Parse(f)
if tt.wantErr != "" {
require.NotNil(t, err)
assert.Contains(t, err.Error(), tt.wantErr)
} else {
require.NoError(t, err)
sort.Slice(got, func(i, j int) bool {
ret := strings.Compare(got[i].Name, got[j].Name)
if ret == 0 {
return got[i].Version < got[j].Version
}
return ret < 0
})
sort.Slice(tt.want, func(i, j int) bool {
ret := strings.Compare(tt.want[i].Name, tt.want[j].Name)
if ret == 0 {
return tt.want[i].Version < tt.want[j].Version
}
return ret < 0
})
assert.Equal(t, tt.want, got)
}
})
}
}
<file_sep>/README.md
# go-dep-parser
Dependency Parser for Multiple Programming Languages
<file_sep>/pkg/utils/utils.go
package utils
import (
"fmt"
"sort"
"github.com/aquasecurity/go-dep-parser/pkg/types"
"golang.org/x/exp/maps"
)
func UniqueStrings(ss []string) []string {
var results []string
uniq := map[string]struct{}{}
for _, s := range ss {
if _, ok := uniq[s]; ok {
continue
}
results = append(results, s)
uniq[s] = struct{}{}
}
return results
}
func UniqueLibraries(libs []types.Library) []types.Library {
if len(libs) == 0 {
return nil
}
unique := map[string]types.Library{}
for _, lib := range libs {
identifier := fmt.Sprintf("%s@%s", lib.Name, lib.Version)
if l, ok := unique[identifier]; !ok {
unique[identifier] = lib
} else if len(lib.Locations) > 0 {
// merge locations
l.Locations = append(l.Locations, lib.Locations...)
sort.Sort(l.Locations)
unique[identifier] = l
}
}
libSlice := maps.Values(unique)
sort.Sort(types.Libraries(libSlice))
return libSlice
}
func MergeMaps(parent, child map[string]string) map[string]string {
if parent == nil {
return child
}
for k, v := range child {
parent[k] = v
}
return parent
}
func PackageID(name, version string) string {
return fmt.Sprintf("%s@%s", name, version)
}
<file_sep>/pkg/conda/meta/parse.go
package meta
import (
"encoding/json"
"golang.org/x/xerrors"
dio "github.com/aquasecurity/go-dep-parser/pkg/io"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
type packageJSON struct {
Name string `json:"name"`
Version string `json:"version"`
License string `json:"license"`
}
type Parser struct{}
func NewParser() types.Parser {
return &Parser{}
}
// Parse parses Anaconda (a.k.a. conda) environment metadata.
// e.g. <conda-root>/envs/<env>/conda-meta/<package>.json
// For details see https://conda.io/projects/conda/en/latest/user-guide/concepts/environments.html
func (p *Parser) Parse(r dio.ReadSeekerAt) ([]types.Library, []types.Dependency, error) {
var data packageJSON
err := json.NewDecoder(r).Decode(&data)
if err != nil {
return nil, nil, xerrors.Errorf("JSON decode error: %w", err)
}
if data.Name == "" || data.Version == "" {
return nil, nil, xerrors.Errorf("unable to parse conda package")
}
return []types.Library{{
Name: data.Name,
Version: data.Version,
License: data.License, // can be empty
}}, nil, nil
}
<file_sep>/pkg/java/pom/settings.go
package pom
import (
"encoding/xml"
"os"
"path/filepath"
"golang.org/x/net/html/charset"
)
type settings struct {
LocalRepository string `xml:"localRepository"`
}
func readSettings() settings {
userSettingsPath := filepath.Join(os.Getenv("HOME"), ".m2", "settings.xml")
userSettings, err := openSettings(userSettingsPath)
if err == nil && userSettings.LocalRepository != "" {
return userSettings
}
globalSettingsPath := filepath.Join(os.Getenv("MAVEN_HOME"), "conf", "settings.xml")
globalSettings, err := openSettings(globalSettingsPath)
if err == nil && globalSettings.LocalRepository != "" {
return globalSettings
}
return settings{}
}
func openSettings(filePath string) (settings, error) {
f, err := os.Open(filePath)
if err != nil {
return settings{}, err
}
s := settings{}
decoder := xml.NewDecoder(f)
decoder.CharsetReader = charset.NewReaderLabel
if err = decoder.Decode(&s); err != nil {
return settings{}, err
}
return s, nil
}
<file_sep>/pkg/nodejs/packagejson/parse.go
package packagejson
import (
"encoding/json"
"io"
"github.com/aquasecurity/go-dep-parser/pkg/types"
"github.com/aquasecurity/go-dep-parser/pkg/utils"
"golang.org/x/xerrors"
)
type packageJSON struct {
Name string `json:"name"`
Version string `json:"version"`
License interface{} `json:"license"`
Dependencies map[string]string `json:"dependencies"`
OptionalDependencies map[string]string `json:"optionalDependencies"`
DevDependencies map[string]string `json:"devDependencies"`
Workspaces []string `json:"workspaces"`
}
type Package struct {
types.Library
Dependencies map[string]string
OptionalDependencies map[string]string
DevDependencies map[string]string
Workspaces []string
}
type Parser struct{}
func NewParser() *Parser {
return &Parser{}
}
func (p *Parser) Parse(r io.Reader) (Package, error) {
var pkgJSON packageJSON
if err := json.NewDecoder(r).Decode(&pkgJSON); err != nil {
return Package{}, xerrors.Errorf("JSON decode error: %w", err)
}
var id string
// Name and version fields are optional
// https://docs.npmjs.com/cli/v9/configuring-npm/package-json#name
if pkgJSON.Name != "" && pkgJSON.Version != "" {
id = utils.PackageID(pkgJSON.Name, pkgJSON.Version)
}
return Package{
Library: types.Library{
ID: id,
Name: pkgJSON.Name,
Version: pkgJSON.Version,
License: parseLicense(pkgJSON.License),
},
Dependencies: pkgJSON.Dependencies,
OptionalDependencies: pkgJSON.OptionalDependencies,
DevDependencies: pkgJSON.DevDependencies,
Workspaces: pkgJSON.Workspaces,
}, nil
}
func parseLicense(val interface{}) string {
// the license isn't always a string, check for legacy struct if not string
switch v := val.(type) {
case string:
return v
case map[string]interface{}:
if license, ok := v["type"]; ok {
return license.(string)
}
}
return ""
}
<file_sep>/pkg/golang/binary/parse_test.go
package binary_test
import (
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/aquasecurity/go-dep-parser/pkg/golang/binary"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
func TestParse(t *testing.T) {
tests := []struct {
name string
inputFile string
want []types.Library
wantErr string
}{
{
name: "ELF",
inputFile: "testdata/test.elf",
want: []types.Library{
{
Name: "github.com/aquasecurity/go-pep440-version",
Version: "v0.0.0-20210121094942-22b2f8951d46",
},
{
Name: "github.com/aquasecurity/go-version",
Version: "v0.0.0-20210121072130-637058cfe492",
},
{
Name: "golang.org/x/xerrors",
Version: "v0.0.0-20200804184101-5ec99f83aff1",
},
},
},
{
name: "PE",
inputFile: "testdata/test.exe",
want: []types.Library{
{
Name: "github.com/aquasecurity/go-pep440-version",
Version: "v0.0.0-20210121094942-22b2f8951d46",
},
{
Name: "github.com/aquasecurity/go-version",
Version: "v0.0.0-20210121072130-637058cfe492",
},
{
Name: "golang.org/x/xerrors",
Version: "v0.0.0-20200804184101-5ec99f83aff1",
},
},
},
{
name: "Mach-O",
inputFile: "testdata/test.macho",
want: []types.Library{
{
Name: "github.com/aquasecurity/go-pep440-version",
Version: "v0.0.0-20210121094942-22b2f8951d46",
},
{
Name: "github.com/aquasecurity/go-version",
Version: "v0.0.0-20210121072130-637058cfe492",
},
{
Name: "golang.org/x/xerrors",
Version: "v0.0.0-20200804184101-5ec99f83aff1",
},
},
},
{
name: "with replace directive",
inputFile: "testdata/replace.elf",
want: []types.Library{
{
Name: "github.com/davecgh/go-spew",
Version: "v1.1.1",
},
{
Name: "github.com/go-sql-driver/mysql",
Version: "v1.5.0",
},
},
},
{
name: "sad path",
inputFile: "testdata/dummy",
wantErr: "unrecognized executable format",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f, err := os.Open(tt.inputFile)
require.NoError(t, err)
defer f.Close()
got, _, err := binary.NewParser().Parse(f)
if tt.wantErr != "" {
require.NotNil(t, err)
assert.Contains(t, err.Error(), tt.wantErr)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.want, got)
})
}
}
<file_sep>/pkg/rust/cargo/parse_test.go
package cargo
import (
"fmt"
"os"
"path"
"sort"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
var (
cargoNormalLibs = []types.Library{
{ID: "[email protected]", Name: "normal", Version: "0.1.0", Locations: []types.Location{{StartLine: 8, EndLine: 13}}},
{ID: "[email protected]", Name: "libc", Version: "0.2.54", Locations: []types.Location{{StartLine: 3, EndLine: 6}}},
{ID: "[email protected]", Name: "typemap", Version: "0.3.3", Locations: []types.Location{{StartLine: 20, EndLine: 26}}},
{ID: "[email protected]", Name: "url", Version: "1.7.2", Locations: []types.Location{{StartLine: 43, EndLine: 51}}},
{ID: "[email protected]", Name: "unsafe-any", Version: "0.4.2", Locations: []types.Location{{StartLine: 15, EndLine: 18}}},
{ID: "[email protected]", Name: "matches", Version: "0.1.8", Locations: []types.Location{{StartLine: 33, EndLine: 36}}},
{ID: "[email protected]", Name: "idna", Version: "0.1.5", Locations: []types.Location{{StartLine: 28, EndLine: 31}}},
{ID: "[email protected]", Name: "percent-encoding", Version: "1.0.1", Locations: []types.Location{{StartLine: 38, EndLine: 41}}},
}
cargoNormalDeps = []types.Dependency{
{
ID: "[email protected]",
DependsOn: []string{"[email protected]"}},
{
ID: "[email protected]",
DependsOn: []string{"[email protected]"},
},
{
ID: "[email protected]",
DependsOn: []string{"[email protected]", "[email protected]", "[email protected]"},
},
}
cargoMixedLibs = []types.Library{
{ID: "[email protected]", Name: "normal", Version: "0.1.0", Locations: []types.Location{{StartLine: 17, EndLine: 22}}},
{ID: "[email protected]", Name: "libc", Version: "0.2.54", Locations: []types.Location{{StartLine: 3, EndLine: 6}}},
{ID: "[email protected]", Name: "typemap", Version: "0.3.3", Locations: []types.Location{{StartLine: 55, EndLine: 61}}},
{ID: "[email protected]", Name: "url", Version: "1.7.2", Locations: []types.Location{{StartLine: 26, EndLine: 34}}},
{ID: "[email protected]", Name: "unsafe-any", Version: "0.4.2", Locations: []types.Location{{StartLine: 9, EndLine: 12}}},
{ID: "[email protected]", Name: "matches", Version: "0.1.8", Locations: []types.Location{{StartLine: 41, EndLine: 44}}},
{ID: "[email protected]", Name: "idna", Version: "0.1.5", Locations: []types.Location{{StartLine: 36, EndLine: 39}}},
{ID: "[email protected]", Name: "percent-encoding", Version: "1.0.1", Locations: []types.Location{{StartLine: 46, EndLine: 49}}},
}
cargoV3Libs = []types.Library{
{ID: "[email protected]", Name: "aho-corasick", Version: "0.7.20", Locations: []types.Location{{StartLine: 5, EndLine: 12}}},
{ID: "[email protected]", Name: "app", Version: "0.1.0", Locations: []types.Location{{StartLine: 14, EndLine: 21}}},
{ID: "[email protected]", Name: "libc", Version: "0.2.140", Locations: []types.Location{{StartLine: 23, EndLine: 27}}},
{ID: "[email protected]", Name: "memchr", Version: "1.0.2", Locations: []types.Location{{StartLine: 29, EndLine: 36}}},
{ID: "[email protected]", Name: "memchr", Version: "2.5.0", Locations: []types.Location{{StartLine: 38, EndLine: 42}}},
{ID: "[email protected]", Name: "regex", Version: "1.7.3", Locations: []types.Location{{StartLine: 44, EndLine: 53}}},
{ID: "[email protected]", Name: "regex-syntax", Version: "0.5.6", Locations: []types.Location{{StartLine: 55, EndLine: 62}}},
{ID: "[email protected]", Name: "regex-syntax", Version: "0.6.29", Locations: []types.Location{{StartLine: 64, EndLine: 68}}},
{ID: "[email protected]", Name: "ucd-util", Version: "0.1.10", Locations: []types.Location{{StartLine: 70, EndLine: 74}}},
}
cargoV3Deps = []types.Dependency{
{
ID: "[email protected]",
DependsOn: []string{"[email protected]"}},
{
ID: "[email protected]",
DependsOn: []string{"[email protected]", "[email protected]", "[email protected]"},
},
{
ID: "[email protected]",
DependsOn: []string{"[email protected]"},
},
{
ID: "[email protected]",
DependsOn: []string{"[email protected]", "[email protected]", "[email protected]"},
},
{
ID: "[email protected]",
DependsOn: []string{"[email protected]"},
},
}
)
func TestParse(t *testing.T) {
vectors := []struct {
file string // Test input file
wantLibs []types.Library
wantDeps []types.Dependency
wantErr assert.ErrorAssertionFunc
}{
{
file: "testdata/cargo_normal.lock",
wantLibs: cargoNormalLibs,
wantDeps: cargoNormalDeps,
wantErr: assert.NoError,
},
{
file: "testdata/cargo_mixed.lock",
wantLibs: cargoMixedLibs,
wantDeps: cargoNormalDeps,
wantErr: assert.NoError,
},
{
file: "testdata/cargo_v3.lock",
wantLibs: cargoV3Libs,
wantDeps: cargoV3Deps,
wantErr: assert.NoError,
},
{
file: "testdata/cargo_invalid.lock",
wantErr: assert.Error,
},
}
for _, v := range vectors {
t.Run(path.Base(v.file), func(t *testing.T) {
f, err := os.Open(v.file)
require.NoError(t, err)
gotLibs, gotDeps, err := NewParser().Parse(f)
if !v.wantErr(t, err, fmt.Sprintf("Parse(%v)", v.file)) {
return
}
if err != nil {
return
}
sortLibs(v.wantLibs)
sortDeps(v.wantDeps)
assert.Equalf(t, v.wantLibs, gotLibs, "Parse libraries(%v)", v.file)
assert.Equalf(t, v.wantDeps, gotDeps, "Parse dependencies(%v)", v.file)
})
}
}
func sortLibs(libs []types.Library) {
sort.Slice(libs, func(i, j int) bool {
return strings.Compare(libs[i].ID, libs[j].ID) < 0
})
}
func sortDeps(deps []types.Dependency) {
sort.Slice(deps, func(i, j int) bool {
return strings.Compare(deps[i].ID, deps[j].ID) < 0
})
}
<file_sep>/pkg/swift/swift/parse.go
package swift
import (
dio "github.com/aquasecurity/go-dep-parser/pkg/io"
"github.com/aquasecurity/go-dep-parser/pkg/types"
"github.com/aquasecurity/go-dep-parser/pkg/utils"
"github.com/liamg/jfather"
"golang.org/x/xerrors"
"io"
"sort"
"strings"
)
// Parser is a parser for Package.resolved files
type Parser struct{}
func NewParser() types.Parser {
return &Parser{}
}
func (Parser) Parse(r dio.ReadSeekerAt) ([]types.Library, []types.Dependency, error) {
var lockFile LockFile
input, err := io.ReadAll(r)
if err != nil {
return nil, nil, xerrors.Errorf("read error: %w", err)
}
if err := jfather.Unmarshal(input, &lockFile); err != nil {
return nil, nil, xerrors.Errorf("decode error: %w", err)
}
var libs types.Libraries
pins := lockFile.Object.Pins
if lockFile.Version > 1 {
pins = lockFile.Pins
}
for _, pin := range pins {
name := libraryName(pin, lockFile.Version)
libs = append(libs, types.Library{
ID: utils.PackageID(name, pin.State.Version),
Name: name,
Version: pin.State.Version,
Locations: []types.Location{
{
StartLine: pin.StartLine,
EndLine: pin.EndLine,
},
},
})
}
sort.Sort(libs)
return libs, nil, nil
}
func libraryName(pin Pin, lockVersion int) string {
// Package.resolved v1 uses `RepositoryURL`
// v2 uses `Location`
name := pin.RepositoryURL
if lockVersion > 1 {
name = pin.Location
}
// Swift uses `https://github.com/<author>/<package>.git format
// `.git` suffix can be omitted (take a look happy test)
// Remove `https://` and `.git` to fit the same format
name = strings.TrimPrefix(name, "https://")
name = strings.TrimSuffix(name, ".git")
return name
}
// UnmarshalJSONWithMetadata needed to detect start and end lines of deps for v1
func (p *Pin) UnmarshalJSONWithMetadata(node jfather.Node) error {
if err := node.Decode(&p); err != nil {
return err
}
// Decode func will overwrite line numbers if we save them first
p.StartLine = node.Range().Start.Line
p.EndLine = node.Range().End.Line
return nil
}
<file_sep>/pkg/nodejs/npm/parse_test.go
package npm
import (
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/aquasecurity/go-dep-parser/pkg/types"
)
func TestParse(t *testing.T) {
tests := []struct {
name string
file string // Test input file
want []types.Library
wantDeps []types.Dependency
}{
{
name: "lock version v1",
file: "testdata/package-lock_v1.json",
want: npmV1Libs,
wantDeps: npmDeps,
},
{
name: "lock version v2",
file: "testdata/package-lock_v2.json",
want: npmV2Libs,
wantDeps: npmDeps,
},
{
name: "lock version v3",
file: "testdata/package-lock_v3.json",
want: npmV2Libs,
wantDeps: npmDeps,
},
{
name: "lock version v3 with workspace",
file: "testdata/package-lock_v3_with_workspace.json",
want: npmV3WithWorkspaceLibs,
wantDeps: npmV3WithWorkspaceDeps,
},
{
name: "lock version v3 with workspace and without direct deps field",
file: "testdata/package-lock_v3_without_root_deps_field.json",
want: npmV3WithoutRootDepsField,
wantDeps: npmV3WithoutRootDepsFieldDeps,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f, err := os.Open(tt.file)
require.NoError(t, err)
got, deps, err := NewParser().Parse(f)
require.NoError(t, err)
assert.Equal(t, tt.want, got)
if tt.wantDeps != nil {
assert.Equal(t, tt.wantDeps, deps)
}
})
}
}
<file_sep>/pkg/java/pom/utils.go
package pom
import (
"fmt"
"os"
"strings"
)
func isDirectory(path string) (bool, error) {
fileInfo, err := os.Stat(path)
if err != nil {
return false, err
}
return fileInfo.IsDir(), err
}
func isProperty(version string) bool {
if version != "" && strings.HasPrefix(version, "${") && strings.HasSuffix(version, "}") {
return true
}
return false
}
func packageID(name, version string) string {
return fmt.Sprintf("%s:%s", name, version)
}
<file_sep>/pkg/io/io.go
package io
import "io"
type ReadSeekerAt interface {
io.ReadSeeker
io.ReaderAt
}
type ReadSeekCloserAt interface {
io.ReadSeekCloser
io.ReaderAt
}
// NopCloser returns a ReadSeekCloserAt with a no-op Close method wrapping
// the provided Reader r.
func NopCloser(r ReadSeekerAt) ReadSeekCloserAt {
return nopCloser{r}
}
type nopCloser struct {
ReadSeekerAt
}
func (nopCloser) Close() error { return nil }
<file_sep>/pkg/python/pip/testdata/requirements_hyphens.txt
oauth2-client==4.0.0
python-gitlab==2.0.0<file_sep>/pkg/rust/cargo/naive_pkg_parser.go
package cargo
import (
"bufio"
"fmt"
"io"
"strings"
"github.com/aquasecurity/go-dep-parser/pkg/utils"
)
type pkgPosition struct {
start int
end int
}
type minPkg struct {
name string
version string
position pkgPosition
}
func (pkg *minPkg) setEndPositionIfEmpty(n int) {
if pkg.position.end == 0 {
pkg.position.end = n
}
}
type naivePkgParser struct {
r io.Reader
}
func (parser *naivePkgParser) parse() map[string]pkgPosition {
var currentPkg minPkg = minPkg{}
var idx = make(map[string]pkgPosition, 0)
scanner := bufio.NewScanner(parser.r)
lineNum := 1
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(strings.TrimSpace(line), "[") {
if currentPkg.name != "" {
pkgId := utils.PackageID(currentPkg.name, currentPkg.version)
currentPkg.setEndPositionIfEmpty(lineNum - 1)
idx[pkgId] = currentPkg.position
}
currentPkg = minPkg{}
currentPkg.position.start = lineNum
} else if strings.HasPrefix(strings.TrimSpace(line), "name =") {
currentPkg.name = propertyValue(line)
} else if strings.HasPrefix(strings.TrimSpace(line), "version =") {
currentPkg.version = propertyValue(line)
} else if strings.TrimSpace(line) == "" {
currentPkg.setEndPositionIfEmpty(lineNum - 1)
}
lineNum++
}
// add last item
if currentPkg.name != "" {
pkgId := fmt.Sprintf("%s@%s", currentPkg.name, currentPkg.version)
currentPkg.setEndPositionIfEmpty(lineNum - 1)
idx[pkgId] = currentPkg.position
}
return idx
}
func propertyValue(line string) string {
parts := strings.Split(line, "=")
if len(parts) == 2 {
return strings.Trim(parts[1], ` "`)
}
return ""
}
<file_sep>/pkg/java/pom/artifact_test.go
package pom
import (
"os"
"testing"
"github.com/stretchr/testify/assert"
)
func Test_evaluateVariable(t *testing.T) {
type args struct {
s string
props map[string]string
}
tests := []struct {
name string
args args
want string
}{
{
name: "happy path",
args: args{
s: "${java.version}",
props: map[string]string{
"java.version": "1.7",
},
},
want: "1.7",
},
{
name: "two variables",
args: args{
s: "${foo.name}-${bar.name}",
props: map[string]string{
"foo.name": "aaa",
"bar.name": "bbb",
},
},
want: "aaa-bbb",
},
{
name: "looped variables",
args: args{
s: "${foo.name}",
props: map[string]string{
"foo.name": "${bar.name}",
"bar.name": "${foo.name}",
},
},
want: "",
},
{
name: "same variables",
args: args{
s: "${foo.name}-${foo.name}",
props: map[string]string{
"foo.name": "aaa",
},
},
want: "aaa-aaa",
},
{
name: "nested variables",
args: args{
s: "${jackson.version.core}",
props: map[string]string{
"jackson.version": "2.12.1",
"jackson.version.core": "${jackson.version}",
},
},
want: "2.12.1",
},
{
name: "environmental variable",
args: args{
s: "${env.TEST_GO_DEP_PARSER}",
},
want: "1.2.3",
},
{
name: "no variable",
args: args{
s: "1.12",
},
want: "1.12",
},
}
envName := "TEST_GO_DEP_PARSER"
os.Setenv(envName, "1.2.3")
defer os.Unsetenv(envName)
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := evaluateVariable(tt.args.s, tt.args.props, nil)
assert.Equal(t, tt.want, got)
})
}
}
|
622fe340d676f996e7332366b5e3a4a84f559757
|
[
"Ruby",
"JavaScript",
"Markdown",
"TOML",
"Maven POM",
"Gradle",
"Go Module",
"Text",
"Go",
"Dockerfile"
] | 114 |
Go
|
aquasecurity/go-dep-parser
|
841bc0f812c78d6155469f8b214bb28f56440819
|
411ce1d20dca73e887fe362d31a4bd5e825de9e1
|
refs/heads/master
|
<repo_name>arttioz/healthdata_rti<file_sep>/OLD SCRIPT/IPD_Death.sql
SELECT DEATH_IPD.*, SUM(admission.PRICE) as Price
FROM
admission,
(
Select diagnosis_ipd.PID, diagnosis_ipd.HOSPCODE, diagnosis_ipd.DIAGCODE, diagnosis_ipd.DATETIME_ADMIT
From
diagnosis_ipd,
(SELECT DISTINCT PID, HOSPCODE
FROM admission
WHERE admission.DISCHSTATUS = 9 ) AS DeathAdmid
WHERE
diagnosis_ipd.PID = DeathAdmid.PID AND
diagnosis_ipd.HOSPCODE = DeathAdmid.HOSPCODE AND
diagnosis_ipd.DIAGCODE BETWEEN "V0" and "V899" AND
diagnosis_ipd.DATETIME_ADMIT BETWEEN "2016-01-01" and "2016-01-31" ) AS DEATH_IPD
WHERE
admission.PID = DEATH_IPD.PID AND
admission.HOSPCODE = DEATH_IPD.HOSPCODE AND
admission.DATETIME_ADMIT BETWEEN "2016-01-01" and "2016-01-31"
GROUP BY DEATH_IPD.PID
<file_sep>/OLD SCRIPT/IPD_OPD_Death.sql
SELECT ACCIDENT_DEATH.PID , ACCIDENT_DEATH.HOSPCODE, ACCIDENT_DEATH.DIAGCODE, ACCIDENT_DEATH.DATE_SERV,
person.CID, person.`NAME`, person.LNAME, person.sex, person.BIRTH , floor(datediff (DATE_SERV,BIRTH)/365) as age
FROM
((Select diagnosis_ipd.PID, diagnosis_ipd.HOSPCODE, diagnosis_ipd.DIAGCODE, diagnosis_ipd.DATETIME_ADMIT AS DATE_SERV
From
diagnosis_ipd,
(SELECT DISTINCT PID, HOSPCODE
FROM admission
WHERE admission.DISCHSTATUS = 8 or admission.DISCHSTATUS = 9 ) AS DeathAdmid
WHERE
diagnosis_ipd.PID = DeathAdmid.PID AND
diagnosis_ipd.HOSPCODE = DeathAdmid.HOSPCODE AND
diagnosis_ipd.DIAGCODE BETWEEN "V0" and "V899" AND
diagnosis_ipd.DATETIME_ADMIT BETWEEN "2016-03-01" and "2016-03-31"
)
UNION
(
Select diagnosis_opd.PID, diagnosis_opd.HOSPCODE, diagnosis_opd.DIAGCODE, diagnosis_opd.DATE_SERV
From
diagnosis_opd,
(SELECT DISTINCT PID, HOSPCODE
FROM service
WHERE service.TYPEOUT = 4 OR
service.TYPEOUT = 5 OR
service.TYPEOUT = 6) AS DeathService
WHERE
diagnosis_opd.PID = DeathService.PID AND
diagnosis_opd.HOSPCODE = DeathService.HOSPCODE AND
diagnosis_opd.DIAGCODE BETWEEN "V0" and "V899" AND
diagnosis_opd.DATE_SERV BETWEEN "2016-03-01" and "2016-03-31"
)
UNION
(
Select death.Pid, death.HOSPCODE, death.CDEATH, death.DDEATH AS DATE_SERV
FROM
death
WHERE
death.CDEATH BETWEEN "V0" and "V899" AND
death.DDEATH BETWEEN "2016-03-01" and "2016-03-31"
)
) AS ACCIDENT_DEATH
INNER JOIN person
on ACCIDENT_DEATH.PID = person.PID AND
ACCIDENT_DEATH.HOSPCODE = person.HOSPCODE
GROUP BY PID, HOSPCODE<file_sep>/OLD SCRIPT/OPD_Death.sql
SELECT DEATH_OPD.*, SUM(service.PRICE) as Price
FROM
service,
(
Select diagnosis_opd.PID, diagnosis_opd.HOSPCODE, diagnosis_opd.DIAGCODE, diagnosis_opd.DATE_SERV
From
diagnosis_opd,
(SELECT DISTINCT PID, HOSPCODE
FROM service
WHERE service.TYPEOUT = 4 OR
service.TYPEOUT = 5 OR
service.TYPEOUT = 6) AS DeathService
WHERE
diagnosis_opd.PID = DeathService.PID AND
diagnosis_opd.HOSPCODE = DeathService.HOSPCODE AND
diagnosis_opd.DIAGCODE BETWEEN "V0" and "V899" AND
diagnosis_opd.DATE_SERV BETWEEN "2016-01-01" and "2016-01-31"
) AS DEATH_OPD
WHERE
service.PID = DEATH_OPD.PID AND
service.HOSPCODE = DEATH_OPD.HOSPCODE AND
service.DATE_SERV BETWEEN "2016-01-01" and "2016-01-31"
GROUP BY DEATH_OPD.PID
|
e838fbbf64553a06b6ca126321885e04a7eeb8ca
|
[
"SQL"
] | 3 |
SQL
|
arttioz/healthdata_rti
|
44272d2fd851b971617e0d8b8df868229b0966e1
|
e29e7990240c2295fdf57082c475b8d3160f2724
|
refs/heads/main
|
<file_sep># Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'AdmobAdapterDemo' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
pod 'Ads-Global'
pod 'Google-Mobile-Ads-SDK', '8.0.0'
# Pods for AdmobAdapterDemo
end
<file_sep>Pod::Spec.new do |s|
s.name = 'Pangle-adapter-for-admob'
s.version = '1.4.1'
s.summary = 'Integrating Pangle with Admob Mediation'
s.description = <<-DESC
For publishers who want to use the Google Mobile Ads SDK to load and display ads from Pangle via mediation.
DESC
s.license = { :type => 'MIT', :file => 'AdmobAdapter/LICENSE' }
s.author = { 'zengyang' => '<EMAIL>' }
s.homepage = 'https://www.pangle.cn'
s.source = { :http => 'https://sf16-fe-tos-sg.i18n-pglstatp.com/obj/pangle-sdk-static-va/Adapter/Admob/1.4.1/AdmobAdapter.zip' }
s.pod_target_xcconfig = {"EXCLUDED_ARCHS[sdk=iphonesimulator*]" => "arm64 arm64e armv7 armv7s", "EXCLUDED_ARCHS[sdk=iphoneos*]" => "i386 x86_64"}
s.platform = :ios, "10.0"
s.static_framework = true
s.source_files = "AdmobAdapter/*.{h,m}"
s.dependency "Ads-Global",">= 3.7.0.0"
s.dependency "Google-Mobile-Ads-SDK",">= 8.0.0"
# pod trunk push Pangle-adapter-for-admob.podspec --allow-warnings --verbose --use-libraries --skip-import-validation
# pod trunk push Pangle-adapter-for-admob.podspec --allow-warnings --verbose --skip-import-validation
end
|
1b3575a5e0399300d7d69f24f85b6d5e38325db7
|
[
"Ruby"
] | 2 |
Ruby
|
Eason-yangyang/AdmobAdapterPangleDemo
|
a061e57971068afb6dd76683cf269ff798d72da9
|
228f6481f7cc679c93fb09ff09f5358f7c8d91bc
|
refs/heads/master
|
<repo_name>tinwatchman/use-import<file_sep>/spec/UseSpec.js
describe("UseImporter", function() {
var fs = require('fs-extra');
var path = require('path');
var _ = require('underscore');
var replaceBackSlashes = require("../lib/util").replaceBackSlashes;
describe("use, use.load, and use.isLoaded", function() {
var useJsonPath = path.join(__dirname, "./use.json");
var myClassPath = path.join(__dirname, "./MyClass.js");
beforeEach(function() {
fs.writeJsonSync(useJsonPath, {
"MyClass": "./MyClass"
});
fs.writeFileSync(myClassPath,
"module.exports = { hello: 'Hello!' };",
{'encoding':'utf8'}
);
});
afterEach(function() {
fs.removeSync(useJsonPath);
fs.removeSync(myClassPath);
});
it("should load a use.json file in the loading module's root " +
"directory, and return the proper file in response to the given " +
"name", function() {
var use = require('../useimport').load();
var MyClass = use('MyClass');
expect(use).toBeDefined();
expect(_.isFunction(use)).toBe(true);
expect(MyClass).toBeDefined();
expect(MyClass.hello).toEqual("Hello!");
});
describe("use.isLoaded", function() {
it("should return true when load has been called", function() {
var use = require('../useimport');
expect(use.isLoaded).toBe(true);
});
});
});
describe("use.unload", function() {
it("should exist", function() {
var use = require('../useimport');
expect(use.unload).toBeDefined();
expect(_.isFunction(use.unload)).toBe(true);
});
it("should clear all loaded data", function() {
var use = require('../useimport');
expect(use.isLoaded).toBe(true);
use.unload();
expect(use.isLoaded).toBe(false);
});
});
describe("use.load filePath parameter", function() {
var jsonPath = path.join(__dirname, "./something.json");
beforeEach(function() {
fs.writeJsonSync(jsonPath, {
"MyClass": "./MyClass"
});
});
afterEach(function() {
fs.removeSync(jsonPath);
});
it("should load config data from a specific file path", function() {
var use = require("../useimport").load(jsonPath);
var p = use.resolve("MyClass");
expect(p).toEqual(replaceBackSlashes(path.join(__dirname, "./MyClass")));
});
});
describe("use and use.config", function() {
var myClassPath = path.join(__dirname, "./MyClass.js");
beforeEach(function() {
fs.writeFileSync(myClassPath,
"module.exports = { hello: 'Hello!' };",
{'encoding':'utf8'}
);
});
afterEach(function() {
fs.removeSync(myClassPath);
});
it("should be configurable when first called", function() {
var use = require('../useimport').config({
"MyClass": "./MyClass"
});
var MyClass = use('MyClass');
expect(use).toBeDefined();
expect(_.isFunction(use)).toBe(true);
expect(MyClass).toBeDefined();
expect(MyClass.hello).toEqual("Hello!");
});
});
});<file_sep>/spec/LoaderSpec.js
describe("UseLoader", function() {
var UseLoader = require('../lib/loader');
var fs = require('fs-extra');
var path = require('path');
var UseMap = require('../lib/usemap');
var replaceBackSlashes = require('../lib/util').replaceBackSlashes;
var loader;
var tmpDir = path.join(__dirname, "./UseLoaderJasmine" + Date.now() + "/");
beforeAll(function() {
fs.ensureDirSync(tmpDir);
});
beforeEach(function() {
loader = new UseLoader();
});
afterAll(function() {
fs.removeSync(tmpDir);
});
describe("searchPath", function() {
var root = path.join(tmpDir, "./root/"),
level2 = path.join(root, "./level2/"),
level3 = path.join(level2, "./level3/")
beforeAll(function() {
fs.ensureDirSync(level3);
});
beforeEach(function() {
fs.emptyDirSync(root);
fs.emptyDirSync(level2);
fs.emptyDirSync(level3);
});
afterAll(function() {
fs.removeSync(root);
});
it("should search the given path for a use.json file and return the file's path if found", function() {
var configFilePath = path.join(root, "./use.json"),
startPoint = path.join(level3, "./index.js");
fs.outputJsonSync(configFilePath, { "name": "path" });
var r = loader.searchPath(startPoint);
expect(r).toEqual(configFilePath);
});
it("should search the given path for a project.json file and return the file's path if found", function() {
var configFilePath = path.join(root, "./project.json"),
startPoint = path.join(level3, "./index.js");
fs.writeJsonSync(configFilePath, { "name": "path" });
var r = loader.searchPath(startPoint);
expect(r).toEqual(configFilePath);
});
it("should prefer use.json files over project.json files", function() {
var useFilePath = path.join(root, "./use.json"),
projFilePath = path.join(root, "./project.json"),
startPoint = path.join(level3, "./index.js");
fs.ensureFileSync(useFilePath);
fs.ensureFileSync(projFilePath);
var r = loader.searchPath(startPoint);
expect(r).toEqual(useFilePath);
});
it("should return null when file is not found", function() {
var startPoint = path.join(level3, './index.js');
var r = loader.searchPath(startPoint);
expect(r).toBeNull();
});
});
describe("load", function() {
var root = path.join(tmpDir, './root/'),
rootPath = path.join(root, './index.js');
beforeEach(function() {
fs.ensureDirSync(root);
});
afterEach(function() {
fs.removeSync(root);
});
it("should configure a UseMap object with data from a use.json file", function() {
// set up
var configFilePath = path.join(root, "./use.json"),
useMap = new UseMap();
fs.writeJsonSync(configFilePath, {"name": "./path"});
// load
var result = loader.load(rootPath, useMap);
expect(result).toBe(true);
expect(useMap.isConfigured).toBe(true);
expect(useMap.map.name).toEqual(replaceBackSlashes(path.join(root, "./path")));
expect(useMap.isFileLoaded(configFilePath)).toBe(true);
});
it("should be able to handle data from a project.json file", function() {
var useMap = new UseMap(),
configPath = path.join(root, "./project.json"),
projectData = {
"namespace": {
"map": {
"name": "./path"
}
},
"srcDir": "./src"
};
fs.writeJsonSync(configPath, projectData);
// load
var result = loader.load(rootPath, useMap);
expect(result).toBe(true);
expect(useMap.isConfigured).toBe(true);
expect(useMap.map.name).toEqual(replaceBackSlashes(path.join(root, "./src", "./path")));
});
it("should return false when a config file isn't found", function() {
var useMap = new UseMap();
var result = loader.load(rootPath, useMap);
expect(result).toBe(false);
expect(useMap.isConfigured).toBe(false);
});
});
});<file_sep>/lib/usemap.js
module.exports = (function() {
"use strict";
var _ = require('underscore');
var pathlib = require('path');
var replaceBackSlashes = require('./util').replaceBackSlashes;
var UseMap = function() {
this.rootDir = null;
this.map = {};
this.files = [];
this.isConfigured = false;
var self = this;
/**
* Configures the map.
* @param {Object} nameMap Object containing name => relative path
* value pairs
* @param {String} rootDir Optional. Project root directory.
* @param {String} srcDir Optional. Project source directory (within
* root).
* @param {String} file Optional. Path of source config file.
* @return {void}
*/
this.config = function(nameMap, options) {
// optional rootDir argument
var rootDir;
if (_.has(options, 'rootDir') && !_.isEmpty(options.rootDir)) {
rootDir = options.rootDir;
} else if (this.rootDir !== null) {
rootDir = this.rootDir;
} else {
throw new Error("PROJECT_ROOT_DIR_NOT_DEFINED");
}
// optional srcDir argument
var srcDir;
if (_.has(options, 'srcDir') && !_.isEmpty(options.srcDir)) {
srcDir = options.srcDir;
}
// add new names to map; resolve paths to absolute
for (var name in nameMap) {
if (_.isUndefined(srcDir)) {
this.map[name] = replaceBackSlashes(pathlib.join(rootDir, nameMap[name]));
} else {
this.map[name] = replaceBackSlashes(pathlib.join(rootDir, srcDir, nameMap[name]));
}
}
// save config file path if provided
if (_.has(options, 'file') && !_.isEmpty(options.file)) {
this.files.push(pathlib.normalize(options.file));
}
// save root dir if it hasn't been set
if (this.rootDir === null) {
this.rootDir = rootDir;
}
this.isConfigured = true;
};
/**
* Gets module path for name (if found)
* @param {String} name Module name
* @return {String} Module path if found, undefined otherwise
*/
this.getPath = function(name) {
if (_.has(this.map, name) && !_.isEmpty(this.map[name])) {
return this.map[name];
}
return undefined;
};
/**
* Returns whether or not the given filepath has been loaded.
* @param {String} filePath Path to a config file
* @return {Boolean} True if already loaded, false otherwise
*/
this.isFileLoaded = function(filePath) {
return (this.files.indexOf(pathlib.normalize(filePath)) > -1);
};
/**
* Dumps out all data and resets the UseMap to its starting state
* @return {void}
*/
this.dispose = function() {
if (this.isConfigured) {
this.rootDir = null;
for (var key in this.map) {
delete this.map[key];
}
this.files = [];
this.isConfigured = false;
}
};
/* Getter for length */
this.__defineGetter__('length', function() {
return _.keys(self.map).length;
});
};
return UseMap;
})();<file_sep>/lib/util.js
module.exports = (function() {
"use strict";
/**
* Common utility functions
*/
/**
* Replaces Windows-style backslashes in filepaths with Unix-style
* forward-slashes for consistency
* @param {String} path A filepath
* @return {String} Path with all backslashes converted
*/
var replaceBackSlashes = function(path) {
while (path.search(/\\/i) > -1) {
path = path.replace(/\\/i, '/');
}
return path;
};
return {
'replaceBackSlashes': replaceBackSlashes
};
})();<file_sep>/example/example-app.js
var use = require('use-import').load();
var Class1 = use('Class1');
var classOne = new Class1();
classOne.method();
<file_sep>/useimport.js
module.exports = (function() {
"use strict";
var _ = require("underscore");
var pathlib = require("path");
var UseMap = require("./lib/usemap");
var UseLoader = require("./lib/loader");
var UseImporter = function() {
var self = this,
useMap = new UseMap();
// public api
/**
* Require module by name
* @param {String} name Valid/configured name for module
* @return {*}
*/
this.use = function(name) {
if (!useMap.isConfigured) {
throw new Error("USE_IMPORTER_NOT_CONFIGURED");
}
var namePath = useMap.getPath(name);
if (_.isUndefined(namePath)) {
throw new Error("USE_IMPORTER_MODULE_NOT_FOUND");
}
return require(namePath);
};
/**
* Loads config information from a use.json or project.json file on the
* requesting module"s filepath
* @param {String} filePath Optional. Path to a specific JSON config
* file to load.
* @return {Function} Returns the use function. Useful for
* chaining.
*/
this.use.load = function() {
if (arguments.length > 0) {
self.load(arguments[0]);
} else {
self.load();
}
return self.use;
};
/**
* Configures use-import
* @param {Object} map Object with name => module relative path
* key-value pairs.
* @param {String} rootDir Optional. The root directory the module
* paths are given in relation to. Defaults to
* the root directory of the first module to
* require use-import.
* @return {Function} Returns the `use` function. Useful for
* chaining.
*/
this.use.config = function(map) {
if (arguments.length > 1 && !_.isEmpty(arguments[1])) {
useMap.config(map, arguments[1]);
} else if (!useMap.isConfigured) {
useMap.config(map, {
rootDir: pathlib.dirname(module.parent.filename)
});
} else {
useMap.config(map);
}
return self.use;
};
/**
* Returns the relative file path for the given name
* @param {String} name Valid name for a module
* @return {String} Filepath if found, undefined otherwise
*/
this.use.resolve = function(name) {
if (!useMap.isConfigured) {
return undefined;
}
return useMap.getPath(name);
};
/**
* Clears out all loaded data. Mostly useful for unit tests, or other
* situations where there might not be just one entry point.
*/
this.use.unload = function() {
useMap.dispose();
};
/* getter for isLoaded */
this.use.__defineGetter__("isLoaded", function() {
return useMap.isConfigured;
});
// protected functions
this.load = function() {
// check for filePath property
var filePath;
if (arguments.length > 0 && !_.isEmpty(arguments[0])) {
filePath = arguments[0];
}
// load if not configured
if (!useMap.isConfigured ||
(!_.isUndefined(filePath) && !useMap.isFileLoaded(filePath))) {
var loader = new UseLoader();
var r;
if (!_.isUndefined(filePath)) {
r = loader.loadFile(filePath, useMap);
} else {
r = loader.load(module.parent.filename, useMap);
}
if (!r) {
throw new Error("USE_IMPORTER_CONFIG_FILE_NOT_FOUND");
}
}
};
};
var useImporter = new UseImporter();
return useImporter.use;
})();<file_sep>/example/src/Class1.js
module.exports = (function() {
var use = require('use-import');
var Class2 = use('Class2');
var Class1 = function() {
this.type = "Class1";
this.classTwo = new Class2();
this.method = function() {
console.log("Class1 Method Called!");
this.classTwo.method();
};
};
return Class1;
})();<file_sep>/README.md
# use-import
> Imports modules by name instead of by filepath
Tired of dealing with lengthy relative file paths in your `require` statements? This module gives your project files access to the `use` function, enabling you to import modules by name rather than by filepath. Module names are configured either via a JSON file placed in the project's root directory or an object passed in at application startup.
## Installation
```sh
npm install use-import --save
```
## Configuration
To configure your project's names, create a new file in your project's root directory called **use.json**. Within this file, map out the modules' names to their respective filepaths:
```javascript
{
// all key-value pairs in this file should follow the format of
// "name": "filepath." Like so:
"MyClass": "./src/data/MyClass",
"MyOtherClass": "./src/model/MyOtherClass"
// all file paths should be expressed relative to the project's
// root directory
}
```
(If this seems like a hassle to you, you may want to take a look at [use-automapper](https://www.npmjs.com/package/use-automapper) or [projectjs](https://www.npmjs.com/package/projectjs). Note that `use-import` will also accept configuration in the form of a *project.json* file.)
For another way to handle configuration, see [In-Code Configuration](#in_code_configuration) below.
## Usage
Add the following code to the top of your project's main script or entry point:
```javascript
// This call is REQUIRED at the start of the application
// in order to make `use-import` work when using a use.json
// file for configuration!
var use = require('use-import').load();
```
Note that `use.load` only needs to be called *once* in a project. From that point on, you can (and should) require the use function normally in any of your project files, like so:
```javascript
var use = require('use-import');
```
The `use` function acts as a wrapper around `require`, allowing you to request modules by name or shorthand alias rather than having to bother with filepaths.
```javascript
// so instead of having to write something like this...
var MyClass = require('../../data/MyClass');
// ... you can simply refer to the module by name
var use = require('use-import');
var MyClass = use('MyClass');
```
<a name="in_code_configuration"></a>
## Optional: In-Code Configuration
As an additional option, instead of creating and loading a use.json file at runtime, you can also pass in a name-filepath map in your project's entry point, instead of calling `use.load`:
```javascript
// make this call in your entry point or start script INSTEAD of calling use.load as described above.
var use = require('use-import').config({
"MyClass": "./src/data/MyClass",
"MyOtherClass": "./src/model/MyOtherClass"
});
```
## Code Examples
To see a working example of how to use `use-import` in a project, see [example/example-app.js](https://github.com/tinwatchman/use-import/blob/master/example/example-app.js) and [example/use.json](https://github.com/tinwatchman/use-import/blob/master/example/use.json). For an example of in-code configuration, see [example/in-code-config-example.js](https://github.com/tinwatchman/use-import/blob/master/example/in-code-config-example.js).
## Changelist
+ 0.1.2
- removed USE_IMPORTER_LOAD_CALLED_TWICE error. Proved to be too much of a pain in situations involving multiple entry points (like unit tests).
+ 0.1.1
- added use.unload function
- use.load() can now accept direct filepath to JSON file.
## Contributing
Bug reports, feature requests, pull requests and general feedback would all be appreciated.
## Credits and Licensing
Created by [<NAME>](http://www.jonstout.net). Licensed under [the MIT license](http://opensource.org/licenses/MIT).
<file_sep>/spec/MapSpec.js
describe("UseMap", function() {
var UseMap = require('../lib/usemap');
var useMap;
beforeEach(function() {
useMap = new UseMap();
});
describe("config", function() {
it("should accept a map of name-path pairs, and resolve the paths relative to the given root directory", function() {
var nameMap = {
'name1': './src/package/module1',
'name2': './src/package/subpackage/module2',
'name3': './lib/module3'
};
useMap.config(nameMap, {
rootDir: "/Users/someone/project/"
});
expect(useMap.isConfigured).toBe(true);
expect(useMap.length).toEqual(3);
expect(useMap.map.name1).toEqual("/Users/someone/project/src/package/module1");
expect(useMap.map.name2).toEqual("/Users/someone/project/src/package/subpackage/module2");
expect(useMap.map.name3).toEqual("/Users/someone/project/lib/module3");
});
it("should hold onto the first valid rootDir it sees for future reference", function() {
var nameMap = {
'name1': './src/package/module1'
};
useMap.config(nameMap, {
rootDir: "/Users/someone/project/"
});
expect(useMap.isConfigured).toBe(true);
expect(useMap.rootDir).not.toBeNull();
expect(useMap.rootDir).toEqual("/Users/someone/project/");
});
it("should add additional config options as provided, and resolve them with the cached rootDir", function() {
var map1 = {
'name1': './src/package/module1'
},
map2 = {
'name2': './src/package/subpackage/module2',
'name3': './lib/module3'
};
useMap.config(map1, {
rootDir: "/Users/someone/project/"
});
useMap.config(map2);
expect(useMap.isConfigured).toBe(true);
expect(useMap.length).toEqual(3);
expect(useMap.map.name1).toEqual("/Users/someone/project/src/package/module1");
expect(useMap.map.name2).toEqual("/Users/someone/project/src/package/subpackage/module2");
expect(useMap.map.name3).toEqual("/Users/someone/project/lib/module3");
});
it("should allow a different root dir to be passed in, without overwriting the original rootDir", function() {
var map1 = {
'name1': './src/package/module1'
},
map2 = {
'name2': './package/subpackage/module2',
'name3': './module3'
};
useMap.config(map1, {
rootDir: "/Users/someone/project/"
});
useMap.config(map2, {
rootDir: "/Users/someone/project/subproj/"
});
expect(useMap.isConfigured).toBe(true);
expect(useMap.length).toEqual(3);
expect(useMap.map.name1).toEqual("/Users/someone/project/src/package/module1");
expect(useMap.map.name2).toEqual("/Users/someone/project/subproj/package/subpackage/module2");
expect(useMap.map.name3).toEqual("/Users/someone/project/subproj/module3");
expect(useMap.rootDir).toEqual("/Users/someone/project/");
});
it("should support an additional srcDir argument", function() {
var nameMap = {
'name1': './package/module1',
'name2': './package/subpackage/module2',
'name3': './module3'
};
useMap.config(nameMap, {
rootDir: "/Users/someone/project/",
srcDir: "./src"
});
expect(useMap.isConfigured).toBe(true);
expect(useMap.length).toEqual(3);
expect(useMap.map.name1).toEqual("/Users/someone/project/src/package/module1");
expect(useMap.map.name2).toEqual("/Users/someone/project/src/package/subpackage/module2");
expect(useMap.map.name3).toEqual("/Users/someone/project/src/module3");
});
it("should throw an error when rootDir is not defined", function() {
var nameMap = {
'name1': './package/module1',
'name2': './package/subpackage/module2',
'name3': './module3'
};
var err;
try {
useMap.config(nameMap);
} catch (e) {
err = e;
}
expect(err).toBeDefined();
expect(err.message).toEqual("PROJECT_ROOT_DIR_NOT_DEFINED");
});
});
describe("getPath", function() {
beforeEach(function() {
useMap.config({
'name1': './package/module1',
'name2': './package/subpackage/module2',
'name3': './module3'
},
{
rootDir: "/Users/someone/project/",
srcDir: "./src"
}
);
});
it("should return a path for a valid name", function() {
var p = useMap.getPath('name1');
expect(p).toBeDefined();
expect(p).toEqual("/Users/someone/project/src/package/module1");
});
it("should return undefined for an invalid name", function() {
var p = useMap.getPath('name0');
expect(p).not.toBeDefined();
});
});
describe("isFileLoaded", function() {
it("should return true when a certain config file has already been loaded", function() {
useMap.config({
'name1': './package/module1',
'name2': './package/subpackage/module2',
'name3': './module3'
},
{
rootDir: "/Users/someone/project/",
file: "/Users/someone/project/use.json"
}
);
expect(useMap.isFileLoaded("/Users/someone/project/use.json")).toEqual(true);
expect(useMap.isFileLoaded("/Users/someone/otherProject/use.json")).toEqual(false);
});
});
describe("dispose", function() {
it("should exist", function() {
expect(useMap.dispose).toBeDefined();
});
it("should dispose of all data within the map", function() {
useMap.config({
'name1': './package/module1',
'name2': './package/subpackage/module2',
'name3': './module3'
},
{
rootDir: "/Users/someone/project/",
file: "/Users/someone/project/use.json"
}
);
useMap.dispose();
expect(useMap.isConfigured).toBe(false);
expect(useMap.length).toEqual(0);
expect(useMap.files.length).toEqual(0);
expect(useMap.map['name1']).not.toBeDefined();
expect(useMap.rootDir).toBeNull();
});
});
});<file_sep>/example/in-code-config-example.js
console.log("Use-Import: In-Code Configuration Example");
var use = require('use-import').config({
"Class1": "./src/Class1",
"Class2": "./src/Class2",
"Class3": "./src/some/insane/directory/structure/Class3"
});
var Class1 = use('Class1');
var classOne = new Class1();
classOne.method();
<file_sep>/example/src/Class2.js
module.exports = (function() {
var use = require('use-import');
var Class3 = use('Class3');
var Class2 = function() {
this.type = "Class2";
this.classThree = new Class3();
this.method = function() {
console.log("Class2 Method Called!");
this.classThree.method();
};
};
return Class2;
})();
|
8b59d14275157dabc49f00b4672e5907a198a971
|
[
"JavaScript",
"Markdown"
] | 11 |
JavaScript
|
tinwatchman/use-import
|
a38aaa2b8410d8bfff7ff755d637562f23b3b226
|
b7450911a45060fda28994ef06fcc03d1f118113
|
refs/heads/master
|
<file_sep>
#include "util.h"
#include "face_lift.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <sys/time.h>
// just for debug
static LiftingSettings errorPrintParams;
static bool errorParamsAssigned = false;
void set_error_print_params(LiftingSettings* set)
{
errorParamsAssigned = true;
errorPrintParams = *set;
}
void error_exit(const char* str)
{
printf("Error: %s\n", str);
// print the params that caused the error
if (errorParamsAssigned)
{
printf("\nSettings:\n");
printf("Reach Time = %f\n", errorPrintParams.reachTime);
printf("Runtime = %i ms\n", errorPrintParams.maxRuntimeMilliseconds);
printf("Init = ");
println(&errorPrintParams.init);
}
else {
printf("Error print params were not assigned.\n");
}
fflush(stdout);
exit(1);
}
bool initialized = false;
long int startSec = 0;
long int milliseconds()
{
startSec = 0;
struct timeval now;
gettimeofday(&now, NULL);
if (!initialized)
{
initialized = true;
}
long int difSec = now.tv_sec - startSec;
long int ms = now.tv_usec / 1000;
long int ds = difSec * 1000 + ms;
// printf("from milliseconds: %ld\n",ds);
return ds;
}
long int milliseconds2(struct timeval * t1)
{
struct timeval now;
gettimeofday(&now, NULL);
// printf("t1_sec: %lld, npw_sec: %lld\n\n",(long long) t1->tv_sec,(long long) now.tv_sec);
long int elapsedTime;
elapsedTime = (now.tv_sec - t1->tv_sec) * 1000.0;
elapsedTime += (now.tv_usec - t1->tv_usec) / 1000.0;
return elapsedTime;
}
<file_sep>#include "dynamics_obstacle.h"
#include "dynamics_obstacle_model.h"
#include "util.h"
#include "interval.h"
#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
#include <math.h>
#ifdef DYNAMICS_OBSTACLE_MODEL
// Dynamical model for the UUV Obstacles.
// In the Simulation Environment, they are essentially constant moving large boxes
// So the model I'm using is a simple point particle simulation with constant speed that is configurable via
// input parameters.
// x' = v_x
// y' = v_y
// implement the derivative using interval arithmetic
double get_derivative_obstacle(HyperRectangle* rect, int faceIndex,REAL v_x, REAL v_y)
{
int dim = faceIndex / 2;
bool isMin = (faceIndex % 2) == 0;
Interval rv;
if( dim == 0 )
{
rv = new_interval_v(v_x);
}
else if(dim == 1)
{
rv = new_interval_v(v_y);
}
else
{
printf("Error: Invalid Dimension");
exit(0);
}
return isMin ? rv.min : rv.max;
}
#endif<file_sep>#!/bin/bash
pushd src
# Compile the source files needed to create the C shared library files
gcc -c -std=gnu99 -O3 -Wall -fpic face_lift_bicycle_model.c geometry.c interval.c simulate_bicycle.c util.c dynamics_bicycle_model.c bicycle_safety.c bicycle_model.c face_lift_bicycle_model_visualization.c bicycle_model_vis.c bicycle_dynamic_safety.c bicycle_model_dynamic_vis.c -lm
gcc -c -std=gnu99 -Wall -fpic face_lift_parametrizeable.c geometry.c interval.c util.c simulate_bicycle.c dynamics_bicycle_model.c bicycle_model_parametrizeable.c -lm
# There are five shared library files we need
gcc -shared -o libRtreachdyn.so face_lift_parametrizeable.o dynamics_bicycle_model.o geometry.o interval.o util.o simulate_bicycle.o bicycle_model_parametrizeable.o
gcc -shared -o libRtreach.so face_lift_bicycle_model.o bicycle_model.o dynamics_bicycle_model.o geometry.o interval.o simulate_bicycle.o util.o bicycle_safety.o
gcc -shared -o libRtreachvis.so face_lift_bicycle_model_visualization.o bicycle_model_vis.o dynamics_bicycle_model.o geometry.o interval.o simulate_bicycle.o util.o bicycle_safety.o
gcc -shared -o libRtreachDynamicvis.so face_lift_bicycle_model_visualization.o bicycle_model_dynamic_vis.o dynamics_bicycle_model.o geometry.o interval.o simulate_bicycle.o util.o bicycle_dynamic_safety.o
gcc -c -std=gnu99 -fpic face_lift_obstacle_visualization.c geometry.c interval.c util.c simulate_obstacle.c dynamics_obstacle.c obstacle_model_plots.c -lm -DOBSTACLE_MODEL
gcc -shared -o libRtreachObs.so face_lift_obstacle_visualization.o dynamics_obstacle.o geometry.o interval.o simulate_obstacle.o util.o obstacle_model_plots.o
popd
# create the rtreach rospkg
mkdir -p ../rtreach_ros/src
# copy the rospkg into the newly created directory
cp -r ros_src/rtreach/ ../rtreach_ros/src/
# copy the batch files into the rospkg
cp run_batch_rl.sh run_batch.sh reproduce_emsoft_experiments.sh run_emsoft_experiments.sh run_batch_worlds.sh ../rtreach_ros
# copy all the neccessary header files and library files into the rospackage
cp src/libRtreachDynamicvis.so src/libRtreachdyn.so src/libRtreachObs.so src/libRtreach.so src/libRtreachvis.so src/bicycle_dynamic_safety.h src/bicycle_model_parametrizeable.h src/bicycle_safety.h src/dynamics_bicycle.h src/dynamics_obstacle.h src/geometry.h src/main.h src/face_lift.h src/simulate_bicycle_plots.h src/simulate_obstacle.h ../rtreach_ros/src/rtreach/src/
pushd ../rtreach_ros
catkin_make
popd<file_sep>// <NAME>
// 10-2020
// Obstacle Model Header file
#ifndef DYNAMICS_OBSTACLE_MODEL_H_
#define DYNAMICS_OBSTACLE_MODEL_H_
#include <stdbool.h>
#include "geometry.h"
// This is the most basic model I could have used
double get_derivative_obstacle(HyperRectangle* rect, int faceIndex,REAL v_x, REAL v_y);
#endif<file_sep>#include "ros/ros.h"
#include <iostream>
#include <tf/tf.h>
#include <nav_msgs/Odometry.h>
#include <message_filters/subscriber.h>
// message files defined within this package
#include <rtreach/reach_tube.h>
#include <rtreach/angle_msg.h>
#include <rtreach/velocity_msg.h>
#include <rtreach/stamped_ttc.h>
#include <rtreach/obstacle_list.h>
#include <message_filters/synchronizer.h>
#include <message_filters/sync_policies/approximate_time.h>
#include <ros/package.h>
#include <ros/console.h>
#include "std_msgs/Float32.h"
#include <visualization_msgs/MarkerArray.h>
#include <visualization_msgs/Marker.h>
#include <math.h>
#include <cstdlib>
#include <memory>
// The following node will receive messages from the LEC which will be prediction of the steering angle
// It will also receive messages from the speed node which will dictate how fast the car should travel
// Initially the assmumption will be the the car moves at constant velocity
const int max_hyper_rectangles = 2000;
bool debug = false;
extern "C"
{
#include "bicycle_model_parametrizeable.h"
// run reachability for a given wall timer (or iterations if negative)
bool runReachability_bicycle_dyn(REAL* start, REAL simTime, REAL wallTimeMs, REAL startMs,REAL heading, REAL throttle,HyperRectangle VisStates[],int *total_intermediate,int max_intermediate,bool plot);
REAL getSimulatedSafeTime(REAL start[4],REAL heading_input, REAL throttle);
bool check_safety(HyperRectangle* rect, REAL (*cone)[2]);
HyperRectangle hr_list2[max_hyper_rectangles];
}
int count = 0;
int rect_count = 0;
bool safe=true;
ros::Publisher vis_pub;
rtreach::reach_tube static_obstacles;
double sim_time;
double state[4] = {0.0,0.0,0.0,0.0};
double control_input[2] = {0.0,0.0};
int wall_time;
int markers_allocated = 1;
bool bloat_reachset = true;
double ttc = 0.0;
int num_obstacles = 0;
double display_max;
int display_count = 1;
double display_increment = 1.0;
void callback(const nav_msgs::Odometry::ConstPtr& msg, const rtreach::velocity_msg::ConstPtr& velocity_msg,
const rtreach::angle_msg::ConstPtr& angle_msg, const rtreach::stamped_ttc::ConstPtr& ttc_msg)
{
using std::cout;
using std::endl;
double roll, pitch, yaw, lin_speed;
double x,y,u,delta,qx,qy,qz,qw,uh;
HyperRectangle hull;
ttc = ttc_msg->ttc;
// the lookahead time should be dictated by the lookahead time
// since the car is moving at 1 m/s the max sim time is 1.5 seconds
// sim_time = fmin(1.5*ttc,sim_time);
if(debug)
std::cout << "sim_time: " << sim_time << endl;
x = msg-> pose.pose.position.x;
y = msg-> pose.pose.position.y;
qx = msg->pose.pose.orientation.x;
qy = msg->pose.pose.orientation.y;
qz = msg->pose.pose.orientation.z;
qw = msg->pose.pose.orientation.w;
// define the quaternion matrix
tf::Quaternion q(
msg->pose.pose.orientation.x,
msg->pose.pose.orientation.y,
msg->pose.pose.orientation.z,
msg->pose.pose.orientation.w);
tf::Matrix3x3 m(q);
// convert to rpy
m.getRPY(roll, pitch, yaw);
// normalize the speed
tf::Vector3 speed = tf::Vector3(msg->twist.twist.linear.x, msg->twist.twist.linear.x, 0.0);
lin_speed = speed.length();
if(debug)
{
cout << "x: " << x;
cout << " y: " << y;
cout << " yaw: " << yaw;
cout << " speed: " << lin_speed << endl;
}
u = velocity_msg->velocity;
delta = angle_msg->steering_angle;
if(debug)
{
cout << "u: " << u << endl;
cout << "delta: " << delta << endl;
}
state[0] = x;
state[1] = y;
state[2] = lin_speed;
state[3] = yaw;
runReachability_bicycle_dyn(state, sim_time, wall_time, 0,delta,u,hr_list2,&rect_count,max_hyper_rectangles,true);
if(debug)
printf("num_boxes: %d, \n",rect_count);
visualization_msgs::MarkerArray ma;
display_increment = rect_count / display_max;
display_count = std::max(1.0,nearbyint(display_increment));
if(debug)
cout << "display_max: " << display_increment << ", display count: " << display_count << endl;
// allocate markers
for(int i= 0; i<std::min(max_hyper_rectangles-1,rect_count-1); i+=display_increment)
{
hull = hr_list2[i];
if(bloat_reachset)
{
hull.dims[0].min = hull.dims[0].min - 0.25;
hull.dims[0].max = hull.dims[0].max + 0.25;
hull.dims[1].min = hull.dims[1].min - 0.15;
hull.dims[1].max = hull.dims[1].max + 0.15;
}
visualization_msgs::Marker marker;
marker.header.frame_id = "/map";
marker.header.stamp = ros::Time::now();
marker.id = i;
marker.type = visualization_msgs::Marker::CUBE;
marker.action = visualization_msgs::Marker::ADD;
marker.pose.position.x = (hull.dims[0].max+hull.dims[0].min)/2.0;
marker.pose.position.y = (hull.dims[1].max+hull.dims[1].min)/2.0;
marker.pose.position.z = 0.5;
marker.pose.orientation.x = qx;
marker.pose.orientation.y = qy;
marker.pose.orientation.z = qz;
marker.pose.orientation.w = qw;
marker.scale.x = (hull.dims[0].max-hull.dims[0].min);
marker.scale.y = (hull.dims[1].max-hull.dims[1].min);
marker.scale.z = 0.05;
marker.color.a = 1.0;
marker.color.r = 0.0; //(double) rand() / (RAND_MAX);
marker.color.g = 0.0; //(double) rand() / (RAND_MAX);
marker.color.b = 0.8; //(double) rand() / (RAND_MAX);
marker.lifetime =ros::Duration(0.5);
ma.markers.push_back(marker);
}
vis_pub.publish(ma);
}
int main(int argc, char **argv)
{
using namespace message_filters;
int num_dynamic_obstacles;
std::string ego_vehicle;
// initialize the ros node
ros::init(argc, argv, "reach_node_param");
ros::NodeHandle n;
if(argv[1] == NULL)
{
std::cout << "Please give the walltime 10" << std::endl;
exit(0);
}
if(argv[2] == NULL)
{
std::cout << "Please give the sim time (e.g) 2" << std::endl;
exit(0);
}
if(argv[3] == NULL)
{
std::cout << "Please give the display max(e.g) 100" << std::endl;
exit(0);
}
if(argv[4] == NULL)
{
debug = false;
}
else
debug = (bool)atoi(argv[4]);
if(argv[5] == NULL)
{
ego_vehicle = "racecar2";
}
else {
ego_vehicle = argv[5];
}
// wall-time is how long we want the reachability algorithm to run
wall_time = atoi(argv[1]);
// sim-time is how far in the future we want the reachability algorithm to look into the future
sim_time = atof(argv[2]);
// as there are numerous boxes computed within the reachability computation, we must limit the number
// we send to rviz
display_max = atof(argv[3]);
// visualization publisher
vis_pub = n.advertise<visualization_msgs::MarkerArray>( ego_vehicle+"/reach_hull_param", 100 );
// Initialize the list of subscribers
message_filters::Subscriber<nav_msgs::Odometry> odom_sub(n, ego_vehicle+"/odom", 10);
message_filters::Subscriber<rtreach::velocity_msg> vel_sub(n, ego_vehicle+"/velocity_msg", 10);
message_filters::Subscriber<rtreach::angle_msg> angle_sub(n, ego_vehicle+"/angle_msg", 10);
message_filters::Subscriber<rtreach::stamped_ttc> ttc_sub(n, ego_vehicle+"/ttc", 10);
// message synchronizer
typedef sync_policies::ApproximateTime<nav_msgs::Odometry, rtreach::velocity_msg, rtreach::angle_msg,rtreach::stamped_ttc> MySyncPolicy;
// ApproximateTime takes a queue size as its constructor argument, hence MySyncPolicy(10)
Synchronizer<MySyncPolicy> sync(MySyncPolicy(100), odom_sub, vel_sub,angle_sub,ttc_sub);//,interval_sub);
sync.registerCallback(boost::bind(&callback, _1, _2,_3,_4));
while(ros::ok())
{
ros::spinOnce();
}
return 0;
}
<file_sep>FROM ros:kinetic-robot
RUN apt-get update && apt-get install apt-transport-https
RUN apt-get update && apt-get install -y ros-kinetic-ros-control ros-kinetic-ros-controllers ros-kinetic-gazebo-ros-control ros-kinetic-ackermann-msgs ros-kinetic-joy
RUN apt-get update && apt-get install -y ros-kinetic-teb-local-planner ros-kinetic-move-base ros-kinetic-navigation ros-kinetic-hector-slam ros-kinetic-driver-common ros-kinetic-actionlib
#install pip
RUN apt-get install -y python-pip && apt-get install -y python3-pip
RUN pip install rospkg defusedxml PySide2
RUN pip install empy
#Need these packages for debugging
RUN apt-get install -y nano
RUN apt-get install -y net-tools
# bootstrap rosdep
RUN rosdep update
# clone the repository
RUN git clone https://github.com/pmusau17/rtreach_f1tenth.git
WORKDIR rtreach_f1tenth/
RUN /bin/bash -c "git pull && source /opt/ros/kinetic/setup.bash && ./build_rtreach.sh"
WORKDIR ..
WORKDIR rtreach_ros/
RUN ls src/rtreach/launch
CMD /bin/bash -c "source devel/setup.bash && rosrun rtreach reach_node porto_obstacles.txt"
<file_sep>// <NAME>
// 11-2020
// Simulate Header
#ifndef SIMULATE_OBSTACLE_H_
#define SIMULATE_OBSTACLE_H_
#include "geometry.h"
#include "main.h"
#include <stdbool.h>
// simulate dynamics using Euler's method
void simulate_obstacle(REAL point[NUM_DIMS], REAL v_x, REAL v_y,
REAL stepSize,
bool (*shouldStop)(REAL state[NUM_DIMS], REAL simTime, void* p),
void* param);
#endif
<file_sep>// example call: ./obstacle 10 0 0 1.0 0.0
// example call output:
// started!
// Argc: 7
// runtime: 10 ms
// x_0[0]: 0.0
// x_0[1]: 0.0
// u_0[0]: 1.0
// u_0[1]: 0.0
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "util.h"
#include "main.h"
#include "obstacle_model_vis.h"
#include "simulate_obstacle.h"
const int state_n = 2; // state dimension
const int max_hyper_rectangles = 2000;
int main( int argc, const char* argv[] )
{
DEBUG_PRINT("started!\n\r");
int runtimeMs = 0;
REAL startState[2] = {0.0, 0.0};
REAL v_u[2] = {0.0,0.0};
DEBUG_PRINT("Argc: %d\n\r", argc);
if (argc < 6) {
printf("Error: not enough input arguments!\n\r");
return 0;
}
else {
runtimeMs = atoi(argv[1]);
startState[0] = atof(argv[2]);
startState[1] = atof(argv[3]);
v_u[0] = atof(argv[4]);
v_u[1] = atof(argv[5]);
DEBUG_PRINT("runtime: %d ms\n\rx_0[0]: %f\n\rx_0[1]: %f\n\ru_0[0]: %f\n\ru_0[1]: %f\n\r\n", runtimeMs, startState[0], startState[1],v_u[0],v_u[1]);
}
REAL v_x = v_u[0];
REAL v_y = v_u[1];
// simTime
REAL timeToSafe = 2.0;
// startMs
int startMs = 0;
// define array of hyperrectangles (array of structs)
HyperRectangle hr_list[max_hyper_rectangles];
HyperRectangle hr_list2[max_hyper_rectangles];
// num_rects
int rects = 0;
int rects2 = 0;
bool plot_all= true;
getSimulatedSafeTime(startState,v_x,v_y);
printf("\n");
// run reachability analysis test
HyperRectangle reach_hull = runReachability_obstacle_vis(startState, timeToSafe, runtimeMs, startMs,v_x,v_y,hr_list,&rects,max_hyper_rectangles,plot_all);
DEBUG_PRINT("Number of Iterations: %d\n",iterations_at_quit);
HyperRectangle reach_hull2 = runReachability_obstacle_vis(startState, timeToSafe, runtimeMs, startMs,v_x+0.1,v_y+0.1,hr_list2,&rects2,max_hyper_rectangles,plot_all);
DEBUG_PRINT("Number of Iterations: %d\n",iterations_at_quit);
// DEBUG_PRINT("done, result = %s\n", safe ? "safe" : "unsafe");
// // print the hull
printf("%d\n", rects);
printf("%d\n", rects2);
for(int i= 0; i<10; i++)
{
println(&hr_list[i]);
}
printf("\n\n States 2 \n");
for(int i= 0; i<10; i++)
{
println(&hr_list2[i]);
}
printf("\n\n Final States\n");
println(&reach_hull);
println(&reach_hull2);
return 0;
}<file_sep>#include "ros/ros.h"
#include <iostream>
#include <tf/tf.h>
#include <nav_msgs/Odometry.h>
#include <message_filters/subscriber.h>
// message files defined within this package
#include <rtreach/reach_tube.h>
#include <rtreach/angle_msg.h>
#include <rtreach/velocity_msg.h>
#include <rtreach/stamped_ttc.h>
#include <rtreach/obstacle_list.h>
#include <message_filters/synchronizer.h>
#include <message_filters/sync_policies/approximate_time.h>
#include <ros/package.h>
#include <ros/console.h>
#include "std_msgs/Float32.h"
#include <visualization_msgs/MarkerArray.h>
#include <visualization_msgs/Marker.h>
#include <math.h>
#include <cstdlib>
#include <memory>
// The following node will receive messages from the LEC which will be prediction of the steering angle
// It will also receive messages from the speed node which will dictate how fast the car should travel
// Initially the assmumption will be the the car moves at constant velocity
const int max_hyper_rectangles = 2000;
extern "C"
{
#include "bicycle_model_parametrizeable.h"
// run reachability for a given wall timer (or iterations if negative)
bool runReachability_bicycle_dyn(REAL* start, REAL simTime, REAL wallTimeMs, REAL startMs,REAL heading, REAL throttle,HyperRectangle VisStates[],int *total_intermediate,int max_intermediate,bool plot);
REAL getSimulatedSafeTime(REAL start[4],REAL heading_input, REAL throttle);
bool check_safety(HyperRectangle* rect, REAL (*cone)[2]);
HyperRectangle hr_list2[max_hyper_rectangles];
void println(HyperRectangle* r);
}
int count = 0;
int rect_count = 0;
bool safe=true;
bool debug = false;
ros::Publisher res_pub;
//ros::Publisher res_pub; // publisher for reachability results
//ros::ServiceClient client; // obstacle_service client
//rtreach::obstacle_list srv;// service call
rtreach::reach_tube static_obstacles;
double sim_time;
double state[4] = {0.0,0.0,0.0,0.0};
double control_input[2] = {0.0,0.0};
int wall_time;
int markers_allocated = 1;
bool bloat_reachset = true;
double ttc = 0.0;
int num_obstacles = 0;
double display_max;
int display_count = 1;
double display_increment = 1.0;
// Naive O(N^2) check
bool check_obstacle_safety(rtreach::reach_tube obs,HyperRectangle VisStates[],int rect_count)
{
bool safe = true;
HyperRectangle hull;
double cone[2][2] = {{0.0,0.0},{0.0,0.0}};
std::cout << "obs_count: " << obs.count << ", rect_count: "<< rect_count << std::endl;
for (int i=0;i<obs.count;i++)
{
if(!safe)
{
break;
}
cone[0][0] = obs.obstacle_list[i].x_min;
cone[0][1] = obs.obstacle_list[i].x_max;
cone[1][0] = obs.obstacle_list[i].y_min;
cone[1][1] = obs.obstacle_list[i].y_max;
for(int j = 0; j<rect_count;j++)
{
hull = VisStates[j];
hull.dims[0].min = hull.dims[0].min - 0.25;
hull.dims[0].max = hull.dims[0].max + 0.25;
hull.dims[1].min = hull.dims[1].min - 0.15;
hull.dims[1].max = hull.dims[1].max + 0.15;
safe = check_safety(&hull,cone);
if(!safe)
{
break;
}
}
}
return safe;
}
void callback(const nav_msgs::Odometry::ConstPtr& msg, const rtreach::velocity_msg::ConstPtr& velocity_msg,
const rtreach::angle_msg::ConstPtr& angle_msg, const rtreach::stamped_ttc::ConstPtr& ttc_msg,const rtreach::reach_tube::ConstPtr& obs1, const rtreach::reach_tube::ConstPtr& obs2,const rtreach::reach_tube::ConstPtr& wall)//,const rtreach::obstacle_list::ConstPtr& obs_msg)
{
using std::cout;
using std::endl;
double roll, pitch, yaw, lin_speed;
double x,y,u,delta,qx,qy,qz,qw,uh;
HyperRectangle hull;
ttc = ttc_msg->ttc;
// the lookahead time should be dictated by the lookahead time
// since the car is moving at 1 m/s the max sim time is 1.5 seconds
// need to look into this safety specification more earnestly
// sim_time = fmin(1.5*ttc,sim_time);
std::cout << "sim_time: " << sim_time << endl;
x = msg-> pose.pose.position.x;
y = msg-> pose.pose.position.y;
qx = msg->pose.pose.orientation.x;
qy = msg->pose.pose.orientation.y;
qz = msg->pose.pose.orientation.z;
qw = msg->pose.pose.orientation.w;
// define the quaternion matrix
tf::Quaternion q(
msg->pose.pose.orientation.x,
msg->pose.pose.orientation.y,
msg->pose.pose.orientation.z,
msg->pose.pose.orientation.w);
tf::Matrix3x3 m(q);
// convert to rpy
m.getRPY(roll, pitch, yaw);
// normalize the speed
tf::Vector3 speed = tf::Vector3(msg->twist.twist.linear.x, msg->twist.twist.linear.x, 0.0);
lin_speed = speed.length();
cout << "x: " << x;
cout << " y: " << y;
cout << " yaw: " << yaw;
cout << " speed: " << lin_speed << endl;
u = velocity_msg->velocity;
delta = angle_msg->steering_angle;
cout << "u: " << u << endl;
cout << "delta: " << delta << endl;
state[0] = x;
state[1] = y;
state[2] = lin_speed;
state[3] = yaw;
runReachability_bicycle_dyn(state, sim_time, wall_time, 0,delta,u,hr_list2,&rect_count,max_hyper_rectangles,true);
printf("num_boxes: %d, obs1 count: %d, obs2 count: %d, \n",rect_count,obs1->count,obs2->count);
// do the safety checking between the dynamic obstacles here
if(obs1->count>0)
{
safe = check_obstacle_safety(*obs1,hr_list2,std::min(max_hyper_rectangles,rect_count));
}
if(obs2->count>0 && safe)
{
safe = check_obstacle_safety(*obs2,hr_list2,std::min(max_hyper_rectangles,rect_count));
}
if(wall->count>0 && safe)
{
safe = check_obstacle_safety(*wall,hr_list2,std::min(max_hyper_rectangles,rect_count));
}
std_msgs::Float32 res_msg;
res_msg.data = (double)safe;
res_pub.publish(res_msg);
printf("safe: %d\n",safe);
}
int main(int argc, char **argv)
{
using namespace message_filters;
int num_dynamic_obstacles;
std::string controller_topic;
std::string result_topic = "reachability_result";
// initialize the ros node
ros::init(argc, argv, "reach",ros::init_options::AnonymousName);
ros::NodeHandle n;
if(argv[1] == NULL)
{
std::cout << "Please give the walltime 10" << std::endl;
exit(0);
}
if(argv[2] == NULL)
{
std::cout << "Please give the sim time (e.g) 2" << std::endl;
exit(0);
}
if(argv[3] == NULL)
{
std::cout << "Please give the display max(e.g) 100" << std::endl;
exit(0);
}
if(argc <4)
{
debug = false;
}
else
debug = (bool)atoi(argv[4]);
if(argc<5)
{
controller_topic = "racecar2/angle_msg";
}
else
{
controller_topic = argv[5];
result_topic = controller_topic+"/reachability_result";
if(controller_topic=="racecar2/angle_msg")
result_topic ="reachability_result";
}
std::cout << controller_topic << result_topic << std::endl;
// wall-time is how long we want the reachability algorithm to run
wall_time = atoi(argv[1]);
// sim-time is how far in the future we want the reachability algorithm to look into the future
sim_time = atof(argv[2]);
// as there are numerous boxes computed within the reachability computation, we must limit the number
// we send to rviz
display_max = atof(argv[3]);
// Initialize the list of subscribers
message_filters::Subscriber<nav_msgs::Odometry> odom_sub(n, "racecar2/odom", 10);
message_filters::Subscriber<rtreach::velocity_msg> vel_sub(n, "racecar2/velocity_msg", 10);
message_filters::Subscriber<rtreach::angle_msg> angle_sub(n, controller_topic, 10);
message_filters::Subscriber<rtreach::stamped_ttc> ttc_sub(n, "racecar2/ttc", 10);
message_filters::Subscriber<rtreach::reach_tube> obs1(n,"racecar/reach_tube",10);
message_filters::Subscriber<rtreach::reach_tube> obs2(n,"racecar3/reach_tube",10);
message_filters::Subscriber<rtreach::reach_tube> wall(n,"wallpoints",10);
res_pub = n.advertise<std_msgs::Float32>(result_topic, 10);
// message synchronizer
typedef sync_policies::ApproximateTime<nav_msgs::Odometry, rtreach::velocity_msg, rtreach::angle_msg,rtreach::stamped_ttc,rtreach::reach_tube,rtreach::reach_tube,rtreach::reach_tube> MySyncPolicy;
// ApproximateTime takes a queue size as its constructor argument, hence MySyncPolicy(10)
Synchronizer<MySyncPolicy> sync(MySyncPolicy(100), odom_sub, vel_sub,angle_sub,ttc_sub,obs1,obs2,wall);//,interval_sub);
sync.registerCallback(boost::bind(&callback, _1, _2,_3,_4,_5,_6,_7));
while(ros::ok())
{
// call service periodically
ros::spinOnce();
}
return 0;
}<file_sep>// example call: ./obstacle 10 0 0 1.0 0.0
// example call output:
// started!
// Argc: 7
// runtime: 10 ms
// x_0[0]: 0.0
// x_0[1]: 0.0
// u_0[0]: 1.0
// u_0[1]: 0.0
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "util.h"
#include "main.h"
#include "obstacle_model.h"
#include "simulate_obstacle.h"
const int state_n = 2; // state dimension
int main( int argc, const char* argv[] )
{
DEBUG_PRINT("started!\n\r");
int runtimeMs = 0;
REAL startState[2] = {0.0, 0.0};
REAL v_u[2] = {0.0,0.0};
DEBUG_PRINT("Argc: %d\n\r", argc);
if (argc < 6) {
printf("Error: not enough input arguments!\n\r");
return 0;
}
else {
runtimeMs = atoi(argv[1]);
startState[0] = atof(argv[2]);
startState[1] = atof(argv[3]);
v_u[0] = atof(argv[4]);
v_u[1] = atof(argv[5]);
DEBUG_PRINT("runtime: %d ms\n\rx_0[0]: %f\n\rx_0[1]: %f\n\ru_0[0]: %f\n\ru_0[1]: %f\n\r\n", runtimeMs, startState[0], startState[1],v_u[0],v_u[1]);
}
REAL v_x = v_u[0];
REAL v_y = v_u[1];
// simTime
REAL timeToSafe = 2.0;
// startMs
int startMs = 0;
getSimulatedSafeTime(startState,v_x,v_y);
printf("\n");
// run reachability analysis test
bool safe = runReachability_obstacle(startState, timeToSafe, runtimeMs, startMs,v_x,v_y);
DEBUG_PRINT("done, result = %s\n", safe ? "safe" : "unsafe");
DEBUG_PRINT("Number of Iterations: %d\n",iterations_at_quit);
// // print the hull
// println(&reach_hull);
// deallocate_2darr(file_rows,file_columns);
// deallocate_obstacles(obstacle_count);
return 0;
}<file_sep>// <NAME>
// 11-2020
// UUV model header
#ifndef OBSTACLE_H_
#define OBSTACLE_H_
#include "main.h"
#include "geometry.h"
#include <stdbool.h>
// run reachability for a given wall timer (or iterations if negative)
bool runReachability_obstacle(REAL* start, REAL simTime, REAL wallTimeMs, REAL startMs,REAL v_x, REAL v_y);
HyperRectangle runReachability_obstacle_vis(REAL* start, REAL simTime, REAL wallTimeMs, REAL startMs,REAL v_x, REAL v_y);
REAL getSimulatedSafeTime(REAL start[2],REAL v_x, REAL v_y);
#endif<file_sep>// example call: ./bicycle 100 0.0 0.0 0.0 0.0 16.0 0.26666
// example call output:
// started!
// Argc: 6
// runtime: 100 ms
// x_0[0]: -0.100000
// x_0[1]: 0.000000
// x_0[2]: 0.000000
// x_0[3]: 1.100000
// u_0[0]: 16.0
// u_1[1]: 0.266
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "util.h"
#include "main.h"
#include "bicycle_model.h"
#include "bicycle_safety.h"
#include "simulate_bicycle_plots.h"
const int state_n = 4; // state dimension
// This particular example also needs to know where the walls are
const char * filepath= "../ros_src/rtreach/obstacles/porto_obstacles.txt";
int main( int argc, const char* argv[] )
{
DEBUG_PRINT("started!\n\r");
int runtimeMs = 0;
REAL startState[4] = {0.0, 0.0, 0.0, 0.0};
REAL control_input[2] = {0.0,0.0};
DEBUG_PRINT("Argc: %d\n\r", argc);
if (argc < 8) {
printf("Error: not enough input arguments!\n\r");
return 0;
}
else {
runtimeMs = atoi(argv[1]);
startState[0] = atof(argv[2]);
startState[1] = atof(argv[3]);
startState[2] = atof(argv[4]);
startState[3] = atof(argv[5]);
printf("%f\n",startState[0]);
control_input[0] = atof(argv[6]);
control_input[1] = atof(argv[7]);
DEBUG_PRINT("runtime: %d ms\n\rx_0[0]: %f\n\rx_0[1]: %f\n\rx_0[2]: %f\n\rx_0[3]: %f\n\ru_0[0]: %f\n\ru_0[1]: %f\n\r\n", runtimeMs, startState[0], startState[1], startState[2], startState[3],control_input[0],control_input[1]);
}
REAL delta = control_input[1];
REAL u = control_input[0];
// simTime
REAL timeToSafe = 2.0;
// startMs
int startMs = 0;
// load the wall points into the global variable
load_wallpoints(filepath,true);
// location of obstacles in our scenario
int num_obstacles = 5;
double points[5][2] = {{2.0,2.0},{4.7,2.7},{11.36,-1.46},{3.0,6.4},{-9.64,2.96}};
allocate_obstacles(num_obstacles,points);
printf("offending cone (%f,%f) (%f, %f)\n",obstacles[0][0][0],obstacles[0][0][1],obstacles[0][1][0],obstacles[0][1][1]);
// run reachability analysis test
HyperRectangle reach_hull = runReachability_bicycle_vis(startState, timeToSafe, runtimeMs, startMs,delta,u);
DEBUG_PRINT("Number of Iterations: %d\n",iterations_at_quit);
printf("\n");
printf("num VisStates: %d\n",num_intermediate);
printf("total encountered intermediate: %d\n",total_intermediate);
// println(&VisStates[num_intermediate-2]);
// println(&VisStates[num_intermediate-1]);
for (int i =0; i < num_intermediate; i+=2)
{
println(&VisStates[i]);
}
// print the hull
println(&reach_hull);
deallocate_2darr(file_rows,file_columns);
deallocate_obstacles(obstacle_count);
return 0;
}<file_sep>#!/bin/bash
# Notes (mostly for me)
# $! Contains the process ID of the most recently executed background pipeline
# $? This the exit status of the last executed command
# The linux trap command allows you to catch signals and execute code when they occur
# SIGINT is generated when you type Ctrl-C at the keyboard to interrupt a running script
# kill -INT $pid sends the "interrupt" signal to the process with process ID pid.
# However, the process may decide to ignore the signal, or catch the signal and do
# something before exiting and/or ignore it.
if [ -n "$1" ]; then
world=$1
else
world='0'
fi
# Change this to select the algorithm
# 0 is e2e image 1 is e2e porto training, 2 is SAC, 3 is ddpg, 4 is e2e all tracks
algorithm_number=0
# Select the velocity for evaluation
velocity=1.0
# this keeps track of how many experiments we have run
count=0
exit_status=0
_term() {
exit_status=$? # = 130 for SIGINT
echo "Caught SIGINT signal!"
kill -INT "$child" 2>/dev/null
}
trap _term SIGINT
while [ $count -lt 30 ]
do
((count=count+1))
roslaunch race sim_for_rtreach_batch_worlds.launch world_number:=$world algorithm:=$algorithm_number velocity:=$velocity timeout:=60 &
child=$!
wait "$child"
if [ $exit_status -eq 130 ]; then
# SIGINT was captured meaning the user
# wants full stop instead of start_simulation.launch
# terminating normally from end of episode so...
echo "stop looping"
break
fi
echo count: $count
done<file_sep>#include "ros/ros.h"
#include <iostream>
#include <tf/tf.h>
#include <nav_msgs/Odometry.h>
#include <message_filters/subscriber.h>
// message files defined within this package
#include <rtreach/reach_tube.h>
#include <rtreach/angle_msg.h>
#include <rtreach/velocity_msg.h>
#include <rtreach/stamped_ttc.h>
#include <rtreach/obstacle_list.h>
#include <message_filters/synchronizer.h>
#include <message_filters/sync_policies/approximate_time.h>
#include <ros/package.h>
#include <ros/console.h>
#include "std_msgs/Float32.h"
#include <visualization_msgs/MarkerArray.h>
#include <visualization_msgs/Marker.h>
#include <math.h>
#include <cstdlib>
#include <memory>
#include<ctime>
#include <fstream>
#include <string>
// The following node will receive messages from the LEC which will be prediction of the steering angle
// It will also receive messages from the speed node which will dictate how fast the car should travel
// Initially the assmumption will be the the car moves at constant velocity
const int max_hyper_rectangles = 2000;
extern "C"
{
#include "bicycle_model_parametrizeable.h"
#include "face_lift.h"
// run reachability for a given wall timer (or iterations if negative)
bool runReachability_bicycle_dyn(REAL* start, REAL simTime, REAL wallTimeMs, REAL startMs,REAL heading, REAL throttle,HyperRectangle VisStates[],int *total_intermediate,int max_intermediate,bool plot);
REAL getSimulatedSafeTime(REAL start[4],REAL heading_input, REAL throttle);
bool check_safety(HyperRectangle* rect, REAL (*cone)[2]);
HyperRectangle hr_list2[max_hyper_rectangles];
void println(HyperRectangle* r);
}
int count = 0;
int rect_count = 0;
bool safe=true;
bool debug = false;
ros::Publisher res_pub;
//ros::Publisher res_pub; // publisher for reachability results
//ros::ServiceClient client; // obstacle_service client
//rtreach::obstacle_list srv;// service call
rtreach::reach_tube static_obstacles;
double sim_time;
double state[4] = {0.0,0.0,0.0,0.0};
double control_input[2] = {0.0,0.0};
int wall_time;
int markers_allocated = 1;
bool bloat_reachset = true;
double ttc = 0.0;
int num_obstacles = 0;
double display_max;
int display_count = 1;
double display_increment = 1.0;
clock_t start, end,total_start,total_end, reach_start, reach_end;
// variable for cumulative moving average
double iter_count = 0.0;
double avg_reach_time = 0.0;
double avg_iterations = 0.0;
double avg_checking_time = 0.0;
double checking_time = 0.0;
double new_mean;
double differential;
double itq;
double wcet = 0.0;
double wcet_checking =0.0;
// Naive O(N^2) check
bool check_obstacle_safety(rtreach::reach_tube obs,HyperRectangle VisStates[],int rect_count)
{
bool safe = true;
HyperRectangle hull;
double cone[2][2] = {{0.0,0.0},{0.0,0.0}};
std::cout << "obs_count: " << obs.count << ", rect_count: "<< rect_count << std::endl;
for (int i=0;i<obs.count;i++)
{
if(!safe)
{
break;
}
cone[0][0] = obs.obstacle_list[i].x_min;
cone[0][1] = obs.obstacle_list[i].x_max;
cone[1][0] = obs.obstacle_list[i].y_min;
cone[1][1] = obs.obstacle_list[i].y_max;
for(int j = 0; j<rect_count;j++)
{
hull = VisStates[j];
hull.dims[0].min = hull.dims[0].min - 0.25;
hull.dims[0].max = hull.dims[0].max + 0.25;
hull.dims[1].min = hull.dims[1].min - 0.15;
hull.dims[1].max = hull.dims[1].max + 0.15;
safe = check_safety(&hull,cone);
if(!safe)
{
break;
}
}
}
return safe;
}
void callback(const nav_msgs::Odometry::ConstPtr& msg, const rtreach::velocity_msg::ConstPtr& velocity_msg,
const rtreach::angle_msg::ConstPtr& angle_msg, const rtreach::stamped_ttc::ConstPtr& ttc_msg,const rtreach::reach_tube::ConstPtr& obs1, const rtreach::reach_tube::ConstPtr& obs2,const rtreach::reach_tube::ConstPtr& wall)//,const rtreach::obstacle_list::ConstPtr& obs_msg)
{
using std::cout;
using std::endl;
double roll, pitch, yaw, lin_speed;
double x,y,u,delta,qx,qy,qz,qw,uh;
HyperRectangle hull;
ttc = ttc_msg->ttc;
// the lookahead time should be dictated by the lookahead time
// since the car is moving at 1 m/s the max sim time is 1.5 seconds
// need to look into this safety specification more earnestly
// sim_time = fmin(1.5*ttc,sim_time);
std::cout << "sim_time: " << sim_time << endl;
x = msg-> pose.pose.position.x;
y = msg-> pose.pose.position.y;
qx = msg->pose.pose.orientation.x;
qy = msg->pose.pose.orientation.y;
qz = msg->pose.pose.orientation.z;
qw = msg->pose.pose.orientation.w;
// define the quaternion matrix
tf::Quaternion q(
msg->pose.pose.orientation.x,
msg->pose.pose.orientation.y,
msg->pose.pose.orientation.z,
msg->pose.pose.orientation.w);
tf::Matrix3x3 m(q);
// convert to rpy
m.getRPY(roll, pitch, yaw);
// normalize the speed
tf::Vector3 speed = tf::Vector3(msg->twist.twist.linear.x, msg->twist.twist.linear.x, 0.0);
lin_speed = speed.length();
cout << "x: " << x;
cout << " y: " << y;
cout << " yaw: " << yaw;
cout << " speed: " << lin_speed << endl;
u = velocity_msg->velocity;
delta = angle_msg->steering_angle;
cout << "u: " << u << endl;
cout << "delta: " << delta << endl;
state[0] = x;
state[1] = y;
state[2] = lin_speed;
state[3] = yaw;
// do the timing for the reachability
reach_start = clock();
runReachability_bicycle_dyn(state, sim_time, wall_time, 0,delta,u,hr_list2,&rect_count,max_hyper_rectangles,true);
reach_end = clock();
double reach_time = double(reach_end - reach_start) / double(CLOCKS_PER_SEC);
// do the timing for the reachability
reach_start = clock();
if(obs1->count>0)
{
safe = check_obstacle_safety(*obs1,hr_list2,std::min(max_hyper_rectangles,rect_count));
}
if(obs2->count>0 && safe)
{
safe = check_obstacle_safety(*obs2,hr_list2,std::min(max_hyper_rectangles,rect_count));
}
if(wall->count>0 && safe)
{
safe = check_obstacle_safety(*wall,hr_list2,std::min(max_hyper_rectangles,rect_count));
}
reach_end = clock();
checking_time = double(reach_end - reach_start) / double(CLOCKS_PER_SEC);
if(reach_time>wcet)
{
wcet = reach_time;
}
if(checking_time>wcet_checking)
{
wcet_checking = checking_time;
}
// calculate exponential moving average
iter_count++;
differential = (reach_time - avg_reach_time) / iter_count;
new_mean = avg_reach_time + differential;
avg_reach_time = new_mean;
// calculate exponential moving average of iterations
itq = (double)iterations_at_quit;
differential = (iterations_at_quit-avg_iterations) / iter_count;
new_mean = avg_iterations+differential;
avg_iterations = new_mean;
differential = (checking_time - avg_checking_time) / iter_count;
new_mean = avg_checking_time + differential;
avg_checking_time = new_mean;
std_msgs::Float32 res_msg;
res_msg.data = (double)safe;
res_pub.publish(res_msg);
printf("safe: %d\n",safe);
}
int main(int argc, char **argv)
{
using namespace message_filters;
int num_dynamic_obstacles;
std::string controller_topic;
std::string result_topic = "reachability_result";
std::string save_path;
save_path = ros::package::getPath("rtreach") +"/benchmarking/"+"dynamic_experiments.csv";
// initialize the ros node
ros::init(argc, argv, "reach",ros::init_options::AnonymousName);
ros::NodeHandle n;
if(argv[1] == NULL)
{
std::cout << "Please give the walltime 10" << std::endl;
exit(0);
}
if(argv[2] == NULL)
{
std::cout << "Please give the sim time (e.g) 2" << std::endl;
exit(0);
}
if(argv[3] == NULL)
{
std::cout << "Please give the display max(e.g) 100" << std::endl;
exit(0);
}
if(argc <4)
{
debug = false;
}
else
debug = (bool)atoi(argv[4]);
if(argc<5)
{
controller_topic = "racecar2/angle_msg";
}
else
{
controller_topic = argv[5];
result_topic = controller_topic+"/reachability_result";
if(controller_topic=="racecar2/angle_msg")
result_topic ="reachability_result";
}
std::cout << controller_topic << result_topic << std::endl;
// wall-time is how long we want the reachability algorithm to run
wall_time = atoi(argv[1]);
// sim-time is how far in the future we want the reachability algorithm to look into the future
sim_time = atof(argv[2]);
// as there are numerous boxes computed within the reachability computation, we must limit the number
// we send to rviz
display_max = atof(argv[3]);
// Initialize the list of subscribers
message_filters::Subscriber<nav_msgs::Odometry> odom_sub(n, "racecar2/odom", 10);
message_filters::Subscriber<rtreach::velocity_msg> vel_sub(n, "racecar2/velocity_msg", 10);
message_filters::Subscriber<rtreach::angle_msg> angle_sub(n, controller_topic, 10);
message_filters::Subscriber<rtreach::stamped_ttc> ttc_sub(n, "racecar2/ttc", 10);
message_filters::Subscriber<rtreach::reach_tube> obs1(n,"racecar/reach_tube",10);
message_filters::Subscriber<rtreach::reach_tube> obs2(n,"racecar3/reach_tube",10);
message_filters::Subscriber<rtreach::reach_tube> wall(n,"wallpoints",10);
res_pub = n.advertise<std_msgs::Float32>(result_topic, 10);
// message synchronizer
typedef sync_policies::ApproximateTime<nav_msgs::Odometry, rtreach::velocity_msg, rtreach::angle_msg,rtreach::stamped_ttc,rtreach::reach_tube,rtreach::reach_tube,rtreach::reach_tube> MySyncPolicy;
// ApproximateTime takes a queue size as its constructor argument, hence MySyncPolicy(10)
Synchronizer<MySyncPolicy> sync(MySyncPolicy(100), odom_sub, vel_sub,angle_sub,ttc_sub,obs1,obs2,wall);//,interval_sub);
sync.registerCallback(boost::bind(&callback, _1, _2,_3,_4,_5,_6,_7));
while(ros::ok())
{
// call service periodically
ros::spinOnce();
}
std::ofstream outfile(save_path.c_str() , std::ios::app);
outfile << wcet << "," << avg_reach_time << "," << avg_iterations << "," << avg_checking_time << "," << wcet_checking << "\n";
outfile.close();
return 0;
}<file_sep>#include "interval.h"
#include "stdio.h"
#include <math.h>
// for matlab, compiler may not have M_PI defined
#ifndef M_PI
# define M_PI 3.141592653589793238
#endif
#define TWO_PI (2*M_PI)
Interval new_interval(double min, double max)
{
Interval rv;
rv.min = min;
rv.max = max;
return rv;
}
Interval new_interval_v(double val)
{
Interval rv;
rv.min = rv.max = val;
return rv;
}
Interval add_interval(Interval i, Interval j)
{
Interval rv;
double a = i.min;
double b = i.max;
double c = j.min;
double d = j.max;
rv.min = a + c;
rv.max = b + d;
return rv;
}
Interval sub_interval(Interval i, Interval j)
{
Interval rv;
double a = i.min;
double b = i.max;
double c = j.min;
double d = j.max;
rv.min = a - d;
rv.max = b - c;
return rv;
}
Interval mul_interval(Interval i, Interval j)
{
Interval rv;
double a = i.min;
double b = i.max;
double c = j.min;
double d = j.max;
rv.min = fmin(fmin(a*c,a*d), fmin(b*c,b*d));
rv.max = fmax(fmax(a*c,a*d), fmax(b*c,b*d));
return rv;
}
Interval div_interval(Interval i, Interval j)
{
double c = j.min;
double d = j.max;
return mul_interval(i, new_interval(1 / d, 1 / c));
}
Interval pow_interval(Interval i, int n) // a^n
{
double a = i.min;
double b = i.max;
double c = 0;
double d = 0;
if (n % 2 == 1)
{
c = pow(a, n);
d = pow(b, n);
}
else
{
if (a >= 0)
{
c = pow(a, n);
d = pow(b, n);
}
else if (b < 0)
{
c = pow(b, n);
d = pow(a, n);
}
else
{
c = 0;
d = fmax(pow(a, n), pow(b, n));
}
}
return new_interval(c, d);
}
Interval sin_interval(Interval i)
{
double a = i.min;
double b = i.max;
double c = 0;
double d = 0;
if (floor((a-1.5*M_PI) / TWO_PI) != floor((b-1.5*M_PI) / TWO_PI))
c = -1;
else
c = fmin(sin(a), sin(b));
if (floor((a-0.5*M_PI) / TWO_PI) != floor((b-0.5*M_PI) / TWO_PI))
d = 1;
else
d = fmax(sin(a), sin(b));
return new_interval(c, d);
}
Interval cos_interval(Interval i)
{
double a = i.min;
double b = i.max;
double c = 0;
double d = 0;
if (floor((a+M_PI) / TWO_PI) != floor((b+M_PI) / TWO_PI))
c = -1;
else
c = fmin(cos(a), cos(b));
if (floor(a / TWO_PI) != floor(b / TWO_PI))
d = 1;
else
d = fmax(cos(a), cos(b));
return new_interval(c, d);
}
<file_sep>#include <stdio.h>
#include <float.h>
#include <math.h>
#include <stdlib.h>
#include "bicycle_model_parametrizeable.h"
#include "main.h"
#include "face_lift_obstacle.h"
#include "util.h"
#include "simulate_bicycle.h"
// do face lifting with the given settings, iteratively improving the computation
// returns true if the reachable set of states is satisfactory according to the
// function you provide in LiftingSettings (reachedAtIntermediateTime, reachedAtFinalTime)
bool face_lifting_iterative_improvement_bicycle_dyn(int startMs, LiftingSettings* settings, REAL heading_input, REAL throttle,HyperRectangle VisStates[],int *total_intermediate,int max_intermediate,bool plot);
// function that stops simulation after two seconds
bool shouldStop(REAL state[NUM_DIMS], REAL simTime, void* p)
{
bool rv = false;
REAL maxTime = 2.0f;
// stop if the maximum simulation time
if (simTime >= maxTime)
{
rv = true;
REAL* stopTime = (REAL*)p;
*stopTime = -1;
}
return rv;
}
// Simulation
REAL getSimulatedSafeTime(REAL start[4],REAL heading_input,REAL throttle)
{
REAL stepSize = 0.02f;
REAL rv = 0.0f;
simulate_bicycle(start, heading_input,throttle,stepSize, shouldStop, (void*)&rv); // TODO: look here
return rv;
}
void restartedComputation(int *total_intermediate)
{
// reset the counter of intermediate states
*total_intermediate = 0;
}
// called on states reached during the computation
bool intermediateState(HyperRectangle* r,HyperRectangle VisStates[],int *total_intermediate,int max_intermediate)
{
if(*total_intermediate < max_intermediate)
{
VisStates[*total_intermediate] = *r;
}
*total_intermediate=*total_intermediate+1;
return true;
}
bool finalState(HyperRectangle* rect, HyperRectangle VisStates[],int *total_intermediate,int max_intermediate)
{
if(*total_intermediate < max_intermediate)
{
VisStates[*total_intermediate] = *rect;
}
*total_intermediate=*total_intermediate+1;
return true;
}
bool runReachability_bicycle_dyn(REAL* start, REAL simTime, REAL wallTimeMs, REAL startMs,REAL heading, REAL throttle,HyperRectangle VisStates[],int *total_intermediate,int max_intermediate,bool plot)
{
LiftingSettings set;
for (int d = 0; d < NUM_DIMS; ++d)
{
set.init.dims[d].min = start[d];
set.init.dims[d].max = start[d];
}
set.reachTime = simTime;
set.maxRuntimeMilliseconds = wallTimeMs;
REAL iss = set.reachTime;
iss = iss * 0.10f;
set.initialStepSize = iss;
set.maxRectWidthBeforeError = 100;
set.reachedAtFinalTime = finalState;
set.reachedAtIntermediateTime = intermediateState;
set.restartedComputation = restartedComputation;
return face_lifting_iterative_improvement_bicycle_dyn(startMs, &set,heading, throttle,VisStates, total_intermediate,max_intermediate,plot);
}
bool check_safety(HyperRectangle* rect, REAL (*cone)[2])
{
REAL l1[2] = {rect->dims[0].min,rect->dims[1].max};
REAL r1[2] = {rect->dims[0].max,rect->dims[1].min};
REAL l2[2] = {cone[0][0],cone[1][1]};
REAL r2[2] = {cone[0][1],cone[1][0]};
if (l1[0] >= r2[0] || l2[0] >= r1[0])
return true;
if (l1[1] <= r2[1] || l2[1] <= r1[1])
return true;
return false;
}<file_sep># printing utility for benchmarking
def summarize_data(pd,sep_str=
"\n============================================================================================"):
moet=pd[['wcet']].mean()
meanet=pd[['mean_reach_time']].mean()
sum_times = pd['time_taken_lec']+pd['time_taken_safety_controller']
lec_percentage = pd['time_taken_lec']/sum_times
safety_controller_percentage = pd['time_taken_safety_controller']/sum_times
mean_experiment_time = sum_times.mean()
num_experiments = len(sum_times)
mean_lec_percentage = lec_percentage.mean()
mean_safety_controller_percentage = safety_controller_percentage.mean()
print("\nlec usage %:",round(100*round(mean_lec_percentage,4),2)," | safety_controller usage %:",
round(100*round(mean_safety_controller_percentage,4),2),"| moet: ",round(1000* round(moet.values[0],4),2),
"| mean_et:",round(1000*round(meanet.values[0],4),2),sep_str,"| num_experiments: ",num_experiments)
return num_experiments<file_sep>// <NAME>
// 08-2020
// Safety checking for uuv model file
#include "bicycle_dynamic_safety.h"
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#include <sys/time.h>
// provide initial value for global variables
double *** obstacles = 0;
int file_rows = 0;
int file_columns = 0;
int obstacle_count = 0;
bool check_safety(HyperRectangle* rect, REAL (*cone)[2])
{
REAL l1[2] = {rect->dims[0].min,rect->dims[1].max};
REAL r1[2] = {rect->dims[0].max,rect->dims[1].min};
REAL l2[2] = {cone[0][0],cone[1][1]};
REAL r2[2] = {cone[0][1],cone[1][0]};
if (l1[0] >= r2[0] || l2[0] >= r1[0])
return true;
if (l1[1] <= r2[1] || l2[1] <= r1[1])
return true;
return false;
}
bool check_safety_obstacles(HyperRectangle* rect)
{
// loop through the obstacles
bool allowed = true;
for (int j = 0; j < obstacle_count; j++)
{
double obs[2][2] = {{obstacles[j][0][0],obstacles[j][0][1]}, {obstacles[j][1][0],obstacles[j][1][1]}};
allowed= check_safety(rect,obs);
if(!allowed)
{
// printf("offending cone [%f, %f], ,[%f, %f]\n",obstacles[j][0][0],obstacles[j][0][1],obstacles[j][1][0],obstacles[j][1][1]);
break;
}
}
return allowed;
}
// function that allocates the 3d array for the obstacles
void allocate_obstacles(int num_obstacles)
{
int rows = num_obstacles;
int cols = 2;
int height = 2;
int i,j;
obstacles = (double***)malloc(rows * sizeof(double **));
// check if memory was allocated
if(obstacles == NULL)
{
fprintf(stderr, "out of memory\n");
exit(0);
}
for(i=0;i<rows;i++)
{
obstacles[i] = (double **)malloc(cols * sizeof(double*));
// check if memory was allocated
if(obstacles[i] == NULL)
{
fprintf(stderr, "out of memory\n");
exit(0);
}
for(j=0;j<cols;j++)
{
obstacles[i][j] = (double*)malloc(height*sizeof(double));
// check if memory was allocated
if(obstacles[i][j] == NULL)
{
fprintf(stderr, "out of memory\n");
exit(0);
}
}
}
}
void print_obstacles()
{
printf("interval list of obstacles: \n");
for(int i=0;i<obstacle_count;i++)
{
printf("[%f,%f], [%f,%f]\n", obstacles[i][0][0],obstacles[i][0][1],obstacles[i][1][0],obstacles[i][1][1]);
}
printf("\n");
}
void append_obstacle(int index,double (*box)[2])
{
obstacles[index][0][0] = box[0][0];
obstacles[index][0][1] = box[0][1];
obstacles[index][1][0] = box[1][0];
obstacles[index][1][1] = box[1][1];
}
// free the memory allocated for the wall points
void deallocate_obstacles()
{
int rows = obstacle_count;
int cols = 2;
int i,j;
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
free(obstacles[i][j]);
}
free(obstacles[i]);
}
free(obstacles);
}
<file_sep>// <NAME>
// 09-2020
// Header file for safety checking of dynamic obstacles
#ifndef BICYCLE_DYNAMIC_SAFETY_H_
#define BICYCLE_DYNAMIC_SAFETY_H_
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#include <sys/time.h>
#include "geometry.h"
// array that will store the hyper-rectangle representations of the objects
// in this particular example they are conese but this can be easily converted to generic obstacles
extern double *** obstacles;
extern int obstacle_count;
bool check_safety(HyperRectangle* rect, double (*box)[2]);
bool check_safety_obstacles(HyperRectangle* rect);
void allocate_obstacles(int num_obstacles);
void append_obstacle(int index,double (*box)[2]);
void print_obstacles();
void deallocate_obstacles();
#endif <file_sep>#!/bin/bash
# build the simulation docker
docker build -t simulator -f docker/SimulatorDockerfile_GPU .
#docker build -t simulatorheadless -f docker/SimulatorDockerfileHeadless .
#build the rtreach docker
docker build -t rtreach -f docker/Dockerfile .
<file_sep>#include "bicycle_model.h"
#include "main.h"
#include "face_lift.h"
#include "util.h"
#include "bicycle_safety.h"
#include "simulate_bicycle_plots.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// a note from the f1tenth simulator
// the car is 0.5 m long in the x direction
// 0.3 long in the y direction
// do face lifting with the given settings, iteratively improving the computation
// returns true if the reachable set of states is satisfactory according to the
// function you provide in LiftingSettings (reachedAtIntermediateTime, reachedAtFinalTime)
// visualization version, returns convex hull
HyperRectangle face_lifting_iterative_improvement_bicycle_vis(int startMs, LiftingSettings* settings, REAL heading_input, REAL throttle,bool plot);
// function that stops simulation after two seconds
bool shouldStop(REAL state[NUM_DIMS], REAL simTime, void* p)
{
bool rv = false;
REAL maxTime = 2.0f;
// stop if the maximum simulation time
if (simTime >= maxTime)
{
rv = true;
REAL* stopTime = (REAL*)p;
*stopTime = -1;
}
return rv;
}
// if computation restarts we close and reopen files
void restartedComputation()
{
// reset the counter of intermediate states
num_intermediate = 0;
total_intermediate = 0;
final_hull = false;
}
// called on states reached during the computation
bool intermediateState(HyperRectangle* r)
{
bool allowed = true;
//const REAL FIFTEEN_DEGREES_IN_RADIANS = 0.2618;
// bloat the box for the width of the car
// r->dims[0].min = r->dims[0].min - 0.25;
// r->dims[0].max = r->dims[0].max + 0.25;
// r->dims[1].min = r->dims[1].min - 0.15;
// r->dims[1].max = r->dims[1].max + 0.15;
// allowed = check_safety_obstacles(r);
// if(allowed)
// {
// allowed = check_safety_wall(r);
// }
// // reset it
// r->dims[0].min = r->dims[0].min + 0.25;
// r->dims[0].max = r->dims[0].max - 0.25;
// r->dims[1].min = r->dims[1].min + 0.15;
// r->dims[1].max = r->dims[1].max - 0.15;
// copy intermediate state into array
// add state to array for plotting
if(num_intermediate < MAX_INTERMEDIATE)
{
VisStates[num_intermediate] = *r;
num_intermediate++;
}
total_intermediate++;
//if(!allowed)
// printf("unsafe....\n");
return allowed;
}
// This function enumerates all of the corners of the current HyperRectangle and
// returns whether or not any of the points lies outside of the ellipsoid
bool finalState(HyperRectangle* rect)
{
return intermediateState(rect);
}
// reachability analysis
HyperRectangle runReachability_bicycle_vis(REAL* start, REAL simTime, REAL wallTimeMs, REAL startMs,REAL heading_input, REAL throttle)
{
LiftingSettings set;
for (int d = 0; d < NUM_DIMS; ++d)
{
set.init.dims[d].min = start[d];
set.init.dims[d].max = start[d];
}
set.reachTime = simTime;
set.maxRuntimeMilliseconds = wallTimeMs;
REAL iss = set.reachTime;
iss = iss * 0.10f;
set.initialStepSize = iss; //set.reachTime / 10.0f;
set.maxRectWidthBeforeError = 100;
set.reachedAtFinalTime = finalState;
set.reachedAtIntermediateTime = intermediateState;
set.restartedComputation = restartedComputation;
return face_lifting_iterative_improvement_bicycle_vis(startMs, &set,heading_input, throttle,false);
}
<file_sep>#!/usr/bin/env python
import rospy
from visualization_msgs.msg import Marker
from visualization_msgs.msg import MarkerArray
from rtreach.msg import reach_tube
from rtreach.msg import interval
import numpy as np
import rospkg
from nav_msgs.msg import Odometry
class publish_wallpoints:
def __init__(self,obstacle_file='porto',racecar_name='racecar'):
# use the rospack object to get paths
rospack = rospkg.RosPack()
package_path=rospack.get_path('rtreach')
filename=package_path+'/obstacles/{}_obstacles.txt'.format(obstacle_file)
f= open(filename, "r")
points= f.read().split('\n')
f.close()
self.points = points
self.pub = rospy.Publisher('wallpoints',reach_tube,queue_size=1)
self.intervals = []
self.wallpoints = []
self.load_wallpoints()
self.sub = rospy.Subscriber(racecar_name+"/odom", Odometry,self.odom_callback,queue_size=10)
def load_wallpoints(self):
#interval_list = []
for i in range(len(self.points)):
point=self.points[i].split(',')
if(len(point)<2):
continue
self.wallpoints.append([float(point[0]),float(point[1])])
self.wallpoints = np.asarray(self.wallpoints).reshape((-1,2))
print(self.wallpoints)
#self.intervals =
def odom_callback(self,odom_msg):
# position
x = odom_msg.pose.pose.position.x
y = odom_msg.pose.pose.position.y
pt = np.asarray([[x,y]]).reshape((-1,2))
dists = np.linalg.norm(self.wallpoints - pt,axis=-1)
relevant_indexes=np.where(dists<2.0)[0]
relevant_points = self.wallpoints[relevant_indexes]
interval_list = []
markerArray = MarkerArray()
for i in range(relevant_points.shape[0]):
# Interval Portion
point = relevant_points[i]
intv = interval()
intv.x_min = float(point[0])
intv.x_max = float(point[0])
intv.y_min = float(point[1])
intv.y_max = float(point[1])
interval_list.append(intv)
msg = reach_tube()
msg.obstacle_list = interval_list
msg.header.stamp = rospy.Time.now()
msg.count = len(interval_list)
self.pub.publish(msg)
if __name__=="__main__":
rospy.init_node("publish_wall_markers")
args = rospy.myargv()[1:]
obstacle_path_name=args[0]
gm = publish_wallpoints(obstacle_file=obstacle_path_name)
#gm.execute()
rospy.spin()<file_sep>source rtreach_ros/devel/setup.bash
rosrun rtreach reach_node porto_obstacles.txt<file_sep>// example call: ./bicycle 100 0.0 0.0 0.0 0.0 16.0 0.26666
// example call output:
// started!
// Argc: 6
// runtime: 100 ms
// x_0[0]: -0.100000
// x_0[1]: 0.000000
// x_0[2]: 0.000000
// x_0[3]: 1.100000
// u_0[0]: 16.0
// u_1[1]: 0.266
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "util.h"
#include "main.h"
#include "bicycle_model.h"
#include "bicycle_safety.h"
const int state_n = 4; // state dimension
// This particular example also needs to know where the walls are
const char * filepath= "../ros_src/rtreach/obstacles/porto_obstacles.txt";
int main( int argc, const char* argv[] )
{
DEBUG_PRINT("started!\n\r");
int runtimeMs = 0;
REAL startState[4] = {0.0, 0.0, 0.0, 0.0};
REAL control_input[2] = {0.0,0.0};
DEBUG_PRINT("Argc: %d\n\r", argc);
if (argc < 6) {
printf("Error: not enough input arguments!\n\r");
return 0;
}
else {
runtimeMs = atoi(argv[1]);
startState[0] = atof(argv[2]);
startState[1] = atof(argv[3]);
startState[2] = atof(argv[4]);
startState[3] = atof(argv[5]);
control_input[0] = atof(argv[6]);
control_input[1] = atof(argv[7]);
DEBUG_PRINT("runtime: %d ms\n\rx_0[0]: %f\n\rx_0[1]: %f\n\rx_0[2]: %f\n\rx_0[3]: %f\n\ru_0[0]: %f\n\ru_0[1]: %f\n\r\n", runtimeMs, startState[0], startState[1], startState[2], startState[3],control_input[0],control_input[1]);
}
REAL delta = control_input[1];
REAL u = control_input[0];
// simulate the car with a constant input passed from the command line
getSimulatedSafeTime(startState,delta,u);
printf("\n");
// location of obstacles in our scenario
int num_obstacles = 5;
double points[5][2] = {{2.0,2.0},{4.7,2.7},{11.36,-1.46},{3.0,6.4},{-9.64,2.96}};
allocate_obstacles(num_obstacles,points);
// simTime
REAL timeToSafe = 2.0;
// startMs
int startMs = 0;
// load the wall points into the global variable
load_wallpoints(filepath,true);
// run reachability analysis test
bool safe = runReachability_bicycle(startState, timeToSafe, runtimeMs, startMs,delta,u);
//int runtimeMs = 20; // run for 20 milliseconds
DEBUG_PRINT("Number of Iterations: %d\n",iterations_at_quit);
DEBUG_PRINT("done, result = %s\n", safe ? "safe" : "unsafe");
deallocate_2darr(file_rows,file_columns);
deallocate_obstacles(obstacle_count);
return 0;
}<file_sep>// <NAME>
// 08-2020
// Safety checking for f1tenth model file
#include "bicycle_safety.h"
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#include <sys/time.h>
// provide initial value for global variables
double ** wallCoords = 0;
double *** obstacles = 0;
int file_rows = 0;
int file_columns = 0;
int obstacle_count = 0;
// function that allocates the 2d array of wall points
void allocate_2darr(int rows,int columns)
{
wallCoords = malloc(rows * sizeof(double *));
if(wallCoords == NULL)
{
fprintf(stderr, "out of memory\n");
exit(0);
}
// allocate each of the rows with arrays of length 2
for(int i = 0; i < rows; i++)
{
wallCoords[i] = malloc(columns * sizeof(double));
if(wallCoords[i] == NULL)
{
fprintf(stderr, "out of memory\n");
exit(0);
}
}
}
// free the memory allocated for the wall points
void deallocate_2darr(int rows,int columns)
{
for(int i = 0; i < rows; i++)
free(wallCoords[i]);
free(wallCoords);
printf("Done\n");
}
int countlines(const char * filename)
{
int cnt =0;
FILE *fp;
char line[60];
// open the file
fp = fopen(filename,"r");
if(fp==NULL)
{
printf("Could not open file %s",filename);
}
else
{
while( fgets(line, 60, fp)!=NULL )
{
cnt+=1;
}
fclose(fp);
}
return cnt;
}
// function that loads points of the wall from the file
void load_wallpoints(const char * filename, bool print)
{
char line[60];
char * x, * y;
double xd, yd;
int i;
FILE *wallPoints;
file_rows = countlines(filename);
if(print)
printf("Opening file...with %d points\n", file_rows);
// allocate the memory
allocate_2darr(file_rows,file_columns);
// open the file
wallPoints = fopen(filename,"r");
if(wallPoints==NULL)
{
printf("Could not open file %s\n",filename);
}
else
{
i =0;
while( fgets (line, 60, wallPoints)!=NULL )
{
x = strtok(line,",");
y = strtok(NULL,",");
xd = strtod(x,NULL);
yd = strtod(y,NULL);
wallCoords[i][0] = xd;
wallCoords[i][1] = yd;
i+=1;
}
fclose(wallPoints);
}
}
bool check_safety(HyperRectangle* rect, REAL (*cone)[2])
{
REAL l1[2] = {rect->dims[0].min,rect->dims[1].max};
REAL r1[2] = {rect->dims[0].max,rect->dims[1].min};
REAL l2[2] = {cone[0][0],cone[1][1]};
REAL r2[2] = {cone[0][1],cone[1][0]};
if (l1[0] >= r2[0] || l2[0] >= r1[0])
return true;
if (l1[1] <= r2[1] || l2[1] <= r1[1])
return true;
return false;
}
bool check_safety_obstacles(HyperRectangle* rect)
{
// loop through the obstacles
bool allowed = true;
for (int j = 0; j < obstacle_count; j++)
{
double obs[2][2] = {{obstacles[j][0][0],obstacles[j][0][1]}, {obstacles[j][1][0],obstacles[j][1][1]}};
allowed= check_safety(rect,obs);
if(!allowed)
{
// printf("offending cone [%f, %f], ,[%f, %f]\n",obstacles[j][0][0],obstacles[j][0][1],obstacles[j][1][0],obstacles[j][1][1]);
break;
}
}
return allowed;
}
bool check_safety_wall(HyperRectangle* rect)
{
bool safe = true;
for (int i = 0;i<file_rows;i++)
{
double point[2][2] = {{wallCoords[i][0],wallCoords[i][0]},{wallCoords[i][1],wallCoords[i][1]}};
safe = check_safety(rect,point);
if(!safe)
{
// printf("offending point (%f,%f)\n",wallCoords[i][0],wallCoords[i][1]);
// println(rect);
break;
}
}
return safe;
}
// function that allocates the 3d array for the obstacles
void allocate_obstacles(int num_obstacles,double (*points)[2])
{
int rows = num_obstacles;
obstacle_count = num_obstacles;
int cols = 2;
int height = 2;
int i,j;
double w = 0.13;
double h = 0.13;
obstacles = (double***)malloc(rows * sizeof(double **));
// check if memory was allocated
if(obstacles == NULL)
{
fprintf(stderr, "out of memory\n");
exit(0);
}
for(i=0;i<rows;i++)
{
obstacles[i] = (double **)malloc(cols * sizeof(double*));
// check if memory was allocated
if(obstacles[i] == NULL)
{
fprintf(stderr, "out of memory\n");
exit(0);
}
for(j=0;j<cols;j++)
{
obstacles[i][j] = (double*)malloc(height*sizeof(double));
// check if memory was allocated
if(obstacles[i][j] == NULL)
{
fprintf(stderr, "out of memory\n");
exit(0);
}
}
}
printf("interval list of obstacles: \n");
for(i=0;i<rows;i++)
{
obstacles[i][0][0] = points[i][0]-w/2.0;
obstacles[i][0][1] = points[i][0]+w/2.0;
obstacles[i][1][0] = points[i][1]-h/2.0;
obstacles[i][1][1] = points[i][1]+h/2.0;
printf("[%f,%f], [%f,%f]\n", obstacles[i][0][0],obstacles[i][0][1],obstacles[i][1][0],obstacles[i][1][1]);
}
printf("\n");
}
// free the memory allocated for the wall points
void deallocate_obstacles(int num_obstacles)
{
int rows = num_obstacles;
int cols = 2;
int i,j;
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
free(obstacles[i][j]);
}
free(obstacles[i]);
}
free(obstacles);
}
<file_sep>#! /bin/bash
#run the docker container
docker container run -it --name=rtreach_ntainer --rm --net=host rtreach /bin/bash -c "source devel/setup.bash && roslaunch rtreach multi_agent_reach.launch"<file_sep>// <NAME>
// 4-2014
// Real-time face lifting main algorithm header
#ifndef FACE_LIFT_H_
#define FACE_LIFT_H_
#include <stdbool.h>
#include "main.h"
#include "geometry.h"
//#include "dynamics.h"
extern int iterations_at_quit;
typedef struct LiftingSettings
{
HyperRectangle init;
REAL reachTime; // total reach time
REAL initialStepSize; // the initial size of the steps to use
REAL maxRectWidthBeforeError; // maximum allowed rectangle size
int maxRuntimeMilliseconds; // maximum runtime in milliseconds
// called at the intermediate times
// return true if this rectangle is satisfactory (for safety or whatever)
bool (*reachedAtIntermediateTime)(HyperRectangle* r);
// called at the final time
// return true if the system is satisfactory (for liveness or whatever)
bool (*reachedAtFinalTime)(HyperRectangle* r);
// called whenever we restart the computation after refining
void (*restartedComputation)();
} LiftingSettings;
#endif
<file_sep>#include "obstacle_model.h"
#include "main.h"
#include "face_lift.h"
#include "util.h"
#include "simulate_obstacle.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// a note from the f1tenth simulator
// the car is 0.5 m long in the x direction
// 0.3 long in the y direction
// do face lifting with the given settings, iteratively improving the computation
// returns true if the reachable set of states is satisfactory according to the
// function you provide in LiftingSettings (reachedAtIntermediateTime, reachedAtFinalTime)
bool face_lifting_iterative_improvement_obstacle(int startMs, LiftingSettings* settings, REAL v_x, REAL v_y);
// helper function to check safety
// bool check_safety(HyperRectangle* rect, double (*box)[2]);
// function that stops simulation after two seconds
bool shouldStop(REAL state[NUM_DIMS], REAL simTime, void* p)
{
bool rv = false;
REAL maxTime = 2.0f;
// stop if the maximum simulation time
if (simTime >= maxTime)
{
rv = true;
REAL* stopTime = (REAL*)p;
*stopTime = -1;
}
return rv;
}
// Simulation
REAL getSimulatedSafeTime(REAL start[2],REAL v_x,REAL v_y)
{
REAL stepSize = 0.02f;
REAL rv = 0.0f;
simulate_obstacle(start, v_x,v_y,stepSize, shouldStop, (void*)&rv); // TODO: look here
//DEBUG_PRINT("time until simulation reaches safe state = %f\n", rv);
return rv;
}
// called on states reached during the computation
bool intermediateState(HyperRectangle* r)
{
bool allowed = true;
return allowed;
}
// This function enumerates all of the corners of the current HyperRectangle and
// returns whether or not any of the points lies outside of the ellipsoid
bool finalState(HyperRectangle* rect)
{
return intermediateState(rect);
}
bool runReachability_obstacle(REAL* start, REAL simTime, REAL wallTimeMs, REAL startMs,REAL v_x, REAL v_y)
{
LiftingSettings set;
for (int d = 0; d < NUM_DIMS; ++d)
{
set.init.dims[d].min = start[d];
set.init.dims[d].max = start[d];
}
set.reachTime = simTime;
set.maxRuntimeMilliseconds = wallTimeMs;
REAL iss = set.reachTime;
iss = iss * 0.10f;
set.initialStepSize = iss;
set.maxRectWidthBeforeError = 100;
set.reachedAtFinalTime = finalState;
set.reachedAtIntermediateTime = intermediateState;
set.restartedComputation = 0; //restartedComputation;
return face_lifting_iterative_improvement_obstacle(startMs, &set,v_x, v_y);
}
<file_sep>#!/usr/bin/env python
import rospy
from visualization_msgs.msg import Marker
from visualization_msgs.msg import MarkerArray
from rtreach.msg import reach_tube
from rtreach.msg import interval
import numpy as np
import rospkg
from nav_msgs.msg import Odometry
class publish_wallpoints:
def __init__(self,obstacle_file='porto',racecar_name='racecar'):
# use the rospack object to get paths
rospack = rospkg.RosPack()
package_path=rospack.get_path('rtreach')
filename=package_path+'/obstacles/{}_obstacles.txt'.format(obstacle_file)
f= open(filename, "r")
points= f.read().split('\n')
f.close()
self.points = points
self.marker_pub = rospy.Publisher('relevant_boundaries', MarkerArray, queue_size="1")
self.wallpoints = []
self.load_wallpoints()
self.sub = rospy.Subscriber(racecar_name+"/odom", Odometry,self.odom_callback,queue_size=10)
def load_wallpoints(self):
#interval_list = []
for i in range(len(self.points)):
point=self.points[i].split(',')
if(len(point)<2):
continue
self.wallpoints.append([float(point[0]),float(point[1])])
self.wallpoints = np.asarray(self.wallpoints).reshape((-1,2))
def odom_callback(self,odom_msg):
# position
x = odom_msg.pose.pose.position.x
y = odom_msg.pose.pose.position.y
pt = np.asarray([[x,y]]).reshape((-1,2))
dists = np.linalg.norm(self.wallpoints - pt,axis=-1)
relevant_indexes=np.where(dists<2.0)[0]
relevant_points = self.wallpoints[relevant_indexes]
markerArray = MarkerArray()
for i in range(relevant_points.shape[0]):
# Interval Portion
point = relevant_points[i]
# Markers
marker = Marker()
marker.id = i
marker.header.frame_id = "/map"
marker.type = marker.SPHERE
marker.action = marker.ADD
marker.scale.x = 0.1
marker.scale.y = 0.1
marker.scale.z = 0.1
marker.color.a = 1.0
marker.color.r = 1.0
marker.color.g = 1.0
marker.color.b = 0.0
marker.pose.orientation.w = 1.0
marker.pose.position.x = point[0]
marker.pose.position.y = point[1]
marker.pose.position.z = 0
markerArray.markers.append(marker)
marker.lifetime =rospy.Duration(0.1)
self.marker_pub.publish(markerArray)
if __name__=="__main__":
rospy.init_node("publish_wall_markers")
args = rospy.myargv()[1:]
obstacle_path_name=args[0]
gm = publish_wallpoints(obstacle_file=obstacle_path_name)
#gm.execute()
rospy.spin()<file_sep>#include <iostream>
extern "C"
{
double getSimulatedSafeTime(double start[4],double heading_input,double throttle);
}
int main(void)
{
double startState[4] = {0.0, 0.0, 0.0, 0.0};
double control_input[2] = {0.0,0.0};
double delta = control_input[1];
double u = control_input[0];
getSimulatedSafeTime(startState,delta,u);
return 0;
}<file_sep>#!/bin/bash
# Notes (mostly for me)
# $! Contains the process ID of the most recently executed background pipeline
# $? This the exit status of the last executed command
# The linux trap command allows you to catch signals and execute code when they occur
# SIGINT is generated when you type Ctrl-C at the keyboard to interrupt a running script
# kill -INT $pid sends the "interrupt" signal to the process with process ID pid.
# However, the process may decide to ignore the signal, or catch the signal and do
# something before exiting and/or ignore it.
_term() {
exit_status=$? # = 130 for SIGINT
echo "Caught SIGINT signal!"
kill -INT "$child" 2>/dev/null
}
# for future reference generating a random number within a range
# $(shuf -i 0-4 -n 1)
Velocities="0.5 1.0 1.5"
Runtimes="25 10"
Obstacles="0 6"
for ((algorithm_number=0;algorithm_number<4;algorithm_number++))
do
for vel in $Velocities
do
for rt in $Runtimes
do
for obs in $Obstacles
do
count=0
trap _term SIGINT
while [ $count -lt 30 ]
do
((count=count+1))
echo "${algorithm_number}|${vel}|${rt}|${obs}|${count}"
roslaunch race sim_for_rtreach_batch_emsoft.launch random_seed:=$count algorithm:=$algorithm_number velocity:=$vel world_number:=0 num_obstacles:=$obs wall_time:=$rt experiment_number:=$count timeout:=60 &
child=$!
wait "$child"
if [ $exit_status -eq 130 ]; then
# SIGINT was captured meaning the user
# wants full stop instead of start_simulation.launch
# terminating normally from end of episode so...
echo "stop looping"
echo count: $count
exit 1
fi
done
done
done
done
done
<file_sep>#! /bin/bash
#run the docker container
docker container run --runtime=nvidia -it -e DISPLAY --rm --net=host --env="QT_X11_NO_MITSHM=1" -v /tmp/.X11-unix:/tmp/.X11-unix simulator /bin/bash -c "source devel/setup.bash && roslaunch race sim_for_rtreach_multi_agent.launch number_of_cars:=3 docker:=true"<file_sep>// <NAME>
// 8-2014
// Dynamics header file for real-time reachability obstacle
#ifndef DYNAMICS_OBSTACLE_H_
#define DYNAMICS_OBSTACLE_H_
#define DYNAMICS_OBSTACLE_MODEL
#define NUM_DIMS (2)
#endif<file_sep>#include "ros/ros.h"
#include <iostream>
#include <tf/tf.h>
#include <nav_msgs/Odometry.h>
#include <message_filters/subscriber.h>
#include <rtreach/stamped_ttc.h>
#include <rtreach/reach_tube.h>
#include <rtreach/interval.h>
#include <message_filters/synchronizer.h>
#include <message_filters/sync_policies/approximate_time.h>
#include <ros/package.h>
#include <ros/console.h>
#include <visualization_msgs/MarkerArray.h>
#include <visualization_msgs/Marker.h>
#include <math.h>
#include <cstdlib>
// The following node will receive odometry estimates from a vehicle (velocity and position) and will compute the reachable set bounding box of where it
// could go based on it's current velocity
const int max_hyper_rectangles = 8000;
extern "C"
{
#include "simulate_obstacle.h"
HyperRectangle runReachability_obstacle_vis(double* start, double simTime, double wallTimeMs, double startMs,double v_x, double v_y, HyperRectangle VisStates[],int *total_intermediate,int max_intermediate,bool plot);
double getSimulatedSafeTime(double start[2],double v_x, double v_y);
HyperRectangle hr_list[max_hyper_rectangles];
}
ros::Publisher vis_pub;
ros::Publisher tube_pub;
ros::Subscriber sub; // markerArray subscriber
// reachability parameters
double sim_time;
double walltime;
bool bloat_reachset = true;
// rect_count is used by the reachability algorithm to compue the reachsets
int rect_count;
int count = 0;
// initial state for estimate of vehicle position
double startState[2] = {0.0, 0.0};
// parameters for visualizing the obstacle reachsets
double display_max;
int display_count = 1;
double display_increment = 1.0;
// odometry message pointer
nav_msgs::Odometry::ConstPtr msg;
void box_pose_callback(const nav_msgs::Odometry::ConstPtr& nav_msg)
{
msg = nav_msg;
//ROS_WARN("got nav message");
count++;
}
void timer_callback(const ros::TimerEvent& event)
{
using std::cout;
using std::endl;
double roll, pitch, yaw;
double x,y,vx,vy;
//sim_time = 2.0;
rect_count = 0;
HyperRectangle hull;
if(count>0)
{
// position and velocity
x = msg-> pose.pose.position.x;
y = msg-> pose.pose.position.y;
vx = msg->twist.twist.linear.x;
vy = msg->twist.twist.linear.y;
// assign positions to array
startState[0] = x;
startState[1] = y;
// compute the reachable set
HyperRectangle reach_hull = runReachability_obstacle_vis(startState, sim_time, walltime, 0,vx,vy,hr_list,&rect_count,max_hyper_rectangles,true);
// define the quaternion matrix
tf::Quaternion q(
msg->pose.pose.orientation.x,
msg->pose.pose.orientation.y,
msg->pose.pose.orientation.z,
msg->pose.pose.orientation.w);
tf::Matrix3x3 m(q);
// convert to rpy
m.getRPY(roll, pitch, yaw);
printf("num_boxes: %d, \n",rect_count);
visualization_msgs::MarkerArray ma;
rtreach::reach_tube reach_set;
display_increment = rect_count / display_max;
display_count = std::max(1.0,nearbyint(display_increment));
cout << "display_max: " << display_increment << ", display count: " << display_count << endl;
// publish some of the markers,
// don't freeze gazebo
for(int i= 0; i<std::min(max_hyper_rectangles,rect_count-1); i+=display_count)
{
hull = hr_list[i];
if(bloat_reachset)
{
hull.dims[0].min = hull.dims[0].min - 0.25;
hull.dims[0].max = hull.dims[0].max + 0.25;
hull.dims[1].min = hull.dims[1].min - 0.15;
hull.dims[1].max = hull.dims[1].max + 0.15;
}
visualization_msgs::Marker marker;
marker.header.frame_id = "map";
marker.header.stamp = ros::Time::now();
marker.id = i;
marker.type = visualization_msgs::Marker::CUBE;
marker.action = visualization_msgs::Marker::ADD;
marker.pose.position.x = (hull.dims[0].max+hull.dims[0].min)/2.0;
marker.pose.position.y = (hull.dims[1].max+hull.dims[1].min)/2.0;
marker.pose.position.z = 0.2;
marker.pose.orientation.x = 0;
marker.pose.orientation.y = 0;
marker.pose.orientation.z = 0;
marker.pose.orientation.w = 0;
marker.scale.x = (hull.dims[0].max-hull.dims[0].min);
marker.scale.y = (hull.dims[1].max-hull.dims[1].min);
marker.scale.z = 0.05;
marker.color.a = 1.0;
marker.color.r = (double) rand() / (RAND_MAX);
marker.color.g = (double) rand() / (RAND_MAX);
marker.color.b = (double) rand() / (RAND_MAX);
marker.lifetime =ros::Duration(0.1);
ma.markers.push_back(marker);
}
// publish marker
vis_pub.publish(ma);
// publish all the rectangles we have or the max we can
for(int i= 0; i<std::min(max_hyper_rectangles,rect_count-1); i++)
{
hull = hr_list[i];
if(bloat_reachset)
{
hull.dims[0].min = hull.dims[0].min - 0.25;
hull.dims[0].max = hull.dims[0].max + 0.25;
hull.dims[1].min = hull.dims[1].min - 0.15;
hull.dims[1].max = hull.dims[1].max + 0.15;
}
rtreach::interval tube;
tube.x_min = hull.dims[0].min;
tube.x_max = hull.dims[0].max;
tube.y_min = hull.dims[1].min;
tube.y_max = hull.dims[1].max;
reach_set.obstacle_list.push_back(tube);
}
reach_set.header.stamp = ros::Time::now();
reach_set.count = reach_set.obstacle_list.size();
tube_pub.publish(reach_set);
}
else
{
// visualization_msgs::MarkerArray ma;
rtreach::reach_tube reach_set;
reach_set.header.stamp = ros::Time::now();
reach_set.count = 0;
// vis_pub.publish(ma);
tube_pub.publish(reach_set);
}
}
int main(int argc, char **argv)
{
using namespace message_filters;
if(argv[1] == NULL)
{
std::cout << "Please the name of the dynamic obstacle for which you would like to compute reachsets for e.g (racecar)" << std::endl;
exit(0);
}
// if(argv[2] == NULL)
// {
// std::cout << "Please enter the box size e.g 10" << std::endl;
// exit(0);
// }
if(argv[2] == NULL)
{
std::cout << "Please enter the sim_time e.g 2" << std::endl;
exit(0);
}
if(argv[3] == NULL)
{
std::cout << "Please enter the wall time e.g 1" << std::endl;
exit(0);
}
if(argv[4] == NULL)
{
std::cout << "Please enter the number of boxes to display e.g 100" << std::endl;
exit(0);
}
std::string obs_name= argv[1];
//box_size = atof(argv[2]) / 2.0;
walltime = atoi(argv[2]);
sim_time = atof(argv[3]);
display_max = atof(argv[4]);
// initialize the ros node
ros::init(argc, argv, "visualize_node_obstacle");
ros::NodeHandle n;
vis_pub = n.advertise<visualization_msgs::MarkerArray>(obs_name+"/reach_hull_obs", 100 );
tube_pub = n.advertise<rtreach::reach_tube>(obs_name+"/reach_tube",100);
sub = n.subscribe(obs_name+"/odom", 1000, box_pose_callback);
ros::Timer timer = n.createTimer(ros::Duration(0.01), timer_callback);
ros::Rate r(80);
while(ros::ok())
{
r.sleep();
ros::spinOnce();
}
// de-allocate obstacles
return 0;
}
<file_sep># F1Tenth Rtreach
# Table of Contents
1. [Introduction](#introduction)
2. [Multi-Agent Reachability](#MultiAgent)
3. [Docker](#Docker)
4. [Repositiory Organization](#CodeDescrip)
### Real Time Reachability for the F1Tenth Platform <a name="introduction"></a>
This repo is an implementation of a runtime assurance approach by [<NAME> et al.](https://ieeexplore.ieee.org/document/7010482) for the F1Tenth platform. The motivation for runtime assurance stems from the ever-increasing complexity of software needed to control autonomous systems, and the need for these systems to be certified for safety and correctness. Thus the methods contained herein are used to build monitors for the system that can be used to ensure that the system remains within a safe operating mode. As an example, in the following animations we display a system with an unsafe neural network inspired controller that occasionally causes the f1tenth model to crash into walls. In the second animation, we add a real time safety monitor that switches to a safe controller when it detects a potential collision. Though the safety controller sacrifices performance it ensures that we do not collide with obstacles. The safety monitor was designed using the algorithms described by Bak et al.
#### Neural Network Only (LEC)

#### Neural Network + Monitor + Safety Controller

**Disclaimer**: Our assumption is that you are using linux. A major part of this effort involves ROS. This code was tested on a computer running Ubuntu 16.04.6 LTS.
### Intro to rtreach: Let's start with an example.
<hr />
The safey monitor implemented in this repository relies on an anytime real-time reachability algorithm based on [mixed face-lifting](http://www.taylortjohnson.com/research/bak2014rtss.pdf). The reach-sets obtained using this method are represented as hyper-rectangles and we utilize these reachsets to check for collisons with obstacles in the vehicle's environment. The following example shows the use of this algorithm to check whether the vehicle will enter an unsafe operating mode in the next one second using the current control command.
### Before we continue let's first compile the example code by executing the following:
<hr />
```
$ cd src/
$ gcc -std=gnu99 -O3 -Wall face_lift_bicycle_model.c geometry.c interval.c simulate_bicycle.c util.c dynamics_bicycle_model.c bicycle_safety.c main.c bicycle_model.c -lm -o bicycle
```
In this example, our vehicle is at the origin (x = 0, y = 0) with a current heading of 0 radians and an initial linear velocity of 0 m/s. The current control command being considered issues a speed set point of 1 m/s and a steering angle of 0.266 radians. Executing the code below will print whether or not the vehicle will enter an unsafe state. The alloted time that we have specified for reachability computations is 100ms. Since our technique is anytime it refines the precision of the reachability computation based on available runtime by halving the step size used in the face-lifting technique.
### Run a one second simulation using the following command
<hr />
```
$ ./bicycle 100 0.0 0.0 0.0 0.0 1.0 0.2666
```
Expected output:
```
runtime: 100 ms
x_0[0]: 0.000000
x_0[1]: 0.000000
x_0[2]: 0.000000
x_0[3]: 0.000000
u_0[0]: 1.000000
u_0[1]: 0.266600
Quitting simulation: time: 2.020000, stepSize: 0.020000
If you keep the same input for the next 2.000000 s, the state will be:
[1.545528,1.046166,1.283163,1.203507]
Opening file...with 5536 points
offending cone (1.500000,2.500000) (1.500000, 2.500000)
unsafe....
Quitting from runtime maxed out
[HyperRectangle (1.527867, 1.529682) (1.032242, 1.033770) (1.280197, 1.280286) (1.188098, 1.188847)]
133ms: stepSize = 0.000391
iterations at quit: 10
done, result = safe
Done
```
As we can see our initial computation identified a collision with a cone in the vehicle's environment but by refining the reachset in successive iterations of the reachability computation, it becomes clear that this warning is spurious.
### Plotting of Reachsets
<hr />
We can visualize the results of the above example by executing the following:
```
$ gcc -std=gnu99 -O3 -Wall face_lift_bicycle_model_visualization.c geometry.c interval.c simulate_bicycle_plots.c util.c dynamics_bicycle_model.c bicycle_plots_main.c bicycle_model_plots.c -lm -o bicycle_plot
```
and then:
```
$ ./bicycle_plot 100 2.0 0.0 0.0 0.0 0.0 1.0 0.2666
```
Finally, (assuming you have [gnuplot](http://gausssum.sourceforge.net/DocBook/ch01s03.html)), you can visualize the results by running:
```
$ gnuplot < plot_bicycle.gnuplot
```
Usage of plotting utilities:
```
$ ./bicycle_plot (milliseconds-runtime) (seconds-reachtime) (x) (y) (linear velocity) (heading) (throttle control input) (heading control input)
```

In the above image, the green rectangles are the intermediate reachable sets encountered after each face-lifting operation, and the red rectangle is the convex hull of these rectangles.
### Building rtreach as a C library.
<hr />
Now that you have a taste of what rtreach is, we can move on to the more fun part. Using rtreach within ROS. By doing this, we can implement a safety monitor using the archtichture displayed again below:

First compile the code and create the rospackage, credit: [mix-c-and-cpp](https://www.thegeekstuff.com/2013/01/mix-c-and-cpp/):
```
$ cd src
$ gcc -c -std=gnu99 -O3 -Wall -fpic face_lift_bicycle_model.c geometry.c interval.c simulate_bicycle.c util.c dynamics_bicycle_model.c bicycle_safety.c bicycle_model.c face_lift_bicycle_model_visualization.c bicycle_model_vis.c bicycle_dynamic_safety.c bicycle_model_dynamic_vis.c -lm
```
Next create a shared library:
```
$ gcc -shared -o libRtreach.so face_lift_bicycle_model.o bicycle_model.o dynamics_bicycle_model.o geometry.o interval.o simulate_bicycle.o util.o bicycle_safety.o
```
This will create a file called **libRtreach.so**.
Let's compile a test to make sure everything worked correctly.
```
$ g++ -L$(pwd)/ -Wall test.cpp -o test -lRtreach
```
Before running the executable make sure that the path of shared library is contain in the environment variable LD_LIBRARY_PATH.
```
$ export LD_LIBRARY_PATH=$(pwd):$LD_LIBRARY_PATH
$ ./test
```
The output of the test should be:
```
Quitting simulation: time: 2.020000, stepSize: 0.020000
If you keep the same input for the next 2.000000 s, the state will be:
[1.931151,0.000000,1.249570,0.000000]
```
If that test worked, smile, take a breath and let's have some fun with ROS. If not feel free to send me an [email](mailto:<EMAIL>) and we will see what we can do.
### Using rtreach with the F1Tenth Simulator
<hr />
The platform that we seek to use these techniques on is a 1/10 scale autonomous race car named the [F1Tenth](https://f1tenth.org/). The platform was inspired as an international competition for researchers, engineers, and autonomous systems enthusiasts originally founded ath University of Pennsylvania in 2016. Our initial implmentation is done in simulation but we are also planning on doing this on the hardware platform. Thus, This assumes that you have the F1Tenth Simulator installed. If not please install it by following the instructions available [here](https://github.com/pmusau17/Platooning-F1Tenth).
### Overlaying worskpaces
<hr />
Once that is installed. You have to add the setup script to your ~/.bashrc file. This allows you to [overlay workspaces](http://wiki.ros.org/catkin/Tutorials/workspace_overlaying). Using your favourite editor add the following line to your ~/.bashrc. I like gedit or nano (vim lovers just relax).
```
gedit ~/.bashrc
```
add this to the bottom of that file
```
source /path/to/Platooning-F1Tenth/setup.bash
```
**change the path above to reflect the one on your machine**.
Then run
```
$ source ~/.bashrc
```
You're now all set to build rtreach. In the rtreach_f1tenth/ folder run the following:
```
$ ./build_rtreach.sh
```
This will create a ros package called rtreach_ros in the directory above this one. Run the following command to use the package
```
cd ../rtreach_ros && source devel/setup.bash
```
### Running Rtreach
<hr />
In the Platooning-F1Tenth ros package execute the following:
```
$ source devel/setup.bash
```
Then start the simulation. This will bring up the track displayed at the start of this readme and a green model of a simplistic autonomous vehicle.
```
$ roslaunch race sim_for_rtreach.launch
```
The neural network inspired controller that we use in our experiments maps images captured from the vehicle's camera into one of five discrete actions (turn left, turn right, continue straight, turn weakly left, turn weakly right). The network model used to make inferences is [VGG-7](https://towardsdatascience.com/only-numpy-implementing-mini-vgg-vgg-7-and-softmax-layer-with-interactive-code-8994719bcca8). The safe controller is a gap following algorithm that we select because of its ability to avoid obstacles.
Run the safety monitor + safety_controller + neural network controller.
```
$ rosrun rtreach reach_node porto_obstacles.txt
```
In this setup the decision manager will allow the neural network model to control the vehicle so long as the control command issue will not cause the vehicle to enter an unsafe state in the next one second. Otherwise the safety controller will be used. The decision manager can then return to the neural network controller provided that the car has been in a safe operating mode for 20 control steps.
To select a different set of weights for the neural network, you can specify the model .hdf5 in the [rtreach.launch](https://github.com/pmusau17/Platooning-F1Tenth/blob/master/src/race/launch/rtreach.launch) file. The available .hdf5 files are listed in the following [directory](https://github.com/pmusau17/Platooning-F1Tenth/tree/master/src/computer_vision/models). You are also free to train your own!
Arguments that can be provided to the [sim_for_rtreach launch file](https://github.com/pmusau17/Platooning-F1Tenth/blob/master/src/race/launch/sim_for_rtreach.launch):
- world_name: gazebo world file used to generate environment.
- model_name: network .hdf5 keras model file.
- csv_filename: waypoint file used by pure pursuit algorithm.
- lec_only: flag that limits experiment to LEC only control.
- map_file: occupancy grid for corresponding world name.
- random_seed: random seed used to allocte obstacles within vehicle environment.
- freespace_file: free space points within occupancy grid this file is generate by [gen_map.py](https://github.com/pmusau17/Platooning-F1Tenth/blob/master/src/race/scripts/gen_map.py)
- timeout: how long to run each experiment before timeout.
Example specification of argument parameter: **argument_name:=value**
```
$ roslaunch race sim_for_rtreach.launch timeout:=10
```
### Visualizing the Reachable Set
<hr />
You can visualize the reachable set by running the following:
```
$ rosrun rtreach visualize_node porto_obstacles.txt 1 2.0 10
```
Usage:
```
$ rosrun rtreach visualize_node (file containing obstacle locations) (boolean for bloating of reachset) (reachset time horizon) (reachability wall time)
```

### Run Benchmarking Series of Experiments
<hr />
One of the things that may be useful to do is to run a series of simulations with a diverse number of obstacle placements for a given track. Then one can monitor how effective the safety controller under consideration is. We have made this functionality available. The bash script [run_batch.sh](run_batch.sh) performs several experiments with a timeout of 60 seconds and randomly places obstacles within the racetrack.
To use the script first source both the rtreach and Platooning-F1Tenth packages and then run the bash file:
#### End-to-End Controller Experiments
```
$ source rtreach_ros/devel/setup.bash
$ source Platooning-F1Tenth/devel/setup.bash
$ ./run_batch.sh
```
#### Reinforcement Learning Experiments
```
$ source rtreach_ros/devel/setup.bash
$ source Platooning-F1Tenth/devel/setup.bash
$ ./run_batch_rl.sh
```
If a collision occurs during any of the experiments it will be logged along with the random_seed, and number of obstacles so that the scenario can be re-produced. The logs can be found in the following [directory](https://github.com/pmusau17/Platooning-F1Tenth/blob/master/src/race/logs).
# Docker <a name="Docker"></a>
[NVIDIA-Docker](https://github.com/NVIDIA/nvidia-docker) is a requirement for running dockerized. If it is not installed run the following:
```
$ distribution=$(. /etc/os-release;echo $ID$VERSION_ID)
$ curl -s -L https://nvidia.github.io/nvidia-docker/gpgkey | sudo apt-key add -
$ curl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.list | sudo tee /etc/apt/sources.list.d/nvidia-docker.list
$ sudo apt-get update && sudo apt-get install -y nvidia-docker2
$ sudo systemctl restart docker
```
Once that is installed use the [build_docker.sh] file to build the docker images:
```
$ ./build_docker.sh
```
This should take about 10-15 minutes.
In order to enable the use of graphical user interfaces within Docker containers such as Gazebo and Rviz give docker the rights to access the X-Server with:
```bash
$ xhost +local:docker
```
This command allows one to connect a container to a host's X server for display **but it is not secure.** It compromises the access control to X server on your host. So with a little effort, someone could display something on your screen, capture user input, in addition to making it easier to exploit other vulnerabilities that might exist in X.
**So When you are done run :**
```bash
$ xhost -local:docker
```
### Starting the Simulation:
<hr />
To start the simuation run:
```
$ docker container run --runtime=nvidia -it -e DISPLAY --rm --net=host --env="QT_X11_NO_MITSHM=1" -v /tmp/.X11-unix:/tmp/.X11-unix simulator
```
Once gazebo and rviz have completed their startup, in a seperate terminal run:
```
docker container run -it --name=rtreach_ntainer --rm --net=host rtreach
```
### Computing Reachsets for Dynamic Obstacles
<hr />
The obstacle tracking problem is a well studied and challenging topic within the autonomous vehicle, computer vision, and robotics literature.
Typically some assumptions are required in order to constrain the tracking problem to best suit the context of the application. In our framework we assumed that the obstacles could be described a two dimensional kinematic model and a corresponding bounding box. The code below implements reachability using this model
```
$ gcc -std=gnu99 -Wall face_lift_obstacle.c geometry.c interval.c util.c simulate_obstacle.c dynamics_obstacle.c main_obstacle.c obstacle_model.c -lm -o obstacle -DOBSTACLE_MODEL
```
```
./obstacle 10 0 0 1.0 0.0
```
### Obstacle Visualization
<hr />
To visualize the reachsets using a two-dimensional kinematic model:
```
$ gcc -std=gnu99 -Wall face_lift_obstacle_visualization.c geometry.c interval.c util.c simulate_obstacle.c dynamics_obstacle.c main_obstacle_vis.c obstacle_model_plots.c -lm -o obstacle_plot -DOBSTACLE_MODEL
```
```
./obstacle_plot 5 0 0 1.0 0.1
```
### Using the kinematic model within the simulator.
<hr />
As an example, if we assume that the F1Tenth model can be described by a two-dimensional kinematic model, then the reachability analysis code takes the following form:
In two seperate terminals run the following:
**Make sure to source PlatooningF1Tenth/devel/setup.bash**
Terminal 1:
```
roslaunch race sim_for_rtreach.launch
```
**Make sure to source rtreach_ros/devel/setup.bash**
Terminal 2:
```
rosrun rtreach visualize_obs racecar 1.0 2.0 100
```
# Multi-Agent Reachability<a name="MultiAgent"></a>

To enable reachability regimes within the context of dynamic obstacles and multiple agents we need a way to send the hyper-rectangles on the ROS network. Additionally we need to set an upper limit on the number of hyper-rectangles used to represent the reachable set. This is what the following code implements.
To launch such a simulation run the following
```
$ source rtreach_ros/devel/setup.bash
$ source Platooning-F1Tenth/devel/setup.bash
$ roslaunch race sim_for_rtreach_multi_agent.launch
```
Multi-agent nodes
```
rosrun rtreach reach_node_dyn 1.0 2.0 100 1
rosrun rtreach vis_node_param 1.0 2.0 100 1
```
### Running the Multi-Agent Experiments in Docker
To run the multi-agent experiments, open two terminals and run the following:
```
./docker/launch_docker_sim.sh
```
To change the number of vehicles open the above bash script and change number of cars from 2 to 3.
In the second terminal run:
```
./docker/launch_multi_agent.sh
```
# Repository Organization <a name="CodeDescrip"></a>
**ros_src/rtreach:** ros-package containing rtreach implementation.
- [reach_node_sync.cpp](ros_src/rtreach/src/reach_node_sync.cpp): ROS-node implementation of safety monitor and controller.
- [visualize_reachset.cpp](ros_src/rtreach/src/visualize_reachset.cpp): ROS-node for visualization of hyper-rectangles.
**src:** C-implementation of rtreach.
- [dynamics_bicycle_model.c](src/dynamics_bicycle_model.c): Interval arithmetic implementation of a kinematic bicycle model for a car. Parameters are identified using [grey-box system identification](https://github.com/pmusau17/Platooning-F1Tenth/tree/master/src/race/sys_id).
- [interval.c](src/interval.c): Implementation of interval arithmetic methods.
- [geometry.c](src/geometry.c): Implementation of hyper-rectangle methods.
- [face_lift_bicycle_model.c](src/face_lift_bicycle_model.c): Facelifting method implementation with bicycle model dynamics.
- [bicycle_safety.c](src/bicycle_safety.c): Implementation of safety checking for the f1tenth model. Current checking includes static obstacles and collisions with walls.
- [simulate_bicycle.c](src/simulate_bicycle.c): Implementation of Euler simulation of kinematic bicycle model.
- [simulate_bicycle_plots.c](src/simulate_bicycle_plots.c): Implementation of methods for plotting for reach sets.
- [bicycle_model.c](src/bicycle_model.c): Implementation of safety checking for f1tenth platform, makes use of the facelifting algorithms in [face_lift_bicycle_model.c](src/face_lift_bicycle_model.c).
- [bicycle_model_plots.c](src/bicycle_model_plots.c): Same as above but intented for plotting purposes.
- [util.c](src/util.c): Helper functions for timing and printing.
<file_sep>// <NAME>
// 11-2020
// UUV model header
#ifndef OBSTACLE_VIS_H_
#define OBSTACLE_VIS_H_
#include "main.h"
#include "geometry.h"
#include <stdbool.h>
// run reachability for a given wall timer (or iterations if negative)
HyperRectangle runReachability_obstacle_vis(REAL* start, REAL simTime, REAL wallTimeMs, REAL startMs,REAL v_x, REAL v_y, HyperRectangle VisStates[],int *total_intermediate,int max_intermediate,bool plot);
REAL getSimulatedSafeTime(REAL start[2],REAL v_x, REAL v_y);
#endif
|
a9bdb4c5423563d8645764970acd744880886624
|
[
"Markdown",
"Dockerfile",
"Python",
"C",
"C++",
"Shell"
] | 36 |
C
|
michaelchi08/rtreach_f1tenth
|
c61bf3cfed6eee55cc1759a969f592716ffff4aa
|
0f4ef8c4f610571c66519697cadc482e6d01c0b2
|
refs/heads/master
|
<repo_name>shafat010/ProgrammingAssignment2<file_sep>/cachematrix.R
## (Note to my peer reviewers: I've test run this code and it seems to work properly.
## Please test run if you think there's any error.)
#The following "makeCacheMatrix" function creates
#a special "matrix" object that can cache its inverse:
makeCacheMatrix <- function(x = matrix()) {
#setting up the null inverse property
i <- NULL
#Setting the matrix
set <- function(z) {
x <<- z
i <<- NULL
}
#To get the matrix
get <- function() {
## Returning the value of the matrix
return(x) }
#Setting the inverse of the matrix
setinverse <- function(inverse){
i <<- inverse}
#Setting the inverse of the matrix
getinverse <- function(){
## Returning the inverse property
return(i)
}
## Returning the list of the used methods
list(set = set,
get = get,
setinverse = setinverse,
getinverse = getinverse)
}
##The following "cachesolve" function calculates the inverse of the matrix
##returned by the above function. If the inverse has already been calculated,
##(and the matrix has not changed), then the function retrieves the inverse from the cache.
cacheSolve <- function(x, ...) {
## Returning a matrix that is the inverse of 'x'
i <- x$getinverse()
##Returning the inverse if it's already calculated
if (!is.null(i)) {
message("getting cached data")
return(i)
}
#Getting the matrix object and calculating the inverse
data <- x$get()
i <- solve(data, ...)
x$setinverse(i)
i
}
|
eba4794e2f5376f78a38d246ae591ff7f2a807d6
|
[
"R"
] | 1 |
R
|
shafat010/ProgrammingAssignment2
|
d72fd3958b4bed785e754509c21e49de4064b027
|
9b15a82387617ad2eaaec1107ceec9222216ffcf
|
refs/heads/master
|
<repo_name>mkljngd/React-Native-Beginner-<file_sep>/index.js
/**
* @format
*/
/*import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
AppRegistry.registerComponent(appName, () => App);
*/
/*
//Import a library to help create a component
import React from 'react';
import { AppRegistry } from 'react-native';
import Header from './src/components/header';
//Create a component
const App = () => (
<Header headerText={'Albums'}/>
);
//Render it to device
AppRegistry.registerComponent('albums',() => App);
*/
import React, { Component } from 'react'
import {
Text,
View
} from 'react-native'
export default class reactApp extends Component {
constructor() {
super()
this.state = {
myText: 'My Original Text'
}
}
updateText = () => {
this.setState({myText: 'My Changed Text'})
}
render() {
return (
<View>
<Text onPress = {this.updateText}>
{this.state.myText}
</Text>
</View>
);
}
}<file_sep>/README.md
# React-Native-Beginner-
I am learning react native and this is that repository
|
c8fa6c2c3f2884b38efe0b8ecb117e119f6fcfdf
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
mkljngd/React-Native-Beginner-
|
3b34a206c10ffefbb96e868f49845df42ce35ced
|
8c512554fede2d9caaceb384e52ac37f31992346
|
refs/heads/master
|
<file_sep>#include <algorithm>
#include <cstdio>
#include <iterator>
#include <set>
#include <vector>
using namespace std;
typedef pair<int,int> P;
typedef vector< vector<bool> > Matrix;
void dfs(int x, int y, vector<P>& result, Matrix& matrix) {
static int dx[] = {-1, 1, 0, 0};
static int dy[] = {0, 0, 1, -1};
result.push_back(make_pair(x, y));
matrix[x][y] = false;
for(int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if(nx >= 0 && nx < matrix.size() && ny >= 0 && ny < matrix[0].size() && matrix[nx][ny]) {
dfs(nx, ny, result, matrix);
}
}
}
int calculate_hash(vector<P>& points) {
int res = 0;
for(int i = 0; i < points.size(); i++) {
P& x = points[i];
for(int j = i + 1; j < points.size(); j++) {
P& y = points[j];
res += (x.first - y.first) * (x.first - y.first)
+ (x.second - y.second) * (x.second - y.second);
}
}
return res;
}
void handle(multiset<int>& result_set, Matrix& matrix) {
for(int i = 0; i < matrix.size(); i++) {
for(int j = 0; j < matrix[0].size(); j++) {
if(matrix[i][j]) {
vector<P> result;
dfs(i, j, result, matrix);
int hash_value = calculate_hash(result);
result_set.insert(hash_value);
}
}
}
}
bool check(multiset<int>& hash_left, multiset<int> hash_right) {
for(multiset<int>::iterator it = hash_left.begin(); it != hash_left.end(); ++it) {
int t = *it;
multiset<int>::iterator t_it = hash_right.find(t);
if(t_it != hash_right.end()) {
hash_right.erase(t_it);
} else {
return false;
}
}
return hash_right.empty();
}
int main() {
int t,w,h,n,x,y;
scanf("%d",&t);
while(t--) {
scanf("%d%d%d",&w,&h,&n);
Matrix matrix_left(w, vector<bool>(h, false));
Matrix matrix_right(matrix_left);
for(int i = 0; i < n; i++) {
scanf("%d%d", &x, &y);
matrix_left[x][y] = true;
}
for(int i = 0; i < n; i++) {
scanf("%d%d", &x, &y);
matrix_right[x][y] = true;
}
multiset<int> hash_left, hash_right;
handle(hash_left, matrix_left);
handle(hash_right, matrix_right);
bool ans = check(hash_left, hash_right);
printf(ans ? "YES\n" : "NO\n");
}
return 0;
}
<file_sep>#include <cstdio>
using namespace std;
int main() {
double current = 0, total = 0;
for(int i = 0; i < 12; i++) {
scanf("%lf", ¤t);
total += current;
}
printf("$%.2f\n", total / 12);
return 0;
}
<file_sep>#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
char matrix[10][20];
bool vis[10][20];
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};
bool valid_position(int x, int y) {
return x >= 0 && x < 10 && y >= 0 && y < 20;
}
void find_max_cluster(int x,
int y,
int& chess_count,
int& left_most,
int& bottom_most) {
if(left_most == -1 || y < left_most) {
left_most = y;
bottom_most = x;
}
if(y == left_most && x < bottom_most) {
bottom_most = x;
}
vis[x][y] = true;
chess_count++;
for(int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if(valid_position(nx, ny) && !vis[nx][ny] && matrix[nx][ny] == matrix[x][y]) {
find_max_cluster(nx, ny, chess_count, left_most, bottom_most);
}
}
}
void fill_dot(int x, int y, char c) {
matrix[x][y] = '.';
for(int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if(valid_position(nx, ny) && matrix[nx][ny] == c) {
fill_dot(nx, ny, c);
}
}
}
void regular_column(int y, vector<char>& v) {
v.clear();
for(int x = 0; x < 10; x++) {
if(matrix[x][y] != '.') {
v.push_back(matrix[x][y]);
}
}
}
void regular_chessboard() {
int y = 0;
vector<char> v;
for(int j = 0; j < 15; j++) {
regular_column(j, v);
if(v.empty()) continue;
for(int i = 0; i < 10; i++) {
matrix[i][y] = i < v.size() ? v[i] : '.';
}
y++;
}
while(y < 15) {
for(int i = 0; i < 10; i++) {
matrix[i][y] = '.';
}
y++;
}
}
int main() {
int t;
scanf("%d", &t);
int game_index = 1;
while(t--) {
for(int i = 9; i >= 0; i--) scanf("%s", matrix[i]);
int score = 0;
int move_index = 1;
int moved_balls = 0;
printf("Game %d:\n\n", game_index++);
while(true) {
int x = -1, y = -1, max_chess_count = -1;
memset(vis, 0, sizeof(vis));
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 15; j++) {
if(!vis[i][j] && matrix[i][j] != '.') {
int chess_count = 0, left_most = -1, bottom_most = -1;
find_max_cluster(i, j, chess_count, left_most, bottom_most);
if(chess_count > max_chess_count) {
x = bottom_most; y = left_most; max_chess_count = chess_count;
} else if(chess_count == max_chess_count) {
if(left_most < y || (left_most == y && bottom_most < x)) {
x = bottom_most; y = left_most;
}
}
}
}
}
if(max_chess_count < 2) break;
int current_score = (max_chess_count - 2) * (max_chess_count - 2);
score += current_score;
moved_balls += max_chess_count;
printf("Move %d at (%d,%d): removed %d balls of color %c, got %d points.\n",
move_index++, x+1, y+1, max_chess_count, matrix[x][y], current_score);
fill_dot(x, y, matrix[x][y]);
regular_chessboard();
}
if(moved_balls == 150) {
score += 1000;
}
printf("Final score: %d, with %d balls remaining.\n\n", score, 150-moved_balls);
}
return 0;
}
<file_sep>#include <cstdio>
#include <cstring>
#include <cctype>
using namespace std;
char directory[] = "22233344455566677778889999";
int m[10000000];
int mapStringToPhone(const char* str) {
int len = strlen(str);
int phone = 0;
for(int i = 0; i < len; i++) {
if(str[i] != '-') {
if(isalpha(str[i])) phone = phone * 10 + directory[str[i]-'A'] - '0';
else phone = phone * 10 + str[i] - '0';
}
}
return phone;
}
int main() {
int n;
scanf("%d", &n);
char phone_number[100];
for(int i = 0; i < n; i++) {
scanf("%s", phone_number);
int phone = mapStringToPhone(phone_number);
m[phone]++;
}
bool has_duplicate = false;
for(int i = 0; i < 10000000; i++) {
if(m[i] > 1) has_duplicate = true;
}
if(!has_duplicate) {
printf("No duplicates.\n");
} else {
for(int i = 0; i < 10000000; i++) {
if(m[i] > 1) {
printf("%03d-%04d %d\n", i / 10000, i % 10000, m[i]);
}
}
}
return 0;
}
<file_sep>#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
struct DnaString{
char* dna_string;
int unorder_count;
};
bool compare(const DnaString& a, const DnaString& b) {
return a.unorder_count < b.unorder_count;
}
void freeDnaString(DnaString& dna) {
delete[] dna.dna_string;
}
DnaString inputDnaString(int length) {
DnaString res;
res.dna_string = new char[length + 1];
res.unorder_count = 0;
scanf("%s", res.dna_string);
return res;
}
int getUnorderCount(char* dna_string, int l, int r, char* buff) {
int m = (l + r) >> 1;
if(l + 1 == r) {
return 0;
}
int count = 0;
count += getUnorderCount(dna_string, l, m, buff);
count += getUnorderCount(dna_string, m, r, buff);
int ptr = 0;
int ptr_l = l, ptr_r = m;
while(ptr_l < m && ptr_r < r) {
if(dna_string[ptr_r] < dna_string[ptr_l]) {
buff[ptr++] = dna_string[ptr_r++];
count += m - ptr_l;
} else {
buff[ptr++] = dna_string[ptr_l++];
}
}
while(ptr_l < m) buff[ptr++] = dna_string[ptr_l++];
while(ptr_r < r) buff[ptr++] = dna_string[ptr_r++];
for(int i = l; i < r; i++) {
dna_string[i] = buff[i - l];
}
return count;
}
int main() {
int n, length;
scanf("%d%d", &length, &n);
vector<DnaString> dna_strings;
for(int i = 0; i < n; i++) {
DnaString dna_string = inputDnaString(length);
dna_strings.push_back(dna_string);
}
char *buff = new char[length];
char *dna_string = new char[length + 1];
for(int i = 0; i < n; i++) {
DnaString& current_dna = dna_strings[i];
memcpy(dna_string, current_dna.dna_string, sizeof(char)*length);
current_dna.unorder_count = getUnorderCount(dna_string, 0, length, buff);
}
delete[] buff;
delete[] dna_string;
sort(dna_strings.begin(), dna_strings.end(), compare);
for(int i = 0; i < n; i++) {
printf("%s\n", dna_strings[i].dna_string);
freeDnaString(dna_strings[i]);
}
return 0;
}
<file_sep>#include <algorithm>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
string print_binary(int* binary, int k) {
string res = "";
for(int i = k - 1; i >= 0; i--) {
res.append(1, binary[i] + '0');
}
return res;
}
bool solve(int* binary, char* bit, int k, bool positive) {
int i = 0;
while(i < k) {
for(; i < k; i++) {
if(binary[i] == 1 && bit[i] == (positive ? 'n' : 'p')) {
break;
}
}
if(i == k) {
return true;
}
i++;
for(; i < k; i++) {
if(binary[i] == 0 && bit[i] == (positive ? 'p' : 'n')) {
binary[i] = 1;
break;
}
binary[i] = 1 - binary[i];
}
if(i == k) {
return false;
}
i++;
}
return true;
}
string solve(char* bit, int k, long long N) {
reverse(bit, bit+k);
int *binary = new int[k];
memset(binary, 0, sizeof(int)*k);
bool positive = N >= 0;
unsigned long long M = N >= 0 ? N : -N;
int ptr = 0;
while(ptr < k && M) {
binary[ptr++] = M % 2;
M >>= 1;
}
string res = "Impossible";
if(!M && solve(binary, bit, k, positive)) {
res = print_binary(binary, k);
}
delete[] binary;
return res;
}
int main() {
int t, k;
scanf("%d", &t);
while(t--) {
scanf("%d", &k);
char *bit = new char[k+1];
scanf("%s", bit);
long long N;
scanf("%lld", &N);
printf("%s\n", solve(bit, k, N).c_str());
delete[] bit;
}
return 0;
}
/*
Input:
5
4
nppp
-5
4
ppnn
10
3
pnp
6
4
ppnn
-3
5
pnppn
11
--------------
Output:
1011
1110
Impossible
0011
11101
*/
<file_sep>#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
const int INF = ~0U>>2;
int F[2][21][901];
bool P[201][21][901];
struct Candidate{
int d;
int p;
};
Candidate candidates[201];
int& f(int i, int j, int k) {
return F[i % 2][j][k+400];
}
bool& p(int i, int j, int k) {
return P[i][j][k+400];
}
void get_answer(vector<int>& answer, int volume, int n, int m) {
while(n > 0 && m > 0) {
if(p(n, m, volume)) {
answer.push_back(n);
m--;
volume = volume - candidates[n].d + candidates[n].p;
}
n--;
}
reverse(answer.begin(), answer.end());
}
int main() {
int m, n;
int jury_number = 1;
while(scanf("%d%d", &n, &m) != EOF) {
if(n == 0 && m == 0) break;
for(int i = 1; i <= n; i++) {
scanf("%d%d", &candidates[i].d, &candidates[i].p);
}
for(int i = 0; i < 2; i++) {
for(int j = 0; j <= 20; j++) {
for(int k = 0; k < 901; k++) {
F[i][j][k] = -INF;
}
}
}
memset(P, 0, sizeof(P));
for(int i = 0; i <= 1; i++) {
f(i, 0, 0) = 0;
}
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= min(m,i); j++) {
for(int k = -400; k <= 400; k++) {
f(i, j, k) = f(i-1, j, k);
if(k - candidates[i].d + candidates[i].p >= -400
&& k - candidates[i].d + candidates[i].p <= 400) {
int t = f(i-1, j-1, k-candidates[i].d+candidates[i].p) + candidates[i].d + candidates[i].p;
if(f(i, j, k) <= t) {
p(i, j, k) = true;
f(i, j, k) = t;
}
}
}
}
}
int min_number = INF;
for(int i = -400; i <= 400; i++) {
if(f(n, m, i) >= 0)
min_number = min(min_number, abs(i));
}
vector<int> result;
if(f(n, m, -min_number) <= f(n, m, min_number)) {
get_answer(result, min_number, n, m);
} else {
get_answer(result, -min_number, n, m);
}
int DJ = 0, PJ = 0;
for(int i = 0; i < result.size(); i++) {
DJ += candidates[result[i]].d;
PJ += candidates[result[i]].p;
}
printf("Jury #%d\n", jury_number++);
printf("Best jury has value %d for prosecution and value %d for defence:\n", DJ, PJ);
for(int i = 0; i < result.size(); i++) printf(" %d", result[i]);
printf("\n");
}
return 0;
}
<file_sep>#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iterator>
#include <queue>
#include <set>
using namespace std;
typedef set< pair< pair<int,int>, pair<int,int> > > wallset;
char path[10010];
int f[110][110];
bool check_boundary(int w, int h, int x, int y) {
return x >= 0 && x < w && y >= 0 && y < h;
}
pair<int, int> get_direction(char dir) {
if(dir == 'U') return make_pair(0, 1);
if(dir == 'D') return make_pair(0, -1);
if(dir == 'L') return make_pair(-1, 0);
return make_pair(1, 0);
}
bool not_wall(int x1, int y1, int x2, int y2, wallset& walls) {
return walls.find(make_pair(make_pair(x1,y1), make_pair(x2,y2))) == walls.end() &&
walls.find(make_pair(make_pair(x2,y2), make_pair(x1,y1))) == walls.end();
}
pair<int,int> check_walls_and_get_terminal(int w, int h, wallset& walls) {
for(wallset::iterator it = walls.begin(); it != walls.end(); ++it) {
pair<int, int> wall_a = it->first;
pair<int, int> wall_b = it->second;
if(wall_a.first == wall_b.first) {
if(abs(wall_a.second - wall_b.second) != 1) {
return make_pair(-1, -1);
}
} else if(wall_a.second == wall_b.second) {
if(abs(wall_a.first - wall_b.first) != 1) {
return make_pair(-1, -1);
}
} else {
return make_pair(-1, -1);
}
}
pair<int, int> res = make_pair(0, 0);
for(int i = 0; path[i]; i++) {
pair<int,int> d = get_direction(path[i]);
int dx = d.first, dy = d.second;
int x = res.first, y = res.second;
int nx = x + dx, ny = y + dy;
if(not_wall(x, y, nx, ny, walls)) {
if(check_boundary(w, h, nx, ny)) {
res = make_pair(nx, ny);
} else {
return make_pair(-1, -1);
}
} else {
return make_pair(-1, -1);
}
}
return res;
}
bool check_unique_and_shortest(int tx, int ty, int w, int h, wallset& walls) {
static int dx[] = {-1, 1, 0, 0};
static int dy[] = {0, 0, 1, -1};
for(int i = 0; i < w; i++) {
for(int j = 0; j < h; j++) {
f[i][j] = -1;
}
}
int path_length = strlen(path);
int count = 0;
queue< pair<int, int> > q;
f[0][0] = 0;
q.push(make_pair(0, 0));
while(!q.empty()) {
pair<int, int> t = q.front(); q.pop();
int x = t.first, y = t.second;
int step = f[x][y];
if(step > path_length) continue;
if(x == tx && y == ty) {
if(step < path_length) return false;
++count;
if(count == 2) return false;
}
for(int i = 0; i < 4; i++) {
int nx = x + dx[i], ny = y + dy[i];
if(check_boundary(w, h, nx, ny) &&
not_wall(x, y, nx, ny, walls) && f[nx][ny] == -1) {
f[nx][ny] = step+1;
q.push(make_pair(nx, ny));
}
}
}
while(tx != 0 || ty != 0) {
int cnt = 0;
int xx = tx, yy = ty;
for(int i = 0; i < 4; i++) {
int nx = xx + dx[i], ny = yy + dy[i];
if(check_boundary(w, h, nx, ny)
&& not_wall(xx, yy, nx, ny, walls)
&& f[xx][yy] == f[nx][ny] + 1) {
++cnt;
tx = nx;
ty = ny;
}
}
if(cnt > 1) return false;
}
return true;
}
bool check_correct(int w, int h, wallset& walls) {
pair<int, int> terminal = check_walls_and_get_terminal(w, h, walls);
if(terminal.first == -1) {
return false;
}
if(!check_unique_and_shortest(terminal.first, terminal.second, w, h, walls)) {
return false;
}
for(wallset::iterator it = walls.begin(); it != walls.end(); ++it) {
pair< pair<int,int>, pair<int,int> > t = *it;
walls.erase(it);
if(check_unique_and_shortest(terminal.first, terminal.second, w, h, walls)) {
return false;
}
walls.insert(t);
it = walls.find(t);
}
return true;
}
int main() {
int t, w, h, m, x1, y1, x2, y2;
scanf("%d", &t);
while(t--) {
wallset walls;
scanf("%d%d", &w, &h);
scanf("%s", path);
scanf("%d", &m);
for(int i = 0; i < m; i++) {
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
walls.insert(make_pair(make_pair(x1,y1), make_pair(x2,y2)));
}
printf(check_correct(w, h, walls) ? "CORRECT\n" : "INCORRECT\n");
}
return 0;
}
<file_sep>#include <cstdio>
#include <cstring>
#include <map>
using namespace std;
char left[3][20], right[3][20], verdict[3][10];
int weight[12];
char ans[2][30]= {"light", "heavy"};
int len[3];
bool check(int id, int w) {
weight[id] = w;
for(int i = 0; i < 3; i++) {
int left_weight = 0, right_weight = 0;
for(int j = 0; j < len[i]; j++) {
left_weight += weight[left[i][j] - 'A'];
right_weight += weight[right[i][j] - 'A'];
}
if((left_weight == right_weight && strcmp(verdict[i], "even"))
|| (left_weight > right_weight && strcmp(verdict[i], "up"))
|| (left_weight < right_weight && strcmp(verdict[i], "down"))) {
weight[id] = 1;
return false;
}
}
weight[id] = 1;
return true;
}
pair<int, int> solve() {
for(int i = 0; i < 12; i++) weight[i] = 1;
for(int i = 0; i < 12; i++) {
if(check(i, 0)) {
return make_pair(i, 0);
}
if(check(i, 2)) {
return make_pair(i, 1);
}
}
return make_pair(-1, -1);
}
int main() {
int n;
scanf("%d", &n);
while(n--) {
for(int i = 0; i < 3; i++) {
scanf("%s%s%s", left[i], right[i], verdict[i]);
len[i] = strlen(left[i]);
}
pair<int,int> result = solve();
printf("%c is the counterfeit coin and it is %s.\n", char(result.first + 'A'), ans[result.second]);
}
return 0;
}
<file_sep>#include <algorithm>
#include <cstdio>
#include <functional>
#include <vector>
using namespace std;
void find_maximum_types(vector<int>& types, int index, int last_index, int sum, int aim, int type_count, vector<int>& output, vector<int>& ans, int& ans_type_count, bool& tie) {
if(sum > aim) return;
if(sum == aim) {
if(type_count > ans_type_count) {
ans_type_count = type_count;
ans = vector<int>(output);
tie = false;
} else if(type_count == ans_type_count) {
if(output.size() < ans.size() || (output.size() == ans.size() && output[0] > ans[0])) {
ans.clear();
ans = vector<int>(output);
} else if(output.size() == ans.size() && output[0] == ans[0]){
tie = true;
}
}
return;
}
if(output.size() == 4) return;
int add_count = 0;
output.push_back(types[index]);
if(index != last_index) add_count = 1;
find_maximum_types(types, index, index, sum+types[index], aim, type_count + add_count, output, ans, ans_type_count, tie);
output.pop_back();
if(index+1 < types.size()) {
find_maximum_types(types, index+1, last_index, sum, aim, type_count, output, ans, ans_type_count, tie);
}
}
int main() {
int stamp_type;
while(scanf("%d", &stamp_type) != EOF) {
vector<int> types;
types.push_back(stamp_type);
while(scanf("%d", &stamp_type)==1 && stamp_type) {
types.push_back(stamp_type);
}
sort(types.begin(), types.end(), greater<int>());
int aim;
while(scanf("%d", &aim) == 1 && aim) {
vector<int> output, ans;
int ans_type_count = 0;
bool tie = false;
find_maximum_types(types, 0, -1, 0, aim, 0, output, ans, ans_type_count, tie);
if(ans.size() == 0) {
printf("%d ---- none\n", aim);
} else {
sort(ans.begin(), ans.end());
printf("%d (%d): ", aim, ans_type_count);
if(tie) printf("tie\n");
else {
for(int i = 0; i < ans.size(); i++) {
printf(i == ans.size() - 1 ? "%d\n":"%d ", ans[i]);
}
}
}
}
}
return 0;
}
<file_sep>#include <algorithm>
#include <cstdio>
#include <functional>
#include <vector>
using namespace std;
void calculate_factor(int x, vector<int>& factors) {
for(int i = 1; i * i <= x; i++) {
if(x % i == 0) {
factors.push_back(i);
if(x / i != i) {
factors.push_back(x / i);
}
}
}
sort(factors.begin(), factors.end());
}
bool can(vector<int>& sticks, int index, int aim, int sum, vector<bool>& vis, const vector<int>& next) {
vis[index] = true;
sum += sticks[index];
if(sum == aim) {
for(int i = 0; i < sticks.size(); i++) {
if(!vis[i]) {
bool res = can(sticks, i, aim, 0, vis, next);
if(!res) vis[index] = false;
return res;
}
}
return true;
}
for(int i = index+1; i < sticks.size(); i++) {
if(!vis[i] && sum + sticks[i] <= aim) {
bool res = can(sticks, i, aim, sum, vis, next);
i = next[i];
if(res) return true;
}
}
vis[index] = false;
return false;
}
int main() {
int n;
while(scanf("%d", &n) != EOF && n) {
vector<int> sticks(n, 0);
int sum_length = 0, max_length = 0;
for(int i = 0; i < n; i++) {
scanf("%d", &sticks[i]);
sum_length += sticks[i];
max_length = max(max_length, sticks[i]);
}
sort(sticks.begin(), sticks.end(), greater<int>());
vector<int> next(n, 0);
for(int i = 0; i < n; i++) next[i] = i;
for(int i = n-2; i >= 0; i--) {
if(sticks[i+1] == sticks[i]) {
next[i] = next[i+1];
}
}
vector<int> factors;
calculate_factor(sum_length, factors);
vector<bool> vis(n, false);
for(int i = 0; i < factors.size(); i++) {
if(factors[i] >= max_length) {
// printf("Current factor: %d\n", factors[i]);
bool c = can(sticks, 0, factors[i], 0, vis, next);
if(c) {
printf("%d\n", factors[i]);
break;
}
}
}
}
return 0;
}
<file_sep>#include <cstdio>
#include <string>
#include <map>
using namespace std;
string haab_months[] = {"pop", "no", "zip", "zotz",
"tzec", "xul", "yoxkin", "mol",
"chen", "yax", "zac", "ceh",
"mac", "kankin", "muan", "pax", "koyab", "cumhu"};
string tzolkin_months[] = {"imix", "ik", "akbal", "kan", "chicchan",
"cimi", "manik", "lamat", "muluk", "ok",
"chuen", "eb", "ben", "ix", "mem",
"cib", "caban", "eznab", "canac", "ahau"};
map<string, int> month_number;
struct HaabDate{
int number_of_the_day;
string month;
int year;
};
struct TzolkinDate{
int number;
int name_of_the_day_index;
int year;
};
TzolkinDate convertHaabDateToTzolkinDate(HaabDate& date) {
TzolkinDate t_date;
int month_day = getMonthDay(getMonthNumber(date.month));
int total_day = date.year * 365 + month_day + date.number_of_the_day;
t_date.year = total_day / 260;
total_day %= 260;
t_date.name_of_the_day_index = total_day % 20;
t_date.number = total_day % 13 + 1;
return t_date;
}
int getMonthDay(int month_number) {
return month_number * 20;
}
int getMonthNumber(const string& month) {
if(month_number.find(month) == month_number.end()) return 18;
return month_number[month];
}
void inputHaabDate(HaabDate& date) {
char buff[100];
scanf("%d. %s %d", &date.number_of_the_day, buff, &date.year);
date.month = string(buff);
}
void init() {
for(int i = 0; i < 18; i++) {
month_number[haab_months[i]] = i;
}
}
void outputTzolkinDate(TzolkinDate& date) {
printf("%d %s %d\n", date.number,
tzolkin_months[date.name_of_the_day_index].c_str(), date.year);
}
int main() {
init();
int n;
scanf("%d", &n);
printf("%d\n", n);
HaabDate haab_date;
for(int i = 0; i < n; i++) {
inputHaabDate(haab_date);
TzolkinDate t_date = convertHaabDateToTzolkinDate(haab_date);
outputTzolkinDate(t_date);
}
return 0;
}
<file_sep>#include <algorithm>
#include <cstdio>
#include <functional>
#include <vector>
using namespace std;
bool can(int s, vector<int>& sides, int placed, int n, vector<int>& column) {
if(placed == n) {
return true;
}
int next_column = 0;
for(int i = 1; i < s; i++) {
if(column[i] < column[next_column]) {
next_column = i;
}
}
for(int i = 10; i >= 1; i--) {
if(sides[i] == 0 || i+column[next_column] > s || next_column+i > s) {
continue;
}
bool can_place = true;
for(int j = next_column; j < next_column+i; j++) {
if(column[j] != column[next_column]) {
can_place = false;
break;
}
}
if(!can_place) continue;
sides[i]--;
for(int j = next_column; j < next_column+i; j++) {
column[j] += i;
}
if(can(s, sides, placed+1, n, column)) {
return true;
}
sides[i]++;
for(int j = next_column; j < next_column+i; j++) {
column[j] -= i;
}
}
return false;
}
int main() {
int t, s, n, side;
scanf("%d", &t);
while(t--) {
scanf("%d%d", &s, &n);
vector<int> sides(11, 0);
for(int i = 0; i < n; i++) {
scanf("%d", &side);
sides[side]++;
}
vector<int> column(s, 0);
bool ans = can(s, sides, 0, n, column);
printf(ans?"KHOOOOB!\n":"HUTUTU!\n");
}
return 0;
}
<file_sep>#include <algorithm>
#include <cstdio>
#include <vector>
#include <set>
using namespace std;
struct RlePair {
int pixel_value;
int run_length;
};
void addOutput(vector<RlePair>& output, RlePair& output_pair) {
int m = output.size();
if(m > 0 && output_pair.pixel_value == output[m-1].pixel_value) {
output[m-1].run_length += output_pair.run_length;
} else {
output.push_back(output_pair);
}
}
bool check(int x, int y, int width, int height) {
return x >= 0 && x < height && y >= 0 && y < width;
}
bool compare(const RlePair& a, const RlePair& b) {
return a.run_length < b.run_length;
}
int getPixel(int x, int y, int width, vector<RlePair>& rle_pairs) {
int index = x * width + y;
int l = 0, r = rle_pairs.size();
while(r - l > 1) {
int m = (l+r) >> 1;
if(rle_pairs[m].run_length > index) r = m;
else l = m;
}
return rle_pairs[l].pixel_value;
}
pair<int, int> getCoordinates(int index, int width) {
int x = index / width;
int y = index % width;
return make_pair(x, y);
}
int getEdgePixel(int x, int y, int width, int height, int current_pixel, vector<RlePair>& rle_pairs) {
int max_absolute_pixel = 0;
for(int i = -1; i <= 1; i++) {
for(int j = -1; j <= 1; j++) {
if(i == 0 && j == 0) continue;
int dx = x + i;
int dy = y + j;
if(check(dx, dy, width, height)) {
int pixel = getPixel(dx, dy, width, rle_pairs);
max_absolute_pixel = max(max_absolute_pixel, abs(current_pixel - pixel));
}
}
}
return max_absolute_pixel;
}
void edgeDetect(int width, vector<RlePair>& rle_pairs, vector<RlePair>& output) {
output.clear();
vector<RlePair> total;
int sum = 0;
for(int i = 0; i < rle_pairs.size(); ++i) {
RlePair t_pair;
t_pair.pixel_value = rle_pairs[i].pixel_value;
t_pair.run_length = sum;
sum += rle_pairs[i].run_length;
total.push_back(t_pair);
}
vector<RlePair> t_output;
int height = sum / width;
/*
for(int i = 0; i < height; ++i) {
for(int j = 0; j < width; j++) {
int pixel = getPixel(i, j, width, total);
int c_pixel = getEdgePixel(i, j, width, height, pixel, total);
RlePair output_pair;
output_pair.pixel_value = c_pixel;
output_pair.run_length = 1;
addOutput(output, output_pair);
}
}
return;
*/
sum = 0;
set< pair<int, int> > s;
for(int i = 0; i < rle_pairs.size(); ++i) {
RlePair& current_pair = rle_pairs[i];
pair<int, int> coordinate = getCoordinates(sum, width);
int x = coordinate.first, y = coordinate.second;
for(int dx = -1; dx <= 1; dx++) {
for(int dy = -1; dy <= 1; dy++) {
int nx = x + dx, ny = y + dy;
if(check(nx, ny, width, height) && s.find(make_pair(nx, ny)) == s.end()) {
s.insert(make_pair(nx, ny));
RlePair t_pair;
int current_pixel = getPixel(nx, ny, width, total);
t_pair.pixel_value = getEdgePixel(nx, ny, width, height, current_pixel, total);
t_pair.run_length = nx * width + ny;
t_output.push_back(t_pair);
}
}
}
sum += current_pair.run_length;
}
sort(t_output.begin(), t_output.end(), compare);
for(int i = 0; i < t_output.size(); i++) {
RlePair output_pair;
if(i == t_output.size() - 1) {
output_pair.run_length = sum - t_output[i].run_length;
} else {
output_pair.run_length = t_output[i+1].run_length - t_output[i].run_length;
}
output_pair.pixel_value = t_output[i].pixel_value;
addOutput(output, output_pair);
}
}
int main() {
int width, pixel_value, run_length;
RlePair rle_pair;
while(scanf("%d", &width) && width) {
vector<RlePair> rle_pairs;
while(true) {
scanf("%d%d", &pixel_value, &run_length);
rle_pair.pixel_value = pixel_value;
rle_pair.run_length = run_length;
rle_pairs.push_back(rle_pair);
if(pixel_value == 0 && run_length == 0) break;
}
vector<RlePair> output;
edgeDetect(width, rle_pairs, output);
printf("%d\n", width);
for(int i = 0; i < output.size(); i++) {
printf("%d %d\n", output[i].pixel_value, output[i].run_length);
}
printf("0 0\n");
}
printf("0\n");
return 0;
}
/*
30
10 41
20 41
15 41
30 41
25 41
0 5
0 0
==
30
0 10
10 62
5 20
15 62
5 20
25 6
5 15
0 9
25 6
0 0
*/
<file_sep>#include <cstdio>
#include <cstring>
#include <map>
#include <string>
using namespace std;
string get_inventory(const string& str) {
int cnt[10];
memset(cnt, 0, sizeof(cnt));
for(int i = 0; i < str.size(); i++) {
cnt[str[i]-'0']++;
}
char t_cnt[5];
string res = "";
for(int i = 0; i < 10; i++) if(cnt[i]) {
sprintf(t_cnt, "%d", cnt[i]);
res += string(t_cnt);
res.append(1, char(i+'0'));
}
return res;
}
int main() {
char number[100];
while(scanf("%s", number) != EOF) {
if(!strcmp(number, "-1")) break;
map<string, int> inventories;
string inventory = number;
inventories[inventory] = 0;
int i;
for(i = 1; i <= 15; i++) {
inventory = get_inventory(inventory);
if(inventories.find(inventory) != inventories.end()) {
int k = i - inventories[inventory];
if(k == 1) {
if(i == 1) printf("%s is self-inventorying\n", number);
else printf("%s is self-inventorying after %d steps\n", number, i - 1);
} else {
printf("%s enters an inventory loop of length %d\n", number, k);
}
break;
}
inventories[inventory] = i;
}
if(i == 16) {
printf("%s can not be classified after 15 iterations\n", number);
}
}
}
<file_sep>#include <cstdio>
using namespace std;
const int P = 23;
const int E = 28;
const int I = 33;
int t1, t2, t3, lcm_total;
int gcd(int a, int b) {
while(b) {
int t = a % b;
a = b;
b = t;
}
return a;
}
int lcm(int a, int b) {
int gcd_number = gcd(a, b);
return a / gcd(a, b) * b;
}
int lcm(int a, int b, int c) {
return lcm(lcm(a, b), c);
}
int extGcd(int a, int b, int &x, int &y) {
if(b == 0) {
x = 1;
y = 0;
return a;
}
int dx, dy;
int gcd_number = extGcd(b, a%b, dx, dy);
x = dy;
y = dx - (a / b) * dy;
return gcd_number;
}
int getNextDay(int p, int e, int i, int d) {
p = p % P;
e = e % E;
i = i % I;
int crt_result = (p * t1 * (lcm_total / P)) % lcm_total;
crt_result = (crt_result + (e * t2 * (lcm_total / E)) % lcm_total) % lcm_total;
crt_result = (crt_result + (i * t3 * (lcm_total / I)) % lcm_total) % lcm_total;
crt_result = (crt_result + lcm_total) % lcm_total;
while(crt_result <= d) {
crt_result += lcm_total;
}
return crt_result - d;
}
void init() {
int t, a;
lcm_total = lcm(P, E, I);
a = lcm_total / P;
extGcd(a, P, t1, t);
a = lcm_total / E;
extGcd(a, E, t2, t);
a = lcm_total / I;
extGcd(a, I, t3, t);
}
int main() {
init();
int p,e,i,d;
int case_num = 1;
while(scanf("%d%d%d%d", &p, &e, &i, &d) != EOF) {
if(p == -1 && e == -1 && i == -1 && d == -1) break;
int next_day = getNextDay(p, e, i, d);
printf("Case %d: the next triple peak occurs in %d days.\n", case_num++, next_day);
}
return 0;
}
<file_sep>#include <iostream>
#include <string>
#include <stack>
using namespace std;
int main() {
string command, url;
stack<string> back_stack, forward_stack;
back_stack.push("http://www.acm.org/");
while(cin >> command) {
if(command == "QUIT") break;
if(command == "VISIT") {
while(!forward_stack.empty()) forward_stack.pop();
cin >> url;
cout << url << endl;
back_stack.push(url);
}
else if(command == "BACK") {
if(back_stack.size() == 1) {
cout << "Ignored" << endl;
continue;
}
forward_stack.push(back_stack.top());
back_stack.pop();
cout << back_stack.top() << endl;
}
else if(command == "FORWARD") {
if(forward_stack.empty()) {
cout << "Ignored" << endl;
continue;
}
back_stack.push(forward_stack.top());
forward_stack.pop();
cout << back_stack.top() << endl;
}
}
return 0;
}
<file_sep>#include <cstdio>
#include <cstring>
#include <deque>
#include <queue>
using namespace std;
const int INF = ~0U>>2;
int n[7];
int f[60001];
int main() {
int case_number = 1;
while(scanf("%d", &n[1]) != EOF) {
int sum = n[1];
for(int i = 2; i <= 6; i++) {
scanf("%d", &n[i]);
sum += i * n[i];
}
if(sum == 0) break;
printf("Collection #%d:\n", case_number++);
if(sum % 2 == 1) {
printf("Can't be divided.\n\n");
continue;
}
memset(f, 0, sizeof(f));
for(int i = 1; i <= 6; i++) if(n[i]) {
queue<int> p;
deque<int> q;
for(int j = 0; j < i; j++) {
for(int k = j, s = 0; k <= sum / 2; k += i, s++) {
if(p.size() == n[i] + 1) {
if(p.front() == q.front()) q.pop_front();
p.pop();
}
int t = f[k] - i * s;
p.push(t);
while(!q.empty() && q.back() < t) q.pop_back();
q.push_back(t);
f[k] = q.front() + i * s;
}
}
}
if(f[sum / 2] == sum / 2) {
printf("Can be divided.\n\n");
} else {
printf("Can't be divided.\n\n");
}
}
return 0;
}
<file_sep>#include <cstdio>
using namespace std;
int get_initial_number(int x, int m, int k) {
for(int i = k + 1; i <= k+k; i++) {
x = (x + m) % i;
}
return x;
}
bool can(int k, int m) {
for(int i = 0; i < k; i++) {
int initial_number = get_initial_number(i, m, k);
if(initial_number >= k) return false;
}
return true;
}
int main() {
int k;
while(scanf("%d", &k) == 1 && k) {
for(int i = k + 1; ; i++) {
if(can(k, i)) {
printf("%d\n", i);
break;
}
}
}
return 0;
}
<file_sep>#include <cstdio>
#include <cmath>
using namespace std;
const double PI = acos(-1.0);
int getErosionYear(double x, double y) {
double radius_square = x * x + y * y;
double area = PI * radius_square * 0.5;
double year = area / 50;
return ceil(year);
}
int main() {
int T;
scanf("%d", &T);
for(int i = 0; i < T; i++) {
double x, y;
scanf("%lf%lf", &x, &y);
int year = getErosionYear(x, y);
printf("Property %d: This property will begin eroding in year %d.\n", i + 1, year);
}
printf("END OF OUTPUT.\n");
return 0;
}
<file_sep>#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
void roll(char* text, vector<int>& roll_vec, int k) {
int n = roll_vec.size();
char t_text[222];
for(int i = 0; text[i] != '\0'; i++) {
t_text[i] = text[i];
}
for(int i = 0; i < n; i++) {
int id = (i+k)%n;
t_text[roll_vec[id]] = text[roll_vec[i]];
}
for(int i = 0; text[i] != '\0'; i++) {
text[i] = t_text[i];
}
}
void encode(const char* raw_text, char* output_text, int n, vector<int>& p, int k) {
int i;
for(i = 0; raw_text[i]; i++) {
output_text[i] = raw_text[i];
}
while(i < n) {
output_text[i++] = ' ';
}
output_text[i] = '\0';
vector<bool> vis(n, false);
vector<int> pc;
for(i = 0; i < n; i++) {
if(!vis[i]) {
pc.clear();
int id = i;
do{
vis[id] = true;
pc.push_back(id);
id = p[id];
} while(id != i);
int mod = pc.size();
int k_count = k % mod;
roll(output_text, pc, k_count);
}
}
}
int main() {
int n;
char raw_text[222];
while(scanf("%d", &n) != EOF && n) {
vector<int> p(n, 0);
for(int i = 0; i < n; i++) {
scanf("%d", &p[i]);
p[i]--;
}
int k;
while(scanf("%d", &k)!=0 && k) {
getchar();
gets(raw_text);
char output_text[222];
encode(raw_text, output_text, n, p, k);
puts(output_text);
}
printf("\n");
}
return 0;
}
<file_sep>#include <cstdio>
#include <cmath>
using namespace std;
int solve(double c) {
int res = 0;
double current = 0;
while(current < c) {
res++;
current += 1.0 / (res+1);
}
return res;
}
int main() {
double c;
while(scanf("%lf", &c) != EOF) {
if(fabs(c) < 1e-8) break;
int ans = solve(c);
printf("%d card(s)\n", ans);
}
return 0;
}
<file_sep>#include <cstdio>
#include <cstring>
using namespace std;
struct BigDecimal{
int *num;
int dot_position;
int len;
};
void freeBigDecimal(BigDecimal &decimal) {
delete[] decimal.num;
}
BigDecimal multiply(BigDecimal* a, BigDecimal* b) {
int len_a = a->len;
int len_b = b->len;
BigDecimal res;
res.len = len_a + len_b;
res.dot_position = a->dot_position + b->dot_position;
res.num = new int[len_a + len_b];
memset(res.num, 0, sizeof(int) * (len_a + len_b));
for(int i = 0; i < len_a; i++) {
int promote = 0;
for(int j = 0; j < len_b; j++) {
int d = i + j;
int t = a->num[i] * b->num[j] + promote + res.num[d];
res.num[d] = (t % 10);
promote = t / 10;
}
int ptr = i + len_b;
while(promote) {
int t = res.num[ptr] + promote;
res.num[ptr] = t % 10;
promote = t / 10;
ptr++;
}
}
return res;
}
BigDecimal parseStrToBigDecimal(const char* R) {
int len = strlen(R);
BigDecimal decimal;
decimal.dot_position = 0;
decimal.num = new int[len];
memset(decimal.num, 0, sizeof(int) * len);
int ptr = 0;
for(int i = len - 1; i >= 0; i--) {
int pos = len - 1 - i;
if(R[i] == '.') {
decimal.dot_position = pos;
} else {
decimal.num[ptr++] = R[i] - '0';
}
}
decimal.len = ptr;
return decimal;
}
void printBigDecimal(BigDecimal& decimal) {
char *str = new char[decimal.len+1];
for(int i = 0; i <= decimal.len; i++) {
str[i] = '0';
}
int ptr = 0;
for(int i = 0; i < decimal.len; i++) {
if(i == decimal.dot_position) str[ptr++] = '.';
str[ptr++] = decimal.num[i] + '0';
}
int first = 0;
int last = decimal.len;
while(first <= decimal.len && str[first] == '0') first++;
while(last >= 0 && str[last] == '0') last--;
if(str[first] == '.') first++;
if(first > last) printf("0\n");
else {
for(int i = last ; i >= first; i--) {
printf("%c", str[i]);
}
printf("\n");
}
delete[] str;
}
int main() {
char R[100];
int n;
BigDecimal ans;
while(scanf("%s%d", R, &n) != EOF) {
BigDecimal decimal = parseStrToBigDecimal(R);
BigDecimal ans = parseStrToBigDecimal("1");
for(int i = 0; i < n; i++) {
BigDecimal t = multiply(&decimal, &ans);
freeBigDecimal(ans);
ans = t;
}
printBigDecimal(ans);
freeBigDecimal(decimal);
freeBigDecimal(ans);
}
return 0;
}
<file_sep>#include <cstdio>
#include <vector>
using namespace std;
bool check(vector< vector<int> >& left,
vector< vector<int> >& right,
vector<char>& verdict,
vector<int>& weight) {
int n = left.size();
for(int i = 0; i < n; i++) {
int left_weight = 0, right_weight = 0;
int m = left[i].size();
for(int j = 0; j < m; j++) {
left_weight += weight[left[i][j]];
right_weight += weight[right[i][j]];
}
if((left_weight < right_weight && verdict[i] != '<')
|| (left_weight > right_weight && verdict[i] != '>')
|| (left_weight == right_weight && verdict[i] != '='))
return false;
}
return true;
}
int main() {
int N, K;
char s[2];
scanf("%d%d", &N, &K);
vector<int> weight(N+1, 1);
vector< vector<int> > left, right;
vector<char> verdict;
int p, a;
for(int i = 0; i < K; i++) {
scanf("%d", &p);
vector<int> cur_left, cur_right;
for(int j = 0; j < p; j++) {
scanf("%d", &a);
cur_left.push_back(a);
}
for(int j = 0; j < p; j++) {
scanf("%d", &a);
cur_right.push_back(a);
}
left.push_back(cur_left);
right.push_back(cur_right);
scanf("%s", s);
verdict.push_back(s[0]);
}
int ans = 0, ans_count = 0;
for(int i = 1; i <= N; i++) {
weight[i] = 0;
if(check(left, right, verdict, weight) && ans != i) {
ans = i;
ans_count ++;
}
weight[i] = 2;
if(check(left, right, verdict, weight) && ans != i) {
ans = i;
ans_count ++;
}
weight[i] = 1;
}
if(ans_count != 1) printf("0\n");
else printf("%d\n", ans);
return 0;
}
<file_sep>#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iterator>
#include <map>
#include <vector>
using namespace std;
double get_maximize_b_over_p(vector< vector<int> >& bandwidths, vector< vector<int> >& prices) {
map<int, int> devices[2];
for(int i = 0; i < bandwidths[0].size(); i++) {
devices[0][bandwidths[0][i]] = prices[0][i];
}
for(int i = 1; i < bandwidths.size(); i++) {
map<int, int>& c_device = devices[i%2];
map<int, int>& p_device = devices[(i-1)%2];
c_device.clear();
for(int j = 0; j < bandwidths[i].size(); j++) {
for(map<int,int>::iterator it = p_device.begin(); it != p_device.end(); ++it) {
int bandwidth = min(it->first, bandwidths[i][j]);
int price = it->second + prices[i][j];
map<int,int>::iterator c_it = c_device.find(bandwidth);
if(c_it == c_device.end()) {
c_device[bandwidth] = price;
} else {
c_it->second = min(c_it->second, price);
}
}
}
}
int n = bandwidths.size();
map<int,int>& c_device = devices[(n-1) % 2];
double res = 0;
for(map<int,int>::iterator it = c_device.begin(); it != c_device.end(); ++it) {
res = max(res, 1.0 * it->first / it->second);
}
return res;
}
int main() {
int t, n, m;
scanf("%d", &t);
while(t--) {
scanf("%d", &n);
vector< vector<int> > bandwidths, prices;
for(int i = 0; i < n; i++) {
scanf("%d", &m);
vector<int> bandwidth(m, 0), price(m, 0);
for(int j = 0; j < m; j++) {
scanf("%d%d", &bandwidth[j], &price[j]);
}
bandwidths.push_back(bandwidth);
prices.push_back(price);
}
double result = get_maximize_b_over_p(bandwidths, prices);
printf("%.3f\n", result);
}
return 0;
}
<file_sep>#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
using namespace std;
typedef long long ll;
vector<ll> counts;
string str;
void init() {
const int upper = 2147483647;
ll total_count = 0;
ll current_length = 0;
int current_number = 1;
str = "";
char buff[10];
while(total_count <= upper) {
sprintf(buff, "%d", current_number);
current_length = current_length + strlen(buff);
total_count += current_length;
current_number++;
counts.push_back(total_count);
str += buff;
}
}
int binary_search(ll n) {
int l = -1, r = counts.size() - 1;
while(r - l > 1) {
int m = (l+r) / 2;
if(counts[m] >= n) r = m;
else l = m;
}
return l;
}
int main() {
init();
int t, n;
scanf("%d", &t);
while(t--) {
scanf("%d", &n);
int base = binary_search(n);
printf("%c\n", base == -1 ? '1' : str[n - counts[base] - 1]);
}
return 0;
}
|
514ccf53ae286e6592103285faf3f90f6fb681c1
|
[
"C++"
] | 26 |
C++
|
llkpersonal/poj
|
a6837e8abd9c071464ba1125084566ebf17d8efe
|
6d41a74adadf3e15cf967f394ba0bca436e7e6a1
|
refs/heads/master
|
<file_sep>var fs = require('fs');
var axios = require('axios');
const sourceLanguage = 'en'
const targetLanguage = 'es'
const URL = 'https://translate.yandex.net/api/v1.5/tr.json/translate'
const API_KEY = '<KEY>'
var obj;
fs.readFile('./source/en.json', 'utf8', function (err, data) {
if (err) throw err;
obj = JSON.parse(data);
let parmas = new URLSearchParams();
Object.keys(obj).forEach(ele => {
parmas.append('text', obj[ele])
})
parmas.append("key", API_KEY)
parmas.append("lang",`${sourceLanguage}-${targetLanguage}`)
axios.get(URL, {
params: parmas,
})
.then(function (response) {
if (response.data.code === 200){
fs.writeFile(`./target/${targetLanguage}.json`, '{\n', function(err) {
if(err) {
return console.log(err);
}
});
const length = response.data.text.length;
for (let i = 0; i < length; i ++){
fs.appendFile(`./target/${targetLanguage}.json`, `\t"${Object.keys(obj)[i]}": "${response.data.text[i]}",\n`, function(err) {
if(err) {
return console.log(err);
}
});
}
setTimeout(() => {
fs.appendFile(`./target/${targetLanguage}.json`, `}`, function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
}, 3000)
}
})
.catch(function (error) {
console.log(error);
});
});
|
2031ff51c5c56bb68ab071df4af76f01b376687d
|
[
"JavaScript"
] | 1 |
JavaScript
|
vqthanh1412489/translate
|
7d2dce1388d13d14fa6286229415e8c32fa46f99
|
0985fd66536e44fc568c27371f89f2bb62111b93
|
refs/heads/master
|
<repo_name>alanrabelo/PersistingImages<file_sep>/README.md
# PersistingImages
Demo project working with the camera and persisting image data locally
<file_sep>/PersistingImages/ImagePlacement.swift
//
// ImageViews.swift
// PersistingImages
//
// Created by <NAME> on 3/29/17.
// Copyright © 2017 Dougly. All rights reserved.
//
import Foundation
enum ImagePlacement {
case topImage, middleImage, bottomImage
}
<file_sep>/PersistingImages/ViewController.swift
//
// ViewController.swift
// PersistingImages
//
// Created by <NAME> on 3/29/17.
// Copyright © 2017 Dougly. All rights reserved.
//
import UIKit
import CoreData
class ViewController: UIViewController {
var selectedImageTag = 0
let appDelegate = UIApplication.shared.delegate as! AppDelegate
@IBOutlet weak var topImageView: UIImageView!
@IBOutlet weak var middleImageView: UIImageView!
@IBOutlet weak var bottomImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
addTapGestures()
fetchData()
}
func addTapGestures() {
let tapGR0 = UITapGestureRecognizer(target: self, action: #selector(tappedImage))
topImageView.addGestureRecognizer(tapGR0)
topImageView.tag = 1
let tapGR1 = UITapGestureRecognizer(target: self, action: #selector(tappedImage))
middleImageView.addGestureRecognizer(tapGR1)
middleImageView.tag = 2
let tapGR2 = UITapGestureRecognizer(target: self, action: #selector(tappedImage))
bottomImageView.addGestureRecognizer(tapGR2)
bottomImageView.tag = 3
}
@IBAction func clearImagesCache(_ sender: Any) {
let fileManager = FileManager.default
let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
let documentPath = documentsURL.path
do {
let files = try fileManager.contentsOfDirectory(atPath: "\(documentPath)")
for file in files {
try fileManager.removeItem(atPath: "\(documentPath)/\(file)")
}
} catch {
print("could not clear cache")
}
}
}
extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func tappedImage(_ sender: UITapGestureRecognizer) {
// Make sure device has a camera
if UIImagePickerController.isSourceTypeAvailable(.camera) {
// Save tag of image view we selected
if let view = sender.view {
selectedImageTag = view.tag
}
// Setup and present default Camera View Controller
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .camera
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
// Dismiss the view controller a
picker.dismiss(animated: true, completion: nil)
// Get the picture we took
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
// Set the picture to be the image of the selected UIImageView
switch selectedImageTag {
case 1: topImageView.image = image
case 2: middleImageView.image = image
case 3: bottomImageView.image = image
default: break
}
// Save imageData to filePath
// Get access to shared instance of the file manager
let fileManager = FileManager.default
// Get the URL for the users home directory
let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
// Get the document URL as a string
let documentPath = documentsURL.path
// Create filePath URL by appending final path component (name of image)
let filePath = documentsURL.appendingPathComponent("\(String(selectedImageTag)).png")
// Check for existing image data
do {
// Look through array of files in documentDirectory
let files = try fileManager.contentsOfDirectory(atPath: "\(documentPath)")
for file in files {
// If we find existing image filePath delete it to make way for new imageData
if "\(documentPath)/\(file)" == filePath.path {
try fileManager.removeItem(atPath: filePath.path)
}
}
} catch {
print("Could not add image from document directory: \(error)")
}
// Create imageData and write to filePath
do {
if let pngImageData = UIImagePNGRepresentation(image) {
try pngImageData.write(to: filePath, options: .atomic)
}
} catch {
print("couldn't write image")
}
// Save filePath and imagePlacement to CoreData
let container = appDelegate.persistentContainer
let context = container.viewContext
let entity = Image(context: context)
entity.filePath = filePath.path
switch selectedImageTag {
case 1: entity.placement = "top"
case 2: entity.placement = "middle"
case 3: entity.placement = "bottom"
default:
break
}
appDelegate.saveContext()
}
func fetchData() {
// Set up fetch request
let container = appDelegate.persistentContainer
let context = container.viewContext
let fetchRequest = NSFetchRequest<Image>(entityName: "Image")
do {
// Retrive array of all image entities in core data
let images = try context.fetch(fetchRequest)
// For each image entity get the imageData from filepath and assign it to image view
for image in images {
if let placement = image.placement,
let filePath = image.filePath {
// Retrive image data from filepath and convert it to UIImage
if FileManager.default.fileExists(atPath: filePath) {
if let contentsOfFilePath = UIImage(contentsOfFile: filePath) {
switch placement {
case "top": topImageView.image = contentsOfFilePath
case "middle": middleImageView.image = contentsOfFilePath
case "bottom": bottomImageView.image = contentsOfFilePath
default: break
}
}
}
}
}
} catch {
print("entered catch for image fetch request")
}
}
}
|
75db73b845f915f3e6f224cffcda6f67a74014d8
|
[
"Markdown",
"Swift"
] | 3 |
Markdown
|
alanrabelo/PersistingImages
|
6595e7de355e2f54ca8b99cb1110230a80e9bb1d
|
851b959f8a5e2d35d69bb59f99d4f44e5c7bdcf4
|
refs/heads/master
|
<file_sep>import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { createExam } from '../../../../actions/exam';
import CreateExam from '../../../../components/AdminDashboard/Exams/CreateExam/CreateExam';
const mapStateToProps = state => ({
courses: state.courseState.courses,
});
const mapDispatchToProps = dispatch => bindActionCreators({
createExam,
}, dispatch);
export default connect(mapStateToProps, mapDispatchToProps)(CreateExam);
<file_sep>import { Record, List, Map } from 'immutable';
const ExamRecord = Record({
id: '',
name: '',
course: '',
duration: 0,
date: '',
type: 0,
registeredStudents: new Map(),
questions: new List(),
});
export default class Exam extends ExamRecord {
static fromObject(key, exam) {
return new this(exam).merge({
id: key,
registeredStudents: new Map(exam.registeredStudents || {}),
});
}
static loadExams(exams) {
const result = {};
Object.keys(exams).forEach((examKey) => {
result[examKey] = this.fromObject(examKey, exams[examKey]);
});
return result;
}
}
<file_sep>import { List } from 'immutable';
import Student from '../models/student';
const INITIAL_STATE = {
student: new Student(),
students: new List(),
};
function studentReducer(state = INITIAL_STATE, action) {
let studentIndex = -1;
let students;
let updatedStudent;
switch (action.type) {
case 'UPDATING_STUDENT':
if (action.key === 'enrolledCourses') {
updatedStudent = state.student.setEnrolledCourses(action.data);
} else if (action.key === 'exams') {
updatedStudent = state.student.setExams(action.data);
} else {
updatedStudent = state.student.set(action.key, action.data);
}
return Object.assign({}, state, { student: updatedStudent });
case 'UPDATING_STUDENTS':
studentIndex = state.students.findIndex(student => student.id === action.key);
if (studentIndex >= 0) {
students = state
.students
.set(studentIndex, Student.fromObject(action.key, action.item));
} else {
students = state.students.push(Student.fromObject(action.key, action.item));
}
return Object.assign({}, state, { students });
default:
return state;
}
}
export default studentReducer;
<file_sep>import { functions } from './firebase';
export const registerStudent = functions.httpsCallable('registerStudent');
export const registerExamStudent = functions.httpsCallable('registerExamStudent');
<file_sep>import { fork } from 'redux-saga/effects';
import { watchStudentSaga } from './student';
import { watchAuth } from './auth';
import { updatedItemSaga, watchItemSaga } from './database';
import { watchExamSaga } from './exam';
export default function* rootSaga() {
yield fork(watchStudentSaga);
yield fork(watchItemSaga);
yield fork(watchExamSaga);
yield fork(watchAuth);
yield fork(updatedItemSaga);
}
<file_sep>import { connect } from 'react-redux';
import Account from '../../components/Account/Account';
const mapStateToProps = state => ({
authUser: state.sessionState.authUser,
});
export default connect(mapStateToProps)(Account);
<file_sep>import React from 'react';
import * as routes from '../../constants/routes';
import Courses from '../../containers/AdminDashboard/Courses/Courses';
import Faculties from '../../containers/AdminDashboard/Faculties/Faculties';
import Students from '../../containers/AdminDashboard/Students/Students';
import Exams from '../../containers/AdminDashboard/Exams/Exams';
import Dashboard from '../Dashboard/Dashboard';
import { userIsAdmin } from '../../helpers/authHelpers';
const items = {
[routes.FACULTIES]: userIsAdmin(Faculties),
[routes.COURSES]: userIsAdmin(Courses),
[routes.EXAMS]: userIsAdmin(Exams),
[routes.STUDENTS]: userIsAdmin(Students),
};
const AdminDashboard = props => (
<Dashboard items={items} {...props} />
);
export default AdminDashboard;
<file_sep>import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { toggleRegisterStudentForExam } from '../../../actions/exam';
import Exams from '../../../components/AdminDashboard/Exams/Exams';
const mapStateToProps = state => ({
exams: state.examState.exams,
students: state.studentState.students,
});
const mapDispatchToProps = dispatch => bindActionCreators({
toggleRegisterStudentForExam,
}, dispatch);
export default connect(mapStateToProps, mapDispatchToProps)(Exams);
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
// import { Form } from 'semantic-ui-react';
import MultipleChoice from './MultipleChoice';
import Short from './Short';
import Code from './Code';
export default class Answer extends React.Component {
static propTypes = {
questionType: PropTypes.string.isRequired,
value: PropTypes.oneOfType([PropTypes.string, PropTypes.array]).isRequired,
correctAnswer: PropTypes.number.isRequired,
onChange: PropTypes.func.isRequired,
}
renderAnswerInput = (questionType, value, correctAnswer) => {
const { onChange } = this.props;
switch (questionType) {
case 0:
return (<MultipleChoice
onChange={onChange}
value={value}
correctAnswer={correctAnswer}
/>);
case 2:
return (<Short
onChange={onChange}
value={value}
/>);
case 3:
return (<Code
onChange={onChange}
value={value}
/>);
default:
return null;
}
}
render() {
const { questionType, value, correctAnswer } = this.props;
return (
this.renderAnswerInput(questionType, value, correctAnswer)
);
}
}
<file_sep>import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { enrollCourse } from '../../actions/student';
import Courses from '../../components/Student/Courses';
const mapStateToProps = () => {};
const mapDispatchToProps = dispatch => bindActionCreators({
enrollCourse,
}, dispatch);
export default connect(mapStateToProps, mapDispatchToProps)(Courses);
<file_sep>import * as firebase from 'firebase';
import 'firebase/functions';
const {
REACT_APP_FIREBASE_API_KEY,
REACT_APP_FIREBASE_AUTH_DOMAIN,
REACT_APP_FIREBASE_DATABASE_URL,
REACT_APP_FIREBASE_PROJECT_ID,
REACT_APP_FIREBASE_STORAGE_BUCKET,
REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
} = process.env;
const config = {
apiKey: REACT_APP_FIREBASE_API_KEY,
authDomain: REACT_APP_FIREBASE_AUTH_DOMAIN,
databaseURL: REACT_APP_FIREBASE_DATABASE_URL,
projectId: REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
};
firebase.initializeApp(config);
const auth = firebase.auth();
const db = firebase.database();
const functions = firebase.functions();
export {
db,
auth,
functions,
};
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import ReactRouterPropTypes from 'react-router-prop-types';
import { Grid } from 'semantic-ui-react';
import { Route } from 'react-router-dom';
import DashboardMenu from './DashboardMenu';
const Dashboard = (props) => {
const { items, match } = props;
const routes = Object.entries(items).map(([path, Component]) =>
(<Route key={path} exact path={`${match.path}/${path}`} component={() => <Component {...props} />} />));
return (
<Grid>
<Grid.Row>
<Grid.Column width={3}>
<DashboardMenu
menuItems={Object.keys(items)}
/>
</Grid.Column>
<Grid.Column width={11}>
{routes}
</Grid.Column>
</Grid.Row>
</Grid>
);
};
Dashboard.propTypes = {
match: ReactRouterPropTypes.match.isRequired,
items: PropTypes.shape({}).isRequired,
};
export default Dashboard;
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Container, Header, Grid } from 'semantic-ui-react';
import Countdown from 'react-countdown-now';
import ExamModel from '../../models/exam';
import Question from './Question';
export default class Exam extends React.Component {
static propTypes = {
// params: PropTypes.shape({
// examKey: PropTypes.string.isRequired,
// }).isRequired,
exam: PropTypes.instanceOf(ExamModel).isRequired,
}
constructor(props) {
super(props);
this.state = {
questionPos: 0,
answers: [],
};
this.submitAnswers = this.submitAnswers.bind(this);
this.nextQuestion = this.nextQuestion.bind(this);
}
submitAnswers(answer) {
const answers = [
...this.state.answers,
answer,
];
console.log(answers);
}
nextQuestion(answer) {
this.setState({
questionPos: this.state.questionPos + 1,
answers: [
...this.state.answers,
answer,
],
});
}
examtimer = ({
hours, minutes, seconds, completed,
}) => {
if (completed) {
return <span>Time is up!</span>;
}
return <span>{hours}:{minutes}:{seconds}</span>;
}
render() {
const { exam } = this.props;
const { questionPos } = this.state;
return (
<Container>
<Grid>
<Grid.Row>
<Grid.Column width={3}>
<Header as="h2">{exam.course}</Header>
<Countdown
date={Date.now() + (exam.duration * 3600000)}
renderer={this.examtimer}
/>
</Grid.Column>
<Grid.Column width={10}>
<Question
index={questionPos}
question={exam.questions[questionPos]}
onNextQuestion={this.nextQuestion}
onSubmit={this.submitAnswers}
last={(questionPos + 1) === exam.questions.length}
/>
</Grid.Column>
</Grid.Row>
</Grid>
</Container>
);
}
}
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Grid, Form, Button } from 'semantic-ui-react';
import EssayQuestion from './EssayQuestion';
export default class Question extends React.Component {
static propTypes = {
question: PropTypes.string.isRequired,
onNextQuestion: PropTypes.func.isRequired,
onSubmit: PropTypes.func.isRequired,
last: PropTypes.bool.isRequired,
}
constructor(props) {
super(props);
this.state = {
answer: '',
};
this.handleChange = this.handleChange.bind(this);
this.onSubmitAnswer = this.onSubmitAnswer.bind(this);
}
onSubmitAnswer() {
if (this.props.last) {
this.props.onSubmit(this.state.answer);
return;
}
this.props.onNextQuestion(this.state.answer);
this.setState({
answer: '',
});
}
handleChange(e, { name, value }) {
this.setState({ [name]: value });
}
render() {
const { question, last } = this.props;
const { answer } = this.state;
return (
<Grid centered>
<Grid.Row>
<Grid.Column width={10}>
<Form onSubmit={this.onSubmitAnswer}>
<EssayQuestion
question={question.question}
answer={answer}
handleChange={this.handleChange}
/>
<Button
size="huge"
primary
>{last ? 'Finish' : 'Next question'}
</Button>
</Form>
</Grid.Column>
</Grid.Row>
</Grid>
);
}
}
<file_sep>import { Record } from 'immutable';
const CourseRecord = Record({
id: '',
name: '',
code: '',
secretKey: '',
semester: 0,
year: 0,
});
export default class Course extends CourseRecord {
static fromObject(key, course) {
return new this(course).merge({
id: key,
});
}
static loadCourses(courses) {
const result = {};
Object.keys(courses).forEach((courseKey) => {
if (courseKey !== 'enrollmentKey') {
result[courseKey] = this.fromObject(courseKey, courses[courseKey]);
}
});
return result;
}
prepareForEnrollment() {
return {
name: this.name,
code: this.code,
semester: this.semester,
year: this.year,
};
}
}
<file_sep>import React from 'react';
// import PropTypes from 'prop-types';
import { Form } from 'semantic-ui-react';
const Short = () => (
<Form.Input
name="answer"
label="Answer"
// value={options[i]}
// onChange={this.setOption}
className="new-question-answer"
/>
);
export default Short;
<file_sep>import { List } from 'immutable';
import Faculty from '../models/faculty';
const INITIAL_STATE = {
faculties: new List(),
};
function facultyReducer(state = INITIAL_STATE, action) {
let facultyIndex = -1;
let faculties;
switch (action.type) {
case 'UPDATING_FACULTIES':
facultyIndex = state.faculties.findIndex(faculty => faculty.id === action.key);
if (facultyIndex >= 0) {
faculties = state
.faculties
.set(facultyIndex, Faculty.fromObject(action.key, action.item));
} else {
faculties = state.faculties.push(Faculty.fromObject(action.key, action.item));
}
return Object.assign({}, state, { faculties });
default:
return state;
}
}
export default facultyReducer;
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Field, propTypes } from 'redux-form';
import { List as ImmutableList } from 'immutable';
import { List, Form, Button } from 'semantic-ui-react';
const DropdownField = props =>
(
<Form.Dropdown
disabled={props.disabled}
selection
options={props.options}
{...props.input}
value={props.input.value}
onChange={(param, data) => props.input.onChange(data.value)}
placeholder={props.label}
/>
);
DropdownField.propTypes = {
...propTypes,
};
const EditCourses = (props) => {
const { courses, courseIds, handleSubmit } = props;
const addedCourses = courses.filter(course => courseIds.contains(course.id));
const courseOptions = courses.reduce((result, course) => {
if (!courseIds.contains(course.id)) {
return [
...result,
{ key: course.id, value: course.id, text: course.name },
];
}
return result;
}, []);
return (
<div>
<List divided relaxed size="large">
{addedCourses.map(course => (
<List.Item>
<List.Icon name="graduation" />
<List.Content>{course.name} ({course.code})</List.Content>
</List.Item>
))}
</List>
<Form onSubmit={handleSubmit}>
<Form.Group>
<Field
component={DropdownField}
name="course"
label="Add a new course"
options={courseOptions}
disabled={courseOptions.length === 0}
/>
<Button type="submit" positive icon="add" disabled={courseOptions.length === 0} />
</Form.Group>
</Form>
</div>
);
};
EditCourses.propTypes = {
courseIds: PropTypes.instanceOf(ImmutableList).isRequired,
courses: PropTypes.instanceOf(ImmutableList).isRequired,
handleSubmit: PropTypes.func.isRequired,
};
export default EditCourses;
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Modal, Button, Form, Table } from 'semantic-ui-react';
import { List } from 'immutable';
import EditCourses from '../../../containers/AdminDashboard/Faculties/EditCourses';
export default class Faculties extends React.Component {
static propTypes = {
createFaculty: PropTypes.func.isRequired,
faculties: PropTypes.instanceOf(List).isRequired,
}
constructor(props) {
super(props);
this.state = {
name: '',
shortName: '',
};
this.handleChange = this.handleChange.bind(this);
this.saveFaculty = this.saveFaculty.bind(this);
this.newFacultyForm = this.newFacultyForm.bind(this);
}
handleChange(e, { name, value }) {
this.setState({ [name]: value });
}
saveFaculty() {
const { name, shortName } = this.state;
this.props.createFaculty({ name, shortName });
}
newFacultyForm(name, shortName) {
return (
<Form onSubmit={this.saveFaculty}>
<Form.Input placeholder="Computer Science and Engineering" name="name" value={name} onChange={this.handleChange} />
<Form.Input placeholder="CSE" name="shortName" value={shortName} onChange={this.handleChange} />
<Button positive type="submit">Create</Button>
</Form>
);
}
showEditCoursesModal = faculty =>
(
<Modal trigger={<Button basic icon="edit" color="green" />} closeIcon>
<Modal.Header>Editing courses for faculty: {faculty.shortName}</Modal.Header>
<Modal.Content>
<EditCourses
facultyId={faculty.id}
courseIds={faculty.courseIds}
/>
</Modal.Content>
<Modal.Actions>
<Button primary>
Save
</Button>
</Modal.Actions>
</Modal>
);
render() {
const { faculties } = this.props;
const { name, shortName } = this.state;
return (
<div>
<Table celled padded>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Name</Table.HeaderCell>
<Table.HeaderCell>Short Name</Table.HeaderCell>
<Table.HeaderCell>Courses</Table.HeaderCell>
<Table.HeaderCell>Lecturers</Table.HeaderCell>
<Table.HeaderCell>Students</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{faculties.map(faculty =>
(
<Table.Row key={faculty.id}>
<Table.Cell>{faculty.name}</Table.Cell>
<Table.Cell>{faculty.shortName}</Table.Cell>
<Table.Cell>
{faculty.courseIds.size} {this.showEditCoursesModal(faculty)}
</Table.Cell>
<Table.Cell>
0 <Button basic icon="edit" color="green" />
</Table.Cell>
<Table.Cell>
0 <Button basic icon="edit" color="green" />
</Table.Cell>
</Table.Row>
))}
</Table.Body>
</Table>
{ this.newFacultyForm(name, shortName) }
</div>
);
}
}
<file_sep>import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import { compose } from 'recompose';
import Navigation from '../../components/Main/Navigation';
const mapStateToProps = state => ({
session: state.sessionState,
});
export default compose(
connect(mapStateToProps),
withRouter,
)(Navigation);
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Form, Button } from 'semantic-ui-react';
import { getCourseBySecretKey } from '../../firebase/db';
export default class Account extends React.Component {
static propTypes = {
authUser: PropTypes.shape({
email: PropTypes.string.isRequired,
}).isRequired,
}
constructor(props) {
super(props);
this.state = {
enrollmentKey: '',
};
this.handleChange = this.handleChange.bind(this);
this.enrollCourse = this.enrollCourse.bind(this);
}
handleChange(e, { name, value }) {
this.setState({ [name]: value });
}
enrollCourse() {
getCourseBySecretKey(this.state.enrollmentKey);
}
render() {
const { enrollmentKey } = this.state;
return (
<div>
<h1>Account: {this.props.authUser.email}</h1>
<Form onSubmit={this.enrollCourse}>
<Form.Input
label="Enrollment key"
name="enrollmentKey"
value={enrollmentKey}
type="password"
width={4}
onChange={this.handleChange}
/>
<Button>Enroll</Button>
</Form>
</div>
);
}
}
<file_sep>import { Map } from 'immutable';
import Exam from '../models/exam';
const INITIAL_STATE = {
exams: new Map(),
};
function examReducer(state = INITIAL_STATE, action) {
switch (action.type) {
case 'UPDATING_EXAMS':
return Object.assign(
{},
state,
{
exams: state.exams.set(action.key, Exam.fromObject(action.key, action.item)),
},
);
default:
return state;
}
}
export default examReducer;
<file_sep>import { List } from 'immutable';
import Course from '../models/course';
const INITIAL_STATE = {
courses: new List(),
};
function courseReducer(state = INITIAL_STATE, action) {
switch (action.type) {
case 'UPDATING_COURSES':
return Object.assign(
{},
state,
{ courses: state.courses.push(Course.fromObject(action.key, action.item)) },
);
default:
return state;
}
}
export default courseReducer;
<file_sep>export function enrollCourse(enrollmentKey, studentId) {
return {
type: 'ENROLLING_STUDENT_COURSE',
payload: { enrollmentKey, studentId },
};
}
export function updateStudent(id, fields) {
return {
type: 'UPDATING_STUDENT',
payload: { id, fields },
};
}
<file_sep>import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { reduxForm } from 'redux-form';
import EditCourses from '../../../components/AdminDashboard/Faculties/EditCourses';
import { updateFaculty } from '../../../actions/faculty';
const mapStateToProps = state => ({
courses: state.courseState.courses,
});
const mapDispatchToProps = dispatch => bindActionCreators({
updateFaculty,
}, dispatch);
const onSubmit = (values, dispatch, props) => {
props
.updateFaculty(
props.facultyId,
{ courseIds: props.courseIds.push(values.course).toArray() },
);
};
const Form = reduxForm({
form: 'editCoursesForm',
onSubmit,
})(EditCourses);
export default connect(mapStateToProps, mapDispatchToProps)(Form);
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import MonacoEditor from 'react-monaco-editor';
export default class Editor extends React.Component {
static propTypes = {
name: PropTypes.string.isRequired,
onChange: PropTypes.func,
width: PropTypes.string,
height: PropTypes.string,
language: PropTypes.string,
theme: PropTypes.string,
value: PropTypes.string,
}
static defaultProps = {
onChange: null,
width: '800',
height: '600',
language: 'javascript',
theme: 'vs',
value: null,
}
onChange = (newValue, e) => {
const { name } = this.props;
if (this.props.onChange) {
this.props.onChange(e, { name, value: newValue });
}
}
editorDidMount = (editor /* , monaco */) => {
console.log('editorDidMount', editor);
editor.focus();
}
render() {
const {
width,
height,
language,
theme,
value,
} = this.props;
const options = {
selectOnLineNumbers: true,
};
return (
<MonacoEditor
width={width}
height={height}
language={language}
theme={theme}
value={value}
options={options}
onChange={this.onChange}
editorDidMount={this.editorDidMount}
/>
);
}
}
<file_sep>import React from 'react';
import { Container, Form, Button } from 'semantic-ui-react';
const TakeExam = () => (
<Container>
<Form>
<Form.Input
name="secretKey"
label="Exam secret key"
/>
<Button type="button" positive>Load exam</Button>
</Form>
</Container>
);
export default TakeExam;
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Form, Button, Table } from 'semantic-ui-react';
import { List } from 'immutable';
export default class Students extends React.Component {
static propTypes = {
students: PropTypes.instanceOf(List).isRequired,
createStudent: PropTypes.func.isRequired,
}
constructor(props) {
super(props);
this.state = {
fullName: '',
emailAddress: '',
faculty: '',
indexNumber: 0,
};
this.handleChange = this.handleChange.bind(this);
this.saveStudent = this.saveStudent.bind(this);
this.newStudentForm = this.newStudentForm.bind(this);
}
handleChange(e, { name, value }) {
this.setState({ [name]: value });
}
saveStudent() {
const {
fullName,
emailAddress,
faculty,
indexNumber,
} = this.state;
this.props.createStudent({
fullName,
emailAddress,
faculty,
indexNumber,
});
}
newStudentForm(fullName, emailAddress, faculty, indexNumber) {
return (
<Form onSubmit={this.saveStudent}>
<Form.Input label="Full Name" name="fullName" value={fullName} onChange={this.handleChange} />
<Form.Input label="E-mail Address" name="emailAddress" value={emailAddress} onChange={this.handleChange} />
<Form.Input label="Faculty" name="faculty" value={faculty} onChange={this.handleChange} />
<Form.Input label="Index number" name="indexNumber" value={indexNumber} onChange={this.handleChange} />
<Button positive type="submit">Create</Button>
</Form>
);
}
render() {
const {
fullName,
emailAddress,
faculty,
indexNumber,
} = this.state;
const { students } = this.props;
return (
<div>
<Table celled padded>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Full Name</Table.HeaderCell>
<Table.HeaderCell>E-mail Address</Table.HeaderCell>
<Table.HeaderCell>Faculty</Table.HeaderCell>
<Table.HeaderCell>Index number</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{students.map(student =>
(
<Table.Row key={student.id}>
<Table.Cell>{student.fullName}</Table.Cell>
<Table.Cell>{student.emailAddress}</Table.Cell>
<Table.Cell>{student.faculty}</Table.Cell>
<Table.Cell>{student.indexNumber}</Table.Cell>
</Table.Row>
))}
</Table.Body>
</Table>
{ this.newStudentForm(fullName, emailAddress, faculty, indexNumber) }
</div>
);
}
}
<file_sep>export function onFetchFaculties(faculties) {
return {
type: 'LOADING_FACULTIES',
faculties,
};
}
export function createFaculty(item) {
return {
type: 'CREATING_ITEM',
payload: { item, table: 'faculties' },
};
}
export function updateFaculty(id, fields) {
return {
type: 'UPDATING_ITEM',
payload: { id, fields, table: 'faculties' },
};
}
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { List, Checkbox } from 'semantic-ui-react';
import { List as ImmutableList } from 'immutable';
export default class RegisterStudents extends React.Component {
static propTypes = {
examId: PropTypes.string.isRequired,
students: PropTypes.instanceOf(ImmutableList).isRequired,
toggleRegisterStudentForExam: PropTypes.func.isRequired,
}
toggleRegisterStudent(studentId) {
const { examId, toggleRegisterStudentForExam } = this.props;
return (event, { checked }) => {
toggleRegisterStudentForExam(examId, studentId, checked);
};
}
render() {
const { students, examId } = this.props;
return (
<List divided>
{students.map(student => (
<List.Item key={student.id}>
<List.Content floated="left">{student.fullName} ({student.indexNumber})</List.Content>
<List.Content floated="right">
<Checkbox
toggle
onChange={this.toggleRegisterStudent(student.id)}
checked={student.isRegisteredExam(examId)}
/>
</List.Content>
</List.Item>
))}
</List>
);
}
}
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Form, Button, Grid, Header, Divider } from 'semantic-ui-react';
import { List } from 'immutable';
import format from 'date-fns/format';
import DayPicker from 'react-day-picker';
import 'react-day-picker/lib/style.css';
import {
examTypes,
questionTypes,
examDurations,
} from '../../../../constants/examConstants';
import Answer from './Answer/Answer';
class CreateExam extends React.Component {
static propTypes = {
courses: PropTypes.instanceOf(List).isRequired,
createExam: PropTypes.func.isRequired,
setExamFormRef: PropTypes.func.isRequired,
}
constructor(props) {
super(props);
this.state = {
name: '',
type: '',
date: '',
course: '',
duration: '',
questions: [
{
type: '',
question: '',
answer: '',
points: '',
},
],
};
this.handleChange = this.handleChange.bind(this);
this.onAddQuestion = this.onAddQuestion.bind(this);
this.onSaveExam = this.onSaveExam.bind(this);
this.handleDaySelection = this.handleDaySelection.bind(this);
}
onQuestionChange(index) {
return (e, { name, value }) => {
let update = {};
if (name === 'type') {
update = {
[name]: value,
answer: this.createAnswerStructure(value),
};
} else {
update = {
[name]: value,
};
}
this.setState({
questions: [
...this.state.questions.slice(0, index),
{
...this.state.questions[index],
...update,
},
...this.state.questions.slice(index + 1),
],
});
};
}
onAddQuestion() {
this.setState({
questions: [
...this.state.questions,
{
question: '',
answer: '',
correctAnswer: 1,
points: '',
},
],
});
}
onRemoveQuestion(index) {
return () => {
this.setState({
questions: [
...this.state.questions.slice(0, index),
...this.state.questions.slice(index + 1),
],
});
};
}
onSaveExam() {
this.props.createExam({
...this.state,
date: format(this.state.date, 'YYYY/MM/DD'),
});
}
createAnswerStructure = (questionType) => {
switch (questionType) {
case 0:
return [''];
case 2:
return '';
case 3:
return {
input: '// Input',
output: '// Output',
};
default:
return null;
}
}
handleChange(e, { name, value }) {
this.setState({ [name]: value });
if (name === 'course') {
const course = this.props.courses.find(c => c.id === value);
this.setState({ name: course.name });
}
}
handleDaySelection(date) {
this.setState({ date });
}
render() {
const { setExamFormRef } = this.props;
const courseOptions
= this.props.courses
.toArray()
.map(course => ({ key: course.id, value: course.id, text: course.name }));
const {
date,
duration,
course,
type,
questions,
} = this.state;
return (
<Form onSubmit={this.onSaveExam} ref={setExamFormRef}>
<Grid>
<Grid.Row>
<Grid.Column width={4}>
<DayPicker
onDayClick={this.handleDaySelection}
selectedDays={date}
/>
<Form.Dropdown
name="duration"
value={duration}
selection
placeholder="Exam duration"
options={examDurations}
onChange={this.handleChange}
/>
</Grid.Column>
<Grid.Column width={12}>
<Grid>
<Grid.Row>
<Grid.Column width={6}>
<Form.Dropdown
name="course"
value={course}
search
selection
placeholder="Choose course"
options={courseOptions}
onChange={this.handleChange}
/>
</Grid.Column>
<Grid.Column width={6}>
<Form.Dropdown
name="type"
value={type}
selection
placeholder="Type"
options={examTypes}
onChange={this.handleChange}
/>
</Grid.Column>
</Grid.Row>
<Divider />
{questions.map((question, index) => (
<React.Fragment>
<Grid.Row>
<Grid.Column width={3}>
<Header className="new-question-heading" as="h3">Question {index + 1}</Header>
</Grid.Column>
<Grid.Column width={10}>
<Form.Select
name="type"
value={question.type}
options={questionTypes}
placeholder="Question type"
width={4}
onChange={this.onQuestionChange(index)}
/>
</Grid.Column>
<Grid.Column width={2}>
<Button
floated="right"
negative
icon="minus"
onClick={this.onRemoveQuestion(index)}
disabled={questions.length === 1}
/>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column width={16}>
<Form.Group>
<Form.TextArea
name="question"
value={question.question}
rows={3}
label="Question text"
placeholder="What is a bit?"
onChange={this.onQuestionChange(index)}
width={11}
/>
<Form.Input
name="points"
value={question.points}
label="Points"
placeholder="10"
width={4}
onChange={this.onQuestionChange(index)}
/>
</Form.Group>
</Grid.Column>
<Grid.Column width={16}>
<Answer
questionType={question.type}
value={question.answer}
correctAnswer={question.correctAnswer}
onChange={this.onQuestionChange(index)}
/>
</Grid.Column>
</Grid.Row>
<Divider />
</React.Fragment>
))}
</Grid>
<Button className="new-question-button" type="button" positive icon="add" onClick={this.onAddQuestion} />
</Grid.Column>
</Grid.Row>
</Grid>
</Form>
);
}
}
export default CreateExam;
<file_sep>import { eventChannel } from 'redux-saga';
function databaseCreatedEventChannel(dbRef) {
const listener = eventChannel((emit) => {
dbRef
.on(
'child_added',
data => emit({ key: data.key, item: data.val() }),
);
return () => dbRef.off(listener);
});
return listener;
}
function databaseUpdatedEventChannel(dbRef) {
const listener = eventChannel((emit) => {
dbRef
.on(
'child_changed',
data => emit({ key: data.key, item: data.val() }),
);
return () => dbRef.off(listener);
});
return listener;
}
function createDatabaseChannels(dbRef) {
return {
createChannel: databaseCreatedEventChannel(dbRef),
updateChannel: databaseUpdatedEventChannel(dbRef),
};
}
function authenticationChannel(auth) {
const listener = eventChannel(emit => auth.onAuthStateChanged((authUser) => {
emit({ authUser });
}));
return listener;
}
export {
databaseCreatedEventChannel,
databaseUpdatedEventChannel,
createDatabaseChannels,
authenticationChannel,
};
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Grid } from 'semantic-ui-react';
import Editor from '../../../../CodeChallenge/Editor';
export default class Code extends React.Component {
static propTypes = {
value: PropTypes.shape({
input: PropTypes.string.isRequired,
output: PropTypes.string.isRequired,
}).isRequired,
onChange: PropTypes.func.isRequired,
}
onChange(valueObj) {
return (e, { name, value }) => {
const result = {
...valueObj,
[name]: value,
};
this.props.onChange(e, { name: 'answer', value: result });
};
}
render() {
const { value } = this.props;
return (
<div className="new-question-answer">
<Grid>
<Grid.Row>
<Grid.Column width={7}>
<Editor
name="input"
value={value.input}
width="300"
height="100"
onChange={this.onChange(value)}
/>
</Grid.Column>
<Grid.Column width={7}>
<Editor
name="output"
value={value.output}
width="300"
height="100"
onChange={this.onChange(value)}
/>
</Grid.Column>
</Grid.Row>
</Grid>
</div>
);
}
}
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Grid, Form, Radio, Button } from 'semantic-ui-react';
export default class ChoiceQuestion extends React.Component {
static propTypes = {
question: PropTypes.string.isRequired,
choices: PropTypes.arrayOf({
label: PropTypes.string.isRequired,
value: PropTypes.number.isRequired,
}).isRequired,
}
constructor(props) {
super(props);
this.state = {
answer: null,
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(e, { name, value }) {
this.setState({ [name]: value });
}
render() {
const { question, choices } = this.props;
const { answer } = this.state;
return (
<Grid centered>
<Grid.Row>
<Grid.Column width={10}>
<Form>
<Form.Group>
{question}
{choices
.map(choice => (<Form.Field
name="answer"
control={Radio}
label={choice.label}
value={choice.value}
checked={answer === choice.value}
onChange={this.handleChange}
/>))}
</Form.Group>
<Button size="huge" primary>Next question</Button>
</Form>
</Grid.Column>
</Grid.Row>
</Grid>
);
}
}
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Button, Table, Modal, Icon } from 'semantic-ui-react';
import { Map, List } from 'immutable';
import CreateExam from '../../../containers/AdminDashboard/Exams/CreateExam/CreateExam';
import RegisterStudents from './RegisterStudents';
export default class Exams extends React.Component {
static propTypes = {
exams: PropTypes.instanceOf(Map).isRequired,
students: PropTypes.instanceOf(List).isRequired,
toggleRegisterStudentForExam: PropTypes.func.isRequired,
}
constructor(props) {
super(props);
this.state = {
modalOpen: false,
};
this.setExamFormRef = this.setExamFormRef.bind(this);
this.toggleModal = this.toggleModal.bind(this);
this.newExam = this.newExam.bind(this);
this.saveExam = this.saveExam.bind(this);
}
setExamFormRef(form) {
this.examFormRef = form;
}
toggleModal() {
this.setState({
modalOpen: !this.state.modalOpen,
});
}
saveExam() {
this.examFormRef.handleSubmit();
this.toggleModal();
}
newExam() {
const { modalOpen } = this.state;
return (
<Modal
open={modalOpen}
size="fullscreen"
trigger={<Button onClick={this.toggleModal}>New</Button>}
closeIcon
closeOnEscape={false}
closeOnDocumentClick={false}
onClose={this.toggleModal}
>
<Modal.Header>Creating a new exam</Modal.Header>
<Modal.Content scrolling>
<CreateExam
setExamFormRef={this.setExamFormRef}
/>
</Modal.Content>
<Modal.Actions>
<Button
submit
primary
onClick={this.saveExam}
>
Create <Icon name="right chevron" />
</Button>
</Modal.Actions>
</Modal>
);
}
registerStudents(exam) {
const eligibleStudents = this.props.students
.filter(student => student.isEnrolledCourse(exam.course));
const { toggleRegisterStudentForExam } = this.props;
return (
<Modal trigger={<Button basic icon="edit" color="green" />} closeIcon>
<Modal.Header>Registered students for {exam.name}</Modal.Header>
<Modal.Content>
<RegisterStudents
examId={exam.id}
students={eligibleStudents}
toggleRegisterStudentForExam={toggleRegisterStudentForExam}
/>
</Modal.Content>
<Modal.Actions>
<Button primary>
Save
</Button>
</Modal.Actions>
</Modal>
);
}
render() {
const { exams } = this.props;
return (
<React.Fragment>
<Table celled padded>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Exam</Table.HeaderCell>
<Table.HeaderCell>Date</Table.HeaderCell>
<Table.HeaderCell>Duration</Table.HeaderCell>
<Table.HeaderCell>Questions</Table.HeaderCell>
<Table.HeaderCell>Students</Table.HeaderCell>
<Table.HeaderCell>Preview</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{exams.valueSeq().map(exam =>
(
<Table.Row key={exam.id}>
<Table.Cell>{exam.name}</Table.Cell>
<Table.Cell>{exam.date}</Table.Cell>
<Table.Cell>{exam.duration}</Table.Cell>
<Table.Cell>{exam.questions.length}</Table.Cell>
<Table.Cell>
{ this.registerStudents(exam) }
</Table.Cell>
<Table.Cell>
<Button basic icon="eye" />
</Table.Cell>
</Table.Row>
))}
</Table.Body>
</Table>
{ this.newExam() }
</React.Fragment>
);
}
}
<file_sep># EXAMS
A student management and exam administration system built for a school-project. The back-end is Firebase + Google Cloud Functions based, whereas for the frontend I am using React, Redux (with Redux-Saga to handle async actions) and Immutable.js
The ESLint [config](https://github.com/airbnb/javascript/tree/master/packages/eslint-config-airbnb) is based on Airbnb's [style guide](https://github.com/airbnb/javascript).
## SSR
Under consideration
*Note: This is WIP (Work in Progress)*<file_sep>import React from 'react';
import ReactRouterPropTypes from 'react-router-prop-types';
import { Menu } from 'semantic-ui-react';
import { withRouter } from 'react-router-dom';
import * as routes from '../../constants/routes';
class DashboardMenu extends React.Component {
static propTypes = {
history: ReactRouterPropTypes.history.isRequired,
match: ReactRouterPropTypes.match.isRequired,
}
constructor(props) {
super(props);
this.onItemClick.bind(this);
}
state = { activeItem: 'home' };
onItemClick(path) {
return (e, { name }) => {
this.setState({ activeItem: name });
this.props.history.push(`${this.props.match.path}/${path}`);
};
}
render() {
const { activeItem } = this.state;
return (
<Menu
fixed
vertical
pointing
secondary
>
<Menu.Item name="users" active={activeItem === 'users'} onClick={this.onItemClick()} />
<Menu.Item name="faculties" active={activeItem === 'faculties'} onClick={this.onItemClick(routes.FACULTIES)} />
<Menu.Item name="courses" active={activeItem === 'courses'} onClick={this.onItemClick(routes.COURSES)} />
<Menu.Item name="exams" active={activeItem === 'exams'} onClick={this.onItemClick(routes.EXAMS)} />
</Menu>
);
}
}
export default withRouter(DashboardMenu);
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Table } from 'semantic-ui-react';
import Student from '../../models/student';
export default class Exams extends React.Component {
static propTypes = {
student: PropTypes.instanceOf(Student).isRequired,
}
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e, { name, value }) {
this.setState({ [name]: value });
}
render() {
const { student } = this.props;
return (
<React.Fragment>
<Table celled padded>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Exam</Table.HeaderCell>
<Table.HeaderCell>Type</Table.HeaderCell>
<Table.HeaderCell>Date</Table.HeaderCell>
<Table.HeaderCell>Duration</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{student.exams.valueSeq().map(exam =>
(
<Table.Row key={exam.id}>
<Table.Cell>{exam.name}</Table.Cell>
<Table.Cell>{exam.type}</Table.Cell>
<Table.Cell>{exam.date}</Table.Cell>
<Table.Cell>{exam.duration}</Table.Cell>
</Table.Row>
))}
</Table.Body>
</Table>
</React.Fragment>
);
}
}
<file_sep>export const SIGN_UP = '/signup';
export const SIGN_IN = '/signin';
export const LANDING = '/';
export const HOME = '/home';
export const ACCOUNT = '/account';
export const PASSWORD_FORGET = '/forgotten-password';
export const EXAM = '/exam';
export const DASHBOARD = '/dashboard';
export const PROFILE = 'profile';
export const FACULTIES = 'faculties';
export const COURSES = 'courses';
export const STUDENTS = 'students';
export const EXAMS = 'exams';
<file_sep>import React from 'react';
import * as routes from '../../constants/routes';
import { userIsAuthenticated } from '../../helpers/authHelpers';
import Courses from '../../containers/Student/Courses';
import Dashboard from '../Dashboard/Dashboard';
import Exams from './Exams';
const items = {
[routes.COURSES]: userIsAuthenticated(Courses),
[routes.EXAMS]: userIsAuthenticated(Exams),
};
const StudentDashboard = props => (
<Dashboard items={items} {...props} />
);
export default StudentDashboard;
<file_sep>import { call, takeLatest } from 'redux-saga/effects';
import { registerExamStudent } from '../firebase/functions';
export function* registerStudentForExam(action) {
const { examId, studentId, toggle } = action.payload;
try {
yield call(registerExamStudent, { examId, studentId, toggle });
} catch (e) {
// do nothing
}
}
export function* watchExamSaga() {
yield takeLatest('REGISTERING_STUDENT_FOR_EXAM', registerStudentForExam);
}
<file_sep>import { Record, List } from 'immutable';
const FacultyRecord = Record({
id: '',
name: '',
shortName: '',
courseIds: new List(),
});
export default class Faculty extends FacultyRecord {
static fromObject(key, faculty) {
return new this(faculty).merge({
id: key,
courseIds: new List(faculty.courseIds || []),
});
}
}
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Form, Button } from 'semantic-ui-react';
import { Field, reduxForm } from 'redux-form';
import generator from 'generate-password';
const generateSecretKey = () => generator.generate({
length: 14,
numbers: true,
uppercase: true,
});
class NewCourse extends React.Component {
static propTypes = {
reset: PropTypes.func.isRequired,
handleSubmit: PropTypes.func.isRequired,
onSubmit: PropTypes.func.isRequired,
change: PropTypes.func.isRequired,
}
constructor(props) {
super(props);
this.onSubmit = this.onSubmit.bind(this);
}
onSubmit(values) {
this.props.onSubmit(values);
this.props.reset();
this.props.change('secretKey', generateSecretKey());
}
render() {
return (
<Form onSubmit={this.props.handleSubmit(this.onSubmit)}>
<Field
component={Form.Input}
label="Course name"
placeholder="Mathematics 1"
name="name"
/>
<Field
component={Form.Input}
label="Code name"
placeholder="MAT001"
name="code"
/>
<Field
component={Form.Input}
label="Semester"
placeholder="Winter"
name="semester"
/>
<Field
component={Form.Input}
label="Study year"
placeholder="2018"
name="year"
/>
<Field
component={Form.Input}
label="Enrollment key"
placeholder="Input a secret key here"
name="secretKey"
/>
<Button positive type="submit">Create</Button>
</Form>
);
}
}
export default reduxForm({
form: 'newCourse',
initialValues: {
secretKey: generateSecretKey(),
},
})(NewCourse);
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import ReactRouterPropTypes from 'react-router-prop-types';
import { Menu } from 'semantic-ui-react';
import { withRouter } from 'react-router-dom';
class DashboardMenu extends React.Component {
static propTypes = {
history: ReactRouterPropTypes.history.isRequired,
match: ReactRouterPropTypes.match.isRequired,
menuItems: PropTypes.arrayOf(PropTypes.string).isRequired,
}
constructor(props) {
super(props);
this.onItemClick.bind(this);
}
state = { activeItem: 'home' };
onItemClick(path) {
return (e, { name }) => {
this.setState({ activeItem: name });
this.props.history.push(`${this.props.match.path}/${path}`);
};
}
render() {
const { activeItem } = this.state;
const { menuItems } = this.props;
return (
<Menu
vertical
pointing
secondary
>
{
menuItems.map(path =>
(<Menu.Item
key={path}
name={path}
active={activeItem === path}
onClick={this.onItemClick(path)}
/>))
}
</Menu>
);
}
}
export default withRouter(DashboardMenu);
<file_sep>import { Record, Map } from 'immutable';
import Course from './course';
import Exam from './exam';
const StudentRecord = Record({
id: null,
emailAddress: '',
faculty: '',
fullName: '',
indexNumber: 0,
exams: new Map(),
enrolledCourses: new Map(),
});
export default class Student extends StudentRecord {
static fromObject(key, student) {
const enrolledCourses = Course.loadCourses(student.enrolledCourses || {});
const exams = Exam.loadExams(student.exams || {});
return new this(student).merge({
id: key,
enrolledCourses: new Map(enrolledCourses),
exams: new Map(exams),
});
}
isEnrolledCourse(courseId) {
return this.enrolledCourses.has(courseId);
}
isRegisteredExam(examId) {
return this.exams.has(examId);
}
setEnrolledCourses(data) {
const enrolledCourses = new Map(Course.loadCourses(data || {}));
return this.set('enrolledCourses', enrolledCourses);
}
setExams(data) {
const exams = new Map(Exam.loadExams(data || {}));
return this.set('exams', exams);
}
}
|
85f887710d450acacdcc781c42037b265fb5bab3
|
[
"JavaScript",
"Markdown"
] | 45 |
JavaScript
|
xha-75/exams
|
bd99792ca1736375731f000e4a325cca884ff789
|
2b17d0772f616e49a3219318e5b3c2536b94bc39
|
refs/heads/master
|
<repo_name>lukyrys/Zimbra<file_sep>/ImapSync
#!/bin/bash
##############################
#DADOS DO SERVIDOR E USUARIO##
##############################
SERVIDOR_ORIGEM='IP_ORIGEM'
#ADMIN_ORIGEM='<EMAIL>'
#PASSWORDADMIN_ORIGEM='<PASSWORD>'
USUARIO_ORIGEM='E-MAIL_ORIGEM'
PASSWORD_ORIGEM='<PASSWORD>'
SERVIDOR_DESTINO='IP_DESTINO'
#ADMIN_DESTINO='<EMAIL>'
#PASSWORDADMIN_DESTINO='SENHA_<PASSWORD>'
USUARIO_DESTINO='E-MAIL_DESTINO'
PASSWORD_DESTINO='<PASSWORD>'
########################################
##MIGRAR USUARIO POR USUARIO COM SENHA##
########################################
#imapsync --nosyncacls --subscribe --syncinternaldates --host1 $SERVIDOR_ORIGEM --user1 $USUARIO_ORIGEM --password1 $<PASSWORD> --host2 $SERVIDOR_DESTINO --user2 $USUARIO_DESTINO --password2 $<PASSWORD> --noauthmd5
# GMAIL
imapsync --addheader --host1 $SERVIDOR_ORIGEM --ssl1 --user1 "$USUARIO_ORIGEM" --password1 "$<PASSWORD>" --host2 $SERVIDOR_DESTINO --ssl2 --user2 "$USUARIO_DESTINO" --password2 "$<PASSWORD>" --noauthmd5 --maxbytespersecond 10000 --automap --exclude "\[Gmail\]$"
#Desativar segurança para GMAIL
#https://www.google.com/settings/security/lesssecureapps?pli=1
########################################
##MIGRAR USUARIO POR USUARIO SEM SENHA##
########################################
#imapsync --nosyncacls --subscribe --syncinternaldates --host1 $SERVIDOR_ORIGEM --user1 $USUARIO_ORIGEM --authuser1 $ADMIN_ORIGEM --password1 $<PASSWORD> --authmech1 PLAIN --host2 $SERVIDOR_DESTINO --user2 $USUARIO_DESTINO --authuser2 $ADMIN_DESTINO --password2 $<PASSWORD> --authmech2 PLAIN --noauthmd5
######################################
##MIGRAR TODOS OS USUARIOS SEM SENHA##
######################################
#ZMPROV="/opt/zimbra/bin/zmprov"
#for USER in $($ZMPROV -l gaa); do
#imapsync --nosyncacls --subscribe --syncinternaldates --host1 $SERVIDOR_ORIGEM --user1 $USER --authuser1 $ADMIN_ORIGEM --password1 $<PASSWORD> --authmech1 PLAIN --host2 $SERVIDOR_DESTINO --user2 $USER --authuser2 $ADMIN_DESTINO --password2 $<PASSWORD> --authmech2 PLAIN --noauthmd5
#done
######################################
<file_sep>/_Limitar_Usuarios_Dominio
#!/bin/bash
clear
#Variavel
UsrZ="su - zimbra -c"
#Checa se o usuario é root
LOCAL_USER=`id -u -n`
if [ $LOCAL_USER != "root" ] ; then
echo " Rodar como usuario root"
echo " saindo..."
echo ""
exit
fi
Principal() {
clear
echo "+-------------------------------------------------+"
echo "| Utilitario para Zimbra v1.2 |"
echo "+-------------------------------------------------+"
echo "| Limitar contas por Dominio |"
echo "+-------------------------------------------------+"
echo "| Escrito por: |"
echo "| <NAME> - www.hostlp.net |"
echo "+-------------------------------------------------+"
echo
echo
echo "Opcoes:"
echo "1. Listar Dominios Configurados"
echo "2. Limite atual de usuarios de um Dominio"
echo "3. Alterar limite de usuarios de um Dominio"
echo
echo "4. Sair"
echo
echo
echo -n "Entre com a opcao desejada => "
read opcao
echo
case $opcao in
1) Listar ;;
2) Limite ;;
3) Alterar ;;
4) exit ;;
*) "Opcao desconhecida." ; echo ; Principal ;;
esac
}
Listar() {
echo "Dominios atuais no Zimbra..."
echo
$UsrZ 'zmprov gad'
echo
echo "Pressione qualquer tecla para continuar..."
read msg
Principal
}
Limite() {
echo -n "Verificar limite do dominio: "
read DOMINIO
$UsrZ 'zmprov gd '$DOMINIO' zimbraDomainMaxAccounts'
echo
echo "Pressione qualquer tecla para continuar..."
read msg
Principal
}
Alterar() {
echo -n "Limitar usuarios para o dominio: "
read DOMINIO
echo -n "Quantas contas? "
read QTSCONTAS
$UsrZ 'zmprov md '$DOMINIO' zimbraDomainMaxAccounts '$QTSCONTAS''
echo
echo "Alterado"
echo
echo "Pressione qualquer tecla para continuar..."
read msg
Principal
}
Principal
<file_sep>/_Export_Import_Dados
#!/bin/bash
#+----------------GERANDO LOG-----------------------+OK"
SCRIPT=`basename $0`
LOG=`echo $DEST/$SCRIPT.log | sed s/'.sh'/'.log'/g`
exec &> >(tee -a "$LOG")
echo "[`date`] ==== Inicio de rotina..."
#+----------------GERANDO LOG-----------------------+OK"
cd /tmp/
clear
#Checa se o usuario é zimbra
LOCAL_USER=`id -u -n`
if [ $LOCAL_USER != "zimbra" ] ; then
echo " Rodar como usuario Zimbra"
echo " saindo..."
echo ""
exit
fi
Principal() {
clear
dir="Diretorio Atual : `pwd`"
hostname="Hostname : `hostname --fqdn`"
ip="IP : `ifconfig | awk 'NR>=2 && NR<=2' | awk '{print $3}'`"
versaoso="Versao S.O. : `lsb_release -d | cut -d : -f 2- | sed 's/^[ \t]*//;s/[ \t]*$//'`"
release="Release : `lsb_release -r | cut -d : -f 2- | sed 's/^[ \t]*//;s/[ \t]*$//'`"
codename="Codename : `lsb_release -c | cut -d : -f 2- | sed 's/^[ \t]*//;s/[ \t]*$//'`"
kernel="Kernel : `uname -r`"
arquitetura="Arquitetura : `uname -m`"
versaozimbra="Versao Zimbra : `/opt/zimbra/bin/zmcontrol -v`"
echo
echo "+-------------------------------------------------+"
echo "| Utilitario para Zimbra |"
echo "+-------------------------------------------------+"
echo "| Exportar / Importar Contas do Zimbra v1.6 |"
echo "+-------------------------------------------------+"
echo "| Escrito por: |"
echo "| <NAME> - www.hostlp.net |"
echo "+-------------------------------------------------+"
echo
echo $dir
echo "+-------------------------------------------------+"
echo $hostname
echo "+-------------------------------------------------+"
echo $ip
echo "+-------------------------------------------------+"
echo $versaoso
echo "+-------------------------------------------------+"
echo $release
echo "+-------------------------------------------------+"
echo $codename
echo "+-------------------------------------------------+"
echo $kernel
echo "+-------------------------------------------------+"
echo $arquitetura
echo "+-------------------------------------------------+"
echo $versaozimbra
echo "+-------------------------------------------------+"
echo
echo
echo "Opcoes:"
echo "1. Exportar COS, Dominios, Contas, Contatos, Agendas, Listas, Alias, Assinaturas e Filtros"
echo
echo "2. Importar COS, Dominios, Contas, Contatos, Agendas, Listas, Alias, Assinaturas e Filtros"
echo
echo "3. Sair"
echo
echo
echo -n "Entre com a opcao desejada => "
read opcao
echo
case $opcao in
1) Exportar1 ;;
2) Importar1 ;;
3) exit ;;
*) "Opcao desconhecida." ; echo ; Principal ;;
esac
}
Exportar1() {
# Obtemos uma lista de todas as contas do servidor
source ~/bin/zmshutil
zmsetvars
echo "Exportar todo os dados de um dominio"
echo -n "Digite dominio completo...: "
read DOMAIN
echo
DEST="zimbra/$DOMAIN"
cp -rf $DEST zimbra/$DOMAIN-BKP-$(date "+%Y%m%d")
mkdir $DEST/cos $DEST/dominio $DEST/contas $DEST/contatos $DEST/listas $DEST/alias $DEST/assinaturas $DEST/filtros -p
chown zimbra:zimbra $DEST -R
clear
#######################################################
echo "Exportando COS..."
echo
echo "Exportar COS? - Sim/Nao"
read CONFIRMA
case $CONFIRMA in
s|S|Sim|sim)
$zmprov gac | tee -a $DEST/cos/cos
ldapsearch -x -H $ldap_master_url -D $zimbra_ldap_userdn -w $zimbra_ldap_password -b '' -LLL "(objectclass=zimbraCOS)" > $DEST/cos/cos.ldiff
;;
n|N|Nao|nao)
;;
*) echo "Opcao Invalida" ;; esac
echo "+-------------------------------------------------+OK"
echo
echo "Exportando Dominios..."
echo
rm -rf $DEST/dominio/dominio
zmprov gad | grep "$DOMAIN" | tee -a $DEST/dominio/dominio
echo "+-------------------------------------------------+OK"
echo
echo "Exportando Contas..."
echo
rm -rf $DEST/contas/*
zmhostname > $DEST/server_old
zmprov gaaa | grep "$DOMAIN" | tee -a $DEST/contas/admins
zmprov -l gaa | grep "$DOMAIN" | tee -a $DEST/contas/usuarios
for user in `cat $DEST/contas/usuarios`; do ldapsearch -x -H $ldap_master_url -D $zimbra_ldap_userdn -w $zimbra_ldap_password -b '' -LLL "(zimbraMailDeliveryAddress=$user)" > $DEST/contas/$user.ldiff ; done
echo "+-------------------------------------------------+OK"
echo
echo "Exportando os dados das Contas..."
echo
echo "Exportar dados de caixa postal? - Sim/Nao"
read CONFIRMA
case $CONFIRMA in
s|S|Sim|sim)
for user in `cat $DEST/contas/usuarios`; do zmmailbox -z -m $user getRestURL '/?fmt=tgz' > $DEST/contas/$user.tgz ; echo $user ; done
;;
n|N|Nao|nao)
;;
*) echo "Opcao Invalida" ;; esac
echo "+-------------------------------------------------+OK"
echo
echo "Exportando Contatos..."
echo
zmprov -l gaa "$DOMAIN" | while read conta; do zmmailbox -z -m $conta gru /Contacts > $DEST/contatos/$conta.csv ; echo "$conta"; done
echo "+-------------------------------------------------+OK"
echo
echo "Exportando Agendas..."
echo
cd $DEST/agendas
for user in $($zmprov -l gaa | sort); do
$zmmailbox -z -m $user getRestURL "/calendar?fmt=ics" > $DEST/agendas/$user.ics ; echo $user ; done
echo "+-------------------------------------------------+OK"
echo
echo "Exportando Listas de Distribuição..."
echo
zmprov gadl "$DOMAIN" | tee -a $DEST/listas/listas
for lists in `cat $DEST/listas/listas`; do zmprov gdlm $lists > $DEST/listas/$lists ; done
echo "+-------------------------------------------------+OK"
echo
echo "Exportando Alias..."
echo
for user in `cat $DEST/contas/usuarios`; do zmprov ga $user | grep zimbraMailAlias | awk '{print $2}' | tee -a $DEST/alias/$user ; done
find $DEST/alias/. -type f -empty | xargs -n1 rm -v 1&> /dev/null
echo "+-------------------------------------------------+OK"
echo
echo "Exportando Assinaturas..."
echo
for user in `cat $DEST/contas/usuarios`; do
zmprov ga $user zimbraPrefMailSignatureHTML > /tmp/assinatura;
sed -i -e "1d" /tmp/assinatura ;
sed 's/zimbraPrefMailSignatureHTML: //g' /tmp/assinatura > $DEST/assinaturas/$user.assinatura ;
rm -rf /tmp/assinatura;
`zmprov ga $user zimbraSignatureName > /tmp/name` ;
sed -i -e "1d" /tmp/name ;
sed 's/zimbraSignatureName: //g' /tmp/name > $DEST/assinaturas/$user.name ;
rm -rf /tmp/name ;
echo "$user";
done
echo "+-------------------------------------------------+OK"
echo "Exportando Filtros..."
echo
for user in `cat $DEST/contas/usuarios`; do
zmprov ga $user zimbraMailSieveScript > /tmp/filtros
sed -i -e "1d" /tmp/filtros
sed 's/zimbraMailSieveScript: //g' /tmp/filtros > $DEST/filtros/$user.filtros
rm -f /tmp/filtros
echo "$user"
done
echo "+-------------------------------------------------+OK"
echo
chown zimbra:zimbra $DEST -R
echo "Dados Exportadas"
echo "Pressione qualquer tecla para continuar..."
read msg
Principal
}
Importar1() {
# já com todos os dados no novo servidor servidor
source ~/bin/zmshutil
zmsetvars
echo "Importar todo os dados de um dominio"
echo -n "Digite dominio completo...: "
read DOMAIN
echo
cd /tmp/
DEST="zimbra/$DOMAIN"
# mkdir $DEST/cos $DEST/dominio $DEST/contas $DEST/contatos $DEST/listas $DEST/alias -p
chown zimbra:zimbra $DEST -R
clear
#######################################################
echo "Importando COS..."
echo
echo "Importar COS? - Sim/Nao"
read CONFIRMA
case $CONFIRMA in
s|S|Sim|sim)
cat $DEST/cos/cos
ldapadd -c -x -H $ldap_master_url -D $zimbra_ldap_userdn -w $zimbra_ldap_password -f $DEST/cos/cos.ldiff
;;
n|N|Nao|nao)
;;
*) echo "Opcao Invalida" ;; esac
echo "+-------------------------------------------------+OK"
echo
echo "Importando Dominios..."
echo
for domain in `cat $DEST/dominio/dominio`; do zmprov cd $domain zimbraAuthMech zimbra ;echo $domain ;done
echo "+-------------------------------------------------+OK"
echo
echo "Retirando da importação contas spam, ham, virus e galsync..."
echo
find $DEST -type f -name '*' -exec sed -i '/spam/d' "{}" \;
find $DEST -type f -name '*' -exec sed -i '/ham/d' "{}" \;
find $DEST -type f -name '*' -exec sed -i '/virus/d' "{}" \;
find $DEST -type f -name '*' -exec sed -i '/gal/d' "{}" \;
find $DEST -type f -name '*' -exec sed -i '/admin/d' "{}" \;
find $DEST -name 'spam.*' -exec rm {} \;
find $DEST -name 'ham.*' -exec rm {} \;
find $DEST -name 'virus.*' -exec rm {} \;
find $DEST -name 'gal.*' -exec rm {} \;
find $DEST -name 'admin.*' -exec rm {} \;
echo "+-------------------------------------------------+OK"
echo
echo "Importando Contas..."
echo
# echo -n "Digite o nome do Servidor antigo...: "
# read SERVEROLD
# echo -n "Digite o nome do Servidor novo.....: "
# read SERVENEW
SERVEROL="cat $DEST/server_old"
SERVERNE="`zmhostname`"
find $DEST -type f -name '*.ldiff' -exec sed -i 's/$SERVEROL/$SERVERNE/g' "{}" \;
for user in `cat $DEST/contas/usuarios`; do ldapadd -x -H $ldap_master_url -D $zimbra_ldap_userdn -c -w $zimbra_ldap_password -f $DEST/contas/$user.ldiff ; done
echo "+-------------------------------------------------+OK"
echo
echo "Importando os dados das Contas..."
echo
echo "Importar dados de caixa postal? - Sim/Nao"
read CONFIRMA
case $CONFIRMA in
s|S|Sim|sim)
for user in `cat $DEST/contas/usuarios`; do zmmailbox -z -m $user postRestURL "/?fmt=tgz&resolve=skip" $DEST/contas/$user.tgz ; echo "$user -- OK "; done
;;
n|N|Nao|nao)
;;
*) echo "Opcao Invalida" ;; esac
echo "+-------------------------------------------------+OK"
echo
echo "Importando Contatos..."
echo
for conta in $(ls $DEST/contatos |awk -F ".csv" '{print $1}') ; do zmmailbox -z -m $conta pru /Contacts $DEST/contatos/$conta.csv ;done
#zmprov -l gaa "$DOMAIN" | while read conta; do zmmailbox -z -m $conta pru /Contacts $DEST/contatos/$conta.csv ; done
echo "+-------------------------------------------------+OK"
echo
echo "Importando Agendas..."
echo
cd $DEST/agendas
find . -type f -size -95c -exec rm -f {} \;
for user in $(ls |awk -F ".ics" '{print $1}') ; do zmmailbox -z -m $user pru /Calendar $DEST/agendas/$user.ics ; echo $user ; done
echo "+-------------------------------------------------+OK"
echo
echo "Importando Listas de Distribuição..."
echo
for lists in `cat $DEST/listas/listas`; do zmprov cdl $lists ; echo "$lists -- OK " ; done
echo "+-------------------------------------------------+OK"
echo
echo "Importando Alias..."
echo
for user in `cat $DEST/contas/usuarios`
do
echo $user
if [ -f "./$user.txt" ]; then
for alias in `grep '@' ./$user.txt`
do
zmprov aaa $user $alias
echo "$user ALIAS $alias - OK"
done
fi
done
echo "+-------------------------------------------------+OK"
echo
echo "Importando Assinaturas..."
echo
for user in `cat $DEST/contas/usuarios`; do
zmprov ma $user zimbraSignatureName "`cat $DEST/assinaturas/$user.name`";
zmprov ma $user zimbraPrefMailSignatureHTML "`cat $DEST/assinaturas/$user.assinatura`";
zmprov ga $user zimbraSignatureId > /tmp/firmaid; sed -i -e "1d" /tmp/firmaid;
firmaid=`sed 's/zimbraSignatureId: //g' /tmp/firmaid`;
zmprov ma $user zimbraPrefDefaultSignatureId "$firmaid";
zmprov ma $user zimbraPrefForwardReplySignatureId "$firmaid";
rm -rf /tmp/firmaid;
echo "$user -- OK";
done
echo "+-------------------------------------------------+OK"
echo
echo "Importando Filtros..."
echo
for user in `cat $DEST/contas/usuarios`; do
zmprov ma $user zimbraMailSieveScript "`cat $DEST/filtros/$user.filtros`";
echo "$user -- OK";
done
echo "+-------------------------------------------------+OK"
echo
echo
echo "Dados Importados"
echo "Pressione qualquer tecla para continuar..."
read msg
Principal
}
Principal
echo "[`date`] ==== Fim da rotina..."
#https://syslint.com/blog/tutorial/zimbra-server-migration-and-zimbra-account-transfer-the-perfect-method/
#https://blog.johannfenech.com/migrating-opensource-zimbra-8-6-0-on-centos-6-8-to-zimbra-8-7-1-on-centos-7-safely-and-with-no-downtime/
<file_sep>/_Delegar_Admin
#!/bin/bash
#+----------------GERANDO LOG-----------------------+OK"
SCRIPT=`basename $0`
LOG=`echo /opt/zimbra/$SCRIPT.log | sed s/'.sh'/'.log'/g`
exec &> >(tee -a "$LOG")
echo "[`date`] ==== Inicio de rotina..."
#+----------------GERANDO LOG-----------------------+OK"
clear
#Checa se o usuario é Zimbra
LOCAL_USER=`id -u -n`
if [ $LOCAL_USER != "zimbra" ] ; then
echo " Rodar como usuario Zimbra"
echo " saindo..."
echo ""
exit
fi
dir="Diretorio Atual : `pwd`"
hostname="Hostname : `hostname --fqdn`"
ip="IP : `ifconfig | awk 'NR>=2 && NR<=2' | awk '{print $3}'`"
versaoso="Versao S.O. : `lsb_release -d | cut -d : -f 2- | sed 's/^[ \t]*//;s/[ \t]*$//'`"
release="Release : `lsb_release -r | cut -d : -f 2- | sed 's/^[ \t]*//;s/[ \t]*$//'`"
codename="Codename : `lsb_release -c | cut -d : -f 2- | sed 's/^[ \t]*//;s/[ \t]*$//'`"
kernel="Kernel : `uname -r`"
arquitetura="Arquitetura : `uname -m`"
versaozimbra="Versao Zimbra : `zmcontrol -v`"
echo "+-------------------------------------------------+"
echo "| Utilitario para Zimbra |"
echo "+-------------------------------------------------+"
echo "+-------------------------------------------------+"
#echo "| Escrito por: |"
#echo "| <NAME> - www.hostlp.net |"
echo "+-------------------------------------------------+"
echo
echo $dir
echo "+-------------------------------------------------+"
echo $hostname
echo "+-------------------------------------------------+"
echo $ip
echo "+-------------------------------------------------+"
echo $versaoso
echo "+-------------------------------------------------+"
echo $release
echo "+-------------------------------------------------+"
echo $codename
echo "+-------------------------------------------------+"
echo $kernel
echo "+-------------------------------------------------+"
echo $arquitetura
echo "+-------------------------------------------------+"
echo $versaozimbra
echo "+-------------------------------------------------+"
echo
echo "Aperte <ENTER> para continuar e começar..."
read
sleep 5
echo
echo "==================EXECUTANDO======================="
echo
choose_domain() {
clear
if [ ! -z '$1' ] ; then
if [ "$1" == "fail" ] ; then
echo " !!! Dominio $USER_EMAIL não existe !!!"
echo ""
fi
fi
echo "#########################################################"
read -p '# Digite o nome do domínio: ' DOMAIN
DOMAIN_CHECK=`zmprov gad |grep -E ^$DOMAIN |wc -l`
}
choose_user() {
clear
if [ ! -z '$1' ] ; then
if [ "$1" == "fail" ] ; then
echo " !!! $USER não existe !!!"
echo ""
fi
fi
echo "#########################################################"
read -p '# Digite o email do usuário: ' USER_EMAIL
# echo "zmprov gaa $DOMAIN |grep -E ^$USER_EMAIL "
USER_CHECK=`zmprov -l gaa $DOMAIN |grep -E ^$USER_EMAIL |wc -l`
}
delegateAdmin() {
zmprov ma $USER_EMAIL zimbraIsDelegatedAdminAccount TRUE
zmprov ma $USER_EMAIL zimbraAdminConsoleUIComponents cartBlancheUI \
zimbraAdminConsoleUIComponents domainListView zimbraAdminConsoleUIComponents \
accountListView zimbraAdminConsoleUIComponents DLListView
zmprov ma $USER_EMAIL zimbraDomainAdminMaxMailQuota 0
zmprov grantRight domain $DOMAIN usr $USER_EMAIL +createAccount
zmprov grantRight domain $DOMAIN usr $USER_EMAIL +createAlias
zmprov grantRight domain $DOMAIN usr $USER_EMAIL +createCalendarResource
zmprov grantRight domain $DOMAIN usr $USER_EMAIL +createDistributionList
zmprov grantRight domain $DOMAIN usr $USER_EMAIL +deleteAlias
zmprov grantRight domain $DOMAIN usr $USER_EMAIL +listDomain
zmprov grantRight domain $DOMAIN usr $USER_EMAIL +domainAdminRights
zmprov grantRight domain $DOMAIN usr $USER_EMAIL +configureQuota
zmprov grantRight domain $DOMAIN usr $USER_EMAIL set.account.zimbraAccountStatus
zmprov grantRight domain $DOMAIN usr $USER_EMAIL set.account.sn
zmprov grantRight domain $DOMAIN usr $USER_EMAIL set.account.displayName
zmprov grantRight domain $DOMAIN usr $USER_EMAIL set.account.zimbraPasswordMustChange
zmprov grantRight account $USER_EMAIL usr $USER_EMAIL +deleteAccount
zmprov grantRight account $USER_EMAIL usr $USER_EMAIL +getAccountInfo
zmprov grantRight account $USER_EMAIL usr $USER_EMAIL +getAccountMembership
zmprov grantRight account $USER_EMAIL usr $USER_EMAIL +getMailboxInfo
zmprov grantRight account $USER_EMAIL usr $USER_EMAIL +listAccount
zmprov grantRight account $USER_EMAIL usr $USER_EMAIL +removeAccountAlias
zmprov grantRight account $USER_EMAIL usr $USER_EMAIL +renameAccount
zmprov grantRight account $USER_EMAIL usr $USER_EMAIL +setAccountPassword
zmprov grantRight account $USER_EMAIL usr $USER_EMAIL +viewAccountAdminUI
zmprov grantRight account $USER_EMAIL usr $USER_EMAIL +configureQuota
echo
echo "Feito! teste seu novo usuário admin"
}
#Start script
choose_domain
choose_user
if [ $DOMAIN_CHECK -ne 1 ] ; then
choose_domain fail
fi
if [ $USER_CHECK -ne 1 ] ; then
choose_user fail
fi
clear
echo ""
echo " Aplicando privilégios de administrador a $USER_EMAIL no domínio $DOMAIN"
read -r -p " Você tem certeza? (S/n) " ACCEPT_OPTION
case $ACCEPT_OPTION in
[sS]* )
echo "Começando..."
delegateAdmin
;;
*)
echo "Saindo..."
exit 0
;;
esac
echo "[`date`] ==== Fim de rotina..."
<file_sep>/_Importar_Contas_Externas
#!/bin/bash
zmprov="/opt/zimbra/bin/zmprov";
# Limpa tela
clear
# Lista de e-mails para importar
# <EMAIL>:123456:user:group
lista=/Scripts_Zimbra/lista_emails
# Separador da lista por ":"
while IFS=: read -r email senha nome snome
do
# Adiciona e-mail da lista
# E-<EMAIL>:SENHA:NOME:SOBRENOME
$zmprov ca $email $senha givenName "$nome" sn "$snome" displayName "$nome $snome"
# Gera Log da criação
echo "Senha : $senha ==> Mail : $email ==> Nome : $nome ==> Sobrenome : $snome" >> /Scripts_Zimbra/log_de_contas_importadas.txt
# Marca para alterar a senha no primeiro Login
for each in `$zmprov -l gaa | grep $email`; do $zmprov ma $each zimbraPasswordMustChange TRUE; done
done < "$lista"
<file_sep>/_Export_Dados
#!/bin/bash
#+----------------GERANDO LOG-----------------------+OK"
SCRIPT=`basename $0`
LOG=`echo $DEST/$SCRIPT.log | sed s/'.sh'/'.log'/g`
exec &> >(tee -a "$LOG")
echo "[`date`] ==== Inicio de rotina..."
#+----------------GERANDO LOG-----------------------+OK"
cd /tmp/
clear
#Checa se o usuario é zimbra
LOCAL_USER=`id -u -n`
if [ $LOCAL_USER != "zimbra" ] ; then
echo " Rodar como usuario Zimbra"
echo " saindo..."
echo ""
exit
fi
clear
dir="Diretorio Atual : `pwd`"
hostname="Hostname : `hostname --fqdn`"
ip="IP : `ifconfig | awk 'NR>=2 && NR<=2' | awk '{print $3}'`"
versaoso="Versao S.O. : `lsb_release -d | cut -d : -f 2- | sed 's/^[ \t]*//;s/[ \t]*$//'`"
release="Release : `lsb_release -r | cut -d : -f 2- | sed 's/^[ \t]*//;s/[ \t]*$//'`"
codename="Codename : `lsb_release -c | cut -d : -f 2- | sed 's/^[ \t]*//;s/[ \t]*$//'`"
kernel="Kernel : `uname -r`"
arquitetura="Arquitetura : `uname -m`"
versaozimbra="Versao Zimbra : `/opt/zimbra/bin/zmcontrol -v`"
echo
echo "+-------------------------------------------------+"
echo "| Utilitario para Zimbra |"
echo "+-------------------------------------------------+"
echo "| Exportar / Importar Contas do Zimbra v1.6 |"
echo "+-------------------------------------------------+"
echo "| Escrito por: |"
echo "| <NAME> - www.hostlp.net |"
echo "+-------------------------------------------------+"
echo
echo $dir
echo "+-------------------------------------------------+"
echo $hostname
echo "+-------------------------------------------------+"
echo $ip
echo "+-------------------------------------------------+"
echo $versaoso
echo "+-------------------------------------------------+"
echo $release
echo "+-------------------------------------------------+"
echo $codename
echo "+-------------------------------------------------+"
echo $kernel
echo "+-------------------------------------------------+"
echo $arquitetura
echo "+-------------------------------------------------+"
echo $versaozimbra
echo "+-------------------------------------------------+"
echo
sleep 5
echo
echo "==================EXECUTANDO======================="
echo
# Obtemos uma lista de todas as contas do servidor
# source ~/bin/zmshutil
source /opt/zimbra/bin/zmshutil
zmsetvars
zmprov=/opt/zimbra/bin/zmprov
zmmailbox=/opt/zimbra/bin/zmmailbox
ldapsearch=/opt/zimbra/common/bin/ldapsearch
DOMAIN=`hostname`
DEST="/opt/zimbra/backup/$DOMAIN"
cp -rf $DEST /tmp/$DOMAIN-BKP-$(date "+%Y%m%d")
mkdir $DEST/cos $DEST/dominio $DEST/contas $DEST/contatos $DEST/agendas $DEST/listas $DEST/alias $DEST/assinaturas $DEST/filtros -p
chown zimbra:zimbra $DEST -R
clear
#######################################################
echo "Exportando COS..."
echo
$zmprov gac | tee -a $DEST/cos/cos
$ldapsearch -x -H $ldap_master_url -D $zimbra_ldap_userdn -w $zimbra_ldap_password -b '' -LLL "(objectclass=zimbraCOS)" > $DEST/cos/cos.ldiff
echo "+-------------------------------------------------+OK"
echo
echo "Exportando Dominios..."
echo
rm -rf $DEST/dominio/dominio
$zmprov gad | tee -a $DEST/dominio/dominio
echo "+-------------------------------------------------+OK"
echo
echo "Exportando Contas..."
echo
rm -rf $DEST/contas/*
/opt/zimbra/bin/zmhostname > $DEST/server_old
$zmprov gaaa | tee -a $DEST/contas/admins
$zmprov -l gaa | tee -a $DEST/contas/usuarios
for user in `cat $DEST/contas/usuarios`; do $ldapsearch -x -H $ldap_master_url -D $zimbra_ldap_userdn -w $zimbra_ldap_password -b '' -LLL "(zimbraMailDeliveryAddress=$user)" > $DEST/contas/$user.ldiff ; done
echo "+-------------------------------------------------+OK"
echo
echo "Exportando Contatos..."
echo
$zmprov -l gaa | while read conta; do $zmmailbox -z -m $conta gru /Contacts > $DEST/contatos/$conta.csv ;
echo "$conta" ;
done
echo "+-------------------------------------------------+OK"
echo
echo "Exportando Agendas..."
echo
cd $DEST/agendas
for user in $($zmprov -l gaa | sort); do
$zmmailbox -z -m $user getRestURL "/calendar?fmt=ics" > $DEST/agendas/$user.ics ;
echo "$user" ;
done
echo "+-------------------------------------------------+OK"
echo
echo "Exportando Listas de Distribuição..."
echo
$zmprov gadl | tee -a $DEST/listas/listas
for lists in `cat $DEST/listas/listas`; do $zmprov gdlm $lists > $DEST/listas/$lists ; done
echo "+-------------------------------------------------+OK"
echo
echo "Exportando Alias..."
echo
for user in `cat $DEST/contas/usuarios`; do $zmprov ga $user | grep zimbraMailAlias | awk '{print $2}' | tee -a $DEST/alias/$user ; done
find $DEST/alias/. -type f -empty | xargs -n1 rm -v 1&> /dev/null
echo "+-------------------------------------------------+OK"
echo
echo "Exportando Assinaturas..."
echo
for user in `cat $DEST/contas/usuarios`; do
$zmprov ga $user zimbraPrefMailSignatureHTML > /tmp/assinatura;
sed -i -e "1d" /tmp/assinatura ;
sed 's/zimbraPrefMailSignatureHTML: //g' /tmp/assinatura > $DEST/assinaturas/$user.assinatura ;
rm -rf /tmp/assinatura;
`$zmprov ga $user zimbraSignatureName > /tmp/name` ;
sed -i -e "1d" /tmp/name ;
sed 's/zimbraSignatureName: //g' /tmp/name > $DEST/assinaturas/$user.name ;
rm -rf /tmp/name ;
echo "$user";
done
echo "+-------------------------------------------------+OK"
echo
echo "Exportando Filtros..."
echo
for user in `cat $DEST/contas/usuarios`; do
$zmprov ga $user zimbraMailSieveScript > /tmp/filtros
sed -i -e "1d" /tmp/filtros
sed 's/zimbraMailSieveScript: //g' /tmp/filtros > $DEST/filtros/$user.filtros
rm -f /tmp/filtros
echo "$user"
done
echo "+-------------------------------------------------+OK"
echo
chown zimbra:zimbra $DEST -R
echo "Dados Exportadas"
echo "[`date`] ==== Fim da rotina..."
|
e87429b73ed475297e5bcba0f67bd5008dd68e90
|
[
"Shell"
] | 6 |
Shell
|
lukyrys/Zimbra
|
92ad621958fa1efc28f077e4026c92d9e6dbd3fb
|
3934ae8d89d9c1aa2c9880a8cad076ad13f17594
|
refs/heads/master
|
<repo_name>0xtvarun/Bunk-Confidently<file_sep>/app/src/main/java/com/vtewari/bunkconfidently/SplashActivity.java
package com.vtewari.bunkconfidently;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.util.Log;
import com.afollestad.materialdialogs.MaterialDialog;
import com.vtewari.bunkconfidently.utils.StaticStrings;
/**
* Created by a0_ on 9/9/16.
*/
public class SplashActivity extends AppCompatActivity {
private static final String TAG = SplashActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
if(savedInstanceState == null){
SharedPreferences sp = getSharedPreferences(getString(R.string.pref_file_key), MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
MaterialDialog.Builder builder = new MaterialDialog.Builder(this)
.title("Minimum Attendance Requirement")
.inputType(InputType.TYPE_CLASS_NUMBER)
.input("Minimum Attendance Requirement", "75", new MaterialDialog.InputCallback() {
@Override
public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
if(StaticStrings.DEBUG){
Log.d(TAG, "onInput: " + input);
}
}
});
builder.show();
}
startActivity(new Intent(this,MainActivity.class));
}
}
<file_sep>/app/src/main/java/com/vtewari/bunkconfidently/utils/StaticStrings.java
package com.vtewari.bunkconfidently.utils;
/**
* Created by a0_ on 5/9/16.
*/
public class StaticStrings {
public static String UPDATE = "update";
public static String FECTCH_ALL = "fetch_all";
public static String REMOVE_ALL = "remove_all";
public static String INSERT_ONE = "insert_one";
public static String DELETE_ONE = "delete_one";
public static String ALLOWED_PERCENTAGE = "percentage";
public static boolean DEBUG = true;
}
<file_sep>/app/src/main/java/com/vtewari/bunkconfidently/utils/FloatingActionButtonBehaviour.java
package com.vtewari.bunkconfidently.utils;
import android.content.Context;
import android.support.design.widget.FloatingActionButton;
import android.util.AttributeSet;
/**
* Created by a0_ on 8/9/16.
*/
public class FloatingActionButtonBehaviour extends FloatingActionButton.Behavior {
public FloatingActionButtonBehaviour(Context context, AttributeSet attrs) {
super(context, attrs);
}
}
<file_sep>/app/src/main/java/com/vtewari/bunkconfidently/database/DBContract.java
package com.vtewari.bunkconfidently.database;
/**
* Created by a0_ on 2/9/16.
*/
public class DBContract {
int _id;
String lecture;
int attended;
int total;
private float PERCENTAGE;
public float getPERCENTAGE() {
return PERCENTAGE;
}
public void setPERCENTAGE(float PERCENTAGE) {
this.PERCENTAGE = PERCENTAGE;
}
public int getCAN_BUNK() {
return CAN_BUNK;
}
public void setCAN_BUNK() {
if(getPERCENTAGE() > 75.0){
this.CAN_BUNK = Math.abs(((75*this.total)/100)-this.attended);
}else {
this.CAN_BUNK = 0;
}
}
private int CAN_BUNK;
public static String KEY_ID = "id";
public static String KEY_LECTURE = "lecture";
public static String KEY_ATTENDED = "attended";
public static String KEY_TOTAL = "total";
public static final String TABLE_NAME = "Bunks";
public DBContract() {}
public DBContract(int attended, String lecture, int total) {
this.attended = attended;
this.lecture = lecture;
this.total = total;
this.setPERCENTAGE((this.attended/this.total)*100);
this.setCAN_BUNK();
}
public DBContract(int _id, int attended, String lecture, int total) {
this._id = _id;
this.attended = attended;
this.lecture = lecture;
this.total = total;
}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public int getAttended() {
return attended;
}
public void setAttended(int attended) {
this.attended = attended;
}
public String getLecture() {
return lecture;
}
public void setLecture(String lecture) {
this.lecture = lecture;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
}
<file_sep>/README.md
#Bunk Confidently
This is an application for android to keep track of the lectures bunked
to be able to maintain your attendance
It gives a list of the Classes added by the user along with functionality
to add the total number of lectures attended and total number of lectures
taken
It also gives a Pie-Graph showing the user the current Attendance percentge
and also tells the users the number of lectures they can afford to bunk<file_sep>/app/src/main/java/com/vtewari/bunkconfidently/adapter/Lecture.java
package com.vtewari.bunkconfidently.adapter;
/**
* Created by a0_ on 3/9/16.
*/
public class Lecture {
private static final String TAG = Lecture.class.getSimpleName();
private int _id;
private String lecture_name;
private int attended;
private int total;
private double PERCENTAGE;
private int CAN_BUNK;
public Lecture(int attended, String lecture_name, int total) {
this.attended = attended;
this.lecture_name = lecture_name;
this.total = total;
this.setPERCENTAGE();
this.setCAN_BUNK();
}
public Lecture(int _id, int attended, String lecture_name, int total) {
this._id = _id;
this.attended = attended;
this.lecture_name = lecture_name;
this.total = total;
this.setPERCENTAGE();
this.setCAN_BUNK();
}
public int getCAN_BUNK() {
return CAN_BUNK;
}
public void setCAN_BUNK() {
if(this.PERCENTAGE >= 75.0){
int required = (75 * this.total)/100;
this.CAN_BUNK = Math.abs(required - attended);
}else{
this.CAN_BUNK = 0;
}
}
public double getPERCENTAGE() {
return PERCENTAGE;
}
public void setPERCENTAGE() {
double att = ((double)this.attended/(double)this.total)*100;
this.PERCENTAGE = att;
}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public int getAttended() {
return attended;
}
public void setAttended(int attended) {
this.attended = attended;
}
public String getLecture_name() {
return lecture_name;
}
public void setLecture_name(String lecture_name) {
this.lecture_name = lecture_name;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
}
<file_sep>/app/src/main/java/com/vtewari/bunkconfidently/database/DBHandler.java
package com.vtewari.bunkconfidently.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by a0_ on 2/9/16.
*/
public class DBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Lectures";
private static final String TABLE_NAME = "Bunks";
/*Column names*/
private static String KEY_ID = "id";
private static String KEY_LECTURE = "lecture";
private static String KEY_ATTENDED = "attended";
private static String KEY_TOTAL = "total";
public DBHandler(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_BUNKS_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_LECTURE + " TEXT,"
+ KEY_ATTENDED + " INTEGER," + KEY_TOTAL + " INTEGER" + ")" ;
db.execSQL(CREATE_BUNKS_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void addLecture(DBContract lecture){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_LECTURE, lecture.getLecture());
values.put(KEY_ATTENDED, lecture.getAttended());
values.put(KEY_TOTAL, lecture.getTotal());
db.insert(TABLE_NAME,null,values);
db.close();
}
DBContract getLecture(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(
TABLE_NAME,
new String[]{KEY_ID, KEY_LECTURE, KEY_ATTENDED, KEY_TOTAL},
KEY_ID + "=?",
new String[]{ String.valueOf(id)},
null,null,null,null);
if(cursor != null)
cursor.moveToFirst();
DBContract lecture = new DBContract(
Integer.parseInt(cursor.getString(0)),
Integer.parseInt(cursor.getString(1)),
cursor.getString(2),
Integer.parseInt(cursor.getString(3))
);
return lecture;
}
public Cursor getAllLectures(SQLiteDatabase db){
Cursor mCursor = db.query(
TABLE_NAME,
new String[]{KEY_ID, KEY_LECTURE, KEY_ATTENDED, KEY_TOTAL},
null,null,null,null,null
);
return mCursor;
}
public int updateLectureInfo(DBContract lecture){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ATTENDED, lecture.getAttended());
values.put(KEY_TOTAL, lecture.getTotal());
return db.update(
TABLE_NAME,
values,
KEY_ID + " = ? ",
new String[] {String.valueOf(lecture.get_id())}
);
}
public void deleteLecture(DBContract lecture){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(
TABLE_NAME,
KEY_ID + " = ? ",
new String[]{ String.valueOf(lecture.get_id())}
);
db.close();
}
public void deleteAll(SQLiteDatabase db){
db.execSQL("DELETE FROM " + TABLE_NAME);
}
}
|
de386a490600f2f93d7cf1de24e4a27ccf009bab
|
[
"Markdown",
"Java"
] | 7 |
Java
|
0xtvarun/Bunk-Confidently
|
6aa2cf092aae5cf1c02ea805dee8c86cc7cb47b7
|
10fc7f501c7101e515d9f79b5a71fd8874078caa
|
refs/heads/master
|
<repo_name>melai-melai/starting-template<file_sep>/gulpfile.js
/*
* Load plugins
*/
const gulp = require('gulp');
const sass = require('gulp-sass');
const autoprefixer = require('gulp-autoprefixer');
const babel = require('gulp-babel');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
const rename = require('gulp-rename');
const cleanCSS = require('gulp-clean-css');
//const imagemin = require('gulp-imagemin');
const image = require('gulp-image');
const newer = require('gulp-newer');
const plumber = require('gulp-plumber');
const stylelint = require('gulp-stylelint');
const eslint = require('gulp-eslint');
const del = require('del');
const sourcemaps = require('gulp-sourcemaps');
const browsersync = require('browser-sync').create();
sass.compiler = require('node-sass');
/*
* Paths
*/
const paths = {
styles: {
src: 'resources/scss/**/*.scss',
dest: 'public_html/css/'
},
scripts: {
src: 'resources/js/**/*.js',
dest: 'public_html/js/'
},
images: {
src: 'resources/images/**/*',
dest: 'public_html/images/'
},
html: {
src: 'public_html/**/*.html'
},
maps: {
dest: '/maps'
}
};
/*
* Task: Clear public_html except html files
*/
function clean() {
return del([ 'public_html/**/*' , '!public_html/**/*.html' ]);
}
/*
* Task: BrowserSync reload
*/
function browserSyncReload(done) {
browsersync.reload();
done();
}
/*
* Task: BrowserSync init
*/
function browserSync(done) {
browsersync.init({
server: {
baseDir: './public_html',
index: 'index.html'
},
//proxy: 'yourlocal.dev',
port: 3000,
browser: 'firefox'
});
done();
}
/*
* Task: Optimize css
*/
function styles() {
return gulp.src(paths.styles.src)
.pipe(sourcemaps.init())
.pipe(plumber())
.pipe(sass({ outputStyle: 'expanded' }).on('error', sass.logError)) // scss to css
.pipe(autoprefixer({
cascade: false
}))
.pipe(cleanCSS({compatibility: 'ie8'}))
.pipe(rename({
basename: 'styles',
suffix: '.min'
}))
.pipe(sourcemaps.write(paths.maps.dest))
.pipe(gulp.dest(paths.styles.dest))
.pipe(browsersync.stream());
}
/*
* Task: Lint styles
*/
function stylesLint() {
return gulp.src(paths.styles.src)
.pipe(plumber())
.pipe(stylelint({
failAfterError: true,
reporters: [
{formatter: 'string', console: true}
]
}));
}
/*
* Task: Optimize js
*/
function scripts() {
return gulp.src(paths.scripts.src, { sourcemaps: true })
.pipe(sourcemaps.init())
.pipe(plumber())
.pipe(babel({presets: ['@babel/env']}))
.pipe(uglify())
.pipe(concat('scripts.min.js'))
.pipe(sourcemaps.write(paths.maps.dest))
.pipe(gulp.dest(paths.scripts.dest));
}
/*
* Task: Lint scripts
*/
function scriptsLint() {
return gulp.src(paths.scripts.src)
.pipe(plumber())
.pipe(eslint())
.pipe(eslint.format());
//.pipe(eslint.failAfterError());
}
/*
* Task: Optimize images
*/
function images() {
return gulp.src(paths.images.src)
.pipe(newer(paths.images.dest))
// .pipe(
// imagemin([
// imagemin.gifsicle({ interlaced: true }),
// imagemin.jpegtran({ progressive: true }),
// imagemin.optipng({ optimizationLevel: 5 }),
// imagemin.svgo({
// plugins: [
// {
// removeViewBox: false,
// collapseGroups: true
// }
// ]
// })
// ])
// )
.pipe(image())
.pipe(gulp.dest(paths.images.dest));
}
/*
* Task: Watch files
*/
function watchFiles() {
gulp.watch(paths.styles.src, gulp.series(stylesLint, styles));
gulp.watch(paths.scripts.src, gulp.series(scriptsLint, scripts, browserSyncReload));
gulp.watch(paths.images.src, images, browserSyncReload);
gulp.watch(paths.html.src).on('change', browsersync.reload);
}
/*
* Define complex tasks
*/
const css = gulp.series(stylesLint, styles);
const js = gulp.series(scriptsLint, scripts);
const watch = gulp.parallel(watchFiles, browserSync);
const build = gulp.series(clean, gulp.parallel(styles, scripts, images));
/*
* Export tasks
*/
exports.clean = clean;
exports.css = css;
exports.js = js;
exports.images = images;
exports.watch = watch;
exports.build = build;
exports.default = watch;<file_sep>/public_html/index.html
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<meta name="description" content="">
<meta name="keywords" content="">
<meta name="author" content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/css/styles.min.css">
<script src="/js/scripts.min.js"></script>
</head>
<body>
<img src="/images/image.jpg" alt="Картинка">
<h3>Список улучшений</h3>
<ul>
<li>Указывать браузер для открытия BrowserSync</li>
<li>Файл конфигурации StyleLint</li>
</ul>
</body>
</html><file_sep>/README.md
# Starting template with Gulp4
The project helps you to work with css(sass), js, minified files and optomization of images. It contains stylelint.
## Setting
- Babel settings are in babel.config.js
- StyleLint settings are in .stylelintrc
- ESLint settings are in .eslintrc.js
## Getting Started
1. Download the project.
2. In console enter "npm i"
3. Create! =)
### Prerequisites
You need:
1. node.js
2. npm
|
654fffb7dbb431b8e477ac19b06436ed4787f1b0
|
[
"JavaScript",
"HTML",
"Markdown"
] | 3 |
JavaScript
|
melai-melai/starting-template
|
7a4442f61adda48a6d30db55c5f17c18ebf2822a
|
791206a32a27007174e1f5c83ea24484dbe92b53
|
refs/heads/main
|
<file_sep>const de = require('dotenv');
de.config({ path: '.env.local' });
module.exports = {
client: {
includes: [
'./{pages,lib,components,models,queries,utils}/**/*.{ts,tsx,graphql}',
],
service: {
name: 'contentful',
url: `https://graphql.contentful.com/content/v1/spaces/${process.env.NEXT_PUBLIC_CONTENTFUL_SPACE}/environments/${process.env.NEXT_PUBLIC_CONTENTFUL_ENVIRONMENT}`,
// optional headers
headers: {
authorization: `Bearer ${process.env.NEXT_PUBLIC_CONTENTFUL_TOKEN}`,
},
// optional disable SSL validation check
skipSSLValidation: true,
},
// service: {
// name: 'GitHub',
// localSchemaFile: './github.schema.graphql',
// },
},
};
<file_sep>export interface Theme {
colorPrimary: string;
colorSecondary: string;
colorPaper: string;
colorShadow: string;
colorText: string;
pageWidth: number;
}
export const theme: Theme = {
colorPaper: '#fff',
colorPrimary: '#e10fee',
colorSecondary: '#0f19ee',
colorShadow: '#a3a3a3',
colorText: '#000',
pageWidth: 1000,
};
<file_sep>export interface ContactLinkedin {
type: 'linkedin';
username: string;
}
export interface ContactGithub {
type: 'github';
username: string;
}
export interface ContactTelegram {
type: 'telegram';
username: string;
}
export interface ContactPhone {
type: 'phone';
number: string;
}
export interface ContactEmail {
type: 'email';
address: string;
}
export interface ContactSkype {
type: 'skype';
username: string;
}
export type ContactIcon =
| 'email'
| 'github'
| 'url'
| 'linkedin'
| 'phone'
| 'telegram'
| 'skype';
export interface ContactLink {
type: 'link';
name: string;
url: string;
icon: ContactIcon;
}
//--------
export type CVContactItem =
| ContactEmail
| ContactGithub
| ContactLink
| ContactLinkedin
| ContactPhone
| ContactTelegram
| ContactSkype;
<file_sep>import NextAuth from 'next-auth';
import Providers from 'next-auth/providers';
const options = {
providers: [
Providers.Auth0({
clientId: process.env.AUTH0_ID,
clientSecret: process.env.AUTH0_SECRET,
domain: process.env.AUTH0_DOMAIN,
}),
],
};
export default (req, res) => NextAuth(req, res, options);
<file_sep>import { useQuery } from '@apollo/client';
import GetCVGraphql from './GetCV.graphql';
export const useCV = () => {
return useQuery(GetCVGraphql);
};
<file_sep>const { compose } = require('recompose');
const withGraphql = require('next-graphql-loader');
const withYaml = require('next-plugin-yaml');
const withMDX = require('@next/mdx')({
extension: /\.mdx?$/,
});
module.exports = compose(
withGraphql,
withYaml,
withMDX
)({ pageExtensions: ['js', 'jsx', 'mdx', 'tsx', 'ts'] });
|
c6a6c03bf43fdb65f39014cb0dff82e45afbbf82
|
[
"JavaScript",
"TypeScript"
] | 6 |
JavaScript
|
corporateanon/typescript.work
|
123f5b7c9756721ba92864d1599f23e2f19afd24
|
19b451d98250ec3ef6d691e28a18e0f1f52c4326
|
refs/heads/master
|
<repo_name>dosurprise/contacts<file_sep>/application/controllers/TestController.php
<?php
require_once '../application/models/Users.php';
class TestController extends Zend_Controller_Action{
public function testAction(){
}
}<file_sep>/application/forms/loginForm.php
<?php
class LoginForm extends Zend_Form{
public function init(){
$username=$this->createElement('text', 'username');
$username->setLabel('用户名')->setRequired(true);
$username->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_textInput.phtml'
)
)
));
$password=$this->createElement('password', '<PASSWORD>');
$password->setLabel('密码')->setRequired(true);
$password->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_textInput.phtml'
)
)
));
$signin = $this->createElement('submit', 'signin');
$signin->setLabel('begin login end')->setValue('Login')->setIgnore(false);
$signin->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_btns.phtml'
)
)
));
$this->addElements(array($username,$password,$signin));
}
}<file_sep>/application/controllers/AuthController.php
<?php
require_once '../application/forms/loginForm.php';
require_once '../application/forms/registerForm.php';
require_once '../application/forms/editForm.php';
require_once '../application/models/Users.php';
class AuthController extends Zend_Controller_Action {
public function loginAction() {
$storage = new Zend_Auth_Storage_Session ( );
$data = $storage->read ();
if ($data) {
$this->_redirect ( 'index/index' );
}
$users = new Users ( );
$form = new loginForm ( );
$this->view->form=$form;
if ($this->getRequest ()->isPost ()) {
if ($form->isValid ( $_POST )) {
$dataForm = $form->getValues ();
$auth = Zend_Auth::getInstance ();
$authAdapter = new Zend_Auth_Adapter_DbTable ( $users->getAdapter (), 'users' );
$authAdapter->setIdentityColumn ( 'username' ) ->setCredentialColumn ( 'password' );
$authAdapter->setIdentity ( $dataForm ['username'] ) ->setCredential ( $dataForm ['password'] );
$authAdapter->setCredentialTreatment('md5(?)');
$result = $auth->authenticate ( $authAdapter );
if ($result->isValid ()) {
$users->setLoginTime($dataForm ['username']);
$storage = new Zend_Auth_Storage_Session ( );
$storage->write ( $authAdapter->getResultRowObject () );
$this->_redirect ( 'index/index' );
}else {
$this->view->errorMessage = "Invalid username or password, Please try again.";
}
}
}
}
public function signupAction(){
$users = new Users ( );
$form = new RegisterForm ( );
$this->view->form =$form;
if ($this->getRequest ()->isPost ()) {
if ($form->isValid ( $_POST )) {
$data = $form->getValues ();
if ($data ['password'] != $data ['passConfirm']) {
$this->view->errorMessage = "Password and confirm password donnot match."; return;
}
if ($users->checkUnique ( $data ['username'] )) {
$this->view->errorMessage = "Name already taken."; return;
}
$data ['password']=md5($data ['password']);
unset ( $data ['passConfirm'] );
$users->addUser($data);
$this->_redirect ( 'index/index' );
}
}
}
public function editAction(){
$storage = new Zend_Auth_Storage_Session ( );
$data = $storage->read ();
if (!$data) {
$this->_redirect ( 'index/index' );
}
$users = new Users ( );
$form = new EditForm ( );
$this->view->form =$form;
if ($this->getRequest ()->isPost ()) {
if ($form->isValid ( $_POST )) {
$dataForm = $form->getValues ();
if($dataForm ['password']){
if($data->password!==md5($dataForm ['oldpassword'])){
$this->view->errorMessage = "Oldpassword doesnnot match."; return;
}
if ($dataForm ['password'] != $dataForm ['passConfirm']) {
$this->view->errorMessage = "Password and confirm password donnot match."; return;
}
$dataForm ['password']=md5($dataForm ['password']);
}
else{unset ( $dataForm ['password'] );}
unset ( $dataForm ['passConfirm'] );
unset ( $dataForm ['oldpassword'] );
$users->updateUser($dataForm,$dataForm ['username']);
$this->_redirect ( 'auth/edit' );
}
}
}
public function logoutAction() {
$storage = new Zend_Auth_Storage_Session ( );
$storage->clear ();
$this->_redirect ( 'auth/login' );
}
} <file_sep>/application/models/Groups.php
<?php
class Groups extends Zend_Db_Table_Abstract{
protected $_name='groups';
public function checkUnique($groupname){
$select = $this->_db->select()->from($this->_name,array('groupname'))-> where ('groupname=?',$groupname);
$result = $this->getAdapter()->fetchOne($select);
if($result){
return true;
}
return false;
}
public function addGroup($array){
$this->getAdapter()->insert($this->_name, $array);
}
public function getGroupInfo($groupid){
$select = $this->_db->select()->from($this->_name)-> where ('groupid=?',$groupid);
$result = $this->getAdapter()->fetchRow($select);
if($result){
return $result;
}
return false;
}
}
class RelGroup extends Zend_Db_Table_Abstract{
protected $_name='relgroup';
public function whetherJoin($userid,$groupid){
$select = $this->_db->select()->from($this->_name,array('user'))->where ('groupjoin='.$groupid.' and user="'.$userid.'"');
$result = $this->getAdapter()->fetchAll($select);
if($result&&sizeof($result)){
return true;
}
return false;
}
public function joinGroup($userid,$groupid){
if(!$this->whetherJoin($userid, $groupid)){
$this->getAdapter()->insert($this->_name,array("user"=>$userid,"groupjoin"=>$groupid));
}
}
public function getUserList($groupid){
$select = $this->_db->select()->from('users',array('id','username'))->joinLeft('relgroup', 'users.id = relgroup.user')->where('groupjoin="'.$groupid.'"');
$result = $this->getAdapter()->fetchAll($select);
return $result;
}
}<file_sep>/application/forms/editForm.php
<?php
require_once '../application/models/Users.php';
class EditForm extends Zend_Form{
public function init(){
$storage = new Zend_Auth_Storage_Session ( );
$data = $storage->read (); if (! $data) {
$this->_redirect ( 'auth/login' );
}
$user=new Users();
$userinfo=$user->getUserInfo($data->id);
$username=$this->createElement('text', 'username');
$username->setLabel('Username')->setValue($userinfo['username'])->setAttrib('readonly',true)->setRequired(true);
$username->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_textInput.phtml'
)
)
));
$oldpassword=$this->createElement('password', '<PASSWORD>');
$oldpassword->setLabel('<PASSWORD>');
$oldpassword->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_textInput.phtml'
)
)
));
$password=$this->createElement('password', '<PASSWORD>');
$password->setLabel('<PASSWORD>');
$password->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_textInput.phtml'
)
)
));
$passConfirm=$this->createElement('password', '<PASSWORD>');
$passConfirm->setLabel('<PASSWORD>');
$passConfirm->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_textInput.phtml'
)
)
));
$realname=$this->createElement('text', 'realname');
$realname->setLabel('Realname')->setValue($userinfo['realname'])->setRequired(true);
$realname->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_textInput.phtml'
)
)
));
$email=$this->createElement('text', 'email');
$email->setLabel('Email')->setValue($userinfo['email'])->setAttrib('readonly',true)->setRequired(true);
$email->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_textInput.phtml'
)
)
));
$address=$this->createElement('text', 'address');
$address->setLabel('Address')->setValue($userinfo['address'])->setRequired(false);
$address->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_textInput.phtml'
)
)
));
$city=$this->createElement('text', 'city');
$city->setLabel('City')->setValue($userinfo['city'])->setRequired(false);
$city->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_textInput.phtml'
)
)
));
$country=$this->createElement('text', 'country');
$country->setLabel('Country')->setValue($userinfo['country'])->setRequired(false);
$country->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_textInput.phtml'
)
)
));
$mobileHome=$this->createElement('text', 'mobileHome');
$mobileHome->setLabel('Mobile Home')->setValue($userinfo['mobileHome'])->setRequired(false);
$mobileHome->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_textInput.phtml',
)
)
));
$mobileWork=$this->createElement('text', 'mobileWork');
$mobileWork->setLabel('Mobile Work')->setValue($userinfo['mobileWork'])->setRequired(false);
$mobileWork->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_textInput.phtml'
)
)
));
$description=$this->createElement('textarea', 'description');
$description->setLabel('Description')->setValue($userinfo['description'])->setRequired(false)->setAttribs(array('cols'=>40,'rows'=>12));
$description->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_textArea.phtml'
)
)
));
$update = $this->createElement('submit', 'update');
$update->setLabel('begin')->setValue('Update')->setIgnore(true);
$update->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_btns.phtml'
)
)
));
$reset = $this->createElement('reset', 'reset');
$reset->setLabel('end')->setValue('Reset')->setIgnore(true);
$reset->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_btns.phtml'
)
)
));
$this->clearDecorators();
$this->addDecorator('FormElements')->addDecorator('Form');
$this->addElements(array($username,$oldpassword,$<PASSWORD>,$<PASSWORD>,$realname,$email,$address,$city,$country,$mobileHome,$mobileWork,$description,$update,$reset));
}
}<file_sep>/application/forms/registerForm.php
<?php
class RegisterForm extends Zend_Form{
public function init(){
$username=$this->createElement('text', 'username');
$username->setLabel('Username')->setRequired(true);
$username->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_textInput.phtml'
)
)
));
$password=$this->createElement('password', '<PASSWORD>');
$password->setLabel('Password')->setRequired(true);
$password->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_textInput.phtml'
)
)
));
$passConfirm=$this->createElement('password', '<PASSWORD>');
$passConfirm->setLabel('Confirm Password')->setRequired(true);
$passConfirm->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_textInput.phtml'
)
)
));
$realname=$this->createElement('text', 'realname');
$realname->setLabel('Realname')->setRequired(true);
$realname->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_textInput.phtml'
)
)
));
$email=$this->createElement('text', 'email');
$email->setLabel('Email')->setRequired(true);
$email->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_textInput.phtml'
)
)
));
$address=$this->createElement('text', 'address');
$address->setLabel('Address')->setRequired(false);
$address->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_textInput.phtml'
)
)
));
$city=$this->createElement('text', 'city');
$city->setLabel('City')->setRequired(false);
$city->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_textInput.phtml'
)
)
));
$country=$this->createElement('text', 'country');
$country->setLabel('Country')->setRequired(false);
$country->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_textInput.phtml'
)
)
));
$mobileHome=$this->createElement('text', 'mobileHome');
$mobileHome->setLabel('Mobile Home')->setRequired(false);
$mobileHome->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_textInput.phtml',
)
)
));
$mobileWork=$this->createElement('text', 'mobileWork');
$mobileWork->setLabel('Mobile Work')->setRequired(false);
$mobileWork->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_textInput.phtml'
)
)
));
$description=$this->createElement('textarea', 'description');
$description->setLabel('Description')->setRequired(false)->setAttribs(array('cols'=>40,'rows'=>12));
$description->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_textArea.phtml'
)
)
));
$register = $this->createElement('submit', 'register');
$register->setLabel('begin')->setValue('Register')->setIgnore(true);
$register->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_btns.phtml'
)
)
));
$reset = $this->createElement('reset', 'reset');
$reset->setLabel('end')->setValue('Reset')->setIgnore(true);
$reset->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_btns.phtml'
)
)
));
$this->clearDecorators();
$this->addDecorator('FormElements')->addDecorator('Form');
$this->addElements(array($username,$password,$passConfirm,$realname,$email,$address,$city,$country,$mobileHome,$mobileWork,$description,$register,$reset));
}
}<file_sep>/application/controllers/UserController.php
<?php
require_once '../application/models/Users.php';
class UserController extends Zend_Controller_Action {
public function displayAction(){
if ($this->_helper->getHelper('FlashMessenger')->getMessages()) {
$this->view->messages = $this->_helper
->getHelper('FlashMessenger')
->getMessages();
}
$storage = new Zend_Auth_Storage_Session ( );
$data = $storage->read (); if (! $data) {
$this->_redirect ( 'auth/login' );
}
$this->view->username = $data->username;
$request = new Zend_Controller_Request_Http();
$front = Zend_Controller_Front::getInstance();
$front->getRouter()->route($request);
$params = $request->getParams();
if($data->id===$params['userid']){$this->_redirect ('index/index');}
$user=new Users();
$info=$user->getUserInfo($params['userid']);
$this->view->userinfo=$info;
}
public function processAction(){
$storage = new Zend_Auth_Storage_Session ( );
$data = $storage->read ();
if (! $data) {
$this->_redirect ( 'auth/login' );
}
$request = new Zend_Controller_Request_Http();
$front = Zend_Controller_Front::getInstance();
$front->getRouter()->route($request);
$params = $request->getParams();
$userProcess=new UserRelations();
$msg=$userProcess->processRequest($params['userid'],$data->id,$params['actionString']);
$this->_helper->getHelper('FlashMessenger')->addMessage($msg);
$this->_redirect("/index/index");
}
public function deleteAction(){
$storage = new Zend_Auth_Storage_Session ( );
$data = $storage->read (); if (! $data) {
$this->_redirect ( 'auth/login' );
}
$request = new Zend_Controller_Request_Http();
$front = Zend_Controller_Front::getInstance();
$front->getRouter()->route($request);
$params = $request->getParams();
$userProcess=new UserRelations();
$msg=$userProcess->deleteRequest($data->id,$params['userid'],$params['actionString']);
$this->_helper->getHelper('FlashMessenger')->addMessage($msg);
$this->_redirect("/index/index");
}
}<file_sep>/application/forms/addGroupForm.php
<?php
require_once '../application/models/Users.php';
class addGroupForm extends Zend_Form{
public function init(){
$storage = new Zend_Auth_Storage_Session ( );
$data = $storage->read (); if (! $data) {
$this->_redirect ( 'auth/login' );
}
$user=new Users();
$userinfo=$user->getUserInfo($data->id);
$groupname=$this->createElement('text', 'groupname');
$groupname->setLabel('Groupname')->setRequired(true);
$groupname->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_textInput.phtml'
)
)
));
$founder=$this->createElement('text', 'founder');
$founder->setLabel('Founder')->setRequired(true)->setValue($data->username)->setAttrib('readonly',true);
$founder->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_textInput.phtml'
)
)
));
$description=$this->createElement('textarea', 'description');
$description->setLabel('Description')->setRequired(false)->setAttribs(array('cols'=>40,'rows'=>12));
$description->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_textArea.phtml'
)
)
));
$add = $this->createElement('submit', 'add');
$add->setLabel('begin')->setValue('Add')->setIgnore(true);
$add->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_btns.phtml'
)
)
));
$reset = $this->createElement('reset', 'reset');
$reset->setLabel('end')->setValue('Reset')->setIgnore(true);
$reset->setDecorators(array(
array('ViewScript',
array(
'viewScript' => 'form_element/_btns.phtml'
)
)
));
$this->clearDecorators();
$this->addDecorator('FormElements')->addDecorator('Form');
$this->addElements(array($groupname,$founder,$description,$add,$reset));
}
}<file_sep>/application/controllers/AjaxController.php
<?php
require_once '../application/models/Users.php';
class AjaxController extends Zend_Controller_Action {
public function shareAction(){
$storage = new Zend_Auth_Storage_Session ( );
$data = $storage->read (); if (! $data) {
$this->_redirect ( 'auth/login' );
}
try {
if (!$this->_request->isPost()) {
throw new Exception('Invalid action. Not post.');
}
$rel=new UserRelations();
$message=$rel->addRelation($data->id, $_POST['id']);
$json = Zend_Json::encode(array('message'=>$message,'id'=>$_POST['id']));
echo $json;//this will echo JSON to the Javascript
unset($json);
unset($data);
return true;
} catch (Exception $e) {
echo $e->getMessage();
}
}
}<file_sep>/data/db_contacts.sql
-- phpMyAdmin SQL Dump
-- version 3.4.8
-- http://www.phpmyadmin.net
--
-- 主机: localhost
-- 生成日期: 2011 年 12 月 26 日 08:25
-- 服务器版本: 5.5.18
-- PHP 版本: 5.2.5 (x64)
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- 数据库: `dosurprise_phpfogapp_com`
--
-- --------------------------------------------------------
--
-- 表的结构 `groups`
--
CREATE TABLE IF NOT EXISTS `groups` (
`groupid` int(11) NOT NULL AUTO_INCREMENT,
`groupname` varchar(36) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`founder` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`description` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
`timeFound` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`groupid`),
UNIQUE KEY `groupname` (`groupname`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;
--
-- 转存表中的数据 `groups`
--
INSERT INTO `groups` (`groupid`, `groupname`, `founder`, `description`, `timeFound`) VALUES
(1, 'UIR', 'nirvxyj', 'university of international relations', '2011-12-19 06:41:41');
-- --------------------------------------------------------
--
-- 表的结构 `relgroup`
--
CREATE TABLE IF NOT EXISTS `relgroup` (
`user` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`groupjoin` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- 转存表中的数据 `relgroup`
--
INSERT INTO `relgroup` (`user`, `groupjoin`) VALUES
('5', '1'),
('24', '1');
-- --------------------------------------------------------
--
-- 表的结构 `relusers`
--
CREATE TABLE IF NOT EXISTS `relusers` (
`follower` varchar(50) NOT NULL,
`target` varchar(50) NOT NULL,
`status` varchar(20) NOT NULL DEFAULT 'noAction'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- 转存表中的数据 `relusers`
--
INSERT INTO `relusers` (`follower`, `target`, `status`) VALUES
('25', '24', 'noAction'),
('24', '25', 'noAction');
-- --------------------------------------------------------
--
-- 表的结构 `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`password` varchar(32) NOT NULL,
`realname` varchar(50) NOT NULL,
`email` varchar(255) NOT NULL,
`address` varchar(255) DEFAULT NULL,
`city` varchar(50) DEFAULT NULL,
`country` varchar(80) DEFAULT NULL,
`mobileHome` varchar(11) DEFAULT NULL,
`mobileWork` varchar(11) DEFAULT NULL,
`description` varchar(255) DEFAULT NULL,
`timeLastLogin` varchar(255) DEFAULT NULL,
`timeReg` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=26 ;
--
-- 转存表中的数据 `users`
--
INSERT INTO `users` (`id`, `username`, `password`, `realname`, `email`, `address`, `city`, `country`, `mobileHome`, `mobileWork`, `description`, `timeLastLogin`, `timeReg`) VALUES
(5, 'nirvxyj', '9d5576841ea29220a18f5cc86580726f', '', '<EMAIL>', NULL, NULL, NULL, '15921425025', NULL, NULL, '2011-12-23 12:04:57', '2011-12-23 04:04:57'),
(24, 'remoo', '9d5576841ea29220a18f5cc86580726f', '阮默', '<EMAIL>', '宣武区某某小区23号3838室', '北京', '中国', '15921426537', '15921426537', '贱人', '2011-12-26 15:56:56', '2011-12-26 07:56:56'),
(25, 'dosurprise', '9d5576841ea29220a18f5cc86580726f', '薛源晶', '<EMAIL>', '松江区泗泾镇江川一村57号301', '上海', '中国', '15921425025', '15921425025', '前端开发天才', '2011-12-26 16:06:28', '2011-12-26 08:06:28');
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/application/Bootstrap.php
<?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initView()
{
// Initialize view
$view = new Zend_View();
$view->doctype('XHTML1_STRICT');
$view->headTitle('My First Zend Framework Application');
$view->headScript()->appendFile('/js/require-jquery.js','text/javascript');
// Add it to the ViewRenderer
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper(
'ViewRenderer'
);
$viewRenderer->setView($view);
// Return it, so that it can be stored by the bootstrap
return $view;
}
protected function _initAutoload()
{
define(APPLICATION_PATH, "http://dosurprise.phpfogapp.com/public/");
$moduleLoader = new Zend_Application_Module_Autoloader(array(
'namespace' => '',
'basePath' => APPLICATION_PATH."/public"));
return $moduleLoader;
}
}
<file_sep>/application/models/Users.php
<?php
class Users extends Zend_Db_Table_Abstract{
protected $_name='users';
public function checkUnique($username){
$select = $this->_db->select()->from($this->_name,array('username'))-> where ('username=?',$username);
$result = $this->getAdapter()->fetchOne($select);
if($result){
return true;
}
return false;
}
public function addUser($array){
$this->getAdapter()->insert($this->_name, $array);
}
public function updateUser($array,$username){
$this->getAdapter()->update($this->_name, $array,'id='.$this->getUserId($username));
}
public function setLoginTime($username){
$curr=array('timeLastLogin'=>Date('Y-m-d H:i:s'));
$this->getAdapter()->update($this->_name, $curr,'username="'.$username.'"');
}
public function getUserId($username){
$select = $this->_db->select()->from($this->_name,array('id'))-> where ('username=?',$username);
$result = $this->getAdapter()->fetchOne($select);
if($result){
return $result;
}
return false;
}
public function getUserInfo($id){
$select = $this->_db->select()->from($this->_name)-> where ('id=?',$id);
$result = $this->getAdapter()->fetchRow($select);
if($result){
return $result;
}
return false;
}
}
class UserRelations extends Zend_Db_Table_Abstract{
protected $_name='relusers';
public function checkRequest($follower,$target){
$select = $this->_db->select()->from($this->_name)-> where ('follower='.$follower.' and target='.$target);
$result = $this->getAdapter()->fetchOne($select);
if($result){
return true;
}
return false;
}
public function addRelation($follower,$target){
if($follower===$target){$message='you cant exchange contacts with yourself';}
else if(!$this->checkRequest($follower, $target)){
$this->getAdapter()->insert($this->_name,array("follower"=>$follower,"target"=>$target));
$message='successfully send the request';
}
else{$message='you have already send the request';}
return $message;
}
public function getRelations($relation,$userid){
$selectArea=($relation==='target')?'follower':'target';
$result = $this->_db->fetchAll("select users.id,users.username,relusers.status from users left join relusers on relusers.".$relation."=users.id where ".$selectArea."=".$userid);
if($result){
return $result;
}
return false;
}
public function getFriends($userid){
$result = $this->_db->fetchAll("select id,username from users where id in (select a.target from relusers a inner join relusers b where a.follower=".$userid." and a.follower = b.target and b.follower = a.target and a.status='agreed' and b.status='agreed')");
if($result){
return $result;
}
return false;
}
public function processRequest($requester,$target,$action){
$request=($action==='1')?'agreed':'denied';
$this->_db->update($this->_name, array('status'=>$request),"follower=".$requester." and target=".$target);
$name=$this->_db->fetchOne('select username from users where id='.$target);
$msg='you have successfully '.$request.' '.$name."'s request.";
return $msg;
}
public function deleteRequest($requester,$target){
$this->_db->delete($this->_name,"follower=".$requester." and target=".$target);
$name=$this->_db->fetchOne('select username from users where id='.$target);
$msg='you have successfully deleted '.$name."'s request.";
return $msg;
}
}<file_sep>/application/controllers/GroupController.php
<?php
require_once '../application/forms/addGroupForm.php';
require_once '../application/models/Groups.php';
class GroupController extends Zend_Controller_Action {
public function addAction(){
$storage = new Zend_Auth_Storage_Session ( );
$data = $storage->read (); if (! $data) {
$this->_redirect ( 'auth/login' );
}
$group = new Groups ( );
$form = new addGroupForm ( );
$this->view->form=$form;
if ($this->getRequest ()->isPost ()) {
if ($form->isValid ( $_POST )) {
$dataForm = $form->getValues ();
if ($group->checkUnique ( $dataForm ['groupname'] )) {
$this->view->errorMessage = "Name already taken."; return;
}
$group->addGroup($dataForm);
$this->_redirect ( 'group/index' );
}
}
}
public function displayAction(){
$storage = new Zend_Auth_Storage_Session ( );
$data = $storage->read (); if (! $data) { $this->_redirect ( 'auth/login' ); }
$this->view->username = $data->username;
$request = new Zend_Controller_Request_Http();
$front = Zend_Controller_Front::getInstance();
$front->getRouter()->route($request);
$params = $request->getParams();
$group = new Groups ( );
$result=$group->getGroupInfo($params['groupid']);
if($result){
$this->view->info = $result;
}
$relgroup= new RelGroup();
$resUsers=$relgroup->getUserList($params['groupid']);
$this->view->users = $resUsers;
}
public function joinAction(){
$storage = new Zend_Auth_Storage_Session ( );
$data = $storage->read ();
if (!$data) {
$this->_redirect ( 'auth/login' );
}
$request = new Zend_Controller_Request_Http();
$front = Zend_Controller_Front::getInstance();
$front->getRouter()->route($request);
$params = $request->getParams();
$relgroup=new RelGroup();
$relgroup->joinGroup($data->id, $params['groupid']);
$this->_redirect ( 'group/display/groupid/'.$params['groupid'] );
}
}<file_sep>/application/controllers/IndexController.php
<?php
require_once '../application/models/Users.php';
class IndexController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
}
public function indexAction()
{
if ($this->_helper->getHelper('FlashMessenger')->getMessages()) {
$this->view->messages = $this->_helper
->getHelper('FlashMessenger')
->getMessages();
}
$storage = new Zend_Auth_Storage_Session ( );
$data = $storage->read (); if (! $data) { $this->_redirect ( 'auth/login' ); }
$this->view->username = $data->username;
$users=new UserRelations();
$followers=$users->getRelations('follower',$data->id);
$targets=$users->getRelations('target',$data->id);
$friends=$users->getFriends($data->id);
$this->view->relations = array('followers'=>$followers,'targets'=>$targets,'friends'=>$friends);
}
}
|
cd229f26155b0793f138b735dc20506d0dfc0935
|
[
"SQL",
"PHP"
] | 14 |
PHP
|
dosurprise/contacts
|
1691b75a584d1764ae57d85f78c8b16fd1bd2296
|
3a6b17e4acb5b6de2028a152de4e8f27eee31f59
|
refs/heads/master
|
<file_sep>using FizzWare.NBuilder;
using System;
using System.Linq;
using System.Runtime.InteropServices;
namespace GuidPKTest.Models
{
internal class DataGenerator
{
public static TestTable<int>[] GetTestTableWithIntPK(int listSize = 10_000)
{
return Builder<TestTable<int>>.CreateListOfSize(listSize)
.All()
.With(x => x.Id = 0)
.With(x => x.Prop_d1 = DateTimeOffset.Now)
.With(x => x.Prop_d2 = DateTimeOffset.Now)
.With(x => x.Prop_d3 = DateTimeOffset.Now)
.Build()
.ToArray();
}
public static TestTable<Guid>[] GetTestTableWithGuidPK(int listSize = 10_000)
{
return Builder<TestTable<Guid>>.CreateListOfSize(listSize)
.All()
.With(x => x.Id = NewSequentialId())
.With(x => x.Prop_d1 = DateTimeOffset.Now)
.With(x => x.Prop_d2 = DateTimeOffset.Now)
.With(x => x.Prop_d3 = DateTimeOffset.Now)
.Build()
.ToArray();
}
public static TestTable_ClusterId[] GetTestTable_ClusterId(int listSize = 10_000)
{
return Builder<TestTable_ClusterId>.CreateListOfSize(listSize)
.All()
.With(x => x.Prop_d1 = DateTimeOffset.Now)
.With(x => x.Prop_d2 = DateTimeOffset.Now)
.With(x => x.Prop_d3 = DateTimeOffset.Now)
.With(x => x.ClusterId = 0)
.With(x => x.Id = NewSequentialId())
.Build()
.ToArray();
}
public static TestTable_ExtraGuid[] GetTestTable_ExtraGuid(int listSize = 10_000)
{
return Builder<TestTable_ExtraGuid>.CreateListOfSize(listSize)
.All()
.With(x => x.Prop_d1 = DateTimeOffset.Now)
.With(x => x.Prop_d2 = DateTimeOffset.Now)
.With(x => x.Prop_d3 = DateTimeOffset.Now)
.With(x => x.Id = 0)
.With(x => x.ExtraGuid = Guid.NewGuid())
.Build()
.ToArray();
}
[DllImport("rpcrt4.dll", SetLastError = true)]
static extern int UuidCreateSequential(out Guid guid);
private static Guid NewSequentialId()
{
Guid guid;
UuidCreateSequential(out guid);
var s = guid.ToByteArray();
var t = new byte[16];
t[3] = s[0];
t[2] = s[1];
t[1] = s[2];
t[0] = s[3];
t[5] = s[4];
t[4] = s[5];
t[7] = s[6];
t[6] = s[7];
t[8] = s[8];
t[9] = s[9];
t[10] = s[10];
t[11] = s[11];
t[12] = s[12];
t[13] = s[13];
t[14] = s[14];
t[15] = s[15];
return new Guid(t);
}
}
}
<file_sep>using System;
using System.Data.SqlClient;
namespace GuidPKTest.Models
{
/// <summary>
/// Guid ID, non clustered, plus clustered int autoinc
/// </summary>
public class TestTable_ClusterId : TestTable<Guid>
{
public int ClusterId { get; set; }
public static void CreateTableWithGuidPKAndClusterId (string connString)
{
var sql = @"
CREATE TABLE [dbo].[TestTable_guidPk_ClusterId](
[Id] [uniqueidentifier] NOT NULL,
[Prop_s1] [nvarchar](max) NULL,
[Prop_s2] [nvarchar](max) NULL,
[Prop_s3] [nvarchar](max) NULL,
[Prop_s4] [nvarchar](max) NULL,
[Prop_n1] [bigint] NULL,
[Prop_n2] [decimal](18, 2) NULL,
[Prop_s5] [nvarchar](max) NULL,
[Prop_d1] [datetimeoffset](7) NOT NULL,
[Prop_d2] [datetimeoffset](7) NOT NULL,
[Prop_s6] [nvarchar](max) NULL,
[Prop_s7] [nvarchar](max) NULL,
[Prop_n5] [int] NULL,
[Prop_s8] [nvarchar](max) NULL,
[Prop_n6] [int] NULL,
[Prop_s9] [nvarchar](max) NULL,
[Prop_n4] [decimal](18, 2) NULL,
[Prop_d3] [datetimeoffset](7) NULL,
[Prop_b1] [bit] NULL,
[Prop_b2] [bit] NOT NULL,
[Prop_b3] [bit] NULL,
[Prop_n3] [decimal](18, 2) NULL,
[ClusterId] [int] IDENTITY(1,1) NOT NULL,
PRIMARY KEY NONCLUSTERED
(
[Id] ASC
))";
using (var conn = new SqlConnection(connString))
{
conn.Open();
using (var command = new SqlCommand())
{
command.Connection = conn;
try {
command.CommandText = "DROP TABLE TestTable_guidPk_ClusterId";
command.ExecuteNonQuery();
}
catch { }
command.CommandText = sql;
command.ExecuteNonQuery();
}
}
}
}
}
<file_sep>using GuidPKTest.Models;
using System;
namespace GuidPKTest
{
class Program
{
static void Main(string[] args)
{
var connString = "Server=localhost;Database=POC;User Id=user;Password=<PASSWORD>;";
TestTable<int>.CreateTableWithGuidPK(connString);
TestTable<int>.CreateTableWithIntIdentityPK(connString);
TestTable_ClusterId.CreateTableWithGuidPKAndClusterId(connString);
TestTable_ExtraGuid.CreateTableWithIntIdentityPkAndExtraGuidField(connString);
Console.WriteLine("Created tables");
var metrics = new Metrics(connString);
metrics.TestTables_intPK(); // base line. Int identity PK
metrics.TestTables_ExtraGuid(); // int identity PK, expecting to be as fast as int_PK. Actual - a bit slower
metrics.TestTables_GuidPK(); // GUID PK, expecting to be somewhat slower. Actual - ~60 times slower.
metrics.TestTables_GuidPK_ClusterId(); // GUID non-clustered PK and clusterd identity column. Expecting to be faster than clustered guid PK. Actual - a bit faster than GUID PK.
Console.WriteLine("Done");
Console.ReadLine();
}
}
}
<file_sep>using System;
using System.Data.SqlClient;
namespace GuidPKTest.Models
{
/// <summary>
/// Int id
/// </summary>
public class TestTable<TPk>
{
public TPk Id { get; set; }
public string Prop_s1 { get; set; }
public string Prop_s2 { get; set; }
public string Prop_s3 { get; set; }
public string Prop_s4 { get; set; }
public string Prop_s5 { get; set; }
public string Prop_s6 { get; set; }
public string Prop_s7 { get; set; }
public string Prop_s8 { get; set; }
public string Prop_s9 { get; set; }
public long? Prop_n1 { get; set; }
public decimal? Prop_n2 { get; set; }
public decimal? Prop_n3 { get; set; }
public decimal? Prop_n4 { get; set; }
public int? Prop_n5 { get; set; }
public int? Prop_n6 { get; set; }
public DateTimeOffset Prop_d1 { get; set; }
public DateTimeOffset Prop_d2 { get; set; }
public DateTimeOffset? Prop_d3 { get; set; }
public bool? Prop_b1 { get; set; }
public bool Prop_b2 { get; set; }
public bool? Prop_b3 { get; set; }
public static void CreateTableWithIntIdentityPK(string connString)
{
var sql = @"
CREATE TABLE [dbo].[TestTable_intPk](
[Id] [int] IDENTITY(1,1) PRIMARY KEY,
[Prop_s1] [nvarchar](max) NULL,
[Prop_s2] [nvarchar](max) NULL,
[Prop_s3] [nvarchar](max) NULL,
[Prop_s4] [nvarchar](max) NULL,
[Prop_n1] [bigint] NULL,
[Prop_n2] [decimal](18, 2) NULL,
[Prop_s5] [nvarchar](max) NULL,
[Prop_d1] [datetimeoffset](7) NOT NULL,
[Prop_d2] [datetimeoffset](7) NOT NULL,
[Prop_s6] [nvarchar](max) NULL,
[Prop_s7] [nvarchar](max) NULL,
[Prop_n5] [int] NULL,
[Prop_s8] [nvarchar](max) NULL,
[Prop_n6] [int] NULL,
[Prop_s9] [nvarchar](max) NULL,
[Prop_n4] [decimal](18, 2) NULL,
[Prop_d3] [datetimeoffset](7) NULL,
[Prop_b1] [bit] NULL,
[Prop_b2] [bit] NOT NULL,
[Prop_b3] [bit] NULL,
[Prop_n3] [decimal](18, 2) NULL,
)";
using (var conn = new SqlConnection(connString))
{
conn.Open();
using (var command = new SqlCommand())
{
command.Connection = conn;
try
{
command.CommandText = "DROP TABLE TestTable_intPk";
command.ExecuteNonQuery();
}
catch { }
command.CommandText = sql;
command.ExecuteNonQuery();
}
}
}
public static void CreateTableWithGuidPK(string connString)
{
var sql = @"
CREATE TABLE [dbo].[TestTable_guidPk](
[Id] [uniqueidentifier] NOT NULL,
[Prop_s1] [nvarchar](max) NULL,
[Prop_s2] [nvarchar](max) NULL,
[Prop_s3] [nvarchar](max) NULL,
[Prop_s4] [nvarchar](max) NULL,
[Prop_n1] [bigint] NULL,
[Prop_n2] [decimal](18, 2) NULL,
[Prop_s5] [nvarchar](max) NULL,
[Prop_d1] [datetimeoffset](7) NOT NULL,
[Prop_d2] [datetimeoffset](7) NOT NULL,
[Prop_s6] [nvarchar](max) NULL,
[Prop_s7] [nvarchar](max) NULL,
[Prop_n5] [int] NULL,
[Prop_s8] [nvarchar](max) NULL,
[Prop_n6] [int] NULL,
[Prop_s9] [nvarchar](max) NULL,
[Prop_n4] [decimal](18, 2) NULL,
[Prop_d3] [datetimeoffset](7) NULL,
[Prop_b1] [bit] NULL,
[Prop_b2] [bit] NOT NULL,
[Prop_b3] [bit] NULL,
[Prop_n3] [decimal](18, 2) NULL,
PRIMARY KEY CLUSTERED
(
[Id] ASC
))";
using (var conn = new SqlConnection(connString))
{
conn.Open();
using (var command = new SqlCommand())
{
command.Connection = conn;
try {
command.CommandText = "DROP TABLE TestTable_guidPk";
command.ExecuteNonQuery();
}
catch { }
command.CommandText = sql;
command.ExecuteNonQuery();
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
namespace GuidPKTest.Models
{
internal class Metrics
{
private readonly string connectionString;
public Metrics(string connectionString)
{
this.connectionString = connectionString;
}
public void TestTables_intPK()
{
var sw = new Stopwatch();
var ttInt = DataGenerator.GetTestTableWithIntPK();
var insert = @"
INSERT INTO [dbo].[TestTable_intPk]
([Prop_s9],[Prop_s8],[Prop_s7],[Prop_s6],[Prop_s5],[Prop_s4],[Prop_s3]
,[Prop_s2],[Prop_s1],[Prop_n6],[Prop_n5],[Prop_n4],[Prop_n3],[Prop_n2]
,[Prop_n1],[Prop_d3],[Prop_d2],[Prop_d1],[Prop_b3],[Prop_b2],[Prop_b1])";
var selects = ttInt.Select(x => $@"SELECT '{x.Prop_s9}','{x.Prop_s8}','{x.Prop_s7}','{x.Prop_s6}','{x.Prop_s5}','{x.Prop_s4}','{x.Prop_s3}',
'{x.Prop_s2}','{x.Prop_s1}',{x.Prop_n6},{x.Prop_n5},{x.Prop_n4},{x.Prop_n3},{x.Prop_n2},
{x.Prop_n1},'{x.Prop_d3}','{x.Prop_d2}','{x.Prop_d1}',{(x.Prop_b3.GetValueOrDefault() ? 1 : 0)},{(x.Prop_b2 ? 1 : 0)},{(x.Prop_b1.GetValueOrDefault() ? 1 : 0)}")
.ToArray();
var sql = insert + Environment.NewLine + string.Join(Environment.NewLine + " UNION ALL " + Environment.NewLine, selects);
// same query 10 times
var sqls = Enumerable.Range(1, 10).Select(x => sql).ToArray();
this.TimeQueryExecution(sqls);
}
public void TestTables_ExtraGuid()
{
Console.WriteLine("TestTables_ExtraGuid");
var sw = new Stopwatch();
var ttInt = DataGenerator.GetTestTable_ExtraGuid();
var insert = @"
INSERT INTO [dbo].[TestTable_extraGuid]
([Prop_s9],[Prop_s8],[Prop_s7],[Prop_s6],[Prop_s5],[Prop_s4],[Prop_s3]
,[Prop_s2],[Prop_s1],[Prop_n6],[Prop_n5],[Prop_n4],[Prop_n3],[Prop_n2]
,[Prop_n1],[Prop_d3],[Prop_d2],[Prop_d1],[Prop_b3],[Prop_b2],[Prop_b1], ExtraGuid)";
var selects = ttInt.Select(x => $@"SELECT '{x.Prop_s9}','{x.Prop_s8}','{x.Prop_s7}','{x.Prop_s6}','{x.Prop_s5}','{x.Prop_s4}','{x.Prop_s3}',
'{x.Prop_s2}','{x.Prop_s1}',{x.Prop_n6},{x.Prop_n5},{x.Prop_n4},{x.Prop_n3},{x.Prop_n2},
{x.Prop_n1},'{x.Prop_d3}','{x.Prop_d2}','{x.Prop_d1}',{(x.Prop_b3.GetValueOrDefault() ? 1 : 0)},{(x.Prop_b2 ? 1 : 0)},
{(x.Prop_b1.GetValueOrDefault() ? 1 : 0)},'{x.ExtraGuid}'")
.ToArray();
var sql = insert + Environment.NewLine + string.Join(Environment.NewLine + " UNION ALL " + Environment.NewLine, selects);
// same query 10 times
var sqls = Enumerable.Range(1, 10).Select(x => sql).ToArray();
this.TimeQueryExecution(sqls);
}
public void TestTables_GuidPK()
{
Console.WriteLine("TestTables_GuidPK");
var sw = new Stopwatch();
var sqls = new List<string>();
for (int i = 0; i < 10; i++)
{
var ttInt = DataGenerator.GetTestTableWithGuidPK();
var insert = @"
INSERT INTO [dbo].[TestTable_guidPk]
(Id,[Prop_s9],[Prop_s8],[Prop_s7],[Prop_s6],[Prop_s5],[Prop_s4],[Prop_s3]
,[Prop_s2],[Prop_s1],[Prop_n6],[Prop_n5],[Prop_n4],[Prop_n3],[Prop_n2]
,[Prop_n1],[Prop_d3],[Prop_d2],[Prop_d1],[Prop_b3],[Prop_b2],[Prop_b1])";
var selects = ttInt.Select(x => $@"SELECT '{x.Id}', '{x.Prop_s9}','{x.Prop_s8}','{x.Prop_s7}','{x.Prop_s6}','{x.Prop_s5}','{x.Prop_s4}','{x.Prop_s3}',
'{x.Prop_s2}','{x.Prop_s1}',{x.Prop_n6},{x.Prop_n5},{x.Prop_n4},{x.Prop_n3},{x.Prop_n2},
{x.Prop_n1},'{x.Prop_d3}','{x.Prop_d2}','{x.Prop_d1}',{(x.Prop_b3.GetValueOrDefault() ? 1 : 0)},{(x.Prop_b2 ? 1 : 0)},
{(x.Prop_b1.GetValueOrDefault() ? 1 : 0)}")
.ToArray();
var sql = insert + Environment.NewLine + string.Join(Environment.NewLine + " UNION ALL " + Environment.NewLine, selects);
sqls.Add(sql);
}
this.TimeQueryExecution(sqls.ToArray());
}
public void TestTables_GuidPK_ClusterId()
{
Console.WriteLine("TestTables_GuidPK_ClusterId");
var sw = new Stopwatch();
var sqls = new List<string>();
for (int i = 0; i < 10; i++)
{
var ttInt = DataGenerator.GetTestTable_ClusterId();
var insert = @"
INSERT INTO [dbo].[TestTable_guidPk_ClusterId]
(Id,[Prop_s9],[Prop_s8],[Prop_s7],[Prop_s6],[Prop_s5],[Prop_s4],[Prop_s3]
,[Prop_s2],[Prop_s1],[Prop_n6],[Prop_n5],[Prop_n4],[Prop_n3],[Prop_n2]
,[Prop_n1],[Prop_d3],[Prop_d2],[Prop_d1],[Prop_b3],[Prop_b2],[Prop_b1])";
var selects = ttInt.Select(x => $@"SELECT '{x.Id}', '{x.Prop_s9}','{x.Prop_s8}','{x.Prop_s7}','{x.Prop_s6}','{x.Prop_s5}','{x.Prop_s4}','{x.Prop_s3}',
'{x.Prop_s2}','{x.Prop_s1}',{x.Prop_n6},{x.Prop_n5},{x.Prop_n4},{x.Prop_n3},{x.Prop_n2},
{x.Prop_n1},'{x.Prop_d3}','{x.Prop_d2}','{x.Prop_d1}',{(x.Prop_b3.GetValueOrDefault() ? 1 : 0)},{(x.Prop_b2 ? 1 : 0)},
{(x.Prop_b1.GetValueOrDefault() ? 1 : 0)}")
.ToArray();
var sql = insert + Environment.NewLine + string.Join(Environment.NewLine + " UNION ALL " + Environment.NewLine, selects);
sqls.Add(sql);
}
this.TimeQueryExecution(sqls.ToArray());
}
private TimeSpan TimeQueryExecution(string[] sqls)
{
var sw = Stopwatch.StartNew();
using (var conn = new SqlConnection(this.connectionString)) // using same connection
{
conn.Open();
for (int i = 0; i < sqls.Length; i++)
{
var sw2 = Stopwatch.StartNew();
using (var command = new SqlCommand(sqls[i], conn))
{
command.CommandTimeout = 60_000;
command.ExecuteNonQuery();
}
Console.WriteLine($" Executed insert {i} in {sw2.ElapsedMilliseconds}ms");
}
}
sw.Stop();
Console.WriteLine($"Stored 10k in {sw.ElapsedMilliseconds / 10}ms per 10k");
return sw.Elapsed;
}
}
}
|
8c8efd8d768f97e9978c5f51f4717fb37c75aa90
|
[
"C#"
] | 5 |
C#
|
Thinkhoop/SqlServerGuidPKPOC
|
69fbbe07ce611c3202fae4a4ad52c0c0374704ab
|
a25b0de9533c71d930c192cc744f438911ac8a5f
|
refs/heads/master
|
<repo_name>jisbruzzi/loconozco<file_sep>/js6/Instrucciones.js
import ReactDOM from 'react-dom';
import React from 'react';
export class Instrucciones extends React.Component{
constructor(props){
super(props);
this.state={
address:""
}
fetch("/address").then(r => r.text()).then( address =>this.setState({address}));
}
render(){
return <span>hola, conectate entrando a https://{this.state.address}</span>
}
}<file_sep>/js6/Grafico.js
import ReactDOM from 'react-dom';
import React from 'react';
let audioStreamPromise=navigator.mediaDevices.getUserMedia({audio: true, video:false})
const TAMANIO_GRAFICO=20
export function Graficador(props){
function promediosPorVentana(datos,cantidad){
let ret=[];
for(let b=0;b<cantidad;b++){
let semiLargo=Math.floor(datos.length/cantidad);
let suma=0;
let q=0;
for(let i=b*semiLargo;i<(b+1)*semiLargo;i++){
suma+=0.0+datos[i];
q++;
}
ret.push(suma/q);
}
return ret;
}
function desviacionesPorVentana(datos,cantidad){
let ret=[];
for(let b=0;b<cantidad;b++){
let semiLargo=Math.floor(datos.length/cantidad);
let suma=0;
let q=0;
for(let i=b*semiLargo;i<(b+1)*semiLargo;i++){
suma+=0.0+datos[i];
q++;
}
let promedio = suma/q;
let sumaDifs=0;
for(let i=b*semiLargo;i<(b+1)*semiLargo;i++){
sumaDifs+=(datos[i]-promedio)*(datos[i]-promedio);
}
ret.push(Math.sqrt(sumaDifs/q));
}
return ret;
}
let canvas=document.getElementById("canvas");
if(canvas==null) return <span></span>;
let ctx=canvas.getContext("2d");
let dataArray = props.datos;
ctx.fillStyle="blue";
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillRect(0,0,TAMANIO_GRAFICO,TAMANIO_GRAFICO);
ctx.strokeStyle="black";
ctx.beginPath();
ctx.moveTo(0,TAMANIO_GRAFICO);
for(let i=0;i<dataArray.length;i++){
ctx.lineTo(i/dataArray.length*TAMANIO_GRAFICO,TAMANIO_GRAFICO-dataArray[i]/256*TAMANIO_GRAFICO);
}
ctx.stroke();
ctx.strokeStyle="red";
ctx.beginPath();
ctx.moveTo(0,TAMANIO_GRAFICO);
let promedios=promediosPorVentana(dataArray,20)
for(let i=0;i<promedios.length;i++){
ctx.lineTo(i/promedios.length*TAMANIO_GRAFICO,TAMANIO_GRAFICO-promedios[i]/256*TAMANIO_GRAFICO);
}
ctx.stroke();
ctx.strokeStyle="green";
ctx.beginPath();
ctx.moveTo(0,TAMANIO_GRAFICO);
let desviaciones=desviacionesPorVentana(dataArray,20)
for(let i=0;i<desviaciones.length;i++){
ctx.lineTo(i/desviaciones.length*TAMANIO_GRAFICO,TAMANIO_GRAFICO-(promedios[i]+2.5*desviaciones[i])/256*TAMANIO_GRAFICO);
}
ctx.stroke();
return <span></span>
}<file_sep>/js6/EscuchaFrecuencia.js
import ReactDOM from 'react-dom';
import React from 'react';
export function EscuchaFrecuencia(props){
let banda=Math.ceil(props.frecuencia/props.sampleRate*props.fftSize);
let dataArray=props.datos;
let valor=dataArray[banda];
let valorCoeficiente=Array.from(Array(100).keys())
.map((v,i,a)=>Math.floor(i-a.length/2))//de -20 a 20
.filter((v)=>v!=0)//sin 0
.map( (v,i,a) => [v+banda,v/(a.length/2)])//de banda-20 a banda+20, de -1 a 1
.map( v => [v[0],1/Math.sqrt(2*Math.PI)*Math.exp(-0.5*v[1]*v[1])])//agrego la distribución en el segundo item
.filter((v)=>v[0]>=0 && v[0]<dataArray.length)//filtro los externos
.map((v)=>[dataArray[v[0]],v[1]]);//agrego el valor en el primer item
let sumaCoeficientes=valorCoeficiente
.map((v)=>v[1])
.reduce((a,b)=>a+b,0);
let promedioPonderado=valorCoeficiente
.map((v)=>v[0]*v[1]/sumaCoeficientes)
.reduce((a,b)=>a+b,0);
let asd=Array.from(Array(100).keys())
.map((v,i,a)=>Math.floor(i-a.length/2))//de -20 a 20
if(valor>1.5*promedioPonderado && valor>5){
props.callback();
return <li>Estoy escuchando a {props.nombre} ({props.puntaje})</li>
}else{
return <li> No escucho a {props.nombre} ({props.puntaje})</li>
}
}<file_sep>/js6/CambiaVolumen.js
import ReactDOM from 'react-dom';
import React from 'react';
export function CambiaVolumen(props){
let actual=props.volumen;
function haceCallback(q){
return function(e){
props.callback(actual+q);
}
}
return <div style={{
width:"100vw",
height:"25vw",
display:"flex",
flexDirection:"row",
justifyContent:"space-around",
alignItems:"center"
}}>
<button
style={{width:"20vw",height:"20vw"}}
onClick={haceCallback(-0.01)}
>--</button>
<button
style={{width:"20vw",height:"20vw"}}
onClick={haceCallback(-0.001)}
>-</button>
<span>{actual.toFixed(3)}</span>
<button
style={{width:"20vw",height:"20vw"}}
onClick={haceCallback(0.001)}
>+</button>
<button
style={{width:"20vw",height:"20vw"}}
onClick={haceCallback(0.01)}
>++</button>
</div>
}<file_sep>/server.js
const express = require("express");
const fs = require('fs');
const https = require('https');
const options = {
cert: fs.readFileSync("./rootCA.pem"),
key: fs.readFileSync("./rootCA.key")
};
const app=express();
app.use("/",express.static("./"));
//app.get('/', (req, res) => res.send('Hello World!'))
let server = https.createServer(options,app)
server.listen(3030,()=>console.log("listening!"));
let io=require("socket.io")(server);
function sacarCualquiera(array){
let i=Math.floor(Math.random()*array.length);
let elem=array[i];
array.splice(i,1);
return {array,e:elem};
}
console.log(sacarCualquiera([1]))
console.log(sacarCualquiera([1,2]))
console.log(sacarCualquiera([1,2,3]))
let descriptores={};
function reasignar(){
console.log("REASIGNANDO")
let noAsignados=Object.keys(descriptores);
while(noAsignados.length>1){
console.log("NoAsignados1:",noAsignados)
let o1=sacarCualquiera(noAsignados)
noAsignados=o1.array;
console.log("NoAsignados2:",noAsignados)
let o2=sacarCualquiera(noAsignados)
noAsignados=o2.array;
console.log("NoAsignados3:",noAsignados)
descriptores[o1.e].pareja=o2.e;
descriptores[o2.e].pareja=o1.e;
console.log("descriptores:",descriptores)
}
}
let sockets=[];
io.on("connection",function(socket){
console.log("SE CONECTO ALGIUEN WTF");
sockets.push(socket);
let nombre="";
setInterval(()=>{
enviarCambios();
},5000)
socket.on("hola",(m)=>{
nombre=m.nombre;
console.log("Se conecto uno y me mando el hola")
console.log(m);
let frecuencia=Math.random()*3000+5000;
socket.emit("bienvenida",{nombre,frecuencia})
descriptores[nombre]={frecuencia,puntaje:0,pareja:null,escuchaDesconocido:0};
enviarCambios();
});
socket.on("pantalla",(m)=>{
enviarCambios();
})
socket.on("empezar",(m)=>{
console.log("Empiezo")
reasignar();
enviarCambios();
})
socket.on("escuchoDesconocido",(m)=>{
if(! descriptores[nombre]) return;
let desconocido=descriptores[nombre].pareja;
if(!descriptores[desconocido]) return;
if(descriptores[nombre].pareja===m){
console.log(nombre," escucha a su desconocido!")
descriptores[nombre].escuchaDesconocido=Date.now();
let diferencia = descriptores[nombre].escuchaDesconocido - descriptores[m].escuchaDesconocido;
if(diferencia<500){
descriptores[nombre].puntaje+=1;
descriptores[m].puntaje+=1;
for(let n in descriptores){
descriptores[n].pareja="nadie";
}
enviarCambios();
setTimeout(()=>{
reasignar();
enviarCambios();
},3000)
}
}
})
console.log(descriptores);
socket.on("disconnect",()=>{
delete descriptores[nombre];
console.log(descriptores);
enviarCambios();
})
})
function enviarCambios(socket){
let cambios = Object.keys(descriptores).map((k)=>{
return {
nombre:k,
frecuencia:descriptores[k].frecuencia,
puntaje:descriptores[k].puntaje,
pareja:descriptores[k].pareja
}
})
for(let s of sockets){
s.emit(
"cambios",
cambios
)
}
console.log("envie los cambios",cambios)
}
require("./myHost")(app)<file_sep>/myHost.js
const interfaces=require("os").networkInterfaces();
module.exports=function(app){
app.get("/address",(req,res)=>{
console.log("Me piden las interfaces");
console.log(interfaces);
for(interface in interfaces){
let currentInterface=interfaces[interface];
console.log("!!!!!!!!!!!!!")
console.log(currentInterface);
for(let current of currentInterface){
console.log("**********")
console.log(current)
if(!current.internal && current.family=="IPv4"){
if(( current.netmask.match(/255/g) || []).length==3){
console.log("ENVIO:")
console.log(current.address);
res.send(current.address+":3030");
}
}
}
}
})
}<file_sep>/gulpfile.js
var argv = require('yargs').argv;
var gulpif = require('gulp-if');
var gulp = require('gulp');
var browserify = require('browserify'); //
var babelify = require('babelify');
var source = require('vinyl-source-stream');
var uglify = require('gulp-uglify');
var buffer = require('vinyl-buffer');
/**
* Build an output file. Babelify is used to transform 'jsx' code to JavaScript code.
**/
gulp.task("build-react", function(){
var options = {
entries: "./js6/main.js", // Entry point
extensions: [".js"], // consider files with these extensions as modules
debug: argv.production ? false : true, // add resource map at the end of the file or not
paths: ["./js6/"] // This allows relative imports in require, with './scripts/' as root
};
var options2 = {
entries: "./js6/mainPantalla.js", // Entry point
extensions: [".js"], // consider files with these extensions as modules
debug: argv.production ? false : true, // add resource map at the end of the file or not
paths: ["./js6/"] // This allows relative imports in require, with './scripts/' as root
};
return Promise.all([
browserify(options)
.transform(babelify)
.bundle()
.pipe(source("main.min.js"))
.pipe(gulpif(argv.production, buffer())) // Stream files
.pipe(gulpif(argv.production, uglify()))
.pipe(gulp.dest("./js")),
browserify(options2)
.transform(babelify)
.bundle()
.pipe(source("mainPantalla.min.js"))
.pipe(gulpif(argv.production, buffer())) // Stream files
.pipe(gulpif(argv.production, uglify()))
.pipe(gulp.dest("./js"))
])
});
<file_sep>/js6/IngresaNombre.js
import ReactDOM from 'react-dom';
import React from 'react';
export class IngresaNombre extends React.Component{
constructor(props){
super(props);
this.state={
nombre:""
}
}
render(){
return <div>
Tu nombre:
<input
type="text"
value={this.state.nombre}
onChange={this.onChange.bind(this)}
/>
<button
onClick={this.onSubmit.bind(this)}
>enviar</button>
</div>
}
onSubmit(){
this.props.callback(this.state.nombre);
}
onChange(e){
this.setState({nombre:e.target.value})
}
}<file_sep>/js6/ListaJugadores.js
import ReactDOM from 'react-dom';
import React from 'react';
export function ListaJugadores(props){
console.log(props.jugadores);
let itemsJugadores=props.jugadores.map((j)=>{
return <li key={j.nombre}>{j.nombre}</li>
})
console.log(itemsJugadores)
return <ul>
{itemsJugadores}
</ul>
}<file_sep>/js6/Pantalla.js
import ReactDOM from 'react-dom';
import React from 'react';
import {Instrucciones} from "./Instrucciones.js"
import {ListaJugadores} from "./ListaJugadores.js"
export class Pantalla extends React.Component{
constructor(props){
super(props);
this.state={
empezado:false,
jugadores:[]
}
let socket=io();
this.socket=socket;
socket.emit("pantalla")
socket.on("cambios",(args)=>{
console.log("LOS JUGADORES QUE TENGO SON:")
console.log(args);
this.setState({jugadores:args});
})
}
empezar(){
alert("Y empieza")
this.setState({empezado:true})
this.socket.emit("empezar")
}
render(){
return <div>
<Instrucciones/>
{!this.state.empezado?
<span>
<ListaJugadores jugadores={this.state.jugadores}/>
<button onClick={this.empezar.bind(this)}>Ya estamos todos:Empezar</button>
</span>:
<ListaJugadores jugadores={this.state.jugadores}/>
}
</div>
}
}
|
a92c1e128516e57b4ee200856198eeea9c6fb2eb
|
[
"JavaScript"
] | 10 |
JavaScript
|
jisbruzzi/loconozco
|
ac1ff5b2ccb97c05591c1c2d26b28f3c38b03120
|
a18aae76d8c7fb66662a930e0c4b1ed7ec33c12b
|
refs/heads/master
|
<repo_name>mdellagi77/Perfect-FCM-Server<file_sep>/Tests/LinuxMain.swift
import XCTest
@testable import Perfect_FCM_ServerTests
XCTMain([
testCase(Perfect_FCM_ServerTests.allTests),
])
<file_sep>/README.md
# Perfect FCM Server
## Summary
I have created this [Perfect](http://perfect.org/) package in order to send PUSH notification to iOS and Android devices threw the [Firebase Cloud Messaging](https://firebase.google.com/docs/cloud-messaging/) system.
## Compatibility with Swift
The master branch of this project currently compiles with **Xcode 9.2** or the **Swift 4.0** toolchain on Ubuntu.
## Building
Add this project as a dependency in your Package.swift file.
```
.package(url: "https://github.com/iMac0de/Perfect-FCM-Server.git", "1.0.0"..<"2.0.0")
```
## How to use it?
### Firebase Cloud Messaging server key
The first thing to do is to create a project on the [Firebase](https://firebase.google.com/) console in order to retrieve a server key.
### Config
In order to use the [Firebase](https://firebase.google.com/) API from your server side, you need to provide your server key to the Perfect FCM Server package.
```
let config = PerfectFCM.Config(serverKey: YOUR_SERVER_KEY)
```
### Send a notification
Once the Perfect FCM Server is configured, you should be able to send PUSH notification threw the Firebase Cloud Messaging system.
```
do {
try PerfectFCM.send(config, to: "A_FCM_DEVICE_TOKEN_OR_TOPIC", title: "YOUR_TITLE", body: "YOUR_BODY", data: ["CUSTOM_KEY": "CUSTOM_DATA"])
} catch {
print(error.localizedDescription)
}
```
It is possible to send the PUSH notification to a specific device by providing to the _to_ parameter the device token retrieved with a [Firebase client](https://firebase.google.com/docs/) or to a topic aka _/topics/daily-news_ where this topic send a PUSH notification each day to a group of devices for example.
### Store the device token
It is up to you to create the logic to store the device token once you get it. In my case, I generally create a REST API that allow me to POST some data about the devices and save them in a database. Here is my _Device_ class:
```
class Device {
var name: String
var token: String
var brand: String
var model: String
var os: String
var version: String
init() {
self.name = ""
self.token = ""
self.brand = ""
self.model = ""
self.os = ""
self.version = ""
}
init(name: String, token: String, brand: String, model: String, os: String, version: String) {
self.name = name
self.token = token
self.brand = brand
self.model = model
self.os = os
self.version = version
}
}
```
Then you can collect these data on your client device and store them to a [database](http://perfect.org/docs/databaseConnectors.html) of your choice.
You should know that a token is updated time-to-time for the same device. You should take that in account in order to be able to update the device in your database when the token has been changed.
## Test
If you want to test it, you can create the following script in a file (test.sh for exemple):
```
#!/bin/sh
export FCM_SERVER_KEY="YOUR_SERVER_KEY"
export FCM_DEVICE_TOKEN="YOUR_DEVICE_TOKEN"
swift test
```
Apply the execution right to the file:
```
chmod +x test.sh
```
And then run the script:
```
./test.sh
```
You should receive a PUSH notification to your device with the title "Hello world!" and the body "Perfect FCM PUSH notification!".
<file_sep>/Sources/Perfect-FCM-Server/PerfectFCM.swift
import Foundation
import cURL
import PerfectCURL
open class PerfectFCM {
open class Config {
var serverKey: String
public init(serverKey: String) {
self.serverKey = serverKey
}
}
public enum Exception: Error {
case UnknownHost
case InvalidHeader
case CannonConvertToJson
case CannotGetAccessToken
}
public static var debug = false
public class func prepare(_ config: Config) throws -> CURLRequest? {
if !config.serverKey.isEmpty {
let curlRequest = CURLRequest("https://fcm.googleapis.com/fcm/send", .failOnError)
curlRequest.addHeader(.authorization, value: "key=\(config.serverKey)")
curlRequest.addHeader(.contentType, value: "application/json")
return curlRequest
}
return nil
}
public class func send(_ config: PerfectFCM.Config, to: String, title: String, body: String, data: [String: String]?) throws {
var json: [String: Any] = [
"to": to,
"notification": [
"title": title,
"body": body
]
]
if let data = data {
json["data"] = data
}
let jsonData = try JSONSerialization.data(withJSONObject: json, options: [])
guard let jsonString = String(data: jsonData, encoding: .utf8) else {
throw Exception.CannonConvertToJson
}
if let curlRequest = try prepare(config) {
curlRequest.options.append(.httpMethod(.post))
curlRequest.options.append(.postString(jsonString))
let curlResponse = try curlRequest.perform()
if debug {
print(curlResponse.bodyString)
}
}
}
}
<file_sep>/Tests/Perfect-FCM-ServerTests/Perfect_FCM_ServerTests.swift
import XCTest
@testable import Perfect_FCM_Server
extension String {
public var sysEnv: String {
guard let e = getenv(self) else { return "" }
return String(cString: e)
}
}
class Perfect_FCM_ServerTests: XCTestCase {
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert andz related functions to verify your tests produce the correct
// results.
let config = PerfectFCM.Config(serverKey: "FCM_SERVER_KEY".sysEnv)
do {
try PerfectFCM.send(config, to: "FCM_DEVICE_TOKEN".sysEnv, title: "Hello world!", body: "Perfect FCM PUSH notification!", data: nil)
} catch {
print(error.localizedDescription)
}
}
static var allTests = [
("testExample", testExample),
]
}
|
1225c2de6c860c9427ec462d80d6087ba99fdcfd
|
[
"Swift",
"Markdown"
] | 4 |
Swift
|
mdellagi77/Perfect-FCM-Server
|
e1af1b6e13b90f962c4818d08c187737a0a10f79
|
b86ef41ae91b96e6899d330d6206d1c49ea29557
|
refs/heads/main
|
<repo_name>lips-coding4fun/c4f-open-telemetry<file_sep>/Postman/Controllers/MailController.cs
using System.Linq;
using Postman.Data;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace Postman.Controllers
{
[ApiController]
[Route("[controller]")]
public class MailController : ControllerBase
{
private readonly AppDbContext _dbContext;
private readonly ILogger<MailController> _logger;
private readonly HttpClient _client;
public MailController(AppDbContext dbContext, ILogger<MailController> logger)
{
_dbContext = dbContext;
_logger = logger;
_client = new HttpClient();
_dbContext.Database.EnsureCreated();
}
[HttpGet]
[ProducesResponseType(200, Type = typeof(string))]
public async Task<IActionResult> Get()
{
try
{
await Task.WhenAll(_dbContext.Mails.OrderBy(x => x.Receiver).ToList().Select(x =>
{
using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, $"http://localhost:{x.Address}"))
{
requestMessage.Headers.Add("mail-message", x.Message);
_logger.LogInformation($"Sending mail to {x.Receiver}");
return _client.SendAsync(requestMessage);
}
}));
}
catch(HttpRequestException e)
{
_logger.LogError(e.Message);
}
return Ok("Sent");
}
}
}
<file_sep>/Postman/Data/MailEntity.cs
using System;
using System.ComponentModel.DataAnnotations.Schema;
namespace Postman.Data
{
[Table("Mails")]
public sealed class MailEntity
{
public Guid Id { get; set; }
public string Receiver { get; set; }
public int Address { get; set; }
public string Message { get; set; }
}
}
<file_sep>/README.md
# Démo Open Telemetry
## Introduction
Le but de cette démo va être de simuler la tournée du facteur et de s'assurer de la distribution du courrier en ayant une traçabilité complète.
Notre "facteur" (Postman) sera un service ASP.NET et les "destinataires" (Alice et Bob) des services Java. Il envoit le courrier par requête HTTP à des adresses définies (localhost:2000 et 3000) avec un petit message.
Bob habite à une adresse inexistante (il n'y a pas de services qui tourne sur 3000), ça nous permettra de voir comment Open Telemetry se comporte en cas d'erreur.
## Prérequis
Il vous faut Jaeger qui tourne en local, le plus simple est via docker :
```bash
docker run -d --name jaeger \
-e COLLECTOR_ZIPKIN_HTTP_PORT=9411 \
-p 5775:5775/udp \
-p 6831:6831/udp \
-p 6832:6832/udp \
-p 5778:5778 \
-p 16686:16686 \
-p 14268:14268 \
-p 14250:14250 \
-p 9411:9411 \
jaegertracing/all-in-one:1.22
```
Si vous n'avez pas Docker, vous pouvez toujours utiliser le binaire. Plus d'infos ici : https://www.jaegertracing.io/docs/1.22/getting-started/
Une fois la commande exécutée, le UI de Jaeger doit être accessible sur http://localhost:16686
## Les destinataires (Partie Java)
Du Vert.X pour la partie serveur, OpenTelemetry supporte aussi le réactif !
```bash
cd Alice
./mvnw clean package #Si vous êtes sur un réseau d'entreprise utilisez plutôt mvn directement pour fetch
```
Maintenant il faut configurer la SDK d'Open Telemetry avec les exporteurs qu'on souhaite utiliser (ici Jaeger) et nommer notre service.
Sur Windows, passez bien par CMD et non Powershell ni le nouveau terminal Windows avec cette syntaxe.
Sur Windows | Sur Linux
------------ | -------------
set OTEL_TRACES_EXPORTER=jaeger | export OTEL_TRACES_EXPORTER=jaeger
set OTEL_METRICS_EXPORTER=none | export OTEL_METRICS_EXPORTER=none
set OTEL_RESOURCE_ATTRIBUTES=service.name=alice | export OTEL_RESOURCE_ATTRIBUTES=service.name=alice
Plus d'infos sur les variables sont dispos ici : https://github.com/open-telemetry/opentelemetry-java/tree/main/sdk-extensions/autoconfigure
```bash
java -javaagent:opentelemetry-javaagent-all.jar -jar .\target\alice-1.0.0-SNAPSHOT-fat.jar
```
La console doit afficher *"Alice's ready to receive her mails..."*
## Le facteur (Partie .NET)
Documentation : https://github.com/open-telemetry/opentelemetry-dotnet
```bash
cd Postman
dotnet add package OpenTelemetry.Extensions.Hosting --prerelease
dotnet add package OpenTelemetry.Exporter.Jaeger --prerelease
dotnet add package OpenTelemetry.Instrumentation.AspNetCore --prerelease
dotnet add package OpenTelemetry.Instrumentation.Http --prerelease
dotnet run
```
Faites une requête sur https://localhost:5001/mail et le facteur fera sa tournée ! 🚀
## Enrichir un Span
On aimerait bien pouvoir ajouter de l'information dans les spans qui sont remontés dans Jaeger.
On peut ajouter le contenu du message (en théorie on ne doit pas mettre d'infos sensibles !) mais j'ai ajouté dans les headers des requêtes HTTP le contenu du message ("mail-message"). Vous pouvez donc l'intercepter avec Open Telemetry et ajouter cette info au Span.
Vous trouverez les explications sur comment faire ici : https://github.com/open-telemetry/opentelemetry-dotnet/blob/metrics/src/OpenTelemetry.Instrumentation.Http/README.md#enrich
<details>
<summary>Et la solution en spoiler :</summary>
```csharp
.AddHttpClientInstrumentation((options) => options.Enrich = (activity, eventName, rawObject) =>
{
if (eventName.Equals("OnStartActivity"))
{
if (rawObject is HttpRequestMessage httpRequest)
{
activity.SetTag("mail-message", httpRequest.Headers.First(x => x.Key.Equals("mail-message")).Value);
}
}
})
```
</details>
## Bonus Open Telemetry
Si vous avez encore du temps et un langage de coeur qui n'est ni le C#, ni le Java, vous pouvez tenter d'implémenter Bob.
Il existe pleins de langages instrumentés sur https://github.com/open-telemetry et tous ont des exemples très simples pour commencer.
## Bonus Jaeger
- Vous pouvez comparer des traces entre elles : http://localhost:16686/trace/...
- Dans la vue détaillée, vous pouvez changer le mode d'affichage (Mode JSON, stats, timeline sont dispos)
- http://localhost:16686/dependencies vous affiche une cartographie dans l'onglet DAG
<file_sep>/Postman/Data/AppDbContext.cs
using System;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
namespace Postman.Data
{
public class AppDbContext : DbContext
{
public DbSet<MailEntity> Mails { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
optionsBuilder.UseSqlite(connection);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<MailEntity>().ToTable("Mails");
modelBuilder.Entity<MailEntity>().HasData(
new MailEntity()
{
Id = new Guid("11111111-1111-1111-1111-111111111111"),
Receiver = "Alice",
Address = 2000,
Message = "Hello Alice!",
},
new MailEntity()
{
Id = new Guid("33333333-3333-3333-3333-333333333333"),
Receiver = "Bob",
Address = 3000,
Message = "Hello Bob!",
}
);
}
}
}
<file_sep>/Postman/Startup.cs
using System;
using System.Linq;
using Postman.Data;
using System.Net.Http;
using OpenTelemetry.Trace;
using OpenTelemetry.Resources;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Postman
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddOpenTelemetryTracing(builder => builder
.SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("postman"))
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation((options) => options.Enrich = (activity, eventName, rawObject) =>
{
if (eventName.Equals("OnStartActivity"))
{
if (rawObject is HttpRequestMessage httpRequest)
{
activity.SetTag("mail-message", httpRequest.Headers.First(x => x.Key.Equals("mail-message")).Value);
}
}
})
.AddJaegerExporter()
);
services.AddScoped<DbContext, AppDbContext>();
services.AddDbContext<AppDbContext>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
|
09a87a73bfd1ea76fc59781d695e4ad54769cbf7
|
[
"Markdown",
"C#"
] | 5 |
C#
|
lips-coding4fun/c4f-open-telemetry
|
ed2c3fae651860abef348fb058063930fbc0d627
|
a28cc5633ec648ac1f4c36f7fd68ab1acb63cf71
|
refs/heads/main
|
<file_sep>CREATE USER IF NOT EXISTS 'usermysql'@'%' IDENTIFIED BY '<PASSWORD>';
GRANT ALL PRIVILEGES ON *.* TO 'terraform'@'%' IDENTIFIED BY '<PASSWORD>';
FLUSH PRIVILEGES;
|
8841bea26c217c23dcd0423ea9d10c9f3028b530
|
[
"SQL"
] | 1 |
SQL
|
jbockhorny/terraform
|
999910e16e3527f628069a030d5e1f55c543e200
|
a1976b8c03c1c11ce0437acb35ea55a2bc9ca080
|
refs/heads/master
|
<file_sep>'use strict';
const fs = require('fs');
const path = require('path');
const url = require('url');
let FileServer = require('./../../../nodejs/3rd/cjs-3/cjhttp_file_server');
const fileServer = new FileServer();
fileServer.config.assetsPath = path.normalize(path.join(__dirname, './../../../../../'));
const UserData = require('./data/user');
const LoginUsers = UserData[0];
const Users = UserData[1];
let _Users = Users;
let parseBody = function(req, res, body) {
if (body) {
let r = undefined;
try {
r = JSON.parse(body);
}
catch (e) {
let err = 'error: JSON.parse(body) by url :' + req.url;
console.log(err);
res.writeHead(500);
res.end(JSON.stringify({code: 500, msg: err}));
}
return r;
}
return undefined;
};
let getRequestIp = function(req, res) {
return req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
(req.connection.socket ? req.connection.socket.remoteAddress : null);
};
// {
// id: 1,
// username: 'admin',
// password: '<PASSWORD>',
// avatar: 'https://raw.githubusercontent.com/taylorchen709/markdown-images/master/vueadmin/user.png',
// name: '张某某'
// }
let dealUser = function(app, httpMysqlServer) {
// mock success request
app.route('/success')
.get(function(req, res) {
res.writeHead(200);
res.end(JSON.stringify({
msg: 'success'
}));
});
// mock error request
app.route('/error')
.get(function(req, res) {
res.writeHead(500);
res.end(JSON.stringify({
msg: 'failure'
}));
});
//登录模拟
app.route('/login-1')
.post(function(req, res) {
let body = '';
req.on('data', function(chunk) {
body += chunk;
});
req.on('end', function() {
let reqBody = parseBody(req, res, body);
if (!reqBody) return;
let {username, password} = reqBody;
let user = null;
let hasUser = LoginUsers.some(u => {
if (u.username === username && u.password === <PASSWORD>) {
user = JSON.parse(JSON.stringify(u));
user.password = <PASSWORD>;
return true;
}
});
if (hasUser) {
res.writeHead(200);
res.end(JSON.stringify({code: 200, msg: '请求成功', user}));
}
else {
res.writeHead(200);
res.end(JSON.stringify({code: 500, msg: '账号或密码错误', user}));
}
});
});
//登录
app.route('/login')
.post(function(req, res) {
let body = '';
req.on('data', function(chunk) {
body += chunk;
});
req.on('end', function() {
let reqBody = parseBody(req, res, body);
if (!reqBody) return;
let {username, password} = reqBody;
let sql = 'select id as `id`,f_name as `name`,f_uri as `username`,f_pw as `password`, f_img as `avatar` from ti_obj_user where f_uri=\'' + username + '\' and f_pw = \'' + password + '\'';
httpMysqlServer.query(sql, function(err, values, fields) {
let user = null;
if (err) {
res.writeHead(200);
res.end(JSON.stringify({code: 500, msg: '数据访问错误', user}));
}
else {
if (Array.isArray(values)) {
if (values.length == 0) {
res.writeHead(200);
res.end(JSON.stringify({code: 500, msg: '账号或密码错误', user}));
}
else {
user = values[0];
user.password = <PASSWORD>;
res.writeHead(200);
res.end(JSON.stringify({code: 200, msg: '请求成功', user}));
}
}
else {
res.writeHead(200);
res.end(JSON.stringify({code: 500, msg: '数据返回错误', user}));
}
}
});
});
});
//获取用户列表
app.route('/user/list')
.get(function(req, res) {
let paramsObj = url.parse(req.url, true).query;
let {name} = paramsObj;
let mockUsers = _Users.filter(user => {
if (name && user.name.indexOf(name) == -1) return false;
return true;
});
let sessionId = paramsObj.sessionId;
let fncode = paramsObj.fncode;
res.writeHead(200);
res.end(JSON.stringify({
users: mockUsers
}));
});
//获取用户列表(分页)
app.route('/user/listpage')
.get(function(req, res) {
let paramsObj = url.parse(req.url, true).query;
let {page, name} = paramsObj;
let mockUsers = _Users.filter(user => {
if (name && user.name.indexOf(name) == -1) return false;
return true;
});
let total = mockUsers.length;
mockUsers = mockUsers.filter((u, index) => index < 20 * page && index >= 20 * (page - 1));
res.writeHead(200);
res.end(JSON.stringify({
total: total,
users: mockUsers
}));
});
//删除用户
app.route('/user/remove')
.get(function(req, res) {
let paramsObj = url.parse(req.url, true).query;
let {id} = paramsObj;
_Users = _Users.filter(u => u.id !== id);
res.writeHead(200);
res.end(JSON.stringify({
code: 200,
msg: '删除成功'
}));
});
//批量删除用户
app.route('/user/batchremove')
.get(function(req, res) {
let paramsObj = url.parse(req.url, true).query;
let {ids} = paramsObj;
ids = ids.split(',');
_Users = _Users.filter(u => !ids.includes(u.id));
res.writeHead(200);
res.end(JSON.stringify({
code: 200,
msg: '删除成功'
}));
});
//编辑用户
app.route('/user/edit')
.get(function(req, res) {
let paramsObj = url.parse(req.url, true).query;
let {id, name, addr, birth, age, sex} = paramsObj;
_Users.some(u => {
if (u.id === id) {
u.name = name;
u.addr = addr;
u.age = age;
u.birth = birth;
u.sex = sex;
return true;
}
});
res.writeHead(200);
res.end(JSON.stringify({
code: 200,
msg: '编辑成功'
}));
});
//新增用户
app.route('/user/add')
.get(function(req, res) {
let paramsObj = url.parse(req.url, true).query;
let {name, addr, age, birth, sex} = paramsObj;
_Users.push({
name: name,
addr: addr,
age: age,
birth: birth,
sex: sex
});
res.writeHead(200);
res.end(JSON.stringify({
code: 200,
msg: '新增成功'
}));
});
};
/**
* @param app
* @param httpMysqlServer
*/
let dealSql = function(app, httpMysqlServer) {
/**
// request url:
http://localhost:xxxx/sql/query
// data.json
{
session: Date.now(),
sqls: [
"inseart table xx",
"update table xx",
"select id=1 from t1",
]
}
// resp1.json
// "data".item is object || array
{
session: ^,
values:[
{err:null, state: {affectedRows: 1}},
{err:null, state: {affectedRows: 1}},
{err:null, data: [ {f1: v11, f2: v12},{f1: v21, f2: v22}]}
],
state: {err:null}
}
*/
app.route('/sql/query')
.post(function(req, res) {
let body = '';
req.on('data', function(chunk) {
body += chunk;
});
req.on('end', function() {
let reqBody = parseBody(req, res, body);
if (!reqBody) return;
let {session, sql} = reqBody;
httpMysqlServer.query(sql, function(err, values, fields) {
let r = {
session: session,
sql: sql,
state: {}
};
if (err) {
r.state.err = err;
res.writeHead(200);
res.end(JSON.stringify(r));
}
else {
if (Array.isArray(values)) {
r.state.affectedRows = values.length;
r.data = values;
}
else {
r.state.affectedRows = values.affectedRows;
}
res.writeHead(200);
res.end(JSON.stringify(r));
}
});
});
});
/**
// request url:
http://localhost:xxxx/sql/queries
// data.json
{
session: Date.now(),
sqls: [
"select * from t1",
"select * from t1",
]
}
// resp1.json
// "data".item is object || array
{
session: ^,
values:[
{err:null, data: [ {f1: v11, f2: v12},{f1: v21, f2: v22}], state: {affectedRows: 1}},
{err:null, data: [ {f1: v11, f2: v12},{f1: v21, f2: v22}], state: {affectedRows: 1}}
],
state: {err:null}
}
*/
app.route('/sql/queries')
.post(function(req, res) {
let body = '';
req.on('data', function(chunk) {
body += chunk;
});
req.on('end', function() {
let reqBody = parseBody(req, res, body);
if (!reqBody) return;
let {session, sqls} = reqBody;
httpMysqlServer.querySqls(sqls, function(err, res) {
let r = {
session: session,
state: {}
};
if (err) {
r.state.err = err;
res.writeHead(200);
res.end(JSON.stringify(r));
}
else {
r.values = [];
res.forEach(rs => {
if (Array.isArray(rs.values)) {
r.values.push({err: rs.err, data: rs.values});
}
else {
r.values.push({err: rs.err, state: {affectedRows: rs.values.affectedRows}});
}
});
res.writeHead(200);
res.end(JSON.stringify(r));
}
});
});
});
/**
// request url:
http://localhost:xxxx/sql/trans
// data.json
{
session: Date.now(),
sqls: [
"inseart table xx",
"update table xx",
"select id=1 from t1",
]
}
// resp1.json
// "data".item is object || array
{
session: ^,
values:[
{err:null, state: {affectedRows: 1}},
{err:null, state: {affectedRows: 1}},
{err:null, data: [ {f1: v11, f2: v12},{f1: v21, f2: v22}]}
],
state: {err:null}
}
*/
app.route('/sql/trans')
.post(function(req, res) {
let body = '';
req.on('data', function(chunk) {
body += chunk;
});
req.on('end', function() {
let reqBody = parseBody(req, res, body);
if (!reqBody) return;
let {session, sqls} = reqBody;
httpMysqlServer.queryTrans(sqls, null, function(err, rs) {
let r = {
session: session,
state: {}
};
if (err) {
r.state.err = err;
res.writeHead(200);
res.end(JSON.stringify(r));
}
else {
r.values = [];
rs.forEach(re => {
if (Array.isArray(re.values)) {
r.values.push({err: re.err, data: re.values});
}
else {
r.values.push({err: re.err, state: {affectedRows: re.values.affectedRows}});
}
});
res.writeHead(200);
res.end(JSON.stringify(r));
}
});
});
});
};
/**
* @param app
* @param httpMysqlServer
*/
let dealOdl = function(app, httpMysqlServer) {
/**
// request url:
http://localhost:xxxx/odo/query
action: ['ls', 'add', 'edit', 'del']
token.state: ['req', 'ing', 'ed', 'del']
*/
/** ls.req.json
{
session: Date.now(),
odc: 'odcName',
action: 'ls',
queryCounter: false,
counter: 100,
conditions = {
index: 0,
count: 20,
attrs: [
{
name: 'name',
operation: '%',
value: 'aa'
}
]
};
}
// ls.resp.json
{
session: ^,
odc: 'odcName',
action: ^,
queryCounter: false,
counter: ^ | resp,
conditions = ^,
data: [ {f1: v11, f2: v12},{f1: v21, f2: v22}],
state: {err:null}
}
*/
/** add.req.token.json
{
session: Date.now(),
odc: 'odcName',
action: 'add',
token: {
state: 'req',
},
}
// add.resp.token.json
{
session: ^,
odc: 'odcName',
action: 'add',
token: {
state: 'ing',
id: 'xxx',
duration: 'ms',
deadline: 'datetime',
},
data: [ {key: v11},{key: v21}],
state: {err:null}
}
// add.req.json
{
session: Date.now(),
odc: 'odcName',
action: 'add',
token: {
state: 'ing',
id: 'xxx',
duration: 'ms',
deadline: 'datetime',
},
data: [{f1: v11, f2: v12}],
}
// add.resp.json
{
session: ^,
odc: 'odcName',
action: 'add',
state: {err:null, affectedRows: 1}
}
*/
/** edit.req.token.json
{
session: Date.now(),
odc: 'odcName',
action: 'edit',
token: {
state: 'req',
},
data: [{id: v11}],
}
// edit.resp.token.json
{
session: ^,
odc: 'odcName',
action: 'edit',
token: {
state: 'ing',
id: 'xxx',
duration: 'ms',
deadline: 'datetime',
},
state: {err:null}
}
// edit.req.json
{
session: Date.now(),
odc: 'odcName',
action: 'edit',
token: {
state: 'ing',
id: 'xxx',
duration: 'ms',
deadline: 'datetime',
},
data: [{f1: v11, f2: v12}],
}
// edit.resp.json
{
session: ^,
odc: 'odcName',
action: 'edit',
token: {
state: 'ed',
id: 'xxx',
duration: 'ms',
deadline: 'datetime',
},
state: {err:null, affectedRows: 1}
}
*/
/** del.req.json
{
session: Date.now(),
odc: 'odcName',
action: 'del',
data: [{id: v11},{id: v21}],
}
// del.resp.json
{
session: ^,
odc: 'odcName',
action: 'del',
state: {err:null, affectedRows: 1}
}
*/
/** validate.req.token.json
{
session: Date.now(),
odc: 'odcName',
action: 'validate',
token: {
state: 'req',
},
conditions = {
index: 0,
count: 20,
attrs: [
{
name: 'name',
operation: '%',
value: 'aa'
}
]
}
}
// validate.resp.token.json
{
session: ^,
odc: 'odcName',
action: 'validate',
token: {
state: 'ing',
id: 'xxx',
duration: 'ms',
deadline: 'datetime',
},
data: [ {key: v11},{key: v21}],
state: {err:null}
}
// validate.req.json
{
session: Date.now(),
odc: 'odcName',
action: 'validate',
token: {
state: 'ing',
id: 'xxx',
duration: 'ms',
deadline: 'datetime',
},
data: [{f1: v11, f2: v12}],
}
// validate.resp.json
{
session: ^,
odc: 'odcName',
action: 'validate',
state: {err:null, affectedRows: 1}
}
*/
app.route('/odo/query')
.post(function(req, res) {
let body = '';
req.on('data', function(chunk) {
body += chunk;
});
req.on('end', function() {
let respError = (err, code) => {
let code2 = code ? code : 500;
let data = {err: 'error: ' + err, code: code2}
res.writeHead(code2);
res.end(JSON.stringify(data));
console.log(data);
};
let reqBody = parseBody(req, res, body);
if (!reqBody) return;
let {session, action, odc, token} = reqBody;
let odcName = odc;
odc = odl.findOdc(odcName);
if (!odc) {
respError('can not findOdc: ' + reqBody.odc);
return;
}
let dispatchOdcEvent = (data, old) => {
if (!global.EventBus) return;
EventBus.dispatch(odcName, {action: action, data: data, old: old});
};
let hasEventBus = () => {
if (!global.EventBus) return false;
return EventBus.hasEventListener(odcName);
};
let nMysql = odl.DbMysql;
if (action === 'ls') {
let {queryCounter, conditions} = reqBody;
let sqls = [];
if (queryCounter) {
sqls.push(nMysql.getSelectCountSql(odc, conditions));
}
sqls.push(nMysql.getSelectSql(odc, conditions));
let callback = (err, rs) => {
let counter = Array.isArray(rs) && rs.length > 1 && Array.isArray(rs[0].values) && rs[0].values.length > 0 ? rs[0].values[0]['counter'] : -1;
let data = null;
if (queryCounter) {
if (Array.isArray(rs) && rs.length > 1) {
data = rs[1].values;
}
} else {
if (Array.isArray(rs) && rs.length > 0) {
data = rs[0].values;
}
}
let r = {
session: session,
odc: reqBody.odc,
action: action,
queryCounter: queryCounter,
counter: queryCounter ? counter : reqBody.hasOwnProperty('counter') ? reqBody.counter : -1,
conditions: conditions,
data: data,
state: {err: err}
};
res.writeHead(200);
res.end(JSON.stringify(r));
};
httpMysqlServer.querySqls(sqls, null, callback);
}
else if (action === 'add') {
let {token} = reqBody;
if (token && token.state === 'req') {
let respToken = (err, data) => {
let r = {
session: session,
odc: reqBody.odc,
action: action,
data: data,
state: {err: err},
};
if (!err) {
let ip = getRequestIp(req, res);
let tk = odl.OpToken.reqToken({ip: ip}, odc, action);
if (typeof tk === 'string') {
r.state.err = tk;
}
else {
r.token = tk;
}
}
res.writeHead(200);
res.end(JSON.stringify(r));
};
let rSqls = nMysql.getSelectKeySqls(odc);
// has key, return
if (rSqls.length>0) {
httpMysqlServer.query(rSqls[0], (err, values) => {
nMysql.getSelectKeySqlsValidateValues(odc, values, rSqls);
respToken(err, values);
});
}
else {
respToken(null, [{key: Date.now()}]);
}
}
else {
let {data} = reqBody;
let respState = (err, affectedRows) => {
let r = {
session: session,
odc: reqBody.odc,
action: action,
state: {err: null, affectedRows: affectedRows},
};
if (!err) {
odl.OpToken.releaseToken(odc, action);
}
res.writeHead(200);
res.end(JSON.stringify(r));
if (affectedRows > 0 && hasEventBus()) {
dispatchOdcEvent(data);
}
};
let sqlAry = nMysql.getInsertSqlAry(odc, data);
if (sqlAry) {
let sqlAryLog = nMysql.getLogInsertSql(odc, action, data);
if (sqlAryLog.length === sqlAry.length) {
httpMysqlServer.queryTrans(sqlAry.concat(sqlAryLog), null, (err, res) => {
respState(err, err ? 0 : 1);
});
} else {
respState('getLogInsertSql is empty!', 0);
}
}
else {
respState('getInsertSqlAry is empty!', 0);
}
}
}
else if (action === 'edit') {
let {token} = reqBody;
if (token && token.state === 'req') {
let r = {
session: session,
odc: reqBody.odc,
action: action,
state: {},
};
let ip = getRequestIp(req, res);
let tk = odl.OpToken.reqToken({ip: ip}, odc, action);
if (typeof tk === 'string') {
r.state.err = tk;
}
else {
r.token = tk;
}
res.writeHead(200);
res.end(JSON.stringify(r));
}
else {
let {data, conditions, old} = reqBody;
let respState = (err, affectedRows) => {
let r = {
session: session,
odc: reqBody.odc,
action: action,
state: {err: null, affectedRows: affectedRows},
};
if (!err) {
odl.OpToken.releaseToken(odc, action);
}
res.writeHead(200);
res.end(JSON.stringify(r));
if (affectedRows > 0 && hasEventBus()) {
dispatchOdcEvent(data, old);
}
};
let sqlAry = nMysql.getUpdateSqlAry(odc, data, conditions);
if (sqlAry) {
let sqlAryLog = nMysql.getLogInsertSql(odc, action, conditions);
if (sqlAryLog.length === sqlAry.length) {
httpMysqlServer.queryTrans(sqlAry.concat(sqlAryLog), null, (err, res) => {
respState(err, err ? 0 : 1);
});
} else {
respState('getLogInsertSql is empty!', 0);
}
}
else {
respState('getUpdateSqlAry is empty!', 0);
}
}
}
else if (action === 'del') {
let {conditions} = reqBody;
let respState = (err, affectedRows) => {
let r = {
session: session,
odc: reqBody.odc,
action: action,
state: {err: null, affectedRows: affectedRows},
};
if (!err) {
odl.OpToken.releaseToken(odc, action);
}
res.writeHead(200);
res.end(JSON.stringify(r));
};
let sqlAry = nMysql.getDeleteSqlAry(odc, conditions);
if (sqlAry) {
let sqlAryLog = nMysql.getLogInsertSql(odc, action, conditions);
if (sqlAryLog.length === sqlAry.length) {
httpMysqlServer.queryTrans(sqlAry.concat(sqlAryLog), null, (err, res) => {
respState(err, err ? 0 : 1);
if (!err && hasEventBus()) {
dispatchOdcEvent(conditions);
}
});
} else {
respState('getLogInsertSql is empty!', 0);
}
}
else {
respState('getDeleteSqlAry is empty!', 0);
}
}
else if (action === 'validate') {
let {token, conditions} = reqBody;
if (token && token.state === 'req') {
let respToken = (err, data) => {
let r = {
session: session,
odc: reqBody.odc,
action: action,
data: data,
state: {err: err},
};
if (!err) {
let ip = getRequestIp(req, res);
let tk = odl.OpToken.reqToken({ip: ip}, odc, action);
if (typeof tk === 'string') {
r.state.err = tk;
}
else {
r.token = tk;
}
}
res.writeHead(200);
res.end(JSON.stringify(r));
};
let sql = nMysql.getSelectSql(odc, conditions);
// has key
if (sql) {
httpMysqlServer.query(sql, (err, values) => {
respToken(err, values);
});
}
else {
respToken(null, [{key: Date.now()}]);
}
}
else {
let respState = (err, affectedRows) => {
let r = {
session: session,
odc: reqBody.odc,
action: action,
state: {err: null, affectedRows: affectedRows},
};
if (!err) {
odl.OpToken.releaseToken(odc, action);
}
res.writeHead(200);
res.end(JSON.stringify(r));
};
let {data} = reqBody;
let objs = data;
if (Array.isArray(objs)) {
for (let i = 0; i < objs.length; i++) {
let obj = objs[i];
}
}
// let obj = {};
// for (let i = 0; i < conditions.length; i++) {
// let condition = conditions[i];
// let attrs = condition.attrs;
// if (!Array.isArray(attrs)) continue;
// for (let j = 0; j < attrs.length; j++) {
// let attr = attrs[j];
// obj[attr.name] = attr.value;
// }
// }
// objs.push(obj);
let ip = getRequestIp(req, res);
let logEnv = {
time: Date.now(),
operation: 'validate',
who: 'gcl3-master-node.js',
where: ip,
message: ''
};
let sqlAry = nMysql.log.getInsertSqlAry(odc, objs, logEnv);
if (Array.isArray(sqlAry) && sqlAry.length > 0) {
httpMysqlServer.queryTrans(sqlAry, null, (err, res) => {
respState(err, err ? 0 : 1);
});
}
else {
respState('getInsertLogSqlAry is empty!', 0);
}
}
}
else {
respError('action is invalid: ' + action);
}
});
});
};
let dealAssets = function(app) {
app.route(/\/assets\/.*/)
.get(function(req, res) {
fileServer.dispatch(req, res);
})
};
exports = module.exports = {
/**
* mock bootstrap
*/
init(app, httpMysqlServer) {
dealUser(app, httpMysqlServer);
dealOdl(app, httpMysqlServer);
dealSql(app, httpMysqlServer);
dealAssets(app);
}
};
<file_sep>(function() {
'use strict';
if (typeof exports === 'object' && typeof global === 'object') {
global.cjs = global.cjs || {};
} else if (typeof window === 'object') {
window.cjs = window.cjs || {};
} else {
throw Error('cjs only run at node.js or web browser');
}
let CjJson = cjs.CjJson || {};
cjs.CjJson = CjJson;
if (typeof exports === 'object' && typeof global === 'object') {
exports = module.exports = CjJson;
if (!cjs.CjMeta) require('./cjmeta');
}
if (CjJson.hasOwnProperty('parse')) return;
/**
* parse
* @param {string[]|string}sJsons
* @param {object}dest
* @return {*}
*/
CjJson.parse = function parse(sJsons, dest) {
if (!cjs.CjMeta) {
throw new ReferenceError('CjMeta is required');
}
if ((sJsons instanceof Array) && sJsons.length >= 2) {} else {
if (typeof sJsons === 'string') {
let obj = JSON.parse(sJsons);
if (dest) {
cjs.CjMeta.merge(dest, obj);
return dest;
}
return obj;
}
throw new TypeError('argument sJsons is required, sJsons is array of json string, and length >= 2');
}
let r = null;
try {
r = JSON.parse(sJsons[0]);
if (dest) {
cjs.CjMeta.merge(dest, r);
r = dest;
}
for (let i = 1; i < sJsons.length; i++) {
let sJson = sJsons[i];
let obj = JSON.parse(sJson);
cjs.CjMeta.merge(r, obj);
}
} catch (e) {
r = null;
console.log('except CjJson.load.');
}
return r;
};
CjJson.refer2object = function(obj, referObject) {
if (typeof obj !== 'object' || typeof referObject !== 'object') {
return;
}
let sNames = Object.getOwnPropertyNames(obj);
for (let i = 0; i < sNames.length; i++) {
let sName = sNames[i];
if (referObject.hasOwnProperty(sName)) {
let sType1 = typeof obj[sName];
let sType2 = typeof referObject[sName];
if (sType1 === sType2) {
if (sType1 === 'object') {
CjJson.refer2object(obj[sName], referObject[sName]);
}
} else {
switch (sType2) {
case 'string':
obj[sName] = obj[sName].toString();
break;
case 'number':
obj[sName] = Number(obj[sName]);
break;
case 'boolean':
obj[sName] = Boolean(obj[sName]);
break;
}
}
}
}
};
CjJson.fromJson = function(sJson, ReferClass) {
if (typeof sJson !== 'string' && !(sJson instanceof String)) {
return null;
}
try {
let obj1 = JSON.parse(sJson);
if (ReferClass) {
let r = new ReferClass();
this.refer2object(obj1, r);
}
return obj1;
} catch (e) {
}
return null;
};
})();
<file_sep>(function() {
'use strict';
if (typeof exports === 'object' && typeof global === 'object') {
global.cjs = global.cjs || {};
} else if (typeof window === 'object') {
window.cjs = window.cjs || {};
} else {
throw Error('cjs only run at node.js or web browser');
}
let CjNumber = cjs.CjNumber || {};
cjs.CjNumber = CjNumber;
if (typeof exports === 'object' && typeof global === 'object') {
exports = module.exports = CjNumber;
}
if (CjNumber.hasOwnProperty('toOrdinal')) return;
/**
*
* @param num
* @returns {string}
* sample : CjNumber.toOrdinal( yourNumber )
*/
CjNumber.toOrdinal = function(num) {
let num2 = num - 0;
let n = num2 % 100;
let suffix = ['th', 'st', 'nd', 'rd', 'th'];
let ord = n < 21 ? (n < 4 ? suffix[n] : suffix[0]) : (n % 10 > 4 ? suffix[0] : suffix[n % 10]);
return num2 + ord;
};
CjNumber.isNumber = function(num) {
return Number.isNaN(parseInt(num));
};
})();
<file_sep>let cjAjax = {
version: '1.0.1',
};
// function init () {
// window.cjAjax = {};
//
// var cjAjax = window.cjAjax;
/**
* cxAjax.post(url, callBack_fn, fn_param);
* @param sendData
* @param callBack_fn
* @param params
*/
cjAjax.getUrlParamsString = function(urlParams) {
if (!urlParams) return '';
let r = new Array(urlParams.length);
let i = 0;
for (let key in urlParams) {
r[i++] = key + '=' + urlParams[key];
}
return r.join('&');
};
/**
* @param ajaxParams = {
url: '',
urlParams: null,
sendData: '',
sendDataType: '',
callback:null,
callbackParams:null
};
*/
cjAjax.createAjaxParams = function() {
let ajaxParams = {
url: '',
urlParams: null,
sendData: '',
sendDataType: '',
callback: null,
callbackParams: null,
};
return ajaxParams;
};
cjAjax.request = function(ajaxParams) {
if (!ajaxParams.url) {
console.log('cjAjax.request ajaxParams.url is null');
return;
}
if (!ajaxParams.callback) {
console.log('cjAjax.request ajaxParams.callback is null');
return;
}
let xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
// *特定IP
// xmlhttp.open("post", "http:// 10.31.16.253:8821/ics/xxx.cgi?fncode=req.sql.", true);
let sMethod = ajaxParams.sendData ? 'post' : 'get';
let sUrl = ajaxParams.url + '?' + cjAjax.getUrlParamsString(ajaxParams.urlParams);
// xmlhttp.open(sMethod, ajaxParams.url, true);
xmlhttp.open(sMethod, sUrl, true);
// *跨域授权
// xmlhttp.setRequestHeader("POWERED-BY-AID", "Approve");
// xmlhttp.setRequestHeader('Content-Type', 'json');
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
let res = {};
if (xmlhttp.status == 200) {
res = JSON.parse(xmlhttp.response);
res['http_status'] = 200;
} else {
res['http_status'] = xmlhttp.status;
}
ajaxParams.callback(JSON.stringify(res), ajaxParams);
}
// if (xmlhttp.readyState==4 && xmlhttp.status==200) {
// ajaxParams.callback(xmlhttp.response, ajaxParams);
// }
};
let sSendDataType = ajaxParams.sendDataType ? ajaxParams.sendDataType : 'application/json';
xmlhttp.setRequestHeader('Content-Type', sSendDataType);
if (ajaxParams.sendData) {
let r = xmlhttp.send(ajaxParams.sendData);
console.log();
} else {
xmlhttp.send();
}
};
cjAjax.post = function(url, callBack_fn, param1) {
let xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
// xmlhttp.open("post", "http:// 10.31.16.253:8821/ics/xxx.cgi?fncode=req.sql.", true);
// xmlhttp.open("post", "http:// 10.31.16.73:8821/ics/xxx.cgi?fncode=req.sql.", true);
xmlhttp.open('post', 'ics.cgi?fncode=req.sql.', true);
xmlhttp.setRequestHeader('POWERED-BY-AID', 'Approve');
xmlhttp.setRequestHeader('Content-Type', 'json');
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callBack_fn(xmlhttp.response, param1);
}
};
return xmlhttp.send(url);
};
// }
if (typeof module === 'object') {
if (module.exports) {
module.exports = cjAjax;
}
} else {
window.cjAjax = cjAjax;
}
<file_sep>FROM alpine
RUN apk update && \
apk upgrade
RUN apk add --no-cache openssh \
&& sed -i s/#PermitRootLogin.*/PermitRootLogin\ yes/ /etc/ssh/sshd_config \
&& echo "root:root" | chpasswd \
&& passwd -d root \
&& ssh-keygen -A
COPY identity.pub /root/.ssh/authorized_keys
CMD exec /usr/sbin/sshd -D -e "$@"<file_sep>'use strict';
const CjChannelUdp = require('./../cjs-3/cjchannel_udp');
const fs = require('fs');
const path = require('path');
const util = require('util');
exports = module.exports = PsmProtocol;
let crc16Table = [
0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,
0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6,
0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,
0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485,
0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d,
0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4,
0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc,
0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823,
0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b,
0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12,
0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,
0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41,
0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49,
0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70,
0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78,
0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f,
0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,
0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e,
0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256,
0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,
0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c,
0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634,
0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab,
0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3,
0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a,
0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92,
0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9,
0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1,
0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8,
0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0,
];
if (typeof Int32Array !== 'undefined') {
crc16Table = new Int32Array(crc16Table);
}
function crc16(buf, iOffset, length) {
let crc = 0;
let byte;
for (let i = iOffset; i < length; i++) {
byte = buf[i];
crc = (crc16Table[((crc >> 8) ^ byte) & 0xff] ^ (crc << 8)) & 0xffff;
}
return crc;
}
//* * body
//* 1 head
// uint head;
//* 2 front
// ushort version;
//* 3 dataLength
// ushort dataLength;
//* 4 body
function PsmPacketBody() {
this.frameType = 0; // send received calcer : IEC104
this.sourceOriginal = 0;
this.sourceAddress = 0;
this.resFrame = 0;
this.targetAddress = 0;
// 4(head) + 2 + 2 + 10 + 2
this.controlWord = 0; // short controlWord; short frameNo;
// + 24 + 2(crc)
this.command = 0;
this.reason = 0;
this.resCommand = 0;
this.container = 0;
this.paramType = 0;
this.paramCount = 0;
}
PsmPacketBody.byteCout = 48;
PsmPacketBody.prototype.fromBuffer = function(buf, offset) {
let offset2 = offset;
this.frameType = buf.readInt32LE(offset2, true);
offset2 += 4;
this.sourceOriginal = buf.readInt32LE(offset2, true);
offset2 += 4;
this.sourceAddress = buf.readInt32LE(offset2, true);
offset2 += 4;
this.resFrame = buf.readInt32LE(offset2, true);
offset2 += 4;
this.targetAddress = buf.readInt32LE(offset2, true);
offset2 += 4;
this.controlWord = buf.readInt32LE(offset2, true);
offset2 += 4;
this.command = buf.readInt32LE(offset2, true);
offset2 += 4;
this.reason = buf.readInt32LE(offset2, true);
offset2 += 4;
this.resCommand = buf.readInt32LE(offset2, true);
offset2 += 4;
this.container = buf.readInt32LE(offset2, true);
offset2 += 4;
this.paramType = buf.readInt32LE(offset2, true);
offset2 += 4;
this.paramCount = buf.readInt32LE(offset2, true);
offset2 += 4;
return offset2;
};
PsmPacketBody.prototype.toBuffer = function() {
let rBuf = Buffer.allocUnsafe(PsmPacketBody.byteCout);
let iOffset = 0;
rBuf.writeInt32LE(this.frameType, iOffset, true);
iOffset += 4;
rBuf.writeInt32LE(this.sourceOriginal, iOffset, true);
iOffset += 4;
rBuf.writeInt32LE(this.sourceAddress, iOffset, true);
iOffset += 4;
rBuf.writeInt32LE(this.resFrame, iOffset, true);
iOffset += 4;
rBuf.writeInt32LE(this.targetAddress, iOffset, true);
iOffset += 4;
rBuf.writeInt32LE(this.controlWord, iOffset, true);
iOffset += 4;
rBuf.writeInt32LE(this.command, iOffset, true);
iOffset += 4;
rBuf.writeInt32LE(this.reason, iOffset, true);
iOffset += 4;
rBuf.writeInt32LE(this.resCommand, iOffset, true);
iOffset += 4;
rBuf.writeInt32LE(this.container, iOffset, true);
iOffset += 4;
rBuf.writeInt32LE(this.paramType, iOffset, true);
iOffset += 4;
rBuf.writeInt32LE(this.paramCount, iOffset, true);
return rBuf;
};
//* 5 data
// char data[dataLength]
//* 6 crc
// int crc;
//* * define
/**
* PsmDefine
* @constructor
*/
function PsmDefine() {
}
PsmDefine.CI_psm_packet_max = 3980;
PsmDefine.CI_PSM_PACKET_DATA = 4000;
PsmDefine.c_psm_head = 0x5aa55aa5;
PsmDefine.CIPsmControlCode_Initiactive = 0x4000;
PsmDefine.CIPsmControlCode_Passivity = 0x8000;
PsmDefine.CIPsmControlCode_NACK = 0xC000;
PsmDefine.ci_psm_packet_default_size = 1024 * 2;
PsmDefine.ci_psm_fix_size = (PsmPacketBody.byteCout + 10);
PsmDefine.ci_psm_packet_default_count = function(byteCout) {
return ( (PsmDefine.ci_psm_packet_default_size - PsmDefine.ci_psm_fix_size) / byteCout );
};
PsmDefine.PACKAGE_MAX_SIZE = 4096;
PsmDefine.PACKAGE_MAX_BUF_SIZE = PsmDefine.PACKAGE_MAX_SIZE * 3;
PsmDefine.DealReplyType_Error_Data = (-1);
PsmDefine.ci_psm_process_result_message_command = 0x101;
PsmDefine.ci_psm_process_result_file_write = 0x102;
PsmDefine.ci_psm_process_result_realtime_data_request = 0x103;
PsmDefine.ci_psm_process_result_realtime_data_post = 0x104;
PsmDefine.ci_psm_process_received_message_command = 0x201;
PsmDefine.ci_psm_process_received_file_write = 0x202;
PsmDefine.ci_psm_process_received_realtime_data_request = 0x203;
PsmDefine.ci_psm_process_received_realtime_data_post = 0x204;
/*
命令码:分127个区
核心区有:7个,其它是扩展区
核心区0x01000000:平台环境、网络环境(局域网、广域网)
核心区0x02000000:系统、框架、程序运行环境
核心区0x03000000:APP、应用程序、进程、消息、文件
核心区0x04000000:(所在的APP产生的)配置、固化、整参
核心区0x05000000:(所在的APP产生的)实时、动态数据、日常活动、事件、告警
核心区0x06000000:(所在的APP产生的)控制、命令、任务
核心区0x07000000:(所在的APP产生的)日志、历史查询、分析、业务支持
*/
PsmDefine.gct_core1_base = (0x01000000);
PsmDefine.gct_core2_base = (0x02000000);
PsmDefine.gct_core3_base = (0x03000000);
PsmDefine.gct_core4_base = (0x04000000);
PsmDefine.gct_core5_base = (0x05000000);
PsmDefine.gct_core6_base = (0x06000000);
PsmDefine.gct_core7_base = (0x07000000);
// link check
PsmDefine.gct_channel_base = (PsmDefine.gct_core1_base + (0x050000));
PsmDefine.gct_channel_hand = (PsmDefine.gct_channel_base + (0x0202));
PsmDefine.gct_channel_check = (PsmDefine.gct_channel_base + (0x0302));
// message
PsmDefine.gct_message_base = (PsmDefine.gct_core3_base + (0x050000));
// 0x03050101 03 05 01 01
PsmDefine.gct_message_command_param = (PsmDefine.gct_message_base + (0x0101));
// file
PsmDefine.gct_file_base = (PsmDefine.gct_core3_base + (0x060000));
// PsmDefine.gct_file_information_read = (PsmDefine.gct_file_base + (0x0101));
// 0x03060102 03 06 01 02
PsmDefine.gct_file_information_write = (PsmDefine.gct_file_base + (0x0102));
// PsmDefine.gct_file_content_read = (PsmDefine.gct_file_base + (0x0201));
// 0x03060202 03 06 02 02
PsmDefine.gct_file_content_write = (PsmDefine.gct_file_base + (0x0202));
// 0x03060302 03 06 03 02
PsmDefine.gct_file_shell = (PsmDefine.gct_file_base + (0x0302));
// realtime
PsmDefine.gct_realtime_base = (PsmDefine.gct_core5_base + (0x050000));
// 0x05050101 05 05 01 01
PsmDefine.gct_realtime_data_request = (PsmDefine.gct_realtime_base + (0x0101));
// 0x05050101 05 05 01 02
PsmDefine.gct_realtime_data_post = (PsmDefine.gct_realtime_base + (0x0102));
PsmDefine.GM_req_sys_login_1 = 'req.sys.user.login.1';
PsmDefine.GM_req_db_sql_execute_1 = 'req.db.sql.execute.1';
PsmDefine.GM_req_db_sql_select_1 = 'req.db.sql.select.1';
PsmDefine.GM_resp_sys_login_1 = 'resp.sys.user.login.1';
PsmDefine.GM_resp_db_sql_execute_1 = 'resp.db.sql.execute.1';
PsmDefine.GM_resp_db_sql_select_1 = 'resp.db.sql.select.1';
PsmDefine.CS_EntryPsmStationNumSource = 'PsmStationNumSource';
PsmDefine.CS_EntryPsmStationNumTarget = 'PsmStationNumTarget';
PsmDefine.CS_EntryPsmSentReason = 'PsmSentReason';
PsmDefine.CS_EntryPsmSentContainerId = 'PsmSentContainerId';
PsmDefine.CS_EntryPsmSentSourceId = 'PsmSentSourceId';
PsmDefine.CS_EntryPsmSentTargetId = 'PsmSentTargetId';
PsmDefine.CS_EntryPsmSentTag = 'PsmSentTag';
PsmDefine.CS_EntryPsmHeartJumpInterval = 'PsmHeartJumpInterval';
PsmDefine.CS_EntryPsmYxSendInterval = 'PsmSendYxInterval';
PsmDefine.CS_EntryPsmYcSendInterval = 'PsmSendYcInterval';
PsmDefine.CS_EntryPsmYwSendInterval = 'PsmSendYwInterval';
PsmDefine.DealReplyType_None = 0;
PsmDefine.DealReplyType_Ack = 1;
PsmDefine.DealReplyType_Nack = 2;
PsmDefine.DealReplyType_Define = 3;
//* *
function PsmAttach(iReason = 0, iContainerId = 0, iSourceId = 0, iTargetId = 0, iTag = 0) {
this.reason = iReason;
this.containerId = iContainerId;
this.sourceId = iSourceId;
this.targetId = iTargetId;
this.tag = iTag;
}
/**
* UserException
* @param message
* @constructor
*/
function UserException(message) {
this.message = message;
this.name = 'UserException';
}
/**
* BasAttr
* @param name
* @param size
* @param type
* @param encoding
* @constructor
*/
function BaseAttr(name, size, type, encoding) {
if (!name) {
throw new UserException('invalid name');
}
this.name = name;
this.size = size;
this.type = type;
this.encoding = encoding;
}
BaseAttr.CI_Type_None = 0;
BaseAttr.CI_Type_int = 1;
BaseAttr.CI_Type_long = 2;
BaseAttr.CI_Type_float = 3;
BaseAttr.CI_Type_double = 4;
BaseAttr.CI_Type_string = 5;
/**
* PsmRealtimeDataStruct
* @constructor
*/
function PsmRealtimeDataStruct() {
this.stack = [];
this.paramType = 0;
this.byteCount = 0;
}
PsmRealtimeDataStruct.structs = new Map();
PsmRealtimeDataStruct.getByteCount = function(stack) {
let iSize = 0;
let attr;
let idx = 0;
while (idx < stack.length) {
attr = stack[idx++];
iSize += attr.size;
}
return iSize;
};
PsmRealtimeDataStruct.prototype.add = function(name, size = 4, type = BaseAttr.CI_Type_int, encoding = 'ascii') {
if (size === 4 && type !== BaseAttr.CI_Type_int) {
return;
}
this.stack.push(new BaseAttr(name, size, type, encoding));
};
PsmRealtimeDataStruct.prototype.setParamType = function(paramType) {
this.paramType = paramType;
this.byteCount = PsmRealtimeDataStruct.getByteCount(this.stack);
PsmRealtimeDataStruct.structs.set(paramType, this);
};
PsmRealtimeDataStruct.prototype.toBuffer = function(objs) {
if (!(objs instanceof Array)) {
return Buffer.allocUnsafe(0);
}
let rBuf = Buffer.allocUnsafe(this.byteCount * objs.length);
let obj;
let stack = this.stack;
let stackLength = stack.length;
let i, j;
let attr;
let value;
let iOffset = 0;
for (i = 0; i < objs.length; i++) {
obj = objs[i];
for (j = 0; j < stackLength; j++) {
attr = stack[j];
value = obj[attr.name];
switch (attr.type) {
case BaseAttr.CI_Type_int:
if (attr.size > 4) {
rBuf.writeInt32LE(value, iOffset, true);
iOffset += 4;
} else {
rBuf.writeIntLE(value, iOffset, attr.size, true);
iOffset += attr.size;
}
break;
case BaseAttr.CI_Type_long:
rBuf.writeIntLE(value, iOffset, 6, true);
iOffset += 8;
break;
case BaseAttr.CI_Type_float:
rBuf.writeFloatLE(value, iOffset, true);
iOffset += 4;
break;
case BaseAttr.CI_Type_double:
rBuf.writeDoubleLE(value, iOffset, true);
iOffset += 8;
break;
case BaseAttr.CI_Type_string:
if (value.length > attr.size) {
rBuf.write(value, iOffset, attr.size);
} else {
rBuf.write(value, iOffset, value.length);
rBuf[iOffset + value.length] = 0;
}
iOffset += attr.size;
break;
default:
break;
}
}
}
return rBuf;
};
PsmRealtimeDataStruct.prototype.fromBuffer = function(bufData) {
let objs = [];
if (!(bufData instanceof Buffer)) {
return objs;
}
let stack = this.stack;
let stackLength = stack.length;
let i, j;
let attr;
let value;
let iOffset = 0;
let iCount = bufData.length / this.byteCount;
for (i = 0; i < iCount; i++) {
let obj = {};
for (j = 0; j < stackLength; j++) {
attr = stack[j];
switch (attr.type) {
case BaseAttr.CI_Type_int:
if (attr.size > 4) {
value = bufData.readInt32LE(iOffset, 4, true);
iOffset += 4;
} else {
value = bufData.readIntLE(iOffset, attr.size, true);
iOffset += attr.size;
}
break;
case BaseAttr.CI_Type_long:
value = bufData.readIntLE(iOffset, 6, true);
iOffset += 8;
break;
case BaseAttr.CI_Type_float:
value = bufData.readFloatLE(iOffset, 4, true);
iOffset += 4;
break;
case BaseAttr.CI_Type_double:
value = bufData.readDoubleLE(iOffset, 8, true);
iOffset += 8;
break;
case BaseAttr.CI_Type_string:
value = bufData.toString('utf8', iOffset, iOffset + attr.size);
iOffset += attr.size;
break;
default:
//
break;
}
Object.defineProperty(obj, attr.name, {
configurable: true,
enumerable: true,
value: value,
});
}
objs.push(obj);
}
return objs;
};
function PsmReceivePacket() {
this._head = 0;
this._front = 0;
this._dataLength = 0;
this._body = new PsmPacketBody();
this._end = 0;
this._state = 0;
this._dataOffset = 0;
// recvCache : recv data -> push to recvCache
this.recvCache = Buffer.allocUnsafeSlow(PsmDefine.PACKAGE_MAX_BUF_SIZE);
this.recvOffset = 0;
this.dealOffset = 0;
this.onReceivedPacket = 0;
}
/**
* only deal on complete psm packet
* @param data
*/
PsmReceivePacket.prototype.doReceived = function(data) {
if (!data) {
throw new UserException('BasParser.prototype.handleRecv(buf) : invalid buf!');
}
if (data.length > PsmDefine.PACKAGE_MAX_SIZE) {
console.log('BasParser.prototype.handleRecv(buf) : data.length > PsmDefine.PACKAGE_MAX_SIZE!');
return;
}
if (data.length > (PsmDefine.PACKAGE_MAX_BUF_SIZE - this.recvOffset)) {
let iNoDeal = this.recvOffset - this.dealOffset;
if (iNoDeal > PsmDefine.PACKAGE_MAX_SIZE) {
this.recvOffset = 0;
console.log('BasParser.prototype.handleRecv(buf) : iNoDeal > PsmDefine.PACKAGE_MAX_SIZE!');
} else {
this.recvCache.copy(this.recvCache, 0, this.dealOffset, this.recvOffset);
this.recvOffset = iNoDeal;
}
this.dealOffset = 0;
}
data.copy(this.recvCache, this.recvOffset);
this.recvOffset += data.length;
this.dealCache();
};
PsmReceivePacket.prototype.dealCache = function() {
let index = this.dealOffset;
let end = this.recvOffset;
let buf = this.recvCache;
let state = this._state;
if (end - index < PsmDefine.ci_psm_fix_size) {
return;
}
while (index < end) {
switch (state) {
case 0: {
this._head = buf.readInt32LE(index, true);
index += 4;
if (this._head === PsmDefine.c_psm_head) {
state = 1;
}
}
break;
case 1: {
this._front = buf.readInt16LE(index, true);
index += 2;
state = 2;
}
break;
case 2: {
this._dataLength = buf.readInt16LE(index, true);
index += 2;
state = 3;
}
break;
case 3: {
index = this._body.fromBuffer(buf, index);
this._dataOffset = index;
state = (this._dataLength > 0) ? 4 : 5;
}
break;
case 4: {
if (index >= (this._dataOffset + this._dataLength)) {
state = 5;
break;
}
++index;
}
break;
case 5: {
if (end - index > 1) {
this._end = buf.readInt16LE(index, true);
index += 2;
state = 0;
// todo:best:crc
if (this.onReceivedPacket) {
this.onReceivedPacket();
}
}
}
break;
default:
break;
}
}
this.dealOffset = index;
this._state = state;
};
function packetPsmSend(body, bufData) {
let r = Buffer.allocUnsafe(PsmDefine.ci_psm_fix_size + bufData.length);
let iOffset = 0;
r.writeInt32LE(PsmDefine.c_psm_head, iOffset, true);
iOffset += 4;
r.writeInt16LE(1, iOffset, true);
iOffset += 2;
r.writeInt16LE(bufData.length, iOffset, true);
iOffset += 2;
let bufBody = body.toBuffer();
bufBody.copy(r, iOffset);
iOffset += bufBody.length;
bufData.copy(r, iOffset);
iOffset += bufData.length;
let crc = crc16(r, 0, iOffset);
r.writeInt16LE(crc, iOffset, true);
return r;
}
function PsmFileDataInfo(fileName = '', fileDir = '', fileSize = 0, fileData = [], attach = null) {
this.fileName = fileName;
this.fileDir = fileDir;
this.fileSize = fileSize;
this.fileData = fileData;
this.attach = attach;
}
PsmFileDataInfo.getFileSize = function(fileData) {
let iFileSize = 0;
for (let i = 0; i < fileData.length; i++) {
iFileSize += fileData[i].length;
}
return iFileSize;
};
function PsmProtocol() {
let self = this;
this._psmExplainNotify = null;
this._psmExplainWrite = null;
this._receiveFileCurrentDataInfo = new PsmFileDataInfo();
this._receivedFileSize = 0; // int
this._receiveFileInfoTargetId = 0; // int
this._sendFileCurrentDataInfo = new PsmFileDataInfo();
this._sendFileQueueDataInfos = [];
this._sendFilePathes = new Map(); // std::map<std::string, PsmAttach>
this._sendFileCurrentIndex = 0; // int
this._sendFileTime = 0; // msepoch_t
this._sendingFileTime = 0; // msepoch_t
this._sendFileInfoName = '';
this._sendFileInfoSize = 0;
this._sendFileInfoAttach = new PsmAttach(); // PsmAttach
this._sendFileTexts = [];// std::vector<std::string>
this._sendFileSreamInfos = []; // std::queue<CxFileSystem::PathInfo>
this._sendFileSreamDatas = []; // std::queue<std::vector<std::string> >
this._sendFileSreamAttach = []; // std::queue<PsmAttach>
this._lastReceivedDataTime = 0; // msepoch_t
this._sentSourceId = 0; // int
this._sentTargetId = 0; // int
// //*lock
// std::queue<PsmMessage> _processMessages;
// std::queue<PsmFile> _processFiles;
// std::queue<PsmData> _processRealtimeDataRequests;
// std::queue<PsmRealtimeData> _processRealtimeDatas;
// std::queue<PsmFile> _processResultFiles;
this._fileSavePath = ''; // std::string
// //#lock
// CxMutex _processLock;
//* receivePacket
let receivePacket = new PsmReceivePacket();
receivePacket.onReceivedPacket = function() {
self.dealPacket();
};
//* channel
let channel = new CjChannelUdp();
channel.isAutoOpen = true;
channel.onReceived = function(data) {
receivePacket.doReceived(data);
};
this.fns = new Map();
this.fnAllPacket = null;
this.channel = channel;
this.receivePacket = receivePacket;
//* on
this.onReceivedMessage = null; // onReceivedMessage(sCommand, sParam, attach)
this.onReceivedFile = null; // onReceivedFile(PsmFileDataInfo)
this.onReceivedRealtimeDataPost = null; // onReceivedRealtimeDataPost(iParamType, bufParam, iParamCount, attach)
this.onReceivedRealtimeDataStruct = null; // onReceivedRealtimeDataStruct(iParamType, structs, attach)
this.onReceivedRealtimeDataRequest = null; // onReceivedRealtimeDataRequest(attach)
this.onSentMessage = null; // onSentMessage(iResult, sCommand, sParam, attach)
this.onSentFile = null; // onSentFile(iResult, sFilePath) || onSentFile(iResult, PsmFileDataInfo)
}
/**
*
* @param option = {LocalIpAddress:'127.0.0.1', LocalPort: 5555, RemoteIpAddress: '127.0.0,.1', RemotePort: 5556, FileSavePath: '/temp'};
*/
PsmProtocol.prototype.start = function(option) {
// tcpclient1.open({port: 5556, host: '127.0.0.1'});
this.channel.open(option);
this.checkProtocol(1000);
this._fileSavePath = option.FileSavePath;
};
PsmProtocol.prototype.stop = function() {
this.checkProtocol(0);
this.channel.close();
};
// this._body, this.recvCache, this._dataOffset, this._dataLength
PsmProtocol.prototype.dealPacket = function() {
let body = this.receivePacket._body;
if (body.controlWord === PsmDefine.CIPsmControlCode_NACK) {
this.dealNack(body);
} else {
let bufData = Buffer.allocUnsafe(this.receivePacket._dataLength);
this.receivePacket.recvCache.copy(bufData, 0, this.receivePacket._dataOffset, this.receivePacket._dataOffset + this.receivePacket._dataLength);
let iDeal = 0;
switch (body.command) {
//* heart jump
case PsmDefine.gct_channel_hand: {
iDeal = PsmDefine.DealReplyType_Ack;
}
break;
//* message
case PsmDefine.gct_message_command_param: {
iDeal = this.dealMessageCommand(body, bufData);
}
break;
//* realtime
case PsmDefine.gct_realtime_data_request: {
iDeal = this.dealRealtimeRequest(body, bufData);
}
break;
case PsmDefine.gct_realtime_data_post: {
iDeal = this.dealRealtimePost(body, bufData);
}
break;
//* file
case PsmDefine.gct_file_information_write: {
iDeal = this.dealFileInformationWrite(body, bufData);
}
break;
case PsmDefine.gct_file_content_write: {
iDeal = this.dealFileDataWrite(body, bufData);
}
break;
case PsmDefine.gct_file_shell:
// iDeal = this.dealFileShell();
break;
default:
break;
}
if (iDeal === PsmDefine.DealReplyType_Ack) {
let iReason = body.reason;
let iContainerId = body.container;
let iSourceID = body.targetAddress;
let iTargetId = body.sourceAddress;
let iTag = body.resCommand;
let attach = new PsmAttach(iReason, iContainerId, iSourceID, iTargetId, iTag);
this.responseAck(body.command, attach);
} else if (iDeal < 0) {
let iReason = body.reason;
let iContainerId = body.container;
let iSourceID = body.targetAddress;
let iTargetId = body.sourceAddress;
let iTag = body.resCommand;
let attach = new PsmAttach(iReason, iContainerId, iSourceID, iTargetId, iTag);
this.responseNack(body.command, iDeal, attach);
}
}
};
PsmProtocol.prototype.dealNack = function(body) {
switch (body.command) {
case PsmDefine.gct_file_information_write:
case PsmDefine.gct_file_content_write: {
if (body.command === PsmDefine.gct_file_information_write) {
this._sendFileCurrentIndex = -1;
}
++this._sendFileCurrentIndex;
if (this._sendFileCurrentIndex < this._sendFileCurrentDataInfo.fileData.length) {
let fileData = this._sendFileCurrentDataInfo.fileData[this._sendFileCurrentIndex];
let iReason = body.reason;
let iContainerId = body.container;
let iSourceID = body.targetAddress;
let iTargetId = body.sourceAddress;
let iTag = body.resCommand;
let attach = new PsmAttach(iReason, iContainerId, iSourceID, iTargetId, iTag);
this.sendFileData(fileData, attach);
} else {
this.sendFileComplete();
this._sendFileCurrentIndex = -1;
this._sendFileTime = 0;
this._sendingFileTime = 0;
this.sendNextFilePath();
}
}
break;
default:
break;
}
};
PsmProtocol.prototype.dealMessageCommand = function(body, bufData) {
if (bufData.length > 0) {
let iParam = bufData.indexOf(0);
let sCommand = bufData.toString('utf8', 0, iParam);
let iParamLength = bufData.readInt32LE(iParam + 1);
let sParam = '';
if (iParamLength > 0) {
sParam = bufData.toString('utf8', iParam + 5);
}
let iReason = body.reason;
let iContainerId = body.container;
let iSourceID = body.sourceOriginal;
let iTargetId = body.targetAddress;
let iTag = body.resCommand;
let attach = new PsmAttach(iReason, iContainerId, iSourceID, iTargetId, iTag);
this.receivedMessageCommand(sCommand, sParam, attach);
return PsmDefine.DealReplyType_Ack;
}
return PsmDefine.DealReplyType_Error_Data;
};
PsmProtocol.prototype.dealFileInformationWrite = function(body, bufData) {
let pathInfo = PsmProtocol.pathInfoFromBuffer(bufData);
this._receiveFileCurrentDataInfo.fileName = pathInfo[0];
this._receiveFileCurrentDataInfo.fileSize = pathInfo[1];
if (this._receiveFileCurrentDataInfo.fileSize > 0) {
this._receiveFileCurrentDataInfo.fileData = [];
this._receivedFileSize = 0;
this._receiveFileInfoTargetId = body.targetAddress;
return PsmDefine.DealReplyType_Ack;
} else {
return PsmDefine.DealReplyType_Error_Data;
}
};
PsmProtocol.prototype.dealFileDataWrite = function(body, bufData) {
if (bufData.length <= 0) {
return;
}
this._receiveFileCurrentDataInfo.fileData.push(bufData);
this._receivedFileSize += bufData.length;
if (this._receivedFileSize >= this._receiveFileCurrentDataInfo.fileSize) {
let iReason = body.reason;
let iContainerId = body.container;
let iSourceID = body.sourceOriginal;
let iTargetId = this._receiveFileInfoTargetId;// body.targetAddress;
let iTag = body.resCommand;
this._receiveFileCurrentDataInfo.attach = new PsmAttach(iReason, iContainerId, iSourceID, iTargetId, iTag);
this.receivedFileWrite();
}
};
PsmProtocol.prototype.dealRealtimeRequest = function(body, bufData) {
let iReason = body.reason;
let iContainerId = body.container;
let iSourceID = body.sourceOriginal;
let iTargetId = body.targetAddress;
let iTag = body.resCommand;
let attach = new PsmAttach(iReason, iContainerId, iSourceID, iTargetId, iTag);
this.receivedRealtimeDataRequest(attach);
return PsmDefine.DealReplyType_Define;
};
PsmProtocol.prototype.dealRealtimePost = function(body, bufData) {
if (bufData.length > 0) {
let iReason = body.reason;
let iContainerId = body.container;
let iSourceID = body.sourceOriginal;
let iTargetId = body.targetAddress;
let iTag = body.resCommand;
let attach = new PsmAttach(iReason, iContainerId, iSourceID, iTargetId, iTag);
this.receivedRealtimeDataPost(body.paramType, bufData, body.paramCount, attach);
return PsmDefine.DealReplyType_Ack;
}
return PsmDefine.DealReplyType_Error_Data;
};
PsmProtocol.prototype.postMessageCommand = function(sCommand, sParam = '', attach = null) {
if (!(typeof sCommand === 'string' || sCommand instanceof String)) {
return -1;
}
if (!(typeof sParam === 'string' || sParam instanceof String)) {
return -1;
}
let bufCommand = Buffer.from(sCommand);
let bufParam = Buffer.from(sParam);
let bufData = Buffer.allocUnsafe(bufCommand.length + 1 + 4 + bufParam.length);
let iOffset = 0;
bufCommand.copy(bufData, iOffset);
iOffset += bufCommand.length;
bufData.writeInt8(0, iOffset, true);
iOffset += 1;
bufData.writeInt32LE(bufParam.length, iOffset, true);
iOffset += 4;
bufParam.copy(bufData, iOffset);
return this.postData(PsmDefine.gct_message_command_param, 0, bufData, 0, attach);
};
PsmProtocol.prototype.postFile = function(sFilePath, attach = null) {
this._sendFilePathes.set(sFilePath, attach);
return this.sendNextFilePath();
};
PsmProtocol.prototype.postFileData = function(fileName, fileData, attach = null) {
let fileDataInfo = new PsmFileDataInfo(fileName, '', PsmFileDataInfo.getFileSize(fileData), fileData, attach);
this._sendFileQueueDataInfos.push(fileDataInfo);
return this.sendNextFilePath();
};
PsmProtocol.prototype.postRealtimeDataRequest = function(attach = null) {
return this.postData(PsmDefine.gct_realtime_data_request, 0, 0, 0, attach);
};
PsmProtocol.prototype.postRealtimeDataPost = function(iParamType, bufParam, iParamCount, attach = null) {
return this.postData(PsmDefine.gct_realtime_data_post, iParamType, bufParam, iParamCount, attach);
};
PsmProtocol.prototype.postRealtimeDataStructsPost = function(iParamType, structs, attach = null) {
let struct = PsmRealtimeDataStruct.structs.get(iParamType);
if (struct) {
let bufData = struct.toBuffer(structs);
if (bufData.length > 0) {
return this.postData(PsmDefine.gct_realtime_data_post, iParamType, bufData, structs.length, attach);
} else {
return -2;
}
} else {
return -1;
}
};
PsmProtocol.prototype.postHeartJump = function(attach = null) {
return this.postData(PsmDefine.gct_channel_hand, 0, 0, 1, attach);
};
PsmProtocol.prototype.sendFileData = function(fileData, attach) {
this.postData(PsmDefine.gct_file_content_write, 0, fileData, 0, attach);
this._sendingFileTime = Date.now();
};
/**
*
* @param sFilePath
* @param fnAfterLoad = function(iResult, <Array<buffer>>fileDatas)
* @param iSpitLength
*/
PsmProtocol.loadFile = function(sFilePath, fnAfterLoad, iSpitLength = 1024) {
if (!(fnAfterLoad instanceof Function)) {
return;
}
const readable = fs.createReadStream(sFilePath);
let iResult = 0;
let rFileDatas = [];
readable.on('error', (err) => {
iResult = -1;
fnAfterLoad(iResult);
});
readable.on('readable', () => {
let chunk;
while (null !== (chunk = readable.read(iSpitLength))) {
rFileDatas.push(chunk);
iResult += chunk.length;
}
});
readable.on('end', function() {
fnAfterLoad(iResult, rFileDatas);
});
};
PsmProtocol.prototype.sendNextFilePath = function() {
let r = 0;
let self = this;
if (self._sendFilePathes.size > 100) {
self._sendFilePathes.clear();
r = -2;
return r;
}
if (self._sendFileQueueDataInfos.size > 100) {
self._sendFileQueueDataInfos = [];
r = -2;
return r;
}
if (self._sendFileTime === 0 && self._sendingFileTime === 0) {
if (self._sendFileQueueDataInfos.size() > 0) {
self._sendFileCurrentDataInfo = self._sendFileQueueDataInfos.shift();
self._sendFileTime = Date.now();
r = self.sendFileInfo();
} else {
let sFilePath = null, attach = null;
for ([sFilePath, attach] of self._sendFilePathes) {
break;
}
if (sFilePath !== null) {
self._sendFilePathes.delete(sFilePath);
PsmProtocol.loadFile(sFilePath, function(iResult, fileDates) {
if (iResult > 0) {
self._sendFileCurrentDataInfo = new PsmFileDataInfo(path.basename(sFilePath), path.dirname(sFilePath), iResult, fileDates, attach);
self._sendFileTime = Date.now();
r = self.sendFileInfo();
} else {
if (self.onSentFile) {
self.onSentFile(-3, sFilePath);
}
}
});
} else {
r = -4;
}
}
} else {
r = 1;
}
return r;
};
PsmProtocol.prototype.sendFileComplete = function() {
if (this.onSentFile) {
this.onSentFile(this._sendFileCurrentDataInfo.fileSize, this._sendFileCurrentDataInfo);
}
};
PsmProtocol.prototype.sendFileInfo = function() {
let bufData = PsmProtocol.pathInfoToBuffer(this._sendFileCurrentDataInfo.fileName, this._sendFileCurrentDataInfo.fileSize);
return this.postData(PsmDefine.gct_file_information_write, 0, bufData, 0, this._sendFileCurrentDataInfo.attach);
};
PsmProtocol.pathInfoToBuffer = function(fileName, fileSize) {
let bufFileName = new Buffer(fileName);
let r = Buffer.allocUnsafe(bufFileName.length + 5);
bufFileName.copy(r, 0);
r.writeInt8(0, bufFileName.length, true);
r.writeInt32LE(fileSize, bufFileName.length + 1, true);
return r;
};
PsmProtocol.pathInfoFromBuffer = function(buf) {
let rFileName = buf.toString('utf8', 0, buf.length - 5);
let rFileSize = buf.readInt32LE(buf.length - 4, true);
return [rFileName, rFileSize];
};
/**
*
* @param iCommand
* @param iParamType
* @param bufData
* @param iParamCount
* @param attach
* @returns int
*/
PsmProtocol.prototype.postData = function(iCommand, iParamType, bufData, iParamCount, attach = null) {
let iReason = 0;
let iContainerId = 0;
let iSourceId = 0;
let iTargetId = 0;
let iTag = 0;
if (attach !== null) {
iReason = attach.reason;
iContainerId = attach.containerId;
iSourceId = attach.sourceId;
iTargetId = attach.targetId;
iTag = attach.tag;
}
let body = new PsmPacketBody();
body.sourceOriginal = iSourceId;
if (this._sentSourceId > 0) {
body.sourceAddress = this._sentSourceId;
} else {
body.sourceAddress = iSourceId;
}
body.resFrame = 0;
if (this._sentTargetId > 0) {
body.targetAddress = this._sentTargetId;
} else {
body.targetAddress = iTargetId;
}
body.controlWord = PsmDefine.CIPsmControlCode_Initiactive;
body.command = iCommand;
body.reason = iReason;
body.resCommand = iTag;
body.container = iContainerId;
body.paramType = iParamType;
body.paramCount = iParamCount;
return this.postPacketData(body, bufData);
};
/**
*
* @param iCommand
* @param attach
* @returns int
*/
PsmProtocol.prototype.responseAck = function(iCommand, attach) {
let iReason = 0;
let iContainerId = 0;
let iSourceId = 0;
let iTargetId = 0;
let iTag = 0;
if (attach !== null) {
iContainerId = attach.containerId;
iSourceId = attach.sourceId;
iTargetId = attach.targetId;
iTag = attach.tag;
}
let body = new PsmPacketBody();
body.frameType = 0;
body.sourceOriginal = iSourceId;
if (this._sentSourceId > 0) {
body.sourceAddress = this._sentSourceId;
} else {
body.sourceAddress = iSourceId;
}
body.resFrame = 0;
body.targetAddress = iTargetId;
body.controlWord = PsmDefine.CIPsmControlCode_NACK;
body.command = iCommand;
body.reason = iReason;
body.resCommand = iTag;
body.container = iContainerId;
body.paramType = 0;
body.paramCount = 0;
return this.postPacketData(body, Buffer.allocUnsafe(0));
};
/**
*
* @param iCommand
* @param iErrorid
* @param attach
* @returns int
*/
PsmProtocol.prototype.responseNack = function(iCommand, iErrorid, attach) {
let iReason = iErrorid;
let iContainerId = 0;
let iSourceId = 0;
let iTargetId = 0;
let iTag = 0;
if (attach !== null) {
iContainerId = attach.containerId;
iSourceId = attach.sourceId;
iTargetId = attach.targetId;
iTag = attach.tag;
}
let body = new PsmPacketBody();
body.frameType = 0;
body.sourceOriginal = iSourceId;
if (this._sentSourceId > 0) {
body.sourceAddress = this._sentSourceId;
} else {
body.sourceAddress = iSourceId;
}
body.resFrame = 0;
body.targetAddress = iTargetId;
body.command = iCommand;
body.reason = iReason;
body.resCommand = iTag;
body.container = iContainerId;
body.paramType = 0;
body.paramCount = 0;
return this.postPacketData(body, Buffer.allocUnsafe(0));
};
/**
* postPacketData
* @param {Object}body
* @param {Buffer}bufData
* @return {Number}int
*/
PsmProtocol.prototype.postPacketData = function(body, bufData) {
let buf = packetPsmSend(body, bufData);
return this.channel.sendData(buf);
};
/**
* reportSelf
* @return {String}string
*/
PsmProtocol.prototype.reportSelf = function() {
let sLastTime = new Date(this._lastReceivedDataTime);
return util.format(' sentSourceId: %d, sentTargetId: %d, lastReceivedDataTime: %s ',
this._sentSourceId, this._sentTargetId, sLastTime);
};
PsmProtocol.prototype.checkProtocol = function(interval) {
let self = this;
if (interval < 1000) {
if (self.checkTimer) {
clearTimeout(self.checkTimer);
}
return;
}
if (self.checkTimer) {
clearTimeout(self.checkTimer);
}
let timeOut = function() {
// 发送超时
if (self._sendingFileTime !== 0) {
if ((Date.now() - self._sendingFileTime) > 1000) {
self._sendFileCurrentDataInfo = new PsmFileDataInfo();
self._sendFileCurrentIndex = -1;
self._sendFileTime = 0;
self._sendingFileTime = 0;
}
} else if (self._sendFileTime !== 0) {
if ((Date.now() - self._sendFileTime) > 1000) {
self._sendFileCurrentDataInfo = new PsmFileDataInfo();
self._sendFileCurrentIndex = -1;
self._sendFileTime = 0;
self._sendingFileTime = 0;
}
}
self.checkTimer = setTimeout(timeOut, interval);
};
self.checkTimer = setTimeout(timeOut, interval);
};
PsmProtocol.prototype.receivedMessageCommand = function(sCommand, sParam, attach) {
if (this.onReceivedMessage instanceof Function) {
this.onReceivedMessage(sCommand, sParam, attach);
}
};
PsmProtocol.prototype.receivedFileWrite = function() {
if (this.onReceivedFile instanceof Function) {
this.onReceivedFile(this._receiveFileCurrentDataInfo);
}
};
PsmProtocol.prototype.receivedRealtimeDataRequest = function(attach) {
if (this.onReceivedRealtimeDataRequest instanceof Function) {
this.onReceivedRealtimeDataRequest(attach);
}
};
PsmProtocol.prototype.receivedRealtimeDataPost = function(iParamType, bufParam, iParamCount, attach) {
if (this.onReceivedRealtimeDataPost instanceof Function) {
this.onReceivedRealtimeDataPost(iParamType, bufParam, iParamCount, attach);
}
if (this.onReceivedRealtimeDataStruct instanceof Function) {
let struct = PsmRealtimeDataStruct.structs.get(iParamType);
if (struct) {
let objs = struct.fromBuffer(bufParam);
this.onReceivedRealtimeDataStruct(iParamType, objs, attach);
}
}
};
PsmProtocol.prototype.on = function(command, fn) {
this.fns.set(command, fn);
};
PsmProtocol.prototype.dispatch = function(command, msgObj) {
let fn = this.fns.get(command);
if (fn) {
fn(msgObj);
} else if (this.fnAllPacket) {
this.fnAllPacket(command, msgObj);
}
};
PsmProtocol.prototype.sendPacket = function(packet) {
return this.channel.sendData(packet);
};
PsmProtocol.PsmDefine = PsmDefine;
PsmProtocol.PsmRealtimeDataStruct = PsmRealtimeDataStruct;
// Init User Packet
{
let yxStruct = new PsmRealtimeDataStruct();
yxStruct.add('address');
yxStruct.add('value');
yxStruct.add('quality');
yxStruct.add('datetime', 8, BaseAttr.CI_Type_long);
yxStruct.setParamType(0x01010203);
PsmRealtimeDataStruct.yxStruct = yxStruct;
let ycStruct = new PsmRealtimeDataStruct();
ycStruct.add('address');
ycStruct.add('value', 8, BaseAttr.CI_Type_double);
ycStruct.add('quality');
ycStruct.add('datetime', 8, BaseAttr.CI_Type_long);
ycStruct.setParamType(0x0101021C);
PsmRealtimeDataStruct.ycStruct = ycStruct;
let ywStruct = new PsmRealtimeDataStruct();
ywStruct.add('address');
ywStruct.add('value', 128, BaseAttr.CI_Type_string);
ywStruct.add('quality');
ywStruct.add('datetime', 8, BaseAttr.CI_Type_long);
ywStruct.setParamType(0x0101022F);
PsmRealtimeDataStruct.ycStruct = ywStruct;
if (false) {
let psm = new PsmProtocol();
psm.start({
LocalIpAddress: '127.0.0.1',
LocalPort: 5555,
RemoteIpAddress: '127.0.0,.1',
RemotePort: 5556,
FileSavePath: 'f:/temp',
});
let yxes = [
{address: 0x01000001, value: 1, quality: 1, datetime: Date.now()},
{address: 0x01000002, value: 2, quality: 1, datetime: Date.now()},
];
let iResult = psm.postRealtimeDataStructsPost(PsmRealtimeDataStruct.yxStruct.paramType, yxes);
console.log('psm.postRealtimeDataStructsPost iResult=', iResult);
}
}
PsmProtocol.test1 = function() {
let psmProtocol = new PsmProtocol();
psmProtocol.start({
LocalIpAddress: '127.0.0.1',
LocalPort: 9005,
RemoteIpAddress: '127.0.0.1',
RemotePort: 9105,
FileSavePath: 'f:/temp',
});
// all in
psmProtocol.onReceivedMessage = function(sCommand, sParam, attach) {
console.log(sCommand, sParam);
};
let iTimes = 0;
setInterval(function() {
let yxes = [
{address: 0x01000001 + iTimes, value: iTimes++, quality: 1, datetime: Date.now()},
{address: 0x01000001 + iTimes, value: iTimes++, quality: 1, datetime: Date.now()},
];
let iResult = psmProtocol.postRealtimeDataStructsPost(PsmRealtimeDataStruct.yxStruct.paramType, yxes);
let sLog = 'psmProtocol.postRealtimeDataStructsPost iResult=' + iResult.toString();
console.log(sLog);
fs.writeFile('f:/001.txt', sLog, function(err) {
if (err) {
console.log(err);
}
});
iResult = psmProtocol.postMessageCommand('post.tts.1', 'txt=你好才是大家好');
sLog = 'psmProtocol.postMessageCommand iResult=' + iResult.toString();
console.log(sLog);
fs.writeFile('f:/001.txt', sLog, function(err) {
if (err) {
console.log(err);
}
});
}, 3000);
};
<file_sep>#!/usr/bin/env bash
# build dockerfile
docker build -t oudream/ubuntu-ccxx-env:18.04.12 .
# run on vps
docker run -d -p 2235:22 -v /opt/ddd:/opt/ddd oudream/ubuntu-ccxx-env:18.04.12
ssh [email protected] -p 2235 -AXY -v
# run on macos(localhost)
docker run -d -p 2235:22 -p 8821:8821 -p 8841:8841 -p 8861:8861 -v /opt/ddd:/opt/ddd oudream/ubuntu-ccxx-env:18.04.12
ssh root@localhost -p 2235 -AXY -v
###
docker run -d -p 2235:22 oudream/ubuntu-ccxx-env:18.04.12
ssh root@localhost -p 2235 -AXY -v
password: <PASSWORD>
/opt/ccxx/build/deploy/unix/bin_d/cxtest_timer
# or
/opt/ccxx/build/deploy/unix/bin_d/cxtest_channel_udp_client1
# or
/opt/ccxx/build/deploy/unix/bin_d/cxtest_channel_udp_server1
# or
/opt/ccxx/build/deploy/unix/bin_d/cxsample_lua
# or
/opt/ccxx/build/deploy/unix/bin_d/benchmark_cxstring
# ctrl + c to exit
^c
docker login
docker push oudream/ubuntu-ccxx-env:18.04.12
<file_sep>cmake_minimum_required(VERSION 3.0)
project(hello)
find_package(Qt5 REQUIRED COMPONENTS Widgets)
add_executable(hello Main.cpp)
target_link_libraries(hello Qt5::Widgets)<file_sep>require('./../cjmeta_lang');
let expect = require('./../../chai-4').expect;
describe('CjMeta', function() {
it('getObjectClassName', function() {
function Obj1() { }
let obj1 = new Obj1();
// var util = require('util');
// util.inherits(obj, Object);
// console.log('xxxxx1:'+cjs.CjMeta.getObjectClassName(obj1));
Object.setPrototypeOf(Obj1.prototype, Object.prototype);
expect(cjs.CjMeta.getObjectClassName(obj1)).to.equal('Obj1');
});
});
<file_sep>FROM alpine:3.10
LABEL maintainer="oudream - https://github.com/oudream"
ENTRYPOINT ["/opt/entrypoint.sh"]
EXPOSE 22
COPY rootfs /opt/
RUN apk update && \
apk upgrade
RUN apk add --no-cache openssh \
&& sed -i s/#PermitRootLogin.*/PermitRootLogin\ yes/ /etc/ssh/sshd_config \
&& echo "root:root" | chpasswd \
&& passwd -d root \
&& ssh-keygen -A
COPY identity.pub /root/.ssh/authorized_keys
RUN apk add xauth \
xclock \
&& sed -i "s/^.*X11Forwarding.*$/X11Forwarding yes/" /etc/ssh/sshd_config \
&& sed -i "s/^.*X11UseLocalhost.*$/X11UseLocalhost no/" /etc/ssh/sshd_config \
&& grep "^X11UseLocalhost" /etc/ssh/sshd_config || echo "X11UseLocalhost no" >> /etc/ssh/sshd_config \
&& touch /root/.Xauthority \
&& chmod 600 /root/.Xauthority
RUN apk add --update alpine-sdk && \
apk add autoconf cmake git gdb rsync vim screen unixodbc-dev unixodbc libuuid ncurses-dev && \
apk add libffi-dev openssl-dev python3-dev && \
apk add nodejs && \
apk add python3 && \
apk add qt5-qtbase-dev qt5-qtsvg-dev && \
apk add qt5-qtbase qt5-qtsvg
<file_sep>/**
* Created by oudream on 2017/1/11.
*/
(function() {
'use strict';
var CjHtml = CjHtml || {};
if ( typeof window === 'object' ) {
window.cjs = window.cjs || {};
} else {
throw Error('cjs only run at web browser');
}
cjs.CjHtml = CjHtml;
/**
* escape html character
* @param {string} str
* @returns {string}
*/
CjHtml.escapeHtml = function escapeHtml(str) {
return str.replace(/[<>'&]/g,
function(match) {
switch (match) {
case '<':
return '<';
case '>':
return '>';
case '&':
return '&';
case '\'':
return '"';
}
}
);
};
CjHtml.cumulativeOffset = function(element) {
let top = 0, left = 0;
do {
top += element.offsetTop || 0;
left += element.offsetLeft || 0;
element = element.offsetParent;
} while (element);
return {
top: top,
left: left,
};
};
/**
* 获取元素所有属性
* @param elem: 元素
* @returns {{}}: 属性对象
*/
CjHtml.getAllAttrOfElem = function(elem) {
let attrs = elem.attributes;
let attrObj = {};
let i;
for (i = 0; i < attrs.length; i++) {
let attr = attrs[i];
attrObj[attr.nodeName] = attr.value;
}
return attrObj;
};
/**
* 由相对路径转换成绝对路径
* @param url : 相对路径
* @returns {*}
*/
CjHtml.getAbsoluteUrl = function(url) {
let a = document.createElement('a');
a.href = url; // 设置相对路径给Image, 此时会发送出请求
url = a.href; // 此时相对路径已经变成绝对路径
a = null;
return url;
};
})();
<file_sep>/**
* Created by oudream on 2017/1/11.
*/
(function() {
'use strict';
if (typeof exports === 'object' && typeof global === 'object') {
global.cjs = global.cjs || {};
} else if (typeof window === 'object') {
window.cjs = window.cjs || {};
} else {
throw Error('cjs only run at node.js or web browser');
}
let CjHttp = cjs.CjHttp || {};
cjs.CjHttp = CjHttp;
if (typeof exports === 'object' && typeof global === 'object') {
exports = module.exports = CjHttp;
}
if (CjHttp.hasOwnProperty('urlToObject')) return;
CjHttp.urlToObject = function urlToObject(query) {
let sQuery = query;
if (sQuery == null) {
if (typeof location === 'object') {
sQuery = location.search.substr(1);
if (!sQuery.length) {
let pos = location.href.indexOf('?');
if (pos == -1) return [];
sQuery = location.href.substr(pos + 1);
}
}
} else {
let pos = sQuery.indexOf('?');
if (pos !== -1) {
sQuery = sQuery.substr(pos + 1);
}
}
let result = {};
sQuery.split('&').forEach(function(part) {
if (!part) return;
part = part.split('+').join(' '); // replace every + with space, regexp-free version
let eq = part.indexOf('=');
let key = eq > -1 ? part.substr(0, eq) : part;
let val = eq > -1 ? decodeURIComponent(part.substr(eq + 1)) : '';
let from = key.indexOf('[');
if (from === -1) result[decodeURIComponent(key)] = val;
else {
let to = key.indexOf(']');
let index = decodeURIComponent(key.substring(from + 1, to));
key = decodeURIComponent(key.substring(0, from));
if (!result[key]) result[key] = [];
if (!index) result[key].push(val);
else result[key][index] = val;
}
});
return result;
};
})();
<file_sep>const path = require('path');
const fs = require('fs');
let odcPathes = [
'./../../../assets/3rd/odl-3/odl',
'./../../../assets/3rd/odl-3/odl_n_mysql',
'./../../../assets/3rd/odl-3/odl_n_vue',
'./../../../assets/3rd/odl-3/odl_n_token',
'./../../../assets/gcl3/master/config/odc_department',
'./../../../assets/gcl3/master/config/odc_role_group',
'./../../../assets/gcl3/master/config/odc_user',
'./../../../assets/gcl3/master/config/odc_bureau',
'./../../../assets/gcl3/master/config/odc_container_stat',
'./../../../assets/gcl3/master/config/odc_locket',
'./../../../assets/gcl3/master/config/odc_client_upload',
];
// let odcPathes = [];
// let odcPath = "./../../../assets/gcl3/master/config";
// const odcFileNames = require('./../../../assets/gcl3/master/config/odc').odcFileNames;
//
// for (let i = 0; i < odcFileNames.length; i++) {
// odcPathes.push(path.normalize(path.join(odcPath, odcFileNames[i])));
// }
for (let i = 0; i < odcPathes.length; i++) {
require(odcPathes[i]);
}
exports = module.exports = {
/**
* mock bootstrap
*/
init(httpServer, db) {
}
};
<file_sep>#!/usr/bin/env bash
docker build -t py3node13 .
docker build -t js-py-limi .
<file_sep>#!/usr/bin/env bash
# build dockerfile
docker build -t gcl3-ubuntu .
# run on vps
docker run -d -p 2235:22 -v /opt/ddd:/opt/ddd gcl3-ubuntu
ssh [email protected] -p 2235 -AXY -v
# run on macos(localhost)
docker run -d -p 2235:22 -p 8821:8821 -p 8841:8841 -p 8861:8861 5ed
ssh root@localhost -p 2235 -AXY -v
<file_sep>'use strict';
let CjChannelTcpclient = require('./../cjs-3/cjchannel_tcpclient');
let CjChannelUdp = require('./../cjs-3/cjchannel_udp');
let fs = require('fs');
exports = module.exports = BasProtocol;
/**
* BasDefine
* @constructor
*/
function BasDefine() {
}
BasDefine.PROTOCOL_MODEL_OMC = 1001;
BasDefine.PROTOCOL_MODEL_RT = 1002;
BasDefine.PACKAGE_OK = 0;
BasDefine.PACKAGE_ERROR = 300;
BasDefine.PACKAGE_REQ_START = 0xE9;
BasDefine.PACKAGE_REQ_END = 0xEA;
BasDefine.PACKAGE_REQ_TRANS = 0xE8;
BasDefine.PACKAGE_REQ_CRC = 0x7A;
BasDefine.PACKAGE_ITEM_REQ_LEN = 4;
BasDefine.OMC_OK = 0;
// 一般的响应内存长度
BasDefine.PACKAGE_SIMPLE_REQ_LEN = 512;
BasDefine.PACKAGE_MAX_REQ_LEN = 1024 * 50;
// 接收缓冲池打消
BasDefine.PACKAGE_MAX_BUF_SIZE = BasDefine.PACKAGE_MAX_REQ_LEN * 5 + 1;
// 无基本信息
BasDefine.OMC_OK_WITHINFO = 100;
BasDefine.OMC_ERROR = 300;
BasDefine.OMC_NE_NO_EXIST = 301;
BasDefine.OMC_PARAM_ERROR = 302;
BasDefine.OMC_ALARM_NO_LEN = 4;
BasDefine.OMC_ADDR_LEN = 32;
BasDefine.OMC_NE_LEN = 32;
BasDefine.OMC_NORMAL_INFO_LEN = 32;
BasDefine.OMC_PHYSICAL_NO_LEN = 48;
// 检查过期数据 1小时检测一次 6秒的60倍
BasDefine.OMC_CHECK_OVER_TM = 60;
// package type=
// BasDefine.OMC_REQ_HEARTBEAT = 0x11
BasDefine.OMC_REQ_LOGIN = 0x12;
BasDefine.OMC_REQ_UPD_DATA = 0x13;
BasDefine.OMC_REQ_MOD_ALARM = 0x14;
BasDefine.OMC_REQ_ALARM_INFO_BY_ADDR = 0x15;
BasDefine.OMC_REQ_ALARM_INFO_BY_IDX = 0x16;
BasDefine.OMC_REQ_EXIT = 0x17;
BasDefine.OMC_ANS_LOGIN = 0x22;
BasDefine.OMC_ANS_UPD_DATA = 0x23;
BasDefine.OMC_ANS_MOD_ALARM = 0x24;
BasDefine.OMC_ANS_ALARM_INFO_BY_ADDR = 0x25;
BasDefine.OMC_ANS_ALARM_INFO_BY_IDX = 0x26;
BasDefine.OMC_ANS_EXIT = 0x27;
// modify action for alarm
BasDefine.OMC_CONFIRM_ALARM = 1; // 告警确认
BasDefine.OMC_INVOKE_CONFIRM_ALARM = 2; // 取消确认
BasDefine.OMC_ERASE_ALARM = 3; // 告警清除
BasDefine.OMC_SET_ALARM = 4; // 告警同步
BasDefine.OMC_CLEAR_ALARM = 5; // 告警恢复
// rt 命令
BasDefine.RTDB_REQ_HEARTBEAT = 23;
BasDefine.RTDB_REQ_OPEN_TABLE = 1;
BasDefine.RTDB_REQ_SAVE_TABLE = 17;
BasDefine.RTDB_REQ_CLOSE_TABLE = 18;
BasDefine.RTDB_REQ_RCDCNT = 2;
BasDefine.RTDB_REQ_RCDLEN = 3;
BasDefine.RTDB_REQ_ADDRCD = 4;
BasDefine.RTDB_REQ_DELRCD_BY_KEY = 5;
BasDefine.RTDB_REQ_DELRCD_BY_IDX = 6;
BasDefine.RTDB_REQ_DELALL = 7;
BasDefine.RTDB_REQ_UPDRCD_BY_KEY = 0x08;
BasDefine.RTDB_REQ_UPDRCD_BY_IDX = 9;
BasDefine.RTDB_REQ_GETRCD_BY_KEY = 10;
BasDefine.RTDB_REQ_GETRCD_BY_IDX = 11;
BasDefine.RTDB_REQ_GET_RCD_SEG = 12;
BasDefine.RTDB_REQ_GET_ALL_RCD = 13;
BasDefine.RTDB_REQ_GET_RCD_LIST = 26;
BasDefine.RTDB_REQ_SUBSCRIBE = 14;
// BasDefine.RTDB_REQ_RAW_SUBSCRIBE = 23;
BasDefine.RTDB_REQ_SYNC = 16;
BasDefine.RTDB_REQ_GET_COLUMN_INFO = 19;
BasDefine.RTDB_REQ_GETRCD_BY_COND = 20;
BasDefine.RTDB_REQ_UPDRCD_BY_COND = 21;
BasDefine.RTDB_REQ_DELRCD_BY_COND = 22;
BasDefine.RTDB_REQ_UPD_RCD_LIST = 27;
BasDefine.RTDB_REQ_LOGIN = 0x19;
BasDefine.RTDB_REQ_UPD_CFG = 0x1C;
// rt 命令回复
BasDefine.RTDB_ANS_HEARTBEAT = 43;
BasDefine.RTDB_ANS_OPEN_TABLE = 21;
BasDefine.RTDB_ANS_SAVE_TABLE = 37;
BasDefine.RTDB_ANS_CLOSE_TABLE = 38;
BasDefine.RTDB_ANS_RCDCNT = 22;
BasDefine.RTDB_ANS_RCDLEN = 23;
BasDefine.RTDB_ANS_ADDRCD = 24;
BasDefine.RTDB_ANS_DELRCD_BY_KEY = 25;
BasDefine.RTDB_ANS_DELRCD_BY_IDX = 26;
BasDefine.RTDB_ANS_DELALL = 27;
BasDefine.RTDB_ANS_UPDRCD_BY_KEY = 28;
BasDefine.RTDB_ANS_UPDRCD_BY_IDX = 29;
BasDefine.RTDB_ANS_GETRCD_BY_KEY = 30;
BasDefine.RTDB_ANS_GETRCD_BY_IDX = 31;
BasDefine.RTDB_ANS_GET_RCD_SEG = 32;
BasDefine.RTDB_ANS_GET_RCD_LIST = 46;
BasDefine.RTDB_ANS_FIRST_RCD_SEG = 0x21;
BasDefine.RTDB_ANS_NEXT_RCD_SEG = 0x22;
BasDefine.RTDB_ANS_SUBSCRIBE = 35;
// BasDefine.RTDB_ANS_RAW_SUBSCRIBE = 43;
BasDefine.RTDB_ANS_SYNC = 36;
BasDefine.RTDB_ANS_GET_COLUMN_INFO = 39;
BasDefine.RTDB_ANS_GETRCD_BY_COND = 40;
BasDefine.RTDB_ANS_UPDRCD_BY_COND = 41;
BasDefine.RTDB_ANS_DELRCD_BY_COND = 42;
BasDefine.RTDB_ANS_UPD_RCD_LIST = 47;
BasDefine.RTDB_ANS_LOGIN = 45;
BasDefine.RTDB_ANS_UPD_CFG = 48;
// rt
BasDefine.RTDB_MAX_TABLE_NAME = 64;
BasDefine.RTDB_MAX_COLUMN_NAME = 64;
BasDefine.RTDB_MAX_KEY = 128;
// da
BasDefine.ICS_DA_REQ_DETAIL = 0x01;
BasDefine.ICS_DA_ANS_DETAIL = 0x31;
BasDefine.ICS_DA_DATA_DETAIL = 0x61;
BasDefine.ICS_DA_REQ_SPOT = 0x02;
BasDefine.ICS_DA_ANS_SPOT = 0x32;
BasDefine.ICS_DA_DATA_SPOT = 0x62;
BasDefine.ICS_YX_TABLENAME = 'T_RT_YX';
BasDefine.ICS_YC_TABLENAME = 'T_RT_YC';
BasDefine.ICS_YW_TABLENAME = 'T_RT_YW';
/**
* UserException
* @param {String}message
* @constructor
*/
function UserException(message) {
this.message = message;
this.name = 'UserException';
}
/**
* BasAttr
* @param {String}name
* @param {Number}size
* @param {Number}type
* @param {String}encoding
* @constructor
*/
function BasAttr(name, size, type, encoding) {
if (!name) {
throw new UserException('invalid name');
}
this.name = name;
this.size = size;
this.type = type;
this.encoding = encoding;
}
BasAttr.CI_Type_None = 0;
BasAttr.CI_Type_int = 1;
BasAttr.CI_Type_double = 2;
BasAttr.CI_Type_string = 3;
BasAttr.CI_Type_long = 4;
BasAttr.CI_Type_buffer = 5;
/**
* BasPacket
* @constructor
*/
function BasPacket() {
this.commandAttrs = [];
this.commandSeq = 0;
this.commandCode = 0;
this.commandAttrBufferCount = 0;
}
BasPacket.packets = new Map();
BasPacket.prototype.toBuffer = function(...args) {
let self = this;
let commandAttrs = self.commandAttrs;
// :todo.best : compatible : arguments.length != commandAttrs.length
if (args.length !== commandAttrs.length) {
return Buffer.alloc(0);
}
let iTotalSize = self.getStaticTotalSize();
let idx = 0;
let attr;
let value;
// get attrs's buffer size
if (self.commandAttrBufferCount > 0) {
while (idx < commandAttrs.length) {
attr = commandAttrs[idx];
value = args[idx];
if (attr.type === BasAttr.CI_Type_buffer) {
iTotalSize += value.length;
}
++idx;
}
}
if (iTotalSize <= 0) {
return Buffer.alloc(0);
}
let rBuf = Buffer.alloc(iTotalSize);
let iOffset = 0;
idx = 0;
while (idx < commandAttrs.length) {
attr = commandAttrs[idx];
value = args[idx];
switch (attr.type) {
case BasAttr.CI_Type_int:
rBuf.writeIntLE(value, iOffset, attr.size, true);
break;
case BasAttr.CI_Type_long:
rBuf.writeIntLE(value, iOffset, 6, true);
break;
case BasAttr.CI_Type_double:
rBuf.writeDoubleLE(value, iOffset, true);
break;
case BasAttr.CI_Type_string:
if (value.length > attr.size) {
throw new UserException('BasPacket: value.length > attr.size');
}
rBuf.write(value, iOffset, attr.size);// Default: 'utf8'
rBuf[iOffset + value.length] = 0;
break;
case BasAttr.CI_Type_buffer:
if (value.length > attr.size) {
throw new UserException('BasPacket: value.length > attr.size');
}
value.copy(rBuf, iOffset);// Default: 'utf8'
break;
default:
break;
}
iOffset += attr.size;
++idx;
}
return rBuf;
};
BasPacket.prototype.fromBuffer = function(buf, iStart, iEnd) {
let self = this;
let commandAttrs = self.commandAttrs;
let r = {};
let iTotalSize = self.getStaticTotalSize();
if (!buf || iStart + iTotalSize > buf.length - 2) {
console.log('BasPacket.prototype.fromBuffer : buf length no enough, ', iStart + iTotalSize, buf.length);
return r;
}
let attr;
let value;
let idx = 0;
let iOffset = iStart;
let iZeroIndex = 0;
while (idx < commandAttrs.length) {
attr = commandAttrs[idx];
switch (attr.type) {
case BasAttr.CI_Type_int:
value = buf.readIntLE(iOffset, attr.size, true);
iOffset += attr.size;
break;
case BasAttr.CI_Type_long:
value = buf.readIntLE(iOffset, 6, true);
iOffset += attr.size;
break;
case BasAttr.CI_Type_double:
value = buf.readDoubleLE(iOffset, true);
iOffset += attr.size;
break;
case BasAttr.CI_Type_string:
value = buf.toString('utf8', iOffset, iOffset + attr.size);
iZeroIndex = value.indexOf('\0');
if (iZeroIndex >= 0) {
value = value.substring(0, iZeroIndex);
}
iOffset += attr.size;
break;
case BasAttr.CI_Type_buffer:
// do not increate ioffset
break;
default:
iOffset += attr.size;
break;
}
Object.defineProperty(r, attr.name, {
configurable: true,
enumerable: true,
value: value,
});
++idx;
}
r.buffer = buf;
r.offset = iOffset;
r.end = iEnd;
return r;
};
BasPacket.prototype.add = function(...args) {
if (arguments.length < 1) {
throw new UserException('BasPacket.prototype.add arguments length<1!');
}
let name = args[0];
let size = 4;
if (arguments.length > 1) {
size = args[1];
}
// get default type
let type;
if (arguments.length > 2) {
type = args[2];
} else {
if (size === 4) {
type = BasAttr.CI_Type_int;
} else if (size === 8) {
type = BasAttr.CI_Type_double;
} else if (size > 8) {
type = BasAttr.CI_Type_string;
} else {
throw new UserException('BasPacket.prototype.add arguments length<3!');
}
}
let encoding = 'ascii';
if (arguments.length > 3) {
encoding = args[3];
}
if (type === BasAttr.CI_Type_buffer) {
this.commandAttrBufferCount += 1;
}
this.commandAttrs.push(new BasAttr(name, size, type, encoding));
};
BasPacket.prototype.getStaticTotalSize = function() {
let iSize = 0;
let self = this;
let commandAttrs = self.commandAttrs;
let attr;
let idx = 0;
while (idx < commandAttrs.length) {
attr = commandAttrs[idx++];
if (attr.type === BasAttr.CI_Type_buffer) {
continue;
}
iSize += attr.size;
}
return iSize;
};
BasPacket.prototype.preparePacket = function(buf) {
if (!buf || buf.length === 0) {
return Buffer.allocUnsafe(0);
}
let iOldSize = buf.length;
let r = Buffer.allocUnsafe(iOldSize * 2);
let i = 1;
let j = 1;
r[0] = buf[0];
while (i < iOldSize - 1) {
if (buf[i] >= BasDefine.PACKAGE_REQ_TRANS) {
r[j] = BasDefine.PACKAGE_REQ_TRANS;
j++;
r[j] = buf[i] - BasDefine.PACKAGE_REQ_TRANS;
} else {
r[j] = buf[i];
}
i++;
j++;
}
r[j] = buf[iOldSize - 1];
let iNewSize = j + 1;
// return r.slice(0, iNewSize);
let iCrc = 0;
for (let h = 1; h < iNewSize - 2; h++) {
iCrc = (iCrc + r[h]) & 0xff;
}
r[iNewSize - 2] = BasDefine.PACKAGE_REQ_CRC - iCrc;
return r.slice(0, iNewSize);
};
BasPacket.prototype.encodePacket = function(buf, iTotalSize) {
if (!buf || buf.length === 0) {
return Buffer.allocUnsafe(0);
}
let iOldSize = buf.length;
// total length : 1 + 3 + 3 + 3 + 1 + 1
let r = Buffer.allocUnsafe(iOldSize + 1 + 4 + 4 + 4 + 1 + 1);
let iOffset = 0;
r[iOffset] = BasDefine.PACKAGE_REQ_START;
iOffset += 1;
r.writeIntLE(this.commandSeq, iOffset, BasDefine.PACKAGE_ITEM_REQ_LEN, true);
iOffset += BasDefine.PACKAGE_ITEM_REQ_LEN;
r.writeIntLE(this.commandCode, iOffset, BasDefine.PACKAGE_ITEM_REQ_LEN, true);
iOffset += BasDefine.PACKAGE_ITEM_REQ_LEN;
r.writeIntLE(iTotalSize, iOffset, BasDefine.PACKAGE_ITEM_REQ_LEN, true);
iOffset += BasDefine.PACKAGE_ITEM_REQ_LEN;
buf.copy(r, iOffset);
iOffset += buf.length;
r[iOffset] = 0;// crc
iOffset += 1;
r[iOffset] = BasDefine.PACKAGE_REQ_END;
iOffset += 1; // r.length
return this.preparePacket(r);
};
BasPacket.prototype.setCommand = function(iCommandSeq, iCommand) {
this.commandSeq = iCommandSeq;
this.commandCode = iCommand;
BasPacket.packets.set(iCommand, this);
};
BasPacket.prototype.toPacket = function(...args) {
let self = this;
let commandAttrs = self.commandAttrs;
// :todo.best : compatible : arguments.length != commandAttrs.length
if (args.length !== commandAttrs.length) {
return Buffer.alloc(0);
}
let iTotalSize = self.getStaticTotalSize();
let idx = 0;
let attr;
let value;
// get attrs's buffer size
if (self.commandAttrBufferCount > 0) {
while (idx < commandAttrs.length) {
attr = commandAttrs[idx];
value = args[idx];
if (attr.type === BasAttr.CI_Type_buffer) {
iTotalSize += value.length;
}
++idx;
}
}
if (iTotalSize <= 0) {
return Buffer.alloc(0);
}
let rBuf = Buffer.alloc(iTotalSize);
let iOffset = 0;
idx = 0;
while (idx < commandAttrs.length) {
attr = commandAttrs[idx];
value = args[idx];
switch (attr.type) {
case BasAttr.CI_Type_int:
rBuf.writeIntLE(value, iOffset, attr.size, true);
break;
case BasAttr.CI_Type_long:
rBuf.writeIntLE(value, iOffset, 6, true);
break;
case BasAttr.CI_Type_double:
rBuf.writeDoubleLE(value, iOffset, true);
break;
case BasAttr.CI_Type_string:
if (value.length > attr.size) {
throw new UserException('BasPacket: value.length > attr.size');
}
rBuf.write(value, iOffset, attr.size);// Default: 'utf8'
rBuf[iOffset + value.length] = 0;
break;
case BasAttr.CI_Type_buffer:
if (value.length > attr.size) {
throw new UserException('BasPacket: value.length > attr.size');
}
value.copy(rBuf, iOffset);// Default: 'utf8'
break;
default:
break;
}
iOffset += attr.size;
++idx;
}
let buf = rBuf;
if (!buf || buf.length === 0) {
return Buffer.allocUnsafe(0);
}
let iOldSize = buf.length;
// total length : 1 + 3 + 3 + 3 + 1 + 1
let r = Buffer.allocUnsafe(iOldSize + 1 + 4 + 4 + 4 + 1 + 1);
iOffset = 0;
r[iOffset] = BasDefine.PACKAGE_REQ_START;
iOffset += 1;
r.writeIntLE(this.commandSeq, iOffset, BasDefine.PACKAGE_ITEM_REQ_LEN, true);
iOffset += BasDefine.PACKAGE_ITEM_REQ_LEN;
r.writeIntLE(this.commandCode, iOffset, BasDefine.PACKAGE_ITEM_REQ_LEN, true);
iOffset += BasDefine.PACKAGE_ITEM_REQ_LEN;
r.writeIntLE(iTotalSize, iOffset, BasDefine.PACKAGE_ITEM_REQ_LEN, true);
iOffset += BasDefine.PACKAGE_ITEM_REQ_LEN;
buf.copy(r, iOffset);
iOffset += buf.length;
r[iOffset] = 0;// crc
iOffset += 1;
r[iOffset] = BasDefine.PACKAGE_REQ_END;
iOffset += 1; // r.length
return this.preparePacket(r);
//
// return this.encodePacket(BasPacket.prototype.toBuffer.apply(this, args));
};
/**
* BasParser
* @constructor
*/
function BasParser() {
// recvCache : recv data -> push to recvCache
this.recvCache = Buffer.allocUnsafeSlow(BasDefine.PACKAGE_MAX_BUF_SIZE);
this.recvOffset = 0;
this.dealOffset = 0;
// deal recvCache and take msg (one Complete Packet msgLength) to msgCache
this.msgCache = Buffer.allocUnsafeSlow(BasDefine.PACKAGE_MAX_REQ_LEN);
this.msgLength = 0;
this.onReceivedMsg = 0;
}
BasParser.prototype.doReceived = function(data) {
if (!data) {
throw new UserException('BasParser.prototype.handleRecv(buf) : invalid buf!');
}
if (data.length > BasDefine.PACKAGE_MAX_BUF_SIZE - (BasDefine.PACKAGE_MAX_REQ_LEN * 2)) {
console.log('BasParser.prototype.handleRecv(buf) : buf.length > BasDefine.PACKAGE_MAX_BUF_SIZE!');
return;
}
if (data.length > (BasDefine.PACKAGE_MAX_BUF_SIZE - this.recvOffset)) {
let iNoDeal = this.recvOffset - this.dealOffset;
if (iNoDeal > BasDefine.PACKAGE_MAX_REQ_LEN) {
this.recvOffset = 0;
} else {
this.recvCache.copy(this.recvCache, 0, this.dealOffset, this.recvOffset);
this.recvOffset = iNoDeal;
}
this.dealOffset = 0;
}
data.copy(this.recvCache, this.recvOffset);
this.recvOffset += data.length;
this.dealCache();
};
BasParser.prototype.dealCache = function() {
let index = this.dealOffset;
let end = this.recvOffset;
let buf = this.recvCache;
while (index < end) {
if (buf[index] === BasDefine.PACKAGE_REQ_START) {
let iStartPos = index;
let iEndPos = 0;
let j = index + 1;
while ((j < end) && (iEndPos === 0)) {
if ((buf[j]) === BasDefine.PACKAGE_REQ_START) {
iStartPos = j;
}
if (buf[j] === BasDefine.PACKAGE_REQ_END) {
iEndPos = j;
}
j++;
}
if (iEndPos === 0) {
// nothing to do, wait to receive all bytes
return;
} else {
let iMsgLength = iEndPos - iStartPos + 1;
if (iMsgLength <= BasDefine.PACKAGE_MAX_REQ_LEN) {
let iMsgEnd = this.repairMsg(iStartPos, iEndPos + 1);
if (this.onReceivedMsg) {
this.onReceivedMsg(this.msgCache, iMsgEnd);
}
// BasPacket.dealPacket(this.msgCache, iMsgEnd);
}
index = iEndPos;
if (iEndPos > 0) {
this.dealOffset = iEndPos + 1;
}
}
}
index++;
}
};
BasParser.prototype.repairMsg = function(iStartPos, iEndPos) {
let buf = this.recvCache;
let msgBuf = this.msgCache;
msgBuf[0] = buf[iStartPos];
let i = iStartPos + 1;
let j = 1;
for (; i < iEndPos - 1; i++, j++) {
if (buf[i] === BasDefine.PACKAGE_REQ_TRANS) {
msgBuf[j] = buf[i] + buf[i + 1];
i++;
} else {
msgBuf[j] = buf[i];
}
}
msgBuf[j] = buf[i];
j++;
this.msgLength = j;
let iCrc = 0;
for (let h = 1; h < j - 2; h++) {
iCrc = (iCrc + msgBuf[h]) & 0xff;
}
iCrc = BasDefine.PACKAGE_REQ_CRC - iCrc;
if (iCrc !== msgBuf[j - 2]) {
// 校验失败
console.log('BasParser.prototype.repairMsg(iStartPos, iEndPos), crc invalid!');
}
return j;
};
/**
*
* @constructor
*/
function BasProtocol(bIsTcp = true, iProtocolModel = BasDefine.PROTOCOL_MODEL_OMC) {
let self = this;
let channelBase;
if (bIsTcp) {
channelBase = new CjChannelTcpclient();
} else {
channelBase = new CjChannelUdp();
}
channelBase.isAutoOpen = true;
channelBase.isAutoHeartbeat = false;
let basParser = new BasParser();
basParser.onReceivedMsg = function(buf, iEnd) {
self.dealPacket(buf, iEnd);
};
channelBase.onReceived = function(data) {
basParser.doReceived(data);
};
this.fns = new Map();
this.fnAllPacket = null;
this.channel = channelBase;
this.parser = basParser;
this.protocolModel = iProtocolModel;
this.lastReceivedDataTime = 0;
}
/**
* start
* @param {Object}option = {RemoteIpAddress: '127.0.0,.1', RemotePort: 5556};
*/
BasProtocol.prototype.start = function(option) {
this.channel.open(option);
this.checkProtocol(1000 * 10);
};
BasProtocol.prototype.stop = function() {
this.channel.close();
};
BasProtocol.prototype.dealPacket = function(buf, iEnd) {
if (!buf || buf.length < iEnd || buf.length < 1 + 4 + 4 + 4 + 1 + 1) {
console.log('BasProtocol.prototype.dealPacket buf:', buf ? buf.length : null);
return;
}
let iOffset = 0;
// let pkStart = buf[iOffset];// BasDefine.PACKAGE_REQ_START;
iOffset += 1;
// let pkCommandSeq = buf.readIntLE(iOffset, 4, true);
iOffset += BasDefine.PACKAGE_ITEM_REQ_LEN;
let pkCommand = buf.readIntLE(iOffset, 4, true);
iOffset += BasDefine.PACKAGE_ITEM_REQ_LEN;
// let pkRequest = buf.readIntLE(iOffset, 4, true);
iOffset += BasDefine.PACKAGE_ITEM_REQ_LEN;
let packet = BasPacket.packets.get(pkCommand);
if (packet) {
this.lastReceivedDataTime = Date.now();
let msgObj = packet.fromBuffer(buf, iOffset, iEnd);
this.dispatch(pkCommand, msgObj);
console.log('BasPacket.dealPacket : pkCommand [', pkCommand, '] dispatch!');
} else {
console.log('BasPacket.dealPacket : pkCommand [', pkCommand, '] is undefined!');
}
// let pkCrc = buf[iEnd - 2];// crc
// let pkEnd = buf[iEnd - 1];// = BasDefine.PACKAGE_REQ_END;
};
BasProtocol.prototype.onAllPacket = function(fn) {
this.fnAllPacket = fn;
};
BasProtocol.prototype.on = function(commandCode, fn) {
this.fns.set(commandCode, fn);
};
BasProtocol.prototype.dispatch = function(commandCode, msgObj) {
let fn = this.fns.get(commandCode);
if (fn) {
fn(msgObj);
} else if (this.fnAllPacket) {
this.fnAllPacket(commandCode, msgObj);
}
};
BasProtocol.prototype.sendPacket = function(packet) {
return this.channel.sendData(packet);
};
BasProtocol.prototype.checkProtocol = function(interval) {
let self = this;
if (interval < 1000) {
if (self.checkTimer) {
clearTimeout(self.checkTimer);
self.checkTimer = null;
}
return;
}
if (self.checkTimer) {
clearTimeout(self.checkTimer);
}
let timeOut = function() {
// *recycle heart jump
if (self.channel.isOpen()) {
let packet = self.protocolModel === BasDefine.PROTOCOL_MODEL_OMC ? BasPacket.userLoginPacket : BasPacket.rtReqHeartbeat;
if (packet) {
let packetBuf = packet.toPacket('user1', '<PASSWORD>1', 'no1', 1001);
if (packetBuf.length > 0) {
let iResult = self.sendPacket(packetBuf);
console.log('BasProtocol timer auto heartbeat ! result : ', iResult);
} else {
console.log('BasProtocol heart jump : packetBuf.length <= 0!');
}
} else {
console.log('BasProtocol heart jump : packet is null ! ');
}
} else {
console.log('BasProtocol timer auto heartbeat fail! channel.isOpen:', self.channel.isOpen());
}
self.checkTimer = setTimeout(timeOut, interval);
};
self.checkTimer = setTimeout(timeOut, interval);
};
BasProtocol.BasDefine = BasDefine;
BasProtocol.BasPacket = BasPacket;
// Init User Packet
if (true) {
let userLoginPacket = new BasPacket();
userLoginPacket.add('user', BasDefine.OMC_NORMAL_INFO_LEN);
userLoginPacket.add('password', BasDefine.OMC_NORMAL_INFO_LEN);
userLoginPacket.add('physicalNo', BasDefine.OMC_PHYSICAL_NO_LEN);
userLoginPacket.add('kind');
userLoginPacket.setCommand(1, BasDefine.OMC_REQ_LOGIN);
BasPacket.userLoginPacket = userLoginPacket;
let updateInfo = new BasPacket();
updateInfo.add('user', BasDefine.OMC_NORMAL_INFO_LEN);
updateInfo.add('kind');
updateInfo.setCommand(1, BasDefine.OMC_REQ_UPD_DATA);
BasPacket.updateInfo = updateInfo;
let alarmReqPacket = new BasPacket();
alarmReqPacket.add('AlarmNo');
alarmReqPacket.add('Action');
alarmReqPacket.add('User', BasDefine.OMC_NORMAL_INFO_LEN);
alarmReqPacket.add('NeID');
alarmReqPacket.add('AlarmType');
alarmReqPacket.add('ModuleNo');
alarmReqPacket.add('CardNo');
alarmReqPacket.add('PortNo');
alarmReqPacket.setCommand(1, BasDefine.OMC_REQ_MOD_ALARM);
BasPacket.alarmReqPacket = alarmReqPacket;
let alarmAnsPacket = new BasPacket();
alarmAnsPacket.add('AlarmNo');
alarmAnsPacket.add('Action');
alarmAnsPacket.add('User', BasDefine.OMC_NORMAL_INFO_LEN);
alarmAnsPacket.add('NeID');
alarmAnsPacket.add('AlarmType');
alarmAnsPacket.add('ModuleNo');
alarmAnsPacket.add('CardNo');
alarmAnsPacket.add('PortNo');
alarmAnsPacket.setCommand(1, BasDefine.OMC_ANS_MOD_ALARM);
BasPacket.alarmAnsPacket = alarmAnsPacket;
// ### rt
let rtLoginPacket = new BasPacket();
rtLoginPacket.add('AppId');
rtLoginPacket.setCommand(1, BasDefine.RTDB_REQ_LOGIN);
BasPacket.rtLoginPacket = rtLoginPacket;
let rtUpdcfgPacket = new BasPacket();
rtUpdcfgPacket.add('AppId');
rtUpdcfgPacket.setCommand(1, BasDefine.RTDB_REQ_UPD_CFG);
BasPacket.rtUpdcfgPacket = rtUpdcfgPacket;
let rtAnsFirstPacket = new BasPacket();
rtAnsFirstPacket.add('StateCode');
rtAnsFirstPacket.add('TableName', BasDefine.RTDB_MAX_TABLE_NAME);
rtAnsFirstPacket.add('Count');
rtAnsFirstPacket.setCommand(1, BasDefine.RTDB_ANS_FIRST_RCD_SEG);
BasPacket.rtAnsFirstPacket = rtAnsFirstPacket;
let rtAnsNextPacket = new BasPacket();
rtAnsNextPacket.add('StateCode');
rtAnsNextPacket.add('TableName', BasDefine.RTDB_MAX_TABLE_NAME);
rtAnsNextPacket.add('Count');
rtAnsNextPacket.setCommand(1, BasDefine.RTDB_ANS_NEXT_RCD_SEG);
BasPacket.rtAnsNextPacket = rtAnsNextPacket;
let rtReqUpdlistPacket = new BasPacket();
rtReqUpdlistPacket.add('TableName', BasDefine.RTDB_MAX_TABLE_NAME);
rtReqUpdlistPacket.add('Count');
rtReqUpdlistPacket.add('MeasuresBuffer', BasDefine.PACKAGE_MAX_REQ_LEN - 128, BasAttr.CI_Type_buffer);
rtReqUpdlistPacket.setCommand(1, BasDefine.RTDB_REQ_UPD_RCD_LIST);
BasPacket.rtReqUpdlistPacket = rtReqUpdlistPacket;
let rtReqUpdkeyPacket = new BasPacket();
rtReqUpdkeyPacket.add('TableName', BasDefine.RTDB_MAX_TABLE_NAME);
rtReqUpdkeyPacket.add('Key', 8, BasAttr.CI_Type_long);
rtReqUpdkeyPacket.add('KeyRes', BasDefine.RTDB_MAX_KEY - 8);
rtReqUpdkeyPacket.add('MeasureBuffer', BasDefine.PACKAGE_SIMPLE_REQ_LEN - 128, BasAttr.CI_Type_buffer);
rtReqUpdkeyPacket.setCommand(1, BasDefine.RTDB_REQ_UPDRCD_BY_KEY);
BasPacket.rtReqUpdkeyPacket = rtReqUpdkeyPacket;
let rtReqHeartbeat = new BasPacket();
rtReqHeartbeat.add('user', BasDefine.OMC_NORMAL_INFO_LEN);
rtReqHeartbeat.add('password', BasDefine.OMC_NORMAL_INFO_LEN);
rtReqHeartbeat.add('physicalNo', BasDefine.OMC_PHYSICAL_NO_LEN);
rtReqHeartbeat.add('kind');
rtReqHeartbeat.setCommand(1, BasDefine.RTDB_REQ_HEARTBEAT);
BasPacket.rtReqHeartbeat = rtReqHeartbeat;
// ### da
let rtReqDaSpotPacket = new BasPacket();
rtReqDaSpotPacket.add('StartTm', 8, BasAttr.CI_Type_long);
rtReqDaSpotPacket.add('Key', 8, BasAttr.CI_Type_long);
rtReqDaSpotPacket.add('KeyLen', 8, BasAttr.CI_Type_long);
rtReqDaSpotPacket.setCommand(2, BasDefine.ICS_DA_REQ_SPOT);
BasPacket.rtReqDaSpotPacket = rtReqDaSpotPacket;
let rtAnsDaSpotPacket = new BasPacket();
rtAnsDaSpotPacket.setCommand(2, BasDefine.ICS_DA_ANS_SPOT);
BasPacket.rtAnsDaSpotPacket = rtAnsDaSpotPacket;
let rtDataDaSpotPacket = new BasPacket();
rtDataDaSpotPacket.setCommand(2, BasDefine.ICS_DA_DATA_SPOT);
BasPacket.rtDataDaSpotPacket = rtDataDaSpotPacket;
let rtReqDaDetailPacket = new BasPacket();
rtReqDaDetailPacket.add('StartTm', 8, BasAttr.CI_Type_long);
rtReqDaDetailPacket.add('EndTm', 8, BasAttr.CI_Type_long);
rtReqDaDetailPacket.add('Interval', 8, BasAttr.CI_Type_long);
rtReqDaDetailPacket.add('Key', 8, BasAttr.CI_Type_long);
rtReqDaDetailPacket.add('KeyLen', 8, BasAttr.CI_Type_long);
rtReqDaDetailPacket.add('KeyList', BasDefine.PACKAGE_MAX_REQ_LEN - 128, BasAttr.CI_Type_buffer);
rtReqDaDetailPacket.setCommand(1, BasDefine.ICS_DA_REQ_DETAIL);
BasPacket.rtReqDaDetailPacket = rtReqDaDetailPacket;
let rtAnsDaDetailPacket = new BasPacket();
rtAnsDaDetailPacket.add('StateCode');
rtAnsDaDetailPacket.add('Count', 8, BasAttr.CI_Type_long);
rtAnsDaDetailPacket.setCommand(1, BasDefine.ICS_DA_ANS_DETAIL);
BasPacket.rtAnsDaDetailPacket = rtAnsDaDetailPacket;
let rtDataDaDetailPacket = new BasPacket();
rtDataDaDetailPacket.add('StateCode');
rtDataDaDetailPacket.add('Count', 8, BasAttr.CI_Type_long);
rtDataDaDetailPacket.setCommand(1, BasDefine.ICS_DA_DATA_DETAIL);
BasPacket.rtDataDaDetailPacket = rtDataDaDetailPacket;
// ### had set command :
// 0x19, 0x14, 0x21, 0x22, 0x08
// 0x12, 0x13, 0x14, 0x24
// 0x01, 0x31, 0x61, 0x02, 0x32, 0x62
}
BasProtocol.test1 = function() {
let basProtocol = new BasProtocol();
basProtocol.start({port: 5556, host: '127.0.0.1'});
// only commandCode
basProtocol.on(BasPacket.userLoginPacket.commandCode, function(msgObj) {
console.log(msgObj); // msgObj = {user: 'user1', password: '<PASSWORD>'}
});
// all in
basProtocol.onAllPacket(function(commandCode, msgObj) {
console.log(commandCode, msgObj);
});
setTimeout(function() {
// send packet
let packet = BasPacket.userLoginPacket.toPacket('user1', '<PASSWORD>', 'no1', 1001);
basProtocol.sendPacket(packet);
console.log(packet);
fs.writeFile('f:/001.txt', packet, function(err) {
if (err) {
console.log(err);
}
});
}, 3000);
};
<file_sep>'use strict';
const path = require('path');
const fs = require('fs');
const os = require('os');
require('./../../../nodejs/3rd/cjs-3/cjfs.js');
const odlLoader = require('./../../../projects/pinfox/pf_omc/odl-loader');
let mysqlConfig = require('./master.json');
const mysqlOption = mysqlConfig.database.mysql1;
let dtNow = Date.now();
let argv = {};
let argKey = '';
let argValue = '';
process.argv.forEach(function(arg) {
if (arg.startsWith('-')) {
if (argKey) {
argv[argKey] = argValue;
}
argKey = arg;
argValue = '';
return;
}
if (argValue.length > 0)
argValue += ' ' + arg;
else
argValue = arg;
});
if (argKey) {
argv[argKey] = argValue;
}
console.log(argv);
const savePath = process.argv['-p'] ? process.argv['-p'] : (os.platform() === 'win32' ? 'd:/tmp/odl' : '/tmp/odl');
if (!fs.existsSync(savePath)) {
console.log(' --- savePath --- : ');
console.log(savePath);
cjs.CjFs.mkdirMultiLevelSync(savePath);
}
let mysql = require('mysql');
let pool = null;
// let pool = mysql.createPool(mysqlOption);
//
// var sqlCommand = `
// create database test;
//
// use test;
//
// CREATE TABLE users (
// id int(11) NOT NULL auto_increment,
// name varchar(100) NOT NULL,
// age int(3) NOT NULL,
// email varchar(100) NOT NULL,
// PRIMARY KEY (id)
// );
// `
function querySqlOnce(sql, values) {
return new Promise((resolve, reject) => {
var con = mysql.createConnection({
host: mysqlOption.host,
user: mysqlOption.user,
password: <PASSWORD>Option.password,
multipleStatements: true // this allow you to run multiple queries at once.
});
con.connect(function(err) {
if (err) throw err;
// console.log("Connected yet no db is selected yet!");
con.query(sql, values, function (err, result) {
if (err) {
reject(err);
}
else {
resolve(result);
}
con.end();
});
});
});
}
function execSql(sql) {
pool.getConnection(function(err, connection) {
if (err) {
console.log('error ' + String(i));
}
else {
connection.query(sql, function(err, result) {
if (err) throw err;
console.log(result.affectedRows + " record(s) exec");
});
}
});
}
function querySql(sql) {
pool.getConnection(function(err, connection) {
if (err) {
console.log('error ' + String(i));
}
else {
connection.query(sql, function(err, rows, fields) {
if (err) throw err;
console.log(rows.length + ' record(s) query');
console.log(JSON.stringify(rows));
console.log(JSON.stringify(fields));
});
}
})
}
function querySqlPromise(sql, values) {
return new Promise((resolve, reject) => {
pool.getConnection(function(err, connection) {
if (err) {
reject(err);
}
else {
connection.query(sql, values, (err, rows) => {
if (err) {
reject(err);
}
else {
resolve(rows);
}
connection.release();
});
}
});
});
}
let countTestSql = 0;
function closePool() {
if (countTestSql === 0) {
pool.end();
}
}
let insertObjs = {
user: {
data: [
{
id: 1,
name: "admin",
password: "<PASSWORD>",
},
{
id: 2,
name: "administrator",
password: "<PASSWORD>",
}
]
},
};
let selectConditions = {
user: {
start: 0,
end: 20,
attrs: [
{
name: 'name',
operation: '%',
value: 'a',
isAnd: false
},
{
name: 'id',
operation: '>',
value: 0,
isAnd: true
}
]
},
};
async function testSql(odc) {
countTestSql++;
let odcName = odc.metadata.name;
let fp = path.resolve(savePath, odcName + ".json");
fs.writeFileSync(fp, JSON.stringify(odc));
console.log('fs.writeFileSync(fp), fp: ', fp);
let values = [];
let sqlExist = odl.DbMysql.getExistSql(odc);
try {
values = await querySqlPromise(sqlExist);
}
catch (e) {
console.log(e);
}
console.log('sqlExist: ', values);
if (Array.isArray(values) && values.length > 0) {
return;
}
let sqlDrop = odl.DbMysql.getDropSql(odc);
// execSql(sqlDrop);
values = await querySqlPromise(sqlDrop);
console.log('sqlDrop: ', values);
let sqlCreate = odl.DbMysql.getCreateSql(odc);
fp = path.resolve(savePath, odcName + ".create.sql");
fs.writeFileSync(fp, sqlCreate);
console.log('fs.writeFileSync(fp), fp: ', fp);
// execSql(sqlCreate);
values = await querySqlPromise(sqlCreate);
console.log('sqlCreate: ', values);
let sqlCreateLog = odl.DbMysql.log.getCreateSql(odc);
if (sqlCreateLog){
fp = path.resolve(savePath, odcName + ".create-log.sql");
fs.writeFileSync(fp, sqlCreateLog);
console.log('fs.writeFileSync(fp), fp: ', fp);
// execSql(sqlCreateLog);
values = await querySqlPromise(sqlCreateLog);
console.log('sqlCreateLog: ', values);
}
fp = path.resolve(savePath, odcName + ".insert.sql");
let objs = insertObjs[odcName] ? insertObjs[odcName].data : undefined;
if (objs) {
let sqlsInsert = odl.DbMysql.getInsertSqlAry(odc, objs);
fs.writeFileSync(fp, sqlsInsert.join('\n'));
console.log('fs.writeFileSync(fp), fp: ', fp);
for (let i = 0; i < sqlsInsert.length; i++) {
let sql = sqlsInsert[i];
// execSql(sql);
values = await querySqlPromise(sql);
console.log('sqlInsert: ', values, ' cost time: ', Date.now() - dtNow);
}
}
let conditions = selectConditions[odcName];
if (conditions) {
let sqlSelect = odl.DbMysql.getSelectSql(odc, conditions);
fp = path.resolve(savePath, odcName + ".select.sql");
fs.writeFileSync(fp, sqlSelect);
console.log('fs.writeFileSync(fp), fp: ', fp);
// querySql(sqlSelect);
values = await querySqlPromise(sqlSelect);
console.log('sqlSelect: ', values);
}
let sqlSelectAll = odl.DbMysql.getSelectAllSql(odc);
fp = path.resolve(savePath, odcName + ".select-all.sql");
fs.writeFileSync(fp, sqlSelectAll);
console.log('fs.writeFileSync(fp), fp: ', fp);
// querySql(sqlSelectAll);
values = await querySqlPromise(sqlSelectAll);
console.log('sqlSelectAll: ', values);
console.log(Date.now() - dtNow);
countTestSql--;
closePool();
}
async function testSqls() {
let r = await querySqlOnce("CREATE DATABASE IF NOT EXISTS " + mysqlOption.database + " default charset utf8");
console.log(r);
pool = mysql.createPool(mysqlOption);
let odcs = odl.getOdcs();
await odcs.forEach(testSql);
}
testSqls();
<file_sep>import axios from 'axios';
let base = '';
export const requestLogin = params => { return axios.post(`${base}/login`, params).then(res => res.data); };
export const getUserList = params => { return axios.get(`${base}/user/list`, { params: params }); };
export const getUserListPage = params => { return axios.get(`${base}/user/listpage`, { params: params }); };
export const removeUser = params => { return axios.get(`${base}/user/remove`, { params: params }); };
export const batchRemoveUser = params => { return axios.get(`${base}/user/batchremove`, { params: params }); };
export const editUser = params => { return axios.get(`${base}/user/edit`, { params: params }); };
export const addUser = params => { return axios.get(`${base}/user/add`, { params: params }); };
export const getOdoQuery = params =>{
if (params.data) odl.DbMysql.fromM(params.odc, params.data);
return axios.post(`${base}/odo/query`, params).then(res => {
let rs = res.data;
if (rs && rs.action === 'ls' && rs.data) {
odl.DbMysql.toM(rs.odc, rs.data);
}
return rs;
});
};
export const getHello1 = params => { return axios.get(`http://127.0.0.1:2211/mysql/`, { params: params }); };
export const getSqlQuery = params => { return axios.post(`${base}/sql/query`, params).then(res => res.data); };
export const getSqlQueries = params => { return axios.post(`${base}/sql/queries`, params).then(res => res.data); };
export const getSqlTrans = params => { return axios.post(`${base}/sql/trans`, params).then(res => res.data); };
export const getContainerQuery = params => { return axios.post(`${base}/container/query`, params).then(res => res.data); };
<file_sep>FROM ubuntu:18.04
RUN apt update \
&& apt upgrade -y \
&& apt install -y \
apt-utils build-essential clang cmake gdb gdbserver openssh-server rsync
# Taken from - https://docs.docker.com/engine/examples/running_ssh_service/#environment-variables
RUN mkdir /var/run/sshd
RUN echo 'root:root' | chpasswd
RUN sed -i 's/PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
# SSH login fix. Otherwise user is kicked off after login
RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd
ENV NOTVISIBLE "in users profile"
RUN echo "export VISIBLE=now" >> /etc/profile
# 22 for ssh server. 7777 for gdb server.
EXPOSE 22 7777
# Create dev user with password 'dev'
RUN useradd -ms /bin/bash dev
RUN echo 'dev:dev' | chpasswd
# Upon start, run ssh daemon
CMD ["/usr/sbin/sshd", "-D"]<file_sep>'use strict';
exports = module.exports = CjDbBase;
/**
* Class CjDbBase
* @constructor
*/
function CjDbBase() {
this.onError = null;
this.onOpened = null;
this.onClosed = null;
this.onDisconnected = null;
}
CjDbBase.prototype.open = function open() {};
CjDbBase.prototype.close = function close() {};
CjDbBase.prototype.isOpen = function isOpen() {};
/**
* query data by sql
* @param sql
* @param callback : fn(data, err)
*/
CjDbBase.prototype.query = function query(sql, callback) {};
<file_sep>/**
* Created by oudream on 2016/12/29.
*/
require('./../cjfunction_lang');
let expect = require('./../../chai-4').expect;
describe('CjFunction', function() {
it('getFunctionObject empty', function() {
expect(cjs.CjFunction.getFunctionObject()).to.deep.equal({
type: null,
name: '',
content: '',
arguments: null,
});
});
it('getFunctionObject', function() {
function fn1() {
expect(cjs.CjFunction.getFunctionObject(fn1, arguments)).to.deep.equal({
type: 'function',
name: 'fn1',
content: fn1.toString(),
arguments: arguments,
});
}
fn1(true, {a: 'a', b: 1});
});
});
<file_sep>require('./../cjinterinfo_lang');
let expect = require('./../../chai-4').expect;
describe('CjInterinfo', function() {
// it("base64Encode or base64Decode", function () {
// var strOrig = "Hello, world";
// var strEncode = "SGVsbG8sIHdvcmxk";
// var strEncode2 = cjs.CjEncoding.base64Encode(strOrig);
// var strOrig2 = cjs.CjEncoding.base64Decode(strEncode);
// expect(strEncode).to.equal(strEncode2);
// expect(strOrig).to.equal(strOrig2);
// });
});
<file_sep>/*!
// ICS实时数据请求的 json格式:支持散列请求:rtdata_v101;数组请求是:rtdata_v102;返回时都统一用:rtdata_v001
// url 是全局统一资源名(可以通用在容器对象或实体对象中)
// mid 是实时库的实时点全局唯一id
// url和mid可以只有一个,两个同时都有时以mid为准
// ics.json 散列请求
http://10.31.0.15:8821/ics.cgi?fncode=req.rtdata_v101&filetype=json
fncode = req.rtdata_v101
filetype = json
{
"session":"sbid=0001;xxx=adfadsf",
"structtype": "rtdata_v101",
"params":
[
{
"url": "/fp/zyj/fgj01/rfid",
"mid": 33556644
},
{
"url": "/fp/zyj/fgj01/ypmm",
"mid": 33556645
}
]
}
// ics.json 数组请求
// 数组请求中是以url为索引时,如果url可以对应到mid就以mid为开始索引;如果url是容器时就返回容器对应数量内个数
fncode = req.rtdata_v102
filetype = json
{
"session":"sbid=0001;xxx=adfadsf",
"structtype": "rtdata_v102",
"params":
[
{
"url": "/fp/zyj/fgj01/rfid",
"mid": 33556644,
"count": 100
},
{
"url": "/fp/zyj/fgj01/ypmm",
"mid": 33556645,
"count": 100
}
]
}
// ics.json返回时都统一用:rtdata_v001
// "v": 数值
// "q": 值的质量
// "t": 值的时间,unix时间戳(1970到目前的毫秒数,服务器的当地时间)
// 可选属性"srcid": 实时数据信息来源的源ID,
// 可选属性"srcurl": 实时数据信息来源的源url,
// 可选属性"state":状态码,无或0时表示成功,其它值看具体数据字典
{
"session":"sbid=0001;xxx=adfadsf",
"structtype":"rtdata_v001",
"data":[
{
"url":"/fp/zyj/fgj01/rfid",
"mid":33556644,
"v":"ABC12345678D",
"q":1,
"t":1892321321,
"srcid":1231231,
"srcurl":"/fp/zyj/fgjapp",
"state":0
},
{
"url":"/fp/zyj/fgj01/ypmm",
"mid":33556645,
"v":"20160100001",
"q":1,
"t":1892321521
"srcid":1231231,
"srcurl":"/fp/zyj/fgjapp",
"state":0
}
]
*/
(function () {
window.gcl = window.gcl || {};
window.gcl.rtdb = window.gcl.rtdb || {};
let rtdb = window.gcl.rtdb;
let myDebug = function () {
console.log.apply(null, arguments);
};
let EnumMeasureType = {
none: 0,
monsb: 1,
ycadd: 2,
straw: 3
};
rtdb.EnumMeasureType = EnumMeasureType;
let getMeasureTypeById = function getMeasureTypeById(measureId) {
let iId = Number(measureId);
if (iId >= 0x01000000 && iId < 0x02000000) {
return EnumMeasureType.monsb;
}
else if (iId >= 0x02000000 && iId < 0x03000000) {
return EnumMeasureType.ycadd;
}
else if (iId >= 0x03000000 && iId < 0x04000000) {
return EnumMeasureType.straw;
}
else {
return EnumMeasureType.none;
}
};
rtdb.getMeasureTypeById = getMeasureTypeById;
let MeasureBase = function MeasureBase() {
let iId = 0;
let sUrl = '';
if (arguments.length > 0) {
let arg0 = arguments[0];
if (typeof arg0 === 'number') {
iId = arg0;
if (arguments.length > 1) {
let arg1 = arguments[1];
if (typeof arg0 === 'string') {
sUrl = arg1;
}
}
}
else if (typeof arg0 === 'string') {
sUrl = arg0;
if (arguments.length > 1) {
let arg1 = arguments[1];
if (typeof arg0 === 'number') {
iId = arg1;
}
}
}
else if (arg0 !== null && typeof value === 'object') {
this.id = arg0.id ? arg0.id : iId;
this.url = arg0.url ? arg0.url : sUrl;
this.value = arg0.value ? arg0.value : null;
this.quality = arg0.quality ? arg0.quality : 0;
this.refreshTime = arg0.refreshTime ? arg0.refreshTime : Date();
this.changedTime = arg0.changedTime ? arg0.changedTime : Date();
this.refreshSourceId = arg0.refreshSourceId ? arg0.refreshSourceId : 0;
this.changedSourceId = arg0.changedSourceId ? arg0.changedSourceId : 0;
this.refreshReasonId = arg0.refreshReasonId ? arg0.refreshReasonId : 0;
this.changedReasonId = arg0.changedReasonId ? arg0.changedReasonId : 0;
this.equalStrategyId = arg0.equalStrategyId ? arg0.equalStrategyId : 0;
this.res = arg0.res ? arg0.res : 0;
return this;
// this.id = arg0.id ? arg0.id : iId;
// this.url = arg0.url ? arg0.url : sUrl;
// this.value = arg0.value ? arg0.value : null;
// this.quality = arg0.quality ? arg0.quality : 0;
// this.refreshTime = arg0.refreshTime ? arg0.refreshTime : Date();
// this.changedTime = arg0.changedTime ? arg0.changedTime : Date();
// this.refreshSourceId = arg0.refreshSourceId ? arg0.refreshSourceId : 0;
// this.changedSourceId = arg0.changedSourceId ? arg0.changedSourceId : 0;
// this.refreshReasonId = arg0.refreshReasonId ? arg0.refreshReasonId : 0;
// this.changedReasonId = arg0.changedReasonId ? arg0.changedReasonId : 0;
// this.equalStrategyId = arg0.equalStrategyId ? arg0.equalStrategyId : 0;
// this.res = arg0.res ? arg0.res : 0;
}
}
this.id = iId;
this.url = sUrl;
this.value = null;
this.quality = 0;
this.refreshTime = Date();
this.changedTime = Date();
this.refreshSourceId = 0;
this.changedSourceId = 0;
this.refreshReasonId = 0;
this.changedReasonId = 0;
this.equalStrategyId = 0;
this.res = 0;
};
rtdb.MeasureBase = MeasureBase;
MeasureBase.prototype.setValue = function (v) {
myDebug('!!!error. setValue is abstract method!');
};
MeasureBase.prototype.setVQT = function (v, q, t) {
myDebug('!!!error. setValue is abstract method!');
};
let MeasureManagerBase = function () {
this.measures = [];
this.measureClass = MeasureBase;
};
rtdb.MeasureManagerBase = MeasureManagerBase;
MeasureManagerBase.prototype.findById = function findById(iId = 0) {
let measures = this.measures;
for (let i = 0; i < measures.length; i++) {
let measure = measures[i];
if (measure.id === iId) {
return measure;
}
}
return null;
};
MeasureManagerBase.prototype.findByUrl = function findByUrl(sUrl = '') {
let measures = this.measures;
for (let i = 0; i < measures.length; i++) {
let measure = measures[i];
if (measure.url === sUrl) {
return measure;
}
}
return null;
};
MeasureManagerBase.prototype.append = function append(measure) {
if (measure) {
let bId = (typeof measure.id === 'number' && measure.id > 0 && this.findById(measure.id) === null);
let bUrl = (typeof measure.url === 'string' && this.findByUrl(measure.url) === null);
if (bId || bUrl) {
let measure = new this.measureClass(measure);
this.measures.push(measure);
return measure;
}
}
else {
return null;
}
};
MeasureManagerBase.prototype.appendById = function appendById(iId) {
if (typeof iId === 'number' && iId > 0 && this.findById(iId) === null) {
let measure = new this.measureClass(iId);
this.measures.push(measure);
return measure;
}
else {
return null;
}
};
MeasureManagerBase.prototype.appendByUrl = function appendByUrl(sUrl) {
if (typeof sUrl === 'string' && this.findByUrl(sUrl) === null) {
let measure = new this.measureClass(sUrl);
this.measures.push(measure);
return measure;
}
else {
return null;
}
};
MeasureManagerBase.prototype.remove = function remove(measure) {
let r = 0;
if (measure) {
let bId = (typeof measure.id === 'number' && measure.id > 0);
let bUrl = (typeof measure.url === 'string');
if (bId) r = this.removeById(measure.id);
if (bUrl) r += this.removeByUrl(measure.url);
}
return r;
};
MeasureManagerBase.prototype.removeById = function removeById(iId) {
let r = 0;
if (typeof iId === 'number') {
let measures = this.measures;
for (let i = measures.length - 1; i >= 0; i--) {
let measure = measures[i];
if (measure.id === iId) {
measures.splice(i, 1);
r++;
}
}
}
return r;
};
MeasureManagerBase.prototype.removeByUrl = function removeByUrl(sUrl) {
let r = 0;
if (typeof sUrl === 'string') {
let measures = this.measures;
for (let i = measures.length - 1; i >= 0; i--) {
let measure = measures[i];
if (measure.url === sUrl) {
measures.splice(i, 1);
r++;
}
}
}
return r;
};
MeasureManagerBase.prototype.getReqMeasures = function getReqMeasures() {
let r = [];
let measures = this.measures;
for (let i = 0; i < measures.length; i++) {
let measure = measures[i];
let reqMeasure = {
mid: measure.id,
url: measure.url
};
r.push(reqMeasure);
}
return r;
};
// # monsb
let MonsbMeasure = function MonsbMeasure() {
MeasureBase.apply(this, arguments);
this.value = -1;
};
MonsbMeasure.prototype = Object.create(MeasureBase.prototype);
MonsbMeasure.prototype.constructor = MonsbMeasure;
rtdb.MonsbMeasure = MonsbMeasure;
MonsbMeasure.prototype.setValue = function (v) {
let newValue = Number(v);
if (newValue !== this.value) {
this.value = newValue;
}
};
MonsbMeasure.prototype.setVQT = function (v, q, t) {
this.setValue(v);
if (q !== this.quality) {
this.quality = q;
}
if (t !== this.changedTime) {
this.changedTime = t;
}
};
let MonsbManager = function MonsbManager() {
MeasureManagerBase.call(this);
this.monsbs = this.measures;
this.measureClass = MonsbMeasure;
};
MonsbManager.prototype = Object.create(MeasureManagerBase.prototype);
MonsbManager.prototype.constructor = MonsbManager;
rtdb.MonsbManager = MonsbManager;
// # ycadd
let YcaddMeasure = function YcaddMeasure() {
MeasureBase.apply(this, arguments);
this.value = -1;
};
YcaddMeasure.prototype = Object.create(MeasureBase.prototype);
YcaddMeasure.prototype.constructor = YcaddMeasure;
rtdb.YcaddMeasure = YcaddMeasure;
YcaddMeasure.prototype.setValue = function (v) {
let newValue = Number(v);
if (newValue !== this.value) {
this.value = newValue;
}
};
YcaddMeasure.prototype.setVQT = function (v, q, t) {
this.setValue(v);
if (q !== this.quality) {
this.quality = q;
}
if (t !== this.changedTime) {
this.changedTime = t;
}
};
let YcaddManager = function YcaddManager() {
MeasureManagerBase.call(this);
this.ycadds = this.measures;
this.measureClass = YcaddMeasure;
};
YcaddManager.prototype = Object.create(MeasureManagerBase.prototype);
YcaddManager.prototype.constructor = YcaddManager;
rtdb.YcaddManager = YcaddManager;
// # straw
let StrawMeasure = function StrawMeasure() {
MeasureBase.apply(this, arguments);
this.value = -1;
};
StrawMeasure.prototype = Object.create(MeasureBase.prototype);
StrawMeasure.prototype.constructor = StrawMeasure;
rtdb.StrawMeasure = StrawMeasure;
StrawMeasure.prototype.setValue = function (v) {
let newValue = String(v);
if (newValue !== this.value) {
this.value = newValue;
}
};
YcaddMeasure.prototype.setVQT = function (v, q, t) {
this.setValue(v);
if (q !== this.quality) {
this.quality = q;
}
if (t !== this.changedTime) {
this.changedTime = t;
}
};
let StrawManager = function StrawManager() {
MeasureManagerBase.call(this);
this.straws = this.measures;
this.measureClass = StrawMeasure;
};
StrawManager.prototype = Object.create(MeasureManagerBase.prototype);
StrawManager.prototype.constructor = StrawManager;
rtdb.StrawManager = StrawManager;
// # rtdb's container
let monsbManager = new MonsbManager();
rtdb.monsbManager = monsbManager;
let ycaddManager = new YcaddManager();
rtdb.ycaddManager = ycaddManager;
let strawManager = new StrawManager();
rtdb.strawManager = strawManager;
// # rtdb's generic find - append
let findMeasureById = function findMeasureById(measureId) {
let iId = Number(measureId);
let r = null;
switch (getMeasureTypeById(iId)) {
case EnumMeasureType.monsb:
r = monsbManager.findById(iId);
break;
case EnumMeasureType.ycadd:
r = ycaddManager.findById(iId);
break;
case EnumMeasureType.straw:
r = strawManager.findById(iId);
break;
default:
break;
}
return r;
};
rtdb.findMeasureById = findMeasureById;
let findMeasureByUrl = function findMeasureByUrl(sUrl = '') {
return monsbManager.findByUrl(sUrl)
|| ycaddManager.findByUrl(sUrl)
|| strawManager.findByUrl(sUrl);
};
rtdb.findMeasureByUrl = findMeasureByUrl;
let appendMeasureById = function (measureId) {
let iId = Number(measureId);
let r = null;
switch (getMeasureTypeById(iId)) {
case EnumMeasureType.monsb:
r = monsbManager.appendById(iId);
break;
case EnumMeasureType.ycadd:
r = ycaddManager.appendById(iId);
break;
case EnumMeasureType.straw:
r = strawManager.appendById(iId);
break;
default:
break;
}
return r;
};
rtdb.appendMeasureById = appendMeasureById;
// # rtdb's sync data
let getReqMeasuresJson = function getReqMeasuresJson() {
return JSON.stringify({
session: '',
structtype: 'rtdata_v101',
params: (((monsbManager.getReqMeasures()).concat(ycaddManager.getReqMeasures())).concat(strawManager.getReqMeasures()))
});
};
rtdb.getReqMeasuresJson = getReqMeasuresJson;
let retReqMeasuresJson = '';
rtdb.retReqMeasuresJson = retReqMeasuresJson;
let dealRespMeasures = function (response) {
let arr = JSON.parse(response);
let measures = arr.data;
for (let i = 0; i < measures.length; i++) {
let measure = measures[i];
let iId = measure.mid;
let myMeasure = rtdb.findMeasureById(iId);
if (myMeasure !== null) {
myMeasure.setVQT(measure.v, measure.q, measure.t);
}
}
};
let startSyncMeasures = function () {
retReqMeasuresJson = getReqMeasuresJson();
let req_resp_rtdatas = function () {
let xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("post", "xxx.rtdata", true);
xmlhttp.setRequestHeader("POWERED-BY-AID", "Approve");
xmlhttp.setRequestHeader('Content-Type', 'json');
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
myDebug('接收:RespMeasures - ' + Date() + ' ' + xmlhttp.response.length);
dealRespMeasures(xmlhttp.responseText)
}
};
retReqMeasuresJson = getReqMeasuresJson();
let r = xmlhttp.send(retReqMeasuresJson);
myDebug('发送:ReqMeasures - ' + Date() + ' ' + r);
};
if (retReqMeasuresJson.length > 0) {
setInterval(req_resp_rtdatas, 1000);
return true;
}
else {
console.log('!!! warnning: retReqMeasuresJson is empty!!!')
return false;
}
};
rtdb.startSyncMeasures = startSyncMeasures;
})(typeof window !== "undefined" ? window : this);
<file_sep>FROM python:3.7.5-alpine3.10
ADD . /code
WORKDIR /code
RUN chmod +x timer1.py
CMD python timer1.py<file_sep>#!/usr/bin/env bash
### install node npm chrome puppeteer
# https://github.com/GoogleChrome/puppeteer/blob/master/docs/troubleshooting.md
#
# https://nodejs.org/en/download/package-manager/#debian-and-ubuntu-based-linux-distributions-enterprise-linux-fedora-and-snap-packages
#
# https://github.com/nodesource/distributions/blob/master/README.md
#
# chrome
# https://stackoverflow.com/questions/50942353/e-repository-http-dl-google-com-linux-chrome-deb-stable-release-changed-its
wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \
&& sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' \
&& apt-get update \
&& apt-get install -y google-chrome-unstable fonts-ipafont-gothic fonts-wqy-zenhei fonts-thai-tlwg fonts-kacst fonts-freefont-ttf --no-install-recommends \
&& rm -rf /var/lib/apt/lists/*
cd /opt \
&& apt-get update -y ; apt-get upgrade -y \
&& apt-get install sudo curl wget vim -y \
&& curl -sL https://deb.nodesource.com/setup_13.x | sudo -E bash - \
&& sudo apt-get install -y nodejs \
&& wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \
&& sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' \
&& apt-get update \
&& export PUPPETEER_SKIP_CHROMIUM_DOWNLOAD="true" \
&& npm i puppeteer \
&& rm -rf /var/lib/apt/lists/*
cd /opt \
&& apt-get update -y ; apt-get upgrade -y \
&& apt-get install sudo curl wget vim -y \
&& curl -sL https://deb.nodesource.com/setup_13.x | sudo -E bash - \
&& sudo apt-get install -y nodejs \
&& wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \
&& sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' \
&& apt-get update \
&& npm i puppeteer \
&& rm -rf /var/lib/apt/lists/*
### ok
cd /opt \
&& apt-get update -y ; apt-get upgrade -y \
&& apt-get install sudo curl wget vim -y \
&& curl -sL https://deb.nodesource.com/setup_13.x | sudo -E bash - \
&& sudo apt-get install -y nodejs \
&& npm i puppeteer
<file_sep>'use strict';
define(['jquery', 'global', 'async', 'cjcommon', 'cjstorage', 'cjdatabaseaccess', 'cjajax', 'modal'], function($, g, async) {
// let db = window.top.cjDb;
// let serverInfo = JSON.parse(localStorage.getItem('server-config'));
// let reqHost = serverInfo['server']['ipAddress'];
// let reqPort = serverInfo['server']['httpPort'];
// let reqParam = {
// reqHost: reqHost,
// reqPort: reqPort,
// };
// let sGetSignalSql = 'select F_PID as NeNo,F_URI as SignalUrl, F_NAME as SignalName, F_V as para from omc_user_subscribe where F_CLASS = ' + '\'' + 'RT_SILENCE' +'\'';
// db.load(sGetSignalSql, function(err, val) {
// if (err) {
// console.log(err);
// } else {
// for (let i = 0; i < val.length; i++) {
// cc4k.rtdb.appendMeasureByNenoCode(Number(val[i].NeNo), val[i].SignalUrl);
// }
// cc4k.rtdb.startSyncMeasures();
// cc4k.rtdb.registerMeasuresChangedCallback(function() {
// let aMeasure = [];
// let arr = [];
// let temp = 0;
// for (let i = 0; i < val.length; i++) {
// aMeasure.push(cc4k.rtdb.findMeasureByNenoCode(Number(val[i].NeNo), val[i].SignalUrl));
// }
// for (let i = 0; i < val.length; i++) {
// for (let j = 0; j < aMeasure.length; j++) {
// if (val[i].SignalUrl === aMeasure[j].code && Number(val[i].NeNo) === Number(aMeasure[j].neno)) {
// arr[temp] = {
// code: aMeasure[j].code,
// neNo: Number(aMeasure[j].neno),
// para: val[i].para,
// value: aMeasure[j].value,
// };
// temp++;
// break;
// }
// }
// }
// let msg ='';
// for (let i = 0; i < arr.length; i++) {
// let obj = JSON.parse(arr[i].para);
// if (arr[i].value === -1) {
// msg = msg + obj.msg;
// }
// }
// let confirm= new modal.Modal(msg);
// confirm.confirmInit(test);
// });
// }
// }, reqParam);
let confirm= new modal.CreateModal('当前入厂车号与实际叫号不符,请检查!<br/>');
setInterval(function() {
let a = sessionStorage.getItem('s_user');
if (a!=='admin') {
confirm.confirmInit(test);
}
}, 1000);
function test(flag) {
console.log(flag);
if (flag === 0) {
confirm.confirmCancel();
}
}
});
<file_sep>/**
* Created by oudream on 2017/1/6.
*/
'use strict';
let fs = require('fs');
let path = require('path');
let http = require('http');
let url = require('url');
let zlib = require('zlib');
exports = module.exports = Common;
function Common() {
};
Common.getJsonFromUrl = function getJsonFromUrl(hashBased) {
let query;
if (hashBased) {
let pos = location.href.indexOf('?');
if (pos==-1) return [];
query = location.href.substr(pos+1);
} else {
query = location.search.substr(1);
}
let result = {};
query.split('&').forEach(function(part) {
if (!part) return;
part = part.split('+').join(' '); // replace every + with space, regexp-free version
let eq = part.indexOf('=');
let key = eq>-1 ? part.substr(0, eq) : part;
let val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : '';
let from = key.indexOf('[');
if (from==-1) result[decodeURIComponent(key)] = val;
else {
let to = key.indexOf(']');
let index = decodeURIComponent(key.substring(from+1, to));
key = decodeURIComponent(key.substring(0, from));
if (!result[key]) result[key] = [];
if (!index) result[key].push(val);
else result[key][index] = val;
}
});
return result;
};
<file_sep>#!/bin/ash
# do not detach (-D), log to stderr (-e), passthrough other arguments
/usr/sbin/sshd -e "$@"
# nginx -c /opt/ddd/ccpp/gcl3/deploy/nginx/nginx.conf
nginx
/opt/ddd/ccpp/gcl3/build/deploy/bin_unix_d/gcl_svr_bus &
/opt/ddd/ccpp/gcl3/build/deploy/bin_unix_d/gcl_svr_fastcgi_rtdata
<file_sep>'use strict'
process.env.BABEL_ENV = 'web'
const path = require('path')
const webpack = require('webpack')
const MinifyPlugin = require("babel-minify-webpack-plugin")
const CopyWebpackPlugin = require('copy-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { VueLoaderPlugin } = require('vue-loader')
const vueLoaderConfig = require('./vue-loader.conf')
let utils = require('./utils')
let webConfig = {
devtool: '#cheap-module-eval-source-map',
entry: {
web: path.join(process.env.CVUE3_WEB_P, './main.js')
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [process.env.CVUE3_WEB_P, path.join(process.env.CVUE3_WEB_P, '_test')]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
},
plugins: [
new VueLoaderPlugin(),
new MiniCssExtractPlugin({filename: 'styles.css'}),
new HtmlWebpackPlugin({
filename: 'index.html',
template: path.resolve(process.env.CVUE3_NODE_P, './config/index.html'),
minify: {
collapseWhitespace: true,
removeAttributeQuotes: true,
removeComments: true
},
nodeModules: false
}),
new webpack.DefinePlugin({
'process.env.IS_WEB': 'true'
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin()
],
output: {
filename: '[name].js',
path: path.resolve(process.env.CVUE3_NODE_P, './dist/web')
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'@': process.env.CVUE3_WEB_P,
'scss_vars': path.resolve(process.env.CVUE3_WEB_P, 'styles/vars.scss'),
}
},
target: 'web'
}
/**
* Adjust webConfig for production settings
*/
if (process.env.NODE_ENV === 'production') {
webConfig.devtool = ''
webConfig.plugins.push(
new MinifyPlugin(),
new CopyWebpackPlugin([
{
from: path.resolve(process.env.CVUE3_NODE_P, './static'),
to: path.resolve(process.env.CVUE3_NODE_P, './dist/web/static'),
ignore: ['.*']
}
]),
new webpack.DefinePlugin({
'process.env.NODE_ENV': '"production"'
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
)
}
module.exports = webConfig
<file_sep>#!/bin/sh
npm i;
ionic cordova build android --prod;<file_sep>#!/usr/bin/env bash
### build docker bus prepare
dk_gcl_bus_p=/opt/limi/hello-docker/projects/gcl3/alpine-bus
#ln -s /opt/ddd/ccpp/gcl3/build/deploy ${dk_gcl_bus_p}/deploy
#ln -s /opt/ddd/ccpp/gcl3/deploy/assets ${dk_gcl_bus_p}/assets
## delete deploy
rm -r ${dk_gcl_bus_p}/assets
rm -r ${dk_gcl_bus_p}/deploy/bin_unix_d
## copy deploy
#cp -r /opt/ddd/ccpp/gcl3/build/deploy ${dk_gcl_bus_p}/deploy
cp -r /opt/ddd/web/limi3/assets/projects/gcl3 ${dk_gcl_bus_p}/assets
## copy binary
mkdir -p ${dk_gcl_bus_p}/deploy/bin_unix_d
cp /opt/ddd/ccpp/gcl3/build/deploy/bin_unix_d/liblibccxx.so ${dk_gcl_bus_p}/deploy/bin_unix_d/
cp /opt/ddd/ccpp/gcl3/build/deploy/bin_unix_d/liblibccxx_database_sqlite.so ${dk_gcl_bus_p}/deploy/bin_unix_d/
cp /opt/ddd/ccpp/gcl3/build/deploy/bin_unix_d/gcl_svr_bus ${dk_gcl_bus_p}/deploy/bin_unix_d/
cp /opt/ddd/ccpp/gcl3/build/deploy/bin_unix_d/gcl_svr_fastcgi_rtdata ${dk_gcl_bus_p}/deploy/bin_unix_d/
cp /opt/ddd/ccpp/gcl3/build/deploy/bin_unix_d/gcl_svr_fastcgi_filesystem ${dk_gcl_bus_p}/deploy/bin_unix_d/
cp /opt/ddd/ccpp/gcl3/build/deploy/bin_unix_d/gcl_svr_fastcgi_rtlog ${dk_gcl_bus_p}/deploy/bin_unix_d/
cp /opt/ddd/ccpp/gcl3/build/deploy/bin_unix_d/gcl_svr_rtdbs ${dk_gcl_bus_p}/deploy/bin_unix_d/
## copy config
cp -r /opt/ddd/ccpp/gcl3/deploy/config ${dk_gcl_bus_p}/deploy/
#cp -r /opt/ddd/ccpp/gcl3/deploy/gcl_sdk ${dk_gcl_bus_p}/deploy/bin_unix_d/
### build docker bus build
cd /opt/limi/hello-docker/projects/gcl3/alpine-bus
## ssh ca RSA
cat ./../../../assets/ssh/identity.pub > ./identity.pub
## build
docker build -t oudream/gcl3-bus-alpine:1.0.2 .
### run docker bus
# local
docker run -p 2231:22 -p 2232:8821 -d --restart=always oudream/gcl3-bus-alpine:1.0.2
# local debug
docker run -p 2231:22 -p 2232:8821 -it --entrypoint='' oudream/gcl3-bus-alpine:1.0.2 /bin/sh
## ssh
# remote
ssh [email protected] -p 2233 -AXY -v # or $(docker-machine ip default)
# local
ssh root@localhost -p 2233 -AXY # or $(docker-machine ip default)
## brower
172.16.31.10:2232
open http://172.16.31.10:2232/bus/viewer.html
open http://172.16.31.10:2232/bus/poster.html
192.168.127.12:2232
## node
node ./httpserver-mock-master.js
## upload
cd /opt/limi/hello-docker/hello/nginx/upload1
sFp1=$PWD/readme.md
curl -F "file=@${sFp1};type=text/plain;filename=a1" 172.16.31.10:2232/upload
### docker push image
docker login
docker tag gcl3-bus-alpine oudream/gcl3-bus-alpine:1.0.2
docker push oudream/gcl3-bus-alpine:1.0.2
docker pull oudream/gcl3-bus-alpine:1.0.2
<file_sep>(function() {
'use strict';
let Vehicle = {
apiVersion: 'v1',
kind:
'odc',
metadata:
{
name: 'vehicle',
namespace: 'gcl3'
},
spec: {
attrs: [
{
name: 'VehID',
title: '⻋辆ID',
model: 'int',
isNull: false
},
{
name: 'ManID',
desc: '品牌',
model: 'int',
refer: {
odc: 'man',
key: 'ManID',
title: 'ManName'
}
},
{
name: 'ModelName',
title: '⻋型名称',
model: 'string',
isNull: false
},
{
name: 'ModelPy',
title: '⻋型拼音',
model: 'string',
isNull: false
},
{
name: 'VehDT',
title: '创建日期',
model: 'string',
isNull: false
},
{
name: 'LanID',
title: '语言ID',
model: 'enum',
scopes: ['1033,英语(美国)', '2052,简体中文', '1028,繁体中文(台湾)'],
values: [1033, 2052, 1028],
default: 1033,
width: 100,
},
{
name: 'BeginDT',
title: '生产日期',
model: 'string',
width: 100,
},
{
name: 'EndDT',
title: '结束日期',
model: 'string',
width: 100,
},
{
name: 'FrontPhotoFileName',
title: '前面照片',
model: 'string',
},
{
name: 'SidePhotoFileName',
title: '侧面照片',
model: 'string',
},
{
name: 'BackPhotoFileName',
title: '后面照片',
model: 'string',
},
{
name: 'Wheelbase',
title: '轴距',
model: 'double',
scopes: [0, 9999],
width: 100,
},
{
name: 'TrackDia',
title: '轮毂直径',
model: 'double',
scopes: [0, 9999],
width: 100,
},
{
name: 'FTreadWidth',
title: '前轮距',
model: 'double',
scopes: [0, 9999],
width: 100,
},
{
name: 'RTreadWidth',
title: '后轮距',
model: 'double',
scopes: [0, 9999],
width: 100,
},
{
name: 'FToeMin',
title: '前轮前束最小',
model: 'double',
scopes: [0, 9999],
width: 90,
},
{
name: 'FToe',
title: '前轮前束标准',
model: 'double',
scopes: [0, 9999],
width: 90,
},
{
name: 'FToeMax',
title: '前轮前束最大',
model: 'double',
scopes: [0, 9999],
width: 90,
},
{
name: 'FCamberMin',
title: '前轮外倾最小',
model: 'double',
scopes: [0, 9999],
width: 90,
},
{
name: 'FCamber',
title: '前轮外倾典型',
model: 'double',
scopes: [0, 9999],
width: 90,
},
{
name: 'FCamberMax',
title: '前轮外倾最大',
model: 'double',
scopes: [0, 9999],
width: 90,
},
{
name: 'KpiCasterMin',
title: '主销后倾最小',
model: 'double',
scopes: [0, 9999],
width: 90,
},
{
name: 'KpiCaster',
title: '主销后倾标准',
model: 'double',
scopes: [0, 9999],
width: 90,
},
{
name: 'KpiCasterMax',
title: '主销后倾最大',
model: 'double',
scopes: [0, 9999],
width: 90,
},
{
name: 'KpiCamberMin',
title: '主销内倾最小值',
model: 'double',
scopes: [0, 9999],
width: 90,
},
{
name: 'KpiCamber',
title: '主销内倾标准值',
model: 'double',
scopes: [0, 9999],
width: 90,
},
{
name: 'KpiCamberMax',
title: '主销内倾最大值',
model: 'double',
scopes: [0, 9999],
width: 90,
},
{
name: 'RToeMin',
title: '后轮前束最小值',
model: 'double',
scopes: [0, 9999],
width: 90,
},
{
name: 'RToe',
title: '后轮前束标准值',
model: 'double',
scopes: [0, 9999],
width: 90,
},
{
name: 'RToeMax',
title: '后轮前束最大值',
model: 'double',
scopes: [0, 9999],
width: 90,
},
{
name: 'RCamberMin',
title: '后轮外倾最小值',
model: 'double',
scopes: [0, 9999],
width: 90,
},
{
name: 'RCamber',
title: '后轮外倾典型值',
model: 'double',
scopes: [0, 9999],
width: 90,
},
{
name: 'RCamberMax',
title: '后轮外倾最大值',
model: 'double',
scopes: [0, 9999],
width: 90,
},
{
name: 'RThrustMin',
title: '推进⻆最小值',
model: 'double',
scopes: [0, 9999],
width: 90,
},
{
name: 'RThrust',
title: '推进⻆标准值',
model: 'double',
scopes: [0, 9999],
width: 90,
},
{
name: 'RThrustMax',
title: '推进⻆最大值',
model: 'double',
scopes: [0, 9999],
width: 90,
}
],
container: {
keys: ['VehID'],
sorts: ['ModelName']
},
table: {},
tree: {},
ns: [
{
kind: odl.UiVueBase ? odl.UiVueBase.kind : '',
metadata:
{
name: '',
},
spec: {
title: {
text: '⻋辆信息管理',
},
attrs: [
{
name: 'VehID',
readonly: true,
visible: false,
},
{
name: 'ManID',
visible: false,
required: true,
},
{
name: 'ModelPy',
required: true,
},
{
name: 'VehDT',
visible: false,
readonly: true,
required: true,
default: () => {
return Date.now()
},
},
{
name: 'ManID',
visible: false,
},
{
name: 'FrontPhotoFileName',
contentType: "image"
},
{
name: 'SidePhotoFileName',
contentType: "image"
},
{
name: 'BackPhotoFileName',
contentType: "image"
}
],
filter: {
filters: [
{
fields: [
{value: 'ManID', label: '品牌名称'}
],
operations: [
{value: '=', label: '='}
],
type: 'refer',
},
{
fields: [
{value: 'ModelName', label: '车型名称'},
{value: 'ModelPy', label: '车型拼音'},
],
}
]
}
}
},
{kind: odl.UiVueForm ? odl.UiVueForm.kind : ''},
{kind: odl.UiVueTable ? odl.UiVueTable.kind : ''},
{
kind: odl.DbMysql ? odl.DbMysql.kind : '',
metadata: {
name: '',
},
spec: {
table: {
name: 'Vehicle'
}
}
},
{
kind: odl.DbSqlite ? odl.DbSqlite.kind : '',
metadata: {
name: ''
},
spec: {
table: {
name: 'Vehicle',
sync: true
},
attrs: [
{
name: 'remark',
field: {
fieldType: 'text'
}
}
]
}
}
]
}
};
odl.register(Vehicle);
return Vehicle;
})();
/**
*
⻋辆信息表
(Vehicle)
属性名/列名
类型
⻓度
是否主外键
是否为 空
默认 值
备注
ManID
varchar
20
不为主外键
可为空
品牌ID
ManName
varchar
20
为主外键
不为空
品牌名称
ManPy
varchar
20
不为主外键
不为空
品牌拼音
VehID
varchar
20
为主键
可为空
⻋辆ID
ModelName
varchar
20
为主外键
不为空
⻋型名称
ModelPy
varchar
20
不为主外键
不为空
⻋型拼音
VehDT
varchar
20
不为主外键
不为空
创建日期
LanID
varchar
10
不为主外键
不为空
语言ID
ModelID
varchar
20
不为主外键
可为空
⻋型ID
ModelName
varchar
20
为主外键
不为空
⻋型名称
ModelPy
varchar
20
不为主外键
不为空
⻋型拼音
BeginDT
Date
不为主外键
不为空
生产日期
EndDT
Date
不为主外键
不为空
结束日期
Wheelbase
decimal
(7,5 )
不为主外键
可为空
轴距
TrackDia
decimal
(7,5 )
不为主外键
可为空
轮毂直径
FTreadWidth
decimal
(7,5 )
不为主外键
可为空
前轮距
RTreadWidth
decimal
(7,5 )
不为主外键
可为空
后轮距
FToeMin
decimal
(7,5 )
不为主外键
可为空
前轮前束最小值(左右轮一 样)
FToe
decimal
(7,5 )
不为主外键
可为空
前轮前束标准 值
FToeMax
decimal
(7,5 )
不为主外键
可为空
前轮前束最大 值 (左右轮一 样)
FCamberMin
decimal
(7,5 )
不为主外键
可为空
前轮外倾最小 值
FCamber
decimal
(7,5 )
不为主外键
可为空
前轮外倾典型 值
FCamberMax
decimal
(7,5 )
不为主外键
可为空
前轮外倾最大 值
KpiCasterMin
decimal
(7,5 )
不为主外键
可为空
主销后倾最小 值 (左右轮一 样)
KpiCaster
decimal
(7,5 )
不为主外键
可为空
主销后倾标准 值
KpiCasterMax
decimal
(7,5 )
不为主外键
可为空
主销后倾最大 值 (左右轮一 样)
KpiCamberMin
decimal
(7,5 )
不为主外键
可为空
主销内倾最小值
KpiCamber
decimal
(7,5 )
不为主外键
可为空
主销内倾标准值
KpiCamberMax
decimal
(7,5 )
不为主外键
可为空
主销内倾最大值
RToeMin
decimal
(7,5 )
不为主外键
可为空
后轮前束最小值
RToe
decimal
(7,5 )
不为主外键
可为空
后轮前束标准值
RToeMax
decimal
(7,5 )
不为主外键
可为空
后轮前束最大值
RCamberMin
decimal
(7,5 )
不为主外键
可为空
后轮外倾最小值
RCamber
decimal
(7,5 )
不为主外键
可为空
后轮外倾典型值
RCamberMax
decimal
(7,5 )
不为主外键
可为空
后轮外倾最大值
RThrustMin
decimal
(7,5 )
不为主外键
可为空
推进⻆最小值
RThrust
decimal
(7,5 )
不为主外键
可为空
推进⻆标准值
RThrustMax
decimal
(7,5 )
不为主外键
可为空
推进⻆最大值
*/
<file_sep>#!/usr/bin/env bash
#docker build --no-cache -t ionic3-android-builder .
docker build -t oudream/ionic3-android-ubuntu:1.0.2 .
docker login
docker push oudream/ionic3-android-ubuntu:1.0.2
docker run -it oudream/ionic3-android-ubuntu:1.0.2 /bin/bash
git clone https://github.com/yannbf/ionic3-components.git
ionic cordova platform add android
<file_sep># https://github.com/CenturyLinkLabs/dockerfile-from-image
# https://github.com/CenturyLinkLabs/dockerfile-from-image/issues/14
docker build -t docker-from-file-image .
#Make sure that /run/docker.sock exist on your system, if not, try with /var/run/docker.sock instead.
#For the, it was the problem, i was using /run/docker.sock while the right path for my system was /var/run/docker.sock
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock docker-from-file-image docker-from-file-image
#---------------
#FROM alpine:3.2
#RUN apk --update add ruby-dev ca-certificates && gem install --no-rdoc --no-ri docker-api && apk del ruby-dev ca-certificates && apk add ruby ruby-json && rm /var/cache/apk/*
#ADD file:8a5c43d666322dd4df724cc7c2c838b2ef82e3656edcb4af264bcc89aedd4502 in /usr/src/app/dockerfile-from-image.rb
#RUN chmod +x /usr/src/app/dockerfile-from-image.rb
#I would say the result is close enough ;)
#Docker version 1.13.0-rc4 on Mac OS X.11.6<file_sep>FROM ubuntu:18.04
RUN echo "deb http://security.ubuntu.com/ubuntu xenial-security main" | tee /etc/apt/sources.list.d/libjasper.list && \
apt update -y ; apt upgrade -y && \
apt install -y gcc g++ cmake build-essential gdb gdbserver git \
unixodbc unixodbc-dev libcurl4-openssl-dev uuid uuid-dev libssl-dev libncurses5-dev \
qt5-default libqt5svg5 libqt5svg5-dev qtcreator \
software-properties-common \
libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev \
python3 python3-pip python3-dev python3-numpy \
libtbb2 libtbb-dev libjpeg-dev libpng-dev libtiff-dev libjasper-dev libdc1394-22-dev && \
update-alternatives --install /usr/bin/python python /usr/bin/python3 1 && \
update-alternatives --install /usr/bin/pip python /usr/bin/pip3 1
RUN cd /opt && \
git clone https://github.com/opencv/opencv.git opencv && \
cd /opt/opencv && git reset --hard 4c71dbf && \
mkdir build && cd build && \
cmake -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local .. && \
make -j7 && make install && \
rm -r /opt/opencv
RUN apt update \
&& apt install -y openssh-server \
xauth \
x11-apps \
&& mkdir /var/run/sshd \
&& mkdir /root/.ssh \
&& chmod 755 /root/.ssh \
&& ssh-keygen -A \
&& sed -i "s/^.*PasswordAuthentication.*$/PasswordAuthentication yes/" /etc/ssh/sshd_config \
&& sed -i "s/^#PermitRootLogin.*$/PermitRootLogin yes/" /etc/ssh/sshd_config \
&& sed -i "s/^.*X11Forwarding.*$/X11Forwarding yes/" /etc/ssh/sshd_config \
&& sed -i "s/^.*X11UseLocalhost.*$/X11UseLocalhost no/" /etc/ssh/sshd_config \
&& grep "^X11UseLocalhost" /etc/ssh/sshd_config || echo "X11UseLocalhost no" >> /etc/ssh/sshd_config \
&& rm -rf /var/lib/apt/lists/*
RUN echo "root:123456" | chpasswd
ENTRYPOINT ["sh", "-c", "/usr/sbin/sshd && tail -f /dev/null"]
<file_sep>FROM alpine
RUN apk add --update alpine-sdk \
apk add libffi-dev openssl-dev \
apk add cmake git openssh-server vim gdb gdbserver \
apk add unixodbc-dev uuid-dev \
apk add unixodbc uuid
ENTRYPOINT ["tail -f /dev/null"]<file_sep>#!/usr/bin/env bash
#
# https://github.com/GoogleChrome/puppeteer/issues/1793
#
# build dockerfile
cat ./../../../assets/ssh/identity.pub > ./identity.pub
docker build -t oudream/puppeteer-dev-alpine:1.2 .
# run on vps
docker run -d -p 2231:22 -p 8821:8821 -p 8841:8841 -p 8861:8861 -v /opt/ddd:/opt/ddd oudream/puppeteer-dev-alpine:1.2
# on vps
ssh -AXY [email protected]
# on macos
ssh [email protected] -p 2231 -AXY -v # or $(docker-machine ip default)
# run on macos(localhost)
docker run -d -p 2231:22 -p 8821:8821 -p 8841:8841 -p 8861:8861 oudream/puppeteer-dev-alpine:1.2
ssh root@localhost -p 2231 -AXY -v
### docker push image
docker login
docker tag puppeteer-dev-alpine oudream/puppeteer-dev-alpine:1.2
docker push oudream/puppeteer-dev-alpine:1.2
docker pull oudream/puppeteer-dev-alpine
### test
git clone https://github.com/oudream/hello-puppeteer.git /opt/ddd/ops/puppeteer/hello-puppeteer && \
docker run -itd -v /opt/ddd/ops/puppeteer/hello-puppeteer:/opt/ddd/ops/puppeteer/hello-puppeteer --restart=always --entrypoint="" \
oudream/puppeteer-dev-alpine:1.2 node /opt/ddd/ops/puppeteer/hello-puppeteer/projects/gcl3/bus/poster-enabled-timer.js
docker run -itd -v /opt/ddd/ops/puppeteer/hello-puppeteer:/opt/ddd/ops/puppeteer/hello-puppeteer --entrypoint="" \
oudream/puppeteer-dev-alpine:1.2 /bin/sh
# error
# npm i puppeteer # error at launch
# (node:37) UnhandledPromiseRejectionWarning: Error: Failed to launch chrome! spawn /node_modules/puppeteer/.local-chromium/linux-706915/chrome-linux/chrome ENOENT
# npm i puppeteer # Unfortunately this is not enough.
# You will require the following Dependencies
# sudo apt-get install gconf-service libasound2 libatk1.0-0 libatk-bridge2.0-0 libc6 libcairo2 libcups2
# libdbus-1-3 libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0
# libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1
# libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2
# libxrender1 libxss1 libxtst6 ca-certificates fonts-liberation libappindicator1 libnss3
# lsb-release xdg-utils wget
### https://stackoverflow.com/questions/52993002/headless-chrome-node-api-and-puppeteer-installation
<file_sep>
let deepmergeAll = require('./deepmerge1')
const result = deepmergeAll([,
{ level1: { level2: { name: 'David', parts: ['head', 'shoulders'] } } },
{ level1: { level2: { face: 'meh', parts: ['knees', 'toes'] } } },
{ level1: { level2: { eyes: 'more meh', parts: ['eyes'] } } },
]);
console.log(result);
<file_sep># docker-tutorial
Docker 基本教學 - 從無到有 Docker-Beginners-Guide
教你用 [Docker](https://www.docker.com/) 建立 [Django](https://github.com/django/django) + [PostgreSQL](https://www.postgresql.org/) 📝
* [Youtube Tutorial PART 1 - Docker 基本教學 - 從無到有 Docker-Beginners-Guide](https://youtu.be/Wg5m0-Jyox8)
* [Youtube Tutorial PART 2 - 用 Docker 實戰 Django 以及 Postgre](https://youtu.be/aZ6woJ7qekE)
* [Youtube Tutorial PART 3 - Docker 基本教學 - 透過 portainer 管理 Docker](https://youtu.be/VZjHmBcEcew)
* [Youtube Tutorial PART 4 - Docker push image to Docker Hub 教學](https://youtu.be/dVBKwmqO5e4)
其他說明
* [Youtube Tutorial-Ubuntu(Linux) 如何安裝 docker](https://youtu.be/eS_HMBC_RaA)
* [Youtube Tutorial-docker-compose networks 說明](https://youtu.be/wmV9WfkpyGk)
* [Youtube Tutorial-docker-compose up/down 和 restart 的差異](https://youtu.be/nX-sbLPz-MU)
* [Youtube Tutorial-Linux 教學-開機自動啟動 docker / compose](https://youtu.be/c4YIQHCDLnQ)
* [Youtube Tutorial - Docker 基本教學 - 在 docker compose 中善用 Environment variables](https://youtu.be/JwbI1aNKbtY) - [Environment variables in Compose](https://github.com/twtrubiks/docker-tutorial/tree/master/docker-env-tutorial)
* [Youtube Tutorial - 如何清除 Docker container log](https://youtu.be/SiG0tmwhqqg)
## 簡介
[Docker](https://www.docker.com/)

***Containers as a Service ( CaaS ) - 容器如同服務***
算是近幾年才開始紅的技術,蠻多公司都有使用 Docker,而且真的很方便,值得大家去了解一下 :smile:
如果你有環境上不統一的問題? 請用 Docker :smile:
如果你有每次建立環境都快抓狂的問題? 請用 Docker :blush:
如果你想要高效率、輕量、秒開的環境,請用 Docker :blush:
如果你不想搞死自己,請用 Docker :smile:
如果你想潮到出水,請一定要用 Docker :laughing:
### 什麼是 Docker
[Docker](https://www.docker.com/) 是一個開源專案,出現於 2013 年初,最初是 Dotcloud 公司內部的 Side-Project。
它基於 Google 公司推出的 Go 語言實作。( Dotcloud 公司後來改名為 Docker )
技術原理我們這邊就不提了,簡單提一下他的好處。
我們先來看看官網的說明
Comparing Containers and Virtual Machines ( 傳統的虛擬化 )

從這張圖可以看出 Containers 並沒有 OS ,容量自然就小,而且啟動速度神快
詳細可參考 [https://www.docker.com/what-container](https://www.docker.com/what-container)
Virtual Machines 是什麼?
類似 [https://www.virtualbox.org/](https://www.virtualbox.org/),我們可能用它裝裝看其他作業系統,例如說
我是 MAC,但我想玩 Windows,我就會在 MAC 中裝 VM 並且灌 Windows 系統。
一個表格了解 Docker 有多棒 :+1:
Feauture | Containers | Virtual Machines ( 傳統的虛擬化 )
-- | ---------- | ----------
啟動 | 秒開 | 最快也要分鐘
容量 | MB | GB
效能 | 快 | 慢
支援數量 | 非常多 Containers | 10多個就很了不起了
複製相同環境 | 快 | 超慢
不理解:question::question::question:
我們來看一張圖,包準你懂

圖的來源
[https://blog.jayway.com/2015/03/21/a-not-very-short-introduction-to-docker/](https://blog.jayway.com/2015/03/21/a-not-very-short-introduction-to-docker/)
### 為什麼要使用 Docker
潮~ 不解釋 :satisfied:
#### 更有效率的利用資源
比起像是 [https://www.virtualbox.org/](https://www.virtualbox.org/),Docker 的利用率更高,我們可以設定更多
的 Containers ,而且啟動速度飛快!!:flushed:
#### 統一環境
相信大家都有每次搞電腦的環境都搞的很煩的經驗 :angry:
假設今天公司來了個新同事,就又要幫他建立一次環境 :expressionless:
不然就是,我的電腦 run 起來正常阿~ 你的怎麼不行,是不是 xxx 版本的關係阿 :joy:
相信大家多多少少都遇過上面這些事情,我們可以透過 Docker 來解決這些問題,
保持大家環境一致,而且要建立的時候也很快 :smile:
#### 對於 DevOps 的好處
對於 [DevOps](https://zh.wikipedia.org/wiki/DevOps) 來說,最希望的就是可以設定一次,將來在其他地方都可以快速建立環境且正常執行。
### Docker 概念
建議大家先了解一下 Docker 中的幾個名詞,分別為
***Image***
映像檔,可以把它想成是以前我們在玩 VM 的 Guest OS( 安裝在虛擬機上的作業系統 )。
Image 是唯讀( R\O )
***Container***
容器,利用映像檔( Image )所創造出來的,一個 Image 可以創造出多個不同的 Container,
Container 也可以被啟動、開始、停止、刪除,並且互相分離。
Container 在啟動的時候會建立一層在最外(上)層並且是讀寫模式( R\W )。
這張圖解釋了 Image 是唯讀( R\O )以及 Container 是讀寫模式( R\W ) 的關係

更多關係可參考 [https://docs.docker.com/engine/userguide/storagedriver/imagesandcontainers/#images-and-layers](https://docs.docker.com/engine/userguide/storagedriver/imagesandcontainers/#images-and-layers)
***Registry***
可以把它想成類似 [GitHub](https://github.com/),裡面存放了非常多的 Image ,可在 [Docker Hub](https://hub.docker.com/) 中查看。
更詳細的我這邊就不再解釋惹,留給大家做作功課:stuck_out_tongue:
## 安裝
Windows
請先到 Docker 官網
[https://www.docker.com/docker-windows](https://www.docker.com/docker-windows)
下載 stable 版本

接下來就是無腦安裝,安裝完後他會叫你登出電腦,點下去後就會幫你登出電腦

接著如果你的電腦沒有啟用 [Hyper-V](https://msdn.microsoft.com/zh-tw/library/hh831531(v=ws.11).aspx) ,他會叫你重啟電腦
(一樣,點下去就對惹)
( 更多可 Hyper-V 介紹請參考 [https://docs.microsoft.com/zh-tw/virtualization/hyper-v-on-windows/about/](https://docs.microsoft.com/zh-tw/virtualization/hyper-v-on-windows/about/) )

重新開機後,你就會發現可愛的 Docker 在右下角蹦出來惹

我們可以再用 cmd 確認一下是否有成功安裝
```cmd
docker --version
docker-compose --version
```

記得再設定一個東西 Shared Drives

裝完了之後,建議大家再多裝一個 [Kitematic](https://kitematic.com/),他是 GUI 介面的,方便你使用 Docker,
( 後面會再介紹一個更贊的 GUI 介面 [portainer](https://github.com/portainer/portainer) :grin: )
我知道打指令很潮,但還是建議裝一下。
直接對著你的 Docker 圖示右鍵,就可以看到 [Kitematic](https://kitematic.com/)


下載回來直接解壓縮雙點擊即可使用

MAC
MAC 我本身也有,但因為更早之前就裝了,步驟就沒記錄了,基本上大同小異
[https://www.docker.com/docker-mac](https://www.docker.com/docker-mac)
Linux
[Youtube Tutorial-Ubuntu(Linux) 如何安裝 docker](https://youtu.be/eS_HMBC_RaA)
這裡使用 Ubuntu 當作範例,
雖然在 ubuntu 中有 `snap` 可以非常快速的安裝 docker,
但在這邊我們不使用 `snap` 的方法安裝:smile:
請參考官方文件步驟安裝,
Get Docker Engine - Community for Ubuntu
[Get Docker Engine - Community for Ubuntu](https://docs.docker.com/install/linux/docker-ce/ubuntu/)
安裝後步驟 (optional:exclamation:), 但建議參考一下
[Post-installation steps for Linux](https://docs.docker.com/install/linux/linux-postinstall/)
docker-compose 的安裝
[docker-compose install](https://docs.docker.com/compose/install/)
系統資源分配問題,
假如你是使用 windows 或是 mac 的 docker,
你會有一個界面可以設定你要分多少的 cpu 以及 ram 給你的 docker,
通常會在 Preferences -> Advanced, 有 GUI 界面,

但如果是使用 linux, 就不會有這個界面, 因為在 Linux 中,
會自動依照系統的資源進行分配.
## 指令介紹
接著介紹一些 Docker 的指令,
Docker 的指令真的很多,這裡就介紹我比較常用的或是實用的指令
查看目前 images
```cmd
docker images
```
建立 image
```cmd
docker create [OPTIONS] IMAGE [COMMAND] [ARG...]
```
詳細的參數可參考 [https://docs.docker.com/engine/reference/commandline/create/](https://docs.docker.com/engine/reference/commandline/create/)
範例 ( 建立一個名稱為 busybox 的 image )
```cmd
docker create -it --name busybox busybox
```
刪除 Image
```cmd
docker rmi [OPTIONS] IMAGE [IMAGE...]
```
查看目前運行的 container
```cmd
docker ps
```
查看目前全部的 container( 包含停止狀態的 container )
```cmd
docker ps -a
```
新建並啟動 Container
```cmd
docker run [OPTIONS] IMAGE[:TAG|@DIGEST] [COMMAND] [ARG...]
```
舉個例子
```cmd
docker run -d -p 80:80 --name my_image nginx
```
`-d` 代表在 Detached( 背景 )執行,如不加 `-d`,預設會 foreground ( 前景 ) 執行
`-p` 代表將本機的 80 port 的所有流量轉發到 container 中的 80 port
`--name` 設定 container 的名稱
在舉一個例子
```cmd
docker run -it --rm busybox
```
`--rm` 代表當 exit container 時,會自動移除 container。 ( incompatible with -d )
更詳細的可參考 [https://docs.docker.com/engine/reference/run/](https://docs.docker.com/engine/reference/run/)
啟動 Container
```cmd
docker start [OPTIONS] CONTAINER [CONTAINER...]
```
如果想讓他在前景跑順便觀看輸出 , 可以使用以下指令
```cmd
docker start -a [OPTIONS] CONTAINER [CONTAINER...]
```
`--attach` 或 `-a` 代表 Attach STDOUT/STDERR and forward signals.
更詳細的可參考 [https://docs.docker.com/engine/reference/commandline/start/](https://docs.docker.com/engine/reference/commandline/start/)
( container ID 寫幾個就可以了,和 Git 的概念是一樣的 ,
不了解 Git 可以參考 [Git-Tutorials GIT基本使用教學](https://github.com/twtrubiks/Git-Tutorials) )
停止 Container
```cmd
docker stop [OPTIONS] CONTAINER [CONTAINER...]
```
重新啟動 Container
```cmd
docker restart [OPTIONS] CONTAINER [CONTAINER...]
```
删除 Container
```cmd
docker rm [OPTIONS] CONTAINER [CONTAINER...]
```
`--volumes , -v` 加上這個參數,會移除掉連接到這個 container 的 volume。
可參考 [https://docs.docker.com/engine/reference/commandline/rm/](https://docs.docker.com/engine/reference/commandline/rm/)
進入 Container
```cmd
docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
docker exec -it <Container ID> bash
```
使用 root 使用者進入
```cmd
docker exec -u 0 -it <Container ID> bash
docker exec -u root -it <Container ID> bash
```
打指令比較潮,或是說你也可以透過 [Kitematic](https://kitematic.com/) 進入。
[](https://i.imgur.com/Yui1UZb.png)
當我們進入了 Container 之後,有時候想看一下裡面 Linux 的版本,
這時候可以使用以下指令查看
```cmd
cat /etc/os-release
```
查看 Container 詳細資料
```cmd
docker inspect [OPTIONS] NAME|ID [NAME|ID...]
```
查看 log
```cmd
docker logs [OPTIONS] CONTAINER
```
`--follow` , `-f` , Follow log output
更詳細的可參考 [https://docs.docker.com/engine/reference/commandline/logs/](https://docs.docker.com/engine/reference/commandline/logs/)
從最後 100 行開始追蹤,
```cmd
docker logs -f --tail 100 CONTAINER
```
顯示容器資源 ( CPU , I/O ...... )
```cmd
docker stats [OPTIONS] [CONTAINER...]
```
停止指定的 CONTAINER 中全部的 **processes**
```cmd
docker pause CONTAINER [CONTAINER...]
```
執行 `docker pause` 之後,可以試這用 `docker ps` 查看,會發現
還是有在執行,這裡拿 `docker stop` 比較一下,差異如下。
`docker stop` : process 級別。
`docker pause`: container 級別。
恢復指定暫停的 CONTAINER 中全部的 **processes**
```cmd
docker unpause CONTAINER [CONTAINER...]
```
docker tag
```cmd
docker tag SOURCE_IMAGE[:TAG] TARGET_IMAGE[:TAG]
```
範例
```cmd
docker tag 0e5574283393 twtrubiks/nginx:version1.0
```
更多可參考 [https://docs.docker.com/engine/reference/commandline/tag/](https://docs.docker.com/engine/reference/commandline/tag/)
儲存 (備份) image 成 tar 檔案
```cmd
[OPTIONS] IMAGE [IMAGE...]
```
範例
```cmd
docker save busybox > busybox.tar
```
或
```cmd
docker save --output busybox.tar busybox
```
或 ( 也可以一次備份多個 )
```cmd
docker save -o images.tar postgres:9.6 busybox
```
更多可參考 [https://docs.docker.com/engine/reference/commandline/save/](https://docs.docker.com/engine/reference/commandline/save/)
載入 image
```cmd
docker load [OPTIONS]
```
範例
```cmd
docker load < busybox.tar
```
或
```cmd
docker load -i busybox.tar
```
更多可參考 [https://docs.docker.com/engine/reference/commandline/load/](https://docs.docker.com/engine/reference/commandline/load/)
顯示 image 的 history,查詢 image 的每一層
```cmd
docker history [OPTIONS] IMAGE
```
在 docker 中,一層一層的概念很重要。

更多可參考 [https://docs.docker.com/engine/reference/commandline/history/](https://docs.docker.com/engine/reference/commandline/history/)
剛剛有教大家如何儲存 (備份) images, 載入 images,
還有另外一種是 export 和 import containers,
docker export container 請參考 [https://docs.docker.com/engine/reference/commandline/export/](https://docs.docker.com/engine/reference/commandline/export/)。
docker import container 請參考 [https://docs.docker.com/engine/reference/commandline/import/](https://docs.docker.com/engine/reference/commandline/import/)。
其他指令
刪除所有 dangling images
```cmd
docker image prune
```
移除全部 unused images (不只 dangling images)
```cmd
docker image prune -a
```
更多資訊可參考 [image_prune](https://docs.docker.com/engine/reference/commandline/image_prune/)
停止所有正在運行的 Container
```cmd
docker container stop $(docker ps -q)
```
更多資訊可參考 [container_stop](https://docs.docker.com/engine/reference/commandline/container_stop/)
移除全部停止的 containers
```cmd
docker container prune
```
更多資訊可參考 [container_prune](https://docs.docker.com/engine/reference/commandline/container_prune/)
### Volume
接下來要介紹 Volume,Volume 是 Docker 最推薦存放 persisting data( 數據 )的機制,
使用 Volume 有下列優點
* Volumes are easier to back up or migrate than bind mounts.
* You can manage volumes using Docker CLI commands or the Docker API.
* Volumes work on both Linux and Windows containers.
* Volumes can be more safely shared among multiple containers.
* Volume drivers allow you to store volumes on remote hosts or cloud providers, to encrypt the contents of volumes, or to add other functionality.
* A new volume's contents can be pre-populated by a container.
在 container 的可寫層中,使用 volume 是一個比較好的選擇,因為他不會增加 container 的容量,
volume 的內容存在於 container 之外。
也可參考下圖

更詳細的可參考 [https://docs.docker.com/engine/admin/volumes/volumes/](https://docs.docker.com/engine/admin/volumes/volumes/)
查看目前的 volume
```cmd
docker volume ls [OPTIONS]
```
創造一個 volume
```cmd
docker volume create [OPTIONS] [VOLUME]
```
刪除一個 volume
```cmd
docker volume rm [OPTIONS] VOLUME [VOLUME...]
```
查看 volume 詳細資料
```cmd
docker volume inspect [OPTIONS] VOLUME [VOLUME...]
```
移除全部未使用的 volume
```cmd
docker volume prune [OPTIONS]
```
### network
建議大家花點時間研究 docker 中的 network,會蠻有幫助的 :smiley:
查看目前 docker 的網路清單
```cmd
docker network ls [OPTIONS]
```
詳細可參考 [https://docs.docker.com/engine/userguide/networking/](https://docs.docker.com/engine/userguide/networking/)
docker 中的網路主要有三種 Bridge、Host、None,預設皆為 Bridge 模式。
指定 network 範例 ( 指定使用 `host` 網路 )
```cmd
docker run -it --name busybox --rm --network=host busybox
```
建立 network
```cmd
docker network create [OPTIONS] NETWORK
```
移除 network
```cmd
docker network rm NETWORK [NETWORK...]
```
移除全部未使用的 network
```cmd
docker network prune [OPTIONS]
```
查看 network 詳細資料
```cmd
docker network inspect [OPTIONS] NETWORK [NETWORK...]
```
將 container 連接 network
```cmd
docker network connect [OPTIONS] NETWORK CONTAINER
```
更多詳細資料可參考 [https://docs.docker.com/engine/reference/commandline/network_connect/](https://docs.docker.com/engine/reference/commandline/network_connect/)
Disconnect container network
```cmd
docker network disconnect [OPTIONS] NETWORK CONTAINER
```
更多詳細資料可參考 [https://docs.docker.com/engine/reference/commandline/network_disconnect/](https://docs.docker.com/engine/reference/commandline/network_disconnect/)
#### User-defined networks
這個方法是官方推薦的 :thumbsup:
透過內建的 DNS 伺服器,可以直接使用容器名稱,就可解析出 IP,不需要再使用 IP 讓容器互相
溝通,我們只需要知道容器的名稱就可以連接到容器。
更多詳細資料可參考 [https://docs.docker.com/engine/userguide/networking/#user-defined-networks](https://docs.docker.com/engine/userguide/networking/#user-defined-networks)
## docker-compose
再來要介紹 docker-compose,可參考官網 [https://docs.docker.com/compose/](https://docs.docker.com/compose/)

Compose 是定義和執行多 Container 管理的工具,不懂我在說什麼:question::question::question:
試著想想看,通常一個 Web 都還會有 DB,甚至可能還有 [Redis](https://redis.io/) 或 [Celery](http://www.celeryproject.org/),
所以說我們需要有 Compose 來管理這些,透過 `docker-compose.yml` ( YML 格式 ) 文件。
`docker-compose.yml` 的寫法可參考 [https://docs.docker.com/compose/compose-file/](https://docs.docker.com/compose/compose-file/)
也可以直接參考官網範例 [https://docs.docker.com/compose/compose-file/#compose-file-structure-and-examples](https://docs.docker.com/compose/compose-file/#compose-file-structure-and-examples)
Compose 的 Command-line 很多和 Docker 都是類似的,
可參考 [https://docs.docker.com/glossary/?term=compose](https://docs.docker.com/glossary/?term=compose)
查看目前 Container
```cmd
docker-compose ps
```
加上 `-q` 的話,只顯示 id
```cmd
docker-compose ps -q
```
啟動 Service 的 Container
```cmd
docker-compose start [SERVICE...]
```
停止 Service 的 Container ( 不會刪除 Container )
```cmd
docker-compose stop [options] [SERVICE...]
```
重啟 Service 的 Container
```cmd
docker-compose restart [options] [SERVICE...]
```
Builds, (re)creates, starts, and attaches to containers for a service
```cmd
docker-compose up [options] [--scale SERVICE=NUM...] [SERVICE...]
```
加個 `-d`,會在背景啟動,一般建議正式環境下使用。
```cmd
docker-compose up -d
```
`up` 這個功能很強大,建議可以參考 [https://docs.docker.com/compose/reference/up/](https://docs.docker.com/compose/reference/up/)
如果你希望每次都重新 build image,可以加上
`--build` ( Build images before starting containers. )
```cmd
docker-compose up -d --build
```
docker-compose down
```cmd
docker-compose down [options]
```
`down` 這個功能也建議可以參考 [https://docs.docker.com/compose/reference/down/](https://docs.docker.com/compose/reference/down/)
舉個例子
```cmd
docker-compose down -v
```
加個 `-v` 就會順便幫你把 volume 移除( 移除你在 `docker-compose.yml` 裡面設定的 volume )
在指定的 Service 中執行一個指令
```cmd
docker-compose run [options] [-v VOLUME...] [-p PORT...] [-e KEY=VAL...] SERVICE [COMMAND] [ARGS...]
[ARGS...]
```
舉個例子
```cmd
docker-compose run web bash
```
在 web Service 中執行 `bash` 指令
可參考 [https://docs.docker.com/compose/reference/run/](https://docs.docker.com/compose/reference/run/)
觀看 Service logs
```cmd
docker-compose logs [options] [SERVICE...]
```
檢查 `docker-compose.yml` 格式是否正確
```cmd
docker-compose config
```
如下指令,和 `docker exec` 一樣
```cmd
docker-compose exec
```
範例 ( 進入 web 這個 service 的 bash )
```cmd
docker-compose exec web bash
```
顯示被使用到的 container 中的 images 清單
```cmd
docker-compose images
```
移除 service containers
```cmd
docker-compose rm
```
Pushes images 到 docker hub
```cmd
docker-compose push
```
目前這個指令其實我也搞不太懂,可參考 [https://github.com/docker/compose/issues/4283](https://github.com/docker/compose/issues/4283)
官網也解釋的沒有很清楚 [https://docs.docker.com/compose/reference/push/](https://docs.docker.com/compose/reference/push/)
### docker-compose up/down 和 restart 的差異
* [Youtube Tutorial- docker-compose up/down 和 restart 的差異](https://youtu.be/nX-sbLPz-MU)
先來談 `docker-compose up/down`,
假如今天你修改了 `docker-compose.yml` 又或是更新了 image,
當你要重建 docker , 有幾種方法,
方法一.
先停止 container, 執行 `docker-compose down` 再執行 `docker-compose up`.
方法二.
不需要停止 container, 直接執行 `docker-compose up -d`.
(他會自動幫你重建, 很方便, 不需要多一步先關閉 container )
結論, 只要你的 `docker-compose.yml` 有任何變動, 一定要執行 `docker-compose up` 才會生效.
再來談 `docker-compose restart`,
請看官方文件 [docker-compose restart](https://docs.docker.com/compose/reference/restart/), 如果你對 `docker-compose.yml` 修改, 然後使用這個指令, 是**不會**生效的,
但是, 如果你是改 code (可能是 python code), 那這個指令是有效的.
### docker-compose networks
* [Youtube Tutorial - docker-compose networks 說明](https://youtu.be/wmV9WfkpyGk)
這邊多補充 docker-compose networks 的觀念,因為剛好最近有用到:smile:
```yml
version: '3.5'
services:
db:
container_name: 'postgres'
image: postgres
environment:
POSTGRES_PASSWORD: <PASSWORD>
ports:
- "5432:5432"
# (HOST:CONTAINER)
volumes:
- pgdata:/var/lib/postgresql/data/
networks:
- proxy
web:
build: ./api
command: python manage.py runserver 0.0.0.0:8000
restart: always
volumes:
- api_data:/docker_api
# (HOST:CONTAINER)
ports:
- "8000:8000"
# (HOST:CONTAINER)
depends_on:
- db
networks:
- proxy
volumes:
api_data:
pgdata:
networks:
proxy:
# external:
name: my_network
```
先把 version 改成 3.5,因為這版本才開始有 networks name 的概念,在
db 以及 web 中都加了 networks ( 自己定義的 ),定義的地方在最後面,
proxy 是名稱 ( 類似 volumes 的概念 ),`external` option 的意思代表
是不是要參考外部別人已經定義好的 network ( 所以如果找不到就會報錯 ),
但如果不加上 `external` option,也就代表是自己定義的,會幫你自動建立
你所定義的 network,名稱為 my_network。
如果你都完全沒有定義 networks,預設就是資料夾的名稱_default 。
### docker-compose ports 和 expose 差異
在 docker-compose 中有兩種方法可以暴露容器 ports,
分別是 ports 和 expose,
#### ports
```yml
...
ports:
- "5000:5000" # 绑定 container 中的 5000 port 到 本機(HOST) 的 5000 port
# (HOST:CONTAINER)
- "5001:5000" # 绑定 container 中的 5000 port 到 本機(HOST) 的 5001 port
- "5000" # 绑定 container 中的 5000 port 到本機的任意 port (本機會隨機被分配到一個 port)
...
```
隨機 port 範例,
這邊使用 dpage/pgadmin4 這個 images 來示範,
```cmd
docker run -p 80 \
-e "PGADMIN_DEFAULT_EMAIL=<EMAIL>" \
-e "PGADMIN_DEFAULT_PASSWORD=<PASSWORD>" \
-d dpage/pgadmin4
```
如果我們執行兩次以上指令,你會發現本機被分配到兩個隨機的 ports (如下圖),

本機被隨機分配到 32768 以及 32769 port,
這邊不管我們怎麼設定 ports,這些 ports 都會暴露給本機 (HOST) 以及其他 containers,這點很重要:exclamation::exclamation:
也就是說,如果本機 5001 ports 被使用了,其他的 containers 就無法使用 5001 ports,
可能要改成5002 ports 之類的。
#### expoese
```yml
...
expose:
- "4000"
- "6000"
...
```
expose 是將 port 暴露給其他容器。
expose 和 ports 最大的差別就是在 expose 不會暴露 port 給本機(HOST),
所以 本機(HOST)絕對無法被訪問,但 containers 內可以被訪問,
所以說如果今天你的容器想要在 本機(HOST) 被訪問,一定要使用 ports 方式。
***ports 和 expose 差異***
簡單說,就是 ports 可以被 本機(HOST) 和 containers 訪問 ; 而
expose 是本機(HOST) 無法被訪問,只有在 containers 中可以被訪問。
## Docker Registry

可以把它想成是一個類似 github 的地方,只不過裡面變成是存 docker 的東西,當然,
也可以自己架,但會有一些額外的成本,像是網路,維護等等,這部分就要自己衡量了:grinning:
接下來教大家如何將 image push 到 Docker Registry :smiley:
* [Youtube Tutorial PART 4 - Docker push image to Docker Hub 教學](https://youtu.be/dVBKwmqO5e4)
首先,先登入 [Docker Registry](https://hub.docker.com/) ( 註冊流程很簡單,我就跳過了 )
```cmd
docker login
```

舉個例子,先 run 一個 busybox 的容器
```cmd
docker run -it busybox
```
接著在裡面新增一筆資料
```cmd
echo 'text' > data.txt
```

然後打開另一個 terminal ,使用 `docker ps` 查看目前容器的 id

再來使用像 git 一樣的方式 commit
docker commit
```cmd
docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]
```
可參考 [https://docs.docker.com/engine/reference/commandline/commit/](https://docs.docker.com/engine/reference/commandline/commit/)
```cmd
docker commit -m "test" 4fb4ef51e917 twtrubiks/my_busybox
```
`-m` commit message ,和 git 一樣。
twtrubiks/my_busybox 則為我們定義的 REPOSITORY。
如果需要 tag , 也可以增加
```cmd
docker commit -m "test" 4fb4ef51e917 twtrubiks/my_busybox:v1
```
( 如果沒定義 tag , 則會顯示 latest )
這時候可以用 `docker images` 查看

最後 push
```cmd
docker push twtrubiks/my_busybox
```

docker 是一層一層的概念,他只會 push 自己新增的幾層上去而已,
所以不用擔心整個 image 很大,要上傳很久 :relaxed:
最後可以到 [https://hub.docker.com/](https://hub.docker.com/) 確認是否有成功 :smile:

## 用 Docker 實戰 Django 以及 Postgre
* [Youtube Tutorial PART 2 - 用 Docker 實戰 Django 以及 Postgre](https://youtu.be/aZ6woJ7qekE)
上面介紹了那麼多,來實戰一下是必須的 :satisfied:
我們使用 [Django-REST-framework 基本教學 - 從無到有 DRF-Beginners-Guide](https://github.com/twtrubiks/django-rest-framework-tutorial) 來當範例
有幾個地方必須修改一下,
將 `settings.py` 裡面的 db 連線改成 [PostgreSQL](https://www.postgresql.org/)
```pyhon
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'postgres',
'USER': 'postgres',
'PASSWORD': '<PASSWORD>',
'HOST': 'db',
'PORT': 5432,
}
}
```
建議也將 `ALLOWED_HOSTS = []` 改為 `ALLOWED_HOSTS = ['*']`
( 這只是方便,實務上不會這樣使用 )
再來是兩個很重要的檔案,分別為 `Dockerfile` 和 `docker-compose.yml`
`Dockerfile`
```text
FROM python:3.6.2
LABEL maintainer twtrubiks
ENV PYTHONUNBUFFERED 1
RUN mkdir /docker_api
WORKDIR /docker_api
COPY . /docker_api/
RUN pip install -r requirements.txt
```
詳細可參考 [https://docs.docker.com/engine/reference/builder/](https://docs.docker.com/engine/reference/builder/)
`docker-compose.yml`
```yml
version: '3'
services:
db:
container_name: 'postgres'
image: postgres
environment:
POSTGRES_PASSWORD: <PASSWORD>
ports:
- "5432:5432"
# (HOST:CONTAINER)
volumes:
- pgdata:/var/lib/postgresql/data/
web:
build: ./api
command: python manage.py runserver 0.0.0.0:8000
restart: always
volumes:
- api_data:/docker_api
# (HOST:CONTAINER)
ports:
- "8000:8000"
# (HOST:CONTAINER)
depends_on:
- db
volumes:
api_data:
pgdata:
```
詳細可參考 [https://docs.docker.com/compose/compose-file/#compose-file-structure-and-examples](https://docs.docker.com/compose/compose-file/#compose-file-structure-and-examples)
溫馨小提醒 1 :heart:
可能有人會問為什麼我是使用 `0.0.0.0`,而不是使用 `127.0.0.1`:question::question:
```cmd
python manage.py runserver 0.0.0.0:8000
```
`127.0.0.1`,並不代表真正的 **本機**,我們經常認為他是本機是因為我們電腦的 `host` 預設都幫你設定好了:smirk:
詳細的 `host` 設定教學可參考 [hosts-設定檔 以及 查詢內網 ip](https://github.com/twtrubiks/docker-django-nginx-uswgi-postgres-tutorial#hosts-設定檔-以及-查詢內網-ip),
`0.0.0.0` 才是真正的代表,**當下 ( 本 ) 網路中的本機** :pencil2:
如果大家想更深入的了解,可 google 再進一步的了解 `127.0.0.1` 以及 `0.0.0.0` 的差異 :smile:
溫馨小提醒 2 :heart:
這邊要特別提一下 `depends_on` 這個參數,
詳細可參考 [https://docs.docker.com/compose/compose-file/#depends_on](https://docs.docker.com/compose/compose-file/#depends_on),
上面連結中有一段說明很值得看
****depends_on does not wait for db and redis to be 「ready」 before starting web - only until they have been started. If you need to wait for a service to be ready, see Controlling startup order for more on this problem and strategies for solving it.****
以我的 [docker-compose.yml](https://github.com/twtrubiks/docker-tutorial/blob/master/docker-compose.yml) 為例,啟動順序雖然為 db -> web,**但他不會等待 db 啟動完成後才啟動 web**,
也就是說,還是有可能 **web 比 db 先啟動完成**,這樣就需要重啟 web service,否則會無法連上 db :sob:
如果真的要控制啟動順序,請參考 [Controlling startup order](https://docs.docker.com/compose/startup-order/)。
溫馨小提醒 3 :heart:
`docker-compose.yml` 其實使用 `docker run` 也是可以完成的,例如這個範例中,如果使用
`docker run` 來寫,會變成這樣。
首先,為了讓容器彼此可以溝通,我們先建立一個網路 ( User-defined networks ),
```cmd
docker network create my_network
```
db 容器
```cmd
docker run --name db -v pgdata:/var/lib/postgresql/data/ -p 5432:5432 --network=my_network -e POSTGRES_PASSWORD=<PASSWORD> postgres
```
接下來先去 api 資料夾中 build 出 image
```cmd
docker build --tag web_image .
```
`--tag , -t` , tag 這個 image 名稱為 web_image
也可以是
```cmd
docker build -t user/repo:tag .
```
web 容器
```cmd
docker run --name web -v api_data:/docker_api -p 8000:8000 --network=my_network --restart always web_image python manage.py runserver 0.0.0.0:8000
```
以上這樣,和 `docker-compose.yml` 其實是一樣的:open_mouth:
設定完了之後,接下來我們就可以啟動他了
```cmd
docker-compose up
```
接下來你會看到類似的畫面


假如你出現了類似的畫面

代表 database 還在建立的時候,你的 web ( Django ) 就去連接他,
所以導致連接不上,這時候我們可以先終止他 ( 按 Ctrl+C )
接著在重新 `docker-compose up`
我們成功啟動了 ( db 連線也正常 )

但你仔細看上圖,你會發現他說你還沒 migrate
接下來我們開啟另一個 cmd 進入 web 的 service,
透過剛剛介紹的指令進入 service
```cmd
docker ps
docker exec -it <Container ID> bash
```
或是說也可以從 [Kitematic](https://kitematic.com/) 進入,
進入後我們可以開始 migrate
```cmd
python manage.py makemigrations musics
python manage.py migrate
```

順便在建立一個 superuser
```cmd
python manage.py createsuperuser
```
接著我們可以試著使用 GUI 介紹連接 db,
因為我們是用 [PostgreSQL](https://www.postgresql.org/) ,可以透過 [pgadmin](https://www.pgadmin.org/) 連線

我們剛剛 migrate 的東西確實有存在

我們不需要再重新啟動
直接可以開開心心的去瀏覽 [http://127.0.0.1:8000/api/music/](http://127.0.0.1:8000/api/music/)
大家一定會看到很熟悉的畫面

接著依照自己剛剛設定的帳密登入進去即可


以上整個環境,都是在 Docker 中 :open_mouth:
如果我們再 Ctrl+C 退出,重新啟動一次 `docker-compose up`
這次就不會再和你說你沒有 migrate 了

## 其他管理 Docker GUI 的工具
* [Youtube Tutorial PART 3 - Docker 基本教學 - 透過 portainer 管理 Docker](https://youtu.be/VZjHmBcEcew)
除了 [Kitematic](https://kitematic.com/) 之外,還有其他不錯的推薦給大家,
這次要介紹的就是 [portainer](https://github.com/portainer/portainer) 功能強大又好用 :fire:
其實如果去看看 [Kitematic](https://github.com/docker/kitematic) 以及 [portainer](https://github.com/portainer/portainer) 的 github,
你會發現 [portainer](https://github.com/portainer/portainer) 感覺比較有在 maintenance :smile:
而且我使用了 [portainer](https://github.com/portainer/portainer) 之後,真心大推 :smiley:
安裝方法可參考 [https://portainer.io/install.html](https://portainer.io/install.html)
```cmd
docker volume create portainer_data
docker run --name=portainer -d -p 9000:9000 -v /var/run/docker.sock:/var/run/docker.sock -v portainer_data:/data portainer/portainer
```
`-d` `-p` 在前面的 `docker run` 有介紹過代表的含意,`--name` 只是命名而已。
`Note 1`: The -v /var/run/docker.sock:/var/run/docker.sock option is available on Linux environments only.
`Note 2`: The -v portainer_data:/data portainer/portainer option will persist Portainer data in portainer_data on the host where Portainer is running. You can specify another location on your filesystem.
( 建立起來之後,就依照 container 的操作即可 )
之後查看 [http://localhost:9000/](http://localhost:9000/) 就會看到下圖
然後設定帳號、密碼

選 Local or Remote

畫面真的不錯看,而且資訊也很豐富 :heart_eyes:

相信我,你使用完他之後,你會默默的邊緣化 [Kitematic](https://kitematic.com/) :smirk:
## 查看 port 佔用狀況
這個推薦給大家,有時候會遇到 port 被佔用,用指令查比較方便
Windows
查看所有 port 的佔用狀況
```cmd
netstat -ano
```
查看指定 port 的佔用狀況,例如現在想要查看 port 5432 佔用的狀況
```cmd
netstat -aon|findstr "5432"
```
查看 PID 對應的 process
```cmd
tasklist|findstr "2016"
```
停止 PID 為 6093 的 process
```cmd
taskkill /f /PID 6093
```
停止 vscode.exe process
```cmd
taskkill /f /t /im vscode.exe
```
MAC
將 port 為 8000 的 process 全部停止
```cmd
sudo lsof -t -i tcp:8000 | xargs kill -9
```
查看指定 port 的佔用狀況,例如現在想要查看 port 5432 佔用的狀況
```cmd
lsof -i tcp:5432
```
## 在 Linux 中自動啟動 docker
[在 Linux 中自動啟動 docker](https://github.com/twtrubiks/docker-tutorial/tree/master/docker-auto-run-linux)
## 如何清除 Docker container log
[Youtube Tutorial - 如何清除 Docker container log](https://youtu.be/SiG0tmwhqqg)
docker 的 container log 都會在 `/var/lib/docker/containers` 裡面
( 前提是你使用官方的安裝方法, [Youtube Tutorial-Ubuntu(Linux) 如何安裝 docker](https://youtu.be/eS_HMBC_RaA))
如果你是使用 `snap` 安裝 docker, 路徑則會在 `/var/snap/docker/common/var-lib-docker/containers`.

log 是一個 json 的檔案

如果你一直不去管他, log 就會越來越大:scream:
以下狀況這個 log 會被清除, 就是修改了 `docker-compose.yml` 或是
你執行了 `docker-compose down`, 這些 logs 都會被清除 (因為 containers 重新建立).
(`docker-compose stop` 不受影響, 因為只是暫停而已)
建立大家可參考 [docker-compose up/down 和 restart 的差異](https://github.com/twtrubiks/docker-tutorial#docker-compose-updown-%E5%92%8C-restart-%E7%9A%84%E5%B7%AE%E7%95%B0)
那你可能會問我, 如果我很長一段時間都不會修改 `docker-compose.yml` 以及執行
`docker-compose down` 該怎麼辦:sob: (因為 log 可能會長很快)
這邊提供大家一個方法, 使用 linux 中的 truncate 指令(可參考 [ Linux 指令教學 - truncate](https://github.com/twtrubiks/linux-note#truncate))
刪除全部 container 的 logs
```cmd
truncate -s 0 /var/lib/docker/containers/*/*-json.log
```
但是有時候只希望針對(清除)某個 container 的 logs, 這時候就可以使用以下的指令
```cmd
truncate -s 0 $(docker inspect --format='{{.LogPath}}' <container_name_or_id>)
```
(`container_name_or_id` 請換上自己 container 的 id 或 name)
其中的 `docker inspect --format='{{.LogPath}}' <container_name_or_id>` 只是顯示路徑而已.

## 後記:
Docker 算是我最近才開始接觸的,所以也算是新手,如果我有任何講錯的,歡迎和我說,我會再修改 :grinning:
Docker 可以玩的真的很多,延伸參考
* [實戰 Docker + Jenkins + Django + Postgres 📝](https://github.com/twtrubiks/docker-jenkins-django-tutorial) - 結合 Jenkins
* [Docker + Django + Nginx + uWSGI + Postgres 基本教學 - 從無到有](https://github.com/twtrubiks/docker-django-nginx-uwsgi-postgres-tutorial)
* [實戰 Docker + Django + Nginx + uWSGI + Postgres - Load Balance 📝](https://github.com/twtrubiks/docker-django-nginx-uwsgi-postgres-load-balance-tutorial)
也可以再玩玩 **Docker Swarm** ( 分散式系統 ) :satisfied:
* [Docker Swarm 基本教學 - 從無到有 Docker-Swarm-Beginners-Guide📝](https://github.com/twtrubiks/docker-swarm-tutorial)
最後,希望大家在學習 Docker 的過程中,遇到不懂的,可以去找資料並且了解他,
順便補足一些之前不足的知識。
## 執行環境
* Mac
* Python 3.6.2
* windows 10
## Reference
* [https://docs.docker.com/](https://docs.docker.com/)
* [portainer](https://github.com/portainer/portainer)
## Donation
文章都是我自己研究內化後原創,如果有幫助到您,也想鼓勵我的話,歡迎請我喝一杯咖啡:laughing:
綠界科技ECPAY ( 不需註冊會員 )

[贊助者付款](http://bit.ly/2F7Jrha)
歐付寶 ( 需註冊會員 )

[贊助者付款](https://payment.opay.tw/Broadcaster/Donate/9E47FDEF85ABE383A0F5FC6A218606F8)
## 贊助名單
[贊助名單](https://github.com/twtrubiks/Thank-you-for-donate)
## License
MIT license
<file_sep>/**
* Created by oudream on 2016/12/7.
*/
(function() {
'use strict';
if (typeof exports === 'object' && typeof global === 'object') {
global.cjs = global.cjs || {};
} else if (typeof window === 'object') {
window.cjs = window.cjs || {};
} else {
throw Error('cjs only run at node.js or web browser');
}
let CjFunction = cjs.CjFunction || {};
cjs.CjFunction = CjFunction;
if (typeof exports === 'object' && typeof global === 'object') {
exports = module.exports = CjFunction;
}
if (CjFunction.hasOwnProperty('getFunctionName')) return;
CjFunction.getFunctionName = function getFunctionName(fn) {
return fn && ( fn.name || this.toString().match(/function\s*([^(]*)\(/)[1] );
};
CjFunction.getFunctionObject = function getFunctionObject(fn, args) {
if (typeof fn !== 'function') {
return {
type: null,
name: '',
content: '',
argumentsLength: null,
arguments: null,
};
}
return {
type: typeof fn,
name: fn.name || '',
content: fn.toString(),
arguments: args,
};
};
CjFunction.getFunctionString = function getFunctionString(fn, args) {
return JSON.toString(CjFunction.getFunctionObject(fn, args));
};
})();
<file_sep>#!/usr/bin/env bash
docker build -t python3a .
docker run -d python3a<file_sep>/**
* Created by oudream on 2016/12/29.
*/
require('./../cjencoding');
let expect = require('./../../chai-4').expect;
describe('CjEncoding', function() {
it('base64Encode or base64Decode', function() {
let strOrig = 'Hello, world';
let strEncode = 'SGVsbG8sIHdvcmxk';
let strEncode2 = cjs.CjEncoding.base64Encode(strOrig);
let strOrig2 = cjs.CjEncoding.base64Decode(strEncode);
expect(strEncode).to.equal(strEncode2);
expect(strOrig).to.equal(strOrig2);
});
it('base64Encode to2 base64Decode', function() {
let strOrig = '123456789.;/abcdefgaquwerpozcxv地人为';
let strEncode2 = cjs.CjEncoding.base64Encode(strOrig);
let strOrig2 = cjs.CjEncoding.base64Decode(strEncode2);
expect(strOrig).to.equal(strOrig2);
});
});
<file_sep>FROM python:3.7.5-alpine3.10
ADD . /code
WORKDIR /code
RUN pip install Flask && \
chmod +x httpserver.py
ENTRYPOINT ["python", "httpserver.py"]<file_sep>FROM alpine
ARG ssh_pub_key
RUN apk update && \
apk upgrade
RUN apk add --no-cache openssh \
&& sed -i s/#PermitRootLogin.*/PermitRootLogin\ yes/ /etc/ssh/sshd_config \
&& echo "root:root" | chpasswd \
&& passwd -d root \
&& mkdir /root/.ssh \
&& chmod 755 /root/.ssh \
&& ssh-keygen -A \
&& touch /root/.ssh/authorized_keys \
&& chmod 644 /root/.ssh/authorized_keys \
&& echo "$ssh_pub_key" > /root/.ssh/authorized_keys
CMD exec /usr/sbin/sshd -D -e "$@"
#drwxr-xr-x 2 root root 4096 Oct 29 11:33 .ssh
<file_sep>#!/bin/bash
# Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
# This script will simply use sed to replace placeholder variables in the
# files in template/ with version-specific variants.
set -e
source ./VERSION
if grep -q Microsoft /proc/version; then
echo "Running on Windows Subsystem for Linux"
# WSL doesn't have its own docker host, we have to use the one
# from Windows itself.
# https://medium.com/@sebagomez/installing-the-docker-client-on-ubuntus-windows-subsystem-for-linux-612b392a44c4
export DOCKER_HOST=localhost:2375
shopt -s expand_aliases
alias inspec="cmd.exe /c C:/opscode/inspec/bin/inspec"
fi
ARCH=amd64; [ -n "$1" ] && ARCH=$1
MAJOR_VERSIONS=("${!MYSQL_SERVER_VERSIONS[@]}"); [ -n "$2" ] && MAJOR_VERSIONS=("${@:2}")
for MAJOR_VERSION in "${MAJOR_VERSIONS[@]}"; do
ARCH_SUFFIX=""
for MULTIARCH_VERSION in ${MULTIARCH_VERSIONS}; do
if [[ "$MULTIARCH_VERSION" == "$MAJOR_VERSION" ]]; then
ARCH_SUFFIX="-$ARCH"
fi
done
docker run -d --name mysql-server mysql/mysql-server:"$MAJOR_VERSION$ARCH_SUFFIX"
inspec exec "$MAJOR_VERSION/inspec/control.rb" --controls container
inspec exec "$MAJOR_VERSION/inspec/control.rb" -t docker://mysql-server --controls server-package
if [ "${MAJOR_VERSION}" == "5.7" ] || [ "${MAJOR_VERSION}" == "8.0" ]; then
inspec exec "$MAJOR_VERSION/inspec/control.rb" -t docker://mysql-server --controls shell-package
fi
docker stop mysql-server
docker rm mysql-server
done
<file_sep>(function() {
'use strict';
if (typeof exports === 'object' && typeof global === 'object') {
global.cjs = global.cjs || {};
} else {
throw Error('cjs only run at node.js or web browser');
}
let CjLog = cjs.CjLog || {};
cjs.CjLog = CjLog;
if (typeof exports === 'object' && typeof global === 'object') {
exports = module.exports = CjLog;
}
if (CjLog.hasOwnProperty('log')) return;
let fs = require('fs');
let path = require('path');
let CjInterinfo = require('./cjinterinfo_lang.js');
// CjLog._defaultLogPath = path.join(process.cwd(), 'log');
CjLog._defaultLogPath = path.normalize(path.join(__dirname, '../../../log'));
CjLog.setDefaultLogPath = function(sLogPath) {
CjLog._defaultLogPath = sLogPath;
};
CjLog.defaultDateString = function(dt) {
let dt2 = dt instanceof Date ? dt : new Date();
let D = ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09'];
return [dt2.getFullYear(), D[dt2.getMonth() + 1] || dt2.getMonth() + 1, D[dt2.getDate()] || dt2.getDate()].join('-');
};
CjLog.mkdirsSync = function(dirname) {
if (fs.existsSync(dirname)) {
return true;
} else {
if (CjLog.mkdirsSync(path.dirname(dirname))) {
fs.mkdirSync(dirname, 0o777);
return true;
}
}
};
function CjModule(sModule) {
this.module = sModule;
this.logPath = path.join(CjLog._defaultLogPath, sModule);
CjLog.mkdirsSync(this.logPath);
this.logFileCreateTime = new Date();
this.currentLogFilePath = '';
this.currentWriteStream = null;
this.updateLog = function() {
let sLogFilePath = path.join(this.logPath, CjLog.defaultDateString() + '.json');
if (this.currentLogFilePath === sLogFilePath) return;
try {
if (this.currentWriteStream) {
let writeStream = this.currentWriteStream;
this.currentWriteStream = null;
writeStream.end();
}
this.currentWriteStream = fs.createWriteStream(sLogFilePath, {
flags: 'a+',
defaultEncoding: 'utf8',
fd: null,
mode: 0o666,
autoClose: false,
});
this.currentWriteStream.write('\r\n\r\n\r\n' + JSON.stringify({
logStartTime: new Date(),
}) + '\r\n');
this.currentLogFilePath = sLogFilePath;
this.logFileCreateTime = new Date();
} catch (e) {
console.error('CjLog Error!!!');
console.error(e);
}
};
this.updateLog();
}
CjModule.prototype.log = function(sInfo) {
if (this.logFileCreateTime.getDate() !== (new Date()).getDate()) {
this.updateLog();
}
this.currentWriteStream.write(sInfo);
};
CjLog._modules = [];
CjLog.findModule = function(sModule) {
for (let i = 0; i < CjLog._modules.length; i++) {
let module = CjLog._modules[i];
if (module.module === sModule) {
return module;
}
}
return null;
};
CjLog.registerModule = function(sModule) {
if (typeof sModule !== 'string' && !(sModule instanceof String)) {
return false;
}
if (CjLog.findModule(sModule) === null) {
let module = new CjModule(sModule);
CjLog._modules.push(module);
CjLog[sModule] = module;
}
};
CjLog.defaultModule = new CjModule('default');
CjLog.registerModule(CjLog.defaultModule);
// log out
function CjOutputLog() {
CjInterinfo.OutPutI.call(this);
let self = this;
this.output = function() {
let module = CjLog.findModule(self.infoParam.module);
if (module !== null) {
module.log(self.getInfoParamString() + '\r\n');
module.log(JSON.stringify(arguments) + '\r\n');
} else {
CjLog.defaultModule.log(self.getInfoParamString() + '\r\n');
CjLog.defaultModule.log(JSON.stringify(arguments) + '\r\n');
}
};
}
CjInterinfo.registerRegisterModule(CjLog.registerModule);
CjInterinfo.registerOutput(CjOutputLog);
CjInterinfo.Module.prototype.log = function() {
let output = new CjOutputLog();
output.infoParam.module = this.module;
output.infoParam.level = CjInterinfo.LevelInfo;
output.output(...arguments);
};
CjInterinfo.Module.prototype.logDebug = function() {
let output = new CjOutputLog();
output.infoParam.module = this.module;
output.infoParam.level = CjInterinfo.LevelDebug;
output.output(...arguments);
};
CjInterinfo.Module.prototype.logInfo = function() {
let output = new CjOutputLog();
output.infoParam.module = this.module;
output.infoParam.level = CjInterinfo.LevelInfo;
output.output(...arguments);
};
CjInterinfo.Module.prototype.logWarn = function() {
let output = new CjOutputLog();
output.infoParam.module = this.module;
output.infoParam.level = CjInterinfo.LevelWarn;
output.output(...arguments);
};
CjInterinfo.Module.prototype.logError = function() {
let output = new CjOutputLog();
output.infoParam.module = this.module;
output.infoParam.level = CjInterinfo.LevelError;
output.output(...arguments);
};
cjs.log = CjLog.log = function() {
let output = new CjOutputLog();
output.infoParam.level = CjInterinfo.LevelInfo;
output.output(...arguments);
};
cjs.logDebug = CjLog.logDebug = function() {
let output = new CjOutputLog();
output.infoParam.level = CjInterinfo.LevelDebug;
output.output(...arguments);
};
cjs.logInfo = CjLog.logInfo = function() {
let output = new CjOutputLog();
output.infoParam.level = CjInterinfo.LevelInfo;
output.output(...arguments);
};
cjs.logWarn = CjLog.logWarn = function() {
let output = new CjOutputLog();
output.infoParam.level = CjInterinfo.LevelWarn;
output.output(...arguments);
};
cjs.logError = CjLog.logError = function() {
let output = new CjOutputLog();
output.infoParam.level = CjInterinfo.LevelError;
output.output(...arguments);
};
})();
<file_sep>(function() {
'use strict';
window.gcl = window.gcl || {};
window.gcl.gis = window.gcl.gis || {};
let gis = window.gcl.gis;
let Computer = {
merge(){
},
split() {
},
};
gis.computer = Computer;
return Computer;
})();
<file_sep>FROM alpine:3.9
LABEL maintainer "<NAME> - https://github.com/sickp"
ENTRYPOINT ["/entrypoint.sh"]
EXPOSE 22
COPY rootfs /
RUN apk add --no-cache openssh \
&& sed -i s/#PermitRootLogin.*/PermitRootLogin\ yes/ /etc/ssh/sshd_config \
&& echo "root:root" | chpasswd
RUN passwd -d root
COPY identity.pub /root/.ssh/authorized_keys
<file_sep>#!/usr/bin/env bash
GCL3_MYSQL_PASSWORD=<PASSWORD>
cd /opt/limi/hello-docker
git pull origin master
sed -i "s/123456/${GCL3_MYSQL_PASSWORD}/g" ./projects/gcl3/master/master.json
# build
node ./projects/gcl3/master/main-build.js
# cp
# rm -r ./projects/gcl3/master/dist
# mkdir ./projects/gcl3/master/dist
# cp ./projects/gcl3/master/dist/index.html ./projects/gcl3/master/index.html
# cp -r ./projects/gcl3/master/dist/static ./projects/gcl3/master/dist/
# run
node ./projects/gcl3/master/main-run.js
### ----------------------------------------------------------------------------------------------
### install node
sudo apt update
sudo apt install nodejs
# or 或者
NODE_VERSION=v12.16.0
NODE_DISTRO=linux-x64
wget https://nodejs.org/dist/${NODE_VERSION}/node-${NODE_VERSION}-linux-x64.tar.xz
sudo mkdir -p /usr/local/lib/nodejs
sudo tar -xJvf node-${NODE_VERSION}-${NODE_DISTRO}.tar.xz -C /usr/local/lib/nodejs
sed -i "$ a export PATH=/usr/local/lib/nodejs/node-${NODE_VERSION}-${NODE_DISTRO}/bin:"'$PATH' ~/.profile
### install mysql-server
sudo apt update
sudo apt install mysql-server
### git clone
git clone https://github.com/oudream/hello-docker.git
sed -i "s/123456/${GCL3_MYSQL_PASSWORD}/g" ./projects/gcl3/master/master.json
sed -i "s/db1/db2/g" ./projects/gcl3/master/master.json
# note note note
npm i sqlite3 node-sass --unsafe-perm
npm i
### mysql password.sh
# create table
node ./projects/gcl3/master/main-db-init.js
# debug
node ./projects/gcl3/master/main-debug.js
# open browser
open http://localhost:2292
# open http://localhost:2292/hello-docker/projects/gcl3/master/dist
# upload
cd /opt/limi/hello-docker/hello/nginx/upload1
sFp1=$PWD/readme.md
curl -F "file=@${sFp1};type=text/plain;filename=a1" 172.16.31.10:2232/upload
# backup
# mysql
# # mysql>
# create database db1;
# INSERT INTO `user`(`id`, `name`, `password`) VALUES ('1','<PASSWORD>','<PASSWORD>');
# exit
#
# INSERT INTO `db1`.`bureau`(`id`, `name`, `phone`, `email`, `addr`, `remark`) VALUES (3, '香洲局', '88843121', NULL, '人民西路XXX 号,香洲局', NULL);
# INSERT INTO `db1`.`bureau`(`id`, `name`, `phone`, `email`, `addr`, `remark`) VALUES (4, '唐家局', '8884322', '<EMAIL>', '人民西路XXX号,2', '备注的枯要,备注备注');
# INSERT INTO `db1`.`bureau`(`id`, `name`, `phone`, `email`, `addr`, `remark`) VALUES (5, '金湾局', '8884323', '<EMAIL>', '人民西路3号', NULL);
# INSERT INTO `db1`.`bureau`(`id`, `name`, `phone`, `email`, `addr`, `remark`) VALUES (6, '斗门局', '8884324', '<EMAIL>', '人民西路4号', NULL);
# INSERT INTO `db1`.`bureau`(`id`, `name`, `phone`, `email`, `addr`, `remark`) VALUES (7, '金鼎局', '8884325', '<EMAIL>', '保可可国国是是另国', '村沙发舒服');
<file_sep>#!/usr/bin/env bash
# Basic container for X11 forwarding goodness
# https://gist.github.com/udkyo/c20935c7577c71d634f0090ef6fa8393
# 1 : at vps
docker build -t firefox .
# 2 : at vps
docker run -it --rm -p 2201:22 firefox
# 3 : at pc [ local ]
ssh -AXY -p 2201 root@${vps_ip}
### readme
To get up and running, build it, then:
docker run -it --rm -p 2150:22 firefox
Add this to ~/.ssh/config on the client
Host abc
Hostname HOST_NAME_HERE
Port 2201
user root
ForwardX11 yes
ForwardX11Trusted yes
Connect from client with:
ssh -X root@abc firefox
docker build -t firefox .
docker run -it --rm -p 2201:22 $ImageId
#docker run -it --rm -p 2201:22 firefox
docker run -d x11a
docker exec -e DISPLAY=$DISPLAY -it 05201d90750e /bin/sh
### Dockerfile use password
### --- begin --- :
FROM ubuntu
RUN apt update \
&& apt install -y firefox \
openssh-server \
xauth \
x11-apps \
&& mkdir /var/run/sshd \
&& mkdir /root/.ssh \
&& chmod 700 /root/.ssh \
&& ssh-keygen -A \
&& sed -i "s/^.*PasswordAuthentication.*$/PasswordAuthentication yes/" /etc/ssh/sshd_config \
&& sed -i "s/^.*PermitEmptyPasswords.*$/PermitEmptyPasswords yes/" /etc/ssh/sshd_config \
&& sed -i "s/^.*PermitRootLogin.*$/PasswordAuthentication yes/" /etc/ssh/sshd_config \
&& sed -i "s/^.*X11Forwarding.*$/X11Forwarding yes/" /etc/ssh/sshd_config \
&& sed -i "s/^.*X11UseLocalhost.*$/X11UseLocalhost no/" /etc/ssh/sshd_config \
&& grep "^X11UseLocalhost" /etc/ssh/sshd_config || echo "X11UseLocalhost no" >> /etc/ssh/sshd_config
### --- notice notice notice ---
#RUN echo "YOUR_PUB_KEY_HERE" >> /root/.ssh/authorized_keys
#RUN echo "ssh-rsa <KEY> oudream@bogon" >> /root/.ssh/authorized_keys
ENTRYPOINT ["sh", "-c", "/usr/sbin/sshd && tail -f /dev/null"]
### --- end --- .
<file_sep>let _timeOutIsList = true;
setInterval(()=>{
if (_timeOutIsList) {
console.log('fnListContainers');
} else {
console.log('fnValidator');
}
_timeOutIsList = !_timeOutIsList;
}, 3000);
<file_sep>'use strict';
exports = module.exports = CjDbMysql;
let mysql = require('mysql');
/**
* Class CjDbMysql
* @constructor
* @param option = {
connectionLimit: 10,
host: 'localhost',
user: 'root',
password: '<PASSWORD>',
database: 'db1',
}
*/
function CjDbMysql(option) {
this._option = {
connectionLimit: option.connectionLimit ? option.connectionLimit : 10,
host: option.host ? option.host : 'localhost',
user: option.user ? option.user : 'root',
password: option.password ? option.password : '<PASSWORD>',
database: option.database ? option.database : 'db1',
};
this._pool = mysql.createPool(this._option);
}
CjDbMysql.prototype.close = function close() {
this._pool.end();
this._pool = null;
};
CjDbMysql.prototype.getOption = function getOption() {
return this._option;
};
CjDbMysql.prototype.isOpen = function isOpen() {
return this._pool !== null;
};
/**
* CjDbMysql.prototype.query
* @param {String} sql
* @param {function} callback
*/
CjDbMysql.prototype.query = function query(sql, callback) {
this._pool.getConnection(function(err, connection) {
if (err) {
console.log('CjDbMysql-query: ', err);
callback(err);
return;
}
// let sql = 'SELECT id,name FROM users';
connection.query(sql, [], function(err, values, fields) {
connection.release(); // always put connection back in pool after last query
if (err) {
console.log('CjDbMysql-query: ', err);
callback(err);
return;
}
callback(false, values, fields);
});
});
};
/**
* CjDbMysql.prototype.queryPromise
* @param {CjDbMysql} dbMysql
* @param {String} sql
* @param {Array} values
* @return {Array}
*/
CjDbMysql.prototype.queryPromise = function(sql, values) {
return new Promise((resolve, reject) => {
this._pool.getConnection(function(err, connection) {
if (err) {
reject(err);
} else {
connection.query(sql, values, (err, rows) => {
if (err) {
reject(err);
} else {
resolve(rows);
}
connection.release();
});
}
});
});
};
<file_sep>FROM ubuntu
RUN apt update \
&& apt install -y firefox \
openssh-server \
xauth \
&& mkdir /var/run/sshd \
&& mkdir /root/.ssh \
&& chmod 700 /root/.ssh \
&& ssh-keygen -A \
&& sed -i "s/^.*PasswordAuthentication.*$/PasswordAuthentication no/" /etc/ssh/sshd_config \
&& sed -i "s/^.*X11Forwarding.*$/X11Forwarding yes/" /etc/ssh/sshd_config \
&& sed -i "s/^.*X11UseLocalhost.*$/X11UseLocalhost no/" /etc/ssh/sshd_config \
&& grep "^X11UseLocalhost" /etc/ssh/sshd_config || echo "X11UseLocalhost no" >> /etc/ssh/sshd_config
### --- notice notice notice ---
#RUN echo "YOUR_PUB_KEY_HERE" >> /root/.ssh/authorized_keys
#
RUN echo "ssh-rsa A<KEY>TwCX7WySPsMt9hibLlQ6le8ffeU7 oudream@bogon" >> /root/.ssh/authorized_keys
ENTRYPOINT ["sh", "-c", "/usr/sbin/sshd && tail -f /dev/null"]
<file_sep>This CSS & JS library uses Bootstrap 4 + FontAwesome 5 to create a simple admin template with a collapsing & responsive sidebar.
# Usage
Include `bsadmin.css` & `bsadmin.js` in your code, and see the example below.
**Make sure to include all other dependencies shown in the example.**
# Example

```
<!doctype html>
<html lang="en">
<head>
<title>Hello, world!</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/fontawesome.min.css">
<link rel="stylesheet" href="css/bsadmin.css">
</head>
<body>
<nav class="navbar navbar-expand navbar-dark bg-primary">
<a class="sidebar-toggle text-light mr-3"><i class="fa fa-bars"></i></a>
<a class="navbar-brand" href="#"><i class="fa fa-code-branch"></i> Navbar</a>
<div class="navbar-collapse collapse">
<ul class="navbar-nav ml-auto">
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown">
<i class="fa fa-user"></i> Username
</a>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another</a>
</div>
</li>
</ul>
</div>
</nav>
<div class="d-flex align-items-stretch">
<div class="sidebar bg-dark">
<ul class="list-unstyled">
<li><a href="#"><i class="fa fa-fw fa-link"></i> Sidebar Link</a></li>
<li><a href="#"><i class="fa fa-fw fa-link"></i> Sidebar Link</a></li>
<li>
<a href="#submenu1" data-toggle="collapse"><i class="fa fa-fw fa-address-card"></i> Dropdown Link</a>
<ul id="submenu1" class="list-unstyled collapse">
<li><a href="#">Submenu Item</a></li>
<li><a href="#">Submenu Item</a></li>
<li><a href="#">Submenu Item</a></li>
</ul>
</li>
<li>
<a href="#submenu2" data-toggle="collapse"><i class="fa fa-fw fa-address-card"></i> Dropdown Link 2</a>
<ul id="submenu2" class="list-unstyled collapse">
<li><a href="#">Submenu Item</a></li>
<li><a href="#">Submenu Item</a></li>
<li><a href="#">Submenu Item</a></li>
</ul>
</li>
<li><a href="#"><i class="fa fa-fw fa-angle-right"></i> Sidebar Link</a></li>
<li><a href="#"><i class="fa fa-fw fa-link"></i> Sidebar Link</a></li>
</ul>
</div>
<div class="content p-4">
<h1 class="display-5 mb-4">Hello, world!</h1>
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean
ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt
condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat.
Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus</p>
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean
ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt
condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat.
Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus</p>
</div>
</div>
<script src="js/jquery.min.js"></script>
<script src="js/popper.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/bsadmin.js"></script>
</body>
</html>
```
<file_sep>/*!
// GCL实时点的历史实时数据请求的 json格式:支持散列请求:rtlog_v101;数组请求是:rtlog_v102;返回时都统一用:rtlog_v001
// url 是全局统一资源名(可以通用在容器对象或实体对象中)
// mid 是实时库的实时点全局唯一id
// url和mid可以只有一个,两个同时都有时以mid为准
// http://10.31.0.15:8821/ics.cgi?fncode=req.rtlog_v101&filetype=json
// 散列请求:rtlog_v101
fncode = req.rtlog_v101
filetype = json
{
"session":"sbid=0001;xxx=adfadsf",
"structtype": "rtlog_v101",
"params":
[
{
"url": "/fp/zyj/fgj01/rfid",
"mid": 33556644,
"dtday": "20180329",
"dtbegin": 31343242341,
"dtend": 23413241234
},
{
"url": "/fp/zyj/fgj01/ypmm",
"mid": 33556645,
"dtday": "20180329",
"dtbegin": 31343242341,
"dtend": 23413241234
}
]
}
// ics.json返回时都统一用:rtlog_v001
// "v": 数值;数组形式
// "q": 值的质量;数组形式
// "t": 值的时间,unix时间戳(1970到目前的毫秒数,服务器的当地时间);数组形式
// "s": 实时数据信息来源的源ID,ChangedSourceId;数组形式
// "u": 实时数据信息来源的源url,ChangedSourceId;数组形式
// "r": ChangedReasonId;数组形式
// 可选属性"state":状态码,无或0时表示成功,其它值看具体数据字典
{
"session":"sbid=0001;xxx=adfadsf",
"structtype":"rtdata_v001",
"data":[
{
"url":"/fp/zyj/fgj01/rfid",
"mid":33556644,
"dtday": "20180329",
"dtbegin": 31343242341,
"dtend": 23413241234,
"log": "#logfile.text",
"state":0
},
{
"url":"/fp/zyj/fgj01/ypmm",
"mid":33556645,
"dtday": "20180329",
"dtbegin": 31343242341,
"dtend": 23413241234,
"log": "#logfile.text",
"state":0
}
]
}
*/
(function () {
if (window.gclRtLog) {
return;
}
window.gclRtLog = function () {
var gis = {};
function fn_outInfo(s) {
var svgOutInfo = d3.select("text[id=sys-send-time]");
svgOutInfo.text(Date() + " " + r);
}
function getReqMeasureStringXML() {
var CS_req_measure_head =
'<?xml version="1.0" encoding="utf-8"?>' +
'<YGCT>' +
'<HEAD>' +
'<VERSION>1.0</VERSION>' +
'<SRC>1200000003</SRC>' +
'<DES>1200000003</DES>' +
'<MsgNo>9991</MsgNo>' +
'<MsgId>91d9e512-3695-4796-b063-306544be6f1f</MsgId>' +
'<MsgRef/>' +
'<TransDate>20151215094317</TransDate>' +
'<Reserve/>' +
'</HEAD>' +
'<MSG>'
;
var CS_req_measure_body =
'<RealData9991>' +
'<ADDRESSES>%1</ADDRESSES>' +
'</RealData9991>'
;
var CS_req_measure_foot =
'</MSG>' +
'</YGCT>'
;
var sMids = "";
var svgMid = d3.select("svg").selectAll("[id]");
svgMid.each(function (d, i) {
var name = this.id;
var index = name.indexOf("mid-");
if (index >= 0) {
sMids += name.substring(index + 4) + ",";
}
});
if (sMids.length > 0) {
CS_req_measure_body = CS_req_measure_body.replace(/%1/, sMids);
return CS_req_measure_head + CS_req_measure_body + CS_req_measure_foot;
}
return "";
}
var timeOut1000 = window.setTimeout("gclRtLog.timeOut()", 1000);
gis.timeOut = function () {
req_resp_measures();
timeOut1000 = window.setTimeout("gclRtLog.timeOut()", 1000);
}
var req_resp_measures = function () {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var username = document.getElementById("txt_username").value;
var age = document.getElementById("txt_age").value;
xmlhttp.open("post", "ics.cgi?username=" + username
+ "&age=" + age, true);
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var svgOutInfo = d3.select("text[id=sys-recved-time]");
svgOutInfo.text("接收:" + Date() + " " + xmlhttp.response.length);
var doc = (new DOMParser()).parseFromString(xmlhttp.response, "text/xml");
var x = doc.documentElement.getElementsByTagName("RealData9999");
for (var i = 0; i < x.length; i++) {
try {
var xx1 = x[i].getElementsByTagName("ADDRESS");
var sMid = xx1[0].textContent;
var iMid = Number(sMid);
var xx2 = x[i].getElementsByTagName("VALUE");
var sValue = xx2[0].textContent;
var svgMeasure = d3.select("[id=mid-" + sMid + "]");
if (iMid >= 0x01000000 && iMid < 0x02000000) {
var iState = Number(sValue);
if (iMid == 16777231 || iMid == 16777235) {
var iX = 0 + (iState % 1000);
var iY = 0 + (iState % 10);
if (iMid == 16777235) {
iX = 0 + (iState % 10);
iY = 0 + (iState % 600);
}
var lable = d3.select("[id=outInfoEd]");
var sTransform = "translate(" + iX + "," + iY + ")";
if (iMid == 16777231) {
sTransform += " rotate(90 110,700) "
}
lable.text("transform=" + sTransform);
svgMeasure.attr("transform", sTransform);
// var svg_1 = d3.select("[id=mid-16777235]");
// svg_1.attr("transform", "translate("+(count*10)+","+(480+count%10)+")");
continue;
}
var iRemain = iState % 3;
if (iRemain == 0)
svgMeasure.attr("fill", "#ff0000");
else if (iRemain == 1)
svgMeasure.attr("fill", "#00ff00");
else
svgMeasure.attr("fill", "#0000ff");
}
else if (iMid >= 0x02000000 && iMid < 0x03000000) {
svgMeasure.text(sValue);
}
else if (iMid >= 0x03000000 && iMid < 0x04000000) {
svgMeasure.text(sValue);
}
}
catch (er) {
var body = d3.selectAll("body");
var lable = body.append("lable");
lable.text("接收到实时数据,但解释异常:" + er.message);
}
}
}
}
var reqMeasureXml = getReqMeasureStringXML();
var r = xmlhttp.send(reqMeasureXml);
var svgOutInfo = d3.select("text[id=sys-send-time]");
svgOutInfo.text("发送:" + Date() + " " + r);
// return {"r":r,"datetime":Date()}
}
return gis;
}();
})(typeof window !== "undefined" ? window : this);
<file_sep>let fs = require('fs');
let Docker = require('dockerode');
const ProcessStateEnum = Object.freeze({
"none": 0,
"listingConfig": 1,
"listedConfig": 2,
"listingMemory1": 3,
"listedMemory1": 4,
"listingValidator": 5,
"listingMemory2": 6,
"listedMemory2": 7,
"listedValidator": 8,
"end": 9
});
/**
* DockerServer
* @constructor
*/
let DockerServer = function() {
let socket = process.env.DOCKER_SOCKET || '/var/run/docker.sock';
let stats = fs.statSync(socket);
if (!stats.isSocket()) {
throw new Error('Are you sure the docker is running?');
}
this.docker = new Docker({
socketPath: '/var/run/docker.sock',
// timeout: 100
});
// you may specify a timeout (in ms) for all operations, allowing to make sure you don't fall into limbo if something happens in docker
// this.docker = new Docker({host: 'http://127.0.0.1', port: 2375, timeout: 100});
this.configContainers = [];
/**
[
{
Id: '9debfec99555264a992a9a9aaf658a9c3d897da667ffc0f90671fc987a695daa',
Names: [ '/brave_mccarthy' ],
Image: 'alpine',
ImageID: 'sha256:cc0abc535e36a7ede71978ba2bbd8159b8a5420b91f2fbc520cdf5f673640a34',
Command: "/bin/sh -c 'while sleep 2;do printf aaabbbccc134\\\n; done;'",
Created: 1580450783,
Ports: [],
Labels: { Name: 'gcl3-7', Project: 'gcl3' },
State: 'running',
Status: 'Up About an hour',
HostConfig: { NetworkMode: 'default' },
NetworkSettings: { Networks: [Object] },
Mounts: []
}
]
*/
this.memoryContainers = [];
this.beAddedContainers = [];
this.beDeletedContainers = [];
this.processState = ProcessStateEnum.none;
this.processStateTime = Date.now();
this.eventQueue = [];
this.timeOutCount = 0;
};
/**
* check the Containers is same
* @param containers1
* @param containers2
* @returns {boolean}
*/
DockerServer.checkSameContainers = function(containers1, containers2) {
if (containers1.length === containers2.length) {
for (let i = 0; i < containers2.length; i++) {
let container = containers2[i];
if (containers1.findIndex((c) => c.Id === container.Id) < 0) {
return false;
}
}
return true;
}
return false;
};
/**
* get BureauId from Container'info
* @param container
* @returns {string}
*/
DockerServer.getContainerBureauId = function(container) {
let sName = container.Labels.Name;
return sName.substring(sName.lastIndexOf('-') + 1);
};
/**
* ls container's config(container's count = bureau's count) from db
*/
DockerServer.prototype.lsConfigContainers = function() {
if (this.db) {
this.setProcessState(ProcessStateEnum.listingConfig);
this.db.query('select * from bureau', (err, values, fields) => {
if (!err) {
if (Array.isArray(values) && values.length > 0) {
let containers = [];
for (let i = 0; i < values.length; i++) {
let row = values[i];
let id = row['id'];
if (id >= 0) {
let c = {
"Id": id,
"Name": 'gcl3-' + id,
"Row": row,
};
containers.push(c);
}
}
this.configContainers = containers;
}
else {
this.configContainers = [];
console.log('DockerServer lsConfigContainers - result is null!');
}
this.setProcessState(ProcessStateEnum.listedConfig);
this.lsMemoryContainers1();
}
});
}
else {
console.log('DockerServer lsConfigContainers - system error ( db is null )!');
}
};
DockerServer.prototype.lsMemoryContainers1 = function() {
let self = this;
self.setProcessState(ProcessStateEnum.listingMemory1);
self.docker.listContainers(
{
filters: {
"label": [
"Project=gcl3",
]
}
},
(err, containers) => {
if (err) {
console.log('DockerServer lsMemoryContainers1: ', err);
}
let newContainers = [];
if (Array.isArray(containers)) {
newContainers = containers;
}
if (!DockerServer.checkSameContainers(self.memoryContainers, newContainers)) {
console.log('DockerServer lsMemoryContainers1: ', self.memoryContainers);
}
else {
console.log('DockerServer lsMemoryContainers1 same to up. - '+Date.now());
}
self.memoryContainers = newContainers;
self.setProcessState(ProcessStateEnum.listedMemory1);
self.validator();
}
);
};
/**
* run image to container on docker
* docker run -d --rm alpine /bin/sh -c "while sleep 2;do printf aaabbbccc134\\n; done;
* @param config
*/
DockerServer.prototype.run = function(config) {
let self = this;
let beAddedContainer = self.beAddedContainers.find((c => c.Name === config.Name));
if (beAddedContainer) {
// for repeat add
if (Date.now() - beAddedContainer.sendTime < 10000) {
console.log('DockerServer: run ( for repeat add ), so do not run!');
return;
}
}
else {
beAddedContainer = {
Name: config.Name
};
this.beAddedContainers.push(beAddedContainer);
}
beAddedContainer.sendTime = Date.now();
/*
self.docker.run('alpine', [], undefined, {
"Cmd": [
"/bin/sh",
"-c",
"while sleep 2;do printf aaabbbccc134\\\n; done;"
],
"Image": "alpine",
"Labels": {
"Project": "gcl3",
"Name": config.Name
},
"HostConfig": {
"AutoRemove": true,
},
}, (err, data, container) => {
*/
// docker run -p 2231:22 -p 2232:8821 -d --restart=always oudream/gcl3-bus-alpine:1.0.2
let hostPort22 = 2231 + config.Id * 4;
let hostPort21 = 2232 + config.Id * 4;
self.docker.run('oudream/gcl3-bus-alpine:1.0.2', [], undefined, {
"Labels": {
"Project": "gcl3",
"Name": config.Name
},
"HostConfig": {
"AutoRemove": true,
"PortBindings": {
"22/tcp": [{ "HostPort": String(hostPort22) }],
"8821/tcp": [{ "HostPort": String(hostPort21) }],
},
},
}, (err, data, container) => {
let index = self.beAddedContainers.findIndex((c => c.Name === config.Name));
if (index >= 0) {
self.beAddedContainers.splice(index, 1);
}
if (err) {
return console.error(err);
}
console.log('DockerServer: run result ( ', data.StatusCode, container, ' )');
self.operationFinish();
});
};
DockerServer.prototype.remove = function(id) {
let self = this;
// for repeat delete
let beDeletedContainer = self.beDeletedContainers.find((c => c.Id === id));
if (beDeletedContainer) {
if (Date.now() - beDeletedContainer.sendTime < 10000) {
return;
}
}
else {
beDeletedContainer = {
Id: id
};
self.beDeletedContainers.push(beDeletedContainer);
}
beDeletedContainer.sendTime = Date.now();
let container = self.docker.getContainer(id);
if (!container) {
let index = self.beDeletedContainers.findIndex((c => c.Id === id));
if (index >= 0) {
self.beDeletedContainers.splice(index, 1);
}
console.log('DockerServer: remove error! self.docker.getContainer(id) is null. id = ', id);
self.operationFinish();
return;
}
function removeHandler(err, data) {
if (err) {
console.log('DockerServer: remove error! err= ', err, ', data= ', data);
}
else {
console.log('DockerServer: remove success! data= ', data);
}
let index = self.beDeletedContainers.findIndex((c => c.Id === id));
if (index >= 0) {
self.beDeletedContainers.splice(index, 1);
}
self.operationFinish();
}
function stopHandler(err, data) {
if (err) {
container.kill(killHandler);
console.log('DockerServer: Stop: err= ', err);
}
else {
container.remove(removeHandler);
}
}
function killHandler(err, data) {
if (err) {
console.log('DockerServer: kill: err= ', err);
}
container.remove(removeHandler);
}
container.stop(stopHandler);
};
DockerServer.prototype.operationFinish = function() {
if (this.beAddedContainers.length === 0 && this.beDeletedContainers.length === 0) {
this.lsMemoryContainers2();
}
};
DockerServer.prototype.validator = function() {
this.setProcessState(ProcessStateEnum.listingValidator);
let configContainers = this.configContainers;
let memoryContainers = this.memoryContainers;
this.beAddedContainers = [];
this.beDeletedContainers = [];
let hasOperation = false;
// No Healthy
for (let j = 0; j < memoryContainers.length; j++) {
let mContainer = memoryContainers[j];
if (mContainer.State !== 'running') {
console.log("DockerServer validator mContainer.State !== 'running' , mContainer: ", mContainer);
this.remove(mContainer.Id);
hasOperation = true;
}
}
// sync - remove
for (let j = 0; j < memoryContainers.length; j++) {
let mContainer = memoryContainers[j];
let iIndex = configContainers.findIndex((cContainer) => mContainer.Labels && mContainer.Labels.Name === cContainer.Name);
if (iIndex < 0) {
this.remove(mContainer.Id);
hasOperation = true;
}
}
// sync - add
for (let j = 0; j < configContainers.length; j++) {
let cContainer = configContainers[j];
let iIndex = memoryContainers.findIndex((mContainer) => mContainer.Labels && mContainer.Labels.Name === cContainer.Name);
if (iIndex < 0) {
this.run(cContainer);
hasOperation = true;
}
}
if (!hasOperation) {
this.setProcessState(ProcessStateEnum.listedValidator);
}
};
DockerServer.prototype.lsMemoryContainers2 = function() {
let self = this;
self.setProcessState(ProcessStateEnum.listingMemory2);
self.docker.listContainers(
{
filters: {
"label": [
"Project=gcl3",
]
}
},
(err, containers) => {
if (err) {
console.log('DockerServer lsMemoryContainers2 - err: ', err);
}
let newContainers = [];
if (Array.isArray(containers)) {
for (let i = 0; i < containers.length; i++) {
let container = containers[i];
if (container.State === 'running') {
if (container.Labels && container.Labels.Name) {
let index = self.beAddedContainers.findIndex(c => c.Name === container.Labels.Name);
if (index >= 0) {
self.beAddedContainers.splice(index, 1);
}
}
}
}
for (let i = self.beDeletedContainers.length - 1; i >= 0; i--) {
let beDeletedContainer = self.beDeletedContainers[i];
let index = containers.findIndex(c => c.Id === beDeletedContainer.Id);
if (index < 0) {
self.beDeletedContainers.splice(i, 1);
}
}
newContainers = containers;
}
if (!DockerServer.checkSameContainers(self.memoryContainers, newContainers)) {
console.log('DockerServer lsMemoryContainers2: ', self.memoryContainers);
}
else {
console.log('DockerServer lsMemoryContainers2 same to up.');
}
self.memoryContainers = newContainers;
self.setProcessState(ProcessStateEnum.listedMemory2);
if (self.beAddedContainers.length > 0) {
console.log('DockerServer lsMemoryContainers2 - beAddedContainers: ', self.beAddedContainers);
}
if (self.beDeletedContainers.length > 0) {
console.log('DockerServer lsMemoryContainers2 - beDeletedContainers: ', self.beDeletedContainers);
}
self.setProcessState(ProcessStateEnum.listedValidator);
}
);
};
DockerServer.prototype.setProcessState = function(state) {
this.processState = state;
this.processStateTime = Date.now();
};
DockerServer.prototype.eventBusCallback = function(event) {
if (!event || !event.target || !event.target.action) return;
if (event.target.action === 'add' || event.target.action === 'del') {
if (this.processState === ProcessStateEnum.listedValidator) {
this.lsConfigContainers();
}
else {
this.eventQueue.push(event);
}
}
};
DockerServer.prototype.init = function(httpServer, db) {
this.db = db;
this.httpServer = httpServer;
if (global.EventBus) {
EventBus.addEventListener('bureau', this.eventBusCallback, this);
}
let self = this;
let parseBody = function(req, res, body) {
if (body) {
let r = undefined;
try {
r = JSON.parse(body);
}
catch (e) {
let err = 'error: JSON.parse(body) by url :' + req.url;
console.log(err);
res.writeHead(500);
res.end(JSON.stringify({code: 500, msg: err}));
}
return r;
}
return undefined;
};
/**
// request url:
http://localhost:xxxx/container/query
action: ['ls', 'add', 'edit', 'del']
token.state: ['req', 'ing', 'ed', 'del']
*/
/** ls.req.json
{
session: Date.now(),
action: 'ls',
}
// ls.resp.json
{
session: ^,
action: ^,
data: { configContainers,memoryContainers },
state: {err:null}
}
*/
httpServer.route('/container/query')
.post(function(req, res) {
let body = '';
req.on('data', function(chunk) {
body += chunk;
});
req.on('end', function() {
let respError = (err, code) => {
let code2 = code ? code : 500;
let data = {err: 'error: ' + err, code: code2}
res.writeHead(code2);
res.end(JSON.stringify(data));
console.log(data);
};
let reqBody = parseBody(req, res, body);
if (!reqBody) return;
let {session, action} = reqBody;
if (action === 'ls') {
let r = {
session: session,
action: action,
data: {
configContainers: self.configContainers,
memoryContainers: self.memoryContainers
},
state: {err: null}
};
res.writeHead(200);
res.end(JSON.stringify(r));
}
else {
respError('action is invalid: ' + action);
}
});
});
httpServer.route('/upload')
.post(function(req, res) {
let body = '';
req.on('data', function(chunk) {
body += chunk;
});
req.on('end', function() {
let ss = body.match(/(file\.[^]*?[\S]*?--)/g);
let fileInfo = {};
ss.map(s => s.replace(/[ \f\n\r\t\v\-]/g, "")).forEach(s => {
let a = s.split('"');
if (a.length > 1) {
if (a[0] === 'file.size') {
fileInfo[a[0]] = Number(a[1]);
}
else {
fileInfo[a[0]] = a[1];
}
}
});
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end("OK, i am ---");
// INSERT INTO `client_upload`(`id`, `fileName`, `fileContenType`, `filePath`, `md5`, `size`, `uploadTime`) VALUES (1, 'a1', 'a2', 'a3', 'a4', 11, 12);
if (self.db && fileInfo["file.name"]) {
let sqlInsert = ["INSERT INTO `client_upload`(`fileName`, `fileContenType`, `filePath`, `md5`, `size`, `uploadTime`) VALUES ("];
sqlInsert.push("'" + fileInfo["file.name"] + "',");
sqlInsert.push("'" + fileInfo["file.content_type"] + "',");
sqlInsert.push("'" + fileInfo["file.path"] + "',");
sqlInsert.push("'" + fileInfo["file.md5"] + "',");
sqlInsert.push(String(fileInfo["file.size"]) + ',');
sqlInsert.push(String(Date.now()));
sqlInsert.push(");");
let sql = sqlInsert.join('');
try {
self.db.query(sql);
}
catch (e) {
console.log(sql);
console.log(e);
}
}
});
});
};
DockerServer.prototype.reset = function() {
this.processState = ProcessStateEnum.listedValidator;
for (let i = this.eventQueue.length - 1; i >= 0; i++) {
let event = this.eventQueue[i];
if (event.target.action === 'add' || event.target.action === 'del') {
this.eventQueue.splice(i, 1);
}
}
this.lsConfigContainers();
};
DockerServer.prototype.stats = function(memoryContainer) {
let self = this;
let containerId = String(memoryContainer.Id);
let container = self.docker.getContainer(containerId);
if (!container) {
console.log('DockerServer: stats error! self.docker.getContainer(id) is null. id = ', containerId);
return;
}
function statsHandler(err, stream) {
if (err) {
console.log('DockerServer: stats error! err= ', err);
}
if (!stream) return;
let cpu_stats = stream.cpu_stats;
let precpu_stats = stream.precpu_stats;
if (!cpu_stats || !precpu_stats) return;
let memory_stats = stream.memory_stats;
if (!memory_stats) return;
// https://github.com/moby/moby/issues/29306
// https://forums.docker.com/t/how-to-calculate-the-cpu-usage-in-percent/27509
// https://stackoverflow.com/questions/35692667/in-docker-cpu-usage-calculation-what-are-totalusage-systemusage-percpuusage-a
// let cpuPercent = 0.0
// // calculate the change for the cpu usage of the container in between readings
// let cpuDelta = cpuUsage.TotalUsage - float64(previousCPU)
// // calculate the change for the entire system between readings
// systemDelta = float64(v.CPUStats.SystemUsage) - float64(previousSystem)
//
// if systemDelta > 0.0 && cpuDelta > 0.0 {
// cpuPercent = (cpuDelta / systemDelta) * float64(len(v.CPUStats.CPUUsage.PercpuUsage)) * 100.0
// }
let delta_total_usage = (cpu_stats.cpu_usage.total_usage - precpu_stats.cpu_usage.total_usage);
let delta_system_usage = (cpu_stats.system_cpu_usage - precpu_stats.system_cpu_usage);
let cpuPercent = (delta_total_usage / delta_system_usage) * cpu_stats.cpu_usage.percpu_usage.length * 100.0;
// let delta_total_usage = (cpu_stats.cpu_usage.total_usage - precpu_stats.cpu_usage.total_usage) / precpu_stats.cpu_usage.total_usage;
// let delta_system_usage = (cpu_stats.system_cpu_usage - precpu_stats.system_cpu_usage) / precpu_stats.system_cpu_usage;
// let cpuPercent = (delta_total_usage / delta_system_usage) * cpu_stats.cpu_usage.percpu_usage.length * 100.0;
//
// console.log(cpuPercent);
//
// console.log(memory_stats.usage, memory_stats.max_usage, memory_stats.limit);
if (self.db) {
let BureauId = DockerServer.getContainerBureauId(memoryContainer);
let sqlInsert = ["INSERT INTO `container_stat`(`bureauId`, `containerId`, `cpuPercent`, `memUsage`, `memMaxUsage`, `memLimit`, `statTime`) VALUES ("];
sqlInsert.push(BureauId + ',');
sqlInsert.push("'" + containerId + "',");
sqlInsert.push(cpuPercent.toFixed(3) + ',');
sqlInsert.push(String(memory_stats.usage) + ',');
sqlInsert.push(String(memory_stats.max_usage) + ',');
sqlInsert.push(String(memory_stats.limit) + ',');
sqlInsert.push(String(Date.now()));
sqlInsert.push(");");
let sql = sqlInsert.join('');
try {
self.db.query(sql);
}
catch (e) {
console.log(sql);
console.log(e);
}
}
}
container.stats({stream: false}, statsHandler);
};
DockerServer.prototype.lsStatContainers = function() {
for (let i = 0; i < this.memoryContainers.length; i++) {
let memoryContainer = this.memoryContainers[i];
this.stats(memoryContainer);
}
};
DockerServer.prototype.timeOut = function() {
this.timeOutCount++;
let dtNow = Date.now();
// process exception
if (this.processState !== ProcessStateEnum.listedValidator) {
if (dtNow - this.processStateTime > 6000) {
this.reset();
}
}
else {
if (this.timeOutCount % 10 === 0) {
this.lsConfigContainers();
}
else {
if (this.timeOutCount % 7 === 0) {
this.lsStatContainers();
}
}
}
};
DockerServer.prototype.start = function() {
let self = this;
self.lsConfigContainers();
self.timeOutCount = 0;
self.timeOutHandle = setInterval(() => {
self.timeOut();
}, 1000);
};
DockerServer.prototype.stop = function() {
if (this.timeOutHandle) {
clearInterval(this.timeOutHandle);
this.timeOutHandle = null;
}
};
exports = module.exports = DockerServer;
<file_sep>'use strict';
let url = require('url');
let fs = require('fs');
let path = require('path');
let zlib = require('zlib');
exports = module.exports = FileServer;
function FileServer() {
this.config = {
expires: {
fileMatch: /^(gif|png|jpg|js|css)$/ig,
maxAge: 60 * 60 * 24 * 365,
},
compress: {
match: /css|html/ig,
},
assetsPath: process.cwd(),
homePage: 'index.html',
notFoundPage: 'error.html',
};
}
FileServer.mime = {
'css': 'text/css',
'gif': 'image/gif',
'html': 'text/html',
'ico': 'image/x-icon',
'jpeg': 'image/jpeg',
'jpg': 'image/jpeg',
'js': 'text/javascript',
'json': 'application/json',
'pdf': 'application/pdf',
'png': 'image/png',
'svg': 'image/svg+xml',
'swf': 'application/x-shockwave-flash',
'tiff': 'image/tiff',
'txt': 'text/plain',
'wav': 'audio/x-wav',
'wma': 'audio/x-ms-wma',
'wmv': 'video/x-ms-wmv',
'xml': 'text/xml',
};
FileServer.parseRange = function(str, size) {
if (str.indexOf(',') != -1) {
return;
}
let range = str.split('-'),
start = parseInt(range[0], 10),
end = parseInt(range[1], 10);
// Case: -100
if (isNaN(start)) {
start = size - end;
end = size - 1;
// Case: 100-
} else if (isNaN(end)) {
end = size - 1;
}
// Invalid
if (isNaN(start) || isNaN(end) || start > end || end > size) {
return;
}
return {start: start, end: end};
};
FileServer.prototype.dispatch = function(request, response) {
let config = this.config;
response.setHeader('Server', 'HttpFileServer-Node');
response.setHeader('Accept-Ranges', 'bytes');
let pathname = url.parse(request.url).pathname;
console.log(pathname);
if (pathname.slice(-1) === '/') {
pathname = pathname + config.homePage;
}
let realPath = path.join(config.assetsPath, path.normalize(pathname.replace(/\.\./g, '')));
let pathHandle = function(realPath) {
fs.stat(realPath, function(err, stats) {
if (err) {
response.writeHead(404, 'Not Found', {'Content-Type': 'text/plain'});
response.write('This request URL ' + pathname + ' was not found on this server.');
response.end();
} else {
if (stats.isDirectory()) {
realPath = path.join(realPath, '/', config.homePage);
pathHandle(realPath);
} else {
let ext = path.extname(realPath);
ext = ext ? ext.slice(1) : 'unknown';
let contentType = FileServer.mime[ext] || 'text/plain';
response.setHeader('Content-Type', contentType);
// response.setHeader('Content-Length', stats.size);
let lastModified = stats.mtime.toUTCString();
let ifModifiedSince = 'If-Modified-Since'.toLowerCase();
response.setHeader('Last-Modified', lastModified);
if (ext.match(config.expires.fileMatch)) {
let expires = new Date();
expires.setTime(expires.getTime() + config.expires.maxAge * 1000);
response.setHeader('Expires', expires.toUTCString());
response.setHeader('Cache-Control', 'max-age=' + config.expires.maxAge);
}
if (request.headers[ifModifiedSince] && lastModified == request.headers[ifModifiedSince]) {
response.writeHead(304, 'Not Modified');
response.end();
} else {
let compressHandle = function(raw, statusCode, reasonPhrase) {
let stream = raw;
let acceptEncoding = request.headers['accept-encoding'] || '';
let matched = ext.match(config.compress.match);
if (matched && acceptEncoding.match(/\bgzip\b/)) {
response.setHeader('Content-Encoding', 'gzip');
stream = raw.pipe(zlib.createGzip());
} else if (matched && acceptEncoding.match(/\bdeflate\b/)) {
response.setHeader('Content-Encoding', 'deflate');
stream = raw.pipe(zlib.createDeflate());
}
response.writeHead(statusCode, reasonPhrase);
stream.pipe(response);
};
if (request.headers['range']) {
let range = FileServer.parseRange(request.headers['range'], stats.size);
if (range) {
response.setHeader('Content-Range', 'bytes ' + range.start + '-' + range.end + '/' + stats.size);
response.setHeader('Content-Length', (range.end - range.start + 1));
let raw = fs.createReadStream(realPath, {'start': range.start, 'end': range.end});
compressHandle(raw, 206);
} else {
response.removeHeader('Content-Length');
response.writeHead(416);
response.end();
}
} else {
let raw = fs.createReadStream(realPath);
compressHandle(raw, 200);
// console.log(realPath)
}
}
}
}
});
};
pathHandle(realPath);
};
<file_sep>
### https://austinmorlan.com/posts/docker_clion_development/
docker build -t docker-remote-dev ./docker-remote-dev/.
docker-compose up -d
# Go to File -> Settings -> Build, Execution, Deployment -> Toolchains.
# Add a new toolchain named Docker, set it to Remote Host, and configure
# the credentials using the three dots to the right of the field (username: dev password: dev).
#Go to File -> Settings -> Build, Execution, Deployment -> CMake.
# Add a new profile and name it Debug-Remote. Set the toolchain to our previously
# created Docker toolchain.
#Go to File -> Settings -> Build, Execution, Deployment -> Deployment.
#Select the existing Docker entry and fill out the information if it isn’t already there.
# Ensure the Root path is set to /.
#Go to the Mappings tab and set your local project directory to be mapped to a directory in the container.
#We need to do two more things to ensure that we’re able to run an X11 application in the container.
# In a shell on your host, run echo $DISPLAY and note the output. It’s probably :0 but could be something else.
# Then select Edit Configurations from the same build configuration dropdown in CLion and add DISPLAY=:0
# (or whatever the output was) to the list of environment variables. This connects the display of our host to the display of the container.
<file_sep>/**
* Created by oudream on 2016/12/23.
*/
(function() {
'use strict';
var CjEnv = CjEnv || {};
if ( typeof window === 'object' ) {
window.cjs = window.cjs || {};
} else {
throw Error('cjs only run at web browser');
}
cjs.CjEnv = CjEnv;
/**
* get url params
* @param name
* @returns {*}
*/
CjEnv.getUrlParam = function getUrlParam(name) {
let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
let r = window.location.search.substr(1).match(reg);
if (r != null) return decodeURI(r[2]); return null;
};
// 获取本地时间
// 只要到分钟就可以了,new Date().toLocaleString().replace(/:\d{1,2}$/,' ');
CjEnv.getLocalTime = function() {
if ( arguments.length == 0 ) {
return new Date().toLocaleString();
}
let iDt = parseInt(arguments[0]);
if (iDt < 0x7FFFFFFF) iDt = iDt * 1000;
return new Date(iDt).toLocaleString();
};
CjEnv.getServerInfo = function() {
let protocol = window.location.protocol;
let host = window.location.host;
let port = window.location.port;
return {
'protocol': protocol,
'host': host,
'port': port,
};
};
})();
<file_sep>(function() {
'use strict';
let odl = (typeof exports === 'object' && typeof global === 'object') ? global.odl : window.odl;
odl.UiVueBase = {
kind: 'ui.vue.base',
_defaultWidth: {
int: 80,
int32: 60,
int64: 80,
double: 80,
bool: 60,
string: 120,
date: 100,
enum: 80
},
getSimilar: function(odc) {
return odl.findNObj(odc, this.kind);
},
getSimilarByName: function(name) {
let odc = odl.findOdc(name);
return odc ? this.getSimilar(odc) : null;
},
completionAttr: function(attr) {
// visible
if (!attr.hasOwnProperty('visible')) {
attr.visible = true;
}
if (!attr.hasOwnProperty('readonly')) {
attr.readonly = false;
}
},
/**
*
* @param odc
* @param nObj
* @returns {Error|null}
*/
normalize: function(odc, nObj) {
// extend base
let base = odl.findNObj(odc, odl.UiVueBase.kind);
if (base) {
odl.mergeExcepts(nObj, base);
if (base.spec && base.spec.attrs) {
if (nObj.spec && nObj.spec.attrs) {
nObj.spec.attrs = odl.Attr.mergeAttrs(base.spec.attrs, nObj.spec.attrs);
}
else {
if (!nObj.spec) nObj.spec = {};
nObj.spec.attrs = odl.clone(base.spec.attrs);
}
}
}
if (!nObj.spec) nObj.spec = {};
let spec = nObj.spec;
// title
if (!spec.title) {
spec.title = {
title: odc.metadata.name
};
}
// attrs
let supperAttrs = odc.spec.attrs;
if (!spec.attrs) spec.attrs = [];
let attrs = spec.attrs;
let newAttrs = odl.Attr.mergeAttrs(supperAttrs, attrs);
for (let i = 0; i < newAttrs.length; i++) {
let newAttr = newAttrs[i];
this.completionAttr(newAttr);
}
spec.attrs = newAttrs;
// spec.keys & spec.key
if (Array.isArray(odc.spec.container.keys) && !spec.keys) {
spec.keys = odl.clone(odc.spec.container.keys);
}
if (Array.isArray(odc.spec.container.sorts) && !spec.sorts) {
spec.sorts = odl.clone(odc.spec.container.sorts);
}
if (Array.isArray(spec.keys) && spec.keys.length > 0) {
let sKey = spec.keys.find(ele => typeof ele === 'string' && ele.length > 0);
spec.key = spec.attrs.find(ele => ele.name === sKey);
}
return null;
},
/**
*
* @param odc
* @param nObj
* @returns {Error}
*/
normalizeAfer: function(odc, nObj) {
if (nObj.kind !== this.kind) {
return new Error('nObj kind invalid!!');
}
let attrs = nObj.spec.attrs;
},
getFormats: function(name, type) {
let formats = {
formatSex: function(row, column) {
return row[column.property] == 1 ? '男' : row[column.property] == 0 ? '女' : '未知';
},
// double
formatBool: function(row, column) {
return row[column.property] ? 'Y' : 'N';
},
// double
formatDouble: function(row, column) {
let v = row[column.property];
if (typeof v === 'number') {
return row[column.property].toFixed(2);
}
return v;
},
// date
formatDate: function(row, column) {
let dt = row[column.property];
if (dt) {
return String(dt.getFullYear()) + '-' + dt.getMonth() + '-' + dt.getDay();
}
return dt;
},
// time
formatTime: function(row, column) {
let dt = row[column.property];
if (dt) {
return String(dt.getHours()) + ':' + dt.getMinutes() + ':' + dt.getSeconds();
}
return dt;
},
};
let formatDefault = {
int: null,
int32: null,
int64: null,
double: formats.formatDouble,
bool: formats.formatBool,
string: null,
date: formats.formatDate,
enum: null,
};
return name && formats[name] ? formats[name] : formatDefault[type];
},
getSelects: function(scopes, values) {
let r = {options: []};
if (Array.isArray(scopes)) {
if (Array.isArray(values) && values.length >= scopes.length) {
scopes.forEach((s, i) => {
r.options.push({label: s, value: values[i]})
});
}
else {
scopes.forEach((s, i) => {
r.options.push({label: s, value: i})
});
}
}
else {
return null;
}
return r;
},
/**
* attrs
<el-table-column v-for="attr in attrs" :prop="attr.name" :label="attr.label" :width="attr.width" :formatter="attr.format" :sortable="attr.sortable" show-overflow-tooltip="attr.showOverflowTooltip">
* @param nObj
* @returns {[]}
*/
getFields: function(nObj) {
let r = [];
let push = (name, a) => {
let atr = {
name: name,
type: a.type,
maxLength: a.maxLength,
label: a.title,
width: a.width ? a.width : this._defaultWidth[a.type],
height: a.height ? a.height : 30,
format: this.getFormats(a.format, a.type),
sortable: true,
showOverflowTooltip: a.type === 'string' && a.maxLength > this._defaultWidth[a.type],
readonly: a.readonly,
contentType: a.contentType ? a.contentType : 'text'
};
if (a.type !== 'string' || a.type !== 'bool') {
atr.minvalue = a.minvalue;
atr.maxvalue = a.maxvalue;
}
if (a.type === 'enum') {
atr.select = this.getSelects(a.scopes, a.values);
}
r.push(atr);
return atr;
};
nObj.spec.attrs.forEach(a => {
if (a.visible) {
push(a.name, a);
}
if (a.refer) {
let ar = odl.findReferTitleAttr(a.refer, this.kind);
if (ar) {
let atr = push(a.refer.titleName, ar);
atr.from = {};
atr.from.refer = odl.clone(a.refer);
atr.from.prevAttr = a.name;
atr.readonly = a.readonly;
}
}
});
if (r.length > 0) {
r[r.length - 1].width = undefined;
r[r.length - 1]['minWidth'] = 180
}
return r;
},
/**
* attrs
filter: {
filters: [
{
fields: [
{value: 'ManID', label: '品牌名称'}
],
fieldValue: null,
operations: [
{value: '=', label: '='}
],
operationValue: null,
values: [],
value: null,
type: 'refer',
isAnd: true
},
{
fields: [
{value: 'ModelName', label: '车型名称'},
{value: 'ModelPy', label: '车型拼音'},
],
fieldValue: null,
operations: [],
operationValue: null,
values: [],
value: null,
type: null,
isAnd: true
}
]
}
* @param nObj
* @returns {[]}
*/
getFilterFields: function(nObj) {
let attrs = nObj.spec.attrs;
let filters = nObj.spec.filter && Array.isArray(nObj.spec.filter.filters) ? odl.clone(nObj.spec.filter.filters) : null;
if (Array.isArray(filters)) {
let b = true;
for (let i = 0; i < filters.length; i++) {
let filter = filters[i];
if (! Array.isArray(filter.fields)) {
b = false;
break;
}
for (let j = 0; j < filter.fields.length; j++) {
let field = filter.fields[i];
if (! field.value) {
b = false;
break;
}
if (! field.label) {
let attr = attrs.find(a => a.name === field.value);
if (attr) {
field.label = attr.title;
} else {
b = false;
break;
}
}
}
if (b === false) break;
if (! filter.hasOwnProperty('fieldValue')) {
if (filter.fields.length === 1) {
filter.fieldValue = filter.fields[0].value;
} else {
filter.fieldValue = null;
}
}
if (! Array.isArray(filter.operations)) filter.operations = [];
if (! filter.hasOwnProperty('operationValue')) {
if (filter.operations.length === 1) {
filter.operationValue = filter.operations[0].value;
} else {
filter.operationValue = null;
}
}
if (! Array.isArray(filter.values)) filter.values = [];
if (! filter.hasOwnProperty('value')) {
if (filter.values.length === 1) {
filter.value = filter.values[0].value;
} else {
filter.value = null;
}
}
if (! filter.hasOwnProperty('type')) filter.type = null;
if (! filter.hasOwnProperty('isAnd')) filter.isAnd = true;
if (filter.type === 'refer') {
if (filter.fields.length === 1 && filter.operations.length >= 1) {
}
else {
b = false;
break;
}
}
}
if (b) {
return filters;
}
}
{
let filter = {
fields: [],
fieldValue: null,
operations: [],
operationValue: null,
values: [],
value: null,
type: null,
isAnd: true
};
for (let i = 0; i < attrs.length; i++) {
let attr = attrs[i];
if (attr.visible) {
filter.fields.push({
value: attr.name,
label: attr.title,
});
}
}
return [filter];
}
},
/**
* attrs
this.filter.options = [
{
value: '%',
label: 'LIKE',
},
{
value: '>',
label: '>',
},
]
* @param nObj
* @param attrName
* @returns {[]}
*/
getFilterOperations: function(nObj, attrName) {
let r = [
{
value: '=',
label: '=',
}
];
let attr = nObj.spec.attrs.find(a => a.name === attrName);
if (attr) {
let type = attr.type;
if (attr.refer) {
let attr2 = odl.findReferTitleAttr(attr.refer, this.kind);
if (attr2) {
type = attr2.type;
}
}
if (type === 'string') {
r.push({
value: '%',
label: '%',
});
}
else if (type === 'bool' || type === 'enum') {
}
else {
r.push({
value: '>',
label: '>',
});
r.push({
value: '<',
label: '<',
});
}
}
return r;
},
/**
* attrs
* @param nObj
*/
getFormDefault: function(nObj) {
let r = {};
nObj.spec.attrs.forEach(a => {
if (typeof a.default === 'function') {
r[a.name] = a.default();
}
else {
r[a.name] = a.default;
}
});
return r;
},
/**
* attrs
* @param nObj
*/
getFormRules: function(nObj) {
let r = {};
if (Array.isArray(nObj.spec.keys)) {
nObj.spec.keys.forEach(k => {
let attr = nObj.spec.attrs.find(a => a.name === k);
if (attr !== undefined) {
r[k] = [{required: true, message: '请输入' + attr.title, trigger: 'blur'}];
}
});
}
nObj.spec.attrs.forEach(a => {
if (a.required) {
r[a.name] = [{required: true, message: '请输入' + a.title, trigger: 'blur'}];
}
});
return r;
},
getEditSubmitObj: function(nObj, formObj, oldObj) {
let iCount = 0;
let r = {};
let key = nObj.spec.key ? nObj.spec.key.name : '';
for (let prop in oldObj) {
if (prop === key) {
continue;
}
let nv = formObj[prop];
let ov = oldObj[prop];
if (nv != ov) {
r[prop] = nv;
iCount++;
}
}
if (iCount > 0) {
return r;
}
else {
return null;
}
}
};
odl.UiVueForm = {
kind: 'ui.vue.form',
_defaultWidth: odl.UiVueBase._defaultWidth,
getSimilar: odl.UiVueBase.getSimilar,
getSimilarByName: odl.UiVueBase.getSimilarByName,
completionAttr: odl.UiVueBase.completionAttr,
normalize: function(odc, nObj) {
if (nObj.kind !== this.kind) {
return new Error('nObj kind invalid!!');
}
return odl.UiVueBase.normalize(odc, nObj);
},
normalizeAfer: odl.UiVueBase.normalizeAfer,
getFormats: odl.UiVueBase.getFormats,
getSelects: odl.UiVueBase.getSelects,
getFields: odl.UiVueBase.getFields,
getFilterFields: odl.UiVueBase.getFilterFields,
getFilterOperations: odl.UiVueBase.getFilterOperations,
getFormDefault: odl.UiVueBase.getFormDefault,
getFormRules: odl.UiVueBase.getFormRules,
getEditSubmitObj: odl.UiVueBase.getEditSubmitObj
};
odl.UiVueTable = {
kind: 'ui.vue.table',
_defaultWidth: odl.UiVueBase._defaultWidth,
getSimilar: odl.UiVueBase.getSimilar,
getSimilarByName: odl.UiVueBase.getSimilarByName,
completionAttr: odl.UiVueBase.completionAttr,
normalize: function(odc, nObj) {
if (nObj.kind !== this.kind) {
return new Error('nObj kind invalid!!');
}
return odl.UiVueBase.normalize(odc, nObj);
},
normalizeAfer: odl.UiVueBase.normalizeAfer,
getFormats: odl.UiVueBase.getFormats,
getSelects: odl.UiVueBase.getSelects,
getFields: odl.UiVueBase.getFields,
getTableFields: odl.UiVueBase.getFields,
getFilterFields: odl.UiVueBase.getFilterFields,
getFilterOperations: odl.UiVueBase.getFilterOperations,
getFormDefault: odl.UiVueBase.getFormDefault,
getFormRules: odl.UiVueBase.getFormRules,
getEditSubmitObj: odl.UiVueBase.getEditSubmitObj
};
odl.UiVueValidator = {
kind: 'ui.vue.validator',
_defaultWidth: odl.UiVueBase._defaultWidth,
getSimilar: odl.UiVueBase.getSimilar,
getSimilarByName: odl.UiVueBase.getSimilarByName,
completionAttr: odl.UiVueBase.completionAttr,
normalize: function(odc, nObj) {
if (nObj.kind !== this.kind) {
return new Error('nObj kind invalid!!');
}
return odl.UiVueBase.normalize(odc, nObj);
},
normalizeAfer: odl.UiVueBase.normalizeAfer,
getFormats: odl.UiVueBase.getFormats,
getSelects: odl.UiVueBase.getSelects,
getFields: odl.UiVueBase.getFields,
getFilterFields: odl.UiVueBase.getFilterFields,
getFilterOperations: odl.UiVueBase.getFilterOperations,
getFormDefault: odl.UiVueBase.getFormDefault,
getFormRules: odl.UiVueBase.getFormRules,
getEditSubmitObj: odl.UiVueBase.getEditSubmitObj
};
odl.registerNPlugin(odl.UiVueForm);
odl.registerNPlugin(odl.UiVueTable);
odl.registerNPlugin(odl.UiVueValidator);
})();
<file_sep>(function() {
'use strict';
let odl = (typeof exports === 'object' && typeof global === 'object') ? global.odl : window.odl;
odl.OpToken = {
kind: 'op.token',
/**
*
*/
_oTokens: [
{
odc: '-',
add: [
{
odc: 'odcName',
action: 'add',
from: {user: '', ip: '', dt: new Date()},
token: {
state: 'ing',
id: 'xxx',
duration: 'ms',
deadline: 'datetime',
}
}],
edit: [],
del: [],
},
],
getSimilar: function(odc) {
return odl.findNObj(odc, this.kind);
},
getSimilarByName: function(name) {
let odc = odl.findOdc(name);
return odc ? this.getSimilar(odc) : null;
},
findTokenLogById: function(id) {
this._oTokens.forEach(ot => {
if (ot.add.find(t => t.token.id === id)) {
return t;
}
if (ot.edit.find(t => t.token.id === id)) {
return t;
}
if (ot.del.find(t => t.token.id === id)) {
return t;
}
});
return null;
},
/**
*
* @param from
* @param odc
* @param action
* @returns {string|tl.token|{duration, state, id, deadline}}
*/
reqToken: function(from, odc, action) {
let ot = this._oTokens.find(x => x.odc === odc.metadata.name);
if (!ot) {
ot = {
odc: odc.metadata.name,
add: [],
edit: [],
del: [],
validate: []
};
this._oTokens.push(ot);
}
let tls = ot[action];
if (!tls) return ['request token - odc[',odc,'], action[',action,'] : is invalid!'].join('');
// if (tls.length > 0) return ['request token - odc[',odc,'], action[',action,'] : There is already an action in progress!'].join('');
if (tls.length > 100) { ot[action] = []; tls = ot[action] };
let tl = {
odc: odc.metadata.name,
action: action,
from: from,
token: {
state: 'ing',
id: 'xxx',
duration: 30 * 60 * 1000,
deadline: new Date(Date.now() + 30 * 60 * 1000),
}
};
tls.push(tl);
return tl.token;
},
releaseToken: function(odc, action) {
let ot = this._oTokens.find(x => x.odc === odc.metadata.name);
if (!ot) return;
let tls = ot[action];
if (!tls) return;
ot[action] = [];
}
};
odl.registerNPlugin(odl.OpToken);
})();
<file_sep># ionic3-android-builder
## Simple container for building ionic 3 android builds
## Build Image
docker build --no-cache -t ionic3-android-builder .
## Run
docker run -v /myApp:/build smartideasllc/ionic3-adroid-builder /bin/bash -c "npm install; ionic cordova build android --prod"
<file_sep>'use strict';
let http = require('http');
require('./cjinterinfo_lang.js');
require('./cjstring_lang.js');
exports = module.exports = Route;
let toString = Object.prototype.toString;
function Route() {
this.stack = [];
}
// [ 'get', 'post', 'put', 'head', 'delete' ]
Route.methods = function() {
return http.METHODS && http.METHODS.map(function lowerCaseMethod(method) {
return method.toLowerCase();
});
}();
Route.methods.push('all');
Route.methods.forEach(function(method) {
Route.prototype[method] = function(path, handle) {
// cjs.debug('Route %s %s', method, this.path);
let layer = new Layer(method, path, handle);
// cjs.debug('Layer.isValid=', layer.isValid);
// this.methods[method] = true;
this.stack.push(layer);
return layer.isValid;
};
});
Route.prototype.handle = function handle(req, res, out) {
// cjs.debug('Route %s %s', req.method, req.url);
let self = this;
let stack = self.stack;
let layer;
let path = req.url;
let method = req.method;
let match = false;
let idx = 0;
while (match !== true && idx < stack.length) {
layer = stack[idx++];
match = layer.match(method, path);
if (match) {
layer.handle_request(req, res, out);
}
}
return match;
};
function Layer(method, path, handle) {
let regexp = typeof path === 'string' ? new RegExp(path) : null;
if (regexp === null && path instanceof RegExp) regexp = path;
let bIsValid = typeof method === 'string' && (typeof path === 'string' || path instanceof RegExp) && typeof handle === 'function';
let bMethodIsAll = cjs.CjString.equalCase(method, 'all');
let bPathIsAll = path === '/';
let sErrorMsg = bIsValid ? '' : 'method:' + toString.call(method);
this.method = method;
this.path = path;
this.handle = handle;
this.regexp = regexp ? regexp : new RegExp('');
this.methodIsAll = bMethodIsAll;
this.pathIsAll = bPathIsAll;
this.errorMsg = sErrorMsg;
this.isValid = bIsValid;
}
Layer.prototype.handle_request = function handle(req, res, out) {
let fn = this.handle;
if (fn.length > 2) {
if (typeof out === 'function') out('handle_request fn.length>2');
return;
}
try {
fn(req, res);
} catch (err) {
if (typeof out === 'function') out(err);
}
};
Layer.prototype.match = function match(method, path) {
let bMethod = this.isValid && (this.methodIsAll || (typeof method === 'string' && method.toLowerCase() === this.method));
return bMethod && (this.pathIsAll || this.regexp.test(path));
};
<file_sep>FROM httpsserver-flask1:latest
ADD . /code
RUN apk add --no-cache \
libressl-dev \
musl-dev \
libffi-dev \
pip install --no-cache-dir pyopenssl && \
apk del libressl-dev \
musl-dev \
libffi-dev
ENTRYPOINT ["python", "httpsserver.py"]
<file_sep>(function() {
'use strict';
if (typeof exports === 'object' && typeof global === 'object') {
global.cjs = global.cjs || {};
} else if (typeof window === 'object') {
window.cjs = window.cjs || {};
} else {
throw Error('cjs only run at node.js or web browser');
}
let CjString = cjs.CjString || {};
cjs.CjString = CjString;
if (typeof exports === 'object' && typeof global === 'object') {
exports = module.exports = CjString;
}
CjString.toString = Object.prototype.toString;
if (CjString.hasOwnProperty('equalCase')) return;
/**
* equal ignore case
* @param str1
* @param str2
* @returns {boolean}
*/
CjString.equalCase = function(str1, str2) {
let r = false;
if (typeof str1 === 'string' && typeof str2 === 'string') {
r = str1.toLowerCase() === str2.toLowerCase();
}
return r;
};
/**
*
* @returns {string}
* sample : CjString.format('{0} - {1}', 123, 'abc')
*/
CjString.format = function() {
if (arguments.length === 0) {
return null;
}
let sSource = arguments[0];
let args = arguments;
let i = 0;
let r = sSource.replace(/\{\d+\}/g,
function(m) {
i++;
return args[i];
});
return r;
};
/**
* add commas(.)
* @param nStr
* @returns {string}
* Usage: addCommas(12345678);
* result: 12,345,678
*/
CjString.addCommas = function addCommas(nStr) {
nStr += '';
let x = nStr.split('.');
let x1 = x[0];
let x2 = x.length >= 1 ? '.' + x[1] : '';
let rgx = /(d+)(d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
};
/**
* pad zero
*
* @param num, n
* @returns {*}
* sample1 : padZero(1.23, 5) === '01.23'
* sample1 : padZero(123, 5) === '00123'
*/
CjString.padZero = CjString.addZero = function padZero() {
let tbl = [];
return function(num, n) {
let len = n - num.toString().length;
if (len <= 0) return num;
if (!tbl[len]) tbl[len] = (new Array(len + 1)).join('0');
return tbl[len] + num;
};
}();
CjString.nullCheck = function(path, callback) {
if (('' + path).indexOf('\u0000') !== -1) {
let er = new Error('Path must be a string without null bytes');
er.code = 'ENOENT';
if (typeof callback !== 'function') {
throw er;
}
process.nextTick(callback, er);
return false;
}
return true;
};
CjString.urlToObject = function getJsonFromUrl(query) {
let sQuery = query;
if (sQuery == null) {
if (typeof location === 'object') {
sQuery = location.search.substr(1);
if (!sQuery.length) {
let pos = location.href.indexOf('?');
if (pos === -1) return [];
sQuery = location.href.substr(pos + 1);
}
}
} else {
let pos = sQuery.indexOf('?');
if (pos !== -1) {
sQuery = sQuery.substr(pos + 1);
}
}
let result = {};
sQuery.split('&').forEach(function(part) {
if (!part) return;
part = part.split('+').join(' '); // replace every + with space, regexp-free version
let eq = part.indexOf('=');
let key = eq > -1 ? part.substr(0, eq) : part;
let val = eq > -1 ? decodeURIComponent(part.substr(eq + 1)) : '';
let from = key.indexOf('[');
if (from === -1) result[decodeURIComponent(key)] = val;
else {
let to = key.indexOf(']');
let index = decodeURIComponent(key.substring(from + 1, to));
key = decodeURIComponent(key.substring(0, from));
if (!result[key]) result[key] = [];
if (!index) result[key].push(val);
else result[key][index] = val;
}
});
return result;
};
/**
*
* @param aryString<Array>
* @param sKey<String>
*/
CjString.findValueInArray = function(aryString, sKey) {
let r = '';
if (!sKey) return r;
for (let i = 0; i < aryString.length; i++) {
let arg = aryString[i];
if (arg.startsWith(sKey)) {
return arg.substring(sKey.length);
}
}
return r;
};
})();
<file_sep>'use strict';
let path = require('path');
let http = require('http');
const querystring = require('querystring');
let getContentDisposition = function(data) {
let ss = data.split('\r\n');
for (let i = 0; i < ss.length; i++) {
let s = ss[i];
let index = s.indexOf('name=');
}
};
let server = http.createServer(function(req, res) {
console.log(req);
if (req.url.startsWith('/upload') && req.method.toLowerCase() === 'post') {
let data = '';
// 通过req的data事件监听函数,每当接受到请求体的数据,就累加到data变量中
req.on('data', function(chunk){
data += chunk;
});
// 在end事件触发后,解释请求体,取出sql语句,然后向客户端返回。
req.on('end', function() {
let ss = data.match(/(file\.[^]*?[\S]*?--)/g);
let fileInfo = {};
ss.map(s => s.replace(/[ \f\n\r\t\v\-]/g, "")).forEach(s => {
let a = s.split('"');
if (a.length > 1) {
if (a[0] === 'file.size') {
fileInfo[a[0]] = Number(a[1]);
}
else {
fileInfo[a[0]] = a[1];
}
}
});
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end("OK, i am ---");
})
}
});
server.on('checkContinue', function(req, res) {
let msg = 'step checkContinue' + Date();
res.writeContinue();
console.log(msg);
});
server.on('clientError', (err, socket) => {
let msg = 'step clientError' + Date();
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
console.log(msg);
});
server.on('close', function() {
let msg = 'step close' + Date();
console.log(msg);
});
server.on('connect', function(req, socket, firstBodyChunk) {
let msg = 'step connect' + Date();
console.log(msg);
});
server.on('connection', function(connection) {
let msg = 'step connection' + Date();
console.log(msg);
});
server.on('upgrade', function(req, socket, head) {
let msg = 'step upgrade' + Date();
console.log(msg);
});
server.listen(2292);
console.log('http://localhost:%s', 2292);
<file_sep>const path = require('path');
const fs = require('fs');
let odcPathes = [
'./../../../assets/3rd/odl-3/odl',
'./../../../assets/3rd/odl-3/odl_n_mysql',
'./../../../assets/3rd/odl-3/odl_n_sqlite',
'./../../../assets/3rd/odl-3/odl_n_vue',
'./../../../assets/3rd/odl-3/odl_n_token',
'./../../../assets/lishi/sharedb/config/odc_customer',
'./../../../assets/lishi/sharedb/config/odc_role_group',
'./../../../assets/lishi/sharedb/config/odc_user',
'./../../../assets/lishi/sharedb/config/odc_man',
'./../../../assets/lishi/sharedb/config/odc_vehicle',
'./../../../assets/lishi/sharedb/config/odc_client_upload',
'./../../../assets/lishi/sharedb/config/odc_log_record'
];
// let odcPathes = [];
// let odcPath = "./../../../assets/lishi/sharedb/config";
// const odcFileNames = require('./../../../assets/lishi/sharedb/config/odc').odcFileNames;
//
// for (let i = 0; i < odcFileNames.length; i++) {
// odcPathes.push(path.normalize(path.join(odcPath, odcFileNames[i])));
// }
for (let i = 0; i < odcPathes.length; i++) {
require(odcPathes[i]);
}
exports = module.exports = {
/**
* mock bootstrap
*/
init(httpServer, db) {
}
};
<file_sep>#!/bin/ash
# do not detach (-D), log to stderr (-e), passthrough other arguments
exec /usr/sbin/sshd -D -e "$@"
<file_sep>FROM vertexmachina/docker-remote-dev:latest
RUN apt update && apt install -y qt5-default<file_sep>FROM ubuntu:18.04
## 一次性安装
RUN apt-get update -y ; apt-get upgrade -y && \
apt-get install -y apt-utils wget openssh-server telnet screen vim passwd ifstat unzip iftop htop git \
samba net-tools lsof rsync gcc g++ autoconf cmake build-essential gdb gdbserver \
libncurses5-dev unixodbc unixodbc-dev libcurl4-openssl-dev uuid uuid-dev libssl-dev \
qt5-default libqt5svg5 libqt5svg5-dev nginx python3 python3-dev
RUN apt update \
&& apt install -y openssh-server \
xauth \
x11-apps \
&& mkdir /var/run/sshd \
&& mkdir /root/.ssh \
&& chmod 755 /root/.ssh \
&& ssh-keygen -A \
&& sed -i "s/^.*PasswordAuthentication.*$/PasswordAuthentication no/" /etc/ssh/sshd_config \
&& sed -i "s/^#PermitRootLogin.*$/PermitRootLogin yes/" /etc/ssh/sshd_config \
&& sed -i "s/^.*X11Forwarding.*$/X11Forwarding yes/" /etc/ssh/sshd_config \
&& sed -i "s/^.*X11UseLocalhost.*$/X11UseLocalhost no/" /etc/ssh/sshd_config \
&& grep "^X11UseLocalhost" /etc/ssh/sshd_config || echo "X11UseLocalhost no" >> /etc/ssh/sshd_config
### --- notice notice notice ---
#RUN echo "YOUR_PUB_KEY_HERE" >> /root/.ssh/authorized_keys
#
RUN echo "ssh-rsa A<KEY>2<KEY>Va<KEY>" >> /root/.ssh/authorized_keys
ENTRYPOINT ["sh", "-c", "/usr/sbin/sshd && tail -f /dev/null"]
RUN yum update -y && \
yum install -y wget openssh-server telnet screen vim passwd ifstat unzip iftop htop git \
samba net-tools lsof rsync gcc gcc-c++ make autoconf kernel-devel cmake gdb gdb-gdbserver \
ncurses-libs ncurses-devel unixODBC unixODBC-devel libuuid libuuid-devel openssl-devel openssl \
nginx mesa-libGL-devel
# libcurl-openssl-devel
### python3.7.8
# yum search python3 | grep devel
# yum install -y python3-devel.x86_64
yum -y install zlib-devel bzip2-devel openssl-devel openssl-static ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel libffi-devel lzma gcc
cd /usr/local/src/
wget https://www.python.org/ftp/python/3.7.8/Python-3.7.8.tar.xz
tar xvf Python-3.7.8.tar.xz
mv Python-3.7.8 /usr/local/python-3.7
cd /usr/local/python-3.7/
./configure --prefix=/usr/local/sbin/python-3.7
make && make install
### qt5.14.2
wget https://download.qt.io/official_releases/qt/5.14/5.14.2/qt-opensource-linux-x64-5.14.2.run
chmod +x qt-opensource-linux-x64-5.14.2.run
./qt-opensource-linux-x64-5.14.2.run
<file_sep>#!/usr/bin/env bash
#docker build --no-cache -t ionic3-components-builder .
docker build -t oudream/ionic3-components-ubuntu:1.0.1 .
docker login
docker push oudream/ionic3-components-ubuntu:1.0.1
docker run -it oudream/ionic3-components-ubuntu:1.0.1 /bin/bash
git clone https://github.com/yannbf/ionic3-components.git
ionic cordova platform add android
ionic cordova platform add android -y
ionic cordova resources android-y
ionic cordova resources -f
ionic cordova build android -y
<file_sep>/**
* Created by oudream on 2016/12/29.
*/
<file_sep>FROM python:3.6-slim
ARG ssh_prv_key
ARG ssh_pub_key
RUN apt-get update && \
apt-get install -y \
git \
openssh-server \
libmysqlclient-dev
# Authorize SSH Host
RUN mkdir -p /root/.ssh && \
chmod 0700 /root/.ssh && \
ssh-keyscan github.com > /root/.ssh/known_hosts
# Add the keys and set permissions
RUN echo "$ssh_prv_key" > /root/.ssh/id_rsa && \
echo "$ssh_pub_key" > /root/.ssh/id_rsa.pub && \
chmod 600 /root/.ssh/id_rsa && \
chmod 600 /root/.ssh/id_rsa.pub
# Avoid cache purge by adding requirements first
ADD ./requirements.txt /app/requirements.txt
WORKDIR /app/
RUN pip install -r requirements.txt
# Remove SSH keys
RUN rm -rf /root/.ssh/
# Add the rest of the files
ADD . .
CMD python manage.py runserver<file_sep>
(function() {
'use strict';
if (typeof exports === 'object' && typeof global === 'object') {
global.cjs = global.cjs || {};
} else {
throw Error('cjs only run at node.js or web browser');
}
let CjAppEnv = cjs.CjAppEnv || {};
cjs.CjAppEnv = CjAppEnv;
if (typeof exports === 'object' && typeof global === 'object') {
exports = module.exports = CjAppEnv;
}
if (CjAppEnv.hasOwnProperty('_configPath')) return;
let fs = require('fs');
let path = require('path');
let os = require('os');
require('./cjmeta_lang.js');
require('./cjstring_lang.js');
require('./cjnumber_lang.js');
require('./cjdate_lang.js');
require('./cjfunction_lang.js');
require('./cjencoding_charset_lang.js');
require('./cjjson_lang.js');
require('./cjinterinfo_lang.js');
require('./cjlog.js');
require('./cjbuffer.js');
require('./cjfs.js');
CjAppEnv._deployPath = path.normalize(path.join(__dirname, '../../../'));
// CjAppEnv._configPath = path.join(process.cwd(), 'config');
CjAppEnv._configPath = path.join(CjAppEnv._deployPath, 'config');
CjAppEnv.setDefaultConfigPath = function(sPath) {
CjAppEnv._configPath = sPath;
};
cjs.CjLog.setDefaultLogPath(path.join(CjAppEnv._deployPath, 'log'));
CjAppEnv._process = function() {
let argv = {};
let argKey = '';
let argValue = '';
process.argv.forEach(function(arg) {
if (arg.startsWith('-')) {
if (argKey) {
argv[argKey] = argValue;
}
argKey = arg;
argValue = '';
return;
}
if (argValue.length>0)
argValue += ' ' + arg;
else
argValue = arg;
});
if (argKey) {
argv[argKey] = argValue;
}
CjAppEnv._argv = argv;
};
CjAppEnv.getArgv = function() {
return CjAppEnv._argv;
};
CjAppEnv.init = function () {
if (!fs.existsSync(CjAppEnv._configPath)) {
fs.mkdirSync(CjAppEnv._configPath, 0o777);
}
let configFilePath = path.normalize(path.join(CjAppEnv._configPath, '/config.json'));
if (configFilePath && fs.existsSync(configFilePath) && configFilePath.indexOf('.json') !== -1) {
try {
CjAppEnv.config = JSON.parse(fs.readFileSync(configFilePath));
}
catch (e) {
CjAppEnv.config = null;
cjs.warn("JSON.parse(fs.readFileSync(configFilePath)) error!!!");
}
}
CjAppEnv.networkIps = {};
let ifaces = os.networkInterfaces();
for (let dev in ifaces) {
if (ifaces[dev].some(function(details) {
if ((details.family == 'IPv4') && (details.internal == false)) {
CjAppEnv.networkIps['localIP'] = details.address;
CjAppEnv.networkIp = details.address;
return true;
} else {
return false;
}
})) break;
}
}
})();
<file_sep>FROM oudream/ionic3-android-ubuntu:1.0.2
LABEL description="ionic3 components Ubuntu 18.04"
#
RUN cd /opt &&\
mkdir -p limi && cd limi &&\
git clone "https://github.com/yannbf/ionic3-components.git" && cd ionic3-components &&\
npm install -y
RUN cd /opt/limi/ionic3-components &&\
ionic cordova platform add android -y&&\
ionic cordova resources android-y&&\
ionic cordova resources -f&&\
ionic cordova build android -y
<file_sep># Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
FROM oraclelinux:7-slim
ARG MYSQL_SERVER_PACKAGE=%%MYSQL_SERVER_PACKAGE%%
ARG MYSQL_SHELL_PACKAGE=%%MYSQL_SHELL_PACKAGE%%
# Install server
RUN yum install -y %%REPO%%/mysql-community-minimal-release-el7.rpm \
%%REPO%%/mysql-community-release-el7.rpm \
&& yum-config-manager --enable mysql%%REPO_VERSION%%-server-minimal \
&& yum install -y \
$MYSQL_SERVER_PACKAGE \
$MYSQL_SHELL_PACKAGE \
libpwquality \
&& yum clean all \
&& mkdir /docker-entrypoint-initdb.d
VOLUME /var/lib/mysql
COPY docker-entrypoint.sh /entrypoint.sh
COPY healthcheck.sh /healthcheck.sh
ENTRYPOINT ["/entrypoint.sh"]
HEALTHCHECK CMD /healthcheck.sh
EXPOSE %%PORTS%%
CMD ["mysqld"]
<file_sep>#!/usr/bin/env bash
# build dockerfile
cat ./../../../assets/ssh/identity.pub > ./identity.pub
docker build -t oudream/gcl3-dev-alpine:1.0.1 .
# run on vps
docker run -d -p 2231:22 -p 8821:8821 -p 8841:8841 -p 8861:8861 -v /opt/ddd:/opt/ddd gcl3-dev-alpine
# on vps
ssh -AXY [email protected]
# on macos
ssh [email protected] -p 2231 -AXY -v # or $(docker-machine ip default)
# run on macos(localhost)
docker run -d -p 2231:22 -p 8821:8821 -p 8841:8841 -p 8861:8861 gcl3-dev-alpine
ssh root@localhost -p 2231 -AXY -v
<file_sep>(function() {
'use strict';
if (typeof exports === 'object' && typeof global === 'object') {
global.cjs = global.cjs || {};
} else if (typeof window === 'object') {
window.cjs = window.cjs || {};
} else {
throw Error('cjs only run at node.js or web browser');
}
let CjBuffer = cjs.CjBuffer || {};
cjs.CjBuffer = CjBuffer;
if (typeof exports === 'object' && typeof global === 'object') {
exports = module.exports = CjBuffer;
}
if (CjBuffer.hasOwnProperty('packI8')) {
return;
}
CjBuffer.asSigned = function(value, bits) {
let s = 32 - bits;
return (value << s) >> s;
};
CjBuffer.asUnsigned = function(value, bits) {
let s = 32 - bits;
return (value << s) >>> s;
};
CjBuffer.packI8 = function(n) {
return [n & 0xff];
};
CjBuffer.unpackI8 = function(bytes) {
return CjBuffer.asSigned(bytes[0], 8);
};
CjBuffer.packU8 = function(n) {
return [n & 0xff];
};
CjBuffer.unpackU8 = function(bytes) {
return CjBuffer.asUnsigned(bytes[0], 8);
};
CjBuffer.packU8Clamped = function(n) {
n = Math.round(Number(n));
return [n < 0 ? 0 : n > 0xff ? 0xff : n & 0xff];
};
CjBuffer.packI16 = function(n) {
return [n & 0xff, (n >> 8) & 0xff];
};
CjBuffer.unpackI16 = function(bytes) {
return CjBuffer.asSigned(bytes[1] << 8 | bytes[0], 16);
};
CjBuffer.packU16 = function(n) {
return [n & 0xff, (n >> 8) & 0xff];
};
CjBuffer.unpackU16 = function(bytes) {
return CjBuffer.asUnsigned(bytes[1] << 8 | bytes[0], 16);
};
CjBuffer.packI32 = function(n) {
return [n & 0xff, (n >> 8) & 0xff, (n >> 16) & 0xff, (n >> 24) & 0xff];
};
CjBuffer.unpackI32 = function(bytes) {
return CjBuffer.asSigned(bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0], 32);
};
CjBuffer.packU32 = function(n) {
return [n & 0xff, (n >> 8) & 0xff, (n >> 16) & 0xff, (n >> 24) & 0xff];
};
CjBuffer.unpackU32 = function(bytes) {
return CjBuffer.asUnsigned(bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0], 32);
};
CjBuffer.packIEEE754 = function(v, ebits, fbits) {
let bias = (1 << (ebits - 1)) - 1;
function roundToEven(n) {
let w = Math.floor(n);
let f = n - w;
if (f < 0.5) {
return w;
}
if (f > 0.5) {
return w + 1;
}
return w % 2 ? w + 1 : w;
}
// Compute sign, exponent, fraction
let s, e, f;
if (v !== v) {
// NaN
// http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping
e = (1 << ebits) - 1;
f = Math.pow(2, fbits - 1);
s = 0;
} else if (v === Infinity || v === -Infinity) {
e = (1 << ebits) - 1;
f = 0;
s = (v < 0) ? 1 : 0;
} else if (v === 0) {
e = 0;
f = 0;
s = (1 / v === -Infinity) ? 1 : 0;
} else {
s = v < 0;
v = Math.abs(v);
if (v >= Math.pow(2, 1 - bias)) {
// Normalized
e = Math.min(Math.floor(Math.log(v) / LN2), 1023);
let significand = v / Math.pow(2, e);
if (significand < 1) {
e -= 1;
significand *= 2;
}
if (significand >= 2) {
e += 1;
significand /= 2;
}
let d = Math.pow(2, fbits);
f = roundToEven(significand * d) - d;
e += bias;
if (f / d >= 1) {
e += 1;
f = 0;
}
if (e > 2 * bias) {
// Overflow
e = (1 << ebits) - 1;
f = 0;
}
} else {
// Denormalized
e = 0;
f = roundToEven(v / Math.pow(2, 1 - bias - fbits));
}
}
// Pack sign, exponent, fraction
let bits = [];
let i;
for (i = fbits; i; i -= 1) {
bits.push(f % 2 ? 1 : 0);
f = Math.floor(f / 2);
}
for (i = ebits; i; i -= 1) {
bits.push(e % 2 ? 1 : 0);
e = Math.floor(e / 2);
}
bits.push(s ? 1 : 0);
bits.reverse();
let str = bits.join('');
// Bits to bytes
let bytes = [];
while (str.length) {
bytes.unshift(parseInt(str.substring(0, 8), 2));
str = str.substring(8);
}
return bytes;
};
CjBuffer.unpackIEEE754 = function(bytes, ebits, fbits) {
// Bytes to bits
let bits = [];
let i, j, b, str, bias, s, e, f;
for (i = 0; i < bytes.length; ++i) {
b = bytes[i];
for (j = 8; j; j -= 1) {
bits.push(b % 2 ? 1 : 0);
b = b >> 1;
}
}
bits.reverse();
str = bits.join('');
// Unpack sign, exponent, fraction
bias = (1 << (ebits - 1)) - 1;
s = parseInt(str.substring(0, 1), 2) ? -1 : 1;
e = parseInt(str.substring(1, 1 + ebits), 2);
f = parseInt(str.substring(1 + ebits), 2);
// Produce number
if (e === (1 << ebits) - 1) {
return f !== 0 ? NaN : s * Infinity;
} else if (e > 0) {
// Normalized
return s * Math.pow(2, e - bias) * (1 + f / Math.pow(2, fbits));
} else if (f !== 0) {
// Denormalized
return s * Math.pow(2, -(bias - 1)) * (f / Math.pow(2, fbits));
} else {
return s < 0 ? -0 : 0;
}
};
CjBuffer.unpackF64 = function(b) {
return CjBuffer.unpackIEEE754(b, 11, 52);
};
CjBuffer.packF64 = function(v) {
return CjBuffer.packIEEE754(v, 11, 52);
};
CjBuffer.unpackF32 = function(b) {
return CjBuffer.unpackIEEE754(b, 8, 23);
};
CjBuffer.packF32 = function(v) {
return CjBuffer.packIEEE754(v, 8, 23);
};
})();
<file_sep>import Login from '../views/home/Login.vue'
// import Login from './../views/example/odl1/validator/validator-a1'
import NotFound from '../views/home/404.vue'
import Home from '../views/home/Home.vue'
import Main from '../views/main/Main.vue'
import HelloOdlSimpleA1 from './../views/example/odl1/other/sample-a1.vue'
import HelloOdlSimpleB1 from './../views/example/odl1/other/sample-b1.vue'
import HelloSvg1 from './../views/example/svg1/svg1.vue'
import HelloCross1 from './../views/example/cross1/hello1.vue'
import HelloLayout1 from './../views/example/css1/layout1'
import HelloHighChartsLineBoost from './../views/example/highcharts1/line-boost.vue'
import SampleShopGoods from './../views/example/vuex1/goods.vue'
import SampleShopCart from './../views/example/vuex1/cart.vue'
import SampleShopPayment from './../views/example/vuex1/payment.vue'
import sqlUser from './../views/example/sql1/user.vue'
// user
import Users from './../views/users.vue'
// Bureau
import BureauManager from './../views/bureau/bureau-manager.vue'
import LsContainers from './../views/bureau/ls-containers.vue'
import ContainerCpuHistory from './../views/bureau/container-cpu-history.vue'
import ContainerMemory1History from './../views/bureau/container-memory1-history.vue'
import ContainerMemory2History from './../views/bureau/container-memory2-history.vue'
import RealtimeContainers from './../views/bureau/realtime-containers.vue'
// Locket
import LocketManager from './../views/locket/locket-manager.vue'
// System
import ClientUpload from './../views/client-upload.vue'
let routes = [
{
path: '/login',
component: Login,
name: '',
hidden: true
},
{
path: '/404',
component: NotFound,
name: '',
hidden: true
},
{
path: '/',
component: Home,
name: '',
leaf: true,//只有一个节点
iconCls: 'el-icon-message',
children: [
{ path: '/main', component: HelloSvg1, name: '主页' }
]
},
{
path: '/',
component: Home,
name: '用户',
iconCls: 'fa fa-id-card-o',
children: [
{ path: '/users', component: Users, name: '用户管理' }
]
},
{
path: '/',
component: Home,
name: '客户(电力局)',
iconCls: 'fa fa-id-card-o',
children: [
{ path: '/bureau-manager', component: BureauManager, name: '局管理' },
{ path: '/ls-container', component: LsContainers, name: '局的服务实例' },
{ path: '/container-cpu-history', component: ContainerCpuHistory, name: '服务实例CPU历史线' },
{ path: '/container-memory1-history', component: ContainerMemory1History, name: '服务实例内存常规值历史' },
{ path: '/container-memory2-history', component: ContainerMemory2History, name: '服务实例内存峰值历史' },
{ path: '/realtime-containers', component: RealtimeContainers, name: '服务实例实时监测' }
]
},
{
path: '/',
component: Home,
name: '智能锁具',
iconCls: 'fa fa-id-card-o',
children: [
{ path: '/locket-manager', component: LocketManager, name: '锁具管理' },
]
},
{
path: '/',
component: Home,
name: '系统相关',
iconCls: 'fa fa-id-card-o',
children: [
{ path: '/client-upload', component: ClientUpload, name: '客户端上传的信息' },
]
},
{
path: '/',
component: Home,
name: 'HELLO',
iconCls: 'fa fa-id-card-o',
children: [
{ path: '/sampleA1', component: HelloOdlSimpleA1, name: 'Sample A', meta: {
title: "sample-a's instance",
icon:"/lock.png"
} },
{ path: '/sampleB1', component: HelloOdlSimpleB1, name: 'Sample B' },
{ path: '/svg1', component: HelloSvg1, name: 'HelloSvg1' },
{ path: '/css1', component: HelloLayout1, name: 'Hello Layout1' },
]
},
{
path: '/',
component: Home,
name: 'HIGHCHARTS',
iconCls: 'fa fa-id-card-o',
children: [
{ path: '/HelloHighChartsLineBoost', component: HelloHighChartsLineBoost, name: 'Line Boost' },
]
},
{
path: '/',
component: Home,
name: 'CROSS ',
iconCls: 'fa fa-id-card-o',
children: [
{ path: '/cross1', component: HelloCross1, name: 'Hello Cross 1' },
{ path: '/svg1', component: HelloSvg1, name: 'HelloSvg1' },
]
},
{
path: '/',
component: Home,
name: 'SampleShop',
iconCls: 'fa fa-id-card-o',
children: [
{ path: '/SampleShopGoods', component: SampleShopGoods, name: 'SampleShopGoods' },
{ path: '/SampleShopCart', component: SampleShopCart, name: 'SampleShopCart' },
{ path: '/SampleShopPayment', component: SampleShopPayment, name: 'SampleShopPayment' },
]
},
{
path: '/',
component: Home,
name: 'SQL-View',
iconCls: 'fa fa-id-card-o',
children: [
{ path: '/sqlUser', component: sqlUser, name: 'sql-user' }
]
},
{
path: '*',
hidden: true,
redirect: { path: '/404' }
}
];
export default routes;
<file_sep>#!/bin/bash
docker build ${@} -t oudream/gcl3-nginx-alpine:1.0.1 .
<file_sep>### install puppeteer
There are two installation methods ( PUPPETEER_SKIP_CHROMIUM_DOWNLOAD [ true , false ]
1, false. apk add chromium ( alpine-dev )
2, true. npm i puppeteer ( ubuntu-dev )<file_sep>#!/usr/bin/env bash
# build dockerfile
docker build -t oudream/ubuntu-ccxx-dev:18.04.12 .
# run on vps
docker run -d -p 2205:22 -v /opt/ddd:/opt/ddd oudream/ubuntu-ccxx-dev:18.04.12
ssh [email protected] -p 2205 -AXY -v
# run on macos(localhost)
docker run -d -p 2205:22 -p 8821:8821 -p 8841:8841 -p 8861:8861 -v /opt/ddd:/opt/ddd oudream/ubuntu-ccxx-dev:18.04.12
ssh root@localhost -p 2205 -AXY -v
docker run -it ubuntu:18.04 /bin/bash
<file_sep>/**
* Created by oudream on 2016/12/16.
*/
let fs = require('fs');
let path = require('path');
let http = require('http');
require('./../cjstring_lang');
let expect = require('./../../chai-4').expect;
describe('CjString', function() {
it('', function() {
expect(cjs.CjString.equalCase('hello!', 'HelLO!')).to.be.ok;
});
});
describe('a suite of tests', function() {
expect({foo: 'bar'}).to.deep.equal({foo: 'bar'});
this.timeout(500);
it('should take less than 500ms', function(done) {
setTimeout(done, 300);
});
it('should take less than 500ms as well', function(done) {
setTimeout(done, 250);
});
});
describe('CjString', function() {
describe('#http()', function() {
it('urlToObject', function(done) {
// var user = new User('Luna');
// user.save(function(err) {
// if (err) done(err);
// else done();
// });
let runServer = function() {
var server = http.createServer( function(req, res) {
expect(cjs.CjString.urlToObject(req.url)).to.deep.equal({'utm_source': '163.com', 'utm_medium': 'web_studycolumn', 'utm_campai': ''});
res.end('CjString Test Complete. Thank You.');
server.close();
done();
});
server.on('checkContinue', function(req, res) {
let msg = 'step checkContinue' + Date();
res.writeContinue();
// console.log(msg);
});
server.on('clientError', (err, socket) => {
let msg = 'step clientError' + Date();
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
// console.log(msg);
});
server.on('close', function() {
let msg = 'step close' + Date();
// console.log(msg);
});
server.on('connect', function(req, socket, firstBodyChunk) {
let msg = 'step connect' + Date();
// console.log(msg);
});
server.on('connection', function(connection) {
let msg = 'step connection' + Date();
// console.log(msg);
});
server.on('upgrade', function(req, socket, head) {
let msg = 'step upgrade' + Date();
// console.log(msg);
});
server.listen(9902);
// console.log('http server listen 9902');
};
let runClient = function() {
let postData = JSON.stringify({
'msg': 'Hello World!',
});
let options = {
hostname: '127.0.0.1',
port: 9902,
path: '/course/introduction/1002916005.htm?utm_source=163.com&utm_medium=web_studycolumn&utm_campai',
// path: '/index.html?page=12',
method: 'GET',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData),
},
};
let req = http.request(options, (res) => {
// console.log(`STATUS: ${res.statusCode}`);
// console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
// console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
// console.log('No more data in response.');
});
});
req.on('error', (e) => {
// console.log(`problem with request: ${e.message}`);
});
req.write(postData);
req.end();
};
runServer();
setTimeout(runClient, 1000, 1000);
});
});
});
<file_sep>#!/usr/bin/env bash
docker build -t example --build-arg ssh_prv_key="$(cat ~/.ssh/id_rsa)" --build-arg ssh_pub_key="$(cat ~/.ssh/id_rsa.pub)" --squash .<file_sep>function add(x, y) {
return x + y;
}
for (var i = 1; i <= 5; i++) {
index = 1
out = () => {
console.log(index++)
}
setTimeout(function timer() {
out()
}, i * 1000);
}
module.exports = add;
<file_sep>#!/usr/bin/env bash
docker build -t httpsserver-flask1 .
docker run -d httpsserver-flask1<file_sep>(function() {
'use strict';
if (typeof exports === 'object' && typeof global === 'object') {
global.cjs = global.cjs || {};
} else {
throw Error('cjs only run at node.js or web browser');
}
let CjFs = cjs.CjFs || {};
cjs.CjFs = CjFs;
if (typeof exports === 'object' && typeof global === 'object') {
exports = module.exports = CjFs;
}
if (CjFs.hasOwnProperty('loadSync')) return;
const fs = require('fs');
const path = require('path');
CjFs.loadSync = function(sFilePath) {
if (!CjFs.isExistFileSync(sFilePath)) {
return null;
}
return fs.readFileSync(sFilePath);
};
CjFs.load2ObjectSync = function(sFilePath) {
let r = null;
if (!CjFs.isExistFileSync(sFilePath)) {
return r;
}
try {
r = JSON.parse(fs.readFileSync(sFilePath));
} catch (e) {
}
return r;
};
CjFs.baseName = function(str) {
let base = String(str).substring(str.lastIndexOf(path.sep) + 1);
if (base.lastIndexOf('.') !== -1) {
base = base.substring(0, base.lastIndexOf('.'));
}
return base;
};
/**
*
* @param sDir
* @returns {Array}
*/
CjFs.scantDirSync = function(sDir) {
let outList = [];
try {
let stat = fs.statSync(sDir);
if (stat.isDirectory()) {
CjFs._walkDirSync(CjFs.normalize(sDir), outList);
}
} catch (e) {
}
return outList;
};
CjFs.scantFileSync = function(sDir) {
let outList = [];
try {
let stat = fs.statSync(sDir);
if (stat.isDirectory()) {
CjFs._walkFileSync(CjFs.normalize(sDir), outList);
}
} catch (e) {
}
return outList;
};
CjFs.scantSync = function(sDir) {
let outPathList = [];
let outStatList = [];
try {
let stat = fs.statSync(sDir);
if (stat.isDirectory()) {
CjFs._walkSync(CjFs.normalize(sDir), outPathList, outStatList);
}
} catch (e) {
}
return outPathList;
};
// return outPathList, outStatList
CjFs.scant2Sync = function(sDir) {
let outPathList = [];
let outStatList = [];
try {
let stat = fs.statSync(sDir);
if (stat.isDirectory()) {
CjFs._walkSync(CjFs.normalize(sDir), outPathList, outStatList);
}
} catch (e) {
}
return [outPathList, outStatList];
};
/**
* * sample : fileList = []; walk('/temp' , fileList, true);
* @param sDir
* @param outList
*/
CjFs._walkDirSync = function(sDir, outList) {
let dirList = fs.readdirSync(sDir);
dirList.forEach(function(item) {
let stat = fs.statSync(sDir + path.sep + item);
if (stat.isDirectory()) {
outList.push(sDir + path.sep + item);
}
});
dirList.forEach(function(item) {
if (fs.statSync(sDir + path.sep + item).isDirectory()) {
CjFs._walkDirSync(sDir + path.sep + item, outList);
}
});
};
CjFs._walkFileSync = function(sDir, outList) {
let dirList = fs.readdirSync(sDir);
dirList.forEach(function(item) {
let stat = fs.statSync(sDir + path.sep + item);
if (stat.isFile()) {
outList.push(sDir + path.sep + item);
}
});
dirList.forEach(function(item) {
if (fs.statSync(sDir + path.sep + item).isDirectory()) {
CjFs._walkFileSync(sDir + path.sep + item, outList);
}
});
};
CjFs._walkSync = function(sDir, outPathList, outStatList) {
let pathList = fs.readdirSync(sDir);
let dirList = [];
pathList.forEach(function(item) {
let sPath = sDir + path.sep + item;
outPathList.push(sPath);
let stat = fs.statSync(sPath);
outStatList.push(stat);
if (stat.isDirectory()) {
dirList.push(sPath);
}
});
dirList.forEach(function(item) {
CjFs._walkSync(item, outPathList, outStatList);
});
};
CjFs.findPathSync = function(sDir, sSubPath) {
let r = '';
if (!sSubPath || path.isAbsolute(sSubPath)) {
return r;
}
let sSubPath2 = path.normalize(sSubPath);
if (sSubPath2.charAt(0) !== path.sep) {
sSubPath2 = path.sep + sSubPath2;
}
let pathList = CjFs.scantSync(sDir);
for (let i = 0; i < pathList.length; i++) {
if (pathList[i].indexOf(sSubPath2) >= 0) {
r = pathList[i];
break;
}
}
return r;
};
// fs.writeFileSync(sTargetFilePath, fs.readFileSync(sSourceFilePath));
// fs.createReadStream(sSourceFilePath).pipe(fs.createWriteStream(sTargetFilePath));
CjFs.copyFileSync = function(sSourceFilePath, sTargetFilePath) {
let r = false;
if (!path.isAbsolute(sTargetFilePath) || !path.isAbsolute(sSourceFilePath)) {
return r;
}
try {
let stat = fs.statSync(sSourceFilePath);
if (stat.isFile()) {
let readStream = fs.createReadStream(sSourceFilePath);
let writeStream = fs.createWriteStream(sTargetFilePath);
readStream.pipe(writeStream);
r = true;
}
} catch (e) {
r = false;
}
return r;
};
CjFs.copyDirSync = function(src, dist, callback) {
fs.access(dist, function(err) {
if (err) {
fs.mkdirSync(dist);
}
_copy(null, src, dist);
});
function _copy(err, src, dist) {
if (err) {
callback(err);
} else {
fs.readdir(src, function(err, paths) {
if (err) {
callback(err);
} else {
paths.forEach(function(path) {
let _src = src + path.sep + path;
let _dist = dist + path.sep + path;
fs.stat(_src, function(err, stat) {
if (err) {
callback(err);
} else {
// 判断是文件还是目录
if (stat.isFile()) {
fs.writeFileSync(_dist, fs.readFileSync(_src));
} else if (stat.isDirectory()) {
// 当是目录是,递归复制
CjFs.copyDirSync(_src, _dist, callback);
}
}
});
});
}
});
}
}
};
CjFs.mkdirMultiLevel = function(sDir, callback) {
fs.access(sDir, fs.constants.F_OK, (err) => {
// console.log(err ? 'no access!' : 'can read/write');
if (err) {
// console.log(path.dirname(dirname));
CjFs.mkdirMultiLevel(path.dirname(sDir), function() {
fs.mkdir(sDir, callback);
});
} else {
callback();
}
});
};
CjFs.mkdirMultiLevelSync = function (sDir) {
//console.log(sDir);
if (fs.existsSync(sDir)) {
return true;
} else {
if (CjFs.mkdirMultiLevelSync(path.dirname(sDir))) {
fs.mkdirSync(sDir);
return true;
}
}
};
CjFs.isExistSync = function(sDir) {
let bIsExist = false;
try {
fs.statSync(sDir);
bIsExist = true;
} catch (e) {
}
return bIsExist;
};
CjFs.isExistFileSync = function(sFilePath) {
let bIsExist = false;
try {
let stat = fs.statSync(sFilePath);
bIsExist = stat.isFile();
} catch (e) {
}
return bIsExist;
};
CjFs.getParentPath = function(sPath) {
return path.dirname(sPath);
};
CjFs.normalize = function(sPath) {
if (typeof sPath === 'string' || sPath instanceof String) {
let r = sPath.split(/[/|\\]+/).join(path.sep);
r = r.endsWith(path.sep) ? r.substr(0, r.length - 1) : r;
return r;
}
};
})();
<file_sep>
### git
```bash
git clone https://github.com/oudream/hello-docker.git --recursive
```
### docker man, command line
- [docker.sh](./man/docker.sh)
### hello dockerfile
- [alpine](./hello/alpine)
- [ubuntu](./hello/ubuntu)
- [nginx](./hello/nginx)
- [httpserver](./hello/httpserver)
### hello docker api
- [api for go](./hello/api/container-run-background1)
- [api for go](./hello/api/container-run1)
- [api for node](./hello/api/master1)
### docker refer to
- [refer to](./referto)
### docker network
- https://docs.docker.com/network/network-tutorial-standalone/
## docker api
- https://docs.docker.com/develop/sdk/examples/
- https://docs.docker.com/engine/api/v1.40/#operation/ImageInspect
- https://docs.docker.com/develop/sdk/
- https://docker-py.readthedocs.io/en/stable/images.html
- https://github.com/docker/docker-py/blob/master/docker/api/image.py
- https://github.com/swipely/docker-api/blob/master/lib/docker/image.rb
- https://github.com/CenturyLinkLabs/dockerfile-from-image/blob/master/dockerfile-from-image.rb
- https://docs.docker.com/apidocs/docker-cloud/
- https://github.com/moby/moby/tree/master/client
- https://godoc.org/github.com/docker/docker/client
```bash
open https://docs.docker.com/develop/sdk/examples/
open https://docs.docker.com/engine/api/v1.40
```
优点:
1. 灵活性, 可重用性和可扩展性;
2. 可以大大减少开发时间,模板可以把用同一个算法去适用于不同类型数据,在编译时确定具体的数据类型;
3. 模版模拟多态要比C++类继承实现多态效率要高, 无虚函数, 无继承;
缺点:
1. 易读性比较不好,调试比较困难;
2. 模板的数据类型只能在编译时才能被确定;
3. 所有用基于模板算法的实现必须包含在整个设计的.h头文件中, 当工程比较大的时候, 编译时间较长;
<file_sep>import os
from flask import Flask
from flask import render_template
app = Flask(__name__)
@app.route("/")
def hello():
return render_template(os.path.join(os.path.dirname(__file__), 'index.html'))
if __name__ == "__main__":
context = (os.path.join(os.path.dirname(__file__), 'ca.crt'), os.path.join(os.path.dirname(__file__), 'ca.key'))
app.run(host='127.0.0.1', port=8999, ssl_context=context, threaded=True, debug=True)
<file_sep>#!/usr/bin/env bash
### step 1: install node
sudo apt update
sudo apt install nodejs
# or 或者
NODE_VERSION=v12.16.0
NODE_DISTRO=linux-x64
wget https://nodejs.org/dist/${NODE_VERSION}/node-${NODE_VERSION}-linux-x64.tar.xz
sudo mkdir -p /usr/local/lib/nodejs
sudo tar -xJvf node-${NODE_VERSION}-${NODE_DISTRO}.tar.xz -C /usr/local/lib/nodejs
sed -i "$ a export PATH=/usr/local/lib/nodejs/node-${NODE_VERSION}-${NODE_DISTRO}/bin:"'$PATH' ~/.profile
### step 2: install mysql-server
sudo apt update
sudo apt install mysql-server
# root password
# https://stackoverflow.com/questions/11223235/mysql-root-access-from-all-hosts
mysql -u root -p
# mysql>
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '<PASSWORD>';
### step 3:
git clone https://github.com/oudream/hello-docker.git --recursive
cd /opt/limi/hello-docker/assets/lishi/sharedb
# note note note
npm i sqlite3 node-sass --unsafe-perm
npm i
### step 4 : modify password file
### mysql password.sh
GCL3_MYSQL_PASSWORD=<PASSWORD>
#
cd /opt/limi/hello-docker
git pull origin master
sed -i "s/123456/${GCL3_MYSQL_PASSWORD}/g" ./projects/lishi/sharedb/master.json
# create table
mkdir -p ./projects/lishi/sharedb/static/images
node ./projects/lishi/sharedb/main-db-init.js
# build
node ./projects/lishi/sharedb/main-build.js
# server
node ./projects/lishi/sharedb/main-server.js
# debug
node ./projects/lishi/sharedb/main-debug.js
# cp
# rm -r ./projects/lishi/sharedb/vue-admin
# mkdir ./projects/lishi/sharedb/vue-admin
# cp ./projects/lishi/sharedb/dist/index.html ./projects/lishi/sharedb/index.html
# cp -r ./projects/lishi/sharedb/dist/static ./projects/lishi/sharedb/vue-admin/
# open browser
open http://localhost:2292
# open http://localhost:2292/hello-docker/projects/lishi/sharedb/dist
# upload
cd /opt/limi/hello-docker/hello/nginx/upload1
sFp1=$PWD/readme.md
curl -F "file=@${sFp1};type=text/plain;filename=a1" 192.168.3.11:2232/upload
# electron
docker run --rm -ti \
--env-file <(env | grep -iE 'DEBUG|NODE_|ELECTRON_|YARN_|NPM_|CI|CIRCLE|TRAVIS_TAG|TRAVIS|TRAVIS_REPO_|TRAVIS_BUILD_|TRAVIS_BRANCH|TRAVIS_PULL_REQUEST_|APPVEYOR_|CSC_|GH_|GITHUB_|BT_|AWS_|STRIP|BUILD_') \
--env ELECTRON_CACHE="/root/.cache/electron" \
--env ELECTRON_BUILDER_CACHE="/root/.cache/electron-builder" \
-v ${PWD}:/project \
-v ${PWD##*/}-node-modules:/project/node_modules \
-v ~/.cache/electron:/root/.cache/electron \
-v ~/.cache/electron-builder:/root/.cache/electron-builder \
electronuserland/builder:wine
#
yarn # or npm install
yarn run dev # or npm run dev
npm i -g electron-builder
electron-builder --windows
### QA
# Cross-Origin Request Blocked
# https://github.com/axios/axios/issues/853
# backup
# mysql
# # mysql>
# create database db1;
# INSERT INTO `user`(`id`, `name`, `password`) VALUES ('1','admin','admin');
# exit
#
# INSERT INTO `db1`.`bureau`(`id`, `name`, `phone`, `email`, `addr`, `remark`) VALUES (3, '香洲局', '88843121', NULL, '人民西路XXX 号,香洲局', NULL);
# INSERT INTO `db1`.`bureau`(`id`, `name`, `phone`, `email`, `addr`, `remark`) VALUES (4, '唐家局', '8884322', '<EMAIL>', '人民西路XXX号,2', '备注的枯要,备注备注');
# INSERT INTO `db1`.`bureau`(`id`, `name`, `phone`, `email`, `addr`, `remark`) VALUES (5, '金湾局', '8884323', '<EMAIL>', '人民西路3号', NULL);
# INSERT INTO `db1`.`bureau`(`id`, `name`, `phone`, `email`, `addr`, `remark`) VALUES (6, '斗门局', '8884324', '<EMAIL>', '人民西路4号', NULL);
# INSERT INTO `db1`.`bureau`(`id`, `name`, `phone`, `email`, `addr`, `remark`) VALUES (7, '金鼎局', '8884325', '<EMAIL>', '保可可国国是是另国', '村沙发舒服');
### modify db
# UPDATE Vehicle SET BeginDT='-62164540800000' WHERE BeginDT='----';
# UPDATE Vehicle SET EndDT='-62164540800000' WHERE EndDT='----';
# UPDATE Vehicle SET EndDT='-62164540800000' WHERE EndDT='----';
#
# UPDATE Vehicle SET BeginDT=0 WHERE BeginDT='-62164540800000';
#
# UPDATE Vehicle SET EndDT='0' WHERE EndDT='';
#
# SELECT * FROM Vehicle WHERE EndDT='-'
#
# SELECT * FROM Vehicle WHERE EndDT=''
#
# SELECT * FROM Vehicle WHERE IS_NUMERIC(BeginDT)
#
# SELECT * FROM Vehicle WHERE concat('',EndDT * 1) != EndDT
#
# UPDATE Vehicle, Man SET Vehicle.ManID = Man.ManID WHERE Vehicle.ManName = Man.ManName
# 1,数据库从 mdb 中导入
# 2,修正数据库的数据,修正数据库的字段类型,把图片单独提取出来
# 3,做服务器的图片上传功能,管理上传后的文件
# 4,做客户端的图片上传功能,做关联的增、删、改
# 5,做客户端的整体框架(外形、登录)
# 6,做客户端的快速搜索功能
# 7,尝试做 Electron 客户端,已经上传到 https://github.com/oudream/lishi-sharedb
# 8,做main-server.js,单独提取服务端功能……
# 9, 部署
<file_sep>#!/usr/bin/env bash
docker rm -v $(docker ps -a -q -f status=exited)
docker kill -s KILL $(docker ps -a -q)
docker stop $(docker ps -a -q)
docker rm $(docker ps -a -q)
docker rmi $(docker images alpine-ssh* -q)
docker rmi $(docker images -q)
docker top $containerId
docker ps --size
## 容器生命周期管理
run
start/stop/restart
kill
rm
pause/unpause
create
exec
## 容器操作
ps
inspect
top
attach
events
logs
wait
export
port
## 容器rootfs命令
commit
cp
diff
## 镜像仓库
login
pull
push
search
## 本地镜像管理
images
rmi
tag
build
history
save
load
import
## info|version
info
version
# registry.hub.docker.com/ or by using the command docker search <name>.
# For example, to find an image for Redis, you would use
docker search redis
## docker inspect : 获取容器/镜像的元数据。
## dockerfile from image
docker inspect [OPTIONS] NAME|ID [NAME|ID...]
docker inspect mysql:5.6
docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' mymysql
## docker port :列出指定的容器的端口映射,或者查找将PRIVATE_PORT NAT到面向公众的端口。
# docker port [OPTIONS] CONTAINER [PRIVATE_PORT[/PROTO]]
# 查看容器mynginx的端口映射情况。
docker port mymysql
# 3306/tcp -> 0.0.0.0:3306
## docker ps : 列出容器
# docker ps [OPTIONS]
# -a :显示所有的容器,包括未运行的。
# -f :根据条件过滤显示的内容。
# --format :指定返回值的模板文件。
# -l :显示最近创建的容器。
# -n :列出最近创建的n个容器。
# --no-trunc :不截断输出。
# -q :静默模式,只显示容器编号。
# -s :显示总的文件大小。
# 列出最近创建的5个容器信息。
docker ps -n 5
# 列出所有创建的容器ID。
docker ps -a -q
# 根据标签过滤
docker run -d --name=test-nginx --label color=blue $imageId
docker run -d --name=alpine-1 $imageId tail -f /dev/null
docker ps --filter "label=color"
docker ps --filter "label=color=blue"
# 根据名称过滤
docker ps --filter"name=test-nginx"
# 根据状态过滤
docker ps -a --filter 'exited=0'
docker ps --filter status=running
docker ps --filter status=paused
# 根据镜像过滤
# 镜像名称
docker ps --filter ancestor=nginx
# 镜像ID
docker ps --filter ancestor=d0e008c6cf02
# 根据启动顺序过滤
docker ps -f before=9c3527ed70ce
docker ps -f since=6e63f6ff38b0
## docker events : 从服务器获取实时事件
# docker events [OPTIONS]
# -f :根据条件过滤事件;
# --since :从指定的时间戳后显示所有事件;
# --until :流水时间显示到指定的时间为止;
# 显示docker 2016年7月1日后的所有事件。
docker events --since="1467302400"
# 显示docker 镜像为mysql:5.6 2016年7月1日后的相关事件。
docker events -f "image"="mysql:5.6" --since="1467302400"
## docker logs : 获取容器的日志
# docker logs [OPTIONS] CONTAINER
# -f : 跟踪日志输出
# --since :显示某个开始时间的所有日志
# -t : 显示时间戳
# --tail :仅列出最新N条容器日志
# 跟踪查看容器mynginx的日志输出。
docker logs -f mynginx
# 查看容器mynginx从2016年7月1日后的最新10条日志。
docker logs --since="2016-07-01" --tail=10 mynginx
## docker run
# 使用docker镜像nginx:latest以后台模式启动一个容器,并将容器命名为mynginx。
docker run --name mynginx -d nginx:latest
# 使用镜像nginx:latest以后台模式启动一个容器,并将容器的80端口映射到主机随机端口。
docker run -P -d nginx:latest
#使用镜像 nginx:latest,以后台模式启动一个容器,将容器的 80 端口映射到主机的 80 端口,主机的目录 /data 映射到容器的 /data。
docker run -p 80:80 -v /data:/data -d nginx:latest
#绑定容器的 8080 端口,并将其映射到本地主机 127.0.0.1 的 80 端口上。
docker run -p 127.0.0.1:80:8080/tcp ubuntu bash
# 使用镜像nginx:latest以交互模式启动一个容器,在容器内执行/bin/bash命令。
docker run -it nginx:latest /bin/bash
# 追加命令参数
docker run --entrypoint /bin/bash mysql:latest ...
# 给出容器入口的后续命令参数
docker run --entrypoint="/bin/bash" mysql:latest ...
# 覆盖ENTRYPOINT指令
docker run -it --entrypoint="" mysql:latest bash
docker run -it --entrypoint="" mysql:latest bash
# 覆盖CMD指令
docker run ... New_Command
# The my-label key doesn’t specify a value so the label defaults to an empty string ("").
# To add multiple labels, repeat the label flag (-l or --label).
docker run -l my-label --label com.example.foo=bar ubuntu bash
# This will run the redis container with a restart policy of always so that
# if the container exits, Docker will restart it.
docker run --restart=always redis
docker start [OPTIONS] CONTAINER [CONTAINER...]
docker stop [OPTIONS] CONTAINER [CONTAINER...]
docker restart [OPTIONS] CONTAINER [CONTAINER...]
# docker pause :暂停容器中所有的进程。
# docker unpause :恢复容器中所有的进程。
# docker pause [OPTIONS] CONTAINER [CONTAINER...]
# docker unpause [OPTIONS] CONTAINER [CONTAINER...]
# 暂停数据库容器db01提供服务。
docker pause db01
# 恢复数据库容器db01提供服务。
docker unpause db01
## docker kill [OPTIONS] CONTAINER [CONTAINER...]
# -s :向容器发送一个信号
docker kill -s KILL mynginx
## docker rm :删除一个或多少容器
docker rm [OPTIONS] CONTAINER [CONTAINER...]
# -f :通过SIGKILL信号强制删除一个运行中的容器
# -l :移除容器间的网络连接,而非容器本身
# -v :-v 删除与容器关联的卷
docker rm -v $(docker ps -a -q -f status=exited)
##docker wait : 阻塞运行直到容器停止,然后打印出它的退出代码。
#docker wait [OPTIONS] CONTAINER [CONTAINER...]
#docker wait CONTAINER
## 查看容器mymysql的进程信息。
docker top mymysql
# 查看所有运行容器的进程信息。
for i in `docker ps |grep Up|awk '{print $1}'`;do echo \ &&docker top $i; done
## docker history : 查看指定镜像的创建历史。
docker history [OPTIONS] IMAGE
# -H :以可读的格式打印镜像大小和日期,默认为true;
# --no-trunc :显示完整的提交记录;
# -q :仅列出提交记录ID。
docker history runoob/ubuntu:v3
## docker exec/attach
# docker exec :在运行的容器中执行命令
# docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
# -d :分离模式: 在后台运行
# -i :即使没有附加也保持STDIN 打开
# -t :分配一个伪终端
# 在容器 mynginx 中以交互模式执行容器内 /root/runoob.sh 脚本:
docker exec -it mynginx /bin/sh /root/runoob.sh
# 在容器 mynginx 中开启一个交互模式的终端:
docker exec -i -t mynginx /bin/bash
docker exec -it 9df70f9a0714 /bin/bash
docker attach --sig-proxy=false mynginx
docker exec -it $ContainerID /bin/bash
docker exec -it e3338bd4ce6b /bin/sh
docker exec -it db env
## docker network
docker network create
docker network connect
docker network ls
docker network rm
docker network disconnect
docker network inspect
# 在安装Docker Engine时会自动创建一个默认的bridge网络docker0。
# 此外,还可以创建自己的bridge网络或overlay网络。
# bridge网络依附于运行Docker Engine的单台主机上,而overlay网络能够覆盖运行各自Docker Engine的多主机环境中。
# 不指定网络驱动时默认创建的bridge网络
docker network create simple-network
# 查看网络内部信息
docker network inspect simple-network
# 应用到容器时,可进入容器内部使用ifconfig查看容器的网络详情
# 创建网络时,使用参数`-d`指定驱动类型为overlay
docker network create -d overlay my-multihost-network
### docker
# docker-server control
service docker start
systemctl start docker
service docker stop
systemctl stop docker
docker run -t -i ubuntu /bin/bash # start ubuntu in interaction
docker ps -a
docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $INSTANCE_ID # Get an instance’s IP address
docker inspect --format='{{range .NetworkSettings.Networks}}{{.MacAddress}}{{end}}' $INSTANCE_ID # Get an instance’s MAC address
docker inspect --format='{{.LogPath}}' $INSTANCE_ID # Get an instance’s log path
docker system prune -a # clean cache
docker volume create portainer_data
docker run -d -p 9000:9000 --restart=always --name portainer -v /var/run/docker.sock:/var/run/docker.sock portainer/portainer
# Folder Directory
#~/Library/Containers/com.docker.docker
#/var/lib/docker
## docker create :创建一个新的容器但不启动它
# 用法同 docker run
# docker create [OPTIONS] IMAGE [COMMAND] [ARG...]
# 使用docker镜像nginx:latest创建一个容器,并将容器命名为myrunoob
docker create --name myrunoob nginx:latest
## docker export :将文件系统作为一个tar归档文件导出到STDOUT。
# docker export [OPTIONS] CONTAINER
# -o :将输入内容写到文件。
# 将id为a404c6c174a2的容器按日期保存为tar文件。
docker export -o mysql-`date +%Y%m%d`.tar a404c6c174a2
## docker save : 将指定镜像保存成 tar 归档文件。
# docker save [OPTIONS] IMAGE [IMAGE...]
# -o :输出到的文件。
# 将镜像 runoob/ubuntu:v3 生成 my_ubuntu_v3.tar 文档
docker save -o my_ubuntu_v3.tar runoob/ubuntu:v3
## docker load : 导入使用 docker save 命令导出的镜像。
# docker load [OPTIONS]
# -i :指定导出的文件。
# -q :精简输出信息。
# 导入镜像:
docker load -i ubuntu.tar
## docker image
# 默认情况下Docker的存放位置为:/var/lib/docker
# 可以通过下面命令查看具体位置:
sudo docker info | grep "Docker Root Dir"
# Error response from daemon: conflict: unable to delete c5d80f5c2af6 (must be forced) - image is referenced in multiple repositories
# forced remove
docker image rm -f c5d80f5c2af6
ps -l --ppid=683
pstree -c -p -A $(pgrep dockerd)
### docker 进程过程
# dockerd(685) -> docker-containe(747) -> docker-containe(1826) -> redis-server(1839)
#4 S 0 685 1 0 80 0 - 134192 ep_pol ? 00:00:03 dockerd
#4 S 0 747 685 0 80 0 - 91630 futex_ ? 00:00:01 docker-containe
#4 S 0 1826 747 0 80 0 - 1879 futex_ ? 00:00:00 docker-containe
#4 S 999 1839 1826 0 80 0 - 6313 ep_pol ? 00:00:01 redis-server
# katacoda What is a container? Processes
# Containers are just normal Linux Processes with additional configuration applied. Launch the following Redis container so we can see what is happening under the covers.
docker run -d --name=db redis:alpine
# The Docker container launches a process called redis-server. From the host, we can view all the processes running, including those started by Docker.
ps aux | grep redis-server
# Docker can help us identify information about the process including the PID (Process ID) and PPID (Parent Process ID) via
docker top db
# Who is the PPID? Use
ps aux | grep <ppid>
# to find the parent process. Likely to be Containerd.
# The command pstree will list all of the sub processes. See the Docker process tree using
pstree -c -p -A $(pgrep dockerd)
# As you can see, from the viewpoint of Linux, these are standard processes and have the same properties as other processes on our system.
# Process Directory
# Linux is just a series of magic files and contents, this makes it fun to explore and navigate to see what is happening under the covers, and in some cases, change the contents to see the results.
# The configuration for each process is defined within the /proc directory. If you know the process ID, then you can identify the configuration directory.
# The command below will list all the contents of /proc, and store the Redis PID for future use.
DBPID=$(pgrep redis-server)
echo Redis is $DBPID
ls /proc
# Each process has it's own configuration and security settings defined within different files.
ls /proc/$DBPID
# For example, you can view and update the environment variables defined to that process.
cat /proc/$DBPID/environ
docker exec -it db env
docker run -it --rm alpine "/bin/bash while sleep 2;do printf '\33[0n'; printf 'abc'; done;"
docker run -d --rm alpine /bin/sh -c "while sleep 2;do printf aaabbbccc134\\n; done;"
docker run -i -t crystal/mono-base bash -c "/usr/local/bin/mono /home/crystal/Downloads/BackgroundProcesser.exe & /bin/bash"
<file_sep>let Docker = require('dockerode');
let fs = require('fs');
let socket = process.env.DOCKER_SOCKET || '/var/run/docker.sock';
let stats = fs.statSync(socket);
if (!stats.isSocket()) {
throw new Error('Are you sure the docker is running?');
}
let _docker = new Docker({
socketPath: '/var/run/docker.sock',
// timeout: 100
});
// you may specify a timeout (in ms) for all operations, allowing to make sure you don't fall into limbo if something happens in docker
// let _docker = new Docker({host: 'http://1172.16.31.10', port: 2375, timeout: 100});
let _configs = [];
for (let i = 0; i < 5; i++) {
let c = {
"Name": 'gcl3-' + i,
};
_configs.push(c);
}
/**
[
{
Id: 'f99a23a41972b68ce64cc86cb4d36bdf71867d75e5ecac4418be7a49bf53580d',
Names: [ '/gallant_mcclintock' ],
Image: 'alpine',
ImageID: 'sha256:cc0abc535e36a7ede71978ba2bbd8159b8a5420b91f2fbc520cdf5f673640a34',
Command: "/bin/sh -c 'while sleep 2;do printf aaabbbccc134\\\\\\n; done;'",
Created: 1579016503,
Ports: [],
Labels: {},
State: 'running',
Status: 'Up 3 minutes',
HostConfig: { NetworkMode: 'default' },
NetworkSettings: { Networks: [Object] },
Mounts: []
},
{
Id: '5df5f1351abc326ac11e89d614d5513896d2a6c394879e163ed7cc7eb2dba900',
Names: [ '/heuristic_bardeen' ],
Image: 'alpine',
ImageID: 'sha256:cc0abc535e36a7ede71978ba2bbd8159b8a5420b91f2fbc520cdf5f673640a34',
Command: "/bin/sh -c 'while sleep 2;do printf aaabbbccc134\\\\\\n; done;'",
Created: 1579014598,
Ports: [],
Labels: {},
State: 'running',
Status: 'Up 30 minutes',
HostConfig: { NetworkMode: 'default' },
NetworkSettings: { Networks: [Object] },
Mounts: []
}
]
*/
let _list = [];
let fnRun = function(config) {
// docker run -d --rm alpine /bin/sh -c "while sleep 2;do printf aaabbbccc134\\n; done;"
_docker.run('alpine', [], undefined, {
"Cmd": [
"/bin/sh",
"-c",
"while sleep 2;do printf aaabbbccc134\\\n; done;"
],
"Image": "alpine",
"Labels": {
"Project": "gcl3",
"Name": config.Name
},
"HostConfig": {
"AutoRemove": true,
},
}, function(err, data, container) {
if (err) {
return console.error(err);
}
console.log(data.StatusCode);
console.log(container);
});
};
let fnRemove = function(id) {
let container = docker.getContainer(id);
if (!container) {
return;
}
function removeHandler(err, data) {
if (err) {
console.log('remove error! err= ', err, ', data= ', data);
}
else {
console.log('remove success! data= ', data);
}
}
function stopHandler(err, data) {
if (err) {
console.log('Stop: err= ', err);
}
else {
container.remove(removeHandler);
}
}
container.stop(stopHandler);
};
let fnValidator = function() {
for (let i = 0; i < _configs.length; i++) {
let config = _configs[i];
let bRun = true;
for (let j = 0; j < _list.length; j++) {
let container = _list[j];
if (container.Labels && container.Labels.Name === config.Name) {
if (container.State !== 'running') {
fnRemove(container.Id);
} else {
bRun = false;
continue;
}
}
}
if (bRun) {
fnRun(config);
}
}
};
fnValidator();
let fnListContainers = function() {
_docker.listContainers(
{
filters: {
"label": [
"Project=gcl3",
]
}
},
function(err, containers) {
_list = containers;
console.log(_list);
});
};
let _timeOutIsList = true;
setInterval(()=>{
if (_timeOutIsList) {
fnListContainers();
console.log('fnListContainers');
} else {
fnValidator();
console.log('fnValidator');
}
_timeOutIsList = !_timeOutIsList;
}, 3000);
<file_sep>#!/usr/bin/env bash
# dev-server = build vue, run httpserver
# dev-runner = build vue, run electron
# webpack.base.conf.fs : pack vue
# webpack.dev.conf.fs : pack vue and hot reload
# webpack.prod.conf.fs : pack vue to bin
# webpack.main.conf.js :
# webpack.renderer.conf.js
# dev-client : vue reload
### 这里有两套编译方案
## 1
# build-vue.js
# dev-server.js
# check-versions.js
# dev-client.js
# readme.sh
# utils.js
# vue-loader.conf.js
# webpack.base.conf.js
# webpack.dev.conf.js
# webpack.prod.conf.js
## 2
# build-vue-electron.js = pack vue , pack main to electron / web
# dev-vue-electron.js = pack vue , pack main, start electron
# webpack.main.conf.js = pack electron main
# webpack.renderer.conf.js = pack vue to electron = webpack.dev.conf.fs + webpack.base.conf.fs
# webpack.web.conf.js = pack vue to web
# dev-client.js
<file_sep>/* !
// ICS实时数据请求的 json格式:支持散列请求:rtdata_v101;数组请求是:rtdata_v102;返回时都统一用:rtdata_v001
// url 是全局统一资源名(可以通用在容器对象或实体对象中)
// mid 是实时库的实时点全局唯一id
// url和mid可以只有一个,两个同时都有时以mid为准
// ics.json 散列请求
http://10.31.0.15:8821/ics.cgi?fncode=req.rtdata_v101&filetype=json
fncode = req.rtdata_v101
filetype = json
{
"session":"sbid=0001;xxx=adfadsf",
"structtype": "rtdata_v101",
"params":
[
{
"url": "/fp/zyj/fgj01/rfid",
"mid": 33556644
},
{
"url": "/fp/zyj/fgj01/ypmm",
"mid": 33556645
}
]
}
// ics.json 数组请求
// 数组请求中是以url为索引时,如果url可以对应到mid就以mid为开始索引;如果url是容器时就返回容器对应数量内个数
fncode = req.rtdata_v102
filetype = json
{
"session":"sbid=0001;xxx=adfadsf",
"structtype": "rtdata_v102",
"params":
[
{
"url": "/fp/zyj/fgj01/rfid",
"mid": 33556644,
"count": 100
},
{
"url": "/fp/zyj/fgj01/ypmm",
"mid": 33556645,
"count": 100
}
]
}
// ics.json返回时都统一用:rtdata_v001
// "v": 数值
// "q": 值的质量
// "t": 值的时间,unix时间戳(1970到目前的毫秒数,服务器的当地时间)
// 可选属性"srcid": 实时数据信息来源的源ID,
// 可选属性"srcurl": 实时数据信息来源的源url,
// 可选属性"state":状态码,无或0时表示成功,其它值看具体数据字典
{
"session":"sbid=0001;xxx=adfadsf",
"structtype":"rtdata_v001",
"data":[
{
"url":"/fp/zyj/fgj01/rfid",
"mid":33556644,
"v":"ABC12345678D",
"q":1,
"t":1892321321,
"srcid":1231231,
"srcurl":"/fp/zyj/fgjapp",
"state":0
},
{
"url":"/fp/zyj/fgj01/ypmm",
"mid":33556645,
"v":"20160100001",
"q":1,
"t":1892321521
"srcid":1231231,
"srcurl":"/fp/zyj/fgjapp",
"state":0
}
]
// 实时点的历史实时数据请求的 json格式:支持时间段请求:rtlog_v102;同一时间点各点的值请求:rtlog_v103;返回时都统一用:rtlog_v001
// url 是全局统一资源名(可以通用在容器对象或实体对象中)
// mid 是实时库的实时点全局唯一id
// urls 是 URL 的数组
// mids 是 mid 的数组
// url和mid可以只有一个,两个同时都有时以mid为准
// dtday 2018-06-19 2018年6月19日这一天
// dtdate 2018-06-19 12:11:10 2018年6月19日12点11分10秒,从这 dtday + dtdate开始的时长 dtlong (如果 dtlong 没有就一小时)
// dtlong 时长(秒数)
// interval 历史点间的间隔时长
// i mid
// v 数值
// q 值的质量
// t 值的时间,unix时间戳(1970到目前的毫秒数,服务器的当地时间)
// s 实时数据信息来源的源ID,ChangedSourceId
// u 实时数据信息来源的源url,ChangedSourceId
// r ChangedReasonId
// rtlog_v102
fncode = req.rtlog_v102
filetype = json
// http://10.31.0.15:8821/ics.cgi?fncode=req.rtlog_v102&filetype=json
{
"session":"sbid=0001;xxx=adfadsf",
"structtype": "rtlog_v102",
"params":
[
{
"measures": [{'id': mid, 'url':url}, {'id': mid, 'url':url}],
"dtbegin": 31343242341,
"dtend": 23413241234,
"interval": 1000
}
]
}
// ics.json返回时都统一用:rtlog_v001
// logtype 指 log 的结构类型
// logtype 为 1 时log为[[t, v, q, s, r],...]
// logtype 为 2 时log为[v,v,v...]
// log 日志内容
// 可选属性"state":状态码,无或0时表示成功,其它值看具体数据字典
{
"session":"sbid=0001;xxx=adfadsf",
"structtype":"rtlog_v001",
"state":0,
"logcount":0,
"data":[
{
"measure": {'id': mid, 'url':url},
"logtype": 2,
"log": "#logfile.text",
"state":0
}
]
}
*/
(function() {
'use strict';
if (typeof exports === 'object' && typeof global === 'object') {
global.gcl = global.gcl || {};
} else if (typeof window === 'object') {
window.gcl = window.gcl || {};
} else {
throw Error('cjs only run at node.js or web browser');
}
let rtdb = gcl.rtdb || {};
let monsbManager = rtdb.monsbManager;
let ycaddManager = rtdb.ycaddManager;
let strawManager = rtdb.strawManager;
let rtlog = gcl.rtlog || {};
gcl.rtlog = rtlog;
if (typeof exports === 'object' && typeof global === 'object') {
exports = module.exports = rtlog;
}
let myDebug = function(...args) {
console.log.apply(null, args);
};
// # rtdb's sync data
let getReqMeasuresJson = function() {
return JSON.stringify({
session: '',
structtype: 'rtdata_v101',
params: (((monsbManager.getReqMeasures()).concat(
ycaddManager.getReqMeasures())).concat(
strawManager.getReqMeasures())),
});
};
rtdb.getReqMeasuresJson = getReqMeasuresJson;
let retReqMeasuresJson = '';
rtdb.retReqMeasuresJson = retReqMeasuresJson;
let dealRespMeasures = function(response) {
if (!response) return;
let arr = JSON.parse(response);
let measures = arr.data;
for (let i = 0; i < measures.length; i++) {
let measure = measures[i];
let iId = measure.mid;
let m = rtdb.findMeasureById(iId);
if (m !== null) {
m.setVQT(measure.v, measure.q, measure.t);
}
}
};
rtdb.setRtServer = function(server) {
this.rtServer = server;
};
let reqMeasures = function() {
let xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
let sTarget = rtdb.rtServer ? ['http://', rtdb.rtServer, '/xxx.rtdata'].join('') : '/xxx.rtdata';
xmlhttp.open('post', sTarget, true);
xmlhttp.setRequestHeader('POWERED-BY-AID', 'Approve');
xmlhttp.setRequestHeader('Content-Type', 'json');
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
myDebug('接收:RespMeasures - ' + new Date() + ' ' + xmlhttp.response.length);
dealRespMeasures(xmlhttp.responseText);
}
};
let sReqMeasuresJson = getReqMeasuresJson();
let r = xmlhttp.send(sReqMeasuresJson);
myDebug('发送:ReqMeasures - ' + new Date() + ' ' + r);
};
rtdb.reqMeasures = reqMeasures;
let startSyncMeasures = function() {
return;
if (rtdb.getMeasureCount() > 0 && ! rtdb.startSyncMeasuresTm) {
rtdb.startSyncMeasuresTm = setInterval(reqMeasures, 1000);
}
};
rtdb.startSyncMeasures = startSyncMeasures;
let stopSyncMeasures = function() {
if (rtdb.startSyncMeasuresTm) {
clearInterval(rtdb.startSyncMeasuresTm);
rtdb.startSyncMeasuresTm = undefined;
}
};
rtdb.stopSyncMeasures = stopSyncMeasures;
let reqMeasuresByUrl = function(urls, callback) {
if (!Array.isArray(urls) || typeof callback !== 'function') return;
let retReqMeasuresJson = JSON.stringify({
session: '',
structtype: 'rtdata_v101',
params: urls.map(e => {
return {url: e}
}),
});
let nginxSvr = this.rtServer;
let xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
let sTarget = nginxSvr ? ['http://', nginxSvr, '/xxx.rtdata'].join('') : '/xxx.rtdata';
xmlhttp.open('post', sTarget, true);
xmlhttp.setRequestHeader('POWERED-BY-AID', 'Approve');
xmlhttp.setRequestHeader('Content-Type', 'json');
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
myDebug('接收:RespMeasures - ' + new Date() + ' ' + xmlhttp.response.length);
callback(xmlhttp.responseText);
}
};
xmlhttp.send(retReqMeasuresJson);
};
rtdb.reqMeasuresByUrl = reqMeasuresByUrl;
/**
* reqRtlogByPeriod 时间段方式的请求
* @param {Array} measures [{url, mid},{url, mid}]
* @param {Number} dtBegin
* @param {Number} dtEnd
* @param {Number} iInterval
* @param {function} fnCallback(logCount, data, err)
*/
let reqRtlogByPeriod = function(measures, dtBegin, dtEnd, iInterval, fnCallback) {
let retReqMeasuresJson = JSON.stringify({
session: Date.now().toString(),
structtype: 'rtlog_v102',
params: [
{
'measures': measures,
'dtbegin': dtBegin,
'dtend': dtEnd,
'interval': iInterval,
},
],
});
if (!retReqMeasuresJson) {
console.log('!!! warnning: retReqMeasuresJson is empty!!!');
return;
}
let xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.open('post', '001.rtlog.cgi', true);
xmlhttp.setRequestHeader('POWERED-BY-AID', 'Approve');
xmlhttp.setRequestHeader('Content-Type', 'json');
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
myDebug('接收:RespMeasures - ' + new Date() + ' ' + xmlhttp.response.length);
if (fnCallback) {
fnCallback(JSON.parse(xmlhttp.responseText), dtBegin, dtEnd, iInterval);
}
}
};
let r = xmlhttp.send(retReqMeasuresJson);
myDebug('发送:ReqMeasures - ' + new Date() + ' ' + r);
};
rtdb.reqRtlogByPeriod = reqRtlogByPeriod;
let registerReqHeartJumpCallback = function registerReqHeartJumpCallback(fnDataChangedCallback) {
rtdb.reqHeartJumpCallback = fnDataChangedCallback;
};
rtdb.registerReqHeartJumpCallback = registerReqHeartJumpCallback;
let dealRespHeartJump = function dealRespHeartJump(response) {
let arr = JSON.parse(response);
let resSession = arr.session;
let resContent = arr.data;
if (rtdb.reqHeartJumpCallback) {
rtdb.reqHeartJumpCallback(resSession, resContent);
}
};
let sentHeartJumpEach = function sentHeartJumpEach(session, sysInfo) {
let reqRespRtdatas = function() {
let retReqJson = JSON.stringify({
session: session,
structtype: 'sysInfo_v101',
params: sysInfo,
});
if (!retReqJson) {
console.log('!!! warnning: sentHeartJumpEach - retReqJson is empty!!!');
return;
}
let xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.open('post', '001.app.heartjump', true);
xmlhttp.setRequestHeader('POWERED-BY-AID', 'Approve');
xmlhttp.setRequestHeader('Content-Type', 'json');
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
myDebug('接收:reqHeartJumpCallback - ' + new Date() + ' ' + xmlhttp.response.length);
dealRespHeartJump(xmlhttp.responseText);
}
};
let r = xmlhttp.send(retReqJson);
myDebug('发送:ReqMeasures - ' + new Date() + ' ' + r);
};
reqRespRtdatas();
};
rtdb.sentHeartJumpEach = sentHeartJumpEach;
})(typeof window !== 'undefined' ? window : this);
<file_sep>
const dgram = require('dgram');
let fs = require('fs');
exports = module.exports = CjChannelUdp;
function CjChannelUdp() {
this.connectState = CjChannelUdp.CI_ConnectState_Null;
this._udpSocket = null;
this.isAutoOpen = false;
this.isAutoHeartbeat = false;
this.connectParams = {LocalPort: 5555, LocalIpAddress: '127.0.0.1', RemotePort: 5556, RemoteIpAddress: '127.0.0.1'};
this.onReceived = null;
}
CjChannelUdp.prototype.receivedData = function(data, rinfo) {
console.log('received data: ', data.length);
if (this.onReceived) this.onReceived(data);
// var data = Buffer.from('hello')
// this._udpSocket.send([data], rinfo.port, rinfo.address, (err) => {
// // client.close();
// }
// )
};
CjChannelUdp.prototype.sendData = function(data) {
if (this.isOpen()) {
if (Number.isNaN(parseInt(this.connectParams.RemotePort))) {
return 0;
}
this._udpSocket.send(data, this.connectParams.RemotePort, this.connectParams.RemoteIpAddress, (err) => {
if (err !== null) {
console.log(err);
}
});
}
return 0;
};
CjChannelUdp.CI_ConnectState_Null = 0;
CjChannelUdp.CI_ConnectState_Disconnected = 1;
CjChannelUdp.CI_ConnectState_Connecting = 2;
CjChannelUdp.CI_ConnectState_ConnectTimeout = 3;
CjChannelUdp.CI_ConnectState_Connected = 4;
CjChannelUdp.CS_EntryRemoteIpAddress = 'RemoteIpAddress';
CjChannelUdp.CS_EntryRemotePort = 'RemotePort';
CjChannelUdp.CS_EntryLocalIpAddress = 'LocalIpAddress';
CjChannelUdp.CS_EntryLocalPort = 'LocalPort';
/**
* @param option = {LocalIpAddress:'127.0.0.1', LocalPort: 5555, RemoteIpAddress: '127.0.0,.1', RemotePort: 5556};
*/
CjChannelUdp.prototype.open = function(option) {
// var option = {port:5555, ip:'127.0.0.1'};
if (this._udpSocket) {
return;
}
if (this.connectState === CjChannelUdp.CI_ConnectState_Connecting) {
return;
}
let self = this;
if (option) self.connectParams = option;
if (Number.isNaN(parseInt(self.connectParams.LocalPort))) {
console.log('open fail. connectParams.LocalPort is invalid.');
return;
}
if (Number.isNaN(parseInt(self.connectParams.RemotePort))) {
console.log('connectParams.RemotePort is invalid.');
}
self.connectState = CjChannelUdp.CI_ConnectState_Connecting;
let udpSocket = null;
let connectTimeout = function() {
self.connectState = CjChannelUdp.CI_ConnectState_ConnectTimeout;
self._udpSocket = null;
if (udpSocket) {
udpSocket.close();
}
console.log('connect timeout.');
};
let timeout = setTimeout(connectTimeout, 5 * 1000);
udpSocket = dgram.createSocket('udp4');
udpSocket.on('error', function(err) {
self._udpSocket = null;
self.connectState = CjChannelUdp.CI_ConnectState_Disconnected;
self.close();
});
udpSocket.on('message', function(msg, rinfo) {
self.receivedData.call(self, msg, rinfo);
});
udpSocket.on('listening', function() {
if (self._udpSocket) {
console.log('had _udp, system error, or connect timeout.');
return;
}
clearTimeout(timeout);
// 'connect' listener
console.log('connected to server!');
self._udpSocket = udpSocket;
self.connectState = CjChannelUdp.CI_ConnectState_Connected;
});
// if (self.connectParams.LocalIpAddress)
// udpSocket.bind(self.connectParams.LocalPort, self.connectParams.LocalIpAddress);
// else
udpSocket.bind(self.connectParams.LocalPort);
self.checkChannel(3000);
};
CjChannelUdp.prototype.close = function() {
if (this._udpSocket) {
this._udpSocket = null;
this._udpSocket.close();
}
};
CjChannelUdp.prototype.isOpen = function() {
return this._udpSocket && this.connectState == CjChannelUdp.CI_ConnectState_Connected;
};
CjChannelUdp.prototype.checkChannel = function(interval) {
let udp = this;
if (interval < 1000) {
if (udp.checkChannelTimer) {
clearTimeout(udp.checkChannelTimer);
}
return;
}
if (udp.checkChannelTimer) {
clearTimeout(udp.checkChannelTimer);
}
var timeOut = function() {
//* recycle connect
if (udp.isAutoOpen) {
if (!udp.isOpen()) {
udp.open();
console.log('timer auto open');
}
}
//* recycle heart jump
if (udp.isAutoHeartbeat) {
if (udp.isOpen()) {
udp.sendData('heart jump!\r\n');
console.log('timer auto heart jump!');
}
}
udp.checkChannelTimer = setTimeout(timeOut, interval);
};
udp.checkChannelTimer = setTimeout(timeOut, interval);
};
<file_sep>#!/usr/bin/env bash
docker build -t hello-mysql:1.0.2 .
<file_sep>FROM oudream/ubuntu-ccxx-dev:18.04.12
RUN apt update -y && \
cd /opt && \
git clone https://github.com/oudream/ccxx.git && \
cd ccxx && \
cmake . -DCMAKE_BUILD_TYPE=Debug -DCCXX_BUILD_TYPE=all --build . -B"./build/cmake-gcc" && \
cd build/cmake-gcc && make && \
rm -rf /var/lib/apt/lists/*
<file_sep>/**
* Created by oudream on 2016/12/31.
*/
require('./../cjencoding_charset_lang');
let expect = require('./../../chai-4').expect;
describe('CjEncodingCharset', function() {
it('ucs2ToGb2312Url & gd2312ToUcs2', function() {
let str = cjs.CjEncodingCharset.ucs2ToGb2312Url('你');
str = str.replace(/%/g, '');
let iStr = Number.parseInt(str, 16);
let str2 = String.fromCharCode(iStr);
// console.log(str);
let iStr2 = str2.charCodeAt(0);
// console.log(iStr2);
let sGbk = cjs.CjEncodingCharset.gd2312ToUcs2(str2);
// console.log(sGbk);;
expect(sGbk).to.equal('你');
});
it('ucs2ToGb2312Url & gd2312ToUcs2', function() {
let utf8data = cjs.CjEncodingCharset.ucs2ToUtf8data('你');
expect(cjs.CjEncodingCharset.utf8dataToUcs2(utf8data)).to.equal('你');
});
});
<file_sep>#!/usr/bin/env bash
# docker logs显示的是容器内部运行输出到控制台的信息
### docker logs为何没有日志输出?
#spring boot应用使用docker容器启动后,使用docker logs没有日志输出,docker attach 到容器可以看到日志
#启动命令如下:
docker run -d -t -v app.jar:/app.jar -p 8080 docker.io/java:openjdk-8u111-jre-alpine java -jar /app.jar
# 有大神可以解释一下吗?看了一些docker logs的博文,但都没有找到合适的解决办法
RUN ln -sf /dev/stdout /var/log/some-log.log
<file_sep>#!/usr/bin/env bash
docker volume create portainer_data
docker run -d -p 2211:9000 -p 2210:8000 --name portainer --restart always -v /var/run/docker.sock:/var/run/docker.sock -v portainer_data:/data portainer/portainer<file_sep>FROM oudream/gcl3-nginx-alpine:1.0.2
LABEL maintainer="oudream - https://github.com/oudream"
ENTRYPOINT ["/opt/entrypoint.sh"]
EXPOSE 22 8821
COPY rootfs /opt/
RUN apk update && \
apk upgrade
RUN apk add --no-cache openssh \
&& sed -i s/#PermitRootLogin.*/PermitRootLogin\ yes/ /etc/ssh/sshd_config \
&& echo "root:root" | chpasswd \
&& passwd -d root \
&& ssh-keygen -A
COPY identity.pub /root/.ssh/authorized_keys
RUN apk add --update alpine-sdk && \
apk add libuuid
COPY deploy /opt/ddd/ccpp/gcl3/build/deploy
COPY assets /opt/ddd/ccpp/gcl3/deploy/assets
COPY nginx_gcl3.conf /etc/nginx/conf.d/nginx_gcl3.conf
<file_sep>const path = require('path');
const fs = require('fs');
let odcPathes = [
'./../../../assets/3rd/odl-3/odl',
'./../../../assets/3rd/odl-3/odl_n_mysql',
'./../../../assets/3rd/odl-3/odl_n_vue',
'./../../../assets/3rd/odl-3/odl_n_token',
'./../../../assets/pinfox/pl10_safe_lock/config/odc_cmm_cst',
'./../../../assets/pinfox/pl10_safe_lock/config/odc_cmm_obj',
'./../../../assets/pinfox/pl10_safe_lock/config/odc_cmm_prop',
'./../../../assets/pinfox/pl10_safe_lock/config/odc_lock_manu',
'./../../../assets/pinfox/pl10_safe_lock/config/odc_lock_reg',
'./../../../assets/pinfox/pl10_safe_lock/config/odc_lock_rt',
'./../../../assets/pinfox/pl10_safe_lock/config/odc_lock_log',
'./../../../assets/pinfox/pl10_safe_lock/config/odc_sys_user',
'./../../../assets/pinfox/pl10_safe_lock/config/odc_sys_role',
'./../../../assets/pinfox/pl10_safe_lock/config/odc_sys_auth',
'./../../../assets/pinfox/pl10_safe_lock/config/odc_sys_dept',
'./../../../assets/pinfox/pl10_safe_lock/config/odc_sys_log',
'./../../../assets/pinfox/pl10_safe_lock/config/odc_tck_main',
'./../../../assets/pinfox/pl10_safe_lock/config/odc_tck_detail',
'./../../../assets/pinfox/pl10_safe_lock/config/odc_tck_log',
];
// let odcPathes = [];
// let odcPath = "./../../../assets/pinfox/pl10_safe_lock/config";
// const odcFileNames = require('./../../../assets/pinfox/pl10_safe_lock/config/odc').odcFileNames;
//
// for (let i = 0; i < odcFileNames.length; i++) {
// odcPathes.push(path.normalize(path.join(odcPath, odcFileNames[i])));
// }
for (let i = 0; i < odcPathes.length; i++) {
require(odcPathes[i]);
}
exports = module.exports = {
/**
* mock bootstrap
*/
init(httpServer, db) {
}
};
<file_sep>FROM ubuntu:bionic
LABEL maintainer=<EMAIL>
RUN apt-get update -y ; apt-get upgrade -y && \
apt-get install apt-utils wget openssh-server telnet vim passwd ifstat unzip iftop telnet samba net-tools lsof rsync gcc g++ cmake build-essential gdb gdbserver -y && \
rm -rf /var/lib/apt/lists/*
RUN ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key -N '' -y && \
sed -i 's/#PermitRootLogin without-password/PermitRootLogin yes/g' /etc/ssh/sshd_config && \
sed -i 's/PermitRootLogin prohibit-password/PermitRootLogin yes/g' /etc/ssh/sshd_config && \
echo 'root:135246' | chpasswd
#RUN echo 'export LANG=C' >> /etc/profile
#ADD . /code
#WORKDIR /code
# Taken from - https://docs.docker.com/engine/examples/running_ssh_service/#environment-variables
# SSH login fix. Otherwise user is kicked off after login
#ENV NOTVISIBLE "in users profile"
# 22 for ssh server. 7777 for gdb server.
EXPOSE 22 7777
#RUN useradd -ms /bin/bash debugger
#RUN echo 'debugger:pwd' | chpasswd
CMD ["/usr/sbin/sshd", "-D"]
<file_sep>
(function() {
'use strict';
if (typeof window === 'object') {
window.gcl = window.gcl || {};
}
else if (typeof exports === 'object' && typeof global === 'object') {
global.gcl = global.gcl || {};
}
else {
throw Error('cjs only run at node.js or web browser');
}
let rtdb = gcl.rtdb || {};
gcl.rtdb = rtdb;
if (typeof exports === 'object' && typeof global === 'object') {
exports = module.exports = rtdb;
}
rtdb.clone = function(item) {
if (!item) {
return item;
} // null, undefined values check
var types = [Number, String, Boolean],
result;
// normalizing primitives if someone did new String('aaa'), or new Number('444');
types.forEach(function(type) {
if (item instanceof type) {
result = type(item);
}
});
if (typeof result == "undefined") {
if (Object.prototype.toString.call(item) === "[object Array]") {
result = [];
item.forEach(function(child, index, array) {
result[index] = odlClone(child);
});
}
else if (typeof item == "object") {
// testing that this is DOM
if (item.nodeType && typeof item.cloneNode == "function") {
result = item.cloneNode(true);
}
else if (!item.prototype) { // check that this is a literal
if (item instanceof Date) {
result = new Date(item);
}
else {
// it is an object literal
result = {};
for (var i in item) {
result[i] = odlClone(item[i]);
}
}
}
else {
// depending what you would like here,
// just keep the reference, or create new object
if (false && item.constructor) {
// would not advice to do that, reason? Read below
result = new item.constructor();
}
else {
result = item;
}
}
}
else {
result = item;
}
}
return result;
};
let myDebug = function(...args) {
console.log.apply(null, args);
};
let EnumMeasureType = {
none: 0,
monsb: 1,
ycadd: 2,
straw: 3,
};
rtdb.EnumMeasureType = EnumMeasureType;
let getMeasureTypeById = function(measureId) {
let iId = Number(measureId);
if (iId >= 0x01000000 && iId < 0x02000000) {
return EnumMeasureType.monsb;
}
else if (iId >= 0x02000000 && iId < 0x03000000) {
return EnumMeasureType.ycadd;
}
else if (iId >= 0x03000000 && iId < 0x04000000) {
return EnumMeasureType.straw;
}
else {
return EnumMeasureType.none;
}
};
rtdb.getMeasureTypeById = getMeasureTypeById;
rtdb.startSyncMeasures = null;
rtdb.stopSyncMeasures = null;
let MeasureBase = function(...args) {
let iId = 0;
let sUrl = '';
if (args.length > 0) {
let arg0 = args[0];
if (typeof arg0 === 'number') {
iId = arg0;
if (args.length > 1) {
let arg1 = args[1];
if (typeof arg0 === 'string') {
sUrl = arg1;
}
}
}
else if (typeof arg0 === 'string') {
sUrl = arg0;
if (args.length > 1) {
let arg1 = args[1];
if (typeof arg0 === 'number') {
iId = arg1;
}
}
}
else if (arg0 !== null && typeof value === 'object') {
this.id = arg0.id ? arg0.id : iId;
this.url = arg0.url ? arg0.url : sUrl;
this.value = arg0.value ? arg0.value : null;
this.quality = arg0.quality ? arg0.quality : 0;
this.refreshTime = arg0.refreshTime ? arg0.refreshTime : Date();
this.changedTime = arg0.changedTime ? arg0.changedTime : Date();
this.refreshSourceId = arg0.refreshSourceId ? arg0.refreshSourceId : 0;
this.changedSourceId = arg0.changedSourceId ? arg0.changedSourceId : 0;
this.refreshReasonId = arg0.refreshReasonId ? arg0.refreshReasonId : 0;
this.changedReasonId = arg0.changedReasonId ? arg0.changedReasonId : 0;
this.equalStrategyId = arg0.equalStrategyId ? arg0.equalStrategyId : 0;
this.res = arg0.res ? arg0.res : 0;
return this;
// this.id = arg0.id ? arg0.id : iId;
// this.url = arg0.url ? arg0.url : sUrl;
// this.value = arg0.value ? arg0.value : null;
// this.quality = arg0.quality ? arg0.quality : 0;
// this.refreshTime = arg0.refreshTime ? arg0.refreshTime : Date();
// this.changedTime = arg0.changedTime ? arg0.changedTime : Date();
// this.refreshSourceId = arg0.refreshSourceId ? arg0.refreshSourceId : 0;
// this.changedSourceId = arg0.changedSourceId ? arg0.changedSourceId : 0;
// this.refreshReasonId = arg0.refreshReasonId ? arg0.refreshReasonId : 0;
// this.changedReasonId = arg0.changedReasonId ? arg0.changedReasonId : 0;
// this.equalStrategyId = arg0.equalStrategyId ? arg0.equalStrategyId : 0;
// this.res = arg0.res ? arg0.res : 0;
}
}
this.id = iId;
this.url = sUrl;
this.value = null;
this.quality = 0;
this.refreshTime = Date();
this.changedTime = Date();
this.refreshSourceId = 0;
this.changedSourceId = 0;
this.refreshReasonId = 0;
this.changedReasonId = 0;
this.equalStrategyId = 0;
this.res = 0;
};
rtdb.MeasureBase = MeasureBase;
MeasureBase.prototype.setValue = function(v) {
myDebug('!!!error. setValue is abstract method!');
};
MeasureBase.prototype.setVQT = function(v, q, t) {
this.setValue(v);
if (q !== this.quality) {
this.quality = q;
}
if (t !== this.changedTime) {
this.changedTime = t;
}
};
let MeasureManagerBase = function() {
this.measures = new Map();
this.MeasureClass = MeasureBase;
};
rtdb.MeasureManagerBase = MeasureManagerBase;
MeasureManagerBase.prototype.findById = function(iId = 0) {
let r = this.measures.get(iId);
return r ? r : null;
};
MeasureManagerBase.prototype.findByUrl = function(sUrl = '') {
for (let [k, v] of this.measures) {
if (v.url === sUrl) {
return v;
}
}
return null;
};
MeasureManagerBase.prototype.append = function(measure) {
if (measure) {
let bId = (typeof measure.id === 'number' && measure.id > 0 && this.findById(measure.id) === null);
if (bId) {
let r = new this.MeasureClass(measure);
this.measures.set(measure.id, r);
return r;
}
}
else {
return null;
}
};
MeasureManagerBase.prototype.appendById = function(iId) {
if (typeof iId === 'number' && iId > 0 && this.findById(iId) === null) {
let measure = new this.MeasureClass(iId);
this.measures.set(measure.id, measure);
return measure;
}
else {
return null;
}
};
MeasureManagerBase.prototype.remove = function(measure) {
let r = 0;
if (measure && typeof measure.id === 'number') {
let bId = (typeof measure.id === 'number' && measure.id > 0);
let bUrl = (typeof measure.url === 'string');
if (bId) r = this.removeById(measure.id);
if (bUrl) r += this.removeByUrl(measure.url);
}
return r;
};
MeasureManagerBase.prototype.removeById = function(iId) {
return this.measures.delete(iId);
};
MeasureManagerBase.prototype.removeByUrl = function(sUrl) {
let ks = [];
for (let [k, v] of this.measures) {
if (v.url === sUrl) {
ks.push(k);
}
}
let i = 0;
for (let k of ks) {
this.measures.delete(k);
i++;
}
return i;
};
MeasureManagerBase.prototype.getReqMeasures = function() {
let r = [];
for (let [k, v] of this.measures) {
r.push({
mid: v.id,
url: v.url,
});
}
return r;
};
// # monsb
let MonsbMeasure = function(...args) {
MeasureBase.apply(this, args);
this.value = -1;
};
MonsbMeasure.prototype = Object.create(MeasureBase.prototype);
MonsbMeasure.prototype.constructor = MonsbMeasure;
rtdb.MonsbMeasure = MonsbMeasure;
MonsbMeasure.prototype.setValue = function(v) {
let newValue = Number(v);
if (newValue !== this.value) {
this.value = newValue;
}
};
let MonsbManager = function() {
MeasureManagerBase.call(this);
this.monsbs = this.measures;
this.MeasureClass = MonsbMeasure;
};
MonsbManager.prototype = Object.create(MeasureManagerBase.prototype);
MonsbManager.prototype.constructor = MonsbManager;
rtdb.MonsbManager = MonsbManager;
// # ycadd
let YcaddMeasure = function(...args) {
MeasureBase.apply(this, args);
this.value = -1;
};
YcaddMeasure.prototype = Object.create(MeasureBase.prototype);
YcaddMeasure.prototype.constructor = YcaddMeasure;
rtdb.YcaddMeasure = YcaddMeasure;
YcaddMeasure.prototype.setValue = function(v) {
let newValue = Number(v);
if (newValue !== this.value) {
this.value = newValue;
}
};
let YcaddManager = function() {
MeasureManagerBase.call(this);
this.ycadds = this.measures;
this.MeasureClass = YcaddMeasure;
};
YcaddManager.prototype = Object.create(MeasureManagerBase.prototype);
YcaddManager.prototype.constructor = YcaddManager;
rtdb.YcaddManager = YcaddManager;
// # straw
let StrawMeasure = function(...args) {
MeasureBase.apply(this, args);
this.value = -1;
};
StrawMeasure.prototype = Object.create(MeasureBase.prototype);
StrawMeasure.prototype.constructor = StrawMeasure;
rtdb.StrawMeasure = StrawMeasure;
StrawMeasure.prototype.setValue = function(v) {
let newValue = String(v);
if (newValue !== this.value) {
this.value = newValue;
}
};
let StrawManager = function() {
MeasureManagerBase.call(this);
this.straws = this.measures;
this.MeasureClass = StrawMeasure;
};
StrawManager.prototype = Object.create(MeasureManagerBase.prototype);
StrawManager.prototype.constructor = StrawManager;
rtdb.StrawManager = StrawManager;
// # rtdb's container
let monsbManager = new MonsbManager();
rtdb.monsbManager = monsbManager;
let ycaddManager = new YcaddManager();
rtdb.ycaddManager = ycaddManager;
let strawManager = new StrawManager();
rtdb.strawManager = strawManager;
// # rtdb's generic find - append
let findMeasureById = function(measureId) {
let iId = Number(measureId);
let r = null;
switch (getMeasureTypeById(iId)) {
case EnumMeasureType.monsb:
r = monsbManager.findById(iId);
break;
case EnumMeasureType.ycadd:
r = ycaddManager.findById(iId);
break;
case EnumMeasureType.straw:
r = strawManager.findById(iId);
break;
default:
break;
}
return r;
};
rtdb.findMeasureById = findMeasureById;
let findMeasureByUrl = function(sUrl = '') {
return monsbManager.findByUrl(sUrl)
|| ycaddManager.findByUrl(sUrl)
|| strawManager.findByUrl(sUrl);
};
rtdb.findMeasureByUrl = findMeasureByUrl;
let appendMeasureById = function(measureId) {
let iId = Number(measureId);
let r = null;
switch (getMeasureTypeById(iId)) {
case EnumMeasureType.monsb:
r = monsbManager.appendById(iId);
break;
case EnumMeasureType.ycadd:
r = ycaddManager.appendById(iId);
break;
case EnumMeasureType.straw:
r = strawManager.appendById(iId);
break;
default:
break;
}
if (typeof rtdb.startSyncMeasures === 'function')
rtdb.startSyncMeasures();
return r;
};
rtdb.appendMeasureById = appendMeasureById;
let removeMeasureById = function(measureId) {
let iId = Number(measureId);
let r = null;
switch (getMeasureTypeById(iId)) {
case EnumMeasureType.monsb:
r = monsbManager.removeById(iId);
break;
case EnumMeasureType.ycadd:
r = ycaddManager.removeById(iId);
break;
case EnumMeasureType.straw:
r = strawManager.removeById(iId);
break;
default:
break;
}
if (getMeasureCount() <= 0) {
if (typeof rtdb.stopSyncMeasures === 'function')
rtdb.stopSyncMeasures();
}
return r;
};
rtdb.removeMeasureById = removeMeasureById;
let getMeasureCount = function() {
return monsbManager.monsbs.size + ycaddManager.ycadds.size + strawManager.straws.size;
};
rtdb.getMeasureCount = getMeasureCount;
rtdb.printAll = function() {
console.log('monsbManager.monsbs {size:', monsbManager.monsbs.size,);
console.log(monsbManager.monsbs);
console.log('}');
console.log('ycaddManager.ycadds {size:', ycaddManager.ycadds.size,);
console.log(ycaddManager.ycadds);
console.log('}');
console.log('strawManager.straws {size:', strawManager.straws.size,);
console.log(strawManager.straws);
console.log('}');
};
})(typeof window !== 'undefined' ? window : this);
<file_sep>'use strict';
let WebSocketServer = require('ws').Server;
const CjTransferBase = require('./cjtransfer_base');
exports = module.exports = CjTransferWebsocketServer;
let WEBSOCKET_IP = '127.0.0.1';
let WEBSOCKET_PORT = 9101;
/**
* Class CjTransferWebsocketServer
* @constructor
*/
function CjTransferWebsocketServer() {
CjTransferBase.call(this);
this.connectState = CjTransferWebsocketServer.CI_ConnectState_Null;
this._ws = null;
this.isAutoOpen = false;
this.isAutoHeartbeat = false;
this.connectParams = {RemotePort: WEBSOCKET_PORT, RemoteIpAddress: WEBSOCKET_IP};
this.clientId = 0;
this.clientReceivedCount = 0;
this.serverSentBytes = 0;
this.onReceived = null;
}
CjTransferWebsocketServer.prototype = Object.create(CjTransferBase.prototype);
CjTransferWebsocketServer.prototype.constructor = CjTransferWebsocketServer;
CjTransferWebsocketServer.prototype.sendData = function(data) {
if (this.isOpen()) {
this._ws.send(data);
this.serverSentBytes += data.length;
}
};
CjTransferWebsocketServer.CI_ConnectState_Null = 0;
CjTransferWebsocketServer.CI_ConnectState_Disconnected = 1;
CjTransferWebsocketServer.CI_ConnectState_Connecting = 2;
CjTransferWebsocketServer.CI_ConnectState_ConnectTimeout = 3;
CjTransferWebsocketServer.CI_ConnectState_Connected = 4;
CjTransferWebsocketServer.CS_EntryRemoteIpAddress = 'RemoteIpAddress';
CjTransferWebsocketServer.CS_EntryRemotePort = 'RemotePort';
CjTransferWebsocketServer.CS_EntryLocalIpAddress = 'LocalIpAddress';
CjTransferWebsocketServer.CS_EntryLocalPort = 'LocalPort';
/**
* @param {object}option = {RemotePort:5555, RemoteIpAddress:'127.0.0.1'};
*/
CjTransferWebsocketServer.prototype.open = function(option) {
// var option = {port:5555, ip:'127.0.0.1'};
if (this._ws) {
return;
}
if (this.connectState === CjTransferWebsocketServer.CI_ConnectState_Connecting) {
return;
}
let self = this;
if (option) {
self.connectParams = option;
}
self.connectState = CjTransferWebsocketServer.CI_ConnectState_Connecting;
let wss = null;
let connectTimeout = function() {
self.connectState = CjTransferWebsocketServer.CI_ConnectState_ConnectTimeout;
self._ws = null;
if (wss) {
wss.close();
wss.end();
}
console.log('WebSocket: connect timeout.');
};
let timeout = setTimeout(connectTimeout, 5 * 1000);
try {
let wss = new WebSocketServer({port: self.connectParams.RemotePort});
wss.on('connection', function(ws) {
if (self._ws) {
self.close();
console.log('WebSocket: had _client, system error, or connect timeout.');
}
self._ws = ws;
self.connectState = CjTransferWebsocketServer.CI_ConnectState_Connected;
clearTimeout(timeout);
self.clientId++;
console.log('WebSocket: Client #%d connected', self.clientId);
ws.on('message', function(data) {
if (self.onReceived) {
self.onReceived(data);
}
self.clientReceivedCount += data.length;
});
ws.on('close', function() {
self._ws = null;
self.connectState = CjTransferWebsocketServer.CI_ConnectState_Disconnected;
console.log('WebSocket: Client #%d disconnected', self.clientId);
});
ws.on('error', function(e) {
self._ws = null;
self.connectState = CjTransferWebsocketServer.CI_ConnectState_Disconnected;
console.log('WebSocket: Client #%d error: %s', self.clientId, e.message);
});
});
} catch (e) {
console.log(e);
}
self.checkChannel(3000);
};
CjTransferWebsocketServer.prototype.close = function() {
this.checkChannel(0);
if (this._ws) {
this._ws = null;
this._ws.end();
}
};
CjTransferWebsocketServer.prototype.isOpen = function() {
return this._ws && this.connectState === CjTransferWebsocketServer.CI_ConnectState_Connected;
};
CjTransferWebsocketServer.prototype.checkChannel = function(interval) {
let self = this;
if (interval < 1000) {
if (self.checkTimer) {
clearTimeout(self.checkTimer);
self.checkTimer = null;
}
return;
}
if (self.checkTimer) {
clearTimeout(self.checkTimer);
}
let timeOut = function() {
//* recycle connect
if (self.isAutoOpen) {
if (!self.isOpen()) {
self.open();
console.log('WebSocket: timer auto open');
}
}
//* recycle heart jump
if (self.isAutoHeartbeat) {
if (self.isOpen()) {
self.sendData('heart jump!\r\n');
console.log('WebSocket: timer auto heart jump!');
}
}
self.checkTimer = setTimeout(timeOut, interval);
};
self.checkTimer = setTimeout(timeOut, interval);
};
<file_sep>#!/usr/bin/env bash
docker build -t selenium-python3.7.5:1.0.1 .
<file_sep>#!/usr/bin/env bash
docker build -t alpine-ssh1 --build-arg ssh_pub_key="$(cat ~/.ssh/id_rsa.pub)" .
docker run -d -p 2291:22 -l test alpine-ssh1
ssh root@localhost -p 2291 # or $(docker-machine ip default)
docker build -t alpine-ssh9 --build-arg ssh_pub_key="$(cat ~/.ssh/id_rsa.pub)" .
docker run -d -p 2299:22 -l test alpine-ssh9
ssh root@localhost -p 2299 # or $(docker-machine ip default)
cat ~/.ssh/id_rsa.pub > ./identity.pub
docker build -t alpine-ssh8 --build-arg ssh_pub_key="$(cat ~/.ssh/id_rsa.pub)" .
docker run -d -p 2298:22 -l test alpine-ssh8
ssh root@localhost -p 2298 # or $(docker-machine ip default)
cat ~/.ssh/id_rsa.pub > ./identity.pub
docker build -t alpine-ssh7 --build-arg ssh_pub_key="$(cat ~/.ssh/id_rsa.pub)" .
docker run -d -p 2297:22 -l test alpine-ssh7
ssh root@localhost -p 2297 # or $(docker-machine ip default)
cat ~/.ssh/id_rsa.pub > ./identity.pub
docker build -t alpine-ssh6 --build-arg ssh_pub_key="$(cat ~/.ssh/id_rsa.pub)" .
docker run -d -p 2296:22 -l test alpine-ssh6
ssh root@localhost -p 2296 # or $(docker-machine ip default)
cat ~/.ssh/id_rsa.pub > ./identity.pub
docker build -t alpine-ssh5 --build-arg ssh_pub_key="$(cat ~/.ssh/id_rsa.pub)" .
docker run -d -p 2295:22 -l test alpine-ssh5
ssh root@localhost -p 2295 # or $(docker-machine ip default)
cat ~/.ssh/id_rsa.pub > ./identity.pub
docker build -t alpine-ssh4 --build-arg ssh_pub_key="$(cat ~/.ssh/id_rsa.pub)" .
docker run -d -p 2294:22 -l test alpine-ssh4
ssh root@localhost -p 2294 # or $(docker-machine ip default)
cat ~/.ssh/id_rsa.pub > ./identity.pub
docker build -t alpine-ssh3 --build-arg ssh_pub_key="$(cat ~/.ssh/id_rsa.pub)" .
docker run -d -p 2293:22 -l test alpine-ssh3
ssh root@localhost -p 2293 # or $(docker-machine ip default)
<file_sep>import Login from '../views/home/Login.vue'
// import Login from './../views/example/odl1/validator/validator-a1'
import NotFound from '../views/home/404.vue'
import Home from '../views/home/Home.vue'
import Main from '../views/main/Main.vue'
import Customer from './../views/customer'
import RoleGroup from './../views/role-group'
import Users from './../views/users'
import Man from './../views/man'
import Vehicle from './../views/vehicle'
// System
import ClientUpload from './../views/client-upload.vue'
let routes = [
{
path: '/login',
component: Login,
name: '',
hidden: true
},
{
path: '/404',
component: NotFound,
name: '',
hidden: true
},
{
path: '/',
component: Home,
name: '',
leaf: true,//只有一个节点
iconCls: 'el-icon-message',
children: [
{ path: '/main', component: Main, name: '主页' }
]
},
{
path: '/',
component: Home,
name: '客户与用户管理',
iconCls: 'fa fa-id-card-o',
children: [
{ path: '/customer', component: Customer, name: '客户管理' },
{ path: '/role-group', component: RoleGroup, name: '角色分组管理' },
{ path: '/users', component: Users, name: '用户管理' }
]
},
{
path: '/',
component: Home,
name: '汽车信息管理',
iconCls: 'fa fa-id-card-o',
children: [
{ path: '/man', component: Man, name: '品牌管理' },
{ path: '/vehicle', component: Vehicle, name: '型号管理' },
]
},
{
path: '/',
component: Home,
name: '系统相关',
iconCls: 'fa fa-id-card-o',
children: [
{ path: '/client-upload', component: ClientUpload, name: '客户端上传的信息' },
]
},
{
path: '*',
hidden: true,
redirect: { path: '/404' }
}
];
export default routes;
<file_sep>#!/usr/bin/env bash
docker build -t httpsserver .
docker run -d httpsserver<file_sep>(function() {
'use strict';
if (typeof exports === 'object' && typeof global === 'object') {
global.cjs = global.cjs || {};
} else if (typeof window === 'object') {
window.cjs = window.cjs || {};
} else {
throw Error('cjs only run at node.js or web browser');
}
let CjContainer = cjs.CjContainer || {};
cjs.CjContainer = CjContainer;
if (typeof exports === 'object' && typeof global === 'object') {
exports = module.exports = CjContainer;
}
CjContainer.toString = Object.prototype.toString;
if (CjContainer.hasOwnProperty('findInArray')) return;
/**
*
* @param array
* @param elem
* @returns {number}
*/
CjContainer.findInArray = function(array, elem) {
if ( array == null || array == undefined) {
return -2;
} else if (array.length == 0) {
return -1;
}
for ( let i = 0; i < array.length; i++ ) {
if ( elem == array[i] ) {
return i;
}
}
return -1;
};
})();
<file_sep>
## bug
- 20200127 backGroundImage /opt/limi/hello-docker/assets/3rd/cvue-3/odl/validator-a.vue
<file_sep>/*!
*
*/
(function () {
window.gcl = window.gcl || {};
window.gcl.gis = window.gcl.gis || {};
window.gcl.gis.uiRtdb = window.gcl.gis.uiRtdb || {};
window.gcl.gis.uiRtcurve = window.gcl.gis.uiRtcurve || {};
window.gcl.gis.uiRtlog = window.gcl.gis.uiRtlog || {};
let gcl = window.gcl;
let gis = gcl.gis;
let uiRtdb = gis.uiRtdb;
let uiRtcurve = gis.uiRtcurve;
let uiRtlog = gis.uiRtlog;
let myDebug = gcl.debug || function () {
console.log.apply(null, arguments);
};
uiRtdb.rtdataStartRefresh = function () {
let csRtdataUiPrefix = 'show-rtdata-';
let rtdb = gcl.rtdb;
if (rtdb === null) {
myDebug('!!!warning-rtdataStartRefresh. rtdb is null.');
return;
}
let monsbManager = rtdb.monsbManager;
if (monsbManager === null) {
myDebug('!!!warning-rtdataStartRefresh. rtdb.monsbManager is null.');
return;
}
let monsbs = monsbManager.monsbs;
let ycaddManager = rtdb.ycaddManager;
let ycadds = ycaddManager.ycadds;
let strawManager = rtdb.strawManager;
let straws = strawManager.straws;
let svgMids = $("text[id^='" + csRtdataUiPrefix + "']");
svgMids.each(function () {
let name = this.id;
let index = name.indexOf(csRtdataUiPrefix);
if (index >= 0) {
let sMid = name.substring(index + 12);
rtdb.appendMeasureById(sMid);
myDebug('rtdb.appendById: ', sMid);
}
});
let showMeasuresTimeOut = function () {
// * yx
for (let i = 0; i < monsbs.length; i++) {
let monsb = monsbs[i];
let iMid = monsb.id;
let sMid = String(iMid);
let svgMeasure = d3.select("[id=" + csRtdataUiPrefix + sMid + "]");
if (svgMeasure !== null) {
let iRemain = monsb.value % 3;
if (iRemain === 0)
svgMeasure.attr("fill", "#ff0000");
else if (iRemain === 1)
svgMeasure.attr("fill", "#00ff00");
else
svgMeasure.attr("fill", "#0000ff");
}
}
// * yc
for (let i = 0; i < ycadds.length; i++) {
let ycadd = ycadds[i];
let iMid = ycadd.id;
let sMid = String(iMid);
let sValue = String(ycadd.value);
let svgMeasure = d3.select("[id=" + csRtdataUiPrefix + sMid + "]");
if (svgMeasure !== null) {
svgMeasure.text(sValue);
}
}
// * yw
for (let i = 0; i < straws.length; i++) {
let straw = straws[i];
let iMid = straw.id;
let sMid = String(iMid);
let sValue = String(straw.value);
let svgMeasure = d3.select("[id=" + csRtdataUiPrefix + sMid + "]");
if (svgMeasure !== null) {
svgMeasure.text(sValue);
}
}
};
setInterval(showMeasuresTimeOut, 1000);
};
uiRtcurve.rtcurveStartRefresh = function () {
let csRtcurveUiPrefix = 'show-rt-curve-';
let rtdb = gcl.rtdb;
let monsbManager = rtdb.monsbManager;
let monsbs = monsbManager.monsbs;
let ycaddManager = rtdb.ycaddManager;
let ycadds = ycaddManager.ycadds;
let strawManager = rtdb.strawManager;
let straws = strawManager.straws;
// #highcharts
Highcharts.setOptions({
global: {
useUTC: false
}
});
function activeLastPointToolip(chart) {
var points = chart.series[0].points;
chart.tooltip.refresh(points[points.length -1]);
}
let showRtcurve = function (measureId) {
Highcharts.chart(csRtcurveUiPrefix + measureId, {
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function () {
// set up the updating of the chart each second
let series = this.series[0];
let measure = rtdb.findMeasureById(measureId);
if (measure === null) {
return;
}
setInterval(function () {
let x = (new Date(measure.changedTime)).getTime(), // current time
y = measure.value;
series.addPoint([x, y], true, true);
}, 1000);
}
}
},
title: {
text: '温度实时'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: '华氏度'
},
plotLines: [{
value: 0,
width: 100,
color: '#808080'
}]
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: '<NAME>',
data: (function () {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
data.push({x: time + (-19 * 1000), y: 0});
data.push({x: time, y: 100});
for (i = -18; i < 0; i += 1) {
data.push({
x: time + i * 1000,
y: 0
});
}
return data;
}())
}]
});
};
let svgMids = $("div[id^='" + csRtcurveUiPrefix + "']");
svgMids.each(function () {
let name = this.id;
let index = name.indexOf(csRtcurveUiPrefix);
if (index >= 0) {
let sMid = name.substring(index + 14);
rtdb.appendMeasureById(sMid);
showRtcurve(sMid);
myDebug('rtdb.appendById: ', sMid);
}
});
};
})(typeof window !== "undefined" ? window : this);
<file_sep>#!/usr/bin/env bash
dk_gcl_bus_p=/opt/limi/hello-docker/projects/gcl3/alpine-bus
rm -r ${dk_gcl_bus_p}/assets
rm -r ${dk_gcl_bus_p}/deploy/bin_unix_d
rm ./identity.pub
cat ./../../../assets/ssh/identity.pub > ./identity.pub
cp -r /opt/ddd/web/limi3/assets/projects/gcl3 ${dk_gcl_bus_p}/assets
mkdir -p ${dk_gcl_bus_p}/deploy/bin_unix_d
cp /opt/ddd/ccpp/gcl3/build/deploy/bin_unix_d/liblibccxx.so ${dk_gcl_bus_p}/deploy/bin_unix_d/
cp /opt/ddd/ccpp/gcl3/build/deploy/bin_unix_d/liblibccxx_database_sqlite.so ${dk_gcl_bus_p}/deploy/bin_unix_d/
cp /opt/ddd/ccpp/gcl3/build/deploy/bin_unix_d/gcl_svr_bus ${dk_gcl_bus_p}/deploy/bin_unix_d/
cp /opt/ddd/ccpp/gcl3/build/deploy/bin_unix_d/gcl_svr_fastcgi_rtdata ${dk_gcl_bus_p}/deploy/bin_unix_d/
cp /opt/ddd/ccpp/gcl3/build/deploy/bin_unix_d/gcl_svr_fastcgi_filesystem ${dk_gcl_bus_p}/deploy/bin_unix_d/
cp /opt/ddd/ccpp/gcl3/build/deploy/bin_unix_d/gcl_svr_fastcgi_rtlog ${dk_gcl_bus_p}/deploy/bin_unix_d/
cp /opt/ddd/ccpp/gcl3/build/deploy/bin_unix_d/gcl_svr_rtdbs ${dk_gcl_bus_p}/deploy/bin_unix_d/
cp -r /opt/ddd/ccpp/gcl3/deploy/config ${dk_gcl_bus_p}/deploy/
<file_sep>#!/usr/bin/env bash
docker build -t gcl3-ubuntu .
docker run -d python3a
gcc pthreads_demo.c -lpthread -o pthreads_demo<file_sep>#!/usr/bin/env bash
cat ~/.ssh/id_rsa.pub > ./identity.pub
docker build -t alpine-ssh1 .
docker run -d -p 2291:22 alpine-ssh1
ssh root@localhost -p 2291 # or $(docker-machine ip default)
docker build -t alpine-ssh2 .
docker run -d -p 2292:22 alpine-ssh2
ssh root@localhost -p 2292 # or $(docker-machine ip default)
<file_sep>(function() {
'use strict';
if (typeof exports === 'object' && typeof global === 'object') {
global.cjs = global.cjs || {};
} else if (typeof window === 'object') {
window.cjs = window.cjs || {};
} else {
throw Error('cjs only run at node.js or web browser');
}
let CjMeta = cjs.CjMeta || {};
cjs.CjMeta = CjMeta;
if (typeof exports === 'object' && typeof global === 'object') {
exports = module.exports = CjMeta;
}
if (CjMeta.hasOwnProperty('checkStrict')) return;
CjMeta.checkStrict = '(function() { return !this; })();';
/**
* get object's ClassName
*
* @param obj
* @returns {*}
*/
CjMeta.getObjectClassName = function(obj) {
if (obj && obj.constructor && obj.constructor.toString()) {
/*
* for browsers which have name property in the constructor
* of the object,such as chrome
*/
if (obj.constructor.name) {
return obj.constructor.name;
}
let str = obj.constructor.toString();
/*
* executed if the return of object.constructor.toString() is
* "[object objectClass]"
*/
let arr;
if (str.charAt(0) === '[') {
arr = str.match(/\[\w+\s*(\w+)\]/);
} else {
/*
* executed if the return of object.constructor.toString() is
* "function objectClass () {}"
* for IE Firefox
*/
arr = str.match(/function\s*(\w+)/);
}
if (arr && arr.length === 2) {
return arr[1];
}
}
return undefined;
};
CjMeta.objectTypeRegexp = /^\[object (.*)\]$/;
/**
*
* @param obj
* @returns {*}
* usage : let a = []; getType(a) === 'Array'
*/
CjMeta.getType = function getType(obj) {
let type = Object.prototype.toString.call(obj).match(CjMeta.objectTypeRegexp)[1].toLowerCase();
// Let "new String('')" return 'object'
if (typeof Promise === 'function' && obj instanceof Promise) return 'promise';
// PhantomJS has type "DOMWindow" for null
if (obj === null) return 'null';
// PhantomJS has type "DOMWindow" for undefined
if (obj === undefined) return 'undefined';
return type;
};
/**
* Merge the property descriptors of `src` into `dest`
*
* @param {object} dest Object to add descriptors to
* @param {object} src Object to clone descriptors from
* @param {boolean} [redefine=true] Redefine `dest` properties with `src` properties
* @returns {object} Reference to dest
* @public
*/
CjMeta.merge = function(dest, src, redefine) {
if (!dest) {
throw new TypeError('argument dest is required');
}
if (!src) {
throw new TypeError('argument src is required');
}
if (redefine === undefined) {
// Default to true
redefine = true;
}
Object.getOwnPropertyNames(src).forEach(function forEachOwnPropertyName(name) {
if (!redefine && hasOwnProperty.call(dest, name)) {
// Skip desriptor
return;
}
// Copy descriptor
let descriptor = Object.getOwnPropertyDescriptor(src, name);
Object.defineProperty(dest, name, descriptor);
});
return dest;
};
/**
* 对象和数组复制
* @param elem:对象或数组
* @returns {*}
*/
CjMeta.clone = function(elem) {
if (elem && typeof elem === 'object') {
if (elem.length) {
var _elem = [];
for (let i = 0; i < elem.length; i++) {
_elem[i] = elem[i];
}
return _elem;
} else {
var _elem = {};
for (let attr in elem) {
_elem[attr] = elem[attr];
}
return _elem;
}
}
return null;
};
/**
* 判断对象是否有属性(或者指定属性)
* @param obj:待判断对象
* @param propertyName:特定属性,如不传入,将判断是否空对象
* @returns {boolean}
*/
CjMeta.hasProperty = function(obj, propertyName) {
for (let attr in obj) {
if (propertyName != undefined) {
if (attr == propertyName) {
return true;
}
} else {
return true;
}
}
return false;
};
/**
* 新建标签元素
* @param tagName:标签名,input,button...
* @param attrs:属性对象,{'id':'xx','className':'xxx'...}
* @param parent:父标签对象
* @returns {Element}:元素对象
*/
CjMeta.createElement = function(tagName, attrs, parent) {
let elem = document.createElement(tagName);
let ret;
for (let attr in attrs) {
if (typeof(attrs[attr]) != 'function') {
elem[attr] = attrs[attr];
}
}
/** 针对父对象是Dom对象 */
if (parent && ((typeof HTMLElement==='object' && parent instanceof HTMLElement) || (parent.nodeType && parent.nodeType===1))) {
parent.appendChild(elem);
ret = elem;
}
/** 针对父对象是jQuery对象 */
else if (parent && parent.length && (typeof jQuery==='function' || typeof jQuery==='object') && parent instanceof jQuery) {
ret = $(elem);
parent.append(ret);
} else if (parent == undefined || parent == null) {
ret = elem;
}
return ret;
};
/**
* 检测对象是否为空
* @param obj: 对象
* @returns {boolean}
*/
CjMeta.isEmptyObject = function(obj) {
let t;
for (t in obj) {
return !1;
}
return !0;
};
})();
<file_sep>'use strict';
let Route = require('./../cjs-3/cjhttp_route');
let FileServer = require('./../cjs-3/cjhttp_file_server');
let path = require('path');
let http = require('http');
let formidable = require('formidable');
const querystring =require('querystring');
exports = module.exports = HttpServer;
function HttpServer(confParams) {
this.route = new Route();
this.fileServer = new FileServer();
// this.fileServer.config.assetsPath = path.normalize(path.join(process.cwd(), '..'));
// this.fileServer.config.assetsPath = path.normalize(path.join(__dirname, './../..'));
this.fileServer.config.assetsPath = path.normalize(confParams.staticAssetsPath);
let _this = this;
this.server = http.createServer(function(req, res) {
let ret = _this.route.handle(req, res, function() {
console.log(arguments);
});
if (!ret) {
_this.fileServer.dispatch(req, res);
}
});
// this.route.all(/\/(.){0,}.cgi/, function (req, res) {
// res.end('Hello World!');
// });
this.route.all(/^\/upload/, function (req, res) {
let form = new formidable.IncomingForm(),
files = [],
fields = [];
form.uploadDir = os.tmpdir();
form
.on('field', function(field, value) {
console.log(field, value);
fields.push([field, value]);
})
.on('file', function(field, file) {
console.log(field, file);
files.push([field, file]);
})
.on('end', function() {
console.log('-> upload done');
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received fields:\n\n '+util.inspect(fields));
res.write('\n\n');
res.end('received files:\n\n '+util.inspect(files));
});
form.parse(req);
});
// this.route.all(/\/(.){0,}.sql/, function (req, res) {
//
//
// // 定义了一个data变量,用于暂存请求体的信息
// let data = '';
//
// // 通过req的data事件监听函数,每当接受到请求体的数据,就累加到data变量中
// req.on('data', function(chunk){
// data += chunk;
// });
//
// // 在end事件触发后,解释请求体,取出sql语句,然后向客户端返回。
// req.on('end', function(){
// // data = querystring.parse(data);
// data = JSON.parse(data);
// console.log(data);
// res.writeHead(200, {'Content-Type': 'text/plain'});
// res.end();
// });
//
// });
this.server.on('checkContinue', function(req, res) {
let msg = 'step checkContinue' + Date();
res.writeContinue();
console.log(msg);
});
this.server.on('clientError', (err, socket) => {
let msg = 'step clientError' + Date();
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
console.log(msg);
});
this.server.on('close', function() {
let msg = 'step close' + Date();
console.log(msg);
});
this.server.on('connect', function(req, socket, firstBodyChunk) {
let msg = 'step connect' + Date();
console.log(msg);
});
this.server.on('connection', function(connection) {
let msg = 'step connection' + Date();
console.log(msg);
});
this.server.on('upgrade', function(req, socket, head) {
let msg = 'step upgrade' + Date();
console.log(msg);
});
this.server.listen(confParams.port);
console.log('http://localhost:%s', confParams.port);
}
<file_sep>#!/usr/bin/env bash
docker create --name=test centos:latest /bin/sh -c "while true; do echo hello world; sleep 1; done"
<file_sep>(function() {
'use strict';
let odl = (typeof exports === 'object' && typeof global === 'object') ? global.odl : window.odl;
odl.DbMysql = {
kind: 'db.mysql',
fieldTypes: {
int: 'int',
int32: 'int',
int64: 'bigint',
double: 'double',
bool: 'int',
string: 'varchar(255)',
date: 'bigint',
enum: 'int',
},
getSimilar: function(odc) {
return odl.findNObj(odc, this.kind);
},
getSimilarByName: function(name) {
let odc = odl.findOdc(name);
return odc ? this.getSimilar(odc) : null;
},
completionAttr: function(attr) {
console.assert(attr.name);
console.assert(attr.type);
console.assert(this.fieldTypes[attr.type]);
// fieldName
if (!attr.field) {
attr.field = {};
}
if (!attr.field.fieldName) {
attr.field.fieldName = attr.name;
}
// fieldType
if (!attr.field.fieldType) {
attr.field.fieldType = this.fieldTypes[attr.type];
}
},
// fieldType !== type
toM: function(odcName, values) {
let odc = odl.findOdc(odcName);
if (! odc) return;
if (! Array.isArray(values)) return;
let nObj = this.getSimilar(odc);
if (! nObj) return;
nObj.spec.attrs.forEach(attr => {
if (attr.type === 'date') {
values.forEach(value => {
let v = value[attr.name];
if (typeof v === "number") {
value[attr.name] = new Date(v);
}
})
} else if (attr.type === 'bool') {
values.forEach(value => {
let v = value[attr.name];
if (typeof v === "number") {
value[attr.name] = Boolean(v);
}
})
}
});
},
// judge value to undefined
fromM: function(odcName, objs) {
let odc = odl.findOdc(odcName);
if (! odc) return;
if (! Array.isArray(objs)) return;
let nObj = this.getSimilar(odc);
if (! nObj) return;
nObj.spec.attrs.forEach(attr => {
if (attr.type === 'date') {
objs.forEach(o => {
let v = o[attr.name];
if (v) {
o[attr.name] = v.valueOf();
} else {
o[attr.name] = undefined;
}
})
} else if (attr.type === 'bool') {
objs.forEach(o => {
let v = o[attr.name];
if (typeof v === "boolean") {
o[attr.name] = Number(v);
} else {
o[attr.name] = undefined;
}
})
} else if (attr.type === 'string') {
objs.forEach(o => {
let v = o[attr.name];
if (! v) {
o[attr.name] = undefined;
}
})
} else {
objs.forEach(o => {
let v = o[attr.name];
if (typeof v !== 'number') {
o[attr.name] = undefined;
}
})
}
});
},
/**
*
* @param odc
* @param nObj
* @returns {Error|null}
*/
normalize: function(odc, nObj) {
if (nObj.kind !== this.kind) {
return new Error('kind invalid!!');
}
// attrs
let supperAttrs = odc.spec.attrs;
if (!nObj.spec) nObj.spec = {};
let spec = nObj.spec;
if (!spec.attrs) spec.attrs = [];
let attrs = spec.attrs;
let newAttrs = odl.Attr.mergeAttrs(supperAttrs, attrs);
let index = newAttrs.findIndex(a => a.notPersistence );
if (index >= 0) newAttrs.splice(index, 1);
for (let i = 0; i < newAttrs.length; i++) {
let newAttr = newAttrs[i];
this.completionAttr(newAttr);
}
// table
if (!spec.table) spec.table = {};
let table = spec.table;
if (!table.name) table.name = odc.metadata.name;
// table.keys & table.key
if (Array.isArray(odc.spec.container.keys) && !table.keys) {
table.keys = odl.clone(odc.spec.container.keys);
}
if (Array.isArray(odc.spec.container.sorts) && !table.sorts) {
table.sorts = odl.clone(odc.spec.container.sorts);
}
if (Array.isArray(table.keys) && table.keys.length > 0) {
let sKey = table.keys.find(ele => typeof ele === 'string' && ele.length > 0);
table.key = newAttrs.find(ele => ele.name === sKey);
}
spec.table = table;
spec.attrs = newAttrs;
// log
if (spec.log) {
this.log.normalize(odc, nObj);
}
return null;
},
/**
*
* @param odc
* @returns {string}
*/
getExistSql: function(odc) {
let nObj = this.getSimilar(odc);
if (nObj) {
let sql = ["SELECT 1 FROM `"];
sql.push(nObj.spec.table.name);
sql.push("` LIMIT 1");
return sql.join('');
}
return '';
},
/**
*
* @param odc
*
CREATE TABLE `table3` (
`f1` int NOT NULL,
`f2` bigint DEFAULT NULL,
`f3` double DEFAULT NULL,
`f4` char(64) DEFAULT NULL,
`f5` varchar(255) DEFAULT NULL,
`f6` text,
PRIMARY KEY (`f1`)
)
*
*/
/**
* @param odc
* @returns {string}
*/
getCreateSql: function(odc) {
let nObj = this.getSimilar(odc);
if (nObj) {
return this._createSql(nObj.spec.table, nObj.spec.attrs);
}
return '';
},
_createSql: function(table, attrs){
if (! Array.isArray(attrs)) {
return '';
}
let sPrimaryKey = '';
let keys = table.keys;
if (Array.isArray(keys)) {
let pks = keys.filter(x => typeof x === 'string');
sPrimaryKey = pks.map(x => '`' + x + '`').join(',');
}
let sql = ['CREATE TABLE IF NOT EXISTS `'];
sql.push(table.name);
sql.push('` (');
for (let i = 0; i < attrs.length; i++) {
let attr = attrs[i];
if (attr.noPersistence) {
continue;
}
let fieldName = attr.field.fieldName;
let fieldType = attr.field.fieldType;
let sIsNull = attr.isNull ? ' DEFAULT NULL' : ' NOT NULL';
let sAutoIncrement = attr.autoIncrement && attr.autoIncrement > 0 ? ' AUTO_INCREMENT' : '';
let sItem = '`' + fieldName + '` ' + fieldType + sIsNull + sAutoIncrement;
if (i !== attrs.length - 1) {
sItem += ',';
}
else if (sPrimaryKey) {
sItem += ',';
}
sql.push(sItem);
}
if (sPrimaryKey) {
sql.push('PRIMARY KEY (' + sPrimaryKey + ')');
}
sql.push(')');
return sql.join('');
},
/**
*
* @param odc
* @returns {string}
*/
getDropSql: function(odc) {
let nObj = this.getSimilar(odc);
if (nObj) {
let sql = ['DROP TABLE IF EXISTS `'];
sql.push(nObj.spec.table.name);
sql.push('`');
return sql.join('');
}
return '';
},
/**
* get Conditions Where Sql
* @param odc
* @param conditions: {} | null
* @returns {string}
*/
getConditionsWhereSql: function(odc, conditions) {
if (! conditions) return '';
let nObj = this.getSimilar(odc);
if (nObj) {
let tableName = nObj.spec.table.name;
let attrs = conditions.attrs;
// where
if (Array.isArray(attrs)) {
let where = [];
for (let i = 0; i < attrs.length; i++) {
let condition = attrs[i];
let attr = nObj.spec.attrs.find(a => a.name === condition.name);
if (attr) {
let sOpValue = String(condition.value);
let operation = condition.operation;
if (operation === '%') {
sOpValue = "LIKE '%" + sOpValue + "%'";
}
else {
if (attr.type === "string") {
sOpValue = operation + " '" + sOpValue + "'";
}
else {
sOpValue = operation + ' ' + sOpValue;
}
}
let fieldName = attr.field.fieldName;
let sItem = ' `' + tableName + '`.`' + fieldName + '` ' + sOpValue;
if (i < attrs.length - 1) {
sItem += condition.isAnd ? ' AND' : ' OR';
}
where.push(sItem);
}
}
return where.join('');
}
}
return '';
},
/**
*
conditions : {
start: 0,
end: 20,
attrs:[
{
name: "remark",
operation: '%',
value: value,
isAnd: true
}
] }
*
* @param odc
* @param conditions
* @returns {string}
SELECT users.*, department.name as department_name, role_group.name as role_group_name
FROM users
LEFT JOIN department on users.departmentId = department.id
LEFT JOIN role_group on users.roleGroupId = role_group.id
WHERE users.id > 0 and users.name LIKE '%a%'
*/
getSelectSql: function(odc, conditions) {
let nObj = this.getSimilar(odc);
if (nObj) {
let sqlSelect = 'SELECT ';
let sqlFrom;
let sqlLeftJion = '';
let sqlWhere = '';
let tableName = nObj.spec.table.name;
if (conditions && Array.isArray(conditions.fields)) {
// select as
let sqls = [];
nObj.spec.attrs.forEach((a, i) => {
if (conditions.fields.findIndex(f => f.name === a.name)>-1){
if (! a.noPersistence) {
sqls.push(tableName + '.`' + a.field.fieldName + '` as `' + a.name + '`');
}
}
});
sqlSelect += sqls.join(',');
// left join
nObj.spec.attrs.forEach((a, i) => {
if (conditions.fields.findIndex(f => f.name === a.name)>-1) {
let refer = a.refer;
if (refer) {
// todo: refer key
// only suport : one refer , attrs and key is string
let rOdc = odl.findOdc(refer.odc);
if (rOdc) {
let rnObj = this.getSimilar(rOdc);
if (rnObj) {
sqlSelect += ", " + rnObj.spec.table.name + '.`' + refer.title
+ "` as " + refer.titleName;
sqlLeftJion += ' LEFT JOIN ' + rnObj.spec.table.name + ' ON ' + tableName
+ '.`' + a.field.fieldName + '` = ' + rnObj.spec.table.name + '.`' + refer.key + '`';
}
}
}
}
});
} else {
// select as
let sqls = [];
nObj.spec.attrs.forEach((a, i) => {
if (! a.noPersistence) {
sqls.push(tableName + '.`' + a.field.fieldName + '` as `' + a.name + '`');
}
});
sqlSelect += sqls.join(',');
// left join
nObj.spec.attrs.forEach((a, i) => {
let refer = a.refer;
if (refer) {
// todo: refer key
// only suport : one refer , attrs and key is string
let rOdc = odl.findOdc(refer.odc);
if (rOdc) {
let rnObj = this.getSimilar(rOdc);
if (rnObj) {
sqlSelect += ", " + rnObj.spec.table.name + '.`' + refer.title
+ "` as " + refer.titleName;
sqlLeftJion += ' LEFT JOIN ' + rnObj.spec.table.name + ' ON ' + tableName
+ '.`' + a.field.fieldName + '` = ' + rnObj.spec.table.name + '.`' + refer.key + '`';
}
}
}
});
}
// from
sqlFrom = ' FROM ' + tableName;
// where
if (conditions) {
let sConditionsSql = this.getConditionsWhereSql(odc, conditions);
if (sConditionsSql.length > 0)
sqlWhere = ' WHERE ' + sConditionsSql;
if (typeof conditions.index === "number" && typeof conditions.count === "number") {
sqlWhere += ' LIMIT ' + conditions.index + ',' + conditions.count;
}
}
return sqlSelect + sqlFrom + sqlLeftJion + sqlWhere;
}
return '';
},
/**
*
* @param odc
* @param conditions
* @returns {string}
*/
getSelectCountSql: function(odc, conditions) {
let nObj = this.getSimilar(odc);
if (nObj) {
let table = nObj.spec.table;
let sqlSelect = 'SELECT ';
let sqlFrom;
let sqlWhere = '';
let tableName = table.name;
if (table.key) {
sqlSelect += 'COUNT(' + tableName + '.`' + table.key.field.fieldName + '`) as `counter`';
}
else {
sqlSelect += 'COUNT(*) as `counter`';
}
// from
sqlFrom = ' FROM ' + tableName;
// where
if (conditions) {
let sConditionsSql = this.getConditionsWhereSql(odc, conditions);
if (sConditionsSql.length > 0)
sqlWhere = ' WHERE ' + sConditionsSql;
}
return sqlSelect + sqlFrom + sqlWhere;
}
return '';
},
/**
*
* @param odc
* @returns {array}
*/
getSelectKeySqls: function(odc) {
let r = [];
let nObj = this.getSimilar(odc);
if (nObj) {
let table = nObj.spec.table;
let sqlSelect = 'SELECT ';
let sqlFrom;
let sqlWhere = '';
let tableName = table.name;
if (table.key && table.key.type !== 'string') {
sqlSelect += 'MAX(' + tableName + '.`' + table.key.field.fieldName + '`)+1 as `'+table.key.name+'`';
// from
sqlFrom = ' FROM ' + tableName;
r.push( sqlSelect + sqlFrom );
r.push(table.key.name);
}
}
return r;
},
getSelectKeySqlsValidateValues: function(odc, values, rSql) {
if (! Array.isArray(values) || values.length === 0 || ! values[0][rSql[1]]) {
values[0][rSql[1]] = 0;
}
},
getSelectKeyMaxSql: function(odc) {
let r = [];
let nObj = this.getSimilar(odc);
if (nObj) {
let table = nObj.spec.table;
let sqlSelect = 'SELECT ';
let sqlFrom;
let sqlWhere = '';
let tableName = table.name;
if (table.key && table.key.type !== 'string') {
sqlSelect += 'MAX(' + tableName + '.`' + table.key.field.fieldName + '`) as `maxValue`';
// from
sqlFrom = ' FROM ' + tableName;
r.push( sqlSelect + sqlFrom );
r.push(table.key.name);
}
}
return r;
},
getSelectKeyMaxValue: function(row) {
if (row) {
return Number(row['maxValue']);
}
},
/**
*
* INSERT INTO `table1`(`f1`, `f2`, `f3`, `f4`, `f5`, `f6`)
* VALUES (1, 1234567890123456789, 1.23, 'aa', 'aa1', 'abc-123');
* @param odc
* @param objs
* @returns {[]|null}
*/
getInsertSqlAry: function(odc, objs) {
if (!Array.isArray(objs) || objs.length < 1) {
return null;
}
let nObj = this.getSimilar(odc);
if (nObj) {
return this._insertSqlAry(nObj.spec.table, nObj.spec.attrs, objs);
}
return null;
},
_insertSqlAry: function(table, attrs, objs) {
if (!Array.isArray(objs) || objs.length < 1) {
return null;
}
let tableName = table.name;
if (! tableName) return null;
if (attrs.length < 1) return null;
let sqlAry = [];
objs.forEach(o => {
let sql = [' INSERT INTO `', tableName, '`('].join('');
let sFields = [];
let sValues = [];
for (let prop in o) {
let attr = attrs.find(a => a.name === prop);
if (attr) {
if (attr.noPersistence) {
continue;
}
sFields.push(['`', attr.field.fieldName, '`'].join(''))
if (attr.type === 'string') {
sValues.push("'" + o[prop] + "'");
}
else {
sValues.push(String(o[prop]));
}
}
}
sql += sFields.join(',');
sql += ') VALUES(';
if (sValues.length > 0) {
sqlAry.push(sql + sValues.join(',') + ')');
}
});
return sqlAry;
},
/**
*
* UPDATE `table1` SET `f1` = 'v1', `f2` = 1537545552189 WHERE `id` = 5;
* @param odc
* @param obj
* @param conditions
* @returns {string|null}
*/
getUpdateSql: function(odc, obj, conditions) {
if (typeof obj !== 'object' || typeof conditions !== 'object') {
return null;
}
let nObj = this.getSimilar(odc);
if (nObj) {
let tableName = nObj.spec.table.name;
if (! tableName) return null;
let attrs = nObj.spec.attrs;
if (attrs.length < 1) return null;
let sql = [' UPDATE `', tableName, '`('].join('');
let sFieldValues = [];
for (let prop in obj) {
let attr = attrs.find(a => a.name === prop);
if (attr) {
if (attr.noPersistence) {
continue;
}
if (attr.type === 'string') {
sFieldValues.push(['`', attr.field.fieldName, "` = '" + obj[prop] + "'"].join(''));
}
else {
sFieldValues.push(['`', attr.field.fieldName, '` = ', String(obj[prop])].join(''));
}
}
}
sql += sFieldValues.join(',');
// where
let sConditionsSql = this.getConditionsWhereSql(odc, conditions);
if (sConditionsSql.length > 0) {
sql += ' WHERE ' + sConditionsSql;
return sql;
}
}
return null;
},
/**
*
* UPDATE `table1` SET `f1` = 'v1', `f2` = 1537545552189 WHERE `id` = 5;
* @param odc
* @param objs
* @returns {[]|null}
*/
getUpdateSqlAry: function(odc, objs, conditions) {
if (!Array.isArray(objs) || !Array.isArray(conditions) || objs.length !== conditions.length) {
return null;
}
let nObj = this.getSimilar(odc);
if (nObj) {
let tableName = nObj.spec.table.name;
if (! tableName) return null;
let attrs = nObj.spec.attrs;
if (attrs.length < 1) return null;
let sqlAry = [];
objs.forEach((obj, i) => {
let sql = [' UPDATE `', tableName, '` SET '].join('');
let sFieldValues = [];
for (let prop in obj) {
let attr = attrs.find(a => a.name === prop);
if (attr) {
if (attr.noPersistence) {
continue;
}
if (attr.type === 'string') {
sFieldValues.push(['`', attr.field.fieldName, "` = '" + obj[prop] + "'"].join(''));
}
else {
sFieldValues.push(['`', attr.field.fieldName, '` = ', String(obj[prop])].join(''));
}
}
}
sql += sFieldValues.join(',');
// where
let condition = conditions[i];
let sConditionsSql = this.getConditionsWhereSql(odc, condition);
if (sConditionsSql.length > 0) {
sql += ' WHERE ' + sConditionsSql;
sqlAry.push(sql);
}
});
return sqlAry;
}
return null;
},
/**
*
* DELETE FROM users WHERE users.`id`=1 OR users.`id`=2
* @param odc
* @param objs
* @param conditions
* @returns {null|[]}
*/
getDeleteSqlAry: function(odc, conditions) {
if (!Array.isArray(conditions) || conditions.length < 1) {
return null;
}
let nObj = this.getSimilar(odc);
if (nObj) {
let tableName = nObj.spec.table.name;
if (! tableName) return null;
let attrs = nObj.spec.attrs;
if (attrs.length < 1) return null;
let sqlAry = [];
conditions.forEach((condition, i) => {
let sql = [' DELETE FROM `', tableName, '` '].join('');
// where
let sConditionsSql = this.getConditionsWhereSql(odc, condition);
if (sConditionsSql.length > 0) {
sql += ' WHERE ' + sConditionsSql;
sqlAry.push(sql);
}
});
return sqlAry;
}
return null;
},
/**
* { table, name, field, value }
* @param odc
* @param conditions
* @returns {[]|*}
*/
getTableKeyValuesByConditions: function(odc, conditions) {
let nObj = this.getSimilar(odc);
if (! nObj) {
return [];
}
if (!Array.isArray(conditions)) {
return []
}
let table = nObj.spec.table;
let tableKey = table.key;
if (! tableKey) {
return [];
}
let kvs = [];
for (let i = 0; i < conditions.length; i++) {
let condition = conditions[i];
if (Array.isArray(condition.attrs)) {
let attr = condition.attrs.find(a => a.name === tableKey.name);
if (! attr){
return [];
}
kvs.push({
table: table.name,
name: tableKey.name,
field: tableKey.field.fieldName,
value: attr.value
});
}
}
return kvs;
},
getTableKeyValuesByData: function(odc, objs) {
let nObj = this.getSimilar(odc);
if (! nObj) {
return [];
}
if (!Array.isArray(objs)) {
return []
}
let table = nObj.spec.table;
let tableKey = table.key;
if (! tableKey) {
return [];
}
let kvs = [];
for (let i = 0; i < objs.length; i++) {
let obj = objs[i];
if (obj.hasOwnProperty(tableKey.name)) {
kvs.push({
table: table.name,
name: tableKey.name,
field: tableKey.field.fieldName,
value: obj[tableKey.name]
});
} else {
return [];
}
}
return kvs;
},
/**
* LogRecord { id(auto), action, time, odc, table, name, field, value }
CREATE TABLE `LogRecord` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`action` varchar(64) DEFAULT NULL,
`time` double DEFAULT NULL,
`odc` varchar(64) DEFAULT NULL,
`table` varchar(64) DEFAULT NULL,
`name` varchar(64) DEFAULT NULL,
`field` varchar(64) DEFAULT NULL,
`value` varchar(64) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
* @param odc
* @param action
* @param data
* @returns {Array}
*/
getLogInsertSql: function(odc, action, data) {
let kvs = [];
if (action === 'edit' || action === 'del') {
kvs = this.getTableKeyValuesByConditions(odc, data);
} else if (action === 'add') {
kvs = this.getTableKeyValuesByData(odc, data);
}
for (let i = 0; i < kvs.length; i++) {
let kv = kvs[i];
kv.action = action;
kv.time = Date.now();
kv.odc = odc.metadata.name;
}
let sqlAry = [];
kvs.forEach(o => {
let sql = [' INSERT INTO `LogRecord`('].join('');
let sFields = [];
let sValues = [];
for (let prop in o) {
sFields.push(['`', prop, '`'].join(''))
if (prop === 'time') {
sValues.push(String(o[prop]));
}
else {
sValues.push("'" + o[prop] + "'");
}
}
sql += sFields.join(',');
sql += ') VALUES(';
if (sValues.length > 0) {
sqlAry.push(sql + sValues.join(',') + ')');
}
});
return sqlAry;
},
/**
*
* @param odc
* @returns {string}
*/
getSelectAllSql: function(odc) {
let nObj = this.getSimilar(odc);
if (nObj) {
let sqlSelect = '';
let sqlFrom;
let tableName = nObj.spec.table.name;
// select left join
let attrs = nObj.spec.attrs;
if (Array.isArray(attrs)) {
for (let i = 0; i < attrs.length; i++) {
let attr = attrs[i];
if (attr.noPersistence) {
continue;
}
sqlSelect += tableName + '.`' + attr.field.fieldName + '`';
if (i !== attrs.length - 1) {
sqlSelect += ', '
}
}
}
sqlSelect = 'SELECT ' + sqlSelect;
// from
sqlFrom = ' FROM ' + tableName;
return sqlSelect + sqlFrom;
}
return '';
},
/**
*
* INSERT INTO `table1`(`f1`, `f2`, `f3`, `f4`, `f5`, `f6`)
* VALUES (1, 1234567890123456789, 1.23, 'aa', 'aa1', 'abc-123');
*
strategies : { count: 10000, attrs: [
{
name: "name",
start: 0,
end: 10000,
seed: 'index' | 'time' | 'random'
head: 'xxx',
tail: 'xxx'
}
] }
*
* @param odc
* @param strategies
* @returns {null|Array}
*/
genRandomInsertSql: function(odc, strategies) {
function generate(count) {
let _sym = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz- _1234567890';
let str = '';
for (let i = 0; i < count; i++) {
str += _sym[Math.floor(Math.random() * (_sym.length))];
}
return str;
}
let nObj = this.getSimilar(odc);
if (nObj) {
let iCount = strategies.count > 0 && strategies.count < 10000 ? strategies.count : 10000;
let attrsST = Array.isArray(strategies.attrs) && strategies.attrs.length > 0 ? strategies.attrs : [];
let attrs = nObj.spec.attrs;
let valueses = [];
for (let i = 0; i < attrs.length; i++) {
let attr = attrs[i];
if (attr.noPersistence) {
continue;
}
let type = attr.type;
let attrST = attrsST.find(ele => ele.name === attr.name);
let minvalue = attrST && typeof attrST.start === 'number' ? attrST.start : attr.minvalue;
let maxvalue = attrST && typeof attrST.end === 'number' ? attrST.end : attr.maxvalue;
let maxLength = attr.maxLength > 255 ? 254 : attr.maxLength;
let dtNow = Date.now();
let values = [];
if (type === 'string') {
for (let j = 0; j < iCount; j++) {
let value = generate(Math.floor(Math.random() * maxLength));
if (value.length > 255) {
console.log('aa')
}
if (attrST && attrST.head) value = attrST.head + value;
if (attrST && attrST.tail) value = value + attrST.tail;
values.push(value);
}
}
else if (type === 'int') {
let start = attrST && typeof attrST.start === 'number' ? attrST.start : 0;
let end = attrST && typeof attrST.end === 'number' ? attrST.end : 0xFFFFFFFFFFFFF;
let index = start;
let seed = attrST && attrST.seed ? attrST.seed : 'index';
for (let j = 0; j < iCount; j++) {
if (seed === 'index') {
values.push(index++);
if (index > end) {
index = start;
}
}
else if (seed === 'random') {
values.push(Math.round(Math.random() * (maxvalue - minvalue)) + minvalue);
}
else {
values.push(dtNow++);
}
}
}
else if (type === 'double') {
let start = attrST && typeof attrST.start === 'number' ? attrST.start : 0;
let end = attrST && typeof attrST.end === 'number' ? attrST.end : 0xFFFFFFFFFFFFF;
let index = start;
let seed = attrST && attrST.seed ? attrST.seed : 'index';
for (let j = 0; j < iCount; j++) {
if (seed === 'index') {
values.push(index++);
if (index > end) {
index = start;
}
}
else if (seed === 'random') {
values.push(Math.random() * (end - start) + start);
}
else {
values.push(dtNow++ * Math.random());
}
}
}
else if (type === 'bool') {
for (let j = 0; j < iCount; j++) {
values.push(Math.round(Math.random()));
}
}
else if (type === 'date') {
for (let j = 0; j < iCount; j++) {
values.push(dtNow - Math.round(1000 * 60 * 60 * 24 * 365 * Math.random()));
}
}
else if (type === 'enum') {
let start = attrST && attrST.start ? attrST.start : 0;
let end = attrST && attrST.end ? attrST.end : attr.scopes.length;
let index = start;
let seed = attrST && attrST.seed ? attrST.seed : 'index';
for (let j = 0; j < iCount; j++) {
if (seed === 'random') {
values.push(Math.round(Math.random() * (end - start)) + start);
}
else {
values.push(index++);
if (index > end) {
index = start;
}
}
}
}
valueses.push(values);
}
let sqls = [];
for (let j = 0; j < iCount; j++) {
let sql = ['INSERT INTO `', nObj.spec.table.name, '`('].join('');
let attrs = nObj.spec.attrs;
if (!Array.isArray(attrs) || attrs.length < 0) {
return null;
}
let sFields = [];
for (let i = 0; i < attrs.length; i++) {
let attr = attrs[i];
if (attr.noPersistence) {
continue;
}
let fieldName = attr.field.fieldName;
sFields.push(['`', fieldName, '`'].join(''))
}
sql += sFields.join(',');
sql += ') VALUES(';
let sValue = [];
for (let i = 0; i < attrs.length; i++) {
let attr = attrs[i];
if (attr.noPersistence) {
continue;
}
let type = attr.type;
let values = valueses[i];
if (type === 'string') {
sValue.push("'" + values[j] + "'");
}
else {
sValue.push(String(values[j]));
}
}
sql += sValue.join(',') + ')';
sqls.push(sql);
}
return sqls;
}
return null;
},
log: {
prefix: 'log__',
fixFields: [
{
name: 'log__id',
type: 'int',
autoIncrement: 1,
},
{
name: 'log__time',
type: 'date',
},
{
name: 'log__operation',
type: 'string',
},
{
name: 'log__who',
type: 'string',
},
{
name: 'log__where',
type: 'string',
},
{
name: 'log__message',
type: 'string',
},
],
normalize: function(odc, nObj) {
let logAttrs = nObj.spec.log.attrs;
if (!Array.isArray(logAttrs)){
return null;
}
let DbMysql = odl.DbMysql;
let attrs = [];
for (let i = 0; i < this.fixFields.length; i++) {
let attr1 = this.fixFields[i];
let attr2 = odl.clone(attr1);
attr2.field = {
fieldName: attr1.name,
fieldType: DbMysql.fieldTypes[attr1.type]
};
attrs.push(attr2);
}
for (let i = 0; i < nObj.spec.attrs.length; i++) {
let attr1 = nObj.spec.attrs[i];
let attr2 = logAttrs.find(a => a.name === attr1.name);
if (attr2) {
Object.assign(attr2, attr1);
attrs.push(attr2);
}
}
// table
if (!nObj.spec.log.table) nObj.spec.log.table = {};
let table = nObj.spec.log.table;
if (!table.name) table.name = this.prefix + nObj.spec.table.name;
// table.keys & table.key
if (!table.keys) {
table.keys = [this.fixFields[0].name];
}
if (!table.sorts) {
table.sorts = odl.clone(odc.spec.container.sorts);
}
if (Array.isArray(table.keys) && table.keys.length > 0) {
let sKey = table.keys.find(ele => typeof ele === 'string' && ele.length > 0);
table.key = attrs.find(ele => ele.name === sKey);
}
nObj.spec.log.table = table;
nObj.spec.log.attrs = attrs;
return null;
},
getCreateSql: function(odc) {
let DbMysql = odl.DbMysql;
let nObj = DbMysql.getSimilar(odc);
if (nObj && nObj.spec.log && nObj.spec.log.table && nObj.spec.log.attrs) {
return DbMysql._createSql(nObj.spec.log.table, nObj.spec.log.attrs);
}
return '';
},
// logEnv: {time: Date.now(), operation: 'validate', who: 'me', where: 'there', message: ''}
getInsertSqlAry: function(odc, objs, logEnv) {
if (!Array.isArray(objs) || objs.length < 1) {
return null;
}
let DbMysql = odl.DbMysql;
let nObj = DbMysql.getSimilar(odc);
if (nObj && nObj.spec.log && nObj.spec.log.table && nObj.spec.log.attrs) {
for (let i = 0; i < objs.length; i++) {
let obj = objs[i];
for (let prop in logEnv) {
obj[this.prefix + prop] = logEnv[prop];
}
}
return DbMysql._insertSqlAry(nObj.spec.log.table, nObj.spec.log.attrs, objs);
}
return null;
},
}
};
odl.registerNPlugin(odl.DbMysql);
})();
<file_sep>#!/usr/bin/env bash
# cmake . -G "Xcode" --build "/ddd/communication/protobuf/protobuf/cmake" -B"/ddd/communication/protobuf/protobuf/cmake-xcode"
#gcl_deploy_p=/opt/ddd/ccpp/gcl3/build/deploy
## delete config
rm -r /opt/ddd/ccpp/gcl3/build/deploy/business
rm -r /opt/ddd/ccpp/gcl3/build/deploy/config
rm -r /opt/ddd/ccpp/gcl3/build/deploy/data
rm -r /opt/ddd/ccpp/gcl3/build/deploy/db
rm -r /opt/ddd/ccpp/gcl3/build/deploy/describe
rm -r /opt/ddd/ccpp/gcl3/build/deploy/log
rm -r /opt/ddd/ccpp/gcl3/build/deploy/measure
rm -r /opt/ddd/ccpp/gcl3/build/deploy/model
rm -r /opt/ddd/ccpp/gcl3/build/deploy/report
rm -r /opt/ddd/ccpp/gcl3/build/deploy/script
rm -r /opt/ddd/ccpp/gcl3/build/deploy/temp
rm -r /opt/ddd/ccpp/gcl3/build/deploy/terminal
rm -r /opt/ddd/ccpp/gcl3/build/deploy/ui
rm -r /opt/ddd/ccpp/gcl3/build/deploy/bin_unix_d/gcl_sdk
## git update
cd /opt/ddd/ccpp/ccxx && \
git reset --hard origin/master && \
git pull origin master && \
cd /opt/ddd/ccpp/gcl3 && \
git reset --hard origin/master && \
git pull origin master && \
cd /opt/ddd/web/limi3 && \
git reset --hard origin/master && \
git pull origin master
## build clear
rm -r /opt/ddd/ccpp/gcl3/build/cmake-gcc && \
rm -r /opt/ddd/ccpp/gcl3/build/deploy/bin_unix_d/*
## build make
cmake . -DCMAKE_BUILD_TYPE=Debug --build "/opt/ddd/ccpp/gcl3/build/cmake" -B"/opt/ddd/ccpp/gcl3/build/cmake-gcc" && \
cd /opt/ddd/ccpp/gcl3/build/cmake-gcc && make
## copy config
cp -r /opt/ddd/ccpp/gcl3/deploy/config /opt/ddd/ccpp/gcl3/build/deploy/
cp -r /opt/ddd/ccpp/gcl3/deploy/gcl_sdk /opt/ddd/ccpp/gcl3/build/deploy/bin_unix_d/
### delete all binary buf [ gcl_svr_bus liblibccxx.so gcl_svr_fastcgi_rtdata ]
arr1=$(find . -type f)
for a in ${arr1[@]};do [[ ${a} =~ '_d/gcl_svr_bus' || ${a} =~ '_d/liblibccxx.so' || ${a} =~ '_d/gcl_svr_fastcgi_rtdata' ]] && (echo "null ${a}") || (echo "rm ${a}" `rm ${a}` ) ; done
for a in ${arr1[@]};do [[ ${a} =~ gcl_svr_bus$ || ${a} =~ liblibccxx.so || ${a} =~ gcl_svr_fastcgi_rtdata$ ]] && (echo "null ${a}") || (echo "rm ${a}" `rm ${a}`) ; done
### run
cd /opt/ddd/ccpp/gcl3/build/deploy/bin_unix_d
/opt/ddd/ccpp/gcl3/build/deploy/bin_unix_d/gcl_svr_bus
/opt/ddd/ccpp/gcl3/build/deploy/bin_unix_d/gcl_sdk_tool
/opt/ddd/ccpp/gcl3/build/deploy/bin_unix_d/gcl_bus_viewer
/opt/ddd/ccpp/gcl3/build/deploy/bin_unix_d/gcl_svr_fastcgi_rtdata
/opt/ddd/ccpp/gcl3/build/deploy/bin_unix_d/gcl_svr_fastcgi_database
/opt/ddd/ccpp/gcl3/build/deploy/bin_unix_d/gcl_svr_fastcgi_filesystem
/opt/ddd/ccpp/gcl3/build/deploy/bin_unix_d/gcl_svr_fastcgi_rtdata
/opt/ddd/ccpp/gcl3/build/deploy/bin_unix_d/gcl_svr_fastcgi_rtlog
/opt/ddd/ccpp/gcl3/build/deploy/bin_unix_d/gcl_svr_bus &
/opt/ddd/ccpp/gcl3/build/deploy/bin_unix_d/gcl_sdk_tool &
/opt/ddd/ccpp/gcl3/build/deploy/bin_unix_d/gcl_bus_viewer &
/opt/ddd/ccpp/gcl3/build/deploy/bin_unix_d/gcl_svr_fastcgi_rtdata &
nginx -c /opt/ddd/ccpp/gcl3/deploy/nginx/nginx.conf
http://localhost:8821/bus/
rm /opt/ddd/ccpp/gcl3/build/deploy
#gcl_bus_viewer gcl_svr_fastcgi_filesystem libgcl_lua_vdi.so vxd_frame
#gcl_sdk gcl_svr_fastcgi_rtdata libgcl_sdk.so vxd_iec104
#gcl_sdk_main gcl_svr_fastcgi_rtlog libgcl_vdi.so vxd_modbus_rtu
#gcl_sdk_tool gcl_svr_rtdbs liblibccxx.so vxd_modbus_tcp
#gcl_svr_bus gcl_svr_script_vxd liblibccxx_database_odbc.so
#gcl_svr_fastcgi_database libgcl_lua_ccxx.so liblibccxx_database_sqlite.so
arr1=$(find . -type f)
for a in ${arr1[@]};do [[ ${a} =~ '_d/gcl_svr_bus' || ${a} =~ '_d/liblibccxx.so' || ${a} =~ '_d/gcl_svr_fastcgi_rtdata' ]] && (echo "null ${a}") || (echo "rm ${a}" `rm ${a}` ) ; done
for a in ${arr1[@]};do [[ ${a} =~ gcl_svr_bus$ || ${a} =~ liblibccxx.so || ${a} =~ gcl_svr_fastcgi_rtdata$ ]] && (echo "null ${a}") || (echo "rm ${a}" `rm ${a}`) ; done
# clion
# error,msg="Error while executing Python code.
#sys.path.insert(0, "/Applications/CLion.app/Contents/bin/gdb/renderers");
#from default.printers import register_default_printers;
#register_default_printers(None);
#from default.libstdcxx_printers import patch_libstdcxx_printers_module;
#patch_libstdcxx_printers_module();
#from libstdcxx.v6.printers import register_libstdcxx_printers;
#register_libstdcxx_printers(None);
mkdir -p /Applications/CLion.app/Contents/bin/gdb/renderers
scp -P 2201 -r /Applications/CLion.app/Contents/bin/gdb/renderers root@localhost:/Applications/CLion.app/Contents/bin/gdb/renderers
#
echo "alias python=python3" >> ~/.bashrc
limi.135246
<file_sep>import Login from '../views/home/Login.vue'
// import Login from './../views/example/odl1/validator/validator-a1'
import NotFound from '../views/home/404.vue'
import Home from '../views/home/Home.vue'
import Main from '../views/main/Main.vue'
import HelloOdlSimpleA1 from './../views/example/odl1/other/sample-a1.vue'
import HelloSvg1 from './../views/example/svg1/svg1.vue'
import sqlUser from './../views/example/sql1/user.vue'
import SampleDaMaterial from './../views/example/odl1/book/material.vue'
import SampleDaPosition from './../views/example/odl1/book/position.vue'
import SampleDaReader from './../views/example/odl1/book/reader.vue'
import SampleDaStatus from './../views/example/odl1/book/status.vue'
import SampleShopGoods from './../views/example/vuex1/goods.vue'
import SampleShopCart from './../views/example/vuex1/cart.vue'
import SampleShopPayment from './../views/example/vuex1/payment.vue'
import HelloCross1 from './../views/example/cross1/hello1.vue'
let routes = [
{
path: '/login',
component: Login,
name: '',
hidden: true
},
{
path: '/404',
component: NotFound,
name: '',
hidden: true
},
{
path: '/',
component: Home,
name: '',
leaf: true,//只有一个节点
iconCls: 'el-icon-message',
children: [
{ path: '/main', component: HelloSvg1, name: '主页' }
]
},
//{ path: '/main', component: Main },
{
path: '/',
component: Home,
name: 'HELLO',
iconCls: 'fa fa-id-card-o',
children: [
{ path: '/sampleA1', component: HelloOdlSimpleA1, name: 'Sample A' },
{ path: '/svg1', component: HelloSvg1, name: 'HelloSvg1' },
]
},
{
path: '/',
component: Home,
name: 'CROSS ',
iconCls: 'fa fa-id-card-o',
children: [
{ path: '/cross1', component: HelloCross1, name: 'Hello Cross 1' },
{ path: '/svg1', component: HelloSvg1, name: 'HelloSvg1' },
]
},
{
path: '/',
component: Home,
name: 'SampleDa',
iconCls: 'fa fa-id-card-o',
children: [
{ path: '/SampleDaMaterial', component: SampleDaMaterial, name: 'SampleDaMaterial' },
{ path: '/SampleDaPosition', component: SampleDaPosition, name: 'SampleDaPosition' },
{ path: '/SampleDaReader', component: SampleDaReader, name: 'SampleDaReader' },
{ path: '/SampleDaStatus', component: SampleDaStatus, name: 'SampleDaStatus' },
]
},
{
path: '/',
component: Home,
name: 'SampleShop',
iconCls: 'fa fa-id-card-o',
children: [
{ path: '/SampleShopGoods', component: SampleShopGoods, name: 'SampleShopGoods' },
{ path: '/SampleShopCart', component: SampleShopCart, name: 'SampleShopCart' },
{ path: '/SampleShopPayment', component: SampleShopPayment, name: 'SampleShopPayment' },
]
},
{
path: '/',
component: Home,
name: 'SQL-View',
iconCls: 'fa fa-id-card-o',
children: [
{ path: '/sqlUser', component: sqlUser, name: 'sql-user' }
]
},
{
path: '*',
hidden: true,
redirect: { path: '/404' }
}
];
export default routes;
<file_sep>#!/usr/bin/env bash
cat ~/.ssh/id_rsa.pub > ./identity.pub
docker build -t alpine-ssh5 .
docker run -d -p 2295:22 alpine-ssh5
ssh root@localhost -p 2295 # or $(docker-machine ip default)
docker build -t alpine-ssh6 .
docker run -d -p 2296:22 alpine-ssh6
ssh root@localhost -p 2296 # or $(docker-machine ip default)
docker build -t alpine-ssh7 .
docker run -d -p 2297:22 alpine-ssh7
ssh root@localhost -p 2297 # or $(docker-machine ip default)
docker build -t alpine-ssh8 .
docker run -d -p 2298:22 alpine-ssh8
ssh root@localhost -p 2298 # or $(docker-machine ip default)
<file_sep>#!/usr/bin/env bash
cat ~/.ssh/id_rsa.pub > ./identity.pub
docker build -t alpine-ssh3 .
docker run -d -p 2293:22 alpine-ssh3
ssh root@localhost -p 2293 # or $(docker-machine ip default)
docker build -t alpine-ssh4 .
docker run -d -p 2294:22 alpine-ssh4
ssh root@localhost -p 2294 # or $(docker-machine ip default)
<file_sep>#!/usr/bin/env bash
openssl req -x509 -newkey rsa:4096 -nodes -out cert.pem -keyout key.pem -days 365
docker build -t httpserver-ssl1 .
docker run -d httpserver-ssl1<file_sep>/**
* Created by oudream on 2016/12/29.
*/
/**
*
01.
first 1st 11.
eleventh 11th
02.
second 2nd 12.
twelfth 12th
03.
third 3rd 13.
thirteenth 13th
04.
fourth 4th 14.
fourteenth 14th
05.
fifth 5th 15.
fifteenth 15th
06.
sixth 6th 16.
sixteenth 16th
07.
seventh 7th 17.
seventeenth 17th
08.
eighth 8th 18.
eighteenth 18th
09.
ninth 9th 19.
nineteenth 19th
10.
tenth 10th 20.
twentieth 20th
01.
twenty-first 21st 11.
fiftieth 50th
02.
twenty-second 22nd 12.
sixtieth 60th
03.
twenty-third 23rd 13.
seventieth 70th
04.
twenty-fourth 24th 14.
eightieth 80th
05.
twenty-fifth 25th 15.
ninetieth
90th
06.
twenty-sixth 26th 16.
one hundredth 100th
07.
twenty-seventh 27th 17.
one thousandth 1,000th
08.
twenty-eighth 28th 18.
one millionth 1,000,000th
09.
twenty-ninth 29th 19.
seventy-fifth 75th
10.
thirtieth 30th 20.
ninety-ninth 99th
11.
thirty-first 31st 21.
103rd
12.
fortieth 40th 22.
532nd
*
*/
require('./../cjnumber');
let expect = require('./../../chai-4').expect;
describe('CjNumber', function() {
it('1st', function() {
expect((1).toOrdinal()).to.equal('1st');
});
it('2nd', function() {
expect((2).toOrdinal()).to.equal('2nd');
});
it('3rd', function() {
expect((3).toOrdinal()).to.equal('3rd');
});
it('4th', function() {
expect((4).toOrdinal()).to.equal('4th');
});
it('11th', function() {
expect((11).toOrdinal()).to.equal('11th');
});
it('12th', function() {
expect((12).toOrdinal()).to.equal('12th');
});
it('13th', function() {
expect((13).toOrdinal()).to.equal('13th');
});
it('14th', function() {
expect((14).toOrdinal()).to.equal('14th');
});
it('21st', function() {
expect((21).toOrdinal()).to.equal('21st');
});
it('22nd', function() {
expect((22).toOrdinal()).to.equal('22nd');
});
it('23rd', function() {
expect((23).toOrdinal()).to.equal('23rd');
});
it('24th', function() {
expect((24).toOrdinal()).to.equal('24th');
});
});
<file_sep>#!/usr/bin/env bash
docker build -t node13.0.1-limi .
<file_sep>FROM centos:centos7
ARG MYSQL_SERVER_PACKAGE=mysql-community-server-minimal-5.7.30
ARG MYSQL_SHELL_PACKAGE=mysql-shell-8.0.20
# Install server
RUN yum install -y https://repo.mysql.com/mysql-community-minimal-release-el7.rpm \
https://repo.mysql.com/mysql-community-release-el7.rpm \
&& yum-config-manager --enable mysql57-server-minimal \
&& yum install -y \
$MYSQL_SERVER_PACKAGE \
$MYSQL_SHELL_PACKAGE \
libpwquality \
&& yum clean all \
&& mkdir /docker-entrypoint-initdb.d
VOLUME /var/lib/mysql
COPY docker-entrypoint.sh /opt/entrypoint.sh
COPY healthcheck.sh /opt/healthcheck.sh
RUN ["chmod", "777", "/opt/entrypoint.sh"]
RUN ["chmod", "777", "/opt/healthcheck.sh"]
ENTRYPOINT ["/opt/entrypoint.sh"]
HEALTHCHECK CMD /opt/healthcheck.sh
EXPOSE 3306 33060
CMD ["mysqld"]
|
dc171d62c28e7bef568b986f5fafede41a3ae8da
|
[
"CMake",
"JavaScript",
"Markdown",
"Python",
"Dockerfile",
"Shell"
] | 127 |
JavaScript
|
oudream/hello-docker
|
d8252bc00bb122b88b02276687a73bd0ede349d5
|
eefe90aff64cc8a72c3031a3c3a9343c2467b8c8
|
refs/heads/master
|
<file_sep>tb_mbx_sync
===========
Thunderbird Mailboxes Synchronizer: Syncs mailboxes across two Thunderbird profiles (the mailboxes must exist in both profiles).
How to use
----------
python tb_mbx_sync.py /location/of/profile1/directory /location/of/profile2/directory
<file_sep>'''
Thunderbird Mail Synchronizer v. 1.0
Syncs mail across two profiles, in the mailboxes that are present in
both profiles.
Copyright (C) 2013 <NAME>
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 fileinput, os, hashlib, sys, multiprocessing, re, time
from subprocess import call, Popen, PIPE
import sqlite3 as lite
'''
Purges inactive memory on Macs if free memory < 500MB and inactive
memory > 1GB. Runs check every 10 seconds as a daemon (terminating when
main program terminates).
'''
def mac_pages2mb(page_count):
return int(page_count) * 4096 / 1024 ** 2
def mac_free_inactive():
vmstat = Popen('vm_stat', shell=True, stdout=PIPE).stdout.read()
inactive = mac_pages2mb(RE_INACTIVE.search(vmstat).group(1))
free = mac_pages2mb(RE_FREE.search(vmstat).group(1)) + \
mac_pages2mb(RE_SPECULATIVE.search(vmstat).group(1))
return free, inactive
def mac_purge():
while(True):
time.sleep(10)
free, inactive = mac_free_inactive()
if (free < FREE_THRESHOLD) and (inactive > INACTIVE_THRESHOLD):
print("Free: %dmb < %dmb" % (free, FREE_THRESHOLD))
print("Inactive: %dmb > %dmb" % (inactive, INACTIVE_THRESHOLD))
print('Purging...')
call('/usr/bin/purge', shell=True)
if sys.platform == "darwin":
INACTIVE_THRESHOLD = 1024 # Number of MBs
FREE_THRESHOLD = INACTIVE_THRESHOLD / 2
RE_INACTIVE = re.compile('Pages inactive:\s+(\d+)')
RE_FREE = re.compile('Pages free:\s+(\d+)')
RE_SPECULATIVE = re.compile('Pages speculative:\s+(\d+)')
#LOCK_FILE = '/var/tmp/releasemem.lock'
p = multiprocessing.Process(target=mac_purge)
p.daemon = True
p.start()
'''
Inserts data from two corresponding popstate.dat files into database.
'''
def insert_popstates(filepaths, cur):
for index, filepath in enumerate(filepaths):
print "Reading: " + filepath
with con:
cur.execute("CREATE TABLE Pop%i(id INTEGER PRIMARY KEY,"
" msgid TEXT, poptag INT);" % index)
for i, line in enumerate(fileinput.input(filepath)):
if i > 5:
msgid = line.split(' ')[1]
cur.execute("INSERT INTO Pop%i(msgid, poptag) VALUES"
" ('%s', '%s');" % (index, msgid, line))
'''
Compares data from two corresponding popstate.dat files. Appends each
popstate.dat file with unique values.
'''
def compare_popstates(filepaths, cur):
for pop, _ in enumerate(filepaths):
pop2 = not pop
with con:
cur.execute("SELECT poptag FROM Pop%i WHERE msgid NOT IN "
"(SELECT msgid FROM Pop%i)" % (pop, pop2))
f = open(filepaths[pop2], 'a')
u = 0
while(True):
uniquepoptag = cur.fetchone()
if not uniquepoptag: break
f.write(uniquepoptag[0])
u+=1
if u > 0:
print ("%i unique entries found in: %s.\nWritten to: %s"
% (u, filepaths[pop2], _))
'''
Returns paths to the mailboxes and popstate.dat files found under path.
(Filters out everything that is not a mailbox or a popstate.dat file).
'''
def sieve(path):
filteredfiles = []
for root, _, files in os.walk(path):
for f in files:
if f == 'popstate.dat' or f.find('.') < 0:
filteredfiles.append(os.path.join(root, f))
return filteredfiles
'''
Compares paths in path1 with the paths in path2. Returns nonunique
paths as matchedfiles. Returns unique paths in path1 and path2 as
uniquefiles1 and uniquefiles2, respectively.
'''
def compare_paths(path1, path2):
uniquefiles1 = []
uniquefiles2 = sieve(path2)
matchedfiles = []
p2files = sieve(path2)
for filename1 in sieve(path1):
filename2 = match_filename(filename1.replace(path1, ''), p2files,
path2, uniquefiles2)
if filename2:
matchedfiles.append((filename1, filename2))
else:
uniquefiles1.append(filename1)
return matchedfiles, uniquefiles1, uniquefiles2
'''
This is a helper function for compare_paths above. If a filename in
files matches basename, this function removes the filename from uniques
and returns it. Otherwise, returns None.
'''
def match_filename(basename, files, path, uniques):
for filename in files:
if filename.replace(path, '') == basename:
uniques.remove(filename)
return filename
return None
'''
Returns an e-mail message at the given offset from mailbox.
'''
def msg(offset, mailbox):
message = []
f = open(mailbox, 'r')
f.seek(offset)
i = 0
while(True):
l = f.readline()
if not l: break
if l[:7].lower() == 'from - ' and i > 0:
break
message.append(l)
i+=1
f.close()
return ''.join(message)
'''
Creates a hash for the body and certain header fields (from, to, cc,
subject) of each message in each of the provided mailboxes. Adds hash
to database.
'''
def store_hashes(mailboxes, cur):
for fileindex, filepath in enumerate(mailboxes):
print 'Reading: %s' % filepath
inheader = False
message = []
header = []
offset = 0
msgoffset = 0
h = None
with con:
cur.execute("CREATE TABLE Mbx%i(id INTEGER PRIMARY KEY, hash TEXT,"
" offset INT);" % fileindex)
for i, line in enumerate(fileinput.input(filepath)):
line2 = line.rstrip()
if not inheader and line2[:7].lower() == 'from - ':
inheader = True
# The beginning of a new message marks the end of the previous
# message. Generates the hash for the previous message,
# updates the database, and clears the message and header vars.
if i > 0:
h = hashlib.md5()
h.update('\n'.join(header))
h.update('\n'.join(message))
with con:
cur.execute("INSERT INTO Mbx%i(hash, offset) VALUES "
"('%s', %i);" % (fileindex,
h.hexdigest(),
msgoffset))
message = []
header = []
msgoffset = offset
elif inheader and (line2[:8].lower() == 'subject:' or
line2[:5].lower() == 'from:' or
line2[:3].lower() == "to:" or
line2[:3].lower() == "cc:"):
header.append(line2)
elif inheader and line2 == "":
inheader = False
elif not inheader:
message.append(line2)
offset += len(line)
else:
h = hashlib.md5()
h.update('\n'.join(header))
h.update('\n'.join(message))
with con:
cur.execute("INSERT INTO Mbx%i(hash, offset) VALUES"
" ('%s', %i);" % (fileindex,
h.hexdigest(),
msgoffset))
'''
Compares the hash tables of mailboxes. Appends messages keyed to unique
hashes to deficient mailbox.
'''
def comparemsgs(filepaths, cur):
for fileindex, filepath in enumerate(filepaths):
otherindex = not fileindex
print ('Looking for messages in: %s\nthat are not in: %s' %
(filepaths[otherindex], filepath))
f = open(filepath, 'a')
with con:
cur.execute("SELECT offset FROM Mbx%i WHERE hash NOT IN "
"(SELECT hash FROM Mbx%i)" % (otherindex, fileindex))
u = 0
while(True):
offset = cur.fetchone()
if not offset: break
f.write(msg(offset[0], filepaths[otherindex]))
u += 1
f.close()
if u > 0:
print ('%i unique messages found in: %s'
'\nThey have been written to: %s' %
(u, filepaths[otherindex], filepath))
try:
open(filepath + '.msf')
print 'Removing ' + filepath + '.msf'
os.remove(filepath + '.msf')
except IOError:
'' # Do nothing
'''
Run
'''
try:
path1 = sys.argv[1]
path2 = sys.argv[2]
files, uniquefiles1, uniquefiles2 = compare_paths(path1, path2)
if files:
for f in files:
try:
open('map.db')
os.remove('map.db')
except IOError:
'' # Do nothing
con = lite.connect('map.db')
with con:
cur = con.cursor()
if os.path.basename(f[0]) == "popstate.dat":
insert_popstates(f, cur)
compare_popstates(f, cur)
else:
store_hashes(f, cur)
comparemsgs(f, cur)
print "\n\n"
print "Finished!"
sys.exit(0)
except IndexError:
print "Copyright (C) 2013 by <NAME>"
print ("usage: %s path_to_profile1 path_to_profile2" %
os.path.basename(sys.argv[0]))
sys.exit(2)
|
f89c2fbe7b66764723d0d17189472fa7c7588d9a
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
amgreg/tb_mbx_sync
|
d3aa4d8ff0a6b5bc49de451cd2e94f54dbb2d72b
|
59c7234cb0314470345433dcf70406d00d8c799e
|
refs/heads/main
|
<file_sep># musicaCRUD
Para empezar tenemos la elaboracion de un CRUD en aplicacion web bastante sencillo, haciendo uso de Visual Studio y de las herramientas que nos brinda
por otra parte tenemos la elaboracion de un controlador (como viene siendo de constumbre) para realizar todas las acciones de nuestra aplicacion
tambien he de decir que en este controlador podemos observar diferentes tipos de metodos, unos los cuales son invocados de manera normal y otros son llamados por el metodo post
luego tenemos la creacion de las vistas haciendo uso de html y c# las cuales son bastante faciles de hacer dentro de lo que cabe
cada vista ya sea sea de crear, eliminar, etc, nos permiten crear una aplicacion web basica pero sostenible para cualquier tipo de cosas que queramos hacer, desde una aplicacion sencilla como esta, hasta un software con base web para una empresa
<file_sep>using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using musica.Data;
using musica.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace musica.Controllers
{
public class SongsController : Controller
{
private readonly ApplicationDbContext db;
public SongsController(ApplicationDbContext db)
{
this.db = db;
}
public async Task<IActionResult> Index()
{
return View(await db.Songs.ToListAsync());
}
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var song = await db.Songs.FirstOrDefaultAsync(s => s.SongId == id);
if (song == null)
{
return NotFound();
}
return View(song);
}
public IActionResult CreateSong()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Song song)
{
if (ModelState.IsValid)
{
db.Add(song);
await db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(song);
}
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var song = await db.Songs.FindAsync(id);
if (song == null)
{
return NotFound();
}
return View(song);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, Song song)
{
if (id != song.SongId)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
db.Update(song);
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
return NotFound();
}
return RedirectToAction(nameof(Index));
}
return View(song);
}
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var song = await db.Songs.FirstOrDefaultAsync(s => s.SongId == id);
if (song == null)
{
return NotFound();
}
return View(song);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Delete(int id)
{
var song = await db.Songs.FindAsync(id);
db.Songs.Remove(song);
await db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace musica.Models
{
public class Song
{
[Key]
public int SongId { get; set; }
[Display(Name = "Nombre")]
public string SongName { get; set; }
[Display(Name = "Artista")]
public string SongArtist { get; set; }
[Display(Name = "Productor/a")]
public string SongProducer { get; set; }
}
}
|
353c2f16ede9af6b63235d1bd754186379edd128
|
[
"Markdown",
"C#"
] | 3 |
Markdown
|
Kike-Imi/musicaCRUD
|
9dbe52a32f2ea1752590a0bdc8afe329128f124c
|
382722473b2813b872cd3c0c62e941eaef0d338c
|
refs/heads/master
|
<repo_name>mateja176/multipart-form<file_sep>/ota.ts
#!/usr/bin/env ts-node
import FormData from 'form-data';
import fs from 'fs';
import fetch from 'node-fetch';
const formData = new FormData();
const [filePath] = process.argv.slice(2);
if (!filePath) {
throw new Error(`"filePath" parameter was not provided`);
}
(async () => {
formData.append('update', fs.createReadStream(filePath));
const response = await fetch('http://192.168.0.14/update', {
headers: {
// "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
// "accept-language": "en-US,en;q=0.9,en-GB;q=0.8,de;q=0.7,sr;q=0.6,bs;q=0.5",
// "cache-control": "max-age=0",
// "content-type": "multipart/form-data; boundary=----WebKitFormBoundaryihktjbJSiSkG5q97",
// "upgrade-insecure-requests": "1"
},
// "referrer": "http://192.168.0.14/update",
// "referrerPolicy": "strict-origin-when-cross-origin",
// "mode": "cors"
// "body": null,
method: 'POST',
});
console.log(await response.text());
})();
<file_sep>/src/ota.ts
#!/usr/bin/env ts-node
import axios from 'axios';
import FormData from 'form-data';
import fs from 'fs';
import path from 'path';
const formData = new FormData();
const [ipAddress, relativeFilePath] = process.argv.slice(2);
if (!ipAddress) {
throw new Error(`"ipAddress" was not provided`);
}
if (!relativeFilePath) {
throw new Error(`"filePath" parameter was not provided`);
}
(async () => {
let filePath = relativeFilePath;
try {
const file = await fs.promises.readFile(relativeFilePath);
} catch {
filePath = path.join(process.cwd(), relativeFilePath);
}
console.log('Uploading:', filePath);
formData.append('update', fs.createReadStream(filePath));
try {
const response = await axios.post<string>(
`${ipAddress}/update`,
formData,
{},
);
console.log('Data:', response.data);
} catch (error) {
console.error(error);
}
})();
|
18d97f0ae32a4661dc7d6eddd71e13987b4bdfe0
|
[
"TypeScript"
] | 2 |
TypeScript
|
mateja176/multipart-form
|
e46783e9bac22f84b0316376cd58480c572b0ac6
|
5ab1ecfdb14c587218f6f3537bdb5c72e173c339
|
refs/heads/master
|
<repo_name>olman1995/anime_manga<file_sep>/Anime_Manga/nbproject/private/private.properties
compile.on.save=true
user.properties.file=C:\\Users\\<NAME>\\AppData\\Roaming\\NetBeans\\8.1\\build.properties
<file_sep>/Anime_Manga/src/base_datos/bd.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package base_datos;
import java.sql.Connection;
import javax.swing.table.DefaultTableModel;
/**
*
* @author Olman
*/
public abstract class bd {
protected conexion mysql=new conexion();
protected Connection cn=mysql.conectar();
protected String sSQL="";
public Integer totalRegistros;
public abstract DefaultTableModel mostrar(Object buscar);
public abstract DefaultTableModel mostrarTodo();
public abstract boolean insertar(Object datos);
public abstract boolean editar(Object datos);
public abstract boolean eliminar(Object datos);
public abstract Object objeto(Object buscar);
}
<file_sep>/Anime_Manga/src/logica/anime_manga.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package logica;
/**
*
* @author <NAME>
*/
public class anime_manga {
private String nombre;
private String tipo;
private String generos;
private String descrision;
private boolean visto;
private int fecha;
private String imagen;
public anime_manga(String nombre, String tipo, String generos, String descrision, boolean visto, int fecha, String imagen) {
this.nombre = nombre;
this.tipo = tipo;
this.generos = generos;
this.descrision = descrision;
this.visto = visto;
this.fecha = fecha;
this.imagen = imagen;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
public String getGeneros() {
return generos;
}
public void setGeneros(String generos) {
this.generos = generos;
}
public String getDescrision() {
return descrision;
}
public void setDescrision(String descrision) {
this.descrision = descrision;
}
public boolean isVisto() {
return visto;
}
public void setVisto(boolean visto) {
this.visto = visto;
}
public int getFecha() {
return fecha;
}
public void setFecha(int fecha) {
this.fecha = fecha;
}
public String getImagen() {
return imagen;
}
public void setImagen(String imagen) {
this.imagen = imagen;
}
}
<file_sep>/Anime_Manga/src/logica/link.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package logica;
/**
*
* @author <NAME>
*/
public class link {
private String nombre;
private String link;
private String pagina;
public link(String nombre, String link, String pagina) {
this.nombre = nombre;
this.link = link;
this.pagina = pagina;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getPagina() {
return pagina;
}
public void setPagina(String pagina) {
this.pagina = pagina;
}
}
<file_sep>/anime_manga.sql
-- MySQL Script generated by MySQL Workbench
-- 12/10/15 19:03:33
-- Model: New Model Version: 1.0
-- MySQL Workbench Forward Engineering
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Schema Anime_Manga
-- -----------------------------------------------------
-- -----------------------------------------------------
-- Schema Anime_Manga
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `Anime_Manga` DEFAULT CHARACTER SET utf8 ;
USE `Anime_Manga` ;
-- -----------------------------------------------------
-- Table `Anime_Manga`.`Anime/Manga`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Anime_Manga`.`Anime/Manga` (
`Nombre` VARCHAR(100) NOT NULL,
`Tipo` VARCHAR(45) NULL,
`Generos` VARCHAR(45) NULL,
`Descrision` VARCHAR(500) NULL,
`Visto` TINYINT(1) NULL,
`Fecha` INT NULL,
`Imagen` VARCHAR(45) NULL,
PRIMARY KEY (`Nombre`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `Anime_Manga`.`Link`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Anime_Manga`.`Link` (
`Nombre` VARCHAR(100) NOT NULL,
`Pagina` VARCHAR(45) NULL,
`Url` VARCHAR(45) NULL,
`Tipo` VARCHAR(45) NULL,
PRIMARY KEY (`Nombre`),
CONSTRAINT `fk_Link_Anime/manga`
FOREIGN KEY (`Nombre`)
REFERENCES `Anime_Manga`.`Anime/Manga` (`Nombre`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
|
25920be6baca3f22a0b51bcf430382e9d91a7f0d
|
[
"Java",
"SQL",
"INI"
] | 5 |
INI
|
olman1995/anime_manga
|
58e6447cd4723b825f8baa476144f376c99af741
|
3e49953864ca265321667a9af86cd9565b283a32
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
Game game = new Game();
Console.WriteLine("Welcome To Tic Tac Toe Game!");
Console.Write("Press Enter to start the game");
Console.ReadLine();
game.Start();
Console.ReadLine();
}
}
<file_sep>using System;
using System.Collections.Generic;
public class Game
{
private int[] _data = new int[9];
public Game()
{
for (int i = 0; i < _data.Length; i++)
{
_data[i] = -1;
}
}
public void Start()
{
int moveCount = 0;
int WhoseTurn = 1;
bool win = false;
int input = -1;
int whoWon = -1;
Console.WriteLine("Starting Game Now ...");
do
{
Console.WriteLine();
DrawBoard();
Console.WriteLine();
ShowMenu(WhoseTurn);
// Player Move
if (WhoseTurn == 1)
{
//try
//{
// input = int.Parse(Console.ReadLine());
//}
//catch (Exception)
//{
// input = -1;
//}
input = ComputerMove(WhoseTurn);
}
// Computer Move
else
{
input = ComputerMove(WhoseTurn);
}
if (input != -1)
{
bool validResult = false;
validResult = PutValue(input, WhoseTurn, _data);
if (!validResult)
{
Console.WriteLine("\nInvalid Move!");
}
else
{
WhoseTurn = WhoseTurn == 0 ? 1 : 0;
moveCount++;
whoWon = CheckWinCondition(_data);
win = whoWon != -1;
}
}
}
while (moveCount < 9 && !win);
Console.WriteLine("Thanks for playing!\n");
DrawBoard();
Console.WriteLine("\n" + "Game Output: " + (win ? (XorYFromInt(whoWon) + " Won") : "DRAW"));
}
private int CheckWinCondition(int[] board)
{
for (int i = 0; i < 9;)
{
// Horizontal checking
if (board[i] != -1 && board[i] == board[i + 1] && board[i + 1] == board[i + 2])
{
return board[i];
}
i += 3;
}
for (int i = 0; i < 3; i++)
{
// Vertical checking
if (board[i] != -1 && board[i] == board[i + 3] && board[i + 3] == board[i + 6])
{
return board[i];
}
}
// Diagonal Checking
if (board[0] != -1 && board[0] == board[4] && board[4] == board[8])
{
return board[0];
}
if (board[2] != -1 && board[2] == board[4] && board[4] == board[6])
{
return board[2];
}
return -1;
}
private int ComputerMove(int WhoseTurn)
{
for (int i = 0; i < _data.Length; i++)
{
int[] dataCopy = (int[])_data.Clone();
if (dataCopy[i] == -1)
{
PutValue(i, (WhoseTurn == 1 ? 0 : 1), dataCopy);
if (CheckWinCondition(dataCopy) == (WhoseTurn == 1 ? 0 : 1))
return i;
}
dataCopy = (int[])_data.Clone();
if (dataCopy[i] == -1)
{
PutValue(i, WhoseTurn, dataCopy);
if (CheckWinCondition(dataCopy) == WhoseTurn)
return i;
}
}
// Try taking the corners
Random rand = new Random();
List<int> Corners = new List<int> { 0, 2, 6, 8 };
do
{
int j = rand.Next(Corners.Count);
if (_data[Corners[j]] == -1)
return Corners[j];
else
Corners.RemoveAt(j);
} while (Corners.Count == 0);
// Take the middle
if (_data[4] == -1)
return 4;
List<int> sides = new List<int> { 1, 3, 5, 7 };
do
{
int j = rand.Next(sides.Count);
if (_data[sides[j]] == -1)
return sides[j];
else
sides.RemoveAt(j);
} while (sides.Count == 0);
return -1;
}
private void ShowMenu(int XorO)
{
Console.Write("Put a number here to put an " + XorYFromInt(XorO) + " there: ");
}
private bool PutValue(int at, int what, int[] array)
{
if (array[at] == -1)
{
array[at] = what;
return true;
}
else
return false;
}
private void DrawBoard()
{
Console.WriteLine("|-" + XorYFromInt(_data[0]) + "-|-" + XorYFromInt(_data[1]) + "-|-" + XorYFromInt(_data[2]) + "-|");
Console.WriteLine("|-" + XorYFromInt(_data[3]) + "-|-" + XorYFromInt(_data[4]) + "-|-" + XorYFromInt(_data[5]) + "-|");
Console.WriteLine("|-" + XorYFromInt(_data[6]) + "-|-" + XorYFromInt(_data[7]) + "-|-" + XorYFromInt(_data[8]) + "-|");
}
private string XorYFromInt(int number)
{
switch (number)
{
case 0:
return "X";
case 1:
return "O";
default:
return "-";
}
}
}
<file_sep># TicTacToe
Just a simple Tic Tac Toe Game, suporting 3 game modes player vs player, AI vs player, and AI vs AI
## Changing Game Modes
Game modes can be changed in the code at the moment, however further development is needed
so that user is presented with a menu to chose the game mode, which is easy to implement however
requires some time.
## How to run
### Windows
* Using Visual Studio build and run the soultion
* or Install csc to build it in CMD
### MacOS
* Using Visual Studio build and run the soultion
* or Install csc to build it in Terminal
### Linux
* Use either monodevelop or monodevel packages to build the solution and monodevel to run the exe files
* OR Install csc to build it in Terminal
## Output of AI vs AI
```
Welcome To Tic Tac Toe Game!
Press Enter to start the game
Starting Game Now ...
|---|---|---|
|---|---|---|
|---|---|---|
Put a number here to put an O there:
|---|---|---|
|---|---|---|
|---|---|-O-|
Put a number here to put an X there:
|---|---|---|
|---|-X-|---|
|---|---|-O-|
Put a number here to put an O there:
|-O-|---|---|
|---|-X-|---|
|---|---|-O-|
Put a number here to put an X there:
|-O-|-X-|---|
|---|-X-|---|
|---|---|-O-|
Put a number here to put an O there:
|-O-|-X-|---|
|---|-X-|---|
|---|-O-|-O-|
Put a number here to put an X there:
|-O-|-X-|---|
|---|-X-|---|
|-X-|-O-|-O-|
Put a number here to put an O there:
|-O-|-X-|-O-|
|---|-X-|---|
|-X-|-O-|-O-|
Put a number here to put an X there:
|-O-|-X-|-O-|
|---|-X-|-X-|
|-X-|-O-|-O-|
Put a number here to put an O there: Thanks for playing!
|-O-|-X-|-O-|
|-O-|-X-|-X-|
|-X-|-O-|-O-|
DRAW
```
# Signed Commits
* Everone who is contributing should sign their commits with GPG keys.
|
f27f0cd8fff727d7af6ea4379f9014b4e5acd92c
|
[
"Markdown",
"C#"
] | 3 |
C#
|
charliedua/TicTacToe
|
7dc46c03e0f98fd258a13784aea70e8d5146d430
|
c14352ab176b1e6950175953cf7a6fb30a41948e
|
refs/heads/master
|
<repo_name>tomekmatuszewski/Diet_composer<file_sep>/apps/diet_blog/models/__init__.py
from .blog_post import Post
from .post_comment import Comment
<file_sep>/apps/diet_composer/migrations/0012_auto_20201022_1904.py
# Generated by Django 3.1 on 2020-10-22 19:04
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('recipes', '0007_auto_20201014_2049'),
('diet_composer', '0011_auto_20201015_2122'),
]
operations = [
migrations.AlterField(
model_name='meal',
name='name',
field=models.CharField(choices=[('Breakfast', 'Breakfast'), ('Lunch', 'Lunch'), ('Dinner', 'Dinner'), ('Afternoon snack', 'Snack'), ('Post-workout meal', 'Post Workout'), ('Supper', 'Supper')], max_length=50, unique=True),
),
migrations.AlterField(
model_name='recipeitem',
name='recipe',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='recipe_items', to='recipes.recipe'),
),
]
<file_sep>/apps/diet_blog/tests/test_models.py
import pytest
from django.contrib.auth.models import User
from apps.diet_blog.models import Comment, Post
@pytest.mark.django_db()
class TestPost:
@pytest.fixture(name="post", scope="class")
def create_post(self, django_db_blocker, django_db_setup):
with django_db_blocker.unblock():
user = User.objects.create_user(
username="test_user", email="<EMAIL>", password="<PASSWORD>"
)
post = Post.objects.create(
title="Test post", content="Test content", author=user
)
yield post
with django_db_blocker.unblock():
post.delete()
user.delete()
def test_blog_obj_name(self, post):
assert str(post) == "Post 1, title: Test post"
def test_post(self, post):
assert isinstance(post, Post)
assert post.title == "Test post"
assert post.content == "Test content"
assert post.author.username == "test_user"
assert post.total_likes() == 0
@pytest.mark.django_db()
class TestComment:
@pytest.fixture(name="comment", scope="class")
def create_post(self, django_db_blocker, django_db_setup):
with django_db_blocker.unblock():
user = User.objects.create_user(
username="test_user", email="<EMAIL>", password="<PASSWORD>"
)
post = Post.objects.create(
title="Test post", content="Test content", author=user
)
comment = Comment.objects.create(
content="Test content", author=user, post=post
)
yield comment
with django_db_blocker.unblock():
comment.delete()
post.delete()
user.delete()
def test_blog_obj_name(self, comment):
assert str(comment) == "Comment 1 to post Test post"
def test_post(self, comment):
assert isinstance(comment, Comment)
assert comment.content == "Test content"
assert comment.author.username == "test_user"
<file_sep>/apps/diet_composer/apps.py
from django.apps import AppConfig
class DietComposerConfig(AppConfig):
name = "apps.diet_composer"
<file_sep>/apps/diet_composer/migrations/0006_auto_20201012_1009.py
# Generated by Django 3.1 on 2020-10-12 10:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("diet_composer", "0005_auto_20201008_1753"),
]
operations = [
migrations.AlterField(
model_name="dailymenu",
name="meals",
field=models.ManyToManyField(
blank=True, related_name="menus", to="diet_composer.Meal"
),
),
migrations.AlterField(
model_name="meal",
name="ingredients",
field=models.ManyToManyField(
related_name="meals", to="diet_composer.ProductItem"
),
),
migrations.AlterField(
model_name="product",
name="weight_of_pcs",
field=models.DecimalField(
blank=True,
decimal_places=2,
help_text="weight of an average piece / package [g]",
max_digits=6,
null=True,
),
),
]
<file_sep>/apps/diet_composer/models/product.py
from django.contrib.auth.models import User
from django.db import models
from apps.diet_composer.utils import calculate_params, calculate_weight
class ProductCategory(models.Model):
name = models.CharField(max_length=150, unique=True)
def __str__(self):
return f"{self.name}"
class Meta:
ordering = ("name",)
class Product(models.Model):
category = models.ForeignKey(
ProductCategory, on_delete=models.PROTECT, related_name="products"
)
name = models.CharField(max_length=150, unique=True)
calories_per_100 = models.DecimalField(max_digits=6, decimal_places=2)
proteins_per_100 = models.DecimalField(max_digits=6, decimal_places=2)
fats_per_100 = models.DecimalField(max_digits=6, decimal_places=2)
carbohydrates_per_100 = models.DecimalField(max_digits=6, decimal_places=2)
weight_of_pcs = models.DecimalField(
null=True,
blank=True,
max_digits=6,
decimal_places=2,
help_text="weight of an average piece / package [g]",
)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="products")
class Meta:
ordering = ("category", "name")
def __str__(self):
if self.weight_of_pcs:
return f"{self.name}, weight of piece/packege {self.weight_of_pcs} g"
return f"{self.name}"
class ProductItem(models.Model):
class Unit(models.TextChoices):
gram = "g"
piece = "piece"
package = "package"
product = models.ForeignKey(Product, on_delete=models.CASCADE)
category = models.ForeignKey(
ProductCategory,
on_delete=models.CASCADE,
related_name="prod_items",
null=True,
blank=True,
)
unit = models.CharField(choices=Unit.choices, null=True, blank=True, max_length=150)
weight = models.DecimalField(
max_digits=6,
decimal_places=2,
help_text="Depends on selected unit - grams or piece/package",
)
def __str__(self):
return f"Ingredient: {self.product.name}, {self.weight_of_pcs} g"
@property
def weight_of_pcs(self) -> float:
weight = calculate_weight(self.unit, self.weight, self.product.weight_of_pcs)
return weight
@property
def calories(self) -> float:
calories = calculate_params(
self.unit,
self.product.calories_per_100,
self.weight,
self.product.weight_of_pcs,
)
return calories
@property
def proteins(self) -> float:
proteins = calculate_params(
self.unit,
self.product.proteins_per_100,
self.weight,
self.product.weight_of_pcs,
)
return proteins
@property
def fats(self) -> float:
fats = calculate_params(
self.unit,
self.product.fats_per_100,
self.weight,
self.product.weight_of_pcs,
)
return fats
@property
def carbohydrates(self) -> float:
carb = calculate_params(
self.unit,
self.product.carbohydrates_per_100,
self.weight,
self.product.weight_of_pcs,
)
return carb
<file_sep>/apps/diet_composer/admin.py
from django.contrib import admin
from apps.diet_composer.models import (
DailyMenu,
Meal,
Product,
ProductCategory,
ProductItem,
RecipeItem,
)
admin.site.register(Product)
admin.site.register(ProductCategory)
admin.site.register(ProductItem)
admin.site.register(Meal)
admin.site.register(DailyMenu)
admin.site.register(RecipeItem)
<file_sep>/apps/diet_composer/models/daily_menu.py
from django.contrib.auth.models import User
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from apps.diet_composer.utils import calculate_total_value_menu
class DailyMenu(models.Model):
name = models.CharField(max_length=150)
number_of_meals = models.PositiveSmallIntegerField(
validators=[MaxValueValidator(6), MinValueValidator(1)]
)
meals = models.ManyToManyField(
"diet_composer.Meal", related_name="menus", blank=True
)
author = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="user_menus"
)
def __str__(self):
return f"Daily Menu {self.name} created by {self.author.username}"
@property
def total_calories(self) -> float:
value = calculate_total_value_menu(self.meals.all(), "calories")
return value
@property
def total_proteins(self) -> float:
value = calculate_total_value_menu(self.meals.all(), "proteins")
return value
@property
def total_fats(self) -> float:
value = calculate_total_value_menu(self.meals.all(), "fats")
return value
@property
def total_carbohydrates(self) -> float:
value = calculate_total_value_menu(self.meals.all(), "carbohydrates")
return value
def delete(self, using=None, keep_parents=False):
for meal in self.meals.all():
for product in meal.ingredients.all():
product.delete()
for recipe in meal.recipes.all():
recipe.delete()
meal.delete()
super().delete()
<file_sep>/apps/diet_composer/tests/test_product_views.py
import pytest
from django.contrib.auth.models import User
from django.urls import reverse
from apps.diet_composer.models import Product, ProductCategory
@pytest.mark.django_db
class TestProductView:
@pytest.fixture(name="user", scope="class")
def create_user(self, django_db_blocker, django_db_setup):
with django_db_blocker.unblock():
user = User.objects.create_user(
username="test_user", email="<EMAIL>", password="<PASSWORD>"
)
yield user
with django_db_blocker.unblock():
user.delete()
@pytest.fixture(name="product", scope="class")
def create_product(self, django_db_blocker, django_db_setup, user):
with django_db_blocker.unblock():
category = ProductCategory.objects.create(name="cat1")
product = Product.objects.create(
category=category,
name="product_testing",
calories_per_100=100,
proteins_per_100=50,
fats_per_100=50,
carbohydrates_per_100=50,
weight_of_pcs=100,
author=user
)
yield product
with django_db_blocker.unblock():
product.delete()
category.delete()
def test_product_create_view(self, client, product):
client.login(username="test_user", password="<PASSWORD>")
response = client.post(
reverse("product-create"),
data={
"category": product.category.id,
"name": "added_product",
"calories_per_100": 100,
"proteins_per_100": 40,
"fats_per_100": 10,
"carbohydrates_per_100": 80
},
)
assert response.status_code == 302
assert Product.objects.count() == 2
assert Product.objects.get(name="added_product")
def test_products_list_view(self, client, user):
client.login(username="test_user", password="<PASSWORD>")
response = client.get(reverse("products-list", args=[user.username]))
assert response.status_code == 200
assert response.context[0]["products"].count() == 1
def test_product_update_view(self, client, user, product):
client.login(username="test_user", password="<PASSWORD>")
response = client.post(
reverse("product-update", args=[product.pk]),
data={
"category": product.category.id,
"name": "added_product_updated",
"calories_per_100": 200,
"proteins_per_100": 40,
"fats_per_100": 10,
"carbohydrates_per_100": 80
}
)
assert response.status_code == 302
assert Product.objects.get(name="added_product_updated")
assert Product.objects.get(name="added_product_updated").calories_per_100 == 200
def test_product_delete_view(self, client, product):
client.login(username="test_user", password="<PASSWORD>")
response = client.post(reverse("product-delete", args=[product.pk]))
assert response.status_code == 302
assert Product.objects.count() == 0
<file_sep>/apps/diet_composer/tests/test_products_models.py
import pytest
from django.contrib.auth.models import User
from apps.diet_composer.models import Product, ProductCategory, ProductItem
@pytest.mark.django_db()
class TestProduct:
@pytest.fixture(name="product", scope="class")
def create_product(self, django_db_blocker, django_db_setup):
with django_db_blocker.unblock():
user = User.objects.create_user(
username="test_user", email="<EMAIL>", password="<PASSWORD>"
)
category = ProductCategory.objects.create(name="Test Category")
product = Product.objects.create(
category=category,
name="Test Product",
calories_per_100=100,
proteins_per_100=50,
fats_per_100=50,
carbohydrates_per_100=50,
weight_of_pcs=100,
author=user,
)
yield product
with django_db_blocker.unblock():
product.delete()
category.delete()
user.delete()
def test_product_name(self, product):
assert (
str(product)
== f"{product.name}, weight of piece/packege {product.weight_of_pcs} g"
)
def test_product(self, product):
assert product.name == "Test Product"
assert product.author.username == "test_user"
assert product.category.name == "Test Category"
@pytest.mark.django_db()
class TestProductItem:
@pytest.fixture(name="product_item", scope="class")
def create_productitem(self, django_db_blocker, django_db_setup):
with django_db_blocker.unblock():
user = User.objects.create_user(
username="test_user1", email="<EMAIL>", password="<PASSWORD>"
)
category = ProductCategory.objects.create(name="Test Category2")
product = Product.objects.create(
category=category,
name="Test Product",
calories_per_100=100,
proteins_per_100=50,
fats_per_100=50,
carbohydrates_per_100=50,
weight_of_pcs=100,
author=user,
)
product_item = ProductItem(
product=product, category=category, unit="g", weight=150
)
yield product_item
with django_db_blocker.unblock():
product.delete()
category.delete()
user.delete()
def test_product_item_name(self, product_item):
assert (
str(product_item)
== f"Ingredient: {product_item.product.name}, {product_item.weight_of_pcs} g"
)
def test_product_calories(self, product_item):
assert product_item.calories == 150
def test_product_weight_of_pcs(self, product_item):
assert product_item.weight_of_pcs == 150
def test_product_proteins(self, product_item):
assert product_item.proteins == 75
def test_product_fats(self, product_item):
assert product_item.fats == 75
def test_product_carbohydrates(self, product_item):
assert product_item.carbohydrates == 75
def test_product_weight_piece(self, product_item):
product_item.unit = "piece"
product_item.weight = 1
assert product_item.weight_of_pcs == 100
<file_sep>/apps/diet_composer/migrations/0011_auto_20201015_2122.py
# Generated by Django 3.1 on 2020-10-15 21:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("diet_composer", "0010_auto_20201014_2132"),
]
operations = [
migrations.AlterField(
model_name="meal",
name="name",
field=models.CharField(
choices=[
("Breakfast", "Breakfast"),
("Lunch", "Lunch"),
("Dinner", "Dinner"),
("Afternoon snack", "Snack"),
("Post-workout meal", "Post Workout"),
("Supper", "Supper"),
],
max_length=50,
),
),
migrations.AlterField(
model_name="recipeitem",
name="piece",
field=models.DecimalField(decimal_places=2, max_digits=4, max_length=150),
),
]
<file_sep>/apps/diet_composer/tests/test_daily_menu_model.py
import pytest
from django.contrib.auth.models import User
from apps.diet_composer.models import DailyMenu
@pytest.mark.django_db()
class TestDailyMenu:
@pytest.fixture(name="menu", scope="class")
def create_menu(self, django_db_blocker, django_db_setup):
with django_db_blocker.unblock():
user = User.objects.create_user(
username="test_user", email="<EMAIL>", password="<PASSWORD>"
)
daily_menu = DailyMenu(name="Test Menu", number_of_meals=3, author=user)
daily_menu.save()
daily_menu.meals.create(name="Test Meal")
yield daily_menu
with django_db_blocker.unblock():
daily_menu.delete()
user.delete()
def test_menu_str(self, menu):
assert str(menu) == "Daily Menu Test Menu created by test_user"
def test_menu_calories(self, menu):
assert menu.total_calories == 0
def test_menu_proteins(self, menu):
assert menu.total_proteins == 0
def test_menu_fats(self, menu):
assert menu.total_fats == 0
def test_menu_carbohydrates(self, menu):
assert menu.total_carbohydrates == 0
<file_sep>/apps/users/tests/test_models.py
import pytest
from django.contrib.auth.models import User
from apps.users.models import UserActivity
@pytest.mark.django_db(True)
class TestModels:
@pytest.fixture(name="user", scope="class")
def create_user_obj(self, django_db_blocker, django_db_setup):
with django_db_blocker.unblock():
user = User.objects.create_user(
username="test_user", email="<EMAIL>", password="<PASSWORD>",
)
yield user
with django_db_blocker.unblock():
user.delete()
def test_user_profile(self, user):
assert user.profile
assert str(user.profile) == "test_user profile"
assert user.profile.image.url == "/media/default.jpg"
def test_profile_properties(self, user):
activity = UserActivity.objects.create(factor=1.2, description="activity")
user.profile.age = 25
user.profile.height = 190
user.profile.gender = "Male"
user.profile.weight = 80
user.profile.activity = activity
assert user.profile.cmr == 2242
assert user.profile.bmr == 1868.7
assert user.profile.daily_proteins == 112.0
assert user.profile.daily_carb == 308.0
assert user.profile.daily_fats == 62
<file_sep>/apps/diet_composer/models/__init__.py
from apps.diet_composer.models.daily_menu import DailyMenu
from apps.diet_composer.models.meal import Meal
from apps.diet_composer.models.product import Product, ProductCategory, ProductItem
from apps.diet_composer.models.recipe_item import RecipeItem
<file_sep>/apps/diet_blog/tests/test_view.py
import pytest
from django.contrib.auth.models import User
from django.urls import reverse
from apps.diet_blog.models import Comment, Post
@pytest.mark.django_db
class TestPostView:
@pytest.fixture(name="post", scope="class")
def create_post(self, django_db_blocker, django_db_setup):
with django_db_blocker.unblock():
user = User.objects.create_user(
username="test_user", email="<EMAIL>", password="<PASSWORD>"
)
post = Post.objects.create(
title="Test post", content="Test content", author=user
)
yield post
with django_db_blocker.unblock():
post.delete()
user.delete()
def test_blog_view(self, client, post):
response = client.get(reverse("diet_composer-blog"))
assert response.status_code == 200
assert "Main Page" in str(response.content)
assert "Diet composer" in str(response.content)
assert "diet_blog/blog.html" in [
template.name for template in response.templates
]
assert post.content == "Test content"
assert post.author.username == "test_user"
assert post.author.email == "<EMAIL>"
def test_post_detail_view(self, client, post):
response = client.get(reverse("post-detail", kwargs={"pk": post.pk}))
assert response.status_code == 200
assert post.content == "Test content"
assert post.author.username == "test_user"
assert "diet_blog/post_detail.html" in [
template.name for template in response.templates
]
assert post.author.profile.image.url == "/media/default.jpg"
def test_post_update_view(self, client, post):
client.login(username="test_user", password="<PASSWORD>")
response = client.post(
reverse("post-update", kwargs={"pk": post.pk}),
{
"title": "test_post111",
"content": "newcontent",
},
)
post.refresh_from_db()
assert response.status_code == 302
assert post.content == "newcontent"
assert post.title == "test_post111"
def test_post_create_view(self, client):
client.login(username="test_user", password="<PASSWORD>")
response = client.post(
reverse("post-create"),
{
"title": "new_post",
"content": "new post content",
},
)
assert response.status_code == 302
assert Post.objects.last().title == "new_post"
assert Post.objects.last().content == "new post content"
def test_post_create_view_fail(self, client):
client.login(username="test_user", password="<PASSWORD>")
response = client.post(reverse("post-create"), {})
assert response.status_code == 200
assert "This field is required." in str(response.content)
def test_post_delete_view(self, client, post):
client.login(username="test_user", password="<PASSWORD>")
response = client.post(reverse("post-delete", kwargs={"pk": post.pk}))
assert response.status_code == 302
assert not Post.objects.first()
def test_user_posts_view(self, client):
client.login(username="test_user", password="<PASSWORD>")
response = client.get(reverse("user-posts", kwargs={"username": "test_user"}))
assert response.status_code == 200
assert "Posts by test_user (1)" in str(response.content)
assert response.context[0]["posts"].count() == 1
assert response.context[0]["page_obj"].number == 1
@pytest.mark.django_db
class TestCommentView:
@pytest.fixture(name="user", scope="class")
def create_user(self, django_db_blocker, django_db_setup):
with django_db_blocker.unblock():
user = User.objects.create_user(
username="test_user", email="<EMAIL>", password="<PASSWORD>"
)
yield user
with django_db_blocker.unblock():
user.delete()
@pytest.fixture(name="post", scope="class")
def create_post(self, django_db_blocker, django_db_setup, user):
with django_db_blocker.unblock():
post = Post.objects.create(
title="Test post", content="Test content", author=user
)
yield post
with django_db_blocker.unblock():
post.delete()
@pytest.fixture(name="comment", scope="class")
def create_comment(self, django_db_blocker, django_db_setup, user, post):
with django_db_blocker.unblock():
comment = Comment.objects.create(
content="Test content", author=user, post=post
)
yield comment
with django_db_blocker.unblock():
comment.delete()
def test_comment_view(self, client, post):
client.login(username="test_user", password="<PASSWORD>")
response = client.post(
reverse("comment-create", kwargs={"pk": post.pk}),
{"content": "test comment content", "post": post},
)
assert response.status_code == 302
assert post.comments.count() == 1
assert post.comments.all()[0].content == "test comment content"
assert post.comments.all()[0].author.username == "test_user"
def test_comment_update_view(self, client, post, comment):
client.login(username="test_user", password="<PASSWORD>")
response = client.post(
reverse("comment-update", kwargs={"pk": comment.pk}),
{"content": "Test content 123", "post": post},
)
assert response.status_code == 302
assert post.comments.all()[0].content == "Test content 123"
def test_comment_delete_view(self, client, post, comment):
client.login(username="test_user", password="<PASSWORD>5")
response = client.post(reverse("comment-delete", kwargs={"pk": comment.pk}))
assert response.status_code == 302
assert post.comments.count() == 0
@pytest.mark.django_db
class TestLikeView:
@pytest.fixture(name="post", scope="class")
def create_post(self, django_db_blocker, django_db_setup):
with django_db_blocker.unblock():
user = User.objects.create_user(
username="test_user", email="<EMAIL>", password="<PASSWORD>"
)
user.save()
post = Post.objects.create(
title="Test post", content="Test content", author=user
)
post.save()
yield post
with django_db_blocker.unblock():
post.delete()
user.delete()
def test_like_view(self, post, client):
client.login(username="test_user", password="<PASSWORD>")
response = client.post(
reverse("like-post", kwargs={"pk": post.pk}), {"post_id": post.pk}
)
assert response.status_code == 302
assert post.likes.count() == 1
<file_sep>/apps/users/admin.py
from django.contrib import admin
from .models import Profile, UserActivity
admin.site.register(Profile)
admin.site.register(UserActivity)
<file_sep>/apps/diet_blog/apps.py
from django.apps import AppConfig
class DietBlogConfig(AppConfig):
name = "apps.diet_blog"
<file_sep>/apps/diet_composer/views.py
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.auth.models import User
from django.contrib.messages.views import SuccessMessageMixin
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse_lazy
from django.views.generic import (
CreateView,
DeleteView,
DetailView,
ListView,
UpdateView,
)
from apps.diet_composer.forms import ProductForm, ProductItemForm
from apps.diet_composer.models import DailyMenu, Meal, Product, ProductItem, RecipeItem
from apps.diet_composer.utils import check_nutritional_status
from apps.recipes.models import Recipe
class ProductCreateView(LoginRequiredMixin, CreateView):
model = Product
form_class = ProductForm
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def get_success_url(self):
return reverse_lazy("products-list", args=[self.request.user.username])
class ProductListView(ListView):
model = Product
template_name = "diet_composer/product_list.html"
context_object_name = "products"
paginate_by = 10
def get_queryset(self):
user = get_object_or_404(User, username=self.kwargs.get("username"))
return Product.objects.filter(author=user)
class ProductUpdateView(LoginRequiredMixin, SuccessMessageMixin, UpdateView):
model = Product
form_class = ProductForm
def get_success_url(self):
return reverse_lazy("products-list", args=[self.request.user.username])
def get_success_message(self, cleaned_data):
return f"Successfully edited product: {cleaned_data['name']}"
class ProductDeleteView(
LoginRequiredMixin, UserPassesTestMixin, SuccessMessageMixin, DeleteView
):
model = Product
def get_success_url(self):
return reverse_lazy("products-list", args=[self.request.user.username])
def test_func(self):
product = Product.objects.get(pk=self.kwargs["pk"])
if self.request.user == product.author:
return True
return False
class ProductItemCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView):
template_name = "diet_composer/productitem_form.html"
form_class = ProductItemForm
success_message = "Ingredient added to meal"
def form_valid(self, form):
menu = DailyMenu.objects.get(id=self.kwargs["menu_id"])
meal = Meal.objects.get(id=self.kwargs["meal_id"])
if form.is_valid():
category = form.cleaned_data["category"]
product = form.cleaned_data["product"]
weight = form.cleaned_data["weight"]
unit = form.cleaned_data["unit"]
ingredient = ProductItem.objects.create(
category=category, product=product, weight=weight, unit=unit
)
if check_nutritional_status(self.request.user, menu, ingredient):
ingredient.save()
meal.ingredients.add(ingredient)
messages.success(
self.request,
message=f"Successfully added ingredient to {meal.name}",
)
else:
messages.error(
self.request,
message="The nutritional value of your menu has exceeded your personal limit",
)
return HttpResponseRedirect(
reverse_lazy("menu-details", args=[self.kwargs["menu_id"]])
)
class ProductItemUpdateView(LoginRequiredMixin, SuccessMessageMixin, UpdateView):
template_name = "diet_composer/productitem_form.html"
form_class = ProductItemForm
model = ProductItem
def get_success_url(self):
return reverse_lazy("menu-details", kwargs={"pk": self.kwargs["menu_id"]})
def get_success_message(self, cleaned_data):
return f"Successfully edited ingredient: {cleaned_data['product'].name}"
class ProductItemDeleteView(
LoginRequiredMixin, UserPassesTestMixin, SuccessMessageMixin, DeleteView
):
model = ProductItem
def get_success_url(self):
return reverse_lazy("menu-details", kwargs={"pk": self.kwargs["menu_id"]})
def test_func(self):
menu = DailyMenu.objects.get(id=self.kwargs["menu_id"])
if self.request.user == menu.author:
return True
return False
def load_products(request):
category_id = request.GET.get("category")
products = Product.objects.filter(category_id=category_id).order_by("name")
return render(
request,
"diet_composer/product_dropdown_list_options.html",
{"products": products},
)
class UserMenuListView(ListView):
model = DailyMenu
template_name = "diet_composer/user_menus.html"
context_object_name = "menus"
paginate_by = 7
def get_queryset(self):
user = get_object_or_404(User, username=self.kwargs.get("username"))
return DailyMenu.objects.filter(author=user)
class MenuCreateView(LoginRequiredMixin, CreateView):
template_name = "diet_composer/create_menu.html"
model = DailyMenu
fields = ["name", "number_of_meals"]
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def get_success_url(self):
return reverse_lazy(
"user-menus", kwargs={"username": self.object.author.username}
)
class MenuDetailView(DetailView):
model = DailyMenu
template_name = "diet_composer/menu_detail.html"
class MenuUpdateView(LoginRequiredMixin, SuccessMessageMixin, UpdateView):
model = DailyMenu
fields = ["name", "number_of_meals"]
template_name = "diet_composer/create_menu.html"
def get_success_message(self, cleaned_data):
return f"Successfully edited menu: {cleaned_data['name']}"
def get_success_url(self):
return reverse_lazy(
"user-menus", kwargs={"username": self.object.author.username}
)
class MenuDeleteView(
LoginRequiredMixin, UserPassesTestMixin, SuccessMessageMixin, DeleteView
):
model = DailyMenu
template_name = "diet_composer/menu_confirm_delete.html"
def get_success_url(self):
return reverse_lazy(
"user-menus", kwargs={"username": self.object.author.username}
)
def test_func(self):
menu = self.get_object()
if self.request.user == menu.author:
return True
return False
class MealCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView):
model = Meal
fields = ["name"]
success_message = "Succesfully added meal to your Menu"
def form_valid(self, form):
menu = DailyMenu.objects.get(id=self.kwargs["pk"])
if form.is_valid() and menu.meals.count() < menu.number_of_meals:
name = form.cleaned_data["name"]
meal = Meal(name=name)
meal.save()
menu.meals.add(meal)
messages.success(
self.request, message="Succesfully added meal to your Menu"
)
else:
messages.error(
self.request, message=f"Max number of meals achieved for {menu.name}"
)
return HttpResponseRedirect(
reverse_lazy("menu-details", args=[self.kwargs["pk"]])
)
class MealDeleteView(LoginRequiredMixin, UserPassesTestMixin, SuccessMessageMixin, DeleteView):
model = Meal
template_name = "diet_composer/meal_confirm_delete.html"
def get_success_url(self):
return reverse_lazy("menu-details", kwargs={"pk": self.kwargs["menu_id"]})
def test_func(self):
menu = DailyMenu.objects.get(id=self.kwargs["menu_id"])
if self.request.user == menu.author:
return True
return False
class RecipeItemCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView):
model = RecipeItem
fields = "__all__"
success_message = "Recipe added to meal"
def form_valid(self, form):
menu = DailyMenu.objects.get(id=self.kwargs["menu_id"])
meal = Meal.objects.get(id=self.kwargs["meal_id"])
if form.is_valid():
category = form.cleaned_data["recipe_category"]
recipe = form.cleaned_data["recipe"]
piece = form.cleaned_data["piece"]
recipeitem = RecipeItem(
recipe_category=category, recipe=recipe, piece=piece
)
if check_nutritional_status(self.request.user, menu, recipeitem):
recipeitem.save()
meal.recipes.add(recipeitem)
messages.success(
self.request,
message=f"Successfully added recipe to {meal.name}",
)
else:
messages.error(
self.request,
message="The nutritional value of your menu has exceeded your personal limit",
)
return HttpResponseRedirect(
reverse_lazy("menu-details", args=[self.kwargs["menu_id"]])
)
class RecipeItemUpdateView(LoginRequiredMixin, SuccessMessageMixin, UpdateView):
model = RecipeItem
fields = "__all__"
def get_success_url(self):
return reverse_lazy("menu-details", kwargs={"pk": self.kwargs["menu_id"]})
def get_success_message(self, cleaned_data):
return f"Successfully edited recipe: {cleaned_data['recipe'].title}"
class RecipeItemDeleteView(
LoginRequiredMixin, UserPassesTestMixin, SuccessMessageMixin, DeleteView
):
model = RecipeItem
def get_success_url(self):
return reverse_lazy("menu-details", kwargs={"pk": self.kwargs["menu_id"]})
def test_func(self):
menu = DailyMenu.objects.get(id=self.kwargs["menu_id"])
if self.request.user == menu.author:
return True
return False
def load_recipes(request):
category_id = request.GET.get("recipe_category")
recipes = Recipe.objects.filter(category_id=category_id).order_by("title")
return render(
request,
"diet_composer/recipe_dropdown_list_options.html",
{"recipes": recipes},
)
<file_sep>/apps/diet_composer/migrations/0009_auto_20201014_2049.py
# Generated by Django 3.1 on 2020-10-14 20:49
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("recipes", "0007_auto_20201014_2049"),
("diet_composer", "0008_auto_20201013_2023"),
]
operations = [
migrations.CreateModel(
name="RecipeItem",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"piece",
models.DecimalField(decimal_places=1, max_digits=3, max_length=150),
),
(
"category",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to="recipes.category",
),
),
(
"recipe",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE, to="recipes.recipe"
),
),
],
),
migrations.AddField(
model_name="meal",
name="recipes",
field=models.ManyToManyField(
related_name="meals", to="diet_composer.RecipeItem"
),
),
]
<file_sep>/apps/recipes/tests/test_views.py
import os
from pathlib import Path
import pytest
from django.contrib.auth.models import User
from django.core.files.uploadedfile import SimpleUploadedFile
from django.urls import reverse
from apps.recipes.models import Category, Recipe
BASE_DIR = Path(__file__).resolve(strict=True).parent.parent.parent.parent
@pytest.mark.django_db
class TestRecipeView:
@pytest.fixture(name="user", scope="class")
def create_user(self, django_db_blocker, django_db_setup):
with django_db_blocker.unblock():
user = User.objects.create_user(
username="test_user", email="<EMAIL>", password="<PASSWORD>"
)
yield user
with django_db_blocker.unblock():
user.delete()
@pytest.fixture(name="recipe", scope="class")
def create_recipe(self, django_db_blocker, django_db_setup, user):
with django_db_blocker.unblock():
category = Category.objects.create(name="cat1")
recipe = Recipe.objects.create(
title="Test recipe",
description="Test description",
author=user,
preparation_time="10min",
ingredients="test ingredients",
category=category,
total_calories=100,
total_proteins=100,
total_fats=50,
total_carbohydrates=50,
)
yield recipe
with django_db_blocker.unblock():
recipe.delete()
category.delete()
def test_recipe_view(self, client, recipe, user):
response = client.get(reverse("diet_composer-recipes"))
assert response.status_code == 200
assert "recipes/recipes.html" in [
template.name for template in response.templates
]
content = str(response.content)
assert "Test recipe" in content
assert "/media/default_recipe.png" in content
assert "Test description" in content
assert user.username in content
def test_recipe_create_view(self, client, recipe):
client.login(username="test_user", password="<PASSWORD>")
response = client.post(
reverse("recipe-create"),
data={
"category": recipe.category.id,
"title": "Test recipe 2",
"preparation_time": "20 min",
"description": "Test description 2",
"ingredients": "test ingredients",
"total_calories": 100,
"total_proteins": 100,
"total_fats": 50,
"total_carbohydrates": 50,
"tags": "tag",
},
)
assert response.status_code == 302
assert Recipe.objects.count() == 2
assert Recipe.objects.last().title == "Test recipe 2"
assert Recipe.objects.last().preparation_time == "20 min"
def test_recipe_create_view_fail(self, client, recipe):
client.login(username="test_user", password="<PASSWORD>")
response = client.post(reverse("recipe-create"), data={})
assert response.status_code == 200
assert Recipe.objects.count() == 1
def test_recipe_update_view(self, client, recipe):
image_path = os.path.join(BASE_DIR, "media/test_pics/joker.jpg")
client.login(username="test_user", password="<PASSWORD>")
response = client.post(
reverse("recipe-update", kwargs={"pk": recipe.pk}),
data={
"category": recipe.category.id,
"title": "Test recipe changed",
"preparation_time": "40 min",
"description": "Test description changed",
"ingredients": "test ingredients changed",
"total_calories": 100,
"total_proteins": 100,
"total_fats": 50,
"tags": "tag",
"total_carbohydrates": 50,
"image": SimpleUploadedFile(
name="joker.jpg",
content=open(image_path, "rb").read(),
content_type="image/jpg",
),
},
)
recipe.refresh_from_db()
assert response.status_code == 302
assert Recipe.objects.count() == 1
assert Recipe.objects.first().title == "Test recipe changed"
assert Recipe.objects.first().description == "Test description changed"
assert Recipe.objects.first().image.path == os.path.join(
BASE_DIR, "media/recipes_pics/joker.jpg"
)
def test_recipe_detail_view(self, client, recipe, user):
response = client.get(reverse("recipe-detail", kwargs={"pk": recipe.pk}))
assert response.status_code == 200
assert "recipes/recipe_detail.html" in [
template.name for template in response.templates
]
content = str(response.content)
assert "Test recipe" in content
assert "/media/default_recipe.png" in content
assert "Test description" in content
assert response.context["total_likes"] == 0
assert user.username in content
def test_recipe_delete_view(self, client, recipe):
client.login(username="test_user", password="<PASSWORD>")
response = client.post(reverse("recipe-delete", kwargs={"pk": recipe.id}))
assert response.status_code == 302
assert not Recipe.objects.first()
@pytest.mark.django_db
class TestLikeView:
@pytest.fixture(name="recipe", scope="class")
def create_post(self, django_db_blocker, django_db_setup):
with django_db_blocker.unblock():
user = User.objects.create_user(
username="test_user", email="<EMAIL>", password="<PASSWORD>"
)
user.save()
category = Category.objects.create(name="cat2")
recipe = Recipe.objects.create(
title="Test recipe",
description="Test description",
author=user,
preparation_time="10min",
ingredients="test ingredients",
category=category,
total_calories=100,
total_proteins=100,
total_fats=50,
total_carbohydrates=50,
)
recipe.save()
yield recipe
with django_db_blocker.unblock():
recipe.delete()
user.delete()
def test_like_view(self, recipe, client):
client.login(username="test_user", password="<PASSWORD>")
response = client.post(
reverse("recipe-like", kwargs={"pk": recipe.pk}), {"recipe_id": recipe.pk}
)
assert response.status_code == 302
assert recipe.likes.count() == 1
<file_sep>/apps/diet_blog/context_processors.py
from apps.diet_blog.models import Post
def all_posts(request):
return {"all_posts": Post.objects.all()}
<file_sep>/apps/users/utils.py
from django.core.exceptions import ValidationError
from PIL import Image
def change_pic_size(path, size1, size2) -> None:
img = Image.open(path)
if img.height > size1 or img.width > size2:
output_size = (size1, size2)
img.thumbnail(output_size)
img.save(path)
def validate_age(value):
if value > 110:
raise ValidationError(f"Enter correct age value")
return True
def calculate_bmr(weight, height, age, gender) -> float:
if gender == "Male":
return round((9.99 * float(weight) + 6.25 * float(height) - 4.92 * age + 5), 2)
elif gender == "Female":
return round(
(9.99 * float(weight) + 6.25 * float(height) - 4.92 * age - 161), 2
)
def calculate_cmr(bmr, activity) -> float:
return round(bmr * activity, 0)
def calc_daily_proteins(cmr) -> float:
FACTOR = 0.2
CALORIES_PER_GRAM = 4
return round((cmr * FACTOR) / CALORIES_PER_GRAM, 0)
def calc_daily_fats(cmr) -> float:
FACTOR = 0.25
CALORIES_PER_GRAM = 9
return round((cmr * FACTOR) / CALORIES_PER_GRAM, 0)
def calc_daily_carb(cmr) -> float:
FACTOR = 0.55
CALORIES_PER_GRAM = 4
return round((cmr * FACTOR) / CALORIES_PER_GRAM, 0)
<file_sep>/apps/diet_composer/tests/test_utils.py
import pytest
from unittest.mock import MagicMock
from decimal import Decimal
from apps.diet_composer.utils import (
calculate_params,
check_nutritional_status,
calculate_total_value_menu,
calculate_total_value_meal,
calculate_recipe_nutri,
calculate_weight,
)
def test_calculate_params():
unit1 = "g"
unit2 = "piece"
value_to_calc = Decimal(10.5)
weight1 = Decimal(50)
weight2 = Decimal(2)
weight_in_pcs = Decimal(100)
assert calculate_params(unit1, value_to_calc, weight1, weight_in_pcs) == 5.25
assert calculate_params(unit2, value_to_calc, weight2, weight_in_pcs) == 21
@pytest.fixture(name="menu", scope="function")
def create_menu():
menu = MagicMock(total_calories=100, total_proteins=20, total_fats=10, total_carbohydrates=10)
return menu
@pytest.fixture(name="ingredient", scope="function")
def create_ingredient():
ingredient = MagicMock(calories=100, proteins=20, fats=10, carbohydrates=10)
return ingredient
@pytest.fixture(name="user1", scope="function")
def create_user1():
attrs = {'profile.cmr': 1000,
'profile.daily_proteins': 80,
'profile.daily_fats': 80,
'profile.daily_carb': 80,
}
user1 = MagicMock(**attrs)
return user1
@pytest.fixture(name="user2", scope="function")
def create_user2():
attrs = {'profile.cmr': 100,
'profile.daily_proteins': 50,
'profile.daily_fats': 50,
'profile.daily_carb': 80,
}
user2 = MagicMock(**attrs)
return user2
def test_check_nutritional_status(menu, ingredient, user1, user2):
assert check_nutritional_status(user1, menu, ingredient)
assert not check_nutritional_status(user2, menu, ingredient)
def test_total_value_menu():
meal1 = MagicMock(total_calories=100, total_proteins=10, total_fats=5, total_carbohydrates=13)
meal2 = MagicMock(total_calories=98, total_proteins=20, total_fats=6, total_carbohydrates=5)
lst_meals = [meal1, meal2]
assert calculate_total_value_menu(lst_meals, "calories") == 198
assert calculate_total_value_menu(lst_meals, "proteins") == 30
assert calculate_total_value_menu(lst_meals, "fats") == 11
assert calculate_total_value_menu(lst_meals, "carbohydrates") == 18
def test_calculate_total_value_meal():
ingredient1 = MagicMock(calories=10, proteins=5, fats=8, carbohydrates=6)
ingredient2 = MagicMock(calories=10, proteins=5, fats=8, carbohydrates=6)
recipe1 = MagicMock(calories=100, proteins=15, fats=20, carbohydrates=80)
lst_ingredients = [ingredient1, ingredient2]
lst_recipes = [recipe1]
assert calculate_total_value_meal(lst_ingredients, lst_recipes, "calories") == 120
assert calculate_total_value_meal(lst_ingredients, lst_recipes, "proteins") == 25
assert calculate_total_value_meal(lst_ingredients, lst_recipes, "fats") == 36
assert calculate_total_value_meal(lst_ingredients, lst_recipes, "carbohydrates") == 92
def test_calc_recipe_nutri():
calories = Decimal(100.25)
piece = Decimal(1.5)
assert calculate_recipe_nutri(calories, piece) == 150.38
def test_calc_weight():
unit1 = "g"
unit2 = "piece"
weight1 = Decimal(15)
weight2 = Decimal(1)
weight_pcs = Decimal(100)
assert calculate_weight(unit1, weight1, weight_pcs) == 15
assert calculate_weight(unit2, weight2, weight_pcs) == 100
<file_sep>/apps/recipes/tests/test_urls.py
import pytest
from django.contrib.auth.models import User
from django.urls import resolve, reverse
from apps.recipes.models import Category, Recipe
from apps.recipes.views import (
LikeView,
RecipeCreateView,
RecipeDeleteView,
RecipeDetailView,
RecipesListView,
RecipeUpdateView,
)
@pytest.mark.django_db()
class TestUrls:
@pytest.fixture(scope="class", name="user")
def create_user_obj(self, django_db_blocker):
with django_db_blocker.unblock():
user = User.objects.create_user(username="testuser", password="<PASSWORD>")
yield user
with django_db_blocker.unblock():
user.delete()
@pytest.fixture(scope="class", name="recipe")
def create_recipe_obj(self, django_db_blocker, user):
with django_db_blocker.unblock():
category = Category.objects.create(name="cat1")
recipe = Recipe.objects.create(
title="Test recipe",
description="Test description",
author=user,
preparation_time="10 min",
ingredients="test ingredients",
category=category,
total_calories=100,
total_proteins=100,
total_carbohydrates=100,
total_fats=100,
)
yield recipe
with django_db_blocker.unblock():
recipe.delete()
category.delete()
def test_recipes_url(self):
url = reverse("diet_composer-recipes")
assert resolve(url).func.view_class == RecipesListView
def test_recipe_detail_url(self, recipe):
url = reverse("recipe-detail", kwargs={"pk": recipe.id})
assert resolve(url).func.view_class == RecipeDetailView
def test_create_recipe_url(self):
url = reverse("recipe-create")
assert resolve(url).func.view_class == RecipeCreateView
def test_update_recipe_url(self, recipe):
url = reverse("recipe-update", kwargs={"pk": recipe.id})
assert resolve(url).func.view_class == RecipeUpdateView
def test_delete_recipe_url(self, recipe):
url = reverse("recipe-delete", kwargs={"pk": recipe.id})
assert resolve(url).func.view_class == RecipeDeleteView
def test_like_url(self, user):
url = reverse("recipe-like", kwargs={"pk": user.pk})
assert resolve(url).func == LikeView
<file_sep>/apps/diet_composer/tests/test_recipeitem_model.py
import pytest
from apps.diet_composer.models import RecipeItem
from apps.recipes.models import Recipe, Category
from django.contrib.auth.models import User
@pytest.mark.django_db()
class TestRecipeItem:
@pytest.fixture(name="recipe_item", scope="class")
def create_recipe_item(self, django_db_blocker, django_db_setup):
with django_db_blocker.unblock():
user = User.objects.create_user(
username="test_user", email="<EMAIL>", password="<PASSWORD>"
)
category = Category.objects.create(name="cat1")
recipe = Recipe.objects.create(
title="Test recipe",
description="Test description",
author=user,
preparation_time="10 min",
ingredients="test ingredients",
category=category,
total_calories=100,
total_proteins=50,
total_fats=50,
total_carbohydrates=50,
tags="tag",
)
recipe_item = RecipeItem.objects.create(
recipe_category=category, recipe=recipe, piece=1.5
)
yield recipe_item
with django_db_blocker.unblock():
recipe_item.delete()
recipe.delete()
category.delete()
user.delete()
def test_recipe_item_name(self, recipe_item):
assert str(recipe_item) == "Test recipe item"
def test_recipe_calories(self, recipe_item):
assert recipe_item.calories == 150
def test_recipe_proteins(self, recipe_item):
assert recipe_item.proteins == 75
def test_recipe_fats(self, recipe_item):
assert recipe_item.fats == 75
def test_recipe_carbohydrates(self, recipe_item):
assert recipe_item.carbohydrates == 75
<file_sep>/apps/diet_composer/urls.py
from django.urls import path
from .views import (
MealCreateView,
MealDeleteView,
MenuCreateView,
MenuDeleteView,
MenuDetailView,
MenuUpdateView,
ProductCreateView,
ProductDeleteView,
ProductItemCreateView,
ProductItemDeleteView,
ProductItemUpdateView,
ProductListView,
ProductUpdateView,
RecipeItemCreateView,
RecipeItemDeleteView,
RecipeItemUpdateView,
UserMenuListView,
load_products,
load_recipes,
)
urlpatterns = [
path("menus/user/<str:username>", UserMenuListView.as_view(), name="user-menus"),
path("product/new/", ProductCreateView.as_view(), name="product-create"),
path("products/<str:username>/", ProductListView.as_view(), name="products-list"),
path(
"product/<int:pk>/update/", ProductUpdateView.as_view(), name="product-update"
),
path(
"product/<int:pk>/delete/", ProductDeleteView.as_view(), name="product-delete"
),
path("create-menu/", MenuCreateView.as_view(), name="create-menu"),
path("menu/<int:pk>", MenuDetailView.as_view(), name="menu-details"),
path(
"menu/<str:username>/<int:pk>/update/",
MenuUpdateView.as_view(),
name="menu-update",
),
path(
"menu/<str:username>/<int:pk>/delete/",
MenuDeleteView.as_view(),
name="menu-delete",
),
path(
"menu/<int:menu_id>/meal/<int:meal_id>/add-ingredient",
ProductItemCreateView.as_view(),
name="ingredient-create",
),
path(
"menu/<slug:menu_id>/ingredient/<int:pk>/edit",
ProductItemUpdateView.as_view(),
name="ingredient-edit",
),
path(
"menu/<slug:menu_id>/ingredient/<int:pk>/delete",
ProductItemDeleteView.as_view(),
name="ingredient-delete",
),
path("ajax/load-products/", load_products, name="ajax-load-products"),
path("menu/<int:pk>/create-meal/", MealCreateView.as_view(), name="meal-create"),
path("menu/<slug:menu_id>/meal/<int:pk>/delete", MealDeleteView.as_view(), name="meal-delete"),
path(
"menu/<int:menu_id>/meal/<int:meal_id>/add-recipe",
RecipeItemCreateView.as_view(),
name="recipeitem-create",
),
path(
"menu/<slug:menu_id>/recipe/<int:pk>/edit",
RecipeItemUpdateView.as_view(),
name="recipeitem-edit",
),
path(
"menu/<slug:menu_id>/recipe/<int:pk>/delete",
RecipeItemDeleteView.as_view(),
name="recipeitem-delete",
),
path("ajax/load-recipes/", load_recipes, name="ajax-load-recipes"),
]
<file_sep>/apps/diet_composer/tests/test_menu_views.py
import pytest
from django.contrib.auth.models import User
from django.urls import reverse
from apps.diet_composer.models import DailyMenu
@pytest.mark.django_db
class TestMenuView:
@pytest.fixture(name="user", scope="class")
def create_user(self, django_db_blocker, django_db_setup):
with django_db_blocker.unblock():
user = User.objects.create_user(
username="test_user", email="<EMAIL>", password="<PASSWORD>"
)
yield user
with django_db_blocker.unblock():
user.delete()
@pytest.fixture(name="menu", scope="class")
def create_menu(self, django_db_blocker, django_db_setup, user):
with django_db_blocker.unblock():
menu = DailyMenu.objects.create(
name="test_menu",
number_of_meals=2,
author=user
)
menu.save()
yield menu
with django_db_blocker.unblock():
menu.delete()
def test_menu_create_view(self, client, menu):
client.login(username="test_user", password="<PASSWORD>")
response = client.post(
reverse("create-menu"),
{
"name": "Test Menu",
"number_of_meals": 3
})
assert response.status_code == 302
assert DailyMenu.objects.count() == 2
def test_menu_detail_view(self, client, menu):
client.login(username="test_user", password="<PASSWORD>")
response = client.get(
reverse("menu-details", kwargs={"pk": menu.id})
)
assert response.status_code == 200
def test_menu_update_view(self, client, menu, user):
client.login(username="test_user", password="<PASSWORD>")
response = client.post(
reverse("menu-update", kwargs={"username": user.username,
"pk": menu.id}),
data={
"name": "Updated Test Menu",
"number_of_meals": 5
}
)
menu.refresh_from_db()
assert response.status_code == 302
assert menu.name == "Updated Test Menu"
def test_user_menu_list_view(self, menu, user, client):
client.login(username="test_user", password="<PASSWORD>")
response = client.get(
reverse("user-menus", kwargs={"username": user.username})
)
assert response.status_code == 200
def test_menu_delete_view(self, client, menu, user):
client.login(username="test_user", password="<PASSWORD>")
response = client.post(
reverse("menu-delete", kwargs={"username": user.username,
"pk": menu.id})
)
assert response.status_code == 302
<file_sep>/mysite/views.py
from django.views.generic.base import TemplateView
class HomeView(TemplateView):
template_name = "home.html"
extra_context = {"title": "Home"}
class AboutView(TemplateView):
template_name = "about.html"
extra_context = {"title": "About"}
<file_sep>/apps/recipes/tests/test_models.py
import pytest
from django.contrib.auth.models import User
from apps.recipes.models import Category, Recipe
@pytest.mark.django_db()
class TestRecipe:
@pytest.fixture(name="recipe", scope="class")
def create_recipe(self, django_db_blocker, django_db_setup):
with django_db_blocker.unblock():
user = User.objects.create_user(
username="test_user", email="<EMAIL>", password="<PASSWORD>"
)
category = Category.objects.create(name="cat1")
recipe = Recipe.objects.create(
id=1,
title="Test recipe",
description="Test description",
author=user,
preparation_time="10 min",
ingredients="test ingredients",
category=category,
total_calories=100,
total_proteins=50,
total_fats=50,
total_carbohydrates=50,
)
yield recipe
with django_db_blocker.unblock():
recipe.delete()
category.delete()
user.delete()
def test_blog_obj_name(self, recipe):
assert str(recipe) == "Test recipe"
def test_recipe(self, recipe):
assert isinstance(recipe, Recipe)
assert recipe.title == "Test recipe"
assert recipe.description == "Test description"
assert recipe.author.username == "test_user"
assert recipe.total_likes == 0
assert recipe.category.name == "cat1"
def test_get_absolute_url(self, recipe):
assert recipe.get_absolute_url() == "/recipe/1/"
<file_sep>/apps/users/static/users/users.js
function display_params(){
let params = document.getElementById("params");
if (params.style.display === "block") {
params.style.display = "none";
} else {
params.style.display = "block";
}
}<file_sep>/apps/diet_composer/models/recipe_item.py
from django.db import models
from apps.diet_composer.utils import calculate_recipe_nutri
class RecipeItem(models.Model):
recipe_category = models.ForeignKey("recipes.Category", on_delete=models.CASCADE)
recipe = models.ForeignKey(
"recipes.Recipe", on_delete=models.CASCADE, related_name="recipe_items"
)
piece = models.DecimalField(max_digits=4, decimal_places=2, max_length=150)
def __str__(self):
return f"{self.recipe.title} item"
@property
def calories(self) -> float:
calories = calculate_recipe_nutri(self.recipe.total_calories, self.piece)
return calories
@property
def proteins(self) -> float:
proteins = calculate_recipe_nutri(self.recipe.total_proteins, self.piece)
return proteins
@property
def fats(self) -> float:
fats = calculate_recipe_nutri(self.recipe.total_fats, self.piece)
return fats
@property
def carbohydrates(self) -> float:
carbohydrates = calculate_recipe_nutri(
self.recipe.total_carbohydrates, self.piece
)
return carbohydrates
<file_sep>/apps/diet_blog/tests/test_urls.py
import pytest
from django.contrib.auth.models import User
from django.urls import resolve, reverse
from apps.diet_blog.models import Comment, Post
from apps.diet_blog.views import (
CommentCreateView,
CommentDeleteView,
CommentUpdateView,
LikeView,
PostCreateView,
PostDeleteView,
PostDetailView,
PostListView,
PostUpdateView,
UserPostListView,
)
@pytest.mark.django_db()
class TestUrls:
@pytest.fixture(scope="class", name="user")
def create_user_obj(self, django_db_blocker):
with django_db_blocker.unblock():
user = User.objects.create_user(username="testuser", password="<PASSWORD>")
yield user
with django_db_blocker.unblock():
user.delete()
@pytest.fixture(scope="class", name="post")
def create_post_obj(self, django_db_blocker, user):
with django_db_blocker.unblock():
post = Post.objects.create(
title="Test post", content="Test content", author=user
)
yield post
with django_db_blocker.unblock():
post.delete()
def test_blog_url(self):
url = reverse("diet_composer-blog")
assert resolve(url).func.view_class == PostListView
def test_post_url(self, post):
url = reverse("post-detail", kwargs={"pk": post.id})
assert resolve(url).func.view_class == PostDetailView
def test_create_post_url(self):
url = reverse("post-create")
assert resolve(url).func.view_class == PostCreateView
def test_update_post_url(self, post):
url = reverse("post-update", kwargs={"pk": post.id})
assert resolve(url).func.view_class == PostUpdateView
def test_delete_post_url(self, post):
url = reverse("post-delete", kwargs={"pk": post.id})
assert resolve(url).func.view_class == PostDeleteView
def test_user_posts_url(self, user):
url = reverse("user-posts", kwargs={"username": user.username})
assert resolve(url).func.view_class == UserPostListView
def test_user_comment_url(self, user, post):
comment = Comment.objects.create(content="Test content", author=user, post=post)
url = reverse("comment-create", kwargs={"pk": comment.pk})
assert resolve(url).func.view_class == CommentCreateView
def test_user_comment_update_url(self, user, post):
comment = Comment.objects.create(content="Test content", author=user, post=post)
url = reverse("comment-update", kwargs={"pk": comment.pk})
assert resolve(url).func.view_class == CommentUpdateView
def test_user_comment_delete_url(self, user, post):
comment = Comment.objects.create(content="Test content", author=user, post=post)
url = reverse("comment-delete", kwargs={"pk": comment.pk})
assert resolve(url).func.view_class == CommentDeleteView
def test_like_url(self, user):
url = reverse("like-post", kwargs={"pk": user.pk})
assert resolve(url).func == LikeView
<file_sep>/apps/recipes/context_processors.py
from apps.recipes.models import Recipe
def all_recipes(request):
common_tags = Recipe.tags.most_common()
return {"all_recipes": Recipe.objects.all(), "common_tags": common_tags}
<file_sep>/apps/users/migrations/0003_auto_20201006_1847.py
# Generated by Django 3.1 on 2020-10-06 18:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("users", "0002_auto_20201005_1937"),
]
operations = [
migrations.AlterField(
model_name="profile",
name="gender",
field=models.CharField(
blank=True,
choices=[("Male", "Male"), ("Female", "Female")],
max_length=10,
null=True,
),
),
migrations.AlterField(
model_name="profile",
name="height",
field=models.FloatField(
blank=True, help_text="height in centimeters", null=True
),
),
migrations.AlterField(
model_name="profile",
name="weight",
field=models.FloatField(
blank=True, help_text="weight in kilograms", null=True
),
),
]
<file_sep>/apps/recipes/migrations/0002_recipe_likes.py
# Generated by Django 3.1 on 2020-09-28 18:52
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("recipes", "0001_initial"),
]
operations = [
migrations.AddField(
model_name="recipe",
name="likes",
field=models.ManyToManyField(
related_name="recipe_post", to=settings.AUTH_USER_MODEL
),
),
]
<file_sep>/apps/diet_composer/forms.py
from django import forms
from apps.diet_composer.models import Product, ProductItem
class ProductItemForm(forms.ModelForm):
class Meta:
model = ProductItem
fields = ["category", "product", "weight", "unit"]
# def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
# self.fields['product'].queryset = Product.objects.none()
#
# if 'category' in self.data:
# try:
# category_id = int(self.data.get('category'))
# self.fields['product'].queryset = Product.objects.filter(category_id=category_id).order_by('name')
# except (ValueError, TypeError):
# pass
# elif self.instance.pk:
# self.fields['product'].queryset = self.instance.category.product_set.order_by('name')
class ProductForm(forms.ModelForm):
class Meta:
model = Product
exclude = ("author",)
<file_sep>/apps/users/tests/test_forms.py
import pytest
from apps.users.forms import ProfileUpdateForm, UserRegisterForm, UserUpdateForm
@pytest.mark.django_db
class TestForms:
def test_user_valid_data(self):
form = UserRegisterForm(
data={
"username": "test_user",
"email": "<EMAIL>",
"password1": "<PASSWORD>",
"password2": "<PASSWORD>",
}
)
assert form.is_valid()
def test_user_not_valid_data(self):
form = UserRegisterForm(
data={
"username": "test_user",
"email": "<EMAIL>",
"password1": "<PASSWORD>",
"password2": "<PASSWORD>",
}
)
assert not form.is_valid()
assert len(form.errors) == 1
def test_user_not_valid_data_empty(self):
form = UserRegisterForm(data={})
assert not form.is_valid()
assert len(form.errors) == 4
def test_user_update_form(self):
form = UserUpdateForm(
data={
"username": "test_user",
"email": "<EMAIL>",
}
)
assert form.is_valid()
def test_profile_update_form(self):
form = ProfileUpdateForm(
data={
"username": "test_user",
"email": "<EMAIL>",
"image": "media/default.jpg",
}
)
assert form.is_valid()
<file_sep>/apps/recipes/models/recipe.py
from django.contrib.auth.models import User
from django.db import models
from django.urls import reverse
from django.utils import timezone
from taggit.managers import TaggableManager
from apps.users.utils import change_pic_size
class Category(models.Model):
name = models.CharField(max_length=50, null=False, unique=True)
def __str__(self):
return self.name
class Recipe(models.Model):
title = models.CharField(max_length=100, unique=True)
image = models.ImageField(upload_to="recipes_pics", default="default_recipe.png")
description = models.TextField()
total_calories = models.DecimalField(max_digits=6, decimal_places=2)
total_proteins = models.DecimalField(max_digits=6, decimal_places=2)
total_fats = models.DecimalField(max_digits=6, decimal_places=2)
total_carbohydrates = models.DecimalField(max_digits=6, decimal_places=2)
preparation_time = models.CharField(
help_text="Preparation time in minutes", max_length=10
)
ingredients = models.TextField(
help_text="Separate the ingredients on the list "
"with an enter so that they appear one below the other"
)
date_public = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
category = models.ForeignKey(Category, on_delete=models.PROTECT)
likes = models.ManyToManyField(User, related_name="recipe_post")
tags = TaggableManager()
@property
def total_likes(self):
return self.likes.count()
def __str__(self):
return f"{self.title}"
def save(self, *args, **kwargs) -> None:
super().save(*args, **kwargs)
change_pic_size(self.image.path, 350, 200)
def get_absolute_url(self):
return reverse("recipe-detail", kwargs={"pk": self.pk})
<file_sep>/apps/users/models/models.py
from django.contrib.auth.models import User
from django.db import models
from apps.users.utils import (
calc_daily_carb,
calc_daily_fats,
calc_daily_proteins,
calculate_bmr,
calculate_cmr,
change_pic_size,
validate_age,
)
class UserActivity(models.Model):
description = models.CharField(max_length=150)
factor = models.FloatField()
def __str__(self):
return f"{self.description}, factor: {self.factor}"
class Profile(models.Model):
class Gender(models.TextChoices):
Male = "Male"
Female = "Female"
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile")
image = models.ImageField(default="default.jpg", upload_to="profile_pics")
age = models.PositiveSmallIntegerField(
validators=[validate_age], null=True, blank=True
)
gender = models.CharField(
choices=Gender.choices, max_length=10, null=True, blank=True
)
height = models.DecimalField(
max_digits=4,
decimal_places=1,
null=True,
blank=True,
help_text="height in centimeters",
)
weight = models.DecimalField(
max_digits=4,
decimal_places=1,
null=True,
blank=True,
help_text="weight in kilograms",
)
activity = models.ForeignKey(
UserActivity, on_delete=models.PROTECT, null=True, blank=True
)
def __str__(self) -> str:
return f"{self.user.username} profile"
def save(self, *args, **kwargs) -> None:
super().save(*args, **kwargs)
change_pic_size(self.image.path, 300, 300)
@property
def bmr(self):
if self.weight and self.height and self.age and self.gender:
return calculate_bmr(self.weight, self.height, self.age, self.gender)
@property
def cmr(self):
if self.activity:
return calculate_cmr(self.bmr, self.activity.factor)
@property
def daily_proteins(self):
if self.cmr:
return calc_daily_proteins(self.cmr)
@property
def daily_fats(self):
if self.cmr:
return calc_daily_fats(self.cmr)
@property
def daily_carb(self):
if self.cmr:
return calc_daily_carb(self.cmr)
<file_sep>/apps/recipes/migrations/0004_recipe_tags.py
# Generated by Django 3.1 on 2020-10-01 18:55
import taggit.managers
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("taggit", "0003_taggeditem_add_unique_index"),
("recipes", "0003_auto_20200930_1610"),
]
operations = [
migrations.AddField(
model_name="recipe",
name="tags",
field=taggit.managers.TaggableManager(
help_text="A comma-separated list of tags.",
through="taggit.TaggedItem",
to="taggit.Tag",
verbose_name="Tags",
),
),
]
<file_sep>/apps/diet_composer/tests/test_urls.py
import pytest
from unittest.mock import MagicMock
from django.urls import reverse, resolve
from apps.diet_composer.views import UserMenuListView, ProductCreateView, ProductListView, ProductUpdateView, \
ProductDeleteView, MenuCreateView, MenuDetailView, MenuUpdateView, MenuDeleteView, ProductItemUpdateView, \
ProductItemCreateView, ProductItemDeleteView, load_products, load_recipes, MealCreateView, RecipeItemCreateView, \
RecipeItemUpdateView, RecipeItemDeleteView, MealDeleteView
@pytest.fixture(scope="function", name="user")
def crate_user():
user = MagicMock(id=1, username="tm")
return user
@pytest.fixture(scope="function", name="product")
def crate_product():
product = MagicMock(id=1)
return product
@pytest.fixture(scope="function", name="menu")
def crate_menu():
menu = MagicMock(id=1)
return menu
@pytest.fixture(scope="function", name="meal")
def crate_meal():
meal = MagicMock(id=1)
return meal
@pytest.fixture(scope="function", name="recipe_item")
def crate_recipe():
recipe = MagicMock(id=1)
return recipe
def test_menu_list_url(user):
url = reverse("user-menus", kwargs={"username": user.username})
assert resolve(url).func.view_class == UserMenuListView
def test_new_product_url(user):
url = reverse("product-create")
assert resolve(url).func.view_class == ProductCreateView
def test_products_list_url(user):
url = reverse("products-list", kwargs={"username": user.username})
assert resolve(url).func.view_class == ProductListView
def test_product_update_url(product):
url = reverse("product-update", kwargs={"pk": product.id})
assert resolve(url).func.view_class == ProductUpdateView
def test_product_delete_url(product):
url = reverse("product-delete", kwargs={"pk": product.id})
assert resolve(url).func.view_class == ProductDeleteView
def test_menu_create_url():
url = reverse("create-menu")
assert resolve(url).func.view_class == MenuCreateView
def test_menu_detail_url(menu):
url = reverse("menu-details", kwargs={"pk": menu.id})
assert resolve(url).func.view_class == MenuDetailView
def test_menu_update_view(menu, user):
url = reverse("menu-update", kwargs={"username": user.id, "pk": menu.id})
assert resolve(url).func.view_class == MenuUpdateView
def test_menu_delete_view(menu, user):
url = reverse("menu-delete", kwargs={"username": user.id, "pk": menu.id})
assert resolve(url).func.view_class == MenuDeleteView
def test_ingredient_create_view(menu, meal):
url = reverse("ingredient-create", kwargs={"menu_id": menu.id, "meal_id": meal.id})
assert resolve(url).func.view_class == ProductItemCreateView
def test_ingredient_update_view(menu, product):
url = reverse("ingredient-edit", kwargs={"menu_id": menu.id, "pk": product.id})
assert resolve(url).func.view_class == ProductItemUpdateView
def test_ingredient_delete_view(menu, product):
url = reverse("ingredient-delete", kwargs={"menu_id": menu.id, "pk": product.id})
assert resolve(url).func.view_class == ProductItemDeleteView
def test_ajax_load_products():
url = reverse("ajax-load-products")
assert resolve(url).func == load_products
def test_ajax_load_recipes():
url = reverse("ajax-load-recipes")
assert resolve(url).func == load_recipes
def test_create_meal_url(meal):
url = reverse("meal-create", kwargs={"pk": meal.id})
assert resolve(url).func.view_class == MealCreateView
def test_delete_meal_url(meal, menu):
url = reverse("meal-delete", kwargs={"menu_id": menu.id, "pk": meal.id})
assert resolve(url).func.view_class == MealDeleteView
def test_create_recipe_item(menu, meal):
url = reverse("recipeitem-create", kwargs={"menu_id": menu.id, "meal_id": meal.id})
assert resolve(url).func.view_class == RecipeItemCreateView
def test_recipe_item_update_url(menu, recipe_item):
url = reverse("recipeitem-edit", kwargs={"menu_id": menu.id,"pk": recipe_item.id})
assert resolve(url).func.view_class == RecipeItemUpdateView
def test_recipe_item_delete_url(menu, recipe_item):
url = reverse("recipeitem-delete", kwargs={"menu_id": menu.id,"pk": recipe_item.id})
assert resolve(url).func.view_class == RecipeItemDeleteView<file_sep>/apps/users/tests/test_urls.py
from django.urls import resolve, reverse
from apps.users.views import profile, register
class TestUrls:
def test_profile_url(self):
url = reverse("profile")
assert resolve(url).func == profile
def test_register_url(self):
url = reverse("register")
assert resolve(url).func == register
def test_login_url(self):
path = reverse("login")
assert resolve(path).view_name == "login"
def test_logout_url(self):
path = reverse("logout")
assert resolve(path).view_name == "logout"
def test_password_reset_url(self):
path = reverse("password_reset")
assert resolve(path).view_name == "password_reset"
def test_password_reset_done_url(self):
path = reverse("password_reset_done")
assert resolve(path).view_name == "password_reset_done"
def test_password_reset_confirm_url(self):
path = reverse("password_reset_complete")
assert resolve(path).view_name == "password_reset_complete"
<file_sep>/apps/recipes/migrations/0006_auto_20201014_1816.py
# Generated by Django 3.1 on 2020-10-14 18:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("recipes", "0005_auto_20201014_1756"),
]
operations = [
migrations.AlterField(
model_name="recipe",
name="total_calories",
field=models.DecimalField(decimal_places=2, max_digits=6),
),
migrations.AlterField(
model_name="recipe",
name="total_carbohydrates",
field=models.DecimalField(decimal_places=2, default=0, max_digits=6),
preserve_default=False,
),
migrations.AlterField(
model_name="recipe",
name="total_fats",
field=models.DecimalField(decimal_places=2, max_digits=6),
),
migrations.AlterField(
model_name="recipe",
name="total_proteins",
field=models.DecimalField(decimal_places=2, max_digits=6),
),
]
<file_sep>/apps/diet_composer/tests/test_forms.py
from apps.diet_composer import forms
import pytest
from apps.diet_composer.models import Product, ProductCategory
from django.contrib.auth.models import User
@pytest.mark.django_db
class TestForms:
@pytest.fixture(scope="function", name="product")
def create_product(self, django_db_blocker, django_db_setup, user):
category = ProductCategory.objects.create(name="cat1")
product = Product.objects.create(category=category, name="prod1", calories_per_100=100, proteins_per_100=100,
fats_per_100=100, carbohydrates_per_100=100, author=user)
yield product
with django_db_blocker.unblock():
product.delete()
category.delete()
@pytest.fixture(scope="class", name="user")
def create_user(self, django_db_blocker, django_db_setup):
with django_db_blocker.unblock():
user = User.objects.create(username="user1", password="<PASSWORD>")
yield user
with django_db_blocker.unblock():
user.delete()
def test_product_item_valid_data(self, product):
form = forms.ProductItemForm(
data={
"category": product.category.id,
"product": product.id,
"weight": 100,
"unit": "g",
}
)
assert form.is_valid()
def test_product_form(self, user):
category = ProductCategory.objects.create(name="cat2")
form = forms.ProductForm(
data={
"category": category,
"name": "test_product",
"calories_per_100": 100,
"proteins_per_100": 50,
"fats_per_100": 10,
"carbohydrates_per_100": 80,
"author": user
}
)
assert form.is_valid()<file_sep>/readme.md
## Diet composer project
Application directed to people who want adapt diet to their lifestyle, body parameters and to be fit!
You can:
- create your own diet based on products from DB
- blog with other users on topics related with diet
- add Recipe ( nutritional parameters - must have !)
- added Recipe can be used by other users in their Diet
- register and get your own account
Project created in Django
Run with docker:
- docker-compose build
- docker-compose up
- docker exec -it diet_composer_web_1 bash
- pyhon manage.py migrate
- python manage.py createsuperuser (admin)
- http://127.0.0.1:8000
Run manually:
- git clone <repo> .
- virtualenv venv
- source venv/bin/activate
- pip install -r requirements.txt
- python3 manage.py migrate
- python3 manage.py runserver
- http://127.0.0.1:8000/
- register and login
or
http://tomekmatuszewski.pythonanywhere.com/
All tested in Pytest
to check - pytest .
Front-End part created in Bootstrap with JavaScript
Some screens:




<file_sep>/apps/recipes/urls.py
from django.urls import path
from .views import (
LikeView,
RecipeCreateView,
RecipeDeleteView,
RecipeDetailView,
RecipesListView,
RecipeUpdateView,
)
urlpatterns = [
path("recipes/", RecipesListView.as_view(), name="diet_composer-recipes"),
path("recipe/<int:pk>/", RecipeDetailView.as_view(), name="recipe-detail"),
path("recipe/new", RecipeCreateView.as_view(), name="recipe-create"),
path("recipe/<int:pk>/update/", RecipeUpdateView.as_view(), name="recipe-update"),
path("recipe/<int:pk>/delete/", RecipeDeleteView.as_view(), name="recipe-delete"),
path("recipe-like/<int:pk>", LikeView, name="recipe-like"),
]
<file_sep>/apps/diet_composer/migrations/0010_auto_20201014_2132.py
# Generated by Django 3.1 on 2020-10-14 21:32
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("diet_composer", "0009_auto_20201014_2049"),
]
operations = [
migrations.RenameField(
model_name="recipeitem",
old_name="category",
new_name="recipe_category",
),
]
<file_sep>/apps/diet_blog/models/post_comment.py
from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone
from apps.diet_blog.models import Post
class Comment(models.Model):
content = models.TextField()
date_comment = models.DateTimeField(default=timezone.now)
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments")
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return f"Comment {self.id} to post {self.post.title}"
<file_sep>/apps/diet_composer/tests/test_recipe_item_view.py
import pytest
from django.contrib.auth.models import User
from django.urls import reverse
from apps.diet_composer.models import RecipeItem, Meal, DailyMenu
from apps.recipes.models import Recipe, Category
from apps.users.models import UserActivity
@pytest.mark.django_db
class TestRecipeItemView:
@pytest.fixture(name="user", scope="class")
def create_user(self, django_db_blocker, django_db_setup):
with django_db_blocker.unblock():
user = User.objects.create_user(
username="test_user", email="<EMAIL>", password="<PASSWORD>"
)
activity = UserActivity.objects.create(factor=1.2, description="activity")
activity.save()
user.profile.age = 25
user.profile.height = 190
user.profile.gender = "Male"
user.profile.weight = 80
user.profile.activity = activity
user.profile.save()
yield user
with django_db_blocker.unblock():
user.delete()
activity.delete()
@pytest.fixture(name="recipe", scope="class")
def create_recipe(self, django_db_blocker, django_db_setup, user):
with django_db_blocker.unblock():
category = Category.objects.create(name="testing cat")
category.save()
recipe = Recipe.objects.create(
category=category,
title="Recipe test",
description="xxx",
total_calories=100,
total_proteins=50,
total_fats=30,
total_carbohydrates=50,
preparation_time="10",
ingredients="xxx",
tags="Tag",
author=user
)
recipe.save()
yield recipe
with django_db_blocker.unblock():
recipe.delete()
category.delete()
@pytest.fixture(name="menu", scope="class")
def create_menu(self, django_db_blocker, django_db_setup, user):
with django_db_blocker.unblock():
menu = DailyMenu.objects.create(
name="test_menu",
number_of_meals=2,
author=user
)
menu.save()
yield menu
with django_db_blocker.unblock():
menu.delete()
@pytest.fixture(name="meal", scope="class")
def create_meal(self, django_db_blocker, django_db_setup, menu):
with django_db_blocker.unblock():
meal = Meal.objects.create(
name="test_meal"
)
meal.save()
menu.meals.add(meal)
yield meal
def test_create_recipe_item(self, client, recipe, user, menu, meal):
client.login(username="test_user", password="<PASSWORD>")
response = client.post(reverse("recipeitem-create", kwargs={"menu_id": menu.id, "meal_id": meal.id}),
data={
"recipe_category": recipe.category.id,
"recipe": recipe.id,
"piece": 1,
})
assert response.status_code == 302
assert RecipeItem.objects.count() == 1
id_ = RecipeItem.objects.first().id
response = client.post(reverse("recipeitem-edit", kwargs={"menu_id": menu.id, "pk": id_}),
data={
"recipe_category": recipe.category.id,
"recipe": recipe.id,
"piece": 0.5,
})
assert response.status_code == 302
assert RecipeItem.objects.first().piece == 0.5
def test_delete_recipe_item(self, client, recipe, user, menu, meal):
client.login(username="test_user", password="<PASSWORD>")
response = client.post(reverse("recipeitem-create", kwargs={"menu_id": menu.id, "meal_id": meal.id}),
data={
"recipe_category": recipe.category.id,
"recipe": recipe.id,
"piece": 1,
})
assert RecipeItem.objects.count() == 1
id_ = RecipeItem.objects.first().id
response = client.post(reverse("recipeitem-delete", kwargs={"menu_id": menu.id, "pk": id_}))
assert response.status_code == 302
assert RecipeItem.objects.count() == 0
<file_sep>/apps/diet_composer/tests/test_meal_models.py
import pytest
from django.contrib.auth.models import User
from apps.diet_composer.models import Meal, ProductCategory, Product
from apps.recipes.models import Recipe, Category
@pytest.mark.django_db()
class TestMeal:
@pytest.fixture(name="meal", scope="class")
def create_meal(self, django_db_blocker, django_db_setup):
with django_db_blocker.unblock():
user = User.objects.create_user(
username="test_user", email="<EMAIL>", password="<PASSWORD>"
)
product_category = ProductCategory.objects.create(name="Test Category")
product = Product.objects.create(
category=product_category,
name="Test Product",
calories_per_100=100,
proteins_per_100=50,
fats_per_100=50,
carbohydrates_per_100=50,
weight_of_pcs=100,
author=user,
)
category = Category.objects.create(name="cat1")
recipe = Recipe.objects.create(
title="Test recipe",
description="Test description",
author=user,
preparation_time="10 min",
ingredients="test ingredients",
category=category,
total_calories=100,
total_proteins=50,
total_fats=50,
total_carbohydrates=50,
tags="tag",
)
meal = Meal.objects.create(name="Test Meal")
meal.save()
meal.ingredients.create(
product=product, category=product_category, unit="g", weight=100
)
meal.recipes.create(recipe=recipe, recipe_category=category, piece=1)
yield meal
with django_db_blocker.unblock():
product.delete()
recipe.delete()
product_category.delete()
category.delete()
meal.delete()
user.delete()
def test_meal_name(self, meal):
assert str(meal) == "Test Meal"
def test_meal_calories(self, meal):
assert meal.total_calories == 200
def test_meal_proteins(self, meal):
assert meal.total_proteins == 100
def test_meal_fats(self, meal):
assert meal.total_fats == 100
def test_meal_carbo(self, meal):
assert meal.total_carbohydrates == 100
<file_sep>/apps/diet_composer/tests/test_meal_view.py
import pytest
from django.contrib.auth.models import User
from django.urls import reverse
from apps.diet_composer.models import Meal, DailyMenu
@pytest.mark.django_db
class TestMealView:
@pytest.fixture(name="user", scope="class")
def create_user(self, django_db_blocker, django_db_setup):
with django_db_blocker.unblock():
user = User.objects.create_user(
username="test_user", email="<EMAIL>", password="<PASSWORD>"
)
yield user
with django_db_blocker.unblock():
user.delete()
@pytest.fixture(name="menu", scope="class")
def create_menu(self, django_db_blocker, django_db_setup, user):
with django_db_blocker.unblock():
menu = DailyMenu.objects.create(
name="test_menu",
number_of_meals=2,
author=user
)
menu.save()
yield menu
with django_db_blocker.unblock():
menu.delete()
def test_meal_create_view(self, client, menu):
client.login(username="test_user", password="<PASSWORD>")
response = client.post(
reverse("meal-create", kwargs={"pk": menu.id}),
{
"name": "Lunch"
})
assert response.status_code == 302
assert menu.meals.count() == 1
def test_meal_delete_view(self, client, menu):
meal = Meal.objects.create(name="Lunch")
meal.save()
assert Meal.objects.count() == 1
client.login(username="test_user", password="<PASSWORD>")
response = client.post(
reverse("meal-delete", kwargs={"menu_id": menu.id, "pk": meal.id})
)
assert response.status_code == 302
assert Meal.objects.count() == 0<file_sep>/apps/diet_composer/migrations/0005_auto_20201008_1753.py
# Generated by Django 3.1 on 2020-10-08 17:53
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("diet_composer", "0004_auto_20201007_2015"),
]
operations = [
migrations.AddField(
model_name="productitem",
name="category",
field=models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name="prod_items",
to="diet_composer.productcategory",
),
),
migrations.AlterField(
model_name="dailymenu",
name="meals",
field=models.ManyToManyField(
blank=True, related_name="meals", to="diet_composer.Meal"
),
),
migrations.AlterField(
model_name="meal",
name="name",
field=models.CharField(
blank=True,
choices=[
("Breakfast", "Breakfast"),
("Lunch", "Lunch"),
("Dinner", "Dinner"),
("Afternoon snack", "Snack"),
("Post-workout meal", "Post Workout"),
("Supper", "Supper"),
],
max_length=50,
null=True,
),
),
]
<file_sep>/Dockerfile
FROM python:3.8
ENV PYTHONUNBUFFERED=1
WORKDIR /diet_composer
COPY requirements.txt /diet_composer/
RUN pip install -r requirements.txt
COPY . /diet_composer
<file_sep>/apps/recipes/views.py
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.urls import reverse, reverse_lazy
from django.views.generic import (
CreateView,
DeleteView,
DetailView,
ListView,
UpdateView,
)
from apps.recipes.models import Recipe
class RecipesListView(ListView):
model = Recipe
template_name = "recipes/recipes.html"
context_object_name = "recipes"
ordering = ["-date_public"]
extra_context = {"title": "Recipes"}
paginate_by = 4
class RecipeDetailView(DetailView):
model = Recipe
def get_context_data(self, *args, **kwargs):
context = super().get_context_data()
stuff = get_object_or_404(Recipe, id=self.kwargs.get("pk"))
total_likes = stuff.total_likes
context["total_likes"] = total_likes
return context
class RecipeCreateView(LoginRequiredMixin, CreateView):
model = Recipe
fields = [
"category",
"title",
"preparation_time",
"description",
"ingredients",
"image",
"tags",
"total_calories",
"total_proteins",
"total_fats",
"total_carbohydrates",
]
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def get_success_url(self):
return reverse_lazy("recipe-detail", kwargs={"pk": self.object.pk})
class RecipeUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Recipe
fields = [
"category",
"title",
"preparation_time",
"description",
"ingredients",
"image",
"tags",
"total_calories",
"total_proteins",
"total_fats",
"total_carbohydrates",
]
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def test_func(self):
recipe = self.get_object()
if self.request.user == recipe.author:
return True
return False
def get_success_url(self):
return reverse_lazy("recipe-detail", kwargs={"pk": self.object.pk})
class RecipeDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = Recipe
success_url = "/recipes"
def test_func(self):
recipe = self.get_object()
if self.request.user == recipe.author:
return True
return False
def LikeView(request, pk):
recipe = get_object_or_404(Recipe, id=request.POST.get("recipe_id"))
recipe.likes.add(request.user)
return HttpResponseRedirect(reverse("recipe-detail", args=[str(pk)]))
<file_sep>/apps/diet_composer/migrations/0007_auto_20201013_2022.py
# Generated by Django 3.1 on 2020-10-13 20:22
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("diet_composer", "0006_auto_20201012_1009"),
]
operations = [
migrations.AlterModelOptions(
name="product",
options={"ordering": ("category", "name")},
),
migrations.AlterModelOptions(
name="productcategory",
options={"ordering": ("name",)},
),
migrations.AddField(
model_name="product",
name="author",
field=models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name="products",
to=settings.AUTH_USER_MODEL,
),
),
migrations.AlterField(
model_name="product",
name="name",
field=models.CharField(max_length=150, unique=True),
),
migrations.AlterField(
model_name="productcategory",
name="name",
field=models.CharField(max_length=150, unique=True),
),
]
<file_sep>/apps/diet_composer/migrations/0003_auto_20201007_1935.py
# Generated by Django 3.1 on 2020-10-07 19:35
import django.core.validators
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("users", "0004_auto_20201006_1855"),
("diet_composer", "0002_auto_20201007_1436"),
]
operations = [
migrations.RemoveField(
model_name="product",
name="unit",
),
migrations.AlterField(
model_name="product",
name="category",
field=models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
related_name="products",
to="diet_composer.productcategory",
),
),
migrations.CreateModel(
name="ProductItem",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"unit",
models.CharField(
blank=True,
choices=[
("g", "Gram"),
("piece", "Piece"),
("package", "Package"),
],
max_length=150,
null=True,
),
),
(
"weight",
models.DecimalField(
decimal_places=2,
help_text="Depends on selected unit - grams or piece/package",
max_digits=6,
),
),
(
"product",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to="diet_composer.product",
),
),
],
),
migrations.CreateModel(
name="Meal",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"name",
models.CharField(
choices=[
("Breakfast", "Breakfast"),
("Lunch", "Lunch"),
("Dinner", "Dinner"),
("Afternoon snack", "Snack"),
("Post-workout meal", "Post Workout"),
("Supper", "Supper"),
],
max_length=50,
),
),
(
"ingredients",
models.ManyToManyField(
related_name="ingredients", to="diet_composer.ProductItem"
),
),
],
),
migrations.CreateModel(
name="DailyMenu",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("name", models.CharField(max_length=150)),
(
"number_of_meals",
models.PositiveSmallIntegerField(
validators=[
django.core.validators.MaxValueValidator(6),
django.core.validators.MinValueValidator(1),
]
),
),
(
"author",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="user_menus",
to="users.profile",
),
),
(
"meals",
models.ManyToManyField(
related_name="meals", to="diet_composer.Meal"
),
),
],
),
]
<file_sep>/apps/recipes/models/__init__.py
from .recipe import Category, Recipe
<file_sep>/requirements.txt
appdirs==1.4.4
asgiref==3.2.10
attrs==20.1.0
black==20.8b1
click==7.1.2
coverage==5.3
Django==3.1
django-cleanup==5.0.0
django-crispy-forms==1.9.2
django-rename-app==0.1.2
django-taggit==1.3.0
Faker==0.9.1
iniconfig==1.0.1
isort==5.5.0
mixer==6.1.3
more-itertools==8.5.0
mypy-extensions==0.4.3
packaging==20.4
pathspec==0.8.0
Pillow==7.2.0
pluggy==0.13.1
py==1.9.0
pyparsing==2.4.7
pytest==6.0.1
pytest-django==3.9.0
python-dateutil==2.8.1
pytz==2020.1
regex==2020.7.14
six==1.15.0
sqlparse==0.3.1
text-unidecode==1.2
toml==0.10.1
typed-ast==1.4.1
typing-extensions==3.7.4.3
<file_sep>/apps/diet_blog/views.py
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.urls import reverse, reverse_lazy
from django.views.generic import (
CreateView,
DeleteView,
DetailView,
ListView,
UpdateView,
)
from apps.diet_blog.models import Comment, Post
class PostListView(ListView):
model = Post
template_name = "diet_blog/blog.html"
context_object_name = "posts"
ordering = ["-date_posted"]
extra_context = {"title": "Blog"}
paginate_by = 4
class UserPostListView(ListView):
model = Post
template_name = "diet_blog/user_posts.html"
context_object_name = "posts"
paginate_by = 4
def get_queryset(self):
user = get_object_or_404(User, username=self.kwargs.get("username"))
return Post.objects.filter(author=user).order_by("-date_posted")
class PostDetailView(DetailView):
model = Post
def get_context_data(self, *args, **kwargs):
context = super(PostDetailView, self).get_context_data()
stuff = get_object_or_404(Post, id=self.kwargs.get("pk"))
total_likes = stuff.total_likes()
context["total_likes"] = total_likes
return context
class PostCreateView(LoginRequiredMixin, CreateView):
model = Post
fields = ["title", "content"]
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Post
fields = ["title", "content"]
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = Post
success_url = "/blog"
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
class CommentCreateView(LoginRequiredMixin, CreateView):
model = Comment
fields = ["content"]
def get_success_url(self):
return reverse_lazy("post-detail", kwargs={"pk": self.kwargs["pk"]})
def form_valid(self, form):
form.instance.post_id = self.kwargs["pk"]
form.instance.author = self.request.user
return super().form_valid(form)
class CommentUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Comment
fields = ["content"]
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def test_func(self):
comment = self.get_object()
if self.request.user == comment.author:
return True
return False
def get_success_url(self):
return reverse_lazy("post-detail", kwargs={"pk": self.object.post.pk})
class CommentDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = Comment
def get_success_url(self):
return reverse_lazy("post-detail", kwargs={"pk": self.object.post.pk})
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
def LikeView(request, pk):
post = get_object_or_404(Post, id=request.POST.get("post_id"))
post.likes.add(request.user)
return HttpResponseRedirect(reverse("post-detail", args=[str(pk)]))
<file_sep>/apps/diet_composer/migrations/0002_auto_20201007_1436.py
# Generated by Django 3.1 on 2020-10-07 14:36
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("diet_composer", "0001_initial"),
]
operations = [
migrations.RenameField(
model_name="product",
old_name="carb_per_100",
new_name="carbohydrates_per_100",
),
]
<file_sep>/apps/diet_composer/migrations/0001_initial.py
# Generated by Django 3.1 on 2020-10-06 18:47
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="ProductCategory",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("name", models.CharField(max_length=150)),
],
),
migrations.CreateModel(
name="Product",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("name", models.CharField(max_length=150)),
(
"calories_per_100",
models.DecimalField(decimal_places=2, max_digits=6),
),
(
"proteins_per_100",
models.DecimalField(decimal_places=2, max_digits=6),
),
("fats_per_100", models.DecimalField(decimal_places=2, max_digits=6)),
("carb_per_100", models.DecimalField(decimal_places=2, max_digits=6)),
(
"unit",
models.CharField(
blank=True,
choices=[("kg", "Kilogram"), ("piece", "Piece")],
max_length=150,
null=True,
),
),
(
"weight_of_pcs",
models.DecimalField(
blank=True,
decimal_places=2,
help_text="weight of an average piece / package",
max_digits=6,
null=True,
),
),
(
"category",
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
to="diet_composer.productcategory",
),
),
],
),
]
<file_sep>/apps/users/migrations/0002_auto_20201005_1937.py
# Generated by Django 3.1 on 2020-10-05 19:37
import django.db.models.deletion
from django.db import migrations, models
import apps.users.utils
class Migration(migrations.Migration):
dependencies = [
("users", "0001_initial"),
]
operations = [
migrations.CreateModel(
name="UserActivity",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("description", models.CharField(max_length=150)),
("factor", models.FloatField()),
],
),
migrations.AddField(
model_name="profile",
name="age",
field=models.PositiveSmallIntegerField(
blank=True, null=True, validators=[apps.users.utils.validate_age]
),
),
migrations.AddField(
model_name="profile",
name="gender",
field=models.CharField(
blank=True,
choices=[("1", "Male"), ("2", "Female")],
max_length=10,
null=True,
),
),
migrations.AddField(
model_name="profile",
name="height",
field=models.FloatField(blank=True, null=True),
),
migrations.AddField(
model_name="profile",
name="weight",
field=models.FloatField(blank=True, null=True),
),
migrations.AddField(
model_name="profile",
name="activity",
field=models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.PROTECT,
to="users.useractivity",
),
),
]
<file_sep>/apps/diet_composer/tests/test_product_item_views.py
import pytest
from django.contrib.auth.models import User
from django.urls import reverse
from apps.diet_composer.models import Product, ProductCategory, ProductItem, Meal, DailyMenu
from apps.users.models import UserActivity
@pytest.mark.django_db
class TestProductItemView:
@pytest.fixture(name="user", scope="class")
def create_user(self, django_db_blocker, django_db_setup):
with django_db_blocker.unblock():
user = User.objects.create_user(
username="test_user", email="<EMAIL>", password="<PASSWORD>"
)
activity = UserActivity.objects.create(factor=1.2, description="activity")
activity.save()
user.profile.age = 25
user.profile.height = 190
user.profile.gender = "Male"
user.profile.weight = 80
user.profile.activity = activity
user.profile.save()
yield user
with django_db_blocker.unblock():
user.delete()
activity.delete()
@pytest.fixture(name="product", scope="class")
def create_product(self, django_db_blocker, django_db_setup, user):
with django_db_blocker.unblock():
category = ProductCategory.objects.create(name="cat1")
category.save()
product = Product.objects.create(
category=category,
name="product_testing",
calories_per_100=80,
proteins_per_100=50,
fats_per_100=10,
carbohydrates_per_100=80,
weight_of_pcs=150,
author=user
)
product.save()
yield product
with django_db_blocker.unblock():
product.delete()
category.delete()
@pytest.fixture(name="menu", scope="class")
def create_menu(self, django_db_blocker, django_db_setup, user):
with django_db_blocker.unblock():
menu = DailyMenu.objects.create(
name="test_menu",
number_of_meals=2,
author=user
)
menu.save()
yield menu
with django_db_blocker.unblock():
menu.delete()
@pytest.fixture(name="meal", scope="class")
def create_meal(self, django_db_blocker, django_db_setup, menu):
with django_db_blocker.unblock():
meal = Meal.objects.create(
name="test_meal"
)
meal.save()
menu.meals.add(meal)
yield meal
def test_create_update_product_item(self, client, product, user, menu, meal):
client.login(username="test_user", password="<PASSWORD>")
response = client.post(reverse("ingredient-create", kwargs={"menu_id": menu.id, "meal_id": meal.id}),
data={
"category": product.category.id,
"product": product.id,
"weight": 1,
})
assert response.status_code == 302
assert ProductItem.objects.count() == 1
id_ = ProductItem.objects.first().id
response = client.post(reverse("ingredient-edit", kwargs={"menu_id": menu.id, "pk": id_}),
data={
"category": product.category.id,
"product": product.id,
"weight": 100,
"unit": "g"
})
assert response.status_code == 302
assert ProductItem.objects.first().weight == 100
assert ProductItem.objects.first().unit == "g"
def test_delete_product_item(self, client, product, user, menu, meal):
client.login(username="test_user", password="<PASSWORD>")
response = client.post(reverse("ingredient-create", kwargs={"menu_id": menu.id, "meal_id": meal.id}),
data={
"category": product.category.id,
"product": product.id,
"weight": 1,
})
assert response.status_code == 302
assert ProductItem.objects.count() == 1
id_ = ProductItem.objects.first().id
response = client.post(reverse("ingredient-delete", kwargs={"menu_id": menu.id, "pk": id_}))
assert response.status_code == 302
assert ProductItem.objects.count() == 0<file_sep>/apps/users/migrations/0004_auto_20201006_1855.py
# Generated by Django 3.1 on 2020-10-06 18:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("users", "0003_auto_20201006_1847"),
]
operations = [
migrations.AlterField(
model_name="profile",
name="height",
field=models.DecimalField(
blank=True,
decimal_places=1,
help_text="height in centimeters",
max_digits=4,
null=True,
),
),
migrations.AlterField(
model_name="profile",
name="weight",
field=models.DecimalField(
blank=True,
decimal_places=1,
help_text="weight in kilograms",
max_digits=4,
null=True,
),
),
]
<file_sep>/apps/diet_composer/static/diet_composer/diet_composer.js
$("#id_category").change(function () {
var url = $("#product-form").attr("data-products-url"); // get the url of the `load_products` view
var categoryId = $(this).val(); // get the selected category ID from the HTML input
$.ajax({ // initialize an AJAX request
url: url, // set the url of the request (= localhost:8000/hr/ajax/load_products/)
data: {
'category': categoryId // add the category id to the GET parameters
},
success: function (data) { // `data` is the return of the `load_product` view function
$("#id_product").html(data); // replace the contents of the product input with the data that came from the server
}
});
});
$("#id_recipe_category").change(function () {
var url = $("#recipeitem-form").attr("data-recipes-url"); // get the url of the `load_products` view
var categoryId = $(this).val(); // get the selected category ID from the HTML input
$.ajax({ // initialize an AJAX request
url: url, // set the url of the request (= localhost:8000/hr/ajax/load_products/)
data: {
'recipe_category': categoryId // add the category id to the GET parameters
},
success: function (data) { // `data` is the return of the `load_product` view function
$("#id_recipe").html(data); // replace the contents of the product input with the data that came from the server
}
});
});<file_sep>/apps/users/models/__init__.py
from .models import Profile, UserActivity
<file_sep>/apps/__init__.py
from .diet_blog.apps import DietBlogConfig
from .diet_composer.apps import DietComposerConfig
from .recipes.apps import RecipesConfig
from .users.apps import UsersConfig
<file_sep>/apps/users/tests/test_views.py
import os
from pathlib import Path
import pytest
from django.contrib.auth.models import AnonymousUser, User
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import RequestFactory
from django.urls import reverse
from mixer.backend.django import mixer
from apps.users.views import profile
BASE_DIR = Path(__file__).resolve(strict=True).parent.parent.parent.parent
@pytest.mark.django_db
class TestView:
@pytest.fixture(name="user", scope="class")
def create_post(self, django_db_blocker, django_db_setup):
with django_db_blocker.unblock():
user = User.objects.create_user(
username="test_user", email="<EMAIL>", password="<PASSWORD>"
)
yield user
with django_db_blocker.unblock():
os.remove(user.profile.image.path)
user.delete()
def test_profile_view_authenticated(self):
path = reverse("profile")
request = RequestFactory().get(path)
request.user = mixer.blend(User)
response = profile(request)
assert response.status_code == 200
def test_profile_view_unauthenticated(self):
path = reverse("profile")
request = RequestFactory().get(path)
request.user = AnonymousUser()
response = profile(request)
assert response.status_code == 302
assert "login" in response.url
def test_register(self, client):
response = client.get(reverse("register"))
assert response.status_code == 200
assert "Username" in str(response.content)
assert "Password" in str(response.content)
assert "Email" in str(response.content)
assert "users/register.html" in [
template.name for template in response.templates
]
def test_register_user_post(self, client):
response = client.post(
reverse("register"),
{
"username": "test_user",
"email": "<EMAIL>",
"password1": "<PASSWORD>",
"password2": "<PASSWORD>",
},
)
assert response.status_code == 302
assert User.objects.first().username == "test_user"
assert User.objects.first().email == "<EMAIL>"
def test_register_user_post_fail(self, client):
response = client.post(
reverse("register"),
{
"username": "test_user",
"email": "<EMAIL>",
"password1": "<PASSWORD>",
"password2": "<PASSWORD>",
},
)
assert response.status_code == 200
assert not User.objects.first()
assert User.objects.count() == 0
assert (
"This password is too short. It must contain at least 8 characters."
in str(response.content)
)
def test_post_update(self, client, user):
image_path = os.path.join(BASE_DIR, "media/test_pics/joker.jpg")
client.login(username="test_user", password="<PASSWORD>")
response = client.post(
reverse("profile"),
{
"username": "test_user1",
"email": "<EMAIL>",
"image": SimpleUploadedFile(
name="joker.jpg",
content=open(image_path, "rb").read(),
content_type="image/jpg",
),
},
)
user.refresh_from_db()
assert response.status_code == 302
assert user.username == "test_user1"
assert user.email == "<EMAIL>"
assert user.profile.image.path == os.path.join(
BASE_DIR, "media/profile_pics/joker.jpg"
)
<file_sep>/apps/recipes/migrations/0003_auto_20200930_1610.py
# Generated by Django 3.1 on 2020-09-30 16:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("recipes", "0002_recipe_likes"),
]
operations = [
migrations.RenameField(
model_name="recipe",
old_name="preparing_time",
new_name="preparation_time",
),
migrations.AlterField(
model_name="recipe",
name="image",
field=models.ImageField(
default="default_recipe.png", upload_to="recipes_pics"
),
),
]
<file_sep>/apps/diet_composer/utils.py
from django.contrib.auth.models import User
from typing import TypeVar, List
from decimal import Decimal
DailyMenu = TypeVar("DailyMenu")
ProductItem = TypeVar("ProductItem")
RecipeItem = TypeVar("RecipeItem")
Meal = TypeVar("Meal")
def calculate_params(
unit: str, value_to_calculate: Decimal, weight: Decimal, weight_in_psc: Decimal
) -> float:
if unit == "g":
return round(float(value_to_calculate) * float(weight) / 100, 2)
return round(
float(value_to_calculate) * float(weight_in_psc) / 100 * float(weight), 2
)
def check_nutritional_status(
user: User, menu: DailyMenu, ingredient: ProductItem
) -> bool:
""" "
checking personal parameters of user vs diet values
"""
calories = menu.total_calories + ingredient.calories
proteins = menu.total_proteins + ingredient.proteins
fats = menu.total_fats + ingredient.fats
carbohydrates = menu.total_carbohydrates + ingredient.carbohydrates
if (
calories > user.profile.cmr
or proteins > user.profile.daily_proteins
or fats > user.profile.daily_fats
or carbohydrates > user.profile.daily_carb
):
return False
return True
def calculate_total_value_menu(lst: List[Meal], flag: str) -> float:
total = 0
for item in lst:
if flag == "calories":
total += item.total_calories
elif flag == "proteins":
total += item.total_proteins
elif flag == "fats":
total += item.total_fats
else:
total += item.total_carbohydrates
return round(total, 2)
def calculate_total_value_meal(
lst_ingredients: List[ProductItem], lst_recipes: List[RecipeItem], flag: str
) -> float:
total = 0
total_items = list(lst_ingredients) + list(lst_recipes)
for item in total_items:
if flag == "calories":
total += item.calories
elif flag == "proteins":
total += item.proteins
elif flag == "fats":
total += item.fats
else:
total += item.carbohydrates
return round(total, 2)
def calculate_recipe_nutri(nutri_value: Decimal, piece: Decimal) -> float:
return round(float(nutri_value) * float(piece), 2)
def calculate_weight(unit: str, weight: Decimal, weight_pcs: Decimal) -> float:
if unit == "g":
return float(weight)
return round(float(weight_pcs * weight), 1)
<file_sep>/apps/recipes/migrations/0005_auto_20201014_1756.py
# Generated by Django 3.1 on 2020-10-14 17:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("recipes", "0004_recipe_tags"),
]
operations = [
migrations.AddField(
model_name="recipe",
name="total_calories",
field=models.DecimalField(
blank=True, decimal_places=2, max_digits=6, null=True
),
),
migrations.AddField(
model_name="recipe",
name="total_carbohydrates",
field=models.DecimalField(
blank=True, decimal_places=2, max_digits=6, null=True
),
),
migrations.AddField(
model_name="recipe",
name="total_fats",
field=models.DecimalField(
blank=True, decimal_places=2, max_digits=6, null=True
),
),
migrations.AddField(
model_name="recipe",
name="total_proteins",
field=models.DecimalField(
blank=True, decimal_places=2, max_digits=6, null=True
),
),
]
<file_sep>/apps/recipes/migrations/0007_auto_20201014_2049.py
# Generated by Django 3.1 on 2020-10-14 20:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("recipes", "0006_auto_20201014_1816"),
]
operations = [
migrations.AlterField(
model_name="category",
name="name",
field=models.CharField(max_length=50, unique=True),
),
migrations.AlterField(
model_name="recipe",
name="title",
field=models.CharField(max_length=100, unique=True),
),
]
<file_sep>/apps/users/tests/test_utils.py
import os
from pathlib import Path
import pytest
from PIL import Image
from django.core.exceptions import ValidationError
from apps.users.utils import change_pic_size, validate_age, calculate_bmr, calculate_cmr, calc_daily_fats, calc_daily_proteins, calc_daily_carb
BASE_DIR = Path(__file__).resolve(strict=True).parent.parent.parent.parent
@pytest.fixture(scope="module", name="image_path")
def get_image():
image_path = os.path.join(BASE_DIR, "media/test_pics/joker.jpg")
yield image_path
img = Image.open(image_path)
img.thumbnail((400, 400))
img.save(image_path)
def test_change_pic_size(image_path):
change_pic_size(image_path, 300, 300)
assert Image.open(image_path).height == 300
assert Image.open(image_path).width == 300
def test_validate_age():
assert validate_age(50)
with pytest.raises(ValidationError):
assert validate_age(120)
def test_calculate_bmr():
assert calculate_bmr(80, 192, 25, "Male") == 1881.2
assert calculate_bmr(60, 170, 25, "Female") == 1377.9
def test_calc_cmr():
assert calculate_cmr(10, 2) == 20
def test_calc_daily_proteins_fats_carbo():
assert calc_daily_proteins(1800) == 90
assert calc_daily_fats(1800) == 50
assert calc_daily_carb(1800) == 248
<file_sep>/apps/diet_composer/models/meal.py
from django.db import models
from apps.diet_composer.utils import calculate_total_value_meal
class Meal(models.Model):
class Name(models.TextChoices):
breakfast = "Breakfast"
lunch = "Lunch"
dinner = "Dinner"
snack = "Afternoon snack"
post_workout = "Post-workout meal"
supper = "Supper"
name = models.CharField(choices=Name.choices, max_length=50, unique=True)
ingredients = models.ManyToManyField(
"diet_composer.ProductItem", related_name="meals"
)
recipes = models.ManyToManyField("diet_composer.RecipeItem", related_name="meals")
def __str__(self):
return f"{self.name}"
def delete(self, using=None, keep_parents=False):
for ingredient in self.ingredients.all():
ingredient.delete()
for recipe in self.recipes.all():
recipe.delete()
super().delete()
@property
def total_calories(self) -> float:
value = calculate_total_value_meal(
self.ingredients.all(), self.recipes.all(), "calories"
)
return value
@property
def total_proteins(self) -> float:
value = calculate_total_value_meal(
self.ingredients.all(), self.recipes.all(), "proteins"
)
return value
@property
def total_fats(self) -> float:
value = calculate_total_value_meal(
self.ingredients.all(), self.recipes.all(), "fats"
)
return value
@property
def total_carbohydrates(self) -> float:
value = calculate_total_value_meal(
self.ingredients.all(), self.recipes.all(), "carbohydrates"
)
return value
<file_sep>/apps/recipes/admin.py
from django.contrib import admin
from .models import Category, Recipe
admin.site.register(Recipe)
admin.site.register(Category)
|
009a7dbc7855084df4fa972270f7d0152dd9a586
|
[
"JavaScript",
"Markdown",
"Python",
"Text",
"Dockerfile"
] | 75 |
Python
|
tomekmatuszewski/Diet_composer
|
fc8703f38c0e004449345e7df975d189b01856bf
|
76920e7c4b12c774cdd9ce9ac3f4f317dc7024d2
|
refs/heads/master
|
<repo_name>excellencetechnologies/PollingSystemRitika<file_sep>/src/appp.jsx
import React, { Component } from 'react';
import { Link } from 'react-router';
export default class Appp extends Component {
render() {
return (
<div>
<Link to="addpoll" historyType="push">
<button className="btn-danger btn pull-right">Add Poll</button>
</Link>
<Link to="ExistingPolls/home" historyType="push">
<button className="btn-success btn pull-right">Polls</button>
</Link>
{this.props.children}
</div>
);
}
}
<file_sep>/src/index.jsx
import { render } from 'react-dom';
import React from 'react';
import { Router, Route, IndexRoute, hashHistory } from 'react-router';
import Appp from './appp';
import ExistingPolls from './TableRow';
import AddPollComponent from './AddPollComponent';
import EditPolls from './EditPolls';
import '../styles/index.scss';
render((
<Router history={hashHistory}>
<Route path="/" component={Appp}>
<IndexRoute component={ExistingPolls} />
<Route path="addpoll" component={AddPollComponent} />
<Route path="ExistingPolls/:edited" component={ExistingPolls} />
<Route path="EditPolls/:userId" component={EditPolls} />
</Route>
</Router>
), document.getElementById('app'));
<file_sep>/src/AddPoll.jsx
import 'react-date-picker/index.css';
import DatePicker from 'react-date-picker';
import { Link } from 'react-router';
import React from 'react';
import update from 'immutability-helper';
const Modal = require('boron/DropModal');
let id = 0;
let Options = [];
let warning = 'Add Option';
let buttonType = 'btn-primary pull-right btn';
export var data = [
{
name: 'What can be done for the betterment of the country',
finalValue: [
'there should be dictatorship', 'modiji should be given all the powers', 'nothing can be done',
],
expiry: '03/14/2017',
}, {
name: 'What can be done for the betterment of the city',
finalValue: [
'keep the city clean', 'be less violent', 'nothing can be done',
],
expiry: '10/14/2017',
},
];
export class ViewOptions extends React.Component {
render() {
return (
<div>
{Options.map((OptionList, index) => <div key={index}>
{OptionList}
</div>)}
</div>
);
}
}
export default class AddPoll extends React.Component {
constructor() {
super();
this.state = {
data: '',
name: '',
expiry: '',
finalValue: [],
warning: '',
inputValidate: 0,
};
this.addOption = this.addOption.bind(this);
this.handleExpiry = this.handleExpiry.bind(this);
this.handleName = this.handleName.bind(this);
this.handleOpt = this.handleOpt.bind(this);
this.hideModal = this.hideModal.bind(this);
this.submit = this.submit.bind(this);
}
submit() {
if (this.state.name && this.state.expiry && this.state.finalValue.length > 1) {
if (Options.length === this.state.finalValue.length) {
const AddPollData = [
{
name: this.state.name,
expiry: this.state.expiry,
finalValue: this.state.finalValue,
},
];
const initialArray = data;
const newArray = update(initialArray, { $push: AddPollData });
data = newArray;
this.setState({ data });
this.props.aim(data);
this.setState({ name: '', finalValue: '', expiry: '', warning: '' });
Options = [];
id = 0;
this.showModal();
}
} else {
this.setState({ warning: '(Fields are empty and Minimum 2 Options Are To Be Added)' });
}
}
handleName(event) {
this.setState({ name: event.target.value });
}
handleExpiry(date) {
this.setState({ expiry: date });
}
showModal() {
this.refs.modal.show();
}
hideModal() {
this.refs.modal.hide();
}
inputclick() {
this.setState({ inputclick: 1 });
}
handleOpt(event, i) {
// const finalValue = [event.target.value];
// console.log(finalValue);
const a = this.state.finalValue;
a[i] = event.target.value;
this.setState({ finalValue: a });
}
addOption() {
id += 1;
const optionNumber = `Option ${id}`;
const inputTypeAdd = (
<div className="form-group">
<label htmlFor="newpoll">Option {id}:</label>
<input
type="text" className="form-control" id={id} onChange={(event) => {
this.handleOpt(event, this.state.Options.length - 1);
}} placeholder={optionNumber}
/>
</div>);
const initialArray = Options;
if (initialArray.length < 100) {
const newArray = update(initialArray, { $push: [inputTypeAdd] });
Options = newArray;
this.setState({ Options });
} else {
warning = 'Limit Exceeded';
buttonType = 'btn-danger pull-right btn';
this.setState({ th: 'th' });
}
}
render() {
// console.log(this.state);
const pollModal = {
color: 'red',
display: 'inline-block',
};
return (
<div>
<center>
<h1>Add a new Poll</h1>
</center><br />
<div className="col-md-12">
<br />
</div>
<div className="jumbotron">
<div className="form-group">
<label htmlFor="newpoll">New Poll:</label>
<input
type="text" className="form-control" id="newpoll" placeholder="Enter new poll"
onChange={(event) => {
this.handleName(event);
}} value={this.state.name}
/>
</div>
<div>
<ViewOptions />
</div>
<div>
<input type="button" className={buttonType} value={warning} onClick={this.addOption} />
</div>
<br /><br /><br />
<div className="form-group">
<label htmlFor="datepicker">Expiry Date:</label>
<DatePicker
selected={this.state.startDate} onChange={(event) => {
this.handleExpiry(event);
}} value={this.state.date}
/>
</div>
<Modal ref="modal">
<span>
<center>
<h2 style={pollModal}>Congratulations...!! Poll has been added successfully..!</h2>
<Link to="ExistingPolls/new" historyType="push">
<button onClick={this.hideModal} className="btn-primary">close</button>
</Link>
</center>
</span>
</Modal>
<button className="btn btn-default btn-primary" onClick={this.submit}>Submit</button>
<span className="text-danger">
<small>{this.state.warning}</small>
</span>
</div>
</div>
);
}
}
<file_sep>/src/EditPolls.jsx
import React from 'react';
import { Link } from 'react-router';
import update from 'immutability-helper';
import { data } from './AddPoll';
const _ = require('lodash');
export default class EditPolls extends React.Component {
constructor(props) {
super(props);
const a = this.props.params.userId;
const index = (_.findIndex(data, o => o.name === a,
));
this.state = {
Poll: this.props.params.userId,
data: '',
name: data[index].name,
expiry: data[index].expiry,
finalValue: data[index].finalValue,
warning: '',
inputValidate: 0,
};
this.addOption = this.addOption.bind(this);
this.handleNames = this.handleNames.bind(this);
this.handleOpt = this.handleOpt.bind(this);
this.handleRemove = this.handleRemove.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleNames(event) {
this.setState({ name: event.target.value });
// console.log(this.state.name);
}
handleOpt(event, index) {
const a = this.state.finalValue;
a[index] = event.target.value;
this.setState({
finalValue: a,
});
// console.log(event.target.value);
// console.log(index);
}
handleRemove(ind) {
if (this.state.finalValue.length > 1) {
console.log(this.state.finalValue[ind]);
const value = this.state.finalValue[ind];
const finalValues = this.state.finalValue;
const final = _.remove(finalValues, n => n === value);
this.setState({
finalValue: finalValues,
});
} else {
this.setState({ warning: '(Minimum One option Required)' });
}
}
addOption() {
const a = this.props.params.userId;
const index = (_.findIndex(data, o => o.name === a,
));
let id = this.state.finalValue.length;
id += 1;
const inputTypeAdd = `Option ${id}`;
const initialArray = this.state.finalValue;
const newArray = update(initialArray, { $push: [inputTypeAdd] });
this.setState({
finalValue: newArray,
warning: '',
});
data[index].finalValue = newArray;
console.log(this.state);
// this.setState({ Options });
}
handleSubmit() {
const a = this.state.Poll;
const index = (_.findIndex(data, o => o.name === a));
const app = data;
app[index].name = this.state.name;
}
render() {
const a = this.state.Poll;
const index = (_.findIndex(data, o => o.name === a));
const DataUpdate = `ExistingPolls/${this.state.name}`;
return (
<div className="col-md-12">
<div>
<h3>Editing Poll : <b>{this.state.Poll}</b></h3>
<div className="jumbotron">
<div className="form-group container">
<label htmlFor="newpoll">Name:</label>
<input
type="text" className="form-control" id="newpoll" placeholder="Edit poll"
onChange={(event) => {
this.handleNames(event);
// console.log(data);
}} value={this.state.name}
/>
</div>
{data[index].finalValue.map((name, ind) =>
<div key={ind}>
<div className="form-group container">
<div className="col-md-11">
<label htmlFor="poll">Option {ind + 1} :</label>
<input
type="text" className="form-control" name="poll"
value={this.state.finalValue[ind]} onChange={(event) => {
this.handleOpt(event, ind);
}}
/>
</div>
<div className="col-md-1">
<br /><br />
<button
className="btn pull-right btn-xs btn-primary"
value={this.state.finalValue[ind]} onClick={(event) => {
this.handleRemove(ind);
}}
>
<span className="glyphicon glyphicon-remove" />
</button>
</div>
</div>
</div>)}
<div>
<center>
<button
className="btn-primary btn" value="Add Option"
onClick={this.addOption}
>
<span className="glyphicon glyphicon-plus" />
</button>
</center>
</div>
</div>
</div>
<div>
<Link to={DataUpdate} historyType="push">
<button
className="btn-primary btn pull-right"
onClick={this.handleSubmit}
>Update</button>
</Link>
<small>{this.state.warning}</small>
</div>
</div>
);
}
}
<file_sep>/src/AddPollComponent.jsx
import React from 'react';
import { data } from './AddPoll';
import AddPoll from './AddPoll';
export default class AddPollComponent extends React.Component {
constructor() {
super();
this.state = {
data,
id: true,
};
this.aim = this.aim.bind(this);
}
aim(datas) {
console.log(datas);
datas = datas;
this.setState({ newData: datas, id: false });
}
render() {
return (
<div>
<div className="col-md-12">
<AddPoll aim={this.aim} />
</div>
</div>
);
}
}
<file_sep>/src/TableRow.jsx
import React from 'react';
import App from './Polling';
export default class ExistingPolls extends React.Component {
render() {
return (
<div className="container">
<App />
</div>
);
}
}
<file_sep>/README.md
# PollingSystemRitika
A polling system to take and submit polls by adding options dynamically.
<file_sep>/src/Polling.jsx
import React from 'react';
import { Header, TableRow } from './app';
import { data } from './AddPoll';
export default class App extends React.Component {
render() {
return (
<div className="container">
<div className="col-md-12">
<Header /> {data.map((person, i) => <TableRow key={i} data={person} />)}
</div>
</div>
);
}
}
|
2c856851f188c43f46919b41cf64b4f3ac8db20b
|
[
"JavaScript",
"Markdown"
] | 8 |
JavaScript
|
excellencetechnologies/PollingSystemRitika
|
c82d17c694538c5c9002ebe674611a4188a65ce3
|
3b650bce3a5b750785f532001eefa8ecc424b1cd
|
refs/heads/master
|
<repo_name>ekrajchevska/skit-project-client<file_sep>/src/repository/studyProgramRepository.js
export const url = "http://localhost:8080/api/study_programs";
export const listStudyPrograms = () =>{
return fetch(url, {
"method" : "GET",
headers:{
"Content-Type" : "application/json"
}
});
};
export const addStudyProgram = (studyProgram) =>{
console.log("-- studyProgram repository call add --");
return fetch(url,{
method:"POST",
headers:{
"Content-Type":"application/json"
},
body: JSON.stringify({
name : studyProgram.name
})
})
};
export const deleteStudyProgram = (index, name)=>{
console.log("-- studyProgram repository call delete: "+index+" --");
return fetch(url+"/"+index,{
method:"DELETE",
headers: {
"Content-Type":"application/json"
}
})
};
export const modifyStudyProgram = (studyProgram) =>{
console.log("-- studyProgram repository call modify: "+studyProgram.id+" --")
return fetch(url+"/"+studyProgram.id, {
method:"PUT",
headers:{
"Content-type":"application/json"
},
body:JSON.stringify({
name : studyProgram.name
})
})
};<file_sep>/src/components/StudentItem/studentItem.js
import React, { Component } from 'react'
import './studentItem.css';
class StudentItem extends Component{
sendIndex = () =>{
this.props.notifyClick(this.props.index);
};
deleteStudent = () =>{
this.props.notifyDelete(this.props.student.index)
};
render(){
return(
<div className={'container-fluid'}>
<li className={'row'}>
<div className={'col-sm-1'}>{this.props.student.index}</div>
<div className={'col-sm-1'}>{this.props.student.name}</div>
<div className={'col-sm-1'}>{this.props.student.lastName}</div>
<div className={'col-sm-1'}>{this.props.student.studyProgram}</div>
<div className={'col-sm-2'}>
<button className={'btn btn-info'} onClick={this.sendIndex}>Edit</button>
<button className={'btn btn-danger'} onClick={this.deleteStudent}>Delete</button>
</div>
</li>
</div>
);
}
}
export default StudentItem;<file_sep>/src/components/EditStudentDetails/editStudentDetails.js
import React, {Component} from 'react'
class EditStudentDetails extends Component{
callSubmit = (formSubmitEvent) =>{
formSubmitEvent.preventDefault();
if(formSubmitEvent.target.studentName.value==="" ||
formSubmitEvent.target.studentSurname.value ===""){
alert("Missing information!");
return;
}
this.props.formSubmit(
{
name: formSubmitEvent.target.studentName.value,
lastName: formSubmitEvent.target.studentSurname.value,
index: this.props.student.index,
studyProgram: formSubmitEvent.target.studentStudies.value
}
);
};
render(){
if(!this.props.shown) return null;
let studyProgramOptions = this.props.studyPrograms.map((element,index)=>{
return <option key={element.id}
value={element.name}>{element.name}</option>;
});
return(
<div>
<form onSubmit={this.callSubmit} key={this.props.student.index}>
<div className={"row"}>
<div className={"col-2"}>
<input type="text"
name={"studentName"}
defaultValue={this.props.student.name}
/>
</div>
<div className={"col-2"}>
<input type="text"
name={"studentSurname"}
defaultValue={this.props.student.lastName}
/>
</div>
<div className={"col-1"}>
<select name={"studentStudies"} defaultValue={this.props.student.studyProgram}>
{studyProgramOptions}
</select>
</div>
<div className={"col-1"}>
<button className={'btn btn-success'} type={"submit"}>Submit</button>
</div>
</div>
</form>
</div>
)
}
}
export default EditStudentDetails;<file_sep>/src/components/AddStudyProgram/addStudyProgram.js
import React, {Component} from 'react'
class AddStudyProgram extends Component{
callSubmit = (formSubmitEvent) =>{
formSubmitEvent.preventDefault();
this.props.add({
name: formSubmitEvent.target.studyProgramName.value,
})
};
render(){
if(!this.props.shown) return null;
return(
<form onSubmit={this.callSubmit}>
<div className={'container-fluid'}>
<div className={"row"}>
<div className={"col-2"}>
<input id={'programInput'} type="text" name={"studyProgramName"} placeholder={"Name"}/>
</div>
<div className={"col-1"}>
<button id={'programSubmit'} type={"submit"} className={"btn btn-success"}>Add study program</button>
</div>
</div>
</div>
</form>
);
}
};
export default AddStudyProgram;<file_sep>/src/components/StudentsList/studentsList.js
import React, { Component } from 'react'
import StudentItem from "../StudentItem/studentItem";
class StudentsList extends Component{
render(){
let listItems = this.props.students.map((element,index)=>{
return <StudentItem student={element}
key={index}
index={index}
notifyClick={this.props.itemClick}
notifyDelete={this.props.itemDelete}/>
});
return(
<div>
<ul id={'student-items'} className='list-group'>
{listItems}
</ul>
</div>
);
}
}
export default StudentsList;<file_sep>/src/repository/studentRepository.js
export const url = "http://localhost:8080/api/students";
export const listStudents = () =>{
return fetch(url, {
method : "GET",
headers:{
"Content-Type" : "application/json"
}
});
};
export const addStudent = (student) =>{
console.log("-- student repository call add for --");
console.log("index: "+student.index+" name: "+student.name+" lastName: "+
student.lastName+" program: "+student.studyProgram);
return fetch(url,{
method:"POST",
headers:{
"Content-Type":"application/json"},
body:JSON.stringify({
index : student.index,
name : student.name,
lastName : student.lastName,
studyProgram : student.studyProgram
})
})
};
export const deleteStudent = (index) =>{
console.log("-- student repository call delete "+index+" --");
return fetch(url+"/"+index,{
method:"DELETE",
headers: {
"Content-Type":"application/json"
}
})
};
export const modifyStudent = (student) =>{
console.log("-- student repository call modify "+student.index+"--");
return fetch(url+"/"+student.index,{
method:"PUT",
headers:{
"Content-Type":"application/json"
},
body:JSON.stringify({
index : student.index,
name : student.name,
lastName : student.lastName,
studyProgram : student.studyProgram
})
})
};
|
e49f91090e73845b3949c9f2ed44e10d2bed704e
|
[
"JavaScript"
] | 6 |
JavaScript
|
ekrajchevska/skit-project-client
|
97fca37d0c750514a74dae3afde902d2b7cd07a2
|
aca8715d2a4814ff2ba5d048d786f2ed2380f08a
|
refs/heads/master
|
<repo_name>simonatorw/products<file_sep>/app/store/actions/actionTypes.js
export default {
GET_PRODUCTS: 'GET_PRODUCTS',
GET_PRODUCTS_SUCCEEDED: 'GET_PRODUCTS_SUCCEEDED',
GET_PRODUCTS_FAILED: 'GET_PRODUCTS_FAILED',
ADD_TO_CART: 'ADD_TO_CART'
};<file_sep>/app/components/AddProduct/AddProduct.jsx
import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import styled from 'react-emotion';
import { addToCart } from '../../store/actions/actionCreators';
const Button = styled.button`
border: 2px solid #ddd;
background-color: green;
color: #fff;
font-weight: bold;
padding: 3px 10px;
&:active {
background-color: darkgreen;
box-shadow: 0 -1px #666;
}
`;
const Qty = styled.input`
width: 20px;
padding: 2px 6px;
border: 1px solid #ddd;
`;
const AddProductTpl = ({ details, addToCart }) => {
return (
<Fragment>
<Button onClick={addToCart.bind(this, details)}>Add to Cart</Button>
</Fragment>
);
};
const mapDispatchToProps = {
addToCart
};
export default connect(null, mapDispatchToProps)(AddProductTpl);<file_sep>/app/constants.js
export const SERVER = 'http://127.0.0.1:8124';
export const dataUrls = {
ALL: `${SERVER}/products`
};<file_sep>/server.js
const http = require('http');
const express = require('express');
const app = express();
const fs = require('fs');
const path = require('path');
const host = '127.0.0.1';
const port = 8124;
function allowCrossDomain(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
}
function sendResponse(name, res) {
const filePath = path.join(__dirname, `./app/resource/${name}.json`);
if (fs.existsSync(filePath)) {
//res.header('Cache-Control', 'public, max-age=31536000');
res.header('Cache-Control', 'public, max-age=0');
res.header('Last-Modified', 'Mon, 03 Jan 2011 17:45:57 GMT');
const readable = fs.createReadStream(filePath);
readable.pipe(res);
} else {
console.log('No such file!');
}
}
app.use(allowCrossDomain);
const server = require('http').createServer(app);
server.listen(port, host);
console.log(`Server running at http://${host}:${port}`);
app.get('*', function(req, res) {
sendResponse(req.url.split('/')[1], res);
});
<file_sep>/app/store/reducers/appReducer.js
import actionTypes from '../actions/actionTypes';
import stateTree from '../stateTree';
export default function appReducer(state = stateTree, action) {
switch(action.type) {
case actionTypes.ADD_TO_CART:
let cart = state.cart.slice();
cart.push(action.item);
return { ...state, cart };
default:
return state;
}
}<file_sep>/app/components/Tile/Tile.jsx
import React from 'react';
import PropTypes from 'prop-types';
import styled from 'react-emotion';
import AddProduct from '../AddProduct/AddProduct';
const ProductTile = styled.div`
border: 1px solid #ddd;
padding: 16px;
&:hover {
border-color: green;
}
`;
const Title = styled.h2`
margin: 0;
font-size: 1.1rem;
font-weight: normal;
color: #666;
height: 43px;
`;
const Image = styled.div`
margin-top: 10px;
background: url(${p => p.path.base_url + p.path.primary}) no-repeat;
width: 120px;
height: 180px;
background-size: contain;
`;
const TileTpl = ({ details }) => {
return (
<ProductTile>
<Title>{details.title}</Title>
<Image path={details.images[0]} />
<AddProduct details={details} />
</ProductTile>
);
};
TileTpl.propTypes = {
details: PropTypes.object.isRequired
};
export default TileTpl;<file_sep>/app/store/sagas/fetchAll.js
import { call, put, takeEvery } from 'redux-saga/effects';
import actionTypes from '../actions/actionTypes';
import { getProductsSucceeded, getProductsFailed } from '../actions/actionCreators';
import { fetchGet } from '../../api/async';
import { dataUrls } from '../../constants';
export function* fetchAll(action) {
try {
const data = yield call(fetchGet, dataUrls.ALL);
yield put(getProductsSucceeded(data));
} catch (err) {
console.log(err);
yield put(getProductsFailed(err));
}
}
export default function* watchFetchAll() {
yield takeEvery(actionTypes.GET_PRODUCTS, fetchAll);
}
|
0648722f86e773bf762b5f6af6483bf4b9e8fa92
|
[
"JavaScript"
] | 7 |
JavaScript
|
simonatorw/products
|
9d8e1ed1a64b428b4f8528d205edc138cebd9766
|
dbaa3dec058197ba3a40d322bc8c1068884e39d2
|
refs/heads/master
|
<repo_name>debayan3007/lyrics-viz<file_sep>/backend/routes/lyrics.js
const express = require('express');
const router = express.Router();
const request = require('request');
const API_KEY = '7c80e5e7f430562b61edae8165b751d7';
function getLyrics (body) {
let lyrics;
try {
lyrics = JSON.parse(body).message.body.lyrics.lyrics_body;
} catch (e) {
lyrics = '';
}
lyrics = lyrics.replace(`\n...\n\n******* This Lyrics is NOT for Commercial use *******`, '').trim()
return {
lyrics,
};
}
function getResults (body) {
const track_list = JSON.parse(body).message.body.track_list
return track_list.map((el) => {
const {
track: {
track_id: trackId,
track_name: songName,
artist_name: artistName,
}
} = el;
return {
trackId,
songName,
artistName,
}
});
}
router.get('/', function (req, res, next) {
res.send('set of lyrics api');
});
router.get('/get/:trackId', function (req, res, next) {
const { trackId } = req.params
var options = {
method: 'GET',
url: 'http://api.musixmatch.com/ws/1.1/track.lyrics.get',
qs: {
track_id: trackId,
apikey: '7c80e5e7f430562b61edae8165b751d7'
}
};
request(options, function (error, response, body) {
if (error) {
console.log(error);
res.send({ error: true, erorObj: error });
}
res.send(getLyrics(body));
});
})
router.get('/search', (req, res, next) => {
const {
q,
page = 1
} = req.query;
var options = {
method: 'GET',
url: 'http://api.musixmatch.com/ws/1.1/track.search',
qs: {
q,
s_track_rating: 'desc',
apikey: API_KEY,
page_size: '10',
page
}
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
res.send(getResults(body));
});
});
module.exports = router;
<file_sep>/src/components/Lyrics.js
import React, { Component } from 'react';
class Lyrics extends Component {
render() {
return (
<div
>
{this.props.lyrics.map((el, i) => {
if (el.trim() === '') {
return (
<div key={`para-${i}`}>
<br />
</div>
)
}
return (
<div key={`para-${i}`}>
{el}
<br />
</div>
);
})}
</div>
)
}
}
export default Lyrics
|
b5f54d38f04f6d680c599a418dea5ac11d628e87
|
[
"JavaScript"
] | 2 |
JavaScript
|
debayan3007/lyrics-viz
|
7d28c123c42f96a2c2853f770c7241da999133fd
|
c707669a5af1e18f4583ec751b2c81a04abbe2bd
|
refs/heads/main
|
<file_sep>let sayi1 = 10
sayi1 = "<NAME>"
let student = {id:1, name:"Engin"}
console.log(student);
function save(puan=10, ogrenci) {
// console.log(ogrenci.name + " : " + puan)
}
save(undefined, student);
let students = ["<NAME>", "<NAME>", "<NAME>", "Büşra"]
// console.log(students)
let students2= [student, {id:2, name:"Halit"},"Ankara", {city:"İstanbul"}]
// console.log(students2)
//rest (GERİYE KALANLAR)
//params(c#)
//varArgs(Java)
let showProducts = function (id, ...products) {
console.log(id)
console.log(products[0])
}
// console.log(typeof showProducts)
// showProducts(10, ["Elma", "Armut", "Karpuz"])
//spread (ayrıştırmak)
let points = [1,2,3,4,50,4,60,14]
console.log(...points) //point artık array değil.
console.log(Math.max(...points)) //Array olarak gönderirsen çıktı -> NaN (Not a Number)
console.log(..."ABC","D",..."EFG", "H")
//Destructuring --> elinizdeki arrayın değerlerini değişkenlerine atama yöntemi
let populations = [10000, 20000, 30000, [40000, 10000]]
let [small, medium, high, [veryHigh, maximum]] = populations
console.log(small)
console.log(medium)
console.log(high)
console.log(veryHigh)
console.log(maximum)
function someFunction([small1], number){
console.log(small1)
}
someFunction(populations)
let category = {id:1, name:"İçecek"}
console.log(category.id)
console.log(category["name"]) // ["name"] -> bu şekilde de çağrılabilir.
// objenin istediğim elemanlarını değişkenlere atama yöntemi
let {id, name} = category
console.log(id)
console.log(name)
//Redux<file_sep>class Customer{
constructor(id, customerNumber){
this.id =id; // this.x =id
this.customerNumber = customerNumber;
}
}
let customer = new Customer(1, "12345");
//prototyping
customer.name = "<NAME>" //instance'a yapılan prototyping
console.log(customer.name)
Customer.bisey = "Bişey" //classa yapılan prototyping
console.log(Customer.name)
console.log(customer.customerNumber)
class IndividualCustomer extends Customer{
constructor(firstName, id, customerNumber){
super(id, customerNumber)
this.firstName = firstName
}
}
class CorporateCustomer extends Customer{
constructor(companyName, id , customerNumber){
super(id, customerNumber)
this.companyName = companyName
}
}
let products = [
{id:1, name : "Acer Laptop", unitPrice:15000},
{id:2, name : "Asus Laptop", unitPrice:16000},
{id:3, name : "Hp Laptop", unitPrice:13000},
{id:4, name : "Dell Laptop", unitPrice:12000},
{id:5, name : "Casper Laptop", unitPrice:17000},
]
console.log("<ul>")
products.map(product=>console.log(`<li>${product.name}</li>`))
console.log("</ul>")
|
fef795b979707d3f420f11fd7625664b7c67c1ec
|
[
"JavaScript"
] | 2 |
JavaScript
|
Senabahadir/JavaKampJs
|
533bf6c364147bb286b5666c67dfa6fdab2c22b7
|
7135f1f4aa4f658b6b17c1a0225d70e5d5d19fe6
|
refs/heads/master
|
<repo_name>TS-Yaloshi/Vagado<file_sep>/src/main/java/nl/han/oose/vragen/Vragenlijst.java
package nl.han.oose.vragen;
public interface Vragenlijst {
String getNaam();
int[] start();
String getThemaNaam();
}
<file_sep>/src/main/java/nl/han/oose/Spel.java
package nl.han.oose;
import nl.han.oose.exceptions.PlayerNotFoundException;
import java.util.List;
import java.util.Scanner;
public class Spel {
private List<Speler> spelers;
public Spel(List<Speler> spelers) {
this.spelers = spelers;
}
private void kiesMenu(Speler speler) {
Scanner scanner = new Scanner(System.in);
System.out.println("______________________");
System.out.println("<-- Main Menu -->");
System.out.println("1. Start Quiz");
System.out.println("2. Exit");
System.out.println("______________________");
System.out.println("Maak een keuze uit het Menu: ");
System.out.print("--> ");
String input = scanner.nextLine().toLowerCase();
if (input.equals("1")) {
speler.speelQuiz();
} else if (input.equals("2")) {
return;
}
kiesMenu(speler);
}
public void speelQuiz(String spelerNaam) throws PlayerNotFoundException {
Speler speler = getSpelerByName(spelerNaam);
kiesMenu(speler);
}
private Speler getSpelerByName(String spelerNaam) throws PlayerNotFoundException {
for (Speler speler : spelers) {
if (speler.getNaam().toLowerCase().equals(spelerNaam.toLowerCase())) {
return speler;
}
}
throw new PlayerNotFoundException();
}
}
<file_sep>/README.md
Vagado - small console-based application to showcase that we can translate a domain model / sequence diagram / design class diagram to an implementation of an application.
It's in Dutch.<file_sep>/src/main/java/nl/han/oose/puntentelling/PuntenStrategie.java
package nl.han.oose.puntentelling;
public interface PuntenStrategie {
int bereken(int aantalGoed, long tijd);
}
|
8fac58e5a22118d060189ffdc35a9ccb8109a30d
|
[
"Markdown",
"Java"
] | 4 |
Java
|
TS-Yaloshi/Vagado
|
bf1a572cfff43292fff94147d4f3e3525ef8a8bf
|
7eb7b6ede48a585b1b4b63de16797896931d8226
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.