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
|
<repo_name>TheBurlapCat/canvas_lessons<file_sep>/canvas_line_cap/lineCap.js
var canvasElement = document.getElementById('lineCapCanvas');
var renderingContext = canvasElement.getContext('2d');
var render = function() {
//butt line cap (top line)
renderingContext.beginPath();
renderingContext.moveTo(200, canvasElement.height / 2 - 50);
renderingContext.lineTo(canvasElement.width - 200, canvasElement.height / 2 -50);
renderingContext.lineWidth = 20;
renderingContext.strokeStyle = '#0000ff';
renderingContext.lineCap = 'butt';
renderingContext.stroke();
//round line cap (middle line)
renderingContext.beginPath();
renderingContext.moveTo(200, canvasElement.height / 2);
renderingContext.lineTo(canvasElement.width - 200, canvasElement.height / 2);
renderingContext.lineWidth = 20;
renderingContext.strokeStyle = '#0000ff';
renderingContext.lineCap = 'round';
renderingContext.stroke();
//square line cap (bottom line)
renderingContext.beginPath();
renderingContext.moveTo(200, canvasElement.height / 2 + 50);
renderingContext.lineTo(canvasElement.width - 200, canvasElement.height / 2 +50);
renderingContext.lineWidth = 20;
renderingContext.strokeStyle = '#0000ff';
renderingContext.lineCap = 'square';
renderingContext.stroke();
};
render();<file_sep>/canvas_cat_illustration/cat.js
var canvas = document.getElementById('catIllustration');
var contextElement = canvas.getContext('2d');
//cat eye right
var centerX = 200;
var centerY = 200;
var radius = 15;
contextElement.beginPath();
contextElement.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
contextElement.lineWidth = 5;
contextElement.strokeStyle = 'white';
contextElement.stroke();
//cat eye left
var centerX = 280;
var centerY = 200;
var radius = 15;
contextElement.beginPath();
contextElement.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
contextElement.lineWidth = 5;
contextElement.stroke();
//cat face
var centerX = 240;
var centerY = 220;
var radius = 90;
contextElement.beginPath();
contextElement.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
contextElement.lineWidth = 5;
contextElement.stroke();
//cat ear left
contextElement.beginPath();
contextElement.moveTo(160, 177);
contextElement.lineTo(170, 75);
contextElement.lineTo(230, 130);
contextElement.lineJoin = 'round';
contextElement.lineWidth = 5;
contextElement.stroke();
//cat ear right
contextElement.beginPath();
contextElement.moveTo(250, 130);
contextElement.lineTo(310, 75);
contextElement.lineTo(320, 177);
contextElement.lineJoin = 'round';
contextElement.stroke();
//cat nose
contextElement.beginPath();
contextElement.moveTo(220, 230);
contextElement.lineTo(260, 231);
contextElement.lineTo(240, 250);
contextElement.lineTo(220, 230);
contextElement.lineJoin = 'round';
contextElement.lineCap = 'round';
contextElement.stroke();
//cat body top
contextElement.beginPath();
contextElement.moveTo(305, 282)
contextElement.bezierCurveTo(350, 280, 500, 200, 650, 500);
contextElement.lineWidth = 5;
contextElement.stroke();
//cat body bottom
contextElement.beginPath();
contextElement.moveTo(185, 291);
contextElement.bezierCurveTo(180, 420, 180, 600, 650, 500);
contextElement.lineWidth = 5;
contextElement.stroke();
//cat mouth
contextElement.beginPath();
contextElement.moveTo(240, 250);
contextElement.lineTo(210, 270);
contextElement.lineWidth = 5;
contextElement.stroke();
//cat mouth
contextElement.beginPath();
contextElement.moveTo(240, 250);
contextElement.lineTo(270, 270);
contextElement.stroke();
//Wiskers Left
contextElement.beginPath();
contextElement.moveTo(200, 240);
contextElement.lineTo(100, 200);
contextElement.lineWidth = 2;
contextElement.stroke();
contextElement.beginPath();
contextElement.moveTo(180, 250);
contextElement.lineTo(80, 250);
contextElement.stroke();
contextElement.beginPath();
contextElement.moveTo(200, 260);
contextElement.lineTo(100, 280);
contextElement.stroke();
//Wiskers Right
contextElement.beginPath();
contextElement.moveTo(280, 240);
contextElement.lineTo(380, 200);
contextElement.stroke();
contextElement.beginPath();
contextElement.moveTo(300, 250);
contextElement.lineTo(400, 250);
contextElement.stroke();
contextElement.beginPath();
contextElement.moveTo(280, 260);
contextElement.lineTo(380, 280);
contextElement.stroke();
//Tail
contextElement.beginPath();
contextElement.moveTo(649, 500);
contextElement.bezierCurveTo(790, 420, 650, 280, 780, 100);
contextElement.lineWidth = 5;
contextElement.lineCap = 'round';
contextElement.stroke();
//Front Left Leg
contextElement.beginPath();
contextElement.moveTo(238, 480);
contextElement.bezierCurveTo(270, 550, 300, 600, 230, 680);
contextElement.lineWidth = 5;
contextElement.lineCap = 'round';
contextElement.stroke();
//Front Right Leg
contextElement.beginPath();
contextElement.moveTo(310, 450);
contextElement.bezierCurveTo(342, 550, 362, 600, 302, 680);
contextElement.lineWidth = 5;
contextElement.lineCap = 'round';
contextElement.stroke();
//Back Left Leg
contextElement.beginPath();
contextElement.moveTo(470, 527);
contextElement.bezierCurveTo(500, 550, 590, 600, 520, 680);
contextElement.lineWidth = 5;
contextElement.lineCap = 'round';
contextElement.stroke();
//Back Right Leg
contextElement.beginPath();
contextElement.moveTo(500, 400);
contextElement.bezierCurveTo(400, 460, 662, 600, 600, 680);
contextElement.lineWidth = 5;
contextElement.lineCap = 'round';
contextElement.stroke();
<file_sep>/canvas_path_lineJoin/lineJoin.js
var canvas = document.getElementById('lineJoinCanvas');
var contextElement = canvas.getContext('2d');
// set line width for all lines
contextElement.lineWidth = 25;
// miter line join (left)
contextElement.beginPath();
contextElement.moveTo(99, 150);
contextElement.lineTo(149, 50);
contextElement.lineTo(199, 150);
contextElement.lineJoin = 'miter';
contextElement.stroke();
// round line join (middle)
contextElement.beginPath();
contextElement.moveTo(239, 150);
contextElement.lineTo(289, 50);
contextElement.lineTo(339, 150);
contextElement.lineJoin = 'round';
contextElement.stroke();
// bevel line join (right)
contextElement.beginPath();
contextElement.moveTo(379, 150);
contextElement.lineTo(429, 50);
contextElement.lineTo(479, 150);
contextElement.lineJoin = 'bevel';
contextElement.stroke();
<file_sep>/canvas_shapes_circle/circles.js
var canvasElement = document.getElementById('circleCanvas');
var renderingContext = canvasElement.getContext('2d');
console.dir(renderingContext);
var position = {
x: 0,
y: 200
};
var render = function() {
window.requestAnimationFrame( render );
renderingContext.clearRect(0,0,800,400);
position.x += 10;
renderingContext.strokeStyle = '#ffffff';
renderingContext.beginPath();
renderingContext.moveTo(100, 150);
renderingContext.lineTo(position.x, position.y);
renderingContext.stroke();
};
render();
<file_sep>/canvas_curve_bezier/bezier.js
var canvas = document.getElementById('bezierCanvas');
var contextElement = canvas.getContext('2d');
contextElement.beginPath();
contextElement.moveTo(188, 130);
contextElement.bezierCurveTo(140, 10, 388, 10, 388, 170);
contextElement.lineWidth = 10;
// line color
contextElement.strokeStyle = 'white';
contextElement.stroke();
<file_sep>/canvas_path_rounderCorners/roundedCorners.js
var canvas = document.getElementById('roundedCornerPaths');
var contextElement = canvas.getContext('2d');
var rectWidth = 200;
var rectHeight = 100;
var rectX = 189;
var rectY = 50;
var cornerRadius = 50;
contextElement.beginPath();
contextElement.moveTo(rectX, rectY);
contextElement.lineTo(rectX + rectWidth - cornerRadius, rectY);
contextElement.arcTo(rectX + rectWidth, rectY, rectX + rectWidth, rectY + cornerRadius, cornerRadius);
contextElement.lineTo(rectX + rectWidth, rectY + rectHeight);
contextElement.lineWidth = 5;
contextElement.stroke();
<file_sep>/canvas_line/line.js
var canvasElement = document.getElementById('lineCanvas');
var renderingContext = canvasElement.getContext('2d');
var render = function() {
renderingContext.strokeStyle = '#ffffff';
renderingContext.beginPath();
renderingContext.moveTo(100, 150);
renderingContext.lineTo(450, 50);
renderingContext.stroke();
};
render();
<file_sep>/canvas_path/path.js
var canvas = document.getElementById('pathCanvas');
var contextElement = canvas.getContext('2d');
contextElement.beginPath();
contextElement.moveTo(100, 200);
//line 1
contextElement.lineTo(200, 160);
//quadratic curve
contextElement.quadraticCurveTo(230, 200, 250, 120);
//bezier curve
contextElement.bezierCurveTo(290, -40, 300, 200, 400, 150);
//line two
contextElement.lineTo(500, 90);
contextElement.lineWidth = 5;
contextElement.strokeStyle = 'blue';
contextElement.stroke();
|
cc970d30c995db6de1e2e5b616f6ba0214fe933f
|
[
"JavaScript"
] | 8
|
JavaScript
|
TheBurlapCat/canvas_lessons
|
398a8c9b0b1ee21fc3ab669762192fb41e918b31
|
15182a9d177d40a52647a82017e70eccdb1cc64f
|
refs/heads/master
|
<file_sep>
# Comment/uncomment the following line to disable/enable debugging
#DEBUG = y
CC=gcc
ifneq ($(KERNELRELEASE),)
# call from kernel build system
obj-m := habr_drv.o
else
KERNELDIR ?= /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
modules:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
endif
clean:
rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c .tmp_versions *.order *.symvers
depend .depend dep:
$(CC) $(EXTRA_CFLAGS) -M *.c > .depend
test:
sudo dmesg -C
sudo insmod habr_drv.ko
sudo rmmod habr_drv.ko
dmesg
ifeq (.depend,$(wildcard .depend))
include .depend
endif
<file_sep>/*
статья на хабре:
https://habr.com/ru/post/106702/
........................................
root@joker:/tmp/habr_drv# make
make -C /lib/modules/4.15.0-106-generic/build M=/home/vacvvn/software/examples/kernel_example/habr_drv modules
make[1]: Entering directory '/usr/src/linux-headers-4.15.0-106-generic'
CC [M] /home/vacvvn/software/examples/kernel_example/habr_drv/habr_drv.o
Building modules, stage 2.
MODPOST 1 modules
LD [M] /home/vacvvn/software/examples/kernel_example/habr_drv/habr_drv.ko
make[1]: Leaving directory '/usr/src/linux-headers-4.15.0-106-generic'
Теперь посмотрим информацию о только что скомпилированном модуле:
root@joker:/tmp/habr_drv# modinfo habr_drv.ko
filename: habr_drv.ko
description: My nice module
author: <NAME> <<EMAIL>>
license: GPL
depends:
vermagic: 2.6.26-2-openvz-amd64 SMP mod_unload modversions
Ну и наконец установим модуль в ядро:
root@joker:/tmp/habr_drv# insmod habr_drv.ko
Посмотрим есть ли наш модуль с списке:
root@joker:/tmp/habr_drv# lsmod | grep habr_drv
habr_drv 6920 0
И что попало в логи:
root@joker:/tmp/habr_drv# dmesg | tail
[829528.598922] Test module is loaded!
[829528.598926] Please, create a dev file with 'mknod /dev/habr_drv c 249 0'.
Наш модуль подсказываем нам что нужно сделать.
Последуем его совету:
root@joker:/tmp/habr_drv# mknod /dev/habr_drv c 249 0
Ну и наконец проверим работает ли наш модуль:
root@joker:/tmp/habr_drv# cat /dev/habr_drv
habr_drv
Наш модуль не поддерживает приём данных со стороны пользователя:
Внимание, команду давать из под рута!
root@joker:/tmp/habr_drv# echo 1 > /dev/habr_drv
bash: echo: ошибка записи: Недопустимый аргумент
Посмотрим что что скажет модуль на наши действия:
root@joker:/tmp/habr_drv# dmesg | tail
[829528.598922] Test module is loaded!
[829528.598926] Please, create a dev file with 'mknod /dev/habr_drv c 249 0'.
[829747.462715] Sorry, this operation isn't supported.
Удалим его:
root@joker:/tmp/habr_drv# rmmod habr_drv
И посмотрим что он нам скажет на прощание:
root@joker:/tmp/habr_drv# dmesg | tail
[829528.598922] Test module is loaded!
[829528.598926] Please, create a dev file with 'mknod /dev/habr_drv c 249 0'.
[829747.462715] Sorry, this operation isn't supported.
[829893.681197] Test module is unloaded!
Удалим файл устройства, что бы он нас не смущал:
root@joker:/tmp/habr_drv# rm /dev/habr_drv
*/
#include <linux/kernel.h> /* Для printk() и т.д. */
#include <linux/module.h> /* Эта частичка древней магии, которая оживляет модули */
#include <linux/init.h> /* Определения макросов */
#include <linux/fs.h>
/*
Hi! When building the enhanced example with character device, I encountered a build error for kernel 4.15.0–52-generic on 64-bit Mint/Ubuntu:
```
./arch/x86/include/asm/uaccess.h: In function ‘set_fs’: ./arch/x86/include/asm/uaccess.h:32:9: error: dereferencing pointer to incomplete type ‘struct task_struct’ current->thread.addr_limit = fs;
```
The answer to this problem is to include linux/uaccess.h header instead of asm/uaccess.h
*/
// #include <asm/uaccess.h> /* put_user */
#include <linux/uaccess.h> /* put_user */
// Ниже мы задаём информацию о модуле, которую можно будет увидеть с помощью Modinfo
MODULE_LICENSE("GPL");
MODULE_AUTHOR("<NAME> <<EMAIL>>");
MODULE_DESCRIPTION("My nice module");
MODULE_SUPPORTED_DEVICE("habr_drv"); /* /dev/habr_drvdevice */
#define SUCCESS 0
#define DEVICE_NAME "habr_drv" /* Имя нашего устройства */
// Поддерживаемые нашим устройством операции
static int device_open(struct inode *, struct file *);
static int device_release(struct inode *, struct file *);
static ssize_t device_read(struct file *, char *, size_t, loff_t *);
static ssize_t device_write(struct file *, const char *, size_t, loff_t *);
// Глобальные переменные, объявлены как static, воизбежание конфликтов имен.
static int major_number; /* Старший номер устройства нашего драйвера */
static int is_device_open = 0; /* Используется ли девайс ? */
static char text[] = "habr_drv inner text for reading\n"; /* Текст, который мы будет отдавать при обращении к нашему устройству */
static char *text_ptr = text; /* Указатель на текущую позицию в тексте */
// Прописываем обработчики операций на устройством
static struct file_operations fops =
{
.read = device_read,
.write = device_write,
.open = device_open,
.release = device_release};
// Функция загрузки модуля. Входная точка. Можем считать что это наш main()
static int __init habr_drv_init(void)
{
printk(KERN_ALERT "habr_drv driver loaded!\n");
// Регистрируем устройсво и получаем старший номер устройства
major_number = register_chrdev(0, DEVICE_NAME, &fops);
if (major_number < 0)
{
printk("Registering the character device Habr_drv failed with %d\n", major_number);
return major_number;
}
// Сообщаем присвоенный нам старший номер устройства
printk("Habr_drv module is loaded!\n");
printk("Please, create a dev file with 'mknod /dev/habr_drv c %d 0'.\n", major_number);
return SUCCESS;
}
// Функция выгрузки модуля
static void __exit habr_drv_exit(void)
{
// Освобождаем устройство
unregister_chrdev(major_number, DEVICE_NAME);
printk(KERN_ALERT "habr_drv module is unloaded! Bye!\n");
}
// Указываем наши функции загрузки и выгрузки
module_init(habr_drv_init);
module_exit(habr_drv_exit);
static int device_open(struct inode *inode, struct file *file)
{
text_ptr = text;
if (is_device_open)
return -EBUSY;
is_device_open++;
return SUCCESS;
}
static int device_release(struct inode *inode, struct file *file)
{
is_device_open--;
return SUCCESS;
}
static ssize_t
device_write(struct file *filp, const char *buff, size_t len, loff_t *off)
{
printk(KERN_INFO "[device write func]\n");
printk("Sorry, this operation isn't supported.\n");
return -EINVAL;
}
static ssize_t device_read(struct file *filp, /* include/linux/fs.h */
char *buffer, /* buffer */
size_t length, /* buffer length */
loff_t *offset)
{
int byte_read = 0;
if (*text_ptr == 0)
return 0;
printk(KERN_INFO "[device read func]\n");
while (length && *text_ptr)
{
put_user(*(text_ptr++), buffer++);
// printk(KERN_INFO "%c",*text_ptr++);
length--;
byte_read++;
}
return byte_read;
}
|
786b854f52b90a3f2c9591a20a90dd0c3ddfafea
|
[
"C",
"Makefile"
] | 2
|
Makefile
|
vacvvn/habr_drv
|
278a1e62c5209644491981d84042aad23fc64e10
|
58a1a60f7841499a46fa10d890d0ef33ead72c21
|
refs/heads/master
|
<repo_name>yoda31217/gqrwoeormtyy<file_sep>/old/mysite/mysite/templates/mat-deleting-cats.html
{%extends "base.html"%}
{% block mat_deleting %}
<div class = "centered-text">
<h4 class = "title-text" style="text-indent: 1em;"><strong>Удаление колтунов у кошек</strong></h4>
<br>
<img src="/static/polls/koltuny_u_kota.jpg" alt = "удаление колтунов киев" class = "page_image">
<p>
У многих длинношерстных кошек довольно часто бывают подобные проблемы. И в этом случае, основная вина лежит на их хозяевах.
Ведь, как и все домашние животные, они требуют постоянного ухода и внимания. Таких кисок нужно ежедневно причёсывать.
Тем более, что в данный момент нет никакого недостатка в различного вида щетках и расческах. Достаточно зайти в любой
зоомагазин и там Вам предоставят огромный выбор подобных инструментов по уходу за Вашими домашними любимцами. Там Вы
найдёте не только специальные щётки для особенно лохматых питомцев, которые позволят Вам вычесывать шерсть, но и приспособления,
которые срезают колтуны.
<br>
<br>
Колтуны необходимо обязательно срезать. Постарайтесь удержать Вашего питомца и срезать у него спутанные клочки шерсти.
Для улучшения шерсти, советуем Вам обязательно добавлять ему в пищу растительного масла (достаточно одной чайной ложки в день).
Также иногда балуйте Вашу киску рыбкой и нежирным мясом.
В весенний период (как раз именно сейчас) не помешает подкормить Вашу киску витаминами. Самый лучший вариант весенней витаминной
подкормки, это выбрать хорошо сбалансированный поливитаминный комплекс, который во многом положительно сказывается на улучшении
качества шерсти Вашего питомца.
<br>
<br>
<a href="/services/">Цены на удаление колтунов у кошек в Киеве</a>
</p>
</div>
{% endblock %}<file_sep>/old/mysite/mysite/urls.py
from django.conf.urls import patterns, include, url
from mysite.settings import MEDIA_ROOT
from django.contrib import admin
admin.autodiscover()
from polls import views
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': MEDIA_ROOT}),
url(r'^admin/', include(admin.site.urls)),
#url(r'^home/', views.get_home),
url(r'^$', views.home_text, name = "home"),
url(r'^index.html', views.home_text, name = "index"),
url(r'^contactus/', views.get_contactus, name = "contactus"),
url(r'^photos/', views.get_photos, name = "photos"),
url(r'^services/', views.get_services, name = "services"),
url(r'^dog-grooming/', views.get_dog_grooming, name = "dog_grooming"),
url(r'^dog-trimming/', views.get_dog_trimming, name = "dog_trimming"),
url(r'^mat-deleting/', views.get_mat_deleting, name = "mat-deleting"),
url(r'^gigiena-dogs/', views.get_gigiena_dogs, name = "gigiena_dogs"),
url(r'^york-cutting/', views.get_york_cutting, name = "york_cutting"),
url(r'^cat-cutting/', views.get_cat_cutting, name = "cat_cutting"),
url(r'^cat-bath/', views.get_cat_bath, name = "cat_bath"),
url(r'^mat-deleting-cats/', views.get_mat_deleting_cats, name = "mat_deleting_cats"),
url(r'^undercoat-deleting/', views.get_undercoat_deleting, name = "undercoat_deleting"),
url(r'^gigiena-cats/', views.get_gigiena_cats, name = "gigiena_cats"),
)<file_sep>/old/mysite/polls/urls.py
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('',
url(r'^$', views.get_home, name='home'),
url(r'^contactus/$', views.get_contactus, name='contactus'),
)<file_sep>/old/mysite/polls/models.py
from django.db import models
import time
from imagekit.models import ProcessedImageField
from imagekit.processors import ResizeToFill
# Create your models here.
class MainContent(models.Model):
main_text = models.TextField("Some description text")
publish_date = models.TimeField(time.strftime("%H:%M:%S"))
logo = models.ImageField(upload_to = "images/")
def __unicode__(self):
return self.main_text
class ContactPage(models.Model):
contacts_text = models.TextField("This is contacts content")
name = models.TextField(editable = False, blank = True)
def __unicode__(self):
return self.contacts_text
class Photo(models.Model):
image = models.ImageField(upload_to = "images/", blank = True)
title = models.CharField(max_length = 70, blank = True, null = True)
avatar_thumbnail = ProcessedImageField(upload_to='images/',
processors=[ResizeToFill(600, 600)],
format='JPEG',
options={'quality': 60},
blank = True)
def __unicode__(self):
return self.title
class Services(models.Model):
service_text = models.TextField("Some description text")
def __unicode__(self):
return self.service_text
<file_sep>/old/mysite/polls/admin.py
from django.contrib import admin
from polls.models import *
admin.site.register(ContactPage)
admin.site.register(MainContent)
admin.site.register(Photo)
admin.site.register(Services)
<file_sep>/old/mysite/polls/views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext, loader
from models import ContactPage, MainContent, Photo, Services
def get_home(request):
template = loader.get_template('home.html')
return HttpResponse(template.render(RequestContext(request)))
def get_dog_grooming(request):
template = loader.get_template('dog-grooming.html')
return HttpResponse(template.render(RequestContext(request)))
def get_dog_trimming(request):
template = loader.get_template('dog-trimming.html')
return HttpResponse(template.render(RequestContext(request)))
def get_mat_deleting(request):
template = loader.get_template('mat-deleting.html')
return HttpResponse(template.render(RequestContext(request)))
def get_gigiena_dogs(request):
template = loader.get_template('gigiena-dogs.html')
return HttpResponse(template.render(RequestContext(request)))
def get_york_cutting(request):
template = loader.get_template('york-cutting.html')
return HttpResponse(template.render(RequestContext(request)))
def get_cat_cutting(request):
template = loader.get_template('cat-cutting.html')
return HttpResponse(template.render(RequestContext(request)))
def get_cat_bath(request):
template = loader.get_template('cat-bath.html')
return HttpResponse(template.render(RequestContext(request)))
def get_mat_deleting_cats(request):
template = loader.get_template('mat-deleting-cats.html')
return HttpResponse(template.render(RequestContext(request)))
def get_undercoat_deleting(request):
template = loader.get_template('undercoat-deleting.html')
return HttpResponse(template.render(RequestContext(request)))
def get_gigiena_cats(request):
template = loader.get_template('gigiena-cats.html')
return HttpResponse(template.render(RequestContext(request)))
def home_text(request):
home_text_box = MainContent.objects.all()
main_page_image = MainContent.objects.get(id = 1)
context = {'home_text_box': home_text_box,
'main_page_image': main_page_image,
}
return render(request, 'index.html', context)
def get_contactus(request):
country_city = ContactPage.objects.get(name = 'country_city')
#phone = ContactPage.objects.get(name = 'phone')
owner = ContactPage.objects.get(name = 'owner')
context = {'country_city': country_city,
'owner': owner,
}
return render(request, 'contactus.html', context)
def get_photos(request):
images = Photo.objects.all()
titles = Photo.objects.all()
context = {'images': images,
'titles': titles,
}
return render(request, 'photos.html', context)
def get_services(request):
service_text_box = Services.objects.all()
context = {'service_text_box': service_text_box,
}
return render(request, 'services.html', context)
|
4a4f238e76806b391681ae1f6c81b07ba42ff84b
|
[
"Python",
"HTML"
] | 6
|
HTML
|
yoda31217/gqrwoeormtyy
|
e8566c25b9bc1ee965583fba21b298c59bf489ad
|
1c0dd013804543448fd443b0c919188ba9c2eeae
|
refs/heads/master
|
<file_sep>#### 数据库优化
##### 设计篇
1. 选取最适用的字段属性
```
a. 字段宽度尽量小
b. 长度确定时, char > VARCHAR
c. 大小确定时, TINYINT > ... > BIGINT
tinyint: 1字节=8位,-128~127
smallint: 2字节,-32768~32767
int: 4字节,-2147483648~2147483647
bigint: 8字节,-2^63~2^63-1
```
2. 字段尽量设置为not null
```
将来执行查询的时候,数据库不用去比较NULL值
```
##### 索引篇
1. 在合适的字段上建索引
```
```
2. 不对含有大量重复的值的字段建立索引
##### to do or not to do篇
1. join 替代 子查询
2. 不要对有索引的字段做函数操作
3. 可以不用like的时候就不用like
```
select * from book where name like 'mysql%'
select * from book where name >= 'mysql' and name < 'mysqm'
```
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 列表
# 查找和插入的时间随着元素的增加而增加
# 占用空间小
names = ['Tom', 'Jim', 'Kate']
print(names)
print(names[0])
print(names[0:2])
print(names[:2])
print(names[:])
# 更改
names[0] = 'Tomas'
print(names)
# 添加
names.append('Lily')
print(names)
# 删除
del names[0]
print(names)
# 运算符
print(len(names))
print(max(names))
print(min(names))
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 列表生成式
# [expr for iter_var in iterable]
# [expr for iter_var in iterable if cond_expr]
#
# 一行代码打印九九乘法表
print('\n'.join([' '.join ('%dx%d=%2d' % (x,y,x*y) for x in range(1,y+1)) for y in range(1,10)]))
lsit1=[x * x for x in range(1, 11)]
lsit2=[x * x for x in range(1, 11) if x>5]
print(lsit1)
print(lsit2)
lsit3= [(x,y) for x in range(3) for y in range(3)]
print(lsit3)
print('\n------------------------')
# 生成器
# 生成式的中括号改成括号
# (expr for iter_var in iterable)
# (expr for iter_var in iterable if cond_expr)
gen= (x * x for x in range(10))
print(gen)
for num in gen :
print(num)
print('\n------------------------')
# 函数的形式实现生成器
# 在每次调用 next() 的时候执行,遇到 yield语句返回,
# 再次执行时从上次返回的 yield 语句处继续执行
def odd():
print ( 'step 1' )
yield ( 1 )
print ( 'step 2' )
yield ( 3 )
print ( 'step 3' )
yield ( 5 )
o = odd()
print( next( o ) )
print( next( o ) )
print( next( o ) )
print('\n------------------------')
# 打印斐波那契数列
def fibon(n):
a = b = 1
for i in range(n):
yield a
a, b = b, a + b
for x in fibon(10):
print(x , end = ' ')
print('\n------------------------')
# 递归打印斐波那契数列
def fibon2(n):
if n == 0 or n == 1:
return 1
else:
return fibon2(n-1) + fibon2(n-2)
for x in range(10):
print(fibon2(x),end=' ')
print('\n------------------------')
# 打印杨辉三角
def tri(n):
for i in range(n+1):
yield a
a, b = b, a + b
for x in tri(1):
print(x , end = ' ')
print('\n------------------------')
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 函数
# 求和
def sum(a, b):
return a+b
print(sum(1,2))
# 求商与余数
def division ( num1, num2):
a = num1 % num2
b = (num1-a) / num2
return b , a
num1 , num2 = division(9,4)
tuple1 = division(9,4)
print (num1,num2)
print (tuple1)
# 参数列表
#
# 默认参数
# 默认参数必须放参数列表最后
def param_default(name, age = 18, sex = 'male'):
return name, age, sex
print(param_default('Kate', 10,'female'))
print(param_default('Tom'))
# 不定长参数
def param_unknow(name, age, * extras):
print(' name:{0},'.format(name), end='')
print(' age:{0},'.format(age), end='')
print(' extra info:{0}'.format(extras))
return;
param_unknow('Kate', 10, 'female', '165cm', '50kg')
# 强制关键字参数
def param_key(*,name, age):
print(' name:{0}, age:{1}'.format(name,age))
return;
param_key(age = 10, name = 'Kate')
# 匿名函数 lambda
# 代码块
lamSum = lambda a,b : a+b;
print(lamSum(1,2))
#
num2 = 100
sum1 = lambda num1 : num1 + num2 ;
num2 = 10000
sum2 = lambda num1 : num1 + num2 ;
# lambda表达式中的参数num2是自由变量
# 在运行时绑定值,而不是定义时就绑定
# 所以取 10000 而不是 100
print( sum1( 1 ) )
print( sum2( 1 ) )
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 字符串
str1 = 'hello world'
str2 = "hello 'world'"
str3 = '''hello
"world"
'''
print(str1)
print(str2)
print(str3)
# 整数
int1 = 1
int2 = -100
int3 = 0
int4 = 1/2
print(int1)
print(int2)
print(int3)
print(int4)
print(type(str1))
print(type(int1))
print(type(int4))
# 浮点数
print(0.55+0.41)
print(0.55+0.4)
print(0.55+0.411)
# 布尔值
print(1==1)
print(1==0)
print(1==1 and 1==0)
print(1==1 or 1==0)
print(not 1==1)
print(not 1==0)
# 空值
print(None)
# 基本数据类型转换
print(int('100'))
print(int(88.88))
#print(int('88.88'))
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 字典
# 查找和插入的速度极快,不会随着key的增加而变慢
# 需要占用大量的内存
dic = {'name':'hong', 'age':29}
print(dic)
print(dic['age'])
# 修改
dic['age'] = 30
dic['gender'] = 'male'
print(dic)
# 删除
del dic['gender']
print(dic)
# dic.clear()
# print(dic)
# 方法
print(str(dic))
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 打印99乘法表
for i in range(1,10):
for j in range(1,i+1):
# print end='' 把换行符替换成空字符,不换行
print('{}x{}={}\t'.format(i, j, i*j), end='')
print()
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 迭代
# for循环迭代字符串
for char in 'hello world':
print(char, end = ' ')
print('\n')
# for循环迭代list
nums = [1, 2, 3, 4]
for num in nums:
print(num, end = ' ')
print('\n')
# 迭代dictionary
dic = {'name':'hong', 'age':29}
for key in dic:
print('{0}:{1}'.format(key,dic[key]), end=' ')
print('\n')
for value in dic.values():
print(value, end = ' ')
print('\n')
# 其他
for x,y in [(1,'a'), (2,'b')]:
print(x,y)
print('\n------------------------')
# 迭代器
# 字符迭代器
str1 = 'hello'
iter1 = iter(str1)
# list迭代器
list1 = ['a','aa','aaa']
iter2 = iter(list1)
# tuple迭代器
tuple1 = ('father','mother','son','daughter')
iter3 = iter(tuple1)
# 遍历迭代器
for x in iter1:
print(x, end=' ')
print('\n')
while True:
try:
print(next(iter3))
except StopIteration:
break
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 反向迭代
list1 = list(range(10))
print(list1)
list2 = list(reversed(list1))
print(list2)
# 同时迭代 zip
# zip(a, b) 会生成一个可返回元组 (x, y) 的迭代器,其中 x 来自 a,y 来自 b
# 迭代长度跟参数中最短序列长度一致
names = ['Kate', 'Tom', 'Jim']
ages = [18, 19, 20]
for name, age in zip(names, ages):
print(name,age)
dict1= dict(zip(names,ages))
print(dict1)
<file_sep>#### 函数
f:A->B
定义域、值域、上域
区间、开区间、闭区间、半开区间
(a,b) [a,b] (a,b]
求定义域,常见隐含条件
1. 分数的分母不能是0
2. 不能取一个负数的平方根(或四次根、六次根等)
3. 不能取负数或0的对数
4. tan(90°)<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 判断是否是闰年
year = 1900 #int(input("请输入一个年份: "))
if year%100 == 0:
if year%400 ==0:
print('{0}是闰年!'.format(year))
else :
print('{0}不是闰年!'.format(year))
elif year%4 == 0:
print('{0}是闰年!'.format(year))
else :
print('{0}不是闰年!'.format(year))<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# set
set1 = set([1,2,3])
print(set1)
# 新增
set1.add(1)
set1.add(4)
print(set1)
# 删除
set1.remove(2)
print(set1)
# 运用
set2 = set([1,3,5,7,9])
set3 = set([2,4,6,8,10,3])
# 交集
print(set2 & set3)
# 并集
print(set2 | set3)
# 差集
print(set2 - set3)
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 元组
# 初始化后就不能修改
# tuple 的每个元素,指向永远不变
# 但指向的元素可变
# 更安全
sex = ('male', 'female')
week = ('Monday', 'Tuesday', 'Wensday', 'Thursday', 'Friday', 'Saturday', 'Sunday')
print(sex)
print(week)
tuple1 = ()
tuple2 = ('single',) # 单元素的元组必须带个逗号
str1 = ('single') # 不是元组
print(tuple1)
print(tuple2)
print(str1)
# 访问
print(sex[0])
# 修改
# 通过修改可变元组元素
str1 = 'aaa'
list1=[123, 456]
tuple3=(str1,list1)
print(tuple3)
str1 = 'bbb'
list1[0]=789
list1[1]=100
print(tuple3)
# 操作
print(len(sex))
print(max(week))
print(sex+week)
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# if
result = 59
if result >= 60:
print('及格')
else :
print('不及格')
num = 6
if num:
print('default boolean')
cond = ''
if cond:
print('is not enpty')
cond = None
if cond:
print('is not None')
score = 89
if score >= 90:
print('优')
elif score >= 80:
print('良')
elif score >= 60:
print('及格')
else:
print('不及格')
# 循环
for i in [1,2,3]:
print(i)
for i in ('name','age'):
print(i)
for i in set([1,2,3,4]):
print(i)
for i in {'a':1, 'b':222}:
print(i)
# range函数
#
for i in range(3):
print(i)
for i in range(1,9):
print(i)
for i in range(0,5,2):
print(i)
# while
cnt = 1
sum1 = 0
while cnt <= 100:
sum1 = sum1 + cnt
cnt = cnt + 1
print(sum1)
|
443f0be800550e1f248e02f56aff36fee93c9bb1
|
[
"Markdown",
"Python"
] | 14
|
Markdown
|
hongjiacan/learning
|
00b46b09c9ee496addf604bee8b349bc0cf7e6ff
|
d99aa636dfaef829812483c21ca7aa8a15ebe589
|
refs/heads/main
|
<repo_name>jimmyuca/GuiameAndroidApp<file_sep>/app/src/main/java/edu/dami/guiameapp/models/PointModel.java
package edu.dami.guiameapp.models;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class PointModel implements Parcelable {
private String id;
private String name;
private String description;
private String category;
private double lat;
private double lng;
public PointModel(String id, String name, String description, String category, double lat, double lng) {
this.id = id;
this.name = name;
this.description = description;
this.category = category;
this.lat = lat;
this.lng = lng;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLng() {
return lng;
}
public void setLng(double lng) {
this.lng = lng;
}
/*
IMPLEMENTACIONES PARA PARCELABLE
https://developer.android.com/reference/android/os/Parcelable
"Parcelable crushes Serializable in terms of speed..."
Generado con http://www.parcelabler.com/
Alternativas:
https://github.com/johncarl81/parceler
http://parceler.org/
En Kotlin:
https://kotlinlang.org/docs/reference/compiler-plugins.html#parcelable-implementations-generator
*/
protected PointModel(Parcel in) {
id = in.readString();
name = in.readString();
description = in.readString();
category = in.readString();
lat = in.readDouble();
lng = in.readDouble();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
dest.writeString(name);
dest.writeString(description);
dest.writeString(category);
dest.writeDouble(lat);
dest.writeDouble(lng);
}
public static final Parcelable.Creator<PointModel> CREATOR = new Parcelable.Creator<PointModel>() {
@Override
public PointModel createFromParcel(Parcel in) {
return new PointModel(in);
}
@Override
public PointModel[] newArray(int size) {
return new PointModel[size];
}
};
}
<file_sep>/app/src/main/java/edu/dami/guiameapp/helpers/events/ItemTapListener.java
package edu.dami.guiameapp.helpers.events;
import android.view.View;
public interface ItemTapListener {
void onItemTap(View view, int position);
}
<file_sep>/app/build.gradle
apply plugin: 'com.android.application'
// Crea una variable que representa el archivo keystore.properties en la raiz del proyecto
def ksPropsFile = rootProject.file("keystore.properties")
// Instanciar variable que expondrá los datos contenidos en el archivo (keystorePropertiesFile)
def ksProps = new Properties()
// Cargar los datos del archivo en la variable keystoreProperties
ksProps.load(new FileInputStream(ksPropsFile))
android {
compileSdkVersion 30
buildToolsVersion "30.0.2"
defaultConfig {
applicationId "edu.dami.guiameapp"
minSdkVersion 16
targetSdkVersion 30
versionCode 1
versionName "1.0"
vectorDrawables.useSupportLibrary = true
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
signingConfigs {
release {
keyAlias ksProps['keyAlias']
keyPassword ksProps['keyPassword']
storeFile file(ksProps['storeFile'])
storePassword ksProps['storePassword']
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.release
}
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
implementation 'com.google.android.material:material:1.2.1'
implementation "androidx.recyclerview:recyclerview:1.1.0"
//https://developer.android.com/jetpack/androidx/releases/fragment
//implementation "androidx.fragment:fragment:1.2.5"
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.google.android.gms:play-services-location:17.1.0'
implementation 'com.google.code.gson:gson:2.8.6'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.3.0'
androidTestImplementation 'androidx.test.espresso:espresso-intents:3.3.0'
}<file_sep>/app/src/androidTest/java/edu/dami/guiameapp/PointViewHelperTest.java
package edu.dami.guiameapp;
import android.content.Context;
import androidx.annotation.DrawableRes;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import org.junit.Test;
import org.junit.runner.RunWith;
import edu.dami.guiameapp.adapters.PointViewHelper;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@RunWith(AndroidJUnit4.class)
public class PointViewHelperTest {
@Test
public void dado_obtenerRecursoPorCategoria_conUnNombreValido_retornarIdRecurso() {
@DrawableRes int resourceId = PointViewHelper.getResIdByCategory("bannerapp1_c", getAppContext());
assertEquals(resourceId, R.drawable.bannerapp1_c);
}
private Context getAppContext() {
return InstrumentationRegistry.getInstrumentation().getTargetContext();
}
}
<file_sep>/app/src/main/java/edu/dami/guiameapp/fragments/PointsFragment.java
package edu.dami.guiameapp.fragments;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import edu.dami.guiameapp.R;
import edu.dami.guiameapp.adapters.PointsAdapter;
import edu.dami.guiameapp.helpers.events.ItemTapListener;
import edu.dami.guiameapp.models.PointModel;
/**
* A simple {@link Fragment} subclass.
* Use the {@link PointsFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class PointsFragment extends Fragment {
private static final String ARG_LIST = "points_list";
private PointsAdapter pointsAdapter;
private ArrayList<PointModel> mPointsList;
private ItemTapListener itemTapListener;
public PointsFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param points Lista de puntos.
* @return A new instance of fragment PointsFragment.
*/
public static PointsFragment newInstance(ArrayList<PointModel> points) {
PointsFragment fragment = new PointsFragment();
Bundle args = new Bundle();
args.putParcelableArrayList(ARG_LIST, points);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mPointsList = getArguments().getParcelableArrayList(ARG_LIST);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_points, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setup(view);
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
if(!(context instanceof ItemTapListener)) {
throw new ClassCastException("Actividad padre no implementa ItemTapListener");
}
itemTapListener = (ItemTapListener)context;
}
private void setup(@NonNull View view) {
setupPointListView(view);
}
private void setupPointListView(View view) {
RecyclerView rvPoints = view.findViewById(R.id.rv_points);
pointsAdapter = new PointsAdapter(mPointsList, itemTapListener);
rvPoints.setAdapter(pointsAdapter);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
rvPoints.setLayoutManager(layoutManager);
rvPoints.setHasFixedSize(true);
}
}<file_sep>/dist-data/README.md
Se ha agregado este archivo en el repositorio para fines prácticos y pedagógicos, logicamente no se usará para subir a alguna tienda.
Por favor **nunca subas este tipo de archivos a un repositorio público o incluso privado**, si mantenés el archivo en el repositorio por practicidad, agregalo a `.gitignore`<file_sep>/app/src/test/java/edu/dami/guiameapp/PointMockSourceTest.java
package edu.dami.guiameapp;
import org.junit.Test;
import java.util.List;
import edu.dami.guiameapp.data.IPointsSource;
import edu.dami.guiameapp.data.PointsMockSource;
import edu.dami.guiameapp.models.PointModel;
import static org.junit.Assert.*;
public class PointMockSourceTest {
@Test
public void dado_obtenerPuntos_conUnContador_retornarListaFiltrada() {
final int expectedCount = 5;
IPointsSource pointsSource = new PointsMockSource();
List<PointModel> pointsList = pointsSource.getAll(expectedCount);
assertNotNull(pointsList);
assertEquals(expectedCount, pointsList.size());
}
@Test(expected = IllegalArgumentException.class)
public void dado_obtenerPuntos_conUnContadorNegativo_arrojarExcepcion() {
IPointsSource pointsSource = new PointsMockSource();
List<PointModel> pointsList = pointsSource.getAll(-1);
assertNotNull(pointsList);
}
@Test
public void dado_obtenerPuntos_conUnContadorCero_retornarListaCompleta() {
IPointsSource pointsSource = new PointsMockSource();
List<PointModel> pointsList = pointsSource.getAll(0);
assertNotNull(pointsList);
assertFalse(pointsList.isEmpty());
}
}
<file_sep>/app/src/main/java/edu/dami/guiameapp/data/UserConfig.java
package edu.dami.guiameapp.data;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.Locale;
import edu.dami.guiameapp.BuildConfig;
import edu.dami.guiameapp.R;
import edu.dami.guiameapp.models.UserModel;
public class UserConfig {
private static final String USER_PREF_NAME = "user_prefs";
private static final String PREF_FIRST_TIME = "is_first_time";
private static final String PREF_USER_NAME = "user_name";
private static final String PREF_USER_EMAIL = "user_email";
private final SharedPreferences mPrefs;
public UserConfig(@NonNull Context context) {
mPrefs = context.getSharedPreferences(getPrefsName(), Context.MODE_PRIVATE);
}
public boolean isFirstTime() {
return mPrefs.getBoolean(PREF_FIRST_TIME, true);
}
public boolean setIsFirstTime(Boolean value) {
SharedPreferences.Editor prefsEditor = mPrefs.edit();
prefsEditor.putBoolean(PREF_FIRST_TIME, value);
/*
apply() changes the in-memory SharedPreferences object immediately but writes the updates to disk asynchronously.
Alternatively, you can use commit() to write the data to disk synchronously. But because commit() is synchronous,
you should avoid calling it from your main thread because it could pause your UI rendering.
*/
prefsEditor.apply();
return true;
}
public boolean userExists() {
return mPrefs.contains(PREF_USER_NAME) && mPrefs.contains(PREF_USER_EMAIL);
}
@Nullable
public UserModel getUser() {
final String name = mPrefs.getString(PREF_USER_NAME, null);
final String email = mPrefs.getString(PREF_USER_EMAIL, null);
if(TextUtils.isEmpty(name) || TextUtils.isEmpty(email)) {
return null;
}
return new UserModel(name, email);
}
public boolean setUser(@Nullable UserModel user) {
if(user == null) return false;
if(TextUtils.isEmpty(user.getFullname()) || TextUtils.isEmpty(user.getEmail()))
return false;
SharedPreferences.Editor prefsEditor = mPrefs.edit();
prefsEditor.putString(PREF_USER_NAME, user.getFullname());
prefsEditor.putString(PREF_USER_EMAIL, user.getEmail());
prefsEditor.apply();
return true;
}
//When naming your shared preference files, you should use a name that's uniquely identifiable to your app
private String getPrefsName() {
return String.format(
Locale.getDefault(),
"%s_%s",
BuildConfig.APPLICATION_ID , USER_PREF_NAME
);
}
}
<file_sep>/app/src/androidTest/java/edu/dami/guiameapp/UserConfigTest.java
package edu.dami.guiameapp;
import android.content.Context;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.List;
import edu.dami.guiameapp.data.IPointsSource;
import edu.dami.guiameapp.data.PointsAssetSource;
import edu.dami.guiameapp.data.UserConfig;
import edu.dami.guiameapp.models.PointModel;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@RunWith(AndroidJUnit4.class)
public class UserConfigTest {
@Test
public void dado_esPrimeraVez_sinValor_obtenerFalso() {
UserConfig userCfg = new UserConfig(getAppContext());
boolean isFirstTime = userCfg.isFirstTime();
assertFalse(isFirstTime);
}
@Test
public void dado_esPrimeraVez_conValorTrue_guardarOk() {
UserConfig userCfg = new UserConfig(getAppContext());
boolean firstTimeResponse = userCfg.setIsFirstTime(true);
assertTrue(firstTimeResponse);
boolean isFirstTime = userCfg.isFirstTime();
assertTrue(isFirstTime);
}
@Test
public void dado_esPrimeraVez_conValorFalse_guardarOk() {
UserConfig userCfg = new UserConfig(getAppContext());
boolean firstTimeResponse = userCfg.setIsFirstTime(false);
assertTrue(firstTimeResponse);
boolean isFirstTime = userCfg.isFirstTime();
assertFalse(isFirstTime);
}
//TODO: podria usarse Parameters para reemplazar 2 tests anteriores pero demasiado complicado para algo basico
//ref: https://github.com/mobiniustechnologies/android-testing/blob/master/runner/AndroidJunitRunnerSample/app/src/androidTest/java/com/example/android/testing/androidjunitrunnersample/CalculatorAddParameterizedTest.java
private Context getAppContext() {
return InstrumentationRegistry.getInstrumentation().getTargetContext();
}
}
<file_sep>/app/src/androidTest/java/edu/dami/guiameapp/PointAssetSourceTest.java
package edu.dami.guiameapp;
import android.content.Context;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.List;
import edu.dami.guiameapp.data.IPointsSource;
import edu.dami.guiameapp.data.PointsAssetSource;
import edu.dami.guiameapp.data.PointsMockSource;
import edu.dami.guiameapp.models.PointModel;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
@RunWith(AndroidJUnit4.class)
public class PointAssetSourceTest {
@Test
public void dado_obtenerPuntos_conUnContador_retornarListaFiltrada() {
final int expectedCount = 5;
IPointsSource pointsSource = new PointsAssetSource(getAppContext());
List<PointModel> pointsList = pointsSource.getAll(expectedCount);
assertNotNull(pointsList);
assertEquals(expectedCount, pointsList.size());
}
@Test(expected = IllegalArgumentException.class)
public void dado_obtenerPuntos_conUnContadorNegativo_arrojarExcepcion() {
IPointsSource pointsSource = new PointsAssetSource(getAppContext());
List<PointModel> pointsList = pointsSource.getAll(-1);
assertNotNull(pointsList);
}
@Test
public void dado_obtenerPuntos_conUnContadorCero_retornarListaCompleta() {
IPointsSource pointsSource = new PointsAssetSource(getAppContext());
List<PointModel> pointsList = pointsSource.getAll(0);
assertNotNull(pointsList);
assertFalse(pointsList.isEmpty());
}
private Context getAppContext() {
return InstrumentationRegistry.getInstrumentation().getTargetContext();
}
}
<file_sep>/app/src/androidTest/java/edu/dami/guiameapp/SignUpUiTest.java
package edu.dami.guiameapp;
import android.widget.TextView;
import androidx.test.ext.junit.rules.ActivityScenarioRule;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.LargeTest;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.action.ViewActions.closeSoftKeyboard;
import static androidx.test.espresso.action.ViewActions.replaceText;
import static androidx.test.espresso.action.ViewActions.typeText;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.withContentDescription;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withParent;
import static androidx.test.espresso.matcher.ViewMatchers.withResourceName;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static edu.dami.guiameapp.TestHelper.getStringForTest;
import static edu.dami.guiameapp.TestHelper.hasInputErrorText;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.instanceOf;
@RunWith(AndroidJUnit4.class)
@LargeTest
public class SignUpUiTest {
@Rule
public ActivityScenarioRule<SignUpActivity> activityScenarioRule
= new ActivityScenarioRule<>(SignUpActivity.class);
@Test
public void dado_cargarPantalla_conNoParams_presentarForm() {
onView(withId(R.id.iv_hero)).check(matches(withContentDescription(R.string.banner)));
onView(withId(R.id.tv_title)).check(matches(withText(R.string.empecemos)));
}
@Test
public void dado_clickBoton_conNoParams_presentarError() {
final String username = "";
final String email = "";
onView(withId(R.id.et_fullname)).perform(replaceText(username), closeSoftKeyboard());
onView(withId(R.id.et_email)).perform(replaceText(email), closeSoftKeyboard());
onView(withId(R.id.btn_signup)).perform(click());
onView(withId(R.id.til_fullname))
.check(matches(hasInputErrorText(R.string.fullname_error)));
}
@Test
public void dado_clickBoton_conEmailInvalido_presentarError() {
final String username = "jimmy";
final String email = "";
onView(withId(R.id.et_fullname)).perform(replaceText(username), closeSoftKeyboard());
onView(withId(R.id.et_email)).perform(replaceText(email), closeSoftKeyboard());
onView(withId(R.id.btn_signup)).perform(click());
onView(withId(R.id.til_email))
.check(matches(hasInputErrorText(R.string.email_error)));
}
@Test
public void dado_clickBoton_conParamsCorrectos_navegarPrincipal() {
final String username = "Jimmy";
final String email = "<EMAIL>";
onView(withId(R.id.et_fullname)).perform(typeText(username), closeSoftKeyboard());
onView(withId(R.id.et_email)).perform(typeText(email), closeSoftKeyboard());
onView(withId(R.id.btn_signup)).perform(click());
String title = getStringForTest(R.string.welcome_user_title, username);
// si se llegara a cambiar el actionbar por defecto por 1 toolbar,
// se tiene que reemplazar la logica aqui
onView(allOf(instanceOf(TextView.class),
withParent(withResourceName("action_bar"))))
.check(matches(withText(title)));
}
}
<file_sep>/app/src/main/java/edu/dami/guiameapp/models/UserModel.java
package edu.dami.guiameapp.models;
public class UserModel {
String fullname;
String email;
public UserModel(String fullname, String email) {
this.fullname = fullname;
this.email = email;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
<file_sep>/app/src/main/java/edu/dami/guiameapp/helpers/FileHelper.java
package edu.dami.guiameapp.helpers;
import android.content.Context;
import android.os.Build;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
public class FileHelper {
//ref: https://bezkoder.com/java-android-read-json-file-assets-gson/
public static String getJsonFromAssets(Context context, String fileName) {
try {
String jsonString;
InputStream is = context.getAssets().open(fileName);
//obtener cantidad de bytes estimados de archivo
int size = is.available();
//crear un arreglo de bytes donde temporalmente alojaremos el contenido del archivo
byte[] buffer = new byte[size];
//transferir el contenido al arreglo creado
is.read(buffer);
//cerrar el stream para optimizar recursos y evitar efectos secundarios.
is.close();
//StandardCharsets.UTF_8 está disponible de a4.4 en adelante, crear fallback (else)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
jsonString = new String(buffer, StandardCharsets.UTF_8);
} else {
jsonString = new String(buffer, "UTF-8");
}
return jsonString;
} catch (IOException e) {
Log.e("FileHelper",
"Ocurrió un error al procesar el archivo. " + e.getMessage()
);
return null;
}
}
}
<file_sep>/app/src/androidTest/java/edu/dami/guiameapp/TestHelper.java
package edu.dami.guiameapp;
import android.app.Activity;
import android.view.View;
import androidx.annotation.StringRes;
import androidx.test.core.app.ActivityScenario;
import androidx.test.ext.junit.rules.ActivityScenarioRule;
import com.google.android.material.textfield.TextInputLayout;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
public class TestHelper {
//src: https://stackoverflow.com/a/34286462/6814301
public static Matcher<View> hasInputErrorText(final String expectedErrorText) {
return new TypeSafeMatcher<View>() {
@Override
public boolean matchesSafely(View view) {
if (!(view instanceof TextInputLayout)) {
return false;
}
CharSequence error = ((TextInputLayout) view).getError();
if (error == null) {
return false;
}
String hint = error.toString();
return expectedErrorText.equals(hint);
}
@Override
public void describeTo(Description description) {
}
};
}
public static Matcher<View> hasInputErrorText(@StringRes int resId) {
String string = getStringForTest(resId);
return hasInputErrorText(string);
}
public static String getStringForTest(@StringRes int id) {
return getInstrumentation()
.getTargetContext()
.getResources()
.getString(id);
}
public static String getStringForTest(@StringRes int id, Object... formatArgs) {
return getInstrumentation()
.getTargetContext()
.getResources()
.getString(id, formatArgs);
}
public static <T extends Activity> void setupDecorView(
ActivityScenarioRule<T> scenarioRule, final TestActivityActionListener listener) {
scenarioRule.getScenario().onActivity(new ActivityScenario.ActivityAction<T>() {
@Override
public void perform(T activity) {
listener.onGetDecorView(activity.getWindow().getDecorView());
}
});
}
public interface TestActivityActionListener {
void onGetDecorView(View decorView);
}
}
|
526937f00f769f4b0806f505453d95e5e87ab091
|
[
"Markdown",
"Java",
"Gradle"
] | 14
|
Java
|
jimmyuca/GuiameAndroidApp
|
2d39972c5f888a20c2661b760515404f966233d9
|
54bcafddeff0e093a4526c95651d68ffda23cf1e
|
refs/heads/master
|
<file_sep>FROM python:3
MAINTAINER <NAME> <<EMAIL>>
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY comix.json.default /usr/src/app/comix.json
COPY comix.py /usr/src/app
EXPOSE 31258
CMD ["python", "./comix.py"]<file_sep># -*- coding: utf-8 -*-
#!/usr/bin/env python
import os
import sys
import json
import logging
import zipfile
from collections import namedtuple
from io import BytesIO
from functools import wraps
#from flask import request
if sys.version_info.major == 3:
from urllib.parse import *
from io import StringIO
else:
from urllib import *
import StringIO
import argparse
import flask
from werkzeug.routing import BaseConverter
__version__ = (0, 2, 1)
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
CONF = json.loads(open('comix.json', 'r').read())
ROOT = CONF['ROOT']
CONTENTS = CONF['CONTENTS']
image_exts = ["jpg", "gif", "png", "tif", "bmp", "jpeg", "tiff"]
archive_exts = ["zip", "rar", "cbz", "cbr"]
allows = image_exts + archive_exts
to_hex = lambda x: hex(ord(x))
ComixData = namedtuple('ComixData', 'Directories Files')
if not os.path.exists(os.path.join(ROOT, CONTENTS)):
raise Exception("No Folder")
def get_ext(path_name):
ext = os.path.splitext(path_name)[-1]
return ext[1:] if ext else ext
app = flask.Flask(__name__)
def check_auth(username, password):
return username == 'AirComix' and password == CONF['PASSWORD']
def authenticate():
return flask.Response(
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = flask.request.authorization
if not auth or not check_auth(auth.username, auth.password):
logger.error("Failed to login")
return authenticate()
return f(*args, **kwargs)
return decorated
def get_real_path(base, abs_path):
abs_path = unquote(abs_path)
real_path = os.path.join(base, abs_path)
app.logger.debug("real_path: %s", real_path)
return real_path
def get_files_in_zip_path(zipname, path):
"""get list of files in folder in zip file """
data = ComixData(Directories=[], Files=[])
with zipfile.ZipFile(zipname) as zf:
for name in zf.namelist():
name = name.decode('euc-kr').encode('utf-8')
pardir, basename = os.path.split(name)
if basename and path == pardir:
app.logger.debug("get_files_in_zip_path: %s, %s", pardir, basename)
data.Files.append(basename)
if len(data.Files):
response = flask.Response(json.dumps(data._asdict(), ensure_ascii=False), headers=None)
return response
return ('', 204)
def list_zip_files(zip_path):
""" Response list of files in zip file """
with zipfile.ZipFile(zip_path) as zf:
data = ComixData(Directories=[], Files=[])
app.logger.info("Loaded the zip file: %s", zip_path)
dirs = [name for name in zf.namelist() if name.endswith('/')]
subdirs = set([name.split('/')[0] for name in dirs])
if subdirs:
for dirname in subdirs:
dirname = dirname.decode('euc-kr').encode('utf-8')
app.logger.debug('list_zip_files: %s, %s', dirname, [to_hex(c) for c in dirname])
data.Directories.append(dirname)
data = json.dumps(data._asdict(), ensure_ascii=False)
response = flask.Response(data, headers=None)
return reseponse
## No folder in zip file
return get_files_in_zip_path(zip_path, '')
@app.route('/')
@requires_auth
def root():
app.logger.info("root directory")
data = json.dumps(ComixData(Directories=[CONTENTS], Files=[])._asdict(), ensure_ascii=False)
r = flask.Response(data, headers=None)
return r
@app.route('/welcome.102/')
@requires_auth
def welcome():
welcome_str = """Hello!\r\n""" \
"""allowDownload=True\r\n""" \
"""autoResizing=False\r\n""" \
"""minVersion=1.3\r\n""" \
"""supportJson=True"""
return welcome_str
@app.route('/<path:req_path>/<string:name>.<string:ext>')
@requires_auth
def load_file(req_path, name, ext):
""" Load file
/folder1/folder2/file.jpg
/folder1/folder2/file.zip
"""
BASE_DIR = ROOT
full_path = "%s/%s.%s" % (req_path, name, ext)
real_full_path= get_real_path(BASE_DIR, full_path)
if ext not in allows:
return ('', 204)
if not os.path.exists(real_full_path):
logger.error("No Path: %s", real_full_path)
return ('', 204)
if ext in archive_exts:
""" List zip files """
logger.info("Archive File: %s", real_full_path)
return list_zip_files(real_full_path)
## Render Image Files
return flask.send_file(real_full_path)
@app.route('/<path:req_path>/<string:name>.<string:ext>/<path:zip_path>')
@requires_auth
def load_zip_folder(req_path, name, ext, zip_path):
""" Get folder in zip file
/folder1/folder2/file.zip/folder
"""
BASE_DIR = ROOT
full_path = "%s/%s.%s" % (req_path, name, ext)
full_real_path = get_real_path(BASE_DIR, full_path)
try:
zip_path = unquote(zip_path).encode('utf-8')
except Exception as e:
logger.info("Failed to encode: %s", zip_path)
if not os.path.exists(full_real_path):
logger.error("No Path: %s", full_real_path)
return ('', 204)
if ext not in archive_exts:
return ('', 204)
#get list of files in folder in zip file
data = ComixData(Directories=[], Files=[])
with zipfile.ZipFile(full_real_path) as zf:
for name in zf.namelist():
name = name.decode('euc-kr').encode('utf-8')
pardir, basename = os.path.split(name)
if basename and zip_path == pardir:
logger.info("get_files_in_zip_path: %s, %s", pardir, basename)
data.Files.append(basename)
if len(data.Files):
response = flask.Response(json.dumps(data._asdict(), ensure_ascii=False), headers=None)
return response
return ('', 204)
@app.route('/<path:req_path>/<string:archive>.<string:archive_ext>/<path:zip_path>/<string:name>.<string:ext>')
@requires_auth
def load_file_in_archive(req_path, archive, archive_ext, zip_path, name, ext):
""" Get file in zip file
/folder1/folder2/file.zip/folder1/file.jpg
"""
BASE_DIR = ROOT
full_path = u"%s/%s.%s" % (req_path, archive, archive_ext)
zip_path = u"%s/%s.%s" % (zip_path, name, ext)
full_real_path = get_real_path(BASE_DIR, full_path)
logger.info("%s, %s", full_real_path, [to_hex(c) for c in full_real_path])
try:
zip_path = unquote(zip_path).encode('utf-8')
except Exception as e:
logger.info("Failed to encode: %s", zip_path)
if ext == 'thm' or archive_ext not in archive_exts:
logger.info("Unsupported file")
return ('', 204)
if os.path.exists(full_real_path.encode('utf-8')):
logger.info("File doesn't exist: %s", full_real_path)
return ('', 204)
#Only zip files are supported <path>/file.zip/1/01.jpg
## Render single file
with zipfile.ZipFile(full_real_path) as zf:
for name in zf.namelist():
encoded_name = name.decode('euc-kr').encode('utf-8')
logger.info("%s(%s), %s(%s), %s, %s", encoded_name, type(encoded_name), zip_path, type(zip_path),
[to_hex(c) for c in name], [to_hex(c) for c in zip_path])
if encoded_name == zip_path:
with zf.open(name) as f:
bytesIO = BytesIO()
bytesIO.write(f.read())
bytesIO.seek(0)
return flask.send_file(bytesIO, attachment_filename=os.path.basename(zip_path), as_attachment=True)
logger.error("No file Name: %s", zip_path)
return ('', 204)
@app.route('/<path:req_path>')
@requires_auth
def load_folders(req_path):
BASE_DIR = ROOT
ROOT_CONTENTS = os.path.join(BASE_DIR, CONTENTS)
real_path = get_real_path(BASE_DIR, req_path)
## List up Root folder
if real_path == ROOT_CONTENTS:
data = ComixData(Directories=[], Files=[])
for name in os.listdir(real_path):
name = name.encode('utf-8')
data.Directories.append(name)
response = flask.Response(json.dumps(data._asdict(), ensure_ascii=False), headers=None)
return response
if not os.path.exists(real_path):
logger.error("No Path: %s", real_path)
return ('', 204)
data = ComixData(Directories=[], Files=[])
## Send list of files
if os.path.isdir(real_path):
for name in os.listdir(real_path):
if os.path.isdir(os.path.join(real_path, name)) or get_ext(name) == 'zip':
data.Directories.append(name)
elif get_ext(name) not in archive_exts:
data.Files.append(name)
response = flask.Response(json.dumps(data._asdict(), ensure_ascii=False), headers=None)
return response
if __name__ == '__main__':
app.run(host=CONF['HOST'], port=CONF['PORT'], debug=True)
<file_sep># PyComix - Python-based AirComix Server
This application can substitue the AricComix Server which supports Windows and OS X.
## Requirements
```
Flask
```
## Limitation
Only supports folder and zip file.
## run
Configuration file
```
{
"ROOT": "z:/",
"CONTENTS": "comics",
"PORT": 31258,
"HOST": "0.0.0.0",
"PASSWORD": "<PASSWORD>"
}
```
```
python comix.py
```
|
675f94ed27289041469ef0f77f249d13ea017331
|
[
"Markdown",
"Python",
"Dockerfile"
] | 3
|
Dockerfile
|
haginara/pycomix
|
ef77fc678b4879e17e5b85e8705161e586fdcb92
|
53ff2bb5862f128f551cfb9dffa2deb4714ed5fd
|
refs/heads/master
|
<file_sep># RAD-projects
A collection of the RAD team's projects for Thalmic Hack'd 3.0. We're hacking ideas to life. Tweet your Myo armband ideas @ThalmicDev using hashtag #thalmichackd.
<file_sep>var myo = Myo.create();
myo.on('pushup', function(){
console.log('PUSHUP');
});
getEulerAngles = function(q){
return {
roll : Math.atan2(2.0*(q.y*q.z + q.w*q.x), q.w*q.w - q.x*q.x - q.y*q.y + q.z*q.z),
pitch : Math.asin(-2.0*(q.x*q.z - q.w*q.y)),
yaw : Math.atan2(2.0*(q.x*q.y + q.w*q.z), q.w*q.w + q.x*q.x - q.y*q.y - q.z*q.z)
}
}
var getDummyData = function(){
return _.times(500, function(index){
return 0
});
}
var data = {
x : getDummyData(),
y : getDummyData(),
z : getDummyData()
};
var genData = function(){
return _.map(data, function(vals, key){
return {
label : key,
data : _.map(vals, function(d, index){
return [index, d]
})
}
})
}
var graph = $.plot('#plot', genData(),{
series: {shadowSize: 0},
colors: [ '#04fbec', '#ebf1be', '#c14b2a', '#8aceb5'],
/*yaxis : {
min : -3,
max : 3
},*/
});
var addData = function(angles){
//console.log(angles);
data.x.shift();
data.y.shift();
data.z.shift();
var x = Math.cos(angles.yaw) * Math.cos(angles.pitch)
var y = Math.sin(angles.yaw) * Math.cos(angles.pitch)
var z = Math.sin(angles.pitch)
data.x.push(Math.cos(angles.yaw) * Math.cos(angles.pitch))
data.y.push(Math.sin(angles.yaw) * Math.cos(angles.pitch))
data.z.push(Math.sin(angles.pitch))
}
myo.on('vector', function(coords){
$('#x').width(300 + -300*coords[0]);
$('#y').height(300 + 300*coords[1]);
})
var prevVal = 0;
myo.on('orientation', function(o){
var ea = getEulerAngles(o)
addData(ea);
graph.setData(genData());
graph.draw();
$('#roll').text(ea.roll);
});
myo.on('fist', function(){
myo.zeroOrientation();
})
myo.on('grid', function(grid){
$('.grid').removeClass('show');
var gridNumber = 0;
if(grid.band === 'upper') gridNumber = 1;
if(grid.band === 'center') gridNumber = 4;
if(grid.band === 'lower') gridNumber = 7;
if(grid.side === 'left') gridNumber += 0;
if(grid.side === 'center') gridNumber += 1;
if(grid.side === 'right') gridNumber += 2;
$('#grid' + gridNumber).addClass('show');
})<file_sep>var THALMIC_HUB = "22a828f1898a4257c3f181e7532413345"
var myo = Myo.create();
var datLight;
//I wrote a much easier JS API for Hue lights for CES, just using it here :)
hue.discover(THALMIC_HUB);
hue.ready(function(){
console.log('Hue lights are ready!');
datLight = hue.lights[4];
// Uses a myo.js plugin to detect snap I wrote
myo.on('snap', function(){
datLight.toggle()
})
});
|
557fe22f793d68d35d0760271f23b50f95d35f22
|
[
"Markdown",
"JavaScript"
] | 3
|
Markdown
|
Ragnorus/RAD-projects
|
4b77985cc5f0f726ae615849757bb1a310ec8666
|
baf4809272772447e321944e6d4e14b34d506855
|
refs/heads/master
|
<file_sep>#!/usr/bin/python
from __future__ import print_function
sign_repeat = 40
def print_args(args):
timelimit = str(args.time) if args.time > 0 else "-1 (UNLIMITED)"
iters = str(args.num_iters) if args.num_iters > 0 else "-1 (UNLIMITED)"
delay = str(args.delay) if args.delay > 0 else "0"
print ("=" * sign_repeat)
print ("The next crystal parameters will be used:")
print ("=" * sign_repeat)
print ("Size of the crystal: ", args.size)
print ("Number of particles: ", args.num_particles)
print ("Proba: ", args.proba)
print ("Time limit: ", timelimit)
print ("Iteration delay: ", delay)
print ("Number of iterations: ", iters)
print ("=" * sign_repeat)
print ()
<file_sep>#!/usr/bin/python
from __future__ import print_function
import sys
import time
import argparse
from utils import print_args
from crystal import Crystal
parser = argparse.ArgumentParser(description="Run commands")
parser.add_argument('-s', '--size', type=int, default=50,
help="Size (length) of a 1D-Crystal")
parser.add_argument('-n', '--num-particles', type=int, default=2,
help="Number of workers (particles in a crystal)")
parser.add_argument('-p', '--proba', type=float, default=0.5,
help="Probability of a particle to move right")
parser.add_argument('-m', '--mode', type=str, default="TIME", choices=["TIME", "ITER"],
help="Mode that the program will work in")
parser.add_argument('-t', '--time', type=int, default=60,
help="Program execution time limit in seconds")
parser.add_argument('-d', '--delay', type=int, default=100,
help="Time each particle will sleep between iterations in milliseconds")
parser.add_argument('-i', '--num_iters', type=int, default=100,
help="Maximum number of iterations each particle does")
parser.add_argument('--visualise', action='store_true',
help="Visualise a crystal to see positions of particles")
def run_crystal(args):
print ("Crystal is running ", end='')
sys.stdout.flush()
for i in range(10):
print ('.', end='')
sys.stdout.flush()
time.sleep (200.0 / 1000.0)
print ()
crystal = Crystal(args.size, args.num_particles, args.proba,
args.time, args.delay, args.num_iters)
crystal.run(args.visualise)
print ("Finished!")
if __name__ == "__main__":
args = parser.parse_args()
if len(sys.argv) == 1:
parser.print_help()
sys.exit(1)
if (args.mode == "TIME"):
args.num_iters = -1
else:
args.time = -1
args.delay = 0
print_args(args)
run_crystal(args)
<file_sep>#!/usr/bin/python
from __future__ import print_function
import time
import random
import threading
class Particle(threading.Thread):
def __init__(self, p_index, size, position, positions,
condition, proba, delay, num_iters):
threading.Thread.__init__(self)
self.p_index = p_index
self.size = size
self.position = position
self.positions = positions
self.condition = condition
self.proba = proba
self.delay = delay
self.num_iters = num_iters
self.iteration = 0
self.stop_event = threading.Event()
def run(self):
while not self.stop_event.is_set():
if self.iteration == self.num_iters:
self.stop()
## ====== DO A STEP [START] ====== #
if self.position == 0:
self.position += 1
elif self.position == self.size - 1:
self.position -= 1
else:
# +1 to move right or -1 to move left
self.position += \
2 * int(random.random() < self.proba) - 1
# Update global memory with the current position
with self.condition:
self.positions[self.p_index] = self.position
## ====== DO A STEP [END] ====== #
if self.num_iters > 0:
self.iteration += 1
else:
time.sleep (self.delay / 1000.0)
def stop(self):
self.stop_event.set()
def is_stopped(self):
return self.stop_event.is_set()
<file_sep># crystal-python-multithreading
Multithreaded modelling of the movement of particles in a crystal
The program describes a physical process of the motion of particles in a crystal. The crystal is a 1-dimensional object with a size of N. Each of K particles at every step commits a [random walk](https://en.wikipedia.org/wiki/Random_walk).
<div style="text-align:center"><img src="assets/crystal-gif.gif" title="Particles movement visualization" /></div>
The main file could be executed with different parameters, to see all of them type the following
```bash
$ python main.py --help [-h]
```
Available arguments are:
```bash
usage: main.py [-h] [-s SIZE] [-n NUM_PARTICLES] [-p PROBA] [-m {TIME,ITER}]
[-t TIME] [-d DELAY] [-i NUM_ITERS] [--visualise]
Run commands
optional arguments:
-h, --help show this help message and exit
-s SIZE, --size SIZE Size (length) of a 1D-Crystal
-n NUM_PARTICLES, --num-particles NUM_PARTICLES
Number of workers (particles in a crystal)
-p PROBA, --proba PROBA
Probability of a particle to move right
-m {TIME,ITER}, --mode {TIME,ITER}
Mode that the program will work in
-t TIME, --time TIME Program execution time limit in seconds
-d DELAY, --delay DELAY
Time each particle will sleep between iterations in
milliseconds
-i NUM_ITERS, --num_iters NUM_ITERS
Maximum number of iterations each particle does
--visualise Visualise a crystal to see positions of particles
```
There are two two main operating modes:
1. **{TIME}** is used to limit a program execution time
2. **{ITER}** is used to limit a number that each particle of the crystal does
### Examples
```bash
$ python main.py --num_particles 10 --proba 0.73 --mode "TIME" --time 20 --delay 300 --visualise
```
```bash
$ python main.py --num_particles 5 --mode "ITER" --num_iterations 100000 --visualise
```
```bash
$ python main.py -s 100 -n 25 -p 0.27 -m "TIME" -t 45
```
### Notes
`curses` library is used to visualise the movement on-the-fly. Since this library works properly only on UNIX environment, it would be better for Windows users to use Cygwin terminal or to disable a visualization.
<file_sep>#!/usr/bin/python
from __future__ import print_function
import os
import time
import threading
from particle import Particle
def is_unix():
return os.name != "nt"
if is_unix():
import curses
class Crystal:
visualization_delay = 300
def __init__(self, size, num_particles, proba, time_limit, delay, num_iters):
self.size = size
self.num_particles = num_particles
self.proba = proba
self.time_limit = time_limit
self.num_iters = num_iters
self.delay = delay
self.positions = [0 for _ in range(num_particles)]
self.update_position_cond = threading.Condition()
self.particles = [Particle(i, size, 0, self.positions, self.update_position_cond,
proba, delay, num_iters) for i in range(num_particles)]
def start_particles(self):
for p in self.particles:
p.start()
def join_particles(self):
for p in self.particles:
p.join()
def stop_particles(self):
for p in self.particles:
p.stop()
def is_running(self):
num_in_progress = 0
for p in self.particles:
if not p.is_stopped():
num_in_progress += 1
return num_in_progress != 0
def print_current_state(self, window):
for p in range(self.num_particles):
out_str = "[{0: <2}] {1}*{2}".format(p + 1, "-" * self.positions[p], '-' * (self.size - 1 - self.positions[p]))
window.addstr(p, 0, out_str)
window.refresh()
def run(self, visualise):
start_time = time.time()
self.start_particles()
## === INIT VISUALIZATION === ##
if is_unix() and visualise:
window = curses.initscr()
curses.noecho()
curses.cbreak()
## === INIT VISUALIZATION === ##
while self.is_running():
if self.num_iters < 0:
if time.time() - start_time > self.time_limit:
self.stop_particles()
if is_unix() and visualise:
self.print_current_state(window)
time.sleep(Crystal.visualization_delay / 1000.0)
## === STOP VISUALIZATION === ##
if is_unix() and visualise:
curses.echo()
curses.nocbreak()
curses.endwin()
## === STOP VISUALIZATION === ##
self.join_particles()
print ("Last crystal state: ",
*zip([i + 1 for i in range(self.num_particles)], self.positions))
|
30f907ee65788090cead101cd620996d3b37c1b9
|
[
"Markdown",
"Python"
] | 5
|
Python
|
sergeyshilin/crystal-python-multithreading
|
cce89d348187b9e813b9c0e6c2407317e5c76a19
|
047da78c78038da81a767824cb8275b8f0448524
|
refs/heads/master
|
<repo_name>saurabhpathak9/spring-angular-activiti-test<file_sep>/middle-tier/workflow-engine-service/src/main/java/com/business/proposal/workflow/engine/service/WorkItemService.java
package com.business.proposal.workflow.engine.service;
import com.business.proposal.workflow.engine.pojo.WorkItem;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.JavaDelegate;
import org.springframework.stereotype.Component;
@Component
public class WorkItemService implements JavaDelegate {
public void createWorkItem(WorkItem workItem) {
System.out.println("Creating work in database with request:+" + workItem.toString());
}
@Override
public void execute(DelegateExecution delegateExecution) throws Exception {
createWorkItem((WorkItem) delegateExecution.getVariable("workItem"));
}
}
<file_sep>/middle-tier/workflow-engine-service/src/main/java/com/business/proposal/workflow/engine/web/WorkflowEngineServiceController.java
package com.business.proposal.workflow.engine.web;
import com.business.proposal.workflow.engine.pojo.WorkItem;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static com.business.proposal.workflow.engine.util.WorkFlowConstants.*;
@RestController
public class WorkflowEngineServiceController {
@Autowired
private RuntimeService runtimeService;
@Autowired
private TaskService taskService;
@Autowired
private HistoryService historyService;
@ResponseStatus(value = HttpStatus.OK)
@RequestMapping(value = "/create-new-proposal", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public String createNewProposal(@RequestBody Map<String, String> item) {
WorkItem workItem = new WorkItem(item.get("companyName"),
item.get("monthOfYear"), Long.parseLong(item.get("businessAmount")));
Map<String, Object> vars = Collections.<String, Object>singletonMap("workItem", workItem);
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("process", vars);
Task task = taskService.createTaskQuery()
.processInstanceId(processInstance.getId())
.singleResult();
Map<String, Object> taskVariables = new HashMap<String, Object>();
taskVariables.put(PROPOSAL_UPLOADED, true);
taskService.complete(task.getId(), taskVariables);
return processInstance.getId();
}
@ResponseStatus(value = HttpStatus.OK)
@RequestMapping(value = "/process-one-approval/{id}/{status}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public void processOneWorkflow(@PathVariable Integer id,
@PathVariable boolean status) {
Task task = taskService.createTaskQuery()
.processInstanceId(id.toString())
.active()
.singleResult();
Map<String, Object> taskVariables = new HashMap<String, Object>();
taskVariables.put(PROCESS_ONE_APPROVAL, status);
taskService.complete(task.getId(), taskVariables);
}
@ResponseStatus(value = HttpStatus.OK)
@RequestMapping(value = "/process-two-approval/{id}/{status}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public void processTwoWorkflow(@PathVariable Integer id,
@PathVariable boolean status) {
Task task = taskService.createTaskQuery()
.processInstanceId(id.toString())
.active()
.singleResult();
Map<String, Object> taskVariables = new HashMap<String, Object>();
taskVariables.put(PROCESS_TWO_APPROVAL, status);
taskService.complete(task.getId(), taskVariables);
}
@ResponseStatus(value = HttpStatus.OK)
@RequestMapping(value = "/process-status/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public HistoricProcessInstance processHistory(@PathVariable Integer id) {
return historyService.createHistoricProcessInstanceQuery().processInstanceId(id.toString()).singleResult();
}
}
<file_sep>/middle-tier/workflow-engine-service/src/main/java/com/business/proposal/workflow/engine/config/BeanConfiguration.java
package com.business.proposal.workflow.engine.config;
import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class BeanConfiguration {
@Bean
InitializingBean usersAndGroupsInitializer(final IdentityService identityService) {
return new InitializingBean() {
public void afterPropertiesSet() throws Exception {
Group group = identityService.newGroup("user");
group.setName("users");
group.setType("security-role");
identityService.saveGroup(group);
User creator = identityService.newUser("creator");
creator.setPassword("<PASSWORD>");
identityService.saveUser(creator);
}
};
}
}
<file_sep>/README.md
# spring-angular-activiti-test<file_sep>/middle-tier/workflow-engine-service/src/main/resources/application.properties
server.port=5050
logging.level.org.springframework.web:DEBUG
management.security.enabled=false
|
c15be7be1421a33d063ddc0f1c8a2e2a91e187bc
|
[
"Markdown",
"Java",
"INI"
] | 5
|
Java
|
saurabhpathak9/spring-angular-activiti-test
|
636481800ab7ce4f0d0a31dbacac2c822cb784e5
|
fd50d248b7dbb2f7f78c4e34665071ec06f8ded0
|
refs/heads/master
|
<file_sep>import { User } from '../users/user';
import { Feature } from '../backlog/feature';
export class Asignment {
public id : number;
public feature : Feature;
public user : User;
public spendingsInt : number[] = [];
public spending: number;
constructor(values: Object = {}) {
Object.assign(this, values);
this.calculateSumSpending();
}
addSpendings(length: number) : Asignment {
for (let index = 0; index < length; index++) {
this.spendingsInt[index] = null;
}
return this;
}
calculateSumSpending() {
let numOr0 = (n: number) => isNaN(n) ? 0 : n;
this.spending = this.spendingsInt.reduce((a,b) => numOr0(a) + numOr0(b),0);
}
}
<file_sep>import { Component, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { Subscription, Observable } from 'rxjs';
import { NgForm } from '@angular/forms';
import { GridApi, GridOptions } from 'ag-grid';
import { MatEditButtonGridRenderComponent } from '../grid-custom-components/mat-edit-button-grid-render/mat-edit-button-grid-render.component';
import { MatRemoveButtonGridRenderComponent } from '../grid-custom-components/mat-remove-button-grid-render/mat-remove-button-grid-render.component';
import { LoginService } from '../login/login.service';
import { HttpErrorResponse } from '@angular/common/http';
import { Feature } from './feature';
import { FeaturesService } from './features.service';
import { AgFormatterService } from '../shared/ag-formatter.service';
@Component({
selector: 'app-features',
templateUrl: './features.component.html',
styleUrls: ['./features.component.scss']
})
export class FeaturesComponent implements OnInit {
public feature = new Feature();
public context: any;
@ViewChild('myForm', { static: false }) myForm: NgForm;
private gridApi: GridApi;
private gridColumnApi;
private columnDefs: any;
private rowData: Feature[];
private gridOptions: GridOptions;
private errorMessage : string = "";
private isEditMode: boolean = false;
constructor(private featuresService: FeaturesService, private loginService: LoginService, private frm: AgFormatterService) {
this.context = { componentParent: this };
this.gridOptions = <GridOptions>{};
this.gridOptions.enableFilter = true;
this.gridOptions.enableSorting = true;
this.gridOptions.rowSelection = 'single';
this.gridOptions.suppressRowClickSelection = false;
this.gridOptions.enableColResize = true;
this.gridOptions.enableCellChangeFlash = true;
this.columnDefs = [
{ headerName: 'Id', field: 'id', hide: true },
{ headerName: 'F.Code', field: 'code', filter: 'text' , width: 110 },
{ headerName: 'Feature Title', field: 'title', filter: 'text', width: 400 },
{ headerName: 'Estimated Hours', field: 'estimatedHours', type: "numericColumn", filter: 'number' , valueFormatter: this.frm.ag_numberTwoDecimalFormatter, width: 160 },
{ headerName: 'Committed Date', field: 'committedDate', filter: 'text', valueFormatter: this.frm.ag_dateFormatter , width: 170 },
{ headerName: '', cellRendererFramework: MatEditButtonGridRenderComponent, width: 75 },
{ headerName: '', suppressFilter: true, cellRendererFramework: MatRemoveButtonGridRenderComponent, width: 75 }
];
}
ngOnInit(): void {
this.populateFeatures();
}
refeshFeatures(): void {
this.populateFeatures();
this.initialMode();
}
private populateFeatures() {
this.features.subscribe(
featureList => this.rowData = featureList,
error => this.handleError(error)
);
}
dateFormatter(params: any) {
return new Date(params.value).toLocaleDateString("en-US",{timeZone: 'UTC', year:"numeric",month:"2-digit", day:"2-digit"});
}
numberFormatter(params: any) {
return params.value.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})
}
get features(): Observable<Feature[]> {
return this.featuresService.getFeatures();
}
getFeatureById(id: number): Observable<Feature> {
return this.featuresService.getFeatureById(id);
}
removeFeature(id: number) {
this.featuresService.deleteFeatureById(id).subscribe(
data => this.refeshFeatures(),
error => console.log(error)
);
}
editFeature(data: Feature) {
this.feature = new Feature(data);
this.errorMessage = "";
}
addFeature(): void {
// this.project.status = "OPEN";
this.featuresService.addFeature(this.feature).subscribe(
data => this.refeshFeatures(),
error => this.handleError(error)
);
}
handleError(res: HttpErrorResponse) {
this.errorMessage = res.error.error_message;
console.log(res);
}
updateFeature(){
this.featuresService.updateFeature(this.feature).subscribe(
data => this.refeshFeatures(),
error => this.handleError(error)
);
}
resetControls() {
this.myForm.resetForm();
Object.keys(this.myForm.controls).forEach(field => {
const control = this.myForm.control.get(field);
control.markAsUntouched();
});
}
// Call from MatRemoveButtonGridRenderComponent
removeFromComponent(feature: Feature){
this.removeFeature(feature.id);
this.initialMode();
}
// Call from MatEditButtonGridRenderComponent
editFromComponent(data: Feature){
this.isEditMode = true;
this.editFeature(data);
}
cancelEditMode() {
this.initialMode();
}
private initialMode() {
this.feature = new Feature();
this.errorMessage = "";
this.isEditMode = false;
this.resetControls();
}
onGridReady(params: any) {
this.gridApi = params.api;
this.gridColumnApi = params.columnApi;
this.gridColumnApi.autoSizeColumns();
}
}
<file_sep>import { TestBed, inject } from '@angular/core/testing';
import { CapacityService } from './capacity.service';
describe('CapacityService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [CapacityService]
});
});
it('should be created', inject([CapacityService], (service: CapacityService) => {
expect(service).toBeTruthy();
}));
});
<file_sep>import { NgModule } from '@angular/core';
import { OutlookComponent } from './outlook.component';
import { SharedModule } from '../shared/shared.module';
import { AgGridModule } from 'ag-grid-angular';
@NgModule({
declarations: [OutlookComponent],
imports: [
SharedModule,
AgGridModule.withComponents([])
]
})
export class OutlookModule { }
<file_sep>import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { LoginService } from '../login/login.service';
import { Asignment } from '../asignment/asignment';
@Injectable({
providedIn: 'root'
})
export class SpendingService {
private _baseUrl = './api/springs/';
constructor(private http: HttpClient, private loginService: LoginService) {
}
getSpendings() : Observable<Asignment[]>{
return this.http.get(this.baseUrl) as Observable<Asignment[]>;
}
saveSpendings(asignments : Asignment[]): Observable<Asignment> {
return this.http.put(`${this.baseUrl}/spendings`, asignments) as Observable<Asignment>;
}
private get baseUrl(): string {
return this._baseUrl + this.loginService.currentSpringId + '/asignments';
}
}
<file_sep>import { User } from '../users/user';
import { Spring } from '../springs/spirng';
export class Capacity {
id : number;
spring : Spring;
user : User;
availableHours : number
constructor(values: Object = {}) {
Object.assign(this, values);
}
}
<file_sep>import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { LoginService } from '../login/login.service';
import { Asignment } from './asignment';
@Injectable({
providedIn: 'root'
})
export class AsignmentService {
private _baseUrl = './api/springs/';
constructor(private http: HttpClient, private loginService: LoginService) {
}
getAsignments() : Observable<Asignment[]>{
return this.http.get(this.baseUrl) as Observable<Asignment[]>;
}
getAsignmentById(id : number): Observable<Asignment> {
return this.http.get(`${this.baseUrl}/${id}`) as Observable<Asignment>;
}
addAsignment(asignment: Asignment): Observable<Asignment> {
return this.http.post(this.baseUrl, asignment) as Observable<Asignment>;
}
deleteAsignmentById(id: number) : Observable<Asignment> {
return this.http.delete(`${this.baseUrl}/${id}`) as Observable<Asignment>;
}
updateAsignment(asignment : Asignment): Observable<Asignment> {
return this.http.put(`${this.baseUrl}/${asignment.id}`, asignment) as Observable<Asignment>;
}
private get baseUrl(): string {
return this._baseUrl + this.loginService.currentSpringId + '/asignments';
}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { LoginService } from '../login/login.service';
import { Observable } from 'rxjs';
import { Advance } from './advance';
@Injectable({
providedIn: 'root'
})
export class OutlookService {
private currentProjectId = "";
private _baseUrl = './api/projects/';
constructor(private http: HttpClient, private loginService: LoginService) {
}
public getAdvance(): Observable<Advance[]> {
return this.http.get(this.baseUrl) as Observable<Advance[]>;
}
private get baseUrl(): string {
return this._baseUrl + this.loginService.currentProjectId + '/q_spring';
}
}
<file_sep>import { NgModule } from '@angular/core';
import { AgGridModule } from 'ag-grid-angular';
import { SharedModule } from '../shared/shared.module';
import { environment } from '../../environments/environment';
import { SpringsComponent } from './springs.component';
import { NoWeekendValidator } from '../shared/date.weekend.directive';
@NgModule({
imports: [
SharedModule,
AgGridModule.withComponents([])
],
exports: [
SpringsComponent
],
declarations: [SpringsComponent]
})
export class SpringsModule { }
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {
MatButtonModule,
MatIconModule,
MatCardModule,
MatFormFieldModule,
MatInputModule,
MatTableModule,
MatTooltipModule,
MatCheckboxModule,
MatSelectModule,
MatSortModule,
MatStepperModule,
} from '@angular/material';
import { MatCheckboxGridModule } from '../grid-custom-components/mat-checkbox-grid/mat-checkbox-grid.module';
import { MatRemoveButtonGridRenderModule } from '../grid-custom-components/mat-remove-button-grid-render/mat-remove-button-grid-render.module';
import { MatEditButtonGridRenderModule } from '../grid-custom-components/mat-edit-button-grid-render/mat-edit-button-grid-render.module';
import { NoWeekendValidator } from './date.weekend.directive';
import { HttpClientModule } from '@angular/common/http';
import { BrowserModule } from '@angular/platform-browser';
import { TwoDigitDecimalNumber } from './decimal.directive';
@NgModule({
imports: [
CommonModule,
HttpClientModule,
FormsModule,
BrowserModule,
MatButtonModule,
MatIconModule,
MatCardModule,
MatFormFieldModule,
MatInputModule,
MatTableModule,
MatSortModule,
MatTooltipModule,
MatCheckboxModule,
MatSelectModule,
BrowserAnimationsModule,
MatCheckboxGridModule,
MatRemoveButtonGridRenderModule,
MatEditButtonGridRenderModule,
MatStepperModule
],
exports: [
CommonModule,
HttpClientModule,
FormsModule,
BrowserModule,
MatButtonModule,
MatIconModule,
MatCardModule,
MatFormFieldModule,
MatInputModule,
MatTableModule,
MatSortModule,
MatTooltipModule,
MatCheckboxModule,
MatSelectModule,
BrowserAnimationsModule,
MatCheckboxGridModule,
MatRemoveButtonGridRenderModule,
MatEditButtonGridRenderModule,
MatStepperModule
],
declarations: [NoWeekendValidator,TwoDigitDecimalNumber]
})
export class SharedModule { }
<file_sep>export class Project {
id : number;
code : string = '';
name : string = '';
startDate : Date;
springDays : number;
// status: string = '';
// backlog: any;
constructor(values: Object = {}) {
Object.assign(this, values);
}
}
<file_sep>import { AbstractControl, NG_VALIDATORS } from "@angular/forms";
import { Directive } from "@angular/core";
import { Day_of_week } from "./date.model";
function noWeekend(c:AbstractControl) {
if (c.value == null) return null;
let day = new Date(c.value).getDay();
if (day == Day_of_week.Saturday || day == Day_of_week.Sunday ) {
return {weekend: true};
}
return null;
}
@Directive({
selector: '[no-weekend]',
providers: [
{provide: NG_VALIDATORS, multi: true, useValue: noWeekend }
]
})
export class NoWeekendValidator { }<file_sep>import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AgFormatterService {
ag_dateFormatter(params: any): string {
return new Date(params.value).toLocaleDateString(undefined,{timeZone: 'UTC', year:"numeric",month:"2-digit", day:"2-digit"});
}
ag_numberTwoDecimalFormatter(params: any) : string {
if (params.value || params.value == 0) {
return params.value.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})
}
return params.value;
}
ag_percentageTwoDecimalFormatter(params: any) : string {
if (params.value || params.value == 0) {
let value = params.value * 100;
return value.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2}) + "%"
}
return params.value;
}
setTwoNumberDecimal(event: any) {
event.target.value = parseFloat(event.target.value).toFixed(2);
}
validateNumberTwoDecimal(event: any) {
//let input = String.fromCharCode(e.charCode);
let specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home', '-', 'ArrowLeft', 'ArrowRight', 'Del', 'Delete'];
if (specialKeys.indexOf(event.key) !== -1) {
return;
}
let input = event.srcElement.value
let input2 = event.target.value
const reg = new RegExp(/^\d+[.,]?\d{0,2}$/g);
// if (!reg.test(input)) {
// e.preventDefault();
// }
}
}<file_sep>export class Holiday {
date : Date = null;
description : string = '';
constructor(values: Object = {}) {
Object.assign(this, values);
}
}
<file_sep>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ProjectsComponent } from './projects/projects.component';
import { LoginComponent } from './login/login.component';
import { UsersComponent } from './users/users.component';
import { SpringsComponent } from './springs/springs.component';
import { FeaturesComponent } from './backlog/features.component';
import { AsignmentComponent } from './asignment/asignment.component';
import { CapacityComponent } from './capacity/capacity.component';
import { SpendingComponent } from './spending/spending.component';
import { HolidaysComponent } from './holidays/holidays.component';
import { OutlookComponent } from './outlook/outlook.component';
const routes: Routes = [
{ path: '', redirectTo: 'projects', pathMatch: 'full' },
{ path: 'projects', component: ProjectsComponent },
{ path: 'springs', component: SpringsComponent },
{ path: 'backlog', component: FeaturesComponent },
{ path: 'asignment', component: AsignmentComponent },
{ path: 'capacity', component: CapacityComponent },
{ path: 'spending', component: SpendingComponent },
{ path: 'holidays', component: HolidaysComponent },
{ path: 'outlook', component: OutlookComponent },
{ path: 'users', component: UsersComponent },
{ path: 'login', component: LoginComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>import { Component, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { Subscription, Observable } from 'rxjs';
import { NgForm } from '@angular/forms';
import { GridApi, GridOptions } from 'ag-grid';
import { LoginService } from '../login/login.service';
import { HttpErrorResponse } from '@angular/common/http';
import { User } from '../users/user';
import { Feature } from '../backlog/feature';
import { FeaturesService } from '../backlog/features.service';
import { UserService } from '../users/users.service';
import { SpendingService } from './spending.service';
import { Asignment } from '../asignment/asignment';
import { DateModel } from '../shared/date.model';
import { AgFormatterService } from '../shared/ag-formatter.service';
@Component({
selector: 'app-spending',
templateUrl: './spending.component.html',
styleUrls: ['./spending.component.scss']
})
export class SpendingComponent implements OnInit {
public context: any;
@ViewChild('myForm', { static: false }) myForm: NgForm;
private gridApi: GridApi;
private gridColumnApi;
private columnDefs: any;
private rowData: Asignment[];
private features : Feature[];
private users : User[];
private gridOptions: GridOptions;
private errorMessage : string = "";
private isEditMode: boolean = false;
constructor(private spendingsService: SpendingService, private featuresService :FeaturesService, private userService :UserService, private loginService: LoginService, private frm: AgFormatterService) {
this.context = { componentParent: this };
this.gridOptions = <GridOptions>{};
this.gridOptions.enableFilter = true;
this.gridOptions.enableSorting = true;
this.gridOptions.rowSelection = 'single';
this.gridOptions.suppressRowClickSelection = false;
this.gridOptions.enableColResize = true;
this.gridOptions.enableCellChangeFlash = true;
this.gridOptions.getRowStyle = function(params: any) {
if (params.data.feature.estimatedHours - params.data.spending === 0) {
return { background: '#DAEFFE' }
}
}
this.gridOptions.headerHeight = 65;
// this.gridOptions.defaultColDef = { headerComponentParams : {
// menuIcon: 'fa-bars',
// template:
// '<div class="ag-cell-label-container" role="presentation">' +
// ' <span ref="eMenu" class="ag-header-icon ag-header-cell-menu-button"></span>' +
// ' <div ref="eLabel" class="ag-header-cell-label" role="presentation">' +
// ' <span ref="eSortOrder" class="ag-header-icon ag-sort-order" ></span>' +
// ' <span ref="eSortAsc" class="ag-header-icon ag-sort-ascending-icon" ></span>' +
// ' <span ref="eSortDesc" class="ag-header-icon ag-sort-descending-icon" ></span>' +
// ' <span ref="eSortNone" class="ag-header-icon ag-sort-none-icon" ></span>' +
// ' ** <span ref="eText" class="ag-header-cell-text" role="columnheader"></span>' +
// ' <span ref="eFilter" class="ag-header-icon ag-filter-icon"></span>' +
// ' </div>' +
// '</div>'
// } }
this.columnDefs = [
{ headerName: 'Id', field: 'id', hide: true },
{ headerName: 'F.Code', field: 'feature.code', filter: 'text', width: 110},
{ headerName: 'Feature Title', field: 'feature.title', filter: 'text', width: 200 },
{ headerName: 'Estimated', field: 'feature.estimatedHours', type: "numericColumn", filter: 'number', valueFormatter: this.frm.ag_numberTwoDecimalFormatter ,width: 130 },
{ headerName: 'Spending', field: 'spending', type: "numericColumn", filter: 'number', valueFormatter: this.frm.ag_numberTwoDecimalFormatter, width: 120 },
{ headerName: 'Asigned', field: 'user.name', filter: 'text' , width: 150 }
];
for (let index = 0; index < loginService.currentSpring.springDays; index++) {
// this.columnDefs.push( { headerName : this.dateHeader(index+1), children: [{ headerName: index+1, valueGetter: (params: any) => params.data.spendingsInt[index], valueSetter: (params: any) => this.valueSetter(params,index), editable: true, suppressSorting: true, suppressMenu : true, type: "numericColumn", width: 55 }] })
// this.columnDefs.push({ headerName: index+1, valueGetter: (params: any) => params.data.spendingsInt[index], valueSetter: (params: any) => this.valueSetter(params,index), editable: true, suppressSorting: true, suppressMenu : true, type: "numericColumn", width: 55 })
this.columnDefs.push({ headerName: this.dateHeader(index+1), valueGetter: (params: any) => params.data.spendingsInt[index], valueSetter: (params: any) => this.valueSetter(params,index), editable: true, suppressSorting: true, suppressMenu : true, type: "text", valueFormatter: this.frm.ag_numberTwoDecimalFormatter, width: 75, headerComponentParams : {template: this.getHeaderTemplate()} })
}
}
valueSetter(params: any, index: number) {
let ret = false;
this.errorMessage = "";
params.newValue = params.newValue.length == 0 ? params.newValue : params.newValue.replace(",",".");
if (params.newValue.length == 0) {
params.data.spendingsInt[index] = null;
ret = true;
} else if (!isNaN(+params.newValue)) {
params.data.spendingsInt[index] = Math.round(+params.newValue * 100) / 100;
ret = true;
}
params.data.calculateSumSpending();
if (params.data.feature.estimatedHours < params.data.spending) {
this.errorMessage = "It has been consummed all the feature estimaded time, you must extend it"
params.data.spendingsInt[index] = null;
params.data.calculateSumSpending();
params.data.spendingsInt[index] = params.data.feature.estimatedHours - params.data.spending;
params.data.calculateSumSpending();
}
return ret;
}
ngOnInit(): void {
this.populateAsignments();
}
refeshAsignments(): void {
this.populateAsignments();
this.initialMode();
}
private populateAsignments() {
// asignmentList => this.rowData = asignmentList.map(asign => new Asignment(asign).addSpendings(this.loginService.currentSpring.springDays)),
this.asignments.subscribe(
asignmentList => this.rowData = asignmentList.map(asign => new Asignment(asign)),
error => this.handleError(error)
);
}
dateFormatter(params: any) {
return new Date(params.value).toLocaleDateString("es-ES",{timeZone: 'UTC', year:"numeric",month:"2-digit", day:"2-digit"});
}
getHeaderTemplat2() : string {
return '<div class="ag-cell-label-container" role="presentation">' +
' <span ref="eMenu" class="ag-header-icon ag-header-cell-menu-button"></span>' +
' <div ref="eLabel" class="ag-header-cell-label" role="presentation">' +
' <span ref="eSortOrder" class="ag-header-icon ag-sort-order" ></span>' +
' <span ref="eSortAsc" class="ag-header-icon ag-sort-ascending-icon" ></span>' +
' <span ref="eSortDesc" class="ag-header-icon ag-sort-descending-icon" ></span>' +
' <span ref="eSortNone" class="ag-header-icon ag-sort-none-icon" ></span>' +
' ** <span ref="eText" class="ag-header-cell-text" role="columnheader"></span>' +
' <span ref="eFilter" class="ag-header-icon ag-filter-icon"></span>' +
' </div>' +
'</div>';
}
getHeaderTemplate() : string {
return '<div class="ag-cell-label-container ag-header-center" role="presentation">' +
' <span ref="eText" class="ag-header-cell-text" role="columnheader"></span>' +
'</div>';
}
dateHeader(numDay: number) {
let dtM = new DateModel(this.loginService.currentSpring.startDate.toString());
dtM.setAddWorkableDays(dtM,numDay);
return numDay + "</br>" + this.getDayAndMounthFromDate(dtM.getDate()) + "</br>" + this.getWeekdayFromDate(dtM.getDate());
}
getDayAndMounthFromDate(d: Date): string {
let format = d.toLocaleDateString(undefined,{timeZone: 'UTC', year:"numeric" ,month:"2-digit", day:"2-digit"});
// Check locale format and strip year
if(format.match(/.[0-9]{4}/g) ){
format = format.replace(/.[0-9]{4}/, '');
} else if( format.match(/[0-9]{4}./g) ){
format = format.replace(/[0-9]{4}./, '');
} else if( format.match(new RegExp('/[0-9]{4}') ) ) {
format = format.replace(new RegExp('/[0-9]{4}'), '');
} else if( format.match(new RegExp('[0-9]{4}/') ) ) {
format = format.replace(new RegExp('[0-9]{4}/'), '');
}
return format;
}
getWeekdayFromDate(d: Date): string {
let format = d.toLocaleDateString(undefined,{timeZone: 'UTC', weekday: "short"});
format = format.replace('.','');
return format;
}
get asignments(): Observable<Asignment[]> {
return this.spendingsService.getSpendings();
}
editAsignment(data: Asignment) {
this.errorMessage = "";
}
handleError(res: HttpErrorResponse) {
this.errorMessage = res.error.error_message;
console.log(res);
}
saveSpendings() {
this.spendingsService.saveSpendings(this.rowData).subscribe(
data => this.refeshAsignments(),
error => this.handleError(error)
);
}
resetControls() {
this.myForm.resetForm();
Object.keys(this.myForm.controls).forEach(field => {
const control = this.myForm.control.get(field);
control.markAsUntouched();
});
}
cancelEditMode() {
this.initialMode();
}
private initialMode() {
this.errorMessage = "";
this.isEditMode = false;
this.resetControls();
}
onGridReady(params: any) {
this.gridApi = params.api;
this.gridColumnApi = params.columnApi;
this.gridColumnApi.autoSizeColumns();
}
onCellEditingStarted(params: any) {
// console.log("cellEditingStarted");
// console.log(params);
// console.log(params.value);
// console.log(params.column);
// console.log(params.data.capacity);
// console.log(params.node);
// params.node.setDataValue(params.column.colId, params.data.capacity);
}
compareFeatures(o1:Feature,o2:Feature) : boolean {
return (o1 && o2) ? o1.id === o2.id : o1 === o2;
}
compareUsers(o1:User,o2:User) : boolean {
return (o1 && o2) ? o1.username === o2.username : o1 === o2;
}
}
<file_sep>import { Injectable } from '@angular/core';
import { Project } from './project';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ProjectsService {
private baseUrl = './api/projects';
constructor(private http: HttpClient) {
}
getProjects() : Observable<Project[]>{
return this.http.get(this.baseUrl) as Observable<Project[]>;
}
getProjectById(id : number): Observable<Project> {
return this.http.get(`${this.baseUrl}/${id}`) as Observable<Project>;
}
addProject(project: Project): Observable<Project> {
return this.http.post(this.baseUrl, project) as Observable<Project>;
}
deleteProjectById(id: number) : Observable<Project> {
return this.http.delete(`${this.baseUrl}/${id}`) as Observable<Project>;
}
updateProject(project : Project): Observable<Project> {
return this.http.put(`${this.baseUrl}/${project.id}`, project) as Observable<Project>;
}
}
<file_sep>import { Component, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { Subscription, Observable } from 'rxjs';
import { NgForm } from '@angular/forms';
import { GridApi, GridOptions } from 'ag-grid';
import { MatEditButtonGridRenderComponent } from '../grid-custom-components/mat-edit-button-grid-render/mat-edit-button-grid-render.component';
import { MatRemoveButtonGridRenderComponent } from '../grid-custom-components/mat-remove-button-grid-render/mat-remove-button-grid-render.component';
import { LoginService } from '../login/login.service';
import { HttpErrorResponse } from '@angular/common/http';
import { User } from '../users/user';
import { UserService } from '../users/users.service';
import { Capacity } from './capacity';
import { CapacityService } from './capacity.service';
import { AgFormatterService } from '../shared/ag-formatter.service';
@Component({
selector: 'app-capacity',
templateUrl: './capacity.component.html',
styleUrls: ['./capacity.component.scss']
})
export class CapacityComponent implements OnInit {
public capacity = new Capacity();
public context: any;
@ViewChild('myForm', { static: false }) myForm: NgForm;
private gridApi: GridApi;
private gridColumnApi;
private columnDefs: any;
private rowData: Capacity[];
private users : User[];
private gridOptions: GridOptions;
private errorMessage : string = "";
private isEditMode: boolean = false;
constructor(private capacitysService: CapacityService, private userService :UserService, private loginService: LoginService, private frm: AgFormatterService) {
this.context = { componentParent: this };
this.gridOptions = <GridOptions>{};
this.gridOptions.enableFilter = true;
this.gridOptions.enableSorting = true;
this.gridOptions.rowSelection = 'single';
this.gridOptions.suppressRowClickSelection = false;
this.gridOptions.enableColResize = true;
this.gridOptions.enableCellChangeFlash = true;
this.columnDefs = [
{ headerName: 'Id', field: 'id', hide: true },
{ headerName: 'User', field: 'user.name', filter: 'text' , width: 150 },
{ headerName: 'Available Hs', field: 'availableHours', type: "numericColumn", filter: 'number', valueFormatter: this.frm.ag_numberTwoDecimalFormatter, width: 140 },
{ headerName: 'Total Hs', field: 'availableOnSpring', type: "numericColumn", filter: 'number', valueFormatter: this.frm.ag_numberTwoDecimalFormatter, width: 130 },
{ headerName: 'Remaining Hs', field: 'remainingOnSpring', type: "numericColumn", filter: 'number', valueFormatter: this.frm.ag_numberTwoDecimalFormatter, width: 150 },
{ headerName: '', cellRendererFramework: MatEditButtonGridRenderComponent, width: 75 },
{ headerName: '', suppressFilter: true, cellRendererFramework: MatRemoveButtonGridRenderComponent, width: 75 }
];
}
ngOnInit(): void {
this.populateCapacitys();
this.userService.getUsers().toPromise().then(users => this.users = users);
}
refeshCapacitys(): void {
this.populateCapacitys();
this.initialMode();
}
private populateCapacitys() {
this.capacities.subscribe(
capacityList => this.rowData = capacityList,
error => this.handleError(error)
);
}
dateFormatter(params: any) {
return new Date(params.value).toLocaleDateString("es-ES",{timeZone: 'UTC', year:"numeric",month:"2-digit", day:"2-digit"});
}
get capacities(): Observable<Capacity[]> {
return this.capacitysService.getCapacities();
}
getCapacityById(id: number): Observable<Capacity> {
return this.capacitysService.getCapacityById(id);
}
removeCapacity(id: number) {
this.capacitysService.deleteCapacityById(id).subscribe(
data => this.refeshCapacitys(),
error => console.log(error)
);
}
editCapacity(data: Capacity) {
this.capacity = new Capacity(data);
this.errorMessage = "";
}
addCapacity(): void {
// this.project.status = "OPEN";
this.capacitysService.addCapacity(this.capacity).subscribe(
data => this.refeshCapacitys(),
error => this.handleError(error)
);
}
handleError(res: HttpErrorResponse) {
this.errorMessage = res.error.error_message;
console.log(res);
}
updateCapacity(){
this.capacitysService.updateCapacity(this.capacity).subscribe(
data => this.refeshCapacitys(),
error => this.handleError(error)
);
}
resetControls() {
this.myForm.resetForm();
Object.keys(this.myForm.controls).forEach(field => {
const control = this.myForm.control.get(field);
control.markAsUntouched();
});
}
// Call from MatRemoveButtonGridRenderComponent
removeFromComponent(capacity: Capacity){
this.removeCapacity(capacity.id);
this.initialMode();
}
// Call from MatEditButtonGridRenderComponent
editFromComponent(data: Capacity){
this.isEditMode = true;
this.editCapacity(data);
}
cancelEditMode() {
this.initialMode();
}
private initialMode() {
this.capacity = new Capacity();
this.errorMessage = "";
this.isEditMode = false;
this.resetControls();
}
onGridReady(params: any) {
this.gridApi = params.api;
this.gridColumnApi = params.columnApi;
this.gridColumnApi.autoSizeColumns();
}
compareUsers(o1:User,o2:User) : boolean {
return (o1 && o2) ? o1.username === o2.username : o1 === o2;
}
getMatTooltipButton() : string {
if (this.capacity.user) {
return this.capacity.user.username;
}
return "";
}
}
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { SharedModule } from './shared/shared.module';
import { ProjectsModule } from './projects/projects.module';
import { LoginComponent } from './login/login.component';
import { LoginService } from './login/login.service';
import { MatIconModule, MatMenuModule, MatToolbarModule, MatCardModule } from '@angular/material';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { UsersModule } from './users/users.module';
import { SpringsModule } from './springs/springs.module';
import { FeaturesModule } from './backlog/features.module';
import { AsignmentModule } from './asignment/asignment.module';
import { CapacityModule } from './capacity/capacity.module';
import { SpendingModule } from './spending/spending.module';
import { HolidaysModule } from './holidays/holidays.module';
import { OutlookModule } from './outlook/outlook.module';
@NgModule({
declarations: [
AppComponent,
LoginComponent
],
imports: [
SharedModule,
ProjectsModule,
UsersModule,
SpringsModule,
FeaturesModule,
CapacityModule,
AsignmentModule,
SpendingModule,
HolidaysModule,
OutlookModule,
BrowserModule,
AppRoutingModule,
FormsModule,
MatIconModule,
MatMenuModule,
MatToolbarModule,
MatCardModule,
BrowserAnimationsModule,
HttpClientModule
],
providers: [
LoginService
],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>import { Component, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { Subscription, Observable } from 'rxjs';
import { NgForm } from '@angular/forms';
import { GridApi, GridOptions } from 'ag-grid';
import { MatEditButtonGridRenderComponent } from '../grid-custom-components/mat-edit-button-grid-render/mat-edit-button-grid-render.component';
import { MatRemoveButtonGridRenderComponent } from '../grid-custom-components/mat-remove-button-grid-render/mat-remove-button-grid-render.component';
import { LoginService } from '../login/login.service';
import { HttpErrorResponse } from '@angular/common/http';
import { User } from '../users/user';
import { Feature } from '../backlog/feature';
import { FeaturesService } from '../backlog/features.service';
import { UserService } from '../users/users.service';
import { Asignment } from './asignment';
import { AsignmentService } from './asignment.service';
import { AgFormatterService } from '../shared/ag-formatter.service';
@Component({
selector: 'app-asignment',
templateUrl: './asignment.component.html',
styleUrls: ['./asignment.component.scss']
})
export class AsignmentComponent implements OnInit {
public asignment = new Asignment();
public context: any;
@ViewChild('myForm', { static: false }) myForm: NgForm;
private gridApi: GridApi;
private gridColumnApi;
private columnDefs: any;
private rowData: Asignment[];
private features : Feature[];
private users : User[];
private gridOptions: GridOptions;
private errorMessage : string = "";
private isEditMode: boolean = false;
constructor(private asignmentsService: AsignmentService, private featuresService :FeaturesService, private userService :UserService, private loginService: LoginService, private frm: AgFormatterService) {
this.context = { componentParent: this };
this.gridOptions = <GridOptions>{};
this.gridOptions.enableFilter = true;
this.gridOptions.enableSorting = true;
this.gridOptions.rowSelection = 'single';
this.gridOptions.suppressRowClickSelection = false;
this.gridOptions.enableColResize = true;
this.gridOptions.enableCellChangeFlash = true;
this.gridOptions.headerHeight = 56;
this.columnDefs = [
{ headerName: 'Id', field: 'id', hide: true },
{ headerName: 'F.Code', field: 'feature.code', filter: 'text', width: 110},
{ headerName: 'Feature Title', field: 'feature.title', filter: 'text', width: 400 },
{ headerName: 'Estimated Hs.', field: 'feature.estimatedHours', type: "numericColumn", filter: 'number', valueFormatter: this.frm.ag_numberTwoDecimalFormatter, width: 160 },
{ headerName: 'Asigned', field: 'user.name', filter: 'text' , width: 150 },
{ headerName: 'Asign Remaining Hs.', field: 'remaining', colId: 'remaining2x', type: "numericColumn", filter: 'number', valueFormatter: this.frm.ag_numberTwoDecimalFormatter, width: 150 },
{ headerName: '', cellRendererFramework: MatEditButtonGridRenderComponent, width: 75 },
{ headerName: '', suppressFilter: true, cellRendererFramework: MatRemoveButtonGridRenderComponent, width: 75 }
];
}
ngOnInit(): void {
this.populateAsignments();
this.featuresService.getFeaturesToAsign().toPromise().then( feats => this.features = feats);
this.userService.getUsers().toPromise().then(users => this.users = users);
}
refeshAsignments(): void {
this.featuresService.getFeaturesToAsign().toPromise().then( feats => this.features = feats);
this.populateAsignments();
this.initialMode();
}
private populateAsignments() {
this.asignments.subscribe(
asignmentList => this.rowData = asignmentList,
error => this.handleError(error)
);
}
dateFormatter(params: any) {
return new Date(params.value).toLocaleDateString("es-ES",{timeZone: 'UTC', year:"numeric",month:"2-digit", day:"2-digit"});
}
get asignments(): Observable<Asignment[]> {
return this.asignmentsService.getAsignments();
}
getAsignmentById(id: number): Observable<Asignment> {
return this.asignmentsService.getAsignmentById(id);
}
removeAsignment(id: number) {
this.asignmentsService.deleteAsignmentById(id).subscribe(
data => this.refeshAsignments(),
error => console.log(error)
);
}
editAsignment(data: Asignment) {
this.asignment = new Asignment(data);
this.features.push(this.asignment.feature);
this.errorMessage = "";
}
addAsignment(): void {
// this.project.status = "OPEN";
this.asignmentsService.addAsignment(this.asignment).subscribe(
data => this.refeshAsignments(),
error => this.handleError(error)
);
}
handleError(res: HttpErrorResponse) {
this.errorMessage = res.error.error_message;
console.log(res);
}
updateAsignment(){
this.asignmentsService.updateAsignment(this.asignment).subscribe(
data => this.refeshAsignments(),
error => this.handleError(error)
);
}
resetControls() {
this.myForm.resetForm();
Object.keys(this.myForm.controls).forEach(field => {
const control = this.myForm.control.get(field);
control.markAsUntouched();
});
}
// Call from MatRemoveButtonGridRenderComponent
removeFromComponent(asignment: Asignment){
this.removeAsignment(asignment.id);
this.initialMode();
}
// Call from MatEditButtonGridRenderComponent
editFromComponent(data: Asignment){
this.isEditMode = true;
this.editAsignment(data);
}
cancelEditMode() {
this.features = this.features.filter(item => item !== this.asignment.feature);
this.initialMode();
}
private initialMode() {
this.asignment = new Asignment();
this.errorMessage = "";
this.isEditMode = false;
this.resetControls();
}
onGridReady(params: any) {
this.gridApi = params.api;
this.gridColumnApi = params.columnApi;
this.gridColumnApi.autoSizeColumns();
}
compareFeatures(o1:Feature,o2:Feature) : boolean {
return (o1 && o2) ? o1.id === o2.id : o1 === o2;
}
compareUsers(o1:User,o2:User) : boolean {
return (o1 && o2) ? o1.username === o2.username : o1 === o2;
}
getMatTooltipButton() : string {
if (this.asignment.feature) {
return this.asignment.feature.title;
}
return "";
}
}
<file_sep>export class Feature {
id : number;
code : string;
title : string = '';
status : string = '';
estimatedHours : number = 0;
committedDate: Date = null;
constructor(values: Object = {}) {
Object.assign(this, values);
}
}
<file_sep>export class DateModel {
private _value : Date;
constructor(val: string) {
this._value =val && val.length > 0? new Date(val) : new Date();
}
get value() : string {
return this.toString();
}
set value(val : string) {
this._value =val && val.length > 0? new Date(val) : new Date();
}
public setDate(value : Date) {
this._value = value;
}
public addDays(days :number) {
this._value.setDate(this._value.getDate() + days);
}
public setAddDays(dateM : DateModel, days: number) {
this._value = new Date(dateM._value);
this.addDays(days);
}
public setAddWorkableDays(dateM : DateModel, days: number) {
this._value = new Date(dateM._value);
let wdays = this._value.getDay() + days - 1;
let workableDays = days - 1 + Math.trunc(wdays/5)*2;
this.addDays(workableDays);
}
public greaterThan(otherValue : string | Date | DateModel ) : boolean {
return this._value > this.toDate(otherValue);
}
public greaterOrEqualsThan(otherValue : string | Date | DateModel ) : boolean {
return this._value >= this.toDate(otherValue);
}
public lessThan(otherValue : string | Date | DateModel ) : boolean {
return this._value < this.toDate(otherValue);
}
public equalsThan(otherValue : string | Date | DateModel ) : boolean {
return this._value == this.toDate(otherValue);
}
public getDate() : Date {
return this._value;
}
public toDate(value : string | Date | DateModel) : Date {
let valueToDate:Date = null;
if (typeof value === 'string') {
valueToDate = new Date(value);
} else if (value instanceof Date) {
valueToDate = <Date>value;
} else {
valueToDate = (<DateModel>value)._value;
}
return valueToDate;
}
public toString() {
return this._value.toISOString().split('T')[0];
}
}
export enum Day_of_week {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
<file_sep>import { Injectable, OnDestroy, OnInit } from '@angular/core';
import { User } from './user';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class UserService {
private baseUrl = './api/users';
constructor(public http: HttpClient) {
}
getUsers() : Observable<User[]>{
return this.http.get(this.baseUrl) as Observable<User[]>;
}
getUserByUsername(username : string): Observable<User> {
return this.http.get(`${this.baseUrl}/${username}`) as Observable<User>;
}
addUser(user: User): Observable<User> {
return this.http.post(this.baseUrl, user) as Observable<User>;
}
deleteUserByUsername(username: string) : Observable<User> {
return this.http.delete(`${this.baseUrl}/${username}`) as Observable<User>;
}
updateUser(user : User): Observable<User> {
return this.http.put(`${this.baseUrl}/${user.username}`, user) as Observable<User>;
}
}
<file_sep>import { NgModule } from '@angular/core';
import { AgGridModule } from 'ag-grid-angular';
import { SharedModule } from '../shared/shared.module';
import { environment } from '../../environments/environment';
import { CapacityComponent } from './capacity.component';
@NgModule({
imports: [
SharedModule,
AgGridModule.withComponents([])
],
declarations: [CapacityComponent]
})
export class CapacityModule { }
<file_sep>import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Project } from '../projects/project';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { LoginUser } from './loginUser';
import { Spring } from '../springs/spirng';
import { User } from '../users/user';
@Injectable()
export class LoginService {
private userState: User = null;
private projectState: Project = null;
private springState: Spring = null;
//public loginUserObs: Observable<LoginUser[]>;
private baseUrl = './api/login';
constructor(public http: HttpClient) {
}
get isUserAnonymousLoggedIn(): boolean {
return false;
}
get currentUserName(): string {
return this.userState !== null ? this.userState.username : 'Usuario Anónimo';
}
get currentName(): string {
return this.userState !== null ? this.userState.name : '<NAME>';
}
get currentUser(): User {
return (this.userState !== null) ? this.userState : null;
}
set currentUser(user: User) {
this.userState = user;
}
get currentProject() : Project {
return (this.projectState !== null) ? this.projectState : null;
}
set currentProject( project : Project) {
this.projectState = project;
}
get currentProjectId() : number {
return (this.projectState !== null) ? this.projectState.id : NaN;
}
get currentProjectName() : string {
return (this.projectState !== null) ? this.projectState.code + ' - ' + this.projectState.name : 'Select a project';
}
get currentSpring() : Spring {
return (this.springState !== null) ? this.springState : null;
}
set currentSpring( spring : Spring) {
this.springState = spring;
}
get currentSpringId() : number {
return (this.springState !== null) ? this.springState.id : NaN;
}
get currentSpringName() : string {
return '& ' + ((this.springState !== null) ? this.springState.code + ' - ' + this.springState.name : 'Select a spring');
}
public get isUserLoggedIn(): boolean {
// if ((this.userState !== null) && (!this.isUserAnonymousLoggedIn)) {
return (this.userState != null)
}
// public createUserWithEmail(email: string, password: string) :Promise<any> {
// return this.afAuth.auth.createUserWithEmailAndPassword(email, password);
// }
public loginWithUsername(username: string, password: string) {
return this.http.put(`${this.baseUrl}/${username}`, password) as Observable<User>;
}
public signOut(): void {
this.userState = null;
// this.http.get(`${this.baseUrl}/login/singout/${this.userState.username}`);
}
}
<file_sep>import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { Feature } from './feature';
import { LoginService } from '../login/login.service';
@Injectable({
providedIn: 'root'
})
export class FeaturesService {
private currentProjectId = "";
private _baseUrl = './api/projects/';
constructor(private http: HttpClient, private loginService: LoginService) {
}
getFeatures() : Observable<Feature[]>{
return this.http.get(this.baseUrl) as Observable<Feature[]>;
}
getFeatureById(id : number): Observable<Feature> {
return this.http.get(`${this.baseUrl}/${id}`) as Observable<Feature>;
}
getFeaturesToAsign() : Observable<Feature[]>{
return this.http.get(this.baseUrl+"/toAsign") as Observable<Feature[]>;
}
addFeature(feature: Feature): Observable<Feature> {
return this.http.post(this.baseUrl, feature) as Observable<Feature>;
}
deleteFeatureById(id: number) : Observable<Feature> {
return this.http.delete(`${this.baseUrl}/${id}`) as Observable<Feature>;
}
updateFeature(feature : Feature): Observable<Feature> {
return this.http.put(`${this.baseUrl}/${feature.id}`, feature) as Observable<Feature>;
}
private get baseUrl(): string {
return this._baseUrl + this.loginService.currentProjectId + '/features';
}
}
<file_sep>import { NgModule } from '@angular/core';
import { AgGridModule } from 'ag-grid-angular';
import { SharedModule } from '../shared/shared.module';
import { ProjectsComponent } from './projects.component';
import { environment } from '../../environments/environment';
import { DatePipe } from '@angular/common';
@NgModule({
imports: [
SharedModule,
AgGridModule.withComponents([])
],
declarations: [ProjectsComponent]
})
export class ProjectsModule { }
<file_sep>import { Component, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { Project } from './project';
import { Subscription, Observable } from 'rxjs';
import { NgForm } from '@angular/forms';
import { GridApi, GridOptions } from 'ag-grid';
import { ProjectsService } from './projects.service';
import { Router } from '@angular/router';
import { MatEditButtonGridRenderComponent } from '../grid-custom-components/mat-edit-button-grid-render/mat-edit-button-grid-render.component';
import { MatRemoveButtonGridRenderComponent } from '../grid-custom-components/mat-remove-button-grid-render/mat-remove-button-grid-render.component';
import { LoginService } from '../login/login.service';
import { HttpErrorResponse } from '@angular/common/http';
import { AgFormatterService } from '../shared/ag-formatter.service';
@Component({
selector: 'app-projects',
templateUrl: './projects.component.html',
styleUrls: ['./projects.component.scss']
})
export class ProjectsComponent implements OnInit {
public project = new Project();
// public projectSelected = new Project();
public context: any;
@ViewChild('myForm', { static: false }) myForm: NgForm;
private gridApi: GridApi;
private gridColumnApi;
private columnDefs: any;
private rowData: Project[];
private gridOptions: GridOptions;
private errorMessage : string = "";
private isEditMode: boolean = false;
constructor(private projectsService: ProjectsService, private loginService: LoginService, private router: Router, private frm: AgFormatterService) {
this.context = { componentParent: this };
this.gridOptions = <GridOptions>{};
this.gridOptions.enableFilter = true;
this.gridOptions.enableSorting = true;
this.gridOptions.rowSelection = 'single';
this.columnDefs = [
{ headerName: 'Id', field: 'id', hide: true },
{ headerName: 'Code', field: 'code', filter: 'text', width: 120 },
{ headerName: 'Name', field: 'name', filter: 'text', width: 250 },
{ headerName: 'Start Date', field: 'startDate', filter: 'date', width: 140, valueFormatter: this.frm.ag_dateFormatter },
{ headerName: 'Spring Days', field: 'springDays', type: "numericColumn", filter: 'number',width: 150 },
{ headerName: 'Status', field: 'status', filter: 'text', width: 120 },
{ headerName: '', cellRendererFramework: MatEditButtonGridRenderComponent, width: 40 },
{ headerName: '', suppressFilter: true, cellRendererFramework: MatRemoveButtonGridRenderComponent, width: 40 }
];
}
ngOnInit(): void {
this.populateProjects();
}
refeshProjects(): void {
this.populateProjects();
this.initialMode();
}
private populateProjects() {
this.projects.subscribe(
projectList => this.rowData = projectList,
error => this.handleError(error)
);
}
get projects(): Observable<Project[]> {
return this.projectsService.getProjects();
}
getProjectById(id: number): Observable<Project> {
return this.projectsService.getProjectById(id);
}
removeProject(id: number) {
this.projectsService.deleteProjectById(id).subscribe(
data => this.refeshProjects(),
error => console.log(error)
);
}
editProject(data: Project) {
this.project = new Project(data);
this.errorMessage = "";
}
addProject(): void {
// this.project.status = "OPEN";
this.projectsService.addProject(this.project).subscribe(
data => this.refeshProjects(),
error => this.handleError(error)
);
}
handleError(res: HttpErrorResponse) {
this.errorMessage = res.error.error_message;
console.log(res);
}
updateProject(){
this.projectsService.updateProject(this.project).subscribe(
data => this.refeshProjects(),
error => this.handleError(error)
);
}
resetControls() {
this.myForm.resetForm();
Object.keys(this.myForm.controls).forEach(field => {
const control = this.myForm.control.get(field);
control.markAsUntouched();
});
}
// Call from MatRemoveButtonGridRenderComponent
removeFromComponent(project: Project){
this.removeProject(project.id);
this.initialMode();
}
// Call from MatEditButtonGridRenderComponent
editFromComponent(data: Project){
this.isEditMode = true;
this.editProject(data);
}
cancelEditMode() {
this.initialMode();
}
private initialMode() {
this.project = new Project();
this.errorMessage = "";
this.isEditMode = false;
this.resetControls();
}
onGridReady(params: any) {
this.gridApi = params.api;
this.gridColumnApi = params.columnApi;
this.gridColumnApi.autoSizeColumns();
}
onSelectionChanged() {
var selectedRows = this.gridApi.getSelectedRows();
var selectedRowAux: any;
selectedRows.forEach(function(row, index) {
// if (index !== 0) {
// selectedRowsString += ", ";
// }
selectedRowAux = row;
});
this.loginService.currentProject = selectedRowAux;
if (this.loginService.currentSpring===null) {
this.router.navigate(['/springs']);
}
// this.projectSelected = selectedRowAux;
// document.querySelector("#selectedRows").innerHTML = selectedRowsString;
}
}
<file_sep>import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Holiday } from './holiday';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class HolidaysService {
private baseUrl = './api/holidays';
constructor(public http: HttpClient) {
}
getHolidays() : Observable<Holiday[]>{
return this.http.get(this.baseUrl) as Observable<Holiday[]>;
}
getHolidayByDate(date : Date): Observable<Holiday> {
return this.http.get(`${this.baseUrl}/${date}`) as Observable<Holiday>;
}
addHoliday(holiday: Holiday): Observable<Holiday> {
return this.http.post(this.baseUrl, holiday) as Observable<Holiday>;
}
addHolidaysForYears(holiday: Holiday,years: number): Observable<Holiday> {
return this.http.post(`${this.baseUrl}/${years}`, holiday) as Observable<Holiday>;
}
deleteHolidayByDate(date: Date) : Observable<Holiday> {
return this.http.delete(`${this.baseUrl}/${date}`) as Observable<Holiday>;
}
updateHoliday(holiday : Holiday): Observable<Holiday> {
return this.http.put(`${this.baseUrl}/${holiday.date}`, holiday) as Observable<Holiday>;
}
}
<file_sep>import { Component, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { GridApi, GridOptions, RowNode } from 'ag-grid';
import { User } from './user';
import { UserService } from './users.service';
import { MatRemoveButtonGridRenderComponent } from '../grid-custom-components/mat-remove-button-grid-render/mat-remove-button-grid-render.component';
import { MatEditButtonGridRenderComponent } from '../grid-custom-components/mat-edit-button-grid-render/mat-edit-button-grid-render.component';
import { NgForm, FormGroup } from '@angular/forms';
import { LoginService } from '../login/login.service';
import { Observable } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
@Component({
selector: 'app-user',
templateUrl: './users.component.html',
styleUrls: ['./users.component.scss']
})
export class UsersComponent implements OnInit {
public user = new User();
public context;
@ViewChild('myForm',{static: false}) myForm : NgForm;
private gridApi: GridApi;
private gridColumnApi;
private columnDefs: any;
private rowData: User[];
private gridOptions: GridOptions;
private errorMessage : string = "";
private isEditMode: boolean = false;
constructor(private userService: UserService, private loginService: LoginService) {
this.context = { componentParent: this };
this.gridOptions = <GridOptions>{};
this.gridOptions.enableFilter = true;
this.gridOptions.enableSorting = true;
this.gridOptions.rowSelection = 'simple';
this.gridOptions.suppressRowClickSelection = false;
this.gridOptions.enableColResize = true;
this.columnDefs = [
{ headerName: 'User', field: 'username', filter: 'text' },
{ headerName: 'Name', field: 'name', filter: 'text' },
{ headerName: 'Email', field: 'email', filter: 'text' },
{ headerName: 'Phone', field: 'phone', filter: 'text' },
{ headerName: 'Mobile', field: 'mobile', filter: 'text' },
{ headerName: '', cellRendererFramework: MatEditButtonGridRenderComponent, width: 40 },
{ headerName: '', suppressFilter: true, cellRendererFramework: MatRemoveButtonGridRenderComponent, width: 40 }
];
}
ngOnInit(): void {
this.populateUsers();
}
refeshUsers(): void {
this.populateUsers();
this.initialMode();
this.resetControls();
}
private populateUsers() {
this.userService.getUsers().subscribe(
userList => this.rowData = userList,
error => this.handleError(error)
);
}
dateFormatter(params: any) {
return new Date(params.value).toLocaleDateString("es-ES",{timeZone: 'UTC', year:"numeric",month:"2-digit", day:"2-digit"});
}
get users(): Observable<User[]> {
return this.userService.getUsers();
}
getUserByUsername(username: string): Observable<User> {
return this.userService.getUserByUsername(username);
}
removeUser(username: string) {
this.userService.deleteUserByUsername(username).subscribe(
data => this.refeshUsers(),
error => console.log(error)
);
}
editUser(data: User) {
this.user = new User(data);
this.errorMessage = "";
}
addUser(): void {
// this.project.status = "OPEN";
this.userService.addUser(this.user).subscribe(
data => this.refeshUsers(),
error => this.handleError(error)
);
}
handleError(res: HttpErrorResponse) {
this.errorMessage = res.error.error_message;
console.log(res);
}
updateUser(){
this.userService.updateUser(this.user).subscribe(
data => this.refeshUsers(),
error => this.handleError(error)
);
}
resetControls() {
this.myForm.resetForm();
Object.keys(this.myForm.controls).forEach(field => {
const control = this.myForm.control.get(field);
control.markAsUntouched();
});
}
// Call from MatRemoveButtonGridRenderComponent
removeFromComponent(user: User){
this.removeUser(user.username);
this.initialMode();
}
// Call from MatEditButtonGridRenderComponent
editFromComponent(data: User){
this.isEditMode = true;
this.editUser(data);
}
cancelEditMode() {
this.initialMode();
}
private initialMode() {
this.user = new User();
this.errorMessage = "";
this.isEditMode = false;
this.resetControls();
}
onGridReady(params: any) {
this.gridApi = params.api;
this.gridColumnApi = params.columnApi;
this.gridColumnApi.autoSizeColumns();
}
}
<file_sep>import { Injectable } from '@angular/core';
import { LoginService } from '../login/login.service';
import { Spring } from './spirng';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SpringsService {
private currentProjectId = "";
private _baseUrl = './api/projects/';
constructor(private http: HttpClient, private loginService: LoginService) {
}
public getSprings(): Observable<Spring[]> {
return this.http.get(this.baseUrl) as Observable<Spring[]>;
;
}
public getSpringById(id: number): Observable<Spring> {
return this.http.get(`${this.baseUrl}/${id}`) as Observable<Spring>;
}
public addSpring(spring: Spring): Observable<Spring> {
return this.http.post(this.baseUrl, spring) as Observable<Spring>;
;
}
public deleteSpringById(id: number): Observable<Spring> {
return this.http.delete(`${this.baseUrl}/${id}`) as Observable<Spring>;
}
public updateSpring(spring: Spring): Observable<Spring> {
return this.http.put(`${this.baseUrl}/${spring.id}`, spring) as Observable<Spring>;
}
public setSpringDefaultValues(spring: Spring = new Spring()): Spring {
spring.springDays = this.loginService.currentProject.springDays;
spring.startDateMd.value = this.loginService.currentProject.startDate.toString();
spring.setEndDateMdCalculed();
return spring;
}
public changeSpringDefaultValues(spring: Spring, rowData: Spring[]): Spring {
spring = this.setSpringDefaultValues(spring);
if (rowData) {
rowData.forEach(s => {
if (spring.startDateMd.lessThan(s.endDateMd)) {
spring.startDateMd.setAddWorkableDays(s.endDateMd, 2);
spring.setEndDateMdCalculed();
}
});
}
return spring;
}
private get baseUrl(): string {
return this._baseUrl + this.loginService.currentProjectId + '/springs';
}
}
<file_sep>import { Component, OnInit, ViewChild } from '@angular/core';
import { Holiday } from './holiday';
import { NgForm } from '@angular/forms';
import { GridApi, GridOptions } from 'ag-grid';
import { HolidaysService } from './holidays.service';
import { MatEditButtonGridRenderComponent } from '../grid-custom-components/mat-edit-button-grid-render/mat-edit-button-grid-render.component';
import { MatRemoveButtonGridRenderComponent } from '../grid-custom-components/mat-remove-button-grid-render/mat-remove-button-grid-render.component';
import { Observable } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { AgFormatterService } from '../shared/ag-formatter.service';
@Component({
selector: 'app-holidays',
templateUrl: './holidays.component.html',
styleUrls: ['./holidays.component.scss']
})
export class HolidaysComponent implements OnInit {
public holiday = new Holiday();
public years: number;
public context;
@ViewChild('myForm',{static: false}) myForm : NgForm;
private gridApi: GridApi;
private gridColumnApi;
private columnDefs: any;
private rowData: Holiday[];
private gridOptions: GridOptions;
private errorMessage : string = "";
private isEditMode: boolean = false;
constructor(private holidayService: HolidaysService, private frm: AgFormatterService) {
this.context = { componentParent: this };
this.gridOptions = <GridOptions>{};
this.gridOptions.enableFilter = true;
this.gridOptions.enableSorting = true;
this.gridOptions.rowSelection = 'simple';
this.gridOptions.suppressRowClickSelection = false;
this.gridOptions.enableColResize = true;
this.columnDefs = [
{ headerName: 'Date', field: 'date', filter: 'text', valueFormatter: this.frm.ag_dateFormatter , width: 170 },
{ headerName: 'Description', field: 'description', filter: 'text', width: 250 },
{ headerName: '', cellRendererFramework: MatEditButtonGridRenderComponent, width: 40 },
{ headerName: '', suppressFilter: true, cellRendererFramework: MatRemoveButtonGridRenderComponent, width: 40 }
];
}
ngOnInit(): void {
this.populateHolidays();
}
refeshHolidays(): void {
this.populateHolidays();
this.initialMode();
this.resetControls();
}
private populateHolidays() {
this.holidayService.getHolidays().subscribe(
userList => this.rowData = userList,
error => this.handleError(error)
);
}
dateFormatter(params: any) {
return new Date(params.value).toLocaleDateString("es-ES",{timeZone: 'UTC', year:"numeric",month:"2-digit", day:"2-digit"});
}
get holidays(): Observable<Holiday[]> {
return this.holidayService.getHolidays();
}
getHolidayByDate(date: Date): Observable<Holiday> {
return this.holidayService.getHolidayByDate(date);
}
removeHoliday(date: Date) {
this.holidayService.deleteHolidayByDate(date).subscribe(
data => this.refeshHolidays(),
error => console.log(error)
);
}
editHoliday(data: Holiday) {
this.holiday = new Holiday(data);
this.errorMessage = "";
this.years = NaN;
}
addHoliday(): void {
this.holidayService.addHoliday(this.holiday).subscribe(
data => this.refeshHolidays(),
error => this.handleError(error)
);
}
addHolidaysForYears(): void {
this.holidayService.addHolidaysForYears(this.holiday,this.years).subscribe(
data => this.refeshHolidays(),
error => this.handleError(error)
);
}
handleError(res: HttpErrorResponse) {
this.errorMessage = res.error.error_message;
console.log(res);
}
updateHoliday(){
this.holidayService.updateHoliday(this.holiday).subscribe(
data => this.refeshHolidays(),
error => this.handleError(error)
);
}
resetControls() {
this.myForm.resetForm();
Object.keys(this.myForm.controls).forEach(field => {
const control = this.myForm.control.get(field);
control.markAsUntouched();
});
}
// Call from MatRemoveButtonGridRenderComponent
removeFromComponent(holiday: Holiday){
this.removeHoliday(holiday.date);
this.initialMode();
}
// Call from MatEditButtonGridRenderComponent
editFromComponent(data: Holiday){
this.isEditMode = true;
this.editHoliday(data);
}
cancelEditMode() {
this.initialMode();
}
private initialMode() {
this.holiday = new Holiday();
this.errorMessage = "";
this.isEditMode = false;
this.resetControls();
}
onGridReady(params: any) {
this.gridApi = params.api;
this.gridColumnApi = params.columnApi;
this.gridColumnApi.autoSizeColumns();
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { ICellRendererAngularComp } from 'ag-grid-angular';
import { ICellRendererParams } from 'ag-grid';
import { RowNode } from 'ag-grid/dist/lib/entities/rowNode';
@Component({
selector: 'app-mat-edit-button-grid-render',
template: `<button mat-mini-fab color="primary" (click)="edit()">
<mat-icon inline="true">mode_edit</mat-icon>
</button>`,
styleUrls: ['./mat-edit-button-grid-render.component.scss']
})
export class MatEditButtonGridRenderComponent implements ICellRendererAngularComp {
public params: ICellRendererParams;
agInit(params: ICellRendererParams): void {
this.params = params;
}
public edit() {
let data = this.params.data;
this.params.context.componentParent.editFromComponent(data);
}
refresh(): boolean {
return false;
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { ICellRendererAngularComp } from 'ag-grid-angular';
import { ICellRendererParams } from 'ag-grid';
import { RowNode } from 'ag-grid/dist/lib/entities/rowNode';
@Component({
selector: 'app-mat-remove-button-grid-render',
template: `<button mat-mini-fab color="primary" (click)="remove()">
<mat-icon inline="true">remove</mat-icon>
</button>`,
styleUrls: ['./mat-remove-button-grid-render.component.scss']
})
export class MatRemoveButtonGridRenderComponent implements ICellRendererAngularComp {
public params: ICellRendererParams;
agInit(params: ICellRendererParams): void {
this.params = params;
}
public remove() {
let data = this.params.data;
this.params.context.componentParent.removeFromComponent(data);
}
refresh(): boolean {
return false;
}
}
<file_sep>import { NgModule } from '@angular/core';
import { AgGridModule } from 'ag-grid-angular';
import { SharedModule } from '../shared/shared.module';
import { environment } from '../../environments/environment';
import { FeaturesComponent } from './features.component';
@NgModule({
imports: [
SharedModule,
AgGridModule.withComponents([])
],
declarations: [FeaturesComponent]
})
export class FeaturesModule { }
<file_sep>import { TestBed, inject } from '@angular/core/testing';
import { SpringsService } from "./springs.service";
describe('SpringsService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [SpringsService]
});
});
it('should be created', inject([SpringsService], (service: SpringsService) => {
expect(service).toBeTruthy();
}));
});
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { LoginService } from './login.service';
import { LoginUser } from './loginUser';
import { HttpErrorResponse } from '@angular/common/http';
import { User } from '../users/user';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent {
private username : string = "";
private password : string = "";
private errorMessage : string = "";
constructor(public loginService: LoginService, private router: Router) { }
login() {
this.loginService.loginWithUsername(this.username, this.password).subscribe((loginUser:User) => {
this.loginService.currentUser = loginUser;
this.router.navigate(['']);
},
(error: HttpErrorResponse) => {
this.errorMessage = error.status==404 ? "Invalid user name or password":"Known Error";
console.log(error);
this.router.navigate(['/login']);
});
}
logout() {
this.loginService.signOut();
}
}
<file_sep>import { DateModel } from "../shared/date.model";
export class Spring {
id : number;
code : string = '';
name : string = '';
// status : string = '';
springDays : number;
startDate : string;
endDate: string;
startDateMd : DateModel;
endDateMd : DateModel;
constructor(values: Object = {}) {
Object.assign(this, values);
this.startDateMd = new DateModel(this.startDate);
this.endDateMd = new DateModel(this.endDate);
}
applyChanges() {
this.startDate = this.startDateMd.value;
this.endDate = this.endDateMd.value;
}
setEndDateMdCalculed() {
this.endDateMd.setAddWorkableDays(this.startDateMd,this.springDays);
}
isNeededPropagate() : boolean {
return !this.endDateMd.equalsThan(this.endDate);
}
}
<file_sep>import { Component, OnInit, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { GridApi, GridOptions } from 'ag-grid';
import { MatEditButtonGridRenderComponent } from '../grid-custom-components/mat-edit-button-grid-render/mat-edit-button-grid-render.component';
import { MatRemoveButtonGridRenderComponent } from '../grid-custom-components/mat-remove-button-grid-render/mat-remove-button-grid-render.component';
import { SpringsService } from "./springs.service";
import { Spring } from './spirng';
import { DateModel } from '../shared/date.model';
import { LoginService } from '../login/login.service';
import { Observable } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { AgFormatterService } from '../shared/ag-formatter.service';
@Component({
selector: 'app-springs',
templateUrl: './springs.component.html',
styleUrls: ['./springs.component.scss']
})
export class SpringsComponent implements OnInit {
public spring : Spring;
public startDateModel : DateModel;
public context;
@ViewChild('myForm', { static: false }) myForm : NgForm;
private gridApi: GridApi;
private gridColumnApi;
private columnDefs;
private rowData : Spring[];
private gridOptions: GridOptions;
private errorMessage : string = "";
private isEditMode: boolean = false;
constructor(private springsService: SpringsService, private loginService: LoginService, private frm: AgFormatterService) {
this.context = { componentParent: this };
this.gridOptions = <GridOptions>{};
this.gridOptions.enableFilter = true;
this.gridOptions.enableSorting = true;
this.gridOptions.suppressRowClickSelection = false;
this.gridOptions.enableColResize = true;
this.gridOptions.enableCellChangeFlash = true;
this.gridOptions.rowSelection = 'single';
this.spring = this.springsService.setSpringDefaultValues();
this.columnDefs = [
{ headerName: 'Key', field: 'key', hide: true },
{ headerName: 'Spring Code', field: 'code', filter: 'text', width: 150 },
{ headerName: 'Spring Name', field: 'name', filter: 'text', width: 150 },
{ headerName: 'Status', field: 'status', filter: 'text', width: 150 },
{ headerName: 'Spring Days', field: 'springDays', type: "numericColumn", filter: 'number', width: 150 },
{ headerName: 'Start Date', field: 'startDate', filter: 'text', width: 150, valueFormatter: this.frm.ag_dateFormatter },
{ headerName: 'End Date', field: 'endDate', filter: 'text', width: 150, valueFormatter: this.frm.ag_dateFormatter },
{ headerName: '', cellRendererFramework: MatEditButtonGridRenderComponent, width: 75 },
{ headerName: '', suppressFilter: true, cellRendererFramework: MatRemoveButtonGridRenderComponent, width: 75 }
];
}
ngOnInit(): void {
this.populateSprings();
}
refeshSprings(): void {
this.populateSprings();
this.initialMode();
}
private populateSprings() {
this.springs.subscribe(
springList => {
this.rowData = springList?springList.map(s=>new Spring(s)):springList;
this.spring = this.springsService.changeSpringDefaultValues(this.spring, this.rowData);
},
error => this.handleError(error)
);
}
currencyFormatter(params) {
return '£' + params.value;
}
get springs(): Observable<Spring[]>{
return this.springsService.getSprings();
}
getSpringById(id: number) : Observable<Spring> {
return this.springsService.getSpringById(id);
}
removeSpring(id: number) {
this.springsService.deleteSpringById(id).subscribe(
data => this.refeshSprings(),
error => console.log(error)
);
}
editSpring(data: Spring) {
this.spring = new Spring(data);
this.errorMessage = "";
}
addSpring() {
this.spring.applyChanges();
this.springsService.addSpring(this.spring).subscribe(
data => this.refeshSprings(),
error => this.handleError(error)
);
}
updateSpring(){
if (this.spring.isNeededPropagate()) {
this.propagateSprings(this.spring);
}
this.spring.applyChanges();
this.springsService.updateSpring(this.spring).subscribe(
data => this.refeshSprings(),
error => this.handleError(error)
);
}
propagateSprings(spring: Spring) {
let dateToPropagate = new DateModel(this.loginService.currentProject.startDate.toString());
dateToPropagate.setAddWorkableDays(dateToPropagate,0);
this.rowData.forEach(sprg => {
if (sprg.code == spring.code) {
sprg = spring;
}
let spr = this.propagateAndupdateSpring(sprg,dateToPropagate);
dateToPropagate = spr.endDateMd;
})
}
propagateAndupdateSpring(sprg: Spring,endDateMd: DateModel ): Spring {
sprg.startDateMd.setAddWorkableDays(endDateMd,2);
sprg.setEndDateMdCalculed();
sprg.applyChanges();
this.springsService.updateSpring(sprg).subscribe();
return sprg;
}
resetControls() {
this.myForm.resetForm();
Object.keys(this.myForm.controls).forEach(field => { // {1}
const control = this.myForm.control.get(field); // {2}
control.markAsUntouched(); // {3}
});
}
// Call from MatRemoveButtonGridRenderComponent
removeFromComponent(spring: Spring){
this.removeSpring(spring.id);
this.initialMode();
}
// Call from MatEditButtonGridRenderComponent
editFromComponent(data: Spring){
this.isEditMode = true;
this.editSpring(data);
}
cancelEditMode() {
this.initialMode();
}
private initialMode() {
this.spring = new Spring();
this.errorMessage = "";
this.isEditMode = false;
this.resetControls();
}
onSelectionChanged() {
var selectedRows = this.gridApi.getSelectedRows();
var selectedRowAux;
selectedRows.forEach(function(row, index) {
selectedRowAux = row;
});
this.loginService.currentSpring = selectedRowAux;
}
onGridReady(params) {
this.gridApi = params.api;
this.gridColumnApi = params.columnApi;
this.gridColumnApi.autoSizeColumns();
}
handleError(res: HttpErrorResponse) {
this.errorMessage = res.error.error_message;
console.log(res);
}
}
<file_sep>import { Component, OnInit, ViewChild } from '@angular/core';
import { Advance } from './advance';
import { GridApi, GridOptions } from 'ag-grid';
import { OutlookService } from './outlook.service';
import { HttpErrorResponse } from '@angular/common/http';
import { AgFormatterService } from '../shared/ag-formatter.service';
import { MatTableDataSource, MatSort } from '@angular/material';
import { NoWeekendValidator } from '../shared/date.weekend.directive';
export interface PeriodicElement {
name: string;
value: number;
date: string;
}
const ELEMENT_DATA: PeriodicElement[] = [
{name: 'PROYECCION AL ', value: null, date: '10/10/2020'},
{name: 'Hs Restantes', value: 140.00, date: null},
{name: 'Hs Recursos Disponibles x Día', value: 9.00 ,date: null},
{name: 'Días Hábiles Restantes', value: 15.00 ,date: null},
{name: 'Días Hábiles Restantes', value: 15.00 ,date: null},
{name: 'Fecha Finalización Estimada', value: null, date: '20/10/2020'},
];
@Component({
selector: 'app-outlook',
templateUrl: './outlook.component.html',
styleUrls: ['./outlook.component.scss']
})
export class OutlookComponent implements OnInit {
public advance : Advance;
public context;
private gridApi: GridApi;
private gridColumnApi;
private columnDefs ;
private columnDefs2 ;
private rowData : Advance[];
private rowData2 : PeriodicElement[];
private gridOptions: GridOptions;
private errorMessage : string = "";
private isEditMode: boolean = false;
constructor(private outlookService: OutlookService, private frm: AgFormatterService) {
this.context = { componentParent: this };
this.gridOptions = <GridOptions>{};
this.gridOptions.enableFilter = true;
this.gridOptions.enableSorting = true;
this.gridOptions.suppressRowClickSelection = false;
this.gridOptions.enableColResize = true;
this.gridOptions.enableCellChangeFlash = true;
this.gridOptions.rowSelection = 'single';
this.columnDefs = [
{ headerName: 'Name', field: 'name', filter: 'text', width: 300 },
{ headerName: 'Spent', field: 'spent', type: "numericColumn", filter: 'number', valueFormatter: this.frm.ag_numberTwoDecimalFormatter, width: 150 },
{ headerName: 'Advance', field: 'advance', type: "numericColumn", filter: 'number', valueFormatter: this.frm.ag_percentageTwoDecimalFormatter, width: 150 }
];
this.columnDefs2 = [
{ headerName: 'Name', field: 'name', filter: 'text', width: 300 },
{ headerName: 'Value', field: 'value', type: "numericColumn", filter: 'number', valueFormatter: this.frm.ag_numberTwoDecimalFormatter, width: 150 },
{ headerName: 'Date', field: 'date', filter: 'text', width: 150 }
];
}
ngOnInit() {
this.populateAdvance();
this.rowData2 = ELEMENT_DATA;
}
private populateAdvance() {
this.outlookService.getAdvance().subscribe(
list => {
this.rowData = list?list.map(s=>new Advance(s)):list;
},
error => this.handleError(error)
);
}
onGridReady(params) {
this.gridApi = params.api;
this.gridColumnApi = params.columnApi;
this.gridColumnApi.autoSizeColumns();
}
handleError(res: HttpErrorResponse) {
this.errorMessage = res.error.error_message;
console.log(res);
}
}
<file_sep>import { DateModel } from "../shared/date.model";
export class Advance {
code : string = '';
name : string = '';
spent : number;
advance : number;
constructor(values: Object = {}) {
Object.assign(this, values);
}
}
<file_sep>import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { LoginService } from '../login/login.service';
import { Capacity } from './capacity';
@Injectable({
providedIn: 'root'
})
export class CapacityService {
private _baseUrl = './api/springs/';
constructor(private http: HttpClient, private loginService: LoginService) {
}
getCapacities() : Observable<Capacity[]>{
return this.http.get(this.baseUrl) as Observable<Capacity[]>;
}
getCapacityById(id : number): Observable<Capacity> {
return this.http.get(`${this.baseUrl}/${id}`) as Observable<Capacity>;
}
addCapacity(capacity: Capacity): Observable<Capacity> {
return this.http.post(this.baseUrl, capacity) as Observable<Capacity>;
}
deleteCapacityById(id: number) : Observable<Capacity> {
return this.http.delete(`${this.baseUrl}/${id}`) as Observable<Capacity>;
}
updateCapacity(capacity : Capacity): Observable<Capacity> {
return this.http.put(`${this.baseUrl}/${capacity.id}`, capacity) as Observable<Capacity>;
}
private get baseUrl(): string {
return this._baseUrl + this.loginService.currentSpringId + '/capacities';
}
}
|
d3a91543d4b4453b0ec1caa4cd129eef13463b68
|
[
"TypeScript"
] | 42
|
TypeScript
|
jorgemonczer/hoyxhoy-planner-frontend
|
d9a77478ad3ea7f9a7367a2e86b5684635ff8597
|
475ea9c5b4aee19d6aa51c8c7471bc0b6b5cad2b
|
refs/heads/master
|
<file_sep>---
title: "Non-Technical Note Template"
author: "<NAME>"
date: 2019-01-28T00:00:00-07:00
description: "This is a non-technical note template."
type: non-technical_note
draft: false
---
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Sagittis nisl rhoncus mattis rhoncus urna neque. Eget nunc scelerisque viverra mauris in. Nulla aliquet porttitor lacus luctus. Nulla at volutpat diam ut venenatis tellus in. Cum sociis natoque penatibus et magnis. Auctor augue mauris augue neque. Senectus et netus et malesuada fames. Diam sollicitudin tempor id eu. Vestibulum lectus mauris ultrices eros in cursus. Integer enim neque volutpat ac tincidunt vitae semper. Commodo odio aenean sed adipiscing diam donec adipiscing tristique. Hendrerit gravida rutrum quisque non. At consectetur lorem donec massa sapien faucibus et molestie. Quam nulla porttitor massa id neque aliquam vestibulum.
Maecenas **volutpat blandit aliquam** etiam erat. Ornare aenean euismod elementum nisi quis eleifend. Porttitor leo a diam sollicitudin. Eleifend donec pretium vulputate sapien nec sagittis aliquam malesuada. Vel risus commodo viverra maecenas.
## Vel turpis nunc eget lorem dolor
Quisque non tellus orci ac auctor augue mauris augue neque. Quam viverra orci sagittis eu volutpat odio facilisis. Dictum non consectetur a erat nam at. Ac tortor vitae purus faucibus ornare suspendisse sed nisi lacus. Diam quis enim lobortis scelerisque. Nunc mattis enim ut tellus elementum sagittis vitae et. Fermentum odio eu feugiat pretium nibh ipsum consequat.
Tellus integer feugiat scelerisque _varius morbi enim_. Aenean [sed adipiscing diam](https://google.com) donec. Rhoncus mattis rhoncus urna neque viverra justo nec. At tempor commodo ullamcorper a lacus vestibulum sed arcu non. Id volutpat lacus laoreet non curabitur gravida arcu ac tortor. Tincidunt augue interdum velit euismod in. Ut placerat orci nulla pellentesque dignissim enim sit amet venenatis. Ultricies leo integer malesuada nunc vel risus commodo viverra maecenas. Nam aliquam sem et tortor consequat id porta nibh. Vel turpis nunc eget lorem dolor sed viverra ipsum.
- Lobortis feugiat vivamus at augue.
- Eu ultrices vitae auctor eu augue ut.
- Diam sit amet nisl suscipit adipiscing bibendum.
- Pulvinar elementum integer enim neque volutpat ac.
Vitae suscipit tellus mauris a diam. Scelerisque viverra mauris in aliquam sem. Amet `risus nullam eget` felis eget nunc.
```
Nec tincidunt praesent semper
feugiat nibh. At tempor
commodo ullamcorper a
lacus vestibulum.
```
Vulputate ut pharetra sit amet aliquam id diam maecenas. Cursus risus at ultrices mi tempus. Vitae semper quis lectus nulla at volutpat diam ut venenatis. Adipiscing elit ut aliquam purus sit. Integer enim neque volutpat ac tincidunt. At consectetur lorem donec massa sapien faucibus et molestie ac. At urna condimentum mattis pellentesque id nibh.
>Turpis egestas maecenas pharetra convallis. Nisi scelerisque eu ultrices vitae auctor eu augue ut lectus. Commodo odio aenean sed adipiscing diam donec. Faucibus et molestie ac feugiat. Blandit cursus risus at ultrices. At augue eget arcu dictum varius duis at consectetur.
Adipiscing vitae proin sagittis nisl rhoncus mattis rhoncus urna. Praesent tristique magna sit amet purus gravida quis blandit. Nec ullamcorper sit amet risus. Ut diam quam nulla porttitor massa. Lacus luctus accumsan tortor posuere ac ut consequat. Eget nullam non nisi est sit amet facilisis.
### Pretium vulputate sapien nec sagittis.
Ac tincidunt vitae semper quis lectus nulla at volutpat. Enim facilisis gravida neque convallis a cras. Quis vel eros donec ac odio tempor orci. Ac placerat vestibulum lectus mauris ultrices. At quis risus sed vulputate odio. Suspendisse faucibus interdum posuere lorem ipsum dolor sit amet. Nibh nisl condimentum id venenatis a condimentum. Sit amet mauris commodo quis imperdiet massa tincidunt. Lorem sed risus ultricies tristique. Viverra adipiscing at in tellus. Eget aliquet nibh praesent tristique magna sit amet purus. Penatibus et magnis dis parturient montes nascetur ridiculus mus mauris. Amet dictum sit amet justo donec. Consequat id porta nibh venenatis cras sed felis. Nulla pharetra diam sit amet nisl suscipit adipiscing bibendum. Sapien et ligula ullamcorper malesuada proin libero nunc consequat interdum. Faucibus ornare suspendisse sed nisi lacus.<file_sep># notes
This is <NAME>'s collection of personal notes on coding, statistics, machine learning, and technical management. These notes are posted publically at https://ChrisAlbon.com. What is in this repo will not be useful to other folks.
## Overview
The master record of a note is either a Jupyter Notebook or a Markdown file. These files are in the `content` folder. The website HTML is contained in the `docs` folder.
## Full Deploy Procedure
1. Run `make.ipynb` to convert the Jupyter Notebooks and associated images into Markdown files.
2. Run `hugo` to convert the Markdown files into HTML pages.
3. Run `git add -A`
4. Run `git commit -m "commit message"`
5. Run `git push`
## Markdown Head Metadata Example
```
---
title: "Give Table An Alias"
author: "<NAME>"
date: 2019-01-28T00:00:00-07:00
description: "Give a table an alias in Snowflake using SQL."
type: technical_note
draft: false
---
```
## Useful Aliases
To reduce the barriers to publishing a new note as much as possible, here are some useful aliases for your `.bash_profile`:
```
# Notes Project
# Go to Notes folder
alias nn='cd /Users/chrisalbon/dropbox/cra/projects/notes'
# Go to Notes folder and open Jupyter Notebook
alias njn='cd /Users/chrisalbon/dropbox/cra/projects/notes && jupyter notebook'
# Launch in Hugo server of Notes site
alias nhs='cd /Users/chrisalbon/dropbox/cra/projects/notes && hugo server'
# Publish a new note
alias nnn='cd /Users/chrisalbon/dropbox/cra/projects/notes && git pull && hugo && git add -A && git commit -m "made changes" && gp && git push'
```
Note that when you run `nnn` you might be prompted for an application password. You can get that / generate that from GitHub.com in account settings.
## To Do
- Fix Github issues
- Hunt for minor errors
- Refactor make.ipynb to make it .py and cleaner
<file_sep>---
title: "Add Columns To Text"
author: "<NAME>"
date: 2018-07-16T00:00:00-07:00
description: "How to add colummns to text using the Linux command line."
type: technical_note
draft: false
---
## Create A File With Comma Separated Text
{{< highlight markdown >}}
echo "chris, 34, male" >> staff.txt
echo "sarah, 22, female" >> staff.txt
echo "Bob, 59, male" >> staff.txt
{{< /highlight >}}
## View File
{{< highlight markdown >}}
cat staff.txt
{{< /highlight >}}
```
chris, 34, male
sarah, 22, female
Bob, 59, male
```
## Extract Text By Breaking Into Columns And Save To File
`cut` the text in `staff.txt` that is separated by commas (`-d ','`) into columns, then take the second (`-f 2`) column, and finally save to `ages.txt`
{{< highlight markdown >}}
cut -d ',' -f 2 staff.txt > ages.txt
{{< /highlight >}}
## View `ages.txt`
{{< highlight markdown >}}
cat ages.txt
{{< /highlight >}}
```
34
22
59
```
## Add `ages.txt` As New Column Of `staff.txt`
Add (`paste`) the content of `ages.txt` as a new column of `staff.txt` delimited with a comma (`-d ','`).
{{< highlight markdown >}}
paste -d ',' ages.txt staff.txt
{{< /highlight >}}
```
34,chris, 34, male
22,sarah, 22, female
59,Bob, 59, male
```<file_sep>---
title: "What I Learned Tracking My Time At Techstars"
author: "<NAME>"
date: 2016-02-01T11:53:49-07:00
description: "What I Learned Tracking My Time At Techstars."
type: article
draft: false
aliases:
- /blog/what-i-learned-tracking-my-time-at-techstars.html
---

In the fall of 2015, [New Knowledge](http://newknowledge.io/), a company I cofounded with two friends was offered a slot in the 2016 class of Techstars Cloud. Like most people in tech, I had heard about Techstars, but in truth I barely knew anything specific, particularly about the day-to-day of the program. Was Techstars a permanent hackathon fueled by Soylent and Adderall? Was it three months of guest speakers and sponsored happy hours? I watched Techstars's [promotional videos](https://vimeo.com/techstars/videos), but the only impression I could glean was that all the founders worked 36 hours per day while having ample spare time to ride bikes around downtown Boulder. I also found [some posts](https://www.quora.com/What-is-the-first-week-of-a-TechStars-program-like) about people’s experiences, but overall I was in the dark. So, when we joined Techstars Cloud in November, I did what I was trained to do: gather data.
For three months, from November 2nd, 2015 to January 31st, 2016, I tracked how I spent every 15 minutes of every day and categorized each into one of seven activities:
- **Non-Technical Work:** Email, writing, diagramming, project management, PivotalTracker, etc.
- **Technical Work:** Coding, designing, data analysis, etc.
- **Discussion:** Team meetings, speaking events, meeting with mentors or investors, Techstars happy hours, etc.
- **Sleep**
- **Travel:** Driving or flying (when I couldn’t do any work)
- **Exercise:** Running (which basically never happened)
- **Personal:** Time with family, cooking, hobbies, reading, housework etc.
The full data is [available on Github](https://github.com/chrisalbon/techstars_timesheet)I hope you find it useful.

## Lesson 1: Techstars Is For Going All-In
If there was one description of my time at Techstars it was that I worked, a lot -- during evenings, lunches, and holidays; in offices, cars, and AirBnBs; alone, with my team, and while holding my daughter. The combination of the environment and the looming Demo Day made the work all-consuming. I was responsible for the product, so it is unsurprising that the largest number of my hours was spent on technical tasks. In truth, even non-technical tasks were almost always related to product development: UX testing, QAing, or PivotalTracker. My laser focus on the product was sometimes at odds with the myriad of guest speakers and mentor meetings that, while interesting and useful, could suck me in and stall development. As a company we started using two strategies to keep the product moving forward. First, most of the meetings and events were handled by my cofounders, which left me time to focus to a greater degree on the product. Second, when we had a product update or launch goal, I spent weeks away from the Techstars offices so I could get the most work done on the product as possible.

On average, during Techstars I worked 91.6 hours per week. I worked the most hours during the first week of the program, where I averaged 17.4 hours of work per day. This number will be unsurprising to anyone who has going though Techstars. The first three weeks of Techstars are called Mentor Madness and can essentially be described as a full day of back to back 20 minute meetings with every fancy and impressive founder you can imagine. You walk into a room, give a five minute pitch to anyone from the CEO of a boutique ad agency to a founder of a technology giant and hear their take about you, your company, your product, your market, whatever. After 20 minutes you walk into the next room and repeat the entire process again.

Mentor Madness was a grueling experience for all of us, not only because it took up so much of our energy (it takes a lot of focus to be engaged after seven almost-back-to-back meetings), but more importantly it made us have to defend, explain, and face so many fundamental assumptions we implicitly and explicitly made about our company, product, and strategy. In one meeting a mentor would argue that the go-to-market strategy is flawed and 20 minutes later the next mentor is arguing that we need to change our company's name.
Those weeks were brutal. However, it was also probably one of the most important few weeks of our company. Because at the end of all those meetings, our day would just begin; from the last meeting to late at night my cofounders and I would consider, discuss, and debate a hundred points that were brought in the day. Why did the mentor hate the pricing model? Was she right or just old-fashioned? Should we change our name? Who is our customer? All the meetings and all the challenging questions forced us to discuss things which might otherwise be assumed or left unsaid.

For those first few weeks I would get up early, spend an hour emailing, discuss some point or another about strategy or product, take meetings with mentors, discuss more over lunch, take more meetings, discuss over dinner and into the evening, shower, sleep, and start the whole thing over again. Two days during Mentor Madness contained a massive 13 and 14 hours of discussions. Those conversations alone made Techstars worthwhile.
Unsurprisingly, the week with the least work was Christmas when I was traveling with my family and would only be able to sneak in a few hours of work per day after everyone fell asleep.
## Lesson 2: The Start Of Techstars Is About Strategy, The End Is About Execution
Our company was not alone is spending the first weeks of the program focusing on planning and strategy. I think most of the companies in our class spent the first few weeks either going back to the drawing board or mapping out a plan ahead. However, in December, the mid-point of the program there was a general shift from planning to execution.
Looking at hours spent on between technical and non-technical tasks, Techstars could be divided into two periods, before Christmas and after Christmas. In the first half of the program it felt like I spent every moment I wasn’t in meetings writing, updating, or managing user stories. We had a few contract developers and I agonized over the ordering of user stories in PivotalTracker as to maximize the value we would get from every hour of their time. However, during the second half of the problem the planning took a back seat to building.

Between Christmas and our launch on January 19th was probably my happiest in the program, because it was a wonderful coding crunchtime. I would get up, select the next user story in the queue, complete it, QA, and repeat. It was -- frankly -- just fun. All the discussions around marketing, fundraising, or ten thousand other things were put aside (i.e. handled by my cofounders), leaving me free to build.
This switch from planning to building is beautifully seen in the data: in the first half of the program I spent almost all my time on planning and strategy and in the second half I spent almost all my time building.
While non-technical and technical work peaked around the beginning and the end of the program, meetings, networking, and discussions continued throughout. As I said previously, the Mentor Madness of the first three weeks took up a massive amount of time at the start of the program, but after those weeks my cofounders and I actively tried to give each other the space to get stuff done. Our primary tactic was to have regular short(ish) “State Of The Union calls almost every day, leaving the major discussions to multi-day planning sessions every few weeks. These discussion can be easily seen as peaks in the chart below. This system might not work well for everyone, but it gave us the right balance of time to work out problems and time to get shit done.

Did all those hours matter? Completely and absolutely. Over the course of the program the product went from a tricycle to a Harley Davidson. There is more to do, but the leaps and bounds made during Techstars has been incredible.
## Lesson 3: Sleep Is Important! Kinda.
As soon as I started tracking my time, I knew the first question everyone was going to ask: “how much did you sleep?” and because of the power of data I can give you a real answer: 5.5 hours of sleep per night. I will admit I was pretty pleased when I saw that number because while everyone at Techstars works their asses off 4.5 to 6.5 hours of sleep was my normal amount prior to Techstars. That said, on those few nights I received far less sleep than I needed my productivity suffered the next day.
Looking at the data below, it is also notable to see that the amount of sleep I got every night remained relatively stable throughout the program. The only two deviations are the two times I made the twelve hour drive from my house to the Techstars offices overnight and the moderate dip in sleep I got in early January when I was enjoying my late night coding sessions.

## Lesson 4: There Is No Work-Life Balance
I would love to say there was great work-life balance, but in reality was not any sort of work-life balance. There was regular fun events (e.g. happy hours, runs, etc.) during the program, but that isn’t work-life balance, that is fun work events.
The truth is that all the benefits of Techstars, the rapid advance of our product, the boost in users, the improved strategy, and everything else came at a price -- that for three months you lived your work and everything else from family to kids to friends took a backseat. During Techstars my average daily “free time” (i.e. not working or sleeping) was 2.7 hours. That is 2.7 hours per day for everything, from Christmas mornings to birthday parties to doctors appointments to cooking dinner.
I am not complaining. I like working, and I am in a place in my life that I can let work take over for a while, but make no mistake: it did take over. I'd argue that to really get value from Techstars, it probably has to take over.

As a more concrete example to the point above, of the three major holidays that took place during Techstars Cloud two of them were just a regular work day for me.

## Final Thoughts On Techstars
It has been incredibly valuable to every aspect of New Knowledge, from product to strategy. The advice been useful, the connections have been valuable, and Demo Day (February 11th) will be awesome. However, at the end of the day none of that was why I enjoyed Techstars.
The real reason is that for three months I worked with people I enjoy for long hours on hard problems -- and everything else took a back seat. That might not appeal to many people, but it appeals to me. In truth, not once during Techstars did I feel like I was “working”. Rather, I was with my friends, trying to do something genuinely hard -- and I can't ask for more than that.<file_sep># Import standard library's logging
import logging
# Create function that converts dollars to cents
def convert_dollars_to_cents(dollars):
# Convert dollars to cents (as an integer)
cents = int(dollars * 100)
logging.debug("debug")
logging.info("info")
logging.warning("warning")
logging.error("error")
logging.critical("critical")
# Return cents
return cents
# Create dollar amount
dollars = 12.40
# Run dollars to cents convert function
convert_dollars_to_cents(dollars)<file_sep>---
title: "Test"
author: "<NAME>"
date: 2018-07-16T00:00:00-07:00
description: " using the Linux command line."
type: technical_note
draft: true
---
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
## Make Subdirectory
{{< highlight markdown >}}
ls
{{< /highlight >}}
```
AnacondaProjects Documents Dropbox (Personal) Pictures spark
Applications Downloads Library Public spark-warehouse
Creative Cloud Files Dropbox Movies anaconda3 tmp
Desktop Dropbox (BRCK) Music nltk_data
```
## Template Title
{{< highlight markdown >}}
{{< /highlight >}}
```
```
|
7adec65d199cd750eaf6cdd1bf5aa48964cc6277
|
[
"Markdown",
"Python"
] | 6
|
Markdown
|
Zahra-Ns/notes
|
4236f1c70dab14541e71394fa014db333e155183
|
d90d545a15eba64479196732f71a708fb780ff31
|
refs/heads/master
|
<repo_name>piotrku91/LQArmRPI-UI<file_sep>/templates/sloty.html
<!doctype html>
{% extends "layout_p1.html" %}
{% block title %}Stan stołu{% endblock %}
{% block content %}
<br><br><center>
<table><tr><td>
<table style="border: 0px;">
<tr><h2>REWOLWER 1</h2></tr>
<tr> {% for lqo in lq %} <td>
<!-- NACZYNIE 1 -->
{% if lqo[0] < 4 %}
<div class="e" id="Kielich0" style="padding: 70px; text-align: center; height: 80px; width: 70px;" >
<img src="{{ url_for('static', filename = 'bottle.png') }}" width="32" height="32">
<br>{{lqo[0]}}<br>{{lqo[1]}}<br>{{lqo[2]}}<br>{{lqo[3]}} ml</div>
</td> {% endif %} </tr>
{% endfor %}
</table></td>
<td width="50"> </td>
<td>
<table style="border: 0px;">
<tr><h2>REWOLWER 2</h2></tr>
<tr> {% for lqo in lq %} <td>
<!-- NACZYNIE 1 -->
{% if lqo[0] < 7 %}
<div class="e" id="Kielich0" style="padding: 70px; text-align: center; height: 80px; width: 70px;" >
<img src="{{ url_for('static', filename = 'bottle.png') }}" width="32" height="32">
<br>{{lqo[0]}}<br>{{lqo[1]}}<br>{{lqo[2]}}<br>{{lqo[3]}} ml</div>
</td> {% endif %} </tr>
{% endfor %}
</table></td>
<td width="50"> </td>
<td>
<table style="border: 0px;">
<tr><h2>REWOLWER 3</h2></tr>
<tr> {% for lqo in lq %} <td>
<!-- NACZYNIE 1 -->
{% if lqo[0] < 10 %}
<div class="e" id="Kielich0" style="padding: 70px; text-align: center; height: 80px; width: 70px;" >
<img src="{{ url_for('static', filename = 'bottle.png') }}" width="32" height="32">
<br>{{lqo[0]}}<br>{{lqo[1]}}<br>{{lqo[2]}}<br>{{lqo[3]}} ml</div>
</td> {% endif %} </tr>
{% endfor %}
</table></td>
</tr></table>
<br><br>
</center>
{% endblock %}
<file_sep>/deamon_LQArmUI_v3.py
import threading
import time
import serial
import PySimpleGUI as sg
import psycopg2
import requests as req
from config import config
params = config("settings.ini","main")
devadd = params["serial_dev_add"]
devbr = params["serial_dev_br"]
ip=params["ip"]
Powitanie="** Deamon - LQ Arm UI - uruchomiony..."
try:
ser = serial.Serial(devadd, devbr, timeout=1)
s_on=True
except:
s_on=False
THREAD_EVENT = '-THREAD-'
def the_thread(window):
if s_on:
window.write_event_value('-THREAD-', (Powitanie.rstrip()))
window.TKroot.title(devadd+ " (Połączono)")
else:
window.write_event_value('-THREAD-', ("Nie mozna polaczyc z -"+devadd))
window.TKroot.title(devadd+ " (Brak połączenia)")
while s_on:
time.sleep(1)
serBarCode = ser.readline()
if len(serBarCode) >= 0:
Odczytana=serBarCode.decode("utf-8")
window.write_event_value('-THREAD-', (Odczytana.rstrip()))
if s_on: ser.close()
# Data sent is a tuple of thread name and counter
# window.write_event_value('-THREAD-', (threading.current_thread().name, Odczytana)) # Data sent is a tuple of thread name and counter
def main():
sg.theme('Dark brown')
names = ['Komenda']
tab1_layout = [[sg.Text('LQArmGUI Commander', font='Verdana 20')],
[sg.Multiline(size=(200,20), key='-ML-', disabled=True, autoscroll=True, reroute_stdout=True, write_only=True, reroute_cprint=True), sg.Listbox(names, size=(20, 20), enable_events=True, key='-LIST-')],
[sg.Input(key='-IN-',size=(190,1)),sg.B('>>',bind_return_key=True)],
[sg.Button('Koniec')] ]
tab2_layout = [[sg.Text('Tab 2')]]
tab3_layout = [[sg.Text('Tab 3')]]
tab4_layout = [[sg.Text('Tab 3')]]
tab_group_layout = [[sg.Tab('Konsola', tab1_layout, font='Courier 15', key='-TAB1-'),
sg.Tab('Tab 2', tab2_layout, visible=False, key='-TAB2-'),
sg.Tab('Tab 3', tab3_layout, key='-TAB3-'),
sg.Tab('Tab 4', tab4_layout, visible=False, key='-TAB4-'),
]]
layout = [ [sg.TabGroup(tab_group_layout,
enable_events=True,
key='-TABGROUP-') ] ]
window = sg.Window(devadd, layout).Finalize()
T = threading.Thread(target=the_thread, args=(window,), daemon=True)
T.start()
while True: # Event Loop
event, values = window.read()
# sg.cprint(event, values)
if event == THREAD_EVENT:
sg.cprint(f' {values[THREAD_EVENT]} ', colors='red on white')
if event == sg.WIN_CLOSED or event == 'Exit':
break
if event.startswith('>>'):
if s_on:
if not values['-IN-']=="":
IN = '-IN-'
sg.cprint(f' {values[IN]} ', colors='blue on white')
window['-IN-'].update("")
else:
sg.cprint("Jesteś offline.")
window.close()
if __name__ == '__main__':
main()
<file_sep>/wt.py
from playsound import playsound
playsound('bell.wav')
<file_sep>/deamon-LQArmUI.py
#!/usr/bin/python3
from config import config
import serial
import psycopg2
#from playsound import playsound
import requests as req
params = config("settings.ini","main")
devadd = params["serial_dev_add"]
devbr = params["serial_dev_br"]
ip=params["ip"]
Powitanie="** Deamon - LQ Arm UI - uruchomiony..."
ser = serial.Serial(devadd, devbr, timeout=1)
r = req.post('http://'+ip+':5000/db/insert_logcmd',data={'log_newcmd': Powitanie, 'log_infc': 0})
print(Powitanie)
while True:
serBarCode = ser.readline()
if len(serBarCode) >= 1:
Odczytana=serBarCode.decode("utf-8")
print(Odczytana)
# playsound('wosh.wav')
r = req.post('http://'+ip+':5000/db/insert_logcmd',data={'log_newcmd': Odczytana, 'log_infc': 1})
if Odczytana.find("ar_rtn")>-1:
part = Odczytana.split(";")
for i in part[1:(len(part)-1)]:
print(i)
# print(serBarCode.decode("utf-8")[len(serBarCode)-3] )
#if serBarCode.decode("utf-8")[len(serBarCode)-3] == "a":
#print(r.text)
<file_sep>/sender-LQArmUI.py
#!/usr/bin/python3
import sys
import serial
import os
from config import config
import requests as req
ser = serial.Serial("/dev/ttyACM0", "9600")
os.system('clear')
print("")
print("-------------------------------------------")
print(" LQArmUI v0.2 - Modul przekazujacy")
print(" Urzadzenie: "+ser.portstr)
print("-------------------------------------------")
print(" Argumenty wejsciowe: "+ str(len(sys.argv)-1))
print("")
if len(sys.argv)-1>0:
if sys.argv[1][0] == "-":
if sys.argv[1]=="-cl":
while True:
userkom = input("~ ")
if userkom == "exit":
break
print(" Wysylam do Arduino "+ userkom)
## Wyslij do Arduino
ser.write(userkom.encode())
# r = req.post('http://'+ip+':5000/db/insert_logcmd',data={'log_newcmd': userkom, 'log_infc': 2})
if sys.argv[1]=="-u":
newcmd = sys.argv[2]
print(" Wysylam do Arduino"+ newcmd)
# r = req.post('http://'+ip+':5000/db/insert_logcmd',data={'log_newcmd': newcmd, 'log_infc': 2})
ser.write(newcmd.encode())
if sys.argv[1]=="-ar":
newcmd = sys.argv[2]
print(" Wysylam do Arduino"+ newcmd)
# r = req.post('http://'+ip+':5000/db/insert_logcmd',data={'log_newcmd': newcmd, 'log_infc': 1})
ser.write(newcmd.encode())
if sys.argv[1]=="-ui":
newcmd = sys.argv[2]
print(" Wysylam do Arduino"+ newcmd)
# r = req.post('http://'+ip+':5000/db/insert_logcmd',data={'log_newcmd': newcmd, 'log_infc': 0})
ser.write(newcmd.encode())
else:
newcmd = sys.argv[1]
print(" Wysylam do Arduino"+ newcmd)
## Wyslij do Arduino
ser.write(newcmd.encode())
# r = req.post('http://'+ip+':5000/db/insert_logcmd',data={'log_newcmd': newcmd.encode() , 'log_infc': 2})
print("")
print(" Nie ma nic wiecej do roboty...")
print("-------------------------------------------")
print("")
ser.close()
<file_sep>/README.md
# LQArmRPI-UI
It is prototype of Web GUI for my Electronic project (LQArm) but finally I choosed Qt, C++ and QML for my GUI.
I do not develop this anymore.
It's using Python, PySerial, Flask framework, PostgreSQL database, ninja2 templates (flask cooperation).

<file_sep>/baza.py
#!/usr/bin/python3
import psycopg2
from config import config
def connect():
try:
params = config("settings.ini","postgresql")
print('Łączenie z bazą danych PostgreSQL')
c = psycopg2.connect(**params)
return c
except (Exception, psycopg2.DatabaseError) as error:
print(error)
def disconnect(c):
try:
if c is not None:
c.close()
print('Połączenie z bazą danych zamknięte.')
except (Exception, psycopg2.DatabaseError) as error:
print(error)
def ZapytanieZrzut(Tresc,ObjektBazy):
conn = ObjektBazy
cur = conn.cursor()
cur.execute(Tresc)
print("Zapytanie: "+Tresc)
print("Liczba zwróconych wierszy: ", cur.rowcount)
row = cur.fetchall()
cur.close()
return row
def Zapytanie(Tresc):
try:
conn = connect()
cur = conn.cursor()
cur.execute(Tresc)
print("Zapytanie: "+Tresc)
# id = cur.fetchone()[0]
print(conn.commit())
cur.close()
disconnect(conn)
except (Exception, psycopg2.DatabaseError) as error:
print(error)
return "z"
# while row is not None:
# print(row[1])
# row = cur.fetchone()
#cur.close()
# disconnect(conn)
## return 1
<file_sep>/server.py
#!/usr/bin/python3
import os
from flask import Flask, request, abort, redirect, url_for, render_template
from config import config
from baza import ZapytanieZrzut
from baza import Zapytanie
from baza import connect
from baza import disconnect
params = config("settings.ini","main")
sciezka=params["pathtoui"]
ip=params["ip"]
app = Flask(__name__)
@app.route('/')
def index():
baza = connect()
zakladki = ZapytanieZrzut('SELECT * FROM zakladkiui ORDER BY id', baza)
naczynia_db = ZapytanieZrzut('SELECT * FROM naczynia ORDER BY id', baza)
disconnect(baza)
return render_template('index.html',zakladki=zakladki,naczynia_db=naczynia_db)
@app.route('/ui/action_sender',methods=['POST'])
def Triger():
processed_text = request.form['Polecenie']
print(processed_text);
return redirect(url_for("WyslijInne",cmd=processed_text,u=2,esc="index"))
@app.route('/sloty')
def slots():
baza = connect()
zakladki = ZapytanieZrzut('SELECT * FROM zakladkiui ORDER BY id', baza)
lq = ZapytanieZrzut('SELECT * FROM Lq_slot ORDER BY id', baza)
disconnect(baza)
return render_template('sloty.html',zakladki=zakladki,lq=lq)
@app.route('/konsola',methods=['POST'])
def WyslijCMD():
print ('Kliknięto przycisk.')
processed_text = request.form['text']
return redirect(url_for("WyslijInne",cmd=processed_text,u=1,esc="Konsola"))
@app.route('/tosender/<cmd>/<int:u>/<esc>')
def WyslijInne(cmd=None,u=0,esc="Konsola"):
print (u)
processed_text=cmd
if u==1:
os.system('python '+ sciezka + 'sender-LQArmUI.py -u "'+processed_text+'"')
else:
os.system('python '+ sciezka + 'sender-LQArmUI.py -ui "'+processed_text+'"')
return redirect(url_for(esc))
@app.route('/db/insert_cmd',methods=['POST'])
def insert_cmd():
NewV="('"+request.form['n_cmd']+"','"+request.form['n_op']+"','"+request.form['n_ex']+"');"
a=Zapytanie(format("INSERT INTO komendy (naglowek, opis, przyklad) VALUES {}".format(NewV)))
return a
@app.route('/db/insert_logcmd',methods=['POST'])
def insert_logcmd():
NewV="(NOW(),'"+request.form['log_newcmd']+"','"+request.form['log_infc']+"');"
a=Zapytanie(format("INSERT INTO konsola (data,polecenie,interfejs) VALUES {}".format(NewV)))
return a
@app.route('/lista',methods=["GET","POST"])
def Komendy():
baza = connect()
zakladki = ZapytanieZrzut('SELECT * FROM zakladkiui ORDER BY id', baza)
db = ZapytanieZrzut('SELECT * FROM komendy ORDER BY id', baza)
disconnect(baza)
return render_template("lista.html",db=db,zakladki=zakladki)
@app.route('/konsola')
def Konsola():
baza = connect()
zakladki = ZapytanieZrzut('SELECT * FROM zakladkiui ORDER BY id', baza)
return render_template("konsola.html",zakladki=zakladki)
@app.route('/test',methods=["GET","POST"])
def test():
baza = connect()
db = ZapytanieZrzut(" WITH k AS (SELECT id,to_char(data,'DD/MM HH12:MI:SS') ,polecenie, interfejs, data FROM konsola ORDER BY data DESC LIMIT 20) SELECT * FROM k ORDER BY data ASC",baza)
disconnect(baza)
return render_template("pol.html",db=db)
@app.route('/layout')
def laytest():
return render_template("layout_p1.html")
if __name__ == '__main__':
app.run(host=ip,debug=True)
<file_sep>/settings.ini
[postgresql]
host=localhost
database=manipulator
user=postgres
password=<PASSWORD>
[main]
pathtoui=/home/piotr/manipulatorUI
ip=192.168.1.15
serial_dev_add=/dev/ttyACM0
serial_dev_br=9600
|
468d135c36dc763e2aea80fc0ca0fa3840ba0d10
|
[
"Markdown",
"Python",
"HTML",
"INI"
] | 9
|
HTML
|
piotrku91/LQArmRPI-UI
|
9e234a62a2a777ad5f13b30b36fd7cc57fdf1773
|
b30c26bb963a6a1df1c1546d4c4f4e66432933de
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace _3_klase
{
class Zivotinja
{
public bool sretan=false;
private string zvuk="grlglgrgrgl";
public string Zvuk { get => zvuk; set => zvuk = value; }
public void GlasajSe() {
Console.WriteLine($"Ja kazem {Zvuk}");
}
}
}
<file_sep>using System;
namespace _2_nizovi
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Nizovi!");
int[] cijelobrojni = new int[10]; //0-9
cijelobrojni[0] = 5;
cijelobrojni[7] = 9;
Console.WriteLine($"ukupno brojeva {cijelobrojni.Length }");
foreach (var br in cijelobrojni )
{
Console.WriteLine($"broj {br }");
}
int[] niz = new int[] { 1, 2, 4, 66, 78, 89, 45 };
foreach (var item in niz)
{
Console.Write(" " + item*item);
}
Console.WriteLine();
for (int i = 0; i < 10; i++)
{
Console.Write(i);
}
Console.WriteLine();
for (int i = 0; i < 10; i++)
{
Console.Write(i);
cijelobrojni[i] = i;
}
Console.WriteLine();
foreach (var br in cijelobrojni)
{
Console.WriteLine($"broj {br }");
}
Console.WriteLine();
for (int i = 0; i < 10; i+=2)
{
Console.Write(cijelobrojni[i]+" ");
}
Console.WriteLine();
for (int i = 9; i>0; i--)
{
Console.Write(cijelobrojni[i] + " ");
}
Console.WriteLine();
for (int i = 9; i > 0; i-=2)
{
Console.Write(cijelobrojni[i] + " ");
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Skola
{
class Osoba
{
private string ime;
private string prezime;
public Osoba(string Ime, string Prezime)
{
ime = Ime;
prezime = Prezime;
}
public string PunoIme()
{
return
ime + " "+prezime;
}
public override string ToString()
{
Console.ForegroundColor = ConsoleColor.Yellow;
return ime +" "+prezime;
}
}
}
<file_sep>using System;
namespace Skola
{
internal class Nastavnik:Osoba
{
public Nastavnik(string Ime, string Prezime):base(Ime,Prezime)
{
//base(Ime, Prezime);
//ime = Ime;
//prezime = Prezime;
}
public override string ToString()
{
return base.ToString();
}
internal void predajePredmet(Predmet v)
{
// throw new NotImplementedException();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
namespace Skola
{
internal class Ucenik:Osoba
{
private List<Predmet> UpisaniPredmeti = new List<Predmet>();
private List<Ispit> MojiIspiti = new List<Ispit>();
public double Prosjek {
get
{
double broj=0;
foreach (var item in MojiIspiti)
{
broj += item.Ocjena;
}
broj = broj / MojiIspiti.Count;
return broj;
}
}
public string ProsjekRijecima {
get
{
string text = "nema ocjena";
if (Prosjek<2)
{
text = "nedovoljan";
}
else if(Prosjek<2.5)
{
text = "dovoljan";
}
else if (Prosjek < 3.5)
{
text = "dobar";
}
else if (Prosjek < 4.5)
{
text = "vrlo dobar";
}
else
{
text = "odlican";
}
return text;
}
}
public Ucenik(string Ime, string Prezime) : base(Ime, Prezime)
{
}
internal void upisujePredmet(Predmet p1)
{
UpisaniPredmeti.Add(p1);
}
internal void polazeIspit(Ispit I1)
{
MojiIspiti.Add(I1);
}
//Ovdje ispisi ucenika i njegove predmete i ispite
// <NAME>
// predmeti:
// (1) Matem
// (2) Fiz...
// Ispiti:
// - Matematika (2)
// - Fizika (3)
// Ukupan prosjek: (4.5)
internal string Detalji()
{
string text = "";
text += this.PunoIme()+" \n";
text += "Predmeti:\n";
for (int i = 0; i < UpisaniPredmeti.Count; i++)
{
text += $" ({i}) {UpisaniPredmeti[i]} \n";
}
text += "Ispiti:\n";
foreach (var item in MojiIspiti)
{
text += $" - {item.IspisIspitaZaUcenika()} \n";
}
text += $"Ukupan prosjek je {this.Prosjek} ({this.ProsjekRijecima})";
return text;
}
}
}<file_sep>using System;
namespace _3_klase
{
internal class Pas:Zivotinja
{
public Pas()
{
}
public void Sreca()
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine($"Masem repom");
}
public override string ToString()
{
if (sretan)
{
return "Ja sam pas i ja sam sretan";
}
else
{
return "Ja sam pas i ja nisam sretan";
}
}
internal void Vidi(Macka m1)
{
sretan = true;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace C1tutorial
{
class Rectangle
{// member variables
double length;
double width;
public Rectangle(int v1, int v2)
{
this.length = v1;
this.width = v2;
}
public Rectangle()
{
}
public void Acceptdetails()
{
length = 4.5;
width = 3.5;
}
public double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
Console.WriteLine("Pravokutnik {0} {1} ima površinu u {2} ", length, width, length * width);
Console.WriteLine("Pravokutnik {0} {1} ima opseg u {2} ", length, width, (length + width)*2);
}
}
}
<file_sep>using System;
namespace _3_klase
{
internal class Mis:Zivotinja
{
public Mis()
{
}
public void Sreca()
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine($"Skacem");
}
public override string ToString()
{
if (sretan)
{
return "Ja sam mis i ja sam sretan";
}
else
{
return "Ja sam mis i ja sam uplasen";
}
}
internal void Vidi(Macka m1)
{
sretan = false;
}
}
}<file_sep>using System;
using System.Collections.Generic;
namespace Skola
{
/**
*Klasa skola kreira nove ucenike i nove nastavnike
*Ucenici imaju ime, prezime i...
*Nastavnici imaju ime prezime znaci isto sto i ucenici osim sto imaju ispit
*Program treba raditi ispite*/
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Nastavnik n1=new Nastavnik(Ime:"Filip", Prezime:"Fizic");
Nastavnik n2=new Nastavnik(Ime:"Matko", Prezime:"Matkic");
Predmet p1=new Predmet("Fizika");
Predmet p2=new Predmet("Matematika");
Predmet p3 = new Predmet("Kemija");
Predmet p4 = new Predmet("Hrvatski");
n1.predajePredmet(p1);
Ucenik u1 = new Ucenik(Ime: "Đuro", Prezime: "Đurić");
u1.upisujePredmet(p1);
u1.upisujePredmet(p2);
List<Ispit> ispiti = new List<Ispit>();
ispiti.Add(new Ispit(n1,p1,u1, DateTime.Today, 3));
ispiti.Add(new Ispit(n1, p2, u1, DateTime.Today, 2));
ispiti.Add(new Ispit(n1, p3, u1, DateTime.Today, 5));
ispiti.Add(new Ispit(n1, p4, u1, DateTime.Today, 5));
//Ispisujemo svaki clan liste ispiti kao item
foreach (var item in ispiti)
{
Console.WriteLine(item);
}
//Ovdje ispisi ucenika i njegove predmete i ispite
// Pero Peric
// predmeti:
// (1) Matem
// (2) Fiz...
// Ispiti:
// - Matematika (2)
// - Fizika (3)
Console.WriteLine(u1.Detalji());
// ovdje ispisi nastavnika i njegove predmete
}
}
}
<file_sep>using System;
namespace _1_osnovne_operacije
{
class Program
{
static void Main(string[] args)
{
int broj1, broj2;
Console.WriteLine("Unesi 2 broja!");
broj1 = int.Parse(Console.ReadLine());
broj2 = int.Parse(Console.ReadLine());
Console.WriteLine($"zbroj: {broj1}+{broj2} jednako je {zbroj(broj1, broj2)}");
Console.WriteLine($"razlika: {broj1}-{broj2} jednako je {razlika(broj1, broj2)}");
Console.WriteLine($"umn: {broj1}*{broj2} jednako je {umn(broj1, broj2)}");
Console.WriteLine($"kolicnik: {broj1}*{broj2} jednako je {kolicnik(broj1, broj2)}");
}
private static double kolicnik(int broj1, int broj2)
{
return (double)broj1 / broj2;
}
private static int umn(int broj1, int broj2)
{
return broj1 * broj2;
}
private static object zbroj(int b1,int b2)
{
return b1 + b2;
}
static int razlika(int b1,int br2)
{
return b1 - br2;
}
}
}
<file_sep>using System;
namespace _3_klase
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Ovo su psi i macke!");
Macka m1 = new Macka();
m1.Zvuk = "Mjauuuuu";
m1.GlasajSe();
Pas p1 = new Pas();
p1.GlasajSe();
p1.Zvuk = "Vau vau";
p1.GlasajSe();
Macka[] Katzen= new Macka[5];//0-4
for (int i = 0; i < Katzen.Length ; i++)
{
Katzen[i] = m1;
}
foreach (var item in Katzen)
{
item.GlasajSe();
}
m1.Sreca();
p1.Sreca();
p1.Vidi(m1);
Console.WriteLine(p1);
Pas p2 = new Pas();
Console.WriteLine(p2);
m1.Vidi(p1);
Console.WriteLine(m1);
Mis misko = new Mis();
misko.Vidi(m1);
Console.WriteLine(misko);
m1.Vidi(misko);
Console.WriteLine(m1);
}
}
}
<file_sep>using System;
namespace Skola
{
internal class Ispit
{
private Nastavnik n;
private Predmet p;
private Ucenik u;
private DateTime today;
private int ocjena;
public int Ocjena { get => ocjena; set => ocjena = value; }
public Ispit(Nastavnik n, Predmet p, Ucenik u, DateTime today, int ocjena)
{
this.n = n;
this.p = p;
this.u = u;
this.today = today;
this.Ocjena = ocjena;
u.polazeIspit(this);
}
public override string ToString()
{
return $"Ispit iz {p} je polagao ucenik {u} kod nastavnika {n} datuma {today}";
}
public string IspisIspitaZaUcenika()
{
return $"{p} je polozena kod nastavnika {n} datuma {today} ocjena je {Ocjena}";
}
}
}<file_sep>using System;
namespace C1tutorial
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Rectangle r2 = new Rectangle(2, 5);
r2.Display();
}
}
}
<file_sep>namespace Skola
{
internal class Predmet
{
private string naziv;
public Predmet(string naziv)
{
this.Naziv = naziv;
}
public string Naziv { get => naziv; set => naziv = value; }
public override string ToString()
{
return Naziv;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace _3_klase
{
class Macka : Zivotinja
{
public override string ToString()
{
if (sretan)
{
return "Ja sam macka i ja sam sretna";
}
else
{
return "Ja sam macka i ja nisam sretna";
}
}
internal void Sreca()
{
Console.WriteLine($"Predem");
}
internal void Vidi(Pas p1)
{
sretan = false;
}
internal void Vidi(Mis misko)
{
sretan = true;
}
}
}
|
e795ebabd0aa19eac4e75715239784b0d4ba1b8f
|
[
"C#"
] | 15
|
C#
|
PatrikMrvic/C1
|
cccda8569c08a0b75f24c4229b13c23a57042811
|
dace4120651e20a2f28ccb15ef446796008e4eb5
|
refs/heads/main
|
<file_sep>/**
* A ping pong bot, whenever you send "ping", it replies "pong".
*/
// Import the discord.js module
const Discord = require('discord.js');
// Create an instance of a Discord client
const client = new Discord.Client();
/**
* The ready event is vital, it means that only _after_ this will your bot start reacting to information
* received from Discord
*/
client.on('ready', () => {
console.log('I am ready!');
});
//hi guys welcome back to another video in this video we well do dm command
//like and sub):
client.on('message', badboy => {
if(badboy.content.startsWith("dm")){
var user = badboy.mentions.users.first();
if(!user) return badboy.channel.send("Mention The User")
if(user.id === badboy.author.id) return badboy.channel.send("wow")
var args = badboy.content.split(" ").slice(2).join(" ")
if(!args) return badboy.channel.send("MSG??")
user.send(`${args}`).catch(err => {
return
})
badboy.channel.send("Done")
}
})
//my channel : https://www.youtube.com/channel/UCLE3ohDKmUQjBYSJeLetDxQ
https://youtu.be/AYC3nUBrohE
// Log our bot in using the token from
client.login('your token here');
<file_sep># DM-BOT.
|
488b5bd4f1c1ec9a58966d0e98e86e8a1ac418e7
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
antor940/DM-BOT.
|
fe8e9d9f5084ba90a98bae72dccd7f39f7230e3b
|
6181066efa7469a1b8e89e4800399c0d7a6d94cc
|
refs/heads/master
|
<file_sep># make a change so as to do another commit
print "Hello, World!"
|
aa93a4e9f3a39e7dced533d9bd2b51569c9415b7
|
[
"Python"
] | 1
|
Python
|
heintzcode/HelloWorld
|
301b0b424d65a8a728dd905bad5f81f2f010aa88
|
10b4f447fa37dd25309293aa41cf39af840cbd88
|
refs/heads/master
|
<file_sep>""" Development settings and globals."""
from os.path import join, normpath
from base import *
class Local(Common):
########## INSTALLED_APPS
INSTALLED_APPS = Common.INSTALLED_APPS
########## END INSTALLED_APPS
########## DEBUG
# See: https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = values.BooleanValue(True)
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug
TEMPLATE_DEBUG = DEBUG
########## END DEBUG
########## Mail settings
#EMAIL_HOST = "localhost"
#EMAIL_PORT = 1025
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = '***<EMAIL>'
EMAIL_HOST_PASSWORD = '***'
########## End mail settings
########## DATABASE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = values.DatabaseURLValue('postgres://Kevin@localhost/cutter_repo')
########## END DATABASE CONFIGURATION
########## CACHING
# Do this here because thanks to django-pylibmc-sasl and pylibmc memcacheify is painful to install on windows.
# memcacheify is what's used in Production
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': ''
}
}
########## END CACHING
########## STATIC FILE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root
STATIC_ROOT = 'staticfiles'
#STATIC_ROOT = normpath(join(SITE_ROOT, 'static'))
# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url
STATIC_URL = '/static/'
# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS
STATICFILES_DIRS = (
join(BASE_DIR, 'static'),
)
# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
########## END STATIC FILE CONFIGURATION
########## django-debug-toolbar
MIDDLEWARE_CLASSES = Common.MIDDLEWARE_CLASSES + ('debug_toolbar.middleware.DebugToolbarMiddleware',)
INSTALLED_APPS += (
'debug_toolbar',
)
INTERNAL_IPS = ('127.0.0.1',)
DEBUG_TOOLBAR_CONFIG = {
'INTERCEPT_REDIRECTS': False,
'SHOW_TEMPLATE_CONTEXT': True,
}
########## end django-debug-toolbar
<file_sep>CookieCutter
============
CookieCutter
|
d33efbee5c8781f46997d6f0478946c2350106bc
|
[
"Markdown",
"Python"
] | 2
|
Python
|
maninmotion/cutter
|
cddf7fb19bf84ca20f28d85173ca85a0f70cdef1
|
7b65b2330b73954d7f81c2b4ef83014ec5c0ad02
|
refs/heads/master
|
<file_sep>import Utils from './../../services/Utils.js'
import * as DBGet from './../../services/DBGet.js'
let PlaylistEdit = {
render : async () => {
let request = Utils.parseRequestURL()
let query = request.id;
return /*html*/`
<section class="playlist-page-section">
<h1 class="playlist-edit-title">Playlist editing</h1>
<div class="playlist-head-div">
<div>
<div class="playlist-page-image-div">
<img id="img-playlist-on-page" class="playlist-page-image" src="" alt="Cover"></img>
</div>
<input type="file" name="file" accept=".png" value="upload" id="upload-file-button" />
<label class="picure-upload btn-red" for="upload-file-button">Choose picture</label>
</div>
<div class="playlist-page-info-div">
<input id="playlist-name-input-id" class="playlists-edit-name">
<input id="playlist-desc-input-id" class="playlists-edit-description">
<p id="playlist-author-id" class="playlist-page-author">Created by:</p>
</div>
<button class="btn-red" id="playlist-delete-button">Delete</button>
<button class="btn-red" id="playlist-save-button">Save</button>
</div>
<div class="playlist-items">
<ol id="playlist-songs-list" class="playlist-ol"></ol>
</div>
</section>
<section class = "search-results-section">
<h2 id="section-search-h2" class="sections-text" id="genres-title">Search songs to add...</h2>
<input id="playlist-search-input" size="40" placeholder ="Search">
<ul id="search-results-ol" class="playlist-ol"></ul>
</section>
`
}
, after_render: async () => {
let request = Utils.parseRequestURL()
let playlistId = decodeURIComponent(request.id);
const h1 = document.getElementById('playlist-name-input-id');
const desc = document.getElementById('playlist-desc-input-id');
const plaAuthor = document.getElementById('playlist-author-id');
const pic = document.getElementById('img-playlist-on-page');
//const editButton = document.getElementById('playlist-edit-button');
const searchContainer = document.getElementById('search-results-ol');
const searchInput = document.getElementById('playlist-search-input');
const saveButton = document.getElementById('playlist-save-button');
const deleteButton = document.getElementById('playlist-delete-button');
const uploadPic = document.getElementById('upload-file-button');
let createdBy;
let snapshot = await firebase.database().ref('/playlists/' + playlistId);
snapshot.on("value", async function(snapshot) {
let playlist = snapshot.val();
h1.value = playlist.name;
desc.value = playlist.desc;
plaAuthor.innerHTML = "Created by: " + playlist.created;
createdBy = playlist.created;
let picUrl1 = await DBGet.getImagePlaylist(playlist.pic_id);
pic.src = picUrl1;
});
saveButton.addEventListener("click",async function(e) {
firebase.database().ref('/playlists/' + playlistId + "/name").set(h1.value);
firebase.database().ref('/playlists/' + playlistId + "/desc").set(desc.value);
document.location.href ="/#/playlist/" + playlistId;
});
deleteButton.addEventListener("click",async function(e){
firebase.database().ref('/playlists/' + playlistId).remove();
document.location.href ="/#/";
});
const songsContainer = document.getElementById('playlist-songs-list');
async function updatePlaylistSongs(){
songsContainer.innerHTML = "";
snapshot = await firebase.database().ref('/playlists/' + playlistId + '/song_list');
snapshot.on("value", async function(snapshot) {
let idList = snapshot.val();
console.log(idList);
//idList.forEach(async function(itemRef){
songsContainer.innerHTML = "";
if (idList){
for(const [index,itemRef] of idList.entries()){
if (!itemRef)continue;
let songId = itemRef.id;
let songSnapshot = await firebase.database().ref('/songs/' + songId).once('value');
let song = songSnapshot.val();
let picUrl2 = await DBGet.getImageSong(song.pic_id);
let playlistLI = document.createElement('LI');
playlistLI.className = 'playlist-song-item';
//playlistLI.id = index;
playlistLI.innerHTML = `
<div class="song-div">
<div class="image-song-div">
<button class="image-song-a" href="#">
<img class="image-song" src=${picUrl2} alt="Cover"/>
<div class="middle">
<img id="${songId}" class="song-play-image" src="icon/Play.png" alt="Cover"/>
</div>
</button>
</div>
<p class="song-name">${song.name}</p>
<a class="song-author" href="/#/artist/${song.author}">${song.author}</a>
</div>
<div class="duration-div">
<button class="btn-red" id="${index}">X</button>
<p class="duration">2:22</p>
</div>
`;
songsContainer.appendChild(playlistLI);
console.log(song.author);
}
}//);
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
}
function pushSongId(id) {
firebase.database().ref('/playlists/' + playlistId + "/song_id").set(id);
}
await updatePlaylistSongs();
songsContainer.addEventListener("click",async function(e) {
console.log(e.target.nodeName);
if(e.target && e.target.nodeName == "BUTTON") {
console.log(e.target.id);
firebase.database().ref('/playlists/' + playlistId + "/song_list/" + e.target.id).remove();
}
});
searchContainer.addEventListener("click",async function(e) {
console.log(e.target.nodeName);
event.preventDefault();
if(e.target && e.target.nodeName == "LI") {
console.log(e.target.id + " was clicked");
const snapshot = await firebase.database().ref('/playlists/' + playlistId + "/song_id").once('value');
const lastSongId = snapshot.val();
pushSongId(lastSongId + 1);
firebase.database().ref('/playlists/' + playlistId + "/song_list/" + lastSongId).set({
id : e.target.id
}, function(error) {
if (error) {
alert(error.message);
}
});
console.log("UPDATE")
//await updatePlaylistSongs();
}
});
searchInput.addEventListener('keyup',async function(event) {
let query = searchInput.value.toLowerCase();
const snapshot = await firebase.database().ref('/songs');
snapshot.on("value", async function(snapshot) {
let songsList = snapshot.val();
searchContainer.innerHTML = "";
songsList.forEach(async function(itemRef, index){
if (itemRef.name.toLowerCase().includes(query) || itemRef.author.toLowerCase().includes(query)){
const picUrl = await DBGet.getImageSong(itemRef.pic_id);
let songLI = document.createElement('LI');
songLI.className = 'playlist-song-item';
songLI.id = index;
songLI.innerHTML = `<div class="song-div">
<div class="image-song-div">
<button class="image-song-a" href="#">
<img class="image-song" src=${picUrl} alt="Cover"/>
<div class="middle">
<img id="${index}"class="song-play-image" src="icon/Play.png" alt="Cover"/>
</div>
</button>
</div>
<p class="song-name">${itemRef.name}</p>
<a class="song-author" href="/#/artist/${itemRef.author}">${itemRef.author}</a>
</div>
<div class="duration-div">
<p class="duration">2:22</p>
</div>
`;
searchContainer.appendChild(songLI);
}
});
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
});
songsContainer.addEventListener("click",async function(e) {
console.log(e.target.nodeName);
if(e.target && e.target.nodeName == "IMG") {
console.log(e.target.id);
if (firebase.auth().currentUser){
DBGet.pushPlaylist(firebase.auth().currentUser.email, [e.target.id]);
}else{
alert("Login first.")
}
//firebase.database().ref('/playlists/' + playlistId + "/song_list/" + e.target.id).remove();
}
});
searchContainer.addEventListener("click",async function(e) {
console.log(e.target.nodeName);
if(e.target && e.target.nodeName == "IMG") {
console.log(e.target.id);
if (firebase.auth().currentUser){
DBGet.pushPlaylist(firebase.auth().currentUser.email, [e.target.id]);
}else{
alert("Login first.")
}
//firebase.database().ref('/playlists/' + playlistId + "/song_list/" + e.target.id).remove();
}
});
uploadPic.addEventListener('change', async (event) => {
let file = event.target.files[0];
let storageRef = firebase.storage().ref('playlist_pic/idp' + playlistId + '.png');
await storageRef.put(file);
firebase.database().ref('/playlists/' + playlistId + '/pic_id').set("p" + playlistId);
let picUrl1 = await DBGet.getImagePlaylist("p" + playlistId);
pic.src = picUrl1;
});
}
}
export default PlaylistEdit;<file_sep>import * as DBGet from './../../services/DBGet.js'
let Upload = {
render : async () => {
let view = /*html*/
`
<section id="upload-page-section">
<h2 class="sections-text" >Track uploading</h2>
<p class="description-text">Upload your own track, add name and author, so all users can listen it!</p>
<label for="name-input" class="upload-helper">Name</label>
<input id="name-input" class="upload-input">
<label for="author-input" class="upload-helper">Author</label>
<input id="author-input" class="upload-input">
<div class="upload-file-div">
<label class="btn-light-red" id="upload-file-button-label">Select file
<input type='file' accept=".mp3" value="upload" id="upload-file-button">
</label>
<p id="file-name" class="upload-link"></p>
</div>
<div class="upload-file-div">
<label class="btn-light-red" id="upload-img-button-label">Select cover
<input type='file' accept=".png" value="upload" id="upload-image-button">
</label>
<p id="file-img-name" class="upload-link"></p>
</div>
<p id="upload-second-p" class="description-text">Select genre</p>
<ul id=genre-selection>
<li class="genre-selector-div">
<input type="radio" name="genre-radio" value="rock" class="genre-selector-checkbox" id="genre-selector-checkbox1">
<label for="genre-selector-checkbox1" class="genre-selector-label">Rock</label>
</li>
<li class="genre-selector-div">
<input type="radio" name="genre-radio" value="punk" class="genre-selector-checkbox" id="genre-selector-checkbox2">
<label for="genre-selector-checkbox2" class="genre-selector-label">Punk</label>
</li>
<li class="genre-selector-div">
<input type="radio" name="genre-radio" value="classic" class="genre-selector-checkbox" id="genre-selector-checkbox3">
<label for="genre-selector-checkbox3" class="genre-selector-label">Classic</label>
</li>
<li class="genre-selector-div">
<input type="radio" name="genre-radio" value="pop" class="genre-selector-checkbox" id="genre-selector-checkbox4">
<label for="genre-selector-checkbox4" class="genre-selector-label">Pop</label>
</li>
<li class="genre-selector-div">
<input type="radio" name="genre-radio" value="jazz" class="genre-selector-checkbox" id="genre-selector-checkbox5">
<label for="genre-selector-checkbox5" class="genre-selector-label">Jazz</label>
</li>
<li class="genre-selector-div">
<input type="radio" name="genre-radio" value="electro" class="genre-selector-checkbox" id="genre-selector-checkbox6">
<label for="genre-selector-checkbox6" class="genre-selector-label">Electro</label>
</li>
<li class="genre-selector-div">
<input type="radio" name="genre-radio" value="rap and hip-hop" class="genre-selector-checkbox" id="genre-selector-checkbox7">
<label for="genre-selector-checkbox7" class="genre-selector-label">Rap and Hip-Hop</label>
</li>
</ul>
<button id="upload-button" class="btn-red">Upload</button>
</section>
`
return view
}
, after_render: async () => {
//console.log("sosoi");
const fileButton = document.getElementById('upload-file-button');
const pictureButton = document.getElementById('upload-image-button');
const uploadButton = document.getElementById('upload-button');
const fileName = document.getElementById('file-name');
const pictureName = document.getElementById('file-img-name');
const nameInput = document.getElementById('name-input');
const authorInput = document.getElementById('author-input');
const songId = await DBGet.getSongId();
const picId = await DBGet.getPicId();
function pushSongId(id) {
firebase.database().ref('/song_id').set({ id });
}
function pushPicId(id) {
firebase.database().ref('/song_pic_id').set({ id });
}
let file = null;
let picture = null;
fileButton.addEventListener('change', (event) => {
file = event.target.files[0];
fileName.innerHTML = file.name;
});
pictureButton.addEventListener('change', (event) => {
picture = event.target.files[0];
pictureName.innerHTML = picture.name;
});
uploadButton.addEventListener('click', e=>{
if (!nameInput.value || !authorInput.value){
alert("All fields must be provided!");
}else if (file){
let storageRef = firebase.storage().ref('mp3/id' + songId + '.mp3');
storageRef.put(file);
pushSongId(songId + 1);
let thisPicId = 0;
if (picture){
let storageRef = firebase.storage().ref('song_pic/ids' + picId + '.png');
storageRef.put(picture);
pushPicId(picId + 1);
thisPicId = picId;
}
const rbs = document.querySelectorAll('input[name="genre-radio"]');
let selectedValue = 'none';
for (const rb of rbs) {
if (rb.checked) {
selectedValue = rb.value;
break;
}
}
console.log(selectedValue);
firebase.database().ref('songs/' + songId).set({
name: nameInput.value,
author: authorInput.value,
id_mp3: songId,
pic_id: ("s" + thisPicId),
genre: selectedValue
}, function(error) {
if (error) {
alert(error.message);
} else {
console.log('data saved succsessfully!');
}
});
document.location.href = "/#/";
} else {
alert("No file selected..");
}
});
}
}
export default Upload;<file_sep>import * as DBGet from './../../services/DBGet.js'
//import * as Player from './../../services/Player.js'
let Home = {
render : async () => {
let view = /*html*/
`
<main id="main-container">
<nav class="navigation-container">
<h1 id="navigation-title">Home</h1>
<div id="navigation">
<a id="playlists-nav" class="navigation-ref hide" href="#playlists-title">Playlists</a>
<a id="releases" class="navigation-ref" href="#releases-title">releases</a>
<a class="navigation-ref" href="#chart-title">Chart</a>
<a class="navigation-ref" href="#genres-title">Genres</a>
<a class="navigation-ref" href="#artitsts-title">Artists</a>
<a id="upload-nav" class="navigation-ref hide" href="#artitsts-title">Upload</a>
</div>
</nav>
<div id="my-playlists-id" class = "hide">
<section class="playlist-container">
<h2 class="sections-text" id="playlists-title">Your playlists</h2>
<p class="description-text">Create your own playlists</p>
<div class="playlists-div">
<ul id="user-playlists" class="playlists-list">
<li class="playlist-list-item">
<div class="playlist-div">
<a id="new-playlist-link" href="/#/playlistnew">
<img class="add-playlist-image" src="icon/Add.png" alt="Cover"></img>
<div class="playlist-middle-image">
<img class="playlist-play-image" src="icon/Add.png" alt="Cover"/>
</div>
</a>
</div>
<p class="playlist-name">New playlist</p>
</li>
</ul>
</div>
</section>
</div>
<section class="releases-container">
<h2 class="sections-text" id="releases-title">New releases</h2>
<div class="description-text">The most popular releases, albums and mixes </div>
<div id="releases-ul-div" class="playlists-div">
<ul class="playlists-list"></ul>
</div>
</section>
<section class="chart-container">
<h2 class="sections-text" id="chart-title">Chart</h2>
<div class="description-text">
Top 15 most popular songs of last week
</div>
<div>
<ul class="chart-items" id="chart-cont"></ul>
</div>
</section>
<section class="genres-container">
<h2 class="sections-text" id="genres-title">Genres</h2>
<div class="description-text">Select some genres and we will try to find </div>
<ul id=genre-selection>
<li class="genre-selector-div">
<input type="checkbox" class="genre-selector-checkbox" id="genre-selector-checkbox1" value="rock">
<label for="genre-selector-checkbox1" class="genre-selector-label">Rock</label>
</li>
<li class="genre-selector-div">
<input type="checkbox" class="genre-selector-checkbox" id="genre-selector-checkbox2" value="punk">
<label for="genre-selector-checkbox2" class="genre-selector-label">Punk</label>
</li>
<li class="genre-selector-div">
<input type="checkbox" class="genre-selector-checkbox" id="genre-selector-checkbox3" value="classic">
<label for="genre-selector-checkbox3" class="genre-selector-label">Classic</label>
</li>
<li class="genre-selector-div">
<input type="checkbox" class="genre-selector-checkbox" id="genre-selector-checkbox4" value="pop">
<label for="genre-selector-checkbox4" class="genre-selector-label">Pop</label>
</li>
<li class="genre-selector-div">
<input type="checkbox" class="genre-selector-checkbox" id="genre-selector-checkbox5" value="jazz">
<label for="genre-selector-checkbox5" class="genre-selector-label">Jazz</label>
</li>
<li class="genre-selector-div">
<input type="checkbox" class="genre-selector-checkbox" id="genre-selector-checkbox6" value="electro">
<label for="genre-selector-checkbox6" class="genre-selector-label">Electro</label>
</li>
<li class="genre-selector-div">
<input type="checkbox" class="genre-selector-checkbox" id="genre-selector-checkbox7" value="rap and hip-hop">
<label for="genre-selector-checkbox7" class="genre-selector-label">Rap and Hip-Hop</label>
</li>
</ul>
<button id="genres-select-button" class="btn-red">Find</button>
<div>
<ul class="chart-items" id="search-genre-cont"></ul>
</div>
</section>
<section class="artists-container">
<h2 class="sections-text" id="artitsts-title">Artists</h2>
<div class="description-text">
Most popular artitsts
</div>
<ul id="artist-list-id" class="artists-list"></ul>
</section>
<div id="upload-container-id" class="hide">
<section class="upload-container">
<h2 class="sections-text" id="genres-title">Upload</h2>
<div class="description-text">Did not find what you want? Fine. Upload any song you want...</div>
<a href="/#/upload" id="upload-main-button" class="btn-red">Upload</a>
</section>
</div>
</main>
`
return view
}
, after_render: async () => {
const chartContainer = document.getElementById('chart-cont');
const uploadSection = document.getElementById('upload-container-id');
const playlistSection = document.getElementById('my-playlists-id');
const uploadnav = document.getElementById('upload-nav');
const playlistnav = document.getElementById('playlists-nav');
const releasesList = document.getElementById('releases-ul-div');
const artistList = document.getElementById('artist-list-id');
const genresFindButton = document.getElementById('genres-select-button');
const genresContainer = document.getElementById('search-genre-cont');
const songs = await DBGet.getChart();
const playlistsChart = await DBGet.getPlaylistsChart();
let playlists = await DBGet.getPlaylists();
const artists = await DBGet.getArtistsChart();
let user = "";
firebase.auth().onAuthStateChanged(firebaseUser => {
if (firebaseUser){
uploadSection.classList.remove('hide');
playlistSection.classList.remove('hide');
uploadnav.classList.remove('hide');
playlistnav.classList.remove('hide');
user = firebaseUser.email;
}else{
uploadSection.classList.add('hide');
playlistSection.classList.add('hide');
uploadnav.classList.add('hide');
playlistnav.classList.add('hide');
}
});
const userPlaylists = document.getElementById('user-playlists');
if(playlists && firebase.auth().currentUser){
for(let [index,playlist] of playlists.entries()){
if (!playlist)continue;
if (playlist.created != firebase.auth().currentUser.email)continue;
const picUrl = await DBGet.getImagePlaylist(playlist.pic_id);
let playlistLI = document.createElement('LI');
playlistLI.className = 'playlist-list-item';
playlistLI.innerHTML = `
<div class="playlist-div">
<button class="playlist-play">
<img class="add-playlist-image" src=${picUrl} alt="Cover"></img>
<div class="playlist-middle-image">
<img id="${index}" class="playlist-play-image" src="icon/Play.png" alt="Cover"/>
</div>
</button>
</div>
<a class="playlist-name-link" href="/#/playlist/${index}">${playlist.name}</a>
<p class="playlist-description">${playlist.desc}</p>
`;
userPlaylists.appendChild(playlistLI);
}
}
if (playlistsChart){
playlistsChart.forEach(async function(playlistRef){
const playlistId = playlistRef.id;
const snapshot = await firebase.database().ref('/playlists/' + playlistId).once('value');
const playlist = snapshot.val();
const picUrl = await DBGet.getImagePlaylist(playlist.pic_id);
let playlistLI = document.createElement('LI');
playlistLI.className = 'playlist-list-item';
playlistLI.innerHTML = `
<div class="playlist-div">
<button class="playlist-play">
<img class="add-playlist-image" src=${picUrl} alt="Cover"></img>
<div class="playlist-middle-image">
<img id="${playlistId}" class="playlist-play-image" src="icon/Play.png" alt="Cover"/>
</div>
</button>
</div>
<a class="playlist-name-link" href="/#/playlist/${playlistId}">${playlist.name}</a>
<p class="playlist-description">${playlist.desc}</p>
`;
releasesList.appendChild(playlistLI);
});
}
if (artists){
artists.forEach(async function(artistRef){
const snapshot = await firebase.database().ref('/artists/' + artistRef.id).once('value');
const artist = snapshot.val();
const picUrl = await DBGet.getImageArtist(artist.pic_id);
let artistLI = document.createElement('LI');
artistLI.className = 'artist-list-item';
artistLI.innerHTML = `
<div class="artist-image-div">
<a class="artist-link-image">
<img class="artist-image" src=${picUrl} alt="Cover"/>
</a>
</div>
<a class="artist-text" href="/#/artist/${encodeURIComponent(artist.name)}">${artist.name}</a>
`
artistList.appendChild(artistLI);
});
}
if (songs){
let i = 1;
for(const songRef of songs){
if(!songRef)continue;
const songId = songRef.id;
const snapshot = await firebase.database().ref('/songs/' + songId).once('value');
const song = snapshot.val();
const picUrl = await DBGet.getImageSong(song.pic_id);
let songLI = document.createElement('LI');
songLI.className = 'song-item';
songLI.innerHTML = ` <p class="chart-position-text">${i}</p>
<div class="image-song-div">
<button class="image-song-a">
<img class="image-song" src=${picUrl} alt="Cover"/>
<div class="middle">
<img id="${songId}" class="song-play-image" src="icon/Play.png" alt="Cover"/>
</div>
</button>
</div>
<p class="song-name">${song.name}</p>
<a class="song-author" href="/#/artist/${encodeURIComponent(song.author)}">${song.author}</a>`;
chartContainer.appendChild(songLI);
i = i + 1;
};
}
chartContainer.addEventListener("click",async function(e) {
console.log(e.target.nodeName);
if(e.target && e.target.nodeName == "IMG") {
console.log(e.target.id);
if (firebase.auth().currentUser){
DBGet.pushPlaylist(firebase.auth().currentUser.email, [e.target.id]);
}else{
alert("Login first.")
}
}
});
releasesList.addEventListener("click",async function(e) {
console.log(e.target.nodeName);
if(e.target && e.target.nodeName == "IMG") {
console.log(e.target.id);
if (firebase.auth().currentUser){
let list = await DBGet.getPlaylistList(e.target.id);
DBGet.pushPlaylist(firebase.auth().currentUser.email, list);
}else{
alert("Login first.")
}
}
});
userPlaylists.addEventListener("click",async function(e) {
console.log(e.target.nodeName);
if(e.target && e.target.nodeName == "IMG") {
console.log(e.target.id);
if (firebase.auth().currentUser){
let list = await DBGet.getPlaylistList(e.target.id);
DBGet.pushPlaylist(firebase.auth().currentUser.email, list);
}else{
alert("Login first.")
}
}
});
genresFindButton.addEventListener("click",async function(e) {
genresContainer.innerHTML = "";
var checkedValues = [];
var inputElements = document.getElementsByClassName('genre-selector-checkbox');
for(let checkBox of inputElements){
if(checkBox.checked){
checkedValues.push(checkBox.value);
console.log(checkBox.value)
}
}
const snapshot = await firebase.database().ref('/songs').once('value');
const songsList = snapshot.val();
let i = 1;
for(let [index,song] of songsList.entries()){
if (!song) continue;
if (checkedValues.includes(song.genre)){
console.log(song.name);
const picUrl = await DBGet.getImageSong(song.pic_id);
let songLI = document.createElement('LI');
songLI.className = 'song-item';
songLI.innerHTML = `
<div class="image-song-div">
<button class="image-song-a">
<img class="image-song" src=${picUrl} alt="Cover"/>
<div class="middle">
<img id="${index}" class="song-play-image" src="icon/Play.png" alt="Cover"/>
</div>
</button>
</div>
<p class="song-name">${song.name}</p>
<a class="song-author" href="/#/artist/${encodeURIComponent(song.author)}">${song.author}</a>`;
genresContainer.appendChild(songLI);
i = i + 1;
if (i==16)break;
}
}
});
genresContainer.addEventListener("click",async function(e) {
console.log(e.target.nodeName);
if(e.target && e.target.nodeName == "IMG") {
console.log(e.target.id);
if (firebase.auth().currentUser){
DBGet.pushPlaylist(firebase.auth().currentUser.email, [e.target.id]);
}else{
alert("Login first.")
}
}
});
}
}
export default Home;
<file_sep>import * as DBGet from './../../services/DBGet.js'
let Register = {
render: async () => {
return /*html*/ `
<section class="auth-section">
<div class="auth-backPage"></div>
<form class="auth-form">
<div class="auth-title">Registration</div>
<p class="auth-description">One simple step to Yoptify! </p>
<input id="email_input" class="auth-input" type="text" placeholder="Email" size="34">
<input id="pass_input" class="auth-input" type="password" placeholder="<PASSWORD>">
<input id="repeat_pass_input" class="auth-input" type="<PASSWORD>" placeholder="<PASSWORD>">
<button id="login-btn" class="btn-red">Register</button>
</form>
</section>
`
}
, after_render: async () => {
document.getElementById("login-btn").addEventListener ("click", () => {
event.preventDefault();
const email = document.getElementById("email_input");
const pass = document.getElementById("pass_input");
const repeatPass = document.getElementById("repeat_pass_input");
if (pass.value != repeatPass.value) {
alert (`The passwords dont match`)
} else if (email.value =='' | pass.value == '' | repeatPass == '') {
alert (`The fields cannot be empty`)
} else {
const auth = firebase.auth();
const promise = auth.createUserWithEmailAndPassword(email.value, pass.value);
promise
.then(async function(regUser){
let lastUser = await DBGet.getUserId();
await firebase.database().ref("/play_queue/" + lastUser).set({ user : email.value});
await firebase.database().ref('/user_count/id').set(lastUser + 1);
window.location.href = '/#/';
})
.catch(alert(e.message));
}
})
}
}
export default Register;<file_sep>let Bottombar = {
render: async () => {
let view = /*html*/`
<footer id="footer-div">
<nav id="footer-nav">
<p class="get-back-title">Get back</p>
<ul class="get-back-list">
<li class="get-back-list-item"><a class="get-back-link" href="#playlists-title">Playlists</a></li>
<li class="get-back-list-item"><a class="get-back-link" href="#releases-title">New releases</a></li>
<li class="get-back-list-item"><a class="get-back-link" href="#chart-title">Chart</a></li>
<li class="get-back-list-item"><a class="get-back-link" href="/#genres-title">Genres</a></li>
<li class="get-back-list-item"><a class="get-back-link" href="#artitsts-title">Artists</a></li>
</ul>
</nav>
<div id="credits-div">
<a class="send-bugs-link" href="https://vk.com/emoseptember">Bug report</a>
<p class="credits">@September 2020</p>
</div>
</footer>
`
return view
},
after_render: async () => { }
}
export default Bottombar;<file_sep>import Utils from './../../services/Utils.js'
import * as DBGet from './../../services/DBGet.js'
let Artist = {
render : async () => {
let request = Utils.parseRequestURL()
let query = request.id;
return /*html*/`
<section class = "search-results-section">
<div id="artist-info-head">
<img id="img-artist-on-page" class="img-artist-page" src="" alt="Cover">
<div>
<h2 id="section-artist-h2" class="sections-text"></h2>
<div id="section-artist-desc" class="description-text">Artist</div>
</div>
</div>
<ol id="search-results-ol" class="playlist-ol"></ol>
</section>
`
}
, after_render: async () => {
let request = Utils.parseRequestURL()
let query = decodeURIComponent(request.id);
const h2 = document.getElementById('section-artist-h2');
const pic = document.getElementById('img-artist-on-page');
let artistRealName = query;
let picUrl = await DBGet.getImageArtist("a0");
pic.src = picUrl;
let snapshot = await firebase.database().ref('/artists');
snapshot.on("value", async function(snapshot) {
let artistsList = snapshot.val();
artistsList.forEach(async function(artist){
console.log(artist.name.toLowerCase());
if (artist.name.toLowerCase() === query.toLowerCase()){
h2.innerHTML = artist.name;
let picUrl1 = await DBGet.getImageArtist(artist.pic_id);
pic.src = picUrl1;
}
});
});
const searchContainer = document.getElementById('search-results-ol');
snapshot = await firebase.database().ref('/songs');
snapshot.on("value", async function(snapshot) {
let songsList = snapshot.val();
songsList.forEach(async function(itemRef, index){
if (itemRef.author.toLowerCase().includes(query.toLowerCase())){
const picUrl = await DBGet.getImageSong(itemRef.pic_id);
let songLI = document.createElement('LI');
songLI.className = 'playlist-song-item';
songLI.innerHTML = `<div class="song-div">
<div class="image-song-div">
<button class="image-song-a" href="#"><img class="image-song" src=${picUrl} alt="Cover"/>
<div class="middle">
<img id="${index}" class="song-play-image" src="icon/Play.png" alt="Cover"/>
</div>
</button>
</div>
<p class="song-name">${itemRef.name}</p>
<a class="song-author" href="#">${itemRef.author}</a>
</div>
<div class="duration-div">
<p class="duration">2:22</p>
</div>
`;
searchContainer.appendChild(songLI);
}
console.log(itemRef.author);
});
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
searchContainer.addEventListener("click",async function(e) {
console.log(e.target.nodeName);
if(e.target && e.target.nodeName == "IMG") {
console.log(e.target.id);
if (firebase.auth().currentUser){
DBGet.pushPlaylist(firebase.auth().currentUser.email, [e.target.id]);
}else{
alert("Login first.")
}
//firebase.database().ref('/playlists/' + playlistId + "/song_list/" + e.target.id).remove();
}
});
}
}
export default Artist;<file_sep>import Utils from './../../services/Utils.js'
import * as DBGet from './../../services/DBGet.js'
let Playlist = {
render : async () => {
let request = Utils.parseRequestURL()
let query = request.id;
return /*html*/`
<section class="playlist-page-section">
<div class="playlist-head-div">
<div class="playlist-page-image-div">
<button id="play-me" class="playlist-page-play">
<img id="img-playlist-on-page" class="playlist-page-image" src="" alt="Cover"></img>
<div class="playlist-page-middle-image">
<img class="playlist-page-play-image" src="icon/Play.png" alt="Cover"/>
</div>
</button>
</div>
<div class="playlist-page-info-div">
<h1 id="playlist-name-id" class="playlist-page-name">Playlist_Name</h1>
<p id="playlist-desc-id" class="playlist-page-description">Playlist_Description</p>
<p id="playlist-author-id" class="playlist-page-author">Created by:</p>
</div>
<a class="btn-red hide" id="playlist-edit-button">Edit playlist</a>
</div>
<div class="playlist-items">
<ol id="playlist-songs-list" class="playlist-ol"></ol>
</div>
</section>
`
}
, after_render: async () => {
let request = Utils.parseRequestURL()
let playlistId = decodeURIComponent(request.id);
const h1 = document.getElementById('playlist-name-id');
const desc = document.getElementById('playlist-desc-id');
const plaAuthor = document.getElementById('playlist-author-id');
const pic = document.getElementById('img-playlist-on-page');
const editButton = document.getElementById('playlist-edit-button');
const playPlaylist = document.getElementById('play-me');
let createdBy;
let snapshot = await firebase.database().ref('/playlists/' + playlistId);
snapshot.on("value", async function(snapshot) {
let playlist = snapshot.val();
h1.innerHTML = playlist.name;
desc.innerHTML = playlist.desc;
plaAuthor.innerHTML = "Created by: " + playlist.created;
createdBy = playlist.created;
let picUrl1 = await DBGet.getImagePlaylist(playlist.pic_id);
pic.src = picUrl1;
firebase.auth().onAuthStateChanged(firebaseUser => {
console.log(firebaseUser.email);
console.log(createdBy);
if (firebaseUser && (createdBy === firebaseUser.email)){
editButton.classList.remove('hide');
editButton.href="/#/playlistedit/" + playlistId;
}else{
editButton.classList.add('hide');
}
});
});
const songsContainer = document.getElementById('playlist-songs-list');
snapshot = await firebase.database().ref('/playlists/' + playlistId + '/song_list').once("value");
//snapshot.on("value", async function(snapshot) {
let idList = snapshot.val();
console.log(idList);
//idList.forEach(async function(itemRef){
for(const itemRef of idList){
if (!itemRef)continue;
let songId = itemRef.id;
let songSnapshot = await firebase.database().ref('/songs/' + songId).once('value');
let song = songSnapshot.val();
let picUrl2 = await DBGet.getImageSong(song.pic_id);
let playlistLI = document.createElement('LI');
playlistLI.className = 'playlist-song-item';
playlistLI.innerHTML = `
<div class="song-div">
<div class="image-song-div">
<button class="image-song-a">
<img class="image-song" src=${picUrl2} alt="Cover"/>
<div class="middle">
<img id="${songId}" class="song-play-image" src="icon/Play.png" alt="Cover"/>
</div>
</button>
</div>
<p class="song-name">${song.name}</p>
<a class="song-author" href="/#/artist/${song.author}">${song.author}</a>
</div>
<div class="duration-div">
<p class="duration">2:22</p>
</div>
`;
songsContainer.appendChild(playlistLI);
}//);
/*}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});*/
songsContainer.addEventListener("click",async function(e) {
console.log(e.target.nodeName);
if(e.target && e.target.nodeName == "IMG") {
console.log(e.target.id);
if (firebase.auth().currentUser){
DBGet.pushPlaylist(firebase.auth().currentUser.email, [e.target.id]);
}else{
alert("Login first.")
}
}
});
playPlaylist.addEventListener("click",async function(e) {
if (firebase.auth().currentUser){
let list = await DBGet.getPlaylistList(playlistId);
DBGet.pushPlaylist(firebase.auth().currentUser.email, list);
}else{
alert("Login first.")
}
});
}
}
export default Playlist;<file_sep>import Utils from './../../services/Utils.js'
import * as DBGet from './../../services/DBGet.js'
let Search = {
render : async () => {
let request = Utils.parseRequestURL()
let query = decodeURIComponent(request.id);
return /*html*/`
<section class = "search-results-section">
<h2 id="section-search-h2" class="sections-text" id="genres-title">Search results</h2>
<div class="description-text">Founded songs across all uploaded... </div>
<ol id="search-results-ol" class="playlist-ol">
</ol>
</section>
`
}
, after_render: async () => {
let request = Utils.parseRequestURL()
let query = decodeURIComponent(request.id);
const h2 = document.getElementById('section-search-h2');
h2.innerHTML = "Search results for "+query;
const searchContainer = document.getElementById('search-results-ol');
const snapshot = await firebase.database().ref('/songs');
snapshot.on("value", async function(snapshot) {
let songsList = snapshot.val();
songsList.forEach(async function(itemRef, index){
if (itemRef.name.toLowerCase().includes(query) || itemRef.author.toLowerCase().includes(query)){
const picUrl = await DBGet.getImageSong(itemRef.pic_id);
let songLI = document.createElement('LI');
songLI.className = 'playlist-song-item';
songLI.innerHTML = `<div class="song-div">
<div class="image-song-div">
<button class="image-song-a" href="#">
<img class="image-song" src=${picUrl} alt="Cover"/>
<div class="middle">
<img id="${index}" class="song-play-image" src="icon/Play.png" alt="Cover"/>
</div>
</button>
</div>
<p class="song-name">${itemRef.name}</p>
<a class="song-author" href="/#/artist/${itemRef.author}">${itemRef.author}</a>
</div>
<div class="duration-div">
<p class="duration">2:22</p>
</div>
`;
searchContainer.appendChild(songLI);
}
console.log(itemRef.author);
});
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
searchContainer.addEventListener("click",async function(e) {
console.log(e.target.nodeName);
if(e.target && e.target.nodeName == "IMG") {
console.log(e.target.id);
if (firebase.auth().currentUser){
DBGet.pushPlaylist(firebase.auth().currentUser.email, [e.target.id]);
}else{
alert("Login first.")
}
//firebase.database().ref('/playlists/' + playlistId + "/song_list/" + e.target.id).remove();
}
});
}
}
export default Search;<file_sep>export async function getSongs(){
const snapshot = await firebase.database().ref('/songs');
return snapshot;
}
export async function getArtists(){
const snapshot = await firebase.database().ref('/artists');
return snapshot;
}
export async function getChart(){
const snapshot = await firebase.database().ref('/chart_songs').once('value');
return snapshot.val();
}
export async function getPlaylistsChart(){
const snapshot = await firebase.database().ref('/chart_playlists').once('value');
return snapshot.val();
}
export async function getArtistsChart(){
const snapshot = await firebase.database().ref('/chart_artists').once('value');
return snapshot.val();
}
export async function getImageSong(id){
let ref= firebase.storage().ref();
const imgRef = ref.child("/song_pic/id" + id + ".png");
const downloadURL = await imgRef.getDownloadURL();
return downloadURL;
}
export async function getImageArtist(id){
let ref= firebase.storage().ref();
const imgRef = ref.child("/artist_pic/id" + id + ".png");
const downloadURL = await imgRef.getDownloadURL();
return downloadURL;
}
export async function getImagePlaylist(id){
let ref= firebase.storage().ref();
const imgRef = ref.child("/playlist_pic/id" + id + ".png");
const downloadURL = await imgRef.getDownloadURL();
return downloadURL;
}
export async function getSongMP3(id){
let ref= firebase.storage().ref();
const imgRef = ref.child("/mp3/id" + id + ".mp3");
const downloadURL = await imgRef.getDownloadURL();
return downloadURL;
}
export async function getSongId(){
const snapshot = await firebase.database().ref('/song_id/id').once('value');
return snapshot.val();
}
export async function getUserId(){
const snapshot = await firebase.database().ref('/user_count/id').once('value');
return snapshot.val();
}
export async function getPicId(){
const snapshot = await firebase.database().ref('/song_pic_id/id').once('value');
return snapshot.val();
}
export async function getPlaylistId(){
const snapshot = await firebase.database().ref('/playlist_id/id').once('value');
return snapshot.val();
}
export async function getPlaylists(){
const snapshot = await firebase.database().ref('/playlists').once('value');
return snapshot.val();
}
export async function pushPlaylist(user, list){
console.log(user);
const snapshot = await firebase.database().ref('/play_queue').once('value');
const queues = snapshot.val();
let findedUserId = 0;
for(let [index,queue] of queues.entries()){
if (!queue) continue;
if (queue.user == user){
findedUserId = index;
break;
}
}
console.log(findedUserId);
firebase.database().ref('/play_queue/' + findedUserId + '/songs_list/').remove();
let i = 1;
for(let songId of list){
firebase.database().ref('/play_queue/' + findedUserId + '/songs_list/' + i + '/id').set(songId);
i = i + 1;
}
}
export async function getPlaylistList(id){
let ans =[];
let snapshot = await firebase.database().ref('/playlists/' + id + '/song_list').once("value");
let songList = snapshot.val();
for(let song of songList){
if(!song)continue;
ans.push(song.id);
}
return ans;
}<file_sep>import * as DBGet from './../../services/DBGet.js'
let Player = {
render: async () => {
let view = /*html*/`
<section id="player-section">
<div class="player-input-div">
<input type="range" min="0" max="300" value="0" id="range">
</div>
<div class="player-content">
<div class="player-song-details">
<img class="player-song-pic" id="song-image" class="player-image" src=>
<p class="player-song-name" id="player-name-p"></p>
<p class="player-song-author" id="player-author-p"></P>
</div>
<div>
<button class="player-img-button" id="player-prev">
<img class="player-img" id=player-prev-img src="icon/prev.png">
</button>
<button class="player-img-button" id="player-pause">
<img class="player-img" id="player-pause-img" src="icon/player.png" />
</button>
<button class="player-img-button" id="player-next">
<img class="player-img" id=player-next-img src="icon/next.png">
</button>
</div>
<div class="player-duration-div">
<!--p id="duration">test</p-->
<p class="player-duration-time" id="current-time">0:00</p>
</div>
</div>
<audio id="player">
<!--source src="track.ogg" type="audio/ogg"/-->
<!--source src="track.mp3" type="audio/mpeg"/-->
Your browser does not support the audio element.
</audio>
</section>
`
return view
},
after_render: async () => {
const playButton = document.getElementById('player-pause');
const player = document.getElementById('player');
const nextButton = document.getElementById('player-next');
const prevButton = document.getElementById('player-prev');
const duration = document.getElementById('duration');
const curTime = document.getElementById('current-time');
const pic = document.getElementById('song-image');
const playPic = document.getElementById('player-pause-img');
const nameP = document.getElementById('player-name-p');
const authorP = document.getElementById('player-author-p');
const section = document.getElementById('player-section');
let first = true;
let currentSong = 0;
let currentUser;
let songsQueue = [];
async function getPlaylist(){
console.log('started loading');
let snapshot = await firebase.database().ref('/play_queue');
snapshot.on("value", async function(snapshot) {
let idList = snapshot.val();
//idList.forEach(async function(itemRef){
for(const [index,itemRef] of idList.entries()){
if (!itemRef)continue;
console.log('check user ' + itemRef.user);
if (itemRef.user == currentUser){
console.log('found!');
const queueSongSnapshot = await firebase.database().ref('/play_queue/' + index + '/songs_list').once('value');
let songs = queueSongSnapshot.val();
console.log(songs);
songsQueue = [];
if (first && songs == null){
section.classList.add("hide");
break;
}else{
section.classList.remove("hide");
}
for(const song of songs){
if (!song) continue;
console.log(song.id);
songsQueue.push(song.id);
}
currentSong = 0;
await getSong();
break;
}
}
console.log(first);
if (!first){
play();
}
first = false;
});
}
async function getSong(){
player.src = await DBGet.getSongMP3(songsQueue[currentSong]);
let songId = songsQueue[currentSong];
let songSnapshot = await firebase.database().ref('/songs/' + songId).once('value');
let song = songSnapshot.val();
console.log(song);
pic.src = await DBGet.getImageSong(song.pic_id);
nameP.innerHTML = song.name;
authorP.innerHTML = song.author;
}
firebase.auth().onAuthStateChanged(async firebaseUser => {
if (firebaseUser){
//console.log("tut true");
first = true;
currentUser = firebase.auth().currentUser.email;
await getPlaylist();
section.classList.remove("hide");
}else{
pause();
section.classList.add("hide");
console.log('not cool((');
}
});
function play(){
//playButton.innerHTML = "PAUSE";
playPic.src = "icon/pause.png";
isPlay = true;
player.play();
}
function pause(){
//playButton.innerHTML = "PLAY";
playPic.src = "icon/player.png";
isPlay = false;
player.pause();
}
async function next(){
currentSong = currentSong + 1;
if (currentSong == songsQueue.length){
currentSong = 0;
}
await getSong();
play();
}
async function prev(){
currentSong = currentSong - 1;
if (currentSong == -1){
currentSong = songsQueue.length - 1;
}
await getSong();
play();
}
let isPlay = false;
//playButton.innerHTML = "PLAY";
playButton.addEventListener("click",async function(e) {
if (isPlay){
pause();
}else{
play();
}
});
nextButton.addEventListener("click", async function(e){
await next();
});
prevButton.addEventListener("click", async function(e){
await prev();
});
player.addEventListener("ended", async function() {
next();
});
/*player.addEventListener("durationchange", function() {
duration.innerHTML = (player.duration / 60 | 0) + ":" + (player.duration % 60 | 0);
});*/
player.addEventListener("timeupdate", function() {
if (player.currentTime % 60 < 10){
curTime.innerHTML = (player.currentTime / 60 | 0) + ":0" + (player.currentTime % 60 | 0);
}else{
curTime.innerHTML = (player.currentTime / 60 | 0) + ":" + (player.currentTime % 60 | 0);
}
range.value = (player.currentTime / player.duration) * 300 | 0;
});
range.addEventListener('input', function () {
player.currentTime = range.value / 300 * player.duration;
}, false);
}
}
export default Player;<file_sep># FrontEndLabs
~~Сентябрьский~~ <NAME>, 753504, 9. Music player
|
43c2188663ae4eb71c864b89ded7ac459ac4c1d8
|
[
"JavaScript",
"Markdown"
] | 11
|
JavaScript
|
PaulSeptember/Yoptify
|
80216fd031a45defde8b70d21eebb76e8b390882
|
4ee7e5523c742d86f4fa164afc14f57ef9c043a0
|
refs/heads/master
|
<repo_name>sergeykostenko7/landing-react<file_sep>/src/js/Components/Slide/index.js
import React, { Component } from 'react'
import slide from './../../../images/slide.jpg'
import logoRound from './../../../images/logo-round.svg'
export default class Slide extends Component {
render() {
return (
<div className="slide">
<img className="slide__image" src={slide} alt="<NAME>" />
<div className="slide__caption">
<p className="slide__blockquote">
Lorem ipsum dolor sit amet, consectetur adipiscing 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.
</p>
<div className="slide__credits">
<div className="slide__icon">
<img src={logoRound} alt="" />
</div>
<div className="slide__author">
<h6 className="slide__author-name"><NAME></h6>
<p className="slide__author-info">
FrontEnd Developer<br/>
S-PRO
</p>
</div>
</div>
</div>
</div>
)
}
}
<file_sep>/src/js/Components/Header/index.js
import React, { Component } from 'react'
import logo from './../../../images/logo.svg'
export default class Header extends Component {
render() {
return (
<header className="header">
<div className="container">
<a className="company-brand" href="#">
<img src={logo} alt="S-Pro" />
</a>
<button className="btn-toggle" type="button" id="btn-toggle">
<span className="btn-toggle__icon"></span>
</button>
<nav className="header-collapse" id="header-collapse">
<ul className="header-nav">
<li className="header-nav__item">
<a className="header-nav__link" href="#">Item 1</a>
</li>
<li className="header-nav__item">
<a className="header-nav__link" href="#">Item 2</a>
</li>
<li className="header-nav__item">
<a className="header-nav__link" href="#">Item 3</a>
</li>
<li className="header-nav__item">
<a className="header-nav__link" href="#">Item 4</a>
</li>
<li className="header-nav__item">
<a className="header-nav__link" href="#">Item 5</a>
</li>
</ul>
<a className="btn btn--md btn--outline outline-violet header__btn">
Button text
</a>
</nav>
</div>
<div className="header__shape"></div>
</header>
)
}
}
<file_sep>/src/js/Components/Footer/index.js
import React, { Component } from 'react'
import logo from './../../../images/logo.svg'
export default class Footer extends Component {
render() {
return (
<footer className="footer">
<div className="footer__top">
<div className="container container--flex">
<a className="company-brand footer__company-brand" href="#">
<img src={logo} alt="S-Pro" />
</a>
<ul className="footer-social">
<li className="footer-social__item">
<a className="footer-social__link fab fa-telegram-plane" href="https://telegram.org/" target="_blank">
Telegram
</a>
</li>
<li className="footer-social__item">
<a className="footer-social__link fab fa-twitter" href="https://twitter.com/" target="_blank">
Twitter
</a>
</li>
<li className="footer-social__item">
<a className="footer-social__link fab fa-linkedin-in" href="https://www.linkedin.com/" target="_blank">
LinkedIn
</a>
</li>
<li className="footer-social__item">
<a className="footer-social__link fab fa-facebook-f" href="https://www.facebook.com/" target="_blank">
Facebook
</a>
</li>
<li className="footer-social__item">
<a className="footer-social__link fab fa-medium-m" href="https://medium.com/" target="_blank">
Medium
</a>
</li>
<li className="footer-social__item">
<a className="footer-social__link fab fa-reddit-alien" href="https://www.reddit.com/" target="_blank">
Reddit
</a>
</li>
<li className="footer-social__item">
<a className="footer-social__link fab fa-btc" href="https://www.bitcoin.com/" target="_blank">
Bitcoin
</a>
</li>
<li className="footer-social__item">
<a className="footer-social__link fab fa-github" href="https://github.com/" target="_blank">
GitHub
</a>
</li>
</ul>
<div></div>
</div>
</div>
<div className="footer__bottom">
<div className="container container--flex">
<ul className="footer-nav">
<li className="footer-nav__item">
<a className="footer-nav__link" href="#">Privacy Policy</a>
</li>
<li className="footer-nav__item">
<a className="footer-nav__link" href="#">Terms & Conditions</a>
</li>
<li className="footer-nav__item">
<a className="footer-nav__link" href="#">Tokensale Agreement</a>
</li>
</ul>
<p className="footer__copyright">
© 2018 S-PRO - All rights reserved
</p>
</div>
</div>
</footer>
)
}
}
<file_sep>/src/js/Components/Slider/index.js
import React, { Component } from 'react'
import Slide from './../Slide'
export default class Slider extends Component {
render() {
return (
<section className="slider">
<div className="slider__main">
<div className="slick-slider">
<Slide />
<Slide />
<Slide />
</div>
<div className="slick-buttons"></div>
</div>
<div className="slider__aside"></div>
</section>
)
}
}
<file_sep>/readme.md
# S-Pro Landing Page (ReactJS version)
### Installing & Running the App
* Run `yarn install` to install the dependencies
* Run `npm run server` to build the app and launch the development server
* Open http://localhost:8080
<file_sep>/src/js/App.js
import React, { Component } from 'react'
import './../scss/main.scss'
import Header from './Components/Header'
import Jumbotron from './Components/Jumbotron'
import Slider from './Components/Slider'
import Timeline from './Components/Timeline'
import Footer from './Components/Footer'
export default class App extends Component {
render() {
return (
<div>
<Header />
<Jumbotron />
<Slider />
<Timeline />
<Footer />
</div>
)
}
}
<file_sep>/webpack.config.js
const webpack = require('webpack')
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const outputPath = path.resolve(__dirname, './dist')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const autoprefixer = require('autoprefixer')
const webpackConfig = {
entry: {
app: [
path.resolve(__dirname, './src/js/index.js')
]
},
output: {
path: path.resolve(__dirname, './dist'),
filename: '[name].js'
},
devtool: 'cheap-module-eval-source-map',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: ['babel-loader', 'eslint-loader']
},
{
test: /\.scss$/,
exclude: /node_modules/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
// options: {
// sourceMap: true
// }
},
//
{
loader: 'sass-loader',
// options: {
// sourceMap: true
// }
},
{
loader: 'postcss-loader',
},
]
})
},
{
test: /\.(gif|png|jpg|jpeg|svg|ico)$/,
exclude: /node_modules/,
include: path.resolve(__dirname, './src/images/'),
use: 'file-loader?name=images/[name].[ext]'
},
{
test: /\.(woff|woff2|eot|otf|svg|ttf)$/,
exclude: /node_modules/,
include: path.resolve(__dirname, './src/fonts/'),
use: 'file-loader?name=fonts/[name].[ext]'
},
]
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, './src/index.html'),
filename: 'index.html',
favicon: './src/images/favicon.ico',
path: outputPath
}),
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new ExtractTextPlugin('./main.css'),
new webpack.LoaderOptionsPlugin({
minimize: true,
debug: false,
options: {
postcss: [autoprefixer]
}
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
screw_ie8: true,
conditionals: true,
unused: true,
comparisons: true,
sequences: true,
dead_code: true,
evaluate: true,
if_return: true,
join_vars: true,
},
output: {
comments: false,
},
})
],
devServer: {
contentBase: path.resolve(__dirname, './dist'),
port: 8080,
historyApiFallback: true,
inline: true,
hot: true,
host: 'localhost'
}
}
module.exports = webpackConfig
|
e6d5c0af3e64330975c553eea542fe80a3b10232
|
[
"JavaScript",
"Markdown"
] | 7
|
JavaScript
|
sergeykostenko7/landing-react
|
cdfee6cb3e0c4e56ad26064bfc7002024398d200
|
7d50fa66ac706f1580a1ce35166b7613bcef0a6d
|
refs/heads/master
|
<repo_name>getfetch/fetch-demo<file_sep>/public/javascript/localStorage.js
// Origin: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage
// Gets an array from localStorage
function localStorageGetArray(key) {
var data = window.localStorage.getItem(key);
return data ? data.split(',') : [];
}
// Stores an array to localStorage
function localStorageSetArray(key, items) {
if (!Array.isArray(items)) {
throw new Error('localStorageSetArray: items must be an Array.');
}
data = items.join(',');
window.localStorage.setItem(key, data);
}
// Pushes an item to an array stored in localStorage
function localStoragePush(key, item) {
// TODO: Escape the item string if it contains ','
var items = localStorageGetArray(key);
items.push(item.toString());
localStorageSetArray(key, items);
}
// Pops an item to an array stored in localStorage
function localStoragePop(key, item) {
var items = localStorageGetArray(key);
var index = items.indexOf(item.toString());
if (index === -1) {
return false;
}
items.pop(index);
localStorageSetArray(key, items);
return true;
}
if (!window.localStorage) {
Object.defineProperty(window, "localStorage", new (function () {
var aKeys = [], oStorage = {};
Object.defineProperty(oStorage, "getItem", {
value: function (sKey) { return sKey ? this[sKey] : null; },
writable: false,
configurable: false,
enumerable: false
});
Object.defineProperty(oStorage, "key", {
value: function (nKeyId) { return aKeys[nKeyId]; },
writable: false,
configurable: false,
enumerable: false
});
Object.defineProperty(oStorage, "setItem", {
value: function (sKey, sValue) {
if(!sKey) { return; }
document.cookie = escape(sKey) + "=" + escape(sValue) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/";
},
writable: false,
configurable: false,
enumerable: false
});
Object.defineProperty(oStorage, "length", {
get: function () { return aKeys.length; },
configurable: false,
enumerable: false
});
Object.defineProperty(oStorage, "removeItem", {
value: function (sKey) {
if(!sKey) { return; }
document.cookie = escape(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
},
writable: false,
configurable: false,
enumerable: false
});
this.get = function () {
var iThisIndx;
for (var sKey in oStorage) {
iThisIndx = aKeys.indexOf(sKey);
if (iThisIndx === -1) { oStorage.setItem(sKey, oStorage[sKey]); }
else { aKeys.splice(iThisIndx, 1); }
delete oStorage[sKey];
}
for (aKeys; aKeys.length > 0; aKeys.splice(0, 1)) { oStorage.removeItem(aKeys[0]); }
for (var aCouple, iKey, nIdx = 0, aCouples = document.cookie.split(/\s*;\s*/); nIdx < aCouples.length; nIdx++) {
aCouple = aCouples[nIdx].split(/\s*=\s*/);
if (aCouple.length > 1) {
oStorage[iKey = unescape(aCouple[0])] = unescape(aCouple[1]);
aKeys.push(iKey);
}
}
return oStorage;
};
this.configurable = false;
this.enumerable = true;
})());
}
<file_sep>/public/javascript/info.js
var Info = (function() {
var result;
// Info page
//
var infoDoc;
var pageCache;
$.ajax('/info')
.done(function(data) {
infoDoc = createDocument(data);
console.log(infoDoc);
});
function cachePage() {
console.log
pageCache = {
title: document.title,
body: document.body,
url: document.location.href,
positionY: window.pageYOffset,
positionX: window.pageXOffset
};
}
$(window).on('popstate', function(e) {
if(e.originalEvent.state && e.originalEvent.state.info) {
restoreCachedPage();
}
});
function restoreCachedPage() {
if(!pageCache) {
return;
}
document.title = pageCache.title;
document.documentElement.replaceChild(pageCache.body, document.body);
window.history.replaceState({}, '', pageCache.url);
PageSetup();
window.scrollTo(pageCache.positionX, pageCache.positionY);
}
function createDocument(html) {
var doc = document.implementation.createHTMLDocument('');
doc.open('replace');
doc.write(html);
doc.close();
return doc;
}
function displayDog(dog) {
console.log('Displaying: ', dog);
cachePage();
document.title = dog.name;
document.documentElement.replaceChild($(infoDoc.body).clone()[0], document.body);
window.history.pushState({ info: true }, '', '/browse/' + dog.id);
console.log(infoDoc);
window.scrollTo(0, 0);
PageSetup();
$('#back-link').click(function() {
console.log('back');
restoreCachedPage();
return false;
});
$('#main-header-title').text(dog.name);
$('.pet').addClass(dog.options.join(' '));
$('.pet-name').text(dog.name);
$('.pet-age-sex').text(dog.age + " " + dog.sex);
$('.pet-breed').text(dog.breeds[0]);
$('.pet-description').append($(dog.description));
$('.pet-image').append($('<img src="' + dog.photoUrls[0] + '" />'));
$('.breeder-name').text(PetBrowser.lookupShelter(dog.organization.id));
$('.breeder-email').text(dog.organization.email);
$('.breeder-address').text(dog.organization.address);
$('.breeder-phone').text(dog.organization.phone);
}
result = {
popInfo: function(dog) {
displayDog(dog);
}
};
return result;
})();
<file_sep>/profile.js
function load(id, callback){
callback({
});
}
module.exports.load = load;<file_sep>/aggregate.js
var http = require('http');
var querystring = require('querystring');
var crypto = require('crypto');
// TODO: Generate new keys and put then in the config instead of version control
var API_KEY = 'c05eebea71cf26cfa156b08689269176';
var API_SECRET = '<KEY>';
function request(zipcode, callback) {
// TODO: Distance option
// TODO: Filters
var query = querystring.stringify({key: API_KEY, format: 'json', animal: 'dog', location: zipcode});
var signature = crypto.createHash('md5').update(API_SECRET + query).digest('hex');
var content = '';
var url = 'http://api.petfinder.com/pet.find?' + query + '&' + signature;
var get = http.get(url, function(response) {
response.setEncoding('utf8');
response.on('data', function(chunk) {
content += chunk;
});
response.on('end', function() {
callback(content);
});
}).on('error', function(e) {
console.log('got error: ' + e.message);
});
}
function toArray(item) {
if (!item) {
return [];
} else if (Array.isArray(item)) {
return item;
} else {
return [item];
}
}
function transform(json) {
return toArray(json.petfinder.pets.pet).map(function(pet) {
// TODO: Filter on availability? pet.status['$t'] === 'A'
return {
id: pet.id['$t'],
name: pet.name['$t'],
description: pet.description['$t'],
photoUrls: toArray(pet.media.photos.photo)
.filter(function(photo) { return photo['@size'] === 'x'; })
.sort(function(photo) { return photo['@id']; })
.map(function(photo) { return photo['$t']; }),
age: pet.age['$t'], // {'Baby', 'Young', 'Adult', 'Senior'}
sex: pet.sex['$t'], // {'M', 'F'}
size: pet.size['$t'], // {'S', 'M', 'L', 'XL'}
breeds: toArray(pet.breeds.breed)
.map(function(breed) { return breed['$t']; }),
mix: pet.mix['$t'] === 'yes',
organization: {
id: pet.shelterId['$t'],
type: 'shelter',
name: '', // TODO: Request for name
email: pet.contact.email['$t'],
},
options: toArray(pet.options.option)
.map(function(option) {
return option['$t'];
}),
};
});
}
function pull(zipcode, callback) {
console.log('Fetching dogs...');
request(zipcode, function(content) {
petfinder = JSON.parse(content);
console.log('Transforming...');
pets = transform(petfinder);
console.log('Done');
callback(pets);
});
}
module.exports.request = request;
module.exports.pull = pull;
<file_sep>/public/javascript/browse.js
var PetBrowser = (function() {
var result;
var dogToDisplay;
console.log('test');
function loadDogs(dogs) {
var breeds = [];
var $template = $('#pet-template');
// Load favorite dogs
var favoriteDogIds = localStorageGetArray('favorites');
// Render dogs
$.each(dogs, function(i, dog) {
console.log("Loading dog: ", dog);
if(displayId === dog.id) {
dogToDisplay = dog;
}
$.each(dog.breeds, function(i, breed) {
if($.inArray(breed, breeds) == -1) {
breeds.push(breed);
}
});
var $dog = $template.clone();
$dog.data('object', dog);
$dog.attr('style', '');
$dog.attr('id', '');
$dog.addClass(dog.options.join(' '));
var url = '/browse/' + dog.id;
var $favoriteLink = $dog.find('.pet-favorite-link');
$favoriteLink.on('click', function() {
// Toggle favorite
if (localStoragePop('favorites', dog.id)) {
$(this).removeClass('favorited');
} else {
localStoragePush('favorites', dog.id);
$(this).addClass('favorited');
}
return false;
});
if (favoriteDogIds.indexOf(dog.id.toString()) !== -1) {
$favoriteLink.addClass('favorited');
}
$dog.find('.pet-name').text(dog.name);
$dog.find('.pet-info-link').attr('href', url);
$dog.find('.pet-share-link').attr('data-target', '#shareModal-' + dog.id);
$dog.find('.shareModal').attr('id', 'shareModal-' + dog.id);
$dog.find('.share-button').attr('st_url', EXTERNAL_URL + url);
$dog.find('.share-button').attr('st_title', 'How adorable! Take a look at this dog, ' + dog.name + ' #fetch #swpgh');
$dog.find('.share-button').attr('st_summary', 'How adorable! Take a look at this dog, ' + dog.name + ' #fetch #swpgh');
$.each(dog.photoUrls, function(i, url) {
var $img = $('<img src="' + url + '" />');
$dog.find('.pet-images').append($img);
if(i > 0) {
$img.hide();
}
});
$('.pet-container').append($dog);
});
// sort and load breeds
breeds.sort();
$.each(breeds, function(i, breed) {
$('#breed').append($('<option value="' + breed + '">' + breed + '</option>'));
});
filterDogs();
if(dogToDisplay) {
setTimeout(function() {
Info.popInfo(dogToDisplay);
}, 100);
}
}
var filter = {
sex: null,
age: null,
size: null,
breed: 'any'
};
function matchesFilter(dog) {
var matches = (filter.size && dog.size != filter.size) ||
(filter.sex && dog.sex != filter.sex) ||
(filter.age && dog.age != filter.age) ||
(filter.breed != 'any' && $.inArray(filter.breed, dog.breeds));
return matches;
}
function filterDogs() {
$('.pet-container .pet').each(function() {
var dog = $(this).data('object');
if(dog) {
if(matchesFilter(dog)) {
$(this).slideUp(250);
} else {
$(this).slideDown(250);
}
}
});
}
function filterChanged() {
filter.sex = $('input:radio[name="sex"]:checked').val();
filter.age = $('input:radio[name="age"]:checked').val();
filter.size = $('input:radio[name="size"]:checked').val();
filter.breed = $('#breed').val();
filterDogs();
}
$.getJSON('/data/dogs.json')
.done(function(data) {
$(function() {
loadDogs(data);
});
});
$(function() {
$('#filter-settings input:radio, #breed').on('change', function() {
filterChanged();
});
$('.pet-container').on('click', '.pet-info-link', function() {
Info.popInfo($(this).parents('.pet').data('object'));
return false;
});
});
// Shelters
//
var shelterNames = {
'PA834': '<NAME>',
'PA294': 'Animal Advocates'
};
result = {
lookupShelter: function(id) {
return shelterNames[id] || id;
}
};
return result;
})();
<file_sep>/views/reservation.html
{% extends 'layout.html' %}
{% block title %}Notifications{% endblock %}
{% block class %}notifications{% endblock %}
{% block head %}
{% parent %}
{% endblock %}
{% block menuright %}
{% endblock %}
{% block content %}
<article>
<h2>Coming soon!</h2>
<p>
Reserve a dog to ensure it will be available when you show up at the shelter.
</p>
</article>
{% endblock %}
<file_sep>/app.js
var fs = require('fs');
var http = require('http');
var path = require('path');
var util = require('util');
var querystring = require('querystring');
var express = require('express');
var swig = require('swig');
var aggregate = require('./aggregate');
var organization = require('./organization');
// Constants
var ADMIN_EMAIL = '<EMAIL>';
var ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || '';
var ADMIN_ZIPCODE = process.env.ADMIN_ZIPCODE || 15220;
var PUBLIC_DIR = path.join(__dirname, 'public');
// App config
var app = express();
app.engine('html', swig.renderFile);
app.use(express.static(PUBLIC_DIR));
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({secret: process.env.SECRET_KEY || 'DEVELOPMENT'}));
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
app.set('view cache', process.env.CACHE || false);
swig.setDefaults({ cache: false });
// Middleware
function requireLogin(request, response, next) {
if (request.session.loggedIn) {
next();
} else {
response.redirect('/login' +
(request.url ? '?' + querystring.stringify({next: request.url}) : ''));
}
}
// Routes
app.get('/*', function(request, response, next) {
// Redirect www to non-www domain
if(request.headers.host.match(/^www/)) {
response.redirect(301, 'http://' + request.headers.host.replace(/^www\./, '') + request.url);
} else {
next();
}
});
app.get('/', function(request, response) {
response.render('index');
});
app.get('/reservation', function(request, response) {
response.render('reservation', { /* template locals context */ });
});
app.get('/notifications', function(request, response) {
response.render('notifications', { /* template locals context */ });
});
app.get('/browse/:id?', function(request, response) {
response.render('browse', { id: request.params.id });
});
app.get('/info', function(request, response) {
response.render('info');
});
app.get('/favorites/:id?', function(request, response) {
response.render('favorites', { id: request.params.id });
});
app.get('/organization/:id', function(request, response) {
organization.load(request.params.id, function(model) { response.render('organization', model); });
});
app.get('/profile', function(request, response){
var profile = require('./profile');
profile.load(request.params.id, function(model){response.render('profile', model)});
});
app.get('/about', function(request, response) {
response.render('about');
});
app.get('/contact', function(request, response) {
response.render('contact');
});
app.get('/login', function (request, response) {
if (request.session.loggedIn) {
response.redirect('/');
} else {
response.render('login', {next: request.query.next});
}
})
.post('/login', function(request, response) {
if (request.body.email !== ADMIN_EMAIL || request.body.password !== <PASSWORD>_<PASSWORD>) {
response.render('login', {
email: request.body.email,
error: 'Incorrect email or password.',
});
} else {
// TODO: Make this more secure
request.session.loggedIn = true;
response.redirect(request.body.next || '/');
}
});
app.get('/logout', function(request, response) {
request.session.loggedIn = false;
response.redirect('/');
});
app.get('/admin', requireLogin, function(request, response) {
response.render('admin');
});
app.get('/aggregate', requireLogin, function(request, response) {
aggregate.request(ADMIN_ZIPCODE, function(content) {
response.setHeader('Content-Type', 'application/json');
response.send(content);
});
});
app.post('/aggregate', requireLogin, function(request, response) {
aggregate.pull(ADMIN_ZIPCODE, function(pets) {
var data_dir = path.join(PUBLIC_DIR, 'data');
var data_file = path.join(data_dir, 'dogs.json');
var json = JSON.stringify(pets, null, 2);
fs.writeFile(data_file, json, function(err) {
if (err) {
response.send('Could not generate files. <br /><br />' + err + '<br /><br /><a href="/admin">Back to Admin</a>');
} else {
response.send('Files generated successfully. <br /><br /><a href="/admin">Back to Admin</a>');
}
});
});
});
// Run server
var port = process.env.PORT || 3000;
app.listen(port, function() {
console.log('Listening on ' + port);
});
|
211c57b57960d9d93d673af691c4308f25be6eab
|
[
"JavaScript",
"HTML"
] | 7
|
JavaScript
|
getfetch/fetch-demo
|
24ef21ba1785949f21b2e70baf6f1d7d7fae44ea
|
45eb9bf1e3a6db17ff0d3ae1f4321d6ae25310c1
|
refs/heads/master
|
<repo_name>jchai002/craft_engimail<file_sep>/twigextensions/EnigmailTwigExtension.php
<?php
namespace Craft;
use Twig_Extension;
use Twig_Filter_Method;
class EnigmailTwigExtension extends \Twig_Extension
{
public function getName()
{
return 'Enigmail';
}
public function getFilters()
{
return array(
'enigmail' => new Twig_Filter_Method($this, 'enigmail'),
);
}
public function enigmail($email)
{
return str_rot13($email);
}
}
<file_sep>/README.md
# craft_engimail
A tiny plugin to apply the rot13 encryption to strings in order to obfuscate email addresses
<file_sep>/EnigmailPlugin.php
<?php
namespace Craft;
/**
* Enigmail Plugin
*/
class EnigmailPlugin extends BasePlugin
{
public function getName()
{
return Craft::t('Enigmail');
}
public function getVersion()
{
return '1.0.0';
}
public function getDeveloper()
{
return '<NAME>';
}
public function getDeveloperUrl()
{
return 'http://jerrychai.us';
}
public function hasCpSection()
{
return false;
}
public function addTwigExtension()
{
Craft::import('plugins.enigmail.twigextensions.EnigmailTwigExtension');
return new EnigmailTwigExtension();
}
}
|
93e9afdf4da6eee18fdc9dec06141696932385cb
|
[
"Markdown",
"PHP"
] | 3
|
PHP
|
jchai002/craft_engimail
|
59df264205813f546924b2a584d0ad1a0cbb2c7f
|
29b9bbf7355d1ba50235de0108c91d894004ca08
|
refs/heads/master
|
<file_sep>// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
package secrets
import (
"context"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
)
type SecretClient interface {
Create(ctx context.Context, key types.NamespacedName, data map[string][]byte, opts ...SecretOption) error
Upsert(ctx context.Context, key types.NamespacedName, data map[string][]byte, opts ...SecretOption) error
Delete(ctx context.Context, key types.NamespacedName) error
Get(ctx context.Context, key types.NamespacedName) (map[string][]byte, error)
}
type SecretOwner interface {
runtime.Object
metav1.Object
}
// Options contains the inputs available for passing to some methods of the secret clients
type Options struct {
Owner SecretOwner
Scheme *runtime.Scheme
Activates *time.Time
Expires *time.Time
Flatten bool
}
// SecretOption wraps a function that sets a value in the options struct
type SecretOption func(*Options)
// WithActivation can be used to pass an activation duration
func WithActivation(activateAfter *time.Time) SecretOption {
return func(op *Options) {
op.Activates = activateAfter
}
}
// WithExpiration can be used to pass an expiration duration
func WithExpiration(expireAfter *time.Time) SecretOption {
return func(op *Options) {
op.Expires = expireAfter
}
}
// WithOwner allows setting an owning instance in the options struct
func WithOwner(owner SecretOwner) SecretOption {
return func(op *Options) {
op.Owner = owner
}
}
// WithScheme allows setting a runtime.Scheme in the options
func WithScheme(scheme *runtime.Scheme) SecretOption {
return func(op *Options) {
op.Scheme = scheme
}
}
// Flatten can be used to create individual string secrets
func Flatten(flatten bool) SecretOption {
return func(op *Options) {
op.Flatten = flatten
}
}
<file_sep>package mysql
import (
"context"
"database/sql"
"fmt"
"strings"
"github.com/pkg/errors"
"github.com/Azure/azure-service-operator/pkg/errhelp"
"github.com/Azure/azure-service-operator/pkg/helpers"
"github.com/Azure/azure-service-operator/pkg/resourcemanager/iam"
)
// MSqlServerPort is the default server port for sql server
const MySQLServerPort = 3306
// MDriverName is driver name for psqldb connection
const MySQLDriverName = "mysql"
func GetMySQLDatabaseDNSSuffix() string {
// TODO: We need an environment specific way of getting the DNS suffix
// TODO: which the Go SDK doesn't seem to have.
// TODO: see: https://github.com/Azure/azure-sdk-for-go/issues/13749
return "mysql.database.azure.com"
}
func GetFullSQLServerName(serverName string) string {
return serverName + "." + GetMySQLDatabaseDNSSuffix()
}
func GetFullyQualifiedUserName(userName string, serverName string) string {
return fmt.Sprintf("%s@%s", userName, serverName)
}
// ConnectToSqlDb connects to the SQL db using the given credentials
func ConnectToSqlDB(ctx context.Context, driverName string, fullServer string, database string, port int, user string, password string) (*sql.DB, error) {
connString := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?tls=true&interpolateParams=true", user, password, fullServer, port, database)
db, err := sql.Open(driverName, connString)
if err != nil {
return db, err
}
err = db.PingContext(ctx)
if err != nil {
return db, fmt.Errorf("error pinging the mysql db (%s:%d/%s): %v", fullServer, port, database, err)
}
return db, err
}
// ConnectToSQLDBAsCurrentUser connects to the SQL DB using the specified MSI ClientID
func ConnectToSQLDBAsCurrentUser(
ctx context.Context,
driverName string,
fullServer string,
database string,
port int,
user string,
clientID string) (*sql.DB, error) {
tokenProvider, err := iam.GetMSITokenProviderForResourceByClientID("https://ossrdbms-aad.database.windows.net", clientID)
if err != nil {
return nil, err
}
// In our case we can't pass the provider directly so we just invoke it and get the token and use that
token, err := tokenProvider()
if err != nil {
return nil, err
}
// See https://docs.microsoft.com/en-us/azure/mysql/howto-connect-with-managed-identity
// As noted here https://docs.microsoft.com/en-us/azure/mysql/howto-configure-sign-in-azure-ad-authentication#compatibility-with-application-drivers
// we must specify allowCleartextPasswords to pass a token
connString := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?tls=true&allowCleartextPasswords=true&interpolateParams=true", user, token, fullServer, port, database)
db, err := sql.Open(driverName, connString)
if err != nil {
return db, err
}
err = db.PingContext(ctx)
if err != nil {
return db, fmt.Errorf("error pinging the mysql db (%s:%d/%s) as %s: %v", fullServer, port, database, user, err)
}
return db, err
}
// ExtractUserRoles extracts the roles the user has. The result is the set of roles the user has for the requested database
func ExtractUserRoles(ctx context.Context, db *sql.DB, user string, database string) (map[string]struct{}, error) {
if err := helpers.FindBadChars(user); err != nil {
return nil, errors.Wrapf(err, "problem found with username")
}
// Note: This works because we only assign permissions at the DB level, not at the table, column, etc levels -- if we assigned
// permissions at more levels we would need to do something else here such as join multiple tables or
// parse SHOW GRANTS with a regex.
formattedUser := fmt.Sprintf("'%s'@'%%'", user)
rows, err := db.QueryContext(
ctx,
"SELECT PRIVILEGE_TYPE FROM INFORMATION_SCHEMA.SCHEMA_PRIVILEGES WHERE GRANTEE = ? and TABLE_SCHEMA = ?",
formattedUser,
database)
if err != nil {
return nil, errors.Wrapf(err, "listing grants for user %s", user)
}
defer rows.Close()
result := make(map[string]struct{})
for rows.Next() {
var row string
err := rows.Scan(&row)
if err != nil {
return nil, errors.Wrapf(err, "iterating returned rows")
}
result[row] = struct{}{}
}
return result, nil
}
func GrantUserRoles(ctx context.Context, user string, database string, roles []string, db *sql.DB) error {
var errorStrings []string
if err := helpers.FindBadChars(user); err != nil {
return fmt.Errorf("problem found with username: %v", err)
}
rolesMap := make(map[string]struct{})
for _, role := range roles {
rolesMap[role] = struct{}{}
}
// Get the current roles
currentRoles, err := ExtractUserRoles(ctx, db, user, database)
if err != nil {
return errors.Wrapf(err, "couldn't get existing roles for user %s", user)
}
// Remove "USAGE" as it's special and we never grant or remove it
delete(currentRoles, "USAGE")
rolesDiff := helpers.DiffCurrentAndExpectedSQLRoles(currentRoles, rolesMap)
// Due to how go-mysql-driver performs parameter replacement, it always wraps
// string parameters in ''. That doesn't work for these queries because some of
// our parameters are actually SQL keywords or identifiers (requiring backticks). Admittedly
// protecting against SQL injection here is probably pointless as we're giving the caller
// permission to create users, which means there's nothing stopping them from creating
// an administrator user and then doing whatever they want without SQL injection.
// See https://github.com/go-sql-driver/mysql/blob/3b935426341bc5d229eafd936e4f4240da027ccd/connection.go#L198
// for specifics of what go-mysql-driver supports.
err = addRoles(ctx, db, database, user, rolesDiff.AddedRoles)
if err != nil {
errorStrings = append(errorStrings, err.Error())
}
err = deleteRoles(ctx, db, database, user, rolesDiff.DeletedRoles)
if err != nil {
errorStrings = append(errorStrings, err.Error())
}
if len(errorStrings) != 0 {
return fmt.Errorf(strings.Join(errorStrings, "\n"))
}
return nil
}
func addRoles(ctx context.Context, db *sql.DB, database string, user string, roles map[string]struct{}) error {
if len(roles) == 0 {
// Nothing to do
return nil
}
var rolesSlice []string
for elem := range roles {
rolesSlice = append(rolesSlice, elem)
}
toAdd := strings.Join(rolesSlice, ",")
tsql := fmt.Sprintf("GRANT %s ON `%s`.* TO ?", toAdd, database)
_, err := db.ExecContext(ctx, tsql, user)
return err
}
func deleteRoles(ctx context.Context, db *sql.DB, database string, user string, roles map[string]struct{}) error {
if len(roles) == 0 {
// Nothing to do
return nil
}
var rolesSlice []string
for elem := range roles {
rolesSlice = append(rolesSlice, elem)
}
toDelete := strings.Join(rolesSlice, ",")
tsql := fmt.Sprintf("REVOKE %s ON `%s`.* FROM ?", toDelete, database)
_, err := db.ExecContext(ctx, tsql, user)
return err
}
// UserExists checks if db contains user
func UserExists(ctx context.Context, db *sql.DB, username string) (bool, error) {
err := db.QueryRowContext(ctx, "SELECT * FROM mysql.user WHERE User = $1", username)
if err != nil {
return false, nil
}
return true, nil
}
// DropUser drops a user from db
func DropUser(ctx context.Context, db *sql.DB, user string) error {
if err := helpers.FindBadChars(user); err != nil {
return fmt.Errorf("problem found with username: %v", err)
}
_, err := db.ExecContext(ctx, "DROP USER IF EXISTS ?", user)
return err
}
// TODO: This is probably more generic than MySQL
func IsErrorResourceNotFound(err error) bool {
requeueErrors := []string{
errhelp.ResourceNotFound,
errhelp.ParentNotFoundErrorCode,
errhelp.ResourceGroupNotFoundErrorCode,
}
azerr := errhelp.NewAzureError(err)
return helpers.ContainsString(requeueErrors, azerr.Type)
}
func IgnoreResourceNotFound(err error) error {
if IsErrorResourceNotFound(err) {
return nil
}
return err
}
func IsErrorDatabaseBusy(err error) bool {
return strings.Contains(err.Error(), "Please retry the connection later")
}
func IgnoreDatabaseBusy(err error) error {
if IsErrorDatabaseBusy(err) {
return nil
}
return err
}
<file_sep>// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
package errhelp
import (
"fmt"
"regexp"
"strings"
)
// ErrIdsRegex is used to find and remove uuids from errors
var ErrIdsRegex *regexp.Regexp
// ErrTimesRegex allows timestamp seconds to be removed from error strings
var ErrTimesRegex *regexp.Regexp
// StripErrorIDs takes an error and returns its string representation after filtering some common ID patterns
func StripErrorIDs(err error) string {
patterns := []string{
"RequestID=",
"CorrelationId:\\s",
"Tracking ID: ",
"requestId",
}
if ErrIdsRegex == nil {
ErrIdsRegex = regexp.MustCompile(fmt.Sprintf(`(%s)\S+`, strings.Join(patterns, "|")))
}
return ErrIdsRegex.ReplaceAllString(err.Error(), "")
}
// StripErrorTimes removes the hours:minutes:seconds from a date to prevent updates to Status.Message from changing unnecessarily
func StripErrorTimes(err string) string {
if ErrTimesRegex == nil {
ErrTimesRegex = regexp.MustCompile(`(T\d\d:\d\d:\d\d)\"`)
}
return ErrTimesRegex.ReplaceAllString(err, "")
}
<file_sep>// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
package kube
import (
"context"
"strconv"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
)
var _ = Describe("Kube Secrets Client", func() {
BeforeEach(func() {
// Add any setup steps that needs to be executed before each test
})
AfterEach(func() {
// Add any teardown steps that needs to be executed after each test
})
// Add Tests for OpenAPI validation (or additonal CRD features) specified in
// your API definition.
// Avoid adding tests for vanilla CRUD operations because they would
// test Kubernetes API server, which isn't the goal here.
Context("Create and Delete", func() {
It("should create and delete secret in k8s", func() {
//s := strconv.FormatInt(GinkgoRandomSeed(), 10)
secretName := "secret" + strconv.FormatInt(GinkgoRandomSeed(), 10)
var err error
ctx := context.Background()
data := map[string][]byte{
"test": []byte("data"),
"sweet": []byte("potato"),
}
client := New(K8sClient)
key := types.NamespacedName{Name: secretName, Namespace: "default"}
Context("creating secret with secret client", func() {
err = client.Create(ctx, key, data)
Expect(err).To(BeNil())
})
secret := &v1.Secret{}
Context("ensuring secret exists using k8s client", func() {
err = K8sClient.Get(ctx, key, secret)
Expect(err).To(BeNil())
d, err := client.Get(ctx, key)
Expect(err).To(BeNil())
for k, v := range d {
Expect(data[k]).To(Equal(v))
}
})
Context("delete secret and ensure it is gone", func() {
err = client.Delete(ctx, key)
Expect(err).To(BeNil())
err = K8sClient.Get(ctx, key, secret)
Expect(err).ToNot(BeNil())
})
})
})
})
<file_sep>// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// +build all mysql
package controllers
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
azurev1alpha1 "github.com/Azure/azure-service-operator/api/v1alpha1"
"github.com/Azure/azure-service-operator/api/v1alpha2"
"github.com/Azure/azure-service-operator/pkg/resourcemanager/mysql"
"github.com/Azure/azure-service-operator/pkg/resourcemanager/mysql/mysqluser"
)
func TestMySQLHappyPath(t *testing.T) {
t.Parallel()
defer PanicRecover(t)
ctx := context.Background()
// Add any setup steps that needs to be executed before each test
rgLocation := "eastus2"
rgName := tc.resourceGroupName
mySQLServerName := GenerateTestResourceNameWithRandom("mysql-srv", 10)
mySQLReplicaName := GenerateTestResourceNameWithRandom("mysql-rep", 10)
// Create the mySQLServer object and expect the Reconcile to be created
mySQLServerInstance := v1alpha2.NewDefaultMySQLServer(mySQLServerName, rgName, rgLocation)
RequireInstance(ctx, t, tc, mySQLServerInstance)
// Create a mySQL replica
mySQLReplicaInstance := v1alpha2.NewReplicaMySQLServer(mySQLReplicaName, rgName, rgLocation, mySQLServerInstance.Status.ResourceId)
mySQLReplicaInstance.Spec.StorageProfile = nil
EnsureInstance(ctx, t, tc, mySQLReplicaInstance)
mySQLDBName := GenerateTestResourceNameWithRandom("mysql-db", 10)
// Create the mySQLDB object and expect the Reconcile to be created
mySQLDBInstance := &azurev1alpha1.MySQLDatabase{
ObjectMeta: metav1.ObjectMeta{
Name: mySQLDBName,
Namespace: "default",
},
Spec: azurev1alpha1.MySQLDatabaseSpec{
Server: mySQLServerName,
ResourceGroup: rgName,
},
}
EnsureInstance(ctx, t, tc, mySQLDBInstance)
mySQLAdmin := &azurev1alpha1.MySQLServerAdministrator{
ObjectMeta: metav1.ObjectMeta{
Name: "admin",
Namespace: "default",
},
Spec: azurev1alpha1.MySQLServerAdministratorSpec{
ResourceGroup: rgName,
Server: mySQLServerName,
AdministratorType: azurev1alpha1.MySQLServerAdministratorTypeActiveDirectory,
// The below fields are for a user managed identity which exists in the ASO-CI subscription
// TODO: That means this test won't pass locally if not run against that sub...
TenantId: "72f988bf-86f1-41af-91ab-2d7cd011db47",
Login: "azureserviceoperator-test-mi",
Sid: "ad84ef71-31fc-4797-b970-48bd515edf5c",
},
}
EnsureInstance(ctx, t, tc, mySQLAdmin)
// Delete the admin
EnsureDelete(ctx, t, tc, mySQLAdmin)
ruleName := GenerateTestResourceNameWithRandom("mysql-fw", 10)
// This rule opens access to the public internet, but in this case
// there's literally no data in the database
ruleInstance := &azurev1alpha1.MySQLFirewallRule{
ObjectMeta: metav1.ObjectMeta{
Name: ruleName,
Namespace: "default",
},
Spec: azurev1alpha1.MySQLFirewallRuleSpec{
Server: mySQLServerName,
ResourceGroup: rgName,
StartIPAddress: "0.0.0.0",
EndIPAddress: "255.255.255.255",
},
}
EnsureInstance(ctx, t, tc, ruleInstance)
// Create user and ensure it can be updated
RunMySQLUserHappyPath(ctx, t, mySQLServerName, mySQLDBName, rgName)
// Create VNet and VNetRules -----
RunMySqlVNetRuleHappyPath(t, mySQLServerName, rgLocation)
EnsureDelete(ctx, t, tc, ruleInstance)
EnsureDelete(ctx, t, tc, mySQLDBInstance)
EnsureDelete(ctx, t, tc, mySQLServerInstance)
EnsureDelete(ctx, t, tc, mySQLReplicaInstance)
}
func RunMySQLUserHappyPath(ctx context.Context, t *testing.T, mySQLServerName string, mySQLDBName string, rgName string) {
assert := assert.New(t)
// Create a user in the DB
username := GenerateTestResourceNameWithRandom("user", 10)
user := &azurev1alpha1.MySQLUser{
ObjectMeta: metav1.ObjectMeta{
Name: username,
Namespace: "default",
},
Spec: azurev1alpha1.MySQLUserSpec{
ResourceGroup: rgName,
Server: mySQLServerName,
DbName: mySQLDBName,
Username: username,
Roles: []string{"SELECT"},
},
}
EnsureInstance(ctx, t, tc, user)
// Update user
namespacedName := types.NamespacedName{Name: username, Namespace: "default"}
err := tc.k8sClient.Get(ctx, namespacedName, user)
assert.NoError(err)
updatedRoles := []string{"UPDATE", "DELETE", "CREATE", "DROP"}
user.Spec.Roles = updatedRoles
err = tc.k8sClient.Update(ctx, user)
assert.NoError(err)
// TODO: Ugh this is fragile, the path to the secret should probably be set on the status?
// See issue here: https://github.com/Azure/azure-service-operator/issues/1318
secretNamespacedName := types.NamespacedName{Name: mySQLServerName, Namespace: "default"}
adminSecret, err := tc.secretClient.Get(ctx, secretNamespacedName)
adminUser := string(adminSecret["fullyQualifiedUsername"])
adminPassword := string(adminSecret[mysqluser.MSecretPasswordKey])
fullServerName := string(adminSecret["fullyQualifiedServerName"])
db, err := mysql.ConnectToSqlDB(
ctx,
mysql.MySQLDriverName,
fullServerName,
mySQLDBName,
mysql.MySQLServerPort,
adminUser,
adminPassword)
assert.NoError(err)
assert.Eventually(func() bool {
roles, err := mysql.ExtractUserRoles(ctx, db, username, mySQLDBName)
assert.NoError(err)
if len(roles) != len(updatedRoles) {
return false
}
for _, role := range updatedRoles {
if _, ok := roles[role]; !ok {
return false
}
}
return true
}, tc.timeout, tc.retry, "waiting for DB user to be updated")
}
<file_sep># Information about the Resource post deployment
Many of the Azure resources have access information like connection strings, access keys, admin user password etc. that is required by applications consuming the resource. This information is stored as secrets after resource creation.
The operator provides two options to store these secrets:
1. **Kubernetes secrets**: This is the default option. If the secretname is not specified in the Spec, a secret with the same name as ObjectMeta.name is created.
2. **Azure Keyvault secrets**: You can specify the name of the Azure Keyvault to use to store secrets through the environment variable `AZURE_OPERATOR_KEYVAULT`.
If the secretname is not specified in the Spec, the secret in Keyvault is normally created with the name `<kubernetes-namespace-of=resource>-<ObjectMeta.name>`. The namespace is preprended to the name to avoid name collisions across Kubernetes namespaces.
```
export AZURE_OPERATOR_KEYVAULT=OperatorSecretKeyVault
```
Some things to note about this Keyvault:
(i) The Keyvault should have an access policy added for the identity under which the Operator runs as. This access policy should include at least `get`, `set`, `list` and `delete` Secret permissions.
(ii) You can use a Keyvault with "Soft delete" enabled. However, you cannot use a Keyvault with "Purge Protection" enabled, as this prevents the secrets from being deleted and causes issues if a resource with the same name is re-deployed.
## Per resource Keyvault
In addition to being able to specify an Azure Keyvault to store secrets, you also have the option to specify a different Keyvault per resource.
Some situations may require that you use a different Keyvault to store the admin password for the Azure SQL server from the Keyvault used to store the connection string for eventhubs. You can specify the Keyvault name in the Spec field `keyVaultToStoreSecrets`. When this is specified, the secrets from provisioning of that resource will be stored in this Keyvault instead of the global one configured for the operator.<file_sep>// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
package azuresqluser
import (
"context"
"database/sql"
"fmt"
"reflect"
"strings"
azuresql "github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/v3.0/sql"
"github.com/Azure/azure-service-operator/pkg/helpers"
azuresqlshared "github.com/Azure/azure-service-operator/pkg/resourcemanager/azuresql/azuresqlshared"
"github.com/Azure/azure-service-operator/pkg/resourcemanager/config"
"github.com/Azure/azure-service-operator/pkg/secrets"
"github.com/Azure/azure-service-operator/api/v1alpha1"
"k8s.io/apimachinery/pkg/runtime"
_ "github.com/denisenkom/go-mssqldb"
"k8s.io/apimachinery/pkg/types"
)
// SqlServerPort is the default server port for sql server
const SqlServerPort = 1433
// DriverName is driver name for db connection
const DriverName = "sqlserver"
// SecretUsernameKey is the username key in secret
const SecretUsernameKey = "username"
// SecretPasswordKey is the password key in secret
const SecretPasswordKey = "<PASSWORD>"
type AzureSqlUserManager struct {
Creds config.Credentials
SecretClient secrets.SecretClient
Scheme *runtime.Scheme
}
func NewAzureSqlUserManager(creds config.Credentials, secretClient secrets.SecretClient, scheme *runtime.Scheme) *AzureSqlUserManager {
return &AzureSqlUserManager{
Creds: creds,
SecretClient: secretClient,
Scheme: scheme,
}
}
// GetDB retrieves a database
func (m *AzureSqlUserManager) GetDB(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (azuresql.Database, error) {
dbClient, err := azuresqlshared.GetGoDbClient(m.Creds)
if err != nil {
return azuresql.Database{}, err
}
return dbClient.Get(
ctx,
resourceGroupName,
serverName,
databaseName,
)
}
// ConnectToSqlDb connects to the SQL db using the given credentials
func (m *AzureSqlUserManager) ConnectToSqlDb(ctx context.Context, drivername string, server string, database string, port int, user string, password string) (*sql.DB, error) {
fullServerAddress := fmt.Sprintf("%s."+config.Environment().SQLDatabaseDNSSuffix, server)
connString := fmt.Sprintf("server=%s;user id=%s;password=%s;port=%d;database=%s;Persist Security Info=False;Pooling=False;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30", fullServerAddress, user, password, port, database)
db, err := sql.Open(drivername, connString)
if err != nil {
return db, err
}
err = db.PingContext(ctx)
if err != nil {
return db, err
}
return db, err
}
// GrantUserRoles grants roles to a user for a given database
func (m *AzureSqlUserManager) GrantUserRoles(ctx context.Context, user string, roles []string, db *sql.DB) error {
var errorStrings []string
for _, role := range roles {
tsql := "sp_addrolemember @role, @user"
_, err := db.ExecContext(
ctx, tsql,
sql.Named("role", role),
sql.Named("user", user),
)
if err != nil {
errorStrings = append(errorStrings, err.Error())
}
}
if len(errorStrings) != 0 {
return fmt.Errorf(strings.Join(errorStrings, "\n"))
}
return nil
}
// CreateUser creates user with secret credentials
func (m *AzureSqlUserManager) CreateUser(ctx context.Context, secret map[string][]byte, db *sql.DB) (string, error) {
newUser := string(secret[SecretUsernameKey])
newPassword := string(secret[SecretPasswordKey])
// make an effort to prevent sql injection
if err := helpers.FindBadChars(newUser); err != nil {
return "", fmt.Errorf("Problem found with username: %v", err)
}
if err := helpers.FindBadChars(newPassword); err != nil {
return "", fmt.Errorf("Problem found with password: %v", err)
}
tsql := fmt.Sprintf("CREATE USER \"%s\" WITH PASSWORD='%s'", newUser, newPassword)
_, err := db.ExecContext(ctx, tsql)
// TODO: Have db lib do string interpolation
//tsql := fmt.Sprintf(`CREATE USER @User WITH PASSWORD='<PASSWORD>'`)
//_, err := db.ExecContext(ctx, tsql, sql.Named("User", newUser), sql.Named("Password", newPassword))
if err != nil {
return newUser, err
}
return newUser, nil
}
// UpdateUser - Updates user password
func (m *AzureSqlUserManager) UpdateUser(ctx context.Context, secret map[string][]byte, db *sql.DB) error {
user := string(secret[SecretUsernameKey])
newPassword := <PASSWORD>()
// make an effort to prevent sql injection
if err := helpers.FindBadChars(user); err != nil {
return fmt.Errorf("Problem found with username: %v", err)
}
if err := helpers.FindBadChars(newPassword); err != nil {
return fmt.Errorf("Problem found with password: %v", err)
}
tsql := fmt.Sprintf("ALTER USER \"%s\" WITH PASSWORD='%s'", user, newPassword)
_, err := db.ExecContext(ctx, tsql)
return err
}
// UserExists checks if db contains user
func (m *AzureSqlUserManager) UserExists(ctx context.Context, db *sql.DB, username string) (bool, error) {
res, err := db.ExecContext(
ctx,
"SELECT * FROM sysusers WHERE NAME=@user",
sql.Named("user", username),
)
if err != nil {
return false, err
}
rows, err := res.RowsAffected()
return rows > 0, err
}
// DropUser drops a user from db
func (m *AzureSqlUserManager) DropUser(ctx context.Context, db *sql.DB, user string) error {
tsql := fmt.Sprintf("DROP USER %q", user)
_, err := db.ExecContext(ctx, tsql)
return err
}
// DeleteSecrets deletes the secrets associated with a SQLUser
func (m *AzureSqlUserManager) DeleteSecrets(ctx context.Context, instance *v1alpha1.AzureSQLUser, secretClient secrets.SecretClient) (bool, error) {
// determine our key namespace - if we're persisting to kube, we should use the actual instance namespace.
// In keyvault we have some creative freedom to allow more flexibility
secretKey := GetNamespacedName(instance, secretClient)
// delete standard user secret
err := secretClient.Delete(
ctx,
secretKey,
)
if err != nil {
instance.Status.Message = "failed to delete secret, err: " + err.Error()
return false, err
}
// delete all the custom formatted secrets if keyvault is in use
keyVaultEnabled := reflect.TypeOf(secretClient).Elem().Name() == "KeyvaultSecretClient"
if keyVaultEnabled {
customFormatNames := []string{
"adonet",
"adonet-urlonly",
"jdbc",
"jdbc-urlonly",
"odbc",
"odbc-urlonly",
"server",
"database",
"username",
"password",
}
for _, formatName := range customFormatNames {
key := types.NamespacedName{Namespace: secretKey.Namespace, Name: instance.Name + "-" + formatName}
err = secretClient.Delete(
ctx,
key,
)
if err != nil {
instance.Status.Message = "failed to delete secret, err: " + err.Error()
return false, err
}
}
}
return false, nil
}
// GetOrPrepareSecret gets or creates a secret
func (m *AzureSqlUserManager) GetOrPrepareSecret(ctx context.Context, instance *v1alpha1.AzureSQLUser, secretClient secrets.SecretClient) map[string][]byte {
key := GetNamespacedName(instance, secretClient)
secret, err := secretClient.Get(ctx, key)
if err != nil {
// @todo: find out whether this is an error due to non existing key or failed conn
pw := helpers.NewPassword()
return map[string][]byte{
"username": []byte(""),
"password": []byte(pw),
"azureSqlServerNamespace": []byte(instance.Namespace),
"azureSqlServerName": []byte(instance.Spec.Server),
"fullyQualifiedServerName": []byte(instance.Spec.Server + "." + config.Environment().SQLDatabaseDNSSuffix),
"azureSqlDatabaseName": []byte(instance.Spec.DbName),
}
}
return secret
}
// GetNamespacedName gets the namespaced-name
func GetNamespacedName(instance *v1alpha1.AzureSQLUser, secretClient secrets.SecretClient) types.NamespacedName {
var namespacedName types.NamespacedName
keyVaultEnabled := reflect.TypeOf(secretClient).Elem().Name() == "KeyvaultSecretClient"
if keyVaultEnabled {
// For a keyvault secret store, check for supplied namespace parameters
var dbUserCustomNamespace string
if instance.Spec.KeyVaultSecretPrefix != "" {
dbUserCustomNamespace = instance.Spec.KeyVaultSecretPrefix
} else {
dbUserCustomNamespace = "azuresqluser-" + instance.Spec.Server + "-" + instance.Spec.DbName
}
namespacedName = types.NamespacedName{Namespace: dbUserCustomNamespace, Name: instance.Name}
} else {
namespacedName = types.NamespacedName{Name: instance.Name, Namespace: instance.Namespace}
}
return namespacedName
}
<file_sep>// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
package azuresqlfailovergroup
import (
"context"
"fmt"
"github.com/Azure/azure-service-operator/api/v1alpha1"
azurev1alpha1 "github.com/Azure/azure-service-operator/api/v1alpha1"
"github.com/Azure/azure-service-operator/api/v1beta1"
"github.com/Azure/azure-service-operator/pkg/errhelp"
"github.com/Azure/azure-service-operator/pkg/helpers"
"github.com/Azure/azure-service-operator/pkg/resourcemanager"
azuresqlshared "github.com/Azure/azure-service-operator/pkg/resourcemanager/azuresql/azuresqlshared"
"github.com/Azure/azure-service-operator/pkg/secrets"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
)
// Ensure creates a sqlfailovergroup
func (fg *AzureSqlFailoverGroupManager) Ensure(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) {
options := &resourcemanager.Options{}
for _, opt := range opts {
opt(options)
}
if options.SecretClient != nil {
fg.SecretClient = options.SecretClient
}
instance, err := fg.convert(obj)
if err != nil {
return false, err
}
groupName := instance.Spec.ResourceGroup
serverName := instance.Spec.Server
failoverGroupName := instance.ObjectMeta.Name
sqlFailoverGroupProperties := azuresqlshared.SQLFailoverGroupProperties{
FailoverPolicy: v1alpha1.ReadWriteEndpointFailoverPolicy(instance.Spec.FailoverPolicy),
FailoverGracePeriod: instance.Spec.FailoverGracePeriod,
SecondaryServer: instance.Spec.SecondaryServer,
SecondaryServerResourceGroup: instance.Spec.SecondaryServerResourceGroup,
DatabaseList: instance.Spec.DatabaseList,
}
resp, err := fg.GetFailoverGroup(ctx, groupName, serverName, failoverGroupName)
if err == nil {
if *resp.ReplicationState == "SEEDING" {
return false, nil
}
instance.Status.Provisioning = false
instance.Status.Provisioned = true
instance.Status.Message = resourcemanager.SuccessMsg
instance.Status.ResourceId = *resp.ID
return true, nil
}
instance.Status.Message = fmt.Sprintf("AzureSqlFailoverGroup Get error %s", err.Error())
requeuErrors := []string{
errhelp.ResourceGroupNotFoundErrorCode,
errhelp.ParentNotFoundErrorCode,
}
azerr := errhelp.NewAzureError(err)
if helpers.ContainsString(requeuErrors, azerr.Type) {
instance.Status.Provisioning = false
return false, nil
}
_, err = fg.CreateOrUpdateFailoverGroup(ctx, groupName, serverName, failoverGroupName, sqlFailoverGroupProperties)
if err != nil {
instance.Status.Message = err.Error()
catch := []string{
errhelp.ParentNotFoundErrorCode,
errhelp.ResourceGroupNotFoundErrorCode,
errhelp.NotFoundErrorCode,
errhelp.AsyncOpIncompleteError,
errhelp.ResourceNotFound,
errhelp.AlreadyExists,
errhelp.FailoverGroupBusy,
}
catchUnrecoverableErrors := []string{
errhelp.InvalidFailoverGroupRegion,
}
azerr := errhelp.NewAzureError(err)
if helpers.ContainsString(catch, azerr.Type) {
return false, nil
}
if helpers.ContainsString(catchUnrecoverableErrors, azerr.Type) {
// Unrecoverable error, so stop reconcilation
instance.Status.Message = "Reconcilation hit unrecoverable error " + err.Error()
return true, nil
}
return false, err
}
secret, _ := fg.GetOrPrepareSecret(ctx, instance)
// create or update the secret
key := types.NamespacedName{Name: instance.ObjectMeta.Name, Namespace: instance.Namespace}
err = fg.SecretClient.Upsert(
ctx,
key,
secret,
secrets.WithOwner(instance),
secrets.WithScheme(fg.Scheme),
)
if err != nil {
return false, err
}
// create was received successfully but replication is not done
return false, nil
}
// Delete drops a sqlfailovergroup
func (fg *AzureSqlFailoverGroupManager) Delete(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) {
options := &resourcemanager.Options{}
for _, opt := range opts {
opt(options)
}
if options.SecretClient != nil {
fg.SecretClient = options.SecretClient
}
instance, err := fg.convert(obj)
if err != nil {
return false, err
}
groupName := instance.Spec.ResourceGroup
serverName := instance.Spec.Server
failoverGroupName := instance.ObjectMeta.Name
// key for Secret to delete on successful provision
key := types.NamespacedName{Name: instance.ObjectMeta.Name, Namespace: instance.Namespace}
_, err = fg.DeleteFailoverGroup(ctx, groupName, serverName, failoverGroupName)
if err != nil {
instance.Status.Message = err.Error()
azerr := errhelp.NewAzureError(err)
// these errors are expected
ignore := []string{
errhelp.AsyncOpIncompleteError,
errhelp.FailoverGroupBusy,
}
// this means the thing doesn't exist
finished := []string{
errhelp.ResourceNotFound,
}
if helpers.ContainsString(ignore, azerr.Type) {
return true, nil
}
if helpers.ContainsString(finished, azerr.Type) {
// Best case deletion of secret
fg.SecretClient.Delete(ctx, key)
return false, nil
}
instance.Status.Message = fmt.Sprintf("AzureSqlFailoverGroup Delete failed with: %s", err.Error())
return false, err
}
instance.Status.Message = fmt.Sprintf("Delete AzureSqlFailoverGroup succeeded")
// Best case deletion of secret
fg.SecretClient.Delete(ctx, key)
return false, nil
}
// GetParents returns the parents of sqlfailovergroup
func (fg *AzureSqlFailoverGroupManager) GetParents(obj runtime.Object) ([]resourcemanager.KubeParent, error) {
instance, err := fg.convert(obj)
if err != nil {
return nil, err
}
return []resourcemanager.KubeParent{
{
Key: types.NamespacedName{
Namespace: instance.Namespace,
Name: instance.Spec.Server,
},
Target: &azurev1alpha1.AzureSqlServer{},
},
{
Key: types.NamespacedName{
Namespace: instance.Namespace,
Name: instance.Spec.ResourceGroup,
},
Target: &azurev1alpha1.ResourceGroup{},
},
}, nil
}
// GetStatus gets the ASOStatus
func (g *AzureSqlFailoverGroupManager) GetStatus(obj runtime.Object) (*azurev1alpha1.ASOStatus, error) {
instance, err := g.convert(obj)
if err != nil {
return nil, err
}
st := azurev1alpha1.ASOStatus(instance.Status)
return &st, nil
}
func (fg *AzureSqlFailoverGroupManager) convert(obj runtime.Object) (*v1beta1.AzureSqlFailoverGroup, error) {
local, ok := obj.(*v1beta1.AzureSqlFailoverGroup)
if !ok {
return nil, fmt.Errorf("failed type assertion on kind: %s", obj.GetObjectKind().GroupVersionKind().String())
}
return local, nil
}
<file_sep>#-------------------------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See https://go.microsoft.com/fwlink/?linkid=2090316 for license information.
#-------------------------------------------------------------------------------------------------------------
FROM golang:1.13.10-buster
# Configure apt, install packages and cli tools
RUN export DEBIAN_FRONTEND=noninteractive \
&& apt-get update \
&& apt-get -y install --no-install-recommends apt-transport-https ca-certificates curl gnupg2 lsb-release \
#
# Install Kubebuilder
&& curl -sL https://go.kubebuilder.io/dl/2.3.1/$(go env GOOS)/$(go env GOARCH) | tar -xz --strip-components=2 -C /usr/local/bin \
#
# Install Helm
&& curl -s https://get.helm.sh/helm-v3.2.1-linux-amd64.tar.gz | tar -zxv --strip-components=1 -C /usr/local/bin linux-amd64/helm \
#
# Install Docker CLI package source
&& curl -fsSL https://download.docker.com/linux/$(lsb_release -is | tr '[:upper:]' '[:lower:]')/gpg | (OUT=$(apt-key add - 2>&1) || echo $OUT) \
&& echo "deb [arch=amd64] https://download.docker.com/linux/$(lsb_release -is | tr '[:upper:]' '[:lower:]') $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list \
#
# Add the Azure CLI package source
&& curl -sL https://packages.microsoft.com/keys/microsoft.asc | apt-key add - 2>/dev/null \
&& echo "deb [arch=amd64] https://packages.microsoft.com/repos/azure-cli/ $(lsb_release -cs) main" > /etc/apt/sources.list.d/azure-cli.list \
#
# Install Packages
&& apt-get update \
&& apt-get install -y --no-install-recommends \
docker-ce-cli \
azure-cli \
zsh \
#
# Install ZSH shell
&& wget https://github.com/robbyrussell/oh-my-zsh/raw/master/tools/install.sh -O - | zsh || true \
#
# Clean up
&& apt-get autoremove -y \
&& apt-get clean -y \
&& rm -rf /var/lib/apt/lists/*
RUN export DEBIAN_FRONTEND=noninteractive \
#
# Install Go development tools
&& GO111MODULE=on go get -v \
golang.org/x/tools/gopls@latest \
golang.org/x/lint/golint@latest \
github.com/go-delve/delve/cmd/dlv@latest \
2>&1 \
#
# Install Go test dependencies
&& GO111MODULE=on go get -v \
github.com/jstemmer/go-junit-report@latest \
github.com/axw/gocov/gocov@latest \
github.com/AlekSi/gocov-xml \
github.com/wadey/gocovmerge \
2>&1
# Copy shares from localhost into container when new shells are created
RUN echo '\n\
if [ -d "/usr/local/share/kube-localhost" ]; then\n\
mkdir -p $HOME/.kube\n\
cp -r /usr/local/share/kube-localhost/* $HOME/.kube\n\
chown -R $(id -u) $HOME/.kube\n\
sed -i -e "s/localhost/host.docker.internal/g" $HOME/.kube/config\n\
\n\
if [ -d "/usr/local/share/minikube-localhost" ]; then\n\
mkdir -p $HOME/.minikube\n\
cp -r /usr/local/share/minikube-localhost/ca.crt $HOME/.minikube\n\
cp -r /usr/local/share/minikube-localhost/client.crt $HOME/.minikube\n\
cp -r /usr/local/share/minikube-localhost/client.key $HOME/.minikube\n\
chown -R $(id -u) $HOME/.minikube\n\
sed -i -r "s|(\s*certificate-authority:\s).*|\\1$HOME\/.minikube\/ca.crt|g" $HOME/.kube/config\n\
sed -i -r "s|(\s*client-certificate:\s).*|\\1$HOME\/.minikube\/client.crt|g" $HOME/.kube/config\n\
sed -i -r "s|(\s*client-key:\s).*|\\1$HOME\/.minikube\/client.key|g" $HOME/.kube/config\n\
fi\n\
fi\n\
if [ -d "/usr/local/share/azure-localhost" ]; then\n\
mkdir -p $HOME/.azure\n\
cp -r /usr/local/share/azure-localhost/* $HOME/.azure\n\
chown -R $(id -u) $HOME/.azure\n\
fi' | tee -a /root/.bashrc /root/.zshrc /home/${USERNAME}/.bashrc >> /home/${USERNAME}/.zshrc
<file_sep>// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
package azuresqlaction
import (
"context"
"fmt"
"strings"
azurev1alpha1 "github.com/Azure/azure-service-operator/api/v1alpha1"
"github.com/Azure/azure-service-operator/pkg/errhelp"
"github.com/Azure/azure-service-operator/pkg/helpers"
azuresqlserver "github.com/Azure/azure-service-operator/pkg/resourcemanager/azuresql/azuresqlserver"
"github.com/Azure/azure-service-operator/pkg/resourcemanager/azuresql/azuresqlshared"
azuresqluser "github.com/Azure/azure-service-operator/pkg/resourcemanager/azuresql/azuresqluser"
"github.com/Azure/azure-service-operator/pkg/resourcemanager/config"
"github.com/Azure/azure-service-operator/pkg/secrets"
"github.com/Azure/go-autorest/autorest/to"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
)
type AzureSqlActionManager struct {
Creds config.Credentials
SecretClient secrets.SecretClient
Scheme *runtime.Scheme
}
func NewAzureSqlActionManager(creds config.Credentials, secretClient secrets.SecretClient, scheme *runtime.Scheme) *AzureSqlActionManager {
return &AzureSqlActionManager{
Creds: creds,
SecretClient: secretClient,
Scheme: scheme,
}
}
func (s *AzureSqlActionManager) UpdateUserPassword(ctx context.Context, groupName string, serverName string, dbUser string, dbName string,
adminSecretKey types.NamespacedName, adminSecretClient secrets.SecretClient, userSecretClient secrets.SecretClient) error {
data, err := adminSecretClient.Get(ctx, adminSecretKey)
if err != nil {
return err
}
azuresqluserManager := azuresqluser.NewAzureSqlUserManager(s.Creds, userSecretClient, s.Scheme)
db, err := azuresqluserManager.ConnectToSqlDb(ctx, "sqlserver", serverName, dbName, 1433, string(data["username"]), string(data["password"]))
if err != nil {
return err
}
instance := &azurev1alpha1.AzureSQLUser{
ObjectMeta: metav1.ObjectMeta{
Name: dbUser,
Namespace: adminSecretKey.Namespace,
},
Spec: azurev1alpha1.AzureSQLUserSpec{
Server: serverName,
DbName: dbName,
},
}
DBSecret := azuresqluserManager.GetOrPrepareSecret(ctx, instance, userSecretClient)
// reset user from secret in case it was loaded
userExists, err := azuresqluserManager.UserExists(ctx, db, string(DBSecret["username"]))
if err != nil {
return fmt.Errorf("failed checking for user, err: %v", err)
}
if !userExists {
return fmt.Errorf("user does not exist")
}
password := <PASSWORD>()
DBSecret["password"] = []byte(<PASSWORD>)
err = azuresqluserManager.UpdateUser(ctx, DBSecret, db)
if err != nil {
return fmt.Errorf("error updating user credentials: %v", err)
}
secretKey := azuresqluser.GetNamespacedName(instance, userSecretClient)
key := types.NamespacedName{Namespace: secretKey.Namespace, Name: dbUser}
err = userSecretClient.Upsert(
ctx,
key,
DBSecret,
secrets.WithOwner(instance),
secrets.WithScheme(s.Scheme),
)
if err != nil {
return fmt.Errorf("failed to update secret: %v", err)
}
return nil
}
// UpdateAdminPassword gets the server instance from Azure, updates the admin password
// for the server and stores the new password in the secret
func (s *AzureSqlActionManager) UpdateAdminPassword(ctx context.Context, groupName string, serverName string, secretKey types.NamespacedName, secretClient secrets.SecretClient) error {
azuresqlserverManager := azuresqlserver.NewAzureSqlServerManager(s.Creds, secretClient, s.Scheme)
// Get the SQL server instance
server, err := azuresqlserverManager.GetServer(ctx, groupName, serverName)
if err != nil {
return err
}
// We were able to get the server instance from Azure, so we proceed to update the admin password
azureSqlServerProperties := azuresqlshared.SQLServerProperties{
AdministratorLogin: server.ServerProperties.AdministratorLogin,
AdministratorLoginPassword: server.ServerProperties.AdministratorLoginPassword,
}
// Get the secret from the secretclient. If we cannot get this we return err right away.
data, err := secretClient.Get(ctx, secretKey)
if err != nil {
return err
}
// Generate a new password
new<PASSWORD> := <PASSWORD>()
azureSqlServerProperties.AdministratorLoginPassword = <PASSWORD>(new<PASSWORD>)
// Update the SQL server with the newly generated password
_, _, err = azuresqlserverManager.CreateOrUpdateSQLServer(ctx, groupName, *server.Location, serverName, server.Tags, azureSqlServerProperties, true)
if err != nil {
azerr := errhelp.NewAzureError(err)
if !strings.Contains(azerr.Type, errhelp.AsyncOpIncompleteError) {
return err
}
}
// Update the secret with the new password
data["password"] = []byte(*azureSqlServerProperties.AdministratorLoginPassword)
err = secretClient.Upsert(
ctx,
secretKey,
data,
)
if err != nil {
return err
}
return nil
}
<file_sep>// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
package kube
import (
"context"
"fmt"
"github.com/Azure/azure-service-operator/pkg/secrets"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
)
type KubeSecretClient struct {
KubeClient client.Client
}
func New(kubeclient client.Client) *KubeSecretClient {
return &KubeSecretClient{
KubeClient: kubeclient,
}
}
func (k *KubeSecretClient) Create(ctx context.Context, key types.NamespacedName, data map[string][]byte, opts ...secrets.SecretOption) error {
options := &secrets.Options{}
for _, opt := range opts {
opt(options)
}
if options.Flatten {
return fmt.Errorf("FlattenedSecretsNotSupported")
}
secret := &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: key.Name,
Namespace: key.Namespace,
},
// Needed to avoid nil map error
Data: map[string][]byte{},
Type: "Opaque",
}
if err := k.KubeClient.Get(ctx, key, secret); err == nil {
return fmt.Errorf("secret already exists")
}
secret.Data = data
if options.Owner != nil && options.Scheme != nil {
if err := controllerutil.SetControllerReference(options.Owner, secret, options.Scheme); err != nil {
return err
}
}
return k.KubeClient.Create(ctx, secret)
}
func (k *KubeSecretClient) Upsert(ctx context.Context, key types.NamespacedName, data map[string][]byte, opts ...secrets.SecretOption) error {
options := &secrets.Options{}
for _, opt := range opts {
opt(options)
}
if options.Flatten {
return fmt.Errorf("FlattenedSecretsNotSupported")
}
secret := &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: key.Name,
Namespace: key.Namespace,
},
// Needed to avoid nil map error
Data: map[string][]byte{},
Type: "Opaque",
}
_, err := controllerutil.CreateOrUpdate(ctx, k.KubeClient, secret, func() error {
for k, v := range data {
secret.Data[k] = v
}
if options.Owner != nil && options.Scheme != nil {
// the uid is required for SetControllerReference, try to populate it if it isn't
if options.Owner.GetUID() == "" {
ownerKey := types.NamespacedName{Name: options.Owner.GetName(), Namespace: options.Owner.GetNamespace()}
if err := k.KubeClient.Get(ctx, ownerKey, options.Owner); err != nil {
return client.IgnoreNotFound(err)
}
}
if err := controllerutil.SetControllerReference(options.Owner, secret, options.Scheme); err != nil {
return err
}
}
return nil
})
return err
}
func (k *KubeSecretClient) Get(ctx context.Context, key types.NamespacedName) (map[string][]byte, error) {
data := map[string][]byte{}
secret := &v1.Secret{}
if err := k.KubeClient.Get(ctx, key, secret); err != nil {
return data, err
}
for k, v := range secret.Data {
data[k] = v
}
return data, nil
}
func (k *KubeSecretClient) Delete(ctx context.Context, key types.NamespacedName) error {
secret := &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: key.Name,
Namespace: key.Namespace,
},
// Needed to avoid nil map error
Data: map[string][]byte{},
Type: "Opaque",
}
if err := k.KubeClient.Get(ctx, key, secret); err != nil {
return nil
}
return k.KubeClient.Delete(ctx, secret)
}
<file_sep>ACR_NAME='azureserviceoperator'
echo "ACR_NAME", $ACR_NAME
echo "azureserviceoperator_image", $(azureserviceoperator_image)
echo "azureserviceoperator_image_base", $(azureserviceoperator_image_base)
echo "azureserviceoperator_image_latest", $(azureserviceoperator_image_latest)
echo "azureserviceoperator_image_public", $(azureserviceoperator_image_public)
echo "azureserviceoperator_image_version", $(azureserviceoperator_image_version)
az acr login --name $ACR_NAME
docker pull $ACR_NAME.azurecr.io/$(azureserviceoperator_image)
docker tag $ACR_NAME.azurecr.io/$(azureserviceoperator_image) $ACR_NAME.azurecr.io/$(azureserviceoperator_image_latest)
docker tag $ACR_NAME.azurecr.io/$(azureserviceoperator_image) $ACR_NAME.azurecr.io/$(azureserviceoperator_image_public)
docker image ls
docker push $ACR_NAME.azurecr.io/$(azureserviceoperator_image_public)
docker push $ACR_NAME.azurecr.io/$(azureserviceoperator_image_latest)
<file_sep>// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// +build all postgresqluser
package controllers
import (
"context"
"testing"
azurev1alpha1 "github.com/Azure/azure-service-operator/api/v1alpha1"
"github.com/Azure/azure-service-operator/pkg/errhelp"
"github.com/Azure/azure-service-operator/pkg/helpers"
"github.com/stretchr/testify/assert"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func TestPostgreSQLUserControllerNoAdminSecret(t *testing.T) {
t.Parallel()
defer PanicRecover(t)
ctx := context.Background()
var postgresqlServerName string
var postgresqlDatabaseName string
var postgresqlUser *azurev1alpha1.PostgreSQLUser
postgresqlServerName = GenerateTestResourceNameWithRandom("psqlserver-test", 10)
postgresqlDatabaseName = GenerateTestResourceNameWithRandom("psqldb-test", 10)
resourceGroup := GenerateTestResourceNameWithRandom("myrg", 10)
pusername := "psql-test-user" + helpers.RandomString(10)
roles := []string{"azure_pg_admin"}
postgresqlUser = &azurev1alpha1.PostgreSQLUser{
ObjectMeta: metav1.ObjectMeta{
Name: pusername,
Namespace: "default",
},
Spec: azurev1alpha1.PostgreSQLUserSpec{
ResourceGroup: resourceGroup,
Server: postgresqlServerName,
DbName: postgresqlDatabaseName,
AdminSecret: "",
Roles: roles,
},
}
EnsureInstanceWithResult(ctx, t, tc, postgresqlUser, "admin secret", false)
EnsureDelete(ctx, t, tc, postgresqlUser)
}
func TestPostgreSQLUserControllerNoResourceGroup(t *testing.T) {
t.Parallel()
defer PanicRecover(t)
ctx := context.Background()
assert := assert.New(t)
var err error
var psqlServerName string
var psqlDatabaseName string
var psqlUser *azurev1alpha1.PostgreSQLUser
psqlServerName = GenerateTestResourceNameWithRandom("psqlserver-test", 10)
psqlDatabaseName = GenerateTestResourceNameWithRandom("psqldb-test", 10)
pusername := "psql-test-user" + helpers.RandomString(10)
roles := []string{"azure_pg_admin"}
secret := &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: psqlServerName,
Namespace: "default",
},
// Needed to avoid nil map error
Data: map[string][]byte{
"username": []byte("username"),
"password": []byte("<PASSWORD>"),
},
Type: "Opaque",
}
// Create the sqlUser
err = tc.k8sClient.Create(ctx, secret)
assert.Equal(nil, err, "create admin secret in k8s")
psqlUser = &azurev1alpha1.PostgreSQLUser{
ObjectMeta: metav1.ObjectMeta{
Name: pusername,
Namespace: "default",
},
Spec: azurev1alpha1.PostgreSQLUserSpec{
Server: psqlServerName,
DbName: psqlDatabaseName,
AdminSecret: "",
Roles: roles,
ResourceGroup: "fakerg" + helpers.RandomString(10),
},
}
EnsureInstanceWithResult(ctx, t, tc, psqlUser, errhelp.ResourceGroupNotFoundErrorCode, false)
EnsureDelete(ctx, t, tc, psqlUser)
}
<file_sep>// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
package azuresqlfailovergroup
import (
"context"
"net/http"
"github.com/Azure/azure-service-operator/api/v1beta1"
azuresqlshared "github.com/Azure/azure-service-operator/pkg/resourcemanager/azuresql/azuresqlshared"
"github.com/Azure/azure-service-operator/pkg/resourcemanager/config"
"github.com/Azure/azure-service-operator/pkg/secrets"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
sql "github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/v3.0/sql"
"github.com/Azure/go-autorest/autorest"
)
type AzureSqlFailoverGroupManager struct {
Creds config.Credentials
SecretClient secrets.SecretClient
Scheme *runtime.Scheme
}
func NewAzureSqlFailoverGroupManager(creds config.Credentials, secretClient secrets.SecretClient, scheme *runtime.Scheme) *AzureSqlFailoverGroupManager {
return &AzureSqlFailoverGroupManager{
Creds: creds,
SecretClient: secretClient,
Scheme: scheme,
}
}
// GetServer returns a SQL server
func (m *AzureSqlFailoverGroupManager) GetServer(ctx context.Context, resourceGroupName string, serverName string) (result sql.Server, err error) {
serversClient, err := azuresqlshared.GetGoServersClient(m.Creds)
if err != nil {
return sql.Server{}, err
}
return serversClient.Get(
ctx,
resourceGroupName,
serverName,
)
}
// GetDB retrieves a database
func (m *AzureSqlFailoverGroupManager) GetDB(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (sql.Database, error) {
dbClient, err := azuresqlshared.GetGoDbClient(m.Creds)
if err != nil {
return sql.Database{}, err
}
return dbClient.Get(
ctx,
resourceGroupName,
serverName,
databaseName,
)
}
// GetFailoverGroup retrieves a failover group
func (m *AzureSqlFailoverGroupManager) GetFailoverGroup(ctx context.Context, resourceGroupName string, serverName string, failovergroupname string) (sql.FailoverGroup, error) {
failoverGroupsClient, err := azuresqlshared.GetGoFailoverGroupsClient(m.Creds)
if err != nil {
return sql.FailoverGroup{}, err
}
return failoverGroupsClient.Get(
ctx,
resourceGroupName,
serverName,
failovergroupname,
)
}
// DeleteFailoverGroup deletes a failover group
func (m *AzureSqlFailoverGroupManager) DeleteFailoverGroup(ctx context.Context, resourceGroupName string, serverName string, failoverGroupName string) (result autorest.Response, err error) {
result = autorest.Response{
Response: &http.Response{
StatusCode: 200,
},
}
// check to see if the server exists, if it doesn't then short-circuit
_, err = m.GetServer(ctx, resourceGroupName, serverName)
if err != nil {
return result, nil
}
// check to see if the failover group exists, if it doesn't then short-circuit
_, err = m.GetFailoverGroup(ctx, resourceGroupName, serverName, failoverGroupName)
if err != nil {
return result, nil
}
failoverGroupsClient, err := azuresqlshared.GetGoFailoverGroupsClient(m.Creds)
if err != nil {
return result, err
}
future, err := failoverGroupsClient.Delete(
ctx,
resourceGroupName,
serverName,
failoverGroupName,
)
if err != nil {
return result, err
}
return future.Result(failoverGroupsClient)
}
// CreateOrUpdateFailoverGroup creates a failover group
func (m *AzureSqlFailoverGroupManager) CreateOrUpdateFailoverGroup(ctx context.Context, resourceGroupName string, serverName string, failovergroupname string, properties azuresqlshared.SQLFailoverGroupProperties) (result sql.FailoverGroupsCreateOrUpdateFuture, err error) {
failoverGroupsClient, err := azuresqlshared.GetGoFailoverGroupsClient(m.Creds)
if err != nil {
return sql.FailoverGroupsCreateOrUpdateFuture{}, err
}
// Construct a PartnerInfo object from the server name
// Get resource ID from the servername to use
server, err := m.GetServer(ctx, properties.SecondaryServerResourceGroup, properties.SecondaryServer)
if err != nil {
return result, nil
}
secServerResourceID := server.ID
partnerServerInfo := sql.PartnerInfo{
ID: secServerResourceID,
ReplicationRole: sql.Secondary,
}
partnerServerInfoArray := []sql.PartnerInfo{partnerServerInfo}
var databaseIDArray []string
// Parse the Databases in the Databaselist and form array of Resource IDs
for _, each := range properties.DatabaseList {
database, err := m.GetDB(ctx, resourceGroupName, serverName, each)
if err != nil {
return result, err
}
databaseIDArray = append(databaseIDArray, *database.ID)
}
// Construct FailoverGroupProperties struct
failoverGroupProperties := sql.FailoverGroupProperties{
ReadWriteEndpoint: &sql.FailoverGroupReadWriteEndpoint{
FailoverPolicy: azuresqlshared.TranslateFailoverPolicy(properties.FailoverPolicy),
FailoverWithDataLossGracePeriodMinutes: &properties.FailoverGracePeriod,
},
PartnerServers: &partnerServerInfoArray,
Databases: &databaseIDArray,
}
failoverGroup := sql.FailoverGroup{
FailoverGroupProperties: &failoverGroupProperties,
}
return failoverGroupsClient.CreateOrUpdate(
ctx,
resourceGroupName,
serverName,
failovergroupname,
failoverGroup)
}
func (m *AzureSqlFailoverGroupManager) GetOrPrepareSecret(ctx context.Context, instance *v1beta1.AzureSqlFailoverGroup) (map[string][]byte, error) {
failovergroupname := instance.ObjectMeta.Name
azuresqlprimaryserver := instance.Spec.Server
azuresqlsecondaryserver := instance.Spec.SecondaryServer
secret := map[string][]byte{}
key := types.NamespacedName{Name: failovergroupname, Namespace: instance.Namespace}
if stored, err := m.SecretClient.Get(ctx, key); err == nil {
return stored, nil
}
secret["azureSqlPrimaryServer"] = []byte(azuresqlprimaryserver)
secret["readWriteListenerEndpoint"] = []byte(failovergroupname + "." + config.Environment().SQLDatabaseDNSSuffix)
secret["azureSqlSecondaryServer"] = []byte(azuresqlsecondaryserver)
secret["readOnlyListenerEndpoint"] = []byte(failovergroupname + ".secondary." + config.Environment().SQLDatabaseDNSSuffix)
return secret, nil
}
<file_sep>// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
package azuresqlfailovergroup
import (
"context"
"github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/v3.0/sql"
"github.com/Azure/azure-service-operator/pkg/resourcemanager"
azuresqlshared "github.com/Azure/azure-service-operator/pkg/resourcemanager/azuresql/azuresqlshared"
"github.com/Azure/go-autorest/autorest"
)
type SqlFailoverGroupManager interface {
CreateOrUpdateFailoverGroup(ctx context.Context, resourceGroupName string, serverName string, failovergroupname string, properties azuresqlshared.SQLFailoverGroupProperties) (result sql.FailoverGroupsCreateOrUpdateFuture, err error)
DeleteFailoverGroup(ctx context.Context, resourceGroupName string, serverName string, failoverGroupName string) (result autorest.Response, err error)
GetFailoverGroup(ctx context.Context, resourceGroupName string, serverName string, failovergroupname string) (sql.FailoverGroup, error)
GetServer(ctx context.Context, resourceGroupName string, serverName string) (result sql.Server, err error)
GetDB(ctx context.Context, resourceGroupName string, serverName string, databaseName string) (sql.Database, error)
resourcemanager.ARMClient
}
<file_sep># Event Hubs Operator
## Resources supported
The Event Hubs operator can be used to provision the following resources.
1. Event Hubs - Deploys an Event Hubs instance given the Event Hubs namespace, Resource Group and Location.
1. [Sample YAML file](config/samples/azure_v1alpha1_eventhub.yaml)
2. Event Hubs namespace - Deploys an Event Hubs namespace given the resource group and location. Also has the ability to configure SKU, properties, and network rules.
1. [Sample YAML file](config/samples/azure_v1alpha1_eventhub_namespace.yaml)
3. Consumer groups - Deploys a consumer group given the event hub, Event Hubs namespace and resource group.
1. [Sample YAML file](config/samples/azure_v1alpha1_capture.yaml)
### Event Hubs - Deployment output
The Event Hubs operator deploys an event hub in the specified namespace according to the spec.
As an output of deployment, the operator stores a JSON formatted secret with the following fields. For more details on where the secrets are stored, look [here](docs/howto/secrets.md).
- `primaryConnectionString`
- `secondaryConnectionString`
- `primaryKey`
- `secondaryKey`
- `sharedaccessKey`
- `eventhubNamespace`
- `eventhubName`
## Deploy, view and delete resources
You can follow the steps [here](/docs/howto/resourceprovision.md) to deploy, view and delete resources.
<!-- ## How would you use the Event Hubs Operator to support a real application?
TODO: Demo app -->
<file_sep>// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
package mysqlaaduser
import (
"context"
"database/sql"
"fmt"
"strings"
"github.com/pkg/errors"
"github.com/Azure/azure-service-operator/pkg/helpers"
"github.com/Azure/azure-service-operator/pkg/resourcemanager/config"
"github.com/Azure/azure-service-operator/pkg/resourcemanager/mysql"
mysqldatabase "github.com/Azure/azure-service-operator/pkg/resourcemanager/mysql/database"
"github.com/Azure/azure-service-operator/api/v1alpha1"
"github.com/Azure/azure-service-operator/api/v1alpha2"
"github.com/Azure/azure-service-operator/pkg/errhelp"
"github.com/Azure/azure-service-operator/pkg/resourcemanager"
_ "github.com/go-sql-driver/mysql" //sql drive link
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
)
type MySQLAADUserManager struct {
identityFinder *helpers.AADIdentityFinder
Creds config.Credentials
}
// NewMySQLAADUserManager creates a new MySQLAADUserManager
func NewMySQLAADUserManager(creds config.Credentials, identityFinder *helpers.AADIdentityFinder) *MySQLAADUserManager {
return &MySQLAADUserManager{
Creds: creds,
identityFinder: identityFinder,
}
}
var _ resourcemanager.ARMClient = &MySQLAADUserManager{}
// CreateUser creates an aad user
func (m *MySQLAADUserManager) CreateUser(ctx context.Context, db *sql.DB, username string, aadID string) error {
if err := helpers.FindBadChars(username); err != nil {
return fmt.Errorf("problem found with username: %v", err)
}
if err := helpers.FindBadChars(aadID); err != nil {
return fmt.Errorf("problem found with clientID: %v", err)
}
// TODO: Need to talk to MySQL team to understand why we even need to do this, their documentation
// TODO: says that we need to do this only for Managed Identities but it seems we need to do it
// TODO: for normal users too
_, err := db.ExecContext(ctx, "SET aad_auth_validate_oids_in_tenant = OFF")
if err != nil {
return err
}
tsql := "CREATE AADUSER IF NOT EXISTS ? IDENTIFIED BY ?"
_, err = db.ExecContext(ctx, tsql, username, aadID)
if err != nil {
return err
}
return nil
}
// Ensure that user exists
func (m *MySQLAADUserManager) Ensure(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) {
instance, err := m.convert(obj)
if err != nil {
return false, err
}
dbClient := mysqldatabase.GetMySQLDatabasesClient(m.Creds)
_, err = dbClient.Get(ctx, instance.Spec.ResourceGroup, instance.Spec.Server, instance.Spec.DBName)
if err != nil {
instance.Status.Message = errhelp.StripErrorIDs(err)
return false, mysql.IgnoreResourceNotFound(err)
}
adminIdentity, err := m.identityFinder.FindIdentity(ctx)
if err != nil {
err = errors.Wrapf(err, "failed to find identity")
instance.Status.Message = err.Error()
return false, err
}
fullServerName := mysql.GetFullSQLServerName(instance.Spec.Server)
fullUsername := mysql.GetFullyQualifiedUserName(adminIdentity.IdentityName, instance.Spec.Server)
db, err := mysql.ConnectToSQLDBAsCurrentUser(
ctx,
mysql.MySQLDriverName,
fullServerName,
instance.Spec.DBName,
mysql.MySQLServerPort,
fullUsername,
adminIdentity.ClientID)
if err != nil {
instance.Status.Message = errhelp.StripErrorIDs(err)
// catch firewall issue - keep cycling until it clears up
if strings.Contains(err.Error(), "is not allowed to connect to this MySQL server") {
return false, nil
}
return false, mysql.IgnoreDatabaseBusy(err)
}
instance.Status.SetProvisioning("")
err = m.CreateUser(ctx, db, instance.Username(), instance.Spec.AADID)
if err != nil {
instance.Status.Message = "failed creating user, err: " + err.Error()
return false, err
}
// apply roles to user
if len(instance.Spec.Roles) == 0 {
msg := "no roles specified for database user"
instance.Status.SetFailedProvisioning(msg)
return true, fmt.Errorf(msg)
}
// TODO: Need to diff roles
err = mysql.GrantUserRoles(ctx, instance.Username(), instance.Spec.DBName, instance.Spec.Roles, db)
if err != nil {
err = errors.Wrap(err, "GrantUserRoles failed")
instance.Status.Message = err.Error()
return false, err
}
instance.Status.SetProvisioned(resourcemanager.SuccessMsg)
instance.Status.State = "Succeeded" // TODO: What is this value supposed to be...?
return true, nil
}
// Delete deletes a user
func (m *MySQLAADUserManager) Delete(ctx context.Context, obj runtime.Object, opts ...resourcemanager.ConfigOption) (bool, error) {
instance, err := m.convert(obj)
if err != nil {
return false, err
}
// short circuit connection if database doesn't exist
dbClient := mysqldatabase.GetMySQLDatabasesClient(m.Creds)
_, err = dbClient.Get(ctx, instance.Spec.ResourceGroup, instance.Spec.Server, instance.Spec.DBName)
if err != nil {
instance.Status.Message = err.Error()
return false, mysql.IgnoreResourceNotFound(err)
}
adminIdentity, err := m.identityFinder.FindIdentity(ctx)
if err != nil {
err = errors.Wrapf(err, "failed to find identity")
instance.Status.Message = err.Error()
return false, err
}
fullServerName := mysql.GetFullSQLServerName(instance.Spec.Server)
fullUsername := mysql.GetFullyQualifiedUserName(adminIdentity.IdentityName, instance.Spec.Server)
db, err := mysql.ConnectToSQLDBAsCurrentUser(
ctx,
mysql.MySQLDriverName,
fullServerName,
instance.Spec.DBName,
mysql.MySQLServerPort,
fullUsername,
adminIdentity.ClientID)
if err != nil {
instance.Status.Message = errhelp.StripErrorIDs(err)
if strings.Contains(err.Error(), "is not allowed to connect to this MySQL server") {
//for the ip address has no access to server, stop the reconcile and delete the user from controller
return false, nil
}
return false, err
}
err = mysql.DropUser(ctx, db, instance.Username())
if err != nil {
instance.Status.Message = fmt.Sprintf("Delete MySqlUser failed with %s", err.Error())
return false, err
}
instance.Status.Message = fmt.Sprintf("Delete MySqlUser succeeded")
return false, nil
}
// GetParents gets the parents of the user
func (m *MySQLAADUserManager) GetParents(obj runtime.Object) ([]resourcemanager.KubeParent, error) {
instance, err := m.convert(obj)
if err != nil {
return nil, err
}
return []resourcemanager.KubeParent{
{
Key: types.NamespacedName{
Namespace: instance.Namespace,
Name: instance.Spec.DBName,
},
Target: &v1alpha1.MySQLDatabase{},
},
{
Key: types.NamespacedName{
Namespace: instance.Namespace,
Name: instance.Spec.Server,
},
Target: &v1alpha2.MySQLServer{},
},
{
Key: types.NamespacedName{
Namespace: instance.Namespace,
Name: instance.Spec.ResourceGroup,
},
Target: &v1alpha1.ResourceGroup{},
},
}, nil
}
// GetStatus gets the status
func (m *MySQLAADUserManager) GetStatus(obj runtime.Object) (*v1alpha1.ASOStatus, error) {
instance, err := m.convert(obj)
if err != nil {
return nil, err
}
return &instance.Status, nil
}
func (m *MySQLAADUserManager) convert(obj runtime.Object) (*v1alpha1.MySQLAADUser, error) {
local, ok := obj.(*v1alpha1.MySQLAADUser)
if !ok {
return nil, fmt.Errorf("failed type assertion on kind: %s", obj.GetObjectKind().GroupVersionKind().String())
}
return local, nil
}
<file_sep>echo 'ls -d **/*'
ls -d **/*
if [[ ! -d _Azure.azure-service-operator/drop ]] ; then
echo 'ERROR: Folder "_Azure.azure-service-operator/drop" is not there, aborting.'
exit -1
fi
if [[ ! -f _Azure.azure-service-operator/drop/azure-service-operator.txt ]] ; then
echo 'ERROR: File "_Azure.azure-service-operator/drop/azure-service-operator.txt" is not there, aborting.'
exit -1
fi
azureserviceoperator_image=$(head -n 1 _Azure.azure-service-operator/drop/azure-service-operator.txt)
azureserviceoperator_image_public=$(echo ${azureserviceoperator_image//candidate/public})
azureserviceoperator_image_base=$(echo $azureserviceoperator_image | cut -d':' -f 1)
azureserviceoperator_image_version=$(echo $azureserviceoperator_image | cut -d':' -f 2)
azureserviceoperator_image_latest=$(echo ${azureserviceoperator_image_base//candidate/public})':latest'
echo $azureserviceoperator_image
echo $azureserviceoperator_image_base
echo $azureserviceoperator_image_latest
echo $azureserviceoperator_image_public
echo "##vso[task.setvariable variable=azureserviceoperator_image_latest]$azureserviceoperator_image_latest"
echo "##vso[task.setvariable variable=azureserviceoperator_image]$azureserviceoperator_image"
echo "##vso[task.setvariable variable=azureserviceoperator_image_public]$azureserviceoperator_image_public"
echo "##vso[task.setvariable variable=azureserviceoperator_image_base]$azureserviceoperator_image_base"
echo "##vso[task.setvariable variable=azureserviceoperator_image_version]$azureserviceoperator_image_version"
mkdir release/config -p
cp -r _Azure.azure-service-operator/drop/setup.yaml ./release/config
IMG=${azureserviceoperator_image_public/"public/"/"mcr.microsoft.com/"}
echo "updating the manager image "
echo $IMG
sed -i'' -e 's@image: docker.io/controllertest:.*@image: '${IMG}'@' ./release/config/setup.yaml
sed -i'' -e 's@image: IMAGE_URL@image: '${IMG}'@' ./release/config/setup.yaml
echo ${azureserviceoperator_image_public/"public/"/"mcr.microsoft.com/"} >> ./release/notes.txt
cat ./release/config/setup.yaml
echo 'ls ./release'
ls ./release
zip -r release.zip ./release/*
ls
<file_sep>// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
package keyvault_test
import (
"testing"
resourceconfig "github.com/Azure/azure-service-operator/pkg/resourcemanager/config"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
)
func TestKeyvault(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Keyvault Suite")
}
var _ = BeforeSuite(func(done Done) {
logf.SetLogger(zap.LoggerTo(GinkgoWriter, true))
By("BeforeSuite - KeyVault Suite")
resourceconfig.ParseEnvironment()
close(done)
}, 60)
var _ = AfterSuite(func() {
//clean up the resources created for test
By("AfterSuite - KeyVault Suite")
})
|
a2ae82161bb7b20420b0b67de322fe5ff6f5c0bb
|
[
"Markdown",
"Go",
"Dockerfile",
"Shell"
] | 19
|
Go
|
isabella232/azure-service-operator
|
f6f847be8f9760eeacba8fa64bb9a6e12571f46f
|
5d5158f2e93b14fcd2096388bea88e752b6ba68c
|
refs/heads/master
|
<repo_name>NirdeshMohan/diseasetracker<file_sep>/diseasetracker/src/main/java/com/rss/diseasetracker/controllers/AppControler.java
package com.rss.diseasetracker.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import com.rss.diseasetracker.model.LocationWiseStats;
import com.rss.diseasetracker.service.DiseaseDataTrackerService;
@Controller
public class AppControler {
@Autowired
DiseaseDataTrackerService diseaseDataTrackerService;
@GetMapping("/")
public String app(Model model) {
List<LocationWiseStats> listOfCases = diseaseDataTrackerService.getCurrentStatList();
int totalWorldWideCases = listOfCases.stream().mapToInt(total -> total.getCurrentTotalCases()).sum();
model.addAttribute("diseaseresults",listOfCases);
model.addAttribute("totalCases",totalWorldWideCases);
return "diseasedetail";
}
}
|
ece9aecfc3a56da67377bc786ebca81a6d6c19c4
|
[
"Java"
] | 1
|
Java
|
NirdeshMohan/diseasetracker
|
48464a8cfa5dcd8ae271ceb455eb5a37f6e847e4
|
79ecd7866b2dde0ee062ec50aa1a99352084737a
|
refs/heads/master
|
<file_sep>/* Written by <NAME> - http://joeferrucci.info */
#include <iostream>
using namespace std;
int find_substring(char* pattern, char* text) {
int pattern_len = strlen(pattern);
int text_len = strlen(text);
int j; // start of match
for (int i = 0; i <= (text_len - pattern_len); i++) {
j = 0;
while ( (j < pattern_len) && (text[i+j] == pattern[j]) )
j++;
if (j == pattern_len)
return (i);
}
return (-1);
}
int main(int argc, char const *argv[])
{
char article[] = "Today is November 17, 2014";
char pattern[] = "day";
int startOfSubstring = find_substring(pattern, article);
if (startOfSubstring == -1)
cout << "No pattern was matched\n";
else
cout << "Substring pattern was found at position " << startOfSubstring << "\n";
return 0;
}<file_sep>/* Written by <NAME> - http://joeferrucci.info */
/* Description: Using only primitive types, implement a bounded queue to store integers. */
#include <iostream> // STDIN and STDOUT
using namespace std; // Make things easier to read.
class BoundedQueue {
public:
BoundedQueue(size_t initialCapacity = 10) {
currentSize = 0;
maxCapacity = initialCapacity;
queue = new int[initialCapacity];
}
void enqueue(int newInt) {
try {
if (currentSize < maxCapacity) {
queue[currentSize] = newInt;
currentSize++; // Increment after enqueuing
} else {
throw "BoundedQueue is FULL";
}
}
catch (const char* str) {
cerr << "Exception raised: " << str << '\n';
}
}
int dequeue() {
try {
if (currentSize != 0) {
currentSize--;
return queue[currentSize];
} else {
throw "BoundedQueue is EMPTY";
}
}
catch (const char* str) {
cerr << "Exception raised: " << str << '\n';
return 0;
}
}
private:
size_t currentSize;
size_t maxCapacity;
int *queue;
};
int main(int argc, char *argv[]) {
BoundedQueue q1;
// Run the below code, from <Line:52> to <Line:62>, to test "Enqueue" Full.
q1.enqueue(10);
q1.enqueue(9);
q1.enqueue(8);
q1.enqueue(7);
q1.enqueue(6);
q1.enqueue(5);
q1.enqueue(4);
q1.enqueue(3);
q1.enqueue(2);
q1.enqueue(1);
q1.enqueue(0); // Fails at 11th enqueue because its full. See error console.
// The below code, from <Line:65> to <Line:66>, to test "Dequeue" Empty.
BoundedQueue q2;
q2.dequeue(); // It starts empty. When you try to dequeue it fails. See error console.
return 0;
}<file_sep>/* Written by <NAME> - http://joeferrucci.info */
#include <iostream>
using namespace std;
void exchangesort(int S[], int size) {
for (int i = 0; i != size; i++) {
for (int j = i+1; j != size; j++) {
if ( S[j] < S[i])
{
int temp = S[j];
S[j] = S[i];
S[i] = temp;
}
}
}
}
int main(int argc, char *argv[]) {
int SIZE = 10;
int A[] = {3,1,2,6,4,33,5,9,7,8,};
cout << "Before sort:\t";
for (int i = 0; i != SIZE; i++) {
cout << " " << A[i];
}
exchangesort(A,SIZE);
cout << "\nAfter sort:\t\t";
for (int i = 0; i != SIZE; i++) {
cout << " " << A[i];
}
}<file_sep>/* Written by <NAME> - http://joeferrucci.info */
#include <iostream>
using namespace std;
int binaryIterative(int a[], int SIZE, int target) {
int low = 0;
int mid = 0;
int high = SIZE;
while (low != high) {
mid = (low+high)/2;
if (target == a[mid]) {
return mid;
}
else if (target < a[mid]) {
high = mid - 1;
}
else if (target > a[mid]) {
low = mid + 1;
}
}
return 0;
}
int binaryRecursive(int a[], int low, int high, int target) {
int mid;
if (low > high) {
return -1;
}
else {
mid = (low+high)/2;
if (target == a[mid]) {
return mid;
}
else if (target < a[mid]) {
return binaryRecursive(a, low, mid-1, target);
}
else {
return binaryRecursive(a, mid+1, high, target);
}
}
}
int binarySearchRecursiveInterface(int a[], int SIZE, int target) {
int low = 0;
int mid = 0;
int high = SIZE;
mid = (low+high)/2;
if (target == a[mid]) {
return mid;
}
else if (target < a[mid]) {
return binaryRecursive(a, low, mid-1, target);
}
else if (target > a[mid]) {
return binaryRecursive(a, mid+1, high, target);
}
}
int main(int argc, char *argv[]) {
const int SIZE = 10;
int array[SIZE] = {1,2,3,4,5,6,7,8,9,10};
cout << "Binary Iterative - Position: " << binaryIterative(array, SIZE, 10);
cout << "\nBinary Recurive - Position: " << binarySearchRecursiveInterface(array, SIZE, 3);
}<file_sep>/* Written by <NAME> - http://joeferrucci.info */
#include <iostream>
using namespace std;
void binsearch(int n, const int S[], int key, int& location) {
int low = 0;
int high = n;
int mid;
location = -1;
while (low <= high && location == -1) {
mid = (low + high) / 2; // Divide
if (key == S[mid]) // Then conquer!
location = mid;
else if (key < S[mid])
high = mid - 1;
else
low = mid + 1;
}
}
int main(int argc, char *argv[]) {
const int SIZE = 10;
int sorted[SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 33};
int key = 3; // should be @ location 2
int location = -1;
binsearch(SIZE, sorted, key, location);
if (location != -1)
cout << "Found at location: " << location;
else
cout << "Not found";
}<file_sep>Algorithm Playground by <NAME><file_sep>/* Written by <NAME> - http://joeferrucci.info */
#include <iostream>
using namespace std;
int suml(int arr[], int SIZE) {
if (SIZE == 0) {
return 0;
}
else {
// copy array[1...n]
int* arr2 = new int[SIZE-1];
for (int i = 0; i != SIZE; i++) {
arr2[i] = arr[i+1];
}
return arr[0] + suml(arr2, SIZE-1);
}
}
int main(int argc, char *argv[]) {
const int SIZE = 3;
int myArray[SIZE] = {8, 7, 6};
cout << "Total = " << suml(myArray, SIZE);
}<file_sep>#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool isPangram(string &s) {
string scopy = s;
transform(s.begin(), s.end(), scopy.begin(), ::toupper);
bool bits[26] = {false};
for (int i = 0; i < scopy.length(); ++i)
{
if ( int(scopy[i])-65 >= 0 && int(scopy[i])-65 < 26 )
{ // its a letter
bits[int(scopy[i])-65] = true;
}
}
for (int i = 0; i < 26; ++i) {
if (bits[i] == false) {
return(false);
}
}
return(true);
}
int main(int argc, char const *argv[])
{
string s1;
getline (std::cin,s1);
if (s1.length() < 1 || s1.length() > 1000) {
return (0);
}
if (isPangram(s1)) {
cout << "pangram";
}
else {
cout << "not pangram";
}
return(0);
}<file_sep>/* Written by <NAME> - http://joeferrucci.info */
#include <iostream>
using namespace std;
void matrixmult(int n, const int A[][2], const int B[][2], int C[][2]) {
for (int i = 0; i != n; i++) {
for (int j = 0; j != n; j++) {
C[i][j] = 0;
for (int k = 0; k != n; k++) {
C[i][j] = C[i][j] + A[i][k] * B[k][j];
}
}
}
}
int main(int argc, char *argv[]) {
const int N = 2;
int a [N][N] = {{2,3},{4,1}};
int b [N][N] = {{5,7},{6,8}};
int c [N][N] = {0};
cout << "C[][] before:\n";
for (int i = 0; i != N; i++) {
for (int j = 0; j != N; j++) {
cout << " " << c[i][j];
}
cout << "\n";
}
cout << "\n";
matrixmult(N, a, b, c);
cout << "C[][] after:\n";
for (int i = 0; i != N; i++) {
for (int j = 0; j != N; j++) {
cout << " " << c[i][j];
}
cout << "\n";
}
}
|
1b55aae810d7fa3a2e9bcdb7cd93e4d2d310c275
|
[
"Markdown",
"C++"
] | 9
|
C++
|
JoeFerrucci/Algorithms-Playground
|
6b6147e0fae59683eb27cea2fd0ece24e1d69cc7
|
b68a595d6a25d369f305d124964eae8c8d0c9341
|
refs/heads/master
|
<repo_name>beto5120/Colecciones<file_sep>/Main.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.print.attribute.HashAttributeSet;
public class Main {
public static void main(String [] args) {
System.out.println("Ejemplo de uso de colecciones");
//Listas
List listaClientes = new ArrayList();
//1.1
Cliente c1 = new Cliente("<NAME>", "<EMAIL>");
Cliente c2 = new Cliente("<NAME>", "<EMAIL>");
Cliente c3 = new Cliente("<NAME>", "<EMAIL>");
listaClientes.add(c1);
listaClientes.add(c2);
listaClientes.add(c3);
//1.2 recorrer la lista
//1.2.1 For normal
for(int i = 0; i< listaClientes.size(); i++) {
System.out.println("Cliente: "+listaClientes.get(i));
}
//1.2.2 foreach
for(Object o : listaClientes) {
Cliente c = (Cliente) o;
System.out.println("Cliente: "+c);
}
System.out.println("###############################");
Set ClientesSet = new HashSet();
boolean agregado;
agregado = ClientesSet.add(c1);
System.out.println(agregado);
agregado = ClientesSet.add(c2);
System.out.println(agregado);
agregado = ClientesSet.add(c3);
System.out.println(agregado);
for(Object o : ClientesSet) {
Cliente c = (Cliente) o;
System.out.println("Cliente en el Set: "+c);
}
System.out.println("##################################");
Map mapa = new HashMap();
mapa.put(1, c1);
mapa.put(2, c2);
mapa.put(3, c3);
Set llavesMapa = mapa.keySet();
for(Object o : llavesMapa) {
Object clienteDentroDeMapa = mapa.get(o);
Cliente c = (Cliente) clienteDentroDeMapa;
System.out.println("Cliente obtenido"+clienteDentroDeMapa);
}
}
}
|
d9ffdf07615f2a59356fc5b5e5ff11886f0aad6c
|
[
"Java"
] | 1
|
Java
|
beto5120/Colecciones
|
4453911e3c6bafd80e575bc709a4c790af98e53a
|
0e248b3eaa5873bf1ddb1cc3c0622216fc631657
|
refs/heads/master
|
<file_sep>package COM.SDS.DAO;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import COM.SDS.FRAME.Dao;
import COM.SDS.FRAME.SQL;
import COM.SDS.VO.CustomerVO;
import COM.SDS.VO.ItemVO;
public class CustomerDao extends Dao<String, CustomerVO> {
@Override
public void insert(CustomerVO v, Connection con) throws Exception {
// Connection을 통해 PreparedStatement 생성
// SQL 작성하여 DB전송
// Resource Close
// SQL for DB. NOT Coding
PreparedStatement pstmt = con.prepareStatement(SQL.insertCustomer);
try {
pstmt.setString(1, v.getId());
pstmt.setString(2, v.getPwd());
pstmt.setString(3, v.getName());
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
throw e;
}finally {
close(pstmt);
}
}
@Override
public void delete(String t, Connection con) throws Exception {
// TODO Auto-generated method stub
PreparedStatement pstmt = con.prepareStatement(SQL.deleteCustomer);
try {
pstmt.setString(1, t);
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
throw e;
}finally {
close(pstmt);
}
}
@Override
public void update(CustomerVO v, Connection con) throws Exception {
// TODO Auto-generated method stub
PreparedStatement pstmt = con.prepareStatement(SQL.updateCustomer);
try {
pstmt.setString(1, v.getPwd());
pstmt.setString(2, v.getName());
pstmt.setString(3, v.getId());
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
throw e;
}finally {
close(pstmt);
}
}
@Override
public CustomerVO select(String t, Connection con) throws Exception {
CustomerVO customer=null;
PreparedStatement pstmt = null;
ResultSet rset=null;
try {
pstmt=con.prepareStatement(SQL.getCustomer);
pstmt.setString(1, t);
rset=pstmt.executeQuery();
rset.next();
customer=new CustomerVO(rset.getString("ID"),rset.getString("PWD"),rset.getString("NAME"));
customer.setItem(new ItemVO(rset.getString("ID"),rset.getString("ITEM"),rset.getDouble("PRICE")));
} catch (Exception e) {
e.printStackTrace();
throw e;
}finally {
close(pstmt);
close(rset);
}
return customer;
}
@Override
public ArrayList<CustomerVO> select(Connection con) throws Exception {
// TODO Auto-generated method stub
ArrayList<CustomerVO> customers=new ArrayList<>();
CustomerVO customer=null;
PreparedStatement pstmt = con.prepareStatement(SQL.selectAll);
ResultSet rset=null;
try {
rset=pstmt.executeQuery();
while(rset.next())
{
customer=new CustomerVO(rset.getString("ID"),rset.getString("PWD"),rset.getString("NAME"));
customer.setItem(new ItemVO(rset.getString("ID"),rset.getString("ITEM"),rset.getDouble("PRICE")));
customers.add(customer);
}
} catch (Exception e) {
e.printStackTrace();
throw e;
}finally {
close(pstmt);
close(rset);
}
return customers;
}
//t에 아이템명이 들어가서 해당 아이템을 가진 사람들을 반환.
@Override
public ArrayList<CustomerVO> List(String t, Connection con) throws Exception {
ArrayList<CustomerVO> list=new ArrayList<>();
CustomerVO customer=null;
PreparedStatement pstmt = null;
ResultSet rset=null;
try {
pstmt=con.prepareStatement(SQL.ListOfPeople);
pstmt.setString(1, t);
rset=pstmt.executeQuery();
while(rset.next()) {
customer = new CustomerVO(rset.getString("ID"),rset.getString("PWD"),rset.getString("NAME"));
list.add(customer);
}
} catch (Exception e) {
e.printStackTrace();
throw e;
}finally {
close(pstmt);
close(rset);
}
return list;
}
}
<file_sep>package COM.SDS.FRAME;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import COM.SDS.VO.CustomerVO;
import COM.SDS.VO.ItemVO;
public abstract class Service<T,V> {
private String id="db";
private String password="db";
private String url="jdbc:oracle:thin:@127.0.0.1:1521:xe";
public Service() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Connection getConn() throws SQLException{
Connection con=null;
con=DriverManager.getConnection(url, id, password);
con.setAutoCommit(false);
return con;
}
public void close(Connection con) throws SQLException {
if(con!=null) {
con.close();
}
}
public abstract void register(CustomerVO v, ItemVO i) throws Exception ;
public abstract void remove(T t) throws Exception;
public abstract void modify(V v) throws Exception;
public abstract V get(T t) throws Exception;//1개조회
public abstract ArrayList<V> get() throws Exception;//2개조회
public abstract ArrayList<ItemVO> getItem(String t) throws Exception;
public abstract ArrayList<CustomerVO> getCustomer(String t) throws Exception;
}
|
3da64aa5fd24311b890864a5489fbde059b362d7
|
[
"Java"
] | 2
|
Java
|
1thecorean/mvc
|
a20fc44fe53c50f65fc9cd137e8cf91d3e458e41
|
e45bd1a1fe2d3936bf9c0e654eef4cf1b3630bfd
|
refs/heads/master
|
<repo_name>Hernas/soca<file_sep>/test/testapp/hooks/before_push.rb
config["before_push_setting"] = "test"
|
9805b99499cc44d6e0bb6049a573dab31cb3e6ed
|
[
"Ruby"
] | 1
|
Ruby
|
Hernas/soca
|
814300bea6b9944b0eae9cf4590b3852f9dda29b
|
67dc9bd2548631b6cf8308eb2692d184d9961dfc
|
refs/heads/master
|
<repo_name>beneisnr/react-date-picker<file_sep>/README.md
# :calendar: react-date-picker

## Getting started
### Setup
$ git clone https://github.com/beneisnr/react-date-picker.git
$ cd date-picker
$ npm i
#### Run demo
$ npm start
### Usage
```
import DatePicker from "./DatePicker";
class App extends Component {
...
doSomethingWithDates = (start, end) => {
// do something with start and end dates
// executed whenever start or end dates are set
};
render() {
return (
<DatePicker handleUpdate={this.doSomethingWithDates} />
);
}
}
```
<file_sep>/src/components/DatePicker.js
import React, { Component } from "react";
import Day from "./Day";
import {
Picker,
DateRange,
Calendar,
DaysOfWeek,
ArrowButton
} from "../styles/datePickerStyles";
import getWeeklyData from "../lib/getWeeklyData";
import { MONTHS, DAYS } from "../constants";
class DatePicker extends Component {
state = {
start: null, // selected start date
end: null, // selected end date
now: new Date(), // current date
sel: new Date(), // user's selected timeframe, offset from `now`
hov: null, // hovering date
picking: false // for opening calendar view
};
// diff is the change in month -- should either be 1 or -1 ¯\_(ツ)_/¯
updateSel = diff => {
const newSel = this.state.sel;
const currSelMonth = this.state.sel.getMonth();
newSel.setMonth(currSelMonth + diff);
this.setState({ sel: newSel });
};
// set start and end time in state, then lift up to parent
updateStartOrEnd = day => {
const month = this.state.sel.getMonth();
const year = this.state.sel.getFullYear();
const date = new Date(year, month, day);
// check if date is in the past
if (date < this.state.now) {
return;
}
// check if we should set start or end date
if (!this.state.start || (this.state.start && this.state.end)) {
this.setState({ start: date, end: null });
this.props.handleUpdate(date, null);
} else if (this.state.start && date < this.state.start) {
this.setState({ start: date });
this.props.handleUpdate(date, null);
} else {
this.setState({ end: date });
this.props.handleUpdate(this.state.start, date);
this.updatePicking(); // user is done picking
}
};
// update hovering date
updateHov = day => {
const month = this.state.sel.getMonth();
const year = this.state.sel.getFullYear();
const date = new Date(year, month, day);
// check if date is in the past
if (date < this.state.now) {
return;
}
// check if start & end already selected
if (this.state.start && this.state.end) {
return;
}
this.setState({ hov: date });
};
// update picking - whether the user is viewing calendar
updatePicking = () => {
this.setState({ picking: !this.state.picking });
};
// get className for given day
getDateStyle = day => {
if (!day) return "none";
const date = new Date(
this.state.sel.getFullYear(),
this.state.sel.getMonth(),
day
);
const dateTime = date.getTime();
const hovTime = this.state.hov && this.state.hov.getTime();
const startTime = this.state.start && this.state.start.getTime();
const endTime = this.state.end && this.state.end.getTime();
if (date < this.state.now) {
return "past"; // invalid selection
} else if (dateTime === startTime || dateTime === endTime) {
return "selected"; // selected start or end dates
} else if (startTime < dateTime && dateTime < endTime) {
return "range"; // between start and end dates
} else if (startTime && startTime < dateTime && dateTime <= hovTime) {
return "range"; // between start and hover dates
} else {
return "";
}
};
render() {
const dateFormatOptions = { month: "short", day: "numeric" };
return (
<Picker>
{/* start → end */}
<DateRange
onClick={this.updatePicking}
className={this.state.picking && "picking"}
>
{this.state.start
? this.state.start.toLocaleDateString("en-US", dateFormatOptions)
: "Start"}
{" → "}
{this.state.end
? this.state.end.toLocaleDateString("en-US", dateFormatOptions)
: "End"}
</DateRange>
{this.state.picking && (
<Calendar>
{/*MO, YR*/}
<caption>
<ArrowButton onClick={e => this.updateSel(-1)}>‹</ArrowButton>
{MONTHS[this.state.sel.getMonth()]},{" "}
{this.state.sel.getFullYear()}
<ArrowButton onClick={e => this.updateSel(1)}>›</ArrowButton>
</caption>
<tbody>
{/* Su Mo Tu We Th Fr Sa */}
<DaysOfWeek>
{DAYS.map(day => (
<td key={day}>{day}</td>
))}
</DaysOfWeek>
{/* days in the month */}
{getWeeklyData(this.state.sel).map(week => (
<tr key={week[0][1]}>
{week.map((day, i) => (
<Day
key={i}
day={day[1]}
selectDate={this.updateStartOrEnd}
hovering={this.updateHov}
status={this.getDateStyle(day[1])}
/>
))}
</tr>
))}
</tbody>
</Calendar>
)}
</Picker>
);
}
}
export default DatePicker;
<file_sep>/src/components/Day.js
import React, { Component } from "react";
import { DayTile } from "../styles/dayStyles";
class Day extends Component {
render() {
return (
<DayTile
className={this.props.status}
onClick={e => this.props.selectDate(this.props.day)}
onMouseOver={e => this.props.hovering(this.props.day)}
>
<span>{this.props.day}</span>
</DayTile>
);
}
}
export default Day;
<file_sep>/src/styles/dayStyles.js
import styled from "styled-components";
export const DayTile = styled.td`
border: solid 1px #eff0fc;
border-radius: 3px;
:hover {
cursor: pointer;
font-weight: bold;
}
&.past {
color: #e9e9e9;
border: solid 1px #eff0fc;
}
&.range {
color: #383e40;
background-color: #cfd3f6;
border: solid 1px #cfd3f6;
font-weight: bold;
}
&.selected {
color: #383e40;
background-color: #9fa8ed;
font-weight: bold;
border: solid 1px #9fa8ed;
}
&.none {
border: none;
color: #383e40;
}
&.none:hover {
cursor: default;
}
`;
<file_sep>/src/components/App.js
import React, { Component } from "react";
import styled from "styled-components";
import DatePicker from "./DatePicker";
const AppContainer = styled.div`
text-align: center;
`;
class App extends Component {
state = {
start: null,
end: null
};
updateTimes = (start, end) => {
this.setState({ start, end });
};
render() {
return (
<AppContainer>
<h1>date-picker</h1>
<DatePicker handleUpdate={this.updateTimes} />
</AppContainer>
);
}
}
export default App;
<file_sep>/src/lib/getWeeklyData.js
export default function(date) {
const month = date.getMonth() + 1;
const year = date.getFullYear();
const numDaysInMonth = new Date(year, month, 0).getDate();
let dayOfWeek = new Date(year, month - 1, 1).getDay();
let monthlyData = [];
let weeklyData = [];
// fill monthlyData with [dayOfWeek, date] arrays
for (let i = 1; i <= numDaysInMonth; i++) {
monthlyData.push([dayOfWeek, i]);
dayOfWeek = (dayOfWeek + 1) % 7;
}
// calculate and add null padding to prep for weeklyData
let paddingFront = new Array(monthlyData[0][0]).fill([null, null]);
let paddingRear = new Array(6 - monthlyData[monthlyData.length - 1][0]).fill([
null,
null
]);
monthlyData = paddingFront.concat(monthlyData).concat(paddingRear);
// shape into weeklyData
while (monthlyData.length) {
weeklyData.push(monthlyData.splice(0, 7));
}
return weeklyData;
}
|
93b425bf9f81505ebcece65624f9285debad9b48
|
[
"Markdown",
"JavaScript"
] | 6
|
Markdown
|
beneisnr/react-date-picker
|
5799b9ce843332e4b76a8e1b1208b7f523e9a314
|
f701fa21a9a6d02736414226edbc858108159df8
|
refs/heads/master
|
<repo_name>sorohan/fretboard-intervals<file_sep>/index.ts
/**
* See https://en.wikipedia.org/wiki/Interval_(music)#Main_intervals
*/
export enum Interval {
P1 = 0,
d2 = 0,
m2 = 1,
A1 = 1,
M2 = 2,
d3 = 2,
m3 = 3,
A2 = 3,
M3 = 4,
d4 = 4,
P4 = 5,
A3 = 5,
d5 = 6,
TT = 6,
A4 = 6,
P5 = 7,
d6 = 7,
m6 = 8,
A5 = 8,
M6 = 9,
d7 = 9,
m7 = 10,
A6 = 10,
M7 = 11,
d8 = 11,
P8 = 12,
A7 = 12,
}
export enum Note {
Ab = 0,
A = 1,
'A#' = 2,
Bb = 2,
B = 3,
'B#' = 4,
Cb = 3,
C = 4,
'C#' = 5,
Db = 5,
D = 6,
'D#' = 7,
Eb = 7,
E = 8,
'E#' = 9,
Fb = 8,
F = 9,
'F#' = 10,
Gb = 10,
G = 11,
'G#' = 0,
}
export const TuningPresets = {
StandardGuitar: {
strings: new Map([
[1, Note.E],
[2, Note.B],
[3, Note.G],
[4, Note.D],
[5, Note.A],
[6, Note.E],
]),
frets: 15,
},
};
/**
* String position should be starting at 1 for highest pitch (thinnest) string
*/
export type StringPosition = number;
export type Fret = number;
/**
* This doesn't really support weird tuning like a 5 string banjo
*
* @todo: support different length strings
*/
export interface Tuning {
strings: Map<StringPosition, Note>;
frets: number; // how many frets there are
}
export type FretboardPosition = [StringPosition, Fret]; // just a fancy x, y coord
export interface FretboardInterval {
position: FretboardPosition;
interval: Interval;
}
export type Fretboard = Array<FretboardPosition>;
/**
* @todo: allow startNote to just be FretboardPosition, and assume interval of P1
*/
export const getIntervalPositions = (
tuning: Tuning,
startNote: FretboardInterval,
interval: Interval
): Array<FretboardPosition> =>
getAllIntervals(tuning, startNote)
.filter((fretInterval) => fretInterval.interval === interval)
.map((fretInterval) => fretInterval.position);
export const getAllIntervals = (
tuning: Tuning,
startNote: FretboardInterval
): Array<FretboardInterval> =>
getFretboard(tuning).map(
(position: FretboardPosition): FretboardInterval => ({
position,
interval: getInterval(tuning, startNote, position),
})
);
export const getFretboard = (tuning: Tuning): Fretboard => {
const fretboard: Fretboard = [];
for (
let stringPosition: StringPosition = 1;
stringPosition <= tuning.strings.size;
stringPosition++
) {
for (let fret: Fret = 0; fret <= tuning.frets; fret++) {
fretboard.push([stringPosition, fret]);
}
}
return fretboard;
};
export const getInterval = (
tuning: Tuning,
from: FretboardInterval,
to: FretboardPosition
): Interval => {
const rootNote = subtractInterval(
fretboardNote(tuning, from.position),
from.interval
);
const toNote = fretboardNote(tuning, to);
return noteInterval(rootNote, toNote);
};
export const noteInterval = (fromNote: Note, toNote: Note): Interval =>
(toNote + 12 - fromNote) % 12;
export const fretboardNote = (tuning: Tuning, fret: FretboardPosition): Note =>
addInterval(stringNote(tuning.strings, fret[0]), fret[1]);
export const stringNote = (
strings: Map<StringPosition, Note>,
stringN: number
): Note => {
const note = strings.get(stringN);
if (note === undefined) {
throw new Error(`No string ${stringN}`);
}
return note;
};
export const addInterval = (stringNote: Note, interval: Interval): Note =>
Note[Note[(stringNote + interval) % 12] as keyof typeof Note];
export const subtractInterval = (
stringNote: Note,
interval: Interval
): Note => {
const n = (stringNote + 12 - (interval % 12)) % 12;
return Note[Note[n] as keyof typeof Note];
};
// @todo
export const isReachable = (
tuning: Tuning,
fromPosition: FretboardPosition,
toPosition: FretboardPosition
): boolean => true;
<file_sep>/index.test.ts
import test from "tape";
import {
Note,
addInterval,
TuningPresets,
Tuning,
fretboardNote,
Interval,
noteInterval,
getIntervalPositions,
} from "./index";
test("frettedNote", (t) => {
t.equal(addInterval(Note.E, 5), Note.A);
t.equal(addInterval(Note.A, 3), Note.C);
t.end();
});
test("fretboardNote", (t) => {
const tuning: Tuning = TuningPresets.StandardGuitar;
t.equal(fretboardNote(tuning, [1, 0]), Note.E);
t.equal(fretboardNote(tuning, [1, 1]), Note.F);
t.equal(fretboardNote(tuning, [3, 4]), Note.B);
t.end();
});
test("noteInterval", (t) => {
t.equal(noteInterval(Note.C, Note.G), Interval.P5);
t.end();
});
test("getIntervalPositions :: from root to 5th", (t) => {
const tuning: Tuning = {
strings: TuningPresets.StandardGuitar.strings,
frets: 5, // limit it to 5 frets for simplicity
};
// Get all perfect 5ths from G (on 6th string)
const perfect5ths = getIntervalPositions(
tuning,
{
position: [6, 3],
interval: Interval.P1,
},
Interval.P5
);
// These are all the Ds
const actual = [
[4, 0],
[2, 3],
[5, 5],
];
actual.forEach((actualPos) => {
t.ok(
perfect5ths.find(
(pos) => pos[0] === actualPos[0] && pos[1] === actualPos[1]
),
`Perfect 5th of G found at ${actualPos}`
);
});
t.end();
});
test("getIntervalPositions :: from 3rd to minor 7th", (t) => {
const tuning: Tuning = {
strings: TuningPresets.StandardGuitar.strings,
frets: 5, // limit it to 5 frets for simplicity
};
// Get all minor 7ths from G (on 6th string), using the G's minor 3rd as reference
const minor3rds = getIntervalPositions(
tuning,
{
position: [5, 1], // Bb
interval: Interval.m3,
},
Interval.m7
);
// These are all the Fs (minor 3rds of G)
const actual = [
[1, 1],
[4, 3],
[6, 1],
];
actual.forEach((actualPos) => {
t.ok(
minor3rds.find(
(pos) => pos[0] === actualPos[0] && pos[1] === actualPos[1]
),
`Minor 3rd of G found at ${actualPos}`
);
});
t.end();
});
|
72aa74a5cb4b63c61cae8de0f6116a666e0f8c4a
|
[
"TypeScript"
] | 2
|
TypeScript
|
sorohan/fretboard-intervals
|
5992c2072e4a38a0cf6eb752701fee51236a29b9
|
673a639266254aa2d93d6584c9d7ee4c90127846
|
refs/heads/master
|
<file_sep>import './src/tools/wdyr'; // <--- first import
import { AppRegistry } from 'react-native';
import App from './src/App';
import { name as appName } from './app.json';
import { initI18N } from './src/services/i18n';
initI18N();
AppRegistry.registerComponent(appName, () => App);
<file_sep>export default {
translation: {
welcome: 'Welcome to the <Devine> application!',
lang: {
fr: 'Français',
en: 'English',
},
},
};
<file_sep>import { NativeModules, Platform } from 'react-native';
import i18next, { LanguageDetectorAsyncModule } from 'i18next';
import { initReactI18next } from 'react-i18next';
import resources from './translations';
const DEFAULT_LANGUAGE = 'en';
// creating language detection module
const languageDetector: LanguageDetectorAsyncModule = {
type: 'languageDetector',
async: true,
detect: (callback: (lng: string) => void): void => {
let locale = DEFAULT_LANGUAGE;
if (Platform.OS === 'ios' && NativeModules.SettingsManager?.settings) {
locale = NativeModules.SettingsManager.settings.AppleLanguages[0];
} else if (NativeModules.I18nManager?.localeIdentifier) {
locale = NativeModules.I18nManager.localeIdentifier;
}
callback(locale.substring(0, 2));
},
init: (): void => {},
cacheUserLanguage: (): void => {},
};
export const initI18N = async () =>
i18next
.use(languageDetector)
.use(initReactI18next)
.init({
resources,
fallbackLng: DEFAULT_LANGUAGE,
interpolation: {
escapeValue: false, // react already safes from xss
},
});
<file_sep>export default {
translation: {
welcome: "Bienvenue dans l'application <Devine> !",
lang: {
fr: 'Français',
en: 'English',
},
},
};
<file_sep>import en from './en';
import fr from './fr';
const translations = {
en,
fr,
};
export default translations;
<file_sep># POC react-native-pdf
POC for iOS and Android - View PDF files natively.
NOTE: look at `src/screens/PDVViewer/PDFViewer.tsx` for the viewer, which is used inside `Home.tsx`. The rest of the codebase is just bootstraping stuff of the native application copied from another project...
Android | iPhone
-------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------
<img src="docs/screen-captures/demo-pdfviewer-android.png" width="200" alt="demo-pdfviewer-android" /> | <img src="docs/screen-captures/demo-pdfviewer-ios.png" width="200" alt="demo-pdfviewer-ios" />
## Commands
- `yarn start` (starts Metro)
- `yarn run android:dev` (starts app with .env.development configurations)
<file_sep>import {
DarkTheme as NavigationDarkTheme,
DefaultTheme as NavigationDefaultTheme,
Theme as NavigationTheme,
} from '@react-navigation/native';
import { DarkTheme as PaperDarkTheme, DefaultTheme as PaperDefaultTheme } from 'react-native-paper';
import { Theme as PaperTheme } from 'react-native-paper/lib/typescript/types';
const BASE_SPACING = 8;
// Customized theme attributes
type CustomTheme = {
spacing: (value: number) => number;
colors: {
tab: {
activeTintColor: string;
inactiveTintColor: string;
};
};
};
export type AppTheme = PaperTheme & NavigationTheme & CustomTheme;
const appCommonTheme = {
// paper does not yet support spacing function: https://github.com/callstack/react-native-paper/issues/1869
spacing: (n: number) => BASE_SPACING * n,
roundness: 8,
borderWidthThin: 1,
};
const lightTheme = {
colors: {
primary: '#bf3a2b',
secondary: '#e84b3c',
background: '#ffffff',
text: '#bf3a2b',
tab: {
activeTintColor: '#000000',
inactiveTintColor: '#808080',
},
},
};
const darkTheme = {
colors: {
primary: '#bf3a2b',
secondary: '#e84b3c',
background: '#000000',
text: '#ffffff',
tab: {
activeTintColor: '#000000',
inactiveTintColor: '#808080',
},
},
};
export const appLightTheme: AppTheme = {
...NavigationDefaultTheme,
...PaperDefaultTheme,
...appCommonTheme,
...lightTheme,
colors: {
...NavigationDefaultTheme.colors,
...PaperDefaultTheme.colors,
...lightTheme.colors,
},
};
export const appDarkTheme: AppTheme = {
...NavigationDarkTheme,
...PaperDarkTheme,
...appCommonTheme,
...darkTheme,
colors: {
...NavigationDarkTheme.colors,
...PaperDarkTheme.colors,
...darkTheme.colors,
},
};
<file_sep>import { useWindowDimensions } from 'react-native';
const useIsLandscape = () => {
const height = useWindowDimensions().height;
const width = useWindowDimensions().width;
return height < width;
};
export default useIsLandscape;
|
bf60f2e6e5632f8043406b6bd36e00d87cf3c997
|
[
"JavaScript",
"TypeScript",
"Markdown"
] | 8
|
JavaScript
|
amwebexpert/poc-react-native-pdf
|
7268ddf56ecc52c8189cd9cc3c79c3b01b22f4bf
|
e7a51d5ca45f4ff60512f9afce209baefa82e5e0
|
refs/heads/master
|
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<title>News Site</title>
<link rel="icon" href="img/favicon.ico" type="image/ico" sizes="16x16">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/bootstrap.css" rel="stylesheet">
<script src="js/jquery.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<?php
session_start();
include_once 'include/news.php';
$news = new News();
$news->Get_News();
?>
</body>
</html><file_sep>#OOP PHP Authentication System
==============================
Simple Login & Registration system using OOP PHP & Mysql. Created this for helping others who want to learn OOP PHP.
[Full Article Tutorial](http://www.w3programmers.com/login-and-registration-using-oop/)
slightly modified but still using the above one as baseline as it is much easier for the first time OOPHP learner
<file_sep>
<?php
include "db_config.php";
class News{
protected $db;
public function __construct(){
$this->db = new DB_con();
$this->db = $this->db->ret_obj();
}
public function Get_News(){
$statement= "select * from test where deleted_at IS NULL order by id desc";
$result= $this->db->query($statement) or die ($this->db->error);
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
echo "<div class='col-md-12'><div class='panel-group'><div class='panel panel-primary'><div class='panel-heading'><b>"."<a href=\"#?id=$row[id]\" class='text-warning'>".$row['heading']."</a></b> -By Admin at " .$row['datetime']."</div><div class='panel-body'>".$row['summertext'] ."</div></div></div></div>";
}
//echo "output";
}
}
|
cdfdd950ae92cbc5e0dce6f1c0f2c9cf3be7e13b
|
[
"Markdown",
"PHP"
] | 3
|
PHP
|
ping543f/login-oophp
|
19dd85247534da13ed7eec18227773ec65b014cf
|
7f0dc1a553a2a07847e93e7c85036c2e72839c99
|
refs/heads/main
|
<repo_name>vicvinni/2020AdventOfCode<file_sep>/README.md
# :sparkles: :confetti_ball: 2020 Advent Of Code :confetti_ball: :sparkles:
<file_sep>/AdventOfCode2020/AdventOfCode2020/Program.cs
using System;
using System.Collections.Generic;
using System.IO;
namespace AdventOfCode2020
{
public class Program
{
static void Main(string[] args)
{
string NumberList = File.ReadAllText(@"C:\Users\Vinni\source\repos\AdventOfCode2020\Day1.txt");
Console.WriteLine($"The Answer is: {ReportRepair1(NumberList)}");
Console.WriteLine($"The Answer is: {ReportRepair2(NumberList)}");
}
public static double ReportRepair1(string NumsList)
{
var numbers = NumsList.Split('\n');
double Ans = 0;
var intnum = new List<int>();
foreach (var x in numbers)
{
intnum.Add(Convert.ToInt32(x));
}
for (int i = 0; i < intnum.Count; i++)
{
for (int j = 1; j < intnum.Count; j++)
{
if (intnum[i] + intnum[j] == 2020)
{
Ans = intnum[i] * intnum[j];
}
}
}
return Ans;
}
public static double ReportRepair2(string NumsList)
{
var numbers = NumsList.Split('\n');
double Ans = 0;
var intnum = new List<int>();
int[] numArray = new int[3];
foreach (var x in numbers)
{
intnum.Add(Convert.ToInt32(x));
}
for (int i = 0; i < intnum.Count; i++)
{
for (int j = 1; j < intnum.Count; j++)
{
for (int k = 2; k < intnum.Count; k++)
{
if (intnum[i] + intnum[j] + intnum[k] == 2020)
{
numArray[0] = intnum[i];
numArray[1] = intnum[j];
numArray[2] = intnum[k];
Ans = intnum[i] * intnum[j] * intnum[k];
}
}
}
}
return Ans;
}
}
}
<file_sep>/AdventOfCode2020/2020AdventOfCodeTests/UnitTest1.cs
using NUnit.Framework;
using AdventOfCode2020;
using System.Collections.Generic;
namespace AdventOfCode2020Tests
{
public class Tests
{
[TestCase(("1721 \n 979 \n 366 \n 299\n 675 \n1456"), 514579)]
public void Part1_GivenStringofNumber_Find2WithSumof2020_return_ProductOFthe2Nums(string input, double answer)
{
Assert.That(Program.ReportRepair1(input), Is.EqualTo(answer));
}
[TestCase(("1721 \n 979 \n 366 \n 299\n 675 \n1456"), 241861950)]
public void Part2_GivenStringofNumber_Find3WithSumof2020_return_ProductOFthe3Nums(string input, double answer)
{
Assert.That(Program.ReportRepair2(input), Is.EqualTo(answer));
}
}
}
|
665c75324739666c5ba34952ce14832affcc27cc
|
[
"Markdown",
"C#"
] | 3
|
Markdown
|
vicvinni/2020AdventOfCode
|
61da199965d0a624903e1f80b22ebe5662feb5ae
|
cbd88e1333867c798a2f9a076627b4dbda5e64d5
|
refs/heads/master
|
<repo_name>chingching123/pms<file_sep>/pms-server/src/main/java/com/apache/pms/service/impl/JobServiceImpl.java
package com.apache.pms.service.impl;
import com.apache.pms.base.impl.BaseServiceImpl;
import com.apache.pms.entity.SysJob;
import com.apache.pms.mapper.SysJobMapper;
import com.apache.pms.service.JobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.common.BaseMapper;
import java.util.List;
/**
* @author zhuxiaomeng
* @date 2018/1/6.
* @email <EMAIL>
*/
@Service
public class JobServiceImpl implements JobService {
@Autowired
SysJobMapper jobMapper;
@Override
public List<SysJob> selectJobList(SysJob job){
return jobMapper.selectJobList(job);
}
}
<file_sep>/pms-server/src/main/java/com/apache/pms/mapper/SysUserMapper.java
package com.apache.pms.mapper;
import com.apache.pms.entity.SysUser;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import tk.mybatis.mapper.common.BaseMapper;
import java.util.List;
@Mapper
public interface SysUserMapper extends BaseMapper<SysUser> {
SysUser selectByUsername(@Param("username") String username);
List<SysUser> selectUserList(SysUser sysUser);
int checkUser(String username);
/**
* 更新密码
* @param user
* @return
*/
int rePass(SysUser user);
}<file_sep>/pms-server/src/main/java/com/apache/pms/service/RoleService.java
package com.apache.pms.service;
import com.apache.pms.base.BaseService;
import com.apache.pms.entity.SysRole;
import java.util.List;
/**
* @author zhuxiaomeng
* @date 2017/12/19.
* @email <EMAIL>
*/
public interface RoleService extends BaseService<SysRole> {
@Override
int deleteByPrimaryKey(Object id);
@Override
int insert(SysRole record);
@Override
int insertSelective(SysRole record);
@Override
SysRole selectByPrimaryKey(Object id);
@Override
int updateByPrimaryKeySelective(SysRole record);
@Override
int updateByPrimaryKey(SysRole record);
}
<file_sep>/pms-client/src/main/java/com/apache/pms/client/rpc/PmsUserService.java
package com.apache.pms.client.rpc;
import com.apache.pms.client.dto.PmsResultDTO;
import com.apache.pms.client.dto.PmsUserDTO;
public interface PmsUserService {
PmsResultDTO<PmsUserDTO> getUser(String username);
PmsResultDTO<PmsUserDTO> validate(String username,String password);
}
<file_sep>/pms-server/src/main/java/com/apache/pms/mapper/SysRoleMapper.java
package com.apache.pms.mapper;
import com.apache.pms.entity.SysRole;
import org.apache.ibatis.annotations.Mapper;
import tk.mybatis.mapper.common.BaseMapper;
import java.util.List;
@Mapper
public interface SysRoleMapper extends BaseMapper<SysRole> {
List<SysRole> selectRoleList(SysRole sysRole);
List<SysRole> selectUserRoles(String username);
}<file_sep>/pms-server/src/main/java/com/apache/pms/service/impl/PmsPermissionServiceImpl.java
package com.apache.pms.service.impl;
import com.alibaba.dubbo.config.annotation.Service;
import com.apache.pms.client.dto.PermissionQueryParam;
import com.apache.pms.client.dto.PmsPermissionDTO;
import com.apache.pms.client.dto.PmsResultDTO;
import com.apache.pms.client.dto.UserPermissionQueryParam;
import com.apache.pms.client.rpc.PmsPermissionService;
import com.apache.pms.entity.SysMenu;
import com.apache.pms.mapper.SysMenuMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.List;
@Service(version = "1.0.0")
public class PmsPermissionServiceImpl implements PmsPermissionService {
@Autowired
private SysMenuMapper sysMenuMapper;
@Override
public PmsResultDTO<List<PmsPermissionDTO>> getUserPermission(UserPermissionQueryParam queryParam){
PmsResultDTO<List<PmsPermissionDTO>> pmsResult = new PmsResultDTO<List<PmsPermissionDTO>>();
if(StringUtils.isBlank(queryParam.getUsername())){
pmsResult.setSuccess(false);
pmsResult.setErrorMsg("参数: username不能为空");
return pmsResult;
}
List<SysMenu> permissionList = sysMenuMapper.selectUserPermission(queryParam);
List<PmsPermissionDTO> pmsPermissionList = new ArrayList<PmsPermissionDTO>();
for(SysMenu permission : permissionList){
PmsPermissionDTO pmsPermission = new PmsPermissionDTO();
BeanUtils.copyProperties(permission,pmsPermission);
pmsPermissionList.add(pmsPermission);
}
pmsResult.setData(pmsPermissionList);
return pmsResult;
}
@Override
public PmsResultDTO<List<PmsPermissionDTO>> getPermission(PermissionQueryParam queryParam){
PmsResultDTO<List<PmsPermissionDTO>> pmsResult = new PmsResultDTO<List<PmsPermissionDTO>>();
List<SysMenu> permissionList = sysMenuMapper.selectPermission(queryParam);
List<PmsPermissionDTO> pmsPermissionList = new ArrayList<PmsPermissionDTO>();
for(SysMenu permission : permissionList){
PmsPermissionDTO pmsPermission = new PmsPermissionDTO();
BeanUtils.copyProperties(permission,pmsPermission);
pmsPermissionList.add(pmsPermission);
}
pmsResult.setData(pmsPermissionList);
return pmsResult;
}
}
<file_sep>/pms-server/src/main/java/com/apache/pms/filter/LoginCasFilter.java
package com.apache.pms.filter;
import com.alibaba.fastjson.JSONArray;
import com.apache.pms.base.CurrentMenu;
import com.apache.pms.base.CurrentRole;
import com.apache.pms.base.CurrentUser;
import com.apache.pms.client.dto.PmsPermissionDTO;
import com.apache.pms.client.dto.PmsResultDTO;
import com.apache.pms.client.dto.PmsRoleDTO;
import com.apache.pms.client.dto.UserPermissionQueryParam;
import com.apache.pms.client.rpc.PmsPermissionService;
import com.apache.pms.client.rpc.PmsRoleService;
import com.apache.pms.entity.SysMenu;
import com.apache.pms.entity.SysRole;
import com.apache.pms.entity.SysUser;
import com.apache.pms.service.MenuService;
import com.apache.pms.service.RoleService;
import com.apache.pms.service.SysUserService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.cas.CasFilter;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class LoginCasFilter extends CasFilter {
@Autowired
private SysUserService userService;
@Autowired
private PmsPermissionService pmsPermissionService;
@Resource
private PmsRoleService pmsRoleService;
@Resource
private RoleService roleService;
@Resource
private MenuService menuService;
protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
SysUser s = userService.queryByUsername((String) SecurityUtils.getSubject().getPrincipal());
CurrentUser currentUser=new CurrentUser(s.getId(),s.getUsername(),s.getAge(),s.getEmail(),s.getPhoto(),s.getRealName());
/**角色权限封装进去*/
//根据用户获取菜单
//List<SysMenu> menuList=new ArrayList<>(new HashSet<>(menuService.getUserMenu(s.getId())));
UserPermissionQueryParam queryParam = new UserPermissionQueryParam();
queryParam.setUsername(s.getUsername());
queryParam.setAppName("pms");
PmsResultDTO<List<PmsPermissionDTO>> permissionResult = pmsPermissionService.getUserPermission(queryParam);
List<SysMenu> menuList = new ArrayList<SysMenu>();
for(PmsPermissionDTO permission : permissionResult.getData()){
SysMenu menu = new SysMenu();
BeanUtils.copyProperties(menu,permission);
menuList.add(menu);
}
// List<SysRole> roleList = roleService.queryUserRoles(s.getUsername());
PmsResultDTO<List<PmsRoleDTO>> roleResult = pmsRoleService.getUserRoles(s.getUsername());
List<PmsRoleDTO> roleList = roleResult.getData();
JSONArray json=menuService.getMenuJsonByUser(menuList);
Session session= SecurityUtils.getSubject().getSession();
session.setAttribute("menu",json);
CurrentMenu currentMenu=null;
List<CurrentMenu> currentMenuList=new ArrayList<>();
for(SysMenu m:menuList) {
currentMenu = new CurrentMenu(m.getId(), m.getName(), m.getParentPermissionId(), m.getUrl(), m.getOrderNum(), m.getIcon(), m.getPermission(), m.getPermissionType(), m.getNum());
currentMenuList.add(currentMenu);
}
List<CurrentRole> currentRoleList=new ArrayList<>();
CurrentRole role=null;
for(PmsRoleDTO r:roleList){
role=new CurrentRole(r.getId(),r.getRoleName(),r.getRemark());
currentRoleList.add(role);
}
currentUser.setCurrentRoleList(currentRoleList);
currentUser.setCurrentMenuList(currentMenuList);
session.setAttribute("curentUser",currentUser);
return super.onLoginSuccess(token,subject,request,response);
}
}
<file_sep>/pms-server/src/main/java/com/apache/pms/base/CurrentRole.java
package com.apache.pms.base;
import java.io.Serializable;
/**
* @author zhuxiaomeng
* @date 2017/12/30.
* @email <EMAIL>
*/
public class CurrentRole implements Serializable {
/**
* @Fields serialVersionUID : TODO(用一句话描述这个变量表示什么)
*/
private static final long serialVersionUID = 1L;
private String id;
private String roleName;
public static long getSerialVersionUID() {
return serialVersionUID;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
private String remark;
public CurrentRole(String id, String roleName, String remark) {
this.id = id;
this.roleName = roleName;
this.remark = remark;
}
}
<file_sep>/pms-server/src/main/java/com/apache/pms/mapper/SysRoleUserMapper.java
package com.apache.pms.mapper;
import com.apache.pms.entity.SysRole;
import com.apache.pms.entity.SysRoleUser;
import org.apache.ibatis.annotations.Mapper;
import tk.mybatis.mapper.common.BaseMapper;
import java.util.List;
@Mapper
public interface SysRoleUserMapper extends BaseMapper<SysRoleUser> {
public int deleteRoleUser(SysRoleUser roleUser);
}<file_sep>/pms-server/src/main/java/com/apache/pms/service/MenuService.java
package com.apache.pms.service;
import com.alibaba.fastjson.JSONArray;
import com.apache.pms.base.BaseService;
import com.apache.pms.entity.SysMenu;
import java.util.List;
/**
* @author zhuxiaomeng
* @date 2017/12/12.
* @email <EMAIL>
*/
public interface MenuService extends BaseService<SysMenu> {
List<SysMenu> getMenuNotSuper();
@Override
int insert(SysMenu menu);
@Override
SysMenu selectByPrimaryKey(Object id);
List<SysMenu> getMenuChildren(String id);
public JSONArray getMenuJson(String roleId);
public JSONArray getMenuJsonList();
List<SysMenu> getMenuChildrenAll(String id);
public JSONArray getTreeUtil(String roleId);
List<SysMenu> getUserMenu(String id);
public JSONArray getMenuJsonByUser(List<SysMenu> menuList);
}
<file_sep>/pms-server/src/main/java/com/apache/pms/shiro/JwtRealm.java
package com.apache.pms.shiro;
import com.apache.pms.entity.SysUser;
import com.apache.pms.service.SysUserService;
import com.apache.pms.token.JWTToken;
import com.apache.pms.util.JwtUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class JwtRealm extends AuthorizingRealm {
@Autowired
private SysUserService userService;
/**
* 必须重写此方法,不然Shiro会报错
*/
@Override
public boolean supports(AuthenticationToken token) {
return token instanceof JWTToken;
}
/**
* 只有当需要检测用户权限的时候才会调用此方法,例如checkRole,checkPermission之类的
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String username = JwtUtil.getUsername(principals.toString());
SysUser user = userService.queryByUsername(username);
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
return simpleAuthorizationInfo;
}
/**
* 默认使用此方法进行用户名正确与否验证,错误抛出异常即可
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
String token = (String) authenticationToken.getCredentials();
// 解密获得username,用于和数据库进行对比
String username = JwtUtil.getUsername(token);
if (username == null || !JwtUtil.verify(token, username)) {
throw new AuthenticationException("token认证失败!");
}
String password = userService.queryByUsername(username).getPassword();
if (password == null) {
throw new AuthenticationException("该用户不存在!");
}
return new SimpleAuthenticationInfo(token, token, "MyRealm");
}
}
<file_sep>/pms-client/src/main/java/com/apache/pms/client/dto/PermissionQueryParam.java
package com.apache.pms.client.dto;
import lombok.Data;
import java.io.Serializable;
@Data
public class PermissionQueryParam implements Serializable{
private String name;
private String appName;
private String permissionType;
private String parentPermissionId;
}
<file_sep>/pms-server/src/main/java/com/apache/pms/config/ShiroCasConfig.java
package com.apache.pms.config;
import com.apache.pms.filter.LoginCasFilter;
import com.apache.pms.filter.VerfityCodeFilter;
import com.apache.pms.shiro.LoginCasRealm;
import com.apache.pms.shiro.LoginRealm;
import com.apache.pms.shiro.RetryLimitCredentialsMatcher;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.cas.CasFilter;
import org.apache.shiro.cas.CasSubjectFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.jasig.cas.client.session.SingleSignOutFilter;
import org.jasig.cas.client.session.SingleSignOutHttpSessionListener;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.Ordered;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.DelegatingFilterProxy;
import javax.servlet.Filter;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
@Configuration
public class ShiroCasConfig {
@Value("${shiro.cas.serverUrlPrefix}")
private String casServerUrlPrefix = "http://127.0.0.1:8080/cas";
@Value("${shiro.cas.service}")
private String casService = "http://127.0.0.1:9000/shiro-cas";
@Value("${shiro.successUrl}")
private String successUrl = "/";
@Bean
public EhCacheManager getCacheManager() {
EhCacheManager ehCacheManager = new EhCacheManager();
ehCacheManager.setCacheManagerConfigFile("classpath:ehcache/ehcache.xml");
return ehCacheManager;
}
@Bean
public LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
@Bean(name = "securityManager")
public SecurityManager getSecurityManager(@Qualifier("casSubjectFactory") CasSubjectFactory casSubjectFactory,@Qualifier("loginCasRealm") LoginCasRealm loginCasRealm) {
DefaultWebSecurityManager dwm = new DefaultWebSecurityManager();
dwm.setSubjectFactory(casSubjectFactory);
dwm.setRealm(loginCasRealm);
dwm.setCacheManager(getCacheManager());
return dwm;
}
@Bean
public PermissionFilter getPermissionFilter() {
PermissionFilter pf = new PermissionFilter();
return pf;
}
@Bean(name = "shiroFilter")
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") SecurityManager securityManager) throws Exception {
ShiroFilterFactoryBean sfb = new ShiroFilterFactoryBean();
sfb.setSecurityManager(securityManager);
sfb.setLoginUrl(casServerUrlPrefix+"/login?service="+casService);
String message = URLEncoder.encode("权限不足", "utf-8");
sfb.setUnauthorizedUrl("/error/403?message=" + message);
Map<String, Filter> filters = new HashMap<>();
filters.put("loginCasFilter", loginCasFilter());
LogoutFilter logoutFilter = new LogoutFilter();
logoutFilter.setName("logout");
logoutFilter.setEnabled(true);
logoutFilter.setRedirectUrl(casServerUrlPrefix+"/logout?service="+casService);
filters.put("logout", logoutFilter);
sfb.setFilters(filters);
Map<String, String> filterMap = new LinkedHashMap<>();
filterMap.put("/test", "anon");
filterMap.put("/plugin/**", "anon");
filterMap.put("/shiro-cas", "loginCasFilter");
filterMap.put("/logout","logout");
filterMap.put("/getUserPermission","anon");
filterMap.put("/getPermission","anon");
filterMap.put("/getUserRoles","anon");
filterMap.put("/getUser","anon");
filterMap.put("/user/validate", "anon");
filterMap.put("/**", "user");
sfb.setFilterChainDefinitionMap(filterMap);
return sfb;
}
// Spring AOP
@Bean
public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
advisorAutoProxyCreator.setProxyTargetClass(true);
return advisorAutoProxyCreator;
}
//启用Shiro Spring AOP权限注解
@Bean
public AuthorizationAttributeSourceAdvisor getAuthorizationAttributeSourceAdvisor(@Qualifier("securityManager") SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor as = new AuthorizationAttributeSourceAdvisor();
as.setSecurityManager(securityManager);
return as;
}
@Bean
public LoginCasFilter loginCasFilter() {
LoginCasFilter loginCasFilter = new LoginCasFilter();
loginCasFilter.setSuccessUrl(successUrl);
loginCasFilter.setFailureUrl(casServerUrlPrefix+"/login?service="+casService);
return loginCasFilter;
}
@Bean
public LoginCasRealm loginCasRealm(){
LoginCasRealm loginCasRealm = new LoginCasRealm();
//认证通过后的默认角色
loginCasRealm.setDefaultRoles("ROLE_USER");
//cas服务端地址前缀
loginCasRealm.setCasServerUrlPrefix(casServerUrlPrefix);
//应用服务地址,用来接收cas服务端票据
loginCasRealm.setCasService(casService);
//loginCasRealm.setCredentialsMatcher(getRetryLimitCredentialsMatcher());
loginCasRealm.setAuthorizationCacheName("authorizationCache");
loginCasRealm.setAuthenticationCacheName("authenticationCache");
return loginCasRealm;
}
@Bean
public CasSubjectFactory casSubjectFactory(){
CasSubjectFactory casSubjectFactory = new CasSubjectFactory();
return casSubjectFactory;
}
// /**
// * 注册单点登出listener
// * @return
// */
// @Bean
// public ServletListenerRegistrationBean singleSignOutHttpSessionListener(){
// ServletListenerRegistrationBean bean = new ServletListenerRegistrationBean();
// bean.setListener(new SingleSignOutHttpSessionListener());
//// bean.setName(""); //默认为bean name
// bean.setEnabled(true);
// bean.setOrder(Ordered.HIGHEST_PRECEDENCE); //设置优先级
// return bean;
// }
//
// /**
// * 注册单点登出filter
// * @return
// */
// @Bean
// public FilterRegistrationBean singleSignOutFilter(){
// FilterRegistrationBean bean = new FilterRegistrationBean();
// bean.setName("singleSignOutFilter");
// bean.setFilter(new SingleSignOutFilter());
// bean.addUrlPatterns("/*");
// bean.setEnabled(true);
// bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
// return bean;
// }
@Bean
public FilterRegistrationBean filterRegistrationBean1() {
FilterRegistrationBean filterRegistration = new FilterRegistrationBean();
SingleSignOutFilter ssFilter = new SingleSignOutFilter();
filterRegistration.setFilter(ssFilter);
// filterRegistration.addInitParameter("excludedPages", "/customer/package/prealert/**");
filterRegistration.setEnabled(true);
filterRegistration.addUrlPatterns("/*");
// CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
// characterEncodingFilter.setForceEncoding(true);
// characterEncodingFilter.setEncoding("UTF-8");
// filterRegistration.setFilter(characterEncodingFilter);
filterRegistration.setOrder(1);
return filterRegistration;
}
@Bean
public FilterRegistrationBean filterRegistrationBean2() {
FilterRegistrationBean filterRegistration = new FilterRegistrationBean();
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setForceEncoding(true);
characterEncodingFilter.setEncoding("UTF-8");
filterRegistration.setFilter(characterEncodingFilter);
filterRegistration.setOrder(2);
return filterRegistration;
}
@Bean
public FilterRegistrationBean filterRegistrationBean3() {
FilterRegistrationBean filterRegistration = new FilterRegistrationBean();
filterRegistration.setFilter(new DelegatingFilterProxy("shiroFilter"));
// 该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理
filterRegistration.addInitParameter("targetFilterLifecycle", "true");
filterRegistration.setEnabled(true);
filterRegistration.addUrlPatterns("/*");
filterRegistration.setOrder(3);
return filterRegistration;
}
}
<file_sep>/pms-client/src/main/java/com/apache/pms/client/rpc/PmsRoleService.java
package com.apache.pms.client.rpc;
import com.apache.pms.client.dto.PmsResultDTO;
import com.apache.pms.client.dto.PmsRoleDTO;
import java.util.List;
public interface PmsRoleService {
PmsResultDTO<List<PmsRoleDTO>> getUserRoles(String username);
}
<file_sep>/pms-server/src/main/java/com/apache/pms/shiro/LoginCasRealm.java
package com.apache.pms.shiro;
import com.alibaba.fastjson.JSONArray;
import com.apache.pms.base.CurrentMenu;
import com.apache.pms.base.CurrentRole;
import com.apache.pms.base.CurrentUser;
import com.apache.pms.entity.SysMenu;
import com.apache.pms.entity.SysRole;
import com.apache.pms.entity.SysUser;
import com.apache.pms.service.MenuService;
import com.apache.pms.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cas.CasRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class LoginCasRealm extends CasRealm {
@Autowired
private SysUserService userService;
@Autowired
private MenuService menuService;
/**
* 设置角色和权限信息
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
String name= (String) principals.getPrimaryPrincipal();
//根据用户获取角色 根据角色获取所有按钮权限
CurrentUser cUser= (CurrentUser) ShiroUtil.getSession().getAttribute("curentUser");
for(CurrentRole cRole:cUser.getCurrentRoleList()){
info.addRole(cRole.getId());
}
for(CurrentMenu cMenu:cUser.getCurrentMenuList()){
if(!StringUtils.isEmpty(cMenu.getPermission()))
info.addStringPermission(cMenu.getPermission());
}
return info;
}
/**
* 1、CAS认证 ,验证用户身份
* 2、将用户基本信息设置到会话中
*/
// protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
// AuthenticationInfo authc = super.doGetAuthenticationInfo(token);
// return authc;
// }
}
<file_sep>/pms-server/src/main/java/com/apache/pms/service/impl/PmsUserServiceImpl.java
package com.apache.pms.service.impl;
import com.alibaba.dubbo.config.annotation.Service;
import com.apache.pms.client.dto.PmsResultDTO;
import com.apache.pms.client.dto.PmsUserDTO;
import com.apache.pms.client.rpc.PmsUserService;
import com.apache.pms.entity.SysUser;
import com.apache.pms.mapper.SysUserMapper;
import com.apache.pms.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
@Service(version = "1.0.0")
public class PmsUserServiceImpl implements PmsUserService{
@Autowired
private SysUserMapper sysUserMapper;
@Autowired
private SysUserService sysUserService;
@Override
public PmsResultDTO<PmsUserDTO> getUser(String username){
PmsResultDTO<PmsUserDTO> pmsResult = new PmsResultDTO<PmsUserDTO>();
if(StringUtils.isBlank(username)){
pmsResult.setSuccess(false);
pmsResult.setErrorMsg("参数: username不能为空");
return pmsResult;
}
SysUser sysUser = sysUserMapper.selectByUsername(username);
if(sysUser != null){
PmsUserDTO dto = new PmsUserDTO();
BeanUtils.copyProperties(sysUser,dto);
pmsResult.setData(dto);
}
return pmsResult;
}
@Override
public PmsResultDTO<PmsUserDTO> validate(String username,String password){
PmsResultDTO<PmsUserDTO> pmsResult = new PmsResultDTO<>();
SysUser sysUser = sysUserService.queryByUsername(username);
if(sysUser == null || (!password.equals(sysUser.getPassword()))){
pmsResult.setSuccess(false);
}else{
PmsUserDTO dto = new PmsUserDTO();
BeanUtils.copyProperties(sysUser,dto);
pmsResult.setData(dto);
}
return pmsResult;
}
}
|
f028c869e2a98dcb00a98b51762e2b23caad8b45
|
[
"Java"
] | 16
|
Java
|
chingching123/pms
|
3bcc6f7d0dd09a61fe7bc2468082ba3af3fc5fad
|
e363a8a453e847c1c55428395a68acd4e73c7201
|
refs/heads/master
|
<file_sep># 2015.oktober16_Emelt_szintu_Informatika_Erettsegi
Megoldas Python programozasi nyelven
<file_sep>#!usr/bin/python3
# -*- coding:utf-8 -*-
import random
"""2015.oktober.16--odikai Emelt szintu Informatika erettsegi megoldas python programozasi nyelven"""
print("1. feladat ")
"""Penzfeldobast kell szimulalni random."""
print("A pezfedobas eredmenye: {}".format(random.choice("IF")))
print("2. feladat ")
"""Felhasznalotol bekerek egy tippet es le szimulalom hogy eltalalta-e a kerdeses ermet."""
tip=str(input("Tippeljen! (F/I)= "))
feldob = random.choice("IF")
if tip == feldob:
print("On eltalalta")
else:
print("On nem talalta el!")
print("3. feladat ")
"""Meg kell allapitani hogy hany feldobes vagyis hany sor van a kiserlet.txt--ben ugy hogy nem tarolhatjuk el az osszes adatot a memoriaban."""
n = 0
with open("kiserlet.txt", "rt",encoding="utf-8") as f:
for a in f:
n+=1
print("A kiserlet {} dobasbol all.".format(n))
print("4. feladat ")
"""Meg kell hatarozni hogy milyen gyakorisaggla dobtak fejet."""
relativ = 0
with open("kiserlet.txt", "rt",encoding="utf-8") as g:
for h in g:
if h=="F\n":
relativ+=1
print("A kiserlet soran afej relative gyakorisaga {}% volt.".format(round(((relativ/n)*100),2)))
print("5. feladat ")
"""Meg kell hatarozni hogy hanyszor fordult elo hogy egymas uton ketszer fejet dobtak."""
"""
3 esetet kell vizsgalni:
1. %IFFI%
2. FFI%
3. %IFF
Peldaul:
FFIIIIFFIIFFIIIIFF"""
dupla_F_szama = 0
utolso_4 = [] # az utolso negy elemet tartalmazza
with open("kiserlet.txt", "rt",encoding="utf-8") as g:
for k, s in enumerate(g):
utolso_4.append(s.replace('\n',''))
if len(utolso_4) > 4:
del utolso_4[0] # letoroljuk az elso elemet
if k == 3 and utolso_4 == ['F','F','I']: # 2.-es eset vizsgalata
dupla_F_szama += 1
if utolso_4 == ['I','F','F','I']: # 1.-as eset vizsgalata
dupla_F_szama += 1
if utolso_4[1:] == ['I','F','F']: # 3.-as eset vizsgalata
dupla_F_szama += 1
print("A kiserlet soran {} alkalommal dobtak pontosan ket fejet egymas utan.".format(dupla_F_szama))
print("6. feladat ")
"""Meg kell alapitani hogy melyik fej sorozat volt a leghosszabb a fajlban."""
leghosszabb_kezdodik = 0
leghosszabb_hossza = 0
jelenlegi_kezdodik = 0
jelenlegi_hossza = 0
elozo_sor = ''
with open("kiserlet.txt", "rt",encoding="utf-8") as g:
for k, s in enumerate(g):
sor = s.replace("\n", "")
if sor == "F":
jelenlegi_hossza += 1
if elozo_sor != 'F':
jelenlegi_kezdodik = k+1
else:
if jelenlegi_hossza > leghosszabb_hossza:
leghosszabb_hossza = jelenlegi_hossza
leghosszabb_kezdodik = jelenlegi_kezdodik
jelenlegi_hossza = 0
jelenlegi_kezdodik = 0
elozo_sor = sor
if jelenlegi_hossza > leghosszabb_hossza:
leghosszabb_hossza = jelenlegi_hossza
leghosszabb_kezdodik = jelenlegi_kezdodik
print("A leghosszabb tisztafej sorozat {0} tagbol all, kezdete a(z) {1}. dobas".format(leghosszabb_hossza, leghosszabb_kezdodik))
print("7. feladat ")
""" """
dobasok = []
for n in range(1, 1001):
sorozat = []
for i in range(1,5):
sorozat.append(random.choice("IF"))
dobasok.append(sorozat)
ffff_szama = dobasok.count(['F','F','F','F'])
fffi_szama = dobasok.count(['F','F','F','I'])
with open("dobasok.txt", "wt", encoding='utf-8') as f:
f.write("FFFF: {0}, FFFI: {1}\n".format(ffff_szama, fffi_szama))
f.write(' '.join([''.join(sorozat) for sorozat in dobasok]))
|
c568826ef5a3a4d407434d0ef2dc2b2e5c12bff5
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
toroktamas/2015.oktober16_Emelt_szintu_Informatika_Erettsegi
|
a5e69069721bfe8e1f0c9a3c7f7009ce76a7ed42
|
221e1f15963fc62df804a96011a36b79b68146d3
|
refs/heads/master
|
<file_sep>source 'https://rubygems.org'
gem 'sinatra'
gem 'rack'
gem 'data_mapper'
gem 'sinatra-contrib'
gem 'dm-validations'
gem 'dm-constraints'
gem 'dm-types'
gem 'dm-core'
group :development do
gem 'dm-sqlite-adapter'
end<file_sep>Traker
======
<file_sep>require 'data_mapper'
require 'dm-pager'
require 'dm-validations'
require 'dm-constraints'
require 'dm-types'
DataMapper.setup(:default, "sqlite://#{Dir.pwd}/development.db")
class User
include DataMapper::Resource
property :id, Serial
property :email, String, :required => true, :unique => true, :format => :email_address,
property :name, String
property :hashed_password, String
end
class Itinerary
include DataMapper::Resource
property :id, Serial
end
class BlogPost
include DataMapper::Resource
property :id, Serial
property :coordX, String
property :coordY, String
property :title, Text, :length => 1..300
property :body, Text
property :image, Text, :length => 1..300
# def vote(ip, up=true)
# return if already_voted?(ip)
# self.vote_count += 1
# self.up_vote_count += 1 if up
# self.down_vote_count += 1 unless up
# self.vote_score = self.up_vote_count - self.down_vote_count
# self.ips << ip
# self.save
# end
# def already_voted?(ip)
# (settings.block_repeated_votes? && self.ips.count(ip) != 0)
# end
end
#class Vote
# include DataMapper::Resource
#
# property :id, Serial
# property :ip, String, :index => true
# property :up, Boolean, :default => true
#
# property :created_at, DateTime
# property :update_at, DateTime
#
# belongs_to :entry
#end
DataMapper.finalize
DataMapper.auto_upgrade!
|
dc7fe72f7b8a53f9dbba7c49306ba8027539f94c
|
[
"Markdown",
"Ruby"
] | 3
|
Ruby
|
inescoelho/Traker
|
adbe59ec5ef203e50aae7b34bbee82390dcc7146
|
4bf1fb908255e92dce631a42f645f06b27338d00
|
refs/heads/master
|
<file_sep><?php
/**
* The template for displaying search pages.
*
*/
get_header(); ?>
<div id="newsblog-content" class="col1">
<?php if ( have_posts() ) : ?>
<h1 class="page-title"><?php printf( __( 'Search Results for: %s', 'yangliu-name-v2' ), '<span>' . get_search_query() . '</span>' ); ?></h1>
<?php
/* Run the loop for the search to output the results.
* If you want to overload this in a child theme then include a file
* called loop-search.php and that will be used instead.
*/
get_template_part( 'loop', 'archive' );
?>
<?php else : ?>
<div id="post-0" class="post">
<h2 class="title title-4"><a href="#"><?php _e( 'Not Found', 'yangliu-name-v2' ); ?></a></h2>
<div class="post-meta">
</div>
<div class="post-content">
<p><?php _e( 'Apologies, but no results were found for the requested archive.', 'yangliu-name-v2' ); ?></p>
</div>
</div>
<?php endif; ?>
</div>
<?php get_footer(); ?>
<file_sep><?php
/* Sidebar - Footer */
?>
<div id="sidebar" class="widget-area cols3" role="complementary">
<div class="col3 col3-first">
<ul class="widgets">
<?php if (!dynamic_sidebar( 'left-footer-widget-area' )) { ?>
<li id="archives" class="widget-container">
<h3 class="widget-title"><?php _e( 'Archives', 'yangliu-name-v2' ); ?></h3>
<ul>
<?php wp_get_archives( 'type=monthly' ); ?>
</ul>
</li>
<?php } ?>
</ul>
</div>
<div class="col3">
<ul class="widgets">
<?php if (!dynamic_sidebar( 'center-footer-widget-area' )) { ?>
<li id="tagcloud" class="widget-container">
<h3 class="widget-title"><?php _e( 'Tag Cloud','yangliu-name-v2'); ?></h3>
<div class="tagcloud"><?php wp_tag_cloud("smallest=8&largest=22&number=50");?></div>
</li>
<?php } ?>
</ul>
</div>
<div class="col3 col3-last">
<ul class="widgets">
<?php if (!dynamic_sidebar( 'right-footer-widget-area' )) { ?>
<li id="meta" class="widget-container">
<h3 class="widget-title"><?php _e( 'Meta', 'yangliu-name-v2' ); ?></h3>
<ul>
<?php wp_register(); ?>
<li><?php wp_loginout(); ?></li>
<?php wp_meta(); ?>
</ul>
</li>
<?php } ?>
</div>
</div>
<file_sep><?php
/* Footer.php for YangLiu-name-v2 */
?>
</div>
<div id="footer" role="contentinfo">
<div id="endbar"><div class="hr"></div><div class="hr-title">End</div></div>
<div id="site-info">©1984-20?? | <a href="<?php echo home_url( '/' ); ?>" title="Yang's A_SIDE" rel="home">YANGLIU.NAME</a> - <a href="https://liuy.me" title="Yang's B_SIDE">LIUY.ME</a> | ALL RIGHTS RESERVED. (<a href="<?php echo esc_url( __( 'http://wordpress.org/', 'yangliu-name-v2' ) ); ?>" title="<?php esc_attr_e( 'Proudly powered by WordPress.', 'yangliu-name-v2' ); ?>" rel="generator">WP</a>)</div>
<div id="words-i-like"><a href="https://liuy.me/jobs-words" rel="external" title="Stay hungry, stay foolish. - <NAME>">Stay hungry, stay foolish. - <NAME></a></div>
</div>
<?php
wp_footer();
?>
</div></body>
</html><file_sep><?php
/* the loop */
?>
<?php if ( ! have_posts() ) : ?>
<div id="post-0" class="post">
<h2 class="title title-4"><a href="#"><?php _e( 'Not Found', 'yangliu-name-v2' ); ?></a></h2>
<div class="post-meta">
</div>
<div class="post-content">
<p><?php _e( 'Apologies, but no results were found for the requested archive.', 'yangliu-name-v2' ); ?></p>
</div>
</div>
<?php endif; ?>
<?php while ( have_posts() ) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<h1 class="title title-4"><?php the_title(); ?></h1>
<div class="post-content">
<?php the_content(); ?>
<?php wp_link_pages( array( 'before' => '<div class="page-link">' . __( 'Pages:', 'yangliu-name-v2' ), 'after' => '</div>' ) ); ?>
<?php edit_post_link( __( 'Edit', 'yangliu-name-v2' ), '<div class="edit-link">', '</div>' ); ?>
</div>
</div>
<?php endwhile; // End the loop. Whew. ?>
<file_sep><?php
/* the loop */
?>
<?php if ( ! have_posts() ) : ?>
<div id="post-0" class="post">
<h2 class="title title-4"><a href="#"><?php _e( 'Not Found', 'yangliu-name-v2' ); ?></a></h2>
<div class="post-meta">
</div>
<div class="post-content">
<p><?php _e( 'Apologies, but no results were found for the requested archive.', 'yangliu-name-v2' ); ?></p>
</div>
</div>
<?php endif; ?>
<?php while ( have_posts() ) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" class="post <?php post_class(); ?>">
<?php if ( count( get_the_category() ) ) : ?>
<div class="post-cat"><?php echo get_the_category_list( ', ' ); ?></div>
<?php endif; ?>
<h1 class="title title-4"><?php the_title(); ?></h1>
<div class="post-meta">
<div class="post-date">Posted on <?php
echo sprintf( '<a href="%1$s" title="%2$s" rel="bookmark"><span class="entry-date">%3$s</span></a>',
get_permalink(),
esc_attr( get_the_time() ),
get_the_date()
)
?></div>
<?php
$tags_list = get_the_tag_list( '', ' ' );
if ( $tags_list ):
?>
|
<div class="post-tags"><?php _e('Keywords: ', 'yangliu-name-v2');?> <?php echo $tags_list; ?></div>
<?php endif; ?>
|
<div class="post-comments"><?php comments_popup_link( __( 'Leave a comment', 'yangliu-name-v2' ), __( '1 Comment', 'yangliu-name-v2' ), __( '% Comments', 'yangliu-name-v2' ) ); ?></div>
<?php edit_post_link( __( 'Edit', 'twentyten' ), ' | <div class="edit-link">', '</div>' ); ?>
</div>
<div class="post-content">
<?php the_content(); ?>
<?php wp_link_pages( array( 'before' => '<div class="page-link">' . __( 'Pages:', 'yangliu-name-v2' ), 'after' => '</div>' ) ); ?>
</div>
<div id="comments"><?php comments_template( '', true ); ?></div>
</div>
<?php endwhile; // End the loop. Whew. ?>
<div class="navigation">
<div class="nav-previous"><?php previous_post_link( '%link', '<span class="meta-nav">' . _x( '←', 'Previous post link', 'yangliu-name-v2' ) . '</span> %title' ); ?></div>
<div class="nav-next"><?php next_post_link( '%link', '%title <span class="meta-nav">' . _x( '→', 'Next post link', 'yangliu-name-v2' ) . '</span>' ); ?></div>
</div><!-- #nav-above -->
<file_sep><?php
add_action( 'after_setup_theme', 'yl_setup' );
/* Many codes are stolen from Twentyten... */
function yl_setup() {
//add_editor_style();
// Add default posts and comments RSS feed links to head
add_theme_support( 'automatic-feed-links' );
// Make theme available for translation
// Translations can be filed in the /languages/ directory
load_theme_textdomain( 'yangliu-name-v2', TEMPLATEPATH . '/languages' );
$locale = get_locale();
$locale_file = TEMPLATEPATH . "/languages/$locale.php";
if ( is_readable( $locale_file ) )
require_once( $locale_file );
// This theme uses wp_nav_menu() in one location.
register_nav_menus( array(
'primary' => __( 'Primary Navigation', 'yangliu-name-v2' ),
) );
}
function ylname_widgets_init() {
// Area 1, left above footer
register_sidebar( array(
'name' => __( 'Left Footer Widget Area', 'yangliu-name-v2' ),
'id' => 'left-footer-widget-area',
'description' => __( 'Left Footer Widget Area', 'yangliu-name-v2' ),
'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
'after_widget' => '</li>',
'before_title' => '<h3 class="widget-title">',
'after_title' => '</h3>',
) );
// Area 2, center above footer
register_sidebar( array(
'name' => __( 'Center Footer Widget Area', 'yangliu-name-v2' ),
'id' => 'center-footer-widget-area',
'description' => __( 'Center Footer Widget Area', 'yangliu-name-v2' ),
'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
'after_widget' => '</li>',
'before_title' => '<h3 class="widget-title">',
'after_title' => '</h3>',
) );
// Area 3, right above footer
register_sidebar( array(
'name' => __( 'Right Footer Widget Area', 'yangliu-name-v2' ),
'id' => 'right-footer-widget-area',
'description' => __( 'Right Footer Widget Area', 'yangliu-name-v2' ),
'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
'after_widget' => '</li>',
'before_title' => '<h3 class="widget-title">',
'after_title' => '</h3>',
) );
}
/** Register sidebars by running twentyten_widgets_init() on the widgets_init hook. */
add_action( 'widgets_init', 'ylname_widgets_init' );
/*--
wp_nav_menu() fallback
*/
function ylname_page_menu_args( $args ) {
$args['show_home'] = true;
return $args;
}
add_filter( 'wp_page_menu_args', 'ylname_page_menu_args' );
/*--
Removes the default styles that are packaged with the Recent Comments widget.
*/
function ylname_remove_recent_comments_style() {
add_filter( 'show_recent_comments_widget_style', '__return_false' );
}
add_action( 'widgets_init', 'ylname_remove_recent_comments_style' );
/**
* Remove inline styles printed when the gallery shortcode is used.
*/
add_filter( 'use_default_gallery_style', '__return_false' );
/**
* Sets the post excerpt length to 200 characters.
*
*/
function ylname_excerpt_length( $length ) {
return 200;
}
add_filter( 'excerpt_length', 'ylname_excerpt_length' );
/**
* Returns a "Continue Reading" link for excerpts
*/
function ylname_continue_reading_link() {
return ' <a href="'. get_permalink() . '">' . __( 'Continue reading <span class="meta-nav">→</span>', 'yangliu-name-v2' ) . '</a>';
}
/**
* Replaces "[...]" (appended to automatically generated excerpts) with an ellipsis and ylname_continue_reading_link().
*/
function ylname_auto_excerpt_more( $more ) {
return ' …' . ylname_continue_reading_link();
}
add_filter( 'excerpt_more', 'ylname_auto_excerpt_more' );
/**
* Adds a pretty "Continue Reading" link to custom post excerpts.
*/
function ylname_custom_excerpt_more( $output ) {
if ( has_excerpt() && ! is_attachment() ) {
$output .= ylname_continue_reading_link();
}
return $output;
}
add_filter( 'get_the_excerpt', 'ylname_custom_excerpt_more' );
<file_sep><?php
/**
* The template for displaying Tag Archive pages.
*
*/
get_header(); ?>
<div id="newsblog-content" class="col1">
<h1 class="page-title"><?php
printf( __( 'Tag Archives: %s', 'yangliu-name-v2' ), '<span>' . single_tag_title( '', false ) . '</span>' );
?></h1>
<?php
/* Run the loop for the category page to output the posts.
* If you want to overload this in a child theme then include a file
* called loop-category.php and that will be used instead.
*/
get_template_part( 'loop', 'archive' );
?>
</div>
<?php get_footer(); ?>
<file_sep><?php
/**
* The 404 template file.
*/
get_header(); ?>
<div id="newsblog-content" class="col1">
<div id="post-0" class="post">
<h2 class="title title-4"><a href="#"><?php _e( 'Not Found', 'yangliu-name-v2' ); ?></a></h2>
<div class="post-meta">
</div>
<div class="post-content">
<p><?php _e( 'Apologies, but no results were found for the requested archive.', 'yangliu-name-v2' ); ?></p>
</div>
</div>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
<file_sep><?php
/* the loop */
?>
<?php if ( ! have_posts() ) : ?>
<div id="post-0" class="post">
<h2 class="title title-4"><a href="#"><?php _e( 'Not Found', 'yangliu-name-v2' ); ?></a></h2>
<div class="post-meta">
</div>
<div class="post-content">
<p><?php _e( 'Apologies, but no results were found for the requested archive.', 'yangliu-name-v2' ); ?></p>
</div>
</div>
<?php endif; ?>
<?php while ( have_posts() ) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" class="post <?php post_class(); ?>">
<h2 class="title title-4"><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'yangliu-name-v2' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
<div class="post-meta">
<div class="post-date">Posted on <?php
echo sprintf( '<a href="%1$s" title="%2$s" rel="bookmark"><span class="entry-date">%3$s</span></a>',
get_permalink(),
esc_attr( get_the_time() ),
get_the_date()
)
?></div>
<?php
$tags_list = get_the_tag_list( '', ' ' );
if ( $tags_list ):
?>
|
<div class="post-tags"><?php _e('Keywords: ', 'yangliu-name-v2');?> <?php echo $tags_list; ?></div>
<?php endif; ?>
|
<div class="post-comments"><?php comments_popup_link( __( 'Leave a comment', 'yangliu-name-v2' ), __( '1 Comment', 'yangliu-name-v2' ), __( '% Comments', 'yangliu-name-v2' ) ); ?></div>
<?php edit_post_link( __( 'Edit', 'yangliu-name-v2' ), ' | <div class="edit-link">', '</div>' ); ?>
</div>
<div class="post-content">
<?php the_excerpt(); ?>
</div>
</div>
<?php endwhile; // End the loop. Whew. ?>
<?php if ( $wp_query->max_num_pages > 1 ) : ?>
<?php wp_page_navi();?>
<?php endif; ?>
|
2aa11b50d34b24ccdf3e5ac320a177beaa8f83a7
|
[
"PHP"
] | 9
|
PHP
|
yangliu/yangliu-name-v2
|
d6164d1030137ace7cd0de8eed552fc5cf58b7da
|
872a1955ddbe6102bfd614bb7bf50f93ac2ffc0e
|
refs/heads/master
|
<file_sep>var gulp = require('gulp');
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync');
gulp.task('autoprefix', function() {
return gulp.src('resources/css/style.css')
.pipe(autoprefixer({
browsers: ['last 2 versions']
}))
.pipe(gulp.dest('resources/css/'));
});
gulp.task('browserSync', function() {
browserSync.init(['index.html', 'resources/css/*.css', 'resources/js/*.js'], {
server: {
baseDir: "./"
}
});
});
gulp.task('watch', ['browserSync'], function() {
gulp.watch(['index.html', './resources/css/*.css', './resources/js/*.js']);
});
|
3a607887a4a72a92ca1b7bbd392a6dcb9ba6dad4
|
[
"JavaScript"
] | 1
|
JavaScript
|
sstone0/colmar-academy
|
acfe0a71dd8320f18444a41b797bcdf88803bbb4
|
ceb914bf3aa3c2e47501ea2b0005697c453b4260
|
refs/heads/master
|
<repo_name>irinaandreyuk/-2<file_sep>/лаб раб 2/eda.cpp
#include "stdafx.h"
#include <iostream>
#include "eda.h"
using namespace std;
void eda::setkkal(int k)
{
kkal = k;
}
int eda::getkkal(void)
{
return kkal;
}
eda::eda()
{
//cout << "Конструктор еды\n";
}
eda::~eda()
{
//cout << "Деструктор еды\n";
}
void eda::show()
{
cout << "калории " << this->getkkal() << endl;
}
void eda::toConsole()
{
cout << typeid(this).name() << endl;
this->show();
}<file_sep>/лаб раб 2/lunch.cpp
#include "stdafx.h"
#include <iostream>
#include "lunch.h"
using namespace std;
void lunch::setStoim(int k)
{
stoim = k;
}
int lunch::getStoim(void)
{
return stoim;
}
lunch::lunch()
{
// cout << "Конструктор ланча\n";
}
lunch::~lunch()
{
// cout << "Деструктор ланча\n";
}
void lunch::show()
{
cout << "калории еды " << this->getkkal() << endl;
cout << "тип хлеба " << this->getTip() << endl;
cout << "стоимость ланча " << this->getStoim() << endl;
cout << "цена овощей " << this->getTsena() << endl;
cout << "вид мяса " << this->getVid() << endl;
}
int lunch::getkkal()
{
return kkal;
}
void lunch::setkkal(int k)
{
kkal = k;
}
void lunch::toConsole()
{
cout << typeid(this).name() << endl;
this->show();
}<file_sep>/лаб раб 2/hleb.h
#pragma once
#include "eda.h"
#include <string>
using namespace std;
class hleb :public eda
{
string tip;
public:
hleb();
~hleb();
void setTip(string);
string getTip(void);
void show();
void toConsole();
};<file_sep>/лаб раб 2/tost.cpp
#include "stdafx.h"
#include <iostream>
#include "hleb.h"
#include "tost.h"
void baton::setVes(int z)
{
ves = z;
}
int baton::getVes(void)
{
return ves;
}
void baton::setMyka(string x)
{
myka = x;
}
string baton::getMyka(void)
{
return myka;
}
/*void tost::setSirop(string v)
{
//this->setTip("typ");
sirop = v;
}
string tost::getSirop(void)
{
return sirop;
}*/
void baton::show()
{
cout << "Вес хлеба: " << this->getVes() << endl;
cout << "мука: " << this->getMyka() << endl;
}
void tost::show()
{
cout << "Сироп: " << this->getSirop() << endl;
cout << "Вес хлеба: " << this->getVes() << endl;
cout << "мука: " << this->getMyka() << endl;
}
void baton::toConsole()
{
cout << typeid(this).name() << endl;
this->show();
}
void tost::toConsole()
{
cout << typeid(this).name() << endl;
this->show();
}<file_sep>/лаб раб 2/hleb.cpp
#include "stdafx.h"
#include <iostream>
#include "hleb.h"
using namespace std;
void hleb::setTip(string p)
{
tip = p;
}
string hleb::getTip(void)
{
return tip;
}
hleb::hleb()
{
// cout << "Конструктор хлеба\n";
}
hleb::~hleb()
{
// cout << "Деструктор хлеба\n";
}
void hleb::show()
{
cout << "калории еды " << this->getkkal() << endl;
cout << "тип хлеба " << this->getTip() << endl;
}
void hleb::toConsole()
{
cout << typeid(this).name() << endl;
this->show();
}<file_sep>/лаб раб 2/ovoshi.h
#pragma once
#include "eda.h"
#include "мясо.h"
class ovoshi :public eda
{
int tsena;
public:
class luck
{
int kolich;
public:
luck();
~luck();
void setKolich(int);
int getKolich(void);
static ovoshi vegetable();
}l;
ovoshi();
~ovoshi();
ovoshi(const ovoshi&);
void setTsena(int);
int getTsena(void);
bool isLuck();
void show();
void toConsole();
};<file_sep>/лаб раб 2/мясо.cpp
#include "stdafx.h"
#include <iostream>
#include "мясо.h"
using namespace std;
int meat::counter = 0;
void iCanModify(meat&h)
{
h.setkkal(78);
h.vid = "modify";
}
void meat::setVid(string n)
{
vid = n;
}
string meat::getVid(void)
{
return vid;
}
meat::meat()
{
counter ++;
// cout << "Конструктор мяса\n";
}
meat::~meat()
{
counter --;
//cout << "Деструктор мяса\n";
}
void meat::show()
{
cout << "калории еды " << this->getkkal() << endl;
cout << "вид мяса " << this->getVid() << endl;
}
void meat::toConsole()
{
cout << typeid(this).name() << endl;
this->show();
}
<file_sep>/лаб раб 2/ovoshi.cpp
#include "stdafx.h"
#include <iostream>
#include "ovoshi.h"
using namespace std;
void ovoshi::setTsena(int i)
{
tsena = i;
}
int ovoshi::getTsena(void)
{
return tsena;
}
ovoshi::ovoshi()
{
//cout << "Конструктор овощей\n";
}
ovoshi::~ovoshi()
{
// cout << "Деструктор овощей\n";
}
void ovoshi::luck::setKolich(int u)
{
kolich = u;
}
int ovoshi::luck::getKolich(void)
{
return kolich;
}
ovoshi::luck::luck()
{
//cout << "Конструктор вложенного лука\n";
}
ovoshi::luck::~luck()
{
// cout << "Деструктор вложенного лука\n";
}
bool ovoshi::isLuck()
{
return this->l.getKolich() > 0;
}
ovoshi ovoshi::luck::vegetable()
{
ovoshi o;
o.setkkal(20);
o.setTsena(5000);
cout << "цена овощей: " << o.getTsena() << endl;
cout << "калории еды: " << o.getkkal() << endl;
return o;
}
void ovoshi::show()
{
cout << "калории еды" << this->getkkal() << endl;
cout << "цена овощей " << this->getTsena() << endl;
}
ovoshi::ovoshi(const ovoshi& g)
{
(dynamic_cast<eda*> (this))->setkkal(const_cast<ovoshi*>(&g)->getkkal());
this->setTsena((const_cast<ovoshi*>(&g))->getTsena());
}
void ovoshi::toConsole()
{
cout << typeid(this).name() << endl;
this->show();
}<file_sep>/лаб раб 2/eda.h
#pragma once
class abstract
{
public:
abstract(){}
virtual ~abstract(){}
virtual void show() = 0;
virtual void toConsole() = 0;
};
class eda:virtual public abstract
{
int kkal;
public:
eda();
~eda();
void setkkal(int);
int getkkal(void);
void show();
void toConsole();
};
<file_sep>/лаб раб 2/лаб раб 2.cpp
// лаб раб 2.cpp: определяет точку входа для консольного приложения.
//
#include "stdafx.h"
#include <iostream>
#include "eda.h"
#include "мясо.h"
#include "ovoshi.h"
#include "hleb.h"
#include "lunch.h"
#include "tost.h"
using namespace std;
class Printer
{
public:
void iAmPrinting(abstract* gogi)
{
cout << typeid(gogi).name() << endl;
gogi->toConsole();
}
};
int _tmain(int argc, _TCHAR* argv[])
{
setlocale (LC_ALL, "rus");
/*{
eda h;
h.setkkal(228);
cout << "кол-во калорий " << h.getkkal()<<endl;
}
cout << "---------------" << endl;
{
meat r;
r.setVid("курица");
r.setkkal(34);
cout << "\nвид мяса " << r.getVid() << endl;
cout << "кол-во калорий " << r.getkkal() << endl << endl;
}
cout << "---------------" << endl;
{
ovoshi q;
q.setTsena(18);
q.setkkal(50);
q.l.setKolich(1);
cout << "\nцена " << q.getTsena() << endl;
cout << "Количество лука " << q.l.getKolich() << endl;
cout << "кол-во калорий " << q.getkkal() << endl << endl;
}
cout << "---------------" << endl;
{
hleb z;
z.setTip("черный");
z.setkkal(130);
cout << "\nтип " << z.getTip() << endl;
cout << "кол-во калорий " << z.getkkal() << endl << endl;
}
cout << "---------------" << endl;
{
hleb z;
z.setTip("черный");
z.setkkal(130);
cout << "\nтип " << z.getTip() << endl;
cout << "кол-во калорий " << z.getkkal() << endl << endl;
}
cout << "---------------" << endl;
{
lunch z;
z.setStoim(500);
z.setTip("Черный");
z.setTsena(30);
z.setVid("Курица");
z.l.setKolich(1);
cout << "\nСтоимость ланча " << z.getStoim() << endl;
cout << "Цена овощей " << z.getTsena() << endl;
cout << "кол-во лука" << z.l.getKolich() << endl;
cout << "тип хлеба " << z.getTip() << endl;
cout << "вид мяса " << z.getVid() << endl<<endl;
}
cout << "---------------" << endl;
lunch a(21);
cout << "Стоимость ланча " << a.getStoim() << endl;
cout << "---------------" << endl;*/
ovoshi::luck::vegetable();
lunch l;
l.setkkal(2);
l.setStoim(23);
l.setTip("Tip");
l.setTsena(32);
l.setVid("Kuritca");
l.show();
baton b;
b.setMyka("Пшеница");
b.setVes(500);
b.show();
tost m;
// m.setTip();
//m.setSirop("кленовый");
m.setMyka("рожь");
m.setVes(100);
m.show();
meat t;
t.setkkal(250);
t.setVid("курица");
instectore ooo;
ooo.iKnowAllAboutYou(t);
iCanModify(t);
t.show();
meat one;
{
cout << "counter of meat " << meat::getcounter()<<endl;
meat two;
cout << "counter of meat" << meat::getcounter()<<endl;
}
cout << "counter of meat" << one.getcounter()<<endl;
eda *uuu = new eda;
Printer ppp;
uuu->setkkal(44);
ppp.iAmPrinting(uuu);
delete uuu;
const tost zzz;
cout << "----------------------------------------" << endl;
(const_cast <tost*> (&zzz))->setVes(43);
(const_cast <tost*> (&zzz))->setMyka("pshenitsa");
(const_cast<tost*>(&zzz))->toConsole();
cout << "----------------------------------------" << endl;
eda *jjj;
hleb *kkk;
ovoshi *fff;
cout << "\nПонижающее преобразование\ndynamic_cast<hleb*>(eda*):\n" <<
typeid(dynamic_cast<hleb*>(jjj)).name() << endl;//downcast B->P
cout << "\nПовышающее преобразование\ndynamic_cast<eda*>(hleb*):\n" <<
typeid(dynamic_cast<eda*>(kkk)).name() << endl;//upcast P->B
cout << "\nПерекрестное преобразование\ndynamic_cast<hleb*>(ovoshi*):\n" <<
typeid(dynamic_cast<hleb*>(fff)).name() << endl;//crosscast P1->P2
cout << "\ndynamic_cast<ovoshia*>(hleb*):\n" <<
typeid(dynamic_cast<ovoshi*>(kkk)).name() << endl;
cout << "----------------------------------------" << endl;
eda vv;
ovoshi bb;
cout << "\nstatic_cast<eda*>(&ovoshi):\n" <<
typeid(static_cast<eda*>(&bb)).name() << endl;
cout << "\nstatic_cast<ovoshi*>(&eda):\n" <<
typeid(static_cast<ovoshi*>(&vv)).name() << endl;
int i = 3;
cout << i << " " << typeid(static_cast<double>(i)).name() << endl;
return 0;
}
<file_sep>/лаб раб 2/мясо.h
#pragma once
#include "eda.h"
#include <string>
#include<iostream>
using namespace std;
class instectore;
class meat;
/*class curator{
void iCanModify(meat&h)
{
h.setkkal(78);
h.vid = "modify";
}
};*/
void iCanModify(meat&h);
class meat :public eda
{
string vid;
private:
static int counter;
friend void iCanModify(meat& h);
public:
meat(int a)
{
}
meat();
~meat();
static int getcounter()
{
return counter;
}
void setVid(string);
string getVid(void);
void show();
friend instectore;
//friend void curator::iCanModify(meat&);
void toConsole();
};
class instectore
{
public:
void iKnowAllAboutYou(meat& h)
{
cout << " вызов функции iKnowAllAboutYou клвсса инспектор " << endl;
cout <<"вид мяса " << h.vid << endl;
cout << "калории еды" << h.getkkal() << endl;
}
};<file_sep>/лаб раб 2/lunch.h
#pragma once
#include "мясо.h"
#include "ovoshi.h"
#include "hleb.h"
#include "eda.h"
using namespace std;
class lunch:public meat,public hleb,public ovoshi
{ int stoim;
int kkal;
public:
int getkkal();
void setkkal(int);
lunch();
lunch(int a)
{
stoim = a;
cout << "Конструктор с параметром\n";
}
~lunch();
void setStoim(int);
int getStoim(void);
void show();
void toConsole();
};<file_sep>/лаб раб 2/tost.h
#pragma once
#include "hleb.h"
class baton :protected hleb
{
protected:
int ves;
public:
string myka;
void setMyka(string);
string getMyka(void);
void setVes(int);
int getVes(void);
void show();
void toConsole();
};
class tost: public baton
{
const string sirop="кленовый";
public:
//void setSirop(string);
string getSirop(void) const { return sirop; };// в конст методвх нельзя менять поля класса
void show();
void toConsole();
};
|
104eb3fc8d49cf8e48d8c2b320896b6d6fd1de28
|
[
"C++"
] | 13
|
C++
|
irinaandreyuk/-2
|
12fcddd13ba74b8e432215bf187e20cda9cdc4c5
|
9a1261fe97514480ca4e1175d616e9c176f7f156
|
refs/heads/master
|
<repo_name>mariodu/kissyteam.github.com<file_sep>/1.4/source/raw/demo/xtemplate/assets/xModule.js
KISSY.config('packages', {
yModule: {
base: './assets/'
}
});
KISSY.add('xModule', "{{include 'yModule'}}", {
requires: ['./yModule']
});<file_sep>/1.4/source/raw/demo/xtemplate/assets/yModule.js
KISSY.add('yModule', "This is module Y.Info {{info}}");<file_sep>/1.4/source/demo/date/demo4.rst
.. currentmodule:: date
PopupDatePicker 使用示例
=============================
Class
-----------------------------------------------
* :class:`PopupDatePicker`
PopupDatePicker 使用示例
-----------------------------------------------
.. raw:: html
<iframe width="100%" height="400" class="iframe-demo" src="/1.4/source/raw/demo/date/demo4.html"></iframe>
.. code-block:: html
<input type="text" id="date">
<button id="popup">选择日期</button>
.. code-block:: javascript
KISSY.use('node, date/popup-picker, date/format', function(S, Node, PopupDatePicker, DateFormat) {
var input = Node.all('#date');
var dateFormat = DateFormat.getDateInstance(DateFormat.Style.FULL);
var picker = null;
Node.all('#popup').on('click', showPicker);
function showPicker(e) {
e.preventDefault();
if (!picker) {
picker = createPicker();
}
if (input.val()) {
var val;
try {
val = dateFormat.parse(input.val());
picker.set('value', val);
} catch(err) {}
}
picker.set('align', {
node: input,
points: ['bl', 'tl']
});
picker.show();
picker.focus();
}
function createPicker() {
picker = new PopupDatePicker({
shim:true
});
picker.on('blur', function () {
picker.hide();
});
picker.on('select', function (e) {
if (e.value) {
input.val(dateFormat.format(e.value));
} else {
input.val('');
}
input[0].focus();
});
return picker;
}
input.on('keydown', function (e) {
if (e.keyCode == Node.KeyCode.DOWN) {
showPicker(e);
}
});
});
|
d4e7028da60039af2fab6d6ea7a4548df7216de1
|
[
"JavaScript",
"reStructuredText"
] | 3
|
JavaScript
|
mariodu/kissyteam.github.com
|
6da84e522fd6ad329ddb6ba56af1372ef0f40414
|
7326bfc4ca0044ea5d7a71c41d453a395c0783e9
|
refs/heads/master
|
<repo_name>2020201079/suffix_array-Trie_implementation-External_sorting<file_sep>/2020201079_Q1c.cpp
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<climits>
#define ll long long int
using namespace std;
class SuffixArrayNode{
public:
int index;
int rank[2];
};
bool cmpSuffixArrayNodes(SuffixArrayNode a,SuffixArrayNode b){
if(a.rank[0] == b.rank[0]){
return a.rank[1] < b.rank[1];
}
else{
return a.rank[0]<b.rank[0];
}
}
vector<long long int> buildSuffixArray(std::string& input){
long long int n = input.size();
vector<SuffixArrayNode> suffixes(n);
vector<long long int> result(n);
//initializing the suffixes vector with rank and next rank (implies string of size 2)
for(long long int i=0;i<n;i++){
suffixes[i].index = i;
suffixes[i].rank[0] = input[i] - 'a';
if(i+1<n)
suffixes[i].rank[1] = input[i+1] - 'a';
else
suffixes[i].rank[1] = -1;
}
sort(suffixes.begin(),suffixes.end(),cmpSuffixArrayNodes);
vector<long long int> ind(n); // need this array for setting the rank[1] later
// rank[0] we just compare with prev element in sorted if equal then rank is same
//otherwise just the sum of prev rank
//k is from 4 because we already constructed for k=2
for(long long int k=4;k<2*n;k=k*2){
long long int rank = 0;
long long int prev_rank = suffixes[0].rank[0];
suffixes[0].rank[0] = rank;
ind[suffixes[0].index] = rank;
for(long long int i=1;i<n;i++){
if(suffixes[i].rank[0] == prev_rank && suffixes[i].rank[1] == suffixes[i-1].rank[1]){
prev_rank = suffixes[i].rank[0];
suffixes[i].rank[0] = rank;
}
else{
rank += 1;
prev_rank = suffixes[i].rank[0];
suffixes[i].rank[0] = rank;
}
ind[suffixes[i].index] = i;
}
for(long long int i=0;i<n;i++){
int nextIndex = suffixes[i].index + k/2;
if(nextIndex < n){
suffixes[i].rank[1] = suffixes[ind[nextIndex]].rank[0];
}
else{
suffixes[i].rank[1] = -1;
}
}
sort(suffixes.begin(),suffixes.end(),cmpSuffixArrayNodes);
}
for(long long int i=0;i<n;i++)
result[i] = suffixes[i].index;
return result;
}
vector<long long int> getInvSuffix(vector<long long int>& suffixArray){
vector<long long int> result(suffixArray.size(),0);
for(int i=0;i<suffixArray.size();i++)
result[suffixArray[i]]=i;
return result;
}
vector<long long int> getLCP(string& input,vector<long long int> suffixArray){
vector<long long int> result(suffixArray.size(),0);
vector<long long int> invSuffixArray = getInvSuffix(suffixArray);
int k=0;
for(int i=0;i<suffixArray.size();i++){
if(invSuffixArray[i] == suffixArray.size()-1){ //
k=0;
continue;
}
int j = suffixArray[invSuffixArray[i]+1];
while(i+k<suffixArray.size() && j+k<suffixArray.size() && input[i+k]==input[j+k])
k++;
result[invSuffixArray[i]] = k;
if(k>0)
k--;
}
return result;
}
string reverseString(string& input){
string result="";
for(int i=input.size()-1;i>=0;i--){
result.push_back(input[i]);
}
return result;
}
// building segment tree for finding min
void build(ll si,ll ss,ll se,vector<ll>& arr,vector<ll>& segmentTree){
if(ss==se){
segmentTree[si] = arr[ss];
}
else{
ll mid=(ss+se)/2;
build(si*2+1,ss,mid,arr,segmentTree);
build(si*2+2,mid+1,se,arr,segmentTree);
segmentTree[si] = min(segmentTree[si*2+1],segmentTree[si*2+2]);
}
}
ll getMin(ll si,ll ss,ll se,ll qs,ll qe,vector<ll>& segmentTree){
if(qs>se || qe<ss){ // no overlapping
return LLONG_MAX;
}
else if(ss>=qs && se<=qe){ //segment is inside query
return segmentTree[si];
}
else{ //semi overlap need to call on both children
int mid = (ss+se)/2;
return min(getMin(2*si+1,ss,mid,qs,qe,segmentTree),getMin(2*si+2,mid+1,se,qs,qe,segmentTree));
}
}
int main(){
string input;
cin>>input;
long long int n=input.size();
string reverseInput = reverseString(input);
string modifiedInput = input+"#"+reverseInput;
//modifiedInput = "abrakadabra";
cout<<"modified input : "<<modifiedInput<<endl;
auto sa=buildSuffixArray(modifiedInput);
auto lcp = getLCP(modifiedInput,sa);
vector<ll> segmentTree(4*lcp.size());
build(0,0,lcp.size()-1,lcp,segmentTree);
vector<long long int> invSuffixArray = getInvSuffix(sa);
//get even longest first
ll evenPalSize = LLONG_MIN;
for(ll i=1;i<n;i++){
ll otherStringIndex = (2*n)-(i-1);
ll saIndex1 = invSuffixArray[i];
ll saIndex2 = invSuffixArray[otherStringIndex];
if(saIndex1 > saIndex2){
ll temp =saIndex2;
saIndex2 = saIndex1;
saIndex1 = temp;
}
//cout<<"idx1: "<<saIndex1<<" idx2: "<<saIndex2<<" Min is "<<getMin(0,0,lcp.size()-1,saIndex1,saIndex2-1,//segmentTree)<<endl;
evenPalSize = max(getMin(0,0,lcp.size()-1,saIndex1,saIndex2-1,segmentTree),evenPalSize);
}
cout<<"even max size : "<<(2*evenPalSize)<<endl;
ll oddPalSize = LLONG_MIN;
for(ll i=1;i<n;i++){
ll saIndex1 = invSuffixArray[i+1];
ll saIndex2 = invSuffixArray[(2*n)-(i-1)];
if(saIndex1 > saIndex2){
ll temp =saIndex2;
saIndex2 = saIndex1;
saIndex1 = temp;
}
oddPalSize = max(getMin(0,0,lcp.size()-1,saIndex1,saIndex2-1,segmentTree),oddPalSize);
}
cout<<"odd size : "<<(2*oddPalSize)+1<<endl;
cout<<"Max size is "<<max((2*oddPalSize)+1,(2*evenPalSize))<<endl;
}<file_sep>/2020201079_Q2.cpp
#include<iostream>
#include<cmath>
#include<vector>
using namespace std;
typedef long long ll;
class TrieNode{
public:
TrieNode* left;
TrieNode* right;
};
void insert(ll n,TrieNode* head){
auto curr = head;
int s = sizeof(ll)*8; //converting to bits
for(ll i=s-1;i>=0;i--){
int bit = (n>>i)&1;
if(bit==0){
if(curr->left == nullptr)
curr->left = new TrieNode();
curr = curr->left;
}
else{
if(curr->right == nullptr)
curr->right = new TrieNode();
curr = curr->right;
}
}
}
ll getMaxXor(ll n,TrieNode* head){
ll ans = 0;
TrieNode* curr = head;
for(ll j=sizeof(ll)*8-1;j>=0;j-- ){
ll bit = (n>>j)&1;
if(bit==0){
if(curr->right != nullptr){
curr = curr->right;
ans += pow(2,j);
}
else{
curr = curr->left;
}
}
else{//bit is one. Wanna go towards left (opposite side)
if(curr->left != nullptr){
curr = curr->left;
ans += pow(2,j);
}
else{
curr = curr->right;
}
}
}
return ans;
}
int main(){
int n,q;cin>>n>>q;
vector<int> arr(n);
TrieNode* head = new TrieNode();
for(int i=0;i<n;i++){
cin>>arr[i];
insert(arr[i],head);
}
for(int i=0;i<q;i++){
ll x;cin>>x;
cout<<getMaxXor(x,head)<<std::endl;
}
}<file_sep>/2020201079_Q1a.cpp
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
using namespace std;
class SuffixArrayNode{
public:
int index;
int rank[2];
};
bool cmpSuffixArrayNodes(SuffixArrayNode a,SuffixArrayNode b){
if(a.rank[0] == b.rank[0]){
return a.rank[1] < b.rank[1];
}
else{
return a.rank[0]<b.rank[0];
}
}
vector<long long int> buildSuffixArray(std::string& input){
long long int n = input.size();
vector<SuffixArrayNode> suffixes(n);
vector<long long int> result(n);
//initializing the suffixes vector with rank and next rank (implies string of size 2)
for(long long int i=0;i<n;i++){
suffixes[i].index = i;
suffixes[i].rank[0] = input[i] - 'a';
if(i+1<n)
suffixes[i].rank[1] = input[i+1] - 'a';
else
suffixes[i].rank[1] = -1;
}
sort(suffixes.begin(),suffixes.end(),cmpSuffixArrayNodes);
vector<long long int> ind(n); // need this array for setting the rank[1] later
// rank[0] we just compare with prev element in sorted if equal then rank is same
//otherwise just the sum of prev rank
//k is from 4 because we already constructed for k=2
for(long long int k=4;k<2*n;k=k*2){
long long int rank = 0;
long long int prev_rank = suffixes[0].rank[0];
suffixes[0].rank[0] = rank;
ind[suffixes[0].index] = rank;
for(long long int i=1;i<n;i++){
if(suffixes[i].rank[0] == prev_rank && suffixes[i].rank[1] == suffixes[i-1].rank[1]){
prev_rank = suffixes[i].rank[0];
suffixes[i].rank[0] = rank;
}
else{
rank += 1;
prev_rank = suffixes[i].rank[0];
suffixes[i].rank[0] = rank;
}
ind[suffixes[i].index] = i;
}
for(long long int i=0;i<n;i++){
int nextIndex = suffixes[i].index + k/2;
if(nextIndex < n){
suffixes[i].rank[1] = suffixes[ind[nextIndex]].rank[0];
}
else{
suffixes[i].rank[1] = -1;
}
}
sort(suffixes.begin(),suffixes.end(),cmpSuffixArrayNodes);
}
for(long long int i=0;i<n;i++)
result[i] = suffixes[i].index;
return result;
}
int main(){
string input;
cin>>input;
long long int n=input.size();
string inputDouble = input+input;
auto sa=buildSuffixArray(inputDouble);
for(int k:sa)
cout<<k<<" ";
cout<<endl;
long long int minIndex;
for(long long int i=0;i<n;i++){
if(sa[i] < n){
minIndex = sa[i];
break;
}
}
cout<<inputDouble.substr(minIndex,n)<<endl;
}<file_sep>/q1.cpp
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
using namespace std;
class SuffixArrayNode{
public:
int index;
int rank[2];
};
bool cmpSuffixArrayNodes(SuffixArrayNode a,SuffixArrayNode b){
if(a.rank[0] == b.rank[0]){
return a.rank[1] < b.rank[1];
}
else{
return a.rank[0]<b.rank[0];
}
}
vector<int> buildSuffixArray(std::string& input){
int n = input.size();
vector<SuffixArrayNode> suffixes(n);
vector<int> result(n);
//initializing the suffixes vector with rank and next rank (implies string of size 2)
for(int i=0;i<n;i++){
suffixes[i].index = i;
suffixes[i].rank[0] = input[i] - 'a';
if(i+1<n)
suffixes[i].rank[1] = input[i] - 'a';
else
suffixes[i].rank[1] = -1;
}
sort(suffixes.begin(),suffixes.end(),cmpSuffixArrayNodes);
vector<int> ind(n); // need this array for setting the rank[1] later
// rank[0] we just compare with prev element in sorted if equal then rank is same
//otherwise just the sum of prev rank
//k is from 4 because we already constructed for k=2
for(int k=4;k<2*n;k=k*2){
int rank = 0;
int prev_rank = suffixes[0].rank[0];
suffixes[0].rank[0] = rank;
ind[suffixes[0].index] = rank;
for(int i=1;i<n;i++){
if(suffixes[i].rank[0] == prev_rank && suffixes[i].rank[1] == suffixes[i-1].rank[1]){
prev_rank = suffixes[i].rank[0];
suffixes[i].rank[0] = rank;
}
else{
rank += 1;
prev_rank = suffixes[i].rank[0];
suffixes[i].rank[0] = rank;
}
ind[suffixes[i].index] = i;
}
for(int i=0;i<n;i++){
int nextIndex = suffixes[i].index + k/2;
if(nextIndex < n){
suffixes[i].rank[1] = suffixes[ind[nextIndex]].rank[0];
}
else{
suffixes[i].rank[1] = -1;
}
}
sort(suffixes.begin(),suffixes.end(),cmpSuffixArrayNodes);
}
for(int i=0;i<n;i++)
result[i] = suffixes[i].index;
return result;
}
int main(){
string input;
cin>>input;
auto sa=buildSuffixArray(input);
for(int i:sa)
cout<<i<<" ";
cout<<endl;
}<file_sep>/mergeSort.cpp
#include<iostream>
#include<vector>
using namespace std;
void merge(vector<int>& input,int l,int mid,int r){
cout<<"merge called with l:"<<l<<" mid:"<<mid<<" r:"<<r<<endl;
vector<int> result(0);
int i=l;
int j=mid+1;
while(i<=mid && j<=r){
if(input[i]<input[j]){
result.push_back(input[i]);
i++;
}
else{
result.push_back(input[j]);
j++;
}
}
while(i<=mid){
result.push_back(input[i]);
i++;
}
while(j<=r){
result.push_back(input[j]);
j++;
}
for(int z=l;z<=r;z++){
input[z] = result[z-l];
}
cout<<"Merge"<<":";
for(auto n:input)
cout<<n<<" ";
cout<<endl;
}
void mergeSortHelper(vector<int>& input,int l,int r){
cout<<"Merge sort helper l : "<<l<<" r :"<<r<<endl;
if(l<r){
int mid = (l+r)/2;
mergeSortHelper(input,l,mid);
mergeSortHelper(input,mid+1,r);
merge(input,l,mid,r);
}
}
void mergeSort(vector<int>& input){
mergeSortHelper(input,0,input.size()-1);
}
int main(){
vector<int> input = {5,9,78,34,56,32,83,14};
mergeSort(input);
for(auto n:input)
cout<<n<<" ";
}<file_sep>/data/minHeap.cpp
//need min heap of a pair<ll,int> number,blocknumber
#include<iostream>
#include<vector>
#define ll long long int
using namespace std;
template <typename T>
class MinHeap{
private:
vector<T> A;
void minHeapify(int index){
int l = 2*index+1;
int r = 2*index+2;
int smallest = index;
if(l<A.size() && A[l]<A[smallest])
smallest = l;
if(r<A.size() && A[r]<A[smallest])
smallest = r;
if(smallest != index){
T temp = A[smallest];
A[smallest] = A[index];
A[index] = temp;
minHeapify(smallest);
}
}
public:
MinHeap(vector<T> input){
A = input;
for(int i=input.size()/2;i>=0;i--)
minHeapify(i);
}
void printHeap(){
for(T value:A){
cout<<value<<" ";
}
cout<<endl;
}
int getSize(){
return A.size();
}
T heapExtractMin(){
if(A.size() == 0){
perror("Heap is empty");
}
T minValue = A[0];
A[0] = A[A.size()-1];
A.pop_back();
minHeapify(0);
return minValue;
}
void insert(T value){
A.push_back(value);
for(int i=A.size()/2;i>=0;i--)
minHeapify(i);
}
};
int main(){
auto h = MinHeap<int>({6,3});
vector<int> input = {8,9,10,34,2,0};
for(int num:input)
h.insert(num);
h.printHeap();
while(h.getSize() != 0)
cout<<h.heapExtractMin()<<" ";
cout<<endl;
}<file_sep>/2020201079_Q1b.cpp
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<climits>
#define ll long long int
using namespace std;
class SuffixArrayNode{
public:
int index;
int rank[2];
};
bool cmpSuffixArrayNodes(SuffixArrayNode a,SuffixArrayNode b){
if(a.rank[0] == b.rank[0]){
return a.rank[1] < b.rank[1];
}
else{
return a.rank[0]<b.rank[0];
}
}
vector<long long int> buildSuffixArray(std::string& input){
long long int n = input.size();
vector<SuffixArrayNode> suffixes(n);
vector<long long int> result(n);
//initializing the suffixes vector with rank and next rank (implies string of size 2)
for(long long int i=0;i<n;i++){
suffixes[i].index = i;
suffixes[i].rank[0] = input[i] - 'a';
if(i+1<n)
suffixes[i].rank[1] = input[i+1] - 'a';
else
suffixes[i].rank[1] = -1;
}
sort(suffixes.begin(),suffixes.end(),cmpSuffixArrayNodes);
vector<long long int> ind(n); // need this array for setting the rank[1] later
// rank[0] we just compare with prev element in sorted if equal then rank is same
//otherwise just the sum of prev rank
//k is from 4 because we already constructed for k=2
for(long long int k=4;k<2*n;k=k*2){
long long int rank = 0;
long long int prev_rank = suffixes[0].rank[0];
suffixes[0].rank[0] = rank;
ind[suffixes[0].index] = rank;
for(long long int i=1;i<n;i++){
if(suffixes[i].rank[0] == prev_rank && suffixes[i].rank[1] == suffixes[i-1].rank[1]){
prev_rank = suffixes[i].rank[0];
suffixes[i].rank[0] = rank;
}
else{
rank += 1;
prev_rank = suffixes[i].rank[0];
suffixes[i].rank[0] = rank;
}
ind[suffixes[i].index] = i;
}
for(long long int i=0;i<n;i++){
int nextIndex = suffixes[i].index + k/2;
if(nextIndex < n){
suffixes[i].rank[1] = suffixes[ind[nextIndex]].rank[0];
}
else{
suffixes[i].rank[1] = -1;
}
}
sort(suffixes.begin(),suffixes.end(),cmpSuffixArrayNodes);
}
for(long long int i=0;i<n;i++)
result[i] = suffixes[i].index;
return result;
}
vector<long long int> getInvSuffix(vector<long long int>& suffixArray){
vector<long long int> result(suffixArray.size(),0);
for(int i=0;i<suffixArray.size();i++)
result[suffixArray[i]]=i;
return result;
}
vector<long long int> getLCP(string& input,vector<long long int> suffixArray){
vector<long long int> result(suffixArray.size(),0);
vector<long long int> invSuffixArray = getInvSuffix(suffixArray);
int k=0;
for(int i=0;i<suffixArray.size();i++){
if(invSuffixArray[i] == suffixArray.size()-1){ //
k=0;
continue;
}
int j = suffixArray[invSuffixArray[i]+1];
while(i+k<suffixArray.size() && j+k<suffixArray.size() && input[i+k]==input[j+k])
k++;
result[invSuffixArray[i]] = k;
if(k>0)
k--;
}
return result;
}
// building segment tree for finding min
void build(ll si,ll ss,ll se,vector<ll>& arr,vector<ll>& segmentTree){
if(ss==se){
segmentTree[si] = arr[ss];
}
else{
ll mid=(ss+se)/2;
build(si*2+1,ss,mid,arr,segmentTree);
build(si*2+2,mid+1,se,arr,segmentTree);
segmentTree[si] = min(segmentTree[si*2+1],segmentTree[si*2+2]);
}
}
ll getMin(ll si,ll ss,ll se,ll qs,ll qe,vector<ll>& segmentTree){
if(qs>se || qe<ss){ // no overlapping
return LLONG_MAX;
}
else if(ss>=qs && se<=qe){ //segment is inside query
return segmentTree[si];
}
else{ //semi overlap need to call on both children
int mid = (ss+se)/2;
return min(getMin(2*si+1,ss,mid,qs,qe,segmentTree),getMin(2*si+2,mid+1,se,qs,qe,segmentTree));
}
}
int main(){
string input;
cin>>input;
long long int n=input.size();
auto sa=buildSuffixArray(input);
cout<<"suffix array :";
for(auto i:sa)
cout<<i<<" ";
cout<<endl;
auto lcp = getLCP(input,sa);
cout<<"lcp array :";
for(auto l:lcp)
cout<<l<<" ";
cout<<endl;
ll k;cin>>k;
if(k==1){
cout<<"Ans is : "<<n<<endl;
return 0;
}
vector<ll> segmentTree(4*n);
build(0,0,n-1,lcp,segmentTree);
ll currMax = LLONG_MIN;
for(int l=0;l<n-k+1;l++){
int r = l+k-2;
cout<<"l : "<<l<<" r: "<<r<<" min: "<<getMin(0,0,n-1,l,r,segmentTree)<<endl;
currMax = max(currMax,getMin(0,0,n-1,l,r,segmentTree));
}
cout<<"Ans is :"<<currMax<<endl;
}<file_sep>/2020201079_Q3.cpp
#include <iostream>
#include <fstream>
#include <string>
#include<vector>
#include<algorithm>
using namespace std;
#define ll long long int
int partitionSize;
int noOfFilesWritten = 0;
template <typename T>
class MinHeap{
private:
vector<T> A;
void minHeapify(int index){
int l = 2*index+1;
int r = 2*index+2;
int smallest = index;
if(l<A.size() && A[l]<A[smallest])
smallest = l;
if(r<A.size() && A[r]<A[smallest])
smallest = r;
if(smallest != index){
T temp = A[smallest];
A[smallest] = A[index];
A[index] = temp;
minHeapify(smallest);
}
}
public:
MinHeap(vector<T> input){
A = input;
for(int i=input.size()/2;i>=0;i--)
minHeapify(i);
}
int getSize(){
return A.size();
}
T heapExtractMin(){
if(A.size() == 0){
perror("Heap is empty");
}
T minValue = A[0];
A[0] = A[A.size()-1];
A.pop_back();
minHeapify(0);
return minValue;
}
void insert(T value){
A.push_back(value);
for(int i=A.size()/2;i>=0;i--)
minHeapify(i);
}
};
void merge(vector<ll>& input,int l,int mid,int r){
vector<ll> result(0);
int i=l;
int j=mid+1;
while(i<=mid && j<=r){
if(input[i]<input[j]){
result.push_back(input[i]);
i++;
}
else{
result.push_back(input[j]);
j++;
}
}
while(i<=mid){
result.push_back(input[i]);
i++;
}
while(j<=r){
result.push_back(input[j]);
j++;
}
for(int z=l;z<=r;z++){
input[z] = result[z-l];
}
}
void mergeSortHelper(vector<ll>& input,int l,int r){
if(l<r){
int mid = (l+r)/2;
mergeSortHelper(input,l,mid);
mergeSortHelper(input,mid+1,r);
merge(input,l,mid,r);
}
}
void mergeSort(vector<ll>& input){
mergeSortHelper(input,0,input.size()-1);
}
string getOutputPathFromBlockNumber(int blockNumber){
return "data\\output\\output"+to_string(blockNumber)+".txt";
}
void writeInFile(vector<ll> block,int blockNumber){
noOfFilesWritten++;
string outputFilePath = getOutputPathFromBlockNumber(blockNumber);
std::ofstream outFile(outputFilePath);
for (const auto &e : block)
outFile << e << "\n";
outFile.close();
}
int main(int argc, char *argv[]){
if(argc != 4){
cout<<argc;
cout<<" inputPath outputPath blockSize"<<endl;
exit(1);
}
string inputPath = argv[1];
//ifstream file("data\\input\\input1000000.txt");
ifstream file(inputPath);
//string finalOutputFile = "data\\output\\outputFinal.txt";
string finalOutputFile = argv[2];
//partitionSize = 100000;
partitionSize = stoi(argv[3]);
string data = "";
vector<ll> currBlock;
int blockNumber = 0;
int count = 0;
while(getline(file, data,','))
{
if(count<partitionSize){
currBlock.push_back(stoll(data));
//cout << data << endl;
count++;
}
else{
mergeSort(currBlock);
writeInFile(currBlock,blockNumber);
//resetting count and block vector
count = 0;
blockNumber++;
currBlock.clear();
//cout<<"Printing "<<blockNumber<<" block"<<endl;
currBlock.push_back(stoll(data));
//cout << data << endl;
count++;
}
}
// the last block needs to be written
if(!currBlock.empty()){
mergeSort(currBlock);
writeInFile(currBlock,blockNumber);
}
file.close();
//have saved all blocks sorted in chunks in output/output{fileNumber}.txt
//have to sort all the sorted blocks at once now.
vector<ifstream*> sortedFiles;
for(int i=0;i<noOfFilesWritten;i++){
string filePath = getOutputPathFromBlockNumber(i);
ifstream* file = new ifstream(filePath);
sortedFiles.push_back(file);
}
//save a pair in heap <ll,in> value,blocknumber need block number for increament of respective ifstream
vector<pair<ll,int>> firstFileValues;
for(int i=0;i<sortedFiles.size();i++){
string output;
if(getline(*sortedFiles[i],output)){
firstFileValues.push_back({stoll(output),i});
}
}
//got all the first values in a vector now make them a heap
ofstream finalOutFile(finalOutputFile);
auto h = MinHeap<pair<ll,int>>(firstFileValues);
while(h.getSize() != 0){
auto p = h.heapExtractMin();
//cout<<"value : "<<p.first<<" file : "<<p.second<<endl;
finalOutFile<<p.first<<"\n";
string output;
if(getline(*sortedFiles[p.second],output)){
h.insert({stoll(output),p.second});
}
}
finalOutFile.close();
for(int i=0;i<noOfFilesWritten;i++){
auto f = sortedFiles[i];
f->close();
free(sortedFiles[i]);
string filePath = getOutputPathFromBlockNumber(i);
remove(filePath.c_str());
}
}
|
6c4a317faff84c04caacd03706f88fcb8edc0be8
|
[
"C++"
] | 8
|
C++
|
2020201079/suffix_array-Trie_implementation-External_sorting
|
e0548779cbea25237efbed61dddbf36f871a1705
|
8c92dd99c886063b081b66a708d511dc624a754b
|
refs/heads/master
|
<repo_name>daniilosmolovskiy/wiki-bot<file_sep>/index.js
const express = require('express');
const { Telegram } = require('telegraf');
require('dotenv').config();
const tg = new Telegram(process.env.BOT_TOKEN);
const port = process.env.PORT || 3000;
const chat = '-1001342903377';
const app = express();
const getArticle = require('./getArticle');
app.get('/', async (req, res) => {
const fullArticle = await getArticle();
tg.sendPhoto(chat, `https:${fullArticle.imageSrc}`);
tg.sendMessage(chat, fullArticle.text.join('\n \n').trim(), { parse_mode: 'HTML', reply_markup: {
inline_keyboard: [
[{ text: "Полная статья", url: `https://ru.wikipedia.org/${fullArticle.articleLink}` }]
]
} });
res.send("Bot is working!");
})
app.listen(port);<file_sep>/README.md
# wiki-bot
This is a super simple Telegram Bot which sends a featured Wikipedia article of the day in Russian for you every day.
In the nearest future, I'll add some new features like the ability to switch language and maybe the theme of articles.
In this project I used Axios for getting the page, Cheerio to get needed data and Express to routing.
I deployed a project on the Heroku and configure CRON service for everyday notifications from the server and pushing the article to the Telegram.
Bot link - t.me/featured_wiki
Enjoy:)
|
cd9c4f29704576421b3db76e44317d40338e4eee
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
daniilosmolovskiy/wiki-bot
|
a5b53bb9fdeb48b3059118608a19ca6b6d6f7521
|
9bebca5efb5d15a72ea570893a491cde551b025c
|
refs/heads/master
|
<repo_name>DizzyRaven/KnightGame<file_sep>/Assets/Content/Scripts/Archer.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Archer : MonoBehaviour {
float DMGtimer = 0.2f;
public int startHP = 3;
int hp;
private float timer = time_to_wait;
private static float time_to_wait = 3;
float last_carrot = 0;
public float radius_attack = 3.0f;
bool isDead = false;
public AudioClip DMGSound = null;
AudioSource DMGSource = null;
Rigidbody2D abody = null;
private void Start()
{
DMGSource = gameObject.AddComponent<AudioSource>();
DMGSource.clip = DMGSound;
bool isDead = false;
// bool isDead = false;
abody = this.GetComponent<Rigidbody2D>();
hp = startHP;
}
private void FixedUpdate()
{
Animator animator = GetComponent<Animator>();
if (hp < startHP)
{
if (DMGtimer > 0)
{
DMGtimer -= Time.deltaTime;
animator.SetBool("dmg", true);
}
else
{
animator.SetBool("dmg", false);
DMGtimer = 0.2f;
startHP = hp;
}
}
if (hp <= 0)
{
abody.simulated = false;
animator.SetBool("die", true);
isDead = true;
timer -= Time.deltaTime;
if (timer <= 0)
{
Destroy(gameObject);
}
//Destroy(gameObject);
}
if (isDead == false)
{
float value = this.getDirection();
SpriteRenderer sr = this.GetComponent<SpriteRenderer>();
if (value < 0)
{
sr.flipX = false;
}
else if (value > 0)
{
sr.flipX = true;
}
}
}
float getDirection()
{
Animator animator = GetComponent<Animator>();
Vector3 my_pos = this.transform.position;
Vector3 rabit_pos = HeroControl.lastHero.transform.position;
if (Mathf.Abs(rabit_pos.x - my_pos.x) < radius_attack)
{
SpriteRenderer sr = this.GetComponent<SpriteRenderer>();
if (my_pos.x < rabit_pos.x && launchTime() && Mathf.Abs(rabit_pos.x - my_pos.x) < radius_attack)
{
animator.SetBool("attack",true);
launchCarrot(1);
sr.flipX = true;
last_carrot = Time.time;
return 0;
}
else if (my_pos.x > rabit_pos.x && launchTime() && Mathf.Abs(rabit_pos.x - my_pos.x) < radius_attack)
{
animator.SetBool("attack",true);
launchCarrot(-1);
sr.flipX = false;
last_carrot = Time.time;
return 0;
}
}
else
{
animator.SetBool("attack", false);
animator.SetBool("die", false);
}
// animator.SetBool("attack", true);
return 0;
}
bool launchTime()
{
return Time.time - last_carrot > 2.0f;
}
public GameObject prefabArrow;
void launchCarrot(float direction)
{
//Створюємо копію Prefab
GameObject obj = GameObject.Instantiate(this.prefabArrow);
//Розміщуємо в просторі
obj.transform.position = this.transform.position;
Vector3 temp = new Vector3(0, -0.1f, 0);
obj.transform.position += temp;
//Запускаємо в рух
Arrow arrow = obj.GetComponent<Arrow>();
arrow.launch(direction);
}
public void Damage(int damage)
{
hp -= damage;
if (hp<=0)
{
DMGSource.Play();
}
Animator animator = GetComponent<Animator>();
if (DMGtimer > 0)
{
DMGtimer -= Time.deltaTime;
animator.SetBool("dmg",true);
}
else
{
animator.SetBool("dmg", false);
}
//gameObject.GetComponent<Animation>().Play("ADMG");
}
}<file_sep>/Assets/Content/Scripts/Coin.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Coin : Collectable
{
public float Timer = 0.2f;
private bool up = false;
public AudioClip coinSound = null;
AudioSource attackSource = null;
void Start()
{
attackSource = gameObject.AddComponent<AudioSource>();
attackSource.clip = coinSound;
}
private void Update()
{
if (up == true)
{
if (Timer > 0)
{
Timer -= Time.deltaTime;
}
else
{
this.CollectedHide();
}
}
}
protected override void OnHeroHit(HeroControl hero)
{
attackSource.Play();
up = true;
}
}<file_sep>/Assets/Content/Scripts/HeroControl.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HeroControl : MonoBehaviour {
float DMGtimer = 0.2f;
public int startHP = 5;
public int hp = 5;
public float speed = 3f;
public float damage = 3f;
bool isGrounded = false;
bool JumpActive = false;
public bool isDead = false;
float JumpTime = 0f;
public float MaxJumpTime = 0.2f;
public float JumpSpeed = 0.2f;
public static HeroControl lastHero = null;
private float timer = time_to_wait;
private static float time_to_wait = 2;
public int DMG = 30;
private CC cc;
public AudioClip DMGSound = null;
AudioSource DMGSource = null;
Rigidbody2D myBody = null;
Transform heroParent = null;
// Use this for initialization
void Awake()
{
startHP = 5;
hp = startHP;
isDead = false;
lastHero = this;
}
void Start()
{
cc = GameObject.FindGameObjectWithTag("lc").GetComponent<CC>();
//lc = gameObject.findGetComponent<CoinCounter>();
DMGSource = gameObject.AddComponent<AudioSource>();
DMGSource.clip =DMGSound;
isDead = false;
hp = startHP;
LevelController.current.setStartPosition(transform.position);
myBody = this.GetComponent<Rigidbody2D>();
this.heroParent = this.transform.parent;
}
// Update is called once per frame
void Update () {
if (hp < startHP && hp >0)
{
if (DMGtimer > 0)
{
DMGtimer -= Time.deltaTime;
GetComponent<SpriteRenderer>().color = Color.red;
}
else
{
GetComponent<SpriteRenderer>().color = Color.white;
DMGtimer = 0.2f;
startHP = hp;
}
}
if (hp <= 0)
{
isDead = true;
//DMGSource.Play();
GetComponent<SpriteRenderer>().color = Color.white;
}
}
static void SetNewParent(Transform obj, Transform new_parent)
{
if (obj.transform.parent != new_parent)
{
//Засікаємо позицію у Глобальних координатах
Vector3 pos = obj.transform.position;
//Встановлюємо нового батька
obj.transform.parent = new_parent;
//Після зміни батька координати кролика зміняться
//Оскільки вони тепер відносно іншого об’єкта
//повертаємо кролика в ті самі глобальні координати
obj.transform.position = pos;
}
}
void FixedUpdate()
{
Animator animator = GetComponent<Animator>();
if (isDead == true)
{
// myBody.simulated=false;
HeroControl hero = GetComponent<HeroControl>();
animator.SetBool("dead", true);
timer -= Time.deltaTime;
if (timer <= 0)
{
LevelController.current.onHeroDeath(hero);
timer = time_to_wait;
isDead = false;
startHP = 5;
hp = startHP;
}
}
else
{
myBody.simulated = true;
animator.SetBool("dead", false);
}
if (isDead == true)
{
return;
}
Vector3 from = transform.position + Vector3.up * 0.1f;
Vector3 to = transform.position + Vector3.down * 0.2f;
int layer_id = 1 << LayerMask.NameToLayer("Ground");
RaycastHit2D hit = Physics2D.Linecast(from, to, layer_id);
if (hit)
{
//Перевіряємо чи ми опинились на платформі
if (hit.transform != null
&& hit.transform.GetComponent<MovingPlatform>() != null)
{
//Приліпаємо до платформи
SetNewParent(this.transform, hit.transform);
}
}
else
{
//Ми в повітрі відліпаємо під платформи
SetNewParent(this.transform, this.heroParent);
}
if (hit)
{
isGrounded = true;
}
else
{
isGrounded = false;
}
//Намалювати лінію (для розробника)
Debug.DrawLine(from, to, Color.red);
if (Input.GetButtonDown("Jump") && isGrounded)
{
this.JumpActive = true;
}
if (this.JumpActive)
{
//Якщо кнопку ще тримають
if (Input.GetButton("Jump"))
{
this.JumpTime += Time.deltaTime;
if (this.JumpTime < this.MaxJumpTime)
{
Vector2 vel = myBody.velocity;
vel.y = JumpSpeed * (1.0f - JumpTime / MaxJumpTime);
myBody.velocity = vel;
}
}
else
{
this.JumpActive = false;
this.JumpTime = 0;
}
}
if (this.isGrounded)
{
animator.SetBool("jump", false);
}
else
{
animator.SetBool("jump", true);
}
//[-1, 1]
float value = Input.GetAxis("Horizontal");
if (Mathf.Abs(value) > 0)
{
Vector2 vel = myBody.velocity;
vel.x = value * speed;
myBody.velocity = vel;
animator.SetBool("run", true);
}
else
{
animator.SetBool("run", false);
}
SpriteRenderer sr = GetComponent<SpriteRenderer>();
if (value < 0)
{
sr.flipX = true;
}
else if (value > 0)
{
sr.flipX = false;
}
}
private void OnCollisionEnter2D(Collision2D other)
{
if (other.transform.tag == "MovingPlatform")
{
transform.parent = other.transform;
}
}
private void OnCollisionExit2D(Collision2D other)
{
if (other.transform.tag != "MovingPlatform")
{
transform.parent = null;
}
}
void OnTriggerEnter2D(Collider2D collider)
{
if (collider.tag == "bottle")
{
if(hp<=5)
hp += 1;
}
if (collider.tag == "coin")
{
//Destroy(collider.gameObject);
cc.coins += 1;
}
}
public void BottleUp()
{
//int dmg = GetComponent
}
public void Damage(int damage)
{
hp -= damage;
DMGSource.Play();
}
}
<file_sep>/Assets/Content/Scripts/Door.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Door : MonoBehaviour {
public int lvlToLoad;
private CC cc;
private void Start()
{
cc = GameObject.FindGameObjectWithTag("lc").GetComponent<CC>();
}
private void OnTriggerEnter2D(Collider2D col)
{
if (col.CompareTag("hero"))
{
cc.press.text = ("Press E");
}
}
private void OnTriggerStay2D(Collider2D col)
{
if (col.CompareTag("hero"))
{
if (Input.GetKeyDown("e")){
Application.LoadLevel(lvlToLoad);
}
}
}
private void OnTriggerExit2D(Collider2D col)
{
if (col.CompareTag("hero"))
{
cc.press.text = ("");
}
}
}
<file_sep>/Assets/Content/Scripts/Bottle.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bottle : Collectable
{
protected override void OnHeroHit(HeroControl hero)
{
this.CollectedHide();
}
}<file_sep>/Assets/Content/Scripts/Collectable.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Collectable : MonoBehaviour
{
protected virtual void OnHeroHit(HeroControl hero)
{
// CollectedHide();
}
void OnTriggerEnter2D(Collider2D collider)
{
// if (!this.hideAnimation)
//{
HeroControl hero = collider.GetComponent<HeroControl>();
if (hero != null)
{
this.OnHeroHit(hero);
}
// }
}
public void CollectedHide()
{
Destroy(this.gameObject);
}
//=====================Collactables===============
}<file_sep>/Assets/Content/Scripts/EnemyAttack.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyAttack : MonoBehaviour
{
public int dmg = 100;
private void OnTriggerEnter2D(Collider2D col)
{
if (col.isTrigger != true && col.CompareTag("hero"))
{
col.SendMessageUpwards("Damage", dmg);
}
}
}
<file_sep>/Assets/Content/Scripts/Obstacles.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Obstacles : MonoBehaviour {
public int startHP=100;
public int hp;
float DMGtimer = 0.3f;
private void Start()
{
hp = startHP;
}
private void Update()
{
Animator animator = GetComponent<Animator>();
if (hp < startHP)
{
if (DMGtimer > 0)
{
DMGtimer -= Time.deltaTime;
animator.SetBool("dmg", true);
}
else
{
animator.SetBool("dmg", false);
DMGtimer = 0.2f;
startHP = hp;
}
}
if (hp <= 0)
{
Destroy(gameObject);
}
}
public void Damage(int damage)
{
hp -= damage;
}
}
<file_sep>/Assets/Content/Scripts/HeroFollow.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HeroFollow : MonoBehaviour
{
public double pluss = 0.3;
public HeroControl hero;
void Update()
{
//Отримуємо доступ до компонента Transform
//це Скорочення до GetComponent<Transform>
Transform hero_transform = hero.transform;
//Отримуємо доступ до компонента Transform камери
Transform camera_transform = this.transform;
//Отримуємо доступ до координат кролика
Vector3 hero_position = hero_transform.position;
Vector3 camera_position = camera_transform.position;
//Рухаємо камеру тільки по X,Y
camera_position.x = hero_position.x;
camera_position.y = hero_position.y+(1/2);
//Встановлюємо координати камери
camera_transform.position = camera_position;
}
}<file_sep>/Assets/Content/Scripts/CC.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CC : MonoBehaviour {
public int coins;
public Text coinsText;
public Text press;
private void Update()
{
coinsText.text = (""+coins/2);
}
}
<file_sep>/Assets/Content/Scripts/MovingPlatform.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovingPlatform : MonoBehaviour
{
public GameObject patform;
public float speed;
public float time_to_wait;
private float timer;
public Transform currentPoint;
public Transform[] points;
public int pointSelection;
void Start()
{
timer = time_to_wait;
currentPoint = points[pointSelection];
}
void Update()
{
patform.transform.position = Vector3.MoveTowards(patform.transform.position, currentPoint.position, Time.deltaTime * speed);
if (patform.transform.position == currentPoint.position)
{
//timer
timer -= Time.deltaTime;
if (timer <= 0)
{
pointSelection++;
timer = time_to_wait;
}
if (pointSelection == points.Length)
{
pointSelection = 0;
}
currentPoint = points[pointSelection];
}
}
}<file_sep>/Assets/Content/Scripts/Arrow.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Arrow : MonoBehaviour {
public int dmg = 20;
public float speed = 7f;
void Start()
{
StartCoroutine(destroyLater());
}
public void launch(float direction)
{
Rigidbody2D myBody = this.GetComponent<Rigidbody2D>();
float value = direction;
Vector2 vel = myBody.velocity;
vel.x = value * speed;
myBody.velocity = vel;
SpriteRenderer sr = this.GetComponent<SpriteRenderer>();
if (value < 0)
{
sr.flipX = false;
}
else if (value > 0)
{
sr.flipX = true;
}
}
IEnumerator destroyLater()
{
yield return new WaitForSeconds(1.5f);
Destroy(this.gameObject);
}
private void OnTriggerEnter2D(Collider2D col)
{
if (col.isTrigger != true && col.CompareTag("hero"))
{
col.SendMessageUpwards("Damage", dmg);
Destroy(this.gameObject);
}
}
}
<file_sep>/Assets/Content/Scripts/PigController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PigController : MonoBehaviour
{
public int hp = 1;
public float runSpeed = 1f;
public float walkSpeed = 0.3f;
float speed;
public float patrolDistance = 3;
public float value = 0;
bool heroDead = false;
private float timer = time_to_wait;
private static float time_to_wait = 2;
public AudioClip attackSound = null;
AudioSource attackSource = null;
Vector3 pointA;
Vector3 pointB;
Mode mode;
Mode oldMode;
Rigidbody2D myBody = null;
void Start()
{
attackSource = gameObject.AddComponent<AudioSource>();
attackSource.clip = attackSound;
speed = walkSpeed;
mode = Mode.GoToA;
pointA = this.transform.position;
pointB = pointA;
pointA.x += patrolDistance;
pointB.x -= patrolDistance;
// GetComponent<Animator>().SetBool("dead", false);
myBody = this.GetComponent<Rigidbody2D>();
// LevelController.current.setStartPosition(transform.position);
}
public enum Mode
{
GoToA,
GoToB,
Attack,
Dead
}
float getDirection()
{
if (mode != Mode.Attack)
oldMode = mode;
Vector3 hero_pos = HeroControl.lastHero.transform.position;
Vector3 my_pos = this.transform.position;
if (hero_pos.x > Mathf.Min(pointA.x, pointB.x)
&& hero_pos.x < Mathf.Max(pointA.x, pointB.x)&&heroDead==false)
{
mode = Mode.Attack;
}
else {
mode = oldMode;
}
if (hero_pos.x > Mathf.Min(pointA.x, pointB.x)
&& hero_pos.x < Mathf.Max(pointA.x, pointB.x) && heroDead == true)
{
this.mode = Mode.GoToA;
}
else {
heroDead = false;
}
if (mode == Mode.Attack && heroDead==false)
{
Animator animator = GetComponent<Animator>();
animator.SetBool("run", true);
speed = runSpeed;
if (my_pos.x < hero_pos.x)
{
return 1;
}
else
{
return -1;
}
}
else
{
Animator animator = GetComponent<Animator>();
animator.SetBool("run", false);
speed = walkSpeed;
}
//======
if (this.mode == Mode.GoToA)
{
if (my_pos.x > pointA.x)
{
this.mode = Mode.GoToB;
}
return 1;
}
else if (this.mode == Mode.GoToB)
{
if (my_pos.x < pointB.x)
{
this.mode = Mode.GoToA;
}
return -1;
}
return 0;
}
private void Update()
{
}
private void FixedUpdate()
{
Animator animator = GetComponent<Animator>();
if (hp<=0)
{
myBody.simulated = false;
animator.SetBool("die", true);
timer -= Time.deltaTime;
if (timer <= 0)
{
Destroy(gameObject);
}
}
value = this.getDirection();
if (Mathf.Abs(value) > 0)
{
Vector2 vel = myBody.velocity;
vel.x = value * speed;
myBody.velocity = vel;
}
SpriteRenderer sr = GetComponent<SpriteRenderer>();
if (value < 0)
{
sr.flipX = false;
}
else if (value > 0)
{
sr.flipX = true;
}
}
void OnTriggerEnter2D(Collider2D collider)
{
if (collider.tag == "hero")
{
heroDead = true;
}
else{
}
}
public void Damage(int damage)
{
attackSource.Play();
hp -= damage;
}
}<file_sep>/Assets/Content/Scripts/CheckPoint.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CheckPoint : MonoBehaviour {
public AudioClip attackSound = null;
AudioSource attackSource = null;
private int once = 1;
void Start()
{
attackSource = gameObject.AddComponent<AudioSource>();
attackSource.clip = attackSound;
}
void OnTriggerEnter2D(Collider2D collider)
{
//Намагаємося отримати компонент кролика
HeroControl hero = collider.GetComponent<HeroControl>();
//Впасти міг не тільки кролик
if (hero != null)
{
if (once == 1)
{
attackSource.Play();
Vector3 temp = new Vector3(0, 0, -1f);
LevelController.current.setStartPosition(transform.position + temp);
Animator animator = GetComponent<Animator>();
animator.SetBool("fire", true);
once = 0;
}
}
}
//
}
<file_sep>/Assets/Content/Scripts/HeroAttack.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HeroAttack : MonoBehaviour
{
private bool attacking = false;
private float attackTimer = 0;
private float attackCD = 0.4f;
public Collider2D attackTrigger;
private Animator anim;
public AudioClip attackSound = null;
AudioSource attackSource = null;
private void Awake()
{
anim = gameObject.GetComponent<Animator>();
attackTrigger.enabled = false;
}
void Start()
{
attackSource = gameObject.AddComponent<AudioSource>();
attackSource.clip = attackSound;
// attackFlashSource.Play();
}
private void Update()
{
if (Input.GetKeyDown("f") && !attacking)
{
attackSource.Play();
attacking = true;
attackTimer = attackCD;
attackTrigger.enabled = true;
}
if (attacking)
{
if (attackTimer > 0)
{
attackTimer -= Time.deltaTime;
}
else
{
attacking = false;
attackTrigger.enabled = false;
}
}
anim.SetBool("attack", attacking);
}
}
<file_sep>/Assets/Content/Scripts/HUD.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HUD : MonoBehaviour {
public Sprite[] HeartSprites;
public Image HeartUI;
private HeroControl hero;
private void Start()
{
hero = GameObject.FindGameObjectWithTag("hero").GetComponent<HeroControl>();
}
private void Update()
{
int num = hero.hp;
if (hero.hp < 0)
num = 0;
if (hero.hp > 5)
num = 5;
HeartUI.sprite = HeartSprites[num];
}
}
<file_sep>/Assets/Content/Scripts/Archer2.0.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Archer2 : MonoBehaviour {
public int startHP;
public int currentHP;
public float distance;
public float shootInterval;
public float arrrowSpeed = 100;
public float arrowTimer;
//booleans
public GameObject bullet;
public Transform target;
public Animator anim;
public Transform shootPointLeft;
public Transform shootPointRight;
}
|
fa72fd9eacccdd915968b6de7bf51be96c6d650e
|
[
"C#"
] | 17
|
C#
|
DizzyRaven/KnightGame
|
921a300ac6fcc24b1317ec2f2c8eeec735476e29
|
8417b0afd27297ee37f9764c0c00c919afbf1b74
|
refs/heads/master
|
<file_sep>#include <sys/types.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/poll.h>
#include <pthread.h>
#include <iostream>
#define MAX_EVENT_NUMBER 1024
#define BUFFER_SIZE 10
using namespace std;
int setnonblocking(int fd)
{ //设置文件描述符为非阻塞
int old_option = fcntl(fd, F_GETFL);
int new_option = old_option | O_NONBLOCK;
fcntl(fd, F_SETFL, new_option);
return old_option; //返回旧描述符以便以后恢复
}
void addfd(int epollfd, int fd, bool enable_et)
{ //添加文件描述符fd到事件表epollfd中
epoll_event event;
event.data.fd = fd;
event.events = EPOLLIN; //可读事件
if (enable_et)
{ //支持ET模式
event.events |= EPOLLET;
}
epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &event); //添加事件
setnonblocking(fd);
}
void lt(epoll_event *events, int number, int epollfd, int listenfd)
{ //LT模式
char buf[BUFFER_SIZE];
for (int i = 0; i < number; i++)
{ //就绪事件
int sockfd = events[i].data.fd;
if (sockfd == listenfd)
{ //若为服务端监听端口表示事件(有新连接)发生则接受连接
struct sockaddr_in client_address;
socklen_t client_addrlength = sizeof(client_address);
int connfd = accept(listenfd, (struct sockaddr *)&client_address, &client_addrlength);
addfd(epollfd, connfd, false); //将新连接添加到事件表且设置为非ET
}
else if (events[i].events & EPOLLIN)
{ //客户端连接事件(有数据发送到服务端)发生则服务端接收数据
cout << "event trigger once" << endl;
memset(buf, '\0', BUFFER_SIZE);
int ret = recv(sockfd, buf, BUFFER_SIZE - 1, 0);
if (ret <= 0)
{ //客户连接已关闭
close(sockfd);
continue;
}
cout << "receive data:" << ret << " " << buf << endl; //输出服务端接收到的数据
}
else
{
cout << "something wrong" << endl;
}
}
}
void et(epoll_event *events, int number, int epollfd, int listenfd)
{ //ET模式
char buf[BUFFER_SIZE];
for (int i = 0; i < number; i++)
{ //就绪事件
int sockfd = events[i].data.fd;
if (sockfd == listenfd)
{ //监听端口有新连接
struct sockaddr_in client_address;
socklen_t client_addrlength = sizeof(client_address);
int connfd = accept(listenfd, (struct sockaddr *)&client_address, &client_addrlength);
addfd(epollfd, connfd, true); //新连接设置为ET模式
}
else if (events[i].events & EPOLLIN)
{ //客户端有数据发送到服务端
cout << "event trigger once" << endl;
while (1)
{ //这里要一次性读完客户端发送来的数据因为ET是不会重复触发
memset(buf, '\0', BUFFER_SIZE);
int ret = recv(sockfd, buf, BUFFER_SIZE - 1, 0);
if (ret < 0)
{ //非阻塞IO中recv返回-1并不一定是出错
if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
{ //errno为EAGAIN和EWOULDBLOCK时表示数据已经读取完毕可以进行下一次epoll
cout << "epoll again" << endl;
break;
}
close(sockfd);
break;
}
else if (ret == 0)
{ //连接已关闭
close(sockfd);
}
else
{
cout << "receive data:" << ret << " " << buf << endl; //输出接收到的数据
}
}
}
else
{
cout << "somethig wrong" << endl;
}
}
}
int main(int argc, char *argv[])
{
if (argc <= 2)
{
cout << "argc<=2" << endl;
return 1;
}
const char *ip = argv[1];
int port = atoi(argv[2]);
int ret = 0;
struct sockaddr_in address;
bzero(&address, sizeof(address));
address.sin_family = AF_INET;
inet_pton(AF_INET, ip, &address.sin_addr);
address.sin_port = htons(port);
int listenfd = socket(PF_INET, SOCK_STREAM, 0);
assert(listenfd >= 0);
ret = bind(listenfd, (struct sockaddr *)&address, sizeof(address));
assert(ret != -1);
ret = listen(listenfd, 5);
assert(ret != -1);
epoll_event events[MAX_EVENT_NUMBER];
int epollfd = epoll_create(5); //这里的5只是给内核一个提示事件表的大小无实际作用
assert(epollfd != -1);
addfd(epollfd, listenfd, true); //###1###将监听端口设置为非阻塞的理由见后面
while (1)
{
int ret = epoll_wait(epollfd, events, MAX_EVENT_NUMBER, -1); //等待事件就绪
if (ret < 0)
{
cout << "epoll error" << endl;
break;
}
//lt(events,ret,epollfd,listenfd);//采用LT模式
et(events, ret, epollfd, listenfd); //采用ET模式
}
close(listenfd);
return 0;
}<file_sep>#ifndef PROCESSPOOL_H
#define PROCESSPOOL_H
#include <list>
#include <cstdio>
#include <exception>
#include <pthread.h>
#include "locker.h"
template <typename T>
class pthreadpool
{
public:
pthreadpool(int max_pthread = 8, int max_request = 10000);
~pthreadpool();
bool append(T* request);
private:
int max_pthread;
int max_request;
pthread_t *pthread_arr;
std::list<T*> request_list;
locker list_lock;
mem list_mem;
bool stop;
private:
static void* work(void*);
void run();
};
template <typename T>
void* pthreadpool<T>::work(void *arg)
{
pthreadpool *pool = (pthreadpool*)arg;
pool -> run();
return pool;
}
template <typename T>
void pthreadpool<T>::run()
{
while(!stop)
{
list_mem.wait();
list_lock.dolock();
if (request_list.empty())
{
list_lock.unlock();
continue;
}
T* request = request_list.front();
request_list.pop_front();
list_lock.unlock();
if (!request)
{
continue;
}
request -> process();
}
}
template <typename T>
bool pthreadpool<T>:: append(T* request)
{
list_lock.dolock();
if (list.size() > max_request)
{
list_lock.unlock();
return false;
}
request_list.push_back(request);
list.unlock();
list_mem.post();
return true;
}
template <typename T>
pthreadpool<T>::pthreadpool(int max_pthread, int max_request) :
max_pthread(max_pthread), max_request(max_request), pthread_arr(nullptr), stop(true)
{
if (max_pthread <= 0 || max_request <= 0)
{
throw std::exception();
}
pthread_arr = new pthread_t[max_pthread];
if (!pthread_arr)
{
throw std::exception();
}
for (int i = 0; i < max_pthread; ++i)
{
if (pthread_create(&pthread_arr[i], NULL, work, this) != 0)
{
delete [] pthread_arr;
throw std::exception();
}
if (pthread_detach(pthread_arr[i]) != 0)
{
delete [] pthread_arr;
throw std::exception();
}
}
}
template <typename T>
pthreadpool<T>::~pthreadpool()
{
delete [] pthread_arr;
stop = true;
}
#endif<file_sep># A server Demo<file_sep>#ifndef HTTPCONNECTION_H
#define HTTPCONNECTION_H
class http_conn
{
public:
static const int FILENAME_LEN = 200;
static const int READ_BUFFER_SIZE = 2048;
static const int WRITE_BUFFER_SIZE = 1024;
};
#endif<file_sep>#ifndef LOCKER_H
#define LOCKER_H
#include <exception>
#include <pthread.h>
#include <semaphore.h>
class sem
{
public:
sem()
{
if (sem_init(&m_sem, 0, 0) != 0)
{
throw std::exception();
}
}
~sem()
{
sem_destroy(&m_sem);
}
bool wait()
{
return sem_wait(&m_sem) == 0;
}
bool post()
{
return sem_post(&m_sem) == 0;
}
private:
sem_t m_sem;
};
class locker
{
private:
pthread_mutex_t m_lock;
public:
locker()
{
pthread_mutex_init(&m_lock,0);
}
~locker()
{
pthread_mutex_destroy(&m_lock);
}
bool dolock()
{
return (pthread_mutex_lock(&m_lock)==0);
}
bool unlock()
{
return (pthread_mutex_unlock(&m_lock) == 0);
}
};
#endif
|
d123eda7b5b9bdcb1d41fdb615538b35c5cb6f9d
|
[
"Markdown",
"C++"
] | 5
|
C++
|
chenmo874300/ServerDemo
|
24349881c6cd522734c3a192592f5eb89109a0f8
|
3dd60759ab016db2bedbdb04bc21b2fd5493f2a1
|
refs/heads/master
|
<repo_name>moveis-simonetti/ext-php-daruma<file_sep>/config.w32
// $Id$
// vim:ft=javascript
// If your extension references something external, use ARG_WITH
// ARG_WITH("daruma_framework", "for daruma_framework support", "no");
// Otherwise, use ARG_ENABLE
// ARG_ENABLE("daruma_framework", "enable daruma_framework support", "no");
if (PHP_DARUMA_FRAMEWORK != "no") {
EXTENSION("daruma_framework", "daruma_framework.c");
}
<file_sep>/library.c
#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>
#include "library.h"
static void* dynamicLibrary = NULL;
// Load the DarumaFramework for memory
void loadDarumaFramework()
{
dynamicLibrary = dlopen("/opt/DarumaFramework/libDarumaFramework.so", RTLD_LAZY);
if (!dynamicLibrary) {
fputs (dlerror(), stderr);
exit(1);
}
}
// Unload Daruma Framework of memory.
//
void unloadDarumaFramework()
{
char* error = NULL;
int descarregou = 0;
if (dynamicLibrary)
{
#ifdef WIN32
descarregou = FreeLibrary((HMODULE) dynamicLibrary);
#else
descarregou = dlclose(dynamicLibrary);
#endif
}
if (!descarregou) {
#ifdef WIN32
error = (char*) GetLastError();
#else
error = dlerror();
#endif
printf("Erro ao descarregar a DarumaFrameWork: %s\n", error);
}
}
// @param nameFunction function name for load memory.
// @return pointer for function or NULL;
//
void* loadFunctionDarumaFramework(const char* nameFunction)
{
void* function = NULL;
char* error = NULL;
if (NULL == dynamicLibrary)
{
loadDarumaFramework();
}
#ifdef WIN32
function = GetProcAddress((HMODULE) dynamicLibrary, nameFunction);
#else
function = dlsym(dynamicLibrary, nameFunction);
#endif
if (NULL == function)
{
#ifdef WIN32
error = (char*) GetLastError();
#else
error = dlerror();
#endif
printf("error ao carregar a funcao %s: %s\n", nameFunction, error);
}
return function;
}
<file_sep>/daruma_functions.c
#include "daruma_functions.h"
#include "php_daruma_framework.h"
static void* dynamicLibrary = NULL;
int eBuscarPortaVelocidade_DUAL_DarumaFramework(){
return ((int (*) (void)) loadFunctionDarumaFramework("eBuscarPortaVelocidade_DUAL_DarumaFramework")) ();
}
int iCFImprimir_NFCe_Daruma(char* pszPathXMLVenda, char* pszPathRetornoWS, char* pszLinkQrCode, int iNumColunas, int iTipoNF){
return ((int (*) (char*, char*, char*, int, int)) loadFunctionDarumaFramework("iCFImprimir_NFCe_Daruma"))(pszPathXMLVenda, pszPathRetornoWS, pszLinkQrCode, iNumColunas, iTipoNF);
}
int regAlterarValor_Daruma(char* pszPathChave, char* pszValor){
return ((int (*) (char*, char*)) loadFunctionDarumaFramework("regAlterarValor_Daruma")) (pszPathChave, pszValor);
}
int eDefinirProduto_Daruma(char* pszProduto) {
return ((int (*) (char*)) loadFunctionDarumaFramework("eDefinirProduto_Daruma")) (pszProduto);
}
int iImprimirTexto_DUAL_DarumaFramework(char* pszString, int iTam) {
return ((int (*) (char*, int)) loadFunctionDarumaFramework("iImprimirTexto_DUAL_DarumaFramework")) (pszString, iTam);
}
<file_sep>/daruma_functions.h
#ifndef PHP_5_6_18_DARUMA_FUNCTIONS_H
#define PHP_5_6_18_DARUMA_FUNCTIONS_H
#include "library.h"
#define RET_ERRO_ZEND_BIND
#define ZEND_PARAM INTERNAL_FUNCTION_PARAMETERS
#define ZEND_PARAM_PASS INTERNAL_FUNCTION_PARAM_PASSTHRU
#endif //PHP_5_6_18_DARUMA_FUNCTIONS_H
<file_sep>/instalar_daruma
#!/bin/bash
echo "Este aplicativo preparara sua maquina para operaçao com a impressora Daruma"
echo "pressione <Enter> para prosseguir ou CTRL + C para cancelar"
read
sleep 2
export http_proxy=http://192.168.111.25:3128
echo "Atualizando Para a última versão do php5"
apt-get update
apt-get -q -y install php5-dev
if [ -d /tmp/libdaruma ]; then
rm -rf /usr/local/share/DarumaFramework
rm -rf /tmp/libdaruma
fi
mkdir -p /usr/local/share/DarumaFramework
chmod -R 777 /usr/local/share/DarumaFramework
echo "Baixando bibliotecas da Daruma"
mkdir /tmp/libdaruma
cd /tmp/libdaruma
PHP_VERSION=`php -v 2> /dev/null | egrep ^PHP | cut -d ' ' -f 2 | cut -d '-' -f 1`
wget --no-cache http://terminal.moveissimonetti.com.br/desenvolvimento/MS-TEF/$PHP_VERSION/DarumaFramework.zip
if [ $? != 0 ]; then
echo "Erro no download do pacote. Tente novamente"
exit 1
fi
unzip -x DarumaFramework.zip
if [ -d /opt/DarumaFramework ]; then
rm -rf /opt/DarumaFramework
fi
mkdir -p /opt/DarumaFramework
cp DarumaFramework/* /opt/DarumaFramework/
chmod -R 777 /opt/DarumaFramework
cp php_darumaframework.ini /etc/php5/mods-available/
VERSION_ZEND_MODULE=`phpize -v 2> /dev/null | egrep ^Zend\ Module | cut -d ' ' -f 10`
if [ ! -d /usr/lib/php5/$VERSION_ZEND_MODULE ]; then
mkdir /usr/lib/php5/$VERSION_ZEND_MODULE
fi
cp php_darumaframework.so /usr/lib/php5/$VERSION_ZEND_MODULE/
php5enmod php_darumaframework
service apache2 restart
<file_sep>/library.h
//
// Created by <NAME> on 2/17/16.
//
#ifndef PHP_5_6_18_LIBRARY_H
#define PHP_5_6_18_LIBRARY_H
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
#include "php.h"
void loadDarumaFramework();
void unloadDarumaFramework();
void* loadFunctionDarumaFramework(const char* nameFunction);
#endif //PHP_5_6_18_LIBRARY_H
<file_sep>/daruma_framework.c
/*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2016 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| <EMAIL> so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "php_daruma_framework.h"
#include "library.h"
#include "daruma_functions.h"
/* True global resources - no need for thread safety here */
static int le_daruma_framework;
/* {{{ PHP_INI
*/
PHP_INI_BEGIN()
PHP_INI_ENTRY("darumaframework.path", "/opt/DarumaFramework/libDarumaFramework.so", PHP_INI_ALL, NULL)
PHP_INI_END()
PHP_FUNCTION(eBuscarPortaVelocidade_DUAL_DarumaFramework)
{
if(zend_parse_parameters_none() != SUCCESS) {
return RET_ERRO_ZEND_BIND;
}
RETURN_LONG(eBuscarPortaVelocidade_DUAL_DarumaFramework());
}
PHP_FUNCTION(iImprimirTexto_DUAL_DarumaFramework)
{
char* texto;
zend_long tam;
size_t stringLen = 0;
if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sl", &texto, &stringLen, &tam) != SUCCESS) {
return RET_ERRO_ZEND_BIND;
}
RETURN_LONG(iImprimirTexto_DUAL_DarumaFramework(texto, tam));
}
PHP_FUNCTION(eDefinirProduto_Daruma)
{
char* produto;
size_t produtoLen = 0;
if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &produto, &produtoLen) != SUCCESS) {
return RET_ERRO_ZEND_BIND;
}
RETURN_LONG(eDefinirProduto_Daruma(produto));
}
PHP_FUNCTION(regAlterarValor_Daruma)
{
char* pathChave;
char* valor;
size_t pathChaveLen = 0;
size_t valorLen = 0;
if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &pathChave, &pathChaveLen, &valor, &valorLen) != SUCCESS) {
return RET_ERRO_ZEND_BIND;
}
RETURN_LONG(regAlterarValor_Daruma(pathChave, valor));
}
PHP_FUNCTION(iCFImprimir_NFCe_Daruma)
{
char* pathXMLVenda;
char* pathRetornoWS;
char* linkQrCode;
zend_long numColunas = 0;
zend_long tipoNF = 0;
size_t pathXMLVendaLen = 0;
size_t pathRetornoWSLen = 0;
size_t linkQrCodeLen = 0;
if(zend_parse_parameters(ZEND_NUM_ARGS(), "sssll", &pathXMLVenda, &pathXMLVendaLen, &pathRetornoWS, &pathRetornoWSLen, &linkQrCode, &linkQrCodeLen, &numColunas, &tipoNF) != SUCCESS) {
return;
}
RETURN_LONG(iCFImprimir_NFCe_Daruma(pathXMLVenda, pathRetornoWS, linkQrCode, numColunas, tipoNF));
}
PHP_MINIT_FUNCTION(daruma_framework)
{
return SUCCESS;
}
PHP_MSHUTDOWN_FUNCTION(daruma_framework)
{
return SUCCESS;
}
PHP_RINIT_FUNCTION(daruma_framework)
{
return SUCCESS;
}
PHP_RSHUTDOWN_FUNCTION(daruma_framework)
{
unloadDarumaFramework();
return SUCCESS;
}
PHP_MINFO_FUNCTION(daruma_framework)
{
php_info_print_table_start();
php_info_print_table_header(2, "daruma_framework support", "enabled");
php_info_print_table_row(2, "DarumaFramework carregada em", INI_ORIG_STR("darumaframework.path"));
php_info_print_table_row(2, "eBuscarPortaVelocidade_DUAL_DarumaFramework", "Sim");
php_info_print_table_row(2, "iImprimirTexto_DUAL_DarumaFramework", "Sim");
php_info_print_table_row(2, "iCFImprimir_NFCe_Daruma", "Sim");
php_info_print_table_row(2, "eDefinirProduto_Daruma", "Sim");
php_info_print_table_end();
}
const zend_function_entry daruma_framework_functions[] = {
PHP_FE(eBuscarPortaVelocidade_DUAL_DarumaFramework, NULL)
PHP_FE(iImprimirTexto_DUAL_DarumaFramework, NULL)
PHP_FE(eDefinirProduto_Daruma, NULL)
PHP_FE(regAlterarValor_Daruma, NULL)
PHP_FE(iCFImprimir_NFCe_Daruma, NULL)
PHP_FE_END
};
zend_module_entry daruma_framework_module_entry = {
STANDARD_MODULE_HEADER,
"daruma_framework",
daruma_framework_functions,
PHP_MINIT(daruma_framework),
PHP_MSHUTDOWN(daruma_framework),
PHP_RINIT(daruma_framework),
PHP_RSHUTDOWN(daruma_framework),
PHP_MINFO(daruma_framework),
PHP_DARUMA_FRAMEWORK_VERSION,
STANDARD_MODULE_PROPERTIES
};
#ifdef COMPILE_DL_DARUMA_FRAMEWORK
ZEND_GET_MODULE(daruma_framework)
#endif
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
|
387efa73f64da21cab4088ce813097128d279400
|
[
"JavaScript",
"C",
"Shell"
] | 7
|
JavaScript
|
moveis-simonetti/ext-php-daruma
|
806dd692503dc20314297287d88d2c4c6800727d
|
f159fb8d72cf960ec7bbfc5c5cacf41cfe6b2c6a
|
refs/heads/master
|
<repo_name>Yash25gupta/LocationSenderAdmin<file_sep>/settings.gradle
rootProject.name='Location Sender Admin'
include ':app'
<file_sep>/app/src/main/java/com/location/jobservice/admin/DisplayPolyLine.java
package com.location.jobservice.admin;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class DisplayPolyLine extends AppCompatActivity implements OnMapReadyCallback, SeekBar.OnSeekBarChangeListener {
private static final String TAG = "DisplayPolyLine";
private static final String collection = "Locations";
private boolean isShowingBoard = true;
private LinearLayout settingsLayout;
private FirebaseFirestore fStore;
private String target;
private List<Map<String, Double>> historyList = new ArrayList<>();
GoogleMap gMap;
SeekBar seekWidth, seekRed, seekGreen, seekBlue;
Button btnDraw, btnClear;
Polyline polyline = null;
List<LatLng> latLngList = new ArrayList<>();
List<Marker> markerList = new ArrayList<>();
int red = 0, green = 0, blue = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_poly_line);
Toolbar toolbar = findViewById(R.id.pl_toolbar);
setSupportActionBar(toolbar);
if (getIntent().getExtras() == null){
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
} else {
target = getIntent().getExtras().getString("name");
}
seekWidth = findViewById(R.id.pl_seekWidth);
seekRed = findViewById(R.id.pl_seekRed);
seekGreen = findViewById(R.id.pl_seekGreen);
seekBlue = findViewById(R.id.pl_seekBlue);
btnDraw = findViewById(R.id.pl_btnDraw);
btnClear = findViewById(R.id.pl_btnClear);
settingsLayout = findViewById(R.id.pl_settingsLayout);
fStore = FirebaseFirestore.getInstance();
// Initialize SupportMapFragment
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.pl_googleMap);
supportMapFragment.getMapAsync(this);
// Get History List
fStore.collection(collection).document(target)
.get()
.addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()){
DocumentSnapshot document = task.getResult();
if (document.exists()){
Log.d(TAG, "DocumentSnapshot data: " + document.getData());
historyList = (List<Map<String, Double>>) document.get("History");
// history: [{Lng=11.11, Lat=11.11}, {Lng=22.22, Lat=22.22}, {Lng=78.06139, Lat=27.889661}]
for (Map<String, Double> map : historyList){
// map: {Lng=11.11, Lat=11.11}
LatLng latLng = new LatLng(map.get("Lat"), map.get("Lng"));
MarkerOptions markerOptions = new MarkerOptions().position(latLng);
Marker marker = gMap.addMarker(markerOptions);
markerList.add(marker);
latLngList.add(latLng);
}
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
btnDraw.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// latLngList==> [lat/lng: (22.545407609795284,1.2740881741046906), lat/lng: (15.715659846482021,17.871770225465298)]
// Draw Polyline on Map
if (polyline != null) polyline.remove();
// Create PolylineOptions
PolylineOptions polylineOptions = new PolylineOptions().addAll(latLngList).clickable(true);
polyline = gMap.addPolyline(polylineOptions);
// set Polyline Color
polyline.setColor(Color.rgb(red, green, blue));
setWidth();
}
});
btnClear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Clear All
if (polyline != null) polyline.remove();
for (Marker marker : markerList) marker.remove();
latLngList.clear();
markerList.clear();
seekWidth.setProgress(3);
seekRed.setProgress(0);
seekGreen.setProgress(0);
seekBlue.setProgress(0);
}
});
seekRed.setOnSeekBarChangeListener(this);
seekGreen.setOnSeekBarChangeListener(this);
seekBlue.setOnSeekBarChangeListener(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
gMap = googleMap;
/*gMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
// Create MarkerOptions
MarkerOptions markerOptions = new MarkerOptions().position(latLng);
// Create Marker
Marker marker = gMap.addMarker(markerOptions);
// Add LatLng and Marker
latLngList.add(latLng);
markerList.add(marker);
}
});*/
}
private void setWidth() {
seekWidth.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// Get Seekbar Progess
int width = seekWidth.getProgress();
if (polyline != null)
// Set Polyline Width
polyline.setWidth(width);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
switch (seekBar.getId()) {
case R.id.pl_seekRed:
red = progress;
break;
case R.id.pl_seekGreen:
green = progress;
break;
case R.id.pl_seekBlue:
blue = progress;
break;
}
// set Polyline Color
polyline.setColor(Color.rgb(red, green, blue));
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.mnu_home:
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
return true;
case R.id.mnu_eye:
if (isShowingBoard) {
settingsLayout.setVisibility(View.GONE);
isShowingBoard = false;
} else {
settingsLayout.setVisibility(View.VISIBLE);
isShowingBoard = true;
}
return true;
case R.id.mnu_menu:
Toast.makeText(this, "Menu", Toast.LENGTH_SHORT).show();
return true;
case R.id.mnu_menu2:
Toast.makeText(this, "Menu2", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
|
fdd7f08e52e5919933700cfbf1761653db3d4805
|
[
"Java",
"Gradle"
] | 2
|
Gradle
|
Yash25gupta/LocationSenderAdmin
|
2a81d8422a274d3b1092dabac0024fa99c743b35
|
8ee13b54d47a2e23567c7b8d99a5b533165e726a
|
refs/heads/master
|
<repo_name>SoySaucelm/IDCardUtil<file_sep>/IDCardUtil.php
<?php
/**
* 身份证验证的工具(支持15位或18位省份证)
* 身份证号码结构:
* <p>
* 根据〖中华人民共和国国家标准GB11643-1999〗中有关公民身份号码的规定,公民身份号码是特征组合码,由十七位数字本体码和一位数字校验码组成。
* 排列顺序从左至右依次为:6位数字地址码,8位数字出生日期码,3位数字顺序码和1位数字校验码。
* <p>
* 地址码(前6位):表示对象常住户口所在县(市、镇、区)的行政区划代码,按GB/T2260的规定执行。
* <li>前1、2位数字表示:所在省份的代码;</li>
* <li>第3、4位数字表示:所在城市的代码;</li>
* <li>第5、6位数字表示:所在区县的代码;</li>
* <p>
* 出生日期码,(第7位 - 14位):表示编码对象出生年、月、日,按GB按GB/T7408的规定执行,年、月、日代码之间不用分隔符。
* <p>
* 顺序码(第15位至17位):表示在同一地址码所标示的区域范围内,对同年、同月、同日出生的人编订的顺序号,顺序码的奇数分配给男性,偶数分配给女性。
* <li>第15、16位数字表示:所在地的派出所的代码;</li>
* <li>第17位数字表示性别:奇数表示男性,偶数表示女性;</li>
* <li>第18位数字是校检码:也有的说是个人信息码,一般是随计算机的随机产生,用来检验身份证的正确性。校检码可以是0~9的数字,有时也用x表示。</li>
* <p>
* 校验码(第18位数):
* <p>
* 十七位数字本体码加权求和公式 s = sum(Ai*Wi), i = 0..16,先对前17位数字的权求和;
* Ai:表示第i位置上的身份证号码数字值.Wi:表示第i位置上的加权因子.Wi: 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2;
* 计算模 Y = mod(S, 11)
* 通过模得到对应的模 Y: 0 1 2 3 4 5 6 7 8 9 10 校验码: 1 0 X 9 8 7 6 5 4 3 2
* <p>
* 计算步骤:
* 1.将前17位数分别乘以不同的系数。从第1位到第17位的系数分别为:7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2
* 2.将这17位数字和系数相乘的结果相加。
* 3.用加出来和除以11,看余数是多少
* 4.余数只可能有0 1 2 3 4 5 6 7 8 9 10这11个数字,分别对应的最后一位身份证的号码为:1 0 X 9 8 7 6 5 4 3
* <p>
*/
class IDCardUtil
{
//省份证号的长度
private $id_len;
/**
* <pre>
* 省、直辖市代码表:
* 11 : 北京 12 : 天津 13 : 河北 14 : 山西 15 : 内蒙古
* 21 : 辽宁 22 : 吉林 23 : 黑龙江 31 : 上海 32 : 江苏
* 33 : 浙江 34 : 安徽 35 : 福建 36 : 江西 37 : 山东
* 41 : 河南 42 : 湖北 43 : 湖南 44 : 广东 45 : 广西 46 : 海南
* 50 : 重庆 51 : 四川 52 : 贵州 53 : 云南 54 : 西藏
* 61 : 陕西 62 : 甘肃 63 : 青海 64 : 宁夏 65 : 新疆
* 71 : 台湾
* 81 : 香港 82 : 澳门
* 91 : 国外
* </pre>
*/
private static $CITY_CODE = [
"11",
"12",
"13",
"14",
"15",
"21",
"22",
"23",
"31",
"32",
"33",
"34",
"35",
"36",
"37",
"41",
"42",
"43",
"44",
"45",
"46",
"50",
"51",
"52",
"53",
"54",
"61",
"62",
"63",
"64",
"65",
"71",
"81",
"82",
"91"
];
/**
* 校验码
*/
private static $PARITYBIT = [
'1',
'0',
'X',
'9',
'8',
'7',
'6',
'5',
'4',
'3',
'2'
];
/**
* 加权因子
* Math.pow(2, i - 1) % 11
*/
private static $POWER = [
7,
9,
10,
5,
8,
4,
2,
1,
6,
3,
7,
9,
10,
5,
8,
4,
2
];
public function __construct($id)
{
$this->id_len = strlen($id);
/////
var_dump($this->isValid($id));
}
/**
* 身份证验证
*
* @param $id string 号码内容
* @return bool 是否有效
*/
public function isValid($id)
{
if (empty($id))
{
return false;
}
if (!in_array($this->id_len, [
15,
18
]))
{
return false;
}
//校验区位码
if (!$this->validCityCode(substr($id, 0, 2)))
{
return false;
}
//校验生日
if (!$this->validDate($id))
{
return false;
}
//校验位数,即最后一位是否匹配
if ($this->validParityBit($id) == substr($id, -1))
{
return $id . '有效..';
}
return false;
}
//效验区位码
private function validCityCode($id)
{
if (in_array($id, self::$CITY_CODE))
{
return true;
}
return false;
}
//校验生日
private function validDate($id)
{
$birth = strlen($id) == 15 ? '19' . substr($id, 6, 8) : substr($id, 6, 8);
//缺少生日日期
//php有内置函数checkdate — 验证一个格里高里日期 >php5.6
if (checkdate(substr($birth, 4, 2), substr($birth, 6, 2), substr($birth, 0, 4)))
{
return true;
}
return false;
}
//校验位数
private function validParityBit($id)
{
$id_array = str_split(strtoupper($id));
//return $id_array;
$power = 0;
for ($i = 0; $i < strlen($id); $i++)
{
//最后一位可以是X
if ($i == strlen($id) - 1 && $id_array[$i] == 'X')
{
break;
}
//非数字
if ($id_array[$i] < 0 || $id_array[$i] > 9)
{
return false;
}
//核心 加权求和
if ($i < strlen($id) - 1)
{
$power += ($id_array[$i] - 0) * self::$POWER[$i];
}
}
return self::$PARITYBIT[$power % 11];
}
}
///效验
new IDCardUtil('140223199407144215');<file_sep>/README.md
# IDCardUtil
php效验身份证号的合法
-require filename
- new IDCardUtil($param) $param身份证号码
|
73ee993db4a8472bcf04b184149b7cd02b629a50
|
[
"Markdown",
"PHP"
] | 2
|
PHP
|
SoySaucelm/IDCardUtil
|
4440c43bd7f85a7a3ea7b96fa1e4f1c1ca541fc4
|
2e9193eea26e2ab24cd36ce4289f6a7d68fa6db4
|
refs/heads/master
|
<repo_name>faeronsayn/auth-system<file_sep>/functions/setup-database.php
<?php
$db_name = $_POST['db_name'];
$db_user = $_POST['db_user'];
$db_pass = $_POST['db_pass'];
$db_host = $_POST['db_host'];
$db_charset = $_POST['db_charset'];
$config_file = '../as-config.php';
$handle = fopen($config_file, 'w') or die('Cannot open file: '.$config_file); //implicitly creates file
$data = <<<EOT
// Authentication System config file
// Database Settings here
// Database Name
define('DB_NAME', $db_name);
// Database User
define('DB_USER', $db_user);
// Database User password
define('DB_PASS', $db_pass);
// Database host
define('DB_HOST', $db_host);
// Database charset
define('DB_CHARSET', $db_charset);
EOT;
fwrite($handle, $data);
?>
<file_sep>/README.md
Authentication System
===========
Built using PHP, Javascript/jQuery and Bootstrap.
Features
- Uses the Bcrypt algorithm to encrypt passwords
- User's passwords are never stored in the database, only their hashes.
- Registers a user and logs them in all behind the scenes (No page reloads)
- Utilizes the mySQL database system with a single user table
<file_sep>/functions/login-user.php
<?php
include '../as-config.php';
global $db_con;
$password = $_POST['<PASSWORD>'];
$email = $_POST['email'];
$db_con = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
$entry_exist = $db_con->query('SELECT password FROM as_user WHERE email="'. $email .'"');
$row_entry = $entry_exist->fetch_assoc();
$password_hash = $row_entry['password'];
if ($password_hash) {
if (password_verify($password, $password_hash)) {
echo 'true';
// Start session and so on..
} else {
echo 'false';
}
} else {
echo 'false';
}
?><file_sep>/register.php
<?php
include 'header.php';
global $db_con;
$db_con = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
$table_exist = $db_con->query('SELECT 1 from as_user');
if ($table_exist) {
} else {
}
?>
<div class="panel panel-success" style="max-width: 500px; margin: 0 auto;">
<div class="panel-heading">Registration Form</div>
<div class="panel-body">
<form class="form-horizontal" role="form">
<div class="form-group">
<label for="input-name" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input maxlength="50" type="text" class="form-control" id="input-name" placeholder="Name">
</div>
</div>
<div class="form-group">
<label for="input-email" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="input-email" placeholder="Email">
</div>
</div>
<hr />
<div class="form-group">
<label for="input-pass" class="col-sm-2 control-label">Password</label>
<div class="col-sm-5">
<input type="<PASSWORD>" class="form-control" id="input-pass" placeholder="<PASSWORD>">
</div>
<div class="col-sm-5">
<input type="<PASSWORD>" class="form-control" id="input-pass-confirm" placeholder="Confirm password">
</div>
</div>
<hr />
<div class="form-group">
<label class="col-sm-2 control-label">Gender</label>
<div class="btn-group col-sm-10" data-toggle="buttons">
<label class="btn btn-default">
<input type="radio" name="gender" id="male" value="Male"> Male
</label>
<label class="btn btn-default">
<input type="radio" name="gender" id="female" value="Female"> Female
</label>
<label class="btn btn-default">
<input type="radio" name="gender" id="unspecified" value="Unspecified"> Unspecified
</label>
</div>
</div>
<div class="form-group" style="text-align: center;">
<button id="register" type="button" class="btn btn-primary btn-lg">Register</button><div id="waiting"></div>
</div>
</div>
</form>
</div>
</div>
<?php include 'footer.php'; ?>
<script type="text/javascript">
//$('input[name="gender"]').button()
$('#register').click(function() {
var gender = $('input:checked').val();
var password = $('#input-pass').val();
var password_confirm = $('#input-pass-confirm').val();
var name = $('#input-name').val();
var email = $('#input-email').val();
$('#waiting').addClass('loading');
if (!password) {
$('#input-pass').parent().removeClass('has-success');
$('#input-pass').parent().addClass('has-error');
} else {
$('#input-pass').parent().removeClass('has-error');
$('#input-pass').parent().addClass('has-success');
}
if (!password_confirm) {
$('#input-pass-confirm').parent().removeClass('has-success');
$('#input-pass-confirm').parent().addClass('has-error');
}
if (!gender) {
$('.btn-group').parent().removeClass('has-success');
$('.btn-group').parent().addClass('has-error');
} else {
$('.btn-group').parent().removeClass('has-error');
$('.btn-group').parent().addClass('has-success');
}
if (!name) {
$('#input-name').parent().removeClass('has-success');
$('#input-name').parent().addClass('has-error');
} else {
$('#input-name').parent().removeClass('has-error');
$('#input-name').parent().addClass('has-success');
}
if (!email) {
$('#input-email').parent().removeClass('has-success');
$('#input-email').parent().addClass('has-error');
} else {
$('#input-email').parent().removeClass('has-error');
$('#input-email').parent().addClass('has-success');
}
if (password != password_confirm) {
$('#input-pass-confirm').parent().addClass('has-error'); // If passwords don't match, then throw an error
jQuery('#notify-user').html('Passwords don\'t match :(');
$('#waiting').removeClass('loading');
} else if (gender && password && password_confirm && name && email) {
$('#input-pass-confirm').parent().removeClass('has-error');
$('#input-pass-confirm').parent().addClass('has-success');
jQuery.post("functions/register-user.php", {gender:gender, password:<PASSWORD>, name:name, email:email}, function(data) {
console.log(data);
jQuery('#notify-user').html(data);
});
} else {
$('#waiting').removeClass('loading');
$('#notify-user').html('Please fill in all the fields');
}
});
</script>
<?php include 'footer.php'; ?><file_sep>/functions/register-user.php
<?php
include '../as-config.php';
header('HTTP/1.1 200 OK');
$gender = $_POST['gender'];
$name = $_POST['name'];
$email = $_POST['email'];
$pass = $_POST['password'];
$pass_hash = password_hash($pass, PASSWORD_BCRYPT);
global $db_con;
$db_con = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
$entry_exist = $db_con->query('SELECT email FROM as_user WHERE email="'. $email .'"');
$row_entry = $entry_exist->fetch_assoc();
$email_check = $row_entry['email'];
if (!$email_check) {
$db_con->query('INSERT INTO as_user (username, password, email, gender, register_date, user_state) VALUES ( "'. $name .'", "'. $pass_hash .'", "'. $email .'", "'. $gender .'", '. time() .', "email_confirm")');
echo "User has been created, an email has been sent to " . $email . ". Please confirm.";
} else {
echo "Email already exists!";
}
?>
<file_sep>/header.php
<?php
include 'as-config.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<title>Authentication System made by <NAME></title>
</head>
<body style data-twttr-renderd="true">
<header class="navbar navbar-inverse navbar-fixed-top bs-docs-nav" role="banner">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<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="/auth_system/">Auth System</a>
</div>
<div class="collapse navbar-collapse" id="navbar-collapse-1">
<ul class="nav navbar-nav">
<li><a href="/">Maaz Ali</a></li>
<li><a href="https://github.com/faeronsayn/auth-system">github</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="login.php">Login</a></li>
<li><a href="register.php">Register</a></li>
</ul>
</div>
</div>
</header>
<div id="notify-user"></div>
<div class="container" style="padding-top: 70px;"><file_sep>/login.php
<?php
include 'header.php';
global $db_con;
$db_con = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
$table_exist = $db_con->query('SELECT 1 from as_user');
if ($table_exist) {
?>
<div class="panel panel-default" style="max-width: 500px; margin: 0 auto;">
<div class="panel-heading">Login Form</div>
<div class="panel-body">
<form class="form-horizontal" role="form">
<div class="form-group">
<label for="input-email" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="input-email" placeholder="Email">
</div>
</div>
<div class="form-group">
<label for="input-pass" class="col-sm-2 control-label">Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="input-pass" placeholder="<PASSWORD>">
</div>
</div>
<div class="form-group" style="text-align: center;">
<button id="login" type="button" class="btn btn-primary btn-lg">Login</button><div id="waiting"></div>
</div>
</form>
</div>
</div>
<div class="login-notify"><span class="glyphicon"></span></div>
<?php
} else {
}
?>
<script type="text/javascript">
$('#login').click(function() {
var password = $('#input-pass').val();
var email = $('#input-email').val();
$('#waiting').addClass('loading');
jQuery.post("functions/login-user.php", {password:<PASSWORD>, email:email}, function(data) {
$('#waiting').removeClass('loading'); // Remove the loading indicator
// console.log(data); // Log the data for debugging
if (data == 'true') {
$('#notify-user').html('Login successful');
$('#notify-user').removeClass('fail').addClass('success');
$('.panel.panel-default').css('display', 'none'); // Remove the login box since the user has logged in
$('.glyphicon').removeClass('glyphicon-thumbs-down').addClass('glyphicon-thumbs-up');
setTimeout(function() {
$('#notify-user').removeClass('success');
$('#notify-user').html('');
}, 2000)
} else {
$('#notify-user').html('Login failed, email or password is incorrect.');
$('#notify-user').removeClass('success').addClass('fail');
setTimeout(function() {
$('#notify-user').removeClass('fail');
}, 3000)
$('.glyphicon').removeClass('glyphicon-thumbs-up').addClass('glyphicon-thumbs-down');
}
});
});
</script>
<?php include 'footer.php'; ?>
|
8693fe9e384c9261a959762815a540b1cd706526
|
[
"Markdown",
"PHP"
] | 7
|
PHP
|
faeronsayn/auth-system
|
fad24b35edf1a56110cde248d49c8e059719bb86
|
6c80d9f76c5a2c5c6a406df76e641c3ccba95370
|
refs/heads/master
|
<file_sep>
# Load data
setwd('~/Documents/STAT241')
data=read.table('./hw2.data',col.names = c('x1','x2','y'))
X=as.matrix(data[,1:2])
Y=as.matrix(data[,3])
# solve(A,b) solve b = Ax
theta_star = solve(t(X)%*%X,t(X) %*% Y)
row.names(theta_star)=NULL
# Eigen vectors / values
eigen_values = eigen(t(X)%*%X)$values
eigen_vectors = eigen(t(X)%*%X)$vectors
lambda_max=max(eigen_values)
# Cost function with vector input theta
J = function (theta){
a= Y - X %*% theta
return( (t(a)%*%a) [1,1])
}
J_opt=J(theta_star)
J_opt
eigen_vectors
eigen_values
# J when arguments are sequences of numbers
J_seq = function(theta1_seq,theta2_seq){
theta_seq=matrix(c(theta1_seq,theta2_seq),nrow=2,byrow=T)
return(apply(theta_seq,2,J))
}
# Plot
plot_J=function(npoints=100,nlevels=20,xlim=c(theta_star[1]-1,theta_star[1]+1),
ylim=c(theta_star[2]-1,theta_star[2]+1),
title="",col="black",eigen=T){
x=seq(xlim[1],xlim[2],length.out = npoints)
y=seq(ylim[1],ylim[2],length.out = npoints)
z=outer(x,y,function(x,y) J_seq(x,y))
contour(x,y,z,main= title,levels= seq(J_opt,J_opt*20,length.out = nlevels),col=col)
if (eigen)
abline(-eigen_vectors[1,2]*theta_star[1]+theta_star[2],eigen_vectors[1,2],col="darkgray")
abline(-eigen_vectors[2,2]*theta_star[1]+theta_star[2],eigen_vectors[2,2],col="darkgray")
points(theta_star[1],theta_star[2],col="red",cex=2,pch=20)
}
plot_J(title="Cost function J")
## LMS
theta_t = function(t,rho,theta0,Y,X,init_res){
if (t==0)
return(list(theta=theta0,res=init_res))
else
i=sample(1:length(Y),1)
yn=Y[i]
xn=as.matrix(X[i,],nrow=2)
# Precedent values obtained by induction
old=theta_t(t-1,rho,theta0,Y,X,init_res)
old_theta=old$theta
old_res=old$res
# Update theta
new_theta=old_theta+rho*(yn - (t(old_theta) %*% xn)[1,1]) * xn
# Update res
new_res=old_res
new_res[,t+1]=new_theta
return(list(theta=new_theta,res=new_res))
}
lms=function(t,rho,theta0,Y,X){
init_res=matrix(nrow=2,ncol=t+1)
init_res[,1]=theta0
return(theta_t(t,rho,theta0,Y,X,init_res)$res)
}
lms_plot=function(t,rho,theta0,Y,X,it=1000){
plot_J(xlim=theta_star[1]+c(-.2,.2),ylim=theta_star[2]+c(-.2,.2),nlevels=80,col="darkgray",eigen=F)
l=lms(it,rho,theta0,Y,X)
lines(l[1,],l[2,],type="l",xlab="x",ylab="y")
points(theta_star[1],theta_star[2],col="red",pch=19)
points(l[1,length(l)/2],l[2,length(l)/2],col="green",pch=19)
legend( "bottomright",legend=c("Theta_LMS","Theta_star"),col=c("green","red"),pch=c(16,16) )
}
theta0=theta_star+.2
rho1=2/max(eigen_values)
rho2=1/(2*max(eigen_values))
rho3=1/(8*max(eigen_values))
set.seed(4)
it=200
par(mfrow=c(1,3),oma = c(3, 3, 7, 3))
lms_plot(t,rho1,theta0,Y,X,it,title="rho1")
lms_plot(t,rho2,theta0,Y,X,it,title="rho2")
lms_plot(t,rho3,theta0,Y,X,it,title="rho3")
title("LMS algorithm, 200 itérations",outer=T,lwd=3,cex=3)
set.seed(15)
it=1000
par(mfrow=c(1,3),oma = c(3, 3, 7, 3))
lms_plot(t,rho1,theta0,Y,X,it,title="rho1")
lms_plot(t,rho2,theta0,Y,X,it,title="rho2")
lms_plot(t,rho3,theta0,Y,X,it,title="rho3")
title("LMS algorithm, 1000 itérations",outer=T,lwd=3,cex=3)
<file_sep>## Graph
# List of neighbors
Neighbors=vector("list",9)
Neighbors[[1]]=c(6)
Neighbors[[2]]=c(6)
Neighbors[[3]]=c(7)
Neighbors[[4]]=c(7)
Neighbors[[5]]=c(9)
Neighbors[[6]]=c(1,2,8)
Neighbors[[7]]=c(3,4,8)
Neighbors[[8]]=c(6,7,9)
Neighbors[[9]]=c(5,8)
Neighbors
# Evidence nodes
evidence=c(1,2,3,4,5)
f=9 #arbitrary root
### Definition of Potentials
## Dual cliques
def_M = function (m){
# M1
M1=matrix(c(m[1],m[4],m[2],m[3],
m[4],m[1],m[3],m[2],
m[2],m[3],m[1],m[4],
m[3],m[2],m[4],m[1]),4)
# M2
M2=matrix(c(m[1],3*m[4],4*m[2],3*m[3],
3*m[4],m[1],3*m[3],4*m[2],
4*m[2],3*m[3],m[1],3*m[4],
3*m[3],4*m[2],3*m[4],m[1]),4)
# Potentials
M = array(dim=c(9,9,4,4))
M[1,6,,]=M1
M[2,6,,]=M1
M[3,7,,]=M1
M[4,7,,]=M1
M[6,8,,]=M1
M[7,8,,]=M1
M[8,9,,]=M1
M[5,9,,]=M2
M[6,1,,]=M1
M[6,2,,]=M1
M[7,3,,]=M1
M[7,4,,]=M1
M[8,6,,]=M1
M[8,7,,]=M1
M[9,8,,]=M1
M[9,5,,]=M2
return(M)
}
# Single Potentials
psi=matrix(rep(1,9*4),ncol=9)
psi[,9]=c(8,9,9,8)
sum_product = function(Neighbors,psiE,evidence,x,M,f){
psiE=psi
psiE[,evidence]=x*psi[,evidence]
# Messages
mess=array(data=0,dim=c(9,9,4))
#Marginals
marginals=vector("list",9)
# Send message
send_message=function(j,i){
# Compute product of mkj
product_mkj=c(1,1,1,1)
for (k in Neighbors[[j]]){
if (k != i){
product_mkj=product_mkj*mess[k,j,]
}
}
# Compute mji
mji=c(0,0,0,0)
possible_xj=diag(4) # sum over all values
for (j0 in 1:4){
xj=possible_xj[,j0]
# Message to be sent
#mji=mji+ ( M[j,i,,] %*% (psiE[,j]) )* product_mkj*xj
psiE_xj=psiE[j0,j] # real
mkj_xj=product_mkj[j0] # real
psi_xi_xj=M[j,i,,j0] # vector
mji=mji+ psiE_xj*psi_xi_xj*mkj_xj
}
mess[j,i,] <<- mji
}
# Collect
collect = function (i,j){
for (k in Neighbors[[j]]){
if ( k !=i ){
collect(j,k)
}
}
send_message(j,i)
}
# Distribute
distribute = function (i,j){
send_message(i,j)
for (k in Neighbors[[j]]){
if ( k !=i ){
distribute(j,k)
}
}
}
# Marginal
compute_marginal = function(i){
product_mji=1
for (j in Neighbors[[i]]){
product_mji=product_mji*mess[j,i,]
}
marginals[[i]] <<- psiE[,i]*product_mji
}
# Algorithm
for (e in Neighbors[[f]]){
collect(f,e)
}
for (e in Neighbors[[f]]){
distribute(f,e)
}
for (i in 1:9){
compute_marginal(i)
}
return(lapply(marginals,function (x) x/sum(x)))
}
######
#par(mfrow=c(1,2))
############
## Exemple 1
############
m=c(8,3,2,1)
M=def_M(m)
x=matrix(c(0,0,0,1,0,1,0,0,1,0,0,0,0,0,1,0,0,0,1,0),ncol=5)
s1=sum_product(Neighbors,psiE,evidence,x,M,f)
barplot(s1[[9]],names.arg =c("A","C","T","G"),ylab="probability",ylim = c(0,.5),
main= "First example")
###########
# Exemple 2
###########
m=c(7,4,3,2)
M=def_M(m)
x=matrix(c(0,1,0,0,1,0,0,0,0,0,0,1,0,0,1,0,0,1,0,0),ncol=5)
s2=sum_product(Neighbors,psiE,evidence,x,M,f)
barplot(s2[[9]],names.arg =c("A","C","T","G"),ylab="probability",ylim = c(0,0.5),
main= "Second example")
s1[[9]]
s2[[9]]
##
|
71776efbf377d98098fd03b735e0969b9c7db73e
|
[
"R"
] | 2
|
R
|
doutib/SumProduct_algorithm
|
f0301878768d39a9f76ac993df01aa19a77b4c1c
|
fdc2ecc7b16af59034de1174e2ee6f4103c95354
|
refs/heads/master
|
<repo_name>scottsch/sample_app<file_sep>/spec/spec_helper.rb
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
# == Mock Framework
#
# If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
#
# config.mock_with :mocha
# config.mock_with :flexmock
# config.mock_with :rr
config.mock_with :rspec
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
def create_user!(override = {})
user_data = { :name => "<NAME>",
:email => "<EMAIL>",
:password => "<PASSWORD>",
:password_confirmation => "<PASSWORD>" }
User.create!(user_data.merge(override))
# I use create! instead of the Factory in the Rails tutorial.
# I don't see how FactoryGirl is any better than this.
end
def create_micropost!(user, override = {})
micropost_data = { :content => "Foo bar" }
micropost = user.microposts.create!(micropost_data.merge(override))
if not override[:created_at].nil?
micropost.created_at = override[:created_at]
micropost.save
end
return micropost
end
def test_sign_in(user)
controller.sign_in(user)
end
end
|
5743383297ae8e5b950970b1b6b909f6ff011143
|
[
"Ruby"
] | 1
|
Ruby
|
scottsch/sample_app
|
df0e078161168811f75e171e3426f85ac2b26fff
|
522b3f2ff39bb7cc720bc3a68c7979405727ec5c
|
refs/heads/master
|
<repo_name>ravinderuppala/SpringRestPOC<file_sep>/src/main/java/com/rest/poc/config/RewardsConfig.java
package com.rest.poc.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.ServerAddress;
@Configuration
@ComponentScan(basePackages={"properties"})
@PropertySource(value = "classpath:com/rest/properties/rewards.properties")
public class RewardsConfig {
static MongoClient client;
static MongoDbFactory factory;
static MongoTemplate template;
@Autowired
private Environment env;
MongoDbFactory mongoDbFactory() throws Exception {
String host = env.getProperty("local.mongodb.host");
String port = env.getProperty("local.mongodb.port");
String database = env.getProperty("local.mongodb.db");
MongoClientOptions options = new MongoClientOptions.Builder().connectionsPerHost(10).build();
MongoClient client = new MongoClient(new ServerAddress(host,Integer.parseInt(port)), options);
factory = new SimpleMongoDbFactory(client, database);
return factory;
}
@Bean
MongoTemplate mongoTemplate() throws Exception {
if(template == null){
template = new MongoTemplate(mongoDbFactory());
}
return template;
}
}
<file_sep>/src/main/resources/com/rest/properties/rewards.properties
local.mongodb.host=MUSAVA207023
local.mongodb.db=Rewards
local.mongodb.port=27017<file_sep>/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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.restapi.poc</groupId>
<artifactId>SpringRestPOC</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>SpringRestPOC Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<spring.version>4.1.7.RELEASE</spring.version>
<javax.version>1</javax.version>
<spring.mongo.version>1.2.0.RELEASE</spring.mongo.version>
<mongo.java.version>3.0.2</mongo.java.version>
<junit.version>3.8.1</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- javax inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>${javax.version}</version>
</dependency>
<!-- mongodb driver version -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>${spring.mongo.version}</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>${mongo.java.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
</dependencies>
<build>
<finalName>SpringRestPOC</finalName>
</build>
</project>
|
77ffea011f381dea5261da2916a09a7314815b37
|
[
"Java",
"Maven POM",
"INI"
] | 3
|
Java
|
ravinderuppala/SpringRestPOC
|
0cdd94cf5cd60a0fd6cf2a4e544e230aed0382bb
|
8b397f8fcfabf08c802619a722b1b708ed4e7d13
|
refs/heads/master
|
<repo_name>craizile/INB313<file_sep>/custSupp.php
<?php require 'include/custSuppPermission.inc' ?>
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Rent a Car Park</title>
</head>
<body>
<h1>Welcome Customer</h1>
Customer Supply Page.
<a href="logout.php">Log out</a>
</body>
</html>
<file_sep>/FINAL_Purchase.php
<!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" />
<link type="text/css" rel="stylesheet" href="header.css" media="screen" />
<link type="text/css" rel="stylesheet" href="style.css" media="screen" />
<script type="text/javascript" src="script.js"></script>
<title> Purchase </title>
</head>
<body>
<?php include 'header.html' ; ?>
<form action="bookingform.php"
<?php
$price = $_POST['submit'];
$purchaseID = $_POST['ID'];
echo "Items in Cart</br>
CarparkID: $purchaseID </br>
Amount Owed: $$price</br>
<button name='price' value='$price'>CHECK OUT</button>";
?>
<?php include 'footer.html' ; ?>
</body>
</html><file_sep>/include/validateForm.inc
<?php
$letter = '/^[a-zA-z]+$/';
$alphanumeric = '/^[0-9a-zA-Z]+$/';
$number = '/^[0-9]+$/';
validateField($errors, $_POST, 'firstName', $letter, array('First Name', 'letter'));
validateField($errors, $_POST, 'lastName', $letter, array('Last Name', 'letter'));
validateDate($errors, $_POST, array('day', 'month', 'year'), array('Day (1-31)', 'Month (1-12)', 'Year (1980 - 2001)'),
$number);
validateEmail($errors, $_POST, 'email');
confirmField($errors, $_POST, 'confirmEmail', 'email');
validateField($errors, $_POST, 'password', $alphanumeric, array('Password (1-8 alphanumeric characters only)',
'alphanumeric'));
confirmField($errors, $_POST, 'confirmPassword', '<PASSWORD>');
validateField($errors, $_POST, 'phoneNumber', $number, array('Phone number', 'number'));
dropboxSelected($errors, $_POST, 'states');
validateField($errors, $_POST, 'streetNum', $number, array('Street number', 'number'));
validateField($errors, $_POST, 'streetName', $alphanumeric, array('Street name', 'alphanumeric'));
validateField($errors, $_POST, 'suburb', $letter, array('Suburb', 'letter'));
validateField($errors, $_POST, 'postCode', $number, array('Post code', 'numbers'));
isItSelected($errors, $_POST, 'term', 'You must select the checkbox if you agree and want to register');
/* Checks if the text field is empty or has invalid characters.
* If invalid appropriate error message is displayed */
function validateField(&$errors, $fieldList, $fieldName, $validInput, $errorMessage)
{
if (!isset($fieldList[$fieldName]) || $fieldList[$fieldName] == '')
{
$errors[$fieldName] = "$errorMessage[0] required";
}
else if (!preg_match($validInput, $fieldList[$fieldName]))
{
$errors[$fieldName] = "Invalid please supply $errorMessage[1] characters only";
}
}
/* Checks if the text is empty or has invalid email address format.
* If invalid appropriate error message is displayed */
function validateEmail(&$errors, $fieldList, $fieldName)
{
if (!isset($fieldList[$fieldName]) || $fieldList[$fieldName] == '')
{
$errors[$fieldName] = 'Email address required';
}
else if (!filter_var($fieldList[$fieldName], FILTER_VALIDATE_EMAIL))
{
$errors[$fieldName] = 'Invalid email, email must be in this format <EMAIL>';
}
}
/* Checks if the text is empty or does not match the relevant text field
* If invalid appropriate error message is displayed */
function confirmField(&$errors, $fieldList, $fieldName, $textName)
{
if (!isset($fieldList[$fieldName]) || $fieldList[$fieldName] == '')
{
$errors[$fieldName] = "Confirm $textName required";
}
else if ($fieldList[$fieldName] != $fieldList[$textName])
{
$errors[$fieldName] = "Confirm $textName does not match with above $textName";
}
}
/* Checks if the text field is empty or has invalid numbers.
* If invalid appropriate error message is displayed */
function validateDate(&$errors, $fieldList, $fieldName, $errorMessage, $validInput)
{
$dateRange = array(1, 31, 1, 12, 1980, 2001);
$indexMin = 0;
$indexMax = 1;
// validate day, month and year text field
for ($i = 0; $i < 3; $i++)
{
if (!isset($fieldList[$fieldName[$i]]) || $fieldList[$fieldName[$i]] == '')
{
$errors[$fieldName[$i]] = "$errorMessage[$i] required";
}
// check if numerical values of day, month and year have appropriate values
else if ($fieldList[$fieldName[$i]] < $dateRange[$indexMin] || $fieldList[$fieldName[$i]] > $dateRange[$indexMax]
&& !preg_match($validInput, $fieldList[$fieldName[$i]]))
{
$errors[$fieldName[$i]] = "Invalid $fieldName[$i] must have a numerical value between $dateRange[$indexMin] and
$dateRange[$indexMax]";
}
$indexMin = $indexMin + 2;
$indexMax = $indexMax + 2;
}
}
/* Checks if a value is selected from the dropbox */
function dropboxSelected(&$errors, $fieldList, $fieldName)
{
if (!isset($fieldList[$fieldName]) || $fieldList[$fieldName] == '')
{
$errors[$fieldName] = "You must select a state from the dropbox";
}
}
/* Checks if the checkbox is selected */
function isItSelected(&$errors, $fieldList, $fieldName, $errorMessage)
{
if (!isset($fieldList[$fieldName]))
{
$errors[$fieldName] = $errorMessage;
}
}
?><file_sep>/index.php
<!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" />
<link type="text/css" rel="stylesheet" href="header.css" media="screen" />
<link type="text/css" rel="stylesheet" href="style.css" media="screen" />
<script type="text/javascript" src="script.js"></script>
<title> Team Zen </title>
</head>
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Content ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<body>
<?php include 'header.html' ; ?>
<div class="content">
<div class="bodyContainer">
<!-- Rent a private parking -->
<h3>Rent a private parking spot</h3>
<div class="home-benefits">
<div class="introBlock">
<h4 class="pig icon">Save money</h4>
<p>
Renting a private garage, driveway or car park space can save you up to 70% on your parking costs.
</p>
</div>
<div class="introBlock b2">
<h4 class="people icon">Community</h4>
<p>
Join us to our expanding community. We'd love you to be part of it.
</p>
</div>
<div class="introBlock b3">
<h4 class="lock icon">Safe & secure</h4>
<p>
Our booking system is safe and secure, you can have peace of mind when booking.
</p>
</div>
<div class="introBlock b4">
<h4 class="clock icon">Quick & easy</h4>
<p>
You can search, book and pay for a parking space in under 5 minutes.
</p>
</div>
</div>
<img src="images/hr.png" class="hr"/>
<div class="list">
<img src="images/logo.png" alt="logo" class="logo"/>
<div class="listBox">
<h3>Rent out your space</h3>
<h4> <a href="#">Sign Up Now to place a listing </a></h4>
<p>
Convert extra or unused space in your home or business into a regular income
</p>
</div>
</div>
</div>
</div>
<?php include 'footer.html' ; ?>
</body>
</html><file_sep>/Database Info/carparks.sql
-- phpMyAdmin SQL Dump
-- version 4.0.4.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Oct 22, 2013 at 05:23 AM
-- Server version: 5.6.11
-- PHP Version: 5.5.3
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 */;
--
-- Database: `rentcarpark`
--
-- --------------------------------------------------------
--
-- Table structure for table `carparks`
--
CREATE TABLE IF NOT EXISTS `carparks` (
`CPID` int(11) NOT NULL AUTO_INCREMENT,
`AdName` varchar(80) NOT NULL,
`Username` varchar(30) NOT NULL,
`AdDescription` varchar(300) NOT NULL,
`Price` int(11) NOT NULL,
`Picture` mediumblob NOT NULL,
`Location` varchar(200) NOT NULL,
PRIMARY KEY (`CPID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
--
-- Dumping data for table `carparks`
--
INSERT INTO `carparks` (`CPID`, `AdName`, `Username`, `AdDescription`, `Price`, `Picture`, `Location`) VALUES
(1, 'Test', '', 'Test', 1, '', '');
/*!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>/successbook.php
<!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" />
<link type="text/css" rel="stylesheet" href="header.css" media="screen" />
<link type="text/css" rel="stylesheet" href="style.css" media="screen" />
<script type="text/javascript" src="script.js"></script>
<title> Successfully Booked </title>
</head>
<body>
<?php include 'header.html' ; ?>
<div class="content">
<div class="bodyContainer">
<h3> Successfully Booked !! </h3>
<p> Your form has been succesfully submitted and booked. Please wait for the owner to confirm the payment and they will contact you immidiately. If error or fraud occurs, contact us as soon as possible! Thank you for using our service and enjoy. <p> <br> <br>
</div>
</div>
<?php include 'footer.html' ; ?>
</body>
</html><file_sep>/customersupply.sql
-- phpMyAdmin SQL Dump
-- version 4.0.4.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Oct 25, 2013 at 03:06 PM
-- Server version: 5.5.31
-- PHP Version: 5.4.19
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 */;
--
-- Database: `rentcarpark`
--
-- --------------------------------------------------------
--
-- Table structure for table `customersupply`
--
CREATE TABLE IF NOT EXISTS `customersupply` (
`CSID` int(11) NOT NULL AUTO_INCREMENT,
`Firstname` varchar(30) NOT NULL,
`Surname` varchar(30) NOT NULL,
`Emailaddress` varchar(60) NOT NULL,
`Password` varchar(30) NOT NULL,
`Phonenumber` int(11) NOT NULL,
`StateorTerritory` varchar(10) NOT NULL,
`StreetNum` int(11) NOT NULL,
`StreetName` varchar(30) NOT NULL,
`Suburb` varchar(30) NOT NULL,
`Postcode` int(11) NOT NULL,
PRIMARY KEY (`CSID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
--
-- Dumping data for table `customersupply`
--
INSERT INTO `customersupply` (`CSID`, `Firstname`, `Surname`, `Emailaddress`, `Password`, `Phonenumber`, `StateorTerritory`, `StreetNum`, `StreetName`, `Suburb`, `Postcode`) VALUES
(1, 'Test', 'Test', '<EMAIL>', 'Test', 11111111, 'QLD', 1, 'Test', 'Test', 1111),
(2, 'Test', 'Test', '<EMAIL>', 'Test', 1111111111, 'QLD', 1, 'Test', 'Test', 1111),
(3, 'Yancie', 'Ng', '<EMAIL>', 'qwertyu', 42545828, 'QLD', 70, 'Mary', 'Brisbane', 4109),
(4, 'Jason', 'USANG', '<EMAIL>', 'qwertyu', 41552999, 'QLD', 70, 'Mary', 'Brisbane', 4000);
/*!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>/list.php
<?php
echo "<h1>Yes! local host working!</h1>";
echo "<h2>Here is the directory of INB313: </h2>";
$dir = 'file://localhost/Applications/XAMPP/xamppfiles/htdocs/INB313/';
$files1 = scandir($dir);
$n = 0;
for ($i=0; $i < sizeof($files1); $i++) {
if ($i>3) {
print("<a href='http://localhost/INB313/{$files1[$i]}'>{$files1[$i]}</a><br>");
}
}
?><file_sep>/FINAL_AddCarpark.php
<!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" />
<link type="text/css" rel="stylesheet" href="header.css" media="screen" />
<link type="text/css" rel="stylesheet" href="style.css" media="screen" />
<script type="text/javascript" src="script.js"></script>
<title> Add a car park </title>
</head>
<body>
<?php include 'header.html' ; ?>
<div class="bodyContainer">
<div class="modal">
<div class="modal-header">
Add <span> a car park</span>
</div>
<form action="FINAL_CarparkData.php" method="post" enctype="multipart/form-data">
<div class="modal-body">
<div class="control-group required ">
<label for="ad_name">Title:</label>
<div class="controls">
<input type="text" name="ad_name"/></br>
</div>
</div>
<div class="control-group required ">
<label for="ad_description">Description:</label>
<div class="controls">
<input type="textarea" rows="5" name="ad_description" /></br>
</div>
</div>
<div class="control-group required ">
<label for="price">Price:</label>
<div class="controls">
<input type="text" name="price"/></br>
</div>
</div>
<div class="control-group required ">
<label for="location">Car Park Suburb:</label>
<div class="controls">
<input type="text" name="location"/></br>
</div>
</div>
<div class="control-group required ">
Select Image: <input type="file" name="image" ></br>
</div>
</div>
<div class="modal-footer">
<input type="submit" name="post" value ="POST" >
</div>
</form>
</div>
</div
<?php include 'footer.html' ; ?>
</body>
</html>
<file_sep>/include/registrationForm.inc
<div class="modal">
<div class="modal-header">
Register <span>for an account</span>
</div>
<!-- Creates registration form with relevant questions -->
<form action="register.php" method="post" name="signup" accept-charset="utf-8" class="form">
<div class="modal-body">
<?php
include 'include/registrationQuestions.inc';
$states = array('', 'ACT', 'NSW', 'NT', 'QLD', 'SA', 'TAS', 'VIC',
'WA');
inputField($errors, 'firstName', 'First Name', 15);
inputField($errors, 'lastName', 'Last Name', 15);
inputDate($errors);
inputField($errors, 'email', 'Email Address', 25);
inputField($errors, 'confirmEmail', 'Confirm Email Address', 25);
inputPassword($errors, 'password', '<PASSWORD>');
inputPassword($errors, 'confirmPassword', '<PASSWORD> Password');
inputField($errors, 'phoneNumber', 'Phone number <br>(10 digits)', 10);
dropDownList($errors, 'states', 'State or Territory', $states, 9);
inputField($errors, 'streetNum', 'Street Number', 3);
inputField($errors, 'streetName', 'Street Name', 18);
inputField($errors, 'suburb', 'Suburb', 18);
inputField($errors, 'postCode', 'Post Code (4 digits)', 4);
checkBox($errors, 'term');
submitCancelBtns("index.php");
?>
</form>
</div>
<file_sep>/register.php
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<Head>
<link type="text/css" rel="stylesheet" href="header.css" media="screen" />
<link type="text/css" rel="stylesheet" href="style.css" media="screen" />
<script type="text/javascript" src="script.js"></script>
<Title>Register</Title>
</head>
<body>
<?php include 'header.html' ; ?>
<!-- Present the user with a registration form that will validate user's input using
server side validation -->
<div class="bodyContainer">
<?php
$errors = array();
// checks if the form has any inputs
if ($_POST)
{
// validate all fields
include 'include/validateForm.inc';
// if no errors, process data
if (count($errors) == 0)
{
require 'include/registrationSuccess.inc';
}
// display the same form with previous user input
else
{
require 'include/registrationForm.inc';
}
}
// display form with blank fields
else
{
require 'include/registrationForm.inc';
}
?>
</div>
<?php include 'footer.html' ; ?>
</body>
</html><file_sep>/login.php
<!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" />
<link type="text/css" rel="stylesheet" href="header.css" media="screen" />
<link type="text/css" rel="stylesheet" href="style.css" media="screen" />
<script type="text/javascript" src="script.js"></script>
<title> Log in </title>
</head>
<body onload="document.signup.username.focus();">
<?php include 'header.html' ; ?>
<div class="content">
<div class="bodyContainer">
<h3>Login Page</h3>
<?php
if (isset($_POST['login']))
{
include 'include/registrationQuestions.inc';
if (checkPassword($_POST['username'], $_POST['password']))
{
$email = $_POST['username'];
$con=mysqli_connect("localhost","root","","rentcarpark");
$result = mysqli_query($con,"SELECT * FROM customersupply WHERE Emailaddress='$email'");
$record = mysqli_fetch_assoc($result);
session_start();
$_SESSION['isCustSupp'] = true;
$_SESSION['username'] = $record['Firstname'];
header('Location: http://localhost/INB313/index.php');
exit();
}
else
{
echo "<h4>Login failed - invide email address or password </h4>";
}
}
?>
<form action="login.php" method="post" name="signup">
Email Address: <input name="username" type="text"/>
<br/>
Password: <input name="<PASSWORD>" type="<PASSWORD>"/>
<br/> <br/>
<input name="login" type="submit" value="Login"/>
<a href="#">Forgot Password</a>
<br/>
</form>
</div>
</div>
<?php include 'footer.html' ; ?>
</body>
</html> <file_sep>/include/registrationQuestions.inc
<?php
/* If error is in $errors array return error message else
* return nothing */
function errorMessage($errors, $name)
{
if (isset($errors[$name]))
{
return $error = $errors[$name];
}
else
{
return $error = '';
}
}
/* Display red colored error message next to associated question if user supplies an invalid answer */
function errorLabel($errors, $name)
{
$error = errorMessage($errors, $name);
echo " <span id=\"{$name}Error\" class=\"error\">$error</span>";
}
/* Display text label associated with text field */
function label($name, $label)
{
echo "<div class=\"control-group required\"><label for=\"id_first_name\"
class=\"control-label\">$label</label><div class=\"controls\">";
}
/* Stores user input to be used if registration is unsuccessful and the
* registration form is presented back to the user */
function postedValue($name)
{
if (isset($_POST[$name]))
{
return $prefill = htmlspecialchars($_POST[$name]);
}
else
{
return $prefill = '';
}
}
/* Create text field for users to provide text input.
* Displays error message alongside text field if incorrect input is provided and
* remembers previous input. */
function inputField($errors, $name, $label, $maxlength)
{
// displays relevant text to text field
label($name, $label);
// if user provided input, remember input
$value = postedValue($name);
// display text field
echo "<input value=\"\" type=\"text\" id=\"$name\" name=\"$name\" value=\"$value\"
maxlength=\"$maxlength\" />";
// display relevant error text to relevant text field
errorLabel($errors, $name);
echo "</div></div>" ;
}
/* Create text field for users to provide password input, each character is displayed
* as circle symbols. Displays error message alongside text field if incorrect input is provided and
* remembers previous input. */
function inputPassword($errors, $name, $label)
{
// displays relevant text to text field
label($name, $label);
// if user provided input, remember input
$value = postedValue($name);
// display text field
echo "<input type=\"password\" size=\"20\" id=\"$name\" name=\"$name\"
value=\"$value\" maxlength=\"8\"/>";
// display relevant error text to relevant text field
errorLabel($errors, $name);
echo "</div></div>" ;
}
/* Creates three text fields for users to input the day, month and year. Displays error
* message alongside text field if incorrect input is provided and remembers previous input. */
function inputDate($errors)
{
$date = array('day', 'month', 'year');
$maxLength = array(2, 2, 4);
$size = array(10, 10, 20);
$class = array('small', 'small', 'medium');
// if user provided input, remember input
$valueList = array($valueDay = postedValue($date[0]), $valueMonth = postedValue($date[1]),
$valueYear = postedValue($date[2]));
echo "<div class=\"control-group required\"><label for=\"id_first_name\"
class=\"control-label\">Date of birth (dd/mm/yyyy)</label><div class=\"controls\">";
// display three text fields for use for the user's input of the date
for ($i = 0; $i < 3; $i++)
{
echo "<input type=\"text\" class=\"$class[$i]\" size=\"$size[$i]\" id=\"$date[$i]\"
name=\"$date[$i]\" value=\"$valueList[$i]\" maxLength=\"$maxLength[$i]\"/>";
// display relevant error text to relevant text field
errorLabel($errors, $date[$i]);
}
echo "</div></div>" ;
}
/* Allow users to sumbit the registration form or navigate to the index webpage */
function submitCancelBtns($pageFile)
{
echo "<div class=\"modal-footer\">
<button type=\"submit\" class=\"btn btn-large btn-success\">Register</button>
<button class=\"btn btn-large btn-success\">
<a href=\"$pageFile\">Cancel</a></button></div>";
}
/* Creates a drop down list. Displays error message alongside text field and remembers previous input. */
function dropDownList($errors, $name, $label, $list, $size)
{
label($name, $label);
echo "<select name=\"$name\" id=\"$name\">";
for ($i = 0; $i < $size; $i++)
{
// if user has selected an input remember input
// if form fails to validate
if ($_REQUEST[$name] == $list[$i])
{
echo "<option value=\"$list[$i]\" selected=\"selected\" >$list[$i]</option>";
}
// create dropdown box
else
{
echo "<option value=\"$list[$i]\" >$list[$i]</option>";
}
}
echo "</select>";
errorLabel($errors, $name);
echo "</div></div>" ;
}
/* Creates a single check box */
function checkBox($errors, $name)
{
echo "<div class=\"control-group required\">
<label class=\"control-label\"></label>
<div class=\"controls\">
<label for=\"id_tcs\" class=\"checkbox\">";
// remembers if the user has selected the checkbox
// if form fails to validate
if (isset($_POST["term"]))
{
echo "<input type=\"checkbox\" name=\"$name\" value=\"Yes\" checked=\"checked\"/>";
}
// create unchecked checkbox
//else
{
echo "<input type=\"checkbox\" name=\"$name\" value=\"Yes\" />";
}
echo "I have read and agree to the <a href=\"#\">terms and conditions</a></label>";
errorLabel($errors, $name);
echo "</div></div></div>" ;
}
/* check the database if the username and password combination exist in
* the database */
function checkPassword($username, $password)
{
$pdo = new PDO('mysql:host=localhost; dbname=RentCarPark', 'root', '');
$stmt = $pdo->prepare('SELECT * FROM customerSupply WHERE Emailaddress = :emailAddress and
password = :<PASSWORD>');
$stmt->bindvalue(':emailAddress', $username);
$stmt->bindvalue(':password', $password);
$stmt->execute();
return $stmt->rowCount() > 0;
}
?><file_sep>/contactus.php
<html xmlns="http://www.w3.org/1999/xhtml">
<Head>
<link type="text/css" rel="stylesheet" href="header.css" media="screen" />
<link type="text/css" rel="stylesheet" href="style.css" media="screen" />
<Title>About Us/Contact</Title>
</head>
<body>
<?php include 'header.html' ; ?>
<div class="content">
<div class="bodyContainer">
<h3>
About Us/Contact
</h3>
<div class="aboutContent">
<p>
Team Zen is an online for parking spaces. We connect homes and
businesses with parking capacity to individuals seeking either
long term or short term parking.<br/><br/>
This website was first inspired by a friend who had an idea of making
the life of the community more convenient. At the same time it also
make profit. Those who are away for the week may put up their parking
space in the website for rent. It also benefit those who want to park
around that area to avoid any law violation.<br/><br/>
This service is made to make both parties convinient as they do not have
to meet in order to make arrangement and payment.
</p>
</div>
<img src = "http://storage.canoe.ca/v1/dynamic_resize/sws_path/suns-prod-images/1297454719343_ORIGINAL.jpg?quality=80&size=650x&stmp=1376520699777"
border=0 width=300px height=300px>
<img src= "http://i.dailymail.co.uk/i/pix/2012/10/04/article-2213081-0323DC0F0000044D-999_634x327.jpg"
border=0 width=300px height=300px>
<img src="http://www.blogcdn.com/cars.aol.co.uk/media/2013/06/screen-shot-2013-06-19-at-12.08.13.png"
border=0 width=300px height=300px>
<br><br>
<div class="contContent">
<p>
For more information you can contact us using the following email:<br/><br/>
<EMAIL> <br/><br/>
General inquiries and support number: (07) 1234 5678
</p>
</div>
</div>
</div>
<?php include 'footer.html' ; ?>
</body>
</html><file_sep>/CarparkResult.php
<html>
<table>
<form>
<?php
session_start();
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="<PASSWORD>"; // Mysql password
$db_name="test"; // Database name
$tbl_name="carparks"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Info sent from form
$keywords=$_POST['keywords'];
// To protect MySQL injection
$keywords = stripslashes($keywords);
$keywords = mysql_real_escape_string($keywords);
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
//for loop for each row
echo "$count results returned </br></br>";
while($data = mysql_fetch_row($result)){
$purchaseID = $data[0];
echo("<tr><td><header><b>$data[1]</b></header>$data[2]$data[4]</br>Price: $$data[3]</br>
</form>
<button type='submit' value=' .$purchaseID. ' name='purchase'>Purchase</button></form>
</br></br></td></tr>");
}
?>
</form>
</table>
</html><file_sep>/TestSQL.php
<?php
$Test = "Test";
// connect to database
$pdo = new PDO('mysql:host=localhost; dbname=RentCarPark', 'root', '');
// sql insert statement
$stmt = $pdo->prepare('INSERT INTO Test (Name) VALUES (:Firstname)');
// Inputed data from user is recorded into the database
$stmt->bindValue(':Firstname', 'Test', PDO::PARAM_STR);
$stmt->execute();
?><file_sep>/CarparkData.php
<?php
session_start();
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="RentCarPark"; // Database name
$tbl_name="CarParks"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Info sent from form
$ad_name=$_POST['ad_name'];
$ad_description=$_POST['ad_description'];
$price=$_POST['price'];
$file=$_FILES['image']['tmp_name'];
// To protect MySQL injection
$ad_name = stripslashes($ad_name);
$ad_description = stripslashes($ad_description);
$price = stripslashes($price);
$price = mysql_real_escape_string($price);
$ad_description = mysql_real_escape_string($ad_description);
$price = mysql_real_escape_string($price);
if(!isset($file))
echo "please select an image";
else
{
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
}
mysql_query("INSERT INTO carparks (AdName, AdDescription, Price) VALUES ('$ad_name','$ad_description','$price')");
echo "poo";
?><file_sep>/header.html
<div class="header">
<div class="container">
<h1>Team Zen</h1>
<?php
session_start();
if (!isset($_SESSION['isCustSupp']))
{
echo "<h2><a href=\"login.php\">Log in</a> / <a href=\"register.php\">Register</a></h2>";
}
else if(isset($_SESSION['isCustSupp']))
{
echo "<h2>Hello " . $_SESSION['username'] . " / <a href=\"logout.php\">Log out</a></h2>";
}
?>
<h2><a href="login.php">Log in</a> / <a href="register.php">Register</a></h2>
</div>
</div>
<div class="menuContainer">
<div class='cssmenu'>
<ul>
<li class='active'><a href='index.php'><span>Home</span></a></li>
<li><a href='#'><span>Rent Car Park</span></a></li>
<?php
if (!isset($_SESSION['isCustSupp']))
{
echo "<li class=\"hidden\"><a href=\"FINAL_AddCarpark.php\"><span>Place a listing</span></a></li>";
}
else if(isset($_SESSION['isCustSupp']))
{
echo "<li><a href=\"FINAL_AddCarpark.php\"><span>Place a listing</span></a></li>";
}
?>
<li><a href='howitworks.php'><span>How it works</span></a></li>
<li class='last'><a href='contactus.php'><span>About us / Contact</span></a></li>
</ul>
</div>
</div>
<div class="search">
<form action="FINAL_CarparkResult.php" class="searchForm" method="post">
<input class="searchBox" type="text" name="keywords" value="Search for parking - Where do you need to park?" onfocus="clearSearch(this)" onblur="searchText(this)" />
<input type="submit" value="Submit" class="submitButton" />
</form>
</div>
<file_sep>/howitworks.php
html xmlns="http://www.w3.org/1999/xhtml">
<Head>
<link type="text/css" rel="stylesheet" href="header.css" media="screen" />
<link type="text/css" rel="stylesheet" href="style.css" media="screen" />
<Title>How It Works</Title>
</head>
<body>
<?php include 'header.html' ; ?>
<div class="bodyContainer">
<div class="howTitle"><br>
<?php
echo 'How It Works';
?>
</div>
<br><br>
<div class="howContent">
<?php
echo '<b>Register a car park</b><br/><br/>';
echo '1. Register as a user.<br/><br/>';
echo '2. Log in using your email and password.<br/><br/>';
echo '3. Fill in the details of your car park.<br/><br/>';
echo '4. Post it in the website.<br/><br/>';
echo '<br/><br/>';
echo '<b>Rent a car park</b><br/><br/>';
echo '1. Register as a user.<br/><br/>';
echo '2. Log in using your email and password.<br/><br/>';
echo '3. Under "Rent Car Par", browse the car park of your choice.<br/><br/>';
echo '4. Fill in your details.<br/><br/>';
echo '5. Make payment.';
?>
</div>
</div>
</body>
</html><file_sep>/UseThisTemplate.php
<!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" />
<link type="text/css" rel="stylesheet" href="header.css" media="screen" />
<link type="text/css" rel="stylesheet" href="style.css" media="screen" />
<script type="text/javascript" src="script.js"></script>
<title> <!-- Insert Title --> </title>
</head>
<body>
<?php include 'header.html' ; ?>
<!-- ~~~~~~~~~~~TYPE YOUR CODE HERE~~~~~~~~~~~~~~~~~ -->
<?php include 'footer.html' ; ?>
</body>
</html><file_sep>/include/registrationSuccess.inc
<p><b>Registration is successful!!!<b></p>
<?php
$Test = "Test";
// connect to database
$pdo = new PDO('mysql:host=localhost; dbname=RentCarPark', 'root', '');
// sql insert statement
$stmt = $pdo->prepare('INSERT INTO customerSupply (Firstname, Surname, Emailaddress, Password, Phonenumber,
StateorTerritory, StreetNum, StreetName, Suburb, Postcode) VALUES (:Firstname,
:Surname, :Emailaddress, :Password, :Phonenumber, :StateorTerritory,
:StreetNum, :StreetName, :Suburb, :Postcode)');
// Inputed data from user is recorded into the database
$stmt->bindValue(':Firstname', $_POST['firstName']);
$stmt->bindValue(':Surname', $_POST['lastName']);
$stmt->bindValue(':Emailaddress', $_POST['email']);
$stmt->bindValue(':Password', $_POST['<PASSWORD>']);
$stmt->bindValue(':Phonenumber', $_POST['phoneNumber']);
$stmt->bindValue(':StateorTerritory', $_POST['states']);
$stmt->bindValue(':StreetNum', $_POST['streetNum']);
$stmt->bindValue(':StreetName', $_POST['streetName']);
$stmt->bindValue(':Suburb', $_POST['suburb']);
$stmt->bindValue(':Postcode', $_POST['postCode']);
$stmt->execute();
?><file_sep>/bookingform.php
<!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" />
<link type="text/css" rel="stylesheet" href="header.css" media="screen" />
<link type="text/css" rel="stylesheet" href="style.css" media="screen" />
<script type="text/javascript" src="script.js"></script>
<title> Booking Form </title>
</head>
<body>
<?php include 'header.html' ; ?>
<?php
$price = $_POST['submit'];
$purchaseID = $_POST['ID'];
?>
<div class="bodyContainer">
<div class="modal">
<div class="modal-header">
Booking <span>for a car park</span>
</div>
<form id="form-id" action="successbook.php" class="form">
<div class="modal-body">
<?php
echo "CarparkID: $purchaseID </br>";
echo "Amount Owed: $$price</br>";
?>
<div class="control-group required ">
<label for="id_first_name" class="control-label"> Name </label>
<div class="controls">
<input type="text" name="nametxt" required />
</div>
</div>
<div class="control-group required ">
<label for="id_first_name" class="control-label"> Phone </label>
<div class="controls">
<input type="" name="phonetxt" required />
</div>
</div>
<div class="control-group required ">
<label for="id_first_name" class="control-label"> Payment Method </label>
<div class="controls">
<input type="radio" name="payment" value="Credit Card" id="div1" /> Credit Card <input type="radio" name="payment" value="paypal" id="div2" /> PayPal
</div>
</div>
<div id='formdiv1' style='display:none'>
<div class="control-group required ">
<label for="id_first_name" class="control-label"> Card Number </label>
<div class="controls">
<input type="text" name="txtcard1" maxlength="4" size="4" class="small" required /> <input type="text" name="txtcard2" maxlength="4" size="4" class="small"required /> <input type="text" name="txtcard3" maxlength="4" size="4" class="small" required /> <input type="text" name="txtcard4" maxlength="4" size="4" class="small" required /> <br>
<!--<img src="images/cclogo.jpg" alt="cclogospic" width="300" height="28" />-->
</div>
</div>
<div class="control-group required ">
<label for="id_first_name" class="control-label"> Cardholder Name </label>
<div class="controls">
<input type="text" name="ccname" size="30" maxlength="20" required />
</div>
</div>
<div class="control-group required ">
<label for="id_first_name" class="control-label"> Expirty Date </label>
<div class="controls">
<input type="text" name="expmonth" size="2" maxlength="2" class="small" required /> <input type="text" name="expyear" size="4" maxlength="4" class="medium" required />
</div>
</div>
<div class="control-group required ">
<label for="id_first_name" class="control-label"> CVV </label>
<div class="controls">
<input type="text" maxlength="3" name="ccCVV" size="3" required />
</div>
</div>
</div>
<div id="formdiv2" style="display:none">
<h4><a href="http://www.Paypal.com/"> Pay using PayPal </a></h4>
<p> When you press the PayPal link, you will be directed to PayPal website where you can login or create a PayPal account and submit your payment. Upon full payment, you will be transferred back in to this website to obtain booking information.</p>
</div>
</div>
<div class="modal-footer">
<a href="successbook.php"><button type="button" class="btn btn-large btn-success">
Confirm
</button></a>
<button type="reset" class="btn btn-large btn-success">
Delete
</button>
</div>
</form>
</div>
</div>
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript" charset="utf-8">
$('#form-id').change(function() {
if ($('#div1').prop('checked')) {
$('#formdiv1').show();
}
else {
$('#formdiv1').hide();
}
if ($('#div2').prop('checked')) {
$('#formdiv2').show();
}
else {
$('#formdiv2').hide();
}
});
</script>
<?php include 'footer.html' ; ?>
</body>
</html><file_sep>/FINAL_CarparkResult.php
<!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" />
<link type="text/css" rel="stylesheet" href="header.css" media="screen" />
<link type="text/css" rel="stylesheet" href="style.css" media="screen" />
<script type="text/javascript" src="script.js"></script>
<title> <!-- Insert Title --> </title>
</head>
<body>
<?php include 'header.html' ; ?>
<div class="content">
<div class="bodyContainer">
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="rentcarpark"; // Database name
$tbl_name="carparks"; // Table name
// Connect to server and select databse.
$conn = new PDO("mysql:host=$host;dbname=$db_name", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$keywords = $_POST['keywords'];
$keywords = strtoupper($keywords);
if(!isset($keywords) || $keywords == false){
$stmt = $conn->prepare("SELECT * FROM $tbl_name");
$stmt -> execute();
}
else{
$stmt=$conn->prepare("SELECT * FROM $tbl_name WHERE UPPER(AdName) LIKE '%$keywords%' OR UPPER(AdDescription) LIKE '%$keywords%' OR UPPER(Location) LIKE '%$keywords%'");
$stmt->execute ();
}
$count= $stmt->rowCount();
//Display amount of results
echo "$count results returned </br></br>";
$arrayPrice = [];
$arrayID = [];
$index= -1;
// 1: name,
// 2: dis,
// .pic: pic,
// 5: suburb,
// 3: price,
foreach ($stmt as $data) {
$arrayPrice[] = $data[3];
$arrayID[] = $data[0];
$index = $index+1;
$picture = "data:image/jpeg;base64," . base64_encode($data[4]);
echo("
<form action='bookingform.php' method='post'>
<div class=\"block1\">
<span class=\"name\"><h4>$data[1]</h4></span>
<span class=\"price\">Price: $$data[3]</span>
<div class=\"img\"><img src=".$picture."></img></div>
<span class=\"dis\"><b>$data[5]</b></span>
<span class=\"dis2\"><p>$data[2]</p></span>
<div class=\"button\">
<input type='hidden' value='$arrayID[$index]' name='ID'>
<button name='submit' value='$arrayPrice[$index]'>Purchase</button>
</div>
</div>
</form>");
}
?>
</div>
</div>
<?php include 'footer.html' ; ?>
</body>
</html><file_sep>/FINAL_CarparkData.php
<?php
session_start();
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="rentcarpark"; // Database name
$tbl_name="carparks"; // Table name
// Connect to server and select databse.
$conn = new PDO("mysql:host=$host;dbname=$db_name", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Info sent from form
$ad_name=$_POST['ad_name'];
$ad_description=$_POST['ad_description'];
$price=$_POST['price'];
$location=$_POST['location'];
$file=$_FILES['image']['tmp_name'];
//Converting image
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
//Input all data to DB
$stmt = $conn->prepare("INSERT INTO carparks (AdName, AdDescription, Price, Picture, Location) VALUES ('$ad_name','$ad_description','$price', '$image','$location')");
$stmt->execute();
header( "Location: added.php" );
?>
<file_sep>/SQL_test.php
<?php
$con=mysqli_connect("localhost","root","","test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Insert values (more duongasaur!!!)
mysqli_query($con,"INSERT INTO testTable (Name, ID) VALUES ('Duongasaur',69)");
// Display value (A LOT OF duongasaur!)
$result = mysqli_query($con,"SELECT * FROM testTable");
while($row = mysqli_fetch_array($result))
{
echo $row['Name'] . " " . $row['ID'];
echo "<br>";
}
mysqli_close($con);
?>
<file_sep>/script.js
function searchText(a) {
if(a.value === ""){
a.value="Search for parking - Where do you need to park?";
}
}
function clearSearch(a) {
if(a.value == "Search for parking - Where do you need to park?"){
a.value="";
}
}
|
9b396d4b740a48ea888ff811e8c565d82be90eb8
|
[
"JavaScript",
"SQL",
"HTML",
"PHP"
] | 26
|
PHP
|
craizile/INB313
|
7e4beb39684e5f5be0516d5d7570ad0c419c488b
|
f68bc49d65aadd0283a91b081462d7a7e4cf0d37
|
refs/heads/master
|
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pagination
{
}
public class User
{
public string id;
public string full_name;
public string profile_picture;
public string username;
}
public class Thumbnail
{
public int width;
public int height;
public string url;
}
public class LowResolution
{
public int width;
public int height;
public string url;
}
public class StandardResolution
{
public int width;
public int height;
public string url;
}
public class Images
{
public Thumbnail thumbnail;
public LowResolution low_resolution;
public StandardResolution standard_resolution;
}
public class From
{
public string id;
public string full_name;
public string profile_picture;
public string username;
}
public class Caption
{
public string id;
public string text;
public string created_time;
public From from;
}
[System.Serializable]
public class Likes
{
public int count;
}
public class Comments
{
public int count;
}
[System.Serializable]
public class Datum
{
public string id;
public User user;
public Images images;
public string created_time;
public Caption caption;
public bool user_has_liked;
public Likes likes;
public List<object> tags;
public string filter;
public Comments comments;
public string type;
public string link;
public object location;
public object attribution;
public List<object> users_in_photo;
}
public class Meta
{
public int code;
}
[System.Serializable]
public class RootObject
{
public Pagination pagination;
public List<Datum> data;
public Meta meta;
public static RootObject CreateFromJSON(string jsonString)
{
return JsonUtility.FromJson<RootObject>(jsonString);
}
}
<file_sep>using System.Collections;
using UnityEngine;
namespace Player_Scripts
{
public class TrapCollision : MonoBehaviour
{
[SerializeField] private AudioSource _audioSource;
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
_audioSource.Play();
}
}
}
}<file_sep>using System;
using System.Collections;
using UnityEngine;
namespace Player_Scripts
{
public class EnemyDeactivator : MonoBehaviour
{
[SerializeField] private AudioSource _audioSource;
[SerializeField] private GameObject _flash;
private int counter;
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Enemy"))
{
other.gameObject.SetActive(false);
_audioSource.Play();
_flash.SetActive(true);
StartCoroutine(FlashBlip());
counter++;
GameplayController.instance.SetPhotoScore(counter);
}
}
IEnumerator FlashBlip()
{
yield return new WaitForSeconds(0.2f);
_flash.SetActive(false);
}
}
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class InstagramManager : MonoBehaviour
{
//Config
[SerializeField]
private string apiToken;
[SerializeField]
private string postId;
[SerializeField]
public float likesCounter, currentLikesCounter, maxLikes, manaPoints, newLikesCounter, likeValue;
private string URL = "https://api.instagram.com/v1/users/self/media/recent/?access_token=";
private int cnt = 0;
[SerializeField]
private int step = 500;
[SerializeField]
private Slider manabar;
[SerializeField] private Transform _player;
private void Awake()
{
StartCoroutine(GetRequest(URL + apiToken));
}
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (newLikesCounter >= 1)
{
if (Input.GetKeyUp(KeyCode.Space))
{
newLikesCounter -= manaPoints;
manabar.value = newLikesCounter;
DebuffPlayer();
}
} else if (newLikesCounter < 1) {
++cnt;
if (cnt >= step)
{
Debug.Log("Calling API...");
StartCoroutine(GetLikesOnUpdate(URL + apiToken));
cnt = 0;
}
}
if (Input.GetKeyUp(KeyCode.Tab))
{
DebuffPlayer();
}
}
private void DebuffPlayer()
{
GameManager.instance.ScaleReset();
var playerPosition = _player.localPosition;
playerPosition.y += 0.3f;
_player.localPosition = playerPosition;
var temp = _player.localScale;
temp.x = GameManager.instance.PlayerScale;
temp.y = GameManager.instance.PlayerScale;
_player.localScale = temp;
}
// Calls Instagram API and gets data of recent posts
private IEnumerator GetRequest(string uri)
{
using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
{
yield return webRequest.SendWebRequest();
if (webRequest.isNetworkError)
{
Debug.Log("Error: " + webRequest.error);
}
else
{
//Debug.Log(webRequest.downloadHandler.text);
var ResponseObj = RootObject.CreateFromJSON(webRequest.downloadHandler.text);
var responseData = ResponseObj.data;
FindLikesById(responseData);
}
}
}
// Iterate through List to get likes
private void FindLikesById(List<Datum> posts)
{
foreach (Datum post in posts)
{
if (post.id == postId)
{
int likes = post.likes.count;
likesCounter = Mathf.Round(likes);
maxLikes = likesCounter;
newLikesCounter = likesCounter / maxLikes;
manabar.value = newLikesCounter;
}
}
}
//===========================================================================================
// Calls Instagram API and gets data of recent posts
private IEnumerator GetLikesOnUpdate(string uri)
{
using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
{
yield return webRequest.SendWebRequest();
if (webRequest.isNetworkError)
{
Debug.Log("Error: " + webRequest.error);
}
else
{
Debug.Log("Success!");
var ResponseObj = RootObject.CreateFromJSON(webRequest.downloadHandler.text);
var responseData = ResponseObj.data;
FilterCurrentLikes(responseData);
}
}
}
// Iterate through List to get likes
private void FilterCurrentLikes(List<Datum> posts)
{
foreach (Datum post in posts)
{
if (post.id == postId)
{
int likes = post.likes.count;
currentLikesCounter = Mathf.Round(likes);
newLikesCounter = (currentLikesCounter - likesCounter) * likeValue;
manabar.value = newLikesCounter;
//likesCounter = currentLikesCounter;
}
}
}
private void DecreaseLikes() {
newLikesCounter -= manaPoints;
Debug.Log(newLikesCounter);
manabar.value = newLikesCounter;
}
}
<file_sep>using System;
using UnityEngine;
public class TrapActivator : MonoBehaviour
{
[SerializeField] private AudioSource _audioSource;
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
GameManager.instance.ScaleBuff();
_audioSource.Play();
var tempLocalScale = other.transform.localScale;
tempLocalScale.x = GameManager.instance.PlayerScale;
tempLocalScale.y = GameManager.instance.PlayerScale;
other.transform.localScale = tempLocalScale;
gameObject.SetActive(false);
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class CloudCollector : MonoBehaviour {
void OnTriggerEnter2D(Collider2D target) {
if (target.CompareTag("Cloud") || target.CompareTag("Deadly")) {
target.gameObject.SetActive(false);
}
}
}
<file_sep>using System.Collections.Generic;
using UnityEngine;
namespace Game_Controllers
{
public class TrapsSoundController : MonoBehaviour
{
public static TrapsSoundController instance;
[SerializeField] private AudioSource _audioSource;
[SerializeField] private List<AudioClip> _trapsSoundsCollection;
void Awake () {
MakeSingleton ();
}
void MakeSingleton() {
if (instance != null) {
Destroy (gameObject);
} else {
instance = this;
DontDestroyOnLoad(gameObject);
}
}
private void FixedUpdate()
{
// var keyUp = Input.GetKeyDown(KeyCode.Space);
// if (keyUp)
// {
// _audioSource.clip = _trapsSoundsCollection[0];
// _audioSource.Play();
// }
}
}
}<file_sep>using System;
using UnityEngine;
namespace Player_Scripts
{
public class YouDidIt : MonoBehaviour
{
[SerializeField] private GameObject _fin;
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
_fin.SetActive(true);
}
}
}
}<file_sep>using UnityEngine;
using System.Collections;
using System.Diagnostics;
public enum Mode
{
Easy = 0,
Medium = 1,
Hard = 2,
}
public class CameraScript : MonoBehaviour {
private float speed = 1.0f;
private float acceleration = 0.2f;
private float maxSpeed = 3.2f;
[HideInInspector]
public bool moveCamera;
private float easySpeed = 3.2f;
private float mediumSpeed = 3.7f;
private float hardSpeed = 4.2f;
Stopwatch stopwatch = new Stopwatch();
[SerializeField]
private Transform _player;
private int _mode = 0;
private Vector2 _playerSize;
void Start () {
if (GamePreferences.GetEasyDifficultyState () == 0) {
maxSpeed = easySpeed;
}
if (GamePreferences.GetMediumDifficultyState () == 0) {
maxSpeed = mediumSpeed;
}
if (GamePreferences.GetHardDifficultyState () == 0) {
maxSpeed = hardSpeed;
}
moveCamera = true;
_playerSize = _player.GetComponent<CapsuleCollider2D>().size;
}
void Update ()
{
if (moveCamera)
{
MoveCamera (_mode);
}
}
void MoveCamera(int mode) {
var temp = transform.position;
var oldY = temp.y;
var newY = NewCameraY(temp.y);
temp.y = Mathf.Clamp (temp.y, oldY, newY);
transform.position = temp;
speed += acceleration * Time.deltaTime;
if (speed > maxSpeed)
speed = maxSpeed;
}
float NewCameraY(float posY)
{
return _player.position.y; // - _playerSize.y;
// switch (_mode)
// {
// case (int) Mode.Easy:
// return _player.position.y - _playerSize.y;
// case (int) Mode.Medium:
// return _player.position.y - _playerSize.y;
// case (int) Mode.Hard:
// return posY - (speed * Time.deltaTime);
// default:
// return _player.position.y - _playerSize.y;
// }
}
} // CameraScript
|
8221bc04e7c3d3be74db6a58d5e51c6334f0054f
|
[
"C#"
] | 9
|
C#
|
vnemiatyi/JackTheGiant
|
602507f1d1d80c9bc71c6f8dd7e2e3478d8d3f85
|
fd07df46bcc570eda2ae3b88641c2e98cc533897
|
refs/heads/main
|
<file_sep># amsl-cs-vuetify-admin
Amsl customer service admin panel based on vuetify
|
eef1f3be8bff016700264d7e9e70a0466a15cc3b
|
[
"Markdown"
] | 1
|
Markdown
|
versedpro/amsl-cs-vuetify-admin
|
c954b115b581d10af6ecdaff8b400a05f8324bab
|
39acced939c72a35f9020dabe0354d626424d8f6
|
refs/heads/master
|
<repo_name>phuongtd57/Unrar<file_sep>/MoolaMoola/app/src/main/java/com/example/phuongtd/moolamoola/fileExplore/HistoryActivity.java
package com.example.phuongtd.moolamoola.fileExplore;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.phuongtd.moolamoola.MainActivity;
import com.example.phuongtd.moolamoola.R;
import com.example.phuongtd.moolamoola.file.HistoryItem;
import com.example.phuongtd.moolamoola.file.HistoryItemView;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import io.realm.Realm;
/**
* Created by qs109 on 6/10/2016.
*/
public class HistoryActivity extends AppCompatActivity {
ListView listHistory;
TextView tvCancel;
Realm realm;
List<HistoryItem> historyItemList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.history_activity);
initView();
realm = Realm.getInstance(HistoryActivity.this);
historyItemList = realm.where(HistoryItem.class).findAll();
List<HistoryItemView> historyItemViews = new ArrayList<>();
for (HistoryItem historyItem : historyItemList) {
historyItemViews.add(new HistoryItemView(historyItem));
}
Collections.sort(historyItemViews, new Comparator<HistoryItemView>() {
@Override
public int compare(HistoryItemView lhs, HistoryItemView rhs) {
return rhs.getTime().compareTo(lhs.getTime());
}
});
HistoryAdapter historyAdapter = new HistoryAdapter(HistoryActivity.this, historyItemViews);
listHistory.setAdapter(historyAdapter);
listHistory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HistoryItem historyItem = historyItemList.get(position);
File file = new File(historyItem.getFilePath());
if (!file.exists()) {
Toast.makeText(HistoryActivity.this, "File not found", Toast.LENGTH_LONG).show();
} else {
Intent intent = new Intent();
intent.putExtra("FILE", historyItem.getFilePath());
setResult(MainActivity.MY_FILE_CODE, intent);
finish();
}
}
});
}
private void initView() {
listHistory = (ListView) findViewById(R.id.listView);
tvCancel = (TextView) findViewById(R.id.tvCancel);
tvCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
}
@Override
protected void onDestroy() {
realm.close();
super.onDestroy();
}
}
<file_sep>/UnrarJarTest/app/src/main/java/com/example/phuongtd/unrarjartest/MainActivity.java
package com.example.phuongtd.unrarjartest;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import de.innosystec.unrar.Archive;
import de.innosystec.unrar.rarfile.FileHeader;
import java.io.File;
import java.io.FileOutputStream;
public class MainActivity extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File dir = Environment.getExternalStorageDirectory();
File f = new File(dir, "/Download/text.rar");
Archive a = null;
try {
a = new Archive(f, "", false); // extract mode
if(a.isPass()){
Log.d( "phuongtd" , "Pass word");
a = new Archive(f, "123", false);
}
} catch (Exception e) {
e.printStackTrace();
}
if (a != null) {
a.getMainHeader().print();
FileHeader fh = a.nextFileHeader();
while (fh != null) {
try {
File out = new File(dir , "/Download/"
+ fh.getFileNameString().trim());
System.out.println(out.getAbsolutePath());
FileOutputStream os = new FileOutputStream(out);
a.extractFile(fh, os);
os.close();
} catch (Exception e) {
e.printStackTrace();
}
fh = a.nextFileHeader();
}
}
}
}
<file_sep>/MoolaMoola/app/src/main/java/com/example/phuongtd/moolamoola/MainActivity.java
package com.example.phuongtd.moolamoola;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.daimajia.numberprogressbar.NumberProgressBar;
import com.example.phuongtd.moolamoola.dialog.PasswordDialog;
import com.example.phuongtd.moolamoola.file.HistoryItem;
import com.example.phuongtd.moolamoola.file.FileUtils;
import com.example.phuongtd.moolamoola.fileExplore.HistoryActivity;
import com.example.phuongtd.moolamoola.fileExplore.FileExploreActivity;
import com.example.phuongtd.moolamoola.fileExplore.PreviewActivity;
import com.example.phuongtd.moolamoola.fileExplore.SearchActivity;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.exception.ZipExceptionConstants;
import net.rdrei.android.dirchooser.DirectoryChooserConfig;
import net.rdrei.android.dirchooser.DirectoryChooserFragment;
import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;
import de.innosystec.unrar.Archive;
import de.innosystec.unrar.exception.RarException;
import de.innosystec.unrar.rarfile.FileHeader;
import io.realm.Realm;
public class MainActivity extends AppCompatActivity implements DirectoryChooserFragment.OnFragmentInteractionListener {
final int FILE_CODE = 26;
public static final int MY_FILE_CODE = 7;
private DirectoryChooserFragment mDialog;
DirectoryChooserConfig config;
Button btSelectRarFile;
Button btSelectTargetFolder;
Button btExtract;
Button btPreview;
EditText tvFileSelect;
EditText tvFolderTarget;
boolean hasChooseFolder = false;
String targetFolder = "/sdcard";
String uriFile = null;
ProgressBar progressBar;
String password = "";
NumberProgressBar numberProgressBar;
LinearLayout llFileInfo;
TextView tvFilePath;
TextView tvFileSize;
int numOfFile = 1;
int currentExtractFile = 0;
private final String FILE_HAVE_PASS = "<PASSWORD>";
ImageView btHistory;
ImageView btSearch;
File f;
Archive a;
FileHeader fh;
TextView tvInternal;
TextView tvExternal;
// zip
ZipFile zipFile;
List fileHeaderList;
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
Window window = getWindow();
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.LOLLIPOP) {
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(getResources().getColor(R.color.status));
}
initView();
initChooseFolder();
}
private void initChooseFolder() {
config = DirectoryChooserConfig.builder()
.newDirectoryName("New Folder")
.allowNewDirectoryNameModification(true)
.initialDirectory(targetFolder)
.build();
mDialog = DirectoryChooserFragment.newInstance(config);
}
void initView() {
tvInternal = (TextView) findViewById(R.id.tvInternal);
tvExternal = (TextView) findViewById(R.id.tvExternal);
btSelectRarFile = (Button) findViewById(R.id.btSelectRarFile);
btSelectTargetFolder = (Button) findViewById(R.id.btSelectTargetFolder);
tvFileSelect = (EditText) findViewById(R.id.tvFileSelect);
tvFolderTarget = (EditText) findViewById(R.id.tvFolderTarget);
btExtract = (Button) findViewById(R.id.btExtract);
numberProgressBar = (NumberProgressBar) findViewById(R.id.numberBar);
tvFilePath = (TextView) findViewById(R.id.tvFilePath);
tvFileSize = (TextView) findViewById(R.id.tvFileSize);
llFileInfo = (LinearLayout) findViewById(R.id.llFileInfo);
btPreview = (Button) findViewById(R.id.btPreview);
btHistory = (ImageView) findViewById(R.id.btHistory);
btSearch = (ImageView) findViewById(R.id.btSearch);
llFileInfo.setVisibility(View.GONE);
btSelectTargetFolder.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mDialog.show(getFragmentManager(), null);
}
});
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btSelectRarFile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, FileExploreActivity.class);
startActivityForResult(i, MY_FILE_CODE);
}
});
btExtract.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (uriFile == null) {
Toast.makeText(MainActivity.this, "Please choose file", Toast.LENGTH_LONG).show();
return;
}
if (!(uriFile.endsWith(".rar") || uriFile.endsWith(".zip"))) {
Toast.makeText(MainActivity.this, "Please choose compress file", Toast.LENGTH_LONG).show();
return;
}
if (!hasChooseFolder) {
Toast.makeText(MainActivity.this, "Please choose folder to save file", Toast.LENGTH_LONG).show();
return;
}
if (uriFile.endsWith(".rar")) {
new MyAsync().execute();
} else {
try {
zipFile = new ZipFile(uriFile);
} catch (ZipException e) {
e.printStackTrace();
}
new MyAsyncZip().execute();
}
}
});
btPreview.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (uriFile == null) {
Toast.makeText(MainActivity.this, "Please choose .rar file", Toast.LENGTH_LONG).show();
return;
}
Intent intent = new Intent(MainActivity.this, PreviewActivity.class);
intent.putExtra("file", uriFile);
startActivity(intent);
}
});
btHistory.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, HistoryActivity.class);
startActivityForResult(intent, MY_FILE_CODE);
}
});
btSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SearchActivity.class);
startActivityForResult(intent, MY_FILE_CODE);
}
});
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_FILE_CODE) {
if (data != null && data.hasExtra("FILE")) {
String uri = data.getStringExtra("FILE");
tvFileSelect.setText(uri);
uriFile = uri;
llFileInfo.setVisibility(View.VISIBLE);
tvFilePath.setText(uri);
tvFileSize.setText(FileUtils.getFileLength(new File(uri)));
}
}
}
@Override
public void onSelectDirectory(String path) {
mDialog.dismiss();
targetFolder = path;
initChooseFolder();
tvFolderTarget.setText(targetFolder);
hasChooseFolder = true;
}
@Override
public void onCancelChooser() {
mDialog.dismiss();
}
public class MyAsync extends AsyncTask<Void, Integer, String> {
@Override
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
//File dir = Environment.getExternalStorageDirectory();
progressBar.setVisibility(View.VISIBLE);
numberProgressBar.setVisibility(View.VISIBLE);
f = new File(uriFile);
a = null;
try {
a = new Archive(f, password, false); // extract mode
} catch (Exception e) {
e.printStackTrace();
}
currentExtractFile = 0;
numOfFile = a.getFileHeaders().size();
numberProgressBar.setMax(numOfFile);
numberProgressBar.setProgress(currentExtractFile);
}
@Override
protected String doInBackground(Void... params) {
HashSet<String> hashSet = new HashSet<>();
if (a != null) {
a.getMainHeader().print();
FileHeader fh = a.nextFileHeader();
String fileName = fh.getFileNameString().replace('\\', '/');
String tempFile = targetFolder + "/" + "temp";
try {
FileOutputStream os = new FileOutputStream(tempFile);
a.extractFile(fh, os);
os.close();
} catch (RarException e) {
if (e.getMessage().equalsIgnoreCase("crcError")) {
return FILE_HAVE_PASS;
}
} catch (Exception e) {
return "Cant extract this file, " + e.getMessage();
} finally {
File fileTemp = new File(tempFile);
if (fileTemp.exists()) {
fileTemp.delete();
}
}
// caculator sum block
String folderName = null;
if (fileName.contains("/")) {
folderName = fileName.split("/")[0];
String folderString = targetFolder + "/" + folderName;
File folder = new File(folderString);
if (!folder.exists()) {
folder.mkdir();
}
}
while (fh != null) {
currentExtractFile++;
Log.d("phuongtd", "Packname before: " + fh.getFileNameString());
Log.d("phuongtd", "Packname after: " + fh.getFileNameString().replace('\\', '/'));
try {
if (folderName == null || (folderName != null && !fh.getFileNameString().equalsIgnoreCase(folderName))) {
fileName = fh.getFileNameString().replace('\\', '/');
String[] listFolder = fileName.split("/");
String longName = listFolder[0];
//hashSet.add(longName);
for (int i = 1; i < listFolder.length - 1; i++) {
String s = listFolder[i];
longName = longName + "/" + s;
hashSet.add(longName);
File folder = new File(targetFolder + "/" + longName);
if (!folder.exists()) {
folder.mkdir();
}
}
if (!hashSet.contains(fileName)) {
File out = new File("", targetFolder + "/" + fileName);
System.out.println(out.getAbsolutePath());
FileOutputStream os = new FileOutputStream(out);
a.extractFile(fh, os);
os.close();
}
}
} catch (Exception e) {
return "Cant extract this file, " + e.getMessage();
}
fh = a.nextFileHeader();
publishProgress(currentExtractFile);
}
return "";
} else {
return "Cant extract this file ";
}
}
@Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
if (aVoid.equalsIgnoreCase("")) {
Toast.makeText(MainActivity.this, "Extract successfully", Toast.LENGTH_SHORT).show();
Realm realm = Realm.getInstance(MainActivity.this);
try {
realm.beginTransaction();
HistoryItem eh = new HistoryItem();
eh.setId(UUID.randomUUID().toString());
eh.setName(uriFile);
eh.setFilePath(uriFile);
eh.setFolderSave(targetFolder);
eh.setStatus("SUCCESS");
/* Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm - dd MMM");*/
eh.setTime(System.currentTimeMillis());
realm.copyToRealm(eh);
} finally {
realm.commitTransaction();
realm.close();
}
} else if (aVoid.equalsIgnoreCase(FILE_HAVE_PASS)) {
PasswordDialog passwordDialog = new PasswordDialog(MainActivity.this, new PasswordDialog.ActionImpl() {
@Override
public void execute(String pass) {
password = <PASSWORD>;
new MyAsync().execute();
}
});
passwordDialog.show();
} else {
Toast.makeText(MainActivity.this, aVoid, Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
numberProgressBar.setProgress(values[0]);
}
}
public class MyAsyncZip extends AsyncTask<Void, Integer, String> {
@Override
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
//File dir = Environment.getExternalStorageDirectory();
progressBar.setVisibility(View.VISIBLE);
numberProgressBar.setVisibility(View.VISIBLE);
try {
fileHeaderList = zipFile.getFileHeaders();
} catch (ZipException e) {
e.printStackTrace();
}
currentExtractFile = 0;
numOfFile = fileHeaderList.size();
numberProgressBar.setMax(numOfFile);
numberProgressBar.setProgress(currentExtractFile);
}
@Override
protected String doInBackground(Void... params) {
try {
if (zipFile != null) {
for (int i = 0; i < fileHeaderList.size(); i++) {
net.lingala.zip4j.model.FileHeader fileHeader = (net.lingala.zip4j.model.FileHeader) fileHeaderList.get(i);
String fileName = fileHeader.getFileName();
if (fileName.trim().endsWith("/")) {
String[] listName = fileName.split("/");
String longName = listName[0];
File folder = new File(targetFolder + "/" + longName);
if (!folder.exists()) {
folder.mkdir();
}
for (int j = 1; j <= listName.length - 2; j++) {
longName = longName + "/" + listName[j];
folder = new File(targetFolder + "/" + longName);
if (!folder.exists()) {
folder.mkdir();
}
}
}
}
int j = 1;
for (int i = fileHeaderList.size() - 1; i >= 0; i--) {
net.lingala.zip4j.model.FileHeader fileHeader = (net.lingala.zip4j.model.FileHeader) fileHeaderList.get(i);
zipFile.extractFile(fileHeader, targetFolder);
publishProgress(j);
j = j + 1;
}
}
} catch (ZipException e) {
e.printStackTrace();
if (e.getCode() == -1) {
return FILE_HAVE_PASS;
} else {
return "Cant extract this file";
}
}
return "";
}
@Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
if (aVoid.equalsIgnoreCase("")) {
Toast.makeText(MainActivity.this, "Extract successfully", Toast.LENGTH_SHORT).show();
Realm realm = Realm.getInstance(MainActivity.this);
try {
realm.beginTransaction();
HistoryItem eh = new HistoryItem();
eh.setId(UUID.randomUUID().toString());
eh.setName(uriFile);
eh.setFilePath(uriFile);
eh.setFolderSave(targetFolder);
eh.setStatus("SUCCESS");
/*Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm - dd MMM");*/
eh.setTime(System.currentTimeMillis());
realm.copyToRealm(eh);
} finally {
realm.commitTransaction();
realm.close();
}
} else if (aVoid.equalsIgnoreCase(FILE_HAVE_PASS)) {
PasswordDialog passwordDialog = new PasswordDialog(MainActivity.this, new PasswordDialog.ActionImpl() {
@Override
public void execute(String pass) {
try {
zipFile.setPassword(pass);
} catch (ZipException e) {
e.printStackTrace();
}
new MyAsyncZip().execute();
}
});
passwordDialog.show();
} else {
Toast.makeText(MainActivity.this, aVoid, Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
numberProgressBar.setProgress(values[0]);
}
}
}
<file_sep>/MoolaMoola/app/src/main/java/com/example/phuongtd/moolamoola/Type.java
package com.example.phuongtd.moolamoola;
/**
* Created by qs109 on 6/6/2016.
*/
public enum Type {
SUCCESS , ERROR , UPDATE
}
<file_sep>/MoolaMoola/app/src/main/java/com/example/phuongtd/moolamoola/fileExplore/HistoryAdapter.java
package com.example.phuongtd.moolamoola.fileExplore;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.phuongtd.moolamoola.R;
import com.example.phuongtd.moolamoola.file.HistoryItem;
import com.example.phuongtd.moolamoola.file.HistoryItemView;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* Created by qs109 on 6/10/2016.
*/
public class HistoryAdapter extends BaseAdapter {
Context context;
List<HistoryItemView> extractHistories;
public HistoryAdapter(Context context, List<HistoryItemView> extractHistoryList) {
this.context = context;
this.extractHistories = extractHistoryList;
}
@Override
public int getCount() {
return extractHistories.size();
}
@Override
public Object getItem(int position) {
return extractHistories.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.history_item, parent, false);
}
TextView tvPath = (TextView) convertView.findViewById(R.id.tvFilePath);
TextView tvTime = (TextView) convertView.findViewById(R.id.tvTime);
HistoryItemView extractHistory = extractHistories.get(position);
tvPath.setText(extractHistory.getFilePath());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm - dd MMM");
Date date = new Date(extractHistory.getTime());
tvTime.setText(simpleDateFormat.format(date));
return convertView;
}
}
<file_sep>/MoolaMoola/app/build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
applicationId "com.example.phuongtd.moolamoola"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.github.ben-manes:gradle-versions-plugin:0.11.3'
}
}
repositories {
mavenCentral()
maven { url 'http://guardian.github.com/maven/repo-releases' }
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.3.0'
compile 'com.nononsenseapps:filepicker:2.5.2'
compile 'com.gu:option:1.3'
compile 'net.rdrei.android.dirchooser:library:3.2@aar'
compile 'com.daimajia.numberprogressbar:library:1.2@aar'
compile 'io.realm:realm-android:0.87.4'
compile 'org.gnu:gnu-crypto:2.0.1'
compile 'net.lingala.zip4j:zip4j:1.3.2'
compile files('libs/java-unrar-decryption-supported-20120903.jar')
compile files('libs/unrar-lib.jar')
}
<file_sep>/MoolaMoola/app/src/main/java/com/example/phuongtd/moolamoola/MessageObject.java
package com.example.phuongtd.moolamoola;
/**
* Created by qs109 on 6/6/2016.
*/
public class MessageObject {
Type type;
String message;
int value;
public MessageObject(Type type, String message, int value) {
this.type = type;
this.message = message;
this.value = value;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
<file_sep>/MoolaMoola/app/src/main/java/com/example/phuongtd/moolamoola/file/FileObject.java
package com.example.phuongtd.moolamoola.file;
import java.util.ArrayList;
import java.util.List;
/**
* Created by qs109 on 6/7/2016.
*/
public class FileObject
{
boolean isBackFolder;
private String path;
private FileObject parent;
private boolean isFile;
private String extension;
private String volume;
private String name;
List<FileObject> childs;
public String getPath()
{
return path;
}
public void setPath(String path)
{
this.path = path;
}
public FileObject getParent()
{
return parent;
}
public void setParent(FileObject parent)
{
this.parent = parent;
}
public void setIsFile(boolean isFile)
{
this.isFile = isFile;
}
public String getExtension()
{
return extension;
}
public void setExtension(String extension)
{
this.extension = extension;
}
public String getVolume()
{
return volume;
}
public void setVolume(String volume)
{
this.volume = volume;
}
public boolean isBackFolder() {
return isBackFolder;
}
public void setIsBackFolder(boolean isBackFolder) {
this.isBackFolder = isBackFolder;
}
public boolean isFile() {
return isFile;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<FileObject> getChilds() {
return childs;
}
public void setChilds(List<FileObject> childs) {
this.childs = childs;
}
}
|
4ee8416fad23a478b9509a7af507fe63c544c25a
|
[
"Java",
"Gradle"
] | 8
|
Java
|
phuongtd57/Unrar
|
e4019c990f39e2c97057268aeeb98e4b77b6fc3c
|
759d2bc63c02e6fe40acfd7e6fc68adafdb2d712
|
refs/heads/master
|
<repo_name>EAAgafonov/ClientServer<file_sep>/src/ServerPckg/Server.java
package ServerPckg;
import java.net.*;
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
public class Server {
static int port = 6666;
static ExecutorService executeIt = Executors.newFixedThreadPool(10);
public static void main(String[] args) {
try (ServerSocket server = new ServerSocket(port))
{
while (!server.isClosed()) {
System.out.println("Waiting for connections.");
Socket client = server.accept();
System.out.println("Client connected.");
executeIt.execute(new SimpleClientHandler(client, executeIt));
}
} catch (Exception exc) {
System.out.println(exc);
}
}
}
<file_sep>/src/ServerPckg/SimpleClientHandler.java
package ServerPckg;
import java.net.*;
import java.io.*;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
public class SimpleClientHandler implements Runnable {
public static Socket clientDialog;
public static ExecutorService executeIt;
SimpleClientHandler(Socket client, ExecutorService executeIt) {
SimpleClientHandler.clientDialog = client;
SimpleClientHandler.executeIt = executeIt;
}
@Override
public void run() {
try {
DataInputStream in = new DataInputStream(clientDialog.getInputStream());
DataOutputStream out = new DataOutputStream(clientDialog.getOutputStream());
while (!clientDialog.isClosed()) {
String line = in.readUTF();
System.out.println("client sent: " + line);
out.writeUTF(line + " - delivered");
out.flush();
}
} catch (SocketException exc) {
System.out.println(exc + "client disconnected");
} catch (Exception exc) {
System.out.println(exc + "last exc");
}
}
}
|
25e584a2dfc323cb305fc23fa8bbe6f7d644096f
|
[
"Java"
] | 2
|
Java
|
EAAgafonov/ClientServer
|
2a4284a769a83bd2a3f37522529dce060ac2eaa7
|
52081576b37d8e7b32deb1df6bdb47ac8473e6e1
|
refs/heads/master
|
<repo_name>kia3415/algorithm<file_sep>/leetcode/leetcode_3157.py
# https://leetcode.com/explore/learn/card/fun-with-arrays/511/in-place-operations/3157/
# leetcode : Move Zeroes
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
count_zero = 0
place = 0
for num in nums:
if num != 0:
nums[place] = num
place += 1
else:
count_zero += 1
if count_zero > 0:
nums[-count_zero:] = [0] * count_zero
<file_sep>/programmers/programmers_17681.py
def solution(n, arr1, arr2):
answer = []
length = len(arr1)
for n1, n2 in zip(arr1, arr2):
row = bin(n1 | n2)[2:]
row = row.rjust(length, '0')
row = row.replace('1', '#')
row = row.replace('0', ' ')
answer.append(row)
return answer
<file_sep>/baekjoon/baekjoon_17142.py
# https://www.acmicpc.net/problem/17142
# 백준 17142 : 연구소 3
# LEVEL : Gold 4
from itertools import combinations
from collections import deque
import sys
input = sys.stdin.readline
def solution():
EMPTY = '0'
WALL = '1'
VIRUS = '2'
DIRECTION = [[1, 0], [-1, 0], [0, -1], [0, 1]]
N, M = map(int, input().split())
area = [input().rstrip().split() for _ in range(N)] # 맵
times = [] # 각 경우마다 걸리는 시간을 저장
virus_locations = []
wall_cnt = 0
for i in range(N):
for j in range(N):
if area[i][j] == VIRUS:
virus_locations.append((i, j, 0)) # virus를 놓을 수 있는 위치 저장
elif area[i][j] == WALL:
wall_cnt += 1 # 벽 개수 카운트
empty_cnt = N * N - wall_cnt - len(virus_locations) # 빈 공간의 개수 카운트
if empty_cnt == 0: # 만약 빈 공간이 없으면 바로 0 출력
print(0)
return
for viruses in list(combinations(virus_locations, M)): # virues를 놓을 수 있는 위치를 M개 선택한다.
visited = [[False for _ in range(N)] for _ in range(N)]
queue = deque(viruses)
cnt = 0
while queue:
y, x, t = queue.popleft() # y, x : 현재 바이러스의 위치, t : 이 위치까지 오는 데 걸린 시간
for dy, dx in DIRECTION:
ny = y + dy
nx = x + dx
if 0 <= ny < N and 0 <= nx < N and \
area[ny][nx] != WALL and not visited[ny][nx]:
visited[ny][nx] = True
queue.append((ny, nx, t + 1))
if area[ny][nx] == EMPTY: # 빈 공간에 바이러스가 복제된 경우
cnt += 1
if cnt >= empty_cnt: # 빈 공간에 모두 바이러스가 복제된 경우
times.append(t+1)
break
if times:
print(min(times))
else:
print(-1)
solution()
<file_sep>/programmers/programmers_17678.py
# https://programmers.co.kr/learn/courses/30/lessons/17678
# programmers 17678 : 2018 KAKAO BLIND RECRUITMENT - [1차] 셔틀 버스
# LEVEL : 3
def solution(n, t, m, timetable):
answer = 0
timetable = [int(t[:2])*60+int(t[3:]) for t in timetable]
timetable.sort()
crew_i = 0
for i in range(n):
time = 540 + i*t
crews = []
while crew_i < len(timetable) and len(crews) < m and timetable[crew_i] <= time:
crews.append(timetable[crew_i])
crew_i += 1
if len(crews) < m:
answer = time
else:
answer = max(crews)-1
return str(answer//60).zfill(2) + ":" + str(answer % 60).zfill(2)
<file_sep>/programmers/programmers_42861.py
# https://programmers.co.kr/learn/courses/30/lessons/42861?language=python3
# programmers 42861 : 섬 연결하기
# LEVEL : 3
from collections import deque
def solution(n, costs):
answer = 0
weight = [[-1 for _ in range(n)] for _ in range(n)]
for cost in costs:
weight[cost[0]][cost[1]] = cost[2]
weight[cost[1]][cost[0]] = cost[2]
visited = [0]
while len(visited) < n:
min_weight, new_node = 1e9, -1
for node in visited:
for neighbor in range(n):
if neighbor not in visited and weight[node][neighbor] != -1:
if weight[node][neighbor] < min_weight:
new_node = neighbor
min_weight = weight[node][neighbor]
visited.append(new_node)
answer += min_weight
return answer
<file_sep>/programmers/programmers_12913.py
# https://programmers.co.kr/learn/courses/30/lessons/12913
# programmers 12913 : 땅따먹기
# LEVEL : 2
def solution(land):
for i in range(1, len(land)):
for j in range(4):
before_max = 0
for k in range(4):
if k != j and land[i-1][k] > before_max:
before_max = land[i-1][k]
land[i][j] += before_max
return max(land[-1])
<file_sep>/programmers/programmers_86971.py
# https://programmers.co.kr/learn/courses/30/lessons/86971
# programmers 86971 : 위클리 챌린지 - 전력망을 둘로 나누기
# LEVEL : 2
from collections import deque
def solution(n, wires):
def counting(root, cut_node):
dq, visited = deque([root]), [False for _ in range(n+1)]
visited[root] = True
while dq:
node = dq.popleft()
for i in range(1, n+1):
if not visited[i] and i != cut_node and tree[node][i]:
visited[i] = True
dq.append(i)
return visited.count(True)
answer = 100
tree = [[False for _ in range(n+1)] for _ in range(n+1)]
for wire in wires:
tree[wire[0]][wire[1]] = True
tree[wire[1]][wire[0]] = True
for wire in wires:
answer = min(answer, abs(
counting(wire[0], wire[1])-counting(wire[1], wire[0])))
return answer
<file_sep>/leetcode/leetcode_62.py
# https://leetcode.com/problems/unique-paths/
# leetcode 62 : Unique Paths
# LEVEL : Medium
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
row = [1] * n
for _ in range(1, m):
for i in range(1, n):
row[i] += row[i-1]
return row[n-1]<file_sep>/leetcode/leetcode_46.py
# https://leetcode.com/problems/permutations/
# leetcode 46 : Permutations
# LEVEL : Medium
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
def dfs(chosen, used):
if len(chosen) == len(nums):
result.append(chosen[:])
return
for i in range(len(nums)):
if not used[i]:
used[i] = True
chosen.append(nums[i])
dfs(chosen, used)
used[i] = False
chosen.pop()
result = []
used = [False for _ in range(len(nums))]
dfs([], used)
return result
<file_sep>/baekjoon/baekjoon_9205.py
# https://www.acmicpc.net/problem/9205
# 백준 9205 : 맥주 마시면서 걸어가기
# LEVEL : Silver 1
import sys
from collections import defaultdict, deque
input = sys.stdin.readline
def solution():
LIMIT = 20 * 50
TC = int(input())
for _ in range(TC):
N = int(input())
location = [list(map(int, input().split())) for _ in range(N+2)]
graph = defaultdict(dict)
for i in range(len(location)-1):
start_y, start_x = location[i][1], location[i][0]
for j in range(i+1, len(location)):
end_y, end_x = location[j][1], location[j][0]
if abs(start_y-end_y) + abs(start_x-end_x) <= LIMIT:
graph[i][j] = True
graph[j][i] = True
queue = deque([0])
visited = [False for _ in range(N+2)]
result = "sad"
while queue:
node = queue.popleft()
if node == N+1:
result = "happy"
break
for next_node in graph[node].keys():
if not visited[next_node]:
visited[next_node] = True
queue.append(next_node)
print(result)
solution()<file_sep>/baekjoon/baekjoon_14497.py
# https://www.acmicpc.net/problem/14497
# 백준 14497 : 주난의 난
# LEVEL : Gold 4
from collections import deque
import sys
input = sys.stdin.readline
def solution():
DIRECTIONS = [[1, 0], [-1, 0], [0, 1], [0, -1]]
N, M = map(int, input().split())
start_y, start_x, _, _ = map(int, input().split())
start_y -= 1
start_x -= 1
room = [list(input().rstrip()) for _ in range(N)]
def jump_and_find():
visited = [[False for _ in range(M)] for _ in range(N)]
visited[start_y][start_x] = True
queue = deque([(start_y, start_x)])
while queue:
y, x = queue.popleft()
if room[y][x] == '#':
return True
for dy, dx in DIRECTIONS:
ny = y + dy
nx = x + dx
if 0 <= ny < N and 0 <= nx < M and not visited[ny][nx]:
visited[ny][nx] = True
if room[ny][nx] == '1':
room[ny][nx] = '0'
else:
queue.append((ny, nx))
return False
count = 1
while jump_and_find() == False:
count += 1
print(count)
solution()
<file_sep>/programmers/programmers_62048.cpp
int gcd(int a, int b) { // 최대공약수 return
if (b == 0)
return a;
else
return gcd(b, a % b);
}
long long solution(int w, int h) {
long long answer = 1;
long long num = gcd(w, h); // 최대공약수 구하기
answer = (long long)w * (long long)h - (w + h - num);
return answer;
}<file_sep>/baekjoon/baekjoon_13549.py
# https://www.acmicpc.net/problem/13549
# 백준 13549 : 숨바꼭질 3
# LEVEL : Gold 5
import sys
from collections import deque, defaultdict
def solution():
[N, K] = list(map(int, sys.stdin.readline().rstrip().split()))
dq = deque([N])
visited = [-1 for _ in range(100001)]
visited[N] = 0
while dq:
loc = dq.popleft()
if loc == K:
print(visited[loc])
break
if 0 <= loc-1 < 100001 and visited[loc-1] == -1:
visited[loc-1] = visited[loc]+1
dq.append(loc-1)
if 0 < loc*2 < 100001 and visited[loc*2] == -1:
visited[loc*2] = visited[loc]
dq.appendleft(loc*2)
if 0 <= loc+1 < 100001 and visited[loc+1] == -1:
visited[loc+1] = visited[loc]+1
dq.append(loc+1)
solution()
<file_sep>/baekjoon/baekjoon_9372.py
# https://www.acmicpc.net/problem/9372
# 백준 9372 : 상근이의 여행
# LEVEL : Silver 4
import sys
from collections import defaultdict, deque
from this import d
def solution():
T = int(sys.stdin.readline())
for _ in range(T):
N, M = map(int, sys.stdin.readline().split())
airlines = defaultdict(dict)
visited = [False for _ in range(N+1)]
visited[1] = True
for _ in range(M):
a, b = map(int, sys.stdin.readline().split())
airlines[a][b] = True
airlines[b][a] = True
queue = deque([1])
ans = 0
while queue:
country = queue.popleft()
for destination in airlines[country].keys():
if not visited[destination]:
visited[destination] = True
ans += 1
queue.append(destination)
print(ans)
def solution2():
T = int(sys.stdin.readline())
for _ in range(T):
N, M = map(int, sys.stdin.readline().split())
for _ in range(M):
a, b = map(int, sys.stdin.readline().split())
print(N-1)
solution2()
# solution()
<file_sep>/programmers/programmers_72410.py
# https://programmers.co.kr/learn/courses/30/lessons/72410
# programmers 72410 : 2021 KAKAO BLIND RECROUITMENT 신규 아이디 추천
# LEVEL 1
import re
def solution(new_id):
answer = new_id.lower()
answer = "".join(re.findall("[a-z0-9-_.]", answer))
while ".." in answer:
answer = answer.replace("..", ".")
answer = answer.strip(".")
if len(answer) == 0:
answer = "a"
if len(answer) >= 16:
answer = answer[:15]
answer = answer.rstrip(".")
id_length = len(answer)
if id_length <= 2:
for i in range(3-id_length):
answer += answer[id_length-1]
return answer
<file_sep>/baekjoon/baekjoon_2174.cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Robot {
int x, y, dir;
};
int main() {
int A, B, N, M;
vector<Robot> robotList;
vector<pair<int, int>> answer;
cin >> A >> B >> N >> M;
//각 로봇들의 초기위치, 방향
for (int i = 0; i < N; i++) {
int x, y,dir;
char d;
cin >> x >> y >> d;
if (d == 'N')
dir = 0;
else if (d == 'E')
dir = 1;
else if (d == 'S')
dir = 2;
else
dir = 3;
Robot r = { x,y,dir };
robotList.push_back(r);
//cout << robotList.size() << endl;
}
//명령
for (int i = 0; i < M; i++) {
int idx, repeat;
char order;
cin >> idx >> order >> repeat;
if (order == 'L') {
robotList[idx - 1].dir -= repeat % 4;
if (robotList[idx - 1].dir < 0)
robotList[idx - 1].dir += 4;
}
else if (order == 'R') {
robotList[idx - 1].dir += repeat % 4;
if (robotList[idx - 1].dir > 3)
robotList[idx - 1].dir -= 4;
}
else {
int dx, dy;
if (robotList[idx-1].dir ==0) { // y방향위
dx = 0;
dy = 1;
}
else if (robotList[idx - 1].dir == 2) { // y방향아래
dx = 0;
dy = -1;
}
else if (robotList[idx - 1].dir == 1) { // x 오른쪽
dx = 1;
dy = 0;
}
else { // 왼쪽
dx = -1;
dy = 0;
}
for (int k = 0; k < repeat; k++) {
robotList[idx - 1].x += dx;
robotList[idx - 1].y += dy;
if (robotList[idx - 1].x == 0 || robotList[idx - 1].x > A
|| robotList[idx-1].y == 0 || robotList[idx - 1].y > B) {
cout << "Robot " << idx << " crashes into the wall" << endl;
return 0;
}
else {
for (int u = 0; u < robotList.size(); u++) {
if (idx-1 != u && robotList[u].x == robotList[idx - 1].x && robotList[u].y == robotList[idx - 1].y) {
cout << "Robot " << idx << " crashes into robot " << u+1<<endl;
return 0;
}
}
}
}
}
}
cout << "OK" << endl;
return 0;
}
<file_sep>/baekjoon/baekjoon_1431.py
# https://www.acmicpc.net/problem/1431
# 백준 1431 : 시리얼 번호
# LEVEL : Silver 3
import sys
import re
def solution():
N = int(sys.stdin.readline())
guitars = [sys.stdin.readline().rstrip() for _ in range(N)]
serial_lengths = {} # serial 길이
serial_sums = {} # 숫자의 합
for guitar in guitars:
serial_lengths[guitar] = len(guitar)
serial_sums[guitar] = sum(map(int, re.findall(r'\d', guitar)))
def swap(i, j):
guitars[i], guitars[j] = guitars[j], guitars[i]
for i in range(N):
for j in range(N-i-1):
g1, g2 = guitars[j], guitars[j+1]
if serial_lengths[g1] > serial_lengths[g2]:
swap(j, j+1)
elif serial_lengths[g1] == serial_lengths[g2]:
if serial_sums[g1] > serial_sums[g2] or \
serial_sums[g1] == serial_sums[g2] and guitars[j] > guitars[j+1]:
swap(j, j+1)
for guitar in guitars:
print(guitar)
solution()
<file_sep>/baekjoon/baekjoon_2805.py
# https://www.acmicpc.net/problem/2805
# 백준 2805 : 나무 자르기
# LEVEL : Silver 2
import sys
def solution():
N, M = map(int, sys.stdin.readline().split())
heights = list(map(int, sys.stdin.readline().split()))
low, high = 0, max(heights)-1
while low <= high:
mid = (low + high) // 2
height_sum = 0
for h in heights:
if h > mid:
height_sum += (h - mid)
if height_sum >= M:
low = mid + 1
else:
high = mid - 1
print(high)
def solution2():
N, M = map(int, sys.stdin.readline().split())
tree = map(int, sys.stdin.readline().split())
for t in tree:
print(t)
start = 0
end = max(tree)-1
while start <= end:
mid = (start + end) // 2
b = [i-mid if i-mid > 0 else 0 for i in tree]
if sum(b) < M:
end = mid - 1
elif sum(b) == M:
start = mid
break
else:
start = mid + 1
print(start)
solution2()
<file_sep>/baekjoon/baekjoon_11053.py
# https://www.acmicpc.net/problem/11053
# baekjoon 11053 : 가장 긴 증가하는 부분 수열
# LEVEL : 실버2
N = int(input())
nums = list(map(int, input().split()))
result = [nums[0]]
for i in range(1, N):
if nums[i] > result[-1]:
result.append(nums[i])
else:
for j in range(len(result)):
if result[j] >= nums[i]:
result[j] = nums[i]
break
print(len(result))
<file_sep>/baekjoon/baekjoon_1826.cpp
// https://www.acmicpc.net/problem/1826
#include <iostream>
#include <set>
#include<cstring>
#include<queue>
using namespace std;
int station[10000][2];
priority_queue<int> pq;
int station_num, length, gas,stop=0;
int main() {
cin >> station_num;
for (int i = 0; i < station_num; i++)
cin >> station[i][0] >> station[i][1]; // 거리, 채울 수 있는 연료의 양
cin >> station[station_num][0] >> gas; // 마을까지의 거리, 트럭에 있는 연료의 양
for (int i = 0; i < station_num; i++) {
if (i == 0)
gas -= station[i][0];
else
gas -= (station[i][0] - station[i - 1][0]);
int need = station[i + 1][0] - station[i][0];
if (need > gas) { // 다음 주유소까지 갈 수 없을 때
gas += station[i][1]; // 연료 충전
stop++;
if (need > gas) {
while (gas < need) {
if (pq.size() > 0) {
gas += pq.top();
pq.pop();
stop++;
}
else {
cout << "-1";
return 0;
}
}
}
}
else {
pq.push(station[i][1]); // 충전하지 않은 연료 양 저장
}
}
cout << stop;
return 0;
}<file_sep>/leetcode/leetcode_3259.py
# https://leetcode.com/explore/learn/card/fun-with-arrays/511/in-place-operations/3259/
# leetcode : Replace Elements with Greatest Element on Right Side
class Solution:
def replaceElements(self, arr: List[int]) -> List[int]:
max_num = -1
for i in range(len(arr)-1, -1, -1):
if arr[i] > max_num:
temp = arr[i]
arr[i] = max_num
max_num = temp
else:
arr[i] = max_num
return arr
<file_sep>/baekjoon/baekjoon_12904.py
# https://www.acmicpc.net/problem/12904
# 백준 12904 : A와 B
# LEVEL : Gold 4
import sys
from collections import deque
input = sys.stdin.readline
def solution():
S = input().rstrip()
T = input().rstrip()
s_length = len(S)
while len(T) > s_length:
if T[-1] == 'A':
T = T[:-1]
else:
T = T[:-1][::-1]
if T == S:
print(1)
else:
print(0)
solution()
<file_sep>/programmers/programmers_60057.cpp
// https://programmers.co.kr/learn/courses/30/lessons/60057
#include <string>
#include <vector>
#include<iostream>
using namespace std;
int solution(string s) {
int min = 1000; // 최소 문자열의 길이 저장
if(s.length() < 3)
return s.length();
for(int cut=1;cut<=s.length()/2;cut++){ // 단위 : 1 ~ 문자열의길이/2 까지
int now = 0;
int count = 1;
string str = s.substr(0,cut);
for(int start=cut;start<s.length()-s.length()%cut;start+=cut){ // 단위 개수씩 확인
if(str != s.substr(start,cut)){ // 현재 substr이랑 앞 문자열이 일치하지 않을 경우
str = s.substr(start,cut);
if(count == 1){ // 앞 문자열이 압축되지 않은 경우
now+=cut;
}else{ // 앞 문자열이 압축되었을 경우
now+=(cut+to_string(count).length());
}
count = 1;
}else{ // 현재 substr이랑 앞 문자열이 일치할 경우
count++;
}
}
if(count != 1) // 마지막에 압축된 문자가 없다면
now+=(cut+to_string(count).length())+s.length()%cut;
else // 있다면
now+=cut+s.length()%cut;
if(min > now){ // 현재 문자열이 최소 길이라면
min = now;
}
}
return min;
}<file_sep>/base/selection_sort.py
def selection_sort(arr):
n = len(arr)
index_min = 0
for i in range(n):
index_min = i
for j in range(i+1, n): # 최소 값의 위치를 찾는다.
if arr[j] < arr[index_min]:
index_min = j
temp = arr[index_min] # 최소값을 해당 자리에 넣는다.
arr[index_min] = arr[i]
arr[i] = temp
print(arr)
selection_sort([5,4,3,2,1])<file_sep>/baekjoon/baekjoon_14235.py
# https://www.acmicpc.net/problem/14235
# 백준 14235 : 크리스마스 선물
# LEVEL : Silver 3
import sys
import heapq
input = sys.stdin.readline
def solution():
N = int(input())
rows = [input().rstrip() for _ in range(N)]
q = []
for row in rows:
if row == "0":
if q:
print(-heapq.heappop(q))
else:
print("-1")
else:
values = list(map(int, row.split()[1:]))
for value in values:
heapq.heappush(q, -value)
solution()<file_sep>/baekjoon/baekjoon_1260.cpp
// https://www.acmicpc.net/problem/1260
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
vector<int> node[1001];
bool check[1001] = { false, };
int N;
vector<int> v;
queue<int> q;
void dfs(int now) {
for (int i = 0; i < node[now].size(); i++) { // 현재 노드와 연결된 노드마다
int n = node[now][i]; // now와 연결된 노드
if (!check[n]) { // 방문하지 않았다면
check[n] = true; // 방문 표시
cout << n << " ";
dfs(n);
}
}
}
void bfs() {
while (q.size() > 0) {
int now = q.front(); q.pop();
for (int i = 0; i < node[now].size(); i++) { // 현재 노드와 연결된 노드마다
int n = node[now][i]; // now와 연결된 노드
if (!check[n]) { // 방문하지 않았다면
q.push(n); // queue에 push
cout << n << " ";
check[n] = true; // 방문 표시
}
}
}
}
int main() {
int M, V; // 정점의 개수, 간선의 개수, 탐색 시작할 정점
cin >> N >> M >> V;
for (int i = 0; i < M; i++) { // 입력
int a, b;
cin >> a >> b;
node[a].push_back(b);
node[b].push_back(a);
}
for (int i = 0; i <= N; i++)
sort(node[i].begin(), node[i].end());
check[V] = true;
// dfs
cout << V << " ";
dfs(V);
cout << "\n";
for (int i = 0; i < 1001; i++) // 방문 초기화
check[i] = false;
check[V] = true;
// bfs
q.push(V);
cout << V << " ";
bfs();
return 0;
}<file_sep>/leetcode/leetcode_53.py
# https://leetcode.com/problems/maximum-subarray/
# leetcode 53 : Maximum Subarray
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
current, max_sum = 0, nums[0]
for num in nums:
current += num
if current > max_sum:
max_sum = current
if current < 0:
current = 0
return max_sum
<file_sep>/programmers/programmers_12945.cpp
// https://programmers.co.kr/learn/courses/30/lessons/12945#qna
#include <string>
#include <vector>
#include <map>
using namespace std;
map<long long,long long> m;
long long fb(long long n){
if(n == 0) return 0;
else if(n==1) return 1;
map<long long,long long>::iterator iter1 = m.find(n-1);
map<long long,long long>::iterator iter2 = m.find(n-2);
return iter1->second + iter2->second;
}
int solution(int n) {
// 반복해서 같은 값을 구해야 하므로 미리 모든 값을 연산하여 저장한다.
for(int i=0;i<n;i++){
m.insert(make_pair(i,fb(i) % 1234567));
}
long long answer = fb(n) % 1234567;
return answer;
}<file_sep>/leetcode/leetcode_17.py
# https://leetcode.com/problems/letter-combinations-of-a-phone-number/
# leetcode 17 : Letter Combinations of a Phone Number
# level : Medium
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if len(digits) == 0:
return []
buttons = {"2": ['a', 'b', 'c'],
"3": ['d', 'e', 'f'],
"4": ['g', 'h', 'i'],
"5": ['j', 'k', 'l'],
"6": ['m', 'n', 'o'],
"7": ['p', 'q', 'r', 's'],
"8": ['t', 'u', 'v'],
"9": ['w', 'x', 'y', 'z']}
combinations = [""]
for digit in digits:
new_combinations = []
for letters in combinations:
for new_letter in buttons[digit]:
new_combinations.append(letters+new_letter)
combinations = new_combinations
return combinations
<file_sep>/README.md
# algorithm
알고리즘 문제 풀이 코드를 올립니다.
<file_sep>/programmers_school/week_1_step_1_2.py
# 1주차 Step1-2. 문제 먼저 직접 풀어보기 "체육복"
def solution(n, lost, reserve):
students = [1] * n
zero = 0
for l in lost:
students[l-1] -= 1
for r in reserve:
students[r-1] += 1
for i in range(n):
if students[i] == 0:
if i != 0 and students[i-1] == 2:
students[i] += 1
students[i-1] -= 1
elif i != n-1 and students[i+1] == 2:
students[i] += 1
students[i+1] -= 1
else:
zero += 1
return n - zero
<file_sep>/programmers_school/week_3_step_1_1.py
from heapq import heapify, heappop, heappush
def solution(scoville, K):
answer = 0
heapify(scoville)
while scoville[0] < K:
if len(scoville) >= 2:
new_scoville = heappop(scoville) + heappop(scoville) * 2
heappush(new_scoville)
answer += 1
else:
return -1
return answer<file_sep>/baekjoon/baekjoon_1806.py
# https://www.acmicpc.net/problem/1806
# 백준 1806 : 부분합
# LEVEL : Gold 4
import sys
input = sys.stdin.readline
def solution():
N, S = map(int, input().split())
nums = list(map(int, input().split()))
for i in range(N-1):
nums[i+1] += nums[i]
start = 0
distance = N + 1
for end in range(N):
while nums[end] - nums[start] >= S:
start += 1
if nums[end] >= S:
distance = min(distance, end-start+1)
if distance == N + 1:
distance = 0
print(distance)
solution()
<file_sep>/programmers/programmers_92341.py
# https://programmers.co.kr/learn/courses/30/lessons/92341
# programmers 92341 : 2022 <NAME> RECRUITMENT - 주차 요금 계산
# LEVEL : 2
def solution(fees, records):
answer = []
inout, time = {}, {}
# 누적 시간 저장만
for record in records:
record = record.split(' ')
if record[2] == 'IN':
inout[record[1]] = record[0]
else:
before = time.get(record[1], 0)
time[record[1]] = before + calc_time(inout[record[1]], record[0])
del inout[record[1]]
# 남은 차들
for car, t in inout.items():
before = time.get(car, 0)
time[car] = before + calc_time(t, '23:59')
print(time[car])
# 요금 계산
time = list(time.items())
time.sort(key=lambda x: x[0])
for car, t in time:
fee, t = fees[1], t-fees[0]
if t > 0:
fee += (t//fees[2]) * fees[3] + (0 if t %
fees[2] == 0 else fees[3])
answer.append(fee)
return answer
def calc_time(t1, t2):
return int(t2[:2])*60 + int(t2[3:]) - int(t1[:2])*60 - int(t1[3:])
fees = [180, 5000, 10, 600]
records = ["05:34 5961 IN", "06:00 0000 IN", "06:34 0000 OUT", "07:59 5961 OUT",
"07:59 0148 IN", "18:59 0000 IN", "19:09 0148 OUT", "22:59 5961 IN", "23:00 5961 OUT"]
print(solution(fees, records))
<file_sep>/programmers/programmers_68645.py
# https://programmers.co.kr/learn/courses/30/lessons/68645
# programmers 68645 : 월간 코드 챌린지 시즌1 - 삼각 달팽이
# LEVEL : 2
def solution(n):
triangle = [[0 for _ in range(i+1)] for i in range(n)]
direct = [(1,0), (0,1), (-1,-1)]
y, x, i = 0, 0, 0
triangle[0][0] = 1
for number in range(2, n*(n+1)//2+1):
if not (0 <= y+direct[i][0] < len(triangle) and 0 <= x+direct[i][1] < len(triangle[y])) or triangle[y+direct[i][0]][x+direct[i][1]] != 0:
i = (i + 1) % 3
y += direct[i][0]
x += direct[i][1]
triangle[y][x] = number
answer = []
for row in triangle:
answer.extend(row)
return answer<file_sep>/baekjoon/baekjoon_2240.py
# https://www.acmicpc.net/problem/2240
# 백준 2240 : 자두나무
# LEVEL : Gold 5
import sys
input = sys.stdin.readline
def solution():
T, W = map(int, input().split())
trees = [int(input()) for _ in range(T)]
dp = [[0 for _ in range(W+1)] for _ in range(T+1)]
for i in range(1, T+1):
tree = trees[i-1]
# 한 번도 움직이지 않은 경우
if tree == 1:
dp[i][0] = dp[i-1][0] + 1
else:
dp[i][0] = dp[i-1][0]
# 이동 횟수를 1번부터 W번까지 움직이면서 체크
for j in range(1, W+1):
if j > i:
break
if (tree == 1 and j % 2 == 0) or (tree == 2 and j % 2 == 1):
dp[i][j] = max(dp[i-1][j], dp[i-1][j-1]) + 1
else:
dp[i][j] = max(dp[i-1][j], dp[i-1][j-1])
print(max(dp[-1]))
solution()<file_sep>/programmers/programmers_12911.py
# https://programmers.co.kr/learn/courses/30/lessons/12911?language=python3
# programmers 12911 : 다음 큰 숫자
# LEVEL : 2
# 지난 풀이. 통과하지만 코드가 더러움 ..
# def solution(n):
# answer = ''
# n = bin(n)
# count_one = 0
# for i in range(len(n)-1, 1, -1):
# if n[i] == '1':
# count_one += 1
# if n[i] == '0' and count_one > 0:
# if count_one == 1:
# return int(n[:i] + '1' + '0'*(len(n)-i-1), 2)
# else:
# return int(n[:i] + '10' + ('1'*(count_one-1)).zfill(len(n)-i-2), 2)
# if count_one == len(n)-2:
# return int('0b10'+('1'*(count_one-1)).zfill(count_one-1), 2)
# else:
# return int('0b10'+('1'*(count_one-1)).zfill(len(n)-count_one-1), 2)
def solution(n):
count = bin(n).count('1')
while bin(n+1).count('1') != count:
n += 1
return n+1
<file_sep>/baekjoon/baekjoon_15954.cpp
#include<iostream>
#include<algorithm>
#include<math.h>
using namespace std;
int prefer[500];
int main() {
int N, K;
cin >> N >> K;
for (int i = 0; i < N; i++)
cin >> prefer[i];
double min = 1000000000;
while (K < N) {
for (int i = 0; i < N - K + 1; i++) { // 1씩 이동하며 모두 확인
// 평균 계산
double mean = 0;
for (int j = i; j < i + K; j++)
mean += prefer[j];
mean /= K;
// 분산 계산
double variance = 0;
for (int j = i; j < i + K; j++)
variance += pow(mean - prefer[j], 2);
variance /= K;
if (variance < min)
min = variance;
}
K++;
}
cout << fixed;
cout.precision(7);
cout << sqrt(min);
return 0;
}<file_sep>/leetcode/leetcode_35.py
# https://leetcode.com/problems/search-insert-position/
# leetcode 35 : Search Insert Position
# LEVEL : Easy
class Solution:
def searchInsert(nums, target) -> int:
start, end = 0, len(nums)
while start < end:
index = (start + end) // 2
if nums[index] == target:
return index
elif nums[index] < target:
start = index + 1
else:
end = index
return end
nums = [1,3,5,6]
target = 2
Solution.searchInsert(nums, target)
<file_sep>/baekjoon/baekjoon_10026.py
# https://www.acmicpc.net/problem/10026
# 백준 10026 : 적록색약
# LEVEL : Gold 4
import sys
from collections import deque
input = sys.stdin.readline
def solution():
N = int(input())
area = [input().rstrip() for _ in range(N)]
directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
visited = [[False for _ in range(N)] for _ in range(N)]
visited_same = [[False for _ in range(N)] for _ in range(N)]
count = 0
count_same = 0
def bfs(i, j):
queue = deque([(i, j)])
while queue:
y, x = queue.popleft()
if visited[y][x]:
continue
visited[y][x] = True
for dy, dx in directions:
ny = y + dy
nx = x + dx
if 0 <= ny < N and 0 <= nx < N and \
area[i][j] == area[ny][nx] and \
not visited[ny][nx]:
queue.append((ny, nx))
for i in range(N):
for j in range(N):
if not visited[i][j]:
count += 1
dfs(i, j)
visited = [[False for _ in range(N)] for _ in range(N)]
for i in range(N):
area[i] = area[i].replace('R','G')
for i in range(N):
for j in range(N):
if not visited[i][j]:
count_same += 1
dfs(i, j)
print(count, count_same)
solution()
<file_sep>/baekjoon/baekjoon_1013.py
# https://www.acmicpc.net/problem/1013
# 백준 1013 : Contact
# LEVEL : Gold 5
import sys
import re
def solution_fullmatch():
T = int(sys.stdin.readline())
for _ in range(T):
pattern = sys.stdin.readline().rstrip()
p = re.compile('(100+1+|01)+')
result = p.fullmatch(pattern)
if result:
print("YES")
else:
print("NO")
def solution():
T = int(sys.stdin.readline())
for _ in range(T):
pattern = sys.stdin.readline().rstrip()
if match(pattern):
print("YES")
else:
print("NO")
def match(pattern):
if len(pattern) == 0:
return True
first_match = re.compile("100+").match(p)
if first_match:
index = first_match.end()
while index < len(pattern) and pattern[index] == '1':
if match(pattern[index+1:]):
return True
index += 1
second_match = re.compile("01").match(pattern)
if second_match:
index = second_match.end()
if match(pattern[index:]):
return True
return False
solution()
<file_sep>/programmers/programmers_72411.py
# https://programmers.co.kr/learn/courses/30/lessons/72411
# programmers : 2021 <NAME> RECRUITMENT - 메뉴 리뉴얼
# LEVEL 2
from itertools import combinations
def solution(orders, course):
answer = []
for i in range(len(orders)):
order = list(orders[i])
order.sort()
orders[i] = ''.join(order)
for food_num in course:
food_dict = {}
for order in orders:
for combination in list(combinations(order, food_num)):
foods = ''.join(combination)
if foods in food_dict.keys():
food_dict[foods] += 1
else:
food_dict[foods] = 1
# print(foods)
print(food_dict)
selected = []
num = 1
for food, count in food_dict.items():
if count > num:
# print(food, end=", ")
selected.clear()
selected.append(food)
num = count
elif count != 1 and count == num:
# print(food, end=", ")
selected.append(food)
print(selected)
answer.extend(selected)
answer.sort()
return answer
def find_same_order(first, second):
order = ""
for c1 in first:
for c2 in second:
if c1 == c2:
order += c1
return order
orders = ["ABCDE", "AB", "CD", "ADE", "XYZ", "XYZ", "ACD"]
course = [2, 3, 5]
solution(orders, course)
<file_sep>/baekjoon/baekjoon_9012.py
# https://www.acmicpc.net/problem/9012
# 백준 9012 : 괄호
# LEVEL : Silver
import sys
def solution():
TC = int(sys.stdin.readline())
for _ in range(TC):
parenthesis = sys.stdin.readline().rstrip()
check = 0
for p in parenthesis:
if p == '(':
check += 1
else:
if check == 0:
print("NO")
break
check -= 1
else:
if check == 0:
print("YES")
else:
print("NO")
solution()<file_sep>/programmers/programmers_64065.py
# https://programmers.co.kr/learn/courses/30/lessons/64065
# programmers 64065 : 2019 카카오 개발자 겨울 인턴십 - 튜플
# LEVEL 2
def solution(s):
answer = []
total_set = s[2:-2].split("},{")
total_set = [sub_set.split(",") for sub_set in total_set]
total_set.sort(key=len)
for sub_set in total_set:
for num in sub_set:
if num not in answer:
answer.append(num)
answer = list(map(int, answer))
return answer
<file_sep>/baekjoon/baekjoon_1238.py
# https://www.acmicpc.net/problem/1238
# 백준 1238 : 파티
# LEVEL : Gold 3
from collections import defaultdict
import heapq
import sys
input = sys.stdin.readline
def solution():
INF = float('inf')
N, M, X = map(int, input().split())
X = X - 1
graph = defaultdict(dict)
answer = [0 for _ in range(N)]
for _ in range(M):
a, b, t = map(int, input().split())
graph[a-1][b-1] = t
for i in range(N):
graph[i][i] = 0
for i in range(N):
distance = [INF for _ in range(N)]
distance[i] = 0
queue = [(0, i)]
while queue:
curr_cost, curr_node = heapq.heappop(queue)
if curr_cost > distance[curr_node]:
continue
for adj_node, adj_cost in graph[curr_node].items():
next_cost = curr_cost + adj_cost
if distance[adj_node] > next_cost:
distance[adj_node] = next_cost
heapq.heappush(queue, (next_cost, adj_node))
if i != X:
answer[i] += distance[X]
else:
for j in range(N):
answer[j] += distance[j]
max_distance = 0
for i in range(N):
max_distance = max(max_distance, answer[i])
print(max_distance)
solution()<file_sep>/leetcode/leetcode_2.py
# https://leetcode.com/problems/add-two-numbers/
# leetcode 2 : Add Two Numbers
# LEVEL : Medium
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
answer = pointer = ListNode()
carry = 0
while l1 or l2:
val1 = val2 = 0
if l1:
val1, l1 = l1.val, l1.next
if l2:
val2, l2 = l2.val, l2.next
sum = val1 + val2 + carry
carry = sum // 10
pointer.next = ListNode(sum % 10)
pointer = pointer.next
if carry > 0:
pointer.next = ListNode(carry)
return answer.next
<file_sep>/programmers/programmers_84512.py
# https://programmers.co.kr/learn/courses/30/lessons/84512
# programmmers 84512 : 위클리 챌린지 - 모음사전
# LEVEL : 2
from itertools import product
def solution(word):
alphabets = ['A', 'E', 'I', 'O', 'U']
words = []
for i in range(1, 6):
for order in product(alphabets, repeat=i):
words.append(''.join(order))
words.sort()
return words.index(word)+1
print(solution("EIO"))<file_sep>/baekjoon/baekjoon_9997.cpp
#include <iostream>
#include <string>
#include <cstring>
#include <math.h>
using namespace std;
int words[25]; // 비트마스크로 표현한 단어들
int full, canTest, N, answer; // full : 모든 단어 포함한 경우, canTest : 모든 알파벳 포함한 경우, N : 단어 개수, answer : 정답
void dfs(int idx, int alphabets) {
// 현재 선택한 단어들로 테스트가 가능한 경우
if (alphabets == canTest) {
answer += pow(2, N - idx); // 나머지 경우의 수 모두 계산
return;
}
// 모두 확인한 경우
if (idx == N)
return;
// 재귀
dfs(idx + 1, alphabets);
dfs(idx + 1, alphabets | words[idx]);
}
int main() {
cin >> N;
memset(words, 0, sizeof(int) * 25);
for (int i = 0; i < N; i++) {
string word;
cin >> word;
for (int j = 0; j < word.length(); j++) { // 단어를 비트마스크로 표현
words[i] |= (1 << (word[j] - 'a'));
}
}
full = (1 << N) - 1;
canTest = (1 << 26) - 1;
dfs(0, 0);
cout << answer << endl;
return 0;
}<file_sep>/leetcode/leetcode_48.py
# https://leetcode.com/problems/rotate-image/
# leetcode 48 : Rotate Image
# LEVEL : Medium
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
for i in range(len(matrix)):
for j in range(i+1, len(matrix)):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
for i in range(len(matrix)):
matrix[i][:] = matrix[i][:][::-1]
<file_sep>/baekjoon/baekjoon_15989.py
# https://www.acmicpc.net/problem/15989
# 백준 15989 : 1,2,3 더하기 4
# LEVEL : Silver 1
import sys
def solution():
T = int(sys.stdin.readline().rstrip())
for _ in range(T):
N = int(sys.stdin.readline().rstrip())
if N <= 3:
print(N)
else:
for i in range(N//3+1):
<file_sep>/leetcode/leetcode_56.java
/*
https://leetcode.com/problems/merge-intervals/
LeetCode 56 : Merge Intervals (Difficulty : Medium)
[문제]
겹치는 구간이 존재하는 2차원 배열(intervals)이 주어질 때,
그 구간들을 모두 병합하여 다시 배열로 반환하라.
[풀이]
intervals를 시작값을 기준으로 정렬한다.
병합할 구간을 저장할 mInterval을 만들어 첫번째 interval을 저장한다.
- 다음, intervals를 순서대로 확인하며 mInterval과 겹치는지 확인한다.
- 겹친다면 두 끝값 중에 max를 mInterval[1]에 저장한다. (시작값은 정렬된 상태이므로 이미 mInterval[0]이 최소값임)
- 겹치지 않으면 지금까지 정한 mInterval을 result에 추가하고,
mInterval을 현재 interval 값으로 갱신한다.
*/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class leetcode_56 {
public int[][] merge(int[][] intervals) {
Arrays.sort(intervals, (o1, o2) -> o1[0] - o2[0]);
int[] mInterval = {intervals[0][0], intervals[0][1]};
List<int[]> result = new ArrayList<>();
for (int i = 1; i < intervals.length; i++) {
if (intervals[i][0] <= mInterval[1]) {
mInterval[1] = Math.max(mInterval[1], intervals[i][1]);
} else {
result.add(mInterval);
mInterval = intervals[i];
}
}
result.add(mInterval);
return result.toArray(new int[result.size()][2]);
}
}
<file_sep>/baekjoon/baekjoon_4949.cpp
#include <iostream>
#include <vector>
#include <string>
using namespace std;
string checkStr(string str) {
vector<char> v;
// 열기 -> 저장, 닫기 -> 마지막으로 연 괄호와 일치하는지 확인
for (int i = 0; i < str.length(); i++) {
if (str[i] == '(' || str[i] == '[') { // 괄호 열기
v.push_back(str[i]);
}
else if (str[i] == ')') { // 괄호 닫기
if (v.size() > 0 && v.back() == '(')
v.pop_back();
else
return "no";
}
else if (str[i] == ']') { // 괄호 닫기
if (v.size() > 0 && v.back() == '[')
v.pop_back();
else {
return "no";
}
}
}
if (v.size() == 0)
return "yes";
else
return "no";
}
int main() {
vector<string> answer;
while (true) {
string str = "", input;
// 한 문장 읽기
while (true) {
getline(cin, input);
str += input;
if (input[input.length() - 1] == '.')
break;
}
if (str == ".")
break;
// 문장 검사
answer.push_back(checkStr(str));
}
for (int i = 0; i < answer.size(); i++) {
cout << answer[i] << endl;
}
return 0;
}
<file_sep>/programmers/programmers_42889.java
// https://programmers.co.kr/learn/courses/30/lessons/42889
// 프로그래머스 42889번 : 2019 KAKAO BLIND RECRUITMENT - 실패율
import java.util.ArrayList;
import java.util.Collections;
public class programmers_42889 {
class Stage implements Comparable<Stage> {
int level;
double rate;
Stage(int l, double r) {
level = l;
rate = r;
}
@Override
public int compareTo(Stage stage) {
if (rate < stage.rate)
return 1;
else if (rate > stage.rate)
return -1;
else
return (level < stage.level ? -1 : 1);
}
}
public int[] solution(int N, int[] stages) {
int[] answer = new int[N];
double[] fail = new double[N];
int len = stages.length;
for (int level = 0; level < N; level++) { // 스테이지마다
for (int player = 0; player < len; player++) { // 플레이어마다
if (stages[player] == level + 1)// 클리어하지 못한 경우
fail[level] += 1;
if (stages[player] > level + 1) // 클리어한 경우
answer[level] += 1;
}
}
ArrayList<Stage> list = new ArrayList<>();
for (int i = 1; i <= N; i++)
list.add(new Stage(i + 1, fail[i] / answer[i]));
Collections.sort(list);
for (int i = 0; i < N; i++)
answer[i] = list.get(i).level;
return answer;
}
}
<file_sep>/baekjoon/baekjoon_2671.py
# https://www.acmicpc.net/problem/2671
# 백준 2671 : 잠수함식별
# LEVEL : Gold 5
import sys
import re
def solution():
sound = sys.stdin.readline().rstrip()
pattern = re.compile('(100+1+|01)+')
if pattern.fullmatch(sound):
print("SUBMARINE")
else:
print("NOISE")
solution()
<file_sep>/programmers/programmers_12905.py
# https://programmers.co.kr/learn/courses/30/lessons/12905
# programmers 12905 : 가장 큰 정사각형 찾기
# LEVEL : 2
def solution(board):
answer = 0
for i in range(1, len(board)):
for j in range(1, len(board[0])):
if board[i][j] == 1:
board[i][j] = min(board[i-1][j-1], board[i-1][j], board[i][j-1]) + 1
for i in range(len(board)):
for j in range(len(board[0])):
answer = max(answer, board[i][j])
return answer*answer<file_sep>/baekjoon/baekjoon_2573.py
# https://www.acmicpc.net/problem/2573
# 백준 2573 : 빙산
# LEVEL : Gold 4
from collections import deque
import sys
input = sys.stdin.readline
def solution():
N, M = map(int, input().split())
area = [list(map(int, input().split())) for _ in range(N)]
DIRECTIONS = [[0, 1], [1, 0], [-1, 0], [0, -1]]
def get_sub_iceberg_size():
size = 1
visited = [[False for _ in range(M)] for _ in range(N)]
for y in range(1, N-1):
for x in range(1, M-1):
if area[y][x] > 0:
queue = deque([(y, x)])
visited[y][x] = True
while queue:
cy, cx = queue.popleft()
for dy, dx in DIRECTIONS:
ny = cy + dy
nx = cx + dx
if area[ny][nx] > 0 and not visited[ny][nx]:
visited[ny][nx] = True
size += 1
queue.append((ny, nx))
return size
return 0
def decrease_and_get_iceberg_num():
decreasing = []
iceberg = 0
for y in range(1, N-1):
for x in range(1, M-1):
if area[y][x] > 0:
water = 0
for dy, dx in DIRECTIONS:
water += (1 if area[y+dy][x+dx] <= 0 else 0)
decreasing.append((y, x, water))
if area[y][x] - water > 0:
iceberg += 1
for y, x, water in decreasing:
area[y][x] -= water
return iceberg
year = 1
while True:
iceberg = decrease_and_get_iceberg_num()
if get_sub_iceberg_size() < iceberg:
print(year)
break
if iceberg == 0:
print(0)
break
year += 1
solution()
<file_sep>/leetcode/leetcode_121.py
# https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
# leetcode 121 : Best Time to Buy and Sell Stock
class Solution:
def maxProfit(self, prices) -> int:
buy, sell, profit = 10001, -1, 0
for price in prices:
if price < buy:
buy = price
if price > sell:
sell = price
if sell - buy > profit:
profit = sell - buy
print(price, profit)
if profit <= 0:
return 0
else:
return profit
prices = [7, 1, 5, 3, 6, 4]
Solution.maxProfit(0, prices)
<file_sep>/baekjoon/baekjoon_1261.py
# https://www.acmicpc.net/problem/1261
# 백준 1261 : 알고스팟
# LEVEL : Gold 4
import sys
from collections import deque
input = sys.stdin.readline
def solution():
INF = float('inf')
direction = [[0, 1], [0, -1], [1, 0], [-1, 0]]
M, N = map(int, input().split())
maze = [list(input().rstrip()) for _ in range(N)]
q = deque([(0, 0)])
distance = [[INF for _ in range(M)] for _ in range(N)]
distance[0][0] = 0
while q:
y, x = q.popleft()
for dy, dx in direction:
ny = y + dy
nx = x + dx
if 0 <= ny < N and 0 <= nx < M and distance[ny][nx] == INF:
if maze[ny][nx] == '1':
q.append((ny, nx))
distance[ny][nx] = distance[y][x] + 1
else:
q.appendleft((ny, nx))
distance[ny][nx] = distance[y][x]
print(distance[N-1][M-1])
solution()
<file_sep>/baekjoon/baekjoon_5052.py
# https://www.acmicpc.net/problem/5052
# 백준 5052 : 전화번호 목록
# LEVEL : Gold 4
import sys
input = sys.stdin.readline
def solution():
TC = int(input())
for _ in range(TC):
N = int(input())
numbers = [input().rstrip() for _ in range(N)]
numbers.sort()
calls = {} # 전화번호 목록
for number in numbers:
for i in range(1, len(number)+1): # 숫자를 하나씩 추가하면서 calls에 있는지 확인한다.
if calls.get(number[:i]): # 있다면 전화가 걸려버리기 때문에 break
break
else: # 모두 확인했는데 없으면 현재 전화번호를 calls에 저장한다.
calls[number] = True
# 위 else문이 실행되지 않은 경우 중간에 전화가 걸린 것이기 때문에 NO
if calls.get(number) == None:
print("NO")
break
else: # 위 경우에서 break되지 않은 경우 YES
print("YES")
solution()<file_sep>/programmers/programmers_72413.py
# https://school.programmers.co.kr/learn/courses/30/lessons/72413
# programmers 72413 : 합승 택시 요금
# LEVEL : 3
def solution(n, s, a, b, fares):
s, a, b = s-1, a-1, b-1
INF = float('inf')
graph = [[INF for _ in range(n)] for _ in range(n)]
for start, end, fare in fares:
graph[start-1][end-1] = fare
graph[end-1][start-1] = fare
for i in range(n):
graph[i][i] = 0
for k in range(n):
for i in range(n):
for j in range(n):
graph[i][j] = min(graph[i][j], graph[i][k] + graph[k][j])
answer = INF
for k in range(n):
answer = min(answer, graph[s][k] + graph[k][a] + graph[k][b])
print(answer, k)
return answer
<file_sep>/leetcode/leetcode_75.py
# https://leetcode.com/problems/sort-colors/
# leetcode 75 : Sort Colors
# LEVEL : Medium
# Solution
# one-pass algorithm으로 풀이하라고 했으므로 요소를 하나씩 탐색하며 움직인다.
# white의 위치를 0부터 확인하는데,
# (1)
# 0(red)인 경우 white의 위치와 red의 위치를 바꾸고
# red index 를 1증가, white index를 1 증가시킨다.
# (2)
# 1(white)인 경우 white index를 1 증가시킨다.
# (3)
# 2(blue)인 경우 blue와 white 위치를 바꾸고, blue의 인덱스를 -1 감소시킨다.
# (blue는 마지막에 있어야 하기 때문에 맨 마지막 인덱스부터 채워 나간다.)
class Solution:
def sortColors(self, nums: List[int]) -> None:
red = 0
white = 0
blue = len(nums)-1
while white <= blue:
if nums[white] == 0:
nums[red], nums[white] = nums[white], nums[red]
red += 1
white += 1
elif nums[white] == 1:
white += 1
else:
nums[white], nums[blue] = nums[blue], nums[white]
blue -= 1<file_sep>/baekjoon/backjoon_2579.java
// https://www.acmicpc.net/problem/2579
// 백준 2579번 : DP - 계단 오르기
// 간단 풀이
// 각 계단의 점수를 입력 받고, (i)계단에서 (i-1)계단에서의 최대 점수와 (i-2)계단에서의 최대 점수를 저장한다.
// 단, (i-1)계단에서 그 (i-2)계단을 밟고 온 경우는 (i)계단을 밟을 수 없으므로 -> 연속 3개 계단을 밟는 경우!
// 그 경우는 제외한다.
import java.util.Scanner;
public class backjoon_2579 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[][] stairs = new int[n + 2][2];
stairs[0][0] = stairs[0][1] = stairs[1][0] = stairs[1][1] = 0;
for (int i = 2; i <= n + 1; i++) {
int num = sc.nextInt();
stairs[i][0] = num + Math.max(stairs[i - 2][0], stairs[i - 2][1]);
stairs[i][1] = num + stairs[i - 1][0];
}
System.out.println(Math.max(stairs[n + 1][0], stairs[n + 1][1]));
}
}
<file_sep>/programmers/programmers_92343.py
# https://school.programmers.co.kr/learn/courses/30/lessons/92343
# programmers 92343 : 2022 KAKAO BLIND RECRUITMENT - 양과 늑대
# LEVEL : 3
def solution(info, edges):
answer = []
visited = [False] * len(info)
visited[0] = 1
def dfs(sheep, wolf):
if sheep > wolf:
answer.append(sheep)
else:
return
for i in range(len(edges)):
parent = edges[i][0]
child = edges[i][1]
is_wolf = info[child]
if visited[parent] and not visited[child]:
visited[child] = True
dfs(sheep+(is_wolf == 0), wolf+(is_wolf == 1))
visited[child] = False
dfs(1, 0)
return max(answer)
<file_sep>/baekjoon/baekjoon_14728.cpp
#include <iostream>
#include <vector>
using namespace std;
int N, T;
int dp[101][100001];
pair<int, int> value[101];
int main() {
cin >> N >> T;
for (int i = 1; i <= N; i++)
cin >> value[i].first >> value[i].second; // first : 예상 공부 시간, second : 배점
for (int i = 1; i <= N; i++) {
for (int limit = 1; limit <= T; limit++) {
dp[i][limit] = dp[i - 1][limit];
if (value[i].first <= limit && (dp[i-1][limit - value[i].first] + value[i].second) > dp[i][limit]) { // i-1번째까지의 값과 i를 담은 값을 비교
dp[i][limit] = dp[i - 1][limit - value[i].first] + value[i].second;
}
}
}
cout << dp[N][T];
return 0;
}<file_sep>/programmers/programmers_92335.py
# https://programmers.co.kr/learn/courses/30/lessons/92335
# programmers 92335 : 2022 KAKAO BLIND RECRUITMENT - K진수에서 소수 개수 구하기
# LEVEL : 2
from math import sqrt
def solution(n, k):
answer = 0
n_base = ''
while n > 0:
n_base += str(n % k)
n //= k
n_base = n_base[::-1]+'0'
start = 0
for i in range(0, len(n_base)):
if n_base[i] == '0':
if start != i and is_prime(int(n_base[start:i])):
answer += 1
start = i+1
return answer
def is_prime(n):
if n == 1:
return False
for i in range(2, int(sqrt(n))+1):
if n % i == 0:
return False
return True
<file_sep>/baekjoon/baekjoon_1541.py
# https://www.acmicpc.net/problem/1541
# 백준 1541 : 잃어버린 괄호
# LEVEL : Silver 2
import sys
def solution():
calculation = sys.stdin.readline().rstrip().split('-')
ans = sum(map(int, calculation[0].split('+')))
for i in range(1, len(calculation)):
ans -= sum(map(int, calculation[i].split('+')))
print(ans)
solution()
<file_sep>/programmers/programmers_12977.py
# https: // programmers.co.kr/learn/courses/30/lessons/12977
# programmers 12977 : Summer/Winter Coding(~2018) - 소수 만들기
# LEVEL 1
def solution(nums):
answer = 0
for i in range(0, len(nums)-2):
for j in range(i+1, len(nums)-1):
for k in range(j+1, len(nums)):
if is_prime(nums[i]+nums[j]+nums[k]):
answer += 1
return answer
def is_prime(num):
for i in range(2, int(num/2)+1):
if num % i == 0:
return False
return True
<file_sep>/programmers/programmers_42890.py
# https://programmers.co.kr/learn/courses/30/lessons/42890
# programmers 42890 : 2019 KAKAO BLIND RECRUITMENT - 후보키
# LEVEL : 2
from itertools import combinations
def solution(relation):
length = len(relation)
keys = []
columns = [str(i) for i in range(len(relation[0]))]
for i in range(1, len(relation[0])+1):
cols_combination = combinations(columns, i)
for cols in cols_combination:
if is_minimality(set(cols), keys):
joined_cols = set()
for tup in relation:
new_tup = ""
for col in cols:
new_tup += tup[int(col)]
joined_cols.add(new_tup)
if len(joined_cols) == length:
keys.append(set(cols))
return len(keys)
def is_minimality(cols, keys):
for key in keys:
if len(key - cols) == 0:
return False
return True
<file_sep>/baekjoon/baekjoon_16120.py
# https://www.acmicpc.net/problem/16120
# 백준 1260 : PPAP
# LEVEL : Gold 4
import sys
def solution():
p = sys.stdin.readline().rstrip()
stack = []
for i in range(len(p)):
stack.append(p[i])
if stack[-4:] == ['P', 'P', 'A', 'P']:
stack.pop()
stack.pop()
stack.pop()
if stack == ['P']:
print("PPAP")
else:
print("NP")
solution()
<file_sep>/baekjoon/baekjoon_4485.py
# https://www.acmicpc.net/problem/4485
# 백준 4485 : 녹색 옷 입은 애가 젤다지?
# LEVEL : Gold 4
import sys
from collections import deque
from heapq import heappop, heappush
def dijkstra(n, graph, cost, y, x):
direction = [(1, 0), (-1, 0), (0, 1), (0, -1)]
pq = []
heappush(pq, (graph[y][x], y, x))
while pq:
curr_cost, curr_y, curr_x = heappop(pq)
if cost[curr_y][curr_x] < curr_cost:
continue
for dy, dx in direction:
ny, nx = curr_y + dy, curr_x + dx
if 0 <= ny < n and 0 <= nx < n:
next_cost = curr_cost + graph[ny][nx]
if next_cost < cost[ny][nx]:
heappush(pq, (next_cost, ny, nx))
cost[ny][nx] = next_cost
return cost[n-1][n-1]
def solution():
tc = 1
while True:
N = int(sys.stdin.readline().rstrip())
if N == 0:
break
graph = [list(map(int, sys.stdin.readline().rstrip().split())) for _ in range(N)]
cost = [[int(1e5)] * N for _ in range(N)]
answer = dijkstra(N, graph, cost, 0, 0)
print(f"Problem {tc}: {answer}")
tc += 1
solution()
<file_sep>/baekjoon/baekjoon_1058.py
# https://www.acmicpc.net/problem/1058
# 백준 1058 : 친구
# LEVEL : Silver 2
import sys
def solution():
N = int(sys.stdin.readline())
graph = [list(sys.stdin.readline().rstrip()) for _ in range(N)]
friends = []
for i in range(N):
friend = set()
for j in range(N):
if graph[i][j] == 'Y':
friend.add(j)
friends.append(friend)
answer = 0
for i in range(N): # 각 사람 i에 대해서
count = friends[i]
for j in range(N):
if i != j and friends[i].intersection(friends[j]):
count.add(j)
answer = max(answer, len(count))
print(answer)
def solution2():
N = int(sys.stdin.readline())
graph = [list(sys.stdin.readline().rstrip()) for _ in range(N)]
friends = []
for i in range(N):
friend = set()
for j in range(N):
if graph[i][j] == 'Y':
friend.add(j)
friends.append(friend)
answer = 0
for person in range(N):
count = friends[person]
for i in range(friend):
count.update(friends)
answer = max(answer, len(count-set([person])))
print(answer)
solution2()
<file_sep>/baekjoon/baekjoon_8958.java
import java.util.Scanner;
public class baekjoon_8958 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testcase = Integer.parseInt(sc.nextLine());
for (int i = 0; i < testcase; i++) {
String input = sc.nextLine();
int score = 1;
int total = 0;
for (int j = 0; j < input.length(); j++) {
if (input.charAt(j) == 'O') {
total += score;
score++;
} else {
score = 1;
}
}
System.out.println(total);
}
}
}
<file_sep>/leetcode/leetcode_169.py
# https://leetcode.com/problems/majority-element/
# leetcode 169 : Majority Element
# LEVEL : Easy
class Solution:
def majorityElement(self, nums: List[int]) -> int:
n = len(nums)
for num in set(nums):
if nums.count(num) > n/2:
return num
<file_sep>/programmers/programmers_70128.py
# https://programmers.co.kr/learn/courses/30/lessons/70128
# programmers 70128 : 월간 코드 챌린지 시즌1 - 내적
# LEVEL1
def solution(a, b):
return sum([x*y for x, y in zip(a, b)])
<file_sep>/leetcode/leetcode_78.py
# https://leetcode.com/problems/subsets/
# leetcode 78 : Subsets
# LEVEL : Medium
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
result = []
def makeSubset(count, subset, index):
if count == 0:
result.append(subset[:])
return
elif index == len(nums):
return
makeSubset(count-1, subset+[nums[index]], index+1)
makeSubset(count, subset, index+1)
for i in range(len(nums)+1):
makeSubset(i, [], 0)
return result
<file_sep>/baekjoon/baekjoon_1157.java
import java.util.Locale;
import java.util.Scanner;
public class baekjoon_1157 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
input = input.toLowerCase(Locale.ROOT);
int CHARACTER_NUM = 26;
int[] count = new int[CHARACTER_NUM];
for (int i = 0; i < input.length(); i++) {
count[input.charAt(i) - 'a'] += 1;
}
int maxIndex = 0;
boolean isSame = false;
for (int i = 1; i < CHARACTER_NUM; i++) {
if (count[i] > count[maxIndex]) {
maxIndex = i;
isSame = false;
} else if (count[i] == count[maxIndex]) {
isSame = true;
}
}
if (isSame)
System.out.println("?");
else
System.out.println((char)('A'+maxIndex));
}
}
<file_sep>/baekjoon/baekjoon_17404.py
# https://www.acmicpc.net/problem/17404
# 백준 17404 : RGB거리 2
# LEVEL : Gold 4
import sys
input = sys.stdin.readline
def solution():
INF = float('inf')
N = int(input())
cost = [list(map(int, input().split())) for _ in range(N)]
answer = INF
for k in range(3):
dp = [[INF, INF, INF] for _ in range(N)]
dp[0][k] = cost[0][k]
for i in range(1, N):
dp[i][0] = cost[i][0] + min(dp[i-1][1], dp[i-1][2])
dp[i][1] = cost[i][1] + min(dp[i-1][0], dp[i-1][2])
dp[i][2] = cost[i][2] + min(dp[i-1][0], dp[i-1][1])
for j in range(3):
if k != j:
answer = min(answer, dp[-1][j])
print(answer)
solution()<file_sep>/baekjoon/baekjoon_1759.py
# https://www.acmicpc.net/problem/1759
# 백준 1759 : 암호 만들기
# LEVEL : Gold 5
import sys
input = sys.stdin.readline
def solution():
VOWEL = ['a', 'e', 'i', 'o', 'u']
L, C = map(int, input().split())
chars = input().rstrip().split()
chars.sort()
visited = [False] * C
passwords = []
def dfs(pw, idx, vowel_cnt):
if len(pw) == L:
if 0 < vowel_cnt <= L-2: # pw의 모음이 1개~L-2개인 경우 (-> 모음이 L-2개 이하이면 자음은 최소 2개 이상이 됨.)
passwords.append(pw)
return
if idx == C: # 문자의 종류를 모두 확인한 경우
return
for i in range(idx, C): # (idx : 이전에 추가한 문자의 위치 + 1) 부터 추가할 수 있도록 한다. (사전순)
if not visited[i]:
visited[i] = True
if chars[i] in VOWEL:
dfs(pw + chars[i], i + 1, vowel_cnt + 1)
else:
dfs(pw + chars[i], i + 1, vowel_cnt)
visited[i] = False
dfs("", 0, 0)
for password in passwords:
print(password)
solution()<file_sep>/leetcode/leetcode_95.py
# https://leetcode.com/problems/unique-binary-search-trees-ii/
# leetcode 95 : Unique Binary Search Trees II
# LEVEL : Medium
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def generateTree(self, start, end):
trees = []
if start > end:
trees.append(None)
return trees
elif start == end:
trees.append(TreeNode(start))
return trees
for i in range(start, end+1):
left_nodes = self.generateTree(start, i-1)
right_nodes = self.generateTree(i+1, end)
for left in left_nodes:
for right in right_nodes:
root = TreeNode(i)
root.left = left
root.right = right
trees.append(root)
return trees
def generateTrees(self, n: int) -> List[Optional[TreeNode]]:
return self.generateTree(1, n)
<file_sep>/leetcode/leetcode_344.py
# https://leetcode.com/problems/reverse-string/
# leetcode 344 : Reverse String
# LEVEL : Medium
class Solution:
def reverseString(self, s: List[str]) -> None:
s.reverse()<file_sep>/baekjoon/baekjoon_7490.py
# https://www.acmicpc.net/problem/7490
# 백준 7490 : 0 만들기
# LEVEL : Gold 5
import sys
def solution():
TC = int(sys.stdin.readline())
for _ in range(TC):
N = int(sys.stdin.readline())
make("1", 2, N)
print()
def make(expression, number, n):
if number > n:
if eval(expression.replace(' ', '')) == 0:
print(expression)
return
make(expression+' '+str(number), number+1, n)
make(expression+'+'+str(number), number+1, n)
make(expression+'-'+str(number), number+1, n)
solution()<file_sep>/baekjoon/baekjoon_2559.py
# https://www.acmicpc.net/problem/2559
# 백준 2559 : 수열
# LEVEL : Silver 3
import sys
def solution():
N, K = map(int, sys.stdin.readline().split())
temp = list(map(int, sys.stdin.readline().split()))
temp.insert(0, 0)
for i in range(1, N+1):
temp[i] += temp[i-1]
answer = (temp[K] - temp[0])
for i in range(K+1, N+1):
if (temp[i] - temp[i-K]) > answer:
answer = (temp[i] - temp[i-K])
print(answer)
solution()
<file_sep>/programmers_school/week_3_step_1_2.py
def solution(N, number):
s = [set() for _ in range(8)]
s[0].add(N)
for i in range(1, 8):
s[i].add(int(str(N)*(i+1)))
for j in range(0, i):
for n1 in s[j]:
for n2 in s[i-j-1]:
s[i].add(n1 + n2)
s[i].add(n1 - n2)
s[i].add(n1 * n2)
if n2 != 0:
s[i].add(n1 // n2)
for i in range(len(s)):
if number in s[i]:
return i+1
return -1
<file_sep>/programmers/programmers_67257.py
# https://programmers.co.kr/learn/courses/30/lessons/67257#
# programmers 67257 : 2020 카카오 인턴십 - 수식 최대화
# LEVEL 2
from itertools import permutations
def calculate(priority, n, expression):
if n == len(priority):
return str(eval(expression))
elif priority[n] == '+':
return str(eval("+".join([calculate(priority, n+1, e) for e in expression.split('+')])))
elif priority[n] == '-':
return str(eval("-".join([calculate(priority, n+1, e) for e in expression.split('-')])))
elif priority[n] == '*':
return str(eval("*".join([calculate(priority, n+1, e) for e in expression.split('*')])))
def solution(expression):
operators = []
result = 0
if '+' in expression:
operators.append('+')
if '-' in expression:
operators.append('-')
if '*' in expression:
operators.append('*')
priorities = permutations(operators, len(operators))
for priority in priorities:
result = max(result, abs(int(calculate(priority, 0, expression))))
return result<file_sep>/baekjoon/baekjoon_4963.py
# https://www.acmicpc.net/problem/4963
# 백준 4963 : 섬의 개수
# LEVEL : Silver 2
import sys
from collections import deque
def solution():
direct_x = [-1, 0, 1]
direct_y = [-1, 0, 1]
while True:
width, height = map(int, sys.stdin.readline().split())
if width == 0 and height == 0: # 입력 종료 조건
return
area = [list(map(int, sys.stdin.readline().split())) for _ in range(height)] # 지도
ans = 0
for i in range(height):
for j in range(width):
if area[i][j] == 1: # 섬을 발견한 경우
q = deque([(i, j)])
while q: # i, j 위치와 이어진 정사각형을 모두 0(바다)로 바꿈
y, x = q.popleft()
if area[y][x] == 0:
continue
area[y][x] = 0
for dy in direct_y: # i,j와 이곳을 둘러싼 8곳을 탐색. 자기 자신은 0(바다)로 바꿨으므로 append 되지 않음
for dx in direct_x:
ny = y + dy
nx = x + dx
if 0 <= ny < height and 0 <= nx < width and area[ny][nx] == 1:
q.append((ny, nx))
ans += 1
print(ans)
solution()
<file_sep>/leetcode/leetcode_148.py
# https://leetcode.com/problems/sort-list/
# leetcode 148 : Sort List
# LEVEL : Medium
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeSort(self, node, length):
if length <= 1:
return node
nodeA = node
for i in range(length//2-1):
node = node.next
nodeB = node.next
node.next = None
nodeA = self.mergeSort(nodeA, length//2)
nodeB = self.mergeSort(nodeB, length-length//2)
return self.merge(nodeA, nodeB)
def merge(self, nodeA, nodeB):
startNode = ListNode()
pointer = startNode
while nodeA != None and nodeB != None:
if nodeA.val < nodeB.val:
pointer.next = nodeA
nodeA = nodeA.next
else:
pointer.next = nodeB
nodeB = nodeB.next
pointer = pointer.next
while nodeA != None:
pointer.next = nodeA
nodeA = nodeA.next
pointer = pointer.next
while nodeB != None:
pointer.next = nodeB
nodeB = nodeB.next
pointer = pointer.next
return startNode.next
def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
length = 0
node = head
while node != None:
length += 1
node = node.next
return self.mergeSort(head, length)
<file_sep>/programmers/programmers_17683.py
# https://programmers.co.kr/learn/courses/30/lessons/17683
# programmers 17683 : 2018 KAKAO BLIND RECRUITMENT - [3차]방금그곡
# LEVEL : 2
def solution(m, musicinfos):
m = replace(m)
answer = [0, '(None)']
for info in musicinfos:
info = info.split(',')
info[3] = replace(info[3])
time = (int(info[1][:2]) * 60 + int(info[1][3:])) - \
(int(info[0][:2]) * 60 + int(info[0][3:]))
title = info[2]
melody = info[3]*(time//len(info[3])) + \
info[3][:(time % len(info[3]))]
print(melody)
if m in melody and time > answer[0]:
answer = [time, title]
return answer[-1]
def replace(str):
return str.replace('C#','c').replace('D#','d').replace('F#','f').replace('G#','g').replace('A#','a')
m = "CC#BCC#BCC#BCC#B"
musicinfos = ["03:00,03:30,FOO,CC#B", "04:00,04:08,BAR,CC#BCC#BCC#B"]
print(solution(m, musicinfos))
<file_sep>/baekjoon/baekjoon_19598.py
# https://www.acmicpc.net/problem/19598
# 백준 19598 : 최소 회의실 개수
# LEVEL : Gold 5
import sys
from heapq import heappop, heappush
def solution():
N = int(sys.stdin.readline().rstrip())
times = [list(map(int, sys.stdin.readline().split())) for _ in range(N)]
times.sort(key=lambda x : (x[0], x[1]))
rooms = [0]
for start, end in times:
room = heappop(rooms)
if room > start:
heappush(rooms, room)
heappush(rooms, end)
print(len(rooms))
solution()
<file_sep>/programmers/programmers_81303.py
# https://programmers.co.kr/learn/courses/30/lessons/81303
# programmers 71303 : 2021 카카오 채용연계형 인턴십 - 표 편집
# LEVEL : 3
def solution(n, k, cmd):
answer = ['O'] * n
table = {i : [i-1, i+1] for i in range(n)}
remove = []
for c in cmd:
if c == "C":
remove.append([k, table[k][0], table[k][1]])
if table[k][0] != -1:
table[table[k][0]][1] = table[k][1]
if table[k][1] != n:
table[table[k][1]][0] = table[k][0]
k = table[k][1]
else:
k = table[k][0]
elif c == 'Z':
removed, left, right = remove.pop()
if left != -1:
table[left][1] = removed
if right != n:
table[right][0] = removed
else:
c = c.split(' ')
if c[0] == 'U':
for _ in range(int(c[1])):
k = table[k][0]
else:
for _ in range(int(c[1])):
k = table[k][1]
for i in range(len(remove)):
answer[remove[i][0]] = 'X'
return ''.join(answer)
cmd = ["D 2","C","U 3","C","D 4","C","U 2","Z","Z"]
n = 8
k = 2
print(solution(n, k, cmd))<file_sep>/baekjoon/baekjoon_2252.cpp
#include <iostream>
#include <vector>
#include <string>
#include <queue>
using namespace std;
int main() {
int N, M;
cin >> N >> M;
vector<vector<int>> connect;
vector<int> v;
connect.assign(N+1, v);
vector<int> link;
link.assign(N + 1, 0);
queue<int> q;
// 연결 정보 입력
while (M--) {
int A, B;
cin >> A >> B;
connect[A].push_back(B);
link[B]++;
}
// 앞 순서가 없는 학생 push
for (int i = 1; i <= N; i++)
if (!link[i])
q.push(i);
while(!q.empty()) {
int front = q.front();
q.pop();
for (int i = 0; i < connect[front].size(); i++) {
int B = connect[front][i];
if ((--link[B]) == 0) {
q.push(B);
}
}
cout << front << " ";
}
return 0;
}<file_sep>/baekjoon/baekjoon_1926.py
# https://www.acmicpc.net/problem/1926
# 백준 1926 : 그림
# LEVEL : Silver 1
import sys
from collections import deque
input = sys.stdin.readline
def solution():
n, m = map(int, input().split())
paper = [list(map(int, input().split())) for _ in range(n)]
directions = [[0, 1], [1, 0], [-1, 0], [0, -1]]
paintings = [0]
def calculate_area(y, x):
paper[y][x] = 0
cnt = 1
q = deque([(y, x)])
while q:
check_y, check_x = q.popleft()
for dy, dx in directions:
ny = check_y + dy
nx = check_x + dx
if 0 <= ny < n and 0 <= nx < m and paper[ny][nx] == 1:
paper[ny][nx] = 0
cnt += 1
q.append((ny, nx))
return cnt
for i in range(n):
for j in range(m):
if paper[i][j] == 1:
paintings.append(calculate_area(i, j))
print(len(paintings)-1)
print(max(paintings))
solution()
<file_sep>/baekjoon/baekjoon_6603.py
# https://www.acmicpc.net/problem/6603
# 백준 6603 : 로또
# LEVEL : Silver 2
import sys
from itertools import combinations
input = sys.stdin.readline
def solution():
while True:
nums = input().rstrip()
if nums == "0":
break
nums = list(map(int, nums.split()))[1:]
cases = list(combinations(nums, 6))
for case in cases:
for n in case:
print(n, end=" ")
print()
print()
solution()
<file_sep>/baekjoon/baekjoon_1270.py
# https://www.acmicpc.net/problem/1270
# 백준 1270 : 전쟁 - 땅따먹기
# LEVEL : Silver 3
import sys
from collections import defaultdict
def solution():
N = int(sys.stdin.readline())
for _ in range(N):
row = list(map(int, sys.stdin.readline().split()))
half_soldier, nums = row[0]//2, row[1:]
count = defaultdict(int)
for num in nums:
count[num] += 1
state = "SYJKGW"
for key, value in count.items():
if value > half_soldier:
state = key
break
print(state)
solution()<file_sep>/baekjoon/baekjoon_9375.py
# https://www.acmicpc.net/problem/9375
# 백준 9375 : 패션왕 신해빈
# LEVEL : Silver 3
import sys
from collections import defaultdict
def solution():
TC = int(sys.stdin.readline())
for _ in range(TC):
clothes = defaultdict(set)
N = int(sys.stdin.readline())
for _ in range(N):
cname, ctype = sys.stdin.readline().rstrip().split()
clothes[ctype].add(cname)
answer = 1
for names in clothes.values():
answer *= (len(names)+1)
print(answer - 1)
solution()
<file_sep>/baekjoon/baekjoon_11726.java
// https://www.acmicpc.net/problem/11726
// 백준 11726번 : 2*n 타일링
import java.util.Scanner;
public class baekjoon_11726 {
static int[] way;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
way = new int[n + 1];
way[0] = way[1] = 1;
for (int i = 2; i <= n; i++) {
way[i] = (way[i - 1] + way[i - 2]) % 10007;
}
System.out.println(way[n]);
}
}
<file_sep>/codility/codility_YNJ5JV-7C9.py
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A, B):
letters = ""
while A > 0 or B > 0:
if A > B:
if letters[-2:] == 'aa':
letters += 'b'
B -= 1
else:
letters += 'a'
A -= 1
else:
if letters[-2:] == 'bb':
letters += 'a'
A -= 1
else:
letters += 'b'
B -= 1
return letters
<file_sep>/leetcode/leetcode_3270.py
# https://leetcode.com/explore/learn/card/fun-with-arrays/523/conclusion/3270/
# leetcode 3270 : Find All Numbers Disappeared in an Array
class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
exists = [False for i in range(len(nums))]
for num in range(nums):
exists[num-1] = True
answer = []
for idx, is_exist in enumerate(exists):
if not is_exist:
answer.append(idx+1)
return answer
<file_sep>/leetcode/leetcode_923.py
# https://leetcode.com/problems/3sum-with-multiplicity/
# leetcode 923 : 3Sum With Multiplicity
# LEVEL : Medium
import collections
import itertools
class Solution:
def threeSumMulti(self, arr: List[int], target: int) -> int:
maximum = 10**9 + 7
c = collections.Counter(arr)
answer = 0
for i, j in itertools.combinations_with_replacement(c, 2):
k = target - i - j
if i == j == k:
answer += (c[i] * (c[j] - 1) * (c[k] - 2) / 6) % maximum
elif i == j != k:
answer += (c[i] * (c[j] - 1) * c[k] / 2) % maximum
elif k > i and k > j:
answer += (c[i] * c[j] * c[k]) % maximum
return int(answer)<file_sep>/programmers/programmers_17680.py
# https://programmers.co.kr/learn/courses/30/lessons/17680
# programmers 17680 : 2018 KAKAO BLIND RECRUITMENT - [1차]캐시
# LEVEL : 2
def solution(cacheSize, cities):
if cacheSize == 0:
return len(cities) * 5
cities = [c.lower() for c in cities]
cache = []
time = 0
for city in cities:
if city in cache:
cache.remove(city)
cache.insert(0, city)
time += 1
else:
if len(cache) < cacheSize:
cache.insert(0, city)
else:
cache.pop()
cache.insert(0, city)
time += 5
return time
solution(3, ["Jeju", "Pangyo", "Seoul", "NewYork", "LA", "Jeju", "Pangyo", "Seoul", "NewYork", "LA"])<file_sep>/programmers/programmers_42884.py
# https://programmers.co.kr/learn/courses/30/lessons/42884?language=python3
# programmers 42884 : 단속카메라
# LEVEL : 3
def solution(routes):
answer = 0
routes.sort(key=lambda x: x[0], reverse=True)
camera = 30001
for route in routes:
if camera > route[1]:
answer += 1
camera = route[0]
return answer<file_sep>/baekjoon/baekjoon_1388.py
# https://www.acmicpc.net/problem/1388
# 백준 1388 : 바닥 장식
# LEVEL : Silver 3
import sys
def solution():
direct = {'-': [0, 1], '|': [1, 0]}
VISITED = '.'
N, M = map(int, sys.stdin.readline().split())
floor = [list(sys.stdin.readline().rstrip()) for _ in range(N)]
ans = 0
for i in range(N):
for j in range(M):
if floor[i][j] != VISITED:
ans += 1
shape = floor[i][j]
next_y, next_x = i, j
while 0 <= next_y < N and 0 <= next_x < M and \
floor[next_y][next_x] == shape:
floor[next_y][next_x] = VISITED
next_y += direct[shape][0]
next_x += direct[shape][1]
print(ans)
solution()
<file_sep>/leetcode/leetcode_160.py
# https://leetcode.com/problems/intersection-of-two-linked-lists/
# leetcode 160 : Intersection of Two Linked Lists
# LEVEL : Easy
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def moveNode(self, node: ListNode, number: int):
for i in range(number):
node = node.next
return node
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
lengthA, lengthB = 1, 1
nodeA, nodeB = headA, headB
while nodeA.next != None:
lengthA += 1
nodeA = nodeA.next
while nodeB.next != None:
lengthB += 1
nodeB = nodeB.next
if nodeA != nodeB:
return None
else:
if lengthA < lengthB:
headB = self.moveNode(headB, lengthB-lengthA)
else:
headA = self.moveNode(headA, lengthA-lengthB)
while headA != None:
if headA == headB:
return headA
headA = headA.next
headB = headB.next
<file_sep>/baekjoon/baekjoon_2468.cpp
#include <iostream>
#include <set>
#include<cstring>
using namespace std;
int N;
int area[100][100];
bool visited[100][100];
int dx[4] = { 0,0,1,-1 };
int dy[4] = { 1,-1,0,0 };
void dfs(int x, int y,int h) {
if (visited[y][x]) // 이미 방문한 지역인 경우
return;
visited[y][x] = true; // 방문 체크
for (int i = 0; i < 4; i++) { // 상하좌우 탐색
int nx = x + dx[i];
int ny = y + dy[i];
if (nx >= 0 && nx < N && ny >= 0 && ny < N) // 경계 안
if (area[ny][nx] > h) // 안전 영역일 때 탐색
dfs(nx, ny, h);
}
}
int main() {
set<int> rain_list;
int max = 1;
// 입력
cin >> N;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cin >> area[i][j];
rain_list.insert(area[i][j]);
}
}
//비의 양에 따라
for (set<int>::iterator rain = rain_list.begin(); rain != rain_list.end(); ++rain) {
memset(visited, false, sizeof(visited));
int count = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (area[i][j] > *rain && !visited[i][j]) {
dfs(j,i,*rain);
count++;
}
}
}
//cout << "rain : " << *rain << ", count : " << count << endl;
if (count > max)
max = count;
}
cout << max;
return 0;
}<file_sep>/baekjoon/baekjoon_2839.py
# https://www.acmicpc.net/problem/2839
# 백준 2839 : 설탕 배달
# LEVEL : Silver 4
import sys
def solution():
MAX_NUM = 5000
N = int(sys.stdin.readline())
dp = [MAX_NUM] * (N+1)
dp[N] = 0
for num in range(N, 2, -1):
if num >= 5:
dp[num-5] = min(dp[num-5], dp[num] + 1)
dp[num-3] = min(dp[num-3], dp[num]+1)
if dp[0] == MAX_NUM:
print("-1")
else:
print(dp[0])
def solution2():
N = int(sys.stdin.readline())
count = 0
while N >= 0:
if N % 5 == 0:
count += (N//5)
print(count)
break
N -= 3
count += 1
else:
print(-1)
solution2()
<file_sep>/baekjoon/baekjoon_1253.py
# https://www.acmicpc.net/problem/1253
# 백준 1253 : 좋다
# LEVEL : Gold 4
import sys
from collections import defaultdict
input = sys.stdin.readline
def solution():
N = int(input())
A = list(map(int, input().split()))
A.sort()
count = 0
for i in range(N):
arr = A[:i] + A[i+1:]
target = A[i]
start = 0
end = len(arr)-1
while start < end:
num = arr[start] + arr[end]
if num == target:
count += 1
break
if num > target:
end -= 1
else:
start += 1
print(count)
solution()<file_sep>/baekjoon/baekjoon_1654.py
# https://www.acmicpc.net/problem/1654
# 백준 1654 : 랜선 자르기
# LEVEL : Silver 2
import sys
def solution():
K, N = map(int, sys.stdin.readline().split())
rows = [int(sys.stdin.readline()) for _ in range(K)]
rows.sort(reverse=True)
start = 1
end = max(rows)
while start <= end:
mid = (start + end) // 2
count = sum([row//mid for row in rows])
if count >= N:
start = mid + 1
else:
end = mid - 1
print(end)
solution()
<file_sep>/leetcode/leetcode_39.py
# https://leetcode.com/problems/combination-sum/
# leetcode 39 : Combination Sum
# LEVEL : Medium
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
answer = []
def findSum(remain, numbers, start):
if remain == 0:
answer.append(numbers)
return
elif remain < 0:
return
for i in range(start, len(candidates)):
findSum(remain-candidates[i], numbers+[candidates[i]], i)
findSum(target, [], 0)
return answer
Solution.combinationSum(0, [2, 3, 6, 7], 7)
<file_sep>/baekjoon/baekjoon_11721.java
import java.util.Scanner;
public class baekjoon_11721 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
int length = input.length();
for(int i=0;i<=length-10;i+=10){
System.out.println(input.substring(i,i+10));
}
System.out.println(input.substring(length/10*10));
}
}
<file_sep>/programmers/programmers_68935.py
# https://programmers.co.kr/learn/courses/30/lessons/68935
# programmers 68935 : 월간 코드 챌린지 시즌1 - 3진법 뒤집기
# LEVEL 1
def solution(n):
number = ""
while(n > 0):
number += str(n % 3)
n //= 3
return int(number, 3)
<file_sep>/baekjoon/baekjoon_1072.py
# https://www.acmicpc.net/problem/1072
# 백준 1072 : 게임
# LEVEL : Silver 3
import sys
def solution():
X, Y = map(int, sys.stdin.readline().split())
current_rate = (Y * 100) // X
if current_rate >= 99:
print(-1)
else:
start, end = 1, X
while start <= end:
mid = (start + end) // 2
rate = (Y + mid) * 100 // (X + mid)
if rate > current_rate:
end = mid - 1
else:
start = mid + 1
print(end + 1)
solution()
<file_sep>/leetcode/leetcode_739.py
# https://leetcode.com/problems/daily-temperatures/
# leetcode 739 : Daily Temperatures
# LEVEL : Medium
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
stack = []
result = [0 for _ in range(len(temperatures))]
for i in range(len(temperatures)):
while stack and temperatures[stack[-1]] < temperatures[i]:
result[stack[-1]] = i - stack[-1]
stack.pop()
stack.append(i)
return result
<file_sep>/leetcode/leetcode_3260.py
# https://leetcode.com/explore/learn/card/fun-with-arrays/511/in-place-operations/3260/
# leetcode : Sort Array By Parity
class Solution:
def sortArrayByParity(self, nums: List[int]) -> List[int]:
even = []
odd = []
for num in nums:
if num % 2 == 0:
even.append(num)
else:
odd.append(num)
return even+odd
<file_sep>/baekjoon/baekjoon_17615.py
# https://www.acmicpc.net/problem/17615
# 백준 17615 : 볼 모으기
# LEVEL : Silver 1
import sys
def solution():
N = int(sys.stdin.readline().rstrip())
balls = sys.stdin.readline().rstrip()
blue = balls.count('B')
red = N - blue
ans = N
part = balls.rstrip('B')
ans = min(ans, blue - (N - len(part)))
part = balls.rstrip('R')
ans = min(ans, red - (N - len(part)))
part = balls.lstrip('B')
ans = min(ans, blue - (N - len(part)))
part = balls.lstrip('R')
ans = min(ans, red - (N - len(part)))
print(ans)
solution()
# def solution():
# N = int(sys.stdin.readline().rstrip())
# balls = sys.stdin.readline().rstrip()
# blue = balls.count("B")
# red = N-blue
# if N == 1 or blue == 0 or red == 0:
# print('0')
# return
# count = N
# for left in range(1, N):
# if balls[0] != balls[left]:
# if balls[0] == 'B':
# count = min(count, blue-left)
# else:
# count = min(count, red-left)
# break
# for right in range(N-2, -1, -1):
# if balls[N-1] != balls[right]:
# if balls[N-1] == 'B':
# count = min(count, right+1-red)
# else:
# count = min(count, right+1-blue)
# break
# if balls[0] == balls[N-1]:
# count = min(count, min(blue, red))
# print(count)
<file_sep>/base/quick_sort.py
from array import array
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot, tail = arr[0], arr[1:]
left_arr = [x for x in tail if x <= pivot] # pivot보다 작거나 같은 원소들
right_arr = [x for x in tail if x > pivot] # pivot보다 큰 원소들
return quick_sort(left_arr) + [pivot] + quick_sort(right_arr)
def quick_sort2(arr, left, right):
if (left >= right):
return
pi = partition(arr, left, right)
quick_sort2(arr, left, pi-1)
quick_sort2(arr, pi+1, right)
def partition(arr, left, right):
mid = (left + right) // 2
swap(arr, left, mid)
pivot = array[left]
i, j = left, right
while i < j:
while pivot < arr[j]:
j -= 1
while i < j and pivot >= arr[i]:
i += 1
swap(arr, i, j)
arr[left] = arr[i]
arr[i] = pivot
return i
def swap(arr, i, j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
<file_sep>/baekjoon/baekjoon_1520.cpp
#include <iostream>
using namespace std;
int height, width;
int area[500][500];
int way[500][500];
int dx[4] = { 0,0,1,-1 };
int dy[4] = { 1, -1, 0,0 };
int findWay(int y, int x) {
// 기저사례
if (y >= height || y < 0 || x >= width || x < 0) // 지역 이탈
return 0;
else if (y == height - 1 && x == width - 1) // 목적지 도착
return 1;
else if (way[y][x] != -1) // 이미 탐색했던 지역인 경우
return way[y][x];
// 탐색
int count = 0;
int before = area[y][x];
way[y][x] = 0;
for (int i = 0; i < 4; i++) {
int sy = y + dy[i];
int sx = x + dx[i];
if (area[sy][sx] < before) {
count += findWay(sy, sx);
}
}
way[y][x] = count;
return count;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
//입력
cin >> height >> width;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
cin >> area[i][j];
way[i][j] = -1;
}
}
cout << findWay(0, 0);
return 0;
}<file_sep>/leetcode/leetcode_55.py
# https://leetcode.com/problems/jump-game/
# leetcode 55 : Jump Game
# LEVEL : Medium
class Solution:
def canJump(self, nums: List[int]) -> bool:
jump = len(nums)-1
for i in range(len(nums)-1, -1, -1):
if i + nums[i] >= jump:
jump = i
return jump == 0<file_sep>/programmers/programmers_60058.cpp
// https://programmers.co.kr/learn/courses/30/lessons/60058
#include <string>
#include <vector>
using namespace std;
string recursive(string str){
string u,v;
if(str.empty()){ // 빈 문자열인 경우
return "";
}
int check = 0;
for(int i=0;i<str.length();i++){
if(str[i] == '(') check++;
else check--;
if(check == 0){ // 균형잡힌 괄호 문자열인 경우
u = str.substr(0,i+1);
v = str.substr(i+1,str.length()-i-1);
for(int j=0;j<u.length();j++){
if(str[j] == '(') check++;
else check--;
if(check < 0){ // u가 "올바른 괄호 문자열"이 아닐 경우
v = "("+recursive(v)+")";
for(int k=1;k<u.length()-1;k++){
if(u[k] == '(') v += ')';
else v += '(';
}
return v;
}
}
// u가 "올바른 괄호 문자열"인 경우
return u+recursive(v);
}
}
}
string solution(string p){
return recursive(p);
}<file_sep>/leetcode/leetcode_881.py
# https: // leetcode.com/problems/boats-to-save-people/
# leetcode 881 : Boats to Save People
# LEVEL : Medium
class Solution:
def numRescueBoats(self, people: List[int], limit: int) -> int:
people.sort()
light = 0
heavy = len(people)-1
boats = 0
while light < heavy:
if people[light] + people[heavy] <= limit:
light += 1
heavy -= 1
else:
heavy -= 1
boats += 1
if light != heavy:
return boats
else:
return boats + 1
<file_sep>/baekjoon/baekjoon_1484.py
# https://www.acmicpc.net/problem/1484
# 백준 1484 : 다이어트
# LEVEL : Gold 5
import sys
def solution():
G = int(sys.stdin.readline())
answer = []
now = 2
before = 1
while True:
diff = now*now - before*before
if before + 1 == now and diff > G:
break
if diff == G:
answer.append(now)
before += 1
now += 1
elif diff > G:
before += 1
else:
now += 1
if not answer:
print(-1)
else:
for a in answer:
print(a)
solution()
<file_sep>/leetcode/leetcode_121.java
/*
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
LeetCode : Best Time to Buy and Sell Stock (Difficulty : Easy)
[문제]
물건을 구매하고 되파는데 최대의 이익은 얼마인가?
[간단 풀이]
profit : 최대 이익
min : 최소 price
prices[i] 와 min 과의 차이가 profit 보다 큰 경우 그 차이 값을 profit 에 저장한다.
이후 prices[i] 가 min 보다 작은 경우 그 값을 min 에 저장한다.
*/
public class leetcode_121 {
public int maxProfit(int[] prices) {
int profit = 0;
int min = prices[0];
for (int i = 1; i < prices.length; i++) {
if (prices[i] - min > profit)
profit = prices[i] - min;
if (prices[i] < min)
min = prices[i];
}
return profit;
}
}
<file_sep>/programmers/programmers_67256.py
# https://school.programmers.co.kr/learn/courses/30/lessons/67256
# programmers 67275 : 2020 카카오 인턴십 - 키패드 누르기
# LEVEL : 1
def get_loc(number):
if number == "*":
return [3, 0]
elif number == "#":
return [3, 2]
elif number == 0:
return [3, 1]
else:
return [(number-1)//3, (number-1) % 3]
def solution(numbers, hand):
answer = ''
use = {1: 'L', 4: 'L', 7: 'L', 3: 'R', 6: 'R',
9: 'R', 2: 'M', 5: 'M', 8: 'M', 0: 'M'}
hand_use = {"left": 'L', "right": "R"}
left, right = "*", "#"
for number in numbers:
if use[number] == "M":
l_loc, r_loc, n_loc = get_loc(
left), get_loc(right), get_loc(number)
l_dist, r_dist = abs(
l_loc[0]-n_loc[0])+abs(l_loc[1]-n_loc[1]), abs(r_loc[0]-n_loc[0])+abs(r_loc[1]-n_loc[1])
if l_dist == r_dist:
answer += hand_use[hand]
if hand == "left":
left = number
else:
right = number
elif l_dist < r_dist:
answer += 'L'
left = number
else:
answer += 'R'
right = number
else:
answer += use[number]
if use[number] == "L":
left = number
else:
right = number
return answer
print(solution([7, 0, 8, 2, 8, 3, 1, 5, 7, 6, 2], "left"))
<file_sep>/programmers/programmers_72414.py
# https: // programmers.co.kr/learn/courses/30/lessons/72414?language = python3
# programmers 72414 : 2021 KAKAO BLIND RECRUITMENT - 광고 삽입
def solution(play_time, adv_time, logs):
if play_time == adv_time:
return "00:00:00"
play_time, adv_time = str_to_sec(play_time), str_to_sec(adv_time)
time = [0] * (play_time+1)
for log in logs:
[start_time, end_time] = log.split('-')
start_time = str_to_sec(start_time)
end_time = str_to_sec(end_time)
time[start_time] += 1
time[end_time] -= 1
for i in range(1, len(time)):
time[i] += time[i-1]
for i in range(1, len(time)):
time[i] += time[i-1]
max_time, max_index = time[adv_time], 0
for i in range(adv_time, play_time):
total_time = time[i] - time[i-adv_time]
if total_time > max_time:
max_time = total_time
max_index = i - adv_time + 1
return sec_to_str(max_index)
def str_to_sec(time):
[hour, minute, second] = list(map(int, time.split(':')))
return hour * 3600 + minute * 60 + second
def sec_to_str(sec):
hour = sec // 3600
minute = (sec // 60) % 60
second = sec % 60
return str(hour).zfill(2) + ":" + str(minute).zfill(2) + ":" + str(second).zfill(2)
<file_sep>/baekjoon/baekjoon_1932.java
// https://www.acmicpc.net/problem/1932
// 백준 1932번 : DP - 정수 삼각형
// 간단 풀이
// 조건 : 아래층에 있는 수는 현채 층에서 선택된 수의 대각선 왼쪽 또는 대각선 오른쪽에 있는 것 중에서만 선택할 수 있다.
// 해석 : [현재층](i)(j)층에서는 [아래층](i+1)(j) or (i+1)(j+1) 중 하나를 선택할 수 있다.
// -> 이를 아래층의 입장에서 해석해보면 (아래층을 i,j)
// : (i)(j)층에서는 (i-1)(j) or (i-1)(j-1) 중 하나를 지나올 수 있다.
import java.util.Scanner;
public class baekjoon_1932 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[][] floor = new int[n + 1][n + 1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
floor[i][j] = sc.nextInt();
floor[i][j] += Math.max(floor[i - 1][j], floor[i - 1][j - 1]);
}
}
int max = 0;
for (int num : floor[n])
if (num > max)
max = num;
System.out.println(max);
}
}
<file_sep>/baekjoon/baekjoon_2504.py
# https://www.acmicpc.net/problem/2504
# 백준 2504 : 괄호의 값
# LEVEL : Silver 1
import sys
input = sys.stdin.readline
def solution():
arr = input().rstrip()
result = 0
temp = 1
stack = []
for i in range(len(arr)):
if arr[i] == '(':
temp *= 2
stack.append(arr[i])
elif arr[i] == '[':
temp *= 3
stack.append(arr[i])
elif arr[i] == ')':
if stack and stack[-1] == '(':
if arr[i-1] == '(':
result += temp
temp //= 2
stack.pop()
else:
result = 0
break
else:
if stack and stack[-1] == '[':
if arr[i-1] == '[':
result += temp
temp //= 3
stack.pop()
else:
result = 0
break
if stack:
result = 0
print(result)
solution()
<file_sep>/baekjoon/baekjoon_4358.py
# https://www.acmicpc.net/problem/4358
# 백준 4358 : 생태학
# LEVEL : Silver 2
import sys
from collections import defaultdict
def solution():
trees = defaultdict(int)
tree_num = 0
while True:
name = sys.stdin.readline().rstrip()
if name == "":
break
trees[name] += 1
tree_num += 1
names = sorted(trees.keys())
for name in names:
# print(f"{name} {round(trees[name]*100/tree_num, 4)}")
print('%s %.4f' %(name, (trees[name]/tree_num*100)))
solution()
# print(round(2.255, 2))
# print(round(2.265, 2))<file_sep>/baekjoon/baekjoon_4948.py
# https://www.acmicpc.net/problem/4948
# 백준 4948 : 베르트랑 공준
# LEVEL : Silver 3
import sys
from math import sqrt
def solution():
MAX_INDEX = 123456 * 2
primes = [0] * (MAX_INDEX + 1)
primes[1] = 1
for i in range(2, MAX_INDEX + 1):
primes[i] += primes[i-1]
if is_prime(i):
primes[i] += 1
while True:
N = int(sys.stdin.readline())
if N == 0:
return
print(primes[N*2] - primes[N])
def is_prime(n):
if n <= 2:
return 1
for i in range(2, int(sqrt(n))+1):
if n % i == 0:
return False
return True
solution()
<file_sep>/baekjoon/baekjoon_11659.py
# https://www.acmicpc.net/problem/11659
# 백준 11659 : 구간 합 구하기 4
# LEVEL : Silver 3
import sys
def solution():
[N, M] = list(map(int, sys.stdin.readline().rstrip().split()))
nums = list(map(int, sys.stdin.readline().rstrip().split()))
part_sum = [0] + nums.copy()
for i in range(1, N+1):
part_sum[i] += part_sum[i-1]
for _ in range(M):
[start, end] = list(map(int, sys.stdin.readline().rstrip().split()))
print(part_sum[end] - part_sum[start-1])
solution()<file_sep>/baekjoon/baekjoon_11509.py
# https://www.acmicpc.net/problem/11509
# 백준 11509 : 풍선 맞추기
# LEVEL : Gold 5
import sys
input = sys.stdin.readline
def solution():
N = int(input())
heights = list(map(int, input().split()))
arrows = [0] * (1000001)
for h in heights:
if arrows[h] == 0:
arrows[h-1] += 1
else:
arrows[h] -= 1
arrows[h-1] += 1
print(sum(arrows))
solution()<file_sep>/baekjoon/baekjoon_1520.py
# https://www.acmicpc.net/problem/1520
# 백준 1520 : 내리막 길
# LEVEL : Gold 3
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)
def solution():
direction = [[-1, 0], [1, 0], [0, -1], [0, 1]]
M, N = map(int, input().split()) # 세로크기, 가로크기
area = [list(map(int, input().split())) for _ in range(M)]
dp = [[-1 for _ in range(N)] for _ in range(M)]
def dfs(y, x):
if y == M-1 and x == N-1:
return 1
if dp[y][x] != -1:
return dp[y][x]
dp[y][x] = 0
for dy, dx in direction:
ny = y + dy
nx = x + dx
if 0 <= ny < M and 0 <= nx < N and area[ny][nx] < area[y][x]:
dp[y][x] += dfs(ny, nx)
return dp[y][x]
print(dfs(0, 0))
solution()
<file_sep>/programmers/programmers_67258.py
# https://programmers.co.kr/learn/courses/30/lessons/67258
# programmers 67258 : 2020 카카오 인턴십 - 보석 쇼핑
# LEVEL : 3
def solution(gems):
answer = [0, len(gems)]
types = set(gems)
count = {}
start = 0
for end in range(len(gems)):
count[gems[end]] = count.get(gems[end], 0) + 1
if len(count) == len(types):
while count[gems[start]] > 1:
count[gems[start]] -= 1
start += 1
if end - start < answer[1] - answer[0]:
answer[0], answer[1] = start+1, end+1
return answer
<file_sep>/leetcode/leetcode_3250.py
# https://leetcode.com/explore/learn/card/fun-with-arrays/527/searching-for-items-in-an-array/3250/
# leetcode : Check If N and Its Double Exist
class Solution:
def checkIfExist(self, arr: List[int]) -> bool:
for i in range(len(arr)-1):
for j in range(i+1, len(arr)):
if arr[i]*2 == arr[j] or arr[j]*2 == arr[i]:
return True
return False
<file_sep>/leetcode/leetcode_22.py
# https://leetcode.com/problems/generate-parentheses/submissions/
# leetcode 22 : Generate Parentheses
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
p = {"(": 1}
for i in range(2*n-1, 0, -1):
new_p = {}
for key, value in p.items():
if value == 0:
new_p[key+"("] = value+1
elif i-value > 0:
new_p[key+"("] = value+1
new_p[key+")"] = value-1
else:
new_p[key+")"] = value-1
p = new_p
return new_p.keys()
<file_sep>/programmers/programmers_12973.py
# https://programmers.co.kr/learn/courses/30/lessons/12973
# programmers 12973 : 2017 팁스타운 - 짝지어 제거하기
# LEVEL 2
def solution(s):
stack = [s[0], ]
for i in range(1, len(s)):
if len(stack) > 0 and stack[-1] == s[i]:
stack.pop()
else:
stack.append(s[i])
if len(stack) > 0:
return 0
else:
return 1
<file_sep>/leetcode/leetcode_70.py
# https://leetcode.com/problems/climbing-stairs/
# leetcode 70 : Climbing Stairs
class Solution:
def climbStairs(self, n: int) -> int:
if n <= 2:
return n
a, b = 1, 2
for i in range(2, n):
ways = a + b
a = b
b = ways
return b
Solution.climbStairs(0, 3)
<file_sep>/programmers/programmers_42888.java
// https://programmers.co.kr/learn/courses/30/lessons/42888
// 프로그래머스 42888번 : 2019 KAKAO BLIND RECRUITMENT - 오픈채팅방
import java.util.HashMap;
public class programmers_42888 {
public static String[] solution(String[] record) {
int len = record.length;
int ENTER = 0, LEAVE = 1, CHANGE = 2;
HashMap<String, String> userMap = new HashMap<>(); // MAP : Id, Nickname
String[] userID = new String[len];
Integer[] userPerform = new Integer[len]; // Enter(0) or Leave(1) or Change(2)
int EnterAndLeave = 0; // ENTER, LEAVE 횟수
for (int i = 0; i < len; i++) {
String[] command = record[i].split(" ");
if (command[0].equals("Enter")) {
userMap.put(command[1], command[2]);
userPerform[i] = ENTER;
EnterAndLeave++;
} else if (command[0].equals("Change")) {
userMap.put(command[1], command[2]);
userPerform[i] = CHANGE;
} else { // Leave
userPerform[i] = LEAVE;
EnterAndLeave++;
}
userID[i] = command[1];
}
String[] answer = new String[EnterAndLeave];
String[] perform = {"들어왔습니다.", "나갔습니다."};
int count = 0;
for (int i = 0; i < len; i++) {
if (userPerform[i] != CHANGE) {
answer[count++] = userMap.get(userID[i]) + "님이 " + perform[userPerform[i]];
}
}
return answer;
}
public static void main(String[] args) {
String[] record = {"Enter uid1234 Muzi", "Enter uid4567 Prodo", "Leave uid1234", "Enter uid1234 Prodo", "Change uid4567 Ryan"};
solution(record);
}
}
<file_sep>/programmers/programmers_17676.py
# https://programmers.co.kr/learn/courses/30/lessons/17676
# programmers 17676 : 2018 KAKAO BLIND RECRUITMENT - [1차] 추석 트래픽
# LEVEL : 3
def solution(lines):
answer = 1
timeline = []
for log in lines:
log = log.split(' ')
end = (int(log[1][:2]) * 3600 +
int(log[1][3:5]) * 60 + float(log[1][6:]))*1000
start = end - float(log[2][:-1])*1000 + 1
timeline.append((int(start), int(end)))
timeline.sort(key=lambda x: x[0])
for i in range(1, len(timeline)):
count = 1
for j in range(i):
if timeline[j][1]+999 >= timeline[i][0]:
count += 1
answer = max(answer, count)
return answer
<file_sep>/baekjoon/baekjoon_1463.py
# https://www.acmicpc.net/problem/1463
# 백준 1463 : 1로 만들기
# LEVEL : Silver 3
import sys
def solution():
N = int(sys.stdin.readline())
dp = [N for _ in range(N+1)]
dp[N] = 0
for num in range(N, 0, -1):
if dp[num] != N:
if num % 3 == 0:
dp[num//3] = min(dp[num//3], dp[num]+1)
if num % 2 == 0:
dp[num//2] = min(dp[num//2], dp[num]+1)
dp[num-1] = min(dp[num-1], dp[num]+1)
print(dp[1])
solution()
<file_sep>/leetcode/leetcode_33.py
# https://leetcode.com/problems/search-in-rotated-sorted-array/
# leetcode 33 : Search in Rotated Sorted Array
# LEVEL : Medium
class Solution:
def search(self, nums: List[int], target: int) -> int:
def find(left, right):
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
if nums[mid] < nums[right]: # right sorted array
if nums[mid] < target <= nums[right]:
left = mid + 1
else:
right = mid - 1
else: # left sorted array
if nums[left] <= target < nums[mid]:
right = mid - 1
else:
left = mid + 1
return -1
return find(0, len(nums)-1)
<file_sep>/baekjoon/baekjoon_1932.py
# https://www.acmicpc.net/problem/1932
# 백준 1932 : 정수 삼각형
# LEVEL : Silver 2
import sys
def solution():
N = int(sys.stdin.readline())
triangle = [list(map(int, sys.stdin.readline().split()))
for _ in range(N)]
for floor in range(1, N):
for i in range(floor+1):
if i == 0:
triangle[floor][i] += triangle[floor-1][i]
elif i == floor:
triangle[floor][i] += triangle[floor-1][i-1]
else:
triangle[floor][i] += max(triangle[floor-1]
[i-1], triangle[floor-1][i])
print(max(triangle[N-1]))
solution()
<file_sep>/baekjoon/baekjoon_21921.py
# https://www.acmicpc.net/problem/21921
# 백준 21921 : 블로그
# LEVEL : Silver 3
import sys
input = sys.stdin.readline
def solution():
N, X = map(int, input().split())
nums = list(map(int, input().split()))
total = sum(nums[:X])
answer = total
same = 1
for i in range(N-X):
total -= nums[i]
total += nums[i+X]
if total > answer:
answer = total
same = 1
elif total == answer:
same += 1
if answer == 0:
print("SAD")
else:
print(answer)
print(same)
solution()<file_sep>/baekjoon/baekjoon_22233.py
# https://www.acmicpc.net/problem/22233
# baekjoon 22233 : 가희와 키워드
# LEVEL : Silver 2
import sys
from collections import defaultdict
def solution():
[N, M] = list(map(int, sys.stdin.readline().rstrip().split()))
memo = defaultdict(int)
count = N
for _ in range(N):
memo[sys.stdin.readline().rstrip()] += 1
for _ in range(M):
keywords = sys.stdin.readline().rstrip().split(',')
for keyword in keywords:
if memo[keyword] > 0:
memo[keyword] -= 1
count -= 1
print(count)
solution()<file_sep>/baekjoon/baekjoon_1753.py
# https://www.acmicpc.net/problem/1753
# 백준 1753 : 최단경로
# LEVEL : Gold 4
import sys
import heapq
def solution():
INF = float('inf')
V, E = map(int, sys.stdin.readline().split())
start = int(sys.stdin.readline()) - 1
distances = [INF] * V
graph = [[] for _ in range(V)]
for _ in range(E):
s, e, w = map(int, sys.stdin.readline().split())
graph[s-1].append((e-1, w))
def dijkstra(start):
queue = []
heapq.heappush(queue, (0, start))
distances[start] = 0
while queue:
curr_distance, curr_destination = heapq.heappop(queue)
if curr_distance > distances[curr_destination]:
continue
for new_destination, new_distance in graph[curr_destination]:
distance = curr_distance + new_distance
if distance < distances[new_destination]:
distances[new_destination] = distance
heapq.heappush(queue, (distance, new_destination))
dijkstra(start)
for d in distances:
print(d if d != INF else "INF")
solution()
<file_sep>/leetcode/leetcode_1089.java
// https://leetcode.com/explore/learn/card/fun-with-arrays/525/inserting-items-into-an-array/3245/
// Problem : Duplicate Zeros
class Solution {
public void duplicateZeros(int[] arr) {
int len = arr.length;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 0) {
for (int j = len - 1; j > i + 1; j--) {
arr[j] = arr[j - 1];
}
if (i != len - 1)
arr[i + 1] = 0;
i++;
}
}
}
}<file_sep>/leetcode/leetcode_435.java
/*
https://leetcode.com/problems/non-overlapping-intervals/
LeetCode 435 : Non-overlapping Intervals
[문제]
intervals[i] = [start(i), end(i)] 형태로 주어지는 2차원 배열(intervals)가 주어질 때,
겹치는 구간이 발생하지 않도록 하기 위해 삭제해야 하는 구간의 최소 수를 구하여라.
[풀이]
intervals를 start(i)를 기준으로 오름차순 정렬한다.
구간이 -20000 ~ 20000 이기 때문에 인덱스 참조를 위해 20000을 더해준다.
- start가 비어있다면 해당 구간을 저장한다.
- start가 비어있지 않다면 겹치는 구간이 발생한 것이므로,
1) end가 가장 큰 값이라면 해당 구간을 삭제한다.
2) 아니라면 해당 구간 대신 가장 긴 값을 삭제한다. (현재 구간과 겹치는 구간)
여기서, intervals는 start를 기준으로 정렬되어 있기 때문에
(해당 구간의 start, 가장 긴 end) 사이의 구간만 삭제해도 무방하다.
-> 삭제하는 경우의 수를 저장하여 반환한다.
*/
import java.util.Arrays;
public class leetcode_435 {
public int eraseOverlapIntervals(int[][] intervals) {
Arrays.sort(intervals, (o1, o2) -> o1[0] - o2[0]);
boolean[] exist = new boolean[40002];
int end = 0, count = 0;
for (int i = 0; i < intervals.length; i++) {
intervals[i][0] += 20000;
intervals[i][1] += 20000;
if (!exist[intervals[i][0]]) { // 존재하지 않으면
for (int j = intervals[i][0]; j < intervals[i][1]; j++)
exist[j] = true;
end = intervals[i][1];
} else if (intervals[i][1] < end) { // 현재 interval이 전보다 더 짧으면
for (int j = intervals[i][1]; j < end; j++)
exist[j] = false;
count++;
} else {
count++;
}
}
return count;
}
}
<file_sep>/leetcode/leetcode_3251.py
# https://leetcode.com/explore/learn/card/fun-with-arrays/527/searching-for-items-in-an-array/3251/
# leetcode : Valid Mountain Array
class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
top = -1
for i in range(len(arr)-1):
if arr[i] >= arr[i+1]:
top = i
break
if top == 0:
return False
for i in range(top, len(arr)-1):
if arr[i] <= arr[i+1]:
return False
return True
<file_sep>/baekjoon/baekjoon_1446.py
# https://www.acmicpc.net/problem/1446
# 백준 1446 : 지름길
# LEVEL : Silver 1
import sys
from collections import defaultdict
import heapq
def solution():
N, D = map(int, sys.stdin.readline().split()) # N:지름길개수, D:고속도로길이
roads = defaultdict(dict)
fast_destination = []
for _ in range(N): # {지름길 시작위치 : {도착위치1:거리1, 도착위치2:거리, ...}}
start, end, weight = map(int, sys.stdin.readline().split())
roads[start][end] = min(roads[start].get(end, float("inf")), weight)
fast_destination.append(end) # 지름길 도착 위치를 따로 저장
memo = [i for i in range(10001)]
for start in range(D+1):
# 현재 위치 전에 지름길이 존재할 때
for destination in fast_destination:
if destination <= start:
memo[start] = min(memo[start], memo[destination] + (start-destination)) # 지름길을 거쳐오는 길이의 최솟값을 저장
# 현재 위치부터 시작하는 지름길이 존재할 때
for end, length in roads[start].items():
memo[end] = min(memo[end], memo[start] + length) # 지름길의 도착 위치에 최솟값을 저장
print(memo[D])
def solution_dijkstra():
N, D = map(int, sys.stdin.readline().split()) # N:지름길개수, D:고속도로길이
# {지름길 시작위치 : {도착위치1:거리1, 도착위치2:거리, ...}}
graph = {i: {i+1: 1} for i in range(D+1)}
distance = [sys.maxsize] * (D+1)
distance[0] = 0
for _ in range(N):
start, end, length = map(int, sys.stdin.readline().split())
if end <= D:
graph[start][end] = length
queue = []
heapq.heappush(queue, (0, 0))
while queue:
start, length = heapq.heappop(queue)
if length > distance[start]:
continue
for end, next_length in graph[start].items():
cost = length + next_length
if cost < distance[end]:
distance[end] = cost
heapq.heappush(queue, (end, cost))
print(distance[D])
solution_dijkstra()
<file_sep>/leetcode/leetcode_543.py
# https://leetcode.com/problems/diameter-of-binary-tree/
# leetcode 543 : Diameter of Binary Tree
# LEVEL : Easy
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
longest:int=0
def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
def dfs(node):
if not node:
return -1
left = dfs(node.left)
right = dfs(node.right)
self.longest = max(self.longest, left+right+2)
return max(left, right) + 1
dfs(root)
return self.longest
<file_sep>/programmers/programmers_17684.py
# https://programmers.co.kr/learn/courses/30/lessons/17684
# programmers 17684 : 2018 K<NAME> RECRUITMENT - [3차] 압축
# LEVEL : 2
def solution(msg):
answer = []
dict = {chr(e + 64): e for e in range(1, 27)}
msg += 'x'
start, new_index = 0, 27
for i in range(len(msg)):
if dict.get(msg[start:i+1]) == None:
answer.append(dict[msg[start:i]])
dict[msg[ start:i+1]] = new_index
new_index += 1
start = i
return answer<file_sep>/leetcode/leetcode_215.py
# https://leetcode.com/problems/kth-largest-element-in-an-array/
# leetcode 215 : Kth Largest Element in an Array
# LEVEL : Medium
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
return sorted(nums)[len(nums)-k]
<file_sep>/leetcode/leetcode_45.py
# https://leetcode.com/problems/jump-game-ii/
# leetcode 45 : Jump Game II
# LEVEL : Medium
class Solution:
def jump(self, nums: List[int]) -> int:
length = len(nums)
count = [10000] * len(nums)
count[length-1] = 0
jump = -1
for i in range(len(nums)-2, -1, -1):
if nums[i] > 0:
count[i] = min(count[i+1:i+nums[i]+1]) + 1
return count[0]
<file_sep>/leetcode/leetcode_98.py
# https://leetcode.com/problems/validate-binary-search-tree/
# leetcode 98 : Validate Binary Search Tree
# LEVEL : Medium
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
return self.isValid(root.left, -2**31-1, root.val) and self.isValid(root.right, root.val, 2**31)
def isValid(self, node, min, max):
if not node:
return True
if min < node.val < max:
return self.isValid(node.left, min, node.val) and self.isValid(node.right, node.val, max)
else:
return False
<file_sep>/leetcode/leetcode_24.py
# https://leetcode.com/problems/swap-nodes-in-pairs/
# leetcode 24 : Swap Nodes in Pairs
# LEVEL : Medium
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
answer = head.next
node1 = ListNode(0, head)
while node1.next and node1.next.next:
node2 = node1.next
node3 = node2.next
node4 = node3.next
node2.next = node4
node3.next = node2
node1.next = node3
node1 = node2
return answer
<file_sep>/programmers/programmers_42583.java
// https://programmers.co.kr/learn/courses/30/lessons/42583
// 프로그래머스 42583번 : 다리를 지나는 트럭
import java.util.LinkedList;
import java.util.Queue;
public class programmers_42583 {
class Truck {
int weight;
int location;
public Truck(int w, int l) {
weight = w;
location = l;
}
public void move() {
location += 1;
}
}
Queue<Truck> bridge;
public int solution(int bridge_length, int weight, int[] truck_weights) {
int answer = 0;
bridge = new LinkedList<>();
int sum = 0, idx = 0, truck_num = truck_weights.length;
for (int time = 0; ; time++) {
// 제일 앞에 있는 트럭 위치 확인
if (time != 0 && bridge.peek().location == bridge_length) {
sum -= bridge.peek().weight;
bridge.remove();
}
// 트럭들의 위치 + 1
for (Truck t : bridge)
t.move();
// 트럭 추가
if (idx < truck_num && sum + truck_weights[idx] <= weight) {
sum += truck_weights[idx];
bridge.add(new Truck(truck_weights[idx], 1));
idx += 1;
}
// 트럭이 모두 지나간 경우
if (bridge.isEmpty()) {
answer = time + 1;
break;
}
}
return answer;
}
}
<file_sep>/programmers/programmers_49191.py
# https://programmers.co.kr/learn/courses/30/lessons/49191
# programmers 49191 : 그래프 - 순위
# LEVEL : 3
from collections import defaultdict
def solution(n, results):
answer = 0
win_graph = defaultdict(set)
lose_graph = defaultdict(set)
for result in results:
win_graph[result[0]].add(result[1])
lose_graph[result[1]].add(result[0])
for player in range(1, n+1):
for win_player in lose_graph[player]:
win_graph[win_player].update(win_graph[player])
for lose_player in win_graph[player]:
lose_graph[lose_player].update(lose_graph[player])
for player in range(1, n+1):
if len(win_graph[player]) + len(lose_graph[player]) == n-1:
answer += 1
return answer
<file_sep>/leetcode/leetcode_101.py
# https://leetcode.com/problems/symmetric-tree/
# leetcode 101 : Symmetric Tree
# LEVEL : Easy
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
left_q = [root.left]
right_q = [root.right]
while left_q and right_q:
left_node = left_q.pop(0)
right_node = right_q.pop(0)
if not left_node and not right_node:
continue
if not left_node or not right_node:
return False
if left_node.val != right_node.val:
return False
left_q.append(left_node.left)
left_q.append(left_node.right)
right_q.append(right_node.right)
right_q.append(right_node.left)
return True
<file_sep>/baekjoon/baekjoon_1003.java
// https://www.acmicpc.net/problem/1003
// 백준 1003 : 피보나치 함수
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class baekjoon_1003 {
static int[] dp0, dp1;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
dp0 = new int[41];
dp1 = new int[41];
dp0[0] = 1;
dp0[1] = 0;
dp1[0] = 0;
dp1[1] = 1;
for (int i = 2; i < 41; i++) {
dp0[i] = dp0[i - 1] + dp0[i - 2];
dp1[i] = dp1[i - 1] + dp1[i - 2];
}
int T = Integer.parseInt(br.readLine());
for (int i = 0; i < T; i++) {
int num = Integer.parseInt(br.readLine());
System.out.println(dp0[num] + " " + dp1[num]);
}
}
}
<file_sep>/baekjoon/baekjoon_12865.py
# https://www.acmicpc.net/problem/12865
# 백준 12865 : 평범한 배낭
# LEVEL : Gold 5
import sys
input = sys.stdin.readline
def solution():
N, K = map(int, input().split())
stuff = [[0, 0]]
for _ in range(N):
stuff.append(list(map(int, input().split())))
dp = [[0] * (K + 1) for _ in range(N + 1)]
for i in range(1, N+1): # i : 물건 종류
weight, value = stuff[i]
for j in range(K+1): # j : 현재 무게
if j < weight:
dp[i][j] = dp[i-1][j]
else:
dp[i][j] = max(dp[i-1][j], dp[i-1][j-weight]+value)
print(dp[N][K])
solution()<file_sep>/baekjoon/baekjoon_1325.py
# https://www.acmicpc.net/problem/1325
# 백준 1325 : 효율적인 해킹
# LEVEL : Silver 1
import sys
from collections import defaultdict, deque
def solution():
def bfs(num):
visited = [False] * (N + 1)
visited[num] = True
q = deque([num])
count = 1
while q:
computer = q.popleft()
for neighbor in graph[computer].keys():
if not visited[neighbor]:
visited[neighbor] = True
count += 1
q.append(neighbor)
return count
N, M = map(int, sys.stdin.readline().split())
graph = defaultdict(dict)
for _ in range(M):
a, b = map(int, sys.stdin.readline().split())
graph[b][a] = True
hackings = []
max_hacking = 0
for i in range(1, N+1):
hacking = bfs(i)
hackings.append((hacking, i))
max_hacking = max(max_hacking, hacking)
for hacking, computer in hackings:
if hacking == max_hacking:
print(computer, end=' ')
solution()
<file_sep>/programmers/programmers_42628.py
import heapq
# https://programmers.co.kr/learn/courses/30/lessons/42628?language=python3#
# programmers 42628 : 힙(heap) - 이중우선순위큐
# LEVEL : 3
def solution(operations):
answer = []
hq, rhq = [], []
count = 0
for op in operations:
[command, number] = op.split(' ')
if command == 'I':
heapq.heappush(hq, int(number))
heapq.heappush(rhq, -int(number))
count += 1
else:
if len(hq) + len(rhq) > count:
if number == '1':
heapq.heappop(rhq)
else:
heapq.heappop(hq)
count -= 1
if count == 0:
hq, rhq = [], []
if count > 0:
return [-rhq[0], hq[0]]
else:
return [0, 0]
return answer<file_sep>/programmers/programmers_1845.py
# https://programmers.co.kr/learn/courses/30/lessons/1845
# programmers 1845 : 찾아라 프로그래밍 마에스터 - 폰켓몬
# LEVEL 1
def solution(nums):
return min(len(nums)/2, len(set(nums)))
<file_sep>/leetcode/leetcode_3247.py
# https://leetcode.com/explore/learn/card/fun-with-arrays/526/deleting-items-from-an-array/3247/
# leetcode 3247 : Remove Element
class Solution:
def removeElement(nums, val) -> int:
while nums.count(val):
nums.remove(val)
return len(nums)
<file_sep>/programmers/programmers_43164.py
# https://programmers.co.kr/learn/courses/30/lessons/43164?language=python3#
# programmers 43164 : 여행 경로
# LEVEL : 3
from collections import defaultdict
def solution(tickets):
answer = []
route = defaultdict(list)
for ticket in tickets:
route[ticket[0]].append(ticket[1])
for values in route.values():
values.sort(reverse=True)
stack = ["ICN"]
while stack:
if not route[stack[-1]]:
answer.append(stack.pop())
else:
stack.append(route[stack[-1]].pop())
answer.reverse()
return answer
<file_sep>/baekjoon/baekjoon_11725.py
# https://www.acmicpc.net/problem/11725
# 백준 11725 : 트리의 부모 찾기
# LEVEL : Silver 2
import sys
from collections import defaultdict, deque
def solution():
N = int(sys.stdin.readline())
edges = defaultdict(dict)
parents = [-1 for _ in range(N+1)]
for _ in range(N-1):
first, second = map(int, sys.stdin.readline().split())
edges[first][second] = True
edges[second][first] = True
queue = deque([(1, 0)])
while queue:
node, parent = queue.popleft()
parents[node] = parent
for child in edges[node].keys():
if child != parent:
queue.append((child, node))
for i in range(2, N+1):
print(parents[i])
solution()
<file_sep>/baekjoon/baekjoon_1015.py
# https://www.acmicpc.net/problem/1015
# 백준 1015 : 수열 정렬
# LEVEL : Silver 4
import sys
def solution():
N = int(sys.stdin.readline())
list_a = list(map(int, sys.stdin.readline().split()))
index_a = [i for i in range(N)]
for i in range(N):
for j in range(N-i-1):
if list_a[j] > list_a[j+1]:
list_a[j], list_a[j+1] = list_a[j+1], list_a[j]
index_a[j], index_a[j+1] = index_a[j+1], index_a[j]
for i in range(N):
if i == N-1:
print(index_a.index(i), end='')
else:
print(index_a.index(i), end=' ')
solution()<file_sep>/baekjoon/baekjoon_20364.py
# https://www.acmicpc.net/problem/20364
# 백준 20364 : 부동산 다툼
# LEVEL : Silver 2
import sys
def solution():
N, Q = map(int, sys.stdin.readline().split())
nums = [int(sys.stdin.readline()) for _ in range(Q)]
visited = [False] * (N+1)
for i in range(Q):
answer = 0
target = nums[i]
while target:
if visited[target]:
answer = target
target //= 2
if answer == 0:
visited[nums[i]] = True
print(answer)
solution()<file_sep>/programmers_school/week_1_step_1_3.py
# 1주차 Step1-3. 문제 먼저 직접 풀어보기 "가장 큰 수"
from functools import cmp_to_key
def solution(numbers):
numbers = sorted([str(n) for n in numbers], key=cmp_to_key(compare))
return int("".join(numbers)
def compare(a, b):
if int(a+b) > int(b+a):
return -1
else:
return 1
print(solution([3, 30, 34, 5, 9]))
print(solution([6, 10, 2]))
print(solution([0, 10, 6]))
print(solution([0, 0, 0, 0]))
<file_sep>/leetcode/leetcode_11.py
# https://leetcode.com/problems/container-with-most-water/
# leetcode 11 : Container With Most Water
# LEVEL : Medium
# two pointer를 통해 해결.
# 첫번째와 마지막 height의 container를 계산하고
# 둘 중 height가 더 작은 곳을 움직여가며
# max_congtainer를 계산한다.
class Solution:
def maxArea(self, height: List[int]) -> int:
start, end = 0, len(height)-1
max_container = 0
while start != end:
container = (end-start)*min(height[start], height[end])
max_container = max(container, max_container)
if height[start] < height[end]:
start += 1
else:
end -= 1
return max_container
<file_sep>/programmers/programmers_72412.py
# https://programmers.co.kr/learn/courses/30/lessons/72412
# programmers : 2021 <NAME> - 순위 검색
# LEVEL : 2
# 지원자 정보의 종류가 많지 않으므로,
# dictionary를 활용하여 모든 경우의 수에 해당 점수를 리스트로 추가하고
# query의 정보를 dictionary에서 찾아, 점수 리스트를 이분탐색 방법으로 확인한다.
from itertools import combinations
def solution(info, query):
answer = []
option = {}
for applicant in info:
applicant = applicant.split(' ')
for i in range(5):
for c in combinations(applicant[:-1], i):
c = "".join(c)
if option.get(c) is None:
option[c] = [int(applicant[-1])]
else:
option[c].append(int(applicant[-1]))
for value in option.values():
value.sort()
for q in query:
q = q.split(' ')
q_score = int(q[-1])
q_option = "".join(q[:-1]).replace('and', '').replace('-', '')
scores = option.get(q_option)
if scores is None:
answer.append(0)
else:
start, end = 0, len(scores)
while start < end:
mid = (start + end) // 2
if scores[mid] >= q_score:
end = mid
else:
start = mid + 1
answer.append(len(scores)-start)
return answer
info = ["java backend junior pizza 150", "python frontend senior chicken 210", "python frontend senior chicken 150",
"cpp backend senior pizza 260", "java backend junior chicken 80", "python backend senior chicken 50"]
query = ["java and backend and junior and pizza 100", "python and frontend and senior and chicken 200",
"cpp and - and senior and pizza 250", "- and backend and senior and - 150", "- and - and - and chicken 100", "- and - and - and - 150"]
print(solution(info, query))
<file_sep>/baekjoon/baekjoon_2447.cpp
#include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<vector<bool>> square;
void star(int n, int row, int col) { // 재귀 함수
int size = n / 3;
if (n != 1) {
for (int i = 0; i < 3; i++) { // 9개의 공간으로 나누어 각각 재귀 함수 실행. 가운데 제외
for (int j = 0; j < 3; j++) {
if (!(i == 1 && j == 1)) {
star(size, i * size+row, j * size+col);
}
}
}
for (int i = size; i < size * 2; i++) // 가운데 false로 채우기
for (int j = size; j < size * 2; j++)
square[row + i][col + j] = false;
}
}
int main() {
int N;
cin >> N;
vector<bool> v;
v.assign(N, true);
square.assign(N, v);
star(N/3, 0, 0);
// CODE 1
//for (int i = 0; i < N; i++) {
// for (int j = 0; j < N; j++)
// cout << (square[i][j] ? "*" : " ");
// cout << "\n";
//}
// CODE 2
for (int i = 0; i < 3; i++) {
if (i != 1) {
for (int a = 0; a < N / 3; a++) {
for (int r = 0; r < 3; r++) {
for (int b = 0; b < N / 3; b++) {
cout << (square[a][b] ? "*" : " ");
}
}
cout << "\n";
}
}
else {
for (int a = 0; a < N / 3; a++) {
for (int r = 0; r < 3; r++) {
if (r != 1) {
for (int b = 0; b < N / 3; b++) {
cout << (square[a][b] ? "*" : " ");
}
}
else {
for (int b = 0; b < N / 3; b++) {
cout << " ";
}
}
}
cout << "\n";
}
}
}
return 0;
}
<file_sep>/programmers/programmers_17686.py
# https://programmers.co.kr/learn/courses/30/lessons/17686
# programmers 17686 : 2018 KAKAO BLIND RECRUITMENT - [3차]파일명 정렬
# LEVEL : 2
import re
def solution(files):
answer = []
for file in files:
head, number, tail = "", "", ""
for i in range(len(file)):
if file[i].isdigit():
head = file[:i]
number = file[i:]
for j in range(i+1, len(file)):
if not file[j].isdigit():
number = file[i:j]
tail = file[j:]
break
break
answer.append((head, number, tail))
answer = sorted(answer, key=lambda x: (x[0].lower(), int(x[1])))
return ["".join(a) for a in answer]
<file_sep>/baekjoon/baekjoon_1912.py
# https://www.acmicpc.net/problem/1912
# baekjoon 1912 : 연속합
# LEVEL : 실버2
length = int(input())
nums = list(map(int, input().split()))
for i in range(1, length):
if nums[i-1] > 0:
nums[i] += nums[i-1]
print(max(nums))<file_sep>/baekjoon/baekjoon_15831.py
# https://www.acmicpc.net/problem/15831
# 백준 15831 : 준표의 조약돌
# LEVEL : Gold 4
import sys
input = sys.stdin.readline
def solution():
N, B, W = map(int, input().split())
stones = input().rstrip()
start, end = 0, 0
count = {'W':0, 'B':0}
distance = 0
while end < len(stones):
count[stones[end]] += 1
if count['B'] <= B:
if count['W'] >= W:
distance = max(distance, end - start + 1)
end += 1
else:
count[stones[start]] -= 1
start += 1
end += 1
print(distance)
solution()
<file_sep>/baekjoon/baekjoon_1965.py
# https://www.acmicpc.net/problem/1965
# 백준 1965 : 상자넣기
# LEVEL : Silver 2
import sys
def solution():
N = int(sys.stdin.readline())
boxes = list(map(int, sys.stdin.readline().split()))
ans = []
for box in boxes:
if not ans:
ans.append(box)
else:
for i in range(len(ans)):
if box <= ans[i]:
ans[i] = box
break
else:
ans.append(box)
print(len(ans))
solution()
<file_sep>/baekjoon/baekjoon_1149.java
// https://www.acmicpc.net/problem/1149
// 백준 1149번 : RGB 거리
import java.io.IOException;
import java.util.Scanner;
public class baekjoon_1149 {
static final int RED = 0, BLUE = 1, GREEN = 2;
static int[][] sumWeights, weights;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int N = Integer.parseInt(sc.nextLine());
sumWeights = new int[N][3];
weights = new int[N][3];
// weight 입력
for (int i = 0; i < N; i++) {
String[] str = sc.nextLine().split(" ");
for (int j = 0; j < 3; j++)
weights[i][j] = Integer.parseInt(str[j]);
}
// 첫번째 sumWeight 대입
sumWeights[0][RED] = weights[0][RED];
sumWeights[0][BLUE] = weights[0][BLUE];
sumWeights[0][GREEN] = weights[0][GREEN];
// 현재 집에 색칠할 색의 비용과 이전 집까지의 비용의 최솟값을 합하여 계산
for (int i = 1; i < N; i++) {
sumWeights[i][RED] = Math.min(sumWeights[i-1][BLUE],sumWeights[i-1][GREEN])+weights[i][RED];
sumWeights[i][BLUE] = Math.min(sumWeights[i-1][RED],sumWeights[i-1][GREEN])+weights[i][BLUE];
sumWeights[i][GREEN] = Math.min(sumWeights[i-1][RED],sumWeights[i-1][BLUE])+weights[i][GREEN];
}
// 최솟값 계산
int min = Math.min(sumWeights[N - 1][RED], sumWeights[N - 1][BLUE]);
min = Math.min(min, sumWeights[N - 1][GREEN]);
System.out.println(min);
}
}
<file_sep>/base/bubble_sort.py
def bubble_sort(arr):
n = len(arr)
for i in range(n): # i : 0부터 n-1까지
for j in range(1, n-i): # j : 1부터 n-i까지 (1회전 할때마다 끝 원소를 하나씩 제외한다.)
if arr[j-1] > arr[j]:
temp = arr[j-1]
arr[j-1] = arr[j]
arr[j] = temp
print(arr)
bubble_sort([5,4,3,2,1])
<file_sep>/baekjoon/baekjoon_1920.py
# https://www.acmicpc.net/problem/1920
# 백준 1920 : 수 찾기
# LEVEL : Silver 4
import sys
def solution():
N = int(sys.stdin.readline())
nums = list(map(int, sys.stdin.readline().split()))
M = int(sys.stdin.readline())
find_nums = list(map(int, sys.stdin.readline().split()))
nums.sort()
def binary_search(target, start, end):
while start < end:
mid = (start + end) // 2
if nums[mid] == target:
return 1
elif nums[mid] < target:
start = mid + 1
else:
end = mid
return 0
for i in range(M):
print(binary_search(find_nums[i], 0, N))
solution()
<file_sep>/baekjoon/baekjoon_19638.py
# https://www.acmicpc.net/problem/19638
# 백준 19638 : 센티와 마법의 뿅망치
# LEVEL : Silver 1
import sys
from heapq import heappop, heappush, heapify
def solution():
N, H, T = map(int, sys.stdin.readline().split())
heights = [-int(sys.stdin.readline()) for _ in range(N)]
heapify(heights) # 최대힙 큐로 변환
if -heights[0] < H:
print("YES")
print(0)
return
for i in range(T):
height = int(heappop(heights) / 2)
if height == 0:
height = -1
heappush(heights, height)
if -heights[0] < H:
print("YES")
print(i+1)
break
else:
print("NO")
print(-heights[0])
solution()
<file_sep>/programmers/programmers_81302.py
# https://programmers.co.kr/learn/courses/30/lessons/81302
# programmers 81302 : 2021 카카오 채용연계형 인턴십 - 거리두기 확인하기
# LEVEL : 2
dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]
count = {'P': 1, 'O': 2}
def solution(places):
answer = []
for place in places:
answer.append(check(place))
return answer
def check(place):
for i in range(5):
for j in range(5):
if place[i][j] != 'X':
find = 0
for x, y in zip(dx, dy):
if is_range(i+y, j+x) and place[i+y][j+x] == 'P':
find += 1
if find >= count[place[i][j]]:
return 0
return 1
def is_range(y, x):
return (y >= 0 and y < 5 and x >= 0 and x < 5)
<file_sep>/leetcode/leetcode_74.py
# https://leetcode.com/problems/search-a-2d-matrix/
# leetcode 74 : Search a 2D Matrix
# LEVEL : Medium
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
row, col = len(matrix), len(matrix[0])
start, end = 0, row*col-1
while start <= end:
mid = (start + end) // 2
r, c = mid // col, mid % col
if matrix[r][c] == target:
return True
elif matrix[r][c] < target:
start = mid + 1
else:
end = mid - 1
return False<file_sep>/baekjoon/baekjoon_18352.py
`# https://www.acmicpc.net/problem/18352
# 백준 : 183512 : 특정 거리의 도시 찾기
# LEVEL : Silver 2
import sys
import heapq
def solution():
N, M, K, X = map(int, sys.stdin.readline().split())
graph = {i+1:{} for i in range(N)}
for _ in range(M):
start, end = map(int, sys.stdin.readline().split())
graph[start][end] = True
distance = {node:float('inf') for node in graph}
distance[X] = 0
queue = []
heapq.heappush(queue, [distance[X], X])
while queue:
curr_distance, curr_location = heapq.heappop(queue)
if curr_distance > distance[curr_location]:
continue
for next_location in graph[curr_location].keys():
next_distance = curr_distance + 1
if next_distance < distance[next_location]:
distance[next_location] = next_distance
heapq.heappush(queue, [next_distance, next_location])
if K in distance.values():
for location, dist in distance.items():
if dist == K:
print(location)
else:
print(-1)
solution()
`<file_sep>/baekjoon/baekjoon_17219.cpp
// https://www.acmicpc.net/problem/17219
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main() {
cin.tie(NULL);
ios::sync_with_stdio(false);
int siteNum, findNum;
cin >> siteNum >> findNum;
map<string, string> m;
// N개의 사이트 주소와 비밀번호
for (int i = 0; i < siteNum; i++) {
string site, password;
cin >> site >> password;
m[site] = password;
}
// M개의 찾으려는 비밀번호의 사이트 주소
for (int i = 0; i < findNum; i++) {
string findSite;
cin >> findSite;
map<string, string>::iterator it = m.find(findSite);
if (it != m.end()) {
cout << it->second << "\n";
}
}
return 0;
}<file_sep>/programmers/programmers_92344.py
# https://school.programmers.co.kr/learn/courses/30/lessons/92344
# programmers 92344 : 파괴되지 않은 건물
# LEVEL : 3
def solution(board, skill):
answer = 0
N, M = len(board), len(board[0])
temp = [[0 for _ in range(M+1)] for _ in range(N+1)]
for i in range(len(skill)):
[type, r1, c1, r2, c2, degree] = skill[i]
if type == 1:
degree = -degree
temp[r1][c1] += degree
temp[r2 + 1][c2 + 1] += degree
temp[r1][c2 + 1] -= degree
temp[r2 + 1][c1] -= degree
# 열 기준 누적합
for i in range(N):
for j in range(M):
temp[i][j+1] += temp[i][j]
# 행 기준 누적합
for j in range(M):
for i in range(N):
temp[i+1][j] += temp[i][j]
for i in range(N):
for j in range(M):
if board[i][j] + temp[i][j] > 0:
answer += 1
return answer
<file_sep>/programmers/programmers_76501.py
# https://programmers.co.kr/learn/courses/30/lessons/76501
# programmers 76501 : 월간 코드 챌린지 시즌2 - 음양 더하기
# LEVEL 1
def solution(absolutes, signs):
answer = 0
for number, sign in zip(absolutes, signs):
if sign:
answer += number
else:
answer -= number
return answer
<file_sep>/baekjoon/baekjoon_15922.cpp
// https://www.acmicpc.net/problem/15922
#include <iostream>
using namespace std;
int main() {
int N;
cin >> N;
int end = -1000000000, total_length = 0;
while (N--) {
int x, y;
cin >> x >> y; // 선분 x, y 값 입력
if (x < end) { // x가 이전 y의 최대값 보다 작다면
if (y < end) // y가 이전 y의 최대값 보다 작다면 PASS (이미 포함)
continue;
else
total_length += (y - end);
}
else
total_length += (y - x);
end = y;
}
cout << total_length;
return 0;
}<file_sep>/baekjoon/baekjoon_1495.py
# https://www.acmicpc.net/problem/1495
# 백준 1495 : 기타리스트
# LEVEL : Silver 1
import sys
def solution():
N, S, M = map(int, sys.stdin.readline().split())
difference = list(map(int, sys.stdin.readline().split()))
dp = [[False for _ in range(M+1)] for _ in range(N+1)]
dp[0][S] = True
for i in range(1, N+1):
volume = difference[i-1]
for j in range(M+1):
if dp[i-1][j]:
if j - volume >= 0:
dp[i][j-volume] = True
if j + volume <= M:
dp[i][j+volume] = True
result = -1
for i in range(M, -1, -1):
if dp[N][i]:
result = i
break
print(result)
solution()
<file_sep>/programmers/programmers_76502.py
# https://programmers.co.kr/learn/courses/30/lessons/76502
# programmers 76502 : 월간 코드 챌린지 시즌2 - 괄호 회전하기
# LEVEL : 2
def solution(s):
answer = 0
for i in range(len(s)):
if i:
s = s[1:] + s[0]
stack = []
for bracket in s:
if not stack or bracket == '(' or bracket == '{' or bracket == '[':
stack.append(bracket)
else:
if (bracket == ')' and stack[-1] == '(') or \
(bracket == '}' and stack[-1] == '{') or \
(bracket == ']' and stack[-1] == '['):
stack.pop()
if not stack:
answer += 1
return answer<file_sep>/baekjoon/baekjoon_11726.py
# https://www.acmicpc.net/problem/11726
# 백준 11726 : 2xn 타일링
# LEVEL : Silver
import sys
def solution():
N = int(sys.stdin.readline())
memo = [0] * (N+1)
memo[0] = 1
memo[1] = 1
for i in range(2, N+1):
memo[i] = memo[i-1] + memo[i-2]
print(memo[N] % 10007)
solution()
<file_sep>/leetcode/leetcode_526.py
# https://leetcode.com/problems/beautiful-arrangement/
# leetcode 526 : Beautiful Arrangement
# LEVEL : Medium
class Solution:
def countArrangement(self, n: int) -> int:
def dfs(i):
if i == 0:
self.ans += 1
return
for j in range(1, n+1):
if not visited[j] and (j % i == 0 or i % j == 0):
visited[j] = True
dfs(i-1)
visited[j] = False
self.ans = 0
visited = [False]*(n+1)
dfs(n)
return self.ans
<file_sep>/baekjoon/baekjoon_2512.py
# https://www.acmicpc.net/problem/2512
# 백준 2512 : 예산
# LEVEL : Silver 3
import sys
def solution():
N = int(sys.stdin.readline())
requests = list(map(int, sys.stdin.readline().split()))
budget = int(sys.stdin.readline())
requests.sort() # 예산 요청을 오름차순으로 정렬
if sum(requests) <= budget: # 모든 요청이 배정될 수 있는 경우
print(requests[-1]) # 최댓값 출력 (정렬한 상태이기 때문에 [-1])
else: # 모든 요청이 배정될 수 없는 경우
for i in range(N):
mean = budget//(N-i) # i번째 요청을 포함하여 평균적으로 줄 수 있는 예산
if requests[i] <= mean:
budget -= requests[i]
else:
print(mean)
break
solution()
<file_sep>/baekjoon/baekjoon_1012.py
# https://www.acmicpc.net/problem/1012
# 백준 1012 : <NAME>
# LEVEL : Silver 2
import sys
from collections import deque
def solution():
direction = [(0,1),(0,-1),(1,0),(-1,0)]
T = int(sys.stdin.readline())
for _ in range(T):
M, N, K = map(int, sys.stdin.readline().split())
field = [[False for _ in range(M)] for _ in range(N)]
visited = [[False for _ in range(M)] for _ in range(N)]
for _ in range(K):
x, y = map(int, sys.stdin.readline().split())
field[y][x] = True
count = 0
for y in range(N):
for x in range(M):
if field[y][x] and not visited[y][x]:
count += 1
dq = deque([(y, x)])
visited[y][x] = True
while dq:
loc_y, loc_x = dq.popleft()
for dy, dx in direction:
ny, nx = loc_y+dy, loc_x+dx
if 0 <= ny < N and 0 <= nx < M and \
field[ny][nx] and not visited[ny][nx]:
visited[ny][nx] = True
dq.append((ny, nx))
print(count)
solution()
<file_sep>/baekjoon/baekjoon_2531.py
# https://www.acmicpc.net/problem/2531
# baekjoon 2531 : 회전 초밥
# LEVEL : Silver 1
import sys
from collections import defaultdict
def solution():
N, d, k, c = map(int, sys.stdin.readline().split())
nums = [int(sys.stdin.readline()) for _ in range(N)]
max_count = 0
subset = defaultdict(int)
subset[c] += 1
count = 1
for i in range(k): # 0 ~ k-1 초밥 먹기
if not subset[nums[i]]:
count += 1
subset[nums[i]] += 1
for i in range(N-1): # i번째 초밥빼고 i+k번째 초밥 먹었을때의 경우 계산하기
subset[nums[i]] -= 1
if not subset[nums[i]]:
count -= 1
if not subset[nums[(i+k) % N]]:
count += 1
subset[nums[(i+k) % N]] += 1
max_count = max(max_count, count)
print(max_count)
solution()
<file_sep>/baekjoon/baekjoon_14226.cpp
#include <iostream>
#include<string>
#include<vector>
#include<queue>
using namespace std;
int visited[1001][1001]; // 화면, 클립보드
int main() {
ios_base::sync_with_stdio(false);
int S;
cin >> S;
queue<pair<int, int>> q;
q.push(make_pair(1, 0));
visited[1][0] = 0;
int min = -1;
while (!q.empty()) {
int screen = q.front().first;
int clip = q.front().second;
q.pop();
if (visited[screen][screen] == 0) {
visited[screen][screen] = visited[screen][clip] + 1; // 복사
q.push(make_pair(screen, screen));
}
if (screen + clip <= S && visited[screen + clip][clip] == 0) {
visited[screen + clip][clip] = visited[screen][clip] + 1;
q.push(make_pair(screen + clip, clip));
}
if (screen - 1 >= 0 && visited[screen - 1][clip] == 0) {
visited[screen - 1][clip] = visited[screen][clip] + 1;
q.push(make_pair(screen - 1, clip));
}
}
for (int i = 0; i <= S; i++) {
if (visited[S][i] != 0) {
if (min == -1 || min > visited[S][i]) {
min = visited[S][i];
}
}
}
cout << min;
return 0;
}<file_sep>/leetcode/leetcode_114.py
# https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
# leetcode 114 : Flatten Binary Tree to Linked List
# LEVEL : Medium
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def flatten(self, root: Optional[TreeNode]) -> None:
parent = root
while parent != None:
if parent.left != None:
temp = parent.right
parent.right = parent.left
parent.left = None
right_leaf = parent.right
while right_leaf.right != None:
right_leaf = right_leaf.right
right_leaf.right = temp
parent = parent.right
return root
<file_sep>/leetcode/leetcode_19.py
# https://leetcode.com/problems/remove-nth-node-from-end-of-list/
# leetcode 19 : Remove Nth Node From End of List
# LEVEL : Medium
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
root = ListNode(0, head)
length = 0
while head:
head = head.next
length += 1
head = root
for _ in range(length-n):
head = head.next
head.next = head.next.next
return root.next
<file_sep>/leetcode/leetcode_217.java
/*
https://leetcode.com/problems/contains-duplicate/
LeetCode 217 : Contains Duplicate (Difficulty : Easy)
[문제]
주어진 배열에서 중복된 값이 들어있으면 true, 모두 다르면 false를 return 해라.
[간단 풀이]
nums 배열을 정렬하고, 순서대로 2개씩 값을 비교한다.
[시간 복잡도]
sort는 O(nlogn), 비교는 O(n)
*/
import java.util.Arrays;
public class leetcode_217 {
public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums);
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] == nums[i + 1])
return true;
}
return false;
}
}
<file_sep>/leetcode/leetcode_763.py
# https://leetcode.com/problems/partition-labels/
# leetcode 763 : Partition Labels
# LEVEL : Medium
class Solution:
def partitionLabels(self, s: str) -> List[int]:
result = [0]
for end in range(1, len(s)):
start = sum(result)
if not self.include(s[start:end], s[end:]):
result.append(end-start)
result.append(len(s)-sum(result))
return result[1:]
def include(self, s1, s2) -> bool:
for s in s1:
if s in s2:
return True
return False
class Solution:
def partitionLabels(self, s: str) -> List[int]:
res = []
map = {}
for i in range(len(s)):
map[s[i]] = i
start = 0
max_idx = 0
for i in range(len(s)):
max_idx = max(max_idx, map[s[i]])
if max_idx == i:
res.append(i-start)
start = i+1
return res
<file_sep>/codeforces/codeforces_734B.cpp
#include <iostream>
using namespace std;
int min(int a, int b) {
return a > b ? b : a;
}
int main() {
int k2, k3, k5, k6;
cin >> k2 >> k3 >> k5 >> k6;
int make_256 = min(k2, min(k5, k6)); // k2, k5, k6 중에 가장 적은 개수로 256 만들기
int make_32 = k2 > make_256 ? min(k3, k2 - make_256) : 0; // 256 제외하고 숫자 2가 남았다면
cout << make_256 * 256 + make_32 * 32;
return 0;
}<file_sep>/programmers/programmers_42897.py
# https://programmers.co.kr/learn/courses/30/lessons/42897
# programmers 42897 : 도둑질
# LEVEL : 4
def solution(money):
dp = [0 for _ in range(len(money))]
dp[0], dp[1] = money[0], max(money[0], money[1])
for i in range(2, len(money)-1):
dp[i] = max(dp[i-1], money[i] + dp[i-2])
dp2 = [0 for _ in range(len(money))]
dp2[0], dp2[1] = 0, money[1]
for i in range(2, len(money)):
dp2[i] = max(dp2[i-1], money[i] + dp2[i-2])
return max(dp[-2], dp2[-1])<file_sep>/programmers_school/week_1_step_1_1.py
# 1주차 Step1-1. 문제 먼저 직접 풀어보기 "완주하지 못한 선수"
# solution1
def solution(participant, completion):
for p, c in zip(sorted(participant), sorted(completion)+[""]):
if p != c:
return p
# solution2
def solution(participant, completion):
participant.sort()
completion.sort()
for i in range(len(completion)):
if participant[i] != completion[i]:
return participant[i]
return participant[-1]
print(solution(["leo", "kiki", "eden"], ["eden", "kiki"]))
<file_sep>/programmers/programmers_77486.py
# https://programmers.co.kr/learn/courses/30/lessons/77486
# programmers 77486 : 2021-Dev-Matching: 웹 백엔드 개발 - 다단계 칫솔 판매
# LEVEL : 3
def solution(enroll, referral, seller, amount):
answer = []
profit, recommender = {}, {}
for e, r in zip(enroll, referral):
recommender[e] = r
for s, a in zip(seller, amount):
profit[s] = profit.get(s, 0) + int(a * 90)
parent, remain = recommender[s], int(a * 10)
while parent != '-':
if remain >= 10:
profit[parent] = profit.get(parent, 0) + (remain - remain//10)
parent, remain = recommender[parent], remain//10
else:
profit[parent] = profit.get(parent, 0) + remain
break
for e in enroll:
answer.append(profit.get(e, 0))
return answer
<file_sep>/base/insertion_sort.py
def insertion_sort(arr):
n = len(arr)
for i in range(1, n):
temp = arr[i]
prev = i-1
while prev >= 0 and arr[prev] > temp: # 이전 원소가 temp보다 크면 오른쪽으로 이동시킨다.
arr[prev+1] = arr[prev]
prev -= 1
arr[prev+1] = temp # temp보다 큰 값을 모두 왼쪽으로 이동시킨 후 값을 삽입한다.
print(arr)
insertion_sort([5,4,3,2,1])<file_sep>/leetcode/leetcode_338.py
# https://leetcode.com/problems/counting-bits/
# leetcode 338 : Counting Bits
# LEVEL : Easy
class Solution:
def countBits(self, n: int) -> List[int]:
result = [0 for _ in range(n+1)]
for i in range(1, n+1):
result[i] = result[i-(i & -i)]+1
return result
<file_sep>/baekjoon/baekjoon_2529.py
# https://www.acmicpc.net/problem/2529
# 백준 2529 : 부등호
# LEVEL : Silver 1
from socketserver import ThreadingUDPServer
import sys
from itertools import permutations
def solution():
k = int(sys.stdin.readline())
signs = sys.stdin.readline().rstrip().split()
visited = [False] * 10
answer = []
def correct(x, y, op):
if op == '<':
return x < y
else:
return x > y
def find(index, number):
if index == k+1:
answer.append(number)
return
for i in range(10):
if not visited[i] and \
(index == 0 or correct(number[index-1], str(i), signs[index-1])):
visited[i] = True
find(index + 1, number + str(i))
visited[i] = False
find(0, "")
print(answer[-1])
print(answer[0])
solution()
<file_sep>/baekjoon/baekjoon_2606.py
# https://www.acmicpc.net/problem/2606
# 백준 2606 : 바이러스
# LEVEL : Silver 3
import sys
from collections import deque
def solution():
computer_num = int(sys.stdin.readline())
pair_num = int(sys.stdin.readline())
graph = [[False for _ in range(computer_num)] for _ in range(computer_num)]
visited = [False for _ in range(computer_num)]
for _ in range(pair_num):
c1, c2 = map(int, sys.stdin.readline().split())
graph[c1-1][c2-1] = True
graph[c2-1][c1-1] = True
def dfs(com):
if visited[com]:
return
visited[com] = True
for i in range(computer_num):
if graph[com][i]:
dfs(i)
dfs(0)
print(visited.count(True)-1)
solution()<file_sep>/baekjoon/baekjoon_4811.cpp
#include <iostream>
#include <vector>
using namespace std;
long long dp[31][31];
long long calculate(int one, int half) {
if (dp[one][half] != 0) // 이미 계산된 값이면
return dp[one][half];
if (one == 0) // 남은 약이 모두 반알이면
return 1;
if (half == 0)
return dp[one][half] = calculate(one - 1, 1);
else
return dp[one][half] = calculate(one - 1, half + 1) + calculate(one, half - 1);
}
void main() {
int N;
vector<long long> ans;
while (true) {
cin >> N;
if (N == 0) // 입력의 마지막 줄
break;
ans.push_back(calculate(N - 1, 1));
}
for (int i = 0; i < ans.size(); i++)
cout << ans[i] << "\n";
}
<file_sep>/leetcode/leetcode_129.py
# https://leetcode.com/problems/sum-root-to-leaf-numbers/
# leetcode 129 : Sum Root to Leaf Numbers
# LEVEL : Medium
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumNumbers(self, root: Optional[TreeNode]) -> int:
ans = []
def sumNumber(node, before):
if not node.left and not node.right:
ans.append(before * 10 + node.val)
return
if node.left:
sumNumber(node.left, before * 10 + node.val)
if node.right:
sumNumber(node.right, before * 10 + node.val)
sumNumber(root, 0)
return sum(ans)
<file_sep>/baekjoon/baekjoon_2667.py
# https://www.acmicpc.net/problem/2667
# 백준 2667 : 단지번호붙이기
# LEVEL : Silver 1
import sys
from collections import deque
def solution():
N = int(sys.stdin.readline())
area = [list(sys.stdin.readline().rstrip())
for _ in range(N)]
directions = [[0, 1], [0, -1], [1, 0], [-1, 0]] # 탐색할 방향
homes = [] # 각 단지에 속하는 집의 수를 저장하는 리스트
count_total = 0 # 단지 수
for i in range(N):
for j in range(N):
if area[i][j] == '1':
count_home = 0
q = deque([(i, j)])
while q:
y, x = q.popleft()
if area[y][x] == '0':
continue
area[y][x] = '0'
count_home += 1
for dy, dx in directions: # 상하좌우 탐색
ny = y + dy
nx = x + dx
if 0 <= ny < N and 0 <= nx < N and area[ny][nx] == '1':
q.append((ny, nx))
homes.append(count_home)
count_total += 1
print(count_total)
for home in sorted(homes):
print(home)
solution()
<file_sep>/baekjoon/baekjoon_1184.cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Ball {
int x, y, type;
Ball(int _x, int _y, int _type) : x(_x), y(_y), type(_type) {};
};
const int BLUE = 1, RED = 2, HOLE = 3, EMPTY = 4,WALL=5;
int dx[4] = { 0,0,-1,1 }; // 위, 아래, 왼쪽, 오른쪽
int dy[4] = { -1,1,0,0 };
int num = 11;
bool compare_descend_x(const Ball& a, const Ball& b) { // x 내림차순
return a.x > b.x;
}
bool compare_ascend_x(const Ball& a, const Ball& b) { // x 오름차순
return a.x < b.x;
}
bool compare_descend_y(const Ball& a, const Ball& b) { // y 내림차순
return a.y > b.y;
}
bool compare_ascend_y(const Ball& a, const Ball& b) { // y 오름차순
return a.y < b.y;
}
void game(vector<vector<int>> board, vector<Ball> ball_list, int direction, int count) {
if (count == 11) // 10번 초과는 return
return;
if (direction == 0) // 위로 기울이기 (위에 있는 공 순서대로)
sort(ball_list.begin(), ball_list.end(), compare_ascend_y);
else if(direction == 1) // 아래로 기울이기 (아래에 있는 공 순서대로)
sort(ball_list.begin(), ball_list.end(), compare_descend_y);
else if(direction == 2) // 왼쪽으로 기울이기 (왼쪽에 있는 공 순서대로)
sort(ball_list.begin(), ball_list.end(), compare_ascend_x);
else // 오른쪽으로 기울이기 (오른쪽에 있는 공 순서대로)
sort(ball_list.begin(), ball_list.end(), compare_descend_x);
bool move = false;
bool success = false;
for (int i = 0; i < ball_list.size(); i++) {
for (int j = 1;; j++) {
int ball_x = ball_list[i].x + dx[direction] * j;
int ball_y = ball_list[i].y + dy[direction] * j;
int locate = board[ball_y][ball_x];
if (locate == HOLE) { // 공의 위치가 구멍일 때
if (ball_list[i].type == RED) { // 빠진 공이 red
success = true;
move = false;
board[ball_list[i].y][ball_list[i].x] = EMPTY;
break;
}
else { // 빠진 공이 blue
success = false;
move = false;
board[ball_list[i].y][ball_list[i].x] = EMPTY;
break;
}
}
else if (locate == WALL || locate == RED || locate == BLUE) { // 더 움직일 수 없을 때
board[ball_list[i].y][ball_list[i].x] = EMPTY;
ball_list[i].x += dx[direction] * (j - 1);
ball_list[i].y += dy[direction] * (j - 1);
board[ball_list[i].y][ball_list[i].x] = ball_list[i].type;
break;
}
move = true;
}
//cout <<"ball : "<< ball_list[i].y << ", " << ball_list[i].x <<" ("<<ball_list[i].type<<")"<< endl;
}
if (success) {
if (count < num) {
num = count;
//cout << direction << ", " << count << endl;
}
return;
}
if (move) {
for (int i = 0; i < 4; i++) {
if (direction == 0 || direction == 2) { // 0(위), 2(왼) 인 경우, 각각 1(아래), 3(오른) 방향 불가
if (direction+1 != i)
game(board, ball_list, i, count + 1);
}
else { // 1(아래), 3(오른) 인 경우, 각각 0(위), 2(왼) 방향 불가
if (direction - 1 != i)
game(board, ball_list, i, count + 1);
}
}
}
}
int main() {
int board_x, board_y;
cin >> board_y >> board_x;
vector<vector<int>> board;
vector<Ball> ball_list;
vector<int> v; v.assign(board_x, WALL);
board.assign(board_y, v);
for (int i = 0; i < board_y; i++) {
string row;
cin >> row;
if (i != 0 && i != board_y - 1) {
for (int j = 1; j < board_x - 1; j++) {
switch (row[j]) {
case '.':
board[i][j] = EMPTY;
break;
case 'B':
ball_list.push_back(Ball(j, i, BLUE));
board[i][j] = BLUE;
break;
case 'R':
ball_list.push_back(Ball(j, i, RED));
board[i][j] = RED;
break;
case 'O':
board[i][j] = HOLE;
break;
case '#':
board[i][j] = WALL;
}
}
}
}
for (int i = 0; i < 4; i++) {
game(board, ball_list, i, 1);
}
if (num == 11)
cout << "-1";
else
cout << num;
return 0;
}<file_sep>/programmers/programmers_17687.py
# https://programmers.co.kr/learn/courses/30/lessons/17687
# programmers 17687 : 2018 <NAME> RECRUITMENT [3차] n진수 게임
# LEVEL : 2
def solution(n, t, m, p):
answer = ""
order = ""
idx, length = 0, (p-1)+t*m
while len(order) < length:
order += convert(idx, n)
idx += 1
for i in range(t):
answer += order[p-1+m*i]
return answer
def convert(n, x):
number = ['0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']
converted = ""
while n > 0:
converted += number[n % x]
n //= x
return converted[::-1] if converted else "0"
<file_sep>/baekjoon/baekjoon_1504.py
# https://www.acmicpc.net/problem/1504
# 백준 1504 : 특정한 최단 경로
# LEVEL : Gold 4
import sys
import heapq
from collections import defaultdict
input = sys.stdin.readline
def solution():
INF = float('inf')
N, E = map(int, input().split())
graph = defaultdict(dict)
for _ in range(E):
a, b, c = map(int, input().split())
graph[a][b] = c
graph[b][a] = c
v1, v2 = map(int, input().split())
def dijkstra(start):
distance = [INF for _ in range(N+1)]
distance[start] = 0
queue = [(0, start)]
while queue:
curr_cost, curr_node = heapq.heappop(queue)
if curr_cost > distance[curr_node]:
continue
for next_node, next_cost in graph[curr_node].items():
cost = curr_cost + next_cost
if cost < distance[next_node]:
distance[next_node] = cost
heapq.heappush(queue, (cost, next_node))
return distance
s_dist = dijkstra(1)
v1_dist = dijkstra(v1)
v2_dist = dijkstra(v2)
answer = min(s_dist[v1] + v1_dist[v2] + v2_dist[N],
s_dist[v2] + v2_dist[v1] + v1_dist[N])
if answer == INF:
answer = -1
print(answer)
solution()
<file_sep>/leetcode/leetcode_287.py
# https: // leetcode.com/problems/find-the-duplicate-number/
# leetcode 287 : Find the Duplicate Number
# LEVEL : Medium
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
dict = {}
for num in nums:
if dict.get(num) == None:
dict[num] = True
else:
return num
<file_sep>/baekjoon/baekjoon_9084.py
# https://www.acmicpc.net/problem/9084
# baekjoon 9084 : 동전
# LEVEL : Gold 5
import sys
def solution():
T = int(sys.stdin.readline())
for _ in range(T):
N = int(sys.stdin.readline()) # 동전의 종류 수
coins = list(map(int, sys.stdin.readline().split())) # 동전 금액들
target = int(sys.stdin.readline()) # 만들어야 하는 금액
dp = [0] * (target + 1)
dp[0] = 1
for coin in coins:
for i in range(target + 1):
if i >= coin:
dp[i] += dp[i-coin]
print(dp[target])
solution()
<file_sep>/leetcode/leetcode_206.py
# https://leetcode.com/problems/reverse-linked-list/
# leetcode 206 : Reverse Linked List
# LEVEL : Easy
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head:
return None
next_node = head.next
head.next = None
while next_node:
next_next_node = next_node.next
next_node.next = head
head, next_node = next_node, next_next_node
return head
<file_sep>/baekjoon/baekjoon_14503.py
# https://www.acmicpc.net/problem/14503
# 백준 14503 : 로봇 청소기
# LEVEL : Gold 5
import sys
def solution():
EMPTY = 0
WALL = 1
CLEAN = 2
DIRECTIONS = [[-1,0],[0,1],[1,0],[0,-1]] # 북, 동, 남, 서
N, M = map(int, sys.stdin.readline().split())
robot_y, robot_x, robot_d = map(int, sys.stdin.readline().split())
area = [list(map(int, sys.stdin.readline().split())) for _ in range(N)]
count = 0
while True:
if area[robot_y][robot_x] == EMPTY:
area[robot_y][robot_x] = CLEAN
count += 1
for i in range(4):
direction = (robot_d + 3 - i) % 4
dy, dx = DIRECTIONS[direction]
ny = robot_y + dy
nx = robot_x + dx
if area[ny][nx] == EMPTY:
robot_d = direction
robot_y += dy
robot_x += dx
break
else:
back_y, back_x = DIRECTIONS[(robot_d + 2) % 4]
robot_y += back_y
robot_x += back_x
if area[robot_y][robot_x] == WALL:
break
print(count)
solution()<file_sep>/leetcode/leetcode_21.py
# https://leetcode.com/problems/merge-two-sorted-lists/
# leetcode 21 : Merge Two Sorted Lists
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
head = ListNode()
cursor = head
while list1 != None and list2 != None:
if list1.val <= list2.val:
cursor.next = list1
list1 = list1.next
else:
cursor.next = list2
list2 = list2.next
cursor = cursor.next
if list1 != None:
cursor.next = list1
else:
cursor.next = list2
return head.next
<file_sep>/programmers/programmers_118668.py
# https://school.programmers.co.kr/learn/courses/30/lessons/118668
# programmers 118668 : 코딩 테스트 공부
# LEVEL : 3
def solution(alp, cop, problems):
max_alp_req, max_cop_req = 0, 0
for p in problems:
max_alp_req = max(max_alp_req, p[0])
max_cop_req = max(max_cop_req, p[1])
alp = min(alp, max_alp_req)
cop = min(cop, max_cop_req)
dp = [[float('inf') for _ in range(max_cop_req + 1)]
for _ in range(max_alp_req + 1)]
dp[alp][cop] = 0
for i in range(alp, max_alp_req + 1):
for j in range(cop, max_cop_req + 1):
if i + 1 <= max_alp_req:
dp[i + 1][j] = min(dp[i + 1][j], dp[i][j] + 1)
if j + 1 <= max_cop_req:
dp[i][j + 1] = min(dp[i][j + 1], dp[i][j] + 1)
for alp_req, cop_req, alp_rwd, cop_rwd, cost in problems:
if i >= alp_req and j >= cop_req:
next_alp = min(max_alp_req, i + alp_rwd)
next_cop = min(max_cop_req, j + cop_rwd)
dp[next_alp][next_cop] = min(
dp[next_alp][next_cop], dp[i][j] + cost)
answer = dp[-1][-1]
return answer
<file_sep>/baekjoon/baekjoon_10942.cpp
#include <iostream>
#include<string>
#include<vector>
using namespace std;
int answer[2002][2002]; // 답
int main() {
int N,M; // 수열의 크기, 질문의 개수
cin >> N;
int numbers[2002]; // 칠판에 적은 수
for (int i = 0; i < N; i++)
cin >> numbers[i];
cin >> M;
for (int dif=0; dif < N; dif++) { // dif : 차이값
for (int a = 0;a+dif < N; a++) { // b : 시작값
int b = a + dif;
//수 하나 - 팰린드롬
if (dif == 0) {
answer[a][b] = 1;
continue;
}
else if (dif == 1) { // 수 두개
if (numbers[a] == numbers[b]) // 같으면 팰린드롬
answer[a][b] = 1;
else
answer[a][b] = 0;
continue;
}
else if (numbers[a] == numbers[b] && answer[a + 1][b - 1] == 1) { // 두 수가 같고 그 사이의 수열이 팰린드롬일 때
answer[a][b] = 1;
continue;
}
else
answer[a][b] = 0;
}
}
for (int i = 0; i < M; i++) {
int S, E;
cin >> S >> E;
cout << answer[S - 1][E - 1] << endl;
}
return 0;
}<file_sep>/programmers/programmers_60062.py
# https://school.programmers.co.kr/learn/courses/30/lessons/60062
# programmers 60062 : 외벽 점검
# LEVEL : 3
from itertools import permutations
def solution(n, weak, dist):
w_length = len(weak)
for i in range(w_length):
weak.append(n + weak[i])
d_length = len(dist)
answer = d_length + 1
for i in range(w_length):
for d in list(permutations(dist, d_length)):
d_idx, d_dist = 0, d[0]
w_idx = i
while w_idx < i + w_length and d_idx < d_length: # weak와 friend를 다 확인할 때까지
if w_idx == i+w_length-1:
break
if d_dist < weak[w_idx+1] - weak[w_idx]: # f_idx 친구가 갈 수 없을 때
w_idx += 1
d_idx += 1
if d_idx < d_length:
d_dist = d[d_idx]
else: # f_idx 친구가 갈 수 있으면 보냄
d_dist -= (weak[w_idx+1] - weak[w_idx])
w_idx += 1
if d_idx < d_length:
answer = min(answer, d_idx+1)
if answer == d_length + 1:
answer = -1
return answer
<file_sep>/baekjoon/baekjoon_2589.py
# https://www.acmicpc.net/problem/2589
# 백준 2589 : 보물섬
# LEVEL : Gold 5
import sys
from collections import deque
input = sys.stdin.readline
def solution():
direction = [[1,0], [-1, 0], [0, 1], [0, -1]]
row, col = map(int, input().split())
area = [list(input().rstrip()) for _ in range(row)]
def count_neighbor(y, x):
count = 0
for dy, dx in direction:
ny = y + dy
nx = x + dx
if 0 <= ny < row and 0 <= nx < col and area[ny][nx] == 'L':
count += 1
return count
def bfs(y, x):
distance = 0
visited = [[0 for _ in range(col)] for _ in range(row)]
visited[y][x] = 1
q = deque([(y, x)])
while q:
curr_y, curr_x = q.popleft()
for dy, dx in direction:
ny = curr_y + dy
nx = curr_x + dx
if 0 <= ny < row and 0 <= nx < col and area[ny][nx] == 'L' and visited[ny][nx] == 0:
visited[ny][nx] = visited[curr_y][curr_x] + 1
if visited[ny][nx] > distance:
distance = visited[ny][nx]
q.append((ny, nx))
return distance - 1
answer = 0
for i in range(row):
for j in range(col):
if area[i][j] == 'L' and count_neighbor(i, j) <= 2:
time = bfs(i, j)
if time > answer:
answer = time
print(answer)
solution()<file_sep>/programmers/programmers_87946.py
# https://programmers.co.kr/learn/courses/30/lessons/87946
# programmers 87946 : 위클리 챌린지 - 피로도
# LEVEL : 2
from collections import deque
def solution(k, dungeons):
answer = -1
length = len(dungeons)
dq = deque([(k, [])])
while dq:
p, visited = dq.popleft()
if len(visited) > answer:
answer = len(visited)
for i in range(length):
if i not in visited and p >= dungeons[i][0]:
dq.append((p-dungeons[i][1], visited + [i]))
return answer
print(solution(80, [[80,20],[50,40],[30,10]]))
<file_sep>/leetcode/leetcode_240.py
# https://leetcode.com/problems/search-a-2d-matrix-ii/
# leetcode 240 : Search a 2D Matrix II
# LEVEL : Medium
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
m, n = len(matrix), len(matrix[0])
r, c = 0, n-1
while 0 <= r < m and 0 <= c < n:
if matrix[r][c] == target:
return True
elif matrix[r][c] < target:
r += 1
else:
c -= 1
return False
<file_sep>/leetcode/leetcode_96.py
# https://leetcode.com/problems/unique-binary-search-trees/
# leetcode 96 : Unique Binary Search Trees
# LEVEL : Medium
class Solution:
def numTrees(self, n: int) -> int:
if n < 3:
return n
tree = [0] * (n+1)
tree[0], tree[1], tree[2] = 1, 1, 2
for i in range(3, n+1):
tree[i] = sum([tree[j-1] * tree[i-j] for j in range(1, i+1)])
return tree[n]<file_sep>/codility/codility_treeheight.py
from extratypes import Tree # library with types used in the task
def solution(T):
return calculate_depth(T, -1)
def calculate_depth(node, depth):
if not node:
return depth
return max(calculate_depth(node.l, depth + 1), calculate_depth(node.r, depth + 1))
<file_sep>/baekjoon/baekjoon_11723.py
# https://www.acmicpc.net/problem/11723
# 백준 11723 : 집합
# LEVEL : Silver 4
import sys
def solution():
N = int(sys.stdin.readline())
S = 0
for _ in range(N):
row = sys.stdin.readline().split()
command = row[0] # 연산 종류
number = 0 # 연산할 값 : x
if len(row) > 1:
number = int(row[1]) - 1
if command == 'add':
S = S | (1 << number)
elif command == 'remove':
S = S & ~(1 << number)
elif command == 'check':
if S & (1 << number):
print(1)
else:
print(0)
elif command == 'toggle':
S = S ^ (1 << number)
elif command == 'all':
S = ((1 << 20) - 1)
elif command == 'empty':
S = 0
solution()
<file_sep>/baekjoon/baekjoon_10165.cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
long long S[500000];
long long E[500000];
bool result[500000];
int main() {
int N, M; // 버스 정류소 수, 버스 노선 수
cin >> N >> M;
int index = 0;
for (int i = 0; i < M; i++) {
cin >> S[i] >> E[i];
if (i != 0) {
if (S[i] >= S[i - 1] || E[i] > E[i - 1]) {
result[i] = true;
index = i;
}
if (E[i] < S[i]) {
for (int j = 0; j < i; j++) {
if (E[j] <= E[i])
result[j] = false;
}
}
}
}
for (int i = 0; i < index; i++) {
if (result[i])
cout << i + 1 << " ";
}
}<file_sep>/programmers/programmers_12899.cpp
// https://programmers.co.kr/learn/courses/30/lessons/12899
#include <string>
using namespace std;
string solution(int n) {
string answer = "";
while(n > 0){
int remain = n%3;
n = n/3;
if(remain == 0){ // 3으로 나누어지는 경우 몫에 -1을 해준다.
answer = "4" + answer;
n--;
}else if(remain == 1){ // 나머지가 1인 경우
answer = "1" + answer;
}else{ // 나머지가 2인 경우
answer = "2" + answer;
}
}
return answer;
}<file_sep>/leetcode/leetcode_20.java
/*
https://leetcode.com/problems/valid-parentheses/
LeetCode 20 : Valid Parentheses (Difficulty : Easy)
[문제]
'(', ')', '{', '}', '[', ']' 의 문자만을 포함하는 문자열 s가 주어진다.
이때, 유효한 문자열인지 true/false로 반환하라.
1) 여는 괄호는 같은 종류의 괄호로 닫아야 한다.
2) 올바른 순서로 괄호가 닫혀야 한다.
[풀이]
Stack을 활용하여 가장 먼저 닫아야 하는 괄호를 top으로 확인해나간다.
HashMap을 활용하여 올바른 괄호로 닫는지 확인한다.
같은 괄호에 대해,
'('의 key를 1이라고 하고, ')'의 key를 10이라고 하여
닫는 괄호에 10을 나누어 같은지 확인한다.
*/
import java.util.HashMap;
import java.util.Stack;
public class leetcode_20 {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
HashMap<Character, Integer> map = new HashMap<>();
map.put('(', 1);
map.put(')', 10);
map.put('{', 2);
map.put('}', 20);
map.put('[', 3);
map.put(']', 30);
for (int i = 0; i < s.length(); i++) {
char now = s.charAt(i);
if (map.get(now) < 10) {
stack.add(now);
} else if (!stack.isEmpty() && map.get(stack.peek()).equals(map.get(now) / 10)) {
stack.pop();
} else {
return false;
}
}
return stack.isEmpty();
}
}
<file_sep>/leetcode/leetcode_394.py
# https: // leetcode.com/problems/decode-string/
# leetcode 394 : Decode String
# LEVEL : Medium
class Solution:
def decodeString(self, s: str) -> str:
start_bracket = s.find("[")
if start_bracket != -1:
stack = ["["]
end_bracket = start_bracket + 1
while len(stack) != 0:
if s[end_bracket] == "[":
stack.append("[")
elif s[end_bracket] == "]":
stack.pop()
end_bracket += 1
substr = s[start_bracket+1:end_bracket-1]
for i in range(len(s)):
if s[i].isdigit():
start_number = i
break
return s[:start_number] + int(s[start_number:start_bracket]) * self.decodeString(substr) + self.decodeString(s[end_bracket:])
else:
return s
<file_sep>/baekjoon/baekjoon_1461.py
# https://www.acmicpc.net/problem/1461
# 백준 1461 : 도서관
# LEVEL : Gold 5
import sys
def solution():
N, M = map(int, sys.stdin.readline().split())
books = sorted(list(map(int, sys.stdin.readline().split())))
distance = 0
pivot = N
for i in range(N):
if books[i] >= 0:
pivot = i
break
for i in range(0, pivot, M):
distance += books[i] * (-2)
for i in range(N-1, pivot-1, -M):
distance += books[i] * 2
if abs(books[0]) < abs(books[-1]):
distance -= abs(books[-1])
else:
distance -= abs(books[0])
print(distance)
solution()
<file_sep>/baekjoon/baekjoon_1437.cpp
#include <iostream>
#include <cstring>
#define ll long long
using namespace std;
int main() {
int N;
cin >> N;
long long answer = 1;
while (N >= 5) {
answer *= 3;
N -= 3;
}
answer *= N;
cout << answer % 10007;
return 0;
}
<file_sep>/baekjoon/baekjoon_10816.py
# https://www.acmicpc.net/problem/10816
# 백준 10816 : 숫자 카드 2
# LEVEL : Silver 4
import sys
from collections import defaultdict
from bisect import bisect_left, bisect_right
def solution():
N = int(sys.stdin.readline())
nums = list(map(int, sys.stdin.readline().split()))
M = int(sys.stdin.readline())
find_nums = list(map(int, sys.stdin.readline().split()))
d = defaultdict(int)
for num in nums:
d[num] += 1
for num in find_nums:
print(d[num], end=' ')
def solution_binary():
N = int(sys.stdin.readline())
nums = sorted(list(map(int, sys.stdin.readline().split())))
M = int(sys.stdin.readline())
find_nums = list(map(int, sys.stdin.readline().split()))
for find_num in find_nums:
left_index = bisect_left(nums, find_num)
right_index = bisect_right(nums, find_num)
print(right_index-left_index, end=' ')
solution_binary()
<file_sep>/baekjoon/baekjoon_9935.py
# https://www.acmicpc.net/problem/9935
# 백준 9935 : 문자열 폭발
# LEVEL : Gold 4
import sys
input = sys.stdin.readline
def solution():
word = input().rstrip()
target = list(input().rstrip())
target_len = len(target)
arr = []
for i in range(len(word)):
arr.append(word[i])
if arr[-target_len:] == target:
for _ in range(target_len):
arr.pop()
if arr:
print("".join(arr))
else:
print("FRULA")
solution()
<file_sep>/leetcode/leetcode_34.py
# https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
# leetcode 34 : Find First and Last Position of Element in Sorted Array
# LEVEL : Medium
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
def binary_search(left, right, isFirst):
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
if isFirst:
if mid == 0 or nums[mid-1] < target:
return mid
else:
right = mid - 1
else:
if mid == len(nums)-1 or nums[mid+1] > target:
return mid
else:
left = mid + 1
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
return [binary_search(0, len(nums)-1, True), binary_search(0, len(nums)-1, False)]
<file_sep>/leetcode/leetcode_79.py
# https://leetcode.com/problems/word-search/
# leetcode 79 : Word Search
# LEVEL : Medium
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
row, col = len(board), len(board[0])
visited = [[False for _ in range(col)] for _ in range(row)]
def check_word(y, x, index):
if board[y][x] != word[index]:
return False
if index == len(word)-1:
return True
for d in directions:
dy = y + d[0]
dx = x + d[1]
if 0 <= dy < row and 0 <= dx < col and not visited[dy][dx]:
visited[dy][dx] = True
if check_word(dy, dx, index+1):
return True
visited[dy][dx] = False
return False
for i in range(row):
for j in range(col):
visited[i][j] = True
if check_word(i, j, 0):
return True
visited[i][j] = False
return False
<file_sep>/baekjoon/baekjoon_14502.py
# https://www.acmicpc.net/problem/14502
# 백준 14502 : 연구소
# LEVEL : Gold 4
import sys
from itertools import combinations
from collections import deque
input = sys.stdin.readline
def solution():
direction = [[1, 0], [-1, 0], [0, 1], [0, -1]]
N, M = map(int, input().split())
maps = [input().rstrip().split() for _ in range(N)]
empty_list = []
virus_list = []
for i in range(N):
for j in range(M):
if maps[i][j] == '0':
empty_list.append((i, j))
elif maps[i][j] == '2':
virus_list.append((i, j))
empty_num = len(empty_list)
combination_list = combinations(empty_list, 3)
max_size = 0
for combination in combination_list:
for y, x in combination:
maps[y][x] = '1'
queue = deque(virus_list)
visited = [[False for _ in range(M)] for _ in range(N)]
virus = 0
while queue:
y, x = queue.popleft()
for dy, dx in direction:
ny = y + dy
nx = x + dx
if 0 <= ny < N and 0 <= nx < M and maps[ny][nx] == '0' and not visited[ny][nx]:
visited[ny][nx] = True
virus += 1
queue.append((ny, nx))
max_size = max(empty_num - 3 - virus, max_size)
for y, x in combination:
maps[y][x] = '0'
print(max_size)
solution()
<file_sep>/leetcode/leetcode_102.java
/*
https://leetcode.com/problems/binary-tree-level-order-traversal/
LeetCode 102 : Binary Tree Level Order Traversal (Difficulty : Medium)
[문제]
binary tree의 root가 주어질 때, level(층)을 순서대로 value를 2차원 배열로 리턴하라.
순서 : left to right, level by level
[풀이]
먼저, root가 null이면 빈 배열을 리턴한다.
큐를 생성하여 한 층씩 확인하도록 한다.
너비우선탐색과 같은 탐색 순서로, 1층->2층->3층 .. 순서로 확인한다.
while문을 한번씩 실행할 때 마다 현재 큐의 크기만큼 반복하며, 확인하는 노드의 left,right를 다시 큐에 저장한다.
*/
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class leetcode_102 {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> answer = new ArrayList<>();
if (root == null)
return answer;
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) { // 노드를 모두 확인
int size = q.size(); // 현재 큐에 들어있는 노드 수 (한 층의 노드 수)
ArrayList<Integer> values = new ArrayList<>();
while (size > 0) {
TreeNode node = q.poll();
values.add(node.val);
if (node.left != null)
q.add(node.left);
if (node.right != null)
q.add(node.right);
size--;
}
answer.add(values);
}
return answer;
}
}
<file_sep>/programmers/programmers_77884.py
# https://programmers.co.kr/learn/courses/30/lessons/77884
# programmers 77884 : 월간 코드 챌린지 시즌2 - 약수의 개수와 덧셈
# LEVEL 1
import math
def solution(left, right):
answer = 0
for i in range(left, right+1):
sqrt = math.sqrt(i)
if int(sqrt) == sqrt:
answer -= i
else:
answer += i
return answer
<file_sep>/leetcode/leetcode_3248.py
# https://leetcode.com/explore/learn/card/fun-with-arrays/526/deleting-items-from-an-array/3248/
# leetcode : Remove Duplicates from Sorted Array
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
idx = 0
while idx < len(nums)-1:
if nums[idx] == nums[idx+1]:
nums.pop(idx)
else:
idx += 1
return len(nums)
<file_sep>/programmers/programmers_72410.cpp
#include <string>
#include <vector>
using namespace std;
string solution(string new_id) {
string answer = "";
// 1단계
string id1 = "";
for (int i = 0; i < new_id.length(); i++) {
id1 += tolower(new_id[i]);
}
// 2단계
string id2 = "";
for (int i = 0; i < id1.length(); i++) {
char ch = id1[i];
if ((ch >= 'a' && ch <= 'z') ||
(ch >= '0' && ch <= '9') ||
ch == '-' ||
ch == '_' ||
ch == '.') {
id2 += ch;
}
}
// 3단계
string id3 = "";
bool check = false;
for (int i = 0; i < id2.length(); i++) {
if (id2[i] == '.') {
if (!check) { // 연속하여 .이 있는 경우가 아니면
id3 += '.';
check = true;
}
}
else {
id3 += id2[i];
check = false;
}
}
// 4단계
string id4 = id3;
if (id4[0] == '.')
id4 = id4.substr(1, id4.length() - 1);
if (id4[id4.length() - 1] == '.')
id4 = id4.substr(0, id4.length() - 1);
// 5단계
string id5 = "";
if (id4.length() == 0)
id5 = "a";
else
id5 = id4;
// 6단계
string id6 = id5;
if (id5.length() >= 16) {
if (id5[14] == '.')
id6 = id5.substr(0, 14);
else
id6 = id5.substr(0, 15);
}
// 7단계
string id7 = id6;
int len6 = id6.length();
if (len6 <= 2) {
int endChar = id6[len6 - 1];
int repeat = 3 - len6;
for (int i = 0; i < repeat; i++) {
id7 += endChar;
}
}
answer = id7;
return answer;
}<file_sep>/baekjoon/baekjoon_2343.py
# https://www.acmicpc.net/problem/2343
# 백준 2343 : 기타 레슨
# LEVEL : Silver 1
import sys
input = sys.stdin.readline
def solution():
N, M = map(int, input().split())
times = list(map(int, input().split()))
max_time = max(times)
start = 0
end = sum(times)
answer = float('inf')
while start <= end:
mid = (start + end) // 2
if mid < max_time:
start = mid + 1
continue
bluray = 1
length = 0
for i in range(N):
if length + times[i] <= mid:
length += times[i]
else:
bluray += 1
length = times[i]
if bluray <= M:
end = mid - 1
answer = min(answer, mid)
else:
start = mid + 1
print(answer)
solution()<file_sep>/baekjoon/baekjoon_12813.cpp
#include<iostream>
#include <string>
#define SIZE 100000
using namespace std;
int A[SIZE], B[SIZE];
string a_str, b_str;
int main() {
cin >> a_str >> b_str;
for (int i = 0; i < SIZE; i++) {
A[i] = a_str[i] - '0';
B[i] = b_str[i] - '0';
}
// A&B
for (int i = 0; i < SIZE; i++)
cout << (A[i] & B[i]);
cout << "\n";
// A|B
for (int i = 0; i < SIZE; i++)
cout << (A[i] | B[i]);
cout << "\n";
// A^B
for (int i = 0; i < SIZE; i++)
cout << (A[i] ^ B[i]);
cout << "\n";
// ~A
for (int i = 0; i < SIZE; i++)
cout << (!A[i]);
cout << "\n";
// ~B
for (int i = 0; i < SIZE; i++)
cout << (!B[i]);
cout << "\n";
return 0;
}<file_sep>/leetcode/leetcode_31.py
# https://leetcode.com/problems/next-permutation/
# leetcode 31 : Next Permutation
# LEVEL : Medium
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
for i in range(len(nums)-1, 0, -1):
if nums[i] > nums[i-1]:
nums[i:] = sorted(nums[i:])
for j in range(i, len(nums)):
if nums[j] > nums[i-1]:
nums[i-1], nums[j] = nums[j], nums[i-1]
return
nums.sort()
<file_sep>/leetcode/leetcode_347.py
# https://leetcode.com/problems/top-k-frequent-elements/
# leetcode 347 : Top K Frequent Elements
# LEVEL : Medium
import collections
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
c = collections.Counter(nums)
answer = []
for num, _ in c.most_common(k):
answer.append(num)
return answer<file_sep>/baekjoon/baekjoon_2961.py
# https://www.acmicpc.net/problem/2961
# 백준 2961 : 도영이가 만든 맛있는 음식
# LEVEL : Silver 2
import sys
def solution_bitmask():
N = int(sys.stdin.readline())
ingredients = [list(map(int, sys.stdin.readline().split()))
for _ in range(N)]
answer = sys.maxsize
for i in range(1, 1 << N):
sour, bitter = 1, 0
for j in range(N):
if i & (1 << j):
sour *= ingredients[j][0]
bitter += ingredients[j][1]
answer = min(answer, abs(sour-bitter))
print(answer)
def solution():
N = int(sys.stdin.readline())
ingredients = [list(map(int, sys.stdin.readline().split()))
for _ in range(N)]
answer = []
def dfs(sour, bitter, i):
if i == N:
if bitter != 0:
answer.append(abs(sour-bitter))
return
dfs(sour*ingredients[i][0], bitter+ingredients[i][1], i+1)
dfs(sour, bitter, i+1)
dfs(1, 0, 0)
print(min(answer))
solution_bitmask()
<file_sep>/programmers/programmers_42839.py
# https://programmers.co.kr/learn/courses/30/lessons/42839?language=python3
# programmers 42839 : 소수 찾기
# LEVEL : 2
from math import sqrt
from itertools import permutations
def solution(numbers):
numbers = [n for n in numbers]
answer = set()
for i in range(1, len(numbers)+1):
for p in permutations(numbers, i):
num = int(''.join(p))
if is_prime(num):
answer.add(num)
return len(answer)
def is_prime(n):
if n < 2:
return False
for i in range(2, int(sqrt(n)) + 1):
if n % i == 0:
return False
return True
<file_sep>/leetcode/leetcode_99.py
# https://leetcode.com/problems/recover-binary-search-tree/
# leetcode 99 : Recover Binary Search Tree
# LEVEL : Medium
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def recoverTree(self, root: Optional[TreeNode]) -> None:
arr = []
def inOrder(node):
if not node:
return
inOrder(node.left)
arr.append(node)
inOrder(node.right)
inOrder(root)
sortedArr = sorted(arr, key=lambda x: x.val)
for i in range(len(sortedArr)):
if sortedArr[i].val != arr[i].val:
sortedArr[i].val, arr[i].val = arr[i].val, sortedArr[i].val
return
<file_sep>/baekjoon/baekjoon_2141.py
# https://www.acmicpc.net/problem/2141
# 백준 2141 : 우체국
# LEVEL : Gold 4
import sys
input = sys.stdin.readline
def solution():
N = int(input())
town = []
total = 0
for _ in range(N):
location, number = map(int, input().split())
town.append((location, number))
total += number
town.sort(key=lambda x: x[0])
half = 0
target = total / 2
for location, number in town:
half += number
if half >= target:
print(location)
break
solution()<file_sep>/programmers/programmers_12951.py
# https://programmers.co.kr/learn/courses/30/lessons/12951
# programmers 12951 : JadenCase 문자열 만들기
# LEVEL : 2
def solution(s):
answer = ''
is_first = True
for i in range(len(s)):
if s[i] == ' ':
answer += s[i]
is_first = True
else:
if is_first:
answer += s[i].upper()
else:
answer += s[i].lower()
is_first = False
return answer
<file_sep>/baekjoon/baekjoon_14500.py
# https://www.acmicpc.net/problem/14500
# 백준 14500 : 테크로미노
# LEVEL : Gold 4
import sys
input = sys.stdin.readline
answer = 0
def solution():
direction = [[1, 0], [-1, 0], [0, 1], [0, -1]]
N, M = map(int, input().split())
maps = [list(map(int, input().split())) for _ in range(N)]
visited = [[False for _ in range(M)] for _ in range(N)]
max_value = max(map(max, maps))
def dfs(y, x, count, value):
global answer
now_max = value + max_value * (4 - count)
if now_max <= answer:
return
if count == 4:
answer = max(answer, value)
return
for dy, dx in direction:
ny = y + dy
nx = x + dx
if 0 <= ny < N and 0 <= nx < M and not visited[ny][nx]:
if count == 2:
visited[ny][nx] = True
dfs(y, x, count + 1, value + maps[ny][nx])
visited[ny][nx] = False
visited[ny][nx] = True
dfs(ny, nx, count + 1, value + maps[ny][nx])
visited[ny][nx] = False
for i in range(N):
for j in range(M):
visited[i][j] = True
dfs(i, j, 1, maps[i][j])
visited[i][j] = False
print(answer)
solution()
<file_sep>/leetcode/leetcode_3574.py
# https://leetcode.com/explore/learn/card/fun
# leetcode 3574 : Squares of a Sorted Array
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
nums = [num*num for num in nums]
nums.sort()
return nums
<file_sep>/leetcode/leetcode_856.py
# https://leetcode.com/problems/score-of-parentheses/
# leetcode 856 : Score of Parentheses
# LEVEL : Medium
class Solution:
def scoreOfParentheses(self, s: str) -> int:
stack_count = 0
start = 0
score = 0
for end in range(len(s)):
if s[end] == '(':
stack_count += 1
elif stack_count > 0:
stack_count -= 1
if stack_count == 0: # s[start:end+1]이 balanced parentheses string인 경우
if end-start == 1:
score += 1
else:
score += (2*self.scoreOfParentheses(s[start+1:end]))
start = end+1
return score
<file_sep>/leetcode/leetcode_70.java
/*
https://leetcode.com/problems/climbing-stairs/
LeetCode 70 : Climbing Stairs (Difficulty : Easy)
[문제]
n개의 계단이 있을 때, 한 번에 1개 또는 2개의 계단을 올라갈 수 있다.
꼭대기에 오르기까지 계단을 오르는 방법이 몇 가지 인가?
[풀이]
n번 째 계단에 도달하기 위해서는
1) n-1번 째 계단에서 1개의 계단을 오르기
2) n-2번 째 계단에서 2개의 계단을 오르기
위 2가지 방법이 있으므로, 이를 1개부터 n개 까지 순서대로 저장해 나간다.
*/
public class leetcode_70 {
public int climbStairs(int n) {
int[] ways = new int[n + 1]; // ways[i] : i번 째 계단을 오르는 방법의 수
ways[0] = ways[1] = 1;
for (int i = 2; i <= n; i++)
ways[i] = ways[i - 1] + ways[i - 2];
return ways[n];
}
}
<file_sep>/baekjoon/baekjoon_7795.py
# https://www.acmicpc.net/problem/7795
# 백준 7795 : 먹을 것인가 먹힐 것인가
# LEVEL : Silver 3
import sys
input = sys.stdin.readline
def solution():
TC = int(input())
for _ in range(TC):
N, M = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
B.sort()
count = 0
for target in A:
if target <= B[0]:
continue
start = 0
end = M-1
max_index = -1
while start <= end:
mid = (start + end) // 2
if B[mid] < target:
start = mid + 1
max_index = max(max_index, mid)
else:
end = mid - 1
count += (max_index + 1)
print(count)
solution()
<file_sep>/programmers/programmers_86051.py
# https://programmers.co.kr/learn/courses/30/lessons/86051
# programmers 86051 : 월간 코드 챌린지 시즌3 - 없는 숫자 더하기
# LEVEL 1
def solution(numbers):
return 45 - sum(numbers)
|
b2f63db1a5b21a06fc4fdc0aae00e07935126908
|
[
"Markdown",
"Java",
"Python",
"C++"
] | 254
|
Python
|
kia3415/algorithm
|
b161b7164dfe083d1e746e9783e8dca5e847008f
|
2765491ef7077a87df9f1fcef0e2fa98e4c3e658
|
refs/heads/master
|
<file_sep>package mastermind
data class Evaluation(val rightPosition: Int, val wrongPosition: Int)
fun evaluateGuess(secret: String, guess: String): Evaluation {
var absolutelyRight = 0
var trueColor = 0
var nextSecr = ""
var nextGuess = ""
for (i in 0 until CODE_LENGTH) if(secret[i] == guess[i]){
absolutelyRight++
}
else{
nextSecr += secret[i]
nextGuess+=guess[i]
}
var trigger = false
if(absolutelyRight!= CODE_LENGTH){
for(i in 0 until (CODE_LENGTH-absolutelyRight)){
trigger = false
for(j in 0 until nextGuess.length){
if(trigger == false) {
if(nextSecr[i] == nextGuess[j]) {
trigger = true
trueColor++
nextGuess = nextGuess.removeRange(j,j+1)
}
}
}
}
}
else{
return Evaluation(absolutelyRight,trueColor)
}
return Evaluation(absolutelyRight,trueColor)
}
|
03d051140fe650f514afaf936e04fc69b6d63d6c
|
[
"Kotlin"
] | 1
|
Kotlin
|
kesha-dev/coursera-w2
|
979a3e6380d5191f365f13d537b1b8dbf49eceb6
|
a22af878d0d2551407dd3be0bfcce859cc6c21d0
|
refs/heads/master
|
<repo_name>ArtiomBkt/Meme-gen<file_sep>/js/meme-listeners.js
'use strict'
// Event listeners with function pointers for canvas manipulation events
const elTxtInput = document.querySelector('.text-input')
elTxtInput.addEventListener('input', txtInput)
elTxtInput.addEventListener('click', selectAllTxt)
const elAddTxtBtn = document.querySelector('.btn-add-line')
elAddTxtBtn.addEventListener('click', addTxt)
const elRemoveTxtBtn = document.querySelector('.btn-remove-line')
elRemoveTxtBtn.addEventListener('click', removeTxt)
const elSwitchLine = document.querySelector('.btn-switch-line')
elSwitchLine.addEventListener('click', switchLine)
const elMoveLineUp = document.querySelector('.btn-line-up')
elMoveLineUp.addEventListener('click', moveLineUp)
const elMoveLineDown = document.querySelector('.btn-line-down')
elMoveLineDown.addEventListener('click', moveLineDown)
const elIncreaseFontBtn = document.querySelector('.btn-increase-font-size')
elIncreaseFontBtn.addEventListener('click', increaseFontSize)
const elDecreaseFontBtn = document.querySelector('.btn-decrease-font-size')
elDecreaseFontBtn.addEventListener('click', decreaseFontSize)
const elAlignLeftBtn = document.querySelector('.btn-align-left')
elAlignLeftBtn.addEventListener('click', txtAlignLeft)
const elAlignCenterBtn = document.querySelector('.btn-align-center')
elAlignCenterBtn.addEventListener('click', txtAlignCenter)
const elAlignRightBtn = document.querySelector('.btn-align-right')
elAlignRightBtn.addEventListener('click', txtAlignRight)
const elFontFamSelect = document.querySelector('.font-select')
elFontFamSelect.addEventListener('change', fontFamChange)
const elStrokeInput = document.querySelector('.stroke-input')
elStrokeInput.addEventListener('change', strokeChange)
const elFillInput = document.querySelector('.fill-input')
elFillInput.addEventListener('change', fillChange)
const elSaveBtn = document.querySelector('.btn-save')
elSaveBtn.addEventListener('click', onSaveMeme)
function loadCanvasListeners() {
elCanvas.addEventListener('touchstart', touchStart)
elCanvas.addEventListener('touchend', touchEnd)
elCanvas.addEventListener('touchmove', touchMove)
elCanvas.addEventListener('mousedown', pressLine)
elCanvas.addEventListener('mouseup', releaseLine)
elCanvas.addEventListener('mousemove', dragLine)
}<file_sep>/js/services/canvas.service.js
'use strict'
const MEDIUM_BREAKPOINT = 768
const SMALL_BREAKPOINT = 551
const STORAGE_KEY = 'memes'
const gTouchEvs = ['touchstart', 'touchmove', 'touchend']
const gMeme = {
selectedImgId: 0,
selectedLineIdx: -1,
lines: [
{
txt: 'Undefined everywhere!',
size: window.innerWidth < MEDIUM_BREAKPOINT ? 15 : 40,
font: 'impact',
align: 'center',
color: 'white',
stroke: 'black',
rotation: 0,
posX: window.innerWidth < MEDIUM_BREAKPOINT ? '100' : '250',
posY: window.innerWidth < MEDIUM_BREAKPOINT ? '30' : '50'
}
]
}
let elCanvas
let gCtx
let isDragging = false
function initCanvas() {
elCanvas = document.querySelector('#canvas')
gCtx = elCanvas.getContext('2d')
loadCanvasListeners()
}
function loadCurrMeme(id) {
gMeme.selectedImgId = id
}
function resizeCanvas(img) {
let width = (window.innerWidth < SMALL_BREAKPOINT) ? 200 : (window.innerWidth < MEDIUM_BREAKPOINT) ? 250 : img.width
let height = (img.height * width) / img.width
elCanvas.width = width
elCanvas.height = height
}
function memeTxtChange(txt = 'Undefined everywhere!') {
return {
txt,
size: window.innerWidth < MEDIUM_BREAKPOINT ? 15 : 40,
font: 'impact',
align: 'center',
color: 'white',
stroke: 'black',
rotation: 0,
posX: elCanvas.width / 2,
posY: gMeme.lines.length >= 2
? elCanvas.height / 2
: !gMeme.lines.length
? '30'
: elCanvas.height - 10
}
}
const getCanvas = () => elCanvas
const getCtx = () => gCtx
const getMeme = () => gMeme
const toggleDragging = () => isDragging = !isDragging
const pressLine = (ev) => {
selectedLine(ev)
if (gMeme.selectedLineIdx !== -1) {
elCanvas.style.cursor = 'grabbing'
toggleDragging()
}
}
const releaseLine = () => {
elCanvas.style.cursor = 'auto'
toggleDragging()
}
const dragLine = (ev) => {
if (isDragging && gMeme.selectedLineIdx !== -1) {
let selectedLine = _getClickedLine()
let currPos = getClickedPos(ev)
selectedLine.posX = currPos.posX
selectedLine.posY = currPos.posY
renderCanvas()
}
}
function touchStart(ev) {
pressLine(ev)
dragLine(ev)
}
function touchEnd(ev) {
releaseLine(ev.changedTouches[0])
}
function touchMove(ev) {
dragLine(ev)
}
const txtInput = (ev) => {
let txt = ev.target.value
if (gMeme.selectedLineIdx !== -1) {
let selectedLine = _getClickedLine()
selectedLine.txt = txt
renderCanvas()
}
}
const addTxt = () => {
const elTxtInput = document.querySelector('.text-input')
if (!elTxtInput.value) return
let newTxt = memeTxtChange(elTxtInput.value)
gMeme.lines.push(newTxt)
resetInputs()
renderCanvas()
}
const removeTxt = () => {
if (gMeme.selectedLineIdx !== -1) {
gMeme.lines.splice(gMeme.selectedLineIdx, 1)
if (!gMeme.lines.length) gMeme.selectedLineIdx = -1
renderCanvas()
}
}
const increaseFontSize = () => {
if (gMeme.selectedLineIdx !== -1) {
let selectedLine = _getClickedLine()
selectedLine.size++
renderCanvas()
}
}
const decreaseFontSize = () => {
if (gMeme.selectedLineIdx !== -1) {
let selectedLine = _getClickedLine()
selectedLine.size--
renderCanvas()
}
}
const txtAlignLeft = () => {
if (gMeme.selectedLineIdx !== -1) {
let selectedLine = _getClickedLine()
selectedLine.align = 'right'
renderCanvas()
}
}
const txtAlignCenter = () => {
if (gMeme.selectedLineIdx !== -1) {
let selectedLine = _getClickedLine()
selectedLine.align = 'center'
renderCanvas()
}
}
const txtAlignRight = () => {
if (gMeme.selectedLineIdx !== -1) {
let selectedLine = _getClickedLine()
selectedLine.align = 'left'
renderCanvas()
}
}
const fontFamChange = (ev) => {
if (gMeme.selectedLineIdx !== -1) {
let selectedLine = _getClickedLine()
selectedLine.font = ev.target.value
renderCanvas()
}
}
const strokeChange = (ev) => {
if (gMeme.selectedLineIdx !== -1) {
let selectedLine = _getClickedLine()
selectedLine.stroke = ev.target.value
renderCanvas()
}
}
const fillChange = (ev) => {
if (gMeme.selectedLineIdx !== -1) {
let selectedLine = _getClickedLine()
selectedLine.color = ev.target.value
renderCanvas()
}
}
function switchLine() {
if (gMeme.selectedLineIdx !== -1) {
let selectedLine = _getClickedLine()
gMeme.selectedLineIdx = (gMeme.selectedLineIdx === gMeme.lines.length - 1) ? 0 : gMeme.selectedLineIdx + 1
let elTxtInput = document.querySelector('.text-input')
elTxtInput.value = selectedLine.txt
renderCanvas()
}
}
function moveLineUp() {
if (gMeme.selectedLineIdx !== -1) {
let selectedLine = _getClickedLine()
selectedLine.posY--
renderCanvas()
}
}
function moveLineDown() {
if (gMeme.selectedLineIdx !== -1) {
let selectedLine = _getClickedLine()
selectedLine.posY++
renderCanvas()
}
}
function selectAllTxt(ev) {
ev.target.select()
}
function selectedLine(ev) {
let clicked = getClickedPos(ev)
let elTxtInput = document.querySelector('.text-input')
gMeme.selectedLineIdx = gMeme.lines.findIndex(line => {
let txtLength = gCtx.measureText(line.txt)
let half = txtLength.width / 2
let height = txtLength.fontBoundingBoxAscent + txtLength.fontBoundingBoxDescent
return ( clicked.posY < line.posY
&& clicked.posY > line.posY - height
&& clicked.posX < line.posX + half )
})
if (gMeme.selectedLineIdx !== -1) {
let selectedLine = _getClickedLine()
elTxtInput.value = selectedLine.txt
}
renderCanvas()
}
function getClickedPos(ev) {
let pos = { posX: ev.offsetX, posY: ev.offsetY }
if (ev.type === 'touchstart' || ev.type === 'touchmove') {
ev = ev.changedTouches[0]
pos = {
posX: ev.pageX - ev.target.offsetLeft - ev.target.clientLeft,
posY: ev.pageY - ev.target.offsetTop
}
}
return pos
}
function saveMemeToStorage() {
gSavedMemes.push(elCanvas.toDataURL())
saveToStorage(STORAGE_KEY, gSavedMemes)
}
function _getClickedLine() {
return gMeme.lines[gMeme.selectedLineIdx]
}<file_sep>/js/services/meme.service.js
'use strict'
const gKeywords = { 'politics': 3, 'man': 5, 'pets': 3,
'cute': 3, 'kid': 3, 'funny': 8, 'tv': 7, 'epic': 4 }
const gImages = [
{ id: 1, url: './misc/meme-imgs/1.jpg', keywords: ['politics', 'man'] },
{ id: 2, url: './misc/meme-imgs/2.jpg', keywords: ['pets', 'cute'] },
{ id: 3, url: './misc/meme-imgs/3.jpg', keywords: ['pets', 'cute'] },
{ id: 4, url: './misc/meme-imgs/4.jpg', keywords: ['pets', 'cute'] },
{ id: 5, url: './misc/meme-imgs/5.jpg', keywords: ['kid', 'funny'] },
{ id: 6, url: './misc/meme-imgs/6.jpg', keywords: ['funny', 'epic'] },
{ id: 7, url: './misc/meme-imgs/7.jpg', keywords: ['kid', 'funny'] },
{ id: 8, url: './misc/meme-imgs/8.jpg', keywords: ['tv', 'funny'] },
{ id: 9, url: './misc/meme-imgs/9.jpg', keywords: ['kid', 'funny'] },
{ id: 10, url: './misc/meme-imgs/10.jpg', keywords: ['politics', 'man'] },
{ id: 11, url: './misc/meme-imgs/11.jpg', keywords: ['man', 'funny'] },
{ id: 12, url: './misc/meme-imgs/12.jpg', keywords: ['tv', 'man'] },
{ id: 13, url: './misc/meme-imgs/13.jpg', keywords: ['tv', 'epic'] },
{ id: 14, url: './misc/meme-imgs/14.jpg', keywords: ['tv', 'epic'] },
{ id: 15, url: './misc/meme-imgs/15.jpg', keywords: ['tv', 'epic'] },
{ id: 16, url: './misc/meme-imgs/16.jpg', keywords: ['tv', 'funny'] },
{ id: 17, url: './misc/meme-imgs/17.jpg', keywords: ['politics', 'man'] },
{ id: 18, url: './misc/meme-imgs/18.jpg', keywords: ['tv', 'funny'] },
]
const gSavedMemes = []
// _loadMemes()
const getImages = () => gImages
const getSavedMemes = () => gSavedMemes
function _loadMemes() {
let memes = loadFromStorage(STORAGE_KEY)
return memes
}<file_sep>/js/services/share.service.js
'use strict'
const getURL = (type) => elCanvas.toDataURL(type)
function downloadMeme(ev) {
let link = getURL('image/png')
ev.href = link
}
function shareMemeFB(ev) {
ev.preventDefault()
let link = getURL('image/png')
function onSuccess(url) {
let uploadedURL = encodeURIComponent(url)
document.querySelector('.fb-share').innerHTML = `<a class="btn btn-fb-share"
href="https://www.facebook.com/sharer/sharer.php?u=${uploadedURL}&t=${uploadedURL}" title="Share on Facebook" target="_blank" onclick="window.open('https://www.facebook.com/sharer/sharer.php?u=${url}&t=${url}'); return false;">
<img src="misc/images/facebook.svg" alt="fb-share" />
</a>`
}
doUploadImg(link, onSuccess)
}
function doUploadImg(url, onSuccess) {
let formData = new FormData()
formData.append('img', url)
fetch('//ca-upload.com/here/upload.php', {
method: 'POST',
body: formData,
})
.then(res => res.text())
.then(url => onSuccess(url))
.catch(err => console.error(err))
}
async function webShare(link) {
let shareData = {
title: 'My meme',
url: link
}
try {
await navigator.share(shareData)
} catch (e) {
console.error(e)
}
}
|
2468dac0ef4bb8661a2b2a38c0bb750a6dc11f0a
|
[
"JavaScript"
] | 4
|
JavaScript
|
ArtiomBkt/Meme-gen
|
ac3a090f9699f58072f1a526f7d196ca4fe61305
|
b8af9051616389996777d89c789b81d75764247a
|
refs/heads/master
|
<file_sep>package com.example.music.fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupMenu;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SearchView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.music.Interface.IFavoriteControl;
import com.example.music.R;
import com.example.music.Song;
import com.example.music.adapter.SongAdapter;
import com.example.music.database.FavoriteSongsDB;
import com.example.music.service.MediaPlaybackService;
import java.util.ArrayList;
public abstract class BaseSongListFragment extends Fragment implements PopupMenu.OnMenuItemClickListener {
public RecyclerView mRecyclerview;
public SongAdapter mSongAdapter;
protected PopupMenu mPopup;
protected View mView;
protected int mPosition;
private MediaPlaybackService mService;
protected IFavoriteControl mFavoriteControl;
protected boolean mIsFavorite;
protected FavoriteSongsDB mFavoriteSongsDB;
public BaseSongListFragment() {
}
public BaseSongListFragment(IFavoriteControl favoriteControl) {
mFavoriteControl = favoriteControl;
}
public abstract void updateAdapter();
public abstract void updatePopupMenu(View view);
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSongAdapter = new SongAdapter(this);
mFavoriteSongsDB = new FavoriteSongsDB(getContext());
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_action_search, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) item.getActionView();
searchView.setQueryHint(getString(R.string.search_hint));
searchView.setIconified(true);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
mSongAdapter.getFilter().filter(query);
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
mSongAdapter.getFilter().filter(newText);
return false;
}
});
if (mService != null) {
int id;
ArrayList<Song> arraySong = mService.getArraySongs();
int position = mService.getPosition();
Song song = arraySong.get(position);
id = song.getmId();
int i = -1;
do {
i++;
song = arraySong.get(i);
} while (song.getmId() != id);
mPosition = i;
setAnimation(mPosition, id, mService.isPlaying());
}
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable final Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_all_songs, container, false);
updateAdapter();
mRecyclerview = mView.findViewById(R.id.recyclerview);
initRecyclerView();
return mView;
}
public void initRecyclerView() {
LinearLayoutManager linearLayout = new LinearLayoutManager(getActivity());
linearLayout.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerview.setAdapter(mSongAdapter);
mRecyclerview.setLayoutManager(linearLayout);
}
public ArrayList<Song> getArraySongs() {
return mSongAdapter.getArr();
}
public void setAnimation(int position, int id, boolean isPlaying) {
mSongAdapter.mSongId = id;
mSongAdapter.mIsPlaying = isPlaying;
if (position == 0) {
mRecyclerview.smoothScrollToPosition(position);
} else {
mRecyclerview.smoothScrollToPosition(position + 1);
}
mSongAdapter.notifyDataSetChanged();
}
public SongAdapter getAdapter() {
return mSongAdapter;
}
public void setPosition(int position) {
mPosition = position;
}
public void setService(MediaPlaybackService service) {
mService = service;
}
}
<file_sep>package com.example.music.fragment;
import android.view.MenuItem;
import android.view.View;
import android.widget.PopupMenu;
import android.widget.Toast;
import com.example.music.Interface.IFavoriteControl;
import com.example.music.R;
import com.example.music.Song;
public class FavoriteSongsFragment extends BaseSongListFragment {
public FavoriteSongsFragment() {
}
public FavoriteSongsFragment(IFavoriteControl favoriteControl) {
super(favoriteControl);
}
@Override
public void updateAdapter() {
mSongAdapter.getFavoriteList(getContext());
mSongAdapter.notifyDataSetChanged();
}
@Override
public void updatePopupMenu(View view) {
mPopup = new PopupMenu(getContext(), view.findViewById(R.id.action_more));
mPopup.getMenuInflater().inflate(R.menu.menu_popup_media_playback, mPopup.getMenu());
mPopup.setOnMenuItemClickListener(this);
mPopup.show();
}
@Override
public boolean onMenuItemClick(MenuItem item) {
Song song = (Song) mSongAdapter.getArr().get(mPosition);
int id = song.getmId();
if (mPosition < mSongAdapter.getArr().size()) {
mFavoriteSongsDB.setFavorite(id, 1);
mFavoriteSongsDB.updateCount(id, 0);
Toast.makeText(getContext(), R.string.remove_favorite, Toast.LENGTH_SHORT).show();
mIsFavorite = false;
}
song.setmIsFavorite(mIsFavorite);
mFavoriteControl.updateUI(id, mIsFavorite);
updateAdapter();
return true;
}
}
<file_sep>package com.example.music.adapter;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Typeface;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.music.Interface.IClickItem;
import com.example.music.R;
import com.example.music.Song;
import com.example.music.database.FavoriteSongsDB;
import com.example.music.database.SongProvider;
import com.example.music.fragment.BaseSongListFragment;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import es.claucookie.miniequalizerlibrary.EqualizerView;
public class SongAdapter extends RecyclerView.Adapter<SongAdapter.ViewHolder> implements Filterable {
private com.example.music.Interface.IClickItem IClickItem;
public int mPosition;
public int mSongId;
public boolean mIsPlaying;
private BaseSongListFragment mBaseFragment;
public ArrayList<Song> mArraySongs;
private ArrayList<Song> mListFiltered;
public SongAdapter() {
}
public SongAdapter(BaseSongListFragment fragment) {
mBaseFragment = fragment;
}
@NonNull
@Override
public SongAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.song_row, parent, false);
return new ViewHolder(view, this);
}
@Override
public void onBindViewHolder(@NonNull SongAdapter.ViewHolder holder, int position) {
Song song = mArraySongs.get(position);
holder.mSongOrder.setText(position + 1 + "");
holder.mTvSongName.setText(song.getmTitle());
holder.mTvDuration.setText(song.getmDuration());
if (song.getmId() == mSongId) {
holder.mTvSongName.setTypeface(Typeface.DEFAULT_BOLD);
holder.mSongOrder.setVisibility(View.INVISIBLE);
holder.mEqualizer.setVisibility(View.VISIBLE);
if (mIsPlaying) {
holder.mEqualizer.animateBars();
} else {
holder.mEqualizer.stopBars();
}
} else {
holder.mTvSongName.setTypeface(Typeface.DEFAULT);
holder.mEqualizer.stopBars();
holder.mEqualizer.setVisibility(View.GONE);
holder.mSongOrder.setVisibility(View.VISIBLE);
}
}
@Override
public int getItemCount() {
return mArraySongs.size();
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence charSequence) {
String songTitle = charSequence.toString();
ArrayList<Song> filteredList = new ArrayList<>();
if (songTitle.isEmpty()) {
filteredList = mListFiltered;
} else {
for (Song song : mListFiltered) {
if (song.getmTitle().toLowerCase().contains(songTitle.toLowerCase())) {
filteredList.add(song);
}
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = filteredList;
return filterResults;
}
@Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
mArraySongs = (ArrayList<Song>) filterResults.values;
notifyDataSetChanged();
}
};
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView mActionMore;
TextView mTvSongName, mTvDuration, mSongOrder;
EqualizerView mEqualizer;
WeakReference<SongAdapter> mAdapter;
public ViewHolder(@NonNull final View itemView, SongAdapter adapter) {
super(itemView);
mAdapter = new WeakReference<>(adapter);
mSongOrder = itemView.findViewById(R.id.song_order);
mTvSongName = itemView.findViewById(R.id.song_title);
mTvDuration = itemView.findViewById(R.id.duration);
mActionMore = itemView.findViewById(R.id.action_more);
mEqualizer = itemView.findViewById(R.id.equalizer);
//initialize event click item in recyclerview
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mAdapter.get().mPosition = getAdapterPosition();
IClickItem = (IClickItem) view.getContext();
IClickItem.onClickItem(mPosition);
}
});
mActionMore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mBaseFragment.updatePopupMenu(v);
mBaseFragment.setPosition(getAdapterPosition());
}
});
}
}
//method read song from storage
public void getAllSongs(Context context) {
Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Audio.Media.IS_MUSIC + "=1",
null, MediaStore.Audio.Media.TITLE + " ASC");
mArraySongs = new ArrayList<>();
if (cursor != null) {
while (cursor.moveToNext()) {
String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
String resource = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
int time = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
int albumId = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
int id = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media._ID));
//format duration to mm:ss
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");
String duration = simpleDateFormat.format(time);
//add Song to songList
Song song = new Song(title, artist, id, albumId, duration, resource);
mArraySongs.add(song);
}
mListFiltered = new ArrayList<>();
mListFiltered.addAll(mArraySongs);
cursor.close();
notifyDataSetChanged();
}
}
public ArrayList getArr() {
return mArraySongs;
}
public void getFavoriteList(Context context) {
mListFiltered = new ArrayList<>();
Cursor cursor = context.getContentResolver().query(SongProvider.CONTENT_URI, null,
FavoriteSongsDB.IS_FAVORITE + "=2", null, null);
mArraySongs = new ArrayList<>();
if (cursor != null) {
while (cursor.moveToNext()) {
int idOfFavoriteSong = cursor.getInt(cursor.getColumnIndex(FavoriteSongsDB.ID_PROVIDER));
Cursor cursor1 = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Audio.Media.IS_MUSIC + "=1",
null, MediaStore.Audio.Media.TITLE + " ASC");
if (cursor1 != null) {
while (cursor1.moveToNext()) {
String title = cursor1.getString(cursor1.getColumnIndex(MediaStore.Audio.Media.TITLE));
String artist = cursor1.getString(cursor1.getColumnIndex(MediaStore.Audio.Media.ARTIST));
String resource = cursor1.getString(cursor1.getColumnIndex(MediaStore.Audio.Media.DATA));
int time = cursor1.getInt(cursor1.getColumnIndex(MediaStore.Audio.Media.DURATION));
int albumId = cursor1.getInt(cursor1.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
int id = cursor1.getInt(cursor1.getColumnIndex(MediaStore.Audio.Media._ID));
//format duration to mm:ss
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");
String duration = simpleDateFormat.format(time);
//add Song to songList
if (id == idOfFavoriteSong) {
Song song = new Song(title, artist, id, albumId, duration, resource);
mArraySongs.add(song);
mListFiltered.add(song);
}
}
cursor1.close();
notifyDataSetChanged();
}
}
cursor.close();
}
}
}<file_sep>package com.example.music.Interface;
public interface IMediaControl {
void onClick(int id, boolean isPlaying);
void onClickShuffle(boolean isShuffle);
void onClickRepeat(String repeat);
void onClickList();
}
<file_sep>package com.example.music.fragment;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.music.ActivityMusic;
import com.example.music.Interface.IFavoriteControl;
import com.example.music.Interface.IMediaControl;
import com.example.music.R;
import com.example.music.Song;
import com.example.music.database.FavoriteSongsDB;
import com.example.music.service.MediaPlaybackService;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import static android.content.Context.MODE_PRIVATE;
public class MediaPlaybackFragment extends Fragment implements View.OnClickListener {
private Song mSong;
public final static String FALSE = "false";
public final static String TRUE = "true";
public final static String REPEAT = "repeat";
private ImageView mImgArtTop,
mImgQueue, mImgFavorite, mImgRepeat, mImgPrev, mImgPlay,
mImgNext, mImgShuffle, mImgSongArt;
private TextView mTvSongTitle, mTvArtist, mTvCurrentTime, mTvTotalTime;
private SeekBar mSbDuration;
private IMediaControl mMediaControl;
private IFavoriteControl mFavoriteControl;
private boolean mIsShuffle;
private String mRepeat;
private boolean mIsFavorite = false;
private MediaPlaybackService mService;
private Handler mHandler;
private Runnable mRunnable;
private ArrayList<Song> mArraySongs;
private int mPosition;
public MediaPlaybackFragment(IMediaControl mediaControl, IFavoriteControl favoriteControl) {
mFavoriteControl = favoriteControl;
mMediaControl = mediaControl;
}
public MediaPlaybackFragment() {
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_media_playback, container, false);
mImgArtTop = view.findViewById(R.id.sub_art_top);
mImgSongArt = view.findViewById(R.id.music_art);
mImgQueue = view.findViewById(R.id.img_queu);
mImgFavorite = view.findViewById(R.id.img_favorite);
mImgRepeat = view.findViewById(R.id.img_repeat);
mImgPrev = view.findViewById(R.id.img_prev);
mImgPlay = view.findViewById(R.id.img_play);
mImgNext = view.findViewById(R.id.img_next);
mImgShuffle = view.findViewById(R.id.img_shuffle);
mTvSongTitle = view.findViewById(R.id.sub_title_top);
mTvArtist = view.findViewById(R.id.sub_artist_top);
mTvCurrentTime = view.findViewById(R.id.tv_current_time);
mTvTotalTime = view.findViewById(R.id.tv_total_time);
mSbDuration = view.findViewById(R.id.sb_duration);
//event click play, pause, next, prev, shuffle, repeat, queue music
mImgPlay.setOnClickListener(this);
mImgNext.setOnClickListener(this);
mImgPrev.setOnClickListener(this);
mImgRepeat.setOnClickListener(this);
mImgShuffle.setOnClickListener(this);
mImgQueue.setOnClickListener(this);
mImgFavorite.setOnClickListener(this);
//event seek bar change
seekBarChange();
if (mService != null) {
updateTimeSong();
mHandler.postDelayed(mRunnable, 0);
}
SharedPreferences mSharedPrf = getActivity().getSharedPreferences(MediaPlaybackService.PRF_NAME, MODE_PRIVATE);
mIsShuffle = mSharedPrf.getBoolean(MediaPlaybackService.PRF_SHUFFLE, false);
mRepeat = mSharedPrf.getString(MediaPlaybackService.PRF_REPEAT, FALSE);
if (mService != null) {
checkPlaying(mService.isPlaying());
}
Bundle mBundle = getArguments();
if (mBundle != null) {
mSong = mBundle.getParcelable(ActivityMusic.BUNDLE_SONG_KEY);
setSongInfo(mSong);
}
mIsFavorite = mSong.getIsIsFavorite();
checkShuffle();
checkRepeat();
checkFavorite(mIsFavorite);
boolean isPortrait = mSharedPrf.getBoolean(ActivityMusic.PRF_IS_PORTRAIT, false);
if (isPortrait) {
mImgQueue.setVisibility(View.VISIBLE);
} else {
mImgQueue.setVisibility(View.INVISIBLE);
}
return view;
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onStop() {
super.onStop();
}
@Override
public void onDestroy() {
super.onDestroy();
if (mHandler != null) {
mHandler.removeCallbacks(mRunnable);
}
}
private void checkShuffle() {
if (mIsShuffle) {
setImgShuffle(R.drawable.ic_play_shuffle_selected);
} else {
setImgShuffle(R.drawable.ic_play_shuffle_default);
}
}
private void checkRepeat() {
switch (mRepeat) {
case FALSE:
setImgRepeat(R.drawable.ic_play_repeat_default);
break;
case TRUE:
setImgRepeat(R.drawable.ic_play_repeat_selected);
break;
case REPEAT:
setImgRepeat(R.drawable.ic_play_repeat_1);
break;
}
}
public void checkPlaying(boolean isPlaying) {
if (isPlaying) {
mImgPlay.setImageResource(R.drawable.ic_action_pause);
} else {
mImgPlay.setImageResource(R.drawable.ic_action_play);
}
}
public void setFavorite(int id, boolean isFavorite) {
mIsFavorite = isFavorite;
mPosition = mService.getPosition();
mArraySongs = mService.getArraySongs();
mSong = mArraySongs.get(mPosition);
int mId = mSong.getmId();
if (id == mId) {
checkFavorite(mIsFavorite);
mSong.setmIsFavorite(mIsFavorite);
}
}
public void checkFavorite(boolean isFavorite) {
mIsFavorite = isFavorite;
if (mIsFavorite) {
setImgFavorite(R.drawable.ic_favorite_selected);
} else {
setImgFavorite(R.drawable.ic_favorite_default);
}
}
public void setImgPlay(boolean isPlaying) {
if (isPlaying) {
mImgPlay.setImageResource(R.drawable.ic_action_pause);
} else {
mImgPlay.setImageResource(R.drawable.ic_action_play);
}
}
public void setImgShuffle(int res) {
mImgShuffle.setImageResource(res);
}
public void setShuffle(boolean isShuffle) {
mIsShuffle = isShuffle;
}
public void setImgRepeat(int res) {
mImgRepeat.setImageResource(res);
}
public void setRepeat(String repeat) {
mRepeat = repeat;
}
public void setImgFavorite(int res) {
mImgFavorite.setImageResource(res);
}
public void setSongInfo(Song song) {
mSong = song;
mTvSongTitle.setText(mSong.getmTitle());
mTvArtist.setText(mSong.getmArtist());
mTvTotalTime.setText(mSong.getmDuration());
mImgArtTop.setImageBitmap(mSong.getAlbumArt(getContext(), mSong.getmResource()));
mImgSongArt.setImageBitmap(mSong.getAlbumArt(getContext(), mSong.getmResource()));
checkFavorite(mSong.getIsIsFavorite());
}
@Override
public void onDetach() {
super.onDetach();
}
public void setCurrentTime(String currentTime) {
mTvCurrentTime.setText(currentTime);
}
public void setCurrentSeekBar(int currentTime, int duration) {
mSbDuration.setProgress(currentTime);
mSbDuration.setMax(duration);
}
public void seekBarChange() {
mSbDuration.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
mService.playerSeekTo(mSbDuration.getProgress());
}
});
}
@Override
public void onClick(View view) {
mArraySongs = mService.getArraySongs();
mPosition = mService.getPosition();
if (mPosition == -1) {
mPosition = 0;
}
mService.setPosition(mPosition);
switch (view.getId()) {
//click play button
case R.id.img_play:
if (mService.isPlaying()) {
mService.pauseSong();
} else {
if (mService.getCurrentTime() == 0) {
mService.playSong();
} else {
mService.resumeSong();
}
}
mSong = mArraySongs.get(mPosition);
break;
//click next button
case R.id.img_next:
mService.playNext();
break;
//click prev button
case R.id.img_prev:
mService.playPrev();
break;
//click shuffle
case R.id.img_shuffle:
if (mIsShuffle) {
mIsShuffle = false;
} else {
mIsShuffle = true;
}
checkShuffle();
mService.putShuffleToPrf(mIsShuffle);
mMediaControl.onClickShuffle(mIsShuffle);
break;
//click repeat
case R.id.img_repeat:
switch (mRepeat) {
case FALSE:
mRepeat = TRUE;
break;
case TRUE:
mRepeat = REPEAT;
break;
case REPEAT:
mRepeat = FALSE;
break;
}
checkRepeat();
mMediaControl.onClickRepeat(mRepeat);
mService.putRepeatToPrf(mRepeat);
break;
//click favorite
case R.id.img_favorite:
FavoriteSongsDB favoriteSongsDB = new FavoriteSongsDB(getContext());
if (mIsFavorite) {
mIsFavorite = false;
favoriteSongsDB.setFavorite(mSong.getmId(), 1);
Toast.makeText(mService, R.string.remove_favorite, Toast.LENGTH_SHORT).show();
} else {
mIsFavorite = true;
favoriteSongsDB.addToFavoriteDB(mSong.getmId());
favoriteSongsDB.setFavorite(mSong.getmId(), 2);
Toast.makeText(mService, R.string.add_to_favorite, Toast.LENGTH_SHORT).show();
}
mFavoriteControl.onClickFavorite();
mSong.setmIsFavorite(mIsFavorite);
checkFavorite(mIsFavorite);
break;
case R.id.img_queu:
mMediaControl.onClickList();
}
mMediaControl.onClick(mSong.getmId(), mService.isPlaying());
}
private void updateTimeSong() {
mHandler = new Handler();
mRunnable = new Runnable() {
@Override
public void run() {
SimpleDateFormat format = new SimpleDateFormat("mm:ss");
int mCurrentTime = mService.getCurrentTime();
int mDuration = mService.getDuration();
setCurrentTime(format.format(mCurrentTime));
setCurrentSeekBar(mCurrentTime, mDuration);
mHandler.postDelayed(this, 1000);
}
};
}
public void setService(MediaPlaybackService service) {
mService = service;
}
}
<file_sep>package com.example.music.Interface;
public interface IClickItem {
void onClickItem(int position);
}
<file_sep>package com.example.music.Interface;
public interface IFavoriteControl {
void onClickFavorite();
void updateUI(int id, boolean isFavorite);
}
|
6d7ed844cd0214df2d8d368977a7f8ba5ead3e59
|
[
"Java"
] | 7
|
Java
|
tientoan2503/MusicApp
|
cb736384dc271b08cc4b0678ef3879633c81b730
|
5458307e41546f6ea047cb24ba6aca34c1df5835
|
refs/heads/master
|
<file_sep>import React from 'react'
import Layout from './containers/Layout';
import Login from './containers/Login';
LoginPage.displayName = 'Login Page'
function LoginPage () {
return (
<Layout>
<Login />
</Layout>
)
}
export default LoginPage
<file_sep>import * as TYPES from './messages.types'
import { takeLatest, call, put, select } from 'redux-saga/effects'
import { Messages } from '../../api'
import { SetMessages, GetMessages, AllMessagesLoaded, LoadingMessages } from './messages.actions'
import { RequestError } from '../shared/shared.actions'
import { SelectLastMessage } from '../../main.reducer'
export default [
takeLatest(TYPES.GET_MESSAGES, GetMessagesSaga)
]
function* GetMessagesSaga ({ payload: limit }) {
yield put(LoadingMessages(true))
const lastDoc = yield select(SelectLastMessage)
const res = yield call(Messages.LoadMore, lastDoc && lastDoc.doc, limit)
if (res && !res.empty) {
const messages = []
res.docs.forEach(doc => {
const message = doc.data()
message.doc = doc
message.body = message.body
.replace(/@(?!channel)[\w-_]+/g, str => `<strong class="bg-primary text-white px-1">${ str }</strong>`)
.replace(/@channel/g, str => `<strong class="bg-warning px-1">${ str }</strong>`)
messages.push(message)
})
if (messages.length < limit)
yield put(AllMessagesLoaded())
yield put(SetMessages(messages))
} else {
yield put(
RequestError(
GetMessages(limit),
'Could Not Retrieve Messages, Retrying...',
new Error(res.message)
)
)
}
yield put(LoadingMessages(false))
}
<file_sep>import * as TYPES from './messages.types'
const initialState = {
all: [],
filter: '',
loading: true,
allLoaded: false
}
export default (state = initialState, { type, payload }) => {
switch (type) {
case TYPES.SET_MESSAGES:
state = {
...state,
all: state.all.concat(payload)
}
return state
case TYPES.FILTER_MESSAGES:
state = {
...state,
filter: payload
}
return state
case TYPES.LOADING_MESSAGES:
state = {
...state,
loading: payload
}
return state
case TYPES.ALL_MESSAGES_LOADED:
state = {
...state,
allLoaded: true
}
return state
default:
return state
}
}
<file_sep>import React from 'react'
import { connect } from 'react-redux'
import { SelectActiveUser } from '../../store/main.reducer'
import { Logout } from '../../store/modules/users/users.actions'
import Header from '../presentation/layout/Header'
import Sidebar from '../presentation/layout/Sidebar'
const mapStateToProps = state => ({
user: SelectActiveUser(state)
})
const mapDispatchToProps = {
Logout
}
function Layout ({ user, Logout, children }) {
return (
<div>
<header>
<Header />
</header>
<div className="d-flex">
<nav className="p-3">
<Sidebar user={user} logout={Logout} />
</nav>
<main className="flex-grow-1 p-5">
{children}
</main>
</div>
</div>
)
}
export default connect(mapStateToProps, mapDispatchToProps)(Layout)
<file_sep>import React from 'react'
import { object } from 'prop-types'
import Card from '../shared/Card'
MessageCard.displayName = 'Message Card'
MessageCard.propTypes = {
message: object.isRequired
}
function MessageCard ({ message }) {
const timeString = new Date(message.created_at.seconds * 1000).toLocaleTimeString()
return (
<Card className="message-card mb-3">
<span className="username">
{message.sender_username}
</span>
<span className="time-sent float-right">
{timeString}
</span>
<div className="message" dangerouslySetInnerHTML={{ __html: message.body }} />
</Card>
)
}
export default MessageCard
<file_sep>import * as TYPES from './users.types'
import { put, call, takeLatest, select } from 'redux-saga/effects'
import { push } from 'connected-react-router'
import { Users } from '../../api'
import { SetUser } from './users.actions'
import { SelectRouterLocation } from '../../main.reducer'
import { toastr } from 'react-redux-toastr'
export default [
takeLatest(TYPES.LOGIN, LoginSaga),
takeLatest(TYPES.LOGOUT, LogoutSaga)
]
function* LoginSaga ({ payload: loginModel, meta: formik }) {
const res = yield call(Users.Login, loginModel)
if (res && res.status === 200) {
yield put(SetUser(res.data))
const location = yield select(SelectRouterLocation)
if (location.state && location.state.from)
return yield put(push(location.state.from))
yield put(push('/Messages'))
} else if (res && res.status === 401) {
toastr.error('Invalid Credentials', 'Wrong username and/or password')
}
formik && formik.setSubmitting(false)
}
function* LogoutSaga () {
yield call(Users.Logout)
yield put(push('/'))
}
<file_sep>import * as TYPES from './messages.types'
export const GetMessages = (limit = 8) => ({
type: TYPES.GET_MESSAGES,
payload: limit
})
export const SetMessages = messages => ({
type: TYPES.SET_MESSAGES,
payload: messages
})
export const FilterMessages = searchText => ({
type: TYPES.FILTER_MESSAGES,
payload: searchText
})
export const AllMessagesLoaded = () => ({
type: TYPES.ALL_MESSAGES_LOADED
})
export const LoadingMessages = loading => ({
type: TYPES.LOADING_MESSAGES,
payload: loading
})
<file_sep>git clone https://github.com/hunterwebapps/field-chat.git
cd field-chat
npm install
npm start
<file_sep>export const
REQUEST_ERROR = 'REQUEST_ERROR'
<file_sep>import { all } from 'redux-saga/effects'
import usersWatcher from './modules/users/users.saga'
import messagesWatcher from './modules/messages/messages.saga'
import sharedWatcher from './modules/shared/shared.saga'
export default function* rootSaga () {
yield all([
...usersWatcher,
...messagesWatcher,
...sharedWatcher
])
}
<file_sep>import * as TYPES from './shared.types'
import { put, select, takeEvery } from 'redux-saga/effects'
import { delay } from 'redux-saga'
import { toastr } from 'react-redux-toastr'
import { SelectErrorCount } from '../../main.reducer'
export default [
takeEvery(TYPES.REQUEST_ERROR, RequestErrorSaga),
takeEvery('@@router/LOCATION_CHANGE', RedirectErrorSaga)
]
function* RequestErrorSaga ({ payload: { action, message, exception } }) {
const errorCount = yield select(SelectErrorCount)
if (errorCount > 10) {
toastr.error('Loading Error', 'Could not complete request. Please check your internet and try refreshing.')
throw new Error(`Message: ${ exception.message }, Action: ${ JSON.stringify(action) }`)
}
toastr.error(message)
yield delay(5000)
yield put(action)
}
function RedirectErrorSaga ({ payload: { location } }) {
const { state } = location
if (state && state.error === 403)
toastr.warning('Unauthorized', 'Please Login!')
if (state && state.error === 404)
toastr.info('Not Found', 'We can\'t find that page!')
}
<file_sep>import React from 'react'
import Messages from './containers/Messages'
import Layout from './containers/Layout'
function MessagesPage () {
return (
<Layout>
<Messages />
</Layout>
)
}
export default MessagesPage
<file_sep>import React from 'react'
import { connect } from 'react-redux'
import { Route, Switch, Redirect } from 'react-router-dom'
import { Users } from './store/api'
import { Login } from './store/modules/users/users.actions'
import Toastr from 'react-redux-toastr'
import ProtectedRoute from './components/containers/ProtectedRoute'
import LoginPage from './components/Login.page'
import MessagesPage from './components/Messages.page'
const mapDispatchToProps = {
Login
}
class App extends React.Component {
componentDidMount () {
this.props.Login()
}
render () {
return (
<React.Fragment>
<Toastr />
<Switch>
<Route exact path="/" component={LoginPage} />
<ProtectedRoute
path="/Messages"
component={MessagesPage}
authCheck={Users.IsLoggedIn}
redirectTo="/"
/>
<Route render={() =>
<Redirect to={{
pathname: '/',
state: { error: 404 }
}} />
} />
</Switch>
</React.Fragment>
)
}
}
export default connect(null, mapDispatchToProps)(App)
<file_sep>import React from 'react'
function Header () {
return (
<h1>Field Chat Test</h1>
)
}
export default Header
<file_sep>import React from 'react'
import { string, func, bool } from 'prop-types'
import { Route, Redirect } from 'react-router-dom'
ProtectedRoute.displayName = 'Protected Route'
ProtectedRoute.propTypes = {
authCheck: func.isRequired,
path: string.isRequired,
component: func.isRequired,
redirectTo: string,
exact: bool
}
function ProtectedRoute ({
authCheck,
component: Component,
redirectTo,
...rest
}) {
return (
<Route
{...rest}
render={props => authCheck() ?
<Component {...props} />
:
<Redirect
to={{
pathname: redirectTo || '/',
state: { from: props.location, error: 403 }
}}
/>
}
/>
)
}
export default ProtectedRoute
<file_sep>import { combineReducers } from 'redux'
import usersReducer from './modules/users/users.reducer'
import messagesReducer from './modules/messages/messages.reducer'
import sharedReducer from './modules/shared/shared.reducer'
import { reducer as toastrReducer } from 'react-redux-toastr'
export default combineReducers({
users: usersReducer,
messages: messagesReducer,
shared: sharedReducer,
toastr: toastrReducer
})
/* * * * * * *
* Selectors *
* * * * * * */
// Shared
export const SelectErrorCount = state => state.shared.errors
// Users
export const SelectActiveUser = state => state.users.active
// Messages
export const SelectMessages = state => state.messages.all
export const SelectLastMessage = state => state.messages.all[state.messages.all.length - 1]
export const SelectFilteredMessages = state =>
state.messages.all.filter(msg =>
msg.body.includes(state.messages.filter) ||
msg.sender_username.includes(state.messages.filter))
export const SelectAllMessagesLoaded = state => state.messages.allLoaded
export const SelectMessagesLoading = state => state.messages.loading
// Router
export const SelectRouterLocation = state => state.router.location
<file_sep>import * as React from 'react'
import { Field } from 'formik'
export const Textbox = ({ colWidths, label, type, errors, ...rest }) =>
<div className={colWidths}>
<div className="form-group">
{label && <label>{label}</label>}
{errors &&
<ErrorBlock
error={errors.error}
touched={errors.touched}
dirty={errors.dirty}
/>
}
<Field
type={type || 'text'}
className="form-control"
{...rest}
/>
</div>
</div>
export const Checkbox = ({ colWidths, label, type, ...rest }) =>
<div className={colWidths}>
<div className="form-group">
<label>
<Field
type={type || 'checkbox'}
{...rest}
/>
{` ${ label }`}
</label>
</div>
</div>
export const ErrorBlock = ({ error, touched, dirty }) => {
if (dirty === undefined || dirty)
if (touched && error)
return <span className="form-error text-danger"><small>{' ' + error}</small></span>
return null
}
<file_sep>import React from 'react'
import { func } from 'prop-types'
import { connect } from 'react-redux'
import LoginForm from '../presentation/login/Login.form'
import { Login as LoginAction } from '../../store/modules/users/users.actions'
const mapDispatchToProps = {
LoginAction
}
class Login extends React.Component {
state = {
registering: false
}
static displayName = 'Login Page'
static propTypes = {
LoginAction: func.isRequired
}
render () {
const {
LoginAction
} = this.props
const {
registering
} = this.state
return (
<React.Fragment>
{registering ?
{/* TODO: Add Register form here. Manage visibility of login or register with local state. */ }
:
<LoginForm login={LoginAction} />
}
</React.Fragment>
)
}
}
export default connect(null, mapDispatchToProps)(Login)
<file_sep>import React from 'react'
import { arrayOf, object } from 'prop-types'
import MessageCard from './MessageCard'
MessagesList.displayName = 'Messages List'
MessagesList.propTypes = {
messages: arrayOf(object).isRequired
}
function MessagesList ({ messages }) {
return messages.map(msg =>
<MessageCard key={msg.id} message={msg} />
)
}
export default MessagesList
<file_sep>export const
LOGIN = 'LOGIN',
LOGOUT = 'LOGOUT',
SET_USER = 'SET_USER'
<file_sep>import db from '../firebase'
import axios from 'axios'
let authToken = localStorage.getItem('auth-token') || sessionStorage.getItem('auth-token')
let authUsername = localStorage.getItem('username') || sessionStorage.getItem('username')
export const Users = {
IsLoggedIn: () => (authToken && authUsername) ? true : false,
Login: async loginModel => {
if (loginModel) {
const { username, password, rememberMe } = loginModel
authToken = window.btoa(username + ':' + password)
authUsername = username
const storage = rememberMe ? localStorage : sessionStorage
storage.setItem('auth-token', authToken)
storage.setItem('username', authUsername)
}
if (authToken && authUsername) {
const res = await axios.get('/default/FCCodeTestAuth', {
headers: { Authorization: `Basic ${ authToken }` }
}).catch(err => err)
if (res && res.status === 200) {
axios.defaults.headers.common['Authorization'] = `Basic ${ authToken }`
return {
status: 200,
data: { username: authUsername }
}
}
Users.Logout()
return {
status: 401,
message: 'Failed to authenticate user'
}
}
return { status: 204 }
},
Logout: async () => {
authToken = null
authUsername = null
sessionStorage.removeItem('auth-token')
sessionStorage.removeItem('username')
localStorage.removeItem('auth-token')
localStorage.removeItem('username')
delete axios.defaults.headers.common['Authorization']
}
}
export const Messages = {
Get: async messageId =>
await db.collection('messages').doc(messageId).get(),
LoadMore: async (lastDoc, limit) => {
let query = db.collection('messages').orderBy('created_at', 'desc')
if (lastDoc) query = query.startAfter(lastDoc)
return await query.limit(limit).get().catch(err => err)
}
}
<file_sep>import React from 'react'
import { connect } from 'react-redux'
import { GetMessages, FilterMessages } from '../../store/modules/messages/messages.actions'
import { SelectFilteredMessages, SelectMessagesLoading, SelectAllMessagesLoaded } from '../../store/main.reducer'
import throttle from 'lodash/throttle'
import MessagesList from '../presentation/messages/MessagesList'
import FilterBox from '../presentation/shared/FilterBox'
const mapStateToProps = state => ({
messages: SelectFilteredMessages(state),
loading: SelectMessagesLoading(state),
allLoaded: SelectAllMessagesLoaded(state)
})
const mapDispatchToProps = {
GetMessages,
FilterMessages
}
class Messages extends React.Component {
componentDidMount () {
this.props.GetMessages()
window.addEventListener('scroll', this.loadInfinitely)
}
loadInfinitely = throttle(e => {
const { innerHeight, document: { documentElement } } = window
if (innerHeight + documentElement.scrollTop > documentElement.offsetHeight - 200) {
if (this.props.allLoaded)
return window.removeEventListener('scroll', this.loadInfinitely)
this.props.GetMessages(8)
}
}, 200)
componentWillUnmount () {
window.removeEventListener('scroll', this.loadInfinitely)
}
render () {
const {
messages,
FilterMessages,
loading,
allLoaded
} = this.props
return (
<React.Fragment>
<div className="w-25 mb-3">
<FilterBox filterChanged={FilterMessages} />
</div>
<div className="w-50">
<MessagesList messages={messages} />
</div>
{loading && !allLoaded &&
<div className="lds-ring"><div></div><div></div><div></div><div></div></div>
}
</React.Fragment>
)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Messages)
|
1797ef2764b64085701fb7e0c9564d7df1f259fd
|
[
"JavaScript",
"Markdown"
] | 22
|
JavaScript
|
hunterwebapps/field-chat
|
8392d1d4e3633bb44b097351003a83d2394d651c
|
38e10fc9bb9e2767d1e6379dfc66df036a31fc7f
|
refs/heads/master
|
<repo_name>imbmf/pmvcb<file_sep>/pmvcb
#!/bin/bash
# Author: <NAME>
# Created Date: 15/07/2011
#
# Poor man virtual consolidated backup
vmware_cmd=vim-cmd
vmkfstools_cmd=vmkfstools
error() {
echo "ERROR: $@" >&2
exit -1
}
logger() {
echo "INFO: $@" >&2
}
warning() {
echo "WARNING: $@" >&2
}
get_all_vms() {
$ssh_cmd "vim-cmd vmsvc/getallvms" | sed 's/[[:blank:]]\{3,\}/ /g' | awk -F' ' '{print "\""$1"\";\""$2"\";\""$3"\""}' | sed 's/\] /\]\";\"/g' | sed '1,1d'
}
create_snapshot() {
if $ssh_cmd "vim-cmd vmsvc/snapshot.create \"$1\" \"$2\" \"$2\" \"$vm_snapshot_memory\" \"$vm_snapshot_quiesce\""; then
logger "[$vm] Snapshot $2 created"
else
error "[$vm] Unable to create snapshot $2"
fi
}
consolidate_snapshot() {
vm_id=$1
if [ "$vm_snapshot_useid" == "1" ]; then
sn_id=$($ssh_cmd ${vmware_cmd} vmsvc/snapshot.get ${vm_id} | sed -ne "/${snapshot_prefix}-$vm/{n;s/.*Snapshot Id *: *//p;}")
else
snapshot_id=
fi
if $ssh_cmd ${vmware_cmd} vmsvc/snapshot.remove ${vm_id} ${sn_id}; then
logger "[$vm] Snapshot consolidated"
else
logger "[$vm] Error during snapshot consolidation"
fi
}
snapshot_exists(){
#$1=VMX directory
if $ssh_cmd "ls \"$1\" | grep -q \"\-delta\.vmdk\""; then
error "[$vm] Snapshots found for this VM, please commit all snapshots before continuing!"
fi
}
get_vmdks() {
vmx_path="$1"
vmx_filename=$(basename "$vmx_path")
local_vmx_dir=$(mktemp -d /tmp/vmx.XXXXXX)
local_vmx="$local_vmx_dir"/"$vmx_filename"
scp $ssh_opts $user@$host:"${vmx_path// /\\ }" "$local_vmx_dir"
if [ -f "$local_vmx" ]; then
logger "[$vm] local copy of vmx in $local_vmx"
else
rm -rf "$local_vmx_dir"
error "[$vm] cannot copy vmx in local"
fi
vmdks_found=$(grep -iE '(scsi|ide)' "$local_vmx" | grep -i fileName | awk -F " " '{print $1}')
OIFS=$IFS
IFS=$'\n'
for disk in $vmdks_found; do
scsi_id=$(echo ${disk%%.*})
grep -i "${scsi_id}.present" "${local_vmx}" | grep -i "true" > /dev/null 2>&1
if [ $? -eq 0 ]; then
grep -i "${scsi_id}.mode" "${local_vmx}" | grep -i "independent" > /dev/null 2>&1
if [ $? -eq 1 ]; then
# not indipendent disk
grep -i "${scsi_id}.deviceType" "${local_vmx}" | grep -i "scsi-hardDisk" > /dev/null 2>&1
if [ $? -eq 0 ]; then
d=$(grep -i ${scsi_id}.fileName "${local_vmx}" | awk -F "\"" '{print $2}')
vmdks="$vmdks:$d"
else
grep -i ${scsi_id}.fileName "${local_vmx}" | grep -i ".vmdk" > /dev/null 2>&1
if [ $? -eq 0 ]; then
d=$(grep -i ${scsi_id}.fileName "${local_vmx}" | awk -F "\"" '{print $2}')
vmdks="$vmdks:$d"
fi
fi
else
# indipendent disk are not affected by snapshot
warning "[$vm] Indipendent disk found: \"$disk\" not affected by backup"
fi
fi
done
IFS=$OIFS
echo ${vmdks/:/}
rm -rf "$local_vmx_dir"
}
run () {
vmdata=$(get_all_vms | grep "$vm") || error "$vm not found"
vmfs_volume=$(echo $vmdata | awk -F ";" '{print $3}' | sed 's/\[//;s/\]//;s/"//g')
vmx_conf=$(echo $vmdata| awk -F ";" '{print $4}' | sed 's/\[//;s/\]//;s/"//g')
vmx_path="/vmfs/volumes/${vmfs_volume}/${vmx_conf}"
vmx_dir=$(dirname "${vmx_path}")
vm_id=$(echo $vmdata | awk -F ";" '{print $1}' | sed 's/"//g')
logger "[$vm] VMFS Volume: $vmfs_volume"
logger "[$vm] VMX: $vmx_conf"
logger "[$vm] VMX Path: $vmx_path"
logger "[$vm] VMX Dir: $vmx_dir"
logger "[$vm] VM ID: $vm_id"
snapshot_exists "$vmx_dir"
vmdks=$(get_vmdks "$vmx_path")
create_snapshot "$vm_id" "${snapshot_prefix}-$vm"
start_iter_snap=0
while [ $($ssh_cmd $vmware_cmd vmsvc/snapshot.get "$vm_id" | wc -l) -eq 1 ]; do
if [ $start_iter_snap -ge $snapshot_timeout ]; then
error "[$vm] Snapshot timed out."
break
fi
logger "[$vm] Waiting for snapshot creation to be completed. $start_iter_snap"
sleep 60
start_iter_snap=$(($start_iter_snap + 1))
done
$ssh_cmd "mkdir -p \"$backup_dir\""
logger "[$vm] Saving VMX"
$ssh_cmd "cp \"$vmx_path\" \"$backup_dir\""
OIFS=$IFS
IFS=:
for vmdk in $vmdks; do
IFS=$OIFS
echo $vmdk | grep "^/vmfs/volumes" > /dev/null 2>&1
if [ $? -eq 0 ]; then
source_vmdk=$vmdk
ds_uuid="$(echo ${vmdk#/vmfs/volumes/*})"
ds_uuid="$(echo ${ds_uuid%/*/*})"
vmdk_disk="$(echo ${vmdk##/*/})"
$ssh_cmd "mkdir -p \"${backup_dir}/${ds_uuid}\""
destination_vmdk="${backup_dir}/${ds_uuid}/${vmdk_disk}"
else
source_vmdk=${vmx_dir}/${vmdk}
destination_vmdk="${backup_dir}/${vmdk}"
fi
logger "[$vm] VMDK: $vmdk"
logger "[$vm] source: $source_vmdk"
logger "[$vm] destination: $destination_vmdk"
$ssh_cmd "grep vmfsPassthroughRawDeviceMap \"${source_vmdk}\" > /dev/null 2>&1"
if [ $? -eq 1 ]; then
if $ssh_cmd "ls \"${destination_vmdk}\" > /dev/null 2>&1" ; then
logger "[$vm] \"${destination_vmdk}\" exists."
if [ "$overwrite_backup" == "1" ]; then
logger "[$vm] removing \"${destination_vmdk}\""
$ssh_cmd "${vmkfstools_cmd} -U \"${destination_vmdk}\""
else
if $ssh_cmd "ls \"${destination_vmdk}\" > /dev/null 2>&1" ; then
logger "[$vm] skipping \"$vmdk\""
continue
fi
fi
fi
logger "[$vm] Backup of \"${source_vmdk}\" to \"${destination_vmdk}\""
${ssh_cmd} "${vmkfstools_cmd} -i \"${source_vmdk}\" ${vmkfstools_opts} \"${destination_vmdk}\""
if [ $? -ne 0 ] ; then
warning "[$vm] error in backing up of \"${source_vmdk}\""
consolidate_snapshot "$vm_id"
error "[$vm] error in backing up of \"${source_vmdk}\""
else
logger "[$vm] Backup successful."
fi
else
warning "[$vm] A physical RDM \"${source_vmdk}\", which will not be backed up"
fi
IFS=:
done
IFS=$OIFS
consolidate_snapshot "$vm_id"
}
usage(){
[ $# -gt 0 ] && echo "ERROR: $@"
echo
echo "Usage: $0 -v [VM] -d [DIR] -u [USER] -h [host] <options>"
echo
echo "options:"
echo " -v <vm> Virtual machine to backup [*]"
echo " -d <dir> Remote directory to store backup [*]"
echo " -u <user> ESXi username (default: root)"
echo " -h <host> ESXi host [*]"
echo " -f <opts> vmkfstool optons (default: \"-a lsilogic -d zeroedthick\")"
echo " -o overwrite existent backups"
echo " -q use quiesce snapshot"
echo " -s <opts> ssh options (default: \"-i /var/lib/bacula/.ssh/id_rsa\")"
echo " -L <cmd> local command executed after backup of virtual disks, this command is executed on local machine"
echo " -R <cmd> remote command executed on ESXi host after local command execution"
echo " -t <timeout> snapshot creation timeout in minutes. (default 10)"
echo " -U use the snapshot_id syntax in snapshot.remove (default NO)"
echo
echo
echo "[*] required options"
echo
exit 1
}
vm=""
backup_dir=""
user=root
host=
vmkfstools_opts="-a lsilogic -d zeroedthick"
overwrite_backup=0
vm_snapshot_memory=0
vm_snapshot_quiesce=1
vm_snapshot_useid=0
snapshot_timeout=10
ssh_opts="-i /var/lib/bacula/.ssh/id_rsa"
snapshot_prefix="PMVCB"
local_command=""
remote_command=""
while getopts "v:d:u:h:f:oqs:P:L:R:t:U" ARGS; do
case $ARGS in
v)
vm="${OPTARG}"
;;
d)
backup_dir="${OPTARG}"
;;
u)
user="${OPTARG}"
;;
h)
host="${OPTARG}"
;;
f)
vmkfstools_opts="${OPTARG}"
;;
o)
overwrite_backup=1
;;
q)
vm_snapshot_quiesce=1
;;
s)
ssh_opts="${OPTARG}"
;;
P)
snapshot_prefix="${OPTARG}"
;;
L)
local_command="${OPTARG}"
;;
R)
remote_command="${OPTARG}"
;;
t)
snapshot_timeout="${OPTARG}"
;;
U)
vm_snapshot_useid=1
;;
*)
usage "unknown option -$ARG"
;;
esac
done
[ -z "$vm" ] && usage "virtual machine is required"
[ -z "$backup_dir" ] && usage "backup directory is required"
[ -z "$user" ] && usage "username is required"
[ -z "$host" ] && usage "host is required"
ssh_cmd="ssh $ssh_opts $user@$host"
run
if [ -n "$local_command" ];then
logger "[$vm] executing local command"
$local_command
fi
if [ -n "$remote_command" ]; then
logger "[$vm] executing remote command"
$ssh_cmd "$remote_command"
fi
<file_sep>/LEGGIMI.rb
Poor man VMware consolidated Backup
===================================
VMware offre un pacchetto di backup per le macchine virtuali: VCB (VMware consolidated Backup): http://www.vmware.com/products/vi/cb_overview.html
Il VCB non fa altro che:
* eseguire uno snapshot di una VM
* clonare i dischi virtuali della VM
* consolidare lo snapshot (rimozione dello snapshot)
I vantaggi di un backup del genere sono:
* si ha il backup una macchina virtuale intera
* non ci sono downtime: lo snapshot si puo' fare a caldo
* se i vmware tools fanno il loro dovere il filesystem dovrebbe essere consistente
Gli svantaggi sono:
* si ha il backup di una macchina virtuale intera (leggi: no incrementali)
* si hanno gli stessi limiti derivati dall'uso degli snapshot: no RDM, ecc..
In buona sostanza il VCB è un buon sistema per il disaster recovery (se i paletti imposti dall'uso degli snapshot non sono troppo restrittivi).
E' possibile implementare un sistema di backup molto simile automatizzando le operazioni di snapshot, cloning e consolidation tramite uno script.
Lo script in questione è pmvcb: pmvcb esegue le operazioni sopra elencate su un host ESXi.
Di seguito l'help:
Usage: ./pmvcb -v [VM] -d [DIR] -h [host] <options>
options:
-v <vm> Virtual machine to backup [*]
-d <dir> Remote directory to store backup [*]
-h <host> ESXi host [*]
-u <user> ESXi username (default: root)
-f <opts> vmkfstool optons (default: "-a lsilogic -d zeroedthick")
-o overwrite existent backups
-q use quiesce snapshot
-s <opts> ssh options (default: "-i /var/lib/bacula/.ssh/id_rsa")
-L <cmd> local command executed after backup of virtual disks, this command is executed on local machine
-R <cmd> remote command executed on ESXi host after local command execution
-t <timeout> snapshot creation timeout in minutes. (default 10)
-U use the snapshot_id syntax in snapshot.remove (default NO)
[*] required options
come opzioni obbligatorie richiede il nome della VM da backuppare (-v), la directory di appoggio in cui clonare i dischi (-d) e l'host ESXi a cui collegarsi (-h).
Tramite l'opzione -f è possibile specificare diverse opzioni al comando vmkfstool utilizato per le operazioni di cloning, tramite -q richiede un'operazione di Quiescing prima di effettuare lo snapshot.
-s istruisce il comando ssh (es. ad usare l'autenticazione con chiave RSA).
-L e -R eseguono comandi rispettivamente e nell'ordine sull'host locale e sull'host remoto.
-t definisce un timeout per la creazione dello snapshot.
-U supporta la sintassi per snapshot_id in snapshot.remove.
**pmvcb si occupa di:**
1. verificare che la virtual machine non abbia dischi indipendent oppure RDM.
2. verificare che non ci siano snapshot attivi sulla virtual machine
3. eseguire lo snapshot
4. clonare i dischi e il .vmx della virtual machine nella directory specificata dall'opzione -d
5. consolidare lo snapshot creato
6. eseguire i comandi specificati da -L localmente
<file_sep>/README.md
Poor man VMware consolidated Backup
===================================
VMware offers a backup system for virtual machines: VCB (VMware consolidated Backup): http://www.vmware.com/products/vi/cb_overview.htm
When the VCB run it:
* execute a snapshot of VM
* clone virtual machine disks
* consolidates the snapshot (snapshot removing)
The advantages of this backup system are:
* full backup of a virtual machine
* no downtime
* the filesystem should be consistent
The disadvantages are:
* full backup of a virtual machine (read: no incremental or differential)
* is snapshot dependent (no RDM or indipendent devices)
Basically VCB is a good sistem for disaster recovery (whether the restrictions imposed by the use of snapshots ad not too restrictive).
With a lot of bash line is possible to implement a similar system by automating the snapshot, cloning and consolitation operations.
Lo script in questione è pmvcb: pmvcb esegue le operazioni sopra elencate su un host ESXi.
This is the goal of pvcb script.
Below the help of pvcb:
Usage: ./pmvcb -v [VM] -d [DIR] -h [host] <options>
options:
-v <vm> Virtual machine to backup [*]
-d <dir> Remote directory to store backup [*]
-h <host> ESXi host [*]
-u <user> ESXi username (default: root)
-f <opts> vmkfstool optons (default: "-a lsilogic -d zeroedthick")
-o overwrite existent backups
-q use quiesce snapshot
-s <opts> ssh options (default: "-i /var/lib/bacula/.ssh/id_rsa")
-L <cmd> local command executed after backup of virtual disks, this command is executed on local machine
-R <cmd> remote command executed on ESXi host after local command execution
-t <timeout> snapshot creation timeout in minutes. (default 10)
-U use the snapshot_id syntax in snapshot.remove (default NO)
[*] required options
The required options are: the name of VM to do backing-up (-v), the directory where pvcb store the cloned disks (-d) and the ESXi host (-h).
With -f option you can specify more options to vmkfstools command (the comamnd used by ESXi for cloning disks), with -q option you can use quiescent snapshot.
With -s option you can specify more options for ssh (for example using a RSA key).
-L and -R run commands on localhost and remote ESXi host. -t defines the timeout for snapshot creation. -U supports the snapshot_id in snapshot.remove.
**pmvcb deals with:**
1. verify that the virtual machine not have RDM or indipendent disks
2. verify that there are not snapshot in progress
3. executing the snapshot
4. disk cloning and copy .vmx file of virtual machine in the direcotry specified by -d option
5. consolidate the snapshot
6. executing command specified by -L option locally
7. executing command specified by -R option remotely
**really recommended to use rsa authentication with ssh (http://plone.lucidsolutions.co.nz/linux/vmware/esxi/enabling-ssh-with-public-key-authentication-on-vmware-esxi-4)**
**this script is tested on ESXi 4.0 / 4.1**
[](https://bitdeli.com/free "Bitdeli Badge")
|
0492c2a89fe8583cf851d4a204b184a16a0df2ad
|
[
"Markdown",
"Ruby",
"Shell"
] | 3
|
Shell
|
imbmf/pmvcb
|
e64866ff60cde6a804c819df75ff61a35d08cb40
|
5a6668e93987b4c83e4a99f1f1322c21660554de
|
refs/heads/master
|
<file_sep>#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/shm.h>
#include "shm_types.h"
int main()
{
int running = 1;
void *shared_memory = (void *)0; //holds return address of shmat()
struct shared_use_st *shared_stuff;
char buffer[80];
int shmid; //holds return of shmget()
//Create a shared memory
shmid = shmget((key_t)1234, sizeof(struct shared_use_st), 0666 | IPC_CREAT);
if (shmid == -1) {
fprintf(stderr, "shmget failed\n");
exit(EXIT_FAILURE);
}
//Attatche the shm to the prog
shared_memory = shmat(shmid, (void*)0, 0);
if (shared_memory == (void *)-1) {
fprintf(stderr, "shmat failed\n");
exit(EXIT_FAILURE);
}
//printf("Memory attatched at %X\n", (int)shared_memory);
shared_stuff = (struct shared_use_st *)shared_memory;
shared_stuff -> wby = 0;
while(running) {
if (shared_stuff -> wby) {
printf("You wrote: %s", shared_stuff -> buffer);
//sleep(1); //make the other process wait for us
shared_stuff -> wby = 0;
if (strncmp(shared_stuff -> buffer, "end", 3) == 0)
running = 0;
}
}
if (shmdt(shared_memory) == -1) {
fprintf(stderr, "shmdt failed\n");
exit(EXIT_FAILURE);
}
if (shmctl(shmid, IPC_RMID, 0) == -1) {
fprintf(stderr, "shmctl(IPC_RMID) failed\n");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
<file_sep>#define TEXT_SZ 80 //Buffer size
struct shared_use_st {
int wby; //int to tell the consumer that data has been written
char buffer[TEXT_SZ];
};
<file_sep># system-software-and-linux
this repository contains few useful programs on system software and linux. my work for these labs in 4 semester
<file_sep>#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/shm.h>
#include "shm_types.h"
int main()
{
int running = 1;
void *shared_memory = (void *)0; //holds return address of shmat()
struct shared_use_st *shared_stuff;
char buffer[80];
int shmid; //holds return of shmget()
//Create a shared memory
shmid = shmget((key_t)1234, sizeof(struct shared_use_st), 0666 | IPC_CREAT);
if (shmid == -1) {
fprintf(stderr, "shmget failed\n");
exit(EXIT_FAILURE);
}
//Attatch the shm to the program
shared_memory = shmat(shmid, (void*)0, 0);
if (shared_memory == (void *)-1) {
fprintf(stderr, "shmat failed\n");
exit(EXIT_FAILURE);
}
//printf("Memory attatched at %X\n", (int)shared_memory);
shared_stuff = (struct shared_use_st *)shared_memory;
shared_stuff -> wby = 0;
while (running) {
while (shared_stuff -> wby == 1) {
//sleep(1);
printf("Waiting for client...\n");
}
printf("Enter some text: ");
fgets(buffer, 80, stdin);
strncpy(shared_stuff -> buffer, buffer, TEXT_SZ);
shared_stuff -> wby = 1;
if (strncmp(buffer, "end", 3) == 0) {
running = 0;
}
}
if (shmdt(shared_memory) == -1) {
fprintf(stderr, "shmdt failed\n");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
|
3ba3a7bdaf2e091584670050171f820d4ed8cdce
|
[
"Markdown",
"C"
] | 4
|
C
|
krisalpha/system-software-and-linux
|
5433090efc07717b5f58c5e97e392d6454f86b9d
|
ad1b3d8edb6492db8e1edbcd15ea8c9a48075121
|
refs/heads/master
|
<repo_name>felipessalvatore/fin2vec<file_sep>/src/myplots.py
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import joypy
def box_plot_pair(df,
figsize,
first_title,
second_title,
first_value,
second_value,
out_path):
fig, ax = plt.subplots(1, 2, figsize=figsize)
a1 = sns.boxplot(x=first_value, data=df, orient="v", ax=ax[0])
a2 = sns.swarmplot(x=first_value, data=df, color=".25", orient="v", ax=ax[0])
b1 = sns.boxplot(x=second_value, data=df, orient="v", ax=ax[1])
b2 = sns.swarmplot(x=second_value, data=df, color=".25", orient="v", ax=ax[1])
ax[0].title.set_text(first_title)
ax[1].title.set_text(second_title)
plt.savefig(out_path)
def plot_joyplot(df, figsize, title, title_fontsize, out_path):
fig, axes = joypy.joyplot(df, figsize=figsize)
fig.suptitle(title, fontsize=title_fontsize, fontweight='bold')
plt.savefig(out_path)
def plot_series(df_,
title,
xlabel,
ylabel,
figsize,
style,
palette,
linewidth,
err_style,
markers,
dashes,
title_fontsize,
xlabel_fontsize,
ylabel_fontsize,
rot,
out_path):
"""
plot series from df
example:
plot_series(df_=df_signal_r_2,
title="Plot 4: R squared over time",
xlabel="days",
ylabel="R_2",
figsize=(12, 8),
style="whitegrid",
palette='tab20',
linewidth=1.5,
err_style='bars',
markers=False,
dashes=False,
title_fontsize=14,
xlabel_fontsize=12,
ylabel_fontsize=12,
rot=0,
out_path="plot.png")
"""
fig, ax = plt.subplots(1, 1, figsize=figsize)
sns.set(style=style)
ax = sns.lineplot(data=df_,
palette=palette,
linewidth=linewidth,
err_style=err_style,
markers=markers,
dashes=dashes)
fig.suptitle(title, fontsize=title_fontsize, fontweight='bold')
ax.set_xlabel(xlabel, fontsize=xlabel_fontsize)
ax.set_ylabel(ylabel, fontsize=ylabel_fontsize)
if rot is not None:
plt.xticks(rotation=rot)
plt.savefig(out_path)<file_sep>/README.md
# fin2vec
Finance notebook
|
71dee848d472bdc17fee1909b42ede32c2c19e02
|
[
"Markdown",
"Python"
] | 2
|
Python
|
felipessalvatore/fin2vec
|
a0319151096b9162992507d6461ab0efba60fb09
|
834d207edafc181f1e3bb1b359809fc202813678
|
refs/heads/master
|
<repo_name>blomm/simple-redux-tutorial<file_sep>/src/components/App.js
import React from 'react';
import Footer from './Footer';
import AddTodo from '../containers/AddTodo';
import VisibleTodoList from '../containers/VisibleTodoList';
// When we wrote: <Route path="/:filter?" component={App} />,
// it made available inside App a params property.
const App = ({ match: { params } }) => (
<div>
<AddTodo />
<VisibleTodoList filter={params.filter || 'SHOW_ALL'} />
<Footer />
</div>
);
export default App;
<file_sep>/src/redux/reducers/initialState.js
import { VisibilityFilters } from '../actions/actionTypes';
export default initialState = {
todos: [],
visibilityFilter: VisibilityFilters.SHOW_ALL
};
<file_sep>/src/redux/actions/todoActions.js
import * as types from './actionTypes';
// action creator returns an action
export function addTodo(text) {
return { type: types.ADD_TODO, text: text };
}
export function toggleTodo(index) {
return { type: types.TOGGLE_TODO, index: index };
}
export function setTodoVis(filter) {
return { type: types.SET_VISIBILITY_FILTER, filter: filter };
}
<file_sep>/src/containers/FilterLink.js
import React from 'react';
import { NavLink } from 'react-router-dom';
const FilterLink = ({ filter, children }) => (
<NavLink
exact
to={filter === 'SHOW_ALL' ? '/' : `/${filter}`}
activeStyle={{
textDecoration: 'none',
color: 'black'
}}
>
{children}
</NavLink>
);
export default FilterLink;
// import { connect } from 'react-redux';
// import { setTodoVis } from '../redux/actions/todoActions';
// import Link from '../components/Link';
// const mapStateToProps = (state, ownProps) => {
// return {
// active: ownProps.filter === state.visibilityFilter
// };
// };
// const mapDispatchToProps = (dispatch, ownProps) => {
// return {
// onClick: () => {
// dispatch(setTodoVis(ownProps.filter));
// }
// };
// };
// const FilterLink = connect(mapStateToProps, mapDispatchToProps)(Link);
// export default FilterLink;
<file_sep>/src/components/Root.js
import { createStore } from 'redux';
import React from 'react';
import reducers from '../redux/reducers';
import { Provider } from 'react-redux';
import App from './App';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import PropTypes from 'prop-types';
// You may optionally specify the initial state as the second argument to createStore().
// This is useful for hydrating the state of the client to match the
// state of a Redux application running on the server.
const store = createStore(reducers); //, window.STATE_FROM_SERVER);
const Root = () => {
return (
<Router>
<Provider store={store}>
<Route path="/:filter?" component={App} />
</Provider>
</Router>
);
};
Root.propTypes = {
store: PropTypes.object.isRequired
};
export default Root;
|
c9264e6da77f1036ec1857104d9d8b181b4362c7
|
[
"JavaScript"
] | 5
|
JavaScript
|
blomm/simple-redux-tutorial
|
975368a736e7815d4da9b9d1997516f1aaad6bca
|
c1f57d5c87c707556128c52a4280bfd34acad243
|
refs/heads/master
|
<file_sep>#include <cstdio>
#define MAX_WIDTH 256
#define abs(x) ((x)<0?-(x):(x))
using namespace std;
static int top[MAX_WIDTH] = { 0 };
static int diff[MAX_WIDTH] = { 0 };
int main() {
int width, col, row, value, count;
scanf("%d", &width);
while (width) {
printf("%d\n", width);
col = 0;
scanf("%d %d", &value, &count);
while (value && count) {
scanf("%d %d", &value, &count);
}
scanf("%d", &width);
}
return 0;
}
<file_sep>CC := cc
CC_FLAGS := -Wall -g -lstdc++ -std=gnu++11
TEST_FLAGS := -D_TEST_
main: main.cpp
$(CC) -o main main.cpp $(CC_FLAGS)
clean:
@rm main -f
<file_sep>CC := cc
CC_FLAGS := -Wall -g -lstdc++ -std=gnu++11
all: main_commit.cpp
$(CC) -o commit main_commit.cpp $(CC_FLAGS)
clean:
@rm commit -f
<file_sep>CC := cc
CC_FLAGS := -Wall -g -lstdc++ -std=gnu++11
all: main.cpp
$(CC) -o mayaCalendar main.cpp $(CC_FLAGS)
clean:
@rm -rf mayaCalendar
<file_sep>a_plus_b: a_plus_b.cpp
cc -o a_plus_b a_plus_b.cpp -lstdc++
clean:
@rm a_plus_b -f
|
7412ceb7789ed005dbf70b137b5d82a8867a3943
|
[
"Makefile",
"C++"
] | 5
|
C++
|
danceyat/poj
|
d21b79400ad4ab35c2f577173cb3440377c4b902
|
570f10431ae23bcfcd47c6947c6b7a45ef0ac489
|
refs/heads/master
|
<repo_name>amit231/DSALGO<file_sep>/Stack/stack.cpp
#include <iostream>
using namespace std;
#define newl cout << "\n";
template <typename T>
struct node
{
T data;
node *prev;
node(T num)
{
data = num;
prev = nullptr;
}
};
template <typename T>
class stack
{
private:
node<T> *front = nullptr;
int size = 0;
public:
bool isEmpty()
{
return (front == nullptr);
}
void push(T data)
{
node<T> *temp = new node<T>(data);
temp->prev = front;
front = temp;
size++;
}
T peek()
{
if (front == nullptr)
{
cout << "sorry! today's stack stock is empty\n";
return -1;
}
return front->data;
}
void pop()
{
node<T> *temp = front;
if (front == nullptr)
{
return;
}
else
{
size--;
front = front->prev;
delete temp;
}
}
};
int main()
{
stack<double> st;
st.push(21.324);
st.push(12.324);
st.push(92.324);
int top = 0;
while (!st.isEmpty())
{
top++;
if (top >= 2)
{
cout << top << " last element is : " << st.peek() << "\n";
}
else
{
cout << "stack top is : " << st.peek() << "\n";
}
st.pop();
}
}
|
438030b7c7cda7b2c2a0769b80426d8a33e57ed2
|
[
"C++"
] | 1
|
C++
|
amit231/DSALGO
|
8d7ed7a8e19563711ab60227362f6fe27c261802
|
102e84b27766be06fbaf2b4b86cbccc8f4f4ae93
|
refs/heads/master
|
<repo_name>acidtone/node-express-mongodb<file_sep>/bootstrap-bk.sh
# Update packages
sudo apt-get update
# Install Node.js and NPM
sudo apt-get install -y nodejs
# Install MongoDB
sudo apt-get install -y mongodb
# Install NPM
sudo apt-get install -y npm
# --no-optional suppresses harmless fsevents warnings
# on non-Mac systems
sudo npm install -g nodemon --no-optional
# Move user to /vagrant on ssh
echo "cd /vagrant" >> /home/vagrant/.bashrc
echo "PS1='\u:\W\$ '" >> /home/vagrant/.bashrc
# Start Mongodb
sudo systemctl enable mongodb.service
sudo service mongodb start
<file_sep>/bootstrap.sh
# Update packages
sudo apt update
sudo apt -y upgrade
# Install Node.js and NPM
sudo apt update
# sudo apt-get install -y nodejs
sudo apt -y install curl dirmngr apt-transport-https lsb-release ca-certificates
curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -
sudo apt -y install nodejs
# Install MongoDB
sudo apt install -y mongodb
# Install NPM
# sudo apt install -y npm
# --no-optional suppresses harmless fsevents warnings
# on non-Mac systems
# sudo npm install -g nodemon --no-optional
# Move user to /vagrant on ssh
echo "cd /vagrant" >> /home/vagrant/.bashrc
echo "PS1='\u:\W\$ '" >> /home/vagrant/.bashrc
# Start Mongodb
# sudo systemctl enable mongodb.service
# sudo service mongodb start
<file_sep>/Vagrantfile
Vagrant.configure("2") do |config|
# For a complete reference, please see the online documentation at
# https://docs.vagrantup.com.
# Every Vagrant development environment requires a box. You can search for
# boxes at https://vagrantcloud.com/search.
config.vm.box = "ubuntu/bionic64"
# Create a forwarded port mapping which allows access to a specific port
# within the machine from a port on the host machine and only allow access
# via 127.0.0.1 to disable public access
config.vm.network "forwarded_port", guest: 8080, host: 8080, host_ip: "127.0.0.1"
config.vm.network "forwarded_port", guest: 3000, host: 3000, host_ip: "127.0.0.1"
config.vm.network "forwarded_port", guest: 27017, host: 27017, host_ip: "127.0.0.1"
# Share an additional folder to the guest VM. The first argument is
# the path on the host to the actual folder. The second argument is
# the path on the guest to mount the folder. And the optional third
# argument is a set of non-required options.
config.vm.synced_folder "src", "/vagrant"
# Enable provisioning shell script.
config.vm.provision :shell, path: "bootstrap.sh"
end
|
18da64f23a241f258eb802ff05df325b00da9abc
|
[
"Ruby",
"Shell"
] | 3
|
Shell
|
acidtone/node-express-mongodb
|
f5f4015213a6f77f70daaf7d970888cf39b230c9
|
b15db33ea7ac433c65b48a66b9e90a4663575176
|
refs/heads/main
|
<file_sep>//
// main.cpp
// 矢量加法
//
// Created by 李圣韬 on 2020/3/16.
// Copyright © 2020 李圣韬. All rights reserved.
//
#include <iostream>
#include <time.h>
#include "normalVectorAdd.hpp"
#include "openclVectorAdd.hpp"
#include "openclVectorAddOnlyCPU.hpp"
using namespace std;
const int elementnum = 800000;
int main(int argc, const char * argv[]) {
// normal vector add function
normalVectorAdd(elementnum);
// opencl vector add function
openclVectorAdd(elementnum);
// opencl vector add function only CPU
openclVectorAddOnlyCPU(elementnum);
return 0;
}
<file_sep>//
// main.cpp
// 异构计算第七周作业
//
// Created by 李圣韬 on 2020/4/13.
// Copyright © 2020 李圣韬. All rights reserved.
//
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <OpenCL/OpenCL.h>
#include "scalarConvolutionalCompute.hpp"
using namespace std;
const int MAXN = 2000*2000;
const int MAXM = 4*4;
float matrix[MAXN] = {0};
float filter[MAXN] = {0};
int m, n;
int main(int argc, const char * argv[]) {
cin >> m >> n;
for(int i = 0; i<4; ++i){
for(int j = 0; j<4;++j){
srand((unsigned)time(NULL));
filter[i*4+j]= rand()%10;
}
}
for(int i = 1; i<=m; ++i){
for(int j = 1; j<=n; ++j){
cin >> matrix[i*m+j];
}
}
float* result1 = NULL, * result2 = NULL;
result1 = scalarConvolutionalCompute(m, n, matrix, 4, 4, filter);
result2 = openclConclution(matrix);
return 0;
}
<file_sep>//
// scalarConvolutionalCompute.hpp
// 异构计算第七周作业
//
// Created by 李圣韬 on 2020/4/13.
// Copyright © 2020 李圣韬. All rights reserved.
//
#ifndef scalarConvolutionalCompute_hpp
#define scalarConvolutionalCompute_hpp
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <iostream>
#endif /* scalarConvolutionalCompute_hpp */
float* scalarConvolutionalCompute(const int, const int, const float*, const int, const int, const float*);
<file_sep>/*
* @Author: <NAME>
* @Date: 2020-03-30 22:07:52
* @LastEditTime: 2020-03-30 22:07:52
* @LastEditors: <NAME>
* @Description: In User Settings Edit
* @FilePath: /undefined/Users/starwish/Desktop/图像旋转李圣韬1901213315/main.cpp
*/
#include "stdafx.h"
#include <CL/cl.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <iostream>
#include <fstream>
#include "gFreeImage.h"
using namespace std;
#define NWITEMS 4
#pragma comment (lib,"OpenCL.lib")
#pragma comment (lib,"FreeImage.lib")
//把文本文件读入一个string中,其实就是把运行程序传给从机
int convertToString(const char *filename, std::string& s)
{
size_t size;
char* str;
std::fstream f(filename, (std::fstream::in | std::fstream::binary));
if(f.is_open())
{
size_t fileSize;
f.seekg(0, std::fstream::end);
size = fileSize = (size_t)f.tellg();
f.seekg(0, std::fstream::beg);
str = new char[size+1];
if(!str)
{
f.close();
return NULL;
}
f.read(str, fileSize);
f.close();
str[size] = '\0';
s = str;
delete[] str;
return 0;
}
printf("Error: Failed to open file %s\n", filename);
return 1;
}
//CPU旋转图像:使用CPU来旋转图片
void cpu_rotate(unsigned char* inbuf, unsigned char* outbuf, int w, int h,float sinTheta, float cosTheta)
{
int i, j;
int xc = w/2;
int yc = h/2;
for(i = 0; i < h; i++)
{
for(j=0; j< w; j++)
{
int xpos = ( j-xc)*cosTheta - (i-yc)*sinTheta+xc;
int ypos = (j-xc)*sinTheta + ( i-yc)*cosTheta+yc;
if(xpos>=0&&ypos>=0&&xpos<w&&ypos<h)
outbuf[ypos*w + xpos] = inbuf[i*w+j];
}
}
}
int main(int argc, char* argv[])
{
//装入图像
unsigned char *src_image=0;
unsigned char *cpu_image=0;
int W, H;
gFreeImage img;
if(!img.LoadImageGrey("lenna.jpg"))
{
printf("装入lenna.jpg失败\n");
exit(0);
}
else
src_image = img.getImageDataGrey(W, H);
size_t mem_size = W*H;
cpu_image = (unsigned char*)malloc(mem_size);
cl_uint status;
cl_platform_id platform;
//创建平台对象
status = clGetPlatformIDs( 1, &platform, NULL );
cl_device_id device;
//创建GPU设备
clGetDeviceIDs( platform, CL_DEVICE_TYPE_GPU,
1,
&device,
NULL);
//创建context
cl_context context = clCreateContext( NULL,
1,
&device,
NULL, NULL, NULL);
//创建命令队列
cl_command_queue queue = clCreateCommandQueue( context,
device,
CL_QUEUE_PROFILING_ENABLE, NULL );
//创建三个OpenCL内存对象,并把buf1的内容通过隐式拷贝的方式
//拷贝到clbuf1,buf2的内容通过显示拷贝的方式拷贝到clbuf2
cl_mem d_ip = clCreateBuffer(
context, CL_MEM_READ_ONLY,
mem_size,
NULL, NULL);
cl_mem d_op = clCreateBuffer(
context, CL_MEM_WRITE_ONLY,
mem_size,
NULL, NULL);
status = clEnqueueWriteBuffer (
queue , d_ip, CL_TRUE,
0, mem_size, (void *)src_image,
0, NULL, NULL);
const char * filename = "kernel.cl";
std::string sourceStr;
status = convertToString(filename, sourceStr);
const char * source = sourceStr.c_str();
size_t sourceSize[] = { strlen(source) };
//创建程序对象
cl_program program = clCreateProgramWithSource(
context,
1,
&source,
sourceSize,
NULL);
//编译程序对象
status = clBuildProgram( program, 1, &device, NULL, NULL, NULL );
if(status != 0)
{
printf("clBuild failed:%d\n", status);
char tbuf[0x10000];
clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, 0x10000, tbuf, NULL);
printf("\n%s\n", tbuf);
return -1;
}
//创建Kernel对象
//Use the “image_rotate” function as the kernel
//创建Kernel对象
cl_kernel kernel = clCreateKernel( program, "image_rotate", NULL );
//设置Kernel参数
float sintheta = 1, costheta = 0;
clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&d_ip);
clSetKernelArg(kernel, 1, sizeof(cl_mem), (void *)&d_op);
clSetKernelArg(kernel, 2, sizeof(cl_int), (void *)&W);
clSetKernelArg(kernel, 3, sizeof(cl_int), (void *)&H);
clSetKernelArg(kernel, 4, sizeof(cl_float), (void *)&sintheta);
clSetKernelArg(kernel, 5, sizeof(cl_float), (void *)&costheta);
//Set local and global workgroup sizes
size_t localws[2] = {16,16} ;
size_t globalws[2] = {W, H};//Assume divisible by 16
cl_event ev;
//执行kernel
clEnqueueNDRangeKernel(
queue ,kernel,
2, 0, globalws, localws,
0, NULL, &ev);
clFinish( queue );
//计算kerenl执行时间
cl_ulong startTime, endTime;
clGetEventProfilingInfo(ev, CL_PROFILING_COMMAND_START,
sizeof(cl_ulong), &startTime, NULL);
clGetEventProfilingInfo(ev, CL_PROFILING_COMMAND_END,
sizeof(cl_ulong), &endTime, NULL);
cl_ulong kernelExecTimeNs = endTime-startTime;
printf("kernal exec time :%8.6f ms\n ", kernelExecTimeNs*1e-6 );
//数据拷回host内存
// copy results from device back to host
unsigned char *op_data=0;
op_data = (cl_uchar *) clEnqueueMapBuffer( queue,
d_op,
CL_TRUE,
CL_MAP_READ,
0,
mem_size,
0, NULL, NULL, NULL );
int i;
cpu_rotate(src_image,cpu_image, W, H, 1, 0);
for(i = 0; i < mem_size; i++)
{
src_image[i] =cpu_image[i];
}
img.SaveImage("cpu_lenna_rotate.jpg");
for(i = 0; i < mem_size; i++)
{
src_image[i] =op_data[i];
}
img.SaveImage("lenna_rotate.jpg");
if(cpu_image)
free(cpu_image);
//删除OpenCL资源对象
clReleaseMemObject(d_ip);
clReleaseMemObject(d_op);
clReleaseProgram(program);
clReleaseCommandQueue(queue);
clReleaseContext(context);
return 0;
}<file_sep>//
// normalVectorAdd.hpp
// 矢量加法
//
// Created by 李圣韬 on 2020/3/16.
// Copyright © 2020 李圣韬. All rights reserved.
//
#ifndef normalVectorAdd_hpp
#define normalVectorAdd_hpp
#include <iostream>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#endif /* normalVectorAdd_hpp */
using namespace std;
void normalVectorAdd(int);
<file_sep>//
// openclVectorAdd.hpp
// 矢量加法
//
// Created by 李圣韬 on 2020/3/16.
// Copyright © 2020 李圣韬. All rights reserved.
//
#ifndef openclVectorAdd_hpp
#define openclVectorAdd_hpp
#include <stdio.h>
#include <OpenCL/OpenCL.h>
#include <time.h>
#include <iostream>
#endif /* openclVectorAdd_hpp */
using namespace std;
void openclVectorAdd(int);
<file_sep>//
// openclConvolutionalCompute.hpp
// 异构计算第七周作业
//
// Created by 李圣韬 on 2020/4/13.
// Copyright © 2020 李圣韬. All rights reserved.
//
#ifndef openclConvolutionalCompute_hpp
#define openclConvolutionalCompute_hpp
#include <stdio.h>
#include <iostream>
#include <OpenCL/OpenCL.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#endif /* openclConvolutionalCompute_hpp */
<file_sep>//
// scalarConvolutionalCompute.cpp
// 异构计算第七周作业
//
// Created by 李圣韬 on 2020/4/13.
// Copyright © 2020 李圣韬. All rights reserved.
//
#include "scalarConvolutionalCompute.hpp"
using namespace std;
float* scalarConvolutionalCompute(const int matrixH, const int matrixW, const float* matrix, const int filterH, const int filterW, const float* filter){
// 保证卷积生成的矩阵和原始矩阵的长宽相同
float* result = (float*)malloc(sizeof(float)*matrixH*matrixW);
clock_t start, end;
start = clock();
for(int i = 1; i <= matrixH; ++i){
for(int j = 1; j <= matrixW; ++j){
int sum = 0;
for(int y = 0; y < filterH; ++y){
for(int x = 0; x < filterW;++x){
sum += matrix[(i+y)*matrixW + j + x] * filter[y* filterW + x];
}
}
result[i*matrixW+j] = sum;
}
}
end = clock();
cout << "scalr vonvolution compte cost " << (double)(end - start)/CLOCKS_PER_SEC << endl;
return result;
}
<file_sep>//
// openclMatrixMul.hpp
// matrixMul
//
// Created by 李圣韬 on 2020/3/22.
// Copyright © 2020 李圣韬. All rights reserved.
//
#ifndef openclMatrixMul_hpp
#define openclMatrixMul_hpp
#include <stdio.h>
#include <OpenCL/OpenCL.h>
#include <iostream>
#endif /* openclMatrixMul_hpp */
void openclMatrixMul(int);
<file_sep>//
// main.cpp
// test
//
// Created by 李圣韬 on 2020/3/15.
// Copyright © 2020 李圣韬. All rights reserved.
//
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <OpenCL/OpenCL.h>
void checkerr(cl_int err, int num){
if(CL_SUCCESS != err){
printf("OpenCL error(%d) at %d\n", err, num-1);
}
}
int main(int argc, const char * argv[]) {
cl_platform_id* platform;
cl_uint num_platform;
cl_int err;
err = clGetPlatformIDs(0, NULL, &num_platform);
platform = (cl_platform_id*) malloc(sizeof(cl_platform_id) * num_platform);
err = clGetPlatformIDs(num_platform, platform, NULL);
for(int i = 0; i < num_platform; ++i){
size_t size;
// get platform name
err = clGetPlatformInfo(platform[i], CL_PLATFORM_NAME, 0, NULL, &size);
char* Pname = (char*)malloc(size);
err = clGetPlatformInfo(platform[i], CL_PLATFORM_NAME, size, Pname, NULL);
printf("CL_PLATFORM_NAME: %s\n", Pname);
// get platform vendor
err = clGetPlatformInfo(platform[i], CL_PLATFORM_VENDOR, 0, NULL, &size);
char* PVendor = (char*)malloc(size);
err = clGetPlatformInfo(platform[i], CL_PLATFORM_VENDOR, size, PVendor, NULL);
printf("CL_PLATFORM_VENDOR: %s\n", PVendor);
// get platform version
err = clGetPlatformInfo(platform[i], CL_PLATFORM_VERSION, 0, NULL, &size);
char* PVersion = (char*)malloc(size);
err = clGetPlatformInfo(platform[i], CL_PLATFORM_VERSION, size, PVersion, NULL);
printf("CL_PLATFORM_VERSION: %s\n", PVersion);
// get platform profile
err = clGetPlatformInfo(platform[i], CL_PLATFORM_PROFILE, 0, NULL, &size);
char* PProfile = (char*)malloc(size);
err = clGetPlatformInfo(platform[i], CL_PLATFORM_PROFILE, size, PProfile, NULL);
printf("CL_PLATFORM_PROFILE: %s\n", PProfile);
// get paltform extensions
err = clGetPlatformInfo(platform[i], CL_PLATFORM_EXTENSIONS, 0, NULL, &size);
char* PExten = (char*)malloc(size);
err = clGetPlatformInfo(platform[i], CL_PLATFORM_EXTENSIONS, size, PExten, NULL);
printf("CL_PLATFORM_EXTENSIONS: %s\n", PExten);
cl_device_id* devices;
cl_uint num_device;
// get the num of device
err = clGetDeviceIDs(platform[i], CL_DEVICE_TYPE_ALL, 0, NULL, &num_device);
devices = (cl_device_id*)malloc(sizeof(cl_device_id)*num_device);
err = clGetDeviceIDs(platform[i], CL_DEVICE_TYPE_ALL, num_device, devices, NULL);
for(int j = 0; j < num_device; ++j){
// get device name
char DeviceName[100];
err = clGetDeviceInfo(devices[j], CL_DEVICE_NAME, 100, DeviceName, NULL);
printf("DEVICE_NAME: %s\n", DeviceName);
// get device opencl version
char DeviceVersion[100];
err = clGetDeviceInfo(devices[j], CL_DEVICE_VERSION, 100, DeviceVersion, NULL);
printf("DEVICE_VERSION: %s\n", DeviceVersion);
// get max compute units
cl_long UnitNum;
err = clGetDeviceInfo(devices[j], CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(cl_uint), &UnitNum, NULL);
checkerr(err, 73);
printf("MAX_COMPUTE_UNITS: %ld\n", &UnitNum);
// get device frequency
cl_long frequency;
err = clGetDeviceInfo(devices[j], CL_DEVICE_MAX_CLOCK_FREQUENCY, sizeof(cl_uint), &frequency, NULL);
checkerr(err, 78);
printf("MAX_CLOCK_FREQUENCY: %ld(MHz)\n", &frequency);
// get device global memory size
cl_long GlobalSize;
err = clGetDeviceInfo(devices[j], CL_DEVICE_GLOBAL_MEM_SIZE, sizeof(cl_ulong), &GlobalSize, NULL);
printf("Device Global Size: %0.0f(MB)\n", GlobalSize);
}
free(PExten);
free(PProfile);
free(PVersion);
free(PVendor);
free(Pname);
}
free(platform);
return 0;
}
<file_sep>//
// main.cpp
// matrixMul
//
// Created by 李圣韬 on 2020/3/22.
// Copyright © 2020 李圣韬. All rights reserved.
//
#include <iostream>
#include <stdlib.h>
#include "openclMatrixMul.hpp"
#include "openclMatrixMulPro.hpp"
using namespace std;
float* A = NULL;
float* B = NULL;
float* C = NULL;
float* ANS = NULL;
int main(int argc, const char * argv[]) {
//int n = 4196;
int n = 16;
for(int i = 1; i<=100; ++i){
openclMatrixMul(n*i);
openclMatrixMulPro(n*i);
}
return 0;
}
<file_sep>//
// openclMatrixMulPro.hpp
// matrixMul
//
// Created by 李圣韬 on 2020/3/23.
// Copyright © 2020 李圣韬. All rights reserved.
//
#ifndef openclMatrixMulPro_hpp
#define openclMatrixMulPro_hpp
#include <stdio.h>
#include <OpenCL/OpenCL.h>
#include <iostream>
#endif /* openclMatrixMulPro_hpp */
void openclMatrixMulPro(int);
<file_sep>//
// normalVectorAdd.cpp
// 矢量加法
//
// Created by 李圣韬 on 2020/3/16.
// Copyright © 2020 李圣韬. All rights reserved.
//
#include "normalVectorAdd.hpp"
void normalVectorAdd(int n){
int* A, *B, *C;
int elementnum = n;
A = (int*)malloc(sizeof(int) * elementnum);
B = (int*)malloc(sizeof(int) * elementnum);
C = (int*)malloc(sizeof(int) * elementnum);
for(int i = 0; i < elementnum; ++i){
A[i] = i;
B[i] = i;
}
clock_t begin = clock();
for(int i = 0; i < elementnum; ++i){
C[i] = A[i] + B[i];
}
clock_t end = clock();
// Verify the output
bool result = true;
for(int i = 0; i < elementnum; i++) {
if(C[i] != i+i) {
result = false;
break;
}
}
if(result) {
printf("Output is correct\n");
} else {
printf("Output is incorrect\n");
}
cout << "CPU串行向量加法用时: "<< end - begin << "click" << endl;
free(A);
free(B);
free(C);
}
<file_sep>//
// openclConvolutionalCompute.cpp
// 异构计算第七周作业
//
// Created by 李圣韬 on 2020/4/13.
// Copyright © 2020 李圣韬. All rights reserved.
//
#include "openclConvolutionalCompute.hpp"
using namespace std;
float* openclConvolutionalCompute(const int& matrixH,const int& matrixW, const float* matrix, int filterH, int filterW, const float* filter){
/*=================================================
define parameters
=================================================*/
cl_platform_id platform_id = NULL;
cl_uint ret_num_platforms;
cl_device_id device_id = NULL;
cl_uint ret_num_devices;
cl_context context = NULL;
cl_command_queue command_queue = NULL;
cl_mem data_in = NULL;
cl_mem data_out = NULL;
cl_mem filter_in = NULL;
cl_program program = NULL;
cl_kernel kernel = NULL;
size_t kernel_code_size;
char *kernel_str;
float *result;
cl_int ret;
FILE *fp;
cl_uint work_dim;
size_t global_item_size[2];
size_t local_item_size[2];
/*=================================================
load kernel, opencl environment setup
create input and output buffer
set kernel arguments, excute kernels
get final results
=================================================*/
result = (float*)malloc(matrixW * matrixH * sizeof(float));
ret = clGetPlatformIDs(1, &platform_id, &ret_num_platforms);
ret = clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_DEFAULT, 1, &device_id,
&ret_num_devices);
context = clCreateContext(NULL, 1, &device_id, NULL, NULL, &ret);
command_queue = clCreateCommandQueue(context, device_id, CL_QUEUE_PROFILING_ENABLE, &ret);
fp = fopen("Conv2D.cl", "r");
fseek(fp, 0, SEEK_END);
long kernel_str_len = ftell(fp);
rewind(fp);
kernel_str = (char*)malloc(sizeof(char)*kernel_str_len);
kernel_str[kernel_str_len] = '\0';
fread(kernel_str, sizeof(char), kernel_str_len, fp);
fclose(fp);
program = clCreateProgramWithSource(context, 1, (const char **)&kernel_str,
(const size_t *)&kernel_code_size, &ret);
ret = clBuildProgram(program, 1, &device_id, NULL, NULL, NULL);
kernel = clCreateKernel(program, "Conv2D", &ret);
data_in = clCreateBuffer(context, CL_MEM_READ_WRITE, matrixH * matrixW * sizeof(float), NULL, &ret);
data_out = clCreateBuffer(context, CL_MEM_READ_WRITE, matrixH* matrixW * sizeof(float), NULL, &ret);
filter_in = clCreateBuffer(context, CL_MEM_READ_WRITE, filterH*filterW * sizeof(float), NULL, &ret);
//write image data into data_in buffer
ret = clEnqueueWriteBuffer(command_queue, data_in, CL_TRUE, 0, matrixH*matrixW * sizeof(int), matrix, 0, NULL, NULL);
//write filter data into filter_in buffer
ret = clEnqueueWriteBuffer(command_queue, filter_in, CL_TRUE, 0, filterW*filterW * sizeof(int), filter, 0, NULL, NULL);
//set kernel arguments
ret = clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&data_in);
ret = clSetKernelArg(kernel, 1, sizeof(cl_mem), (void *)&filter_in);
ret = clSetKernelArg(kernel, 2, sizeof(int), (void *)&filterW);
ret = clSetKernelArg(kernel, 3, sizeof(cl_mem), (void *)&data_out);
work_dim = 2;
global_item_size[0] = matrixH;
global_item_size[1] = matrixW;
local_item_size[0] = 1;
local_item_size[1] = 1;
//execute data parallel kernel */
ret = clEnqueueNDRangeKernel(command_queue, kernel, work_dim, NULL,
global_item_size, local_item_size, 0, NULL, NULL);
// read data_out to host
ret = clEnqueueReadBuffer(command_queue, data_out, CL_TRUE, 0,
matrixH*matrixW * sizeof(int), result, 0, NULL, NULL);
/*=================================================
release all opencl objects
=================================================*/
ret = clReleaseKernel(kernel);
ret = clReleaseProgram(program);
ret = clReleaseMemObject(data_in);
ret = clReleaseMemObject(data_out);
ret = clReleaseMemObject(filter_in);
ret = clReleaseCommandQueue(command_queue);
ret = clReleaseContext(context);
free(result);
free(kernel_str);
return result;
}
<file_sep>//
// openclVectorAddOnlyCPU.hpp
// 矢量加法
//
// Created by 李圣韬 on 2020/3/16.
// Copyright © 2020 李圣韬. All rights reserved.
//
#ifndef openclVectorAddOnlyCPU_hpp
#define openclVectorAddOnlyCPU_hpp
#include <stdio.h>
#include <OpenCL/OpenCL.h>
#include <time.h>
#include <iostream>
#endif /* openclVectorAddOnlyCPU_hpp */
using namespace std;
void openclVectorAddOnlyCPU(int);
|
8d70e810712f6ffd0ba02503276c3cd8df4d85aa
|
[
"C++"
] | 15
|
C++
|
TaoTao-real/openCL-things
|
e4bd23a3e72d905a979e160e1f516d281a80c05f
|
d9b55983f65531b5635c3ba6a71c6b8b1954c4af
|
refs/heads/master
|
<repo_name>blesslp/CommonAdapter<file_sep>/sample/src/main/java/com/sample/ListViewSampleWithConvertTypeAct.java
package com.sample;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import com.blesslp.adapter.compat.abslistview.ListViewAdapter;
import com.blesslp.adapter.compat.base.intf.CommonAdapterIntf;
import java.util.Arrays;
public class ListViewSampleWithConvertTypeAct extends AppCompatActivity implements View.OnClickListener {
private ListView listView;
private Button btnJumpToFirst;
private ListViewAdapter mAdapter; //ListView,GridView最上级的适配器,用于配置数据,不参与具体逻辑
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view_sample_with_type);
initViews();
configListView();
}
public static final String TYPE_1 = "type1";
public static final String TYPE_2 = "type2";
public static final String TYPE_3 = "type3";
private void configListView() {
//配置ListView的数据类型及对应的Adapter
mAdapter = new ListViewAdapter.Builder()
.of(TYPE_1, new SimpleAdapterItem_type())
.of(TYPE_2, new SimpleAdapterItem2_type())
.of(TYPE_3, new SimpleAdapterItem3_type())
.build();
//设置数据源
//设置自定义转换器
mAdapter.setTypeConvert(new CommonAdapterIntf.TypeConvert() {
@Override
public Object convert(CommonAdapterIntf adapter, int position) {
User4 user4 = adapter.getItem(position);
return user4.getType();
}
});
//模仿一个接口返回的数据中通过某个字段来划分不同视图的情况
mAdapter.setDataSource(Arrays.asList(
new User4("我是一个标题", Arrays.asList(new User4("子标题1", "子内容1"),new User4("子标题1", "子内容1"),new User4("子标题1", "子内容1"),new User4("子标题1", "子内容1"),new User4("子标题1", "子内容1"),new User4("子标题1", "子内容1")),TYPE_2),
new User4("sss", "www",TYPE_1),
new User4("我是一个标题", Arrays.asList(new User4("子标题1", "子内容1"),new User4("子标题1", "子内容1"),new User4("子标题1", "子内容1"),new User4("子标题1", "子内容1"),new User4("子标题1", "子内容1"),new User4("子标题1", "子内容1")),TYPE_2),
new User4("单行数据", "enen",TYPE_3))
);
listView.setAdapter(mAdapter);
}
private void initViews() {
btnJumpToFirst = (Button) findViewById(R.id.btnJumpToFirst);
listView = (ListView) findViewById(R.id.listview);
btnJumpToFirst.setOnClickListener(this);
}
@Override
public void onClick(View view) {
startActivity(new Intent(this,MainActivity.class));
}
}
<file_sep>/sample/src/main/java/com/sample/MainActivity.java
package com.sample;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import com.blesslp.adapter.compat.base.common.AdapterItem;
import com.blesslp.adapter.compat.base.intf.CommonAdapterIntf;
import com.blesslp.adapter.compat.recyclerview.RecyclerAdapter;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private RecyclerView recyclerView;
private RecyclerAdapter mAdapter; //RecyclerView最上级的适配器,用于配置数据,不参与具体逻辑
private Button btnJumpToSecond;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
configRecyclerView();
}
private void configRecyclerView() {
recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
//配置RecyclerView的数据类型及对应的Adapter
mAdapter = new RecyclerAdapter.Builder()
.of(User.class, new SimpleAdapterItem())
.of(User2.class, new SimpleAdapterItem2())
.of(User3.class, new SimpleAdapterItem3())
.build();
//设置数据源
//默认类型是根据Class区分,也可自定义转换器来符合自己的逻辑
mAdapter.setDataSource(Arrays.asList(
new User("嘿嘿", "wuhan"),
new User3("sss", "www"),
new User2("我是一个标题", Arrays.asList(new User3("子标题1", "子内容1"),new User3("子标题2", "子内容2"),new User3("子标题3", "子内容3"),new User3("子标题4", "子内容4"),new User3("子标题1", "子内容1"),new User3("子标题1", "子内容1"))),
new User("单行数据", "enen"))
);
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
recyclerView.setAdapter(mAdapter);
}
private void initViews() {
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
btnJumpToSecond = (Button) findViewById(R.id.btnJumpToSecond);
btnJumpToSecond.setOnClickListener(this);
}
@Override
public void onClick(View view) {
startActivity(new Intent(this,ListViewSampleAct.class));
}
}
<file_sep>/sample/src/main/java/com/sample/ListViewSampleAct.java
package com.sample;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import com.blesslp.adapter.compat.abslistview.ListViewAdapter;
import java.util.Arrays;
public class ListViewSampleAct extends AppCompatActivity implements View.OnClickListener {
private ListView listView;
private Button btnJumpToThird;
private ListViewAdapter mAdapter; //ListView,GridView最上级的适配器,用于配置数据,不参与具体逻辑
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view_sample);
initViews();
configListView();
}
private void configListView() {
//配置ListView的数据类型及对应的Adapter
mAdapter = new ListViewAdapter.Builder()
.of(User.class, new SimpleAdapterItem())
.of(User2.class, new SimpleAdapterItem2())
.of(User3.class, new SimpleAdapterItem3())
.build();
//设置数据源
mAdapter.setDataSource(Arrays.asList(
new User2("我是一个标题", Arrays.asList(new User3("子标题1", "子内容1"),new User3("子标题1", "子内容1"),new User3("子标题1", "子内容1"),new User3("子标题1", "子内容1"),new User3("子标题1", "子内容1"),new User3("子标题1", "子内容1"))),
new User3("sss", "www"),
new User2("我是一个标题", Arrays.asList(new User3("子标题1", "子内容1"),new User3("子标题1", "子内容1"),new User3("子标题1", "子内容1"),new User3("子标题1", "子内容1"),new User3("子标题1", "子内容1"),new User3("子标题1", "子内容1"))),
new User("单行数据", "enen"))
);
listView.setAdapter(mAdapter);
}
private void initViews() {
btnJumpToThird = (Button) findViewById(R.id.btnJumpToThird);
listView = (ListView) findViewById(R.id.listview);
btnJumpToThird.setOnClickListener(this);
}
@Override
public void onClick(View view) {
startActivity(new Intent(this,ListViewSampleWithConvertTypeAct.class));
}
}
<file_sep>/README.md
# CommonAdapter
尝试做一个万能适配器方案,做到一处编写,处处使用,无论AbsListView还是RecyclerView,让你的代码最大化复用.
说明:
```
1.实现了控件无关的Adapter
2.提供多视图解决方案
3.默认多视图以数据源的Class为区分,提供自定义转换接口来定制符合你的所有情况.
```
```
下载玩玩
:project build.gradle
allprojects {
repositories {
maven { url 'https://jitpack.io' }
}
}
:app build.gradle
dependencies {
compile 'com.github.blesslp:CommonAdapter:beta-0.01'
}
```
演示:
#界面分三种viewType,每种type对应一个相应的Adapter,这个adapter就是该项目核心要实现的目标

#这是adapter直接拿到RecyclerView里面的情况,由于RecyclerView与ListView的区别,所以我提供了RecyclerAdapter和ListViewAdapter两种管理器,这个跟视图和逻辑均无关联

#SimpleAdapterItem,SimpleAdapterItem2,SimpleAdapterItem3是我们要实现的适配器

#程序运行图

<file_sep>/app/src/main/java/com/blesslp/adapter/compat/base/intf/CommonViewHolderIntf.java
package com.blesslp.adapter.compat.base.intf;
import android.content.Context;
import android.view.View;
/**
* Created by liufan on 16/12/1.
*/
public interface CommonViewHolderIntf<T extends CommonViewHolderIntf> {
public View getConvertView();
public Context getContext();
public int getCurrentPosition();
public void setCurrentPosition(int position);
}
<file_sep>/app/src/main/java/com/blesslp/adapter/compat/base/intf/ViewHolderalbe.java
package com.blesslp.adapter.compat.base.intf;
import com.blesslp.adapter.compat.base.common.BaseViewHolder;
/**
* Created by liufan on 16/12/2.
*/
public interface ViewHolderalbe<T extends BaseViewHolder> {
public void bindViewHolder(T adapterItem);
public T getViewHolder() ;
}
|
45ed8664ceb6d6add112b590a16a7703ce675f12
|
[
"Markdown",
"Java"
] | 6
|
Java
|
blesslp/CommonAdapter
|
3e159330ad60f5c89dbfa27c77c1aa4d23e44857
|
75dbc81a30676070fb4d6e0e5033a6ed89a59682
|
refs/heads/master
|
<repo_name>tombjarne/fazing-void-frontend<file_sep>/src/assets/images/desktop.ini
[LocalizedFileNames]
profile-icon-fazing-void.png=@profile-icon-fazing-void.png,0
search-icon-fazing-void.png=@search-icon-fazing-void.png,0
tools-icon-fazing-void.png=@tools-icon-fazing-void.png,0
<file_sep>/src/app/articles/articles.component.ts
import { Component, OnInit, Input } from '@angular/core';
import { WebServiceService } from "./../services/web-service.service";
import { Router } from '@angular/router';
import { ShopComponent } from './../shop/shop.component';
import { Article } from './../model/article';
@Component({
selector: 'app-articles',
templateUrl: './articles.component.html',
styleUrls: ['./articles.component.css']
})
export class ArticlesComponent implements OnInit {
@Input() articleDetails = { id_article: '', id_category: '', name_de: '', name_en: '', price: '', release_date: '',
description_de: '', description_en: '', availability: '', pictures: '', game_language: '', audio_languge: '',
video_link: '', teaser_de: '', teaser_en: '', features_de: '', features_en: '', age_rating: '',
content_rating: '', system_requirements: '', c_date: '', active: '',};
constructor(
public restApi: WebServiceService,
public router: Router,
public app: ShopComponent,
) { }
ngOnInit() {
}
// Get article list
addArticle() {
this.restApi.createArticle(this.articleDetails).subscribe(data => {
this.app.loadArticles(); this.router.navigate(['/']);
});
}
}
<file_sep>/src/app/app-routing.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { GamesComponent } from './games/games.component';
import { NewsComponent } from './news/news.component';
import { StudioComponent } from './studio/studio.component';
import { ShopComponent } from './shop/shop.component';
import { ContactComponent } from './contact/contact.component';
import { LoginComponent } from './login/login.component';
import { ProfileComponent } from './profile/profile.component';
import { SignupComponent } from './signup/signup.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'games', component: GamesComponent },
{ path: 'news', component: NewsComponent },
{ path: 'studio', component: StudioComponent },
{ path: 'shop', component: ShopComponent },
{ path: 'contact', component: ContactComponent },
{ path: 'profile', component: ProfileComponent },
{ path: '', redirectTo: '/', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'profile', component: ProfileComponent },
{ path: 'signup', component: SignupComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>/src/app/services/auth.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthService {
uri = 'http://localhost:8000';
token;
ttpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
}
constructor(public http: HttpClient, private router: Router) { }
login(email: string, password: string) {
this.http.post(this.uri + '/auth/login', { email: email, password: password })
.subscribe((resp: any) => {
this.router.navigate(['profile']);
localStorage.setItem('auth_token', resp.token);
})
}
logout() {
localStorage.removeItem('auth_token');
}
public get logIn(): boolean {
return (localStorage.getItem('auth_token') !== null);
}
public userToken(): string {
return localStorage.getItem('auth_token');
}
}
<file_sep>/src/app/fazing-void/fazing-void.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { FazingVoidComponent } from './fazing-void.component';
describe('FazingVoidComponent', () => {
let component: FazingVoidComponent;
let fixture: ComponentFixture<FazingVoidComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ FazingVoidComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(FazingVoidComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>/src/app/profile/profile.component.ts
import { Component, OnInit } from '@angular/core';
import { UserServiceService } from '../services/user-service.service';
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
currentUser;
constructor(private restApi: UserServiceService) { }
ngOnInit() {
this.loadUser();
}
loadUser(){
this.restApi.getUser().subscribe((data: {}) => {
this.currentUser = data;
});
}
}
<file_sep>/src/app/model/review.ts
export class Review {
name: string;
email: string;
}
<file_sep>/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { SignupComponent } from './signup/signup.component';
import { LoginComponent } from './login/login.component';
import { AppComponent } from './app.component';
import { NavComponent } from './nav/nav.component';
import { AboutComponent } from './about/about.component';
import { ContactComponent } from './contact/contact.component';
import { HomeComponent } from './home/home.component';
import { ShopComponent } from './shop/shop.component';
import { ProfileComponent } from './profile/profile.component';
import { FazingVoidComponent } from './fazing-void/fazing-void.component';
import { AppRoutingModule } from './app-routing.module';
import { DashboardComponent } from './dashboard/dashboard.component';
import { GamesComponent } from './games/games.component';
import { NewsComponent } from './news/news.component';
import { StudioComponent } from './studio/studio.component';
import { HttpClientModule } from '@angular/common/http';
import { registerLocaleData } from '@angular/common';
import { FooterComponent } from './footer/footer.component';
import { ArticlesComponent } from './articles/articles.component';
import localeDe from '@angular/common/locales/de';
import localeDeExtra from '@angular/common/locales/extra/de';
import localeUs from '@angular/common/locales/es-US';
import localeUsExtra from '@angular/common/locales/extra/en-US-POSIX';
import { AlertComponent } from './alert/alert.component';
registerLocaleData(localeDe, 'de');
registerLocaleData(localeUs, 'es-US');
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'games', component: GamesComponent },
{ path: 'news', component: NewsComponent },
{ path: 'studio', component: StudioComponent },
{ path: 'shop', component: ShopComponent },
{ path: 'contact', component: ContactComponent },
{ path: 'profile', component: ProfileComponent },
{ path: 'login', component: LoginComponent },
{ path: 'profile', component: ProfileComponent },
{ path: 'signup', component: SignupComponent },
{ path: 'about', component: AboutComponent },
{ path: 'articles', component: ArticlesComponent},
];
@NgModule({
declarations: [
AppComponent,
NavComponent,
AboutComponent,
ContactComponent,
HomeComponent,
ShopComponent,
ProfileComponent,
FazingVoidComponent,
DashboardComponent,
GamesComponent,
NewsComponent,
StudioComponent,
FooterComponent,
SignupComponent,
LoginComponent,
ArticlesComponent,
AlertComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
FormsModule,
RouterModule.forRoot([
{ path: '', component: ShopComponent },
])
],
exports: [RouterModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/src/app/services/web-service.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
import { Article } from './../model/article';
@Injectable({
providedIn: 'root'
})
export class WebServiceService {
apiURL = 'http://localhost:8000';
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
}
constructor(private http: HttpClient) { }
getArticles(): Observable<Article> {
return this.http.get<Article>(this.apiURL + '/article')
.pipe(
retry(1),
catchError(this.handleError)
)
}
/* getComments(id: number): Observable<Comment> {
return this.http.get<Comment>(this.apiURL + '/article/' + id + '/comments')
.pipe(
retry(1),
catchError(this.handleError)
)
} */
deleteArticle(id: number) {
return this.http.delete<Article>(this.apiURL + '/article/' + id, this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
)
}
createArticle(article): Observable<Article> {
console.log(JSON.stringify(article));
return this.http.post<Article>(this.apiURL + '/article', JSON.stringify(article), this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
)
}
// Error handling
handleError(error: any) {
let errorMessage = '';
if (error.error instanceof ErrorEvent) {
// Get client-side error
errorMessage = error.error.message;
} else {
// Get server-side error
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}
window.alert(errorMessage);
return throwError(errorMessage);
}
}
<file_sep>/src/app/model/user.ts
export class User {
id_user: number;
name: string;
email: string;
profile_picture: string;
password: string;
birthday: string;
steam_name: string;
newsletter: string;
status: string;
r_date: number;
active: number;
created_at: string;
updated_at: string;
}
<file_sep>/src/app/shop/shop.component.ts
import { Component } from '@angular/core';
import { ArticlesComponent } from './../articles/articles.component';
import { WebServiceService } from "./../services/web-service.service";
import { Article } from './../model/article';
@Component({
selector: 'app-root',
templateUrl: './shop.component.html',
styleUrls: ['./shop.component.css']
})
export class ShopComponent {
title = 'FazingVoid-Shop';
articles: any = [];
selectedArticle: Article;
constructor(
public restApi: WebServiceService
) { }
ngOnInit() {
this.loadArticles()
}
onSelect(article: Article): void {
console.log('selected id ' + article.id_article);
this.selectedArticle = article;
}
// Get articles list
loadArticles() {
return this.restApi.getArticles().subscribe((data: {}) => {
this.articles = data;
})
}
deleteArticle(id: number) {
if (window.confirm('Are you sure, you want to delete artilce with id ' + id + ' ?' )) {
this.restApi.deleteArticle(id).subscribe(data => {
this.loadArticles();
})
}
}
}
<file_sep>/src/app/model/article.ts
export class Article {
id_article: number;
id_category: number;
name_de: string;
name_en: string;
price: number;
release_date: string;
description_de: string;
description_en: string;
availability: number;
pictures: string;
game_language: string;
audio_language: string;
video_link: string;
teaser_de: string;
teaser_en: string;
features_de: string;
features_en: string;
age_rating: string;
content_rating: string;
system_requirements: string;
c_date: string;
active: number;
}
|
5d66219e1d3d917458f7faa799a24ee28a80890a
|
[
"TypeScript",
"INI"
] | 12
|
INI
|
tombjarne/fazing-void-frontend
|
b3e39ec360d97aa667e469286265de979f0eceff
|
b61597c5039aa0b9b22affd381d5ae348da98f12
|
refs/heads/master
|
<repo_name>Sagar0802/sidemenu<file_sep>/myScript.js
function openNav() {
var x=document.getElementById("mySidenav");
if (x.style.display === "none") {
document.getElementById("mySidenav").style.minWidth="175px";
document.getElementById("main").style.marginLeft = "175px";
x.style.display = "block";
}
else {
x.style.display = "none";
document.getElementById("main").style.marginLeft = "0px";
}
}
|
b79edf983cad18fd9e96d2ee9da89fbe46c8b3a6
|
[
"JavaScript"
] | 1
|
JavaScript
|
Sagar0802/sidemenu
|
5979186f80089a8bdc61f33b321438f3062f51c7
|
af6e8b47afdc73e235e0846813a926d5054f1200
|
refs/heads/master
|
<repo_name>naveen324/mynodejsapplication<file_sep>/startApp.sh
#!/bin/sh
export NODE_ENV=production
export DB_PRD_HOST=
export DB_PRD_USER=postgres
export DB_PRD_PASS=
export NODE_HOST=localhost
export NODE_PORT=8080
node /myapp/index.js&
exit 0
|
e59cc39464f48202f95198dc96f87dad4bdfafc3
|
[
"Shell"
] | 1
|
Shell
|
naveen324/mynodejsapplication
|
49b546985939cf74a6e8f5115cb418f372a25e00
|
a1149887dd1f1e70f502a544f40e6b1b2379b215
|
refs/heads/master
|
<repo_name>cwmat/dwa-project-2<file_sep>/index.php
<!doctype html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
<head>
<!--
<NAME> HES DWA Project 2
Sources:
HTML5-Boilerplate (comes with jquery and modernizer): https://html5boilerplate.com/
Pure CSS: http://purecss.io/
Open source images: https://unsplash.com/
Random Words:
http://listofrandomwords.com/index.cfm?blist
and
http://www.paulnoll.com/Books/Clear-English/words-01-02-hundred.html
-->
<!-- Meta -->
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Chaz Mateer HES DWA Project 2</title>
<meta name="description" content="Project 2 for HES DWA">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Stylesheets -->
<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.6.0/pure-min.css">
<!--[if lte IE 8]>
<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.6.0/grids-responsive-old-ie-min.css">
<![endif]-->
<!--[if gt IE 8]><!-->
<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.6.0/grids-responsive-min.css">
<!--<![endif]-->
<link rel="stylesheet" href="css/main.css">
<!-- modernizr js -->
<script src="js/vendor/modernizr-2.8.3.min.js"></script>
<!-- PHP -->
<?php require "xkcd_password_generator.php" ?>
</head>
<body>
<!-- Header -->
<div class="pure-g is-center">
<header class="pure-u-1">
<h1>xkcd PASSWORD GENERATOR</h1>
</header>
</div>
<!-- Wrapper -->
<div class="pure-g wrapper is-center">
<!-- Results -->
<div class="pure-u-1 results-section">
<div class="content">
<h1 class="content-head">Here is your randomly generated password!</h1>
<form class="pure-form">
<input
class="pure-input-1 pure-input-rounded"
type="text"
readonly
placeholder="Temp"
value=<?php echo get_xkcd_password();?>>
</form>
</div>
</div>
</div>
<!-- Options -->
<div class="pure-g wrapper is-center">
<div class="pure-u-1 options-section">
<h1 class="content-head">Options</h1>
</div>
<div class="pure-u-1 options-section">
<form
class="pure-form pure-form-stacked"
method="POST"
action="index.php">
<fieldset>
<div class="pure-g">
<div class="pure-u-1 pure-u-md-1-3">
<label for="min-words">Number of words</label>
<select id="min-words" class="pure-input-1-2" data-option="min-words" name="min-words">
<option value="2">2</option>
<option value="3">3</option>
<option value="4" selected="selected">4</option>
<option value="5">5</option>
</select>
</div>
<div class="pure-u-1 pure-u-md-1-3"></div>
<div class="pure-u-1 pure-u-md-1-3">
<label for="case-opt">Case</label>
<select id="case-opt" class="pure-input-1-2" data-option="case-opt" name="case-opt">
<option value="lowercase" selected="selected">All lowercase</option>
<option value="uppercase">All uppercase</option>
</select>
</div>
<div class="pure-u-1 pure-u-md-1-3">
<label for="add-num" class="pure-checkbox">
Add a number? <input id="add-num" type="checkbox" name="add-num" data-option="add-num">
</label>
</div>
<div class="pure-u-1 pure-u-md-1-3"></div>
<div class="pure-u-1 pure-u-md-1-3">
<label for="separator">Separator</label>
<input
id="separator"
class="pure-u-23-24"
type="separator"
name="separator"
data-option="separator"
value="-"
maxlength="1"
size="4">
</div>
<div class="pure-u-1 pure-u-md-1-3">
<label for="add-char" class="pure-checkbox">
Add Special characters? <input id="add-char" type="checkbox" name="add-char" data-option="add-char">
</label>
</div>
<div class="pure-u-1 is-center">
<button type="submit" class="pure-button pure-button-primary">GENERATE</button>
</div>
<!-- End sub grid -->
</div>
</fieldset>
</form>
</div>
<!-- End main grid -->
</div>
<div class="pure-g wrapper is-center">
<div class="pure-u-1 submit-section">
<h1 class="content-head">The Back Story</h1>
<p>
xkcd, the self proclaimed "webcomic of romance, sarcasm, math, and language", produced a comic strip questioning the modern trend of password complexity titled “Password Strength”. Their opinion is that there is a threshold at which the 'entropic' value (the level of randomness that would create difficulty for brute force password guessing) of a password gets overshadowed by its ability to actually be remembered by the user. They go further to propose a strategy that provides both a higher value of entropy and an easier means by which to remember said password.
</p>
<p>
The example that the comic presents to showcase their theory consists of a complex string of alphanumeric characters, “Tr0ub4dor83”, contrasted with a seemingly ridiculous statement, “correct horse battery staple”. The logic is that the alphanumeric mashup password, given its shorter length, provides a much easier password for a brute force algorithm to guess versus the longer “semi-ridiculous” and multi-word password. Based on their calculation, even without the random numbers/special characters, the longer password construct provides a much greater level of protection while also allowing for easier remembrance by simply creating an image in your mind of the phrase. Their estimate depicts a brute force algorithm of 1,000 guess/second taking about 550 years to guess the longer easier-to-remember password, while at the same guesses/second, the shorter more complex password could potentially be cracked in about three days.
</p>
<p>
Check out the comic to see for yourself and have fun playing around with this password generator inspired by the comic!
</p>
</div>
</div>
<!-- Footer -->
<footer class="pure-g is-center">
<div class="pure-u-1">
<h4>Check out these cool sites that inspired/supported this project!</h4>
</div>
<div class="pure-u-1 pure-u-md-1-3">
<a href="http://listofrandomwords.com/index.cfm?blist" target="_blank">Random Words!</a>
</div>
<div class="pure-u-1 pure-u-md-1-3">
<a href="http://www.paulnoll.com/Books/Clear-English/words-01-02-hundred.html" target="_blank">More Random Words</a>
</div>
<div class="pure-u-1 pure-u-md-1-3">
<a href="https://xkcd.com/936/" target="_blank">xkcd Comic Strip</a>
</div>
</footer>
<!-- Import JS May add JS features in the future -->
<!-- <script src="js/vendor/jquery-1.11.3.min.js"></script>
<script src="js/main.js"></script> -->
</body>
</html>
<file_sep>/xkcd_password_generator.php
<?php
// Options passed in from client
// Defualt values
$min_words = 4;
$add_num = False;
$add_char = False;
$case_opt = "lowercase";
$separator = "-";
// Pages to scrape for words - Removed due to slow load time
// $pages = Array(
// "http://www.paulnoll.com/Books/Clear-English/words-29-30-hundred.html",
// "http://www.paulnoll.com/Books/Clear-English/words-03-04-hundred.html",
// "http://www.paulnoll.com/Books/Clear-English/words-01-02-hundred.html",
// );
$pages = Array(
"words.txt",
);
/**
* Unpack values from POST array
*
*/
function unpack_post() {
// Globals
global $min_words;
global $add_num;
global $add_char;
global $case_opt;
global $separator;
if (array_key_exists('min-words', $_POST)) {
$min_words = $_POST['min-words'];
}
if (array_key_exists('add-num', $_POST)) {
$add_num = True;
}
if (array_key_exists('add-char', $_POST)) {
$add_char = True;
}
if (array_key_exists('separator', $_POST)) {
$separator = $_POST['separator'];
}
if (array_key_exists('case-opt', $_POST)) {
$case_opt = $_POST['case-opt'];
}
// Mostly just for testing
return [$min_words, (int)$add_num, (int)$add_char, $separator, $case_opt];
}
/**
* Populate an array of words
*
* @param pages - an array of web pages to scrape for words
*/
function get_words_list($pages) {
$output = Array();
$parsed_output = Array();
// Scrape web pages
foreach($pages as $page) {
$page_contents = file_get_contents($page);
preg_match_all('#<li>(.*?)</li>#is', $page_contents, $out);
$output = array_merge($output, $out[0]);
}
// Hinky way of removing <li> tag
foreach ($output as $value) {
$temp = str_replace("<li>", "", $value);
$temp2 = str_replace("</li>", "", $temp);
array_push($parsed_output, $temp2);
}
return $parsed_output;
}
/**
* Add a random number to a random array index
*
*/
function add_number($in_array) {
$random_num = rand(1, 9);
$random_idx = rand(0, count($in_array) - 1);
$in_array[$random_idx] = $in_array[$random_idx] . $random_num;
return $in_array;
}
/**
* Add a random number to a random array index
*
*/
function add_char($in_array) {
$special_chars = ["!", "@", "#", "$", "%", "^", "&", "*"];
$random_char = $special_chars[rand(0, count($special_chars) - 1)];
$random_idx = rand(0, count($in_array) - 1);
$in_array[$random_idx] = $in_array[$random_idx] . $random_char;
return $in_array;
}
/**
* Convert the in_array elements to the specified case
*
* @param case - The desired case for all array elements (all lower or all upper))
* @param in_array - The input array that the case change should occur on
*/
function handle_case($case, &$in_array) {
foreach ($in_array as &$value) {
if ($case == "uppercase") {
$value = strtoupper($value);
} else {
$value = strtolower($value);
}
}
}
/**
* Get a ranomized password
*
*/
function get_xkcd_password() {
// Globals
global $min_words;
global $add_num;
global $add_char;
global $case_opt;
global $separator;
global $pages;
unpack_post();
$words_list = get_words_list($pages);
$xkcd_password = Array();
for ($i = 1; $i <= $min_words; $i++) {
$temp_rand_idx = rand(0, count($words_list) - 1);
array_push($xkcd_password, trim($words_list[$temp_rand_idx]));
unset($words_list[$temp_rand_idx]);
}
// Check special conditions
// Check add num
if ($add_num) {
$xkcd_password = add_number($xkcd_password);
}
// Check add special character
if ($add_char) {
$xkcd_password = add_char($xkcd_password);
}
// Check case
handle_case($case_opt, $xkcd_password);
return implode($separator, $xkcd_password);
}
?>
<file_sep>/README.md
# <NAME>) Mateer Project 2: HES DWA Fall 2015
## XKCD Password Generator
### Live URL to the site
- [p2.cwmat-dwa.me](http://p2.cwmat-dwa.me/)
### Description
> Project to create an xkcd random password generator with various user options to manipulate the password. Utilizes PHP code server side to scrape random words from websites and files on the server and spit them out to the user. Allows the user to cater the password to their needs by allowing them to change case, add numbers, choose their separator value, and/or add special characters.
> Background information:
> xkcd, the self proclaimed "webcomic of romance, sarcasm, math, and language", produced a comic strip questioning the modern trend of password complexity titled “Password Strength”. Their opinion is that there is a threshold at which the 'entropic' value (the level of randomness that would create difficulty for brute force password guessing) of a password gets overshadowed by its ability to actually be remembered by the user. They go further to propose a strategy that provides both a higher value of entropy and an easier means by which to remember said password.
> The example that the comic presents to showcase their theory consists of a complex string of alphanumeric characters, “Tr0ub4dor83”, contrasted with a seemingly ridiculous statement, “correct horse battery staple”. The logic is that the alphanumeric mashup password, given its shorter length, provides a much easier password for a brute force algorithm to guess versus the longer “semi-ridiculous” and multi-word password. Based on their calculation, even without the random numbers/special characters, the longer password construct provides a much greater level of protection while also allowing for easier remembrance by simply creating an image in your mind of the phrase. Their estimate depicts a brute force algorithm of 1,000 guess/second taking about 550 years to guess the longer easier-to-remember password, while at the same guesses/second, the shorter more complex password could potentially be cracked in about three days.
> Check out the comic to see for yourself and have fun playing around with this password generator inspired by the comic!
### Link to screencast
- [Screencast](http://screencast.com/t/ZNTU6BfH9sT)
### Professor/TA Details
None so far.
### Sources
HTML5-Boilerplate (comes with jquery and modernizer): https://html5boilerplate.com/
Pure CSS: http://purecss.io/
Open source images: https://unsplash.com/
Comical filler text: http://www.cheeseipsum.co.uk/
Random Words: http://listofrandomwords.com/index.cfm?blist
More random words: http://www.paulnoll.com/Books/Clear-English/words-01-02-hundred.html
|
fa12dfd427d43a01317c8dde9d6c739aa7d1a9af
|
[
"Markdown",
"PHP"
] | 3
|
PHP
|
cwmat/dwa-project-2
|
7ec15a4e451828880a09b971e7d6da8b72b19e20
|
b0f59c4cdceed1d87ae70fb9251c7be5047c4ac4
|
refs/heads/master
|
<repo_name>PauloMachadoSilva/jasmine-standalone-3.2.1<file_sep>/spec/aninharSuites.spec.js
//SUITES PODEM SER ANINHADAS E CONTER OUTRAS SUÍTES DENTRO DELAS
//AS FUNÇÕES ESPECIAIS COMO BEFOREEACH OU AFTERALL SERÃO EXECUTADAS ANTES E DEPOIS DOS TESTES EM ORDEM
//TOMAR CUIDADO AO ANINHAR SUITES PARA NÃO TORNAR O TESTE COMPLEXO E DE DIFICIL COMPREENSÃO
describe('Suite Externa', function() {
var contadorExterno = 0;
//É EXECUTADO EXTERNAMENTE E INTERNAMENTE
beforeEach(function() {
contadorExterno++;
});
it('Deve conter 1 para o contadorExterno', function () {
expect(contadorExterno).toEqual(1);
});
describe('Suite Interna', function() {
var contadorInterno = 0;
//APENAS UMA UNICA VEZ ANTES DO TESTE
beforeEach(function() {
contadorInterno++;
});
it('Deve validar o valor dos contadores', function () {
expect(contadorInterno).toEqual(1);
expect(contadorExterno).toEqual(2);
});
});
})
<file_sep>/spec/toThrow.spec.js
//VERIFICA SE UMA EXCEÇÃO É LANÇADA POR UM MÉTODO
//NÃO REALIZA VALIDAÇÃO EM DETALHE DO TIPO DE EXCEÇÃO LANÇADA,
//APENA CERTIFICA QUE UM ERRO OCORREU NA EXECUÇÃO DA FUNÇÃO
describe('Comparador com toThrow', function() {
it('Deve validar o uso do toThrow', function () {
var multi = function() {
numero * 10;
}
var somar = function(n1,n2) {
return n1 + n2;
}
expect(multi).toThrow();
expect(somar).not.toThrow();
})
})<file_sep>/spec/fail.spec.js
//FALHA MANUAL PERMITE INTERROMPER UM TESTE LANÇANDO UM ERRO
//O JASMINE POSSUI A FUNÇÃO 'FAIL' PARA FALHAR MANUALKMENTE UM TESTE
//UTILIZAMOS A FALHA MANUAL PARA CERTIFICAR QUE UMA OPERAÇÃO NÃO DESEJADA NÃO SEJA EXECUTADA
describe('Teste a função "Fail" de falha manual', function() {
it('Deve demonstrar o uso do Fail', function () {
var op = function(executar,callback) {
if(executar) {
callback();
}
}
op(false, function() {
fail('não deve executar função de callback');
});
})
})<file_sep>/spec/toBeFalsy.spec.js
//VERIFICA SE UM VALOR É INVALIDO SE FOR 'FALSE', '0', '',
//'UNDEFINED', 'NULL' OU 'Nan'
describe('Comparador com toBeFalsy', function() {
it('Deve demonstrar o uso do toBeFalsy', function () {
expect(null).toBeFalsy();
expect(undefined).toBeFalsy();
expect('').toBeFalsy();
expect(false).toBeFalsy();
expect(NaN).toBeFalsy();
expect(0).toBeFalsy();
expect(true).not.toBeFalsy();
})
})
<file_sep>/spec/beforeEach.spec.js
//FUNÇÃO JAVASCRIPT GLOBAL DO JASMINE QUE É EXECUTADA ANTES DE CADA TESTE
//PODE SER EXECUTADA ANTES DE CADA TESTE, SERVE PARA INICIALIZAR O REINICIAR UM STATUS
//PODE TAMBEM EXECUTAR UMA AÇÃO ANTES DE CADA TESTE
describe('Teste do beforeEach', function() {
var contador = 0;
beforeEach(function() {
contador++;
});
it('Deve incrementar o contador para 1', function () {
expect(contador).toEqual(1);
});
it('Deve incrementar o contador para 2', function () {
expect(contador).toEqual(2);
});
})<file_sep>/spec/beforeAll.spec.js
//FUNÇÃO JAVASCRIPT GLOBAL DO JASMINE QUE É EXECUTADA UMA UNICA VEZ ANTES DA EXECUÇÃO DOS TESTES
//SERVE PARA INICIALIZAR UM STATUS OU CRIAR OBJETOS
describe('Teste do beforeAll', function() {
var contador = 0;
//APENAS UMA UNICA VEZ ANTES DO TESTE
beforeAll(function() {
contador = 10;
});
//A CADA EXECUÇÃO DE TESTE
beforeEach(function() {
contador++;
});
it('Deve garantir o valor 11 para o contador', function () {
expect(contador).toEqual(11);
});
it('Deve garantir o valor 12 para o contador', function () {
expect(contador).toEqual(12);
});
})<file_sep>/spec/toBeGreaterThan.spec.js
//COMPARA DE UM VALOR NUMÉRICO É MAIOR QUE O OUTRO
//REALIZA UMA CONVERSÃO PARA VALOR NUMÉRICO ANTES DA COMPARAÇÃO, PODENDO SER TEXTO
//PARA VALORES IGUAIS UTILIZE O TOEQUAL
describe('Comparador com toBeGreaterThan', function() {
it('Deve demonstrar o uso do toBeGreaterThan', function () {
var pi = 3.1415;
expect(4).toBeGreaterThan(pi);
expect('5').toBeGreaterThan(pi);
expect('3').not.toBeGreaterThan(pi);
})
})
<file_sep>/spec/desabilitandoTestes.spec.js
//PARA DESABILITAR UM TESTE USAMOS UM 'X' NA FRENTE DO 'IT'
//ELES TAMBEM PODEM SER CONSIDERADOS INATIVOS CASO NÃO POSSUAM ARGUMENTOS
//PODEMOS TAMBEM USAR UMA FUNÇÃO DENOMINADA 'PENDING' DENTRO DO TESTE PARA INATIVALO
describe('Desabilitando testes', function() {
var contador = 0;
beforeEach(function() {
contador++;
});
xit('Teste desabilitado com Xit', function () {
expect(contador).toEqual(122);
});
it('Teste sem spec', function () {
});
it('Teste ainda pendente', function () {
expect(contador).toEqual(122);
pending('teste ainda pendente')
});
})<file_sep>/spec/afterAll.spec.js
//FUNÇÃO JAVASCRIPT GLOBAL DO JASMINE QUE É EXECUTADA UMA UNICA VEZ DEPOIS DA EXECUÇÃO DOS TESTES
//SERVE PARA LIMPAR ALGUNS STATUS GLOBAIS
describe('Teste do afterAll', function() {
var contador = 0;
//APENAS UMA UNICA VEZ ANTES DO TESTE
beforeAll(function() {
contador = 10;
});
//A CADA EXECUÇÃO DE TESTE
afterAll(function() {
contador = 0;
});
it('Deve garantir o valor 11 para o contador', function () {
expect(contador).toEqual(10);
});
it('Deve garantir o valor 12 para o contador', function () {
expect(contador).toEqual(10);
});
})<file_sep>/spec/toBeLessThan.spec.js
//COMPARA DE UM VALOR NUMÉRICO É MENOR QUE O OUTRO
//REALIZA UMA CONVERSÃO PARA VALOR NUMÉRICO ANTES DA COMPARAÇÃO, PODENDO SER TEXTO
//PARA VALORES IGUAIS UTILIZE O TOEQUAL
describe('Comparador com toBeLessThan', function() {
it('Deve demonstrar o uso do toBeLessThan', function () {
var pi = 3.1415;
expect(3).toBeLessThan(pi);
expect(3.5).not.toBeLessThan(pi);
})
})
<file_sep>/spec/spyOn.spec.js
//SERVA PARA CRIAR UM MOCK OBJETO FALSO A SER UTILIZADO NOS TESTES
//UM OBJETO SPY RECEBE COMO PARAMETROS O NOME DO OBJETO E DO METODO A SEREM UTILIZADOS NO MOCK
describe('Teste do objeto SPY', function() {
var calculadora = {
somar: function (n1, n2) {
return n1 + n2;
},
somarFake: function (n1, n2) {
return n1 + n2;
},
subtrair: function (n1, n2) {
return n1 - n2;
},
multiplicar: function (n1, n2) {
return n1 * n2;
},
div: function (n1, n2) {
return n1 * n2;
}
}
beforeEach(function() {
//AO CRIAR OS SPY DEIXAMOS NOSSO OBJETO INDEFINIDO
spyOn(calculadora, 'somar');
//SPYFAKE TRANFORMA CALL ANTERIOR EM UMA NOVA CALL
spyOn(calculadora, 'somarFake').and.callFake(function(n1,n2) {
return n1 - n2;
});
//CRIAR UM SPY QUE EXECUTA O MÉTODO ORIGINAL
spyOn(calculadora, 'subtrair').and.callThrough();
//CRIAR UM SPY QUE SIMULAR O RETORNO UM VALOR
spyOn(calculadora, 'multiplicar').and.returnValue(100);
//CRIAR UM SPY QUE SIMULAR O RETORNA VARIOS VALORES
spyOn(calculadora, 'div').and.returnValues(1,2,3);
})
//toHaveBeenCalled - VERIRFICA SE O MÉTODO FOI CHAMADO
it('deve chamar o método somar ao menos uma vez', function() {
calculadora.somar(1,1);
expect(calculadora.somar).toHaveBeenCalled();
});
//toBeUndefined - VERIRFICA SE O MÉTODO É INDEFINIDO
it('deve chamar o método somar como não definido', function() {
//caculadora.somar(1,1);
expect(calculadora.somar(1,1)).toBeUndefined();
});
//toHaveBeenCalledTimes - VERIRFICA SE O MÉTODO FOI CHAMADO 2 VEZES
it('deve chamar o método somar 2 vezes', function() {
calculadora.somar(1,1);
calculadora.somar(1,1);
expect(calculadora.somar).toHaveBeenCalledTimes(2);
});
//VERIRFICA SE O MÉTODO FOI CHAMADO COM OS RESPECTIVOS PARAMETROS
it('deve chamar o método com os respectivos paramentros (1,1) e (1,2)', function() {
calculadora.somar(1,1);
calculadora.somar(1,2);
expect(calculadora.somar).toHaveBeenCalledWith(1,1);
expect(calculadora.somar).toHaveBeenCalledWith(1,2);
});
//EXECUTA O MÉTODO ORGINAL
it('deve chamar o método ORIGINAL', function() {
expect(calculadora.somar(1,1)).toBeUndefined();
expect(calculadora.subtrair(2,1)).toEqual(1);
});
//EXECUTA O MÉTODO ORGINAL
it('deve retornar 100 para o método multiplicar', function() {
expect(calculadora.multiplicar(10,10)).toEqual(100);
});
//DEVE RETORNAR VALORES DISTINTOS
it('deve retornar varios valores de acordo com chamadas', function() {
expect(calculadora.div(3,4)).toEqual(1);
expect(calculadora.div(3,4)).toEqual(2);
expect(calculadora.div(3,4)).toEqual(3);
expect(calculadora.div(3,4)).toBeUndefined(3);
});
//DEVE TRANSFORMAR O MÉTODO SOMAR EM SUB
it('deve transformar o método anterior em um novo método', function() {
expect(calculadora.somarFake(5,1)).toEqual(4);
});
})
|
ea5baa2ca6e2deeb49cce49aecf9bd9dffefc719
|
[
"JavaScript"
] | 11
|
JavaScript
|
PauloMachadoSilva/jasmine-standalone-3.2.1
|
a4578729bf5d404c489e8c7962ca57d9e2ad525f
|
59f37ce97654a7594016bbce40985b41e2061021
|
refs/heads/master
|
<file_sep>package com.example.android.java;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ScrollView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private ScrollView mScroll;
private TextView mLog;
/*The Override annotation will call other methods from an extended subclass
* first before the logging components. The logging components are then called
* from the XML file
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize the logging components
/*The private variables are implemented with XML methods to call an id reference
*to run a specific attribute
*/
mScroll = (ScrollView) findViewById(R.id.scrollLog);
mLog = (TextView) findViewById(R.id.tvLog);
mLog.setText("");
displayMessage("onCreate");
}
public void onRunBtnClick(View v) {
displayMessage("Running code!");
}
public void onClearBtnClick(View v) {
mLog.setText("");
mScroll.scrollTo(0, mScroll.getBottom());
}
public void displayMessage(String message) {
mLog.append(message + "\n");
mScroll.scrollTo(0, mScroll.getBottom());
}
/*The methods will display text when the orientation has switched
*and the code will run again to the onPause method and cycle back
*to running the onResume method*/
@Override
protected void onPause() {
super.onPause();
displayMessage("onPause");
}
@Override
protected void onResume() {
super.onResume();
displayMessage("onResume");
}<file_sep>import java.util.*;
public class MainCollectionTwo {
public static void main(String[] args) {
//Declaring a list of cars and its information and using the Cars class and its methods
Cars vehicle1 = new Cars("Toyota", 1995, "Supra");
Cars vehicle2 = new Cars("Dodge", 2017, "Ram");
Cars vehicle3 = new Cars("BMW", 2017, "M3");
//Creating an ArrayList of vehicles and adding each vehicle to the ArrayList
ArrayList<Cars> vehicles = new ArrayList<>();
vehicles.add(vehicle1);
vehicles.add(vehicle2);
vehicles.add(vehicle3);
System.out.println(vehicles);
}
}
<file_sep>import java.util.*;
public class MainCollectionOne {
public static void main(String[] args) {
//Creating a list of integers and converting them into a collection
//Find and print the number's position using the binarySearch
List<Integer> myArrayList = Arrays.asList(0,1,2,3,4,5,10,20,50,100);
System.out.println(Collections.binarySearch(myArrayList, 50));
System.out.println("Full list:");
/*Iterator method will cycle through each list in the while-loop
* and print each list
*/
Iterator iterator = myArrayList.iterator();
while(iterator.hasNext()) {
System.out.print(iterator.next() + ", ");
}
}
}
|
6714dba35cc2776a82e61d43409b40063677dbd9
|
[
"Java"
] | 3
|
Java
|
MikeGrabin/CIS2D-Final
|
28f22ba5d0decc1ce4e8d637f6c250e649f4d6f5
|
9de7540ac85068da15ab418b37413582f1267489
|
refs/heads/master
|
<file_sep>library(kohonen)
# import data, choose file interactively
data <- read.csv(file.choose(), header = T)
str(data)
X <- scale(data[, -1])
summary(X)
# unsupervised SOM
set.seed(224)
g <- somgrid(xdim = 10, ydim = 10)
map <- som(X, grid=g, alpha = c(0.05, 0.01), radius = 1)
plot(map, type = 'changes')
plot(map)
plot(map, type = 'mapping')
plot(map, type = 'count')
# supervised SOM
set.seed(222)
ind <- sample(2, nrow(X), replace = T, prob = c(0.7, 0.3))
train <- data[ind == 1,]
test <- data[ind == 2,]
trainX <- scale(train[, -1])
testX <- scale(test[, -1],
center = attr(trainX, "scaled:center"),
scale = attr(trainX, "scaled:scale"))
trainY <- factor(train[, 1])
Y <- factor(test[, 1])
test[,1] <- 0
testXY <- list(independent = testX, dependent = test[,1])
# classification and prediction model
set.seed(223)
map1 <- xyf(trainX,
classvec2classmat(factor(trainY)),
grid = somgrid(10, 10, "hexagonal"),
rlen = 200)
plot(map1, type = 'changes')
plot(map1)
pred <- predict(map1, newdata = testXY)
table(Predicted = pred$predictions[[2]], Actual = Y)
<file_sep>import numpy as np
"""
Minimalistic implementation of the Learning Vector Quantization (LVQ)
based on Python Data Science Cookbook
"""
# class of prototype vectors
class prototype(object):
"""
Define prototype, prototype is a vector with weights(p_vector) and label(class_id)
"""
def __init__(self, class_id, p_vector, epsilon):
self.class_id = class_id
self.p_vector = p_vector
self.epsilon = epsilon
def update(self, u_vector, increment = True):
"""
The function to update the prototype vector of the closest point
If the class label of the prototype vector is the same as the input data point, we will
increment the prototype vector with the difference between the prototype vector and data
point.
If the class label is different, we will decrement the prototype vector with the difference
between the prototype vector and data point.
"""
if increment:
# Move the prototype closer to input vector
self.p_vector = self.p_vector + self.epsilon * (u_vector - self.p_vector)
else:
# Move the prototype away from input vector
self.p_vector = self.p_vector - self.epsilon * (u_vector - self.p_vector)
class LVQ(object):
def __init__(self, x, y, n_classes, n_neurons, p_vectors, epsilon=0.9, epsilon_dec_factor=0.001):
"""
Initialize a LVQ network.
Parameters
-------
x, y : the data and label
n_classes: the # of distinctive classes
n_neurons: the # of prototype vectors for each class
epsilon: learning rate
epsilon_dec_factor: decrease factor for learning rate
p_vectors: the set of prototype vectors
"""
self.n_classes = n_classes
self.n_neurons = n_neurons
self.epsilon = epsilon
self.epsilon_dec_factor = epsilon_dec_factor
self.p_vectors = p_vectors
if(len(self.p_vectors) == 0):
p_vectors = []
for i in range(n_classes):
# select class i
y_subset = np.where(y == i)
# select tuple for chosen class
x_subset = x[y_subset]
# get R random indices between 0 and len(x_subset)
samples = np.random.randint(0, len(x_subset), n_neurons)
# select p_vectors, they are chosen randomly from the samples x
for sample in samples:
s = x_subset[sample]
p = prototype(i, s, epsilon)
p_vectors.append(p)
self.p_vectors = p_vectors
def find_closest(self, in_vector, proto_vectors):
"""
Find the closest prototype vector for a given vector
Parameters
-------
in_vector: the given vector
proto_vectors: the set of prototype vectors
"""
closest = None
position = None
closest_distance = 99999
for i in range(len(proto_vectors)):
distance = np.linalg.norm(in_vector - proto_vectors[i].p_vector)
if distance < closest_distance:
closest_distance = distance
closest = proto_vectors[i]
position = i
return [position, closest]
def find_runnerup(self, in_vector, proto_vectors):
"""
Find the second closest prototype vector for a given vector
Parameters
-------
in_vector: the given vector
proto_vectors: the set of prototype vectors
"""
closest_p_vector = self.find_closest(in_vector, proto_vectors)
runnerup = closest_p_vector
closest_distance = 99999
for p_v in proto_vectors:
distance = np.linalg.norm(in_vector - p_v.p_vector)
if (distance < closest_distance) and (p_v != closest_p_vector):
closest_distance = distance
runnerup = p_v
return runnerup
def predict(self, test_vector):
"""
Predict label for a given input
Parameters
-------
test_vector: input vector
"""
return self.find_closest(test_vector, self.p_vectors)[1].class_id
def fit(self, x, y):
"""
Perform iteration to adjust the prototype vector
in order to classify any new incoming points using existing data points
Parameters
-------
x: input
y: label
"""
while self.epsilon >= 0.01:
rnd_i = np.random.randint(0, len(x))
rnd_s = x[rnd_i]
target_y = y[rnd_i]
self.epsilon = self.epsilon - self.epsilon_dec_factor
closest_pvector = self.find_closest(rnd_s, self.p_vectors)[1]
if target_y == closest_pvector.class_id:
closest_pvector.update(rnd_s)
else:
closest_pvector.update(rnd_s, False)
closest_pvector.epsilon = self.epsilon
return self.p_vectors
def train_LVQ2(self, x, y):
"""
First improvement for LVQ, update both the winner and the runner up vector
Parameters
-------
x: input
y: label
"""
while self.epsilon >= 0.01:
rnd_i = np.random.randint(0, len(x))
rnd_s = x[rnd_i]
target_y = y[rnd_i]
self.epsilon = self.epsilon - self.epsilon_dec_factor
closest_pvector = self.find_closest(rnd_s, self.p_vectors)[1]
second_closest_pvector = self.find_runnerup(rnd_s, self.p_vectors)
compare_distance = np.linalg.norm(closest_pvector.p_vector - rnd_s)/np.linalg.norm(second_closest_pvector.p_vector - rnd_s)
if target_y == second_closest_pvector.class_id and target_y != closest_pvector.class_id and compare_distance > 0.8 and compare_distance < 1.2:
closest_pvector.update(rnd_s, False)
second_closest_pvector.update(rnd_s)
elif target_y == closest_pvector.class_id:
closest_pvector.update(rnd_s)
elif target_y != closest_pvector.class_id:
closest_pvector.update(rnd_s, False)
closest_pvector.epsilon = self.epsilon
return self.p_vectors<file_sep>- Implement ý tưởng tính khoảng cách di từ imput đến Best matching unit và dùng tỉ lệ (1/d1) / ( 1/d1 + 1/d2 + 1/d3) để làm weights trong Ensemble Learning.
Kết quả: Không khác cách dùng số lượng sample trong BMU
- Implement ý tưởng Boosting tạo ra 3 classifier.
Kết quả: Không cải thiện so với dùng ensemble dựa vào khoảng cách hay tỉ lệ. Nhưng tốc độ train nhanh<file_sep># Self Organzing Feature Map
This is a mini-project based on the course Deep Learning on Udemy
### Prerequisites
Minisom
https://pypi.org/project/MiniSom/
```
Give examples
```
### Installing
Python 3
Jupyter Notebook
Tensorflow
Keras
```
pip install ~
```
And repeat
```
until finished
```
## Acknowledgments
Deeplearning Course: https://www.udemy.com/deeplearning/
|
19cab79094b05974a3590a44889dc809d2f7d273
|
[
"Text",
"Python",
"R",
"Markdown"
] | 4
|
R
|
thedangnguyen2204/my_som
|
5c1c6f62e80c493898724c2a1b84f6964f49b918
|
8d8069f5f5608674abcd1e5ac541ac62cf718007
|
refs/heads/master
|
<repo_name>haileylgbt/tgiah<file_sep>/legacy/coin.lua
coin = {
graphic = love.graphics.newImage('blinky.png'),
}
function coin.create(this, px, py)
this.x = px + 6
this.y = py + 6
this.width = 20
this.height = 20
this.wave = 0
end
function coin.update(this, dt)
this.wave = (this.wave + dt) % (math.pi * 2)
end
function coin.draw(this, ox, oy)
love.graphics.draw(coin.graphic, this.x + ox, this.y + oy + math.sin(this.wave) * 4)
end<file_sep>/main.lua
-- I would like to thank SkyVaultGames for guiding me through the process thanks to his YouTube series. <3
tlm = require "tools/tlm"
gameLoop = require "tools/gameLoop"
renderer = require "tools/renderer"
obm = require "tools/obm"
asm = require "tools/asm"
Width = love.graphics.getWidth()
Height = love.graphics.getHeight()
key = love.keyboard.isDown
camera = require "tools/camera"
GAMETIME = 0
TILE_SIZE = 16
MAP_SIZE_WIDTH = 128
MAP_SIZE_HEIGHT = 64
local delta_time = {}
local av_dt = 0.016
local sample = 10
function love.load()
asm:load()
asm:add(love.graphics.newImage("assets/images/tile_sheet_1.png"),"tiles")
asm:add(love.audio.newSource("assets/audio/music/mus_belief.wav", "stream"), "bgm")
gameLoop:load()
renderer:load()
tlm:load()
obm:load()
tlm:loadmap("harriet_playzone")
camera.scale.x = 0.3
camera.scale.y = 0.3
obm:add(require("objects/player"):new(map.properties.spawn_x,map.properties.spawn_y))
end
local pop, push = table.remove,
table.insert
function love.update(dt)
push(delta_time,dt)
if #delta_time > sample then
local av = 0
local num = #delta_time
for i = #delta_time,1,-1 do
av = av + delta_time[i]
pop(delta_time,i)
end
av_dt = av / num
end
gameLoop:update(av_dt)
GAMETIME = GAMETIME + av_dt
end
function love.draw()
love.graphics.reset()
camera:set()
renderer:draw()
camera:unset()
love.graphics.setBackgroundColor(1, 1, 1, 1)
love.graphics.setColor(0, 0, 0, 1)
love.graphics.print("this is a test build, not the final game. a lot of things are expected to change, including the placeholder character.", 0, 0, 0, 1, 1)
end
<file_sep>/legacy/waskey.lua
love.keyboard.keysPressed = { }
love.keyboard.keysReleased = { }
-- returns if specified key was pressed since the last update
function love.keyboard.wasPressed(key)
if (love.keyboard.keysPressed[key]) then
return true
else
return false
end
end
-- returns if specified key was released since last update
function love.keyboard.wasReleased(key)
if (love.keyboard.keysReleased[key]) then
return true
else
return false
end
end
-- concatenate this to existing love.keypressed callback, if any
function love.keypressed(key, unicode)
love.keyboard.keysPressed[key] = true
end
-- concatenate this to existing love.keyreleased callback, if any
function love.keyreleased(key)
love.keyboard.keysReleased[key] = true
end
-- call in end of each love.update to reset lists of pressed\released keys
function love.keyboard.updateKeys()
love.keyboard.keysPressed = { }
love.keyboard.keysReleased = { }
end
<file_sep>/legacy/main.lua
-- Grid-based platformer game engine (and example)
-- by YellowAfterlife
-- version 1.0.5, 15/03/2012
-- Actually usable for any grid-based games
require 'trace'
require 'waskey'
require 'level'
require 'harriet'
require 'coin'
require 'block'
require 'stages'
-- block definitions:
blocks = {
brick = {
solid = true,
draw = block.draw,
graphic = block.graphic.brick},
dirt = {
solid = true,
draw = block.draw,
graphic = block.graphic.dirt},
grass = {
solid = true,
draw = block.draw,
graphic = block.graphic.grass},
lava = {
deadly = true,
graphic = block.graphic.lava,
update = block.anim16.update,
draw = block.anim16.draw,
frame = 0,
speed = 11.6},
door = {
win = true,
draw = block.drawOffset,
graphic = block.graphic.door,
ofsX = -4, ofsY = -4},
toggle1 = {
update = block.toggle.update,
timer = 0,
graphic = block.graphic.box2},
toggle2 = {
update = block.toggle.update,
timer = 1,
graphic = block.graphic.box},
}
-- rules for loading levels from string
level.rules = {
{ ' ' },
{ 'x', 0, blocks.brick },
{ 'd', 0, blocks.dirt },
{ 'g', 0, blocks.grass },
{ 'l', 0, blocks.lava },
{ 'w', 0, blocks.door },
{ 't', 0, blocks.toggle1 },
{ 'T', 0, blocks.toggle2 },
{ 'p', 1, harriet },
{ 'c', 1, coin }
}
function love.update(dt)
level.update(dt)
love.keyboard.updateKeys()
if love.keyboard.isDown("j") then
if love.keyboard.isDown("e") then
if love.keyboard.isDown("s") then
if love.keyboard.isDown("s") then
harriet.jumps = 999
harriet.graphic = love.graphics.newImage('jess.png')
love.window.setTitle("This Game Is About Jess")
end
end
end
end
end
function love.draw()
local w, h
w = level.width * level.gridw
h = level.height * level.gridh
--[[
race.print('TGIAH v1.0', trace.styles.green)
trace.print('Running on ' .. tostring(_VERSION), trace.styles.green)
trace.print('Jumps: ' .. tostring(harriet.jumps), trace.styles.blue)
trace.print('by Harry', trace.styles.yellow)
]]--
love.graphics.setColor(0, 255, 255, 255)
love.graphics.rectangle('fill', -3 - level.x, -3 - level.y, w + 6, h + 6)
love.graphics.printf(tostring(level.name), -level.x, -level.y + h + 4, w, 'center')
love.graphics.setColor(63, 63, 63, 255)
love.graphics.rectangle('fill', -2 - level.x, -2 - level.y, w + 4, h + 4)
love.graphics.setColor(255, 240, 127, 255)
love.graphics.printf(tostring(harriet.jumps), -level.x - 3, -level.y + h + 4, w + 6, 'left')
love.graphics.setColor(255, 127, 127, 255)
love.graphics.printf(tostring(deaths), -level.x - 3, -level.y + h + 4, w + 6, 'right')
level.draw()
trace.draw()
end
function love.load()
love.window.setTitle("This Game Is About Harriet")
score = 0
love.graphics.setBackgroundColor(0, 0, 0)
deaths = 0
level.current = 0
level.next()
end
<file_sep>/legacy/block.lua
block = { }
-- resources:
block.graphic = {
brick = love.graphics.newImage('brick.png'),
dirt = love.graphics.newImage('dirt.png'),
grass = love.graphics.newImage('grass.png'),
lava = love.graphics.newImage('lava.png'),
door = love.graphics.newImage('door.png'),
box = love.graphics.newImage('box.png'),
box2 = love.graphics.newImage('box2.png')
}
-- condition functions:
function block.solid(which) return which.solid end
function block.deadly(which) return which.deadly end
function block.win(which) return which.win end
-- default drawing behaviour:
function block.draw(x, y, block, ox, oy)
love.graphics.draw(block.graphic, x * level.gridw + ox, y * level.gridh + oy)
end
-- offset drawing behaviour:
function block.drawOffset(x, y, block, ox, oy)
love.graphics.draw(block.graphic,
x * level.gridw + ox + block.ofsX,
y * level.gridh + oy + block.ofsY)
end
-- 16-frame animated block:
block.anim16 = { }
function block.anim16.update(x, y, this, dt)
this.frame = (this.frame + this.speed * dt) % 16
end
function block.anim16.draw(x, y, this, ox, oy)
love.graphics.draw(this.graphic,
block.anim16.quad[math.floor(this.frame)],
x * level.gridw + ox, y * level.gridh + oy)
end
-- custom block functions:
block.toggle = { }
function block.toggle.update(x, y, this, dt)
this.timer = this.timer + dt
if (this.timer >= 1) then
this.timer = 0
if (this.draw) then
love.graphics.clear()
this.draw = nil
this.solid = false
else
this.draw = block.draw
this.solid = true
end
end
end
function block.init()
local i
-- generate animated block quads:
block.anim16.quad = { }
for i = 0, 15 do
block.anim16.quad[i] = love.graphics.newQuad(
(i % 4) * 32,
math.floor(i / 4) * 32,
32, 32, 128, 128)
end
end
block.init()
<file_sep>/legacy/level.lua
-- Level.lua
-- Engine for grid-based
-- Version: 1.0.2 15/03/2012
-- Author: YellowAfterlife
-- Licence: MIT License
--[[ Copyright (C) 2012 YellowAfterlife
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]]--
-- avoid double inclusion:
if (level) then return end
---- REFERENCES ----
require 'trace'
---- CONSTANTS ----
justabit = 0.001 -- used for collision calculations
---- CONSTRUCTOR ----
level = {
gridw = 32,
gridh = 32,
x = 0,
y = 0,
blocks = { }
}
---- METHODS ----
-- level.rectc(x1, y1, width1, height1, x2, y2, width2, height2)
-- Returns if given rectangles overlap
function level.rectc(x1, y1, w1, h1, x2, y2, w2, h2)
return not (y1+h1 <= y2 or y1 >= y2+h2 or x1+w1 <= x2 or x1 >= x2+w2)
end
-- level.meet(x, y, width, height, meta)
-- Returns instances of given kind 'meta' that overlap given rectangle
-- Instance type must have parameters x,y,width,height defining it's bounds
function level.meet(x, y, w, h, meta)
local idx, obj, rez
for idx, obj in ipairs(level.objects) do if (obj.meta == meta) then
if (level.rectc(obj.x, obj.y, obj.width, obj.height, x, y, w, h)) then
if (rez == nil) then rez = { } end
table.insert(rez, obj)
end
end end
return rez
end
-- level.check(x, y, width, height, checker)
-- Checks if at least one block overlapping given rect meets given requirement.
-- function checker must be defined as checker(obj), return boolean, and
-- work with object data provided.
function level.check(x, y, w, h, func)
local x1, y1, x2, y2, i, j, d
-- find region coordinates to check in:
x1 = math.floor(x / level.gridw)
y1 = math.floor(y / level.gridh)
x2 = math.floor((x + w - justabit) / level.gridw)
y2 = math.floor((y + h - justabit) / level.gridh)
for j = y1, y2 do for i = x1, x2 do
d = level.grid[j] -- find row
if (d ~= nil) then
d = d[i] -- find cell
if (d ~= nil) then
if (func(d)) then return true end -- test cell
end
end
end end
return false
end
-- level.add(x, y, objectType)
-- Creates a new object and adds it to the level
function level.add(x, y, object)
local obj, event
obj = { meta = object }
event = obj.meta.create
if (event) then event(obj, x, y) end
table.insert(level.objects, obj)
end
-- level.remove(object)
-- Removes an object from level
function level.remove(object)
local i, v, event
for i, v in ipairs(level.objects) do if (v == object) then
event = v.meta.destroy
if (event) then event(v) end
table.remove(level.objects, i)
return true
end end
return false
end
-- level.plot(x, y, block)
-- Changes block at given coordinates
function level.plot(x, y, what)
local i, v, obj
obj = { }
for i, v in pairs(what) do obj[i] = v end
-- call destroy event for old block:
v = level.grid[y][x]
if (v) then
i = v.destroy
if (i) then i(x, y, v) end
end
-- replace block:
level.grid[y][x] = obj
-- call creation event for new block:
i = obj.create
if (i) then i(x, y, obj) end
end
-- level.load(data, width, height[, name])
-- Loads level from given string.
-- width, height are dimensions of level in blocks.
function level.load(data, width, height, name)
local x, y, pos, char
local blockIndex, block, blockType
local idx, val, obj
level.width = width
level.height = height
love.window.setMode(level.width * 50, level.height * 50)
level.clear()
pos = 0
for y = 0, height-1 do for x = 0, width-1 do
pos = pos + 1; char = string.sub(data, pos, pos)
for blockIndex, block in pairs(level.rules) do if (block[1] == char) then
blockType = block[2]
if (blockType == nil) then -- blank\air
break
elseif (blockType == 0) then -- block
level.plot(x, y, block[3])
elseif (blockType == 1) then -- object
level.add(x * level.gridw, y * level.gridh, block[3])
else -- unsupported entity type
trace.print('Unsupported type: ' .. tostring(rt), trace.styles.red)
end
break
end end
end end
if (name) then level.name = tostring(name) else level.name = '' end
level.updated = false
end
-- level.clear()
-- Removes everything from level, updating object list and grid to current size.
function level.clear()
local x, y, l, c
-- clear grid:
level.grid = { }
for y = 0, level.height-1 do
l = { }; level.grid[y] = l
for x = 0, level.width-1 do
l[x] = { }
end
end
-- clear object list:
level.objects = { }
end
-- level.update(delta)
-- Updates the level.
-- delta is elapsed time, as passed to love.update
function level.update(dt)
local x, y, block, event, idx, obj
level.updated = true
for y = 0, level.height-1 do for x = 0, level.width-1 do
block = level.grid[y][x]
event = block.update
if (event) then
event(x, y, block, dt)
end
end end
for idx, obj in ipairs(level.objects) do
event = obj.meta.update
if (event) then event(obj, dt) end
end
end
-- level.draw()
-- Draws the level.
-- Normally to be called in love.render,
-- after background drawing and before UI
function level.draw()
local x, y, block, event, idx, obj, ox, oy
if (not level.updated) then level.update(0) end
ox = -level.x
oy = -level.y
love.graphics.setColor(255, 255, 255, 255)
-- execute draw events for blocks:
for y = 0, level.height-1 do for x = 0, level.width-1 do
block = level.grid[y][x]
event = block.draw
if (event) then event(x, y, block, ox, oy) end
end end
-- execute draw events for objects:
for idx, obj in ipairs(level.objects) do
event = obj.meta.draw
if (event) then event(obj, ox, oy) end
end
end
<file_sep>/conf.lua
function love.conf(t)
t.identity = "TGIAH"
t.window.title = "this game is about harriet | TERM2 BUILD #3"
t.window.width = 1200
t.window.height = 700
t.console = true
end
<file_sep>/legacy/stages.lua
-- stages.lua
-- Contains a function to look-up next level in list.
-- Also contains all levels.
function level.next()
local d
level.current = level.current + 1
d = level.levels[level.current]
if (d == nil) then
level.width = 4
level.height = 4
level.name = 'Well done.'
level.clear()
trace.print('Congratulations! You\'ve completed the game!', trace.styles.green)
else
level.load(d[4], d[1], d[2], d[3])
end
end
-- level definitions:
level.levels = {
{ 11, 6, 'Hello, Harriet!',
' '..
' '..
' '..
' p c w '..
'ggg xxx'..
'dddgggggxxx'},
{ 11, 11, "Don't fall",
' '..
' '..
' w '..
'xxxxx '..
' x x g '..
' x c '..
' cgg'..
' p c d '..
' ggggg dd '..
' ddd '..
' d '},
{ 9, 13, 'Jittery chunks',
' '..
'w '..
'gg '..
'dd c '..
'd g '..
' c'..
' g'..
' c '..
' c g c '..
' g c d g '..
' dpg d d '..
'gdgdgdgdg'..
'ddddddddd'},
{ 15, 7, 'Doors',
' xxx '..
' xxx '..
' xxx '..
' xxx w'..
' p T t gg'..
'gggg T t gdd'..
'ddddggxxxxxgddd'},
{ 11, 5, "Lava is hot, but you're hotter~",
'x '..
'xp c w'..
'xxx c d xxx'..
'xxxxllddxxx'..
'xxxxxddxxxx'},
{ 11, 9, 'Madhouse',
'xxxxxxxxxxx'..
'xp c x c x'..
'xxxxtxTxxtx'..
'x cT xc x x'..
'xtxxxxxtxTx'..
'x T t T x x'..
'xxxxxxxxxtx'..
'xw cT t T x'..
'xxxxxxxxxxx'},
{ 17, 8, 'Lava pool',
' '..
' c '..
' c '..
' x c '..
' c x x T '..
'p x x x t w'..
'glllllllllllllllg'..
'dllllllllllllllld'},
{ 7, 13, 'Challenge!',
' '..
' c '..
' gggg '..
' gdld '..
'c l g'..
'g lcgd'..
' cl dd'..
'c gl d'..
'g l c '..
' cl x '..
'p gl w'..
'g l g'..
'dllllld' },
{ 11, 6, 'Time it right',
' '..
' w '..
' TTT T '..
' p t '..
'ggg ttt xxx'..
'dddgggggxxx'},
{ 11, 7, 'Underground Ventures',
' '..
' '..
' '..
' p '..
'gggtttttggg'..
'ddc c c wd'..
'dddgggggddd'},
nil
}
<file_sep>/objects/player.lua
Player = {}
require "tools/camera"
require "tools/physics_helper"
require "world_physics/world_physics"
local rect = require "objects/rect"
local floor = math.floor
local tiles = tlm.tiles[3]
local quad = love.graphics.newQuad
local anim_data = {
quad(0,0,74,148,1280,148),
quad(75,0,74,148,1280,148),
quad(75*2,0,74,148,1280,148),
quad(75*3,0,74,148,1280,148),
quad(75*4,0,74,148,1280,148),
}
local image = love.graphics.newImage("assets/images/harriet.png")
image:setFilter("nearest","nearest")
function Player:new(x,y)
--x,y,w,h,img,quad,id
local player = require("objects/entity"):new(x,y,8,16,nil,nil,"harriet")
function player:load()
gameLoop:addLoop(self)
renderer:addRenderer(self)
init_physics(self,500)
-- rem
self.animation = require("tools/animation"):new(
image,
{
{ -- idle
anim_data[1]
},
{ -- walk right
anim_data[2],
anim_data[3]
},
{ -- walk left
anim_data[4],
anim_data[5]
},
},
0.2
)
self.animation:play()
-- end rem
end
local key = love.keyboard.isDown
function player:die(type)
player.pos.x = 80
player.pos.y = 95
self.vel.x = 0
self.vel.y = 0
end
function player:tick(dt)
camera:goto_point(self.pos)
self.animation:set_animation(1)
-- apply gravity
apply_gravity(self,dt)
if key("r") then
player:die()
end
if key("lctrl") then
self.vel.y = 10
end
if key("i") then
self.on_ground = true
end
if key("left") then
self.animation:set_animation(3)
self.dir.x = -1
if key("lshift") then
self.vel.x = 300
elseif key("lctrl") then
self.vel.x = 50
self.vel.y = 10
else
self.vel.x = 200
end
end
if key("right") then
self.animation:set_animation(2)
self.dir.x = 1
if key("lshift") then
self.vel.x = 300
elseif key("lctrl") then
self.vel.x = 50
self.vel.y = 10
else
self.vel.x = 200
end
end
-- collisions
update_physics(self,tiles,dt)
--
if key("up") then
physics_jump(self)
end
self.pos.x = self.pos.x + (self.vel.x * dt) * self.dir.x
self.pos.y = self.pos.y + (self.vel.y * dt) * self.dir.y
self.vel.x = self.vel.x * (1-dt*12)
self.animation:update(dt)
end
function player:draw()
self.animation:draw({self.pos.x,self.pos.y},0,0.11,0.11)
--love.graphics.rectangle("fill",self.pos.x,self.pos.y,self.size.x,self.size.y)
end
return player
end
return Player
<file_sep>/README.md
# This Gane is About Harriet
A 2D platformer about a girl named Harriet.
<file_sep>/legacy/harriet.lua
require "coin"
harriet = {
jumps = 3,
graphic = love.graphics.newImage('harriet.png')
}
function harriet.create(this, px, py)
-- dimensions:
this.x = px + 6
this.y = py + 6
this.width = 20
this.height = 20
-- original position:
this.xstart = this.x
this.ystart = this.y
-- movement:
this.vspeed = 0
this.gravity = 600
this.jump = 350
this.walk = 200
end
function harriet.update(this, dt)
local i, j, k, m, stuck
-- detect if stuck in a solid, thus should not move
stuck = level.check(this.x, this.y, this.width, this.height, block.solid)
-- horizontal speed:
this.hspeed = 0
if (love.keyboard.isDown('right')) then this.hspeed = this.walk end
if (love.keyboard.isDown('left')) then this.hspeed = -this.walk end
-- vertical speed:
if (level.check(this.x, this.y + 1, this.width, this.height, block.solid)) then
if (love.keyboard.isDown('up') and harriet.jumps > 0) then
this.vspeed = -this.jump
harriet.jumps = harriet.jumps - 1
end
else -- in air
this.vspeed = this.vspeed + this.gravity * dt
end
-- horizontal movement:
if (not stuck and this.hspeed ~= 0) then
m = level.gridw
i = math.abs(this.hspeed) * dt
if this.hspeed > 0 then k = 1 else k = -1 end
while (i > 0) do
if (i < m) then j = i else j = m end
if (not level.check(this.x + k * j, this.y, this.width, this.height, block.solid)) then
this.x = this.x + k * j
else
if k > 0 then
this.x = math.floor((this.x + this.width + j) / m) * m - this.width
else
this.x = math.floor(this.x / m) * m
end
this.hspeed = 0
break
end
i = i - m
end
end
-- vertical movement:
if (not stuck and this.vspeed ~= 0) then
m = level.gridh
i = math.abs(this.vspeed) * dt
if this.vspeed > 0 then k = 1 else k = -1 end
while (i > 0) do
if (i < m) then j = i else j = m end
if (not level.check(this.x, this.y + k * j, this.width, this.height, block.solid)) then
this.y = this.y + k * j
else
if k > 0 then
this.y = math.floor((this.y + this.height + j) / m) * m - this.height
else
this.y = math.floor(this.y / m) * m
end
this.vspeed = 0
break
end
i = i - m
end
end
-- death:
if (love.keyboard.wasPressed('r')
or stuck
or (level.check(this.x, this.y, this.width, this.height, block.deadly))
or (this.y > level.height * level.gridh - this.height)
) then -- reset to start position:
deaths = deaths + 1
harriet.jumps = 3
score = score - 50
level.add(this.x, this.y, harrieteff)
this.x = this.xstart
this.y = this.ystart
end
-- get coins:
m = level.meet(this.x, this.y, this.width, this.height, coin)
if (m) then for i, k in ipairs(m) do
score = score + 1
harriet.jumps = harriet.jumps + 1
level.remove(k)
end end
-- got to exit:
if (level.check(this.x, this.y, this.width, this.height, block.win)) then
level.next()
end
-- limit position:
k = level.width * level.gridw
m = level.height * level.gridh
if (this.y < 0) then this.y = 0 end
if (this.x < 0) then this.x = 0 end
if (this.x > k - this.width) then this.x = k - this.width end
-- snap camera:
i = love.graphics.getWidth()
j = love.graphics.getHeight()
if (k < i) then
level.x = (k - i) / 2
else
level.x = math.min(0, math.max(k - i, this.x + (this.width - i) / 2))
end
if (m < j) then
level.y = (m - j) / 2
else
level.x = math.min(0, math.max(m - j + 20, this.y + (this.height - j) / 2))
end
end
function harriet.draw(this, ox, oy)
love.graphics.draw(harriet.graphic, this.x + ox, this.y + oy)
end
-- harriet death effect:
harrieteff = {
graphic = love.graphics.newImage('harriet-eff.png')
}
function harrieteff.create(this, px, py)
this.x = px - 6
this.y = py - 6
this.frame = 0
this.speed = 48
this.graphic = harrieteff.graphic
end
function harrieteff.update(this, dt)
this.frame = this.frame + dt * this.speed
if (this.frame >= 16) then
level.remove(this)
end
end
function harrieteff.draw(this, ox, oy)
-- utilize animated block drawing function for object:
block.anim16.draw(this.x / level.gridw, this.y / level.gridh, this, ox, oy)
end
|
38aaf2d2553e0713e3feef0cf74784aa4159d2a0
|
[
"Markdown",
"Lua"
] | 11
|
Lua
|
haileylgbt/tgiah
|
efe2296407f56ec91ceb37c89bd3021dda2b7579
|
9fd60d137f36262023d47486ca0def375a862986
|
refs/heads/master
|
<file_sep>def create_an_empty_array
[]
end
def create_an_array
new_array = ["poop","boop","hoop","woop"]
end
def add_element_to_end_of_array(array, element)
new_array<< "zoop"
end
def add_element_to_start_of_array(array, element)
new_array.unshift("goop")
end
def remove_element_from_end_of_array(array)
zoop = new_array.pop("zoop")
zoop
end
def remove_element_from_start_of_array(array)
goop = new_array.unshift("goop")
goop
end
def retrieve_element_from_index(array, index_number)
new_array[2]
end
def retrieve_first_element_from_array(array)
new_array[0]
end
def retrieve_last_element_from_array(array)
new_array[3]
end
def update_element_from_index(array, index_number, element)
new_array[1]= "joop"
end
add_element_to_end_of_array
add_element_to_start_of_array
remove_element_from_end_of_array
remove_element_from_start_of_array
retrieve_last_element_from_array
retrieve_element_from_index
retrieve_first_element_from_array
update_element_from_index
|
81adf2a48f24f74934ca8335a1f209cd0e27d481
|
[
"Ruby"
] | 1
|
Ruby
|
prichard191/programming-univbasics-4-crud-lab-dumbo-web-111819
|
7e00f8c601f8943dfbea724298952020ca4d97b6
|
eca71fa6bc43a65bc10e0d922260a576d9547ac1
|
refs/heads/master
|
<file_sep>'use strict';
// APP BOOTSTRAPPING
(function() {
module.exports = function(options) {
// LOGGER CONFIGURATION
var $log = require('./utils/log.js');
// UTILITIES
var _ = require('lodash');
// DEFAULTS
var _defaults = {};
// OVERRIDES
options = _.extend({}, _defaults, options);
// PRIVATE VARIABLES
var _io = options.io;
// CONFIGURATION
var _configuration = require('./config.json');
return {
init() {
// BOOTSTRAP SOCKET COMMUNICATION MODULE
var socketCommunication = require('./modules/socket-communication/core')(_io, {
config: _configuration
});
// INITIALIZE SOCKET COMMUNICATION MODULE
socketCommunication.init();
// BOOTSTRAP CHAT MODULE
var chatManager = require('./modules/chat-manager/core')({
config: _configuration,
socketCommunication
});
// INIT CHAT MODULE
chatManager.init();
$log.log('info', 'APPLICATION STARTED...');
}
};
};
})();<file_sep>'use strict';
(function(module) {
module.exports = function(overrides) {
// UTILITIES
var _ = require('lodash');
// DEFAULTS
var _defaults = {
config: require('../../config'),
queueManager: eventQueueManager()
};
// OVERRIDES
var _options = _.extend({}, _defaults, overrides || {});
var _config = _options.config;
var _queueManager = _options.queueManager;
// DISPATCHER INSTANCE
var dispatcher = {};
// PUBLIC METHODS
// MODULE INITIALIZATION
dispatcher.init = function() {
Object.keys(_config.EVENTS).forEach(function(eventGroup) {
_queueManager.addEvents(_config.EVENTS[eventGroup]);
});
};
// REGISTER EVENTS
dispatcher.register = function(event, callback) {
_queueManager.register(event, callback);
};
// TRIGGER EVENTS
dispatcher.trigger = function(event, transmission) {
_queueManager.trigger(event, transmission);
};
return dispatcher;
};
// MAINTENANCE OF EVENTS & CALLBACKS
var eventQueueManager = function() {
// EVENT QUEUE : used to maintain event queue
var eventQueue = {};
// PRIVATE METHODS & OBJECTS
var _internal = {};
_internal.addEvent = function(event) {
// REGISTER EVENT
eventQueue[event] = eventQueue[event] || [];
};
var factObj = {};
// PUBLIC METHODS
// ADD EVENTS
factObj.addEvents = function(eventCategory) {
Object.keys(eventCategory).forEach(function(evt) {
_internal.addEvent(eventCategory[evt]);
});
};
// REGISTER CALLBACKS TO EVENTS
factObj.register = function(event, callback) {
_internal.addEvent(event);
eventQueue[event].push(callback);
};
// TRIGGER EVENT
factObj.trigger = function(event, transmission) {
eventQueue[event].forEach(function(callback) {
callback(transmission);
});
};
return factObj;
};
})(module);
<file_sep>'use strict';
(function() {
angular.module('ttt.modules.game.api', [])
})();<file_sep>'use strict';
(function(module) {
module.exports = function(options) {
// UTILITY
var _ = require('lodash');
// DEFAULTS
var _defaults = {
config: require('../../config')
};
// OVERRIDES
options = _.extend({}, _defaults, options);
// PRIVATE VARIABLES
var _socketComm = options.socketCommunication;
var _config = options.config;
// INTERNAL METHOD TRIGGERS
var _internal = {
sendMessage: function(transmission) {
_socketComm.transmitter(_config.EVENTS.CHAT.RECEIVE, {
to: transmission.meta.to,
from: transmission.meta.from
}, transmission.payload);
},
typing: function(transmission) {
_socketComm.transmitter(_config.EVENTS.CHAT.RECEIVE, {
to: transmission.meta.to,
from: transmission.meta.from
}, {
user: transmission.meta.from,
});
},
userJoined: function(transmission) {
_socketComm.broadcast(_config.EVENTS.CHAT.USER_JOINED, {
to: transmission.meta.to,
from: transmission.meta.from
}, {
user: transmission.meta.from,
});
},
userLeft: function(transmission) {
_socketComm.broadcast(_config.EVENTS.CHAT.USER_LEFT, {
to: transmission.meta.to,
from: transmission.meta.from
}, {
user: transmission.meta.from,
});
}
};
return {
init() {
_socketComm.receiver(_config.EVENTS.CHAT.SEND, _internal.sendMessage);
_socketComm.receiver(_config.EVENTS.CHAT.TYPING, _internal.typing);
_socketComm.receiver(_config.EVENTS.CHAT.USER_JOINED, _internal.userJoined);
_socketComm.receiver(_config.EVENTS.CHAT.USER_LEFT, _internal.userLeft);
}
};
};
})(module);<file_sep>'use strict';
(function() {
angular.module('ttt', [
// 3rd Party dependencies
'ui.router',
'ui.bootstrap',
//Custom Code :
'ttt.modules',
'ttt.pages'
])
// Routing
.config(function($urlRouterProvider, $stateProvider) {
// State for login
$stateProvider.state('login', {
url: '/login',
controller: 'LoginController',
templateUrl: 'assets/views/pages/login/login.html'
});
// Main Page of application
$stateProvider
.state('main', {
controller: 'PlayController',
controllerAs: '$ctrl',
url: '/',
templateUrl: 'assets/views/pages/play/main.html',
})
.state('main.play', {
url: 'play',
views: {
//list of Players
players: {
controller: 'PlayersController',
controllerAs: '$ctrl',
templateUrl: 'assets/views/pages/play/players.html'
},
game: {
controller: 'GameController',
controllerAs: '$ctrl',
templateUrl: 'assets/views/pages/play/game.html',
}
}
});
$urlRouterProvider
.otherwise('/login');
})
})();
<file_sep>'use strict';
(function() {
angular.module('ttt.modules.game', [
'ttt.modules.game.gameCoordinator',
'ttt.modules.game.api'
])
.constant('EVENTS', {
CONNECTION: {
CONNECT: 'connection',
DISCONNECT: 'disconnect',
},
USER: {
INIT: 'USER_INITIALIZE'
},
GAME: {
SEND: 'CHAT_SEND',
RECEIVE: 'CHAT_RECEIVE',
TYPING: 'CHAT_TYPING',
USER_JOINED: 'CHAT_USER_JOINED',
USER_LEFT: 'CHAT_USER_LEFT',
}
})
})();<file_sep>(function(env) {
const lodash = require('lodash');
const express = require('express');
const path = require('path');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
// CONFIGURATIONS
process.env = lodash.extend({}, process.env, env);
// ROUTES
// DEPENDENCIES
app.use('/bower_components', express.static(path.join(__dirname + '/bower_components')));
app.use('/node_modules', express.static(path.join(__dirname + '/node_modules')));
// APPLICATION ROUTE
app.use('/app', express.static(path.join(__dirname + '/app')));
// FRONT END ROUTE
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + process.env.FRONT_END));
});
// BOOTSTRAPING APPLICATION
var serverApplication = require('./app/server/app')({io});
serverApplication.init();
// START SERVER
server.listen(process.env.PORT, function() {
console.log('CHAT SERVER ONLINE ON...', process.env.PORT);
});
})(require(__dirname + '/.tmp/config.json'));<file_sep>'use strict';
(function(module) {
module.exports = require('winston');
})(module);<file_sep>'use strict';
(function(module) {
module.exports = function(io, overrides) {
// LOGGER
const $log = require('winston');
// UTILITIES
var _ = require('lodash');
// DEFAULTS
var _defaults = {
userManager: require('./user-manager')(),
dispatcher: require('./dispatcher')({
config: require('../../config')
}),
config: require('../../config')
};
// OVERRIDES
var options = _.extend({}, _defaults, overrides || {});
// PRIVATE INSTANCES
var _userManger = options.userManager;
var _dispatcher = options.dispatcher;
var _config = options.config;
var _decorators = {};
// INITIALIZE DISPATCHER
_dispatcher.init();
// INITIALIZE DECORATORS
_decorators = {
// OUTPUT PAYLOAD DECORATOR
payloadDecorator(event, meta, payload) {
return _.extend({
meta: {
event: event,
from: meta.from,
to: meta.to
}
}, {payload});
},
// SOCKET EVENT ENGINE DECORATOR
socketDecorator(socket) {
Object.keys(_config.EVENTS).forEach(function(eventGroup) {
Object.keys(_config.EVENTS[eventGroup]).forEach(function(event) {
socket.on(_config.EVENTS[eventGroup][event], function(transmission) {
var eventName = _config.EVENTS[eventGroup][event];
$log.log('info', 'EVENT TRIGGERED', eventName, transmission);
_dispatcher.trigger(eventName, transmission);
});
});
});
}
};
// COMMUNICATION CORE
var communicationMod = {};
// INITIALIZE MODULE
communicationMod.init = function() {
// SOCKET IO CONFIG
io.on(_config.EVENTS.CONNECTION.CONNECT, function(socket) {
$log.log('info', 'CONNECTION INITIATED', socket.id);
// INITIAL USER INITIALIZATION
socket.on(_config.EVENTS.USER.INIT, function(transmission) {
// REGISTER USER
_userManger.register(transmission, socket);
$log.log('info', 'USER CONNECTED:::', transmission);
// EVENT ENGINE DECORATOR
_decorators.socketDecorator(socket);
});
// USER DISCONNECTION
socket.on(_config.EVENTS.CONNECTION.DISCONNECT, function() {
// REMOVE USER FROM REGISTRY
_userManger.removeUser(socket.id);
$log.log('info', 'USER DISCONNECTED', socket.id);
});
});
};
// PUBLIC METHODS
// TRANSMIT EVENT
communicationMod.transmitter = function(event, meta, payload) {
var user = _userManger.getUser(meta.to);
if (user) {
user.socket.emit(event, _decorators.payloadDecorator(event, meta, payload));
return true;
}
else {
return false;
}
};
// RECEIVES EVENTS
communicationMod.receiver = function(event, callback) {
_dispatcher.register(event, callback);
};
// BROADCAST EVENT OVER CONTACT LIST
communicationMod.broadcast = function(event, meta, payload) {
var user = _userManger.getUser(meta.from);
(user.contactList || []).forEach(function(contact) {
communicationMod.transmitter(event, _.extend({}, meta, {to: contact}, payload));
});
};
return communicationMod;
};
})(module);
<file_sep>'use strict';
(function() {
angular.module('ttt.pages.play', [
'ttt.modules.game'
])
.controller('PlayController', function() {
})
.controller('GameController', function(gameCoordinator) {
})
.controller('PlayersController', function(gameCoordinator) {
var $ctrl = this;
//list of Players
$ctrl.players = [];
gameCoordinator.game.getPlayers().then(function(players) {
$ctrl.players = players;
});
$ctrl.challenge = function(challenged) {
console.log(challenged + ' Has been challenged');
}
})
.component('playerList', {
templateUrl: '../../assets/views/pages/play/player-list.html',
controller: function() {
console.log('here');
},
bindings: {
players: '<',
onChallenge: '&'
}
});
})();
<file_sep>'use strict';
(function() {
angular.module('ttt.pages', [
'ttt.pages.login',
'ttt.pages.play'
]);
})();
<file_sep>#CHAT SERVER"# jonas-tic-tac-toe"
<file_sep>/* eslint-env node */
'use strict';
(function() {
module.exports = function(grunt) {
// Load grunt tasks automatically
require('load-grunt-tasks')(grunt);
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// setup environment configuration
var environment = null;
if (grunt.file.exists('env.json')) {
environment = grunt.file.readJSON('env.json');
}
// Define the configuration for all the tasks
grunt.initConfig({
eslint: {
src: {
src: 'app/',
options: {
configFile: '.eslintrc'
}
}
},
execute: {
target: {
src: ['index.js']
}
},
json_generator: {
development: {
dest: '.tmp/config.json',
options: environment.development
},
production: {
dest: '.tmp/config.json',
options: environment.production
}
}
});
grunt.registerTask('jscodestyle', [
'eslint:src'
]);
grunt.registerTask('config', function() {
var configTask = 'json_generator:development';
if (grunt.option('production')) {
configTask = 'json_generator:production';
}
grunt.task.run([configTask]);
});
};
})();<file_sep>'use strict';
(function() {
angular
.module('ttt.modules.socket')
.factory('dispatcher', function(eventQueueManager) {
return function(configuration, socket) {
// DISPATCHER INSTANCE
var dispatcher = {};
// OVERRIDES
var _config = configuration;
var _queueManager = eventQueueManager();
// EVENT REGISTRATION
Object.keys(_config.EVENTS).forEach(function(eventGroup) {
_queueManager.addEvents(_config.EVENTS[eventGroup]);
});
// PUBLIC METHODS
// REGISTER EVENTS
dispatcher.register = function(event, callback) {
_queueManager.register(event, callback);
};
// TRIGGER EVENTS
dispatcher.trigger = function(event, transmission) {
_queueManager.trigger(event, transmission);
};
return dispatcher;
};
})
.factory('eventQueueManager', function() {
return function() {
// EVENT QUEUE : used to maintain event queue
var eventQueue = {};
// PRIVATE METHODS & OBJECTS
var _internal = {};
_internal.addEvent = function(event) {
// REGISTER EVENT
eventQueue[event] = eventQueue[event] || [];
};
var factObj = {};
// PUBLIC METHODS
// ADD EVENTS
factObj.addEvents = function(eventCategory) {
Object.keys(eventCategory).forEach(function(evt) {
_internal.addEvent(eventCategory[evt]);
});
};
// REGISTER CALLBACKS TO EVENTS
factObj.register = function(event, callback) {
_internal.addEvent(event);
eventQueue[event].push(callback);
};
// TRIGGER EVENT
factObj.trigger = function(event, transmission) {
eventQueue[event].forEach(function(callback) {
callback(transmission);
});
};
return factObj;
};
});
})();
<file_sep>'use strict';
(function() {
angular.module('ttt.modules.game.gameCoordinator', [])
.factory('gameCoordinator', function(socket, EVENTS, $q) {
var _internal = {
isInit: false,
profile: null,
events: null
};
return {
init: function(config) {
_internal.profile = {loginName: config.loginName};
_internal.events = EVENTS;
_internal.isInit = true;
socket.init({EVENTS: _internal.events}, _internal.profile.loginName, _internal.profile);
},
game: {
getPlayers: function() {
return $q.when(['Tom', 'Dick', 'Harry']);
}
}
}
});
})();<file_sep>'use strict';
(function() {
angular.module('ttt.modules', [
'ttt.modules.socket',
'ttt.modules.game'
]);
})();
<file_sep>'use strict';
/*
USER DATA FORMAT
ID : {
id: <user ID>,
socketId: <socket ID> ,
socket : <socket>,
profile: <user profile>
}
*/
(function(module) {
module.exports = function() {
// FACTORY
var factObj = {};
// USER REPOSITORY
var userRepository = {};
// REGISTER NEW USER
factObj.register = function(transmission, socket) {
userRepository[transmission.meta.from] = {
id: transmission.meta.from,
socketId: socket.id,
socket,
profile: transmission.profile
};
};
// GET USER BASED ON ID
factObj.getUser = function(id) {
return userRepository[id];
};
// REOMVE USER
// @todo: add custom code to delete user based on socket.id
factObj.removeUser = function(id) {
delete userRepository[id];
};
return factObj;
};
})(module);
|
9074d471389df9fa9f294586d88a576156495bc1
|
[
"JavaScript",
"Markdown"
] | 17
|
JavaScript
|
jonathandsouza/jonas-tic-tac-toe
|
073b8489467b1981f2056a2ebeca888045dc0e70
|
c8ba3b98839197b884bcf9fb480689e0d48dd41f
|
refs/heads/master
|
<repo_name>maikimolahlehi/BusReservationApi<file_sep>/BusReservationApi/DB/TicketDAO.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BusReservationApi.DB
{
public class TicketDAO
{
}
}
<file_sep>/BusReservationApi/Controllers/DriverController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using BusReservationApi.DB;
using BusReservationApi.Model;
using BusReservationApi.Service;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace BusReservationApi.Controllers
{
[Route("api/[controller]")]
public class DriverController : Controller
{
DriverService driverService = new DriverService();
// GET: api/<controller>
[HttpGet("all")]
public IEnumerable<Driver> GetAllDrivers()
{
return driverService.GetAllDrivers();
}
[HttpGet("{id}")]
public Driver GetDriver(int id)
{
return driverService.GetDriver(id);
}
// POST api/<controller>
[HttpPost("{id}")]
public Driver Post([FromBody]Driver value)
{
return driverService.createDriver(value);
}
// PUT api/<controller>/5
[HttpPut("{id}")]
public Driver Put(int id, [FromBody]Driver value)
{
return driverService.updateDriver(value);
}
// DELETE api/<controller>/5
[HttpDelete("{id}")]
public bool Delete(int id)
{
return driverService.deleteDriver(id);
}
}
}
<file_sep>/BusReservationApi/Service/TripService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BusReservationApi.Model;
using BusReservationApi.DB;
namespace BusReservationApi.Service
{
public class TripService
{
TripDAO TripDAO = new TripDAO();
<<<<<<< HEAD
=======
//Ready for TicketDAO implementation
>>>>>>> 5e82449416c0eec05f715f141ebac4722f04ae47
public TripService()
{
}
public IEnumerable<Trip> GetAllTrip()
{
try
{
return TripDAO.Get();
}catch (Exception e)
{
throw new Exception(e.Message);
}
}
public Trip GetTrip(int id)
{
return TripDAO.Get(id);
}
public Trip CreateTrip(Trip trip)
{
return TripDAO.Create(trip);
}
public Trip UpdateTrip(Trip trip)
{
return TripDAO.Update(trip);
}
public bool DeleteTrip(int id)
{
return TripDAO.Delete(id);
}
}
}
<file_sep>/BusReservationApi/DB/CustomerDAO.cs
using BusReservationApi.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MySql.Data;
using MySql.Data.MySqlClient;
namespace BusReservationApi.DB
{
public class CustomerDAO
{
private DB db;
public CustomerDAO()
{
db = new DB();
}
public Customer CreateCustomer(Customer customer)
{
Customer new_customer = new Customer();
string query = string.Format("INSERT INTO customer {0}", GenerateInsertString(customer));
MySqlDataReader mySqlDataReader = (MySqlDataReader) db.Query(query, "customer");
new_customer = SetCustomers(mySqlDataReader)[0];
return new_customer;
}
public Customer Get(int id)
{
Customer customer = new Customer();
string query = string.Format("SELECT * FROM customer WHERE id = {0}", id.ToString());
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "customer");
if (mySqlDataReader != null)
{
if (mySqlDataReader.HasRows)
{
customer = SetCustomers(mySqlDataReader)[0];
}
}
return null;
}
public List<Customer> Get()
{
string query = string.Format("SELECT * FROM customer");
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "customer");
return SetCustomers(mySqlDataReader);
}
public bool Delete(int id)
{
string query = string.Format("DELETE FROM customer WHERE id = ", id.ToString());
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "customer");
if (mySqlDataReader == null)
{
return true;
}
return false;
}
public bool Delete(Customer customer)
{
string query = string.Format("DELETE FROM customer WHERE id = ", customer.Id.ToString());
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "customer");
if (mySqlDataReader == null)
{
return true;
}
return false;
}
public Customer Update(Customer customer)
{
Customer updatedCustomer = new Customer();
string query = string.Format("UPDATE customer ", GenerateUpdateString(customer));
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "customer");
mySqlDataReader.Close();
updatedCustomer = Get(int.Parse(customer.Id));
return updatedCustomer;
}
private List<Customer> SetCustomers(MySqlDataReader mySqlDataReader)
{
List<Customer> customers = new List<Customer>();
while(mySqlDataReader.Read())
{
Customer customer = new Customer
{
Id = mySqlDataReader.GetInt32(0).ToString(),
Name = mySqlDataReader.GetString(1).ToString(),
Surname = mySqlDataReader.GetString(2).ToString(),
Next_of_kin = mySqlDataReader.GetString(4).ToString(),
Next_of_kin_number = mySqlDataReader.GetString(5).ToString(),
Phone = mySqlDataReader.GetString(3).ToString()
};
customers.Add(customer);
}
mySqlDataReader.Close();
return customers;
}
private string GenerateInsertString(Customer customer)
{
return string.Format("(name,surname,phone,next_of_kin_name,next_of_kin_number) VALUES('{0}', '{1}','{2}','{3}','{4}')", customer.Name, customer.Surname, customer.Phone, customer.Next_of_kin, customer.Next_of_kin_number);
}
private string GenerateUpdateString(Customer customer)
{
return string.Format("SET name = '{0}',surname = '{1}',phone = '{2}',next_of_kin_name = '{3}',next_of_kin_number = '{4}' WHERE id = {5}", customer.Name, customer.Surname, customer.Phone, customer.Next_of_kin, customer.Next_of_kin_number, customer.Id);
}
}
}
<file_sep>/BusReservationApi/Service/BusService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BusReservationApi.DB;
using BusReservationApi.Model;
namespace BusReservationApi.Service
{
public class BusService
{
BusDAO busDAO = new BusDAO();
public BusService()
{
}
public IEnumerable<Bus> GetAllBusses()
{
return busDAO.Get();
}
public Bus GetBus(int id)
{
return busDAO.Get(id);
}
public Bus CreateBus(Bus bus)
{
return busDAO.Create(bus);
}
public Bus UpdateBus(Bus bus)
{
return busDAO.Update(bus);
}
public bool DeleteBus(int id)
{
return busDAO.Delete(id);
}
}
}
<file_sep>/BusReservationApi/Model/Trip.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BusReservationApi.Model
{
public class Trip
{
public string Id { get; set; }
public Bus Bus { get; set; }
public DateTime Date { get; set; }
public DateTime Depature_time { get; set; }
public DateTime Arrival_time { get; set; }
public string Starting_point { get; set; }
public string Destination { get; set; }
public Driver Driver { get; set; }
public float Price { get; set; }
}
}
<file_sep>/BusReservationApi/Service/RentalService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BusReservationApi.Model;
using BusReservationApi.DB;
namespace BusReservationApi.Service
{
public class RentalService
{
RentalDAO rentalDAO = new RentalDAO();
public RentalService()
{
}
public IEnumerable<Rental> GetAllRentals()
{
return rentalDAO.Get();
}
public Rental GetRental(int id)
{
return rentalDAO.Get(id);
}
public Rental CreateRental(Rental rental)
{
return rentalDAO.CreateRental(rental);
}
public Rental UpdateRental(Rental rental)
{
return rentalDAO.Update(rental);
}
public bool DeleteRental(int id)
{
return rentalDAO.Delete(id);
}
}
}
<file_sep>/BusReservationApi/Controllers/CustomerController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using BusReservationApi.Service;
using BusReservationApi.Model;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace BusReservationApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CustomerController : Controller
{
CustomerService customerService=new CustomerService();
[HttpGet("all")]
public IEnumerable<Customer> GetAllCustomers()
{
return customerService.getAllCustomers();
}
// GET api/<controller>/5
[HttpGet("{id}")]
public Customer Get(int id)
{
return customerService.getCustomer(id);
}
// POST api/<controller>
[HttpPost]
public Customer Post([FromBody]Customer customer)
{
return customerService.createCustomer(customer);
}
// PUT api/<controller>/5
[HttpPut("{id}")]
public Customer Put(int id, [FromBody]Customer customer)
{
return customerService.updateCustomer(customer);
}
// DELETE api/<controller>/5
[HttpDelete("{id}")]
public bool Delete(int id)
{
return customerService.deleteCustomer(id);
}
}
}
<file_sep>/BusReservationApi/Controllers/TripController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using BusReservationApi.Model;
using BusReservationApi.Service;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace BusReservationApi.Controllers
{
[Route("api/[controller]")]
public class TripController : Controller
{
TripService tripService = new TripService();
// GET: api/<controller>
[HttpGet("all")]
public IEnumerable<Trip> GetAllTrips()
{
return tripService.GetAllTrip();
}
// GET api/<controller>/5
[HttpGet("{id}")]
public Trip GetTrip(int id )
{
return tripService.GetTrip(id);
}
// POST api/<controller>
[HttpPost]
public Trip Post([FromBody] Trip value)
{
return tripService.CreateTrip(value);
}
// PUT api/<controller>/5
[HttpPut("{id}")]
public Trip Put(int id, [FromBody] Trip value)
{
return tripService.UpdateTrip(value);
}
// DELETE api/<controller>/5
[HttpDelete("{id}")]
public bool Delete(int id)
{
return tripService.DeleteTrip(id);
}
}
}
<file_sep>/BusReservationApi/Model/Rental.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BusReservationApi.Model
{
public class Rental
{
public Customer Customer { get; set; }
public string Id { get; set; }
public DateTime Rented_date { get; set; }
public DateTime Date_rented { get; set; }
public float Amount { get; set; }
public int number_of_days { get; set; }
public Driver Driver { get; set; }
public Agent Agent { get; set; }
public Bus Bus { get; set; }
}
}
<file_sep>/BusReservationApi/DB/TripDAO.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BusReservationApi.Model;
using MySql.Data;
using MySql.Data.MySqlClient;
namespace BusReservationApi.DB
{
public class TripDAO
{
private DB db;
public TripDAO()
{
db = new DB();
}
public Trip Create(Trip trip)
{
Trip new_trip = new Trip();
string query = string.Format("INSERT INTO trip {0}", GenerateInsertString(trip));
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "trip");
new_trip = SetTrips(mySqlDataReader)[0];
return new_trip;
}
public List<Trip> Get()
{
List<Trip> trips = new List<Trip>();
string query = string.Format("SELECT * FROM trip");
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "trip");
trips = SetTrips(mySqlDataReader);
return trips;
}
public Trip Get(int id)
{
Trip trip = new Trip();
string query = string.Format("SELECT * FROM trip WHERE id = {0}", id.ToString());
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "trip");
if (mySqlDataReader != null)
{
if (mySqlDataReader.HasRows)
{
trip = SetTrips(mySqlDataReader)[0];
}
}
return null;
}
public Trip Update(Trip trip)
{
Trip updatedTrip = new Trip();
string query = string.Format("UPDATE trip ", GenerateUpdateString(trip));
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "trip");
mySqlDataReader.Close();
updatedTrip = Get(int.Parse(trip.Id));
return updatedTrip;
}
public bool Delete(int id)
{
string query = string.Format("DELETE FROM trip WHERE id = ", id.ToString());
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "customer");
if (mySqlDataReader == null)
{
return true;
}
return false;
}
public bool Delete(Trip trip)
{
string query = string.Format("DELETE FROM trip WHERE id = ", trip.Id.ToString());
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "customer");
if (mySqlDataReader == null)
{
return true;
}
return false;
}
private List<Trip> SetTrips(MySqlDataReader mySqlDataReader)
{
List<Trip> trips = new List<Trip>();
while (mySqlDataReader.Read())
{
Trip trip = new Trip
{
Id = mySqlDataReader.GetString(0),
Bus = new Bus {Id = mySqlDataReader.GetString(1) },
Driver = new Driver { Id =mySqlDataReader.GetString(2) },
Date = mySqlDataReader.GetDateTime(3),
Depature_time = mySqlDataReader.GetDateTime(5),
Arrival_time = mySqlDataReader.GetDateTime(5),
Starting_point = mySqlDataReader.GetString(6),
Destination = mySqlDataReader.GetString(7),
Price = mySqlDataReader.GetFloat(8)
};
}
mySqlDataReader.Close();
trips = setTripObjects(trips);
return trips;
}
private List<Trip> setTripObjects(List<Trip> trips)
{
List<Trip> new_trips = trips;
DriverDAO driverDAO = new DriverDAO();
BusDAO busDAO = new BusDAO();
for (int i = 0; i < trips.Count; i++)
{
trips[i].Driver = driverDAO.Get(int.Parse(trips[i].Driver.Id));
trips[i].Bus = busDAO.Get(int.Parse(trips[i].Bus.Id));
}
return new_trips;
}
private string GenerateInsertString(Trip trip)
{
return string.Format("(bus_id,driver_id,departure_date,departure_time,arrival_time,departure_place,destination,price) VALUES('{0}', '{1}','{2}','{3}','{4}','{5}','{6}','{7}')", trip.Bus.Id, trip.Driver.Id, trip.Date.Date, trip.Depature_time, trip.Arrival_time, trip.Starting_point, trip.Destination, trip.Price);
}
private string GenerateUpdateString(Trip trip)
{
return string.Format("SET bus_id = '{0}',driver_id = '{1}',departure_date = '{2}',departure_time = '{3}',arrival_time = '{4}', departure_place = '{5}',destination ='{6}', price = '{7}' WHERE id = {8}",trip.Bus.Id,trip.Driver.Id,trip.Date.Date,trip.Depature_time,trip.Arrival_time,trip.Starting_point,trip.Destination,trip.Price,trip.Id );
}
}
}
<file_sep>/BusReservationApi/Service/AgentService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BusReservationApi.DB;
using BusReservationApi.Model;
namespace BusReservationApi.Service
{
public class AgentService
{
AgentDAO agentDAO = new AgentDAO();
public AgentService()
{
}
public IEnumerable<Agent> getAllAgents()
{
return agentDAO.Get();
}
public Agent getAgent(int id)
{
return agentDAO.Get(id);
}
public Agent createCustomer(Agent agent)
{
return agentDAO.CreateAgent(agent);
}
public Agent updateCustomer(Agent agent)
{
return agentDAO.Update(agent);
}
public bool deleteCustomer(int id)
{
return agentDAO.Delete(id);
}
}
}
<file_sep>/BusReservationApi/DB/DB.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MySql.Data;
using MySql.Data.MySqlClient;
namespace BusReservationApi.DB
{
public class DB
{
private MySqlConnection conn;
public DB()
{
//string connstring = string.Format("server={0};port={1};uid={2};pwd={3};database={4};SslMode={5}", "localhost","3306","root","1<PASSWORD>#", "bookingapp", "none");
string connstring = "Persist Security Info=False;database=bookingapp;server=192.168.17.238;Connect Timeout=30;user id=root; pwd=<PASSWORD>";
conn = new MySqlConnection(connstring);
conn.Open();
}
public Object Query(string query, string table)
{
query = query.Trim();
MySqlCommand cmd = new MySqlCommand(query, conn);
if(!query.Substring(0,1).ToUpper().Contains("D"))
{
if (query.Substring(0, 1).ToUpper().Contains("I")) {
cmd.ExecuteNonQuery();
cmd = new MySqlCommand("select LAST_INSERT_ID()", conn);
MySqlDataReader mySqlDataReader = cmd.ExecuteReader();
mySqlDataReader.Read();
int id = mySqlDataReader.GetInt32(0);
mySqlDataReader.Close();
query = string.Format("SELECT * FROM {0} WHERE id = {1}", table, id.ToString());
cmd = new MySqlCommand(query, conn);
mySqlDataReader = cmd.ExecuteReader();
return mySqlDataReader;
}
else
{
MySqlDataReader mySqlDataReader = cmd.ExecuteReader();
return mySqlDataReader;
}
}
else
{
cmd.ExecuteNonQuery();
return null;
}
}
public void Close()
{
conn.Close();
}
public bool IsConnect()
{
if (conn == null)
{
return false;
}
return true;
}
public void Open()
{
conn.Open();
}
}
}
<file_sep>/BusReservationApi/Model/customer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BusReservationApi.Model
{
public class Customer
{
public string Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Phone { get; set; }
public string Next_of_kin { get; set; }
public string Next_of_kin_number { get; set; }
public Customer(string Id, string Name, string Surname, string Phone, string Next_of_kin, string Next_of_kin_number)
{
this.Id = Id;
this.Name = Name;
this.Surname = Surname;
this.Phone = Phone;
this.Next_of_kin = Next_of_kin;
this.Next_of_kin_number = Next_of_kin_number;
}
public Customer()
{
}
}
}
<file_sep>/BusReservationApi/Controllers/AgentController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using BusReservationApi.Model;
using BusReservationApi.Service;
namespace BusReservationApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AgentController : ControllerBase
{
// CustomerService customersirvice=new CustomerService();
AgentService agentService = new AgentService();
/*[HttpGet("/all")]
public IEnumerable<Customer> GetAllCustomers()
{
return agentService
}
[HttpGet("{id}")]
public Customer GetCustomer(int id)
{
return agentService;
}
// POST api/<controller>
[HttpPost]
public Customer Post([FromBody] Customer value)
{
return agentService;
// PUT api/<controller>/5
[HttpPut("{id}")]
public Trip Put(int id, [FromBody] Trip value)
{
return agentService;
}
// DELETE api/<controller>/5
[HttpDelete("{id}")]
public bool Delete(int id)
{
return agentService;
}*/
}
}<file_sep>/BusReservationApi/Model/Ticket.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BusReservationApi.Model
{
public class Ticket
{
public string Id { get; set; }
public Customer customer { get; set; }
public Trip Trip { get; set; }
public Agent Agent { get; set; }
public string seat { get; set; }
public DateTime Purchase_date { get; set; }
}
}
<file_sep>/BusReservationApi/Service/CustomerService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BusReservationApi.Model;
//using BusReservationApi.Controllers;
using BusReservationApi.DB;
namespace BusReservationApi.Service
{
public class CustomerService : CustomerInterface
{
CustomerDAO customerDAO = new CustomerDAO();
public CustomerService()
{
}
public IEnumerable<Customer> getAllCustomers()
{
return customerDAO.Get();
}
public Customer getCustomer(int id)
{
return customerDAO.Get(id);
}
public Customer createCustomer(Customer customer)
{
return customerDAO.CreateCustomer(customer);
}
public Customer updateCustomer(Customer customer)
{
return customerDAO.Update(customer);
}
public bool deleteCustomer(int id)
{
return customerDAO.Delete(id);
}
}
}
<file_sep>/BusReservationApi/DB/DriverDAO.cs
using BusReservationApi.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MySql.Data;
using MySql.Data.MySqlClient;
namespace BusReservationApi.DB
{
public class DriverDAO
{
private DB db;
public DriverDAO()
{
db = new DB();
}
public Driver CreateDriver(Driver driver)
{
string query = string.Format("INSERT INTO driver {0}", GenerateInsertString(driver));
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "driver");
return driver;
}
public Driver Get(int id)
{
Driver driver = new Driver();
string query = string.Format("SELECT * FROM driver WHERE id = {0}", id.ToString());
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "driver");
if (mySqlDataReader != null)
{
if (mySqlDataReader.HasRows)
{
driver = SetDrivers(mySqlDataReader)[0];
}
}
return null;
}
public List<Driver> Get()
{
string query = string.Format("SELECT * FROM driver");
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "driver");
return SetDrivers(mySqlDataReader);
}
public bool Delete(int id)
{
string query = string.Format("DELETE FROM driver WHERE id = ", id.ToString());
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "driver");
if (mySqlDataReader == null)
{
return true;
}
return false;
}
public bool Delete(Driver driver)
{
string query = string.Format("DELETE FROM driver WHERE id = ", driver.Id.ToString());
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "driver");
if (mySqlDataReader == null)
{
return true;
}
return false;
}
public Driver Update(Driver driver)
{
Driver updatedDriver = new Driver();
string query = string.Format("UPDATE driver ", GenerateUpdateString(driver));
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "driver");
mySqlDataReader.Close();
updatedDriver = Get(int.Parse(driver.Id));
return updatedDriver;
}
private List<Driver> SetDrivers(MySqlDataReader mySqlDataReader)
{
List<Driver> drivers = new List<Driver>();
while (mySqlDataReader.Read())
{
Driver driver = new Driver
{
Id = mySqlDataReader.GetInt32(0).ToString(),
Name = mySqlDataReader.GetString(1).ToString(),
Surname = mySqlDataReader.GetString(2).ToString(),
};
drivers.Add(driver);
}
mySqlDataReader.Close();
return drivers;
}
private string GenerateInsertString(Driver driver)
{
return string.Format("(name,surname) VALUES('{0}', '{1}')", driver.Name, driver.Surname);
}
private string GenerateUpdateString(Driver driver)
{
return string.Format("SET name = '{0}',surname = '{1}', WHERE id = {5}", driver.Name, driver.Surname);
}
}
}
<file_sep>/BusReservationApi/Service/TicketService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BusReservationApi.Model;
using BusReservationApi.DB;
namespace BusReservationApi.Service
{
public class TicketService
{
TicketDAO ticketDAO = new TicketDAO();
public TicketService()
{
}
/*
public IEnumerable<Ticket> GetAllTicket()
{
return ticketDAO.Get();
}
public Ticket GetTicket(int id)
{
return ticketDAO.Get(id);
}
public Ticket CreateTicket(Ticket ticket)
{
return ticketDAO.Create(ticket);
}
public Ticket UpdateTicket(Ticket ticket)
{
return ticketDAO.Update(ticket);
}
public bool DeleteTicket(int id)
{
return ticketDAO.Delete(id);
}
*/
}
}
<file_sep>/BusReservationApi/DB/AgentDAO.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BusReservationApi.Model;
using MySql.Data;
using MySql.Data.MySqlClient;
namespace BusReservationApi.DB
{
public class AgentDAO
{
private DB db;
public AgentDAO()
{
db = new DB();
}
public Agent CreateAgent(Agent agent)
{
Agent new_agent = new Agent();
string query = string.Format("INSERT INTO agent {0}", GenerateInsertString(agent));
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "agent");
return new_agent;
}
public Agent Get(int id)
{
Agent agent = new Agent();
string query = string.Format("SELECT * FROM agent WHERE id = {0}", id.ToString());
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "agent");
if (mySqlDataReader != null)
{
if (mySqlDataReader.HasRows)
{
agent = SetAgents(mySqlDataReader)[0];
}
}
return null;
}
public List<Agent> Get()
{
string query = string.Format("SELECT * FROM agent");
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "agent");
return SetAgents(mySqlDataReader);
}
public bool Delete(int id)
{
string query = string.Format("DELETE FROM agent WHERE id = ", id.ToString());
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "agent");
if (mySqlDataReader == null)
{
return true;
}
return false;
}
public bool Delete(Agent agent)
{
string query = string.Format("DELETE FROM agent WHERE id = ", agent.Id.ToString());
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "agent");
if (mySqlDataReader == null)
{
return true;
}
return false;
}
public Agent Update(Agent agent)
{
Agent updatedAgent = new Agent();
string query = string.Format("UPDATE agent ", GenerateUpdateString(agent));
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "agent");
mySqlDataReader.Close();
updatedAgent = Get(int.Parse(agent.Id));
return updatedAgent;
}
private List<Agent> SetAgents(MySqlDataReader mySqlDataReader)
{
List<Agent> agents = new List<Agent>();
while (mySqlDataReader.Read())
{
Agent agent = new Agent
{
Id = mySqlDataReader.GetInt32(0).ToString(),
Name = mySqlDataReader.GetString(1).ToString(),
Surname = mySqlDataReader.GetString(2).ToString(),
Phone = mySqlDataReader.GetString(3).ToString(),
Email = mySqlDataReader.GetString(4).ToString(),
Password = mySqlDataReader.GetString(5).ToString()
};
agents.Add(agent);
}
mySqlDataReader.Close();
return agents;
}
private string GenerateInsertString(Agent agent)
{
return string.Format("(name,surname,phone,email,password) VALUES('{0}', '{1}','{2}','{3}','{4}')", agent.Name, agent.Surname, agent.Phone, agent.Email, agent.Password);
}
private string GenerateUpdateString(Agent agent)
{
return string.Format("SET name = '{0}',surname = '{1}',phone = '{2}',email = '{3}',password = '{4}' WHERE id = {5}", agent.Name, agent.Surname, agent.Phone, agent.Email, agent.Password, agent.Id);
}
}
}
<file_sep>/BusReservationApi/Controllers/BussController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using BusReservationApi.Service;
using BusReservationApi.Model;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace BusReservationApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class BussController : Controller
{
BusService busService = new BusService();
// GET: api/<controller>
[HttpGet("all")]
public IEnumerable<Bus> GetAllBusses()
{
return busService.GetAllBusses();
}
[HttpGet("{id}")]
public Bus GetBus(int id)
{
return busService.GetBus(id);
}
// POST api/<controller>
[HttpPost]
public Bus Post([FromBody]Bus value)
{
return busService.CreateBus(value);
}
// PUT api/<controller>/5
[HttpPut("{id}")]
public Bus Put(int id, [FromBody]Bus value)
{
return busService.UpdateBus(value);
}
// DELETE api/<controller>/5
[HttpDelete("{id}")]
public bool Delete(int id)
{
return busService.DeleteBus(id);
}
}
}
<file_sep>/BusReservationApi/DB/BusDAO.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BusReservationApi.Model;
using MySql.Data;
using MySql.Data.MySqlClient;
namespace BusReservationApi.DB
{
public class BusDAO
{
private DB db;
public BusDAO()
{
db = new DB();
}
public Bus Create(Bus bus)
{
Bus new_bus = new Bus();
string query = string.Format("INSERT INTO bus {0}", GenerateInsertString(bus));
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "bus");
new_bus = SetBuses(mySqlDataReader)[0];
return new_bus;
}
public Bus Update(Bus bus)
{
Bus updatedBus = new Bus();
string query = string.Format("UPDATE bus ", GenerateUpdateString(bus));
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "bus");
mySqlDataReader.Close();
updatedBus = Get(int.Parse(bus.Id));
return updatedBus;
}
public List<Bus> Get()
{
string query = string.Format("SELECT * FROM bus");
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "bus");
return SetBuses(mySqlDataReader);
}
public Bus Get(int id)
{
Bus bus = new Bus();
string query = string.Format("SELECT * FROM bus WHERE id = {0}", id.ToString());
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "customer");
if (mySqlDataReader != null)
{
if (mySqlDataReader.HasRows)
{
bus = SetBuses(mySqlDataReader)[0];
}
}
return null;
}
public bool Delete(int id)
{
string query = string.Format("DELETE FROM bus WHERE id = ", id.ToString());
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "customer");
if (mySqlDataReader == null)
{
return true;
}
return false;
}
public bool Delete(Bus bus)
{
string query = string.Format("DELETE FROM customer WHERE id = ", bus.Id.ToString());
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "customer");
if (mySqlDataReader == null)
{
return true;
}
return false;
}
private List<Bus> SetBuses(MySqlDataReader mySqlDataReader)
{
List<Bus> buses = new List<Bus>();
while (mySqlDataReader.Read())
{
Bus bus = new Bus
{
Id = mySqlDataReader.GetInt32(0).ToString(),
Name = mySqlDataReader.GetString(1),
Bus_type = mySqlDataReader.GetString(2),
Reg_no = mySqlDataReader.GetString(3),
Num_seat = mySqlDataReader.GetInt32(4)
};
buses.Add(bus);
}
mySqlDataReader.Close();
return buses;
}
private string GenerateInsertString(Bus bus)
{
return string.Format("(name,bus_type,reg_no,seats) VALUES('{0}', '{1}','{2}','{3}')", bus.Name, bus.Bus_type, bus.Reg_no, bus.Num_seat);
}
private string GenerateUpdateString(Bus bus)
{
return string.Format("SET name = '{0}',bus_type = '{1}',reg_no = '{2}',seats = '{3}' WHERE id = {4}", bus.Name, bus.Bus_type, bus.Reg_no, bus.Num_seat, bus.Id);
}
}
}
<file_sep>/README.md
# BusReservationApi
C-sharp project that implements a core web api.
<file_sep>/BusReservationApi/Service/CustomerInterface.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BusReservationApi.Model;
namespace BusReservationApi.Service
{
interface CustomerInterface
{
IEnumerable<Customer> getAllCustomers();
Customer getCustomer(int id);
//bool doesCustomerExist(string ig);
Customer createCustomer(Customer customer);
Customer updateCustomer(Customer customer);
bool deleteCustomer(int id);
}
}
<file_sep>/BusReservationApi/DB/RentalDAO.cs
using BusReservationApi.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MySql.Data;
using MySql.Data.MySqlClient;
namespace BusReservationApi.DB
{
public class RentalDAO
{
private DB db;
private BusDAO busDAO = new BusDAO();
public RentalDAO()
{
db = new DB();
}
public Rental CreateRental(Rental rental)
{
string query = string.Format("INSERT INTO rental {0}", GenerateInsertString(rental));
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "rental");
return rental;
}
public Rental Get(int Id)
{
Rental rental = new Rental();
string query = string.Format("SELECT * FROM rental WHERE id = {0}", Id.ToString());
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "rental");
if (mySqlDataReader != null)
{
if (mySqlDataReader.HasRows)
{
rental = SetRentals(mySqlDataReader)[0];
}
}
return null;
}
public List<Rental> Get()
{
string query = string.Format("SELECT * FROM rental");
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "rental");
return SetRentals(mySqlDataReader);
}
public bool Delete(int Id)
{
string query = string.Format("DELETE FROM rental WHERE id = ", Id.ToString());
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "rental");
if (mySqlDataReader == null)
{
return true;
}
return false;
}
public bool Delete(Rental rental)
{
string query = string.Format("DELETE FROM rental WHERE id = ", rental.Id.ToString());
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "rental");
if (mySqlDataReader == null)
{
return true;
}
return false;
}
public Rental Update(Rental rental)
{
Rental updatedRental = new Rental();
string query = string.Format("UPDATE driver ", GenerateUpdateString(rental));
MySqlDataReader mySqlDataReader = (MySqlDataReader)db.Query(query, "rental");
mySqlDataReader.Close();
updatedRental = Get(int.Parse(rental.Id));
return updatedRental;
}
private List<Rental> SetRentals(MySqlDataReader mySqlDataReader)
{
List<Rental> rentals = new List<Rental>();
while (mySqlDataReader.Read())
{
Rental rental = new Rental
{
Id = mySqlDataReader.GetInt32(0).ToString(),
Bus = new Bus { Id = mySqlDataReader.GetInt32(1).ToString() },
Customer = new Customer { Id = mySqlDataReader.GetInt32(3).ToString() },
Rented_date = mySqlDataReader.GetDateTime(0),
Date_rented = mySqlDataReader.GetDateTime(1),
Amount = mySqlDataReader.GetFloat(1),
number_of_days = mySqlDataReader.GetInt32(1),
Driver = new Driver { Id = mySqlDataReader.GetInt32(2).ToString() },
Agent = new Agent { Id = mySqlDataReader.GetInt32(2).ToString() }
};
rentals.Add(rental);
}
mySqlDataReader.Close();
return rentals;
}
private string GenerateInsertString(Rental rental)
{
return string.Format("(Id,Bus,Customer,Rented_date,Date_rented,Amount,number_of_days,Driver,Agent) VALUES('{0}', '{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}')", rental.Id, rental.Bus.Id,rental.Customer,rental.Rented_date,rental.Date_rented,rental.Amount,rental.number_of_days,rental.Driver.Id,rental.Agent.Id);
}
private string GenerateUpdateString(Rental rental)
{
return string.Format("SET Id = '{0}',Bus = '{1}',Customer = '{2}',Rented_date = '{3}',Date_rented = '{4}', Amount = '{5}',Number_of_days ='{6}', Driver = '{7}',Agent = '{8}' WHERE id = {8}", rental.Id, rental.Bus.Id, rental.Customer, rental.Rented_date, rental.Date_rented, rental.Amount, rental.number_of_days, rental.Driver.Id, rental.Agent.Id);
}
}
}
<file_sep>/BusReservationApi/Service/DriverService.Service.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BusReservationApi.DB;
using BusReservationApi.Model;
using BusReservationApi.Service;
namespace BusReservationApi.Service
{
public class DriverService
{
DriverDAO driverDAO = new DriverDAO();
public IEnumerable<Driver> GetAllDrivers()
{
return driverDAO.Get();
}
public Driver GetDriver(int id)
{
return driverDAO.Get(id);
}
public Driver createDriver( Driver driver)
{
return driverDAO.CreateDriver(driver);
}
public Driver updateDriver(Driver driver)
{
return driverDAO.Update(driver);
}
public bool deleteDriver(int driver)
{
return driverDAO.Delete(driver);
}
}
}
<file_sep>/BusReservationApi/Controllers/RentalController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using BusReservationApi.Model;
using BusReservationApi.Service;
namespace BusReservationApi.Controllers
{
[Route("api/[controller]")]
public class RentalController : Controller
{
RentalService rentalService = new RentalService();
/*[HttpGet("all")]
public IEnumerable<Rental> GetAllRentals()
{
return rentalService.
}
// GET api/<controller>/5
[HttpGet("{id}")]
public Rental GetRental(int id)
{
return rentalService.
}
// POST api/<controller>
[HttpPost]
public Rental Post([FromBody] Rental value)
{
return rentalService.
}
// PUT api/<controller>/5
[HttpPut("{id}")]
public Rental Put(int id, [FromBody] Rental value)
{
return rentalService.
}
// DELETE api/<controller>/5
[HttpDelete("{id}")]
public bool Delete(int id)
{
return rentalService.
}*/
}
}
|
4641b46a3fbb2a9ddfc5b5b02a8156df6053ff82
|
[
"Markdown",
"C#"
] | 27
|
C#
|
maikimolahlehi/BusReservationApi
|
b157c9e4685730f0949db01b7050731b6a809663
|
cfcb9d9e339985c7e4ce3635413bcd144a6f08e8
|
refs/heads/master
|
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.4.10
-- http://www.phpmyadmin.net
--
-- Client : localhost
-- Généré le : Lun 30 Janvier 2017 à 11:21
-- Version du serveur : 5.5.42
-- Version de PHP : 7.0.0
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
--
-- Base de données : `mon-potager`
--
-- --------------------------------------------------------
--
-- Structure de la table `users`
--
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`token` varchar(255) NOT NULL,
`full_name` varchar(255) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=latin1;
--
-- Contenu de la table `users`
--
INSERT INTO `users` (`id`, `email`, `password`, `token`, `full_name`) VALUES
(1, '<EMAIL>', 'secret', '<PASSWORD>', 'Bob'),
(2, '<EMAIL>', 'secret', 'secret2', 'Alice'),
(3, '<EMAIL>', 'secret', 'secret3', 'Oscar'),
(11, 'AAAA@AAAA.AAAA', 'AAAA', 'ss', 'fweijfijw'),
(12, '<EMAIL>', 'fekifjeirjfier', 'ssss', 'fjwioejfjwiejfijwi'),
(13, '<EMAIL>', 'wjeifjw', '1569659610', 'dewjfijweijfi'),
(15, '<EMAIL>', 'BBBB', '520033858', 'BBBB');
-- --------------------------------------------------------
--
-- Structure de la table `vegetables`
--
CREATE TABLE `vegetables` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`description` text NOT NULL,
`user_id` int(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
--
-- Contenu de la table `vegetables`
--
INSERT INTO `vegetables` (`id`, `name`, `description`, `user_id`) VALUES
(1, 'Pomme de terre', 'La pomme de terre est un légume facile à cultiver, à récolte précoce, à bon rendement, à longue période de conservation et aux qualités nutritives indéniables (riche en sucres lents, en vitamine C, en minéraux, en protéines).', 1),
(2, 'Carotte', 'La carotte est sans aucun doute l’un des légumes les plus cultivés et les plus gustatifs.\r\n\r\nL’entretien, du semis à la récolte, est facile.', 1),
(3, 'Fenouil', 'Le fenouil est une plante dont on consomme les racines et dont les vertus nutritives et aromatiques sont excellentes. C’est un très bon légume d’été.', 1),
(6, 'foo', 'bar', 1);
--
-- Index pour les tables exportées
--
--
-- Index pour la table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `email` (`email`),
ADD UNIQUE KEY `token` (`token`);
--
-- Index pour la table `vegetables`
--
ALTER TABLE `vegetables`
ADD PRIMARY KEY (`id`),
ADD KEY `user_id` (`user_id`);
--
-- AUTO_INCREMENT pour les tables exportées
--
--
-- AUTO_INCREMENT pour la table `users`
--
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=17;
--
-- AUTO_INCREMENT pour la table `vegetables`
--
ALTER TABLE `vegetables`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=7;
--
-- Contraintes pour les tables exportées
--
--
-- Contraintes pour la table `vegetables`
--
ALTER TABLE `vegetables`
ADD CONSTRAINT `vegetables_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);
|
5f6969985a402c0c8c9d27768f71777cf36d219f
|
[
"SQL"
] | 1
|
SQL
|
monpotager/database
|
ac7468296fbe8d5813753d9c2a8940b1c5018403
|
b922052f5ac02b4ff1691598a9ff4e08f495524a
|
refs/heads/master
|
<file_sep>from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.request import Request
from rest_framework import serializers
from django_filters.rest_framework import DjangoFilterBackend
from core import exceptions, JWTAPIView, make_response
from .models import Payment
from .serializers import PaymentSerializer
def ignore_inspection_wrap(fn):
def inner(*args, **kwargs):
return fn(*args, **kwargs)
return inner
class TestView(JWTAPIView):
class TestSerializer(serializers.Serializer):
def update(self, instance, validated_data):
pass
def create(self, validated_data):
pass
page = serializers.IntegerField(required=True)
num = serializers.IntegerField(required=True)
@ignore_inspection_wrap
def get(self, request: Request):
s = self.TestSerializer(data=request.query_params)
if not s.is_valid():
raise exceptions.ParamsError()
return self.make_response(s.validated_data)
def post(self, request):
raise exceptions.ParamsError()
def handle_exception(self, exc):
d = super(TestView, self).handle_exception(exc)
print(exc)
return d
class PaymentListView(ListAPIView):
class _PageNumberPagination(PageNumberPagination):
page_size_query_param = "page_size"
max_page_size = 10
authentication_classes = tuple()
permission_classes = tuple()
queryset = Payment.objects.order_by("-id").prefetch_related("user")
serializer_class = PaymentSerializer
pagination_class = _PageNumberPagination
filter_backends = [DjangoFilterBackend]
filterset_fields = ['user__id']
def get(self, request, *args, **kwargs):
d = super().get(request, *args, **kwargs)
return make_response(data=d.data)
<file_sep>
class BaseService:
pass
class Service(BaseService):
pass
<file_sep>from rest_framework.response import Response
from rest_framework import status
from . import exceptions
__all__ = ["CoreResponse", "make_response"]
class CoreResponse(Response):
pass
def make_response(
data=None,
code=exceptions.DEFAULT_CODE,
msg=exceptions.DEFAULT_MSG,
status_code=status.HTTP_200_OK,
**kwargs
):
"""返回response对象
参数:
- data: 数据
- code: 自定义的状态码
- msg: 消息内容
- status_code: http状态码
"""
body = dict(
data=data,
code=code,
msg=msg
)
body.update(kwargs)
r = CoreResponse(body, status=status_code)
return r
<file_sep>from django.db import transaction
from .models import Payment
from core import services
class PaymentService(services.Service):
payment_class = Payment
def fetch(self, user, page, num):
pass
def create_payment(self, user, price, desc, platform_id):
transaction.on_commit()
<file_sep>from django.http.response import JsonResponse
from rest_framework import status
def make_response(code=0, data=None, msg="", status_code=status.HTTP_200_OK):
"""响应数据
"""
r = JsonResponse({
"code": code,
"data": data if data else dict(),
"msg": msg
}, status=status_code)
return r
<file_sep># Django 结构封装
<file_sep>from rest_framework import status
__all__ = [
"ClientError",
"ClientErrorCodeCol",
"ParamsError"
]
DEFAULT_CODE = 0
DEFAULT_MSG = "ok"
class BaseClientErrorCode:
def __init__(self, code, msg, status_code=status.HTTP_200_OK):
self.code = code
self.msg = msg
self.status_code = status_code
class ClientErrorCodeCol:
"""自定义的错误码集合
"""
INVALID_PARAMS = BaseClientErrorCode(1, "参数错误", status.HTTP_422_UNPROCESSABLE_ENTITY)
class ClientError(Exception):
error_code = None
def __init__(self, code=None, msg=None, status_code=None, error_code_ins=None):
# 初始化错误码
self.init_error_code()
if code is not None:
self.code = code
if msg is not None:
self.msg = msg
if status_code is not None:
self.status_code = status_code
# 如果输入了参数 error_code_ins 那么久用这个的
self.load_error_code_ins(error_code_ins)
assert self.status_code is not None
def init_error_code(self):
self.load_error_code_ins(self.error_code)
def load_error_code_ins(self, error_code_ins: BaseClientErrorCode):
if isinstance(self.error_code, BaseClientErrorCode):
self.code = error_code_ins.code
self.status_code = error_code_ins.status_code
self.msg = error_code_ins.msg
class ParamsError(ClientError):
error_code = ClientErrorCodeCol.INVALID_PARAMS
<file_sep>from .exceptions import *
from .views import *
from .response import *
__all__ = (
exceptions.__all__ +
views.__all__ +
response.__all__
)
<file_sep>from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class TimeAbstractModel(models.Model):
create_time = models.DateTimeField(auto_now_add=True)
update_time = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Platform(TimeAbstractModel):
name = models.CharField(max_length=128)
desc = models.CharField(max_length=128)
class Category(models.Model):
desc = models.CharField(max_length=256)
class Payment(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
price = models.DecimalField(max_digits=10, decimal_places=2)
desc = models.CharField(max_length=128)
platform = models.ForeignKey(Platform, on_delete=models.CASCADE)
category = models.ManyToManyField(Category)<file_sep>from rest_framework.views import APIView, exception_handler as _exception_handler
from rest_framework.permissions import IsAuthenticated
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.response import Response
from . import exceptions
from .response import make_response
__all__ = ["CoreAPIView", "JWTAPIView"]
def exception_handler(exc, context):
_ = context
r = _exception_handler(exc, context)
if isinstance(r, Response):
msg = r.data.get("detail", "ok")
r = make_response(
code=r.status_code,
msg=msg,
data=r.data,
status_code=r.status_code
)
return r
if isinstance(exc, exceptions.ClientError):
r = make_response(
code=exc.code,
msg=exc.msg,
status_code=exc.status_code
)
return r
class CoreAPIView(APIView):
def get_exception_handler(self):
return exception_handler
@staticmethod
def make_response(*args, **kwargs):
return make_response(*args, **kwargs)
class JWTAPIView(CoreAPIView):
permission_classes = (IsAuthenticated, )
authentication_classes = (JSONWebTokenAuthentication, )
<file_sep>from rest_framework import serializers
from apps.payment import models
class PaymentSerializer(serializers.ModelSerializer):
id = serializers.IntegerField()
price = serializers.DecimalField(10, 2)
desc = serializers.CharField()
username = serializers.CharField(source="user.username")
class Meta:
model = models.Payment
fields = ("id", "price", "desc", "username")
|
5372e42190b8fce0d0d66b9852e9392641756492
|
[
"Markdown",
"Python"
] | 11
|
Python
|
sky1309/gm_server
|
726f14675446996813b318911622ff128e665180
|
e716077927cc8f6358e37ac5e7645df8968a7902
|
refs/heads/main
|
<file_sep>import csv
f = open("aruco4x4.txt",'r')
wf = open("aruco4x4.csv", 'w')
wc = csv.writer(wf)
counter = 0
for row in f:
row = row.strip()
for i in range(5):
row = row.rstrip(';')
row = row.lstrip('{')
row = row.lstrip(' ')
row = row.rstrip('}')
row = row.rstrip(' ')
row = row.rstrip(',')
row = row.split(',')
row = [int(r) for r in row]
wc.writerow(row)
# print(row)
counter += 1
f.close()
wf.close()
|
5e38b06dd3137327b7599a9e5ed1ae425ef91fec
|
[
"Python"
] | 1
|
Python
|
BenHof1/ENGN4627-Robotics
|
cd92b17c4ab7378601b7566acdd67339ad4adccc
|
9b6bd6d4278d6a5a8add5a35c7dc65ca305463c7
|
refs/heads/main
|
<file_sep>
hw_timer_t *gTimer = NULL;
uint32_t goodbyeCount=0, oldGoodbyeCount=-1;
/*------------------------------------------------------------------------------*/
void gRight( uint32_t fgcolor, int wait, int length, uint32_t bg){
uint32_t color = fgcolor;
uint32_t bgcolor = bg;
if( length < 2 ) return; // prevent division by zero, no use of animating
for( int i = 0; i < (gstrip.ledcount() + length); ++i ){
for ( int j = 0; j < length ; ++j ){
int dimperc = 100 - j*( 100/( length - 1));
if ( dimperc < 10 ){
gstrip.color32(i - j, bgcolor,100);
}else{
gstrip.color32(i - j, color, dimperc );
}
yield();
}
gstrip.show();
delay( wait);
}
}
/*------------------------------------------------------------------------------*/
void gLeft( uint32_t fgcolor, int wait, int length, uint32_t bg){
uint32_t color = fgcolor;
uint32_t bgcolor = bg;
if( length < 2 ) return; // prevent division by zero, no use of animating
for( int i = gstrip.ledcount() -1 ; i > ( -1 * length); --i ){
for ( int j = 0; j < length ; ++j ){
int dimperc = 100 - j*( 100/( length - 1));
if ( dimperc < 10 ){
gstrip.color32(i + j, bgcolor, 100 );
}else{
gstrip.color32(i + j, color, dimperc );
}
}
gstrip.show();
delay( wait);
}
}
/*------------------------------------------------------------------------------*/
void gToSleep( uint32_t fgcolor , int wait, int length ){
uint32_t color = fgcolor;
uint32_t b,e,half, whole, dimperc;
if( length < 2 ) return; // prevent division by zero, no use of animating
whole = gstrip.ledcount() -1;
half = whole / 2;
for ( b=0; b < half + length; ++b ){
e = whole - b;
for ( int j = 0 ; j < length; ++j ){
dimperc = (100 - j*( 100/( length - 1) ));
if ( b-j > half )dimperc = 0;
gstrip.color32( b-j, color, dimperc );
gstrip.color32( e+j, color, dimperc );
}
gstrip.show();
delay( wait);
}
gstrip.clear();
gstrip.show();
return;
}
/*------------------------------------------------------------------------------*/
void doMute( int bg, bool loud ){
int mcolor = gstrip.getcolor( 250,0,0,0);
int dimperc = 100, dim=-5, endvol=40;
int curvol = getVolume(), volstep=-2;
if ( loud ){
mcolor = gstrip.getcolor( 250,0,100,0);
volstep = 2;
dimperc = 0;
dim = 5;
endvol = 75;
}
for ( int i=0; i < 20; ++i ){
dimperc += dim;
mcolor = gstrip.getcolor( 250,0,100 - dimperc,0);
for ( int s=0; s < gstrip.ledcount(); ++s ){
gstrip.color32( s, mcolor, dimperc );
}
gstrip.show();
curvol += volstep;
setVolume( curvol );
delay( 80 );
if ( loud ){
if( curvol + volstep >= endvol ) break;
}else{
if( curvol + volstep <= endvol ) break;
}
}
for ( int s=0; s < gstrip.ledcount(); ++s ){
gstrip.color32( s, bg, 100 );
}
gstrip.show();
setVolume( endvol );
return;
}
/*------------------------------------------------------------------------------*/
void gWakeup( int bg , int wait, int length ){
uint32_t b,half, whole, dimperc;
if( length < 2 ) return; // prevent division by zero, no use of animating
whole = gstrip.ledcount(); // -1
half = whole / 2;
for ( b = 0; b <= half; ++b ){
dimperc = 100; //j*( 100/( length - 1) );
if ( half+b < whole){
//Serial.printf( "%d to bg+\n", half+b);
gstrip.color32( half+b, bg, dimperc );
}
if ( half-b >= 0){
//Serial.printf( "%d to bg-\n", half-b);
gstrip.color32( half-b, bg, dimperc );
}
gstrip.show();
delay( wait);
}
gstrip.show();
return;
}
/*------------------------------------------------------------------------------*/
int getVolume(){
int v;
xSemaphoreTake(volSemaphore, portMAX_DELAY);
v = currentVolume;
xSemaphoreGive(volSemaphore);
return(v);
}
/*------------------------------------------------------------------------------*/
int setVolume( int v){
//Serial.printf( "Changing volume to %d\n", v);
xSemaphoreTake(volSemaphore, portMAX_DELAY);
currentVolume = v;
player.setVolume( v );
xSemaphoreGive(volSemaphore);
showVolume(v);
save_last_volstat(1);
return(v);
}
/*------------------------------------------------------------------------------*/
int getStation(){
int s;
xSemaphoreTake(staSemaphore, portMAX_DELAY);
s = currentStation;
xSemaphoreGive(staSemaphore);
return(s);
}
/*------------------------------------------------------------------------------*/
int setStation(int s, int p){
xSemaphoreTake(staSemaphore, portMAX_DELAY);
currentStation = s;
playingStation = p;
xSemaphoreGive(staSemaphore);
return(s);
}
/*------------------------------------------------------------------------------*/
void change_volstat(int dir){
int current_volume = getVolume();
int current_station = getStation();
if ( gmode == 1 ){
current_volume += (dir*5);
if ( current_volume > 100 )current_volume = 100;
if ( current_volume < 0 ) current_volume = 0;
setVolume(current_volume );
save_last_volstat(1);
}
if ( gmode == 2 ){
current_station += dir;
Serial.printf( "Changing station\n");
while(1){
if ( current_station < 0 )current_station = STATIONSSIZE - 1;
if ( current_station >= STATIONSSIZE )current_station = 0;
if ( stations[ current_station].status == 1 ) break;
current_station += dir;
}
Serial.printf( "Changing station to %d-%s\n", current_station,stations[ current_station].name );
setStation( current_station, -1 );
}
}
/*------------------------------------------------------------------------------*/
void doPixels( void *param ){
static uint32_t bg=0;
uint32_t pixelCommand;
Serial.printf("Pixels running on core %d\n", xPortGetCoreID());
gToSleep( 0 , 50, 5 );
while(1){
//Serial.printf("Pixels waiting on events\n" );
xTaskNotifyWait(0,0,&pixelCommand,portMAX_DELAY);
Serial.printf("doPixels got command %d (mode = %d, goodbyeCount %d, oldGoodbyeCount %d)\n", pixelCommand, gmode, goodbyeCount,oldGoodbyeCount );
switch( gmode ){
case 0:
bg = 0;
break;
case 2:
bg = gstrip.getcolor(20,0,0,20 );
break;
case 3:
bg = gstrip.getcolor(150,0,0,30 );
break;
case 1:
default:
bg = gstrip.getcolor(0,0,100,0 );
break;
}
switch( pixelCommand ){
case 0: // turn pixels off
if ( gmode == 3){
xSemaphoreTake( chooseSemaphore, portMAX_DELAY);
chosenStation = 2;
xSemaphoreGive( chooseSemaphore);
}
gmode = 0;
gToSleep( bg , 100, 5 );
break;
case 1: // turn pixels on
gWakeup( bg, 50, 5 );
break;
case 2: // right, green snake
gLeft( gstrip.getcolor( 0,100,0,0) , 40, 8, bg);
change_volstat( 1);
break;
case 3: // left red snake
gRight( gstrip.getcolor( 100,0,0,0), 40, 8, bg );
change_volstat( -1 );
break;
case 4: // confirm
if ( gmode == 3){
xSemaphoreTake( chooseSemaphore, portMAX_DELAY);
chosenStation = 1;
xSemaphoreGive( chooseSemaphore);
}
gWakeup( gstrip.getcolor( 0,100,0,0) , 10, 6 );
delay(400);
gWakeup( bg , 1, 6 );
break;
case 8:// clockwise only in mode 3
tft_scrollstation( SCROLLUP );
gWakeup( bg, 50, 5 );
break;
case 16:
tft_scrollstation( SCROLLDOWN );
gWakeup( bg, 50, 5 );
break;
case 10:
gToSleep( bg , 100, 5 );
delay(100);
gToSleep( bg , 100, 5 );
break;
case 11:
doMute(bg,0);
break;
case 12:
doMute(bg,1);
break;
case 911:
//Serial.printf("timer fired # %d, do gToSleep\n", goodbyeCount);
gmode = 0;
gToSleep( 0, 100, 5 );
break;
default:
break;
}
}
}
/*------------------------------------------------------------------------------*/
void tellPixels( uint32_t command ){
Serial.printf("tellPixels gmode = %d : command %d \n", gmode, command );
if ( command == 11 ){ //mute
xTaskNotify( pixelTask, 11,eSetValueWithOverwrite);
//return;
}
if ( command == 12 ){ //unmute
xTaskNotify( pixelTask, 12,eSetValueWithOverwrite);
//return;
}
if ( gmode == 0 ){
switch( command ){
case 911:
if ( oldGoodbyeCount != goodbyeCount) {
Serial.printf("gmode = 0 : goodbyeCount %d, oldGoodbyeCount %d\n", goodbyeCount,oldGoodbyeCount );
oldGoodbyeCount = goodbyeCount;
}
stopgTimer();
break;
case 0: // down
stopgTimer();
xTaskNotify( pixelTask, 0,eSetValueWithOverwrite);
break;
case 9: //up
gmode = 1;
setgTimer();
xTaskNotify( pixelTask, 1,eSetValueWithOverwrite);
break;
default:
break;
}
return;
}
if ( gmode ){
switch(command){
case 911:
if ( oldGoodbyeCount != goodbyeCount){
Serial.printf("Do 911, oldgodbye = %d, goodbye %d\n", oldGoodbyeCount, goodbyeCount );
oldGoodbyeCount = goodbyeCount;
gmode = 0;
xTaskNotify( pixelTask, 911,eSetValueWithOverwrite);
}
break;
case 0: //down
//if( gmode != 3 ) gmode = 0;
stopgTimer();
xTaskNotify( pixelTask, 0,eSetValueWithOverwrite);
break;
case 8: //circle
case 16: //circle
setgTimer();
if ( gmode == 1 ){
gmode = 2;
xTaskNotify( pixelTask, 1,eSetValueWithOverwrite);
} else if ( gmode == 2 || gmode == 3){
gmode = 3;
xTaskNotify( pixelTask, command,eSetValueWithOverwrite);
}
break;
case 9: // up; confirm
setgTimer();
xTaskNotify( pixelTask, 4,eSetValueWithOverwrite);
break;
case 10: //fw backw; stop
stopgTimer();
gmode = 0;
xTaskNotify( pixelTask, 10,eSetValueWithOverwrite);
break;
case 11:
case 12:
break;
default:
setgTimer();
xTaskNotify( pixelTask, command,eSetValueWithOverwrite);
break;
}
return;
}
}
/*------------------------------------------------------------------------------*/
void IRAM_ATTR gTmo(){
BaseType_t pxHighP=0;
goodbyeCount++;
xTaskNotifyFromISR( pixelTask, 911,eSetValueWithOverwrite, &pxHighP);
if( pxHighP ){
portYIELD_FROM_ISR();
}
}
/*------------------------------------------------------------------------------*/
void stopgTimer(){
if( gTimer != NULL ){
timerAlarmDisable( gTimer);
gTimer = NULL;
}
}
/*------------------------------------------------------------------------------*/
void setgTimer(){
if( gTimer != NULL ){
timerAlarmDisable( gTimer);
gTimer = NULL;
}
gTimer = timerBegin(0, 80, true); // use time 1 to stop command mode ( = anything not zero )
timerAttachInterrupt(gTimer, gTmo, true); // let it run endMode when due
timerAlarmWrite(gTimer, 10000000, false ); // set it to 10 seconds, no repeat
timerAlarmEnable(gTimer); // turn timer 1 on
}
/*------------------------------------------------------------------------------*/
void gpixelBegin( int brightness )
{
gstrip.begin( NEOPIN, NEONUMBER );
gstrip.setbrightness( brightness);
gstrip.clear();
}
/*------------------------------------------------------------------------------*/
void initPixels(){
gpixelBegin( 80 );
delay(100);
xTaskCreate(
doPixels, // Task to handle special functions.
"Pixels", // name of task.
3*1024, // Stack size of task
NULL, // parameter of the task
PIXELTASKPRIO, // priority of the task
&pixelTask); // Task handle to keep track of created task
}
<file_sep>
static struct {
int mode;
int h;
int bufsize;
int sendsize;
} chunkstate;
//---------------------------------------------------------------------------
void reset_chunkstate(){
chunkstate.mode = 0;
chunkstate.h = 0;
chunkstate.bufsize = 0;
chunkstate.sendsize = 0;
}
//---------------------------------------------------------------------------
void filter_buffer ( uint8_t *rBuffer, int bytecount ){
uint8_t *r,*f;
static char hexstring[16], sendbuffer[32];
if ( ! stationChunked ){
for ( r = rBuffer ; r - rBuffer < bytecount; ++r){
sendbuffer[ chunkstate.sendsize] = *r;
++chunkstate.sendsize;
if ( chunkstate.sendsize == 32 ){
xQueueSend( playQueue, sendbuffer, portMAX_DELAY);
chunkstate.sendsize = 0;
}
}
return;
}
if ( stationChunked ){
delay(1);
for ( r = rBuffer ; r - rBuffer < bytecount; ++r){
switch ( chunkstate.mode ){
case 0:
if ( *r == ';' || *r == '\r' ){
hexstring[chunkstate.h] = 0;
chunkstate.h = 0;
chunkstate.bufsize = strtol( hexstring, NULL, 16 );
//Serial.printf( " String %s = Hex %X\n", hexstring, chunkstate.bufsize);
chunkstate.mode = 1;
if ( chunkstate.bufsize == 0 )chunkstate.mode = 4;
}
hexstring[chunkstate.h] = *r;
++chunkstate.h;
break;
case 1:
if (*r == '\n' ) chunkstate.mode = 2;
break;
case 2:
if( chunkstate.bufsize == 0 ){
chunkstate.mode = 3;
break;
}
sendbuffer[ chunkstate.sendsize] = *r;
++chunkstate.sendsize;
--chunkstate.bufsize;
if ( chunkstate.sendsize == 32 ){
xQueueSend( playQueue, sendbuffer, portMAX_DELAY);
chunkstate.sendsize = 0;
}
break;
case 3:
if (*r == '\n' ) chunkstate.mode = 0;
break;
case 4:
if (*r == '\n' ) chunkstate.mode = 5;
break;
case 5:
if (*r == '\n' ) chunkstate.mode = 6;
break;
case 6:
if (*r == '\n' ) chunkstate.mode = 0;
break;
}
}
}
return;
}
//--------------------------------------------------------------------
void radio( void *param) {
static int connectmillis;
int bufbegin=1, rc;
int noreads = 0;
int totalbytes=0, threshbytes=5000;
//uint8_t radioBuffer[32];
uint8_t radioBuffer[256];
Serial.printf("Radiotask running on core %d\n", xPortGetCoreID());
TIMERG0.wdt_wprotect=TIMG_WDT_WKEY_VALUE;
TIMERG0.wdt_feed=1;
TIMERG0.wdt_wprotect=0;
setStation( get_last_volstat(0),-1 );
Serial.printf("Radiotask starting loop\n", xPortGetCoreID());
while(1){
xSemaphoreTake( updateSemaphore, portMAX_DELAY);
xSemaphoreGive( updateSemaphore);
if(radioclient->available() > 0 ){
if ( unavailablecount > topunavailable ) topunavailable = unavailablecount;
unavailablecount = 0;
int bytesread = 0;
// bytesread = radioclient->read( &radioBuffer[0], 32 );
bytesread = radioclient->read( &radioBuffer[0], 128 );
if ( contentsize != 0 ){
stations[ playingStation].position += bytesread;
}
if ( bytesread <= 0 ){
noreads++;
delay(20); //server may be slow. Wait a bit to please wd.
Serial.printf("noreads : %d (read rc %d)\n", noreads, bytesread);
if ( bytesread < 0 ) bytesread = 0;
}else{
noreads = 0;
filter_buffer( &radioBuffer[0], bytesread );
}
if ( ( errno != EWOULDBLOCK && errno != EINPROGRESS ) || noreads > 5 ) {
// ewouldblock is eagain = 11 on esp32, einprogress (= 119) happens if station is being connected
Serial.printf("Disconnect radio errno %d bytesread %d\n", errno, bytesread );
disconnectcount++;
//radioclient->flush(); //experimental
radioclient->stop();
}
}else{ //no bytes available
if ( millis() > connectmillis )unavailablecount++;
if(!radioclient->connected() ){
Serial.printf("Connect (again?) to %s\n",stations[ getStation() ].name );
if ( unavailablecount > MAXUNAVAILABLE ){
unavailablecount = 0;
}
if( 0 == (rc = stationsConnect( getStation()) ) ){
playingStation = getStation();
save_last_volstat( 0 );
failed_connects = 0;
connectmillis = millis() + 5000;
//reset chunked encoding counters
reset_chunkstate();
}else{
if ( rc == 400 ){
tft_notAvailable( getStation() );
delay(2000 );
//setStation( 0,-1);
}else{
failed_connects++;
delay(100);
if ( failed_connects > 3 ) {
syslog( "Reboot after 3 failed connects");
ESP.restart();
}
}
}
}
}
// Serial.printf("player playptr %d getptr %d endptr %d \n", mp3Playptr, mp3Getptr, mp3Endptr);
// if ( getStation() != playingStation && radioclient->connected() || unavailablecount > MAXUNAVAILABLE ){
if ( getStation() != playingStation || unavailablecount > MAXUNAVAILABLE ){
Serial.printf("playingStation %d != currentStation %d. reconnect...\n", playingStation, getStation() );
//radioclient->flush();
radioclient->stop();
xQueueSend( playQueue, "ChangeStationSoStartANewSongNow!" , portMAX_DELAY);
if ( unavailablecount > MAXUNAVAILABLE ){
Serial.printf("errno %d unavailble more than %d. reconnect...\n", errno, MAXUNAVAILABLE );
syslog( "reconnect after data has been unavailable.");
disconnectcount++;
}else{
Serial.println("switch station...");
}
}
}//end while
}
/*--------------------------------------------------*/
int radio_init(){
xTaskCreatePinnedToCore(
radio, // Task to handle special functions.
"Radio", // name of task.
2048*8, // Stack size of task
NULL, // parameter of the task
RADIOTASKPRIO, // priority of the task
&radioTask, // Task handle to keep track of created task
RADIOCORE); // processor core
return(0);
}
<file_sep># OranjeRadio
web radio with VS1053 and gesture control using PAJ7620
<img src="images/20201113_152249.jpg" />
<ul>
<li>
For the VS1053, this library is used :
https://github.com/baldram/ESP_VS1053_Library.
A modification has been applied to the header: both the read_register and the write register function have been changed from protected to public, to allow for applying the VS1053 patches.
</li>
<li>For the PAJ7620, this library is used:
https://github.com/Seeed-Studio/Gesture_PAJ7620 (also available via the Arduino library manager)
</li>
</ul>
For hardware used see:
<a href="https://oshwlab.com/peut/webradio">webradio</a>
<file_sep>
#ifdef USESSDP
/*-----------------------------------------------------------------*/
void setupSSDP(){
int chipid;
Serial.printf("Starting SSDP...\n");
#ifdef ESP8266
chipid = ESP.getChipId();
#endif
#ifdef ESP32
chipid = ESP.getEfuseMac();
#endif
SSDPDevice.setName( APNAME );
SSDPDevice.setDeviceType("urn:schemas-upnp-org:device:BinaryLight:1");
SSDPDevice.setSchemaURL("description.xml");
SSDPDevice.setSerialNumber( chipid);
SSDPDevice.setURL("/");
SSDPDevice.setModelName( APNAME );
SSDPDevice.setModelNumber( APNAME " " APVERSION );
SSDPDevice.setManufacturer("Peut");
SSDPDevice.setManufacturerURL("http://www.peut.org/");
// server is the globally defined webserver above
server.on("/description.xml", HTTP_GET, [](){
SSDPDevice.schema( server.client());
});
// don't forget to add
// SSDPDevice.handleClient();
// in loop()
}
#endif
/*-----------------------------------------------------------------*/
void send_json_status()
{
char uptime[32];
int sec = millis() / 1000;
int upsec,upminute,uphr,updays;
int retval=0;
upminute = (sec / 60) % 60;
uphr = (sec / (60*60)) % 24;
updays = sec / (24*60*60);
upsec = sec % 60;
sprintf( uptime, "%d %02d:%02d:%02d", updays, uphr, upminute,upsec);
String output = "{\r\n";
output += "\t\"Application\" : \"";
output += APNAME " " APVERSION;
output += "\",\r\n";
output += "\t\"CompileDate\" : \"";
output += __DATE__ " " __TIME__ ;
output += "\",\r\n";
output += "\t\"uptime\" : \"";
output += uptime;
output += "\",\r\n";
output += "\t\"Battery\" : ";
output += batvolt;
output += ",\r\n";
output += "\t\"failed_connects\" : ";
output += failed_connects;
output += ",\r\n";
output += "\t\"disconnectcount\" : ";
output += disconnectcount;
output += ",\r\n";
output += "\t\"topunavailable\" : ";
output += topunavailable;
output += ",\r\n";
output += "\t\"queueDepth\" : ";
output += uxQueueMessagesWaiting(playQueue);
output += ",\r\n";
output += "\t\"currentStation\" : \"";
output += stations[ getStation()].name;
output += "\",\r\n";
output += "\t\"currentStationIndex\" : ";
output += getStation();
output += ",\r\n";
output += "\t\"currentVolume\" : ";
output += getVolume();
output += "\r\n";
output += "}" ;
server.send(200, "application/json;charset=UTF-8", output);
}
//------------------------------------------------------------------
static const char serverIndex[] PROGMEM =
R"(<html><head><style>
input{background:#f1f1f1;border:0;padding:0px;display:block}
h1{color: orange;font-size: 5vw;}
body{background: lightgrey;font-family:sans-serif;font-size:24px;color:#777;}
body { font-family: Arial, Helvetica, sans-serif;}
form{background:#fff;max-width:400px;margin:75px auto;padding:30px;border-radius:5px;text-align:center;}
.btn{border: 1px solid black;color:#000;padding:10px;font-size:18px;cursor:pointer;display:block;margin-left:160px;margin-top:40px;}
</style>
</head><body><h1>OranjeRadio</h1>
<form method='POST' action='' enctype='multipart/form-data'>
<h2>update firmware</h2>
<input type='file' id=file-input name='update'>
<input type='submit' class=btn value='Update' >
</form>
</body></html>)";
static const char successResponse[] PROGMEM =
"<META http-equiv=\"refresh\" content=\"15;URL=/\">Update Success! Rebooting...\n";
static const char failResponse[] PROGMEM =
"<META http-equiv=\"refresh\" content=\"15;URL=/\">Update FAILED, rebooting...\n";
//------------------------------------------------------------------
void handleSettings(){
int hasargs=0;
int reset_ESP=0;
if ( server.hasArg("json") ){
String output = "{";
//nonsense data
output += "\"currentStation\" : \"";
output += stations[ getStation() ].name;
output += "\"";
output += ",\"currentVolume\" : ";
output += getVolume();
output += "}" ;
server.send(200, "text/json", output);
}
if ( ! hasargs ){
handleFileRead( "/settings.html" );
}else{
handleFileRead( "/settings.html" );
}
}
//------------------------------------------------------------------
void handleDel(){
int i, return_status = 400,rc;
char message[80];
if ( !server.hasArg("name") || !server.hasArg("index") ){
sprintf( message, "Error: del host needs ?name=xx&index=xx" );
server.send( return_status, "text/plain", message);
return;
}
rc = del_station( (char *)server.arg("name").c_str(),
server.arg("index").toInt() );
if ( rc ){
sprintf( message, "Error: Station \"%s\" with index %d not found", server.arg("name").c_str(), server.arg("index").toInt() );
Serial.println( message );
}else{
save_stations();
return_status = 200;
read_stations();
sprintf( message,"Deleted station %s", server.arg("name") );
}
server.send( return_status, "text/plain", message);
}
//------------------------------------------------------------------
void handleAdd(){
int return_status = 400,rc;
char message[80];
if ( !server.hasArg("name") || !server.hasArg("host") || !server.hasArg("path") || !server.hasArg("port") || !server.hasArg("idx") || !server.hasArg("protocol") ){
sprintf( message, "Error: add host needs ?host=xx&name=xx&path=xx&port=xx&idx=xx&protocol=xxx" );
server.send( return_status, "text/plain", message);
return;
}
if ( server.arg("idx").toInt() == -1 ){
rc = add_station( (char *)server.arg("name").c_str(),
server.arg("protocol").toInt(),
(char *)server.arg("host").c_str(),
(char *)server.arg("path").c_str(),
server.arg("port").toInt() );
}else{
int idx = server.arg("idx").toInt();
rc = change_station( (char *)server.arg("name").c_str(),
server.arg("protocol").toInt(),
(char *)server.arg("host").c_str(),
(char *)server.arg("path").c_str(),
server.arg("port").toInt(),
idx );
Serial.printf( "- Changed station %d to : name %s, h %s p %d path %s\n", idx, stations[idx].name, stations[idx].host, stations[idx].port, stations[idx].path);
}
if ( rc ){
sprintf( message, "Error: No more stations can be added" );
}else{
save_stations();
return_status = 200;
sprintf( message,"Added station %s", server.arg("name") );
}
server.send( return_status, "text/plain", message);
}
//------------------------------------------------------------------
void handleSet(){
int return_status = 400;
char message[80];
if ( server.hasArg("volume") ){
int desired_volume = server.arg("volume").toInt();
if ( desired_volume >= 0 && desired_volume <= 100 ){
return_status = 200;
sprintf( message,"Volume set to %d", desired_volume );
setVolume( desired_volume );
}else{
sprintf( message,"Volume requested %d, but value must be between 0 and 100", desired_volume);
}
}
if ( server.hasArg("station") ){
int desired_station = server.arg("station").toInt();
if ( desired_station < STATIONSSIZE && desired_station >= 0 && stations[ desired_station ].status == 1 ){
return_status = 200;
if( desired_station != getStation() ) setStation( desired_station, -1 );
sprintf( message,"Station set to %d, %s", desired_station, stations [ desired_station].name );
}else{
sprintf( message,"Station %d does not exist", desired_station);
}
}
server.send( return_status, "text/plain", message);
}
//------------------------------------------------------------------
int dossdp=0;
int uploadThreshold=0;
void handleWebServer( void *param ){
Serial.printf("WebServer running on core %d\n", xPortGetCoreID());
//
//https://github.com/espressif/arduino-esp32/issues/595
//
TIMERG0.wdt_wprotect=TIMG_WDT_WKEY_VALUE;
TIMERG0.wdt_feed=1;
TIMERG0.wdt_wprotect=0;
#ifdef USESSDP
setupSSDP();
#else
MDNS.begin( APNAME);
#endif
server.on("/", []() {
handleFileRead( "/index.html" );
});
server.on("/set", handleSet );
server.on("/add", handleAdd );
server.on("/del", handleDel );
server.on("/upload", HTTP_GET, []() {
if(!handleFileRead("/upload.html")) server.send(404, "text/plain", "FileNotFound");
});
//server.on("/upload", HTTP_POST, handleFileUpload);
server.on("/upload", HTTP_POST, [](){ handleFileRead("/upload.html"); }, handleFileUpload);
server.on("/reset", HTTP_GET, []() {
server.send(200, "text/plain", "Doej!");
delay(20);
ESP.restart();
});
server.on( "/list",handleFileList);
server.on( "/delete",handleFileDelete);
server.on ("/status", send_json_status );
server.on ("/settings", handleSettings );
server.on("/update", HTTP_GET, []() {
server.sendHeader("Connection", "close");
server.send(200, "text/html", serverIndex);
});
//handling uploading firmware file
server.on("/update", HTTP_POST, []() {
server.sendHeader("Connection", "close");
server.send((Update.hasError())?400:200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
delay(20);
ESP.restart();
}, []() {
HTTPUpload& upload = server.upload();
if (upload.status == UPLOAD_FILE_START) {
dossdp = -30000;
xSemaphoreTake( updateSemaphore, portMAX_DELAY);
uploadThreshold = 10000;
tft_ShowUpload( "firmware" );
Serial.printf("Update: %s\n", upload.filename.c_str());
syslog("Installing new firmware through webupload" );
if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size
Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_WRITE) {
// flashing firmware to ESP
delay(1);
if ( upload.totalSize > uploadThreshold ){
if ( (upload.totalSize/10000) % 10 == 0 )Serial.printf("%d ", upload.totalSize/10000 );
tft_uploadProgress( upload.totalSize/10000 );
uploadThreshold += 10000;
}
if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_END) {
xSemaphoreGive( updateSemaphore);
if (Update.end(true)) { //true to set the size to the current progress
tft_uploadEnd( "success");
Serial.printf("\nUpdate Success: written %u bytes.\nRebooting...\n", upload.totalSize);
server.send(200, "text/html", successResponse);
} else {
tft_uploadEnd( "failed");
Update.printError(Serial);
Serial.printf("\n");
server.send(500, "text/html", failResponse );
}
}
});
server.onNotFound([](){
server.sendHeader("Connection", "close");
if(!handleFileRead(server.uri()))
server.send(404, "text/plain", "FileNotFound");
});
server.begin();
#ifndef USESSDP
MDNS.addService("http", "tcp", 80);
#endif
if ( param == NULL ){
dossdp= 0;
int timecount=0, oldmin=987;
time_t rawt;
struct tm tinfo;
while(1){
server.handleClient();
#ifdef USESSDP
++dossdp;
if ( dossdp >= 40 ){
SSDPDevice.handleClient();
dossdp = 0;
}
#endif
#ifdef USEOTA
ArduinoOTA.handle();
#endif
if ( millis() > timecount ){
time( &rawt );
localtime_r( &rawt, &tinfo);
if ( oldmin != tinfo.tm_min ){
oldmin = tinfo.tm_min;
showClock(tinfo.tm_hour, tinfo.tm_min);
showBattery();
}
timecount = millis() + (10*1000);
}
delay(20);
}
}
}
//------------------------------------------------------------------
void setupWebServer(){
xTaskCreatePinnedToCore(
handleWebServer, // Task to handle special functions.
"WebServer", // name of task.
1024*8, // Stack size of task
NULL, // parameter of the task
WEBSERVERTASKPRIO, // priority of the task
&webserverTask, // Task handle to keep track of created task
WEBCORE ); //core to run it on
}
<file_sep>
void play ( void *param ){
uint8_t playBuffer[32];
Serial.printf("Playtask running on core %d\n", xPortGetCoreID());
//
//https://github.com/espressif/arduino-esp32/issues/595
//
TIMERG0.wdt_wprotect=TIMG_WDT_WKEY_VALUE;
TIMERG0.wdt_feed=1;
TIMERG0.wdt_wprotect=0;
player.startSong();
while ( uxQueueMessagesWaiting(playQueue) < (PLAYQUEUESIZE/2) ) delay(5);
while(1){
xQueueReceive(playQueue, &playBuffer[0], portMAX_DELAY);
if ( strncmp( (char *) &playBuffer[0], "ChangeStationSoStartANewSongNow!",32) == 0 ){
player.stopSong();
delay(5);
player.startSong();
xQueueReceive(playQueue, &playBuffer[0], portMAX_DELAY);
}
for ( int i = 0; i < 1 ; ++i ){
if ( digitalRead( VS1053_DREQ ) ){
xSemaphoreTake( tftSemaphore, portMAX_DELAY);
player.playChunk(playBuffer, 32 );
xSemaphoreGive( tftSemaphore);
}else{
--i;
//Serial.printf ( "Waiting for VS1053, %d messages in playQueue\n", uxQueueMessagesWaiting( playQueue ) );
delay(1);
}
}
}
}
/*--------------------------------------------------*/
int play_init(){
xTaskCreatePinnedToCore(
play, // Task to handle special functions.
"Player", // name of task.
2048, // Stack size of task
NULL, // parameter of the task
PLAYTASKPRIO, // priority of the task
&playTask, // Task handle to keep track of created task
PLAYCORE); // processor core
return(0);
}
<file_sep>
//-----------------------------------------------------
char * ps_strndup (const char *s, size_t n)
{
size_t len = strnlen (s, n);
char *newstring = (char *) ps_malloc (len + 1);
if (newstring == NULL)return NULL;
newstring[len] = '\0';
return (char *) memcpy (newstring, s, len);
}
//-----------------------------------------------------
char * ps_strdup (const char *s)
{
size_t len = strlen (s) + 1;
void *newstring = ps_malloc (len);
if (newstring == NULL)return NULL;
return (char *) memcpy (newstring, s, len);
}
//-----------------------------------------------------
int change_station( char *name, int protocol, char *host, char* path, int port, int idx ){
if ( stations[idx].status == 1 ){
Serial.printf( "Changing station %d to : name %s, h %s p %d path %s\n", idx,name, host, port, path);
free( stations[idx].name );
free( stations[idx].host );
free( stations[idx].path );
stations[idx].name = ps_strdup( name);
stations[idx].host = ps_strdup( host);
stations[idx].path = ps_strdup( path);
stations[idx].protocol = protocol;
stations[idx].port = port;
stations[idx].position = 0;
}else{
Serial.printf( "station %d not changed\n",idx);
}
return(0);
}
//-----------------------------------------------------
int add_station( char *name, int protocol, char *host, char* path, int port ){
int i;
for ( i = 0; i< STATIONSSIZE; ++i ){
if ( stations[i].status == 0 ){
stations[i].name = ps_strdup( name);
stations[i].host = ps_strdup( host);
stations[i].path = ps_strdup( path);
stations[i].port = port;
stations[i].protocol = protocol;
stations[i].position = 0;
stations[i].status = 1;
break;
}
}
if ( i == STATIONSSIZE ) return(1);
stationCount++;
return(0);
}
//-----------------------------------------------------
int del_station( char *name, int index ){
int i;
Serial.printf("Trying to delete station [%s], index %d]\n", name, index);
for ( i = 0; i< STATIONSSIZE; ++i ){
if ( stations[i].name != NULL ){
Serial.printf("Found station [%s], i %d]\n", stations[i].name, i);
}
if ( i == index && stations[i].status ){
if ( strcmp( stations[i].name, name ) == 0 ){
stations[i].status = 0;
break;
}
}
}
if ( i == STATIONSSIZE ) return(1);
Serial.printf("Deleted station [%s], index %d]\n", name, index);
stationCount--;
return(0);
}
//-----------------------------------------------------
void stationsInit(){
stations = (Station *) ps_calloc( STATIONSSIZE,sizeof(Station) );
/*
add_station("NPO Radio 1","icecast.omroep.nl","/radio1-bb-mp3",80);
add_station("NPO Radio 2","icecast.omroep.nl","/radio2-bb-mp3",80);
add_station("NPO 3fm","icecast.omroep.nl","/3fm-bb-mp3",80);
add_station("NPO Radio 4","icecast.omroep.nl","/radio4-bb-mp3",80);
add_station("NPO Radio 5","icecast.omroep.nl","/radio5-bb-mp3",80);
add_station("NPO Radio 6","icecast.omroep.nl","/radio6-bb-mp3",80);
add_station("Cncrt Jazz","streams.greenhost.nl","/jazz",8080);
add_station("Cncrt Hardbop","streams.greenhost.nl","/hardbop",8080);
add_station("BBC 1","bbcmedia.ic.llnwd.net","/stream/bbcmedia_radio1_mf_q",80);
add_station("BBC 2","bbcmedia.ic.llnwd.net","/stream/bbcmedia_radio2_mf_q",80);
add_station("BBC 3","bbcmedia.ic.llnwd.net","/stream/bbcmedia_radio3_mf_q",80);
add_station("BBC 4","bbcmedia.ic.llnwd.net","/stream/bbcmedia_radio4fm_mf_q",80);
add_station("BBC 1xtra","bbcmedia.ic.llnwd.net","/stream/bbcmedia_radio1xtra_mf_p",80);
*/
read_stations();
}
//-----------------------------------------------------
int read_header( int stationIdx){
char line[1024];
char *s = line,*t, lastchar='x';
int rc=0,http_status=0;
bool acceptrange=false;
Serial.printf("Reading header\n");
stationChunked = false;
stationClose = true;
for(;;){
//read a line
for(line[0] = 0, s = line, lastchar=0; s - line < 1024; ++s ){
rc = radioclient->read( (uint8_t *)s, 1 );
if ( *s == '\n' && lastchar == '\r' ){
*(s-1) = 0;
break;
}
lastchar = *s;
}
Serial.printf("%s\n", line);
if ( line[0] == 0 ){
return( http_status); // end of header
}
//get HTTP status
if ( strncasecmp( line, "HTTP", 4) == 0 || strncasecmp( line, "ICY ", 4) == 0 ){
for( s = line; *s != ' '; ++s);
++s; t = s;
for( ; *s != ' '; ++s);
*s = 0;
http_status = atoi( t );
Serial.printf("http_status %d\n", http_status );
//if ( http_status == 200 )return(http_status);
//if( http_status >= 400 ) return(http_status);
}
if ( strncasecmp(line,"Transfer-Encoding:", 18) == 0 ){
for( s = line; *s != ' '; ++s);
++s;
if ( 0 == strcmp(s, "chunked") ){
stationChunked = true;
}
}
if ( strncasecmp(line,"Accept-Ranges: bytes",20) == 0 ){
acceptrange = true;
}
if ( strncasecmp(line,"Content-Length:", 15) == 0 && acceptrange){
for( s = line; !isdigit(*s); ++s);
//contentsize = atoi( s );
}
if ( strncasecmp( line, "Connection:",11) == 0 ){
for( s = line; *s != ' '; ++s);
++s;
if ( 0 == strncasecmp(s, "keep-alive", 10) ){
stationClose = false;
}
}
if ( strncasecmp( line, "Location:", 9) == 0 ){
for( s = line; *s != ' '; ++s);
++s;
stations[ stationIdx].protocol = 0;
if ( strncasecmp( s, "https:", 6) == 0) stations[ stationIdx].protocol = 1;
for( ; *s != '/'; ++s);
++s;++s;
t = s;
for( ; *s != '/' && *s != ':'; ++s);
lastchar = *s;
*s = 0;
Serial.printf("host %s\n", t );
free( stations[ stationIdx].host );
stations[stationIdx].host = ps_strdup( t );
Serial.printf("hostidx %s\n", stations[stationIdx].host );
if( lastchar == ':' ){
++s;
t = s;
for( ; *s != '/'; ++s);
*s = 0;
stations[ stationIdx].port = atoi( t );
*s = '/';
}else if( lastchar == '/' ){
*s = '/';
}
free( stations[ stationIdx].path );
stations[ stationIdx].path = ps_strdup( s );
Serial.printf("Redirecting to %s host %s, port %d, path %s\n", stations[ stationIdx].protocol?"https:":"http:",stations[ stationIdx].host, stations[ stationIdx].port, stations[ stationIdx].path );
return( http_status );
}
}
return(0);
}
//-----------------------------------------------------
int justConnect( int stationIdx ){
Serial.println("Connect");
if ( radioclient->connected() ){
//radioclient->flush();
radioclient->stop();
}
Serial.print("connecting to "); Serial.println(stations[stationIdx].host);
radioclient = &iclient;
#ifdef USETLS
if ( stations[stationIdx].protocol == 1 ){
// TLS by not setting //radioclient -> setCACert(rootCACertificate); no certificates are checked.
radioclient = &sclient;
}
#endif
if (!radioclient->connect( stations[stationIdx].host, stations[stationIdx].port) ) {
Serial.println("Connection failed");
return(1);
}
Serial.printf("Connected via %s, send GET\n",radioclient == &iclient? "http":"https");
radioclient->setTimeout(1);
//if ( contentsize == 0 ){
Serial.print(String("GET ") + stations[stationIdx].path + " HTTP/1.1\r\n" +
"Host: " + stations[stationIdx].host + "\r\n" +
"User-Agent: "+ APNAME +" "+ APVERSION + "\r\n" +
"Accept: */*" + "\r\n" +
"Connection: close\r\n\r\n");
radioclient->print(String("GET ") + stations[stationIdx].path + " HTTP/1.1\r\n" +
"Host: " + stations[stationIdx].host + "\r\n" +
"User-Agent: "+ APNAME +" "+ APVERSION + "\r\n" +
"Accept: */*" + "\r\n" +
"Connection: close\r\n\r\n");
// }else{
// Serial.print(String("GET ") + stations[stationIdx].path + " HTTP/1.1\r\n" +
// "Host: " + stations[stationIdx].host + "\r\n" +
// "User-Agent: "+ APNAME +" "+ APVERSION + "\r\n" +
//
// //"Accept: */*" + "\r\n" +
// "Range: bytes=" + stations[stationIdx].position + "-" + (contentsize - 1 - stations[stationIdx].position) + "\r\n" +
// "Connection: close\r\n\r\n");
//
// radioclient->print(String("GET ") + stations[stationIdx].path + " HTTP/1.1\r\n" +
// "Host: " + stations[stationIdx].host + "\r\n" +
// "User-Agent: "+ APNAME +" "+ APVERSION + "\r\n" +
//
// //"Accept: */*" + "\r\n" +
// "Range: bytes=" + stations[stationIdx].position + "-" + (contentsize - 1 - stations[stationIdx].position) + "\r\n" +
// "Connection: close\r\n\r\n");
//}
return(0);
}
//-----------------------------------------------------
int stationsConnect(int stationIdx){
int i,j,rc;
if ( stations[stationIdx].status == 0 ) stationIdx = 0;
contentsize = 0;
for( j = 0; j < 4 ; ++j ){
rc = justConnect( stationIdx );
if ( rc != 0) {
Serial.printf( "Error, justConnect returned %d\n", rc);
return(rc);
}else{
Serial.printf( "justConnect ok, returned %d\n", rc);
}
for( i = 0; i < 200; ++i ){
if ( radioclient->available() > 0 ){
rc = read_header( stationIdx );
Serial.printf( "read_header returned %d, %s , %s\n", rc, stationChunked?"chunked":"stream", stationClose?"HTTP Close":"HTTP Keep-alive" );
if ( rc > 300 && rc < 309 ){
Serial.printf( "Retry connect but now to %s\n", stations[stationIdx].host);
break;
}
if ( contentsize != 0 && rc == 200 ){
if ( stations[stationIdx].position >= contentsize -1 )stations[stationIdx].position = 0;
break;
}
if ( rc >= 400 && rc < 409 ){
return(400);
}
if ( rc != 200 && rc != 206 ) return(4);
setStation( stationIdx, -1 );
Serial.printf("Now start listening to %s\n", stations[stationIdx].name );
tft_showstation(stationIdx);
return(0);
}
Serial.print(".");
delay(10);
}
if ( i == 200 ){
Serial.println("didn't receive any data in 2 seconds");
radioclient->flush();
radioclient->stop();
return(2);
}
Serial.printf("Next Connect loop\n");
}
return(3);
}
//-----------------------------------------------------
int get_last_volstat(int volstat){
FILE *last=NULL;
char buffer[8];
int idx;
switch( volstat ){
case 0:
last = fopen( "/spiffs/last_station.txt", "r");
break;
case 1:
last = fopen( "/spiffs/last_volume.txt", "r");
break;
}
if ( last == NULL) {
Serial.printf("Couldn't open /spiffs/last_%s.txt\n", volstat?"volume":"station" );
return( volstat?65:0);
}
fread( buffer,1, 8, last );
fclose(last);
idx = atoi( buffer);
if ( volstat == 0 ){
if ( idx <0 || idx >= stationCount ) idx = 0;
}
return( idx );
}
//-----------------------------------------------------
int save_last_volstat( int volstat){
FILE *last=NULL;
switch( volstat ){
case 0:
last = fopen( "/spiffs/last_station.txt", "w");
break;
case 1:
last = fopen( "/spiffs/last_volume.txt", "w");
break;
}
if ( last == NULL) {
Serial.printf("Couldn't open /last_%s.txt\n", volstat?"volume":"station" );
return(-1);
}
switch( volstat ){
case 0:
fprintf(last, "%d", getStation());
break;
case 1:
fprintf(last, "%d", getVolume() );
break;
}
fclose(last);
return(0);
}
//-----------------------------------------------------
int save_stations(){
FILE *uit;
int i, stations_written = 0;;
time_t ltime;
char timebuffer[32];
Serial.printf("Saving stations to /spiffs/stations.json\n");
time(<ime);
ctime_r( <ime, timebuffer);
timebuffer[24] = 0;
uit = fopen( "/spiffs/stations.json", "w");
if ( uit == NULL) {
Serial.printf("Couldn't open /spiffs/stations.json\n");
return(-1);
}
fprintf(uit, "{ \"date\" : \"%s\", \"stations\" : [", timebuffer );
for ( i = 0; i< STATIONSSIZE; ++i ){
if ( stations[i].status ){
if ( stations_written ) fprintf(uit,",");
fprintf(uit, "{ \"name\" : \"%s\", \"protocol\" : %d,\"host\" : \"%s\", \"path\" : \"%s\", \"port\" : %d, \"position\" : %d }",
stations[i].name,stations[i].protocol, stations[i].host,stations[i].path, stations[i].port, stations[i].position);
stations_written++;
}
}
fprintf(uit,"]}" );
fclose(uit);
Serial.printf("Saved stations to /spiffs/stations.json\n");
return(0);
}
//-----------------------------------------------------
void free_stations(){
int i;
for ( i = 0; i< STATIONSSIZE; ++i ){
if ( stations[i].status == 1 ){
free( stations[i].name);
free( stations[i].host);
free( stations[i].path);
stations[i].status = 0;
stations[i].protocol = 0;
stations[i].position = 0;
}
}
}
//-----------------------------------------------------
int fill_stations_from_file( char *fileBuffer, size_t bufferlen){
char *s=fileBuffer;
int mode=0;
char searchstring[32];
char *target, *source;
int stationidx=0, targetcount=0;
sprintf( searchstring,"\"name\"");
Serial.println("Loading stations");
for(; *s; ++s ){
switch( mode ){
case 0: // find name
if ( ! strncmp( s, searchstring, strlen(searchstring) )) {
s += strlen( searchstring );
mode = 1;
}
break;
case 1: // find start of value
if ( *s == '\"' )mode= 2;
if ( isdigit(*s)) {
source = s;
mode = 4;
}
break;
case 2:
source = s;
mode = 3;
break;
case 3:
if ( *s == '\"' ){
mode = 0;
switch( targetcount ){
case 0:
stations[stationidx].name = strndup( source, s-source);
Serial.printf("%d - %s\n", stationidx, stations[stationidx].name);
sprintf( searchstring,"\"protocol\"");
targetcount++;
break;
case 2:
stations[stationidx].host = strndup( source, s-source);
sprintf( searchstring,"\"path\"");
targetcount++;
break;
case 3:
stations[stationidx].path = strndup( source, s-source);
sprintf( searchstring,"\"port\"");
targetcount++;
break;
}
}
break;
case 4: // number
if (! isdigit( *s )){
*s = 0;
int value = atoi ( source );
switch( targetcount ){
case 1:
stations[stationidx].protocol = value;
sprintf( searchstring,"\"host\"");
targetcount++;
mode = 0;
break;
case 4:
stations[stationidx].port = value;
stations[stationidx].status = 1;
sprintf( searchstring,"\"position\"");
targetcount++;
mode = 0;
break;
case 5:
stations[stationidx].position = value;
targetcount = 0;
stationidx++;
sprintf( searchstring,"\"name\"");
mode = 0;
break;
}
}
break;
}
}
Serial.printf("\nFound %d stations\n", stationidx);
stationCount = stationidx;
}
//-----------------------------------------------------
int read_stations(){
FILE *in=NULL;
char *readBuffer;
size_t read_result;
struct stat sStat;
Serial.printf("Loading stations fromm /spiffs/stations.json\n");
if( stat("/spiffs/stations.json",&sStat) < 0){
Serial.printf("Couldn't find /spiffs/stations.json\n");
return(-3);
}
Serial.printf("Size of /spiffs/stations.json\t%d bytes\n",sStat.st_size);
readBuffer = (char *)ps_calloc( 1, sStat.st_size+4 );
if ( readBuffer == NULL ){
return(-2);
}
in = fopen( "/spiffs/stations.json", "r" );
if ( in == NULL ) {
return(-1);
}
free_stations();
read_result = fread( readBuffer, 1, sStat.st_size, in );
fclose(in);
Serial.printf("Read %d bytes from /spiffs/stations.json", read_result);
readBuffer[read_result] = 0;
fill_stations_from_file( readBuffer, read_result);
free( readBuffer );
return(0);
}
//-----------------------------------------------------
<file_sep>uint8_t ledlast_state = 255;
/*--------------------------------------------------------------------*/
void IRAM_ATTR gesture_found(){
int started=0;
if( ! digitalRead( GINTPIN ) ){
xTaskNotifyFromISR( gestureTask, 1 ,eSetValueWithOverwrite, &started);
if( started ){
portYIELD_FROM_ISR()
}
}
}
/*-------------------------------------------------------------------*/
void gesture_process( void *param){
uint8_t data = 0, data1 = 0, gerror;
uint32_t notify_value=0;
uint8_t state=99;
Serial.printf("Gesture running on core %d\n", xPortGetCoreID());
Wire.begin( GSDAPIN,GSCLPIN);
pinMode(GINTPIN,INPUT_PULLUP );
attachInterrupt( GINTPIN, gesture_found, CHANGE);
delay(3);
for( gerror = 1; gerror; delay(300) ){
gerror = paj7620Init(); // initialize Paj7620 registers
if (gerror) {
Serial.print("INIT ERROR,CODE:");
Serial.println(gerror);
tellPixels(9);
}else{
Serial.println("PAJ7620 Gesture init ok");
}
}
while(1){
Serial.println("Gesture read...");
xTaskNotifyWait(0,0,¬ify_value,portMAX_DELAY);
gerror = paj7620ReadReg(0x43, 1, &data ); // Read Bank_0_Reg_0x43/0x44 for gesture result.
if ( gerror ) { Serial.println("Error reading register 0x43"); continue;}
Serial.printf("data %02x - ", data);
switch (data) // When different gestures be detected, the variable 'data' will be set to different values by paj7620ReadReg(0x43, 1, &data).
{ // PAJ7620 is installed upside down. updown left and right are flipped
case GES_LEFT_FLAG:
Serial.print("Right\n");
tellPixels(2);
state = 1;
break;
case GES_RIGHT_FLAG:
Serial.print("Left\n");
tellPixels(3);
state = 0;
break;
case GES_UP_FLAG:
Serial.print("Down\n");
tellPixels(0);
state = 3;
break;
case GES_DOWN_FLAG:
Serial.print("Up\n");
tellPixels(9);
state = 2;
break;
case GES_FORWARD_FLAG:
Serial.print("Forward\n");
state = 4;
break;
case GES_BACKWARD_FLAG:
Serial.printf("Backward, last state = %d\n", ledlast_state);
state = 5;
if ( ledlast_state == 4 && gmode ){
state = 10; // forward backward
tellPixels(10);
Serial.print(" - Doej!\n");
}
break;
case GES_CLOCKWISE_FLAG:
Serial.print("Clockwise\n");
tellPixels(8);
state = 6;
break;
case GES_COUNT_CLOCKWISE_FLAG:
Serial.print("anti-clockwise\n");
tellPixels(16);
state = 7;
break;
default:
paj7620ReadReg(0x44, 1, &data1);
if (data1 == GES_WAVE_FLAG)
{
Serial.printf(" data1 %02x - wave\n", data1);
state = 8;
if ( getVolume() > 50 ){
tellPixels(11);
}else{
tellPixels(12);
}
if ( ledlast_state == 8 ){
state = 11; //two waves
}
}else{
Serial.print("funny gesture\n");
if ( data == 0xff ){
gerror = paj7620ReadReg(0x43, 1, &data); // Read Bank_0_Reg_0x43/0x44 for gesture result.
if ( gerror ) { Serial.println("Error readin regster 0x43"); continue;}
gerror = paj7620ReadReg(0x43, 1, &data); // Read Bank_0_Reg_0x43/0x44 for gesture result.
if ( gerror ) { Serial.println("Error readin regster 0x43"); continue;}
}
state = 9;
}
break;
}
if ( state != 9 ){
ledlast_state = state;
}
}
}
/*--------------------------------------------------*/
int gesture_init(){
initPixels();
xTaskCreatePinnedToCore(
gesture_process, // Task to handle special functions.
"Gesture", // name of task.
2048+1024, // Stack size of task
NULL, // parameter of the task
GESTURETASKPRIO, // priority of the task
&gestureTask, // Task handle to keep track of created task
GESTURECORE ); // processor core
return(0);
}
<file_sep>
#undef SNTP_MAIN
#include <wificredentials.h>
// in wificredentials the following are define:
// char* ntpServers[] = { "nl.pool.ntp.org", "be.pool.ntp.org", "de.pool.ntp.org"};
// const char* ntpTimezone = "CET-1CEST,M3.5.0/2,M10.5.0/3";
// const char* wifiSsid = "yourssid";
// const char* wifiPassword = "<PASSWORD>";
#include "WiFi.h"
#include "time.h"
#include "lwip/err.h"
#include "lwip/apps/sntp.h"
/*----------------------------------------------------------------*/
int time_to_jurassic(void )
{
int result;
time_t new_time;
struct tm trex;
struct timeval ptero;
trex.tm_sec =0;
trex.tm_min =0;
trex.tm_hour=0;
trex.tm_mday=30;
trex.tm_mon =8;
trex.tm_year=1993-1900; // set time to release date of Jurassic Park
new_time=mktime(&trex);
ptero.tv_sec =new_time;
ptero.tv_usec=0;
result=settimeofday(&ptero,NULL);
return result;
}
/*--------------------------------------------------------------*/
void ntp_waitforsync(){
time_t rawt;
struct tm *tinfo;
struct tm linfo, ginfo;
int y;
for(;;){
time( &rawt );
tinfo = localtime( &rawt );
Serial.printf( "Waiting for ntp sync, time is now " );
Serial.print(ctime(&rawt));
y = tinfo->tm_year + 1900;
if ( y > 2000 ) break;
delay(500);
}
gmtime_r( &rawt, &ginfo);
localtime_r( &rawt, &linfo);
//Serial.printf(" localtime hour %d\n", linfo.tm_hour);
//Serial.printf(" gmtime hour %d\n", ginfo.tm_hour);
time_t g = mktime(&ginfo);
time_t l = mktime(&linfo);
double offsetSeconds = difftime( l, g );
int offsetHours = (int)offsetSeconds /(60*60);
//Assuming DST is always + 1 hour, which apparently is not always true.
Serial.printf("Timezone offset is %d hour%s, %s, current offset is %d hour%s\n\n",
offsetHours,
(offsetHours>1 || offsetHours < -1)?"s":"",
linfo.tm_isdst?"DST in effect": "DST not in effect",
linfo.tm_isdst?offsetHours+1:offsetHours,
( (offsetHours+1)>1 || (offsetHours+1) < -1)?"s":"");
}
/*--------------------------------------------------------------*/
void ntp_setup(bool waitforsync){
// sometimes the esp boots with a time in the future. This defeats the
// test. The settimeofday_cb function is not available on the ESP32 AFAIK
if ( waitforsync && time_to_jurassic() ) Serial.println( "Error setting time to long long ago");
// set timezone
setenv( "TZ" , ntpTimezone, 1);
tzset();
// configTime on the ESP32 does not honor the TZ env, unlike the ESP8266
sntp_stop();
sntp_setoperatingmode(SNTP_OPMODE_POLL);
sntp_setservername(0, ntpServers[0]);
sntp_setservername(1, ntpServers[1]);
sntp_setservername(2, ntpServers[2]);
sntp_init();
// A new NTP request will be done every hour (hopefully, to be verified
// with tcpdump one day.
if( waitforsync )ntp_waitforsync();
}
/*----------------------------------------------------------------*/
void tellTime(){
time_t now;
now = time(nullptr);
Serial.printf(" localtime : %s", asctime( localtime(&now) ) );
Serial.printf(" gmtime : %s\n", asctime( gmtime(&now) ) );
}
/*----------------------------------------------------------------*/
#ifdef SNTP_MAIN
void setup() {
Serial.begin(115200);
Serial.printf("Connecting to %s ", ssid);
WiFi.setHostname("simplesntp_esp32");
WiFi.begin(wifiSsid, wifiPassword);
for (int wifipoll = 0; WiFi.status() != WL_CONNECTED; ++wifipoll) {
delay(500);
Serial.print(".");
if ( wifipoll%10 == 0 ){
WiFi.begin(wifiSsid, wifiPassword);
}
}
Serial.println(" CONNECTED ");
Serial.print("IP address = ");
Serial.println(WiFi.localIP());
ntp_setup( true );
}
void loop() {
delay(50000);
tellTime();
// put your main code here, to run repeatedly:
}
#endif
<file_sep>
// Oranje radio
// <NAME>, 2019
// public domain
#undef USESSDP
#undef USEOTA
#undef USETLS
//tft
#define TFT_CS 4
#define TFT_RST 14 // you can also connect this to the Arduino reset
#define TFT_DC 13
#include "soc/timer_group_struct.h"
#include "soc/timer_group_reg.h"
#include <freertos/queue.h>
#include <freertos/task.h>
#include <freertos/portmacro.h>
#include <freertos/semphr.h>
#include <SPI.h>
#include <VS1053.h>
#include <WiFi.h>
#include <WiFiManager.h>
#include "FS.h"
#include "SPIFFS.h"
#include <WiFiClient.h>
#ifdef USETLS
#include <WiFiClientSecure.h>
#endif
#include <WebServer.h>
#ifdef USEOTA
#include <ArduinoOTA.h>
#endif
//E][WiFiUdp.cpp:219] parsePacket(): could not receive data: 9
//WIFI_STATIC_RX_BUFFER_NUM=10
//CONFIG_ESP32_WIFI_DYNAMIC_RX_BUFFER_NUM 32
//CONFIG_ESP32_WIFI_RX_BA_WIN 6
//...Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.3-rc1\tools\sdk\include\config\\sdkconfig.h
//https://github.com/espressif/esp-idf/issues/3646
#ifdef USESSDP
#include <SSDPDevice.h>
#else
#include <ESPmDNS.h>
#endif
#include <Update.h>
#include <Wire.h>
#include "paj7620.h"
#include "sk.h"
#include <wificredentials.h>
#define FORMAT_SPIFFS_IF_FAILED true
WiFiClient *radioclient;
WiFiClient iclient;
#ifdef USETLS
WiFiClientSecure sclient;
#endif
int contentsize=0;
//hangdetection
#define MAXUNAVAILABLE 50000
int unavailablecount=0;
int failed_connects=0;
int disconnectcount=0;
int topunavailable=0;
//OTA password
#define APNAME "OranjeRadio"
#define APVERSION "V0.23"
#define APPAS "oranjeboven"
SemaphoreHandle_t staSemaphore;
SemaphoreHandle_t volSemaphore;
SemaphoreHandle_t tftSemaphore;
SemaphoreHandle_t updateSemaphore;
SemaphoreHandle_t scrollSemaphore;
SemaphoreHandle_t chooseSemaphore;
TaskHandle_t gestureTask;
TaskHandle_t pixelTask;
TaskHandle_t webserverTask;
TaskHandle_t radioTask;
TaskHandle_t playTask;
TaskHandle_t scrollTask;
#define WEBCORE 0
#define RADIOCORE 1
#define GESTURECORE 1
#define PLAYCORE 1
#define PIXELTASKPRIO 3
#define GESTURETASKPRIO 7
#define RADIOTASKPRIO 6
#define PLAYTASKPRIO 5
#define WEBSERVERTASKPRIO 7
#define SCROLLTASKPRIO 4
QueueHandle_t playQueue;
#define PLAYQUEUESIZE 512
// stations
typedef struct {
char *name;
int protocol;
char *host;
char *path;
int port;
int status;
unsigned int position;
}Station;
#define STATIONSSIZE 100
Station *stations; //= (Station *) ps_malloc( STATIONSSIZE * sizeof(Station *) );
static volatile int currentStation;
static volatile int stationCount;
int playingStation = -1;
int chosenStation = 0;
int scrollStation = -1;
int scrollDirection;
// neopixel
#define NEOPIN 32
#define NEONUMBER 10
sk gstrip;
//gesture sensor
#define GSDAPIN 27
#define GSCLPIN 26
#define GINTPIN 25
int gmode;
//tft
#define SCROLLUP 0
#define SCROLLDOWN 1
// webserver
WebServer server(80);
//battery
float batvolt = 0.0;
#define BATPIN 36
//vs1053
#define VS1053_CS 5
#define VS1053_DCS 15
#define VS1053_DREQ 22
#define VS1053_RST 21
// Default volume
int currentVolume=65;
VS1053 player(VS1053_CS, VS1053_DCS, VS1053_DREQ);
bool stationChunked = false;
bool stationClose = false;
//pixels and gestures
/*------------------------------------------------------*/
#ifdef USEOTA
void initOTA( char *apname, char *appass){
// Port defaults to 8266
// ArduinoOTA.setPort(8266);
// Hostname defaults to esp8266-[ChipID]
ArduinoOTA.setHostname(apname);
// No authentication by default
ArduinoOTA.setPassword( appass );
// Password can be set with it's md5 value as well
// MD5(admin) = <PASSWORD>a5<PASSWORD>
// ArduinoOTA.setPasswordHash("<PASSWORD>");
ArduinoOTA.onStart([]() {
String type;
xSemaphoreTake( updateSemaphore, portMAX_DELAY);
if (ArduinoOTA.getCommand() == U_FLASH) {
type = "Firmware";
syslog("Installing new firmware over ArduinoOTA");
} else { // U_SPIFFS
type = "filesystem";
SPIFFS.end();
}
// NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
Serial.println("Start updating " + type);
tft_ShowUpload( type );
});
ArduinoOTA.onEnd([]() {
xSemaphoreGive( updateSemaphore);
tft_uploadEnd( "success");
Serial.println("\nEnd");
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
//Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
tft_uploadProgress( (progress / (total / 100)) );
});
ArduinoOTA.onError([](ota_error_t error) {
//tft_uploadEnd("failed");
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) {
tft_uploadEnd("Auth failed");
Serial.println("Auth Failed");
} else if (error == OTA_BEGIN_ERROR) {
tft_uploadEnd("Begin failed");
Serial.println("Begin Failed");
} else if (error == OTA_CONNECT_ERROR) {
tft_uploadEnd("Connect failed");
Serial.println("Connect Failed");
} else if (error == OTA_RECEIVE_ERROR) {
tft_uploadEnd("Receive failed");
Serial.println("Receive Failed");
} else if (error == OTA_END_ERROR) {
tft_uploadEnd("End failed");
Serial.println("End Failed");
}
});
ArduinoOTA.begin();
}
#endif
/*-----------------------------------------------------------*/
void getWiFi( char *apname, char *appass){
//WiFiManager, Local intialization. Once its business is done, there is no need to keep it around
WiFiManager wm;
// Workaround for esp32 failing to set hostname as found here: https://github.com/espressif/arduino-esp32/issues/2537#issuecomment-508558849
// for some reason it does not work here,although it does in th Basic example
Serial.printf("1-config 0 and set hostname to %s\n", apname);
WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE);
WiFi.setHostname( apname );
wm.setHostname( apname );// This only partially works in setting the mDNS hostname
wm.setAPCallback( tft_NoConnect );
wm.setConnectTimeout(20);
//reset settings - wipe credentials for testing
//wm.resetSettings();
// Automatically connect using saved credentials,
// if connection fails, it starts an access point with the specified name ( apname ),
// if empty will auto generate SSID, if password is blank it will be anonymous AP (wm.autoConnect())
// then goes into a blocking loop awaiting configuration and will return success result
bool res;
res = wm.autoConnect( apname, appass ); // anonymous ap
if(!res) {
Serial.println("Failed to connect");
ESP.restart();
}
else {
//if you get here you have connected to the WiFi
Serial.println("Wifi CONNECTED");
ntp_setup( true );
}
Serial.print("IP address = ");
Serial.println(WiFi.localIP());
#ifdef USEOTA
initOTA( apname, appass );
#endif
}
/*----------------------------------------------------------*/
void setup () {
Serial.begin(115200);
Serial.printf("\n%s %s %s %s\n", APNAME, APVERSION, __DATE__, __TIME__);
// Enable WDT
enableCore0WDT();
enableCore1WDT();
TIMERG0.wdt_wprotect=TIMG_WDT_WKEY_VALUE;
TIMERG0.wdt_feed=1;
TIMERG0.wdt_wprotect=0;
Serial.println("SPI begin...");
SPI.begin();
//unreset the VS1053
pinMode( VS1053_RST , OUTPUT);
digitalWrite( VS1053_RST , LOW);
delay( 200);
digitalWrite( VS1053_RST , HIGH);
Serial.println("Creating semaphores...");
staSemaphore = xSemaphoreCreateMutex();
volSemaphore = xSemaphoreCreateMutex();
tftSemaphore = xSemaphoreCreateMutex();
updateSemaphore = xSemaphoreCreateMutex();
scrollSemaphore = xSemaphoreCreateMutex();
chooseSemaphore = xSemaphoreCreateMutex();
Serial.println("Take sta semaphore...");
xSemaphoreTake(staSemaphore, 10);
xSemaphoreGive(staSemaphore);
Serial.println("Take vol semaphore...");
xSemaphoreTake(volSemaphore, 10);
xSemaphoreGive(volSemaphore);
Serial.println("Take tft semaphore...");
xSemaphoreTake(tftSemaphore, 10);
xSemaphoreGive(tftSemaphore);
Serial.println("Take update semaphore...");
xSemaphoreTake(updateSemaphore, 10);
xSemaphoreGive(updateSemaphore);
Serial.println("Create playQueue...");
playQueue = xQueueCreate( PLAYQUEUESIZE, 32);
Serial.println("Start File System...");
setupFS();
Serial.println("Gesture init");
if ( gesture_init() ) Serial.println ( "FAILED to init gesture control");
delay(200);
Serial.println("point radioclient to insecure WiFiclient");
radioclient = &iclient;
Serial.println("Getstations...");
stationsInit();
Serial.println("Start WiFi en web...");
getWiFi(APNAME,APPAS);
Serial.println("log boot");
syslog("Boot");
// Wait for VS1053 and PAM8403 to power up
// otherwise the system might not start up correctly
//delay(3000);
// already a delay in tft_init
// This can be set in the IDE no need for ext library
// system_update_cpu_freq(160);
Serial.println("player begin...");
player.begin();
Serial.println("Test VS1053 chip...");
while(1){
bool isconnected = player.isChipConnected();
Serial.printf( " Chip connected ? %s\n", isconnected?"true":"false");
if ( isconnected ) break;
delay(10);
}
Serial.println("not Switch to MP3...");
//player.switchToMp3Mode();
delay(100);
Serial.println("Apply patches to VS1053...");
patchVS1053();
Serial.println("Set volume and station...");
Serial.println("TFT init...");
tft_init();
delay(50);
Serial.println("Start WebServer...");
setupWebServer();
Serial.println("Start play task...");
play_init();
Serial.println("Start radio task...");
radio_init();
Serial.println("setup done...");
}
void loop(void){
vTaskDelete( NULL );
//ArduinoOTA.handle();
//server.handleClient();
//SSDPDevice.handleClient();
delay(100);
}
<file_sep>#include <TFT_eSPI.h> // Graphics and font library for ST7735 driver chip
TFT_eSPI tft = TFT_eSPI(); // Invoke library, pins defined in User_Setup.h
TFT_eSprite img = TFT_eSprite(&tft); // Create Sprite object "img" with pointer to "tft" object
TFT_eSprite bats = TFT_eSprite(&tft); // Create Sprite object "img" with pointer to "tft" object
TFT_eSprite vols = TFT_eSprite(&tft); // Create Sprite object "img" with pointer to "tft" object
TFT_eSprite clocks = TFT_eSprite(&tft); // Create Sprite object "img" with pointer to "tft" object
TFT_eSprite bmp = TFT_eSprite(&tft); // Create Sprite object "img" with pointer to "tft" object
#define BATVREF 1.1f
#define BATPINCOEF 1.95f // tune -6 db
#define BATDIV 5.54f // (1M + 220k )/220k
#define SCROLLPIN 0
#define STATIONSCROLLH 55
//----------------------------------------------------------
void IRAM_ATTR grabTft(){
//printf("grab TFT\n");
xSemaphoreTake( tftSemaphore, portMAX_DELAY);
//printf("grabbbed TFT\n");
}
//----------------------------------------------------------
void IRAM_ATTR releaseTft(){
//tft.fillRect( 4,12 , 1, 1, TFT_ORANGE ); //flicker kludge, not necessary after changing RMT_MEM_64 to RMT_MEM_384 in sk.h
xSemaphoreGive( tftSemaphore);
//printf("released TFT\n");
}
//----------------------------------------------------------
int read_battery(){
int i;
int batread=0, batotal=0;
for(i=0;i<5;i++){
batread = analogRead( BATPIN );
batotal += batread;
delay(50);
}
batread = batotal/5;
batvolt = ( BATVREF * ( batread * BATDIV)/4096)* BATPINCOEF;
Serial.printf( "read : %d, voltage: %f\n", batread, batvolt);
if ( batread > 1424 ) return(100);
if ( batread > 1404 ) return( 90);
if ( batread > 1362 ) return( 80);
if ( batread > 1345 ) return( 70);
if ( batread > 1321 ) return( 60);
if ( batread > 1300 ) return( 50);
if ( batread > 1280 ) return( 40);
if ( batread > 1262 ) return( 30);
if ( batread > 1242 ) return( 20);
if ( batread > 1220 ) return( 10);
return(0);
}
//-------------------------------------------------------------------------------
void showBattery(){
int w=23,h=12;
int xpos,ypos;
int percentage = read_battery();
bats.createSprite(23+2,h);
bats.setTextColor( TFT_WHITE, TFT_ORANGE);
bats.setTextSize(1);
bats.fillSprite(TFT_BLACK);
bats.fillRect( w, h/3, 2, h/3, TFT_ORANGE );//battery positive
bats.drawRoundRect( 0, 0, w , h, 2,TFT_ORANGE );//rectangle
bats.fillRect( 1, 1, w-2, h-2, TFT_BLACK );// inside
if ( percentage > 20 ){
bats.fillRect( 2, 2, 4, h-4, TFT_ORANGE );
}
if ( percentage > 40 ){
bats.fillRect( 2 + 5, 2, 4, h-4, TFT_ORANGE );
}
if ( percentage > 60 ){
bats.fillRect( 2 + 10, 2, 4, h-4, TFT_ORANGE );
}
if ( percentage > 80 ){
//printf(">80\n");
bats.fillRect( 2 + 15, 2, 4, h-4, TFT_ORANGE );
}
//tft.fillRect( w+2, h/2, 1, 1, TFT_ORANGE ); //flicker kludge
grabTft();
xpos = tft.width()/2 - (w+2)/2;
ypos = 2;
bats.pushSprite( xpos, ypos);
releaseTft();
bats.deleteSprite();
}
//----------------------------------------------------------
void showVolume( int percentage){
int w=30,h=10;
int xpos=2, ypos=1;
char pstring[8];
vols.createSprite(w + 21,h + 1);
vols.setTextColor( TFT_WHITE, TFT_ORANGE );
vols.setTextSize(1);
vols.fillSprite(TFT_BLACK);
sprintf( pstring,"%-3d", percentage);
vols.fillRect( 0, 1, w , h,TFT_ORANGE );//rectangle
vols.fillRect( 0, 0, w-1 , h, TFT_BLACK );//rectangle
vols.fillTriangle( 0, h, //lower left
(w * percentage)/100 - 1, h, //lower right
(w * percentage)/100 - 1, (h * (100-percentage))/100, //upper right
TFT_ORANGE );//rectangle
vols.setTextColor(TFT_ORANGE);
vols.fillRect( w +1, 1, 20 , h,TFT_BLACK );//rectangle
vols.drawString( pstring,w + 2, 2,1);
grabTft();
xpos = 2;
ypos = 2;
vols.pushSprite( xpos, ypos);
releaseTft();
vols.deleteSprite();
}
//--------------------------------------------------------------------------------------------------------
void showClock ( int hour, int min){
int clockx=110, clocky=1,w;
char tijd[8];
sprintf(tijd,"%d : %02d", hour, min);
w = tft.textWidth( tijd, 2 );
clocks.createSprite(w+20, 16);
clocks.setTextColor( TFT_GREEN, TFT_BLACK );
clocks.fillSprite(TFT_BLACK);
clocks.drawString( tijd,0, 0, 2);
grabTft();
clocks.pushSprite( clockx, clocky );
releaseTft();
clocks.deleteSprite();
}
//--------------------------------------------------------------------------------------------------------
//used for testing
/*
void IRAM_ATTR choose_scrollstation(){
int started=0;
if ( xSemaphoreTakeFromISR( chooseSemaphore, NULL ) == pdTRUE ){
chosenStation = 1;
xSemaphoreGiveFromISR( chooseSemaphore, &started );
if ( started ){
portYIELD_FROM_ISR()
}
}
}
*/
//--------------------------------------------------------------------------------------------------------
void tft_showstations( int stationIdx, int spritex){
int xpos, w = 0,f=4, halve;
char sname[80];
char *s, *word[2]={NULL,NULL};
strcpy( sname , stations[stationIdx].name);
halve = (img.width()/2);
if ( (w = img.textWidth(sname,4)) <= img.width() ){
w = img.textWidth( sname,4 );
xpos = halve - w/2;
img.drawString(sname, spritex+xpos, 22, 4);
}else{
word[0] = sname;
for( s = sname; *s && *s != ' '; ++s );
if ( *s ) word[1] = s + 1;
*s = 0;
if ( word[1] == NULL ){
w = img.textWidth( word[0], 2 );
xpos = halve - w/2;
img.drawString(word[0], spritex+xpos, img.height()/2 -4, 2 );
}else{
f = 4;
w = img.textWidth( word[0], f );
if ( w > 162 ) {
f = 2;
w = img.textWidth( word[0], f );
}
xpos = halve - w/2;
img.drawString(word[0], spritex+xpos, 3, f );
f = 4;
w = img.textWidth( word[1], f );
if ( w > 162 ) {
f = 2;
w = img.textWidth( word[1], f );
}
xpos = 80 - w/2;
img.drawString(word[1], spritex+xpos, 29, f );
}
}
}
//---------------------------------------------------------------------
void tft_showstation( int stationIdx){
img.createSprite(tft.width(), STATIONSCROLLH);
img.setTextColor( TFT_WHITE, TFT_BLACK );
img.setTextSize(1);
img.fillSprite(TFT_BLACK);
tft_showstations( stationIdx, 0);
grabTft();
img.pushSprite( 0, tft.height()-STATIONSCROLLH);
releaseTft();
img.deleteSprite();
}
//---------------------------------------------------------------------
void tft_scrollstations( void *param ){
int direction;
int t,begint, endt, inct, tcount;
int beginx, endx, incx;
int halve = (tft.width()/2);
int stopped =0;
int delaytime;
xSemaphoreTake( scrollSemaphore, portMAX_DELAY);
stopgTimer();
scrollStation = -1;
chosenStation = false;
begint = currentStation;
//pinMode( SCROLLPIN,INPUT_PULLUP );
//attachInterrupt( SCROLLPIN, choose_scrollstation, CHANGE);
direction = *((int *)param);
begint = currentStation;
endt = stationCount;
if( endt > 40 ) endt = 40;
img.createSprite(tft.width(), STATIONSCROLLH);
img.setTextColor( TFT_ORANGE, TFT_BLACK );
img.setTextSize(1);
if ( direction == SCROLLUP ){ //station increase, scroll right to left
inct = 1;
beginx = tft.width();
endx = ( -1*tft.width() );
incx = -20;
tcount = 0;
Serial.printf("scrollup\n");
}
if ( direction == SCROLLDOWN ){ //station increase, scroll right to left
inct = -1;
beginx = (-1*tft.width());
endx = tft.width() + 5;
incx = 20;
tcount = 0;
Serial.printf("scrolldown\n");
}
for ( t=begint; tcount < endt; t+= inct, tcount++ ){
//delaytime = (tcount*tcount*100/endt)+100;
delaytime = (tcount*tcount*100/endt)+300;
if ( direction == SCROLLUP )incx = tcount - endt;
if ( direction == SCROLLDOWN )incx = endt - tcount;
if ( t > (stationCount-1) ) t = 0;
if ( t < 0 ) t = (stationCount-1);
int z = t + inct;
if ( z > (stationCount-1) ) z = 0;
if ( z < 0 ) z = (stationCount-1);
for ( int x = 0, stopped=0;1; x += incx ){
//Serial.printf("%s incx %d x = %d endx %d \n", direction == SCROLLDOWN?"scrolldown":"scrollup", incx, x, endx );
if ( direction == SCROLLUP && x <= endx )break;
if ( direction == SCROLLDOWN && x >= endx )break;
img.fillSprite(TFT_BLACK);
tft_showstations( t, x );
if ( direction == SCROLLUP ){
tft_showstations( z, x + tft.width());
}else{
tft_showstations( z, x - tft.width());
img.drawFastVLine(0,0, img.height(), TFT_BLACK);//bug somewhere in lib or display
}
grabTft();
img.pushSprite( 0, tft.height()-STATIONSCROLLH );
releaseTft();
if ( stopped == 0 && x <= halve ){
scrollStation = t;
delay( delaytime );
stopped = 1;
if ( x == 0 && tcount == (endt-1) ) break;
xSemaphoreTake( chooseSemaphore, portMAX_DELAY);
if (chosenStation)break;
xSemaphoreGive( chooseSemaphore);
}
}//end for x loop
if (chosenStation){
if ( chosenStation == 2) tcount = endt; // abort
chosenStation = 0;
xSemaphoreGive( chooseSemaphore);
break;
}
delay(5);
}//end for t looop
img.deleteSprite();
if ( tcount < endt ){
setStation( t, -1 );
//currentStation = t;
//delay(4000);
}else{
tft_showstation( getStation() );
}
//detachInterrupt( SCROLLPIN );
scrollDirection = -1;
gmode = 2;
setgTimer();
xSemaphoreGive( scrollSemaphore);
vTaskDelete( NULL );
}
// -------------------------------------------------------------------------
void tft_scrollstation(int whatway){
xSemaphoreTake( scrollSemaphore, portMAX_DELAY);
scrollDirection = whatway;
Serial.printf("scroll %d %s\n", whatway, whatway?"from left to right":"from right to left" );
int rc = xTaskCreate(
tft_scrollstations, // Task to handle special functions.
"Scroll", // name of task.
32*1024, // Stack size of task
&scrollDirection, // parameter of the task
SCROLLTASKPRIO, // priority of the task
&scrollTask); // Task handle to keep track of created task
Serial.printf("xTaskCreate rc %d \n", rc);
delay(10);
xSemaphoreGive( scrollSemaphore);
}
//------------------------------------------------------
void tft_uploadProgress( int percent ){
int hi;
int percentage = percent;
if ( percentage > 100 ) percentage = 100;
hi = (tft.height() * percentage )/100;
grabTft();
tft.fillRect( tft.width() - 12, tft.height() - hi, 12, hi, TFT_YELLOW );
releaseTft();
}
//------------------------------------------------------
void tft_notAvailable( int stationIdx){
int w;
grabTft();
tft.fillRect(0,80, tft.width(), tft.height()-80, TFT_BLACK );
tft.setTextColor( TFT_RED, TFT_WHITE );
w = tft.textWidth( stations[stationIdx].name,2 );
tft.drawString( stations[stationIdx].name, 80-(w/2), 80, 2 );
w = tft.textWidth( "not available",2 );
tft.drawString( "not available", 80-(w/2), 94, 2 );
releaseTft();
}
//------------------------------------------------------
void tft_ShowUpload(String uploadtype){
grabTft();
tft.fillScreen(TFT_BLACK);
tft.setTextColor(TFT_WHITE );
tft.drawString( uploadtype, 10, 26, 4 );
tft.drawString( "upload", 10, 52, 4 );
tft.drawString( "in progress", 10, 78, 4 );
releaseTft();
}
//------------------------------------------------------
void tft_uploadEnd( String uploadstatus){
grabTft();
if ( uploadstatus.startsWith("s") ){
tft.fillScreen(TFT_WHITE);
tft.setTextColor( TFT_BLACK );
}else{
tft.fillScreen(TFT_GREEN);
tft.setTextColor( TFT_RED );
}
tft.drawString( "upload", 10, 52, 4 );
tft.drawString( uploadstatus, 10, 78, 4 );
releaseTft();
if ( ! uploadstatus.startsWith("s") ){
delay(5000);
ESP.restart();
}
}
//------------------------------------------------------
void tft_NoConnect( WiFiManager *wm) {
tft.setRotation(1);
tft.fillScreen(TFT_BLACK);
tft.setTextColor( TFT_WHITE );
tft.drawString( "Connect to network ", 10, 20, 2 );
tft.drawString( wm->getConfigPortalSSID(), 10, 34,4 );
tft.drawString( "WiFi password ", 10, 52, 2 );
tft.drawString( APPAS, 10, 66,4 );
tft.drawString( "Browse to", 10, 86,2 );
tft.drawString( "192.168.4.1", 10, 102,4 );
}
//------------------------------------------------------------------------------------------
// Bodmers BMP image rendering function
void drawBmp(const char *filename, int16_t x, int16_t y) {
if ((x >= tft.width()) || (y >= tft.height())) return;
fs::File bmpFS;
// Open requested file on SD card
bmpFS = SPIFFS.open(filename, "r");
if (!bmpFS)
{
Serial.print("File not found");
return;
}
uint32_t seekOffset;
uint16_t w, h, row, col;
uint8_t r, g, b;
uint32_t startTime = millis();
if (read16(bmpFS) == 0x4D42)
{
read32(bmpFS);
read32(bmpFS);
seekOffset = read32(bmpFS);
read32(bmpFS);
w = read32(bmpFS);
h = read32(bmpFS);
if ((read16(bmpFS) == 1) && (read16(bmpFS) == 24) && (read32(bmpFS) == 0))
{
y += h - 1;
tft.setSwapBytes(true);
bmpFS.seek(seekOffset);
uint16_t padding = (4 - ((w * 3) & 3)) & 3;
uint8_t lineBuffer[w * 3 + padding];
for (row = 0; row < h; row++) {
bmpFS.read(lineBuffer, sizeof(lineBuffer));
uint8_t* bptr = lineBuffer;
uint16_t* tptr = (uint16_t*)lineBuffer;
// Convert 24 to 16 bit colours
for (uint16_t col = 0; col < w; col++)
{
b = *bptr++;
g = *bptr++;
r = *bptr++;
*tptr++ = ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3);
}
// Push the pixel row to screen, pushImage will crop the line if needed
// y is decremented as the BMP image is drawn bottom up
grabTft();
tft.pushImage(x, y--, w, 1, (uint16_t*)lineBuffer);
releaseTft();
}
Serial.print("Loaded in "); Serial.print(millis() - startTime);
Serial.println(" ms");
}
else Serial.println("BMP format not recognized.");
}
bmpFS.close();
tft.setSwapBytes( false );// handy when proper colors are expected afterwards :-)jb
}
// These read 16- and 32-bit types from the SD card file.
// BMP data is stored little-endian, Arduino is little-endian too.
// May need to reverse subscript order if porting elsewhere.
uint16_t read16(fs::File &f) {
uint16_t result;
((uint8_t *)&result)[0] = f.read(); // LSB
((uint8_t *)&result)[1] = f.read(); // MSB
return result;
}
uint32_t read32(fs::File &f) {
uint32_t result;
((uint8_t *)&result)[0] = f.read(); // LSB
((uint8_t *)&result)[1] = f.read();
((uint8_t *)&result)[2] = f.read();
((uint8_t *)&result)[3] = f.read(); // MSB
return result;
}
//------------------------------------------------------
void tft_init(){
pinMode( TFT_RST , OUTPUT);
digitalWrite( TFT_RST , LOW);
delay( 10);
digitalWrite( TFT_RST , HIGH);
// read battery
pinMode(BATPIN, INPUT);
analogSetAttenuation(ADC_6db);
tft.init();
tft.setRotation(1);
tft.fillScreen(TFT_BLACK);
drawBmp("/OranjeRadio24.bmp", 55, 15 );
delay(100);
setVolume( get_last_volstat(1) );
delay(10);
showBattery();
delay(10);
Serial.println("tft initialized");
}
<file_sep>#define FILESYSTEM SPIFFS
// You only need to format the filesystem once
#define FORMAT_FILESYSTEM false
#if FILESYSTEM == FFat
#include <FFat.h>
#endif
#if FILESYSTEM == SPIFFS
#include <SPIFFS.h>
#endif
//holds the current upload
File fsUploadFile;
//----------------------------------------------
//format bytes
String formatBytes(size_t bytes) {
if (bytes < 1024) {
return String(bytes) + "b";
} else if (bytes < (1024 * 1024)) {
return String(bytes / 1024.0) + "Kb";
} else if (bytes < (1024 * 1024 * 1024)) {
return String(bytes / 1024.0 / 1024.0) + "Mb";
} else {
return String(bytes / 1024.0 / 1024.0 / 1024.0) + "Gb";
}
}
//----------------------------------------------
String getContentType(String filename) {
if(server.hasArg("download")) return "application/octet-stream";
else if(filename.endsWith(".htm")) return "text/html";
else if(filename.endsWith(".html")) return "text/html";
else if(filename.endsWith(".css")) return "text/css";
else if(filename.endsWith(".js")) return "application/javascript";
else if(filename.endsWith(".json")) return "application/json";
else if(filename.endsWith(".png")) return "image/png";
else if(filename.endsWith(".gif")) return "image/gif";
else if(filename.endsWith(".jpg")) return "image/jpeg";
else if(filename.endsWith(".ico")) return "image/x-icon";
else if(filename.endsWith(".svg")) return "image/svg+xml";
else if(filename.endsWith(".xml")) return "text/xml";
else if(filename.endsWith(".pdf")) return "application/x-pdf";
else if(filename.endsWith(".zip")) return "application/x-zip";
else if(filename.endsWith(".gz")) return "application/x-gzip";
else if(filename.endsWith(".bin")) return "application/octet-stream";
return "text/plain";
}
//----------------------------------------------
bool exists(String path){
bool yes = false;
File file = FILESYSTEM.open(path, "r");
if(!file.isDirectory()){
yes = true;
}
file.close();
return yes;
}
//----------------------------------------------
bool handleFileRead(String path) {
Serial.println("handleFileRead: " + path);
if (path.endsWith("/")) {
path += "index.htm";
}
String contentType = getContentType(path);
String pathWithGz = path + ".gz";
if (exists(pathWithGz) || exists(path)) {
if (exists(pathWithGz)) {
path += ".gz";
}
File file = FILESYSTEM.open(path, "r");
server.streamFile(file, contentType);
file.close();
return true;
}
return false;
}
//----------------------------------------------
void handleFileUpload(){
HTTPUpload& upload = server.upload();
String filename=upload.filename;
if(upload.status == UPLOAD_FILE_START){
Serial.print("Uploading ");Serial.println(filename);
if ( server.hasArg("filename") ){
filename = server.arg("filename");
Serial.print("filename in text "); Serial.println(server.arg("filename") );
}
if(!filename.startsWith("/")) filename = "/"+filename;
Serial.print("handleFileUpload Name: "); Serial.println(filename);
//reading_file++;
fsUploadFile = SPIFFS.open(filename, "w");
if ( fsUploadFile == NULL ){
Serial.print("Couldn't open ");Serial.println( filename );
}
filename = String();
} else if(upload.status == UPLOAD_FILE_WRITE){
//Serial.print("handleFileUpload Data: "); Serial.println(upload.currentSize);
if(fsUploadFile)
fsUploadFile.write(upload.buf, upload.currentSize);
delay(1);
} else if(upload.status == UPLOAD_FILE_END){
if(fsUploadFile)
fsUploadFile.close();
if ( filename.equals("/stations.json") ){
int changestation=-1;
read_stations();
if ( server.hasArg("changestation") ){
changestation = server.arg("changestation").toInt();
Serial.printf("Server has arg changestation: %d\n", changestation );
}
if ( changestation != -1 ){
Serial.printf("Changing stations to %d\n", changestation );
//xSemaphoreTake( updateSemaphore, portMAX_DELAY);
setStation( changestation, changestation );
//xSemaphoreGive( updateSemaphore);
}
}
//if ( reading_file ) reading_file--;
Serial.print("handleFileUpload Size: "); Serial.println(upload.totalSize);
}
}
//------------------------------------------------
void handleFileDelete() {
if (server.args() == 0) {
return server.send(500, "text/plain", "BAD ARGS");
}
String path = server.arg(0);
Serial.println("handleFileDelete: " + path);
if (path == "/") {
return server.send(500, "text/plain", "BAD PATH");
}
if (!exists(path)) {
return server.send(404, "text/plain", "FileNotFound");
}
FILESYSTEM.remove(path);
server.send(200, "text/plain", "");
path = String();
}
//----------------------------------------------
void handleFileCreate() {
if (server.args() == 0) {
return server.send(500, "text/plain", "BAD ARGS");
}
String path = server.arg(0);
Serial.println("handleFileCreate: " + path);
if (path == "/") {
return server.send(500, "text/plain", "BAD PATH");
}
if (exists(path)) {
return server.send(500, "text/plain", "FILE EXISTS");
}
File file = FILESYSTEM.open(path, "w");
if (file) {
file.close();
} else {
return server.send(500, "text/plain", "CREATE FAILED");
}
server.send(200, "text/plain", "");
path = String();
}
//----------------------------------------------
void handleFileList() {
if (!server.hasArg("dir")) {
server.send(500, "text/plain", "BAD ARGS");
return;
}
String path = server.arg("dir");
Serial.println("handleFileList: " + path);
File root = FILESYSTEM.open(path);
path = String();
String output = "[";
if(root.isDirectory()){
File file = root.openNextFile();
while(file){
if (output != "[") {
output += ',';
}
output += "{\"type\":\"";
output += (file.isDirectory()) ? "dir" : "file";
output += "\",\"name\":\"";
output += String(file.name()).substring(1);
output += "\"}";
file = root.openNextFile();
}
}
output += "]";
server.send(200, "application/json", output);
}
//----------------------------------------------
void setupFS(void) {
if (FORMAT_FILESYSTEM) FILESYSTEM.format();
FILESYSTEM.begin();
{
File root = FILESYSTEM.open("/");
File file = root.openNextFile();
while(file){
String fileName = file.name();
size_t fileSize = file.size();
Serial.printf("FS File: %s, size: %s\n", fileName.c_str(), formatBytes(fileSize).c_str());
if ( ! strcmp( fileName.c_str(), "/syslog.txt" ) && fileSize > 20000 ){
FILESYSTEM.remove(fileName);
Serial.printf("**************removed syslog.txt as it was over 20k\n" );
}
file = root.openNextFile();
}
Serial.printf("\n");
}
}
//-----------------------------------------------------
int syslog( char *message){
FILE *log=NULL;
time_t now;
now = time(nullptr);
char tijd[32];
log = fopen( "/spiffs/syslog.txt", "a");
if ( log == NULL) {
Serial.printf("Couldn't open /syslog.txt (errno %d)\n", errno );
return(-1);
}
sprintf( tijd,"%s", asctime( localtime(&now)) );
tijd[ strlen(tijd) - 1 ] = 0;
fprintf( log,"%s - %s\n", tijd, message);
fclose(log);
return(0);
}
|
6f97983e1c1222f9b2480ed4fa46689feffd2ec5
|
[
"Markdown",
"C++"
] | 11
|
C++
|
gitpeut/OranjeRadio
|
d9acfaed99f3b3aa8daefd4009ffe56c9be6c75d
|
a6169b50aa2153de5b7f30e7d7024f6bafd1cbb9
|
refs/heads/master
|
<repo_name>wangdpwin/xinput-springboot-base<file_sep>/src/test/java/com/xinput/baseboot/util/JsonUtilDemo.java
package com.xinput.baseboot.util;
import com.xinput.baseboot.domain.Student;
import com.xinput.bleach.util.BuilderUtils;
import com.xinput.bleach.util.JsonUtils;
import org.junit.Test;
/**
* @author xinput
* @date 2020-08-06 14:06
*/
public class JsonUtilDemo {
@Test
public void test() {
Student s0 = null;
System.out.println(JsonUtils.toJsonString(s0));
System.out.println(JsonUtils.toJsonString(s0, true));
Student s1 = create(1);
System.out.println(s1.toString());
System.out.println(JsonUtils.toJsonString(s1));
System.out.println(JsonUtils.toJsonString(s1, true));
String s = null;
Student s2 = JsonUtils.toBean(s, Student.class);
System.out.println(s2 == null);
Student s3 = JsonUtils.toBean("", Student.class);
}
private Student create(int id) {
return BuilderUtils.of(Student::new)
.with(Student::setId, String.valueOf(id))
.with(Student::setName, "学生" + id)
.with(Student::setAge, 10 + id)
.build();
}
}
<file_sep>/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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>com.github.xinput123</groupId>
<artifactId>xinput-springboot-parent</artifactId>
<version>1.0.4</version>
<relativePath/>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.github.xinput123</groupId>
<artifactId>xinput-springboot-base</artifactId>
<version>0.1.4</version>
<name>xinput-springboot-base</name>
<description>springboot的一个基本封装</description>
<url>https://github.com/xinput123/xinput-springboot-base</url>
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.github.xinput123</groupId>
<artifactId>bleach</artifactId>
<version>0.1.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 实现对数据库连接池的自动化配置 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Mongo -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 关键信息加密 -->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot</artifactId>
<version>3.0.3</version>
</dependency>
<!-- 实现对 MyBatis Plus 的自动化配置 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.2</version>
</dependency>
<!-- log begin-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-web</artifactId>
<version>2.11.1</version>
</dependency>
<!-- log end -->
<!-- -jwt -->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.10.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<developers>
<developer>
<name>xinput</name>
<email><EMAIL></email>
<roles>
<role>Developer</role>
</roles>
<timezone>+8</timezone>
</developer>
</developers>
<issueManagement>
<system>Github Issue</system>
<url>https://github.com/xinput123/xinput-springboot-base/issues</url>
</issueManagement>
<licenses>
<license>
<name>BSD 3-Clause</name>
<url>https://spdx.org/licenses/BSD-3-Clause.html</url>
</license>
</licenses>
<scm>
<connection>https://github.com/xinput123/xinput-springboot-base.git</connection>
<url>https://github.com/xinput123/xinput-springboot-base</url>
</scm>
<!-- 项目构建 -->
<build>
<plugins>
<!-- 打包时跳过测试 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<!-- 以下都为上传jar默认配置不做修改 -->
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.8</version>
<!-- autoReleaseAfterClose的值为true,则脚本会自动完成在平台上close、release的操作,至此你将成功发布了 -->
<extensions>true</extensions>
<configuration>
<serverId>sonatype-nexus-snapshots</serverId>
<nexusUrl>https://oss.sonatype.org/</nexusUrl>
<autoReleaseAfterClose>true</autoReleaseAfterClose>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.5.3</version>
<configuration>
<autoVersionSubmodules>true</autoVersionSubmodules>
<useReleaseProfile>false</useReleaseProfile>
<releaseProfiles>release</releaseProfiles>
<goals>deploy</goals>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>1.5</version>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.2.1</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.9.1</version>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
<!-- JDK8必须使用下面的配置 -->
<configuration>
<encoding>UTF-8</encoding>
<charset>UTF-8</charset>
<additionalparam>-Xdoclint:none</additionalparam>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<distributionManagement>
<snapshotRepository>
<id>sonatype-nexus-snapshots</id>
<name>Sonatype Nexus Snapshots</name>
<url>https://oss.sonatype.org/content/repositories/snapshots/</url>
</snapshotRepository>
<repository>
<id>sonatype-nexus-snapshots</id>
<name>Nexus Release Repository</name>
<url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
</repository>
</distributionManagement>
</project>
|
56a10ae85a105e77db2a235b77662c8d5cd331d5
|
[
"Java",
"Maven POM"
] | 2
|
Java
|
wangdpwin/xinput-springboot-base
|
99185094186fa93693e82ede9c89d460c2752705
|
1ff16ff0b5fb0b9484ae609a993577fdfb5e2d40
|
refs/heads/master
|
<repo_name>dhavalsdoshi/Trump-Cards<file_sep>/public/dispatch.fcgi
#!/usr/bin/ruby1.8
#!/usr/local/bin/ruby
#
# You may specify the path to the FastCGI crash log (a log of unhandled
# exceptions which forced the FastCGI instance to exit, great for debugging)
# and the number of requests to process before running garbage collection.
#
# By default, the FastCGI crash log is RAILS_ROOT/log/fastcgi.crash.log
# and the GC period is nil (turned off). A reasonable number of requests
# could range from 10-100 depending on the memory footprint of your app.
#
# Example:
# # Default log path, normal GC behavior.
# RailsFCGIHandler.process!
#
# # Default log path, 50 requests between GC.
# RailsFCGIHandler.process! nil, 50
#
# # Custom log path, normal GC behavior.
# RailsFCGIHandler.process! '/var/log/myapp_fcgi_crash.log'
#
# require File.dirname(__FILE__) + "/../config/environment"
# require 'fcgi_handler'
# RailsFCGIHandler.process!
require File.dirname(__FILE__) + "/../config/environment" unless defined?(RAILS_ROOT)
# If you're using RubyGems and mod_ruby, this require should be changed to an absolute path one, like:
# "/usr/local/lib/ruby/gems/1.8/gems/rails-0.8.0/lib/dispatcher" -- otherwise performance is severely impaired
require "dispatcher"
ADDITIONAL_LOAD_PATHS.reverse.each { |dir| $:.unshift(dir) if File.directory?(dir) } if defined?(Apache::RubyRun)
Dispatcher.dispatch
|
d43c135e21656b38bc0678bd7917d0b858b560d0
|
[
"Ruby"
] | 1
|
Ruby
|
dhavalsdoshi/Trump-Cards
|
0d9fe61ae9a3797e89862af6c2df67d555ec44a6
|
48f22bbf2ca6d38bdfa003d4d4c14da1b96ebbc9
|
refs/heads/master
|
<file_sep>
var Fibonacci = function() {
};
Fibonacci.prototype.series = function(n) {
var fib = [1, 1];
for(var i = 2; i <= n; i++) {
fib.push((fib[i - 1] + fib[i - 2]));
}
return fib[n - 1];
};
|
52df2b115f9b1ea41d8ff64200812bc09f13ff38
|
[
"JavaScript"
] | 1
|
JavaScript
|
EthanLuisMcDonough/FibonacciJS
|
42d3ec4c1131bff732dc63537d80acd8fc1ead86
|
73696fe9e780bac287b2004fdbdcda5c74469744
|
refs/heads/master
|
<repo_name>Inzephirum/broccoli-beml<file_sep>/README.md
# broccoli-beml
> Plugin for processing [BEML][beml] templates
How to use
-----
Install broccoli-beml as a dev dependency:
```shell
npm install broccoli-beml --save-dev
```
Then, add it to your Brocfile.js:
```javascript
var beml = require('broccoli-beml');
var htmls = beml('pathToFolder', {
// These options are defaults and can be ignored
srcDir: '/',
destDir: '/',
files: ['**/*.html'],
elemPrefix: '__',
modPrefix: '_',
modDlmtr: '_'
});
module.exports = htmls;
```
[beml]: https://github.com/zenwalker/node-beml
<file_sep>/index.js
var fs = require('fs'),
path = require('path');
var beml = require('beml'),
helpers = require('broccoli-kitchen-sink-helpers'),
mkdirp = require('mkdirp'),
Writer = require('broccoli-writer');
module.exports = BEML;
BEML.prototype = Object.create(Writer.prototype);
BEML.prototype.constructor = BEML;
function BEML(inputTree, options) {
'use strict';
if (!(this instanceof BEML)) {
return new BEML(inputTree, options);
}
this.inputTree = inputTree;
this.options = {
srcDir: options.srcDir || '/',
destDir: options.destDir || '/',
elemPrefix: options.elemPrefix || '__',
modPrefix: options.modPrefix || '_',
modDlmtr: options.modDlmtr || '_',
files: options.files || ['**/*.html']
};
}
BEML.prototype.write = function (readTree, destDir) {
'use strict';
var self = this;
return readTree(this.inputTree).then(function (srcDir) {
var sourcePath = path.join(srcDir, self.options.srcDir),
destPath = path.join(destDir, self.options.destDir),
baseDir = path.join(srcDir, self.options.srcDir),
files = helpers.multiGlob(self.options.files, {
cwd: baseDir,
root: baseDir,
nomount: false
});
var i = 0,
len = files.length,
fileSourcePath, fileDestPath, config, html, result;
for (i = 0; i < len; i += 1) {
fileSourcePath = path.join(sourcePath, files[i]);
fileDestPath = path.join(destPath, files[i]);
mkdirp.sync(path.dirname(fileDestPath));
config = {
elemPrefix: self.options.elemPrefix,
modPrefix: self.options.modPrefix,
modDlmtr: self.options.modDlmtr
};
html = fs.readFileSync(fileSourcePath, 'utf8');
result = beml(html, config);
fs.writeFileSync(fileDestPath, result, 'utf8');
}
});
};
|
9bfee48d7ba6931e88af29c0a7def64a62a53e8e
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
Inzephirum/broccoli-beml
|
976ff58c81c79111944ca62b51eac17165844dad
|
f2f831da3683b6ab70bdcac9159a41ce0211ebc3
|
refs/heads/master
|
<repo_name>zy-629/AID1905<file_sep>/test/for.py
# for循环
# for语句可以用来遍历序列或可迭代对象的每一个元素
# 可迭代对象:
# 字符串:str 列表:list 元组 tuple 字典:dict 集合:set
# 固定集合: forzenset 迭代器
#
# 语法:for 变量 in 可迭代对象 :
# 语句块1
# b=int(input("请输入数字"))
# list=[1,2,3]
# for:
# if b in list:
# print("你赢了")
# else:
# print("输入有误")
# str = 'hello world'
# for i in s*r:
# print(i)
#
# else:
# print("循环结束")
# import random
# menu = '''(0)石头
# (1)剪刀
# (2)布
# (q)结束游戏
# '''
#
# #存放所有的出拳
# all_list = ["石头","剪刀","布"]
# c = random.choice(all_list)
# y = input(menu)
#
# if y in ['0','1','2','q']:
# if y == 'q':
# print("游戏结束")
# else:
# you = all_list[int(y)] 此句不理解
# if you == c:
# print("平局")
# elif (you == "石头" and c == "剪刀") \
# or (you == "剪刀" and c == "布") \
# or (you == "布" and c == "石头"):
# print("你赢了")
# else:
# print("电脑赢了")
# else:
# print("输入无效")
# a=int(input("请输入一个整数"))
# b=1
# c=0
# for b in range(1,a+1):
# c=c+b
# print(c)
# import random
# mima='qwertyuiopasdfghjklzxcvbnm1234567890_'
# c=random.choice(mima)
# d=''
# a=input(input("请输入密码位数"))
# b=1
# for b in range(a):
# 现有一个已经设定好登录名和密码的系统,现有一个用户忘记登录账号及密码
# 此登录系统只有三次尝试机会,请编写一个用户登录系统,如果在3次之内当用户
# 输入账号密码跟设定密码匹配,则登录成功,否则登录失败,并且当你在输错的时
# 提示还有几次机会。
#
# a=(123)
# b=(456)
# e=1
# while e<=3:
# c=int(input("请输入用户名"))
# d=int(input("请输入密码"))
# if (c==a and d==b):
# print("登录成功")
# break
# elif (c!=a or d!=b and e==1):
# print("输入错误,还剩2次机会")
# e=e+1
# # continue
# elif (c!=a or d!=b and e==2):
# print("输入错误,还剩1次机会")
# e=e+1
# continue
# elif (c!=a or d!=b and e==3):
# print("输入错误,您的账户已被锁定")
# break
# a=123
# b=456
# e=1
# while e<=3:
# c=int(input("请输入用户名"))
# d=int(input("请输入密码"))
# if (c==a and d==b):
# print("登录成功")
# break
# elif (c!=a or d!=b and e==1):
# print("输入错误,还剩2次机会")
# e=e+1
# # continue
# elif (c!=a or d!=b and e==2):
# print("输入错误,还剩1次机会")
# e=e+1
# # continue
# elif (c!=a or d!=b and e==3):
# print("输入错误,您的账户已被锁定")
# e=e+1
# a=''
# b=''
# for m in range(1,10):
# for n in range(1,10):
# print("%d *%d =%d " %(m,n,m*n))
#
# print()
# c=1
# a="a a a cd fda fa "
# for m in a:
#
# prin("%s=%s (c,m))
# c=c+1
# str="hello world"
#
# for i in str:
#
# print(i)
# if i=="o":
# break
# 1 2 3 4 5
# 10 5 2.5 2.5/2 2.5/2/2
# a=int(input("请输入一个整数"))
#
# c=a
#
# for b in range(1,3):
# a=a/2
# c+=a*2
# print(c,a/2)
h = int(input("请输入初始高度"))
sum = h
for i in range(2):
h = h/2
sum += h*2
print(sum, h / 2)
<file_sep>/.gltproject.py
#测试代码
print('修改内容')
|
883b4f90c9ee9ddb2e69ae067ee00290ac4a3021
|
[
"Python"
] | 2
|
Python
|
zy-629/AID1905
|
d71e9d4e09eb7ab3e61d0625650d45e221956cfe
|
cd332a35adc1508ba20555b712f3116962dedf3b
|
refs/heads/master
|
<file_sep>package com.sinanmutlu.Ticketing.controller;
import java.util.Date;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.sinanmutlu.Ticketing.model.Airport;
import com.sinanmutlu.Ticketing.repository.AirportRepository;
@RestController
@RequestMapping("/api")
public class AirportController {
@Autowired
AirportRepository airportRepository;
//TODO comment out
@GetMapping("/airport")
public List<Airport> getAllNotes() {
return airportRepository.findAll();
}
@PostMapping("/addAirport")
public Airport addAirport(@Valid @RequestBody Airport airport) {
Date currentDate = new Date();
airport.setCreatedAt(currentDate);
airport.setUpdatedAt(currentDate);
return airportRepository.save(airport);
}
@PostMapping("/searchAirportName")
public List<Airport> searchAirportName(@Valid @RequestBody Airport airport) {
//TODO null check ve one göre response dön
return airportRepository.findByLocationIgnoreCase(airport.getName());
}
@PostMapping("/searchAirportLocation")
public List<Airport> searchAirportLocation(@Valid @RequestBody Airport airport) {
//TODO null check ve one göre response dön
return airportRepository.findByLocationIgnoreCase(airport.getLocation());
}
}
<file_sep>package com.sinanmutlu.Ticketing.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.sinanmutlu.Ticketing.model.Route;
@Repository
public interface RouteRepository extends JpaRepository<Route, Long> {
List<Route> findBySourceCityAndDestinationCity(String sourceCity, String destinationCity);
List<Route> findBySourceAirportIdAndDestinationAirportId(long sourceAirportId, long destinationAirportId);
}
<file_sep>package com.sinanmutlu.Ticketing.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.sinanmutlu.Ticketing.model.Airline;
@Repository
public interface AirlineRepository extends JpaRepository<Airline, Long> {
List<Airline> findByNameIgnoreCase(String name);
}
<file_sep>package com.sinanmutlu.Ticketing.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.DynamicInsert;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@Entity
@DynamicInsert
@Table(name = "route")
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = { "createdAt", "updatedAt" }, allowGetters = true)
public class Route {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String sourceCity;
private long sourceAirportId;
private String destinationCity;
private long destinationAirportId;
@Column(nullable = true, updatable = false)
@Temporal(TemporalType.TIMESTAMP)
@CreatedDate
private Date createdAt;
@Column(nullable = true)
@Temporal(TemporalType.TIMESTAMP)
@LastModifiedDate
private Date updatedAt;
public Route() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getSourceCity() {
return sourceCity;
}
public void setSourceCity(String sourceCity) {
this.sourceCity = sourceCity;
}
public long getSourceAirportId() {
return sourceAirportId;
}
public void setSourceAirportId(long sourceAirportId) {
this.sourceAirportId = sourceAirportId;
}
public String getDestinationCity() {
return destinationCity;
}
public void setDestinationCity(String destinationCity) {
this.destinationCity = destinationCity;
}
public long getDestinationAirportId() {
return destinationAirportId;
}
public void setDestinationAirportId(long destinationAirportId) {
this.destinationAirportId = destinationAirportId;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
}
<file_sep>package com.sinanmutlu.Ticketing.controller;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.sinanmutlu.Ticketing.model.Flight;
import com.sinanmutlu.Ticketing.model.Ticket;
import com.sinanmutlu.Ticketing.repository.FlightRepository;
import com.sinanmutlu.Ticketing.repository.TicketRepository;
@RestController
@RequestMapping("/api")
public class TicketController {
@Autowired
TicketRepository ticketRepository;
@Autowired
FlightRepository flightRepository;
// TODO comment out
@GetMapping("/ticket")
public List<Ticket> getAllNotes() {
return ticketRepository.findAll();
}
@PostMapping("/buyTicket")
public Ticket addFlight(@Valid @RequestBody Ticket ticket) {
Date currentDate = new Date();
ticket.setCreatedAt(currentDate);
ticket.setUpdatedAt(currentDate);
Flight flight = flightRepository.findOneById(ticket.getFlightId());
flight.setUpdatedAt(currentDate);
flight.setCurrentCapacity(flight.getCurrentCapacity() + 1);
flight.setCurrentPrice(flight.getPrice() / (int) (flight.getCurrentCapacity() / flight.getCapacity()) * 10);
flightRepository.save(flight);
return ticketRepository.save(ticket);
}
@PostMapping("/searchTicketById")
public Optional<Ticket> searchTicketById(@Valid @RequestBody Ticket ticket) {
return ticketRepository.findById(ticket.getId());
}
@PostMapping("/searchTicketByFlight")
public List<Ticket> searchTicketByFlight(@Valid @RequestBody Flight flight) {
return ticketRepository.findByFlightId(flight.getId());
}
@PostMapping("/searchTicketByCustomerName")
public List<Ticket> searchTicketByCustomerName(@Valid @RequestBody Ticket ticket) {
return ticketRepository.findByCustomerName(ticket.getCustomerName());
}
@PostMapping("/cancelTicket")
public String cancelTicket(@Valid @RequestBody Ticket ticket) {
ticketRepository.deleteById(ticket.getId());
return "Ticket (id:" + ticket.getId() + ") deleted";
}
}
<file_sep>package com.sinanmutlu.Ticketing.repository;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.sinanmutlu.Ticketing.model.Flight;
@Repository
public interface FlightRepository extends JpaRepository<Flight, Long> {
List<Flight> findByAirlineId(long airlineId);
List<Flight> findByRouteId(long routeId);
Flight findOneById(long Id);
}
<file_sep>package com.sinanmutlu.Ticketing.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.DynamicInsert;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@Entity
@DynamicInsert
@Table(name = "flight")
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = { "createdAt", "updatedAt" }, allowGetters = true)
public class Flight {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String airlineId;
private long routeId;
private String date;
private int capacity;
private int currentCapacity;
private double price;
private double currentPrice;
@Column(nullable = true, updatable = false)
@Temporal(TemporalType.TIMESTAMP)
@CreatedDate
private Date createdAt;
@Column(nullable = true)
@Temporal(TemporalType.TIMESTAMP)
@LastModifiedDate
private Date updatedAt;
public Flight() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAirlineId() {
return airlineId;
}
public void setAirlineId(String airlineId) {
this.airlineId = airlineId;
}
public long getRouteId() {
return routeId;
}
public void setRouteId(long routeId) {
this.routeId = routeId;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public int getCapacity() {
return capacity;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public int getCurrentCapacity() {
return currentCapacity;
}
public void setCurrentCapacity(int currentCapacity) {
this.currentCapacity = currentCapacity;
}
public double getCurrentPrice() {
return currentPrice;
}
public void setCurrentPrice(double currentPrice) {
this.currentPrice = currentPrice;
}
}
<file_sep>package com.sinanmutlu.Ticketing.controller;
import java.util.Date;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.sinanmutlu.Ticketing.model.Route;
import com.sinanmutlu.Ticketing.repository.RouteRepository;
@RestController
@RequestMapping("/api")
public class RouteController {
@Autowired
RouteRepository routeRepository;
// TODO comment out
@GetMapping("/route")
public List<Route> getAllNotes() {
return routeRepository.findAll();
}
// route from an airport to an airport
@PostMapping("/addRoute")
public Route addRoute(@Valid @RequestBody Route route) {
Date currentDate = new Date();
route.setCreatedAt(currentDate);
route.setUpdatedAt(currentDate);
return routeRepository.save(route);
}
@PostMapping("/searchRouteByCity")
public List<Route> searchRouteByCity(@Valid @RequestBody Route route) {
return routeRepository.findBySourceCityAndDestinationCity(route.getSourceCity(), route.getDestinationCity());
}
@PostMapping("/searchRouteByAirport")
public List<Route> searchRouteByAirport(@Valid @RequestBody Route route) {
return routeRepository.findBySourceAirportIdAndDestinationAirportId(route.getSourceAirportId(), route.getDestinationAirportId());
}
}
<file_sep>package com.sinanmutlu.Ticketing.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.sinanmutlu.Ticketing.model.Airport;
@Repository
public interface AirportRepository extends JpaRepository<Airport, Long> {
List<Airport> findByNameIgnoreCase(String name);
List<Airport> findByLocationIgnoreCase(String location);
}
|
f91121d685553ac7f19c5060141b884c08236e0a
|
[
"Java"
] | 9
|
Java
|
sinanmutlu/TicketingApp
|
f79747a7ec5181eb2926f44b0b87bf4525db0039
|
dc93ce674b3044696a9c60db77ae2caf09dad391
|
refs/heads/master
|
<repo_name>xiaoniuqq/mybatis-xml-generator<file_sep>/src/main/java/top/leeys/codegenerator/User.java
package top.leeys.codegenerator;
import java.util.Date;
public class User extends BaseModel {
private static final long serialVersionUID = 1L;
private String username;
private String password;
private Long loginCount;
private Date loginTime;
private String countryCode;
private String phone;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Long getLoginCount() {
return loginCount;
}
public void setLoginCount(Long loginCount) {
this.loginCount = loginCount;
}
public Date getLoginTime() {
return loginTime;
}
public void setLoginTime(Date loginTime) {
this.loginTime = loginTime;
}
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
|
770fb07a98cea19c2d8c72f84e39472ae78b5e7f
|
[
"Java"
] | 1
|
Java
|
xiaoniuqq/mybatis-xml-generator
|
a37f13ac5db71fdf63c778c3c8b7d1a6c7d5e35e
|
7123a297957e74affec86094085abf720eb21fa1
|
refs/heads/master
|
<file_sep>if [ "$TERM" != "dumb" ]; then
alias l='ls --color=auto -F'
alias ls='ls --color=auto -F'
alias dir='ls --color=auto --format=vertical'
alias vdir='ls --color=auto --format=long'
fi
alias ack='ACK_PAGER_COLOR="less -x4SRFX" /usr/bin/ack --color-filename=white --color-match=cyan'
alias bck='cd /media/nasGom/video/back'
alias ccat='pygmentize'
alias cgrep='grep --colour=always'
alias c11c='clang++ -std=c++11 -stdlib=libc++ -Wall -g'
alias dfh='df -h -T --total -t ext4 | grep -h "[a-zA-Z0-9]\{1,3\}\%"'
alias duf='du -sk * | sort -n | perl -ne '\''($s,$f)=split(m{\t});for (qw(K M G T)) {if($s<1024) {printf("%.1f",$s);print "$_\t$f"; last};$s=$s/1024}'\'
alias dc='deluge-console'
alias f='find . -name'
alias grep='grep --colour=auto'
alias h="history | grep"
alias k9="killall -9"
alias ll='ls -lhF'
alias lll='ls --color=always -lasth | less -R'
alias p='ps -ef | grep'
alias rm_empties='find . -type d -empty -exec rmdir {} \;'
alias sbrecent='grep -h "\-\-\->" $HOME/log/spiderbro/*.log | sed -e "s/&tr.*$//g" | sed -e "s/magnet.*dn=//g" | grep -h -e "\-\-\->" -e "Copying File" -e "Added Torrent" -e " to "'
alias sbadded='grep -h "\-\-\->" $HOME/log/spiderbro/*.log | sed -e "s/&tr.*$//g" | sed -e "s/magnet.*dn=//g" | grep -e "Added Torrent" | grep -h -e "\-\-\->" -e "Added Torrent" -e " to "'
alias sbtoday='grep -h "\-\-\->" $HOME/log/spiderbro/*.log | sed -e "s/&tr.*$//g" | sed -e "s/magnet.*dn=//g" | grep `date +%Y-%m-%d` | grep -h -e "\-\-\->" -e "Copying File" -e "Added Torrent" -e " to "'
alias sbtodaylog='less ~/log/spiderbro/spiderBro_`date +%Y-%m-%d`.log'
alias ta='tmux attach'
alias t='tree -h'
alias tl='tree -C -h | less -R'
alias tmux='tmux -2'
alias todo='vim ~/.todo'
alias vim='vim -p'
alias wreck_your_buzz='sudo ettercap -i eth1 -T -q -F ~/tools/dos.ef -M ARP /192.168.1.5/ //'
alias django_set_env='export PROJECT=`python -c "import os; print os.path.basename(os.getcwd())"`; export PYTHONPATH=../ ; export DJANGO_SETTINGS_MODULE=$PROJECT.settings'
# git
alias gp='git push'
alias gb='git branch'
alias gc='git checkout'
alias gm='git commit -m'
alias gma='git commit -am'
alias gd='git diff'
alias gs='git status'
alias gra='git remote add'
alias grr='git remote rm'
alias gpu='git pull'
alias gl='git log'
alias ga='git add'
alias gcl='git clone'
|
a4c8a4ded2485f7d3d91917bb87ed5ba0ff2fce8
|
[
"Shell"
] | 1
|
Shell
|
GrahamOMalley/dotfiles
|
f5c18b6ca896827009ca98e0907f7801b5c6a952
|
a2854dd4c39b556c8ae633c230a63454901ebd2e
|
refs/heads/main
|
<file_sep>// Sum the amounts of an array of expenses
export default (expenses) => {
return expenses
.map(expense => expense.amount)
.reduce(
(accumulator, amount) => accumulator + amount, 0
);
};<file_sep>import expensesReducer from '../../reducers/expenses';
import expenses from '../fixtures/expenses';
test('should set default state', () => {
const state = expensesReducer(undefined, {'type': '@@INIT'});
expect(state).toEqual([]);
});
test('should remove expense by id', () => {
const idx_to_remove = 1;
expect(idx_to_remove).toBeLessThan(expenses.length);
const action = {
type: 'REMOVE_EXPENSE',
id: expenses[idx_to_remove].id
}
const initial_length = expenses.length;
const state = expensesReducer(expenses, action);
expect(state.length).toEqual(initial_length - 1);
expect(state).toEqual(expenses.slice(0, idx_to_remove).concat(expenses.slice(idx_to_remove + 1)))
});
test('should not remove expense by invalid id', () => {
const action = {
type: 'REMOVE_EXPENSE',
id: 'boogaloo'
}
const initial_length = expenses.length;
const state = expensesReducer(expenses, action);
expect(state.length).toEqual(initial_length);
expect(state).toEqual(expenses);
});
test('should add an expense', () => {
const expense = {
id: '5',
description: 'Bananas and blow',
amount: 667,
note: 'Sancho',
createdAt: 4000
};
const action = {
type: 'ADD_EXPENSE',
expense
};
const state = expensesReducer(expenses, action);
expect(state).toEqual([...expenses, expense]);
});
test('should remove an expense by id', () => {
const action = {
type: 'EDIT_EXPENSE',
id: expenses[1].id,
updates: {
amount: 999
}
};
const state = expensesReducer(expenses, action);
expect(state[1].amount).toBe(999);
});
test('should not remove an expense by invalid id', () => {
const action = {
type: 'EDIT_EXPENSE',
id: parseInt(expenses[1].id),
updates: {
amount: 999
}
};
const state = expensesReducer(expenses, action);
expect(state).toEqual(expenses);
});
test('should call set expenses', () => {
const action = {
type: 'SET_EXPENSES',
expenses: expenses.slice(1, 3)
};
const state = expensesReducer([expenses[0]], action);
expect(state).toEqual(expenses.slice(1, 3));
});<file_sep>//
// Object destrucuring
//
// const person = {
// name: 'Shane',
// age: 98,
// location: {
// city: 'Dublin',
// temperature: 2
// }
// };
// const { name = 'Anonymous', age } = person;
// console.log(`${name} is ${age}.`);
// const { city, temperature: temp } = person.location;
// if (city && temp !== undefined) {
// console.log(`It's ${temp} in ${city}.`);
// }
// const book = {
// title: 'Ego is the Enemy',
// author: '<NAME>',
// publisher: {
// name: 'Penguin'
// }
// };
// const { name:publisherName = 'Self-Published'} = book.publisher;
// console.log(publisherName);
//
// Array destrucuring
//
const address = ['69 Main Street', 'Cityville', 'California', '12345'];
const [ , city, state = 'New York', ] = address;
console.log(`You are in ${city}, ${state}.`)
const item_1 = ['Coffee (hot)', '$2.00', '$2.50', '$2.75'];
const [itemName, , mediumPrice] = item_1;
console.log(`A medium ${itemName} costs ${mediumPrice}.`)
const item_2 = ['Coffee (iced)', '$2.25', '$2.80', '$3.00'];
const [itemName2, , , largePrice2] = item_2;
console.log(`A large ${itemName2} costs ${largePrice2}.`)
|
e57911b0ce833121ecb8759caea75b89b7e1e9ff
|
[
"JavaScript"
] | 3
|
JavaScript
|
spiderbaby/react-course-2-expensify-app
|
62d8dd0e0da7d40be6a014febd7bccd7118c8107
|
fc9ca6c8f88222a9961204617dd4bc2cbeb5bb44
|
refs/heads/main
|
<repo_name>helllrice/dinamika-stroy<file_sep>/js/main.js
$('.slider_container').slick({
});<file_sep>/design_house.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/index.css">
<link rel="stylesheet" href="css/design_house.css">
<link rel="stylesheet" href="slick/slick.css">
<link rel="stylesheet" href="slick/slick-theme.css">
<link rel="stylesheet" href="dist/css/lightbox.css">
<link rel="icon" type="images/romb.png" href="images/romb.png">
<title>Динамикастрой</title>
</head>
<body>
<div class="header">
<div class="header_logo">
<img src="images/logo.png" alt="logo">
</div>
<div class="header_geo">
<p class="geo_street"><i class="fas fa-map-marker-alt"></i>г. Пенза, ул.Кирова 2А</p>
<a href="contacts.html " class="header_link">Мы на карте</a>
</div>
<div class="header_call">
<p class="call"><i class="fas fa-phone-volume"></i>8 (909) 316-83-07</p>
<a href="tel:89093168307" class="header_link2">Заказать звонок</a>
</div>
</div>
<div class="menu">
<ul class="ul_menu">
<li class="li_menu1"><a href="index.html" class="ul_menu_link">ГЛАВНАЯ</a></li>
<li><a href="company.html" class="ul_menu_link">О КОМПАНИИ</a></li>
<li class="li_submenu">
<a href="#" class="ul_menu_link">СТРОИТЕЛЬСТВО ДОМОВ</a>
<ul class="submenu_list">
<li class="li_submenu1"><a href="foundation.html" class="ul_menu_link">СТРОИТЕЛЬСТВО ФУНДАМЕНТА</a></li>
<li class="li_submenu1"><a href="monolith.html" class="ul_menu_link">МОНОЛИТНЫЕ РАБОТЫ</a></li>
<li class="li_submenu1"><a href="brickwork.html" class="ul_menu_link">КИРПИЧНАЯ КЛАДКА</a></li>
<li class="li_submenu1"><a href="roof.html" class="ul_menu_link">МОНТАЖ КРОВЛИ</a></li>
<li class="li_submenu1"><a href="electric_install.html" class="ul_menu_link">МОНТАЖ ЭЛЕКТРИКИ</a></li>
<li class="li_submenu1"><a href="design_house.html" class="ul_menu_link">ПРОЕКТИРОВАНИЕ ДОМОВ</a></li>
<li class="li_submenu1"><a href="project_veranda.html" class="ul_menu_link">
СТРОИТЕЛЬСТВО ВЕРАНДЫ
</a></li>
</ul>
</li>
<li><a href="projects_house.html" class="ul_menu_link">ПРОЕКТЫ ДОМОВ</a></li>
<li class="li_menu2">
<a href="sale_house.html" class="ul_menu_link">УСЛУГИ</a>
<ul class="menu_drop">
<li class="li_menu3"><a href="sale_house.html" class="ul_menu_link">ПРОДАЖА ДОМОВ</a></li>
<li class="li_menu3"><a href="rent.html" class="ul_menu_link">АРЕНДА СПЕЦТЕХНИКИ</a></li>
<li class="li_menu3"><a href="legal.html" class="ul_menu_link">ЮРИДИЧЕСКИЕ УСЛУГИ</a></li>
</ul>
</li>
<li><a href="photo.html" class="ul_menu_link">ФОТО</a></li>
<li><a href="contacts.html" class="ul_menu_link">КОНТАКТЫ</a></li>
</ul>
</div>
<div class="design_house">
<p class="design_house_logo">
Проектирование домов
</p>
<div class="design_house_container">
<div class="photo"><img src="design photo/1.jpg" alt="" style="width: 280px; height: 210px;"></div>
<div class="photo"><img src="design photo/2.jpg" alt="" style="width: 280px; height: 210px;"></div>
<div class="photo"><img src="design photo/3.jpg" alt="" style="width: 280px; height: 210px;"></div>
<div class="photo"><img src="design photo/4.jpg" alt="" style="width: 280px; height: 210px;"></div>
<div class="photo"><img src="design photo/5.jpg" alt="" style="width: 280px; height: 210px;"></div>
<div class="photo"><img src="design photo/6.jpg" alt="" style="width: 280px; height: 210px;"></div>
<div class="photo"><img src="design photo/7.jpg" alt="" style="width: 280px; height: 210px;"></div>
<div class="photo"><img src="design photo/8.jpg" alt="" style="width: 280px; height: 210px;"></div>
<div class="photo"><img src="design photo/9.jpg" alt="" style="width: 280px; height: 210px;"></div>
<div class="photo"><img src="design photo/10.jpg" alt="" style="width: 280px; height: 210px;"></div>
<div class="photo"><img src="design photo/11.jpg" alt="" style="width: 280px; height: 210px;"></div>
<div class="photo"><img src="design photo/12.jpg" alt="" style="width: 280px; height: 210px;"></div>
<div class="photo"><img src="design photo/13.jpg" alt="" style="width: 280px; height: 210px;"></div>
<div class="photo"><img src="design photo/14.jpg" alt="" style="width: 280px; height: 210px;"></div>
<div class="photo"><img src="design photo/15.jpg" alt="" style="width: 280px; height: 210px;"></div>
<div class="photo"><img src="design photo/16.jpg" alt="" style="width: 280px; height: 210px;"></div>
<div class="photo"><img src="design photo/17.jpg" alt="" style="width: 280px; height: 210px;"></div>
<div class="photo"><img src="design photo/18.jpg" alt="" style="width: 280px; height: 210px;"></div>
<div class="photo"><img src="design photo/19.jpg" alt="" style="width: 280px; height: 210px;"></div>
<div class="photo"><img src="design photo/20.jpg" alt="" style="width: 280px; height: 210px;"></div>
<div class="photo"><img src="design photo/21.jpg" alt="" style="width: 280px; height: 210px;"></div>
</div>
<img src="design photo/22.jpg" alt="" style="width: 300px; height: 211px; float: right;">
<p class="design_house_text">
Компания «Динамикастрой» оформляет проекты домов в Пензе и Пензенской области. Профессиональные архитекторы выполнят проектирование любого уровня сложности в требуемом объеме, в том числе проектирование дома под ключ.
</p>
<br>
<p class="design_house_text">
Разработка проектов выполняется для одно- и многоэтажных зданий, различной конфигурации из следующих современных материалов:
</p>
<ul class="design_house_menu">
<li class="design_house_li">деревянный профильный и клееный брус, бревно и оцилиндрованное бревно;</li>
<li class="design_house_li">пеноблок, газо- и железобетон;</li>
<li class="design_house_li">кирпич, сэндвич-панели и другие виды материалов.</li>
</ul>
<br>
<p class="design_house_text2">
Учтите, что разработать проект дома и коттеджа – услуга недешевая, но крайне важная. Стоимость определяется, исходя из объема оформленной документации.
</p>
<br>
<p class="design_house_logo">
Проектирование домов и коттеджей
</p>
<br>
<p class="design_house_text2">
Компания «Динамикастрой» готова выполнить проектирование планировки домов и коттеджей под ключ и отдельные виды проектов других сооружений для частных и юридических лиц в Пензе и Пензенской области:
</p>
<ul class="design_house_menu">
<li class="design_house_li">эскизный, архитектурный и конструктивный;</li>
<li class="design_house_li">прокладка всех инженерных коммуникаций;</li>
<li class="design_house_li">генпланы зданий и сооружений;</li>
<li class="design_house_li">ландшафтное оформление участка;</li>
<li class="design_house_li">сметы на материалы и строительно-монтажные работы.</li>
</ul>
<br>
<p class="design_house_text2">Провести авторский надзор за качественным выполнением строительства дома в соответствии с проектом.
</p>
<p class="design_house_logo">
Гарантии и выгода
</p>
<br>
<p class="design_house_text2">
Компания «Динамикастрой» гарантирует:
</p>
<ul class="design_house_menu">
<li class="design_house_li">обязательное соблюдение строительных ГОСТов и СНиПов;</li>
<li class="design_house_li">разработку с учетом грунта, рельефа и уклона участка;</li>
<li class="design_house_li">разработку с учетом грунта, рельефа и уклона участка;</li>
<li class="design_house_li">полную реализацию Ваших замыслов и идей по созданию дома мечты!</li>
</ul>
<br>
<p class="design_house_text2">Сотрудничая с нашей компанией, Вы можете быть уверены в получении уникального проекта в короткий срок и по адекватной цене. Мы предлагаем комплексный подход к решению вопроса – проектирование и возведение загородного коттеджа или дома по разработанной документации.
</p>
<br>
<p class="design_house_text2">Вы можете выбрать проект дома площадью от нескольких десятков до сотен квадратов, одно- и многоэтажный, для нескольких владельцев, с бассейном и плоской крышей, заказать благоустройство и озеленение усадьбы для создания оригинального ландшафта – все зависит только от Вас.
</p>
<br>
<p class="design_house_text2">
Мы, со своей стороны, обещаем создать проект и построить дом Вашей мечты!
</p>
</div>
<div class="footer">
<div class="footer_container">
<div class="footer_info">
<p class="footer_info_text">
О компании
</p>
<br>
<p class="footer_info_text2">
Компания «Динамикастрой» — команда профессиональных инженеров, проектировщиков, дизайнеров, строителей и т.д., которая готова построить любой частный дом под ключ в Пензе и Пензенской области.
</p>
</div>
<div class="footer_contacts">
<p class="footer_info_text">
Наши контакты
</p>
<br>
<p class="footer_info_text2">Адрес: <NAME>, ул.кирова 2А</p>
<br>
<p class="footer_info_text2">
Телефон: 8 (909) 316-83-07
</p>
<br>
<p class="footer_info_text2">
E-mail: <EMAIL>
</p>
</div>
</div>
</div>
<script src="https://kit.fontawesome.com/2689382108.js" crossorigin="anonymous"></script>
<script src="jquery/jquery-3.5.1.min.js"></script>
<script src="slick/slick.js"></script>
<script src="js/main.js"></script>
<script src="dist/js/lightbox-plus-jquery.js"></script>
</body>
</html>
|
849a97347e8b838f751c1c2858eaa5045b8f27e2
|
[
"JavaScript",
"HTML"
] | 2
|
JavaScript
|
helllrice/dinamika-stroy
|
2056a5a237dbc4f7c29945b94a52fda465eba55d
|
78fafa75fd59f6981c2c41e4b1064eaa03def33a
|
refs/heads/master
|
<file_sep>#!/usr/bin/env node
var q = require('q');
q.longStackSupport = true;
if (module.parent) {
module.exports = require('./src/next-update-as-module');
} else {
var nextUpdate = require('./src/next-update');
var program = require('./src/cli-options');
var pkg = require('./package.json');
var info = pkg.name + '@' + pkg.version + ' - ' + pkg.description;
var report = require('./src/report').report;
var revert = require('./src/revert');
if (program.available) {
nextUpdate.available(program.module, {
color: program.color
});
} else if (program.revert) {
revert(program.module)
.then(function () {
console.log('done reverting');
}, function (error) {
console.error('error while reverting\n', error);
});
} else {
console.log(info);
var updateNotifier = require('update-notifier');
var notifier = updateNotifier();
if (notifier.update) {
notifier.notify();
}
var opts = {
names: program.module,
latest: program.latest,
testCommand: program.test,
all: program.all,
color: program.color,
keep: program.keep,
allow: program.allowed || program.allow
};
var checkCurrent = nextUpdate.checkCurrentInstall.bind(null, opts);
var checkCurrentState = program.skip ? q : checkCurrent;
var checkUpdates = nextUpdate.checkAllUpdates.bind(null, opts);
var reportTestResults = function (results) {
if (Array.isArray(results)) {
report(results, program.color, program.keep);
}
};
checkCurrentState()
.then(checkUpdates)
.then(reportTestResults)
.catch(function (error) {
console.error('ERROR testing next working updates');
console.error(error.stack);
process.exit(1);
});
}
}
|
11ee33abd9439d2d861b189a594199f1c38fd168
|
[
"JavaScript"
] | 1
|
JavaScript
|
mchapman/next-update
|
a9086c59481b1e8ed643c4a1bd4caef63bce8908
|
c174d2f76124ba3b78b976623a2305c2127016c8
|
refs/heads/master
|
<repo_name>SMahlstedt/reverse-madlibs-project<file_sep>/README.md
# Reverse Madlibs Project
### Table of Contents
* [Instructions](#instructions)
* [Dependencies](#dependencies)
* [Contributing](#contributing)
### Instructions
To start the program, open the containing folder and start the reverse-madlibs-project.py file in a python console.
### Dependencies
This project requires Python 3.6 or later.
### Contributing
This repository is a project requirement for Udacity. Therefore, we most likely will not accept pull requests.<file_sep>/reverse-madlibs-project.py
# allows us to clear the screen
def cls():
print "\n" *100
return
# Pause before screen refresh
def user_pause():
raw_input("Press Enter to continue...")
return
# Check for plural and punctuation. Takes the blank space and answer and returns completed word with full puncutation if applicable.
def check_puncuation(word, answer):
if word.find("_") > 0:
answer = word[:word.find("_")] + answer
if word.find("_") + 4 != len(word):
answer = answer + word[word.find("_") + 5:]
return answer
# Input is the madlib, corresponding answer, and question number. Replaces the blank with answer and returns the changed madlib.
def reveal_words(madlib, answer, quest_num):
madlib = madlib.split(" ")
blank = "__" + str(quest_num+1) + "__"
new_madlib = []
for word in madlib:
if blank in word:
new_madlib.append(check_puncuation(word, answer))
else:
new_madlib.append(word)
new_madlib = " ".join(new_madlib)
print "Correct!"
return new_madlib
# Contains the madlibs with answers. Input is difficulty level. Returns the appropriate madlib by difficulty.
def get_madlib(difficulty):
difficulty_one = [ # from Dr. Seuss
[["Today you are __1__! That is truer than __2__! There is no one __3__ who is you-er than __4__!"], ["you", "true", "alive", "you"],],
[["The more that you __1__, the more __2__ you will know. The more that you __3__, the more places you'll __4__."], ["read", "things", "learn", "go"],],
[["__1__ left and think __2__ and think __3__ and think high. Oh, the __4__ you can think up if you only __5__."], ["Think", "right", "low", "things", "try",],],
]
difficulty_two = [ # J.K. <NAME> and the Chamber of Secrets
[["\"You all know, of course, that __1__ was founded over a thousand years ago - the precise date is uncertain - by the four greatest witches and __2__s of the age. The four school Houses are named after them: Godric __3__, <NAME>, <NAME>, and <NAME>. They built this __4__ together, far from prying Muggle __5__s, for it was an age when magic was feared by common people, and witches and wizards suffered much persecution.\" He paused, gazed blearily around the room, and continued. \"For a few years, the founders worked in harmony together, seeking out youngsters who showed signs of magic and bringing them to the castle to be educated. But then disagreements sprang up between them. A rift began to __6__ between Slytherin and the others."],["Hogwarts", "wizard", "Gryffindor", "castle", "eye", "grow"],],
[["__1__ wished to be more selective about the students admitted to Hogwarts. He believed that __2__ learning should be kept within all-magic families. He disliked taking students of __3__ parentage, believing them to be untrustworthy. After a while, there was a serious argument on the subject between Slytherin and Gryffindor, and Slytherin left the __4__.\" <NAME> paused again, pursing his lips, looking like a wrinkled old tortoise. \"Reliable __5__ sources tell us this much,\" he said. \"But these honest facts have been obscured by the fanciful legend of the Chamber of __6__. The story goes that Slytherin had built a hidden chamber in the castle, of which the other founders knew nothing."],["Slytherin", "magical", "Muggle", "school", "historical", "Secrets"],],
[["\"Slytherin, according to the __1__, sealed the Chamber of Secrets so that none would be able to open it until his own true __2__ arrived at the school. The heir alone would be able to unseal the Chamber of Secrets, unleash the horror within, and use it to __3__ the school of all who were unworthy to study magic.\" There was __4__ as he finished telling the story, but it wasn't the usual, sleepy silence that filled Professor Binns's classes. There was unease in the air as everyone continued to watch him, hoping for more. Professor __5__ looked faintly annoyed. \"The whole thing is arrant nonsense, of course,\" he said. \"Naturally, the school has been searched for evidence of such a chamber, many times, by the most learned witches and wizards. It does not exist. A tale told to frighten the __6__.\""],["legend", "heir", "purge", "silence", "Binns", "gullible"],],
]
difficulty_three = [ # Wikipedia - Hiryu aircraft carrier
[["Hiryu (\"Flying Dragon\") was an __1__ carrier built for the Imperial Japanese Navy (IJN) during the __2__s. The only __3__ of her class, she was __4__ to a modified Soryu design. Her aircraft supported the Japanese __5__ of French Indochina in mid-1940. During the first __6__ of the Pacific War, she took part in the __7__ on Pearl Harbor and the Battle of Wake Island. The ship supported the __8__ of the Dutch East Indies in January 1942. "], ["aircraft", "1930", "ship", "built", "invasion", "month", "attack", "conquest"],],
[["The following month, her __1__ bombed Darwin, Australia, and continued to assist in the Dutch __2__ Indies campaign. In April, __3__'s aircraft helped __4__ two British heavy cruisers and several merchant __5__ during the Indian Ocean raid. after a brief refit, Hiryu and three other fleet __6__s of the First Air Fleet (Kido Butai) __7__ in the Battle of __8__ in June 1942."],["aircraft", "East", "Hiryu","sink", "ships", "carrier", "participated", "Midway"],],
[["After __1__ing American forces on the atoll, the carriers were __2__ed by aircraft from Midway and the __3__s USS Enterprise, Hornet, and Yorktown. Dive bombers from Yorktown and __4__ crippled Hiryu and set her afire. She was __5__ the following day after it became clear that she could not be salvaged. The __6__ of Hiryu and three other IJN carriers at Midway was a __7__ strategic defeat for Japan and contributed significantly to the Allies' ultimate __8__ in the Pacific."],["bombarding", "attack", "carrier", "Enterprise", "scuttled", "loss", "crucial", "victory"],],
]
if difficulty == 1:
return difficulty_one
if difficulty == 2:
return difficulty_two
if difficulty == 3:
return difficulty_three
return
# Displays the Madlib and current level for the user. Input is madlib and current level. Empty return.
def display_madlib(madlib, level):
cls()
madlib_spaces = 135
horizontal = 150
verticle = 146
title = "Reverse Madlibs by <NAME>\n"
print " " * (horizontal / 2 - len(title) / 2), title
print "-" * horizontal
print "|", " " * verticle, "|"
for row in format_madlib_display(madlib, madlib_spaces):
if len(row) < madlib_spaces:
print "|", " " * 5, row, " " * (5 + madlib_spaces - len(row)) + "|"
else:
print "|", " " * 5, row, " " * 5 + "|"
print "|", " " * verticle, "|"
print "|", " " * (verticle - len(str(level+1))- 5 - len("Level: ")) + "Level: " + str(level + 1) + " " * 5, "|"
print "-" * horizontal
return
# Determines the length of the madlib row to avoid clipping. Inputs are the madlib and the max length. Returns the new row length.
def check_row_length(madlib, madlib_spaces):
new_madlib_spaces = madlib_spaces
if len(madlib) > madlib_spaces:
if madlib[new_madlib_spaces] != " ":
while madlib[new_madlib_spaces] != " ":
new_madlib_spaces -= 1
new_madlib_spaces += 1
return new_madlib_spaces
# Takes the madlib list and turns it into appropriate display length. Input is the madlib and the length each row should be. Returns the newly formatted madlib.
def format_madlib_display(madlib, madlib_spaces):
display_madlib = []
length = len(madlib)
i = 1
while i > 0:
hold_row = []
new_madlib_spaces = check_row_length(madlib, madlib_spaces)
hold_row.append(madlib[:new_madlib_spaces])
length = length - new_madlib_spaces
madlib = madlib[new_madlib_spaces:]
i += 1
hold_row = "".join(hold_row)
display_madlib.append(hold_row)
if length < madlib_spaces:
display_madlib.append(madlib)
return display_madlib
return
# Asks the user for input to restart the game or end.
def play_again():
cls()
print "Thanks for playing!"
play = raw_input("Would you like to play again? y/n: ")
if play == "y" or play == "Y":
start_game()
return
# Controls the levels of the game. Input is difficulty. Blank return.
def run_levels(difficulty):
game_levels = get_madlib(difficulty)
level = 0
while level < 3:
current_level = game_levels[level]
answer_list = current_level[1]
madlib = "".join(current_level[0])
fill_in_blanks(madlib, answer_list, level)
level += 1
user_pause()
play_again()
return
# Handles the blanks and user input. Inputs are the madlib, corresponding answers, and the level the user is up to.
def fill_in_blanks(madlib, answer_list, level):
question = 0
wrong_count = 3
while question < len(answer_list):
display_madlib(madlib, level)
user_answer = raw_input("\n\n\nWhat is the answer for number " + str(question+1) + "? ")
if user_answer == answer_list[question] or user_answer == "cheat":
madlib = reveal_words(madlib, answer_list[question], question)
question += 1
wrong_count = 3
else:
wrong_count -= 1
print "Sorry, try again.", wrong_count, "tries left."
if wrong_count == 0:
print "The correct answer is", answer_list[question]
user_pause()
display_madlib(madlib, level)
print "\nCongratulations! You completed level " + str(level + 1) + "!"
return
# Begins the game. No inputs. Gets user desired difficulty.
def start_game():
cls()
user_difficulty = 0
while user_difficulty < 1 or user_difficulty > 3:
user_difficulty = input("Please enter desired difficulty (1-3): ")
if user_difficulty < 1 or user_difficulty > 3:
print "Error. Please try again."
run_levels(user_difficulty)
return
start_game()
|
992065c635464d0c66c2c9af3bb509fa0bf58bc1
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
SMahlstedt/reverse-madlibs-project
|
e77a10ed70589f666a421e10dd04eb7b9d0edf57
|
9bb971f8493714a50b56fd0a751c974320b65612
|
refs/heads/master
|
<repo_name>skyformat99/ServiceFramework<file_sep>/CoreServiceInstaller.cs
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
namespace ServiceFramework
{
[RunInstaller(true)]
public class MyServiceInstaller : Installer
{
public MyServiceInstaller()
{
var processInstaller = new ServiceProcessInstaller();
var serviceInstaller = new ServiceInstaller();
processInstaller.Account = ServiceAccount.LocalSystem;
serviceInstaller.StartType = ServiceStartMode.Automatic;
serviceInstaller.ServiceName = Constants.ServiceName;
serviceInstaller.Description = string.Empty;
Installers.Add(serviceInstaller);
Installers.Add(processInstaller);
}
}
}<file_sep>/README.md
# ServiceFramework
Basic C# Windows Service Framework.
The framework provides task processing, logging and health monitoring capabilities by using performance counters.
A processor can be seen as an entity that runs in a seperate thread, performing some kind of task periodically.
|
9d1de64e4f98b2271f4222dad7d0a88efcba30d4
|
[
"Markdown",
"C#"
] | 2
|
C#
|
skyformat99/ServiceFramework
|
88092f53a602905752cd078a84e41720f3be495e
|
c12f56b728663b2a039e53f9889447f3aba588bd
|
refs/heads/master
|
<repo_name>chirag-10/data_struct<file_sep>/README.md
DATA STRUCTURES:
What is a Data Structure?
A data structure is a specialized format for organizing, processing, retrieving and storing data.
While there are several basic and advanced structure types,
any data structure is designed to arrange data to suit a specific purpose.
All the following programs are written in C++ language.
In the following programs we have used different types of data structures according to our purpose.
1)Pizza Parlour:
We have used a Queue Data Structure here to accept orders and deliver i.e...enter data from one end and remove from the other.
2)Ticket Booking:
Data structure used here is Singly Linked List.
It contains 7 head nodes that correspond to a new row of seats in the theatre.
You can cancel your book,cancel your ticket and also view information about a customer who has booked a ticket.
3)Prims Algorithm:
Prims algorithm is an popular algorithm to find the minimum spanning tree of a graph by using a greedy approach.
Code for implementing prims algorithm is provided in the repository with the name primsAlgo.cpp
4)Shopping plaza:
In this piece of code, we have attempted to create a backend of a shopping mall.
Admin login is required with the password as "<PASSWORD>" to login as administrator/owner of mall and add new products with the
discount percentage that will be given to customers.
Customer can buy products and a bill wil be generated for the customer.
<file_sep>/pizzaParlour.cpp
#include<iostream>
using namespace std;
#define size 100
class dominos
{
struct pizza
{
int order_no[size];
int front,rear;
string pname,cname;
float bill=0;
}p;
public:
dominos()
{
p.front=-1;
p.rear=-1;
}
int qfull()
{
if(p.front==(p.rear+1)%size)
return 1;
else
return 0;
}
int qempty()
{
if(p.front==-1)
return 1;
else
return 0;
}
int place_order(int a)
{
cout<<"\n Enter your name:";
cin>>p.cname;
int ch;
if(qfull())
cout<<"\n Further orders are not accepted";
else if(qempty())
p.front=p.rear=0;
else
p.rear=(p.rear+1)%size;
cout<<"\n 1)Veg pizza Cost:300 \n 2)Non-veg pizza Cost:400 \n 3)Veg combo offer Cost:350 \n It includes 200ml Coke and a pizza of your choice \n 4)Non-Veg combo offer Cost:450 \n It includes 200ml Coke and a pizza of your choice";
cout<<"\nEnter your choice of pizza ";
cin>>ch;
if(ch==1)
{
p.bill=300;
p.pname="\nVeg pizza";
}
else if(ch==2)
{
p.bill=400;
p.pname="\nNon-veg pizza";
}
else if(ch==3)
{
p.bill=350;
p.pname="\nVeg pizza with a chilled glass of Coca-Cola";
}
else
{
p.bill=450;
p.pname="Non-veg pizza with a chilled glass of Coca-Cola";
}
p.order_no[p.rear]=a;
return p.rear;
}
int remove_order()
{
cout<<"\n The order number :"<<p.order_no[p.front]<<" is ready.";
cout<<"\n Enjoy your pizza...";
if(p.front==p.rear)
{
p.front=p.rear=-1;
return 0;
}
else
{ p.front=(p.front+1)%size;
return 1;
}
}
void display()
{
int i;
i=p.front;
do
{
cout<<"\nName of the customer is: "<<p.cname;
cout<<"\nOrder is"<<p.pname;
cout<<"\nBill amount is :"<<p.bill;
cout<<"\nOrder number is :"<<p.order_no[i];
i=(i+1)%size;
}while(i!=p.rear+1);
}
};
int main()
{
int choice,item;
dominos obj;
do
{
cout<<"\n WELCOME TO DOMINOS \n 1)Place an order. \n 2)Pizza's that are ready. \n 3)Display the pending orders";
cout<<"\n Enter your choice :";
cin>>choice;
switch(choice)
{
case 1:if(obj.qfull())
cout<<"\n Cannot accept order";
else
{
cout<<"\n Enter order number :";
cin>>item;
obj.place_order(item);
}
break;
case 2:if(obj.qempty())
cout<<"\n None of the orders are ready.";
else
obj.remove_order();
break;
case 3:if(obj.qempty())
cout<<"\n Order queue is empty.";
else
obj.display();
break;
default:
cout<<"\n Wrong choice";
}
}while(choice<=3);
return 0;
}
<file_sep>/ticketBooking.cpp
#include<iostream>
using namespace std;
struct node
{
int col,row;
string status,name;
struct node *next ,*prev;
}
*head[10];
class ticket
{
public:
ticket()
{
for(int j=0 ; j<10 ; j++)
{
head[j]=NULL;
struct node* temp;
for(int i=1 ; i<=7 ; i++)
{
temp=new(struct node);
temp->col=i;
temp->row=j+1;
temp->status="A";
temp->next=NULL;
temp->prev=NULL;
if(head[j]==NULL)
{
head[j]=temp;
head[j]->next=NULL;
}
else
{
temp->next=head[j];
head[j]->prev=temp;
head[j]=temp;
}
}
}
}
void book()
{
int x,y;
cout<<"\nEnter Row:";
cin>>x;
cout<<"\nEnter Seat No:";
cin>>y;
struct node* temp;
temp=head[x-1];
for(int i=0 ; i<7 ; i++)
{
if(temp->col==y)
{
if(temp->status=="A")
{
temp->status="B";
cout<<"Enter Name: ";
cin>>temp->name;
break;
}
else
{
cout<<"\nAlready booked!!\n";
}
}
temp=temp->next;
}
display();
}
void cancel()
{
int x,y;
cout<<"\nEnter row and column to cancel booking : ";
cin>>x>>y;
struct node* temp;
temp=head[x-1];
for(int i=0 ; i<7 ; i++)
{
if(temp->col==y)
{
if(temp->status=="B")
{
temp->status="A";
}
else
{
cout<<"\nAlready Unbooked!!\n";
}
}
temp=temp->next;
}
display();
}
void display()
{
struct node* temp;
for(int j=0 ; j<10 ; j++)
{
temp=head[j];
for(int i=0 ; i<7 ; i++)
{
cout<<temp->status<<"\t";
temp=temp->next;
}
cout<<"\n";
}
}
void Info()
{
int x,y;
cout<<"\nEnter row and column";
cin>>x>>y;
struct node* temp;
temp=head[x-1];
for(int i=0 ; i<7 ; i++)
{
if(temp->col==y)
{
if(temp->status=="B")
cout<<"Name: "<<temp->name<<endl;
else
cout<<"\nEMPTY\n";
}
temp=temp->next;
}
}
};
int main()
{
ticket t;
int ch;
t.display();
do{
cout<<"\nFor Book Ticket: 1 \nFor Cancel Booking: 2 \nFor Info: 3\nEXIT: 4\n";
cin>>ch;
switch(ch)
{
case 1:t.book();
break;
case 2:t.cancel();
break;
case 3:t.Info();
break;
}
}while(ch!=4);
return 0;
}
<file_sep>/primsAlgo.cpp
//============================================================================
// Name : Prims.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#define MAX 20
#define INF 999
using namespace std;
class Prims
{
public:
int v,e;
int G[MAX][MAX];
void init();
void primsfunc();
};
void Prims::init()
{
int m,n,cost;
cout<<"\nEnter number of vertices ";
cin>>v;
for(int i=1;i<=v;i++)
for(int j=1;j<=v;j++)
G[i][j]=INF;
cout<<"\nEnter number of edges ";
cin>>e;
for(int i=0;i<e;i++)
{
cout<<"\nEnter start and end vertex and its cost ";
cin>>m>>n>>cost;
G[m][n]=cost;
G[n][m]=cost;
}
}
void Prims::primsfunc()
{
int i,min,k,lowcost[MAX],from[MAX],visited[MAX];
cout<<"\nMinimum spanning tree \n";
int mincost=0;
for(int i=1;i<=v;i++)
{
lowcost[i]=G[1][i];
from[i]=1;
visited[i]=0;
}
visited[1]=1;
for(int i=1;i<v;i++)
{
int vertex;
min=INF;
for(int j=2;j<=v;j++)
{
if(!visited[j] && (min>lowcost[j]))
{
min=lowcost[j];
vertex=j;
}
}
cout<<"\nEdge : "<<from[vertex]<<" "<<vertex<<"\n";
mincost=mincost+lowcost[vertex];
visited[vertex]=1;
for(int j=1;j<=v;j++)
{
if(!visited[j] && G[vertex][j]<lowcost[j])
{
lowcost[j]=G[vertex][j];
from[j]=vertex;
}
}
}
cout<<"\nCost of MST : "<<mincost<<endl;
}
int main()
{
Prims obj;
int ch=1;
while(ch=1)
{
obj.init();
obj.primsfunc();
cout<<"\nEnter 1 t0 continue ";
cin>>ch;
}
return 0;
}
|
5dbf08925e02ad61deda8c84e811136db6954b5f
|
[
"Markdown",
"C++"
] | 4
|
Markdown
|
chirag-10/data_struct
|
2ef6001022f085565d7bcc49bf73a595eb9b2070
|
b82028ccef36434bcb9100ea4f47d7088cc236d5
|
refs/heads/main
|
<file_sep>print("hello")
print("welcome rutuj")
|
e8b251e41f7a179554287197a547ca8131edf714
|
[
"Python"
] | 1
|
Python
|
Rutujshete45/demopygit
|
c6bcb285349c305e674eb568f1bb9913fe5c9744
|
5bb072950f94f65b48287dfc9e3b8cc9ddae9a0e
|
refs/heads/master
|
<file_sep>import React, {Component, Fragment} from 'react';
class Tutor extends Component{
state = {
order: 127
}
handlePlus = () => {
this.setState ({
order : this.state.order + 1
})
}
handleMinus = () => {
if (this.state.order > 0){
this.setState ({
order : this.state.order - 1
})
}
}
render(){
return(
<Fragment>
<div className="card">
<div className="counter">
<p>~~~~~~~~~~~ </p>
<p>Pilih Pengajar : </p>
<button className="plus" onClick={this.handlePlus}>+</button>
<button className="minus" onClick={this.handleMinus}>-</button>
<div className="count">
<p>Jumlah murid yang sudah ada dikelas pengajar : {this.state.order}</p>
</div>
</div>
</div>
</Fragment>
)
}
}
export default Tutor;<file_sep>import React, { Component } from 'react'; //import dari react biasa
import { Layout, Row, Col, Modal } from 'antd'; //import dari ant seperti biasa
//import './App.css';
import '../Beranda/beranda.css' //import css dari folder css yang ada di folder assets
import Navbar from '../common/layout/navbar-beranda' //import komponen navbar dari folder layout yang ada di folder common
import ButtonBeranda from '../common/button/button-beranda'; //import komponen buttonhome yang ada di dalamn folder component yang ada di folder common
import { Carousel } from 'antd';
import SizeContext from 'antd/lib/config-provider/SizeContext';
const { Content } = Layout; // membuat konstanta content yang berasal dari bawaan layout ant design, bisa dicek di dokumentasi antdesign
class Beranda extends Component{
render(){
//const image1 = require(`../assets/images/picture.svg`); //membuat variabel image 1 dimana isinya merupakan importan gambar yang ada dari folder images
const {initialData,showModal,handleOk,handleCancel} = this.props; {/* ini merupakan fungsi" yang sudah di definsiikan di landing-page.js
kemudian kita panggil di halaman landing-component.js ketika kita memamnggil komponent dari parent komponen, komponen yang dipanggil
akan menjadi sebuah properti, kemudian kita dapat menggunakan properti itu dihalaman ini.
*/}
return(
<Layout className="landing-container" justify='center'>
{/* <Navbar/> ini merupakan component navbar yang kita import dari folder layout yang ada di common */}
<Content
className="site-layout-background"
style={{
padding: 'o 50px',
margin: 0,
minHeight: 280,
}}
>
<Carousel autoplay>
<div>
<img src="https://i1.wp.com/kpopchart.net/wp-content/uploads/2020/02/Neo-Zone-scaled.jpeg?fit=2560%2C1707&ssl=1.jpg" width='1555' height='400'/>
</div>
<div>
<h1>Rumah Belajar Bahasa Korea No.1 di Indonesia</h1>
</div>
<div>
<h1>Memberikan Pengalaman Yang Sangat Menarik</h1>
</div>
<div>
<h1>Bersama Tutor Asli Dari Korea</h1>
</div>
</Carousel>
</Content>
</Layout>
);
}
}
export default Beranda;
<file_sep>import React, {Component} from 'react';
import {Switch, Route} from 'react-router-dom';
import Daftar from '../../Daftar/daftar-page';
import Beranda from '../../Beranda/beranda-page';
class Router extends Component {
render() {
return (
<Switch>
<Route exact path="/" component={Beranda}/>
<Route path="/daftar" component={Daftar}/>
</Switch>
);
}
}
export default Router;
|
9624458836ca43cee0144fb76c714bbc2772452a
|
[
"JavaScript"
] | 3
|
JavaScript
|
cintyaagusti/Web3A-15102
|
b918cf8320e38ecff25853d88bd0d0fcf27c7a32
|
87bb3dfd2bd0f65a457ed825ddcfb9fcde0401ad
|
refs/heads/master
|
<file_sep>//Made with Blockbench
//Paste this code into your mod.
import org.lwjgl.opengl.GL11;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelBox;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.entity.Entity;
public class skyhorse_lusus extends ModelBase {
private final ModelRenderer Body;
private final ModelRenderer Neck;
private final ModelRenderer Neck2;
private final ModelRenderer Head;
private final ModelRenderer LeftEye;
private final ModelRenderer RightEye;
private final ModelRenderer Forehead;
private final ModelRenderer Horns;
private final ModelRenderer Abdomen;
private final ModelRenderer Tail;
private final ModelRenderer Tail2;
private final ModelRenderer Tail3;
private final ModelRenderer Tail4;
private final ModelRenderer Tail5;
public skyhorse_lusus() {
textureWidth = 128;
textureHeight = 128;
Body = new ModelRenderer(this);
Body.setRotationPoint(0.0F, -10.25F, 1.0F);
setRotationAngle(Body, 0.5236F, 0.0F, 0.0F);
Body.cubeList.add(new ModelBox(Body, 52, 44, -5.0F, -5.75F, -7.0F, 10, 13, 14, 0.0F, false));
Neck = new ModelRenderer(this);
Neck.setRotationPoint(0.0F, 1.4374F, 0.8452F);
setRotationAngle(Neck, -0.3491F, 0.0F, 0.0F);
Body.addChild(Neck);
Neck.cubeList.add(new ModelBox(Neck, 59, 22, -3.5F, -12.7588F, -6.0681F, 7, 12, 9, 0.0F, false));
Neck2 = new ModelRenderer(this);
Neck2.setRotationPoint(0.0F, -6.0F, 1.0F);
setRotationAngle(Neck2, -0.2618F, 0.0F, 0.0F);
Neck.addChild(Neck2);
Neck2.cubeList.add(new ModelBox(Neck2, 62, 0, -2.5F, -16.2766F, -6.8943F, 5, 14, 7, 0.0F, false));
Head = new ModelRenderer(this);
Head.setRotationPoint(0.0F, -16.1874F, 0.1548F);
setRotationAngle(Head, 0.3491F, 0.0F, 0.0F);
Neck2.addChild(Head);
Head.cubeList.add(new ModelBox(Head, 33, 1, -3.5F, -5.8126F, -6.1548F, 7, 7, 7, 0.0F, false));
Head.cubeList.add(new ModelBox(Head, 15, 27, -4.0F, -4.8126F, -14.1548F, 8, 7, 8, 0.0F, false));
Head.cubeList.add(new ModelBox(Head, 16, 43, -2.0F, -2.5126F, -23.1548F, 4, 4, 9, 0.0F, false));
LeftEye = new ModelRenderer(this);
LeftEye.setRotationPoint(4.0F, -0.8126F, -14.1548F);
setRotationAngle(LeftEye, 0.0F, 0.3142F, 0.0F);
Head.addChild(LeftEye);
LeftEye.cubeList.add(new ModelBox(LeftEye, 28, 21, -6.0F, -4.0F, 0.0F, 6, 4, 9, 0.0F, false));
RightEye = new ModelRenderer(this);
RightEye.setRotationPoint(-4.0F, -0.8126F, -14.1548F);
setRotationAngle(RightEye, 0.0F, -0.3142F, 0.0F);
Head.addChild(RightEye);
RightEye.cubeList.add(new ModelBox(RightEye, 1, 21, 0.0F, -4.0F, 0.0F, 6, 4, 9, 0.0F, true));
Forehead = new ModelRenderer(this);
Forehead.setRotationPoint(0.0F, -4.8126F, -14.1548F);
setRotationAngle(Forehead, 0.192F, 0.0F, 0.0F);
Head.addChild(Forehead);
Forehead.cubeList.add(new ModelBox(Forehead, 0, 0, -4.0F, 0.0F, 0.0F, 8, 4, 16, 0.0F, false));
Horns = new ModelRenderer(this);
Horns.setRotationPoint(-3.5F, 2.5819F, 9.0831F);
setRotationAngle(Horns, 0.5236F, 0.0F, 0.0F);
Forehead.addChild(Horns);
Horns.cubeList.add(new ModelBox(Horns, 2, 1, 4.8F, 0.2214F, 4.3774F, 2, 2, 4, 0.0F, false));
Horns.cubeList.add(new ModelBox(Horns, 2, 1, 0.2F, 0.2214F, 4.3774F, 2, 2, 4, 0.0F, true));
Abdomen = new ModelRenderer(this);
Abdomen.setRotationPoint(5.0F, 9.4374F, 0.3452F);
setRotationAngle(Abdomen, 0.1745F, 0.0F, 0.0F);
Body.addChild(Abdomen);
Abdomen.cubeList.add(new ModelBox(Abdomen, 54, 72, -9.0F, -6.1874F, -6.3452F, 8, 15, 13, 0.0F, false));
Tail = new ModelRenderer(this);
Tail.setRotationPoint(-5.0F, 11.0F, 1.0F);
setRotationAngle(Tail, -0.8727F, 0.0F, 0.0F);
Abdomen.addChild(Tail);
Tail.cubeList.add(new ModelBox(Tail, 96, 0, -3.0F, -5.1874F, -8.3452F, 6, 16, 10, 0.0F, false));
Tail2 = new ModelRenderer(this);
Tail2.setRotationPoint(0.0F, 12.0F, -1.0F);
setRotationAngle(Tail2, -0.8727F, 0.0F, 0.0F);
Tail.addChild(Tail2);
Tail2.cubeList.add(new ModelBox(Tail2, 101, 27, -2.5F, -2.1874F, -6.3452F, 5, 15, 6, 0.0F, false));
Tail3 = new ModelRenderer(this);
Tail3.setRotationPoint(0.0F, 10.0F, 0.0F);
setRotationAngle(Tail3, -1.309F, 0.0F, 0.0F);
Tail2.addChild(Tail3);
Tail3.cubeList.add(new ModelBox(Tail3, 102, 49, -2.0F, 3.8126F, -2.8452F, 4, 11, 5, 0.0F, false));
Tail4 = new ModelRenderer(this);
Tail4.setRotationPoint(0.0F, 9.5849F, 0.0F);
setRotationAngle(Tail4, -1.4835F, 0.0F, 0.0F);
Tail3.addChild(Tail4);
Tail4.cubeList.add(new ModelBox(Tail4, 104, 66, -1.5F, 1.2278F, 2.1548F, 3, 7, 3, 0.0F, false));
Tail5 = new ModelRenderer(this);
Tail5.setRotationPoint(0.0F, 5.9151F, 0.0F);
setRotationAngle(Tail5, -1.3963F, 0.0F, -0.0873F);
Tail4.addChild(Tail5);
Tail5.cubeList.add(new ModelBox(Tail5, 106, 77, -1.0F, -3.6874F, 1.1548F, 2, 5, 2, 0.0F, false));
}
@Override
public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) {
Body.render(f5);
}
public void setRotationAngle(ModelRenderer modelRenderer, float x, float y, float z) {
modelRenderer.rotateAngleX = x;
modelRenderer.rotateAngleY = y;
modelRenderer.rotateAngleZ = z;
}
}<file_sep># AlterniaCraft
Alternian Minecraft Mod
|
124d56014a3c79b3ad535d950c2b61b426772f27
|
[
"Markdown",
"Java"
] | 2
|
Java
|
praxisparker/AlterniaCraft
|
33f5248c601a2203852395ffc1afd6de7aa8a699
|
1d14a637d614a967cb84c90e523f0d8a89c04669
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.